@vitrinka/web 0.10.1 → 0.12.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.
@@ -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;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Every string Report a problem shows, one catalog per locale (cs, en). The
2
+ * Every string Report a problem shows, one catalog per locale (cs, en, sk). The
3
3
  * browser's language picks one by default; the host's `locale` option,
4
4
  * `locale` attribute and `setLocale()` switch it live — the widget repaints
5
5
  * its text in place, so a draft and its marks survive the switch.
@@ -8,7 +8,7 @@
8
8
  * first-time reporter does not know the word.
9
9
  */
10
10
  import type { MarkerShape } from './markers';
11
- export type Locale = 'cs' | 'en';
11
+ export type Locale = 'cs' | 'en' | 'sk';
12
12
  export type ReportKind = 'bug' | 'suggestion' | 'question' | 'other';
13
13
  export declare const REPORT_KINDS: readonly ReportKind[];
14
14
  export interface Strings {
@@ -133,6 +133,8 @@ export interface Strings {
133
133
  incFiles: string;
134
134
  errorFiles: string;
135
135
  moveHint: string;
136
+ /** The edge drop's move hint (vt-3811): along the edge only. */
137
+ edgeHint: string;
136
138
  size: string;
137
139
  sizes: {
138
140
  sm: string;
@@ -154,7 +156,7 @@ export interface Strings {
154
156
  windowLength: (sec: number) => string;
155
157
  }
156
158
  export declare function strings(locale: Locale): Strings;
157
- /** `cs`, `cs-CZ`, `CS` → cs; `en-GB` → en; anything else → null. */
159
+ /** `cs`, `cs-CZ`, `CS` → cs; `sk-SK` → sk; `en-GB` → en; anything else → null. */
158
160
  export declare function parseLocale(raw: unknown): Locale | null;
159
161
  /** The first of the browser's languages the widget speaks; English otherwise. */
160
162
  export declare function browserLocale(): Locale;
@@ -115,6 +115,7 @@ const en = {
115
115
  incFiles: 'The files you attached',
116
116
  errorFiles: 'Your report arrived, a file not yet — try again to attach it',
117
117
  moveHint: 'Click, hold and move it to another corner, or press Alt and an arrow key.',
118
+ edgeHint: 'Click, hold and move it up or down along the edge, or press Alt and the up or down arrow.',
118
119
  size: 'Size',
119
120
  sizes: { sm: 'Small', md: 'Medium', lg: 'Large' },
120
121
  techDetails: 'Technical details',
@@ -244,6 +245,7 @@ const cs = {
244
245
  incFiles: 'Soubory, které jste přiložili',
245
246
  errorFiles: 'Hlášení dorazilo, soubor zatím ne — zkuste to znovu a přiložíme ho',
246
247
  moveHint: 'Klikněte, podržte a veďte ho do jiného rohu, nebo stiskněte Alt a šipku.',
248
+ edgeHint: 'Klikněte, podržte a posuňte ho nahoru nebo dolů podél okraje, nebo stiskněte Alt a šipku nahoru či dolů.',
247
249
  size: 'Velikost',
248
250
  sizes: { sm: 'Malá', md: 'Střední', lg: 'Velká' },
249
251
  techDetails: 'Technické údaje',
@@ -264,16 +266,147 @@ const cs = {
264
266
  return csPlural(min, '1 minuta', `${min} minuty`, `${min} minut`);
265
267
  },
266
268
  };
267
- const CATALOGS = { cs, en };
269
+ /** Slovak (vt-3811): Slovak plurals take the Czech forms (1 · 2–4 · 5+), so csPlural serves both. */
270
+ const sk = {
271
+ button: 'Nahlásiť problém',
272
+ title: 'Nahlásiť problém',
273
+ close: 'Zavrieť',
274
+ settings: 'Nastavenia',
275
+ prompt: 'Čo sa pokazilo?',
276
+ placeholder: 'Napíšte, čo sa stalo a čo ste čakali',
277
+ attached: (sec) => {
278
+ if (sec < 60) {
279
+ return csPlural(sec, 'Posledná sekunda je priložená', `Posledné ${sec} sekundy sú priložené`, `Posledných ${sec} sekúnd je priložených`);
280
+ }
281
+ const min = Math.round(sec / 60);
282
+ return csPlural(min, 'Posledná minúta je priložená', `Posledné ${min} minúty sú priložené`, `Posledných ${min} minút je priložených`);
283
+ },
284
+ included: 'Čo je priložené',
285
+ incReplay: 'Záznam toho, čo sa na stránke dialo',
286
+ incReplayMasked: {
287
+ strict: 'Texty stránky aj všetko, čo ste napísali, sú v ňom skryté',
288
+ balanced: 'Všetko, čo ste napísali, je v ňom skryté',
289
+ full: 'Ukazuje stránku tak, ako ste ju videli',
290
+ },
291
+ incErrors: 'Chyby, na ktoré stránka narazila',
292
+ incConsole: 'Správy z konzoly prehliadača',
293
+ incNetwork: 'Ktoré adresy stránka načítavala a s akým výsledkom',
294
+ incFailedRequests: 'Požiadavky, ktoré zlyhali — len adresa a výsledok',
295
+ incEnv: 'Váš prehliadač, veľkosť obrazovky, jazyk a adresa stránky',
296
+ incIdentity: 'Vaše meno a e-mail z tejto aplikácie',
297
+ incMarks: 'Miesta, ktoré ste označili, aj s poznámkami',
298
+ showWhere: 'Ukážte nám kde',
299
+ kinds: { bug: 'Chyba', suggestion: 'Návrh', question: 'Otázka', other: 'Iné' },
300
+ kindsLabel: 'Čo to je?',
301
+ linesEmpty: 'Každé označené miesto tu dostane riadok na poznámku.',
302
+ notify: 'Pošlite mi e-mail, keď to bude opravené',
303
+ send: 'Odoslať',
304
+ sending: 'Odosielam…',
305
+ retry: 'Skúsiť znova',
306
+ errorCreate: 'Nepodarilo sa odoslať — váš text zostal, skúste to znova',
307
+ errorCapture: 'Hlásenie dorazilo, záznam zatiaľ nie — skúste to znova a priložíme ho',
308
+ sentTitle: 'Vďaka — máme to',
309
+ sentBody: 'Tím sa na to pozrie.',
310
+ sentNotify: 'Keď to bude opravené, pošleme vám e-mail.',
311
+ seeReport: 'Zobraziť hlásenie',
312
+ tools: { circle: 'Kruh', box: 'Obdĺžnik', arrow: 'Šípka', hide: 'Zakryť' },
313
+ toolbar: 'Nástroje na označenie',
314
+ barLead: 'Označte, kde je problém',
315
+ barLeadHide: 'Zakryte, čo tím nemá vidieť',
316
+ cancelMarking: 'Zrušiť',
317
+ discardMarks: (n) => csPlural(n, 'Zahodiť 1 značku?', `Zahodiť ${n} značky?`, `Zahodiť ${n} značiek?`),
318
+ discard: 'Zahodiť',
319
+ keep: 'Ponechať',
320
+ coach: {
321
+ box: 'Kliknite, podržte a veďte cez problém.',
322
+ circle: 'Kliknite, podržte a veďte okolo problému.',
323
+ arrow: 'Kliknite, podržte a veďte z voľného miesta k problému.',
324
+ hide: 'Kliknite, podržte a veďte cez všetko súkromné — v hlásení zostane prázdne.',
325
+ },
326
+ coachMore: 'Označiť môžete aj viac miest.',
327
+ coachDismiss: 'Rozumiem, už nezobrazovať',
328
+ coachSetting: 'Nápoveda pri označovaní',
329
+ marking: 'Označovanie',
330
+ keyboardHint: 'Klávesnica: Enter začne, šípky posúvajú, Shift+šípky menia veľkosť, Enter umiestni.',
331
+ hidden: 'Zakryté — neodošle sa',
332
+ notePlaceholder: 'Pridajte poznámku (nepovinné)',
333
+ mark: (n) => `Značka ${n}`,
334
+ removeMark: (n) => `Odobrať značku ${n}`,
335
+ shortcut: 'Klávesová skratka',
336
+ shortcutHint: 'Otvorí Nahlásiť problém kdekoľvek v tejto aplikácii.',
337
+ notSet: 'Nenastavená',
338
+ recordShortcut: 'Nahrať novú skratku',
339
+ pressKeys: 'Stlačte klávesy · Esc zruší',
340
+ needModifier: 'Pridajte Ctrl, Alt alebo ⌘ — samotná klávesa by prekážala pri písaní',
341
+ removeShortcut: 'Odobrať',
342
+ back: 'Späť',
343
+ account: 'Váš účet',
344
+ menu: 'Ponuka',
345
+ anonymous: 'Neprihlásené',
346
+ anonymousHint: 'Hlásenie najprv skontroluje tím.',
347
+ signedInByApp: 'Prihlásený touto aplikáciou',
348
+ linkVitrinka: 'Prepojiť s vitrinkou',
349
+ linkedAs: (who) => `Prepojené s vitrinkou ako ${who}`,
350
+ unlink: 'Odpojiť',
351
+ myReports: 'Moje hlásenia',
352
+ recentRecordings: 'Nedávne nahrávky',
353
+ record: 'Nahrávať',
354
+ recordHasDraft: 'Odošlite alebo zmažte rozpísané hlásenie',
355
+ openVitrinka: 'Otvoriť vitrinku',
356
+ openPortal: 'Otvoriť portál hlásení',
357
+ loading: 'Načítavam…',
358
+ listFailed: 'Nepodarilo sa načítať — skúste to znova',
359
+ noReports: 'Zatiaľ žiadne hlásenia.',
360
+ noRecordings: 'Zatiaľ žiadne nahrávky.',
361
+ fromThisBrowser: 'Odoslané z tohto prehliadača',
362
+ steps: { received: 'Prijaté', planned: 'Naplánované', in_progress: 'Riešime', fixed: 'Opravené', done: 'Hotovo' },
363
+ waiting: 'Čaká na schválenie',
364
+ sentQueued: 'Kým ho zaradíme, tím ho skontroluje.',
365
+ linkCode: 'Váš kód',
366
+ linkHint: 'Schváľte kód vo vitrinke — na tomto alebo inom zariadení, kde ste prihlásení.',
367
+ linkWaiting: 'Čakám na schválenie…',
368
+ linkExpired: 'Kód vypršal.',
369
+ linkFailed: 'Prepojenie sa nepodarilo.',
370
+ attach: 'Priložiť súbor',
371
+ removeFile: (name) => `Odobrať ${name}`,
372
+ fileTooBig: (name, cap) => `${name} prekračuje limit ${cap}`,
373
+ tooManyFiles: (n) => csPlural(n, 'Najviac 1 súbor na hlásenie', `Najviac ${n} súbory na hlásenie`, `Najviac ${n} súborov na hlásenie`),
374
+ fileType: (name, types) => `${name} nemožno priložiť — len ${types}`,
375
+ typeNames: { image: 'obrázky', pdf: 'PDF', text: 'textové súbory', office: 'kancelárske dokumenty' },
376
+ incFiles: 'Súbory, ktoré ste priložili',
377
+ errorFiles: 'Hlásenie dorazilo, súbor zatiaľ nie — skúste to znova a priložíme ho',
378
+ moveHint: 'Kliknite, podržte a veďte ho do iného rohu, alebo stlačte Alt a šípku.',
379
+ edgeHint: 'Kliknite, podržte a posuňte ho hore alebo dole pozdĺž okraja, alebo stlačte Alt a šípku hore či dole.',
380
+ size: 'Veľkosť',
381
+ sizes: { sm: 'Malá', md: 'Stredná', lg: 'Veľká' },
382
+ techDetails: 'Technické údaje',
383
+ techVersion: 'Verzia',
384
+ techWindow: 'Okno záznamu',
385
+ techCapture: 'Záznam',
386
+ techBuffer: 'Vyrovnávacia pamäť',
387
+ techServer: 'Server',
388
+ captureOn: 'Beží',
389
+ captureOff: 'Vypnutý',
390
+ captureStarting: 'Spúšťa sa…',
391
+ bufferMemory: 'V pamäti',
392
+ bufferBrowser: 'V tomto prehliadači',
393
+ windowLength: (sec) => {
394
+ if (sec < 60)
395
+ return csPlural(sec, '1 sekunda', `${sec} sekundy`, `${sec} sekúnd`);
396
+ const min = Math.round(sec / 60);
397
+ return csPlural(min, '1 minúta', `${min} minúty`, `${min} minút`);
398
+ },
399
+ };
400
+ const CATALOGS = { cs, en, sk };
268
401
  export function strings(locale) {
269
402
  return CATALOGS[locale];
270
403
  }
271
- /** `cs`, `cs-CZ`, `CS` → cs; `en-GB` → en; anything else → null. */
404
+ /** `cs`, `cs-CZ`, `CS` → cs; `sk-SK` → sk; `en-GB` → en; anything else → null. */
272
405
  export function parseLocale(raw) {
273
406
  if (typeof raw !== 'string')
274
407
  return null;
275
408
  const lang = raw.trim().toLowerCase().split(/[-_]/)[0];
276
- return lang === 'cs' || lang === 'en' ? lang : null;
409
+ return lang === 'cs' || lang === 'en' || lang === 'sk' ? lang : null;
277
410
  }
278
411
  /** The first of the browser's languages the widget speaks; English otherwise. */
279
412
  export function browserLocale() {
@@ -2,6 +2,7 @@ import { type ReportHandle, type ReportOptions } from './element';
2
2
  export type { CaptureClass, CaptureNarrowing, CaptureProfile, CaptureStorage } from './profile';
3
3
  export type { ReportContext, ReportContextInput, ReportContextValue } from './context';
4
4
  export type { Locale } from './i18n';
5
+ export type { EdgeInsets, Launcher } from './edge';
5
6
  export type { IdentifyInput, Identity } from './identity';
6
7
  export type { Marker, MarkerShape, WireMarker } from './markers';
7
8
  export type { ReportEnvelope, SubmitReply } from './wire';
@@ -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
+ }