@vitrinka/web 0.2.2 → 0.3.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 (40) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +46 -4
  3. package/build/hud.d.ts +1 -1
  4. package/build/hud.iife.js +9 -8
  5. package/build/recorder/RecorderProvider.d.ts +2 -1
  6. package/build/recorder/RecorderProvider.js +18 -4
  7. package/build/recorder/capture/net.js +16 -10
  8. package/build/recorder/capture/redact.d.ts +3 -1
  9. package/build/recorder/capture/redact.js +2 -1
  10. package/build/recorder/capture/rrweb.d.ts +7 -1
  11. package/build/recorder/capture/rrweb.js +21 -6
  12. package/build/recorder/config.d.ts +6 -0
  13. package/build/recorder/config.js +1 -0
  14. package/build/recorder/flight.d.ts +63 -0
  15. package/build/recorder/flight.js +93 -0
  16. package/build/recorder/hud/Hud.d.ts +2 -1
  17. package/build/recorder/hud/Hud.js +113 -11
  18. package/build/recorder/hud/Menu.d.ts +4 -2
  19. package/build/recorder/hud/Menu.js +2 -2
  20. package/build/recorder/hud/RecorderPill.d.ts +2 -1
  21. package/build/recorder/hud/RecorderPill.js +11 -5
  22. package/build/recorder/hud/Sheet.d.ts +11 -2
  23. package/build/recorder/hud/Sheet.js +13 -4
  24. package/build/recorder/hud/controller.d.ts +29 -0
  25. package/build/recorder/hud/flow.d.ts +13 -3
  26. package/build/recorder/hud/flow.js +17 -6
  27. package/build/recorder/hud/icons.d.ts +1 -0
  28. package/build/recorder/hud/icons.js +3 -0
  29. package/build/recorder/hud/styles.d.ts +1 -1
  30. package/build/recorder/hud/styles.js +1 -0
  31. package/build/recorder/index.d.ts +5 -0
  32. package/build/recorder/index.js +9 -1
  33. package/build/recorder/page-controller.js +4 -0
  34. package/build/recorder/queue.d.ts +11 -4
  35. package/build/recorder/queue.js +15 -8
  36. package/build/recorder/report.d.ts +36 -0
  37. package/build/recorder/report.js +250 -0
  38. package/build/recorder/session.d.ts +12 -2
  39. package/build/recorder/session.js +23 -10
  40. package/package.json +1 -1
@@ -1,4 +1,5 @@
1
1
  import { api, permanentStatus, uploadChunk, VitrinkaApiError } from './api';
2
+ import { pushFlightEvent } from './flight';
2
3
  import { notify } from './state';
3
4
  import { getRecorderStorage } from './storage';
4
5
  const FLUSH_MS = 2000;
@@ -13,7 +14,9 @@ const MAX_PENDING = 200; // rrweb chunks in memory; oldest evicted loudly
13
14
  * dropped.
14
15
  */
15
16
  const WIRE_BODY_CAP = 4 * 1024 * 1024;
16
- const MAX_BATCH_BYTES = 3 * 1024 * 1024; // pack margin
17
+ export const MAX_BATCH_BYTES = 3 * 1024 * 1024; // pack margin
18
+ /** The server's per-POST event cap. */
19
+ export const EVENTS_PER_POST = 500;
17
20
  const MAX_EVENT_BYTES = WIRE_BODY_CAP - 1024; // solo cap; headroom for the {"events":[…]} envelope
18
21
  /**
19
22
  * rrweb chunk budgets (extension `splitRRWebEvents`): the server's chunk cap
@@ -27,7 +30,7 @@ const CHUNK_HARD_BYTES = CHUNK_WIRE_CAP - 64;
27
30
  const CHUNK_PERSIST_BUDGET = 1024 * 1024;
28
31
  const encoder = new TextEncoder();
29
32
  /** UTF-8 byte length of a string — the unit the server's body limit counts. */
30
- function utf8Bytes(s) {
33
+ export function utf8Bytes(s) {
31
34
  return encoder.encode(s).length;
32
35
  }
33
36
  /** How often a live session reconciles against the server (extension D5). */
@@ -311,14 +314,18 @@ export function isSessionLive(id) {
311
314
  return rec !== null && rec.sessionId === id && !rec.dead;
312
315
  }
313
316
  /**
314
- * Append an event to the durable buffer (drops when no live session or
315
- * paused). `tabId`/`tabHost`/`ts`/`seq` are filled here; capture layers pass
316
- * kind+payload plus the route they observed. Returns the stamped ts (null
317
- * when dropped).
317
+ * Append an event to the durable buffer (drops while paused or dead).
318
+ * `tabId`/`tabHost`/`ts`/`seq` are filled here; capture layers pass
319
+ * kind+payload plus the route they observed. With no session the event goes
320
+ * to the flight recorder when the idle pill keeps one (memory only — never
321
+ * storage, never the network), else it is dropped. Returns the stamped ts
322
+ * (null when dropped).
318
323
  */
319
324
  export function pushEvent(kind, payload, route) {
320
325
  const rec = getState();
321
- if (!rec || rec.paused || rec.dead)
326
+ if (!rec)
327
+ return pushFlightEvent(kind, payload, route);
328
+ if (rec.paused || rec.dead)
322
329
  return null;
323
330
  rec.seq++;
324
331
  const ts = new Date().toISOString();
@@ -527,7 +534,7 @@ async function flushInner(opts) {
527
534
  // A keepalive POST (pagehide) is capped by the browser at 64 KiB.
528
535
  const packCap = opts.keepalive ? 60 * 1024 : MAX_BATCH_BYTES;
529
536
  for (const ev of buffer) {
530
- if (batch.length >= 500)
537
+ if (batch.length >= EVENTS_PER_POST)
531
538
  break;
532
539
  const b = utf8Bytes(JSON.stringify(ev)) + 1;
533
540
  if (b > MAX_EVENT_BYTES) {
@@ -0,0 +1,36 @@
1
+ import { type ViewRect } from './session';
2
+ /** A mounted pill wants the flight recorder; returns the release. */
3
+ export declare function wantFlight(): () => void;
4
+ /**
5
+ * Arm or disarm the flight recorder to match the gate; the provider calls it
6
+ * on every recorder change. Resolves once a pending arm has settled.
7
+ */
8
+ export declare function syncFlight(): Promise<void>;
9
+ /** Can the pill offer "Report a bug" now — into the live session, or with the idle clip? */
10
+ export declare function canReport(): boolean;
11
+ export interface ReportNote {
12
+ /** The description; its first line titles the report session. */
13
+ text: string;
14
+ /** The region the reporter marked, viewport CSS px; null = the whole viewport. */
15
+ rect: ViewRect | null;
16
+ /** The marked element's selector; '' for a region or no mark. */
17
+ selector: string;
18
+ }
19
+ /**
20
+ * The report sheet opened (freeze the last minute — the buffer itself keeps
21
+ * rolling) or was dismissed (drop it, and a report whose send failed). A
22
+ * send in flight is never dropped. Idle only.
23
+ */
24
+ export declare function holdReport(on: boolean): void;
25
+ /**
26
+ * File the report. While recording: a task annotation in the live session.
27
+ * Idle: the held clip as a `kind: "report"` session — rejects with the
28
+ * failing step's error, and a second call (Retry) resumes the same job.
29
+ */
30
+ export declare function sendReport(note: ReportNote): Promise<{
31
+ boardUrl?: string;
32
+ }>;
33
+ /** The provider unmounted: forget the buffer and any held clip; a remount re-arms. */
34
+ export declare function dropFlight(): void;
35
+ /** Test-only. */
36
+ export declare function __resetReportForTests(): void;
@@ -0,0 +1,250 @@
1
+ import { api, fetchPolicy, uploadChunk } from './api';
2
+ import { setRedactionPolicy } from './capture/redact';
3
+ import { recorderConfig, vitrinkaLinked } from './config';
4
+ import { flightActive, startFlightBuffer, stopFlightBuffer, takeFlightClip } from './flight';
5
+ import { EVENTS_PER_POST, getState, MAX_BATCH_BYTES, splitRRWebEvents, utf8Bytes } from './queue';
6
+ import { noteRecent } from './recents';
7
+ import { addAnnotation, createSession, imagePixels } from './session';
8
+ import { currentRoute, notify } from './state';
9
+ // -- the gate ----------------------------------------------------------------
10
+ let pills = 0;
11
+ let armed = false;
12
+ let generation = 0;
13
+ let arming = Promise.resolve();
14
+ /** A mounted pill wants the flight recorder; returns the release. */
15
+ export function wantFlight() {
16
+ pills++;
17
+ notify();
18
+ let released = false;
19
+ return () => {
20
+ if (released)
21
+ return;
22
+ released = true;
23
+ pills--;
24
+ notify();
25
+ };
26
+ }
27
+ function flightWanted() {
28
+ return pills > 0 && getState() === null && vitrinkaLinked() && recorderConfig().flightRecorder !== false;
29
+ }
30
+ /**
31
+ * Arm or disarm the flight recorder to match the gate; the provider calls it
32
+ * on every recorder change. Resolves once a pending arm has settled.
33
+ */
34
+ export function syncFlight() {
35
+ const want = flightWanted();
36
+ if (want && !armed) {
37
+ armed = true;
38
+ const gen = ++generation;
39
+ setRedactionPolicy(null);
40
+ // fetchPolicy never rejects: null is the engine's safe defaults.
41
+ arming = fetchPolicy().then((policy) => {
42
+ if (!armed || gen !== generation)
43
+ return;
44
+ setRedactionPolicy(policy);
45
+ startFlightBuffer();
46
+ notify();
47
+ });
48
+ }
49
+ else if (!want && armed) {
50
+ armed = false;
51
+ generation++;
52
+ stopFlightBuffer();
53
+ // A session that just started owns the rules now; only an idle page resets them.
54
+ if (getState() === null)
55
+ setRedactionPolicy(null);
56
+ }
57
+ return arming;
58
+ }
59
+ /** Can the pill offer "Report a bug" now — into the live session, or with the idle clip? */
60
+ export function canReport() {
61
+ const rec = getState();
62
+ if (rec)
63
+ return !rec.paused && !rec.dead;
64
+ return flightWanted() && flightActive();
65
+ }
66
+ let held = null;
67
+ let job = null;
68
+ let sending = false;
69
+ /**
70
+ * The report sheet opened (freeze the last minute — the buffer itself keeps
71
+ * rolling) or was dismissed (drop it, and a report whose send failed). A
72
+ * send in flight is never dropped. Idle only.
73
+ */
74
+ export function holdReport(on) {
75
+ if (!sending)
76
+ job = null;
77
+ held = on && getState() === null ? takeFlightClip() : null;
78
+ }
79
+ const TITLE_LINE_CAP = 100;
80
+ function reportTitle(text) {
81
+ const line = text.split('\n')[0]?.trim() ?? '';
82
+ return `Bug report: ${line.length > TITLE_LINE_CAP ? `${line.slice(0, TITLE_LINE_CAP - 1)}…` : line}`;
83
+ }
84
+ function viewportRect() {
85
+ return { x: 0, y: 0, w: globalThis.innerWidth || 0, h: globalThis.innerHeight || 0 };
86
+ }
87
+ function pathOf(href) {
88
+ try {
89
+ return new URL(href).pathname;
90
+ }
91
+ catch {
92
+ return currentRoute.pathname;
93
+ }
94
+ }
95
+ function buildJob(clip, note) {
96
+ const tab = { tabId: currentRoute.tabId, tabHost: currentRoute.tabHost };
97
+ const events = [];
98
+ let seq = 0;
99
+ const first = clip.windows[0];
100
+ const startMs = first?.events[0]?.timestamp;
101
+ if (first && startMs !== undefined) {
102
+ events.push({ seq: ++seq, ts: new Date(startMs).toISOString(), ...tab, kind: 'nav', payload: { url: first.href, route: pathOf(first.href) } });
103
+ }
104
+ for (const e of clip.lanes) {
105
+ events.push({ seq: ++seq, ts: e.ts, tabId: e.tabId, tabHost: e.tabHost, kind: e.kind, ...(e.payload ? { payload: e.payload } : {}) });
106
+ }
107
+ const chunks = [];
108
+ let endMs = startMs ?? 0;
109
+ for (const w of clip.windows) {
110
+ // A window is ≤ 4 MiB (the flight cap), far under the chunk cap: nothing drops.
111
+ let at = 0;
112
+ for (const p of splitRRWebEvents(w.events).parts) {
113
+ at += p.count;
114
+ const lastMs = w.events[at - 1]?.timestamp ?? endMs;
115
+ endMs = Math.max(endMs, lastMs);
116
+ chunks.push({ seq: ++seq, ts: new Date(lastMs).toISOString(), ...tab, count: p.count, body: p.body });
117
+ }
118
+ }
119
+ const lastLane = clip.lanes.at(-1);
120
+ if (lastLane)
121
+ endMs = Math.max(endMs, Date.parse(lastLane.ts));
122
+ return {
123
+ title: reportTitle(note.text),
124
+ events,
125
+ chunks,
126
+ note: {
127
+ seq: ++seq,
128
+ ts: new Date().toISOString(),
129
+ ...tab,
130
+ kind: 'note',
131
+ payload: {
132
+ text: note.text,
133
+ rect: imagePixels(note.rect ?? viewportRect()),
134
+ selector: note.selector,
135
+ annotate: true,
136
+ task: true,
137
+ route: currentRoute.pathname,
138
+ },
139
+ },
140
+ durationMs: startMs !== undefined ? Math.max(0, endMs - startMs) : 0,
141
+ sessionId: '',
142
+ done: 0,
143
+ };
144
+ }
145
+ /** POST events in batches under the server's per-POST count and the queue's pack margin. */
146
+ async function postEvents(sessionId, events) {
147
+ let batch = [];
148
+ let bytes = 0;
149
+ const send = async () => {
150
+ if (!batch.length)
151
+ return;
152
+ await api('POST', `/api/v1/sessions/${sessionId}/events`, { events: batch });
153
+ batch = [];
154
+ bytes = 0;
155
+ };
156
+ for (const ev of events) {
157
+ const b = utf8Bytes(JSON.stringify(ev)) + 1;
158
+ if (batch.length >= EVENTS_PER_POST || (batch.length > 0 && bytes + b > MAX_BATCH_BYTES))
159
+ await send();
160
+ batch.push(ev);
161
+ bytes += b;
162
+ }
163
+ await send();
164
+ }
165
+ const steps = [
166
+ async (j) => {
167
+ const ses = await createSession(j.title, { meta: { kind: 'report' } });
168
+ j.sessionId = ses.id;
169
+ if (ses.boardUrl)
170
+ j.boardUrl = ses.boardUrl;
171
+ },
172
+ (j) => postEvents(j.sessionId, j.events),
173
+ async (j) => {
174
+ // The extension's chunk path: upload under the pre-allocated seq, then the row.
175
+ const rows = [];
176
+ for (const c of j.chunks) {
177
+ const up = await uploadChunk(j.sessionId, c.seq, c.body);
178
+ rows.push({ seq: c.seq, ts: c.ts, tabId: c.tabId, tabHost: c.tabHost, kind: 'rrweb', payload: { count: c.count }, blobKey: up.blobKey });
179
+ }
180
+ await postEvents(j.sessionId, rows);
181
+ },
182
+ (j) => postEvents(j.sessionId, [j.note]),
183
+ async (j) => {
184
+ const done = await api('PATCH', `/api/v1/sessions/${j.sessionId}`, { status: 'done' });
185
+ const url = done.board?.url;
186
+ if (url)
187
+ j.boardUrl = url;
188
+ },
189
+ ];
190
+ /**
191
+ * File the report. While recording: a task annotation in the live session.
192
+ * Idle: the held clip as a `kind: "report"` session — rejects with the
193
+ * failing step's error, and a second call (Retry) resumes the same job.
194
+ */
195
+ export async function sendReport(note) {
196
+ const rec = getState();
197
+ if (rec) {
198
+ if (rec.paused || rec.dead)
199
+ throw new Error('the recording is not capturing — resume it to report');
200
+ addAnnotation(note.text, note.rect ?? viewportRect(), note.selector, { task: true });
201
+ return rec.boardUrl ? { boardUrl: rec.boardUrl } : {};
202
+ }
203
+ if (sending)
204
+ throw new Error('a report is already being sent');
205
+ if (!job) {
206
+ if (!held)
207
+ throw new Error('nothing to report — the last minute was not recorded');
208
+ job = buildJob(held, note);
209
+ held = null;
210
+ }
211
+ const j = job;
212
+ sending = true;
213
+ try {
214
+ for (; j.done < steps.length; j.done++) {
215
+ const step = steps[j.done];
216
+ if (step)
217
+ await step(j);
218
+ }
219
+ }
220
+ finally {
221
+ sending = false;
222
+ }
223
+ if (job === j)
224
+ job = null;
225
+ noteRecent({
226
+ sessionId: j.sessionId,
227
+ title: j.title,
228
+ startedAt: Date.now(),
229
+ durationMs: j.durationMs,
230
+ status: 'saved',
231
+ ...(j.boardUrl ? { boardUrl: j.boardUrl } : {}),
232
+ });
233
+ return j.boardUrl ? { boardUrl: j.boardUrl } : {};
234
+ }
235
+ /** The provider unmounted: forget the buffer and any held clip; a remount re-arms. */
236
+ export function dropFlight() {
237
+ armed = false;
238
+ generation++;
239
+ arming = Promise.resolve();
240
+ held = null;
241
+ if (!sending)
242
+ job = null;
243
+ stopFlightBuffer();
244
+ }
245
+ /** Test-only. */
246
+ export function __resetReportForTests() {
247
+ pills = 0;
248
+ sending = false;
249
+ dropFlight();
250
+ }
@@ -17,8 +17,8 @@ import { type SessionState } from './queue';
17
17
  export { currentRoute, notify, subscribe } from './state';
18
18
  export type { SessionDone } from '../protocol';
19
19
  /** Sent as `meta.recorder`; bumped with the package version. */
20
- export declare const RECORDER_VERSION = "0.2.2";
21
- export declare const RECORDER_ID = "web/0.2.2";
20
+ export declare const RECORDER_VERSION = "0.3.0";
21
+ export declare const RECORDER_ID = "web/0.3.0";
22
22
  /** What `POST /api/v1/sessions` answers (the fields this recorder keeps). */
23
23
  export interface SessionOut {
24
24
  id: string;
@@ -40,6 +40,16 @@ export interface StartOptions {
40
40
  /** Tags to attach right after create (non-fatal). */
41
41
  tags?: string[];
42
42
  }
43
+ /**
44
+ * `POST /api/v1/sessions` as every web session makes it — a recording and a
45
+ * bug report alike: the page's `host`, the configured project and lane, and
46
+ * the recorder meta. `devicePixelRatio` is the scale every rect is recorded
47
+ * in (`imagePixels`), so the server shoots its stills at it.
48
+ */
49
+ export declare function createSession(title: string, opts?: {
50
+ environment?: string;
51
+ meta?: Record<string, unknown>;
52
+ }): Promise<SessionOut>;
43
53
  export declare function startSession(opts?: StartOptions): Promise<SessionState>;
44
54
  export declare function togglePause(): Promise<boolean>;
45
55
  /** A plain note — `{text, route}`, the extension's shape. */
@@ -6,7 +6,7 @@ import { noteRecent, updateRecent } from './recents';
6
6
  import { currentRoute, notify } from './state';
7
7
  export { currentRoute, notify, subscribe } from './state';
8
8
  /** Sent as `meta.recorder`; bumped with the package version. */
9
- export const RECORDER_VERSION = '0.2.2';
9
+ export const RECORDER_VERSION = '0.3.0';
10
10
  export const RECORDER_ID = `web/${RECORDER_VERSION}`;
11
11
  /**
12
12
  * Re-apply a RECOVERED session's redaction policy after a reload — and
@@ -54,27 +54,40 @@ function pageHost() {
54
54
  return '';
55
55
  }
56
56
  }
57
- export async function startSession(opts = {}) {
57
+ /**
58
+ * `POST /api/v1/sessions` as every web session makes it — a recording and a
59
+ * bug report alike: the page's `host`, the configured project and lane, and
60
+ * the recorder meta. `devicePixelRatio` is the scale every rect is recorded
61
+ * in (`imagePixels`), so the server shoots its stills at it.
62
+ */
63
+ export function createSession(title, opts = {}) {
58
64
  const cfg = recorderConfig();
59
- // The safe defaults apply from the first captured byte; the workspace
60
- // policy (fetched in parallel — fetchPolicy never rejects) can only ADD
61
- // rules or, self-host only, fullFidelity.
62
- setRedactionPolicy(null);
63
- const policyPromise = fetchPolicy();
64
65
  const environment = opts.environment ?? cfg.environment;
65
- const ses = await api('POST', '/api/v1/sessions', {
66
+ return api('POST', '/api/v1/sessions', {
66
67
  host: pageHost(),
67
- title: opts.title || '',
68
+ title,
68
69
  ...(cfg.project ? { project: cfg.project } : {}),
69
70
  ...(environment ? { environment } : {}),
70
71
  meta: {
71
72
  recorder: RECORDER_ID,
72
73
  userAgent: globalThis.navigator?.userAgent ?? '',
73
74
  platform: 'web',
75
+ devicePixelRatio: globalThis.devicePixelRatio || 1,
74
76
  ...(cfg.appVersion ? { appVersion: cfg.appVersion } : {}),
75
- ...(opts.driver ? { driver: opts.driver } : {}),
77
+ ...opts.meta,
76
78
  },
77
79
  });
80
+ }
81
+ export async function startSession(opts = {}) {
82
+ // The safe defaults apply from the first captured byte; the workspace
83
+ // policy (fetched in parallel — fetchPolicy never rejects) can only ADD
84
+ // rules or, self-host only, fullFidelity.
85
+ setRedactionPolicy(null);
86
+ const policyPromise = fetchPolicy();
87
+ const ses = await createSession(opts.title || '', {
88
+ ...(opts.environment ? { environment: opts.environment } : {}),
89
+ ...(opts.driver ? { meta: { driver: opts.driver } } : {}),
90
+ });
78
91
  void policyPromise.then((policy) => {
79
92
  const rec = getState();
80
93
  if (rec?.sessionId !== ses.id)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitrinka/web",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "description": "vitrinka toolkit for React DOM apps — the journey recorder: capture manual-testing sessions (rrweb DOM stream, clicks, navigation, network, console, notes) straight into vitrinka boards.",
5
5
  "license": "Elastic-2.0",
6
6
  "repository": {