@testerpaykit/sdk 0.0.0-stage → 1.2.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.
@@ -0,0 +1,973 @@
1
+ import { ISessionManager, IStorage, IApiClient, DeviceMetadata, AppMetadata, BugReportInput, VoiceBugExtractResponse, QuickActionKind, MyBugReportsResponse, NotificationsResult, OutboxItemStatus, WeeklySummary, TaskListFilter, TaskListResponse, RetestItem, RetestStepVerdicts, TesterProfile, TesterPoints, IEventTracker } from '@testerpaykit/core';
2
+ export { AppMetadata, BUG_REPORT_CATEGORIES, BUG_REPORT_SEVERITIES, BUG_REPORT_TYPES, BugReportCategory, BugReportInput, BugReportSeverity, BugReportType, DeviceMetadata, IApiClient, IEventTracker, ISessionManager, IStorage, OutboxItemStatus, QualityFlags, SessionMetrics, WeeklySummary } from '@testerpaykit/core';
3
+
4
+ type SessionEndReason = 'completed' | 'lifecycle_flush' | 'timeout' | 'abandoned';
5
+ /**
6
+ * Session manager implementation for tracking user testing sessions.
7
+ *
8
+ * Implements ISessionManager interface and manages the lifecycle of testing sessions,
9
+ * including session creation, duration tracking, foreground/paid-time clock,
10
+ * and database persistence.
11
+ */
12
+ declare class SessionManager implements ISessionManager {
13
+ private currentSessionId;
14
+ private sessionStartTime;
15
+ private storage;
16
+ private foregroundAccumulatedMs;
17
+ private foregroundClockStartMs;
18
+ constructor(storage: IStorage);
19
+ /**
20
+ * Start a new testing session.
21
+ *
22
+ * Creates a new session with a unique ID and stores it in the database.
23
+ * If there's an active session, it will be ended before starting the new one.
24
+ *
25
+ * @returns Promise resolving to the new session ID
26
+ */
27
+ startSession(): Promise<string>;
28
+ /**
29
+ * End the current testing session.
30
+ *
31
+ * Calculates session duration and updates the database.
32
+ * After ending, no session will be active.
33
+ *
34
+ * @param endReason - Reason for ending the session (default: 'completed')
35
+ */
36
+ endSession(endReason?: SessionEndReason): Promise<void>;
37
+ /**
38
+ * Pause the foreground (paid-time) clock.
39
+ * Call when the app moves to background. Has no effect if already paused.
40
+ */
41
+ pauseForegroundClock(): void;
42
+ /**
43
+ * Resume the foreground (paid-time) clock.
44
+ * Call when the app returns to foreground. Has no effect if already running.
45
+ */
46
+ resumeForegroundClock(): void;
47
+ /**
48
+ * Get the accumulated foreground seconds for the current session.
49
+ *
50
+ * @returns Foreground time in whole seconds
51
+ */
52
+ getForegroundSeconds(): number;
53
+ /**
54
+ * Get the current session ID.
55
+ *
56
+ * @returns Current session ID or null if no session is active
57
+ */
58
+ getCurrentSessionId(): string | null;
59
+ /**
60
+ * Check if there's an active session.
61
+ *
62
+ * @returns true if a session is currently active
63
+ */
64
+ hasActiveSession(): boolean;
65
+ /**
66
+ * Get the current session duration in seconds.
67
+ *
68
+ * @returns Duration in seconds, or 0 if no session is active
69
+ */
70
+ getSessionDuration(): number;
71
+ /**
72
+ * Get the epoch-ms timestamp when the current session started.
73
+ *
74
+ * @returns Epoch ms, or null when no session is active
75
+ */
76
+ getCurrentSessionStartedAt(): number | null;
77
+ /**
78
+ * Increment the screen view count for the current session.
79
+ * Internal method used by EventTracker.
80
+ */
81
+ incrementScreenViews(): Promise<void>;
82
+ /**
83
+ * Increment the tap count for the current session.
84
+ * Internal method used by EventTracker.
85
+ */
86
+ incrementTaps(): Promise<void>;
87
+ }
88
+
89
+ /**
90
+ * Configuration for TesterPayKit SDK.
91
+ */
92
+ interface TesterPayKitConfig {
93
+ /**
94
+ * API key for authentication
95
+ */
96
+ apiKey: string;
97
+ /**
98
+ * API base URL (required). Used to derive `environment`.
99
+ * e.g. "https://api.testerpaykit.com" or "http://localhost:18080"
100
+ */
101
+ apiBaseUrl?: string;
102
+ /**
103
+ * Project identifier
104
+ */
105
+ projectId: string;
106
+ /**
107
+ * Tester pseudonymous identifier
108
+ */
109
+ testerId: string;
110
+ /**
111
+ * Device pseudonymous identifier override.
112
+ * When omitted, a UUIDv4 is generated and persisted by DeviceIdManager
113
+ * with a 30-day rotation policy (contract: invariants.device_id).
114
+ */
115
+ deviceId?: string;
116
+ /**
117
+ * Storage adapter instance
118
+ */
119
+ storage: IStorage;
120
+ /**
121
+ * API client instance (optional, for Agent 4 integration)
122
+ */
123
+ apiClient?: IApiClient;
124
+ /**
125
+ * Device metadata
126
+ */
127
+ deviceMetadata: DeviceMetadata;
128
+ /**
129
+ * App metadata
130
+ */
131
+ appMetadata: AppMetadata;
132
+ /**
133
+ * Automatically start a session on init (default: true)
134
+ */
135
+ autoStartSession?: boolean;
136
+ /**
137
+ * Enable debug logging (default: false)
138
+ */
139
+ debugMode?: boolean;
140
+ /**
141
+ * Base payout amount awarded at session start (default: 1.0).
142
+ */
143
+ earningsBaseAmount?: number;
144
+ /**
145
+ * Additional payout per engaged minute (default: 0.10).
146
+ */
147
+ earningsPerMinuteRate?: number;
148
+ /**
149
+ * Currency for earnings display (default: 'EUR').
150
+ */
151
+ earningsCurrency?: string;
152
+ /**
153
+ * Capture screen view events (default: true)
154
+ */
155
+ captureScreenViews?: boolean;
156
+ /**
157
+ * Capture tap/click events (default: true)
158
+ */
159
+ captureTapEvents?: boolean;
160
+ /**
161
+ * Capture error events (default: true)
162
+ */
163
+ captureErrors?: boolean;
164
+ /**
165
+ * Capture crash events (default: true)
166
+ */
167
+ captureCrashes?: boolean;
168
+ /**
169
+ * Day of week for the weekly period submission (1=Mon … 7=Sun, default: 7).
170
+ * Contract: configuration.weeklySubmissionDay
171
+ */
172
+ weeklySubmissionDay?: number;
173
+ /**
174
+ * Extra state the live link to Claude Code reports as `app_state`
175
+ * (MCP `device_snapshot`). Must return JSON-serialisable data. Can also be
176
+ * set later via `sdk.liveStateProvider`.
177
+ */
178
+ liveStateProvider?: () => unknown;
179
+ }
180
+ /** One step verdict of a checklist pass (`step` is 1-based). */
181
+ interface ChecklistStepResult {
182
+ step: number;
183
+ passed: boolean;
184
+ note?: string;
185
+ }
186
+ /** The latest pass through a checklist task (by this tester or the AI). */
187
+ interface ChecklistRun {
188
+ status: 'passed' | 'failed' | 'incomplete' | string;
189
+ steps: ChecklistStepResult[];
190
+ summary?: string;
191
+ at: string;
192
+ tester?: string;
193
+ }
194
+ /** One task of a project's checklist: what should be tested. */
195
+ interface ChecklistTask {
196
+ id: string;
197
+ title: string;
198
+ description?: string;
199
+ steps: string[];
200
+ mine?: ChecklistRun;
201
+ ai?: ChecklistRun;
202
+ }
203
+ /**
204
+ * Main TesterPayKit SDK class.
205
+ *
206
+ * Orchestrates session management, event tracking, and metrics aggregation
207
+ * for the TesterPayKit testing platform.
208
+ *
209
+ * @example
210
+ * ```typescript
211
+ * import { TesterPayKit } from '@testerpaykit/sdk';
212
+ * import { IndexedDBAdapter } from '@testerpaykit/storage-browser';
213
+ *
214
+ * const storage = new IndexedDBAdapter();
215
+ * const sdk = new TesterPayKit({
216
+ * apiKey: 'your-api-key',
217
+ * apiBaseUrl: 'https://api.testerpaykit.com',
218
+ * projectId: 'project-123',
219
+ * testerId: 'tester-456',
220
+ * storage,
221
+ * deviceMetadata: { os: 'Web', osVersion: '1.0', ... },
222
+ * appMetadata: { bundleId: 'com.example.app', version: '1.0.0', ... },
223
+ * });
224
+ *
225
+ * await sdk.init();
226
+ * await sdk.anonymousAuthReady; // wait for auth before first authed call
227
+ * await sdk.trackScreenView('HomeScreen');
228
+ * ```
229
+ */
230
+ declare class TesterPayKit {
231
+ private config;
232
+ private sessionManager;
233
+ private eventTracker;
234
+ private metricsAggregator;
235
+ private outbox;
236
+ private deviceIdManager;
237
+ private initialized;
238
+ private _resolvedDeviceId;
239
+ private _resolvedTesterId;
240
+ private _authToken;
241
+ private _serverSessionId;
242
+ private _pendingSessionEvents;
243
+ readonly anonymousAuthReady: Promise<void>;
244
+ private _resolveAnonymousAuth;
245
+ readonly environment: 'local' | 'prod';
246
+ private static readonly LOG_BUFFER_MAX;
247
+ private _logBuffer;
248
+ /**
249
+ * Host hook for the live link's `app_state` (see
250
+ * `TesterPayKitConfig.liveStateProvider`). Settable at any time.
251
+ */
252
+ liveStateProvider: (() => unknown) | null;
253
+ constructor(config: TesterPayKitConfig);
254
+ get onTokenReady(): Promise<void>;
255
+ get isAuthenticated(): boolean;
256
+ /**
257
+ * Initialize the SDK.
258
+ *
259
+ * Must be called before using any other SDK methods.
260
+ * Initializes storage and optionally starts a session.
261
+ */
262
+ init(): Promise<void>;
263
+ /**
264
+ * Provide an auth token to the SDK (e.g. after anonymous login).
265
+ * Makes isAuthenticated return true and enables runDurabilitySweep.
266
+ */
267
+ setAuthToken(token: string): void;
268
+ /**
269
+ * Request a passwordless magic-link sign-in for a registered tester.
270
+ * TesterPayKit tester auth is magic-link (no passwords): the server emails a
271
+ * single-use link that returns to `returnUrl` (a first-party *.moinsen.dev
272
+ * page) carrying a token, which the host consumes via consumeTesterMagicLink.
273
+ * `country` (DE/AT/CH) lets an unknown email self-signup. Returns true if the
274
+ * request was accepted. Never throws.
275
+ */
276
+ requestTesterMagicLink(email: string, returnUrl: string, country?: string): Promise<boolean>;
277
+ /**
278
+ * Consume a magic-link token (from the returnUrl the tester landed on). On
279
+ * success the real tester token supersedes the anonymous one, the tester is
280
+ * enrolled in this project, and {accessToken, refreshToken} is returned so
281
+ * the host can persist the session. Returns null on failure. Never throws.
282
+ */
283
+ consumeTesterMagicLink(token: string): Promise<{
284
+ accessToken: string;
285
+ refreshToken?: string;
286
+ } | null>;
287
+ /**
288
+ * Enroll the current tester into THIS project (idempotent, best-effort).
289
+ * Used right after loginTester so the tester is a project participant.
290
+ * Returns true if enrolled (or already enrolled), false on hard failure.
291
+ */
292
+ enrollSelf(): Promise<boolean>;
293
+ /** device_info payload for the server session, from configured metadata. */
294
+ private _sessionDeviceInfo;
295
+ /**
296
+ * Lazily create the SERVER tester session once an anonymous token is in
297
+ * hand, then flush any buffered events. This is what makes the session
298
+ * show up in the coordinator dashboard. Best-effort: never throws.
299
+ */
300
+ private _ensureServerSession;
301
+ private _serverSessionInFlight;
302
+ private _createServerSession;
303
+ /** Flush buffered session events to the server (best-effort, re-queues on fail). */
304
+ private _flushServerSessionEvents;
305
+ /** End the server session (best-effort). Clears the id so it won't re-end. */
306
+ private _endServerSession;
307
+ /**
308
+ * Run a durability sweep to ensure testing work is persisted and uploaded.
309
+ *
310
+ * No-op when no auth token is held. Otherwise, best-effort (each step is
311
+ * individually wrapped so one failure does not abort the rest):
312
+ *
313
+ * 1. Reconcile open sessions: find sessions in storage without an end_time
314
+ * and close them with endReason='abandoned' so their duration counts.
315
+ * 2. Auto-create a period submission when overdue: tracks the last submission
316
+ * timestamp in sdk_meta. "Due" = more than 7 days since last enqueue.
317
+ * (Heuristic — uses wall-clock elapsed time, not calendar periods.)
318
+ * 3. Drain the outbox. The Outbox drain already skips server-known submission
319
+ * ids (fetchServerSubmissionIds guard) so no double-pay occurs.
320
+ *
321
+ * Contract: api.submissions.runDurabilitySweep
322
+ */
323
+ runDurabilitySweep(): Promise<void>;
324
+ private _reconcileOpenSessions;
325
+ private _autoCreateSubmissionIfDue;
326
+ /**
327
+ * Start a new testing session.
328
+ *
329
+ * @returns Promise resolving to the new session ID
330
+ */
331
+ startSession(): Promise<string>;
332
+ /**
333
+ * End the current testing session.
334
+ *
335
+ * @param endReason - Reason for ending (default: 'completed')
336
+ */
337
+ endSession(endReason?: SessionEndReason): Promise<void>;
338
+ /**
339
+ * Call when the app moves to the foreground / resumes.
340
+ *
341
+ * Contract behaviour:
342
+ * - If NO active session exists → start a new one.
343
+ * - If a session IS active → resume the foreground clock only.
344
+ * MUST NOT end and restart the active session.
345
+ */
346
+ onAppResumed(): Promise<void>;
347
+ /**
348
+ * Call when the app moves to the background / is paused.
349
+ *
350
+ * Contract behaviour: freezes the foreground clock.
351
+ * MUST NOT end the session.
352
+ */
353
+ onAppPaused(): void;
354
+ /**
355
+ * Call when the app becomes inactive (e.g. phone call overlay, app-switcher).
356
+ *
357
+ * Contract behaviour: no-op for the session (may log only).
358
+ */
359
+ onAppInactive(): void;
360
+ /**
361
+ * Call when the app process is about to be detached / destroyed.
362
+ *
363
+ * Contract behaviour: ends the active session with end_reason='lifecycle_flush'.
364
+ */
365
+ onAppDetached(): Promise<void>;
366
+ /**
367
+ * Track a screen view event.
368
+ *
369
+ * @param screenName - Name or route of the screen
370
+ * @param metadata - Optional additional metadata
371
+ */
372
+ trackScreenView(screenName: string, metadata?: Record<string, any>): Promise<void>;
373
+ /**
374
+ * Track a tap/click event.
375
+ *
376
+ * @param screenName - Name of the screen where the tap occurred
377
+ * @param elementId - Optional ID of the tapped element
378
+ */
379
+ trackTap(screenName: string, elementId?: string): Promise<void>;
380
+ /**
381
+ * Track a custom event.
382
+ *
383
+ * @param eventType - Type of the event
384
+ * @param metadata - Optional event metadata
385
+ */
386
+ trackEvent(eventType: string, metadata?: Record<string, any>): Promise<void>;
387
+ /**
388
+ * Track an error.
389
+ *
390
+ * @param message - Error message
391
+ * @param stack - Optional stack trace
392
+ */
393
+ trackError(message: string, stack?: string): Promise<void>;
394
+ /**
395
+ * Track a crash.
396
+ *
397
+ * @param message - Crash message
398
+ * @param stack - Stack trace
399
+ */
400
+ trackCrash(message: string, stack: string): Promise<void>;
401
+ /**
402
+ * Track feedback submission.
403
+ *
404
+ * @param content - Feedback content
405
+ * @param rating - Optional numeric rating
406
+ */
407
+ trackFeedback(content: string, rating?: number): Promise<void>;
408
+ /**
409
+ * Track task start.
410
+ *
411
+ * @param taskId - Unique task identifier
412
+ * @param title - Task title
413
+ */
414
+ trackTaskStart(taskId: string, title: string): Promise<void>;
415
+ /**
416
+ * Track task completion.
417
+ *
418
+ * @param taskId - Unique task identifier
419
+ */
420
+ trackTaskComplete(taskId: string): Promise<void>;
421
+ /**
422
+ * Enqueue a bug report to the local outbox and return a local UUID
423
+ * immediately. The upload happens in the background — this method
424
+ * never awaits the network.
425
+ *
426
+ * Builds the full payload required by POST /v1/testers/me/bug-reports:
427
+ * sessionId, type, severity, category, title, description,
428
+ * currentScreen, deviceSnapshot, appSnapshot, projectId.
429
+ * testerId is intentionally omitted — the endpoint is tester-namespaced
430
+ * and derives the tester from the JWT.
431
+ *
432
+ * Contract: api.submissions.submitBugReport / invariants.local_first_outbox
433
+ *
434
+ * @param input - Structured bug report input
435
+ * @returns A local UUID that can be passed to getSubmissionStatus()
436
+ */
437
+ submitBugReport(input: BugReportInput): string;
438
+ /**
439
+ * Extract structured bug-report fields from a base64-encoded audio recording.
440
+ *
441
+ * Delegates to apiClient.voiceExtractBugFields. When `sourceLanguage` is
442
+ * explicitly provided (ISO-639-1, e.g. 'de'), it is forwarded as-is.
443
+ * When omitted, the language hint falls back to navigator.language
444
+ * (best-effort, browser-only). Soft-fails to null when the apiClient does
445
+ * not implement voiceExtractBugFields or the call throws.
446
+ *
447
+ * Contract: wire.bug_reports.voiceExtractBugFields
448
+ *
449
+ * @param audioBase64 - Raw base64 audio (no data: prefix)
450
+ * @param mimeType - MIME type of the audio (e.g. 'audio/webm')
451
+ * @param sourceLanguage - Optional explicit ISO-639-1 language code; when
452
+ * omitted the SDK derives it from navigator.language
453
+ * @returns Extracted fields, or null on any failure
454
+ */
455
+ extractBugFromVoice(audioBase64: string, mimeType: string, sourceLanguage?: string): Promise<VoiceBugExtractResponse | null>;
456
+ /**
457
+ * One-tap report draft from a screenshot of the current screen — the
458
+ * quick-action path next to voice. Returns null when the client does
459
+ * not support it; throws on a server error so the UI can show it.
460
+ *
461
+ * Contract: wire.bug_reports.quickDraftBug
462
+ *
463
+ * @param screenshotDataUrl - `data:image/...;base64,...` of the screen
464
+ */
465
+ quickDraftBug(action: QuickActionKind, screenshotDataUrl: string, options?: {
466
+ screenName?: string;
467
+ language?: string;
468
+ }): Promise<VoiceBugExtractResponse | null>;
469
+ /**
470
+ * Upload an arbitrary attachment (screenshot, screen recording, voice note, etc.)
471
+ * to the standalone attachments endpoint (POST /v1/attachments).
472
+ *
473
+ * Returns the stored URL/path on success, null on any failure (best-effort,
474
+ * never throws).
475
+ *
476
+ * Contract: wire.bug_reports.uploadAttachment (standalone path)
477
+ *
478
+ * @param input - Attachment data with base64 content, MIME type, file type, and optional file name
479
+ * @returns The attachment url/path string, or null if upload failed or client unavailable
480
+ */
481
+ uploadAttachment(input: {
482
+ base64: string;
483
+ mimeType: string;
484
+ fileType: 'screen_recording' | 'voice_note' | 'image' | 'screenshot' | 'video' | 'audio' | 'log' | 'document' | 'other';
485
+ fileName?: string;
486
+ }): Promise<string | null>;
487
+ /**
488
+ * Upload a screenshot dataURL to the standalone attachments endpoint.
489
+ *
490
+ * Converts the dataURL to a base64 payload and calls
491
+ * POST /v1/attachments via the api-client. Returns the attachment
492
+ * url/path on success, null on any failure (best-effort, never throws).
493
+ *
494
+ * Contract: wire.bug_reports.uploadAttachment (standalone path)
495
+ *
496
+ * @param dataUrl - A JPEG/PNG dataURL (e.g. from html2canvas or captureScreenshot)
497
+ * @returns The attachment url string, or null if upload failed or client unavailable
498
+ */
499
+ uploadScreenshot(dataUrl: string): Promise<string | null>;
500
+ /**
501
+ * Fetch the bug reports this tester has submitted (newest first).
502
+ * Delegates to apiClient.listMyBugReports. Soft-fails to an empty list
503
+ * when the client lacks the method or the call throws.
504
+ *
505
+ * Requires a tester auth token — if unauthenticated the server 401s and
506
+ * this returns the empty-list soft-fail result.
507
+ */
508
+ getMyBugReports(params?: {
509
+ status?: string;
510
+ limit?: number;
511
+ page?: number;
512
+ }): Promise<MyBugReportsResponse>;
513
+ /**
514
+ * Fetch tester notifications + unread count.
515
+ * Delegates to apiClient.getMyNotifications. Soft-fails to
516
+ * { notifications: [], unreadCount: 0 } on any error or missing method.
517
+ *
518
+ * Requires a tester auth token.
519
+ */
520
+ getNotifications(params?: {
521
+ limit?: number;
522
+ unreadOnly?: boolean;
523
+ }): Promise<NotificationsResult>;
524
+ /**
525
+ * Mark notifications read. Pass an id to mark one; omit to mark all.
526
+ * Delegates to apiClient.markNotificationsRead. Soft-fails to null on
527
+ * any error or missing method (caller should treat null as "no change").
528
+ *
529
+ * Requires a tester auth token.
530
+ *
531
+ * @returns New unread count, or null on soft-fail.
532
+ */
533
+ markNotificationsRead(id?: string): Promise<number | null>;
534
+ /**
535
+ * Aggregate local metrics and enqueue a submission to the outbox.
536
+ * Returns a local UUID immediately — the upload happens in the background.
537
+ *
538
+ * Contract: api.submissions.createSubmissionAsync / invariants.local_first_outbox
539
+ *
540
+ * @returns A local UUID that can be passed to getSubmissionStatus()
541
+ */
542
+ createSubmission(): Promise<string>;
543
+ /**
544
+ * Query the outbox state for a previously-enqueued item.
545
+ *
546
+ * Returns:
547
+ * 'pending' — enqueued, not yet uploaded
548
+ * 'uploading' — upload in progress
549
+ * 'failed' — permanently rejected (4xx); will not be retried
550
+ * null — item not found; treat as successfully sent (deleted on success)
551
+ *
552
+ * Contract: api.submissions.getSubmissionStatus / enums.OutboxItemStatus
553
+ *
554
+ * @param localId - The id returned by submitBugReport() or createSubmission()
555
+ */
556
+ getSubmissionStatus(localId: string): Promise<OutboxItemStatus | null>;
557
+ /**
558
+ * Generate and store a weekly summary.
559
+ *
560
+ * Aggregates all metrics from the past 7 days and stores the summary
561
+ * in the local database for later submission.
562
+ *
563
+ * @returns Promise resolving to the generated summary
564
+ */
565
+ generateWeeklySummary(): Promise<WeeklySummary>;
566
+ /**
567
+ * Get all pending summaries.
568
+ *
569
+ * @returns Array of pending WeeklySummary objects
570
+ */
571
+ getPendingSummaries(): Promise<WeeklySummary[]>;
572
+ /**
573
+ * Submit pending summaries to the server.
574
+ * Requires apiClient to be configured.
575
+ *
576
+ * @returns Number of summaries successfully submitted
577
+ */
578
+ submitPendingSummaries(): Promise<number>;
579
+ /**
580
+ * Get the current session ID.
581
+ *
582
+ * @returns Current session ID or null if no session is active
583
+ */
584
+ getCurrentSessionId(): string | null;
585
+ /**
586
+ * Check if there's an active session.
587
+ *
588
+ * @returns true if a session is currently active
589
+ */
590
+ hasActiveSession(): boolean;
591
+ /**
592
+ * Get the current session duration in seconds.
593
+ *
594
+ * @returns Duration in seconds, or 0 if no session is active
595
+ */
596
+ getSessionDuration(): number;
597
+ /**
598
+ * Close the SDK and clean up resources.
599
+ */
600
+ close(): Promise<void>;
601
+ /**
602
+ * Ensure the SDK is initialized before use.
603
+ * @throws Error if SDK is not initialized
604
+ */
605
+ private ensureInitialized;
606
+ /**
607
+ * Log debug messages. Always pushes to the ring buffer (regardless of
608
+ * debugMode) so TpkDebugLogsScreen has content. Console output stays
609
+ * gated by debugMode.
610
+ */
611
+ private log;
612
+ /**
613
+ * Get a copy of the debug log buffer, newest entry first.
614
+ * The buffer accumulates up to 200 entries regardless of debugMode.
615
+ */
616
+ getDebugLogs(): Array<{
617
+ ts: number;
618
+ message: string;
619
+ }>;
620
+ /**
621
+ * Clear the debug log buffer.
622
+ */
623
+ clearDebugLogs(): void;
624
+ /**
625
+ * Get the epoch-ms timestamp when the current session started.
626
+ * Delegates to SessionManager.
627
+ *
628
+ * @returns Epoch ms, or null when no session is active
629
+ */
630
+ getCurrentSessionStartedAt(): number | null;
631
+ /**
632
+ * Compute estimated session earnings.
633
+ *
634
+ * engagedMinutes = floor(elapsed since session start in minutes).
635
+ * amount = earningsBaseAmount + engagedMinutes * earningsPerMinuteRate.
636
+ * currency = earningsCurrency from config.
637
+ *
638
+ * Soft-safe: never throws; returns base/0/currency when no session.
639
+ * Max cap: 480 minutes (8 hours) to keep amounts sane.
640
+ */
641
+ getSessionEarnings(): {
642
+ engagedMinutes: number;
643
+ amount: number;
644
+ currency: string;
645
+ };
646
+ /**
647
+ * Return the configured app metadata (bundleId, version, buildNumber, etc.).
648
+ * Used by TpkWorkboardScreen to show the current build info block.
649
+ */
650
+ getAppInfo(): AppMetadata;
651
+ private _liveApi;
652
+ /**
653
+ * One-time WebSocket URL for the live link to the developer's Claude Code
654
+ * session (POST /v1/testers/me/live). Fetch a fresh one for every connect.
655
+ * Throws when the call fails.
656
+ */
657
+ openLiveLink(): Promise<string>;
658
+ /**
659
+ * "Send to Claude": one line plus what the screen showed
660
+ * (POST /v1/testers/me/live/notes). Throws when the call fails.
661
+ */
662
+ sendLiveNote(input: {
663
+ text: string;
664
+ snapshot: Record<string, unknown>;
665
+ screenshotBase64?: string | null;
666
+ }): Promise<string>;
667
+ /**
668
+ * The project's checklist ("What to test") with this tester's last pass.
669
+ * Soft-fails to [] (offline, not logged in, older api-client).
670
+ */
671
+ getChecklist(): Promise<ChecklistTask[]>;
672
+ /**
673
+ * One pass through a checklist task, a verdict per step
674
+ * (POST /v1/testers/me/checklist/:id/runs). Resolves with the run status;
675
+ * throws when the call fails.
676
+ */
677
+ submitChecklistRun(input: {
678
+ taskId: string;
679
+ stepResults: ChecklistStepResult[];
680
+ summary?: string;
681
+ }): Promise<string>;
682
+ /**
683
+ * Fetch the tester's assigned tasks.
684
+ * Delegates to apiClient.getMyTasks. Soft-fails to an empty TaskListResponse
685
+ * when the client lacks the method or the call throws.
686
+ */
687
+ getMyTasks(params?: TaskListFilter): Promise<TaskListResponse>;
688
+ /**
689
+ * Mark a task assignment in-progress.
690
+ * Delegates to apiClient.startTaskAssignment. Soft-fails silently on error.
691
+ */
692
+ startTask(assignmentId: string): Promise<void>;
693
+ /**
694
+ * Complete a task assignment.
695
+ * Delegates to apiClient.completeTaskAssignment. Soft-fails silently on error.
696
+ */
697
+ completeTask(assignmentId: string): Promise<void>;
698
+ /**
699
+ * Fetch the tester's retest queue.
700
+ * Delegates to apiClient.getMyRetests. Soft-fails to an empty array.
701
+ */
702
+ getMyRetests(params?: {
703
+ status?: string;
704
+ }): Promise<RetestItem[]>;
705
+ /**
706
+ * Mark a retest as verified (bug is fixed).
707
+ * Delegates to apiClient.verifyRetest. Soft-fails silently on error.
708
+ */
709
+ verifyRetest(bugId: string, stepVerdicts?: RetestStepVerdicts): Promise<void>;
710
+ /**
711
+ * Reopen a retest (bug still present), optionally with a reason.
712
+ * Delegates to apiClient.reopenRetest. Soft-fails silently on error.
713
+ */
714
+ reopenRetest(bugId: string, reason?: string, stepVerdicts?: RetestStepVerdicts): Promise<void>;
715
+ /**
716
+ * Fetch the tester's profile.
717
+ * Delegates to apiClient.getMyProfile. Soft-fails to null on error.
718
+ */
719
+ getMyProfile(): Promise<TesterProfile | null>;
720
+ /**
721
+ * Fetch the tester's points balance.
722
+ * Delegates to apiClient.getMyPoints. Soft-fails to null on error.
723
+ */
724
+ getMyPoints(): Promise<TesterPoints | null>;
725
+ }
726
+
727
+ interface CaptureFlags {
728
+ captureScreenViews: boolean;
729
+ captureTapEvents: boolean;
730
+ captureErrors: boolean;
731
+ captureCrashes: boolean;
732
+ }
733
+ /**
734
+ * Event tracker implementation for capturing user interactions and app events.
735
+ *
736
+ * Implements IEventTracker interface and tracks various event types including
737
+ * screen views, taps, errors, crashes, feedback, and task progress.
738
+ */
739
+ declare class EventTracker implements IEventTracker {
740
+ private storage;
741
+ private sessionId;
742
+ private captureFlags;
743
+ constructor(storage: IStorage, captureFlags?: Partial<CaptureFlags>);
744
+ /**
745
+ * Set the current session ID.
746
+ * Must be called before tracking events.
747
+ *
748
+ * @param sessionId - The active session ID
749
+ */
750
+ setSessionId(sessionId: string): void;
751
+ /**
752
+ * Track a screen view event.
753
+ * Gated by captureScreenViews flag.
754
+ *
755
+ * @param screenName - Name or route of the screen being viewed
756
+ * @param metadata - Optional additional metadata
757
+ */
758
+ trackScreenView(screenName: string, metadata?: Record<string, any>): Promise<void>;
759
+ /**
760
+ * Track a tap/click event.
761
+ * Gated by captureTapEvents flag.
762
+ *
763
+ * @param screenName - Name of the screen where the tap occurred
764
+ * @param elementId - Optional ID of the tapped element
765
+ */
766
+ trackTap(screenName: string, elementId?: string): Promise<void>;
767
+ /**
768
+ * Track a custom event.
769
+ *
770
+ * @param eventType - Type of the event
771
+ * @param metadata - Optional event metadata
772
+ */
773
+ trackEvent(eventType: string, metadata?: Record<string, any>): Promise<void>;
774
+ /**
775
+ * Track an error event.
776
+ * Gated by captureErrors flag.
777
+ *
778
+ * @param message - Error message
779
+ * @param stack - Optional stack trace
780
+ */
781
+ trackError(message: string, stack?: string): Promise<void>;
782
+ /**
783
+ * Track a crash event.
784
+ * Gated by captureCrashes flag.
785
+ *
786
+ * @param message - Crash message
787
+ * @param stack - Stack trace
788
+ */
789
+ trackCrash(message: string, stack: string): Promise<void>;
790
+ /**
791
+ * Track a feedback submission.
792
+ *
793
+ * @param content - Feedback content
794
+ * @param rating - Optional numeric rating
795
+ */
796
+ trackFeedback(content: string, rating?: number): Promise<void>;
797
+ /**
798
+ * Track task start event.
799
+ *
800
+ * @param taskId - Unique task identifier
801
+ * @param title - Task title
802
+ */
803
+ trackTaskStart(taskId: string, title: string): Promise<void>;
804
+ /**
805
+ * Track task completion event.
806
+ *
807
+ * @param taskId - Unique task identifier
808
+ */
809
+ trackTaskComplete(taskId: string): Promise<void>;
810
+ /**
811
+ * Store a bug report (error or crash).
812
+ *
813
+ * @param severity - Severity level ('error' or 'crash')
814
+ * @param message - Error/crash message
815
+ * @param stack - Optional stack trace
816
+ */
817
+ private storeBugReport;
818
+ /**
819
+ * Get event counts for a time period.
820
+ * Internal method for metrics aggregation.
821
+ *
822
+ * @param start - Start timestamp
823
+ * @param end - End timestamp
824
+ * @returns Map of event types to counts
825
+ */
826
+ getEventCounts(start: number, end: number): Promise<Record<string, number>>;
827
+ /**
828
+ * Get unique screen names for a time period.
829
+ * Internal method for metrics aggregation.
830
+ *
831
+ * @param start - Start timestamp
832
+ * @param end - End timestamp
833
+ * @returns Array of unique screen names
834
+ */
835
+ getUniqueScreens(start: number, end: number): Promise<string[]>;
836
+ }
837
+
838
+ /**
839
+ * Validation constants for quality assessment.
840
+ */
841
+ declare const ValidationConstants: {
842
+ minActiveMinutes: number;
843
+ minUniqueScreens: number;
844
+ maxTapsPerMinute: number;
845
+ minSessions: number;
846
+ };
847
+ /**
848
+ * Configuration for MetricsAggregator.
849
+ */
850
+ interface MetricsAggregatorConfig {
851
+ projectId: string;
852
+ testerId: string;
853
+ deviceId: string;
854
+ deviceMetadata: DeviceMetadata;
855
+ appMetadata: AppMetadata;
856
+ }
857
+ /**
858
+ * Metrics aggregator for generating weekly summaries.
859
+ *
860
+ * Aggregates session data, events, feedback, tasks, and bug reports
861
+ * into a comprehensive weekly summary for submission.
862
+ */
863
+ declare class MetricsAggregator {
864
+ private storage;
865
+ private config;
866
+ constructor(storage: IStorage, config: MetricsAggregatorConfig);
867
+ /**
868
+ * Aggregate a weekly summary for the past 7 days.
869
+ *
870
+ * @returns Promise resolving to the generated WeeklySummary
871
+ */
872
+ aggregateWeeklySummary(): Promise<WeeklySummary>;
873
+ /**
874
+ * Aggregate a summary for a specific time period.
875
+ *
876
+ * @param startTime - Start timestamp (milliseconds)
877
+ * @param endTime - End timestamp (milliseconds)
878
+ * @returns Promise resolving to the generated WeeklySummary
879
+ */
880
+ aggregateSummaryForPeriod(startTime: number, endTime: number): Promise<WeeklySummary>;
881
+ /**
882
+ * Store a weekly summary in the local database.
883
+ *
884
+ * @param summary - The summary to store
885
+ */
886
+ storeSummary(summary: WeeklySummary): Promise<void>;
887
+ /**
888
+ * Get pending summaries from the local database.
889
+ *
890
+ * @returns Array of pending WeeklySummary objects
891
+ */
892
+ getPendingSummaries(): Promise<WeeklySummary[]>;
893
+ /**
894
+ * Update summary status.
895
+ *
896
+ * @param summaryId - ID of the summary
897
+ * @param status - New status
898
+ */
899
+ updateSummaryStatus(summaryId: string, status: string): Promise<void>;
900
+ private getSessions;
901
+ private getEventCounts;
902
+ private getUniqueScreens;
903
+ private getFeedbackStats;
904
+ private getTaskStats;
905
+ private getBugReportStats;
906
+ private calculateQualityFlags;
907
+ private generateIntegrityHash;
908
+ private calculateEstimatedPayout;
909
+ }
910
+
911
+ declare class Outbox {
912
+ private storage;
913
+ private apiClient;
914
+ private draining;
915
+ constructor(storage: IStorage, apiClient?: IApiClient);
916
+ initSchema(): Promise<void>;
917
+ recoverInFlight(): Promise<void>;
918
+ /** Enqueue a bug_report item; returns the local UUID immediately. */
919
+ enqueueSync(type: 'bug_report' | 'submission', payload: unknown): string;
920
+ /** Enqueue and wait for the DB insert to complete (for async callers). */
921
+ enqueue(type: 'bug_report' | 'submission', payload: unknown): Promise<string>;
922
+ private _insertRow;
923
+ /**
924
+ * Map DB state → OutboxItemStatus.
925
+ * Returns null when the item is not found (means it was sent and deleted).
926
+ */
927
+ getStatus(localId: string): Promise<OutboxItemStatus | null>;
928
+ /**
929
+ * Schedule a drain on the next microtask. Fire-and-forget.
930
+ * Callers (submitBugReport / createSubmission) call this after enqueue.
931
+ */
932
+ scheduleDrain(): void;
933
+ /**
934
+ * Process all pending outbox items. Idempotent — safe to call concurrently
935
+ * (guarded by draining flag). No-ops when apiClient is absent.
936
+ */
937
+ drain(): Promise<void>;
938
+ private _drainLoop;
939
+ private _processRow;
940
+ private _uploadBugReport;
941
+ private _uploadSubmission;
942
+ /** Register a window.online listener that triggers a drain. */
943
+ registerOnlineListener(): void;
944
+ private _extractStatusCode;
945
+ }
946
+
947
+ /**
948
+ * Manages a locally-generated UUIDv4 device id persisted in storage.
949
+ *
950
+ * Contract: invariants.device_id
951
+ * - Generates a new id on first use.
952
+ * - Rotates (new id) after 30 days.
953
+ * - config.deviceId overrides this (passed through, not persisted here).
954
+ */
955
+ declare class DeviceIdManager {
956
+ private storage;
957
+ constructor(storage: IStorage);
958
+ /**
959
+ * Ensure the sdk_meta table exists. Schema is the adapter's responsibility;
960
+ * this is now a no-op kept for backwards-compatible call-sites.
961
+ */
962
+ initSchema(): Promise<void>;
963
+ /**
964
+ * Return the stored device id, creating or rotating it as needed.
965
+ *
966
+ * Rotation policy: if the id is older than 30 days, a new one is generated.
967
+ */
968
+ getOrCreate(): Promise<string>;
969
+ private _upsert;
970
+ }
971
+
972
+ export { DeviceIdManager, EventTracker, MetricsAggregator, Outbox, SessionManager, TesterPayKit, ValidationConstants };
973
+ export type { CaptureFlags, ChecklistRun, ChecklistStepResult, ChecklistTask, MetricsAggregatorConfig, SessionEndReason, TesterPayKitConfig };