@vitrinka/web 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,56 @@
1
1
  # @vitrinka/web
2
2
 
3
+ ## 0.11.0
4
+
5
+ - **A report shows how the reporter got there.** Report a problem sent a
6
+ replay and one marked frame: the report's timeline in vitrinka held a
7
+ single step, with no page, click, console line or request before it. The
8
+ report face now keeps the clicks and page changes of the kept minutes
9
+ beside the replay (the recorder pill's click and navigation lanes, under
10
+ the `interactions` capture class) and sends them with the report, and each
11
+ network entry says when it finished (`ts`). vitrinka places all of them on
12
+ the report's timeline, with a frame for each click and page.
13
+ - A click is sent as its selector, its text as the replay shows it (nothing
14
+ under strict masking, never a field's value), its box and its route; a page
15
+ change as its origin and path, never a query or a fragment, with token-shaped
16
+ path segments scrubbed. A profile without `interactions` keeps neither.
17
+ - A report that goes without a replay sends no clicks or page changes: there
18
+ is no session for them to stand on.
19
+ - A press at or under a region the replay blocks (`.rr-block`, the
20
+ recorder's own `data-vitrinka-recorder`) is not sent at all.
21
+ - A report with a **Cover** sends no clicks (its page changes still go): a
22
+ click carries its element's text from when it was pressed, and nothing
23
+ matches that against what the reporter covered.
24
+ - While Report a problem runs a page's capture, what it captures goes to the
25
+ report's own buffer alone, even when another tab of the site is recording
26
+ with the pill; before, its console and network entries were written into
27
+ that recording.
28
+ - **Reports from one sitting stay together: test rounds.** The first report
29
+ a browser sends opens a test round in vitrinka, which hands back the
30
+ round's token; Report a problem keeps it for the site (every tab, across
31
+ reloads) and sends it as `round` with each later report, so the team sees
32
+ which reports came from one person's one sitting. vitrinka decides when a
33
+ round is over (two quiet hours, or the reporter ending it) and opens a new
34
+ one for the next report. Nothing to configure: no option, no attribute.
35
+ - The token is kept in localStorage under its own key per vitrinka and
36
+ report key (`vitrinka.recorder.report.round:<vitrinka>|<key>`), so two
37
+ projects' widgets on one site never share a round. It names no person and
38
+ reads nothing.
39
+
40
+ Upgrading:
41
+
42
+ - **The server side ships in vitrinka first.** An older vitrinka ignores a
43
+ network entry's `ts` and files the clicks and page changes as it would any
44
+ staged row; its timeline shows the clicks and pages but no console or
45
+ network steps.
46
+ - **The report face now wraps `history.pushState` and `replaceState`** while
47
+ it captures (as the recorder pill always has), and restores them when it
48
+ unmounts.
49
+ - An older vitrinka also refuses the unknown `round` by name; the widget then sends the report again without
50
+ it, once, as it does for `type`, and every report files on its own.
51
+ - Ending a round from the widget has no control yet: it arrives with the
52
+ pill. Until then a round ends after two quiet hours.
53
+
3
54
  ## 0.10.1
4
55
 
5
56
  - Rebuilt from the cleaned repository history, with no behaviour change.
@@ -8,6 +8,8 @@ export declare function noteNavigation(force?: boolean): boolean;
8
8
  export declare function primeNavigation(): void;
9
9
  /** Wrap pushState/replaceState + popstate/hashchange. Idempotent across HMR. */
10
10
  export declare function installNavLane(): void;
11
+ /** Remove this module's History wrap and its listeners; another bundle's live wrap is its own to remove. */
12
+ export declare function uninstallNavLane(): void;
11
13
  /**
12
14
  * Make this module's History wrap the live one (ONE recorder): the first
13
15
  * recorder bundle on the page installs it, but whichever bundle leads must
@@ -70,6 +70,13 @@ export function installNavLane() {
70
70
  delete g[UNPATCH_MARK];
71
71
  };
72
72
  }
73
+ /** Remove this module's History wrap and its listeners; another bundle's live wrap is its own to remove. */
74
+ export function uninstallNavLane() {
75
+ const g = globalThis;
76
+ if (g[PATCH_MARK] !== OWNER)
77
+ return;
78
+ g[UNPATCH_MARK]?.();
79
+ }
73
80
  /**
74
81
  * Make this module's History wrap the live one (ONE recorder): the first
75
82
  * recorder bundle on the page installs it, but whichever bundle leads must
@@ -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, leadState } from '../state';
19
+ import { captureFace, currentRoute, leadState } from '../state';
20
20
  import { redactAndCap, redactHeaders, redactUrl } from './redact';
21
21
  const BODY_CAP = 64 * 1024;
22
22
  /**
@@ -52,6 +52,11 @@ function captureTarget() {
52
52
  // A follower captures nothing (ONE recorder D2).
53
53
  if (leadState.following)
54
54
  return null;
55
+ // The report face runs this document's capture: its requests are the
56
+ // report buffer's, whatever recording another tab of the origin holds —
57
+ // live, paused or dead (queue.ts pushEvent sends them there).
58
+ if (captureFace() === 'report')
59
+ return flightTarget();
55
60
  const rec = getState();
56
61
  if (rec)
57
62
  return !rec.paused && !rec.dead ? rec.sessionId : null;
@@ -1,6 +1,6 @@
1
1
  import { api, permanentStatus, uploadChunk, uploadImage, VitrinkaApiError } from './api';
2
2
  import { pushFlightEvent } from './flight';
3
- import { leadState, notify } from './state';
3
+ import { captureFace, leadState, notify } from './state';
4
4
  import { getRecorderStorage } from './storage';
5
5
  import { getRecorderBlobStore } from './storage/blobs';
6
6
  const FLUSH_MS = 2000;
@@ -970,6 +970,13 @@ export function pushEvent(kind, payload, route, images = []) {
970
970
  // A follower captures nothing: the leader records this document (ONE recorder D2).
971
971
  if (leadState.following)
972
972
  return null;
973
+ // The report face runs this document's capture: its lanes feed the
974
+ // report's own buffer, under its profile's shapes, and nothing leaves until
975
+ // the reporter presses Send — never the recording another tab of this
976
+ // origin started (the session state is the origin's, the capture claim is
977
+ // this document's).
978
+ if (captureFace() === 'report')
979
+ return pushFlightEvent(kind, payload, route);
973
980
  const rec = getState();
974
981
  if (!rec)
975
982
  return pushFlightEvent(kind, payload, route);
@@ -46,6 +46,8 @@ export declare const leadState: {
46
46
  export type CaptureFace = 'recorder' | 'report';
47
47
  /** Take the runtime for `face`; its release token, or null when a report face finds it taken. */
48
48
  export declare function claimCapture(face: CaptureFace, yieldTo?: () => void): string | null;
49
+ /** The face that runs this document's capture now; null when none does. */
50
+ export declare function captureFace(): CaptureFace | null;
49
51
  /** Give the runtime back — only the claim that `token` names. */
50
52
  export declare function releaseCapture(token: string | null | undefined): void;
51
53
  export declare function subscribe(fn: () => void): () => void;
@@ -70,6 +70,10 @@ export function claimCapture(face, yieldTo) {
70
70
  g[OWNER_KEY] = { face, token, ...(yieldTo ? { yieldTo } : {}) };
71
71
  return token;
72
72
  }
73
+ /** The face that runs this document's capture now; null when none does. */
74
+ export function captureFace() {
75
+ return globalThis[OWNER_KEY]?.face ?? null;
76
+ }
73
77
  /** Give the runtime back — only the claim that `token` names. */
74
78
  export function releaseCapture(token) {
75
79
  const g = globalThis;
@@ -1,3 +1,3 @@
1
1
  /** Sent as `meta.recorder` and written as `data-vitrinka-page`; bumped with the package version. */
2
- export declare const RECORDER_VERSION = "0.10.1";
3
- export declare const RECORDER_ID = "web/0.10.1";
2
+ export declare const RECORDER_VERSION = "0.11.0";
3
+ export declare const RECORDER_ID = "web/0.11.0";
@@ -1,3 +1,3 @@
1
1
  /** Sent as `meta.recorder` and written as `data-vitrinka-page`; bumped with the package version. */
2
- export const RECORDER_VERSION = '0.10.1';
2
+ export const RECORDER_VERSION = '0.11.0';
3
3
  export const RECORDER_ID = `web/${RECORDER_VERSION}`;
@@ -10,8 +10,10 @@
10
10
  * 2. The redaction rules first, then the lanes — so capture runs under the
11
11
  * project's rules from its first byte: the console lane (errors, every
12
12
  * level with `console`), the network lane in metadata-only mode
13
- * (`errors`: failures, `network`: every request), and the rrweb lane
14
- * into the flight buffer (`interactions`).
13
+ * (`errors`: failures, `network`: every request), and with
14
+ * `interactions` the rrweb lane plus the click and navigation lanes —
15
+ * the journey a report's timeline is built from (vt-3094) — all into
16
+ * the flight buffer.
15
17
  * 3. The flight buffer under the profile's window and cap, in memory or
16
18
  * also in IndexedDB (`storage: browser`, storage/capture.ts), whose
17
19
  * expired windows the start sweeps.
@@ -24,7 +26,7 @@
24
26
  */
25
27
  import type { eventWithTime } from '@rrweb/types';
26
28
  import { type RecordFn } from '../recorder/capture/rrweb-lane';
27
- import { type FlightClip, type FlightLaneEvent } from '../recorder/flight';
29
+ import { type FlightClip, type FlightLaneEvent, type FlightProfile } from '../recorder/flight';
28
30
  import { EVENTS_PER_POST } from '../recorder/queue';
29
31
  import { type AttachmentCaps } from './attachments';
30
32
  import { type Marker } from './markers';
@@ -65,6 +67,14 @@ export interface NetEntry {
65
67
  path: string;
66
68
  status: number;
67
69
  ms: number;
70
+ /** When it finished: what places it on the report's timeline (a vitrinka before vt-3094 ignores it). */
71
+ ts: string;
72
+ }
73
+ /** One step of the journey before a report: a click or a page change, as the recorder's lanes shape them. */
74
+ export interface JourneyEntry {
75
+ kind: 'click' | 'nav';
76
+ ts: string;
77
+ payload: Record<string, unknown>;
68
78
  }
69
79
  /** The capture as frozen when the card opened (the buffer keeps rolling). */
70
80
  export interface Frozen {
@@ -89,9 +99,13 @@ export interface BuiltCapture {
89
99
  truncated: boolean;
90
100
  console: ConsoleEntry[];
91
101
  network: NetEntry[];
102
+ /** The clicks and page changes of the kept minutes, oldest first; staged beside the replay's rows. */
103
+ journey: JourneyEntry[];
92
104
  }
93
105
  /** A request URL (already through the redaction engine) as the wire's path: pathname only, token runs scrubbed. */
94
106
  export declare function reportPath(url: unknown): string;
107
+ /** A page URL as a report carries one: origin and path, never a query or a fragment, token runs scrubbed. */
108
+ export declare function reportPageUrl(url: unknown): string;
95
109
  /**
96
110
  * Whole windows only: rrweb's stream is stateful, so a window holding an
97
111
  * event over the wire cap (a huge full snapshot) goes entirely — its
@@ -101,6 +115,17 @@ export declare function wholeWindows(events: readonly eventWithTime[], hardBytes
101
115
  events: eventWithTime[];
102
116
  dropped: boolean;
103
117
  };
118
+ /** What the flight buffer keeps of each lane event under the profile's classes: the wire's shapes only. */
119
+ export declare function laneKeeper(lanes: CaptureLanes): NonNullable<FlightProfile['keepLane']>;
120
+ /**
121
+ * The clicks and page changes among a clip's lane events, newest
122
+ * `MAX_ENTRIES`, oldest first. `clicks: false` leaves the clicks out: a
123
+ * report with a Cover sends none, because a click carries its element's
124
+ * text and box from when it was pressed, and nothing matches that against
125
+ * what the reporter covered at Send — fail closed, as a hide without a
126
+ * mirror withholds the replay.
127
+ */
128
+ export declare function journeyOf(lanes: readonly FlightLaneEvent[], clicks?: boolean): JourneyEntry[];
104
129
  export declare class CaptureEngine {
105
130
  readonly opts: EngineOptions;
106
131
  readonly ready: Promise<ReportConfig>;
@@ -1,10 +1,13 @@
1
1
  import { api } from '../recorder/api';
2
+ import { installClickLane } from '../recorder/capture/click';
2
3
  import { patchConsole, unpatchConsole } from '../recorder/capture/console';
4
+ import { noteNavigation, ownNavLane, uninstallNavLane } from '../recorder/capture/nav';
3
5
  import { patchNetwork, unpatchNetwork } from '../recorder/capture/net';
4
6
  import { setCaptureSanitizer, setRedactionPolicy } from '../recorder/capture/redact';
5
- import { checkoutRRWeb, runningRecord, startRecordWith, stopRRWeb } from '../recorder/capture/rrweb-lane';
7
+ import { checkoutRRWeb, RRWEB_BLOCK_ATTR, runningRecord, startRecordWith, stopRRWeb } from '../recorder/capture/rrweb-lane';
6
8
  import { addOwnBase } from '../recorder/config';
7
9
  import { clearFlight, clipHasSnapshot, FLIGHT_MAX_LANE_EVENTS, flightWrites, persistFlightNow, startFlightBuffer, stopFlightBuffer, takeFlightClip, } from '../recorder/flight';
10
+ import { insideHud } from '../recorder/hud/host';
8
11
  import { listen } from '../recorder/hud/listen';
9
12
  import { EVENTS_PER_POST, splitRRWebEvents, utf8Bytes } from '../recorder/queue';
10
13
  import { browserTabId, claimCapture, currentRoute, releaseCapture, setTabIdentity } from '../recorder/state';
@@ -25,6 +28,28 @@ const TOKENY = /[A-Za-z0-9_-]{20,}/g;
25
28
  function str(v, fallback = '') {
26
29
  return typeof v === 'string' ? v : fallback;
27
30
  }
31
+ /**
32
+ * One path segment with its token runs scrubbed. A pathname keeps percent
33
+ * escapes, and an escaped token is still a token: the segment is judged
34
+ * decoded, and when that finds a run it is emitted decoded and scrubbed, its
35
+ * separators kept as escapes so no new segment appears. A malformed escape
36
+ * decodes nothing and the segment is judged as written.
37
+ */
38
+ function scrubSegment(seg) {
39
+ let decoded = seg;
40
+ if (seg.includes('%')) {
41
+ try {
42
+ decoded = decodeURIComponent(seg);
43
+ }
44
+ catch {
45
+ decoded = seg;
46
+ }
47
+ }
48
+ TOKENY.lastIndex = 0;
49
+ if (decoded === seg || !TOKENY.test(decoded))
50
+ return seg.replace(TOKENY, '•••');
51
+ return decoded.replace(TOKENY, '•••').replace(/[/?#%]/g, (c) => encodeURIComponent(c));
52
+ }
28
53
  /** A request URL (already through the redaction engine) as the wire's path: pathname only, token runs scrubbed. */
29
54
  export function reportPath(url) {
30
55
  const raw = str(url);
@@ -35,7 +60,26 @@ export function reportPath(url) {
35
60
  catch {
36
61
  path = raw.split(/[?#]/)[0] ?? '';
37
62
  }
38
- return path.replace(TOKENY, '•••').slice(0, 300);
63
+ return path.split('/').map(scrubSegment).join('/').slice(0, 300);
64
+ }
65
+ /** What the replay never serializes: rrweb's block class and the lane's own block attribute (rrweb-lane.ts). */
66
+ const REPLAY_BLOCKED = `.rr-block,[${RRWEB_BLOCK_ATTR}]`;
67
+ /**
68
+ * A press at or under a region the replay blocks is not the report's to
69
+ * send: its selector alone would name DOM the replay leaves out.
70
+ */
71
+ function inBlockedRegion(t) {
72
+ return typeof Element !== 'undefined' && t instanceof Element && t.closest(REPLAY_BLOCKED) !== null;
73
+ }
74
+ /** A page URL as a report carries one: origin and path, never a query or a fragment, token runs scrubbed. */
75
+ export function reportPageUrl(url) {
76
+ try {
77
+ const u = new URL(str(url), globalThis.location?.href ?? 'http://localhost');
78
+ return u.origin + reportPath(u.pathname);
79
+ }
80
+ catch {
81
+ return reportPath(url);
82
+ }
39
83
  }
40
84
  /** rrweb's `EventType.Meta`, the head of every window (`@rrweb/types` is type-only here). */
41
85
  const RRWEB_META = 4;
@@ -67,9 +111,36 @@ export function wholeWindows(events, hardBytes) {
67
111
  close();
68
112
  return { events: out, dropped };
69
113
  }
114
+ const MAX_SELECTOR = 300;
115
+ const MAX_CLICK_TEXT = 80;
116
+ function rectOf(v) {
117
+ if (typeof v !== 'object' || v === null)
118
+ return null;
119
+ const r = v;
120
+ const n = (k) => (typeof r[k] === 'number' && Number.isFinite(r[k]) ? r[k] : null);
121
+ const [x, y, w, h] = [n('x'), n('y'), n('w'), n('h')];
122
+ return x === null || y === null || w === null || h === null ? null : { x, y, w, h };
123
+ }
70
124
  /** What the flight buffer keeps of each lane event under the profile's classes: the wire's shapes only. */
71
- function laneKeeper(lanes) {
125
+ export function laneKeeper(lanes) {
72
126
  return (kind, payload) => {
127
+ // The journey rides with the replay (`interactions`): it shows nothing the replay does not.
128
+ if (kind === 'click') {
129
+ if (!lanes.replay)
130
+ return null;
131
+ const rect = rectOf(payload?.rect);
132
+ return {
133
+ selector: str(payload?.selector).slice(0, MAX_SELECTOR),
134
+ text: str(payload?.text).slice(0, MAX_CLICK_TEXT),
135
+ ...(rect ? { rect } : {}),
136
+ route: reportPath(payload?.route),
137
+ };
138
+ }
139
+ if (kind === 'nav') {
140
+ if (!lanes.replay)
141
+ return null;
142
+ return { url: reportPageUrl(payload?.url), route: reportPath(payload?.route), spa: true };
143
+ }
73
144
  if (kind === 'console') {
74
145
  const level = str(payload?.level, 'error');
75
146
  if (level === 'error' ? !(lanes.errors || lanes.console) : !lanes.console)
@@ -91,6 +162,20 @@ function laneKeeper(lanes) {
91
162
  return null;
92
163
  };
93
164
  }
165
+ /**
166
+ * The clicks and page changes among a clip's lane events, newest
167
+ * `MAX_ENTRIES`, oldest first. `clicks: false` leaves the clicks out: a
168
+ * report with a Cover sends none, because a click carries its element's
169
+ * text and box from when it was pressed, and nothing matches that against
170
+ * what the reporter covered at Send — fail closed, as a hide without a
171
+ * mirror withholds the replay.
172
+ */
173
+ export function journeyOf(lanes, clicks = true) {
174
+ return lanes
175
+ .filter((e) => (clicks && e.kind === 'click') || e.kind === 'nav')
176
+ .slice(-MAX_ENTRIES)
177
+ .map((e) => ({ kind: e.kind, ts: e.ts, payload: e.payload ?? {} }));
178
+ }
94
179
  async function fetchConfig(target) {
95
180
  try {
96
181
  const res = await api('GET', '/api/v1/report-config', undefined, { target });
@@ -234,6 +319,18 @@ export class CaptureEngine {
234
319
  this.capture.push(unpatchNetwork);
235
320
  }
236
321
  if (lanes.replay) {
322
+ // The journey (vt-3094): clicks and page changes, held like the console
323
+ // and network entries. The click listener is this engine's alone; the
324
+ // History wrap is shared with a recorder face (nav.ts): this engine holds
325
+ // the capture, so it takes the wrap over — another bundle's recorder may
326
+ // have left its own installed, and that one feeds a queue that is not
327
+ // this buffer — and it comes off in stop() only while this engine still
328
+ // runs the capture.
329
+ if (typeof document !== 'undefined')
330
+ this.capture.push(installClickLane({ ignore: (t) => insideHud(t) || inBlockedRegion(t) }));
331
+ // The journey opens on the page it started on (the takeover notes it when it missed one).
332
+ if (!ownNavLane())
333
+ noteNavigation(true);
237
334
  const record = await opts.loadRecord(opts.base).catch((e) => {
238
335
  // A report without a replay is still a report: never block the card.
239
336
  console.warn('vitrinka: the page recorder did not load — reports go without a replay', e);
@@ -380,8 +477,9 @@ export class CaptureEngine {
380
477
  path: str(e.payload?.path),
381
478
  status: typeof e.payload?.status === 'number' ? e.payload.status : 0,
382
479
  ms: typeof e.payload?.ms === 'number' ? e.payload.ms : 0,
480
+ ts: e.ts,
383
481
  }));
384
- return { chunks, truncated: truncated || dropped.length > 0, console: consoleEntries, network };
482
+ return { chunks, truncated: truncated || dropped.length > 0, console: consoleEntries, network, journey: journeyOf(lanes, hides.length === 0) };
385
483
  }
386
484
  /** A report went out: forget what it carried, in memory and in the store. */
387
485
  clear() {
@@ -391,6 +489,10 @@ export class CaptureEngine {
391
489
  stop() {
392
490
  this.stopped = true;
393
491
  this.listeners.clear();
492
+ // Still this engine's capture: its History wrap goes with it. After a
493
+ // recorder face took the capture over, the wrap is the recorder's.
494
+ if (this.capturing && this.config?.lanes.replay)
495
+ uninstallNavLane();
394
496
  this.standDown();
395
497
  releaseCapture(this.claim);
396
498
  this.claim = null;
@@ -9,7 +9,8 @@
9
9
  * classes ⊆ errors · interactions · full · console · network
10
10
  *
11
11
  * Classes: `interactions` = the masked DOM replay (clicks, scrolls, typing
12
- * as masked input, each page's view); `errors` = uncaught errors, console
12
+ * as masked input, each page's view) and the journey beside it: each click
13
+ * and page change as a timeline row (vt-3094); `errors` = uncaught errors, console
13
14
  * errors and failed requests; `console` = every console level; `network` =
14
15
  * every request's method, path, status and duration; `full` = all of them.
15
16
  * Request and response bodies and headers are never part of a report.
@@ -0,0 +1,56 @@
1
+ /**
2
+ * The test round this browser is in (recorder report mode, vt-3094): one
3
+ * person's reports from one sitting on one site, grouped in vitrinka. The
4
+ * first report opens a round and vitrinka hands back its token; every later
5
+ * report sends the token and joins the round while it stands. vitrinka
6
+ * decides when a round is over (the reporter ended it, or it was quiet too
7
+ * long): the report then opens a new one and `rotated` says so. This module
8
+ * only keeps the token.
9
+ *
10
+ * Kept in the recorder storage (localStorage: every tab of the site shares
11
+ * it, a reload keeps it), one key per vitrinka and report key: two widgets
12
+ * for two projects never share a round, and never rewrite each other's (a
13
+ * shared map would be read and written whole by tabs that do not exclude
14
+ * one another).
15
+ */
16
+ import { type ApiTarget } from '../recorder/api';
17
+ /** The keys' prefix; `roundStorageKey` names a target's own. */
18
+ export declare const ROUND_STORAGE_KEY = "report.round";
19
+ /** The storage key of the round held for this vitrinka and report key. */
20
+ export declare function roundStorageKey(target: ApiTarget): string;
21
+ /** A round as this browser knows it. */
22
+ export interface HeldRound {
23
+ token: string;
24
+ /** How many reports it held when vitrinka last answered. */
25
+ reports: number;
26
+ /** When it opened (RFC 3339), '' when vitrinka did not say. */
27
+ openedAt: string;
28
+ }
29
+ /** The round held for this vitrinka and key; null on a first report. */
30
+ export declare function roundFor(target: ApiTarget): HeldRound | null;
31
+ /** Forget the round (it ended, or vitrinka no longer knows it). */
32
+ export declare function forgetRound(target: ApiTarget): void;
33
+ /**
34
+ * Keep what a create answered as `round` ({token, reports?, openedAt?,
35
+ * rotated?}); anything else leaves the held round as it is. `sent` is the
36
+ * token that create carried ('' on a first report): the reply is kept only
37
+ * while the browser still holds what the request started from. Another tab
38
+ * may have been answered meanwhile — then its round stands and this late
39
+ * reply is dropped, never restoring a token the browser moved on from. A
40
+ * reply for the round still held keeps the higher count of the two. Returns
41
+ * the round now held and whether vitrinka opened a new one in place of the
42
+ * token sent; null when nothing was kept.
43
+ */
44
+ export declare function keepRound(target: ApiTarget, reply: unknown, sent?: string): {
45
+ round: HeldRound;
46
+ rotated: boolean;
47
+ } | null;
48
+ /**
49
+ * End the round this browser holds: vitrinka closes it and the next report
50
+ * opens a new one. The token is forgotten once vitrinka ended the round or
51
+ * no longer knows it; a failure it may recover from (offline, a 5xx) keeps
52
+ * the token and rejects, so End can be pressed again. Only the round the
53
+ * request named is forgotten: a new one another tab was handed meanwhile
54
+ * stays. False when there was no round to end.
55
+ */
56
+ export declare function endRound(target: ApiTarget, signal?: AbortSignal): Promise<boolean>;
@@ -0,0 +1,132 @@
1
+ /**
2
+ * The test round this browser is in (recorder report mode, vt-3094): one
3
+ * person's reports from one sitting on one site, grouped in vitrinka. The
4
+ * first report opens a round and vitrinka hands back its token; every later
5
+ * report sends the token and joins the round while it stands. vitrinka
6
+ * decides when a round is over (the reporter ended it, or it was quiet too
7
+ * long): the report then opens a new one and `rotated` says so. This module
8
+ * only keeps the token.
9
+ *
10
+ * Kept in the recorder storage (localStorage: every tab of the site shares
11
+ * it, a reload keeps it), one key per vitrinka and report key: two widgets
12
+ * for two projects never share a round, and never rewrite each other's (a
13
+ * shared map would be read and written whole by tabs that do not exclude
14
+ * one another).
15
+ */
16
+ import { api, VitrinkaApiError } from '../recorder/api';
17
+ import { getRecorderStorage } from '../recorder/storage';
18
+ /** The keys' prefix; `roundStorageKey` names a target's own. */
19
+ export const ROUND_STORAGE_KEY = 'report.round';
20
+ /** The storage key of the round held for this vitrinka and report key. */
21
+ export function roundStorageKey(target) {
22
+ return `${ROUND_STORAGE_KEY}:${target.url}|${target.key}`;
23
+ }
24
+ /** What the store holds for a target, as stored: whatever another script or version wrote there, so nothing is trusted. */
25
+ function read(target) {
26
+ try {
27
+ return JSON.parse(getRecorderStorage().getString(roundStorageKey(target)) ?? 'null');
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ /**
34
+ * Storage can refuse a write long after it took the first (a full quota, a
35
+ * browser that withdrew it): a round then simply is not kept — the report
36
+ * that was just filed never fails for it, and the next one opens a new round.
37
+ */
38
+ function write(target, round) {
39
+ try {
40
+ const s = getRecorderStorage();
41
+ if (round)
42
+ s.set(roundStorageKey(target), JSON.stringify(round));
43
+ else
44
+ s.remove(roundStorageKey(target));
45
+ }
46
+ catch (e) {
47
+ console.warn('vitrinka: the test round could not be kept in this browser — the next report opens a new one', e);
48
+ }
49
+ }
50
+ /** One stored entry as a round, field by field; null for anything that is not one. */
51
+ function heldOf(v) {
52
+ if (typeof v !== 'object' || v === null)
53
+ return null;
54
+ const r = v;
55
+ if (typeof r.token !== 'string' || !r.token)
56
+ return null;
57
+ return {
58
+ token: r.token,
59
+ reports: typeof r.reports === 'number' && Number.isFinite(r.reports) && r.reports > 0 ? Math.floor(r.reports) : 0,
60
+ openedAt: typeof r.openedAt === 'string' ? r.openedAt : '',
61
+ };
62
+ }
63
+ /** The round held for this vitrinka and key; null on a first report. */
64
+ export function roundFor(target) {
65
+ return heldOf(read(target));
66
+ }
67
+ /** Forget the round (it ended, or vitrinka no longer knows it). */
68
+ export function forgetRound(target) {
69
+ if (read(target) !== null)
70
+ write(target, null);
71
+ }
72
+ /** Forget `token`'s round only while it is still the one held: another tab may have been handed a new one since. */
73
+ function forgetToken(target, token) {
74
+ if (roundFor(target)?.token === token)
75
+ forgetRound(target);
76
+ }
77
+ /**
78
+ * Keep what a create answered as `round` ({token, reports?, openedAt?,
79
+ * rotated?}); anything else leaves the held round as it is. `sent` is the
80
+ * token that create carried ('' on a first report): the reply is kept only
81
+ * while the browser still holds what the request started from. Another tab
82
+ * may have been answered meanwhile — then its round stands and this late
83
+ * reply is dropped, never restoring a token the browser moved on from. A
84
+ * reply for the round still held keeps the higher count of the two. Returns
85
+ * the round now held and whether vitrinka opened a new one in place of the
86
+ * token sent; null when nothing was kept.
87
+ */
88
+ export function keepRound(target, reply, sent = '') {
89
+ if (typeof reply !== 'object' || reply === null)
90
+ return null;
91
+ const r = reply;
92
+ if (typeof r.token !== 'string' || !r.token)
93
+ return null;
94
+ const round = {
95
+ token: r.token,
96
+ reports: typeof r.reports === 'number' && Number.isFinite(r.reports) && r.reports > 0 ? Math.floor(r.reports) : 1,
97
+ openedAt: typeof r.openedAt === 'string' ? r.openedAt : '',
98
+ };
99
+ const held = roundFor(target);
100
+ if ((held?.token ?? '') !== sent) {
101
+ // The browser moved on while this request was in flight. Its own round's reply still counts.
102
+ if (held?.token !== round.token)
103
+ return null;
104
+ }
105
+ if (held?.token === round.token)
106
+ round.reports = Math.max(round.reports, held.reports);
107
+ write(target, round);
108
+ return { round, rotated: r.rotated === true };
109
+ }
110
+ /**
111
+ * End the round this browser holds: vitrinka closes it and the next report
112
+ * opens a new one. The token is forgotten once vitrinka ended the round or
113
+ * no longer knows it; a failure it may recover from (offline, a 5xx) keeps
114
+ * the token and rejects, so End can be pressed again. Only the round the
115
+ * request named is forgotten: a new one another tab was handed meanwhile
116
+ * stays. False when there was no round to end.
117
+ */
118
+ export async function endRound(target, signal) {
119
+ const held = roundFor(target);
120
+ if (!held)
121
+ return false;
122
+ try {
123
+ await api('POST', '/api/v1/report/round/end', { round: held.token }, { target, signal });
124
+ }
125
+ catch (e) {
126
+ // 404: vitrinka knows no such round (or predates rounds) — nothing left to end.
127
+ if (!(e instanceof VitrinkaApiError) || e.status !== 404)
128
+ throw e;
129
+ }
130
+ forgetToken(target, held.token);
131
+ return true;
132
+ }
@@ -49,6 +49,7 @@ import { listMine, openSession, sessionKey, sessionLive } from './reader';
49
49
  import { noteSent, readSent } from './sent';
50
50
  import { COACH_KEY, readCoach, readSize, SIZE_KEY, SIZE_SCALE, SIZES, techDetails, writePref } from './settings';
51
51
  import { REPORT_CSS } from './styles';
52
+ import { roundFor } from './round';
52
53
  import { EMPTY_CAPTURE, prepareCapture, ReportJob } from './wire';
53
54
  const SVG_NS = 'http://www.w3.org/2000/svg';
54
55
  const TITLE_CAP = 100;
@@ -1692,6 +1693,8 @@ export class ReportWidget {
1692
1693
  envelope(description, capture) {
1693
1694
  const who = this.who();
1694
1695
  const member = memberTokenFor(this.opts.base);
1696
+ // The test round this browser is in (vt-3094): the report joins it while vitrinka says it stands.
1697
+ const round = roundFor({ url: this.opts.base, key: this.opts.key });
1695
1698
  const loc = globalThis.location;
1696
1699
  return {
1697
1700
  title: titleOf(description),
@@ -1709,6 +1712,7 @@ export class ReportWidget {
1709
1712
  markers: toWire(this.markers),
1710
1713
  locale: this.locale,
1711
1714
  ...(this.kind ? { type: this.kind } : {}),
1715
+ ...(round ? { round: round.token } : {}),
1712
1716
  // A member linked on this base co-owns the report; the `vkb_` key stays the bearer.
1713
1717
  ...(member ? { memberToken: member } : {}),
1714
1718
  ...contextField(this.context),
@@ -69,6 +69,8 @@ export interface ReportEnvelope {
69
69
  memberToken?: string;
70
70
  /** The host's claimed context (context.ts, vt-9515), already validated; absent when the map is empty. */
71
71
  context?: ReportContext;
72
+ /** The test round this browser holds (round.ts, vt-3094), absent on its first report: the report joins it while it stands. */
73
+ round?: string;
72
74
  }
73
75
  export interface SubmitReply {
74
76
  status: 'filed' | 'quarantined';
@@ -146,7 +148,7 @@ export declare class ReportJob {
146
148
  * The create leg, answering with the member link the accepted body carried
147
149
  * ('' none). A vitrinka older than an optional field refuses it by name;
148
150
  * the reporter's word (`type`), the member link (`memberToken`) and the host's context (`context`) are
149
- * optional, the report is not, so it goes again without each field named,
151
+ * optional, and so is the test round (`round`); the report is not, so it goes again without each field named,
150
152
  * once. A refusal naming nothing still in the body fails the leg.
151
153
  */
152
154
  private create;