@vitrinka/web 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +34 -1
  3. package/build/hud.d.ts +4 -1
  4. package/build/hud.iife.js +6 -6
  5. package/build/one.iife.js +1 -0
  6. package/build/recorder/RecorderProvider.js +48 -9
  7. package/build/recorder/capture/console.d.ts +2 -0
  8. package/build/recorder/capture/console.js +22 -2
  9. package/build/recorder/capture/nav.d.ts +13 -2
  10. package/build/recorder/capture/nav.js +49 -11
  11. package/build/recorder/capture/net.d.ts +2 -0
  12. package/build/recorder/capture/net.js +30 -4
  13. package/build/recorder/control.d.ts +17 -0
  14. package/build/recorder/control.js +39 -2
  15. package/build/recorder/hud/Hud.js +70 -20
  16. package/build/recorder/hud/RecorderPill.js +6 -2
  17. package/build/recorder/hud/chords.d.ts +10 -0
  18. package/build/recorder/hud/chords.js +34 -0
  19. package/build/recorder/hud/controller.d.ts +24 -0
  20. package/build/recorder/hud/flow.d.ts +22 -1
  21. package/build/recorder/hud/flow.js +16 -1
  22. package/build/recorder/index.d.ts +1 -0
  23. package/build/recorder/index.js +1 -0
  24. package/build/recorder/lead.d.ts +90 -0
  25. package/build/recorder/lead.js +404 -0
  26. package/build/recorder/one-iife.d.ts +13 -0
  27. package/build/recorder/one-iife.js +13 -0
  28. package/build/recorder/one.d.ts +170 -0
  29. package/build/recorder/one.js +292 -0
  30. package/build/recorder/page-controller.js +23 -2
  31. package/build/recorder/queue.js +5 -2
  32. package/build/recorder/report.js +9 -2
  33. package/build/recorder/session.d.ts +22 -4
  34. package/build/recorder/session.js +70 -20
  35. package/build/recorder/state.d.ts +9 -0
  36. package/build/recorder/state.js +7 -0
  37. package/build/recorder/version.d.ts +3 -0
  38. package/build/recorder/version.js +3 -0
  39. package/package.json +5 -3
@@ -0,0 +1 @@
1
+ (()=>{var{defineProperty:E,getOwnPropertyNames:z,getOwnPropertyDescriptor:K}=Object,B=Object.prototype.hasOwnProperty;function j(e){return this[e]}var G=(e)=>{var n=(w??=new WeakMap).get(e),t;if(n)return n;if(n=E({},"__esModule",{value:!0}),e&&typeof e==="object"||typeof e==="function"){for(var o of z(e))if(!B.call(n,o))E(n,o,{get:j.bind(e,o),enumerable:!(t=K(e,o))||t.enumerable})}return w.set(e,n),n},w;var J=(e)=>e;function W(e,n){this[e]=J.bind(null,n)}var Z=(e,n)=>{for(var t in n)E(e,t,{get:n[t],enumerable:!0,configurable:!0,set:W.bind(n,t)})};var cn={};var _={};Z(_,{ACK_EVENT:()=>C,COMMAND_EVENT:()=>x,HELLO_EVENT:()=>c,LEAD_ATTR:()=>l,ONE_VERSION:()=>u,PAGE_ATTR:()=>d,announce:()=>H,answeredBy:()=>D,ask:()=>M,documentEnv:()=>F,holderAnswers:()=>V,isLive:()=>k,markPage:()=>rn,nonce:()=>h,pageMarked:()=>an,parseAck:()=>R,parseClaim:()=>L,parseCommand:()=>P,parseHello:()=>A,readClaim:()=>b,releaseClaim:()=>tn,sendCommand:()=>ln,serializeClaim:()=>I,serveCommands:()=>dn,serveHello:()=>un,takeClaim:()=>nn,unmarkPage:()=>sn,updateClaim:()=>en,watchClaim:()=>on});function S(e,n,t,o={}){let r=e,i=r.__zone_symbol__addEventListener??e.addEventListener,a=r.__zone_symbol__removeEventListener??e.removeEventListener,p=o.capture??!1;return i.call(e,n,t,{capture:p,passive:!1}),()=>a.call(e,n,t,p)}var u=1,d="data-vitrinka-page",l="data-vitrinka-lead",c="vitrinka:hello",x="vitrinka:command",C="vitrinka:ack";function F(){let n=globalThis.document?.documentElement;if(!n||typeof globalThis.dispatchEvent!=="function")return null;return{root:n,bus:globalThis}}function h(e){return`${e}.${Math.random().toString(36).slice(2,10)}`}var q=["page","extension"],Q=["starting","recording","paused","stopping","saved"],U=["pause","stop","note"],X=["not_recording","stopping","not_here","bad_command"];function v(e){if(typeof e!=="string")return null;try{let n=JSON.parse(e);return n!==null&&typeof n==="object"&&!Array.isArray(n)?n:null}catch{return null}}var s=(e)=>typeof e==="string",f=(e)=>s(e)&&q.includes(e),T=(e)=>s(e)&&Q.includes(e),g=(e)=>typeof e==="number"&&Number.isInteger(e)&&e>=1;function L(e){let n=v(e);if(!n||!g(n.v)||!f(n.by)||!s(n.id)||!n.id||!T(n.state))return null;return{v:n.v,by:n.by,id:n.id,state:n.state,sessionId:s(n.sessionId)?n.sessionId:"",since:typeof n.since==="number"?n.since:0}}function I(e){return JSON.stringify({v:e.v,by:e.by,id:e.id,state:e.state,sessionId:e.sessionId,since:e.since})}function k(e){return e!==void 0&&e!==null&&e!=="saved"}function Y(e){if(e===null||typeof e!=="object"||Array.isArray(e))return null;let n=e;if(!f(n.by)||!T(n.state))return null;return{by:n.by,state:n.state,here:n.here===!0,...s(n.id)&&n.id?{id:n.id}:{}}}function A(e){let n=v(e);if(!n||!g(n.v)||!f(n.from)||!s(n.inst)||!n.inst)return null;let t=Y(n.live);return{v:n.v,from:n.from,inst:n.inst,...n.ask===!0?{ask:!0}:{},...n.live!==void 0?{live:t}:{},...n.gone===!0?{gone:!0}:{}}}function P(e){let n=v(e);if(!n||!g(n.v)||!f(n.from)||!s(n.inst)||!n.inst||!s(n.id)||!n.id)return null;if(!s(n.op)||!U.includes(n.op))return null;return{v:n.v,from:n.from,inst:n.inst,id:n.id,op:n.op,...s(n.text)?{text:n.text}:{}}}function R(e){let n=v(e);if(!n||!g(n.v)||!f(n.from)||!s(n.inst)||!s(n.id)||typeof n.ok!=="boolean")return null;return{v:n.v,from:n.from,inst:n.inst,id:n.id,ok:n.ok,...s(n.code)&&X.includes(n.code)?{code:n.code}:{},...s(n.error)?{error:n.error}:{}}}function b(e){return L(e.root.getAttribute(l))}function N(e,n){let t=I(n);if(e.root.getAttribute(l)!==t)e.root.setAttribute(l,t)}function nn(e,n,t){let o=b(e);if(o&&o.id!==t.id&&k(o.state)&&V(e,n,o))return{ok:!1,holder:o};let r={v:u,by:n.from,id:t.id,state:t.state,sessionId:t.sessionId??"",since:o?.id===t.id&&k(o.state)?o.since:Date.now()};return N(e,r),{ok:!0,claim:r}}function en(e,n,t){let o=b(e);if(o?.id!==n)return!1;return N(e,{...o,v:u,state:t.state,sessionId:t.sessionId??o.sessionId}),!0}function tn(e,n){if(b(e)?.id!==n)return!1;return e.root.removeAttribute(l),!0}function on(e,n){if(e.watch)return e.watch(n);if(typeof MutationObserver!=="function"||typeof Node>"u"||!(e.root instanceof Node))return()=>{return};let t=new MutationObserver(n);return t.observe(e.root,{attributes:!0,attributeFilter:[l]}),()=>t.disconnect()}function rn(e,n){if(e.root.getAttribute(d)!==n)e.root.setAttribute(d,n)}function sn(e){e.root.removeAttribute(d)}function an(e){return e.root.getAttribute(d)!==null}function y(e,n,t){e.bus.dispatchEvent(new CustomEvent(n,{detail:JSON.stringify(t)}))}function O(e,n,t){return S(e.bus,n,(o)=>t(o.detail))}function M(e,n){let t=[],o=O(e,c,(r)=>{let i=A(r);if(i&&!i.ask&&i.inst!==n.inst)t.push(i)});try{y(e,c,{v:u,from:n.from,inst:n.inst,ask:!0})}finally{o()}return t}function H(e,n,t,o={}){y(e,c,{v:u,from:n.from,inst:n.inst,live:t,...o.gone?{gone:!0}:{}})}function un(e,n,t,o,r={}){return O(e,c,(i)=>{let a=A(i);if(!a||a.inst===n.inst)return;if(!a.ask)o?.(a);else if(r.answerIf?.()??!0)H(e,n,t())})}function D(e,n){return e.some((t)=>t.live?.here===!0&&(t.live.id?t.live.id===n.id:t.from===n.by))}function V(e,n,t){return D(M(e,n),t)}function ln(e,n,t,o){let r=h("c"),i=null,a=O(e,C,(p)=>{let m=R(p);if(m&&m.id===r&&m.inst!==n.inst&&!i)i=m});try{y(e,x,{v:u,from:n.from,inst:n.inst,id:r,op:t,...o!==void 0?{text:o}:{}})}finally{a()}return i}function dn(e,n,t){return O(e,x,(o)=>{let r=P(o);if(!r||r.inst===n.inst)return;let i=t(r);if(!i)return;y(e,C,{v:u,from:n.from,inst:n.inst,id:r.id,...i})})}globalThis.VitrinkaOne=Object.freeze({..._});})();
@@ -7,19 +7,20 @@ import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
7
7
  */
8
8
  import { useEffect } from 'react';
9
9
  import { installClickLane } from './capture/click';
10
- import { patchConsole, unpatchConsole } from './capture/console';
11
- import { installNavLane, noteNavigation, primeNavigation } from './capture/nav';
12
- import { patchNetwork, unpatchNetwork } from './capture/net';
10
+ import { ownConsolePatch, patchConsole, unpatchConsole } from './capture/console';
11
+ import { installNavLane, noteNavigation, ownNavLane, primeNavigation } from './capture/nav';
12
+ import { ownNetworkPatch, patchNetwork, unpatchNetwork } from './capture/net';
13
13
  import { checkoutRRWeb, flushRRWeb, startFlightRRWeb, startRRWeb, stopRRWeb } from './capture/rrweb';
14
14
  import { configureRecorder } from './config';
15
15
  import { installControl } from './control';
16
16
  import { flightActive } from './flight';
17
17
  import { installUnauthorizedHandler } from './link';
18
18
  import { insideHud } from './hud/host';
19
+ import { startLead } from './lead';
19
20
  import { armReconcile, flush, getState, persistNow, reconcile, scheduleFlush } from './queue';
20
21
  import { dropFlight, syncFlight } from './report';
21
- import { followOtherTabs, onBeforeStop, recoverRedactionPolicy } from './session';
22
- import { annotateState, setTabIdentity, subscribe } from './state';
22
+ import { addNote, followOtherTabs, onBeforeStop, recoverRedactionPolicy, resyncStoredSession, stopSession, togglePause } from './session';
23
+ import { annotateState, leadState, setTabIdentity, subscribe } from './state';
23
24
  const TAB_KEY = 'vitrinka.tab';
24
25
  /** One lane per browser tab: a per-tab id kept in sessionStorage (survives reloads). */
25
26
  function tabId() {
@@ -43,13 +44,38 @@ export function RecorderProvider({ config, children, }) {
43
44
  }, [config]);
44
45
  useEffect(() => {
45
46
  setTabIdentity(tabId(), location.host);
47
+ // ONE recorder: mark the document, hear who records, then lead or follow.
48
+ // A remote command opens this recorder's own doors.
49
+ const leaveLead = startLead({
50
+ pause: () => void togglePause(),
51
+ stop: () => void stopSession().catch((e) => console.warn('vitrinka: remote stop —', e instanceof Error ? e.message : e)),
52
+ note: (text) => addNote(text),
53
+ resync: resyncStoredSession,
54
+ });
46
55
  primeNavigation();
47
56
  // The fetch/XHR and console patches are idempotent (a globalThis mark)
48
57
  // and UNINSTALLED on unmount below, so the recorder never outlives its
49
58
  // tree; the History wrap is idempotent too and stays (a nav event with no
50
59
  // session is dropped at the queue unless the flight recorder holds it).
51
- patchNetwork();
52
- patchConsole();
60
+ // They are global, so with two recorder bundles on the page the one that
61
+ // starts capturing takes them over (`own*`): whoever leads, not whoever
62
+ // mounted first, hears the traffic. A mount takes the wrappers over too
63
+ // (a stale Fast Refresh copy's, an idle bundle's) unless another bundle
64
+ // on the page leads — never from under a live recording.
65
+ /** True when the nav takeover recorded the navigation it had missed. */
66
+ const ownLanes = () => {
67
+ ownNetworkPatch();
68
+ ownConsolePatch();
69
+ return ownNavLane();
70
+ };
71
+ if (leadState.following === 'page') {
72
+ patchNetwork();
73
+ patchConsole();
74
+ }
75
+ else {
76
+ ownNetworkPatch();
77
+ ownConsolePatch();
78
+ }
53
79
  installNavLane();
54
80
  const uninstallClicks = installClickLane({
55
81
  ignore: (t) => annotateState.active || insideHud(t),
@@ -59,15 +85,27 @@ export function RecorderProvider({ config, children, }) {
59
85
  // Keep the rrweb lane in step with the session: start on record, a fresh
60
86
  // checkout on resume, ship-and-stop on stop. While idle the same lane
61
87
  // feeds the pill's flight recorder; it hands rrweb over (one record() at
62
- // a time) before a recording takes it.
88
+ // a time) before a recording takes it. A follower records nothing: its
89
+ // own session (if any) waits until the leader lets go.
63
90
  let wasRecording = false;
64
91
  let wasPaused = false;
65
92
  let wasFlying = false;
93
+ // This document's own session waited while another recorder led (D14).
94
+ let waited = false;
66
95
  const syncLanes = () => {
67
96
  void syncFlight();
68
97
  const rec = getState();
69
- const recording = rec !== null && !rec.dead;
98
+ if (rec !== null && leadState.following !== null)
99
+ waited = true;
100
+ const recording = rec !== null && !rec.dead && leadState.following === null;
70
101
  const flying = flightActive();
102
+ const caughtUp = (recording && !wasRecording) || (flying && !wasFlying) ? ownLanes() : false;
103
+ // A waiting session resumes: its timeline gets this document's nav as a
104
+ // keyframe (the mount's, captured while following, was dropped).
105
+ if (recording && !wasRecording && waited && !caughtUp)
106
+ noteNavigation(true);
107
+ if (rec === null || recording)
108
+ waited = false;
71
109
  if (wasFlying && !flying)
72
110
  stopRRWeb();
73
111
  if (recording && !wasRecording)
@@ -123,6 +161,7 @@ export function RecorderProvider({ config, children, }) {
123
161
  dropFlight();
124
162
  unpatchNetwork();
125
163
  unpatchConsole();
164
+ leaveLead();
126
165
  };
127
166
  // The lanes install once per mount; config changes are handled above.
128
167
  // eslint-disable-next-line react-hooks/exhaustive-deps
@@ -1,3 +1,5 @@
1
1
  /** Restore console.error (while it is still ours) and drop the window listeners. */
2
2
  export declare function unpatchConsole(): void;
3
+ /** Make this module's wrapper the live one (a no-op when it already is). */
4
+ export declare function ownConsolePatch(): void;
3
5
  export declare function patchConsole(): void;
@@ -34,15 +34,35 @@ function record(text) {
34
34
  pushEvent('console', { level: 'error', text: redactText(text) }, { tabId: currentRoute.tabId, tabHost: currentRoute.tabHost });
35
35
  }
36
36
  const UNPATCH_MARK = '__vitrinkaRecorderConsoleUnpatch';
37
+ /**
38
+ * This module instance's mark. The wrappers are global, so the mark says WHOSE
39
+ * are live: another recorder bundle's on the page, or a stale Fast Refresh
40
+ * copy's. `ownConsolePatch` hands them to this one (ONE recorder: whoever leads
41
+ * captures, not whoever mounted first).
42
+ */
43
+ const OWNER = {};
37
44
  /** Restore console.error (while it is still ours) and drop the window listeners. */
38
45
  export function unpatchConsole() {
39
- globalThis[UNPATCH_MARK]?.();
46
+ const g = globalThis;
47
+ // Another bundle's live wrapper is its own to remove.
48
+ if (g[PATCH_MARK] !== undefined && g[PATCH_MARK] !== OWNER)
49
+ return;
50
+ g[UNPATCH_MARK]?.();
51
+ }
52
+ /** Make this module's wrapper the live one (a no-op when it already is). */
53
+ export function ownConsolePatch() {
54
+ const g = globalThis;
55
+ if (g[PATCH_MARK] === OWNER)
56
+ return;
57
+ g[UNPATCH_MARK]?.();
58
+ delete g[PATCH_MARK];
59
+ patchConsole();
40
60
  }
41
61
  export function patchConsole() {
42
62
  const g = globalThis;
43
63
  if (g[PATCH_MARK])
44
64
  return;
45
- g[PATCH_MARK] = true;
65
+ g[PATCH_MARK] = OWNER;
46
66
  const origError = console.error;
47
67
  const orig = origError.bind(console);
48
68
  const patched = (...args) => {
@@ -1,8 +1,19 @@
1
- /** Record a navigation to the document's current URL (idempotent per URL). */
2
- export declare function noteNavigation(): void;
1
+ /**
2
+ * Record a navigation to the document's current URL (idempotent per URL;
3
+ * `force` records it again — the keyframe of a session that resumes here).
4
+ * True when it recorded one.
5
+ */
6
+ export declare function noteNavigation(force?: boolean): boolean;
3
7
  /** Seed the dedupe with the URL the session started on (its nav is pushed by startSession). */
4
8
  export declare function primeNavigation(): void;
5
9
  /** Wrap pushState/replaceState + popstate/hashchange. Idempotent across HMR. */
6
10
  export declare function installNavLane(): void;
11
+ /**
12
+ * Make this module's History wrap the live one (ONE recorder): the first
13
+ * recorder bundle on the page installs it, but whichever bundle leads must
14
+ * hear the navigations. A no-op when it already is; true when the takeover
15
+ * recorded the navigation it had missed.
16
+ */
17
+ export declare function ownNavLane(): boolean;
7
18
  /** Test-only. */
8
19
  export declare function __resetNavForTests(): void;
@@ -9,17 +9,21 @@ import { pushEvent } from '../queue';
9
9
  import { currentRoute, setCurrentPath } from '../state';
10
10
  import { redactUrl } from './redact';
11
11
  let lastUrl = '';
12
- /** Record a navigation to the document's current URL (idempotent per URL). */
13
- export function noteNavigation() {
12
+ /**
13
+ * Record a navigation to the document's current URL (idempotent per URL;
14
+ * `force` records it again — the keyframe of a session that resumes here).
15
+ * True when it recorded one.
16
+ */
17
+ export function noteNavigation(force = false) {
14
18
  const loc = globalThis.location;
15
19
  if (!loc)
16
- return;
20
+ return false;
17
21
  const url = loc.href;
18
22
  setCurrentPath(loc.pathname);
19
- if (url === lastUrl)
20
- return;
23
+ if (url === lastUrl && !force)
24
+ return false;
21
25
  lastUrl = url;
22
- pushEvent('nav', { url: redactUrl(url), route: loc.pathname, spa: true }, { tabId: currentRoute.tabId, tabHost: currentRoute.tabHost });
26
+ return null !== pushEvent('nav', { url: redactUrl(url), route: loc.pathname, spa: true }, { tabId: currentRoute.tabId, tabHost: currentRoute.tabHost });
23
27
  }
24
28
  /** Seed the dedupe with the URL the session started on (its nav is pushed by startSession). */
25
29
  export function primeNavigation() {
@@ -27,26 +31,60 @@ export function primeNavigation() {
27
31
  setCurrentPath(globalThis.location?.pathname ?? '/');
28
32
  }
29
33
  const PATCH_MARK = '__vitrinkaRecorderNavPatched';
34
+ const UNPATCH_MARK = '__vitrinkaRecorderNavUnpatch';
35
+ /** This module instance's mark — whose History wrap is live (see `ownNavLane`). */
36
+ const OWNER = {};
30
37
  /** Wrap pushState/replaceState + popstate/hashchange. Idempotent across HMR. */
31
38
  export function installNavLane() {
32
39
  const g = globalThis;
33
40
  if (g[PATCH_MARK] || typeof history === 'undefined')
34
41
  return;
35
- g[PATCH_MARK] = true;
42
+ g[PATCH_MARK] = OWNER;
43
+ const restores = [];
36
44
  const wrap = (name) => {
37
45
  const orig = history[name];
38
- history[name] = function (...args) {
46
+ const wrapped = (history[name] = function (...args) {
39
47
  const r = orig.apply(this, args);
40
48
  // After the URL changed, off the caller's stack so a router's own
41
49
  // synchronous state update never sees the recorder in its way.
42
50
  queueMicrotask(noteNavigation);
43
51
  return r;
44
- };
52
+ });
53
+ // Restored only while it is still ours: a wrap stacked on top keeps ours beneath it.
54
+ restores.push(() => {
55
+ if (history[name] === wrapped)
56
+ history[name] = orig;
57
+ });
45
58
  };
46
59
  wrap('pushState');
47
60
  wrap('replaceState');
48
- addEventListener('popstate', () => queueMicrotask(noteNavigation));
49
- addEventListener('hashchange', () => queueMicrotask(noteNavigation));
61
+ const onNav = () => queueMicrotask(noteNavigation);
62
+ addEventListener('popstate', onNav);
63
+ addEventListener('hashchange', onNav);
64
+ g[UNPATCH_MARK] = () => {
65
+ for (const r of restores.splice(0))
66
+ r();
67
+ removeEventListener('popstate', onNav);
68
+ removeEventListener('hashchange', onNav);
69
+ delete g[PATCH_MARK];
70
+ delete g[UNPATCH_MARK];
71
+ };
72
+ }
73
+ /**
74
+ * Make this module's History wrap the live one (ONE recorder): the first
75
+ * recorder bundle on the page installs it, but whichever bundle leads must
76
+ * hear the navigations. A no-op when it already is; true when the takeover
77
+ * recorded the navigation it had missed.
78
+ */
79
+ export function ownNavLane() {
80
+ const g = globalThis;
81
+ if (g[PATCH_MARK] === OWNER)
82
+ return false;
83
+ g[UNPATCH_MARK]?.();
84
+ delete g[PATCH_MARK];
85
+ installNavLane();
86
+ // The navigations before the takeover reached the other bundle only: catch up.
87
+ return noteNavigation();
50
88
  }
51
89
  /** Test-only. */
52
90
  export function __resetNavForTests() {
@@ -19,4 +19,6 @@ export declare function __readBoundedTextForTests(clone: Response, headers: Head
19
19
  * (no session ⇒ the wrapper passes straight through).
20
20
  */
21
21
  export declare function unpatchNetwork(): void;
22
+ /** Make this module's wrappers the live ones (a no-op when they already are). */
23
+ export declare function ownNetworkPatch(): void;
22
24
  export declare function patchNetwork(): void;
@@ -16,7 +16,7 @@
16
16
  import { isVitrinkaUrl } from '../config';
17
17
  import { flightTarget } from '../flight';
18
18
  import { getState, pushEvent, trackCapture } from '../queue';
19
- import { currentRoute } from '../state';
19
+ import { currentRoute, leadState } from '../state';
20
20
  import { redactAndCap, redactHeaders, redactUrl } from './redact';
21
21
  const BODY_CAP = 64 * 1024;
22
22
  /**
@@ -47,6 +47,9 @@ function capturing() {
47
47
  * null), else the idle flight recorder's buffer, else null.
48
48
  */
49
49
  function captureTarget() {
50
+ // A follower captures nothing (ONE recorder D2).
51
+ if (leadState.following)
52
+ return null;
50
53
  const rec = getState();
51
54
  if (rec)
52
55
  return !rec.paused && !rec.dead ? rec.sessionId : null;
@@ -343,6 +346,13 @@ export function __readBoundedTextForTests(clone, headers) {
343
346
  const PATCH_MARK = '__vitrinkaRecorderNetPatched';
344
347
  /** The uninstaller of the live patch, kept on globalThis for the same reason as the mark. */
345
348
  const UNPATCH_MARK = '__vitrinkaRecorderNetUnpatch';
349
+ /**
350
+ * This module instance's mark. The wrappers are global, so the mark says WHOSE
351
+ * are live: another recorder bundle's on the page, or a stale Fast Refresh
352
+ * copy's. `ownNetworkPatch` hands them to this one (ONE recorder: whoever leads
353
+ * captures, not whoever mounted first).
354
+ */
355
+ const OWNER = {};
346
356
  /**
347
357
  * Remove the fetch/XHR wrappers installed by `patchNetwork` — the provider's
348
358
  * unmount calls it so the recorder never outlives its tree. Each global is
@@ -353,13 +363,25 @@ const UNPATCH_MARK = '__vitrinkaRecorderNetUnpatch';
353
363
  */
354
364
  export function unpatchNetwork() {
355
365
  const g = globalThis;
366
+ // Another bundle's live wrappers are its own to remove.
367
+ if (g[PATCH_MARK] !== undefined && g[PATCH_MARK] !== OWNER)
368
+ return;
369
+ g[UNPATCH_MARK]?.();
370
+ }
371
+ /** Make this module's wrappers the live ones (a no-op when they already are). */
372
+ export function ownNetworkPatch() {
373
+ const g = globalThis;
374
+ if (g[PATCH_MARK] === OWNER)
375
+ return;
356
376
  g[UNPATCH_MARK]?.();
377
+ delete g[PATCH_MARK];
378
+ patchNetwork();
357
379
  }
358
380
  export function patchNetwork() {
359
381
  const g = globalThis;
360
382
  if (g[PATCH_MARK])
361
383
  return;
362
- g[PATCH_MARK] = true;
384
+ g[PATCH_MARK] = OWNER;
363
385
  const restores = [];
364
386
  g[UNPATCH_MARK] = () => {
365
387
  for (const r of restores.splice(0))
@@ -396,9 +418,13 @@ export function patchNetwork() {
396
418
  const status = res.status;
397
419
  trackCapture((async () => {
398
420
  // Re-check AFTER the await, and require the SAME session — the run may
399
- // have been paused/stopped meanwhile.
400
- if (!stillCapturing(origin))
421
+ // have been paused/stopped meanwhile, or another recorder took the
422
+ // lead. An abandoned clone is cancelled, never left buffering its tee.
423
+ if (!stillCapturing(origin)) {
424
+ if (clone)
425
+ discard(clone);
401
426
  return;
427
+ }
402
428
  const resBody = clone ? await readBoundedBody(clone, headers) : undefined;
403
429
  if (!stillCapturing(origin))
404
430
  return;
@@ -1,6 +1,23 @@
1
+ /**
2
+ * Programmatic control handle — `window.__vitrinkaRecorder`. The web sibling
3
+ * of the Expo recorder's devtools channel: an agent driving the page with
4
+ * Playwright can start a journey, drop notes and stop it without touching
5
+ * the HUD, and read a status snapshot back.
6
+ *
7
+ * ONE recorder: while the browser extension (or another recorder on the
8
+ * page) leads, `status()` names it (`leader`, `following`), `pause`, `stop`
9
+ * and `note` act on it, and `start` rejects with a `RecorderBusyError`
10
+ * (`code: 'recorder_busy'`).
11
+ */
12
+ import { type Leader } from './lead';
1
13
  import { type StartOptions } from './session';
2
14
  export interface RecorderStatus {
15
+ /** A recording captures this document — this recorder's, or the leader's it follows. */
3
16
  recording: boolean;
17
+ /** Who records: this page's recorder, or the one it follows. Absent = nobody. */
18
+ leader?: Leader;
19
+ /** Set while another recorder leads; pause, stop and note then act on it. */
20
+ following?: Leader;
4
21
  sessionId?: string;
5
22
  project?: string;
6
23
  environment?: string;
@@ -3,17 +3,37 @@
3
3
  * of the Expo recorder's devtools channel: an agent driving the page with
4
4
  * Playwright can start a journey, drop notes and stop it without touching
5
5
  * the HUD, and read a status snapshot back.
6
+ *
7
+ * ONE recorder: while the browser extension (or another recorder on the
8
+ * page) leads, `status()` names it (`leader`, `following`), `pause`, `stop`
9
+ * and `note` act on it, and `start` rejects with a `RecorderBusyError`
10
+ * (`code: 'recorder_busy'`).
6
11
  */
12
+ import { leadStatus, sendToLeader } from './lead';
7
13
  import { getState, health } from './queue';
8
14
  import { boardUrlOf } from './recents';
9
15
  import { addNote, elapsedOf, startSession, stopSession, togglePause } from './session';
10
16
  export function snapshot() {
17
+ const lead = leadStatus();
18
+ if (lead.following) {
19
+ // The leader's claim on this document (none when it records another tab).
20
+ const c = lead.claim && lead.claim.by === lead.following ? lead.claim : null;
21
+ const live = c !== null && c.state !== 'saved';
22
+ return {
23
+ recording: live,
24
+ leader: lead.following,
25
+ following: lead.following,
26
+ ...(live && c.sessionId ? { sessionId: c.sessionId } : {}),
27
+ ...(live ? { paused: c.state === 'paused' } : {}),
28
+ };
29
+ }
11
30
  const rec = getState();
12
31
  if (!rec)
13
32
  return { recording: false };
14
33
  const h = health();
15
34
  return {
16
35
  recording: true,
36
+ leader: 'page',
17
37
  sessionId: rec.sessionId,
18
38
  project: rec.project,
19
39
  environment: rec.environment,
@@ -34,19 +54,36 @@ export function installControl() {
34
54
  const control = {
35
55
  async start(opts = {}) {
36
56
  // Idempotent: a second start must not orphan the first recording.
37
- if (getState())
57
+ if (getState() && !leadStatus().following)
38
58
  throw new Error('vitrinka: a session is already recording');
59
+ // Another recorder leading refuses here, before any network call (RecorderBusyError).
39
60
  await startSession(opts);
40
61
  return snapshot();
41
62
  },
42
- pause: () => togglePause(),
63
+ async pause() {
64
+ if (!leadStatus().following)
65
+ return togglePause();
66
+ const was = snapshot().paused === true;
67
+ sendToLeader('pause');
68
+ return !was;
69
+ },
43
70
  async stop() {
71
+ if (leadStatus().following) {
72
+ const captured = snapshot();
73
+ sendToLeader('stop');
74
+ return captured;
75
+ }
44
76
  const captured = snapshot();
45
77
  const done = await stopSession();
46
78
  return { ...captured, boardUrl: boardUrlOf(done) ?? captured.boardUrl };
47
79
  },
48
80
  note(text) {
49
81
  const t = text.trim();
82
+ if (leadStatus().following) {
83
+ if (!t)
84
+ throw new Error('vitrinka: note text is empty');
85
+ return sendToLeader('note', t);
86
+ }
50
87
  if (!getState())
51
88
  throw new Error('vitrinka: no session is recording');
52
89
  if (!t)
@@ -13,6 +13,7 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
13
13
  import { useCallback, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore, } from 'react';
14
14
  import { createPortal } from 'react-dom';
15
15
  import { AnnotateOverlay } from './AnnotateOverlay';
16
+ import { bindChords } from './chords';
16
17
  import { flowReducer, NO_FLOW } from './flow';
17
18
  import { createSheetHost, insideHud, sheetTarget } from './host';
18
19
  import { anchoredLayer, hostOrigin, PHONE_QUERY, phoneLayer, restingBox, useFloat, useMedia, usePresence, useViewportTick, } from './layer';
@@ -266,7 +267,11 @@ export function Hud({ controller, hostMount, defaultTitle, storage }) {
266
267
  setStarting(true);
267
268
  controller
268
269
  .start({ title: defaultTitle() })
269
- .catch((e) => console.warn('vitrinka: start failed', e))
270
+ .catch((e) => {
271
+ // A refusal (another recorder leads, D12) or a failed create: the pill says why.
272
+ console.warn('vitrinka: start failed', e);
273
+ dispatch({ type: 'startFailed', message: errorText(e) });
274
+ })
270
275
  .finally(() => setStarting(false));
271
276
  }, [controller, defaultTitle, beginLink]);
272
277
  onStartRef.current = onStart;
@@ -274,9 +279,18 @@ export function Hud({ controller, hostMount, defaultTitle, storage }) {
274
279
  void controller.togglePause();
275
280
  }, [controller]);
276
281
  // The inline flows. Stop drains first; a refusal (offline) keeps the session.
282
+ // One Stop at a time: a remote stop (D11) or a Retry arriving while a save
283
+ // is out never starts a second one; the flag clears as the face settles.
284
+ const stopInFlight = useRef(false);
277
285
  const runStop = useCallback(() => {
286
+ if (stopInFlight.current)
287
+ return;
288
+ stopInFlight.current = true;
278
289
  const t0 = Date.now();
279
- const settle = (ev) => setTimeout(() => dispatch(ev), Math.max(0, MIN_SAVING_MS - (Date.now() - t0)));
290
+ const settle = (ev) => setTimeout(() => {
291
+ stopInFlight.current = false;
292
+ dispatch(ev);
293
+ }, Math.max(0, MIN_SAVING_MS - (Date.now() - t0)));
280
294
  controller.stop().then((r) => settle({ type: 'saved', ...r }), (e) => {
281
295
  console.warn('vitrinka: stop —', errorText(e));
282
296
  settle({ type: 'failed', message: errorText(e) });
@@ -317,6 +331,9 @@ export function Hud({ controller, hostMount, defaultTitle, storage }) {
317
331
  dispatch({ type: 'dismiss' });
318
332
  }, [failedReport, controller]);
319
333
  const onRetry = useCallback(() => {
334
+ // A refused Start has nothing to retry (and must never run a Stop).
335
+ if (flow.face === 'failed' && flow.start)
336
+ return;
320
337
  if (failedReport) {
321
338
  dispatch({ type: 'retry', queued: 0 });
322
339
  if (reportRef.current)
@@ -325,7 +342,7 @@ export function Hud({ controller, hostMount, defaultTitle, storage }) {
325
342
  }
326
343
  dispatch({ type: 'retry', queued: controller.getSnapshot().recording?.sync.queued ?? 0 });
327
344
  runStop();
328
- }, [failedReport, controller, runStop, runReport]);
345
+ }, [flow, failedReport, controller, runStop, runReport]);
329
346
  // A stop confirm outlives nothing: the session ended under it (401, the server).
330
347
  useEffect(() => {
331
348
  if (!rec && flow.face === 'confirm' && flow.action === 'stop')
@@ -355,27 +372,57 @@ export function Hud({ controller, hostMount, defaultTitle, storage }) {
355
372
  void controller.getMe();
356
373
  void controller.refreshRecents();
357
374
  }, [menu, controller]);
358
- // Shortcuts (window keydown, CAPTURE — the host's shield stops a keydown
359
- // from a focused HUD control before it could bubble to window, and a drag
360
- // leaves the handle focused): ⌥⇧A annotate · ⌥⇧N note · ⌥⇧P pause · ⌥⇧S stop.
375
+ // ONE recorder: another recorder leads and this HUD is its remote (D8).
376
+ const following = snap.following ?? null;
377
+ // Becoming the remote — or ceasing to be — leaves nothing open: the sheet,
378
+ // menu, link sheet and annotate mode close (the drafts and their images
379
+ // survive, as a cancel keeps them), and the pill comes back idle.
380
+ const wasFollowing = useRef(following);
361
381
  useEffect(() => {
362
- const key = (e) => {
363
- if (!e.altKey || !e.shiftKey || e.metaKey || e.ctrlKey)
364
- return;
365
- if (e.code === 'KeyA')
382
+ if (wasFollowing.current === following)
383
+ return;
384
+ wasFollowing.current = following;
385
+ dispatch({ type: 'follow' });
386
+ if (!following)
387
+ return;
388
+ setSheet(null);
389
+ setMenu(false);
390
+ setMarking(false);
391
+ closeLink();
392
+ controller.setAnnotating(false);
393
+ }, [following, closeLink, controller]);
394
+ // A remote stop (D11) runs this HUD's own Stop flow: no second confirm.
395
+ const remoteStop = useRef(() => undefined);
396
+ remoteStop.current = () => {
397
+ setSheet(null);
398
+ setMenu(false);
399
+ setMarking(false);
400
+ controller.setAnnotating(false);
401
+ dispatch({ type: 'stop', queued: controller.getSnapshot().recording?.sync.queued ?? 0 });
402
+ runStop();
403
+ };
404
+ useEffect(() => controller.onRemoteStop?.(() => remoteStop.current()), [controller]);
405
+ // The controller holds its claim as `saved` while a stop's face shows (D7).
406
+ useEffect(() => {
407
+ controller.faceChanged?.(flow.face);
408
+ }, [flow.face, controller]);
409
+ useEffect(() => () => controller.faceChanged?.('none'), [controller]);
410
+ // Shortcuts (chords.ts): ⌥⇧A annotate · ⌥⇧N note · ⌥⇧P pause · ⌥⇧S stop —
411
+ // bound by the leader's HUD only (D9).
412
+ useEffect(() => {
413
+ if (following)
414
+ return;
415
+ return bindChords(window, (c) => {
416
+ if (c === 'annotate')
366
417
  toggleAnnotate();
367
- else if (e.code === 'KeyN')
418
+ else if (c === 'note')
368
419
  openNote();
369
- else if (e.code === 'KeyP')
420
+ else if (c === 'pause')
370
421
  onPause();
371
- else if (e.code === 'KeyS')
372
- askStop();
373
422
  else
374
- return;
375
- e.preventDefault();
376
- };
377
- return listen(window, 'keydown', key, { capture: true });
378
- }, [toggleAnnotate, openNote, onPause, askStop]);
423
+ askStop();
424
+ });
425
+ }, [following, toggleAnnotate, openNote, onPause, askStop]);
379
426
  // Esc anywhere and click-outside close the sheet (capture-phase, so the
380
427
  // page's own dialog never sees the Esc that closed ours).
381
428
  useEffect(() => {
@@ -542,5 +589,8 @@ export function Hud({ controller, hostMount, defaultTitle, storage }) {
542
589
  const dockAttrs = 'tuck' in place
543
590
  ? { 'data-tuck': place.tuck, style: { '--ty': String(place.y) } }
544
591
  : { 'data-row': rowOf(place.spot), 'data-col': colOf(place.spot) };
545
- return (_jsxs("div", { ref: rootRef, className: "hud", "data-size": snap.prefs.size, "data-spot": 'spot' in place ? place.spot : undefined, children: [_jsx("style", { children: HUD_CSS }), annotating && (rec || marking) ? _jsx(AnnotateOverlay, { onPick: onPick, onCancel: cancelAnnotate }) : null, _jsx("div", { ref: dock.ref, className: dock.dragging ? 'dock dragging' : 'dock', ...dockAttrs, onClickCapture: dock.onClickCapture, children: _jsx(RecorderPill, { snap: snap, now: now, flow: flow, flash: flash, composing: sheet !== null, starting: starting, menuOpen: menu, place: place, dragging: dock.dragging, handle: dock.handle, pillRef: pillRef, onMove: dock.moveTo, onLink: beginLink, onStart: onStart, onPause: onPause, onNote: openNote, onAnnotate: toggleAnnotate, onMenu: toggleMenu, onAskStop: askStop, onConfirm: onConfirm, onCancel: onCancel, onRetry: onRetry, onDismiss: onDismiss }) }), menuP.mounted ? (_jsx(Menu, { snap: snap, now: now, place: place, className: `grow ${menuP.cls}`, menuRef: menuRef, onClose: () => setMenu(false), onMove: dock.moveTo, onSize: (size) => void controller.setPrefs({ size }), onVerbose: (verbose) => void controller.setPrefs({ verbose }), onAskUnlink: askUnlink, onLink: beginLink, ...(snap.canReport && controller.report ? { onReport: openReport } : {}) })) : null, _jsx(Tooltip, { root: rootRef, side: side, suppressed: dock.dragging || menu || layerOpen }), detailP.mounted && detailRec ? (_jsx("div", { ref: detailRef, className: ['float detail grow', detailP.cls, snap.prefs.verbose ? '' : 'line', line ? 'bad' : ''].filter(Boolean).join(' '), "data-e2e": "recorder-detail", "aria-hidden": "true", children: snap.prefs.verbose ? (_jsxs(_Fragment, { children: [_jsxs("dl", { children: [_jsx("dt", { children: "events" }), _jsx("dd", { children: detailRec.sync.events }), _jsx("dt", { children: "queue" }), _jsxs("dd", { children: [detailRec.sync.queued, detailRec.sync.chunks ? ` (${detailRec.sync.chunks} chunk${detailRec.sync.chunks === 1 ? '' : 's'})` : ''] }), _jsx("dt", { children: "last sync" }), _jsx("dd", { children: detailRec.sync.lastSyncAt === null ? '—' : `${fmtAgo(now - detailRec.sync.lastSyncAt)} · ${detailRec.sync.state}` }), _jsx("dt", { children: "server seq" }), _jsx("dd", { children: Math.max(0, detailRec.sync.serverMaxSeq) }), _jsx("dt", { children: "session" }), _jsx("dd", { children: detailRec.sessionId }), _jsx("dt", { children: "recorder" }), _jsx("dd", { children: snap.version })] }), line ? _jsx("div", { className: "warnline", children: line }) : null] })) : (line) })) : null, sheetEl && portal ? createPortal(sheetEl, portal.mount) : null, linkP.mounted && shownLink ? (_jsx("div", { ref: layerRef, className: layerCls, style: layer.style, children: _jsx(LinkSheet, { className: `${motionCls} ${linkP.cls}`, origin: layer.origin, phase: shownLink.phase, start: shownLink.flow?.start ?? null, error: shownLink.error, onRetry: beginLink, onClose: closeLink }) })) : null, _jsx("div", { className: "sr", role: "status", "aria-live": "polite", children: status })] }));
592
+ // A remote shows nothing (D7: one pill per document) — except a refused
593
+ // Start's face, which says why the pill steps aside until it is dismissed.
594
+ const hidden = following !== null && !(flow.face === 'failed' && flow.start === true);
595
+ return (_jsxs("div", { ref: rootRef, className: "hud", "data-size": snap.prefs.size, "data-spot": 'spot' in place ? place.spot : undefined, ...(hidden ? { 'data-following': following, style: { display: 'none' } } : {}), children: [_jsx("style", { children: HUD_CSS }), annotating && (rec || marking) ? _jsx(AnnotateOverlay, { onPick: onPick, onCancel: cancelAnnotate }) : null, _jsx("div", { ref: dock.ref, className: dock.dragging ? 'dock dragging' : 'dock', ...dockAttrs, onClickCapture: dock.onClickCapture, children: _jsx(RecorderPill, { snap: snap, now: now, flow: flow, flash: flash, composing: sheet !== null, starting: starting, menuOpen: menu, place: place, dragging: dock.dragging, handle: dock.handle, pillRef: pillRef, onMove: dock.moveTo, onLink: beginLink, onStart: onStart, onPause: onPause, onNote: openNote, onAnnotate: toggleAnnotate, onMenu: toggleMenu, onAskStop: askStop, onConfirm: onConfirm, onCancel: onCancel, onRetry: onRetry, onDismiss: onDismiss }) }), menuP.mounted ? (_jsx(Menu, { snap: snap, now: now, place: place, className: `grow ${menuP.cls}`, menuRef: menuRef, onClose: () => setMenu(false), onMove: dock.moveTo, onSize: (size) => void controller.setPrefs({ size }), onVerbose: (verbose) => void controller.setPrefs({ verbose }), onAskUnlink: askUnlink, onLink: beginLink, ...(snap.canReport && controller.report ? { onReport: openReport } : {}) })) : null, _jsx(Tooltip, { root: rootRef, side: side, suppressed: dock.dragging || menu || layerOpen }), detailP.mounted && detailRec ? (_jsx("div", { ref: detailRef, className: ['float detail grow', detailP.cls, snap.prefs.verbose ? '' : 'line', line ? 'bad' : ''].filter(Boolean).join(' '), "data-e2e": "recorder-detail", "aria-hidden": "true", children: snap.prefs.verbose ? (_jsxs(_Fragment, { children: [_jsxs("dl", { children: [_jsx("dt", { children: "events" }), _jsx("dd", { children: detailRec.sync.events }), _jsx("dt", { children: "queue" }), _jsxs("dd", { children: [detailRec.sync.queued, detailRec.sync.chunks ? ` (${detailRec.sync.chunks} chunk${detailRec.sync.chunks === 1 ? '' : 's'})` : ''] }), _jsx("dt", { children: "last sync" }), _jsx("dd", { children: detailRec.sync.lastSyncAt === null ? '—' : `${fmtAgo(now - detailRec.sync.lastSyncAt)} · ${detailRec.sync.state}` }), _jsx("dt", { children: "server seq" }), _jsx("dd", { children: Math.max(0, detailRec.sync.serverMaxSeq) }), _jsx("dt", { children: "session" }), _jsx("dd", { children: detailRec.sessionId }), _jsx("dt", { children: "recorder" }), _jsx("dd", { children: snap.version })] }), line ? _jsx("div", { className: "warnline", children: line }) : null] })) : (line) })) : null, sheetEl && portal ? createPortal(sheetEl, portal.mount) : null, linkP.mounted && shownLink ? (_jsx("div", { ref: layerRef, className: layerCls, style: layer.style, children: _jsx(LinkSheet, { className: `${motionCls} ${linkP.cls}`, origin: layer.origin, phase: shownLink.phase, start: shownLink.flow?.start ?? null, error: shownLink.error, onRetry: beginLink, onClose: closeLink }) })) : null, _jsx("div", { className: "sr", role: "status", "aria-live": "polite", children: status })] }));
546
596
  }