@burdenoff/microfe-stewards 2026.1202.3 → 2026.1204.1

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.
Files changed (81) hide show
  1. package/dist/generated/wspace-operations.d.ts +3 -3
  2. package/dist/generated/wspace-operations.js.map +1 -1
  3. package/dist/generated/wspace-types.js.map +1 -1
  4. package/dist/node_modules/zustand/esm/vanilla.js.map +1 -1
  5. package/dist/stewards/StewardsRoot.js +15 -15
  6. package/dist/stewards/StewardsRoot.js.map +1 -1
  7. package/dist/stewards/StewardsRoutes.js +35 -35
  8. package/dist/stewards/StewardsRoutes.js.map +1 -1
  9. package/dist/stewards/components/CharterControls.js.map +1 -1
  10. package/dist/stewards/components/ControlBanner.js.map +1 -1
  11. package/dist/stewards/components/DutyEditor.js +44 -44
  12. package/dist/stewards/components/DutyEditor.js.map +1 -1
  13. package/dist/stewards/components/FormField.js.map +1 -1
  14. package/dist/stewards/components/LinesField.js +11 -11
  15. package/dist/stewards/components/LinesField.js.map +1 -1
  16. package/dist/stewards/components/LiveDeskPanel.js +57 -57
  17. package/dist/stewards/components/LiveDeskPanel.js.map +1 -1
  18. package/dist/stewards/components/MemoryDiffView.js.map +1 -1
  19. package/dist/stewards/components/ProposalsQueue.js.map +1 -1
  20. package/dist/stewards/components/RunsTable.js.map +1 -1
  21. package/dist/stewards/components/StewardsTable.js.map +1 -1
  22. package/dist/stewards/components/TeachRecorder.js +84 -84
  23. package/dist/stewards/components/TeachRecorder.js.map +1 -1
  24. package/dist/stewards/components/run/RunHeader.js +63 -63
  25. package/dist/stewards/components/run/RunHeader.js.map +1 -1
  26. package/dist/stewards/components/run/RunStepsSection.js +58 -58
  27. package/dist/stewards/components/run/RunStepsSection.js.map +1 -1
  28. package/dist/stewards/components/run/RunSummaryCards.js.map +1 -1
  29. package/dist/stewards/components/run/StepDetail.js +59 -59
  30. package/dist/stewards/components/run/StepDetail.js.map +1 -1
  31. package/dist/stewards/components/stewardLabels.js.map +1 -1
  32. package/dist/stewards/components/ui.js.map +1 -1
  33. package/dist/stewards/hooks/useStewards.js.map +1 -1
  34. package/dist/stewards/i18n/en.js.map +1 -1
  35. package/dist/stewards/i18n/useStewardsT.js +11 -11
  36. package/dist/stewards/i18n/useStewardsT.js.map +1 -1
  37. package/dist/stewards/live/DeskCanvas.js +35 -35
  38. package/dist/stewards/live/DeskCanvas.js.map +1 -1
  39. package/dist/stewards/live/DeskStreamConnection.js.map +1 -1
  40. package/dist/stewards/live/backoff.js.map +1 -1
  41. package/dist/stewards/live/browserConnection.js +6 -6
  42. package/dist/stewards/live/browserConnection.js.map +1 -1
  43. package/dist/stewards/live/describeStream.js.map +1 -1
  44. package/dist/stewards/live/mintPass.js +19 -19
  45. package/dist/stewards/live/mintPass.js.map +1 -1
  46. package/dist/stewards/live/protocol.js.map +1 -1
  47. package/dist/stewards/live/useDeskStream.js +11 -11
  48. package/dist/stewards/live/useDeskStream.js.map +1 -1
  49. package/dist/stewards/pages/StewardCharterPage.js +166 -166
  50. package/dist/stewards/pages/StewardCharterPage.js.map +1 -1
  51. package/dist/stewards/pages/StewardDaybookPage.js +101 -101
  52. package/dist/stewards/pages/StewardDaybookPage.js.map +1 -1
  53. package/dist/stewards/pages/StewardDutiesPage.js +89 -89
  54. package/dist/stewards/pages/StewardDutiesPage.js.map +1 -1
  55. package/dist/stewards/pages/StewardLayout.js +103 -103
  56. package/dist/stewards/pages/StewardLayout.js.map +1 -1
  57. package/dist/stewards/pages/StewardMemoryPage.js +135 -135
  58. package/dist/stewards/pages/StewardMemoryPage.js.map +1 -1
  59. package/dist/stewards/pages/StewardNewPage.js +172 -172
  60. package/dist/stewards/pages/StewardNewPage.js.map +1 -1
  61. package/dist/stewards/pages/StewardOverviewPage.js.map +1 -1
  62. package/dist/stewards/pages/StewardPlaybooksPage.js +151 -151
  63. package/dist/stewards/pages/StewardPlaybooksPage.js.map +1 -1
  64. package/dist/stewards/pages/StewardRunPage.js +65 -65
  65. package/dist/stewards/pages/StewardRunPage.js.map +1 -1
  66. package/dist/stewards/pages/StewardsListPage.js.map +1 -1
  67. package/dist/stewards/permissions/useStewardPermissions.js +7 -7
  68. package/dist/stewards/permissions/useStewardPermissions.js.map +1 -1
  69. package/dist/stewards/providers/StewardsProvider.js +18 -18
  70. package/dist/stewards/providers/StewardsProvider.js.map +1 -1
  71. package/dist/stewards/store/stewardsStore.js.map +1 -1
  72. package/dist/stewards/utils/charterForm.js.map +1 -1
  73. package/dist/stewards/utils/dates.js.map +1 -1
  74. package/dist/stewards/utils/daybook.js.map +1 -1
  75. package/dist/stewards/utils/dutyForm.js.map +1 -1
  76. package/dist/stewards/utils/errors.js.map +1 -1
  77. package/dist/stewards/utils/memory.js.map +1 -1
  78. package/dist/stewards/utils/playbookForm.js.map +1 -1
  79. package/dist/stewards/utils/recorder.js.map +1 -1
  80. package/dist/stewards/utils/wizard.js.map +1 -1
  81. package/package.json +5 -5
@@ -1,26 +1,26 @@
1
- import { encodeInput as e, normalisePoint as t, sniffImageMime as n } from "./protocol.js";
2
- import { jsx as r, jsxs as i } from "react/jsx-runtime";
3
- import { useEffect as a, useRef as o } from "react";
1
+ import { useEffect as e, useRef as t } from "react";
2
+ import { encodeInput as n, normalisePoint as r, sniffImageMime as i } from "./protocol.js";
3
+ import { jsx as a, jsxs as o } from "react/jsx-runtime";
4
4
  // src/stewards/live/DeskCanvas.tsx
5
5
  var s = 50;
6
6
  function c({ registerSink: c, interactive: l, send: u, label: d, hint: f }) {
7
- let p = o(null), m = o(0);
8
- a(() => {
9
- let e = !1, t = null, r = !1, i = async (e) => {
10
- let t = n(new Uint8Array(e, 0, Math.min(16, e.byteLength))), i = p.current;
11
- if (!t || !i || e.byteLength > 16777216) return;
7
+ let p = t(null), m = t(0);
8
+ e(() => {
9
+ let e = !1, t = null, n = !1, r = async (e) => {
10
+ let t = i(new Uint8Array(e, 0, Math.min(16, e.byteLength))), r = p.current;
11
+ if (!t || !r || e.byteLength > 16777216) return;
12
12
  let a;
13
13
  try {
14
14
  a = await createImageBitmap(new Blob([e], { type: t }));
15
15
  } catch {
16
16
  return;
17
17
  }
18
- r || ((i.width !== a.width || i.height !== a.height) && (i.width = a.width, i.height = a.height), i.getContext("2d")?.drawImage(a, 0, 0)), a.close();
18
+ n || ((r.width !== a.width || r.height !== a.height) && (r.width = a.width, r.height = a.height), r.getContext("2d")?.drawImage(a, 0, 0)), a.close();
19
19
  }, a = async () => {
20
20
  if (!e) {
21
- for (e = !0; t && !r;) {
21
+ for (e = !0; t && !n;) {
22
22
  let e = t;
23
- t = null, await i(e);
23
+ t = null, await r(e);
24
24
  }
25
25
  e = !1;
26
26
  }
@@ -28,43 +28,43 @@ function c({ registerSink: c, interactive: l, send: u, label: d, hint: f }) {
28
28
  return c((e) => {
29
29
  t = e, a();
30
30
  }), () => {
31
- r = !0, t = null, c(null);
31
+ n = !0, t = null, c(null);
32
32
  };
33
- }, [c]), a(() => {
34
- let n = p.current;
35
- if (!n || !l) return;
36
- let r = (r) => {
37
- r.preventDefault();
38
- let i = t(n.getBoundingClientRect(), r.clientX, r.clientY);
39
- u(e({
33
+ }, [c]), e(() => {
34
+ let e = p.current;
35
+ if (!e || !l) return;
36
+ let t = (t) => {
37
+ t.preventDefault();
38
+ let i = r(e.getBoundingClientRect(), t.clientX, t.clientY);
39
+ u(n({
40
40
  type: "wheel",
41
41
  ...i,
42
- dx: r.deltaX,
43
- dy: r.deltaY
42
+ dx: t.deltaX,
43
+ dy: t.deltaY
44
44
  }));
45
45
  };
46
- return n.addEventListener("wheel", r, { passive: !1 }), () => n.removeEventListener("wheel", r);
46
+ return e.addEventListener("wheel", t, { passive: !1 }), () => e.removeEventListener("wheel", t);
47
47
  }, [l, u]);
48
- let h = (n, r) => {
48
+ let h = (e, t) => {
49
49
  if (!l) return;
50
50
  let i = {
51
51
  type: "pointer",
52
- action: n,
53
- ...t(r.currentTarget.getBoundingClientRect(), r.clientX, r.clientY),
54
- button: r.button
52
+ action: e,
53
+ ...r(t.currentTarget.getBoundingClientRect(), t.clientX, t.clientY),
54
+ button: t.button
55
55
  };
56
- u(e(i));
57
- }, g = (t, n) => {
58
- l && n.key !== "Tab" && (n.preventDefault(), u(e({
56
+ u(n(i));
57
+ }, g = (e, t) => {
58
+ l && t.key !== "Tab" && (t.preventDefault(), u(n({
59
59
  type: "key",
60
- action: t,
61
- key: n.key,
62
- code: n.code
60
+ action: e,
61
+ key: t.key,
62
+ code: t.code
63
63
  })));
64
64
  };
65
- return /* @__PURE__ */ i("div", {
65
+ return /* @__PURE__ */ o("div", {
66
66
  className: "flex flex-col gap-1",
67
- children: [/* @__PURE__ */ r("canvas", {
67
+ children: [/* @__PURE__ */ a("canvas", {
68
68
  ref: p,
69
69
  tabIndex: l ? 0 : -1,
70
70
  role: "img",
@@ -84,7 +84,7 @@ function c({ registerSink: c, interactive: l, send: u, label: d, hint: f }) {
84
84
  onContextMenu: (e) => {
85
85
  l && e.preventDefault();
86
86
  }
87
- }), l && /* @__PURE__ */ r("p", {
87
+ }), l && /* @__PURE__ */ a("p", {
88
88
  className: "text-xs text-(color:--color-text-secondary)",
89
89
  children: f
90
90
  })]
@@ -1 +1 @@
1
- {"version":3,"file":"DeskCanvas.js","names":["MOVE_INTERVAL_MS","DeskCanvas","canvasRef","useRef","lastMoveAt","useEffect","decoding","latest","disposed","paint","mime","sniffImageMime","buffer","canvas","bitmap","drain","next","registerSink","frame","interactive","onWheel","point","normalisePoint","event","encodeInput","send","pointer","input","key","label","now","hint"],"sources":["../../../src/stewards/live/DeskCanvas.tsx"],"sourcesContent":["import { useEffect, useRef } from 'react';\nimport {\n encodeInput,\n MAX_FRAME_BYTES,\n normalisePoint,\n sniffImageMime,\n type DeskInput,\n} from './protocol';\nimport type { FrameSink } from './useDeskStream';\n\n/** Most pointer-move messages per second; a click or key is never throttled. */\nconst MOVE_INTERVAL_MS = 50;\n\ninterface DeskCanvasProps {\n /** Receives a function that paints one desk frame; called with null on unmount. */\n registerSink: (sink: FrameSink | null) => void;\n /** Control mode: forward the person's pointer and keys to the desk. */\n interactive: boolean;\n send: (frame: string) => boolean;\n label: string;\n hint: string;\n}\n\n/**\n * Paints the desk's screen frames and, in control mode, turns pointer and key events into input.\n *\n * Keystrokes can be a password or a one-time code. They go straight from the event to `send`:\n * no state, no ref, no log, no copy. Tab is not forwarded, so the keyboard can always leave the\n * desk. Frames are decoded newest-first and older ones are skipped, so a slow device never falls\n * behind.\n */\nexport function DeskCanvas({ registerSink, interactive, send, label, hint }: DeskCanvasProps) {\n const canvasRef = useRef<HTMLCanvasElement>(null);\n const lastMoveAt = useRef(0);\n\n useEffect(() => {\n let decoding = false;\n let latest: ArrayBuffer | null = null;\n let disposed = false;\n\n const paint = async (buffer: ArrayBuffer): Promise<void> => {\n const mime = sniffImageMime(new Uint8Array(buffer, 0, Math.min(16, buffer.byteLength)));\n const canvas = canvasRef.current;\n if (!mime || !canvas || buffer.byteLength > MAX_FRAME_BYTES) return;\n let bitmap: ImageBitmap;\n try {\n bitmap = await createImageBitmap(new Blob([buffer], { type: mime }));\n } catch {\n return; // A frame that does not decode is skipped; the next one repaints.\n }\n if (disposed) {\n bitmap.close();\n return;\n }\n if (canvas.width !== bitmap.width || canvas.height !== bitmap.height) {\n canvas.width = bitmap.width;\n canvas.height = bitmap.height;\n }\n canvas.getContext('2d')?.drawImage(bitmap, 0, 0);\n bitmap.close();\n };\n\n const drain = async (): Promise<void> => {\n if (decoding) return;\n decoding = true;\n while (latest && !disposed) {\n const next = latest;\n latest = null;\n await paint(next);\n }\n decoding = false;\n };\n\n registerSink((frame) => {\n latest = frame;\n void drain();\n });\n return () => {\n disposed = true;\n latest = null;\n registerSink(null);\n };\n }, [registerSink]);\n\n // Wheel needs a non-passive listener to stop the page scrolling while the desk scrolls.\n useEffect(() => {\n const canvas = canvasRef.current;\n if (!canvas || !interactive) return;\n const onWheel = (event: WheelEvent) => {\n event.preventDefault();\n const point = normalisePoint(canvas.getBoundingClientRect(), event.clientX, event.clientY);\n send(encodeInput({ type: 'wheel', ...point, dx: event.deltaX, dy: event.deltaY }));\n };\n canvas.addEventListener('wheel', onWheel, { passive: false });\n return () => canvas.removeEventListener('wheel', onWheel);\n }, [interactive, send]);\n\n const pointer = (\n action: 'move' | 'down' | 'up',\n event: React.PointerEvent<HTMLCanvasElement>\n ) => {\n if (!interactive) return;\n const point = normalisePoint(\n event.currentTarget.getBoundingClientRect(),\n event.clientX,\n event.clientY\n );\n const input: DeskInput = { type: 'pointer', action, ...point, button: event.button };\n send(encodeInput(input));\n };\n\n const key = (action: 'down' | 'up', event: React.KeyboardEvent<HTMLCanvasElement>) => {\n if (!interactive || event.key === 'Tab') return;\n event.preventDefault();\n send(encodeInput({ type: 'key', action, key: event.key, code: event.code }));\n };\n\n return (\n <div className=\"flex flex-col gap-1\">\n <canvas\n ref={canvasRef}\n tabIndex={interactive ? 0 : -1}\n role=\"img\"\n aria-label={label}\n data-testid=\"desk-canvas\"\n className={`block h-auto w-full rounded-md border border-(color:--color-border-seam) bg-(--color-bg-sunken) focus-visible:outline-2 focus-visible:outline-(color:--color-focus-ring) ${interactive ? 'cursor-crosshair' : ''}`}\n onPointerDown={(e) => {\n e.currentTarget.focus();\n pointer('down', e);\n }}\n onPointerUp={(e) => pointer('up', e)}\n onPointerMove={(e) => {\n const now = performance.now();\n if (now - lastMoveAt.current < MOVE_INTERVAL_MS) return;\n lastMoveAt.current = now;\n pointer('move', e);\n }}\n onKeyDown={(e) => key('down', e)}\n onKeyUp={(e) => key('up', e)}\n onContextMenu={(e) => {\n if (interactive) e.preventDefault();\n }}\n />\n {interactive && <p className=\"text-xs text-(color:--color-text-secondary)\">{hint}</p>}\n </div>\n );\n}\n"],"mappings":";;;;AAWA,IAAMA,IAAmB;AAoBzB,SAAgBC,EAAW,EAAE,iBAAc,gBAAa,SAAM,UAAO,WAAyB;CAC5F,IAAMC,IAAYC,EAA0B,IAAI,GAC1CC,IAAaD,EAAO,CAAC;CAoD3B,AAlDAE,QAAgB;EACd,IAAIC,IA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","_jsx","useEffect","useRef","encodeInput","normalisePoint","sniffImageMime","jsx","jsxs","MOVE_INTERVAL_MS","DeskCanvas","registerSink","interactive","send","label","hint","canvasRef","lastMoveAt","decoding","latest","disposed","paint","buffer","mime","canvas","bitmap","drain","next","frame","onWheel","event","point","pointer","action","input","key","now"],"sources":["../../../src/stewards/live/DeskCanvas.tsx"],"sourcesContent":["import { useEffect, useRef } from 'react';\nimport {\n encodeInput,\n MAX_FRAME_BYTES,\n normalisePoint,\n sniffImageMime,\n type DeskInput,\n} from './protocol';\nimport type { FrameSink } from './useDeskStream';\n\n/** Most pointer-move messages per second; a click or key is never throttled. */\nconst MOVE_INTERVAL_MS = 50;\n\ninterface DeskCanvasProps {\n /** Receives a function that paints one desk frame; called with null on unmount. */\n registerSink: (sink: FrameSink | null) => void;\n /** Control mode: forward the person's pointer and keys to the desk. */\n interactive: boolean;\n send: (frame: string) => boolean;\n label: string;\n hint: string;\n}\n\n/**\n * Paints the desk's screen frames and, in control mode, turns pointer and key events into input.\n *\n * Keystrokes can be a password or a one-time code. They go straight from the event to `send`:\n * no state, no ref, no log, no copy. Tab is not forwarded, so the keyboard can always leave the\n * desk. Frames are decoded newest-first and older ones are skipped, so a slow device never falls\n * behind.\n */\nexport function DeskCanvas({ registerSink, interactive, send, label, hint }: DeskCanvasProps) {\n const canvasRef = useRef<HTMLCanvasElement>(null);\n const lastMoveAt = useRef(0);\n\n useEffect(() => {\n let decoding = false;\n let latest: ArrayBuffer | null = null;\n let disposed = false;\n\n const paint = async (buffer: ArrayBuffer): Promise<void> => {\n const mime = sniffImageMime(new Uint8Array(buffer, 0, Math.min(16, buffer.byteLength)));\n const canvas = canvasRef.current;\n if (!mime || !canvas || buffer.byteLength > MAX_FRAME_BYTES) return;\n let bitmap: ImageBitmap;\n try {\n bitmap = await createImageBitmap(new Blob([buffer], { type: mime }));\n } catch {\n return; // A frame that does not decode is skipped; the next one repaints.\n }\n if (disposed) {\n bitmap.close();\n return;\n }\n if (canvas.width !== bitmap.width || canvas.height !== bitmap.height) {\n canvas.width = bitmap.width;\n canvas.height = bitmap.height;\n }\n canvas.getContext('2d')?.drawImage(bitmap, 0, 0);\n bitmap.close();\n };\n\n const drain = async (): Promise<void> => {\n if (decoding) return;\n decoding = true;\n while (latest && !disposed) {\n const next = latest;\n latest = null;\n await paint(next);\n }\n decoding = false;\n };\n\n registerSink((frame) => {\n latest = frame;\n void drain();\n });\n return () => {\n disposed = true;\n latest = null;\n registerSink(null);\n };\n }, [registerSink]);\n\n // Wheel needs a non-passive listener to stop the page scrolling while the desk scrolls.\n useEffect(() => {\n const canvas = canvasRef.current;\n if (!canvas || !interactive) return;\n const onWheel = (event: WheelEvent) => {\n event.preventDefault();\n const point = normalisePoint(canvas.getBoundingClientRect(), event.clientX, event.clientY);\n send(encodeInput({ type: 'wheel', ...point, dx: event.deltaX, dy: event.deltaY }));\n };\n canvas.addEventListener('wheel', onWheel, { passive: false });\n return () => canvas.removeEventListener('wheel', onWheel);\n }, [interactive, send]);\n\n const pointer = (\n action: 'move' | 'down' | 'up',\n event: React.PointerEvent<HTMLCanvasElement>\n ) => {\n if (!interactive) return;\n const point = normalisePoint(\n event.currentTarget.getBoundingClientRect(),\n event.clientX,\n event.clientY\n );\n const input: DeskInput = { type: 'pointer', action, ...point, button: event.button };\n send(encodeInput(input));\n };\n\n const key = (action: 'down' | 'up', event: React.KeyboardEvent<HTMLCanvasElement>) => {\n if (!interactive || event.key === 'Tab') return;\n event.preventDefault();\n send(encodeInput({ type: 'key', action, key: event.key, code: event.code }));\n };\n\n return (\n <div className=\"flex flex-col gap-1\">\n <canvas\n ref={canvasRef}\n tabIndex={interactive ? 0 : -1}\n role=\"img\"\n aria-label={label}\n data-testid=\"desk-canvas\"\n className={`block h-auto w-full rounded-md border border-(color:--color-border-seam) bg-(--color-bg-sunken) focus-visible:outline-2 focus-visible:outline-(color:--color-focus-ring) ${interactive ? 'cursor-crosshair' : ''}`}\n onPointerDown={(e) => {\n e.currentTarget.focus();\n pointer('down', e);\n }}\n onPointerUp={(e) => pointer('up', e)}\n onPointerMove={(e) => {\n const now = performance.now();\n if (now - lastMoveAt.current < MOVE_INTERVAL_MS) return;\n lastMoveAt.current = now;\n pointer('move', e);\n }}\n onKeyDown={(e) => key('down', e)}\n onKeyUp={(e) => key('up', e)}\n onContextMenu={(e) => {\n if (interactive) e.preventDefault();\n }}\n />\n {interactive && <p className=\"text-xs text-(color:--color-text-secondary)\">{hint}</p>}\n </div>\n );\n}\n"],"mappings":";;;;AAWA,IAAMS,IAAmB;AAoBzB,SAAgBC,EAAW,EAAEC,iBAAcC,gBAAaC,SAAMC,UAAOC,WAAyB;CAC5F,IAAMC,IAAYb,EAA0B,IAAI,GAC1Cc,IAAad,EAAO,CAAC;CAE3BD,QAAgB;EACd,IAAIgB,IAAW,IACXC,IAA6B,MAC7BC,IAAW,IAETC,IAAQ,OAAOC,MAAuC;GAC1D,IAAMC,IAAOjB,EAAe,IAAI,WAAWgB,GAAQ,GAAG,KAAK,IAAI,IAAIA,EAAO,UAAU,CAAC,CAAC,GAChFE,IAASR,EAAU;GACzB,IAAI,CAACO,KAAQ,CAACC,KAAUF,EAAO,aAAA,UAA8B;GAC7D,IAAIG;GACJ,IAAI;IACFA,IAAS,MAAM,kBAAkB,IAAI,KAAK,CAACH,CAAM,GAAG,EAAE,MAAMC,EAAK,CAAC,CAAC;GACrE,QAAQ;IACN;GACF;GACIH,OAIAI,EAAO,UAAUC,EAAO,SAASD,EAAO,WAAWC,EAAO,YAC5DD,EAAO,QAAQC,EAAO,OACtBD,EAAO,SAASC,EAAO,SAEzBD,EAAO,WAAW,IAAI,CAAC,EAAE,UAAUC,GAAQ,GAAG,CAAC,IAC/CA,EAAO,MAAM;EACf,GAEMC,IAAQ,YAA2B;GACvC,IAAIR,IACJ;IACA,KADAA,IAAW,IACJC,KAAU,CAACC,IAAU;KAC1B,IAAMO,IAAOR;KACbA,IAAS,MACT,MAAME,EAAMM,CAAI;IAClB;IACAT,IAAW;GAN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AAM;IACpB,EAAE,cAAc,MAAM,GACtBoB,EAAQ,QAAQ,CAAC;GACnB;GACA,cAAc,MAAMA,EAAQ,MAAM,CAAC;GACnC,gBAAgB,MAAM;IACpB,IAAMI,IAAM,YAAY,IAAI;IACxBA,IAAMnB,EAAW,UAAUR,MAC/BQ,EAAW,UAAUmB,GACrBJ,EAAQ,QAAQ,CAAC;GACnB;GACA,YAAY,MAAMG,EAAI,QAAQ,CAAC;GAC/B,UAAU,MAAMA,EAAI,MAAM,CAAC;GAC3B,gBAAgB,MAAM;IAChBvB,KAAa,EAAE,eAAe;GACpC;EACD,CAAA,GACAA,KAAeX,kBAAC,KAAD;GAAG,WAAU;GAA+C,UAAAc;EAAQ,CAAA,CACjF;;AAET"}
@@ -1 +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, attempt: 0, hasFrame: false });\n }\n}\n"],"mappings":";;;AA6CA,IAAaA,IAAoC;CAC/C,OAAO;CACP,MAAM;CACN,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,UAAU;AACZ,GAYaC,IAAb,cAA+B,MAAM;CACnC;CACA;CACA,YAAY,GAAiB,GAAsD;EAIjF,AAHA,MAAMC,CAAO,GACb,KAAK,OAAO,aACZ,KAAK,YAAYC,EAAQ,WACzB,KAAK,YAAYA,EAAQ,aAAa;CACxC;AACF,GAiDMC,IAA+B;CACnC,gBAAgB;CAChB,aAAa;CACb,aAAa;CACb,gBAAgB;CAChB,eAAe;CACf,aAAa;AACf,GAIaC,IAAb,MAAkC;CAgBb;CAfnB,QAA6BL;CAC7B,4BAA6B,IAAI,IAAc;CAC/C;CACA,aAAqB;CACrB,SAAoC;CACpC,aAA8B;CAC9B,aAA8B;CAC9B,iBAAkC;CAClC,WAAmB;CACnB,gBAAwB;CACxB,WAAmB;CACnB,YAAoB;CACpB,kBAA0B;CAE1B,YACE,GACA,IAAgC,CAAC,GACjC;EACA,AAHiB,KAAA,OAAAM,GAGjB,KAAK,SAAS;GAAE,GAAGF;GAAgB,GAAGG;EAAO;CAC/C;CAEA,iBAA8B,KAAK;CAEnC,aAAa,OACX,KAAK,UAAU,IAAIC,CAAQ,SACd;EACX,KAAK,UAAU,OAAOA,CAAQ;CAChC;CAIF,MAAM,GAAwB;EAO5B,AANA,KAAK,SAAS,GACd,KAAK,cAAc,GACnB,KAAK,WAAW,GAChB,KAAK,gBAAgB,IACrB,KAAK,WAAW,GAChB,KAAK,IAAI;GAAE,GAAGR;GAAsB,OAAO;GAAc;EAAK,CAAC,GAC/D,KAAU,QAAQ,KAAK,YAAYS,CAAI;CACzC;CAGA,OAAa;EAGX,AAFA,KAAK,SAAS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,YAAY,GACjB,KAAK,WAAW,GAChB,KAAK,MAAM;GAAE;GAAO;GAAQ,SAAS;GAAG,UAAU;EAAM,CAAC;CAC3D;AACF"}
1
+ {"version":3,"file":"DeskStreamConnection.js","names":["backoffDelay","KEEPALIVE_FRAME","buildRelayUrl","classifyClose","connectFrame","parseReady","INITIAL_STREAM_STATE","MintError","message","options","DEFAULT_TUNING","DeskStreamConnection","deps","tuning","listener","mode","frame","socket","next","partial","timers","generation","pass","error","url","session","ready","event","data","expiresAtMs","code","wasReady","livedMs","action","nearExpiry","exhaustedReason","delay","phase","reason"],"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, attempt: 0, hasFrame: false });\n }\n}\n"],"mappings":";;;AA6CA,IAAaM,IAAoC;CAC/C,OAAO;CACP,MAAM;CACN,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,UAAU;AACZ,GAYaC,IAAb,cAA+B,MAAM;CAC1B;CACA;CACT,YAAYC,GAAiBC,GAAsD;EACjF,MAAMD,CAAO,GACb,KAAK,OAAO,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YN,CAAI;KAClC;IACF;IACA,IAAI,CAAC,KAAK,eAAe;KAEvB,KAAK,gBAAgB,IACrB,KAAK,MAAM;MAAE,OAAO;MAAgB,SAAS;KAAE,CAAC,GAC3C,KAAK,QAAQM,GAAYN,CAAI;KAClC;IACF;IACA,KAAK,OAAO,UAAU,QAAQ;IAC9B;GACF;GACA,KAAK;IACH,KAAK,cAAcM,GAAYN,GAAMe,MAAS,OAAO,YAAY,KAAA,CAAS;IAC1E;EACJ;CACF;CAEQ,cACNT,GACAN,GACAoB,GACM;EACN,IAAId,MAAe,KAAK,YAAY;EAEpC,IADA,KAAK,YAAY,GACb,KAAK,WAAW,KAAK,OAAO,aAAa;GAC3C,KAAK,OAAO,UAAUc,KAAmB,aAAa;GACtD;EACF;EACA,KAAK,MAAM;GAAE,OAAO;GAAgB,SAAS,KAAK;GAAU,UAAU;EAAM,CAAC;EAC7E,IAAMC,IAAQpC,EAAa,KAAK,UAAU,KAAK,KAAK,MAAM;EAC1D,KAAK,aAAa,KAAK,KAAK,OAAO,iBAAiB;GAClD,KAAK,aAAa,MACdqB,MAAe,KAAK,cACnB,KAAK,QAAQA,GAAYN,CAAI;EACpC,GAAGqB,CAAK;CACV;CAEQ,OAAOC,GAA2BC,GAA+B;EACvE,KAAK,YAAY,GACjB,KAAK,WAAW,GAChB,KAAK,MAAM;GAAED;GAAOC;GAAQ,SAAS;GAAG,UAAU;EAAM,CAAC;CAC3D;AACF"}
@@ -1 +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"}
1
+ {"version":3,"file":"backoff.js","names":["backoffDelay","attempt","random","baseMs","capMs","exp","jitter"],"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,EACdC,GACAC,IAAuB,KAAK,QAC5BC,IAAS,KACTC,IAAQ,KACA;CACR,IAAMC,IAAM,KAAK,IAAID,GAAOD,IAAS,KAAK,KAAK,IAAI,GAAGF,IAAU,CAAC,CAAC,GAC5DK,IAAS,KAAKJ,EAAO,IAAI,IAAI,KAAK;CACxC,OAAO,KAAK,MAAMG,IAAMC,CAAM;AAChC"}
@@ -1,13 +1,13 @@
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";
1
+ import { resolveExternalGatewayUrls as e } from "@burdenoff/fe-libs/shared/config/gatewayUrls";
2
+ import { DeskStreamConnection as t } from "./DeskStreamConnection.js";
3
+ import { createPassMinter as n } from "./mintPass.js";
4
4
  // src/stewards/live/browserConnection.ts
5
5
  function r(r, i) {
6
6
  let a = null, o = null;
7
7
  return {
8
- connection: new e({
9
- mint: t(r, i),
10
- gatewayBaseUrl: () => n().workspaceBaseUrl,
8
+ connection: new t({
9
+ mint: n(r, i),
10
+ gatewayBaseUrl: () => e().workspaceBaseUrl,
11
11
  credentials: () => {
12
12
  let e = o?.getAccessToken(), t = o?.getWorkspaceToken();
13
13
  return e && t ? {
@@ -1 +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"}
1
+ {"version":3,"file":"browserConnection.js","names":["resolveExternalGatewayUrls","DeskStreamConnection","createPassMinter","createBrowserConnection","client","runId","sink","session","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,SAAgBG,EAAwBC,GAAsBC,GAAkC;CAC9F,IAAIC,IAAyB,MACzBC,IAAgC;CAwBpC,OAAO;EACL,YAAA,IAxBqBN,EAAqB;GAC1C,MAAMC,EAAiBE,GAAQC,CAAK;GACpC,sBAAsBL,EAA2B,CAAC,CAAC;GACnD,mBAAmB;IACjB,IAAMQ,IAAgBD,GAAS,eAAe,GACxCE,IAAyBF,GAAS,kBAAkB;IAC1D,OAAOC,KAAiBC,IACpB;KAAED;KAAeC;IAAuB,IACxC;GACN;GAEA,eAAeC,MAAQ,IAAI,UAAUA,CAAG;GACxC,UAAUC,MAASL,IAAOK,CAAI;GAC9B,WAAW,KAAK,IAAI;GACpB,QAAQ;IACN,aAAaC,GAAIC,MAAO,OAAO,WAAWD,GAAIC,CAAE;IAChD,eAAeC,MAAO,OAAO,aAAaA,CAAY;IACtD,cAAcF,GAAIC,MAAO,OAAO,YAAYD,GAAIC,CAAE;IAClD,gBAAgBC,MAAO,OAAO,cAAcA,CAAY;GAC1D;GACA,QAAQ,KAAK;GACb,iBAAiB,SAAS,oBAAoB;EAChD,CAEE;EACA,eAAeC,MAAS;GACtBT,IAAOS;EACT;EACA,aAAaA,MAAS;GACpBR,IAAUQ;EACZ;CACF;AACF"}
@@ -1 +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"}
1
+ {"version":3,"file":"describeStream.js","names":["REASON_KEYS","describeStream","state","iAmInControl","reason","keys","controlLease"],"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,EAAeC,GAAoBC,GAA4C;CAC7F,QAAQD,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,IAAME,IAASF,EAAM,UAAU,eACzBG,IAAOL,EAAYI,IACnBE,IAAeF,MAAW,gBAAgBD;GAChD,OAAO;IACL,MAAMD,EAAM,UAAU,WAAW,UAAU;IAC3C,UAAU,iBAAiBG,EAAK;IAChC,SAASC,IACL,wCACA,iBAAiBD,EAAK;GAC5B;EACF;CACF;AACF"}
@@ -1,7 +1,7 @@
1
- import { CreateBotmanorStewardDeskControlDocument as e, CreateBotmanorStewardLiveViewDocument as t } from "../../generated/wspace-operations.js";
2
- import { BotmanorStewardDeskHolder as n } from "../../generated/wspace-types.js";
3
- import { MintError as r } from "./DeskStreamConnection.js";
4
- import { CombinedGraphQLErrors as i } from "@apollo/client";
1
+ import { CombinedGraphQLErrors as e } from "@apollo/client";
2
+ import { CreateBotmanorStewardDeskControlDocument as t, CreateBotmanorStewardLiveViewDocument as n } from "../../generated/wspace-operations.js";
3
+ import { BotmanorStewardDeskHolder as r } from "../../generated/wspace-types.js";
4
+ import { MintError as i } from "./DeskStreamConnection.js";
5
5
  // src/stewards/live/mintPass.ts
6
6
  var a = /* @__PURE__ */ new Set([
7
7
  "FORBIDDEN",
@@ -11,16 +11,16 @@ var a = /* @__PURE__ */ new Set([
11
11
  "NOT_FOUND",
12
12
  "CONFLICT"
13
13
  ]);
14
- function o(e) {
15
- let t = e instanceof Error ? e.message : "Could not get a live view pass";
16
- if (i.is(e)) {
17
- let n = e.errors.map((e) => e.extensions?.code), i = n.some((e) => e === "FORBIDDEN" || e === "UNAUTHORIZED"), o = n.some((e) => typeof e == "string" && a.has(e));
18
- return new r(t, {
14
+ function o(t) {
15
+ let n = t instanceof Error ? t.message : "Could not get a live view pass";
16
+ if (e.is(t)) {
17
+ let e = t.errors.map((e) => e.extensions?.code), r = e.some((e) => e === "FORBIDDEN" || e === "UNAUTHORIZED"), o = e.some((e) => typeof e == "string" && a.has(e));
18
+ return new i(n, {
19
19
  retryable: !o,
20
- forbidden: i
20
+ forbidden: r
21
21
  });
22
22
  }
23
- return new r(t, { retryable: !0 });
23
+ return new i(n, { retryable: !0 });
24
24
  }
25
25
  function s(e) {
26
26
  let t = Date.parse(e.expiresAt);
@@ -29,22 +29,22 @@ function s(e) {
29
29
  relayPath: e.relayPath,
30
30
  mode: e.mode === "CONTROL" ? "control" : "view",
31
31
  expiresAtMs: Number.isFinite(t) ? t : 0,
32
- holder: e.heldBy === n.Person ? "person" : "steward"
32
+ holder: e.heldBy === r.Person ? "person" : "steward"
33
33
  };
34
34
  }
35
- function c(n, r) {
35
+ function c(e, r) {
36
36
  return async (i) => {
37
37
  try {
38
38
  if (i === "control") {
39
- let { data: t } = await n.mutate({
40
- mutation: e,
39
+ let { data: n } = await e.mutate({
40
+ mutation: t,
41
41
  variables: { runId: r }
42
42
  });
43
- if (!t) throw Error("No pass returned");
44
- return s(t.createBotmanorStewardDeskControl);
43
+ if (!n) throw Error("No pass returned");
44
+ return s(n.createBotmanorStewardDeskControl);
45
45
  }
46
- let { data: a } = await n.mutate({
47
- mutation: t,
46
+ let { data: a } = await e.mutate({
47
+ mutation: n,
48
48
  variables: { runId: r }
49
49
  });
50
50
  if (!a) throw Error("No pass returned");
@@ -1 +1 @@
1
- {"version":3,"file":"mintPass.js","names":["FINAL_CODES","toMintError","message","error","CombinedGraphQLErrors","codes","forbidden","c","final","MintError","toPass","expiresAtMs","payload","BotmanorStewardDeskHolder","createPassMinter","mode","client","CreateBotmanorStewardDeskControlDocument","data","CreateBotmanorStewardLiveViewDocument"],"sources":["../../../src/stewards/live/mintPass.ts"],"sourcesContent":["import type { ApolloClient } from '@apollo/client';\nimport { CombinedGraphQLErrors } from '@apollo/client';\nimport {\n CreateBotmanorStewardDeskControlDocument,\n CreateBotmanorStewardLiveViewDocument,\n type CreateBotmanorStewardDeskControlMutation,\n type CreateBotmanorStewardLiveViewMutation,\n} from '../../generated/wspace-operations';\nimport { BotmanorStewardDeskHolder } from '../../generated/wspace-types';\nimport { MintError, type StreamPass } from './DeskStreamConnection';\nimport type { StreamMode } from './protocol';\n\n/** GraphQL error codes where asking again cannot succeed: refusals, not hiccups. */\nconst FINAL_CODES = new Set([\n 'FORBIDDEN',\n 'UNAUTHORIZED',\n 'FEATURE_DISABLED',\n 'BAD_USER_INPUT',\n 'NOT_FOUND',\n 'CONFLICT',\n]);\n\nfunction toMintError(error: unknown): MintError {\n const message = error instanceof Error ? error.message : 'Could not get a live view pass';\n if (CombinedGraphQLErrors.is(error)) {\n const codes = error.errors.map((e) => e.extensions?.code);\n const forbidden = codes.some((c) => c === 'FORBIDDEN' || c === 'UNAUTHORIZED');\n const final = codes.some((c) => typeof c === 'string' && FINAL_CODES.has(c));\n return new MintError(message, { retryable: !final, forbidden });\n }\n // A network failure while minting is worth another try.\n return new MintError(message, { retryable: true });\n}\n\ntype PassPayload =\n | CreateBotmanorStewardLiveViewMutation['createBotmanorStewardLiveView']\n | CreateBotmanorStewardDeskControlMutation['createBotmanorStewardDeskControl'];\n\nfunction toPass(payload: PassPayload): StreamPass {\n const expiresAtMs = Date.parse(payload.expiresAt);\n return {\n token: payload.token,\n relayPath: payload.relayPath,\n mode: payload.mode === 'CONTROL' ? 'control' : 'view',\n expiresAtMs: Number.isFinite(expiresAtMs) ? expiresAtMs : 0,\n holder: payload.heldBy === BotmanorStewardDeskHolder.Person ? 'person' : 'steward',\n };\n}\n\n/**\n * Mints a one-use pass for the relay: `createBotmanorStewardDeskControl` for control (the caller\n * must have taken the run over) and `createBotmanorStewardLiveView` for watching. Mutations are\n * never cached, so a pass is never replayed from the Apollo cache.\n */\nexport function createPassMinter(client: ApolloClient, runId: string) {\n return async (mode: StreamMode): Promise<StreamPass> => {\n try {\n if (mode === 'control') {\n const { data } = await client.mutate<CreateBotmanorStewardDeskControlMutation>({\n mutation: CreateBotmanorStewardDeskControlDocument,\n variables: { runId },\n });\n if (!data) throw new Error('No pass returned');\n return toPass(data.createBotmanorStewardDeskControl);\n }\n const { data } = await client.mutate<CreateBotmanorStewardLiveViewMutation>({\n mutation: CreateBotmanorStewardLiveViewDocument,\n variables: { runId },\n });\n if (!data) throw new Error('No pass returned');\n return toPass(data.createBotmanorStewardLiveView);\n } catch (error) {\n throw toMintError(error);\n }\n };\n}\n"],"mappings":";;;;;AAaA,IAAMA,oBAAc,IAAI,IAAI;CAC1B;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAASC,EAAY,GAA2B;CAC9C,IAAMC,IAAUC,aAAiB,QAAQA,EAAM,UAAU;CACzD,IAAIC,EAAsB,GAAGD,CAAK,GAAG;EACnC,IAAME,IAAQF,EAAM,OAAO,KAAK,MAAM,EAAE,YAAY,IAAI,GAClDG,IAAYD,EAAM,MAAM,MAAME,MAAM,eAAeA,MAAM,cAAc,GACvEC,IAAQH,EAAM,MAAM,MAAM,OAAOE,KAAM,YAAYP,EAAY,IAAIO,CAAC,CAAC;EAC3E,OAAO,IAAIE,EAAUP,GAAS;GAAE,WAAW,CAACM;GAAO;EAAU,CAAC;CAChE;CAEA,OAAO,IAAIC,EAAUP,GAAS,EAAE,WAAW,GAAK,CAAC;AACnD;AAMA,SAASQ,EAAO,GAAkC;CAChD,IAAMC,IAAc,KAAK,MAAMC,EAAQ,SAAS;CAChD,OAAO;EACL,OAAOA,EAAQ;EACf,WAAWA,EAAQ;EACnB,MAAMA,EAAQ,SAAS,YAAY,YAAY;EAC/C,aAAa,OAAO,SAASD,CAAW,IAAIA,IAAc;EAC1D,QAAQC,EAAQ,WAAWC,EAA0B,SAAS,WAAW;CAC3E;AACF;AAOA,SAAgBC,EAAiB,GAAsB,GAAe;CACpE,OAAO,OAAO,MAA0C;EACtD,IAAI;GACF,IAAIC,MAAS,WAAW;IACtB,IAAM,EAAE,YAAS,MAAMC,EAAO,OAAiD;KAC7E,UAAUC;KACV,WAAW,EAAE,SAAM;IACrB,CAAC;IACD,IAAI,CAACC,GAAM,MAAU,MAAM,kBAAkB;IAC7C,OAAOR,EAAOQ,EAAK,gCAAgC;GACrD;GACA,IAAM,EAAE,YAAS,MAAMF,EAAO,OAA8C;IAC1E,UAAUG;IACV,WAAW,EAAE,SAAM;GACrB,CAAC;GACD,IAAI,CAACD,GAAM,MAAU,MAAM,kBAAkB;GAC7C,OAAOR,EAAOQ,EAAK,6BAA6B;EAClD,SAASf,GAAO;GACd,MAAMF,EAAYE,CAAK;EACzB;CACF;AACF"}
1
+ {"version":3,"file":"mintPass.js","names":["CombinedGraphQLErrors","CreateBotmanorStewardDeskControlDocument","CreateBotmanorStewardLiveViewDocument","BotmanorStewardDeskHolder","MintError","FINAL_CODES","toMintError","error","message","codes","forbidden","c","final","toPass","payload","expiresAtMs","createPassMinter","client","runId","mode","data"],"sources":["../../../src/stewards/live/mintPass.ts"],"sourcesContent":["import type { ApolloClient } from '@apollo/client';\nimport { CombinedGraphQLErrors } from '@apollo/client';\nimport {\n CreateBotmanorStewardDeskControlDocument,\n CreateBotmanorStewardLiveViewDocument,\n type CreateBotmanorStewardDeskControlMutation,\n type CreateBotmanorStewardLiveViewMutation,\n} from '../../generated/wspace-operations';\nimport { BotmanorStewardDeskHolder } from '../../generated/wspace-types';\nimport { MintError, type StreamPass } from './DeskStreamConnection';\nimport type { StreamMode } from './protocol';\n\n/** GraphQL error codes where asking again cannot succeed: refusals, not hiccups. */\nconst FINAL_CODES = new Set([\n 'FORBIDDEN',\n 'UNAUTHORIZED',\n 'FEATURE_DISABLED',\n 'BAD_USER_INPUT',\n 'NOT_FOUND',\n 'CONFLICT',\n]);\n\nfunction toMintError(error: unknown): MintError {\n const message = error instanceof Error ? error.message : 'Could not get a live view pass';\n if (CombinedGraphQLErrors.is(error)) {\n const codes = error.errors.map((e) => e.extensions?.code);\n const forbidden = codes.some((c) => c === 'FORBIDDEN' || c === 'UNAUTHORIZED');\n const final = codes.some((c) => typeof c === 'string' && FINAL_CODES.has(c));\n return new MintError(message, { retryable: !final, forbidden });\n }\n // A network failure while minting is worth another try.\n return new MintError(message, { retryable: true });\n}\n\ntype PassPayload =\n | CreateBotmanorStewardLiveViewMutation['createBotmanorStewardLiveView']\n | CreateBotmanorStewardDeskControlMutation['createBotmanorStewardDeskControl'];\n\nfunction toPass(payload: PassPayload): StreamPass {\n const expiresAtMs = Date.parse(payload.expiresAt);\n return {\n token: payload.token,\n relayPath: payload.relayPath,\n mode: payload.mode === 'CONTROL' ? 'control' : 'view',\n expiresAtMs: Number.isFinite(expiresAtMs) ? expiresAtMs : 0,\n holder: payload.heldBy === BotmanorStewardDeskHolder.Person ? 'person' : 'steward',\n };\n}\n\n/**\n * Mints a one-use pass for the relay: `createBotmanorStewardDeskControl` for control (the caller\n * must have taken the run over) and `createBotmanorStewardLiveView` for watching. Mutations are\n * never cached, so a pass is never replayed from the Apollo cache.\n */\nexport function createPassMinter(client: ApolloClient, runId: string) {\n return async (mode: StreamMode): Promise<StreamPass> => {\n try {\n if (mode === 'control') {\n const { data } = await client.mutate<CreateBotmanorStewardDeskControlMutation>({\n mutation: CreateBotmanorStewardDeskControlDocument,\n variables: { runId },\n });\n if (!data) throw new Error('No pass returned');\n return toPass(data.createBotmanorStewardDeskControl);\n }\n const { data } = await client.mutate<CreateBotmanorStewardLiveViewMutation>({\n mutation: CreateBotmanorStewardLiveViewDocument,\n variables: { runId },\n });\n if (!data) throw new Error('No pass returned');\n return toPass(data.createBotmanorStewardLiveView);\n } catch (error) {\n throw toMintError(error);\n }\n };\n}\n"],"mappings":";;;;;AAaA,IAAMK,oBAAc,IAAI,IAAI;CAC1B;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAASC,EAAYC,GAA2B;CAC9C,IAAMC,IAAUD,aAAiB,QAAQA,EAAM,UAAU;CACzD,IAAIP,EAAsB,GAAGO,CAAK,GAAG;EACnC,IAAME,IAAQF,EAAM,OAAO,KAAK,MAAM,EAAE,YAAY,IAAI,GAClDG,IAAYD,EAAM,MAAME,MAAMA,MAAM,eAAeA,MAAM,cAAc,GACvEC,IAAQH,EAAM,MAAME,MAAM,OAAOA,KAAM,YAAYN,EAAY,IAAIM,CAAC,CAAC;EAC3E,OAAO,IAAIP,EAAUI,GAAS;GAAE,WAAW,CAACI;GAAOF;EAAU,CAAC;CAChE;CAEA,OAAO,IAAIN,EAAUI,GAAS,EAAE,WAAW,GAAK,CAAC;AACnD;AAMA,SAASK,EAAOC,GAAkC;CAChD,IAAMC,IAAc,KAAK,MAAMD,EAAQ,SAAS;CAChD,OAAO;EACL,OAAOA,EAAQ;EACf,WAAWA,EAAQ;EACnB,MAAMA,EAAQ,SAAS,YAAY,YAAY;EAC/C,aAAa,OAAO,SAASC,CAAW,IAAIA,IAAc;EAC1D,QAAQD,EAAQ,WAAWX,EAA0B,SAAS,WAAW;CAC3E;AACF;AAOA,SAAgBa,EAAiBC,GAAsBC,GAAe;CACpE,OAAO,OAAOC,MAA0C;EACtD,IAAI;GACF,IAAIA,MAAS,WAAW;IACtB,IAAM,EAAEC,YAAS,MAAMH,EAAO,OAAiD;KAC7E,UAAUhB;KACV,WAAW,EAAEiB,SAAM;IACrB,CAAC;IACD,IAAI,CAACE,GAAM,MAAU,MAAM,kBAAkB;IAC7C,OAAOP,EAAOO,EAAK,gCAAgC;GACrD;GACA,IAAM,EAAEA,YAAS,MAAMH,EAAO,OAA8C;IAC1E,UAAUf;IACV,WAAW,EAAEgB,SAAM;GACrB,CAAC;GACD,IAAI,CAACE,GAAM,MAAU,MAAM,kBAAkB;GAC7C,OAAOP,EAAOO,EAAK,6BAA6B;EAClD,SAASb,GAAO;GACd,MAAMD,EAAYC,CAAK;EACzB;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"protocol.js","names":["RELAY_CLOSE","KEEPALIVE_FRAME","classifyClose","code","buildRelayUrl","relayPath","segment","base","gatewayBaseUrl","connectFrame","credentials","parseReady","value","text","type","mode","expiresAt","MAX_FRAME_BYTES","sniffImageMime","bytes","clamp01","n","normalisePoint","rect","clientX","clientY","encodeInput","input"],"sources":["../../../src/stewards/live/protocol.ts"],"sourcesContent":["/**\n * Wire contract of the gateway's `/steward-desk` relay (BOFF-16552), as the viewer sees it.\n * Source of truth: wspace-public-gateway `docs/steward-desk-relay.md` and `src/steward-desk/relay.ts`.\n *\n * Credentials travel in the first client frame because a browser WebSocket cannot set headers.\n * Everything after `ready` is opaque desk traffic. The relay never inspects it, and neither does\n * this module: input frames are built here and written to the socket, never stored or logged.\n */\n\n/** Close codes the relay uses. 1012 is a gateway restart. */\nconst RELAY_CLOSE = {\n BAD_REQUEST: 4400,\n UNAUTHORIZED: 4401,\n FORBIDDEN: 4403,\n NOT_FOUND: 4404,\n IDLE: 4408,\n LEASE_ENDED: 4410,\n TOO_MANY: 4429,\n UNAVAILABLE: 4503,\n GATEWAY_RESTART: 1012,\n} as const;\n\n/** The exact text the relay treats as a keepalive; any other client frame is desk input. */\nexport const KEEPALIVE_FRAME = '{\"type\":\"keepalive\"}';\n\nexport type StreamMode = 'view' | 'control';\n\n/** Why a stream is not running, as the UI explains it. */\nexport type StreamEndReason =\n | 'leaseEnded'\n | 'idle'\n | 'forbidden'\n | 'notFound'\n | 'signIn'\n | 'badRequest'\n | 'tooMany'\n | 'unavailable'\n | 'mintFailed';\n\n/** What the viewer does after a close code. */\nexport type CloseAction =\n | { kind: 'ended'; reason: StreamEndReason }\n | { kind: 'failed'; reason: StreamEndReason }\n | { kind: 'renewOrSignIn' }\n | { kind: 'reconnect' };\n\n/** Map a relay close code to the next step. Unknown and abnormal codes reconnect with backoff. */\nexport function classifyClose(code: number): CloseAction {\n switch (code) {\n case RELAY_CLOSE.LEASE_ENDED:\n return { kind: 'ended', reason: 'leaseEnded' };\n case RELAY_CLOSE.IDLE:\n return { kind: 'ended', reason: 'idle' };\n case RELAY_CLOSE.FORBIDDEN:\n return { kind: 'failed', reason: 'forbidden' };\n case RELAY_CLOSE.NOT_FOUND:\n return { kind: 'failed', reason: 'notFound' };\n case RELAY_CLOSE.BAD_REQUEST:\n return { kind: 'failed', reason: 'badRequest' };\n case RELAY_CLOSE.UNAUTHORIZED:\n return { kind: 'renewOrSignIn' };\n default:\n // 4429, 4503, 1006 (dropped), 1011, 1012 (gateway restart) and anything unknown.\n return { kind: 'reconnect' };\n }\n}\n\n/**\n * `wss://<gateway host><relayPath>`. The relay path comes from the API, so it is checked before a\n * credential is sent to it: it must be an absolute path on the gateway, never another host.\n * Returns null for anything else.\n */\nexport function buildRelayUrl(gatewayBaseUrl: string, relayPath: string): string | null {\n if (!/^\\/[A-Za-z0-9._~\\-/]*$/.test(relayPath) || relayPath.includes('//')) return null;\n if (relayPath.split('/').some((segment) => segment === '..' || segment === '.')) return null;\n let base: URL;\n try {\n base = new URL(gatewayBaseUrl);\n } catch {\n return null;\n }\n if (base.protocol !== 'https:' && base.protocol !== 'http:') return null;\n const protocol = base.protocol === 'https:' ? 'wss:' : 'ws:';\n return `${protocol}//${base.host}${relayPath}`;\n}\n\nexport interface ConnectCredentials {\n token: string;\n authorization: string;\n workspaceAuthorization: string;\n}\n\n/** The first frame. Built at send time so the pass is not kept around afterwards. */\nexport function connectFrame(credentials: ConnectCredentials): string {\n return JSON.stringify({ type: 'connect', ...credentials });\n}\n\nexport interface ReadyFrame {\n mode: StreamMode;\n expiresAt: number;\n}\n\n/** The relay's `ready` message, or null when the text is anything else. */\nexport function parseReady(text: string): ReadyFrame | null {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n return null;\n }\n if (typeof value !== 'object' || value === null) return null;\n const { type, mode, expiresAt } = value as Record<string, unknown>;\n if (type !== 'ready' || (mode !== 'view' && mode !== 'control')) return null;\n if (typeof expiresAt !== 'number' || !Number.isFinite(expiresAt)) return null;\n return { mode, expiresAt };\n}\n\n// ---------------------------------------------------------------------------\n// Desk frames and input\n//\n// The relay passes desk frames through untouched, so the format is agreed with the desk plugin\n// (BOFF-16145). This viewer renders a binary frame as one screen image (PNG, JPEG or WebP) and\n// ignores text frames it does not know. Input goes the other way as small JSON messages with\n// pointer positions normalised to 0..1 of the screen, so they do not depend on the image size.\n// ---------------------------------------------------------------------------\n\n/** Longest binary frame the viewer will decode, matching the relay's own ceiling. */\nexport const MAX_FRAME_BYTES = 16 * 1024 * 1024;\n\nexport type ImageMime = 'image/png' | 'image/jpeg' | 'image/webp';\n\n/** The image type of a binary frame from its leading bytes, or null when it is not an image. */\nexport function sniffImageMime(bytes: Uint8Array): ImageMime | null {\n if (\n bytes.length >= 8 &&\n bytes[0] === 0x89 &&\n bytes[1] === 0x50 &&\n bytes[2] === 0x4e &&\n bytes[3] === 0x47\n ) {\n return 'image/png';\n }\n if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {\n return 'image/jpeg';\n }\n if (\n bytes.length >= 12 &&\n bytes[0] === 0x52 && // R\n bytes[1] === 0x49 && // I\n bytes[2] === 0x46 && // F\n bytes[3] === 0x46 && // F\n bytes[8] === 0x57 && // W\n bytes[9] === 0x45 && // E\n bytes[10] === 0x42 && // B\n bytes[11] === 0x50 // P\n ) {\n return 'image/webp';\n }\n return null;\n}\n\nexport type PointerAction = 'move' | 'down' | 'up';\n\nexport type DeskInput =\n | { type: 'pointer'; action: PointerAction; x: number; y: number; button: number }\n | { type: 'wheel'; x: number; y: number; dx: number; dy: number }\n | { type: 'key'; action: 'down' | 'up'; key: string; code: string };\n\nconst clamp01 = (n: number): number => (Number.isFinite(n) ? Math.min(1, Math.max(0, n)) : 0);\n\n/** A position inside the rendered screen, as a fraction of its width and height. */\nexport function normalisePoint(\n rect: { left: number; top: number; width: number; height: number },\n clientX: number,\n clientY: number\n): { x: number; y: number } {\n if (rect.width <= 0 || rect.height <= 0) return { x: 0, y: 0 };\n return {\n x: clamp01((clientX - rect.left) / rect.width),\n y: clamp01((clientY - rect.top) / rect.height),\n };\n}\n\nexport function encodeInput(input: DeskInput): string {\n return JSON.stringify(input);\n}\n"],"mappings":";AAUA,IAAMA,IAAc;CAClB,aAAa;CACb,cAAc;CACd,WAAW;CACX,WAAW;CACX,MAAM;CACN,aAAa;CACb,UAAU;CACV,aAAa;CACb,iBAAiB;AACnB,GAGaC,IAAkB;AAwB/B,SAAgBC,EAAc,GAA2B;CACvD,QAAQC,GAAR;EACE,KAAKH,EAAY,aACf,OAAO;GAAE,MAAM;GAAS,QAAQ;EAAa;EAC/C,KAAKA,EAAY,MACf,OAAO;GAAE,MAAM;GAAS,QAAQ;EAAO;EACzC,KAAKA,EAAY,WACf,OAAO;GAAE,MAAM;GAAU,QAAQ;EAAY;EAC/C,KAAKA,EAAY,WACf,OAAO;GAAE,MAAM;GAAU,QAAQ;EAAW;EAC9C,KAAKA,EAAY,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OAAO,MACbA,EAAM,OAAO,MACbA,EAAM,OAAO,MACbA,EAAM,OAAO,MACbA,EAAM,OAAO,MACbA,EAAM,OAAO,MACbA,EAAM,QAAQ,MACdA,EAAM,QAAQ,KAEP,eAEF;AACT;AASA,IAAMC,KAAW,MAAuB,OAAO,SAASC,CAAC,IAAI,KAAK,IAAI,GAAG,KAAK,IAAI,GAAGA,CAAC,CAAC,IAAI;AAG3F,SAAgBC,EACd,GACA,GACA,GAC0B;CAE1B,OADIC,EAAK,SAAS,KAAKA,EAAK,UAAU,IAAU;EAAE,GAAG;EAAG,GAAG;CAAE,IACtD;EACL,GAAGH,GAASI,IAAUD,EAAK,QAAQA,EAAK,KAAK;EAC7C,GAAGH,GAASK,IAAUF,EAAK,OAAOA,EAAK,MAAM;CAC/C;AACF;AAEA,SAAgBG,EAAY,GAA0B;CACpD,OAAO,KAAK,UAAUC,CAAK;AAC7B"}
1
+ {"version":3,"file":"protocol.js","names":["RELAY_CLOSE","KEEPALIVE_FRAME","classifyClose","code","buildRelayUrl","gatewayBaseUrl","relayPath","segment","base","connectFrame","credentials","parseReady","text","value","type","mode","expiresAt","MAX_FRAME_BYTES","sniffImageMime","bytes","clamp01","n","normalisePoint","rect","clientX","clientY","encodeInput","input"],"sources":["../../../src/stewards/live/protocol.ts"],"sourcesContent":["/**\n * Wire contract of the gateway's `/steward-desk` relay (BOFF-16552), as the viewer sees it.\n * Source of truth: wspace-public-gateway `docs/steward-desk-relay.md` and `src/steward-desk/relay.ts`.\n *\n * Credentials travel in the first client frame because a browser WebSocket cannot set headers.\n * Everything after `ready` is opaque desk traffic. The relay never inspects it, and neither does\n * this module: input frames are built here and written to the socket, never stored or logged.\n */\n\n/** Close codes the relay uses. 1012 is a gateway restart. */\nconst RELAY_CLOSE = {\n BAD_REQUEST: 4400,\n UNAUTHORIZED: 4401,\n FORBIDDEN: 4403,\n NOT_FOUND: 4404,\n IDLE: 4408,\n LEASE_ENDED: 4410,\n TOO_MANY: 4429,\n UNAVAILABLE: 4503,\n GATEWAY_RESTART: 1012,\n} as const;\n\n/** The exact text the relay treats as a keepalive; any other client frame is desk input. */\nexport const KEEPALIVE_FRAME = '{\"type\":\"keepalive\"}';\n\nexport type StreamMode = 'view' | 'control';\n\n/** Why a stream is not running, as the UI explains it. */\nexport type StreamEndReason =\n | 'leaseEnded'\n | 'idle'\n | 'forbidden'\n | 'notFound'\n | 'signIn'\n | 'badRequest'\n | 'tooMany'\n | 'unavailable'\n | 'mintFailed';\n\n/** What the viewer does after a close code. */\nexport type CloseAction =\n | { kind: 'ended'; reason: StreamEndReason }\n | { kind: 'failed'; reason: StreamEndReason }\n | { kind: 'renewOrSignIn' }\n | { kind: 'reconnect' };\n\n/** Map a relay close code to the next step. Unknown and abnormal codes reconnect with backoff. */\nexport function classifyClose(code: number): CloseAction {\n switch (code) {\n case RELAY_CLOSE.LEASE_ENDED:\n return { kind: 'ended', reason: 'leaseEnded' };\n case RELAY_CLOSE.IDLE:\n return { kind: 'ended', reason: 'idle' };\n case RELAY_CLOSE.FORBIDDEN:\n return { kind: 'failed', reason: 'forbidden' };\n case RELAY_CLOSE.NOT_FOUND:\n return { kind: 'failed', reason: 'notFound' };\n case RELAY_CLOSE.BAD_REQUEST:\n return { kind: 'failed', reason: 'badRequest' };\n case RELAY_CLOSE.UNAUTHORIZED:\n return { kind: 'renewOrSignIn' };\n default:\n // 4429, 4503, 1006 (dropped), 1011, 1012 (gateway restart) and anything unknown.\n return { kind: 'reconnect' };\n }\n}\n\n/**\n * `wss://<gateway host><relayPath>`. The relay path comes from the API, so it is checked before a\n * credential is sent to it: it must be an absolute path on the gateway, never another host.\n * Returns null for anything else.\n */\nexport function buildRelayUrl(gatewayBaseUrl: string, relayPath: string): string | null {\n if (!/^\\/[A-Za-z0-9._~\\-/]*$/.test(relayPath) || relayPath.includes('//')) return null;\n if (relayPath.split('/').some((segment) => segment === '..' || segment === '.')) return null;\n let base: URL;\n try {\n base = new URL(gatewayBaseUrl);\n } catch {\n return null;\n }\n if (base.protocol !== 'https:' && base.protocol !== 'http:') return null;\n const protocol = base.protocol === 'https:' ? 'wss:' : 'ws:';\n return `${protocol}//${base.host}${relayPath}`;\n}\n\nexport interface ConnectCredentials {\n token: string;\n authorization: string;\n workspaceAuthorization: string;\n}\n\n/** The first frame. Built at send time so the pass is not kept around afterwards. */\nexport function connectFrame(credentials: ConnectCredentials): string {\n return JSON.stringify({ type: 'connect', ...credentials });\n}\n\nexport interface ReadyFrame {\n mode: StreamMode;\n expiresAt: number;\n}\n\n/** The relay's `ready` message, or null when the text is anything else. */\nexport function parseReady(text: string): ReadyFrame | null {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n return null;\n }\n if (typeof value !== 'object' || value === null) return null;\n const { type, mode, expiresAt } = value as Record<string, unknown>;\n if (type !== 'ready' || (mode !== 'view' && mode !== 'control')) return null;\n if (typeof expiresAt !== 'number' || !Number.isFinite(expiresAt)) return null;\n return { mode, expiresAt };\n}\n\n// ---------------------------------------------------------------------------\n// Desk frames and input\n//\n// The relay passes desk frames through untouched, so the format is agreed with the desk plugin\n// (BOFF-16145). This viewer renders a binary frame as one screen image (PNG, JPEG or WebP) and\n// ignores text frames it does not know. Input goes the other way as small JSON messages with\n// pointer positions normalised to 0..1 of the screen, so they do not depend on the image size.\n// ---------------------------------------------------------------------------\n\n/** Longest binary frame the viewer will decode, matching the relay's own ceiling. */\nexport const MAX_FRAME_BYTES = 16 * 1024 * 1024;\n\nexport type ImageMime = 'image/png' | 'image/jpeg' | 'image/webp';\n\n/** The image type of a binary frame from its leading bytes, or null when it is not an image. */\nexport function sniffImageMime(bytes: Uint8Array): ImageMime | null {\n if (\n bytes.length >= 8 &&\n bytes[0] === 0x89 &&\n bytes[1] === 0x50 &&\n bytes[2] === 0x4e &&\n bytes[3] === 0x47\n ) {\n return 'image/png';\n }\n if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {\n return 'image/jpeg';\n }\n if (\n bytes.length >= 12 &&\n bytes[0] === 0x52 && // R\n bytes[1] === 0x49 && // I\n bytes[2] === 0x46 && // F\n bytes[3] === 0x46 && // F\n bytes[8] === 0x57 && // W\n bytes[9] === 0x45 && // E\n bytes[10] === 0x42 && // B\n bytes[11] === 0x50 // P\n ) {\n return 'image/webp';\n }\n return null;\n}\n\nexport type PointerAction = 'move' | 'down' | 'up';\n\nexport type DeskInput =\n | { type: 'pointer'; action: PointerAction; x: number; y: number; button: number }\n | { type: 'wheel'; x: number; y: number; dx: number; dy: number }\n | { type: 'key'; action: 'down' | 'up'; key: string; code: string };\n\nconst clamp01 = (n: number): number => (Number.isFinite(n) ? Math.min(1, Math.max(0, n)) : 0);\n\n/** A position inside the rendered screen, as a fraction of its width and height. */\nexport function normalisePoint(\n rect: { left: number; top: number; width: number; height: number },\n clientX: number,\n clientY: number\n): { x: number; y: number } {\n if (rect.width <= 0 || rect.height <= 0) return { x: 0, y: 0 };\n return {\n x: clamp01((clientX - rect.left) / rect.width),\n y: clamp01((clientY - rect.top) / rect.height),\n };\n}\n\nexport function encodeInput(input: DeskInput): string {\n return JSON.stringify(input);\n}\n"],"mappings":";AAUA,IAAMA,IAAc;CAClB,aAAa;CACb,cAAc;CACd,WAAW;CACX,WAAW;CACX,MAAM;CACN,aAAa;CACb,UAAU;CACV,aAAa;CACb,iBAAiB;AACnB,GAGaC,IAAkB;AAwB/B,SAAgBC,EAAcC,GAA2B;CACvD,QAAQA,GAAR;EACE,KAAKH,EAAY,aACf,OAAO;GAAE,MAAM;GAAS,QAAQ;EAAa;EAC/C,KAAKA,EAAY,MACf,OAAO;GAAE,MAAM;GAAS,QAAQ;EAAO;EACzC,KAAKA,EAAY,WACf,OAAO;GAAE,MAAM;GAAU,QAAQ;EAAY;EAC/C,KAAKA,EAAY,WACf,OAAO;GAAE,MAAM;GAAU,QAAQ;EAAW;EAC9C,KAAKA,EAAY,aACf,OAAO;GAAE,MAAM;GAAU,QAAQ;EAAa;EAChD,KAAKA,EAAY,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A,EAAM,OAAO,MACbA,EAAM,OAAO,MACbA,EAAM,OAAO,MACbA,EAAM,QAAQ,MACdA,EAAM,QAAQ,KAEP,eAEF;AACT;AASA,IAAMC,KAAWC,MAAuB,OAAO,SAASA,CAAC,IAAI,KAAK,IAAI,GAAG,KAAK,IAAI,GAAGA,CAAC,CAAC,IAAI;AAG3F,SAAgBC,EACdC,GACAC,GACAC,GAC0B;CAE1B,OADIF,EAAK,SAAS,KAAKA,EAAK,UAAU,IAAU;EAAE,GAAG;EAAG,GAAG;CAAE,IACtD;EACL,GAAGH,GAASI,IAAUD,EAAK,QAAQA,EAAK,KAAK;EAC7C,GAAGH,GAASK,IAAUF,EAAK,OAAOA,EAAK,MAAM;CAC/C;AACF;AAEA,SAAgBG,EAAYC,GAA0B;CACpD,OAAO,KAAK,UAAUA,CAAK;AAC7B"}
@@ -1,20 +1,20 @@
1
- import { createBrowserConnection as e } from "./browserConnection.js";
2
- import { INITIAL_STREAM_STATE as t } from "./DeskStreamConnection.js";
3
- import { useEffect as n, useMemo as r, useSyncExternalStore as i } from "react";
4
- import { useApolloClient as a } from "@apollo/client/react";
5
- import { useAuthTokenOrNull as o } from "@burdenoff/fe-libs/shared/providers/shell";
1
+ import { useEffect as e, useMemo as t, useSyncExternalStore as n } from "react";
2
+ import { useApolloClient as r } from "@apollo/client/react";
3
+ import { useAuthTokenOrNull as i } from "@burdenoff/fe-libs/shared/providers/shell";
4
+ import { createBrowserConnection as a } from "./browserConnection.js";
5
+ import { INITIAL_STREAM_STATE as o } from "./DeskStreamConnection.js";
6
6
  // src/stewards/live/useDeskStream.ts
7
7
  function s(s, c = null) {
8
- let l = a(), u = o(), d = r(() => e(l, s), [l, s]);
9
- n(() => {
8
+ let l = r(), u = i(), d = t(() => a(l, s), [l, s]);
9
+ e(() => {
10
10
  d.setSession(u);
11
- }, [d, u]), n(() => () => d.connection.stop(), [d]);
11
+ }, [d, u]), e(() => () => d.connection.stop(), [d]);
12
12
  let { connection: f } = d;
13
- return n(() => {
13
+ return e(() => {
14
14
  c ? f.start(c) : f.stop();
15
15
  }, [f, c]), {
16
- state: i(f.subscribe, f.getState, () => t),
17
- ...r(() => ({
16
+ state: n(f.subscribe, f.getState, () => o),
17
+ ...t(() => ({
18
18
  start: (e) => f.start(e),
19
19
  stop: () => f.stop(),
20
20
  send: (e) => f.send(e),
@@ -1 +1 @@
1
- {"version":3,"file":"useDeskStream.js","names":["useDeskStream","client","useApolloClient","auth","useAuthTokenOrNull","bundle","useMemo","createBrowserConnection","runId","useEffect","wanted","connection","useSyncExternalStore","INITIAL_STREAM_STATE","mode","frame"],"sources":["../../../src/stewards/live/useDeskStream.ts"],"sourcesContent":["import { useEffect, useMemo, useSyncExternalStore } from 'react';\nimport { useApolloClient } from '@apollo/client/react';\nimport { useAuthTokenOrNull } from '@burdenoff/fe-libs/shared/providers/shell';\nimport { createBrowserConnection, type FrameSink } from './browserConnection';\nimport { INITIAL_STREAM_STATE, type StreamState } from './DeskStreamConnection';\nimport type { StreamMode } from './protocol';\n\nexport type { FrameSink };\n\nexport interface DeskStream {\n state: StreamState;\n start: (mode: StreamMode) => void;\n stop: () => void;\n /** Write one input frame; false when the stream is not live control. */\n send: (frame: string) => boolean;\n /** Where desk frames go (the canvas). Frames are not kept in React state. */\n setFrameSink: (sink: FrameSink | null) => void;\n}\n\n/**\n * Thin React binding over `DeskStreamConnection`: one connection per run, closed on unmount.\n *\n * `wanted` is the mode the caller wants the stream in, or `null` for no stream. The hook keeps\n * the connection in step with it, so a mode change (control changing hands) reconnects in the\n * new mode and `null` disconnects. `start` stays available for an explicit reconnect after the\n * stream ended or failed while `wanted` did not change.\n */\nexport function useDeskStream(runId: string, wanted: StreamMode | null = null): DeskStream {\n const client = useApolloClient();\n const auth = useAuthTokenOrNull();\n const bundle = useMemo(() => createBrowserConnection(client, runId), [client, runId]);\n\n useEffect(() => {\n bundle.setSession(auth);\n }, [bundle, auth]);\n useEffect(() => () => bundle.connection.stop(), [bundle]);\n\n const { connection } = bundle;\n useEffect(() => {\n if (wanted) connection.start(wanted);\n else connection.stop();\n }, [connection, wanted]);\n\n const state = useSyncExternalStore(\n connection.subscribe,\n connection.getState,\n () => INITIAL_STREAM_STATE\n );\n // Stable identities, so callers can pass them to memoised children.\n const actions = useMemo(\n () => ({\n start: (mode: StreamMode) => connection.start(mode),\n stop: () => connection.stop(),\n send: (frame: string) => connection.send(frame),\n setFrameSink: bundle.setFrameSink,\n }),\n [connection, bundle]\n );\n return { state, ...actions };\n}\n"],"mappings":";;;;;;AA2BA,SAAgBA,EAAc,GAAe,IAA4B,MAAkB;CACzF,IAAMC,IAASC,EAAgB,GACzBC,IAAOC,EAAmB,GAC1BC,IAASC,QAAcC,EAAwBN,GAAQO,CAAK,GAAG,CAACP,GAAQO,CAAK,CAAC;CAKpF,AAHAC,QAAgB;EACd,EAAO,WAAWN,CAAI;CACxB,GAAG,CAACE,GAAQF,CAAI,CAAC,GACjBM,cAAsBJ,EAAO,WAAW,KAAK,GAAG,CAACA,CAAM,CAAC;CAExD,IAAM,EAAE,kBAAeA;CAqBvB,OApBAI,QAAgB;EACd,AAAIC,IAAQC,EAAW,MAAMD,CAAM,IAC9BC,EAAW,KAAK;CACvB,GAAG,CAACA,GAAYD,CAAM,CAAC,GAiBhB;EAAE,OAfKE,EACZD,EAAW,WACXA,EAAW,gBACLE,CAYC;EAAO,GATAP,SACP;GACL,QAAQ,MAAqBK,EAAW,MAAMG,CAAI;GAClD,YAAYH,EAAW,KAAK;GAC5B,OAAO,MAAkBA,EAAW,KAAKI,CAAK;GAC9C,cAAcV,EAAO;EACvB,IACA,CAACM,GAAYN,CAAM,CAEF;CAAQ;AAC7B"}
1
+ {"version":3,"file":"useDeskStream.js","names":["useEffect","useMemo","useSyncExternalStore","useApolloClient","useAuthTokenOrNull","createBrowserConnection","INITIAL_STREAM_STATE","useDeskStream","runId","wanted","client","auth","bundle","connection","mode","frame"],"sources":["../../../src/stewards/live/useDeskStream.ts"],"sourcesContent":["import { useEffect, useMemo, useSyncExternalStore } from 'react';\nimport { useApolloClient } from '@apollo/client/react';\nimport { useAuthTokenOrNull } from '@burdenoff/fe-libs/shared/providers/shell';\nimport { createBrowserConnection, type FrameSink } from './browserConnection';\nimport { INITIAL_STREAM_STATE, type StreamState } from './DeskStreamConnection';\nimport type { StreamMode } from './protocol';\n\nexport type { FrameSink };\n\nexport interface DeskStream {\n state: StreamState;\n start: (mode: StreamMode) => void;\n stop: () => void;\n /** Write one input frame; false when the stream is not live control. */\n send: (frame: string) => boolean;\n /** Where desk frames go (the canvas). Frames are not kept in React state. */\n setFrameSink: (sink: FrameSink | null) => void;\n}\n\n/**\n * Thin React binding over `DeskStreamConnection`: one connection per run, closed on unmount.\n *\n * `wanted` is the mode the caller wants the stream in, or `null` for no stream. The hook keeps\n * the connection in step with it, so a mode change (control changing hands) reconnects in the\n * new mode and `null` disconnects. `start` stays available for an explicit reconnect after the\n * stream ended or failed while `wanted` did not change.\n */\nexport function useDeskStream(runId: string, wanted: StreamMode | null = null): DeskStream {\n const client = useApolloClient();\n const auth = useAuthTokenOrNull();\n const bundle = useMemo(() => createBrowserConnection(client, runId), [client, runId]);\n\n useEffect(() => {\n bundle.setSession(auth);\n }, [bundle, auth]);\n useEffect(() => () => bundle.connection.stop(), [bundle]);\n\n const { connection } = bundle;\n useEffect(() => {\n if (wanted) connection.start(wanted);\n else connection.stop();\n }, [connection, wanted]);\n\n const state = useSyncExternalStore(\n connection.subscribe,\n connection.getState,\n () => INITIAL_STREAM_STATE\n );\n // Stable identities, so callers can pass them to memoised children.\n const actions = useMemo(\n () => ({\n start: (mode: StreamMode) => connection.start(mode),\n stop: () => connection.stop(),\n send: (frame: string) => connection.send(frame),\n setFrameSink: bundle.setFrameSink,\n }),\n [connection, bundle]\n );\n return { state, ...actions };\n}\n"],"mappings":";;;;;;AA2BA,SAAgBO,EAAcC,GAAeC,IAA4B,MAAkB;CACzF,IAAMC,IAASP,EAAgB,GACzBQ,IAAOP,EAAmB,GAC1BQ,IAASX,QAAcI,EAAwBK,GAAQF,CAAK,GAAG,CAACE,GAAQF,CAAK,CAAC;CAEpFR,QAAgB;EACdY,EAAO,WAAWD,CAAI;CACxB,GAAG,CAACC,GAAQD,CAAI,CAAC,GACjBX,cAAsBY,EAAO,WAAW,KAAK,GAAG,CAACA,CAAM,CAAC;CAExD,IAAM,EAAEC,kBAAeD;CAqBvB,OApBAZ,QAAgB;EACVS,IAAQI,EAAW,MAAMJ,CAAM,IAC9BI,EAAW,KAAK;CACvB,GAAG,CAACA,GAAYJ,CAAM,CAAC,GAiBhB;EAAE,OAfKP,EACZW,EAAW,WACXA,EAAW,gBACLP,CAYC;EAAO,GATAL,SACP;GACL,QAAQa,MAAqBD,EAAW,MAAMC,CAAI;GAClD,YAAYD,EAAW,KAAK;GAC5B,OAAOE,MAAkBF,EAAW,KAAKE,CAAK;GAC9C,cAAcH,EAAO;EACvB,IACA,CAACC,GAAYD,CAAM,CAEF;CAAQ;AAC7B"}