@testerpaykit/sdk 0.0.0-stage → 1.1.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/dist/index.js ADDED
@@ -0,0 +1,2097 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ BUG_REPORT_CATEGORIES: () => import_core7.BUG_REPORT_CATEGORIES,
24
+ BUG_REPORT_SEVERITIES: () => import_core7.BUG_REPORT_SEVERITIES,
25
+ BUG_REPORT_TYPES: () => import_core7.BUG_REPORT_TYPES,
26
+ DeviceIdManager: () => DeviceIdManager,
27
+ EventTracker: () => EventTracker,
28
+ MetricsAggregator: () => MetricsAggregator,
29
+ Outbox: () => Outbox,
30
+ SessionManager: () => SessionManager,
31
+ TesterPayKit: () => TesterPayKit,
32
+ ValidationConstants: () => ValidationConstants
33
+ });
34
+ module.exports = __toCommonJS(index_exports);
35
+
36
+ // src/TesterPayKit.ts
37
+ var import_core6 = require("@testerpaykit/core");
38
+
39
+ // src/SessionManager.ts
40
+ var import_core = require("@testerpaykit/core");
41
+ var import_uuid = require("uuid");
42
+ var SessionManager = class {
43
+ // non-null while clock is running
44
+ constructor(storage) {
45
+ this.currentSessionId = null;
46
+ this.sessionStartTime = 0;
47
+ // Foreground (paid-time) clock
48
+ this.foregroundAccumulatedMs = 0;
49
+ this.foregroundClockStartMs = null;
50
+ this.storage = storage;
51
+ }
52
+ /**
53
+ * Start a new testing session.
54
+ *
55
+ * Creates a new session with a unique ID and stores it in the database.
56
+ * If there's an active session, it will be ended before starting the new one.
57
+ *
58
+ * @returns Promise resolving to the new session ID
59
+ */
60
+ async startSession() {
61
+ if (this.hasActiveSession()) {
62
+ await this.endSession();
63
+ }
64
+ const sessionId = (0, import_uuid.v4)();
65
+ this.currentSessionId = sessionId;
66
+ this.sessionStartTime = Date.now();
67
+ this.foregroundAccumulatedMs = 0;
68
+ this.foregroundClockStartMs = Date.now();
69
+ await this.storage.insert(import_core.COLLECTIONS.sessions, {
70
+ id: sessionId,
71
+ started_at: this.sessionStartTime,
72
+ screen_view_count: 0,
73
+ tap_count: 0,
74
+ ended_at: null,
75
+ end_reason: null,
76
+ duration_seconds: null,
77
+ foreground_seconds: null
78
+ });
79
+ return sessionId;
80
+ }
81
+ /**
82
+ * End the current testing session.
83
+ *
84
+ * Calculates session duration and updates the database.
85
+ * After ending, no session will be active.
86
+ *
87
+ * @param endReason - Reason for ending the session (default: 'completed')
88
+ */
89
+ async endSession(endReason = "completed") {
90
+ if (!this.currentSessionId) return;
91
+ this.pauseForegroundClock();
92
+ const endTime = Date.now();
93
+ const duration = Math.floor((endTime - this.sessionStartTime) / 1e3);
94
+ const foregroundSeconds = this.getForegroundSeconds();
95
+ await this.storage.update(
96
+ import_core.COLLECTIONS.sessions,
97
+ { id: this.currentSessionId },
98
+ {
99
+ ended_at: endTime,
100
+ duration_seconds: duration,
101
+ end_reason: endReason,
102
+ foreground_seconds: foregroundSeconds
103
+ }
104
+ );
105
+ this.currentSessionId = null;
106
+ this.sessionStartTime = 0;
107
+ this.foregroundAccumulatedMs = 0;
108
+ this.foregroundClockStartMs = null;
109
+ }
110
+ /**
111
+ * Pause the foreground (paid-time) clock.
112
+ * Call when the app moves to background. Has no effect if already paused.
113
+ */
114
+ pauseForegroundClock() {
115
+ if (this.foregroundClockStartMs !== null) {
116
+ this.foregroundAccumulatedMs += Date.now() - this.foregroundClockStartMs;
117
+ this.foregroundClockStartMs = null;
118
+ }
119
+ }
120
+ /**
121
+ * Resume the foreground (paid-time) clock.
122
+ * Call when the app returns to foreground. Has no effect if already running.
123
+ */
124
+ resumeForegroundClock() {
125
+ if (this.foregroundClockStartMs === null) {
126
+ this.foregroundClockStartMs = Date.now();
127
+ }
128
+ }
129
+ /**
130
+ * Get the accumulated foreground seconds for the current session.
131
+ *
132
+ * @returns Foreground time in whole seconds
133
+ */
134
+ getForegroundSeconds() {
135
+ let totalMs = this.foregroundAccumulatedMs;
136
+ if (this.foregroundClockStartMs !== null) {
137
+ totalMs += Date.now() - this.foregroundClockStartMs;
138
+ }
139
+ return Math.floor(totalMs / 1e3);
140
+ }
141
+ /**
142
+ * Get the current session ID.
143
+ *
144
+ * @returns Current session ID or null if no session is active
145
+ */
146
+ getCurrentSessionId() {
147
+ return this.currentSessionId;
148
+ }
149
+ /**
150
+ * Check if there's an active session.
151
+ *
152
+ * @returns true if a session is currently active
153
+ */
154
+ hasActiveSession() {
155
+ return this.currentSessionId !== null;
156
+ }
157
+ /**
158
+ * Get the current session duration in seconds.
159
+ *
160
+ * @returns Duration in seconds, or 0 if no session is active
161
+ */
162
+ getSessionDuration() {
163
+ if (!this.hasActiveSession()) return 0;
164
+ return Math.floor((Date.now() - this.sessionStartTime) / 1e3);
165
+ }
166
+ /**
167
+ * Get the epoch-ms timestamp when the current session started.
168
+ *
169
+ * @returns Epoch ms, or null when no session is active
170
+ */
171
+ getCurrentSessionStartedAt() {
172
+ if (!this.hasActiveSession()) return null;
173
+ return this.sessionStartTime;
174
+ }
175
+ /**
176
+ * Increment the screen view count for the current session.
177
+ * Internal method used by EventTracker.
178
+ */
179
+ async incrementScreenViews() {
180
+ if (!this.currentSessionId) return;
181
+ const row = await this.storage.findOne(
182
+ import_core.COLLECTIONS.sessions,
183
+ { id: this.currentSessionId }
184
+ );
185
+ if (!row) return;
186
+ await this.storage.update(
187
+ import_core.COLLECTIONS.sessions,
188
+ { id: this.currentSessionId },
189
+ { screen_view_count: (row.screen_view_count ?? 0) + 1 }
190
+ );
191
+ }
192
+ /**
193
+ * Increment the tap count for the current session.
194
+ * Internal method used by EventTracker.
195
+ */
196
+ async incrementTaps() {
197
+ if (!this.currentSessionId) return;
198
+ const row = await this.storage.findOne(
199
+ import_core.COLLECTIONS.sessions,
200
+ { id: this.currentSessionId }
201
+ );
202
+ if (!row) return;
203
+ await this.storage.update(
204
+ import_core.COLLECTIONS.sessions,
205
+ { id: this.currentSessionId },
206
+ { tap_count: (row.tap_count ?? 0) + 1 }
207
+ );
208
+ }
209
+ };
210
+
211
+ // src/EventTracker.ts
212
+ var import_core2 = require("@testerpaykit/core");
213
+ var import_uuid2 = require("uuid");
214
+ var EventTracker = class {
215
+ constructor(storage, captureFlags) {
216
+ this.sessionId = null;
217
+ this.storage = storage;
218
+ this.captureFlags = {
219
+ captureScreenViews: true,
220
+ captureTapEvents: true,
221
+ captureErrors: true,
222
+ captureCrashes: true,
223
+ ...captureFlags
224
+ };
225
+ }
226
+ /**
227
+ * Set the current session ID.
228
+ * Must be called before tracking events.
229
+ *
230
+ * @param sessionId - The active session ID
231
+ */
232
+ setSessionId(sessionId) {
233
+ this.sessionId = sessionId;
234
+ }
235
+ /**
236
+ * Track a screen view event.
237
+ * Gated by captureScreenViews flag.
238
+ *
239
+ * @param screenName - Name or route of the screen being viewed
240
+ * @param metadata - Optional additional metadata
241
+ */
242
+ async trackScreenView(screenName, metadata) {
243
+ if (!this.captureFlags.captureScreenViews) return;
244
+ await this.trackEvent("screen_view", {
245
+ screenName,
246
+ ...metadata
247
+ });
248
+ }
249
+ /**
250
+ * Track a tap/click event.
251
+ * Gated by captureTapEvents flag.
252
+ *
253
+ * @param screenName - Name of the screen where the tap occurred
254
+ * @param elementId - Optional ID of the tapped element
255
+ */
256
+ async trackTap(screenName, elementId) {
257
+ if (!this.captureFlags.captureTapEvents) return;
258
+ await this.trackEvent("tap", {
259
+ screenName,
260
+ elementId
261
+ });
262
+ }
263
+ /**
264
+ * Track a custom event.
265
+ *
266
+ * @param eventType - Type of the event
267
+ * @param metadata - Optional event metadata
268
+ */
269
+ async trackEvent(eventType, metadata) {
270
+ if (!this.sessionId) {
271
+ console.warn("No active session. Event not tracked:", eventType);
272
+ return;
273
+ }
274
+ await this.storage.insert(import_core2.COLLECTIONS.events, {
275
+ id: (0, import_uuid2.v4)(),
276
+ session_id: this.sessionId,
277
+ timestamp: Date.now(),
278
+ event_type: eventType,
279
+ screen_name: metadata?.screenName ?? null,
280
+ element_id: metadata?.elementId ?? null,
281
+ metadata: metadata ? JSON.stringify(metadata) : null
282
+ });
283
+ }
284
+ /**
285
+ * Track an error event.
286
+ * Gated by captureErrors flag.
287
+ *
288
+ * @param message - Error message
289
+ * @param stack - Optional stack trace
290
+ */
291
+ async trackError(message, stack) {
292
+ if (!this.captureFlags.captureErrors) return;
293
+ await this.storeBugReport("error", message, stack);
294
+ }
295
+ /**
296
+ * Track a crash event.
297
+ * Gated by captureCrashes flag.
298
+ *
299
+ * @param message - Crash message
300
+ * @param stack - Stack trace
301
+ */
302
+ async trackCrash(message, stack) {
303
+ if (!this.captureFlags.captureCrashes) return;
304
+ await this.storeBugReport("crash", message, stack);
305
+ }
306
+ /**
307
+ * Track a feedback submission.
308
+ *
309
+ * @param content - Feedback content
310
+ * @param rating - Optional numeric rating
311
+ */
312
+ async trackFeedback(content, rating) {
313
+ if (!this.sessionId) {
314
+ console.warn("No active session. Feedback not tracked.");
315
+ return;
316
+ }
317
+ const feedbackId = (0, import_uuid2.v4)();
318
+ await this.storage.insert(import_core2.COLLECTIONS.feedbacks, {
319
+ id: feedbackId,
320
+ session_id: this.sessionId,
321
+ content,
322
+ rating: rating ?? null,
323
+ created_at: Date.now()
324
+ });
325
+ await this.trackEvent("feedback_submit", {
326
+ feedbackId,
327
+ length: content.length,
328
+ hasRating: rating !== void 0
329
+ });
330
+ }
331
+ /**
332
+ * Track task start event.
333
+ *
334
+ * @param taskId - Unique task identifier
335
+ * @param title - Task title
336
+ */
337
+ async trackTaskStart(taskId, title) {
338
+ if (!this.sessionId) {
339
+ console.warn("No active session. Task start not tracked.");
340
+ return;
341
+ }
342
+ const now = Date.now();
343
+ const existing = await this.storage.findOne(
344
+ import_core2.COLLECTIONS.tasks,
345
+ { id: taskId }
346
+ );
347
+ if (existing) {
348
+ await this.storage.update(import_core2.COLLECTIONS.tasks, { id: taskId }, { started_at: now });
349
+ } else {
350
+ await this.storage.insert(import_core2.COLLECTIONS.tasks, {
351
+ id: taskId,
352
+ task_preset_id: taskId,
353
+ title,
354
+ started_at: now,
355
+ created_at: now,
356
+ is_completed: 0,
357
+ completed_at: null
358
+ });
359
+ }
360
+ await this.trackEvent("task_start", { taskId, title });
361
+ }
362
+ /**
363
+ * Track task completion event.
364
+ *
365
+ * @param taskId - Unique task identifier
366
+ */
367
+ async trackTaskComplete(taskId) {
368
+ if (!this.sessionId) {
369
+ console.warn("No active session. Task completion not tracked.");
370
+ return;
371
+ }
372
+ await this.storage.update(
373
+ import_core2.COLLECTIONS.tasks,
374
+ { id: taskId },
375
+ { completed_at: Date.now(), is_completed: 1 }
376
+ );
377
+ await this.trackEvent("task_complete", { taskId });
378
+ }
379
+ /**
380
+ * Store a bug report (error or crash).
381
+ *
382
+ * @param severity - Severity level ('error' or 'crash')
383
+ * @param message - Error/crash message
384
+ * @param stack - Optional stack trace
385
+ */
386
+ async storeBugReport(severity, message, stack) {
387
+ if (!this.sessionId) {
388
+ console.warn(`No active session. ${severity} not tracked.`);
389
+ return;
390
+ }
391
+ await this.storage.insert(import_core2.COLLECTIONS.bugReports, {
392
+ id: (0, import_uuid2.v4)(),
393
+ session_id: this.sessionId,
394
+ timestamp: Date.now(),
395
+ message,
396
+ stack: stack ?? null,
397
+ severity
398
+ });
399
+ }
400
+ /**
401
+ * Get event counts for a time period.
402
+ * Internal method for metrics aggregation.
403
+ *
404
+ * @param start - Start timestamp
405
+ * @param end - End timestamp
406
+ * @returns Map of event types to counts
407
+ */
408
+ async getEventCounts(start, end) {
409
+ const events = await this.storage.find(
410
+ import_core2.COLLECTIONS.events
411
+ );
412
+ const counts = {};
413
+ for (const event of events) {
414
+ if (event.timestamp >= start && event.timestamp <= end) {
415
+ counts[event.event_type] = (counts[event.event_type] ?? 0) + 1;
416
+ }
417
+ }
418
+ return counts;
419
+ }
420
+ /**
421
+ * Get unique screen names for a time period.
422
+ * Internal method for metrics aggregation.
423
+ *
424
+ * @param start - Start timestamp
425
+ * @param end - End timestamp
426
+ * @returns Array of unique screen names
427
+ */
428
+ async getUniqueScreens(start, end) {
429
+ const events = await this.storage.find(import_core2.COLLECTIONS.events);
430
+ const seen = /* @__PURE__ */ new Set();
431
+ for (const event of events) {
432
+ if (event.event_type === "screen_view" && event.screen_name !== null && event.screen_name !== void 0 && event.timestamp >= start && event.timestamp <= end) {
433
+ seen.add(event.screen_name);
434
+ }
435
+ }
436
+ return Array.from(seen);
437
+ }
438
+ };
439
+
440
+ // src/MetricsAggregator.ts
441
+ var import_core3 = require("@testerpaykit/core");
442
+ var import_uuid3 = require("uuid");
443
+ var ValidationConstants = {
444
+ minActiveMinutes: 10,
445
+ minUniqueScreens: 5,
446
+ maxTapsPerMinute: 100,
447
+ minSessions: 1
448
+ };
449
+ var MetricsAggregator = class {
450
+ constructor(storage, config) {
451
+ this.storage = storage;
452
+ this.config = config;
453
+ }
454
+ /**
455
+ * Aggregate a weekly summary for the past 7 days.
456
+ *
457
+ * @returns Promise resolving to the generated WeeklySummary
458
+ */
459
+ async aggregateWeeklySummary() {
460
+ const now = Date.now();
461
+ const weekAgo = now - 7 * 24 * 60 * 60 * 1e3;
462
+ return this.aggregateSummaryForPeriod(weekAgo, now);
463
+ }
464
+ /**
465
+ * Aggregate a summary for a specific time period.
466
+ *
467
+ * @param startTime - Start timestamp (milliseconds)
468
+ * @param endTime - End timestamp (milliseconds)
469
+ * @returns Promise resolving to the generated WeeklySummary
470
+ */
471
+ async aggregateSummaryForPeriod(startTime, endTime) {
472
+ const sessions = await this.getSessions(startTime, endTime);
473
+ const uniqueScreens = await this.getUniqueScreens(startTime, endTime);
474
+ const feedbackStats = await this.getFeedbackStats(startTime, endTime);
475
+ const taskStats = await this.getTaskStats(startTime, endTime);
476
+ const bugReportStats = await this.getBugReportStats(startTime, endTime);
477
+ const totalSessions = sessions.length;
478
+ const totalDuration = sessions.reduce((sum, s) => sum + (s.duration_seconds || 0), 0);
479
+ const activeMinutes = Math.floor(totalDuration / 60);
480
+ const totalScreenViews = sessions.reduce((sum, s) => sum + s.screen_view_count, 0);
481
+ const totalTaps = sessions.reduce((sum, s) => sum + s.tap_count, 0);
482
+ const avgTapsPerMinute = activeMinutes > 0 ? totalTaps / activeMinutes : 0;
483
+ const sessionMetrics = {
484
+ totalSessions,
485
+ activeMinutes,
486
+ uniqueScreens: uniqueScreens.length,
487
+ totalScreenViews,
488
+ avgTapsPerMinute,
489
+ tasksStarted: taskStats.started,
490
+ tasksCompleted: taskStats.completed,
491
+ crashes: bugReportStats.crashes,
492
+ errors: bugReportStats.errors,
493
+ feedbackCount: feedbackStats.count,
494
+ avgFeedbackLength: feedbackStats.avgLength,
495
+ qualityFlags: this.calculateQualityFlags(
496
+ totalSessions,
497
+ activeMinutes,
498
+ uniqueScreens.length,
499
+ avgTapsPerMinute
500
+ )
501
+ };
502
+ const integrityHash = this.generateIntegrityHash(sessionMetrics);
503
+ const summary = {
504
+ id: (0, import_uuid3.v4)(),
505
+ projectId: this.config.projectId,
506
+ testerId: this.config.testerId,
507
+ deviceId: this.config.deviceId,
508
+ periodStart: new Date(startTime).toISOString(),
509
+ periodEnd: new Date(endTime).toISOString(),
510
+ metrics: sessionMetrics,
511
+ integrityHash,
512
+ deviceMetadata: this.config.deviceMetadata,
513
+ appMetadata: this.config.appMetadata,
514
+ status: "pending",
515
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
516
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
517
+ estimatedPayout: this.calculateEstimatedPayout(sessionMetrics)
518
+ };
519
+ return summary;
520
+ }
521
+ /**
522
+ * Store a weekly summary in the local database.
523
+ *
524
+ * @param summary - The summary to store
525
+ */
526
+ async storeSummary(summary) {
527
+ await this.storage.insert(import_core3.COLLECTIONS.weeklySummaries, {
528
+ id: summary.id,
529
+ data: JSON.stringify(summary),
530
+ status: summary.status,
531
+ created_at: Date.now()
532
+ });
533
+ }
534
+ /**
535
+ * Get pending summaries from the local database.
536
+ *
537
+ * @returns Array of pending WeeklySummary objects
538
+ */
539
+ async getPendingSummaries() {
540
+ const results = await this.storage.find(
541
+ import_core3.COLLECTIONS.weeklySummaries,
542
+ { status: "pending" }
543
+ );
544
+ return results.map((r) => JSON.parse(r.data));
545
+ }
546
+ /**
547
+ * Update summary status.
548
+ *
549
+ * @param summaryId - ID of the summary
550
+ * @param status - New status
551
+ */
552
+ async updateSummaryStatus(summaryId, status) {
553
+ await this.storage.update(
554
+ import_core3.COLLECTIONS.weeklySummaries,
555
+ { id: summaryId },
556
+ { status }
557
+ );
558
+ }
559
+ // Private helper methods
560
+ async getSessions(start, end) {
561
+ const all = await this.storage.find(import_core3.COLLECTIONS.sessions);
562
+ return all.filter((s) => s.started_at >= start && s.started_at <= end);
563
+ }
564
+ async getEventCounts(start, end) {
565
+ const all = await this.storage.find(
566
+ import_core3.COLLECTIONS.events
567
+ );
568
+ const counts = {};
569
+ for (const event of all) {
570
+ if (event.timestamp >= start && event.timestamp <= end) {
571
+ counts[event.event_type] = (counts[event.event_type] ?? 0) + 1;
572
+ }
573
+ }
574
+ return counts;
575
+ }
576
+ async getUniqueScreens(start, end) {
577
+ const all = await this.storage.find(import_core3.COLLECTIONS.events);
578
+ const seen = /* @__PURE__ */ new Set();
579
+ for (const event of all) {
580
+ if (event.event_type === "screen_view" && event.screen_name !== null && event.screen_name !== void 0 && event.timestamp >= start && event.timestamp <= end) {
581
+ seen.add(event.screen_name);
582
+ }
583
+ }
584
+ return Array.from(seen);
585
+ }
586
+ async getFeedbackStats(start, end) {
587
+ const all = await this.storage.find(import_core3.COLLECTIONS.feedbacks);
588
+ const feedbacks = all.filter((f) => f.created_at >= start && f.created_at <= end);
589
+ if (feedbacks.length === 0) {
590
+ return { count: 0, avgLength: 0 };
591
+ }
592
+ const totalLength = feedbacks.reduce((sum, f) => sum + f.content.length, 0);
593
+ return {
594
+ count: feedbacks.length,
595
+ avgLength: Math.round(totalLength / feedbacks.length)
596
+ };
597
+ }
598
+ async getTaskStats(start, end) {
599
+ const all = await this.storage.find(import_core3.COLLECTIONS.tasks);
600
+ const tasks = all.filter((t) => t.created_at >= start && t.created_at <= end);
601
+ const started = tasks.filter((t) => t.started_at !== null).length;
602
+ const completed = tasks.filter((t) => t.is_completed === 1).length;
603
+ return { started, completed };
604
+ }
605
+ async getBugReportStats(start, end) {
606
+ const all = await this.storage.find(import_core3.COLLECTIONS.bugReports);
607
+ const bugReports = all.filter((b) => b.timestamp >= start && b.timestamp <= end);
608
+ const errors = bugReports.filter((b) => b.severity === "error").length;
609
+ const crashes = bugReports.filter((b) => b.severity === "crash").length;
610
+ return { errors, crashes };
611
+ }
612
+ calculateQualityFlags(totalSessions, activeMinutes, uniqueScreens, avgTapsPerMinute) {
613
+ return {
614
+ minDwellOk: activeMinutes >= ValidationConstants.minActiveMinutes,
615
+ routeDepthOk: uniqueScreens >= ValidationConstants.minUniqueScreens,
616
+ tapSpam: avgTapsPerMinute > ValidationConstants.maxTapsPerMinute,
617
+ sufficientCoverage: totalSessions >= ValidationConstants.minSessions && uniqueScreens >= ValidationConstants.minUniqueScreens
618
+ };
619
+ }
620
+ generateIntegrityHash(metrics) {
621
+ const data = JSON.stringify(metrics);
622
+ let hash = 0;
623
+ for (let i = 0; i < data.length; i++) {
624
+ const char = data.charCodeAt(i);
625
+ hash = (hash << 5) - hash + char;
626
+ hash = hash & hash;
627
+ }
628
+ return Math.abs(hash).toString(16).padStart(64, "0");
629
+ }
630
+ calculateEstimatedPayout(metrics) {
631
+ const baseRate = 0.1;
632
+ let payout = metrics.activeMinutes * baseRate;
633
+ if (metrics.qualityFlags.minDwellOk) payout *= 1.1;
634
+ if (metrics.qualityFlags.routeDepthOk) payout *= 1.1;
635
+ if (metrics.qualityFlags.sufficientCoverage) payout *= 1.2;
636
+ if (metrics.qualityFlags.tapSpam) payout *= 0.8;
637
+ if (metrics.feedbackCount > 0) payout += metrics.feedbackCount * 0.5;
638
+ if (metrics.tasksCompleted > 0) payout += metrics.tasksCompleted * 1;
639
+ return Math.round(payout * 100) / 100;
640
+ }
641
+ };
642
+
643
+ // src/Outbox.ts
644
+ var import_core4 = require("@testerpaykit/core");
645
+ var import_uuid4 = require("uuid");
646
+ var MAX_ATTEMPTS = 7;
647
+ var Outbox = class {
648
+ constructor(storage, apiClient) {
649
+ this.draining = false;
650
+ this.storage = storage;
651
+ this.apiClient = apiClient;
652
+ }
653
+ // -------------------------------------------------------------------------
654
+ // Schema — no-op: schema is the adapter's responsibility
655
+ // -------------------------------------------------------------------------
656
+ async initSchema() {
657
+ }
658
+ // -------------------------------------------------------------------------
659
+ // Crash recovery — reset in_flight rows left over from a killed process
660
+ // -------------------------------------------------------------------------
661
+ async recoverInFlight() {
662
+ await this.storage.update(
663
+ import_core4.COLLECTIONS.outbox,
664
+ { state: "in_flight" },
665
+ { state: "pending" }
666
+ );
667
+ }
668
+ // -------------------------------------------------------------------------
669
+ // Enqueue helpers
670
+ // -------------------------------------------------------------------------
671
+ /** Enqueue a bug_report item; returns the local UUID immediately. */
672
+ enqueueSync(type, payload) {
673
+ const localId = (0, import_uuid4.v4)();
674
+ this._insertRow(localId, type, payload).catch(() => {
675
+ });
676
+ return localId;
677
+ }
678
+ /** Enqueue and wait for the DB insert to complete (for async callers). */
679
+ async enqueue(type, payload) {
680
+ const localId = (0, import_uuid4.v4)();
681
+ await this._insertRow(localId, type, payload);
682
+ return localId;
683
+ }
684
+ async _insertRow(localId, type, payload) {
685
+ await this.storage.insert(import_core4.COLLECTIONS.outbox, {
686
+ local_id: localId,
687
+ type,
688
+ payload: JSON.stringify(payload),
689
+ state: "pending",
690
+ attempts: 0,
691
+ last_error: null,
692
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
693
+ });
694
+ }
695
+ // -------------------------------------------------------------------------
696
+ // Status query
697
+ // -------------------------------------------------------------------------
698
+ /**
699
+ * Map DB state → OutboxItemStatus.
700
+ * Returns null when the item is not found (means it was sent and deleted).
701
+ */
702
+ async getStatus(localId) {
703
+ const row = await this.storage.findOne(
704
+ import_core4.COLLECTIONS.outbox,
705
+ { local_id: localId }
706
+ );
707
+ if (!row) return null;
708
+ const state = row.state;
709
+ if (state === "pending") return "pending";
710
+ if (state === "in_flight") return "uploading";
711
+ if (state === "failed_permanent") return "failed";
712
+ return null;
713
+ }
714
+ // -------------------------------------------------------------------------
715
+ // Drainer — process pending items one by one
716
+ // -------------------------------------------------------------------------
717
+ /**
718
+ * Schedule a drain on the next microtask. Fire-and-forget.
719
+ * Callers (submitBugReport / createSubmission) call this after enqueue.
720
+ */
721
+ scheduleDrain() {
722
+ Promise.resolve().then(() => this.drain()).catch(() => {
723
+ });
724
+ }
725
+ /**
726
+ * Process all pending outbox items. Idempotent — safe to call concurrently
727
+ * (guarded by draining flag). No-ops when apiClient is absent.
728
+ */
729
+ async drain() {
730
+ if (this.draining) return;
731
+ if (!this.apiClient) return;
732
+ this.draining = true;
733
+ try {
734
+ await this._drainLoop();
735
+ } finally {
736
+ this.draining = false;
737
+ }
738
+ }
739
+ async _drainLoop() {
740
+ const rows = await this.storage.find(
741
+ import_core4.COLLECTIONS.outbox,
742
+ { state: "pending" }
743
+ );
744
+ if (rows.length === 0) return;
745
+ let serverIds;
746
+ const hasSubmissions = rows.some((r) => r.type === "submission");
747
+ if (hasSubmissions && this.apiClient?.fetchServerSubmissionIds) {
748
+ serverIds = await this.apiClient.fetchServerSubmissionIds();
749
+ }
750
+ for (const row of rows) {
751
+ await this._processRow(row, serverIds);
752
+ }
753
+ }
754
+ async _processRow(row, serverIds) {
755
+ await this.storage.update(
756
+ import_core4.COLLECTIONS.outbox,
757
+ { local_id: row.local_id },
758
+ { state: "in_flight" }
759
+ );
760
+ try {
761
+ const payload = JSON.parse(row.payload);
762
+ if (row.type === "bug_report") {
763
+ await this._uploadBugReport(row.local_id, payload);
764
+ } else if (row.type === "submission") {
765
+ await this._uploadSubmission(row.local_id, payload, serverIds);
766
+ }
767
+ await this.storage.delete(
768
+ import_core4.COLLECTIONS.outbox,
769
+ { local_id: row.local_id }
770
+ );
771
+ } catch (err) {
772
+ const statusCode = this._extractStatusCode(err);
773
+ if (statusCode !== null && statusCode >= 400 && statusCode < 500) {
774
+ await this.storage.update(
775
+ import_core4.COLLECTIONS.outbox,
776
+ { local_id: row.local_id },
777
+ {
778
+ state: "failed_permanent",
779
+ attempts: (row.attempts ?? 0) + 1,
780
+ last_error: String(err)
781
+ }
782
+ );
783
+ } else {
784
+ const nextAttempts = (row.attempts ?? 0) + 1;
785
+ await this.storage.update(
786
+ import_core4.COLLECTIONS.outbox,
787
+ { local_id: row.local_id },
788
+ {
789
+ state: nextAttempts >= MAX_ATTEMPTS ? "failed_permanent" : "pending",
790
+ attempts: nextAttempts,
791
+ last_error: String(err)
792
+ }
793
+ );
794
+ }
795
+ }
796
+ }
797
+ async _uploadBugReport(localId, payload) {
798
+ if (!this.apiClient?.submitBugReport) {
799
+ throw new Error("submitBugReport not available on apiClient");
800
+ }
801
+ await this.apiClient.submitBugReport(payload, { idempotencyKey: localId });
802
+ }
803
+ async _uploadSubmission(localId, payload, serverIds) {
804
+ if (serverIds?.has(localId)) return;
805
+ await this.apiClient.submitSummary(payload);
806
+ }
807
+ // -------------------------------------------------------------------------
808
+ // Connectivity hook (browser only)
809
+ // -------------------------------------------------------------------------
810
+ /** Register a window.online listener that triggers a drain. */
811
+ registerOnlineListener() {
812
+ if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
813
+ window.addEventListener("online", () => {
814
+ this.drain().catch(() => {
815
+ });
816
+ });
817
+ }
818
+ }
819
+ // -------------------------------------------------------------------------
820
+ // Helpers
821
+ // -------------------------------------------------------------------------
822
+ _extractStatusCode(err) {
823
+ if (err && typeof err === "object") {
824
+ const axiosErr = err;
825
+ if (axiosErr.response?.status != null) return axiosErr.response.status;
826
+ const genericErr = err;
827
+ if (genericErr.statusCode != null) return genericErr.statusCode;
828
+ }
829
+ return null;
830
+ }
831
+ };
832
+
833
+ // src/DeviceIdManager.ts
834
+ var import_core5 = require("@testerpaykit/core");
835
+ var import_uuid5 = require("uuid");
836
+ var DEVICE_ID_KEY = "device_id";
837
+ var DEVICE_ID_CREATED_AT_KEY = "device_id_created_at";
838
+ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
839
+ var DeviceIdManager = class {
840
+ constructor(storage) {
841
+ this.storage = storage;
842
+ }
843
+ /**
844
+ * Ensure the sdk_meta table exists. Schema is the adapter's responsibility;
845
+ * this is now a no-op kept for backwards-compatible call-sites.
846
+ */
847
+ async initSchema() {
848
+ }
849
+ /**
850
+ * Return the stored device id, creating or rotating it as needed.
851
+ *
852
+ * Rotation policy: if the id is older than 30 days, a new one is generated.
853
+ */
854
+ async getOrCreate() {
855
+ const rows = await this.storage.find(
856
+ import_core5.COLLECTIONS.sdkMeta,
857
+ { key: { in: [DEVICE_ID_KEY, DEVICE_ID_CREATED_AT_KEY] } }
858
+ );
859
+ const byKey = {};
860
+ for (const r of rows) {
861
+ byKey[r.key] = r.value;
862
+ }
863
+ const existingId = byKey[DEVICE_ID_KEY];
864
+ const createdAt = byKey[DEVICE_ID_CREATED_AT_KEY] ? parseInt(byKey[DEVICE_ID_CREATED_AT_KEY], 10) : null;
865
+ const now = Date.now();
866
+ const expired = createdAt === null || now - createdAt > THIRTY_DAYS_MS;
867
+ if (existingId && !expired) {
868
+ return existingId;
869
+ }
870
+ const newId = (0, import_uuid5.v4)();
871
+ await this._upsert(DEVICE_ID_KEY, newId);
872
+ await this._upsert(DEVICE_ID_CREATED_AT_KEY, String(now));
873
+ return newId;
874
+ }
875
+ async _upsert(key, value) {
876
+ const existing = await this.storage.findOne(
877
+ import_core5.COLLECTIONS.sdkMeta,
878
+ { key }
879
+ );
880
+ if (existing) {
881
+ await this.storage.update(import_core5.COLLECTIONS.sdkMeta, { key }, { value });
882
+ } else {
883
+ await this.storage.insert(import_core5.COLLECTIONS.sdkMeta, { key, value });
884
+ }
885
+ }
886
+ };
887
+
888
+ // src/TesterPayKit.ts
889
+ var import_uuid6 = require("uuid");
890
+ var LOCAL_PATTERNS = [
891
+ "localhost",
892
+ /^127\./,
893
+ /^10\./,
894
+ /^192\.168\./,
895
+ /^172\.(1[6-9]|2\d|3[01])\./,
896
+ /\.local$/,
897
+ /\.lan$/
898
+ ];
899
+ function deriveEnvironment(baseUrl) {
900
+ let host;
901
+ try {
902
+ host = new URL(baseUrl).hostname.toLowerCase();
903
+ } catch {
904
+ return "prod";
905
+ }
906
+ for (const p of LOCAL_PATTERNS) {
907
+ if (typeof p === "string" ? host === p : p.test(host)) {
908
+ return "local";
909
+ }
910
+ }
911
+ return "prod";
912
+ }
913
+ var LAST_SUBMISSION_AT_KEY = "last_submission_at";
914
+ var SUBMISSION_PERIOD_MS = 7 * 24 * 60 * 60 * 1e3;
915
+ var _TesterPayKit = class _TesterPayKit {
916
+ constructor(config) {
917
+ this.initialized = false;
918
+ // ── Resolved tester id (after anonymous login) ──────────────────────────────
919
+ // Populated by init() after a successful loginAnonymous. The server returns the
920
+ // real UUID for the tester row; submissions must use this, NOT the invite code.
921
+ this._resolvedTesterId = null;
922
+ // ── Auth token ──────────────────────────────────────────────────────────────
923
+ this._authToken = null;
924
+ // ── Server-side session sync ────────────────────────────────────────────────
925
+ // The local SessionManager only persists sessions in storage. To make a
926
+ // session appear in the coordinator dashboard we also create a SERVER session
927
+ // (once authed) and mirror screen-view events to it. Best-effort: never blocks
928
+ // or breaks the host app. Events that arrive before the server session exists
929
+ // are buffered, then flushed.
930
+ this._serverSessionId = null;
931
+ this._pendingSessionEvents = [];
932
+ this._logBuffer = [];
933
+ this._serverSessionInFlight = null;
934
+ this.config = {
935
+ autoStartSession: true,
936
+ debugMode: false,
937
+ weeklySubmissionDay: 7,
938
+ earningsBaseAmount: 1,
939
+ earningsPerMinuteRate: 0.1,
940
+ earningsCurrency: "EUR",
941
+ ...config
942
+ };
943
+ this.environment = config.apiBaseUrl ? deriveEnvironment(config.apiBaseUrl) : "prod";
944
+ this._resolvedDeviceId = config.deviceId ?? "";
945
+ this.deviceIdManager = new DeviceIdManager(config.storage);
946
+ this.sessionManager = new SessionManager(config.storage);
947
+ this.eventTracker = new EventTracker(config.storage, {
948
+ captureScreenViews: config.captureScreenViews ?? true,
949
+ captureTapEvents: config.captureTapEvents ?? true,
950
+ captureErrors: config.captureErrors ?? true,
951
+ captureCrashes: config.captureCrashes ?? true
952
+ });
953
+ const aggregatorConfig = {
954
+ projectId: config.projectId,
955
+ testerId: config.testerId,
956
+ deviceId: config.deviceId ?? "",
957
+ deviceMetadata: config.deviceMetadata,
958
+ appMetadata: config.appMetadata
959
+ };
960
+ this.metricsAggregator = new MetricsAggregator(config.storage, aggregatorConfig);
961
+ this.outbox = new Outbox(config.storage, config.apiClient);
962
+ this.anonymousAuthReady = new Promise((resolve) => {
963
+ this._resolveAnonymousAuth = resolve;
964
+ });
965
+ }
966
+ // ── Alias (contract: lifecycle.readiness.onTokenReady) ─────────────────────
967
+ get onTokenReady() {
968
+ return this.anonymousAuthReady;
969
+ }
970
+ // ── Auth state (contract: lifecycle.readiness.isAuthenticated) ─────────────
971
+ get isAuthenticated() {
972
+ return this._authToken !== null;
973
+ }
974
+ /**
975
+ * Initialize the SDK.
976
+ *
977
+ * Must be called before using any other SDK methods.
978
+ * Initializes storage and optionally starts a session.
979
+ */
980
+ async init() {
981
+ if (this.initialized) {
982
+ this.log("SDK already initialized");
983
+ return;
984
+ }
985
+ await this.config.storage.init();
986
+ await this.deviceIdManager.initSchema();
987
+ await this.outbox.initSchema();
988
+ await this.outbox.recoverInFlight();
989
+ if (!this.config.deviceId) {
990
+ this._resolvedDeviceId = await this.deviceIdManager.getOrCreate();
991
+ this.metricsAggregator.config = {
992
+ ...this.metricsAggregator.config,
993
+ deviceId: this._resolvedDeviceId
994
+ };
995
+ }
996
+ this.outbox.registerOnlineListener();
997
+ if (this.config.autoStartSession) {
998
+ const sessionId = await this.sessionManager.startSession();
999
+ this.eventTracker.setSessionId(sessionId);
1000
+ this.log(`Session auto-started: ${sessionId}`);
1001
+ }
1002
+ this.initialized = true;
1003
+ this.log("SDK initialized successfully");
1004
+ const code = this.config.testerId;
1005
+ const apiClient = this.config.apiClient;
1006
+ if (code && apiClient?.loginAnonymous) {
1007
+ void (async () => {
1008
+ try {
1009
+ const res = await apiClient.loginAnonymous(this.config.projectId, code);
1010
+ if (res?.accessToken) {
1011
+ this.setAuthToken(res.accessToken);
1012
+ if (res.testerId) {
1013
+ this._resolvedTesterId = res.testerId;
1014
+ this.metricsAggregator.config = {
1015
+ ...this.metricsAggregator.config,
1016
+ testerId: res.testerId
1017
+ };
1018
+ }
1019
+ this.log("anonymous tester token acquired");
1020
+ void this._ensureServerSession();
1021
+ void this.runDurabilitySweep().catch(() => void 0);
1022
+ }
1023
+ } catch (e) {
1024
+ this.log(`anonymous token acquisition failed: ${String(e)}`);
1025
+ } finally {
1026
+ this._resolveAnonymousAuth();
1027
+ }
1028
+ })();
1029
+ } else {
1030
+ this._resolveAnonymousAuth();
1031
+ }
1032
+ }
1033
+ /**
1034
+ * Provide an auth token to the SDK (e.g. after anonymous login).
1035
+ * Makes isAuthenticated return true and enables runDurabilitySweep.
1036
+ */
1037
+ setAuthToken(token) {
1038
+ this._authToken = token;
1039
+ this.config.apiClient?.setAccessToken(token);
1040
+ }
1041
+ // ── Registered-tester auth (for the tester-launcher widget) ──────────────────
1042
+ /**
1043
+ * Request a passwordless magic-link sign-in for a registered tester.
1044
+ * TesterPayKit tester auth is magic-link (no passwords): the server emails a
1045
+ * single-use link that returns to `returnUrl` (a first-party *.moinsen.dev
1046
+ * page) carrying a token, which the host consumes via consumeTesterMagicLink.
1047
+ * `country` (DE/AT/CH) lets an unknown email self-signup. Returns true if the
1048
+ * request was accepted. Never throws.
1049
+ */
1050
+ async requestTesterMagicLink(email, returnUrl, country) {
1051
+ const api = this.config.apiClient;
1052
+ if (!api?.requestMagicLink) return false;
1053
+ try {
1054
+ await api.requestMagicLink({ email, returnUrl, country });
1055
+ return true;
1056
+ } catch (e) {
1057
+ this.log(`magic-link request failed: ${String(e)}`);
1058
+ return false;
1059
+ }
1060
+ }
1061
+ /**
1062
+ * Consume a magic-link token (from the returnUrl the tester landed on). On
1063
+ * success the real tester token supersedes the anonymous one, the tester is
1064
+ * enrolled in this project, and {accessToken, refreshToken} is returned so
1065
+ * the host can persist the session. Returns null on failure. Never throws.
1066
+ */
1067
+ async consumeTesterMagicLink(token) {
1068
+ const api = this.config.apiClient;
1069
+ if (!api?.consumeMagicLink) return null;
1070
+ try {
1071
+ const res = await api.consumeMagicLink(token);
1072
+ if (res?.accessToken) {
1073
+ this.setAuthToken(res.accessToken);
1074
+ await this.enrollSelf();
1075
+ return {
1076
+ accessToken: res.accessToken,
1077
+ refreshToken: res.refreshToken ?? void 0
1078
+ };
1079
+ }
1080
+ return null;
1081
+ } catch (e) {
1082
+ this.log(`magic-link consume failed: ${String(e)}`);
1083
+ return null;
1084
+ }
1085
+ }
1086
+ /**
1087
+ * Enroll the current tester into THIS project (idempotent, best-effort).
1088
+ * Used right after loginTester so the tester is a project participant.
1089
+ * Returns true if enrolled (or already enrolled), false on hard failure.
1090
+ */
1091
+ async enrollSelf() {
1092
+ const api = this.config.apiClient;
1093
+ if (!api?.enrollInProject) return false;
1094
+ try {
1095
+ await api.enrollInProject(this.config.projectId);
1096
+ return true;
1097
+ } catch (e) {
1098
+ const msg = String(e);
1099
+ if (msg.includes("409") || msg.toLowerCase().includes("already")) {
1100
+ return true;
1101
+ }
1102
+ this.log(`enrollSelf failed: ${msg}`);
1103
+ return false;
1104
+ }
1105
+ }
1106
+ // ── Server-side session sync (best-effort) ───────────────────────────────────
1107
+ /** device_info payload for the server session, from configured metadata. */
1108
+ _sessionDeviceInfo() {
1109
+ const d = this.config.deviceMetadata;
1110
+ return {
1111
+ os: d.os,
1112
+ os_version: d.osVersion,
1113
+ device_model: d.deviceModel,
1114
+ ...d.timezoneOffset != null && { timezone_offset: d.timezoneOffset },
1115
+ // The local device id lives in the FK-free jsonb (not the device_id
1116
+ // column, which references tester_devices) so grouping context is kept
1117
+ // without a registration round-trip.
1118
+ ...this._resolvedDeviceId && { device_id: this._resolvedDeviceId }
1119
+ };
1120
+ }
1121
+ /**
1122
+ * Lazily create the SERVER tester session once an anonymous token is in
1123
+ * hand, then flush any buffered events. This is what makes the session
1124
+ * show up in the coordinator dashboard. Best-effort: never throws.
1125
+ */
1126
+ _ensureServerSession() {
1127
+ if (this._serverSessionId) return Promise.resolve();
1128
+ this._serverSessionInFlight ?? (this._serverSessionInFlight = this._createServerSession().finally(() => {
1129
+ this._serverSessionInFlight = null;
1130
+ }));
1131
+ return this._serverSessionInFlight;
1132
+ }
1133
+ async _createServerSession() {
1134
+ if (!this._authToken) return;
1135
+ const api = this.config.apiClient;
1136
+ if (!api?.startTesterSession) return;
1137
+ try {
1138
+ const res = await api.startTesterSession({
1139
+ projectId: this.config.projectId,
1140
+ deviceInfo: this._sessionDeviceInfo(),
1141
+ appVersion: this.config.appMetadata.version,
1142
+ sdkVersion: this.config.deviceMetadata.sdkVersion
1143
+ // NOTE: deliberately NOT sending device_id. On the server it's an FK
1144
+ // into tester_devices, and the TS SDK has no device-registration flow
1145
+ // yet, so an unregistered local UUID would 500 the session-create.
1146
+ // The deviceId still rides along in deviceInfo for grouping context.
1147
+ });
1148
+ if (res?.sdkUpdate && !isProductionBuild()) {
1149
+ const u = res.sdkUpdate;
1150
+ console.warn(
1151
+ `[testerpaykit] ${u.package} ${u.current} is outdated \u2014 ${u.latest} is out. Update: ${u.command}`
1152
+ );
1153
+ }
1154
+ if (res?.id) {
1155
+ this._serverSessionId = res.id;
1156
+ this.log(`server session created: ${res.id}`);
1157
+ await this._flushServerSessionEvents();
1158
+ }
1159
+ } catch (e) {
1160
+ this.log(`server session create failed: ${String(e)}`);
1161
+ }
1162
+ }
1163
+ /** Flush buffered session events to the server (best-effort, re-queues on fail). */
1164
+ async _flushServerSessionEvents() {
1165
+ const api = this.config.apiClient;
1166
+ if (!this._serverSessionId || !api?.addSessionEvents) return;
1167
+ if (this._pendingSessionEvents.length === 0) return;
1168
+ const batch = this._pendingSessionEvents.splice(0);
1169
+ try {
1170
+ await api.addSessionEvents(this._serverSessionId, batch);
1171
+ } catch (e) {
1172
+ this._pendingSessionEvents.unshift(...batch);
1173
+ this.log(`session events flush failed: ${String(e)}`);
1174
+ }
1175
+ }
1176
+ /** End the server session (best-effort). Clears the id so it won't re-end. */
1177
+ async _endServerSession(endReason) {
1178
+ const api = this.config.apiClient;
1179
+ const id = this._serverSessionId;
1180
+ if (!id || !api?.endTesterSession) return;
1181
+ this._serverSessionId = null;
1182
+ try {
1183
+ await this._flushServerSessionEvents();
1184
+ const allowed = /* @__PURE__ */ new Set([
1185
+ "completed",
1186
+ "lifecycle_flush",
1187
+ "timeout",
1188
+ "abandoned"
1189
+ ]);
1190
+ await api.endTesterSession({
1191
+ sessionId: id,
1192
+ endReason: allowed.has(endReason) ? endReason : "completed"
1193
+ });
1194
+ this.log(`server session ended: ${id}`);
1195
+ } catch (e) {
1196
+ this.log(`server session end failed: ${String(e)}`);
1197
+ }
1198
+ }
1199
+ // ── payout_durability — contract: invariants.payout_durability ──────────────
1200
+ /**
1201
+ * Run a durability sweep to ensure testing work is persisted and uploaded.
1202
+ *
1203
+ * No-op when no auth token is held. Otherwise, best-effort (each step is
1204
+ * individually wrapped so one failure does not abort the rest):
1205
+ *
1206
+ * 1. Reconcile open sessions: find sessions in storage without an end_time
1207
+ * and close them with endReason='abandoned' so their duration counts.
1208
+ * 2. Auto-create a period submission when overdue: tracks the last submission
1209
+ * timestamp in sdk_meta. "Due" = more than 7 days since last enqueue.
1210
+ * (Heuristic — uses wall-clock elapsed time, not calendar periods.)
1211
+ * 3. Drain the outbox. The Outbox drain already skips server-known submission
1212
+ * ids (fetchServerSubmissionIds guard) so no double-pay occurs.
1213
+ *
1214
+ * Contract: api.submissions.runDurabilitySweep
1215
+ */
1216
+ async runDurabilitySweep() {
1217
+ if (!this._authToken) {
1218
+ this.log("runDurabilitySweep: no auth token \u2014 skipping");
1219
+ return;
1220
+ }
1221
+ try {
1222
+ await this._reconcileOpenSessions();
1223
+ } catch (e) {
1224
+ this.log(`runDurabilitySweep step 1 failed: ${e}`);
1225
+ }
1226
+ try {
1227
+ await this._autoCreateSubmissionIfDue();
1228
+ } catch (e) {
1229
+ this.log(`runDurabilitySweep step 2 failed: ${e}`);
1230
+ }
1231
+ try {
1232
+ await this.outbox.drain();
1233
+ } catch (e) {
1234
+ this.log(`runDurabilitySweep step 3 failed: ${e}`);
1235
+ }
1236
+ }
1237
+ async _reconcileOpenSessions() {
1238
+ const currentId = this.sessionManager.getCurrentSessionId() ?? "";
1239
+ await this.config.storage.update(
1240
+ import_core6.COLLECTIONS.sessions,
1241
+ { ended_at: null, id: { ne: currentId } },
1242
+ { ended_at: Date.now(), end_reason: "abandoned" }
1243
+ );
1244
+ this.log("runDurabilitySweep: open sessions reconciled");
1245
+ }
1246
+ async _autoCreateSubmissionIfDue() {
1247
+ const row = await this.config.storage.findOne(
1248
+ import_core6.COLLECTIONS.sdkMeta,
1249
+ { key: LAST_SUBMISSION_AT_KEY }
1250
+ );
1251
+ const lastAt = row ? parseInt(row.value, 10) : null;
1252
+ const now = Date.now();
1253
+ if (lastAt === null) {
1254
+ await this.config.storage.insert(import_core6.COLLECTIONS.sdkMeta, {
1255
+ key: LAST_SUBMISSION_AT_KEY,
1256
+ value: String(now)
1257
+ });
1258
+ this.log("runDurabilitySweep: first run \u2014 period clock started, no submission yet");
1259
+ return;
1260
+ }
1261
+ if (now - lastAt < SUBMISSION_PERIOD_MS) {
1262
+ this.log("runDurabilitySweep: submission not due yet");
1263
+ return;
1264
+ }
1265
+ await this.config.storage.update(
1266
+ import_core6.COLLECTIONS.sdkMeta,
1267
+ { key: LAST_SUBMISSION_AT_KEY },
1268
+ { value: String(now) }
1269
+ );
1270
+ await this.createSubmission();
1271
+ this.log("runDurabilitySweep: auto-created period submission");
1272
+ }
1273
+ /**
1274
+ * Start a new testing session.
1275
+ *
1276
+ * @returns Promise resolving to the new session ID
1277
+ */
1278
+ async startSession() {
1279
+ this.ensureInitialized();
1280
+ const sessionId = await this.sessionManager.startSession();
1281
+ this.eventTracker.setSessionId(sessionId);
1282
+ this.log(`Session started: ${sessionId}`);
1283
+ void this._ensureServerSession();
1284
+ return sessionId;
1285
+ }
1286
+ /**
1287
+ * End the current testing session.
1288
+ *
1289
+ * @param endReason - Reason for ending (default: 'completed')
1290
+ */
1291
+ async endSession(endReason = "completed") {
1292
+ this.ensureInitialized();
1293
+ await this.sessionManager.endSession(endReason);
1294
+ this.log("Session ended");
1295
+ await this._endServerSession(endReason);
1296
+ }
1297
+ // ── App-lifecycle hooks (contract: lifecycle.app_lifecycle_hooks) ─────────
1298
+ /**
1299
+ * Call when the app moves to the foreground / resumes.
1300
+ *
1301
+ * Contract behaviour:
1302
+ * - If NO active session exists → start a new one.
1303
+ * - If a session IS active → resume the foreground clock only.
1304
+ * MUST NOT end and restart the active session.
1305
+ */
1306
+ async onAppResumed() {
1307
+ this.ensureInitialized();
1308
+ if (!this.sessionManager.hasActiveSession()) {
1309
+ const sessionId = await this.sessionManager.startSession();
1310
+ this.eventTracker.setSessionId(sessionId);
1311
+ this.log("onAppResumed: new session started");
1312
+ void this._ensureServerSession();
1313
+ } else {
1314
+ this.sessionManager.resumeForegroundClock();
1315
+ this.log("onAppResumed: foreground clock resumed");
1316
+ }
1317
+ }
1318
+ /**
1319
+ * Call when the app moves to the background / is paused.
1320
+ *
1321
+ * Contract behaviour: freezes the foreground clock.
1322
+ * MUST NOT end the session.
1323
+ */
1324
+ onAppPaused() {
1325
+ this.ensureInitialized();
1326
+ this.sessionManager.pauseForegroundClock();
1327
+ this.log("onAppPaused: foreground clock paused");
1328
+ }
1329
+ /**
1330
+ * Call when the app becomes inactive (e.g. phone call overlay, app-switcher).
1331
+ *
1332
+ * Contract behaviour: no-op for the session (may log only).
1333
+ */
1334
+ onAppInactive() {
1335
+ this.ensureInitialized();
1336
+ this.log("onAppInactive: no-op");
1337
+ }
1338
+ /**
1339
+ * Call when the app process is about to be detached / destroyed.
1340
+ *
1341
+ * Contract behaviour: ends the active session with end_reason='lifecycle_flush'.
1342
+ */
1343
+ async onAppDetached() {
1344
+ this.ensureInitialized();
1345
+ if (this.sessionManager.hasActiveSession()) {
1346
+ await this.sessionManager.endSession("lifecycle_flush");
1347
+ this.log("onAppDetached: session flushed");
1348
+ }
1349
+ await this._endServerSession("lifecycle_flush");
1350
+ }
1351
+ /**
1352
+ * Track a screen view event.
1353
+ *
1354
+ * @param screenName - Name or route of the screen
1355
+ * @param metadata - Optional additional metadata
1356
+ */
1357
+ async trackScreenView(screenName, metadata) {
1358
+ this.ensureInitialized();
1359
+ await this.eventTracker.trackScreenView(screenName, metadata);
1360
+ await this.sessionManager.incrementScreenViews();
1361
+ this.log(`Screen view tracked: ${screenName}`);
1362
+ this._pendingSessionEvents.push({
1363
+ eventType: "screen_view",
1364
+ screenRoute: screenName,
1365
+ ...metadata && { eventData: metadata },
1366
+ timestamp: /* @__PURE__ */ new Date()
1367
+ });
1368
+ if (this._serverSessionId) {
1369
+ void this._flushServerSessionEvents();
1370
+ } else {
1371
+ void this._ensureServerSession();
1372
+ }
1373
+ }
1374
+ /**
1375
+ * Track a tap/click event.
1376
+ *
1377
+ * @param screenName - Name of the screen where the tap occurred
1378
+ * @param elementId - Optional ID of the tapped element
1379
+ */
1380
+ async trackTap(screenName, elementId) {
1381
+ this.ensureInitialized();
1382
+ await this.eventTracker.trackTap(screenName, elementId);
1383
+ await this.sessionManager.incrementTaps();
1384
+ this.log(`Tap tracked: ${screenName}${elementId ? ` (${elementId})` : ""}`);
1385
+ }
1386
+ /**
1387
+ * Track a custom event.
1388
+ *
1389
+ * @param eventType - Type of the event
1390
+ * @param metadata - Optional event metadata
1391
+ */
1392
+ async trackEvent(eventType, metadata) {
1393
+ this.ensureInitialized();
1394
+ await this.eventTracker.trackEvent(eventType, metadata);
1395
+ this.log(`Event tracked: ${eventType}`);
1396
+ }
1397
+ /**
1398
+ * Track an error.
1399
+ *
1400
+ * @param message - Error message
1401
+ * @param stack - Optional stack trace
1402
+ */
1403
+ async trackError(message, stack) {
1404
+ this.ensureInitialized();
1405
+ await this.eventTracker.trackError(message, stack);
1406
+ this.log(`Error tracked: ${message}`);
1407
+ }
1408
+ /**
1409
+ * Track a crash.
1410
+ *
1411
+ * @param message - Crash message
1412
+ * @param stack - Stack trace
1413
+ */
1414
+ async trackCrash(message, stack) {
1415
+ this.ensureInitialized();
1416
+ await this.eventTracker.trackCrash(message, stack);
1417
+ this.log(`Crash tracked: ${message}`);
1418
+ }
1419
+ /**
1420
+ * Track feedback submission.
1421
+ *
1422
+ * @param content - Feedback content
1423
+ * @param rating - Optional numeric rating
1424
+ */
1425
+ async trackFeedback(content, rating) {
1426
+ this.ensureInitialized();
1427
+ await this.eventTracker.trackFeedback(content, rating);
1428
+ this.log(`Feedback tracked: ${content.length} characters`);
1429
+ }
1430
+ /**
1431
+ * Track task start.
1432
+ *
1433
+ * @param taskId - Unique task identifier
1434
+ * @param title - Task title
1435
+ */
1436
+ async trackTaskStart(taskId, title) {
1437
+ this.ensureInitialized();
1438
+ await this.eventTracker.trackTaskStart(taskId, title);
1439
+ this.log(`Task started: ${title}`);
1440
+ }
1441
+ /**
1442
+ * Track task completion.
1443
+ *
1444
+ * @param taskId - Unique task identifier
1445
+ */
1446
+ async trackTaskComplete(taskId) {
1447
+ this.ensureInitialized();
1448
+ await this.eventTracker.trackTaskComplete(taskId);
1449
+ this.log(`Task completed: ${taskId}`);
1450
+ }
1451
+ /**
1452
+ * Enqueue a bug report to the local outbox and return a local UUID
1453
+ * immediately. The upload happens in the background — this method
1454
+ * never awaits the network.
1455
+ *
1456
+ * Builds the full payload required by POST /v1/testers/me/bug-reports:
1457
+ * sessionId, type, severity, category, title, description,
1458
+ * currentScreen, deviceSnapshot, appSnapshot, projectId.
1459
+ * testerId is intentionally omitted — the endpoint is tester-namespaced
1460
+ * and derives the tester from the JWT.
1461
+ *
1462
+ * Contract: api.submissions.submitBugReport / invariants.local_first_outbox
1463
+ *
1464
+ * @param input - Structured bug report input
1465
+ * @returns A local UUID that can be passed to getSubmissionStatus()
1466
+ */
1467
+ submitBugReport(input) {
1468
+ this.ensureInitialized();
1469
+ const sessionId = this.sessionManager.getCurrentSessionId() ?? (0, import_uuid6.v4)();
1470
+ const rawType = input.type ?? "bug";
1471
+ const type = import_core6.BUG_REPORT_TYPES.includes(rawType) ? rawType : (() => {
1472
+ this.log(`[WARN] submitBugReport: invalid type "${rawType}", coercing to "bug"`);
1473
+ return "bug";
1474
+ })();
1475
+ const rawSeverity = input.severity ?? "medium";
1476
+ const severity = import_core6.BUG_REPORT_SEVERITIES.includes(rawSeverity) ? rawSeverity : (() => {
1477
+ this.log(`[WARN] submitBugReport: invalid severity "${rawSeverity}", coercing to "medium"`);
1478
+ return "medium";
1479
+ })();
1480
+ const rawCategory = input.category ?? "functional";
1481
+ const category = import_core6.BUG_REPORT_CATEGORIES.includes(rawCategory) ? rawCategory : (() => {
1482
+ this.log(`[WARN] submitBugReport: invalid category "${rawCategory}", coercing to "functional"`);
1483
+ return "functional";
1484
+ })();
1485
+ const payload = {
1486
+ projectId: this.config.projectId,
1487
+ sessionId,
1488
+ type,
1489
+ severity,
1490
+ category,
1491
+ title: input.title,
1492
+ description: input.description,
1493
+ currentScreen: input.currentScreen ?? "unknown",
1494
+ deviceSnapshot: {
1495
+ os: this.config.deviceMetadata.os,
1496
+ osVersion: this.config.deviceMetadata.osVersion,
1497
+ deviceModel: this.config.deviceMetadata.deviceModel
1498
+ },
1499
+ appSnapshot: {
1500
+ bundleId: this.config.appMetadata.bundleId,
1501
+ version: this.config.appMetadata.version,
1502
+ buildNumber: this.config.appMetadata.buildNumber,
1503
+ environment: this.environment
1504
+ },
1505
+ ...input.metadata
1506
+ };
1507
+ if (input.screenshotPath != null) {
1508
+ payload.screenshotPath = input.screenshotPath;
1509
+ }
1510
+ if (input.expectedBehavior != null) {
1511
+ payload.expectedBehavior = input.expectedBehavior;
1512
+ }
1513
+ if (input.actualBehavior != null) {
1514
+ payload.actualBehavior = input.actualBehavior;
1515
+ }
1516
+ if (input.frequency != null) {
1517
+ payload.frequency = input.frequency;
1518
+ }
1519
+ if (input.reproductionSteps != null) {
1520
+ payload.reproductionSteps = input.reproductionSteps;
1521
+ }
1522
+ if (input.affectedFeature != null) {
1523
+ payload.affectedFeature = input.affectedFeature;
1524
+ }
1525
+ const localId = this.outbox.enqueueSync("bug_report", payload);
1526
+ this.outbox.scheduleDrain();
1527
+ this.log(`Bug report enqueued: ${localId}`);
1528
+ return localId;
1529
+ }
1530
+ /**
1531
+ * Extract structured bug-report fields from a base64-encoded audio recording.
1532
+ *
1533
+ * Delegates to apiClient.voiceExtractBugFields. When `sourceLanguage` is
1534
+ * explicitly provided (ISO-639-1, e.g. 'de'), it is forwarded as-is.
1535
+ * When omitted, the language hint falls back to navigator.language
1536
+ * (best-effort, browser-only). Soft-fails to null when the apiClient does
1537
+ * not implement voiceExtractBugFields or the call throws.
1538
+ *
1539
+ * Contract: wire.bug_reports.voiceExtractBugFields
1540
+ *
1541
+ * @param audioBase64 - Raw base64 audio (no data: prefix)
1542
+ * @param mimeType - MIME type of the audio (e.g. 'audio/webm')
1543
+ * @param sourceLanguage - Optional explicit ISO-639-1 language code; when
1544
+ * omitted the SDK derives it from navigator.language
1545
+ * @returns Extracted fields, or null on any failure
1546
+ */
1547
+ async extractBugFromVoice(audioBase64, mimeType, sourceLanguage) {
1548
+ const apiClient = this.config.apiClient;
1549
+ if (!apiClient?.voiceExtractBugFields) {
1550
+ this.log("extractBugFromVoice: apiClient does not implement voiceExtractBugFields \u2014 skipping");
1551
+ return null;
1552
+ }
1553
+ let resolvedLanguage = sourceLanguage;
1554
+ if (!resolvedLanguage) {
1555
+ try {
1556
+ if (typeof navigator !== "undefined" && navigator.language) {
1557
+ resolvedLanguage = navigator.language.split("-")[0].toLowerCase();
1558
+ }
1559
+ } catch {
1560
+ }
1561
+ }
1562
+ try {
1563
+ const result = await apiClient.voiceExtractBugFields({
1564
+ audioBase64,
1565
+ mimeType,
1566
+ projectId: this.config.projectId,
1567
+ ...resolvedLanguage ? { sourceLanguage: resolvedLanguage } : {}
1568
+ });
1569
+ return result;
1570
+ } catch (e) {
1571
+ this.log(`extractBugFromVoice: failed \u2014 ${String(e)}`);
1572
+ return null;
1573
+ }
1574
+ }
1575
+ /**
1576
+ * One-tap report draft from a screenshot of the current screen — the
1577
+ * quick-action path next to voice. Returns null when the client does
1578
+ * not support it; throws on a server error so the UI can show it.
1579
+ *
1580
+ * Contract: wire.bug_reports.quickDraftBug
1581
+ *
1582
+ * @param screenshotDataUrl - `data:image/...;base64,...` of the screen
1583
+ */
1584
+ async quickDraftBug(action, screenshotDataUrl, options = {}) {
1585
+ const apiClient = this.config.apiClient;
1586
+ if (!apiClient?.quickDraftBug) return null;
1587
+ const match = /^data:([^;]+);base64,(.*)$/.exec(screenshotDataUrl);
1588
+ return apiClient.quickDraftBug({
1589
+ action,
1590
+ screenshotBase64: match ? match[2] : screenshotDataUrl,
1591
+ mimeType: match ? match[1] : "image/png",
1592
+ ...options.screenName ? { screenName: options.screenName } : {},
1593
+ ...options.language ? { language: options.language } : {}
1594
+ });
1595
+ }
1596
+ /**
1597
+ * Upload an arbitrary attachment (screenshot, screen recording, voice note, etc.)
1598
+ * to the standalone attachments endpoint (POST /v1/attachments).
1599
+ *
1600
+ * Returns the stored URL/path on success, null on any failure (best-effort,
1601
+ * never throws).
1602
+ *
1603
+ * Contract: wire.bug_reports.uploadAttachment (standalone path)
1604
+ *
1605
+ * @param input - Attachment data with base64 content, MIME type, file type, and optional file name
1606
+ * @returns The attachment url/path string, or null if upload failed or client unavailable
1607
+ */
1608
+ async uploadAttachment(input) {
1609
+ const apiClient = this.config.apiClient;
1610
+ if (!apiClient?.uploadAttachment) {
1611
+ this.log("uploadAttachment: no api client with uploadAttachment \u2014 skipping");
1612
+ return null;
1613
+ }
1614
+ try {
1615
+ const fileName = input.fileName ?? `${input.fileType}-${Date.now()}.${input.mimeType.split("/")[1]?.split(";")[0] ?? "bin"}`;
1616
+ const fileSize = Math.ceil(input.base64.length * 3 / 4);
1617
+ const response = await apiClient.uploadAttachment({
1618
+ fileName,
1619
+ fileType: input.fileType,
1620
+ fileSize,
1621
+ fileData: input.base64,
1622
+ mimeType: input.mimeType
1623
+ });
1624
+ const path = response.url ?? response.id;
1625
+ this.log(`uploadAttachment: uploaded as ${path}`);
1626
+ return path ?? null;
1627
+ } catch (e) {
1628
+ this.log(`uploadAttachment: failed \u2014 ${String(e)}`);
1629
+ return null;
1630
+ }
1631
+ }
1632
+ /**
1633
+ * Upload a screenshot dataURL to the standalone attachments endpoint.
1634
+ *
1635
+ * Converts the dataURL to a base64 payload and calls
1636
+ * POST /v1/attachments via the api-client. Returns the attachment
1637
+ * url/path on success, null on any failure (best-effort, never throws).
1638
+ *
1639
+ * Contract: wire.bug_reports.uploadAttachment (standalone path)
1640
+ *
1641
+ * @param dataUrl - A JPEG/PNG dataURL (e.g. from html2canvas or captureScreenshot)
1642
+ * @returns The attachment url string, or null if upload failed or client unavailable
1643
+ */
1644
+ async uploadScreenshot(dataUrl) {
1645
+ const apiClient = this.config.apiClient;
1646
+ if (!apiClient?.uploadAttachment) {
1647
+ this.log("uploadScreenshot: no api client with uploadAttachment \u2014 skipping");
1648
+ return null;
1649
+ }
1650
+ try {
1651
+ const commaIdx = dataUrl.indexOf(",");
1652
+ const fileData = commaIdx >= 0 ? dataUrl.slice(commaIdx + 1) : dataUrl;
1653
+ const headerPart = commaIdx >= 0 ? dataUrl.slice(0, commaIdx) : "";
1654
+ const mimeMatch = headerPart.match(/data:([^;]+)/);
1655
+ const mimeType = mimeMatch ? mimeMatch[1] : "image/jpeg";
1656
+ const fileName = `screenshot-${Date.now()}.jpg`;
1657
+ const fileSize = Math.ceil(fileData.length * 3 / 4);
1658
+ const response = await apiClient.uploadAttachment({
1659
+ fileName,
1660
+ fileType: "screenshot",
1661
+ fileSize,
1662
+ fileData,
1663
+ mimeType
1664
+ });
1665
+ const path = response.filePath ?? response.id;
1666
+ this.log(`uploadScreenshot: uploaded as ${path}`);
1667
+ return path ?? null;
1668
+ } catch (e) {
1669
+ this.log(`uploadScreenshot: failed \u2014 ${String(e)}`);
1670
+ return null;
1671
+ }
1672
+ }
1673
+ /**
1674
+ * Fetch the bug reports this tester has submitted (newest first).
1675
+ * Delegates to apiClient.listMyBugReports. Soft-fails to an empty list
1676
+ * when the client lacks the method or the call throws.
1677
+ *
1678
+ * Requires a tester auth token — if unauthenticated the server 401s and
1679
+ * this returns the empty-list soft-fail result.
1680
+ */
1681
+ async getMyBugReports(params) {
1682
+ const apiClient = this.config.apiClient;
1683
+ if (!apiClient?.listMyBugReports) {
1684
+ this.log("getMyBugReports: apiClient does not implement listMyBugReports \u2014 returning empty list");
1685
+ return { bugReports: [] };
1686
+ }
1687
+ try {
1688
+ return await apiClient.listMyBugReports(params);
1689
+ } catch (e) {
1690
+ this.log(`getMyBugReports: failed \u2014 ${String(e)}`);
1691
+ return { bugReports: [] };
1692
+ }
1693
+ }
1694
+ /**
1695
+ * Fetch tester notifications + unread count.
1696
+ * Delegates to apiClient.getMyNotifications. Soft-fails to
1697
+ * { notifications: [], unreadCount: 0 } on any error or missing method.
1698
+ *
1699
+ * Requires a tester auth token.
1700
+ */
1701
+ async getNotifications(params) {
1702
+ const apiClient = this.config.apiClient;
1703
+ if (!apiClient?.getMyNotifications) {
1704
+ this.log("getNotifications: apiClient does not implement getMyNotifications \u2014 returning empty");
1705
+ return { notifications: [], unreadCount: 0 };
1706
+ }
1707
+ try {
1708
+ return await apiClient.getMyNotifications(params);
1709
+ } catch (e) {
1710
+ this.log(`getNotifications: failed \u2014 ${String(e)}`);
1711
+ return { notifications: [], unreadCount: 0 };
1712
+ }
1713
+ }
1714
+ /**
1715
+ * Mark notifications read. Pass an id to mark one; omit to mark all.
1716
+ * Delegates to apiClient.markNotificationsRead. Soft-fails to null on
1717
+ * any error or missing method (caller should treat null as "no change").
1718
+ *
1719
+ * Requires a tester auth token.
1720
+ *
1721
+ * @returns New unread count, or null on soft-fail.
1722
+ */
1723
+ async markNotificationsRead(id) {
1724
+ const apiClient = this.config.apiClient;
1725
+ if (!apiClient?.markNotificationsRead) {
1726
+ this.log("markNotificationsRead: apiClient does not implement markNotificationsRead \u2014 skipping");
1727
+ return null;
1728
+ }
1729
+ try {
1730
+ return await apiClient.markNotificationsRead(id ? { id } : void 0);
1731
+ } catch (e) {
1732
+ this.log(`markNotificationsRead: failed \u2014 ${String(e)}`);
1733
+ return null;
1734
+ }
1735
+ }
1736
+ /**
1737
+ * Aggregate local metrics and enqueue a submission to the outbox.
1738
+ * Returns a local UUID immediately — the upload happens in the background.
1739
+ *
1740
+ * Contract: api.submissions.createSubmissionAsync / invariants.local_first_outbox
1741
+ *
1742
+ * @returns A local UUID that can be passed to getSubmissionStatus()
1743
+ */
1744
+ async createSubmission() {
1745
+ this.ensureInitialized();
1746
+ const summary = await this.metricsAggregator.aggregateWeeklySummary();
1747
+ const localId = await this.outbox.enqueue("submission", summary);
1748
+ this.outbox.scheduleDrain();
1749
+ this.log(`Submission enqueued: ${localId}`);
1750
+ return localId;
1751
+ }
1752
+ /**
1753
+ * Query the outbox state for a previously-enqueued item.
1754
+ *
1755
+ * Returns:
1756
+ * 'pending' — enqueued, not yet uploaded
1757
+ * 'uploading' — upload in progress
1758
+ * 'failed' — permanently rejected (4xx); will not be retried
1759
+ * null — item not found; treat as successfully sent (deleted on success)
1760
+ *
1761
+ * Contract: api.submissions.getSubmissionStatus / enums.OutboxItemStatus
1762
+ *
1763
+ * @param localId - The id returned by submitBugReport() or createSubmission()
1764
+ */
1765
+ async getSubmissionStatus(localId) {
1766
+ this.ensureInitialized();
1767
+ return this.outbox.getStatus(localId);
1768
+ }
1769
+ /**
1770
+ * Generate and store a weekly summary.
1771
+ *
1772
+ * Aggregates all metrics from the past 7 days and stores the summary
1773
+ * in the local database for later submission.
1774
+ *
1775
+ * @returns Promise resolving to the generated summary
1776
+ */
1777
+ async generateWeeklySummary() {
1778
+ this.ensureInitialized();
1779
+ const summary = await this.metricsAggregator.aggregateWeeklySummary();
1780
+ await this.metricsAggregator.storeSummary(summary);
1781
+ this.log(`Weekly summary generated: ${summary.id}`);
1782
+ return summary;
1783
+ }
1784
+ /**
1785
+ * Get all pending summaries.
1786
+ *
1787
+ * @returns Array of pending WeeklySummary objects
1788
+ */
1789
+ async getPendingSummaries() {
1790
+ this.ensureInitialized();
1791
+ return this.metricsAggregator.getPendingSummaries();
1792
+ }
1793
+ /**
1794
+ * Submit pending summaries to the server.
1795
+ * Requires apiClient to be configured.
1796
+ *
1797
+ * @returns Number of summaries successfully submitted
1798
+ */
1799
+ async submitPendingSummaries() {
1800
+ this.ensureInitialized();
1801
+ if (!this.config.apiClient) {
1802
+ throw new Error("API client not configured. Cannot submit summaries.");
1803
+ }
1804
+ const pendingSummaries = await this.metricsAggregator.getPendingSummaries();
1805
+ let successCount = 0;
1806
+ for (const summary of pendingSummaries) {
1807
+ try {
1808
+ await this.config.apiClient.submitSummary(summary);
1809
+ await this.metricsAggregator.updateSummaryStatus(summary.id, "submitted");
1810
+ successCount++;
1811
+ this.log(`Summary submitted: ${summary.id}`);
1812
+ } catch (error) {
1813
+ this.log(`Failed to submit summary ${summary.id}: ${error}`);
1814
+ }
1815
+ }
1816
+ return successCount;
1817
+ }
1818
+ /**
1819
+ * Get the current session ID.
1820
+ *
1821
+ * @returns Current session ID or null if no session is active
1822
+ */
1823
+ getCurrentSessionId() {
1824
+ return this.sessionManager.getCurrentSessionId();
1825
+ }
1826
+ /**
1827
+ * Check if there's an active session.
1828
+ *
1829
+ * @returns true if a session is currently active
1830
+ */
1831
+ hasActiveSession() {
1832
+ return this.sessionManager.hasActiveSession();
1833
+ }
1834
+ /**
1835
+ * Get the current session duration in seconds.
1836
+ *
1837
+ * @returns Duration in seconds, or 0 if no session is active
1838
+ */
1839
+ getSessionDuration() {
1840
+ return this.sessionManager.getSessionDuration();
1841
+ }
1842
+ /**
1843
+ * Close the SDK and clean up resources.
1844
+ */
1845
+ async close() {
1846
+ if (this.sessionManager.hasActiveSession()) {
1847
+ await this.sessionManager.endSession();
1848
+ }
1849
+ await this.config.storage.close();
1850
+ this.initialized = false;
1851
+ this.log("SDK closed");
1852
+ }
1853
+ /**
1854
+ * Ensure the SDK is initialized before use.
1855
+ * @throws Error if SDK is not initialized
1856
+ */
1857
+ ensureInitialized() {
1858
+ if (!this.initialized) {
1859
+ throw new Error("TesterPayKit not initialized. Call init() first.");
1860
+ }
1861
+ }
1862
+ /**
1863
+ * Log debug messages. Always pushes to the ring buffer (regardless of
1864
+ * debugMode) so TpkDebugLogsScreen has content. Console output stays
1865
+ * gated by debugMode.
1866
+ */
1867
+ log(message) {
1868
+ this._logBuffer.push({ ts: Date.now(), message });
1869
+ if (this._logBuffer.length > _TesterPayKit.LOG_BUFFER_MAX) {
1870
+ this._logBuffer.shift();
1871
+ }
1872
+ if (this.config.debugMode) {
1873
+ console.log(`[TesterPayKit] ${message}`);
1874
+ }
1875
+ }
1876
+ /**
1877
+ * Get a copy of the debug log buffer, newest entry first.
1878
+ * The buffer accumulates up to 200 entries regardless of debugMode.
1879
+ */
1880
+ getDebugLogs() {
1881
+ return this._logBuffer.slice().reverse();
1882
+ }
1883
+ /**
1884
+ * Clear the debug log buffer.
1885
+ */
1886
+ clearDebugLogs() {
1887
+ this._logBuffer = [];
1888
+ }
1889
+ /**
1890
+ * Get the epoch-ms timestamp when the current session started.
1891
+ * Delegates to SessionManager.
1892
+ *
1893
+ * @returns Epoch ms, or null when no session is active
1894
+ */
1895
+ getCurrentSessionStartedAt() {
1896
+ return this.sessionManager.getCurrentSessionStartedAt();
1897
+ }
1898
+ /**
1899
+ * Compute estimated session earnings.
1900
+ *
1901
+ * engagedMinutes = floor(elapsed since session start in minutes).
1902
+ * amount = earningsBaseAmount + engagedMinutes * earningsPerMinuteRate.
1903
+ * currency = earningsCurrency from config.
1904
+ *
1905
+ * Soft-safe: never throws; returns base/0/currency when no session.
1906
+ * Max cap: 480 minutes (8 hours) to keep amounts sane.
1907
+ */
1908
+ getSessionEarnings() {
1909
+ try {
1910
+ const base = this.config.earningsBaseAmount ?? 1;
1911
+ const rate = this.config.earningsPerMinuteRate ?? 0.1;
1912
+ const currency = this.config.earningsCurrency ?? "EUR";
1913
+ const startedAt = this.sessionManager.getCurrentSessionStartedAt();
1914
+ if (startedAt === null) {
1915
+ return { engagedMinutes: 0, amount: base, currency };
1916
+ }
1917
+ const elapsedMs = Date.now() - startedAt;
1918
+ const engagedMinutes = Math.min(Math.floor(elapsedMs / 6e4), 480);
1919
+ const amount = base + engagedMinutes * rate;
1920
+ return { engagedMinutes, amount, currency };
1921
+ } catch {
1922
+ return {
1923
+ engagedMinutes: 0,
1924
+ amount: this.config.earningsBaseAmount ?? 1,
1925
+ currency: this.config.earningsCurrency ?? "EUR"
1926
+ };
1927
+ }
1928
+ }
1929
+ /**
1930
+ * Return the configured app metadata (bundleId, version, buildNumber, etc.).
1931
+ * Used by TpkWorkboardScreen to show the current build info block.
1932
+ */
1933
+ getAppInfo() {
1934
+ return this.config.appMetadata;
1935
+ }
1936
+ /**
1937
+ * Fetch the tester's assigned tasks.
1938
+ * Delegates to apiClient.getMyTasks. Soft-fails to an empty TaskListResponse
1939
+ * when the client lacks the method or the call throws.
1940
+ */
1941
+ async getMyTasks(params) {
1942
+ const apiClient = this.config.apiClient;
1943
+ if (!apiClient?.getMyTasks) {
1944
+ this.log("getMyTasks: apiClient does not implement getMyTasks \u2014 returning empty list");
1945
+ return { tasks: [], total: 0, summary: { pending: 0, inProgress: 0, completed: 0 } };
1946
+ }
1947
+ try {
1948
+ return await apiClient.getMyTasks(params);
1949
+ } catch (e) {
1950
+ this.log(`getMyTasks: failed \u2014 ${String(e)}`);
1951
+ return { tasks: [], total: 0, summary: { pending: 0, inProgress: 0, completed: 0 } };
1952
+ }
1953
+ }
1954
+ /**
1955
+ * Mark a task assignment in-progress.
1956
+ * Delegates to apiClient.startTaskAssignment. Soft-fails silently on error.
1957
+ */
1958
+ async startTask(assignmentId) {
1959
+ const apiClient = this.config.apiClient;
1960
+ if (!apiClient?.startTaskAssignment) {
1961
+ this.log("startTask: apiClient does not implement startTaskAssignment \u2014 skipping");
1962
+ return;
1963
+ }
1964
+ try {
1965
+ await apiClient.startTaskAssignment(assignmentId);
1966
+ } catch (e) {
1967
+ this.log(`startTask: failed \u2014 ${String(e)}`);
1968
+ }
1969
+ }
1970
+ /**
1971
+ * Complete a task assignment.
1972
+ * Delegates to apiClient.completeTaskAssignment. Soft-fails silently on error.
1973
+ */
1974
+ async completeTask(assignmentId) {
1975
+ const apiClient = this.config.apiClient;
1976
+ if (!apiClient?.completeTaskAssignment) {
1977
+ this.log("completeTask: apiClient does not implement completeTaskAssignment \u2014 skipping");
1978
+ return;
1979
+ }
1980
+ try {
1981
+ await apiClient.completeTaskAssignment(assignmentId);
1982
+ } catch (e) {
1983
+ this.log(`completeTask: failed \u2014 ${String(e)}`);
1984
+ }
1985
+ }
1986
+ /**
1987
+ * Fetch the tester's retest queue.
1988
+ * Delegates to apiClient.getMyRetests. Soft-fails to an empty array.
1989
+ */
1990
+ async getMyRetests(params) {
1991
+ const apiClient = this.config.apiClient;
1992
+ if (!apiClient?.getMyRetests) {
1993
+ this.log("getMyRetests: apiClient does not implement getMyRetests \u2014 returning empty list");
1994
+ return [];
1995
+ }
1996
+ try {
1997
+ return await apiClient.getMyRetests(params);
1998
+ } catch (e) {
1999
+ this.log(`getMyRetests: failed \u2014 ${String(e)}`);
2000
+ return [];
2001
+ }
2002
+ }
2003
+ /**
2004
+ * Mark a retest as verified (bug is fixed).
2005
+ * Delegates to apiClient.verifyRetest. Soft-fails silently on error.
2006
+ */
2007
+ async verifyRetest(bugId, stepVerdicts) {
2008
+ const apiClient = this.config.apiClient;
2009
+ if (!apiClient?.verifyRetest) {
2010
+ this.log("verifyRetest: apiClient does not implement verifyRetest \u2014 skipping");
2011
+ return;
2012
+ }
2013
+ try {
2014
+ await apiClient.verifyRetest(bugId, stepVerdicts);
2015
+ } catch (e) {
2016
+ this.log(`verifyRetest: failed \u2014 ${String(e)}`);
2017
+ }
2018
+ }
2019
+ /**
2020
+ * Reopen a retest (bug still present), optionally with a reason.
2021
+ * Delegates to apiClient.reopenRetest. Soft-fails silently on error.
2022
+ */
2023
+ async reopenRetest(bugId, reason, stepVerdicts) {
2024
+ const apiClient = this.config.apiClient;
2025
+ if (!apiClient?.reopenRetest) {
2026
+ this.log("reopenRetest: apiClient does not implement reopenRetest \u2014 skipping");
2027
+ return;
2028
+ }
2029
+ try {
2030
+ await apiClient.reopenRetest(bugId, reason, stepVerdicts);
2031
+ } catch (e) {
2032
+ this.log(`reopenRetest: failed \u2014 ${String(e)}`);
2033
+ }
2034
+ }
2035
+ /**
2036
+ * Fetch the tester's profile.
2037
+ * Delegates to apiClient.getMyProfile. Soft-fails to null on error.
2038
+ */
2039
+ async getMyProfile() {
2040
+ const apiClient = this.config.apiClient;
2041
+ if (!apiClient?.getMyProfile) {
2042
+ this.log("getMyProfile: apiClient does not implement getMyProfile \u2014 returning null");
2043
+ return null;
2044
+ }
2045
+ try {
2046
+ return await apiClient.getMyProfile();
2047
+ } catch (e) {
2048
+ this.log(`getMyProfile: failed \u2014 ${String(e)}`);
2049
+ return null;
2050
+ }
2051
+ }
2052
+ /**
2053
+ * Fetch the tester's points balance.
2054
+ * Delegates to apiClient.getMyPoints. Soft-fails to null on error.
2055
+ */
2056
+ async getMyPoints() {
2057
+ const apiClient = this.config.apiClient;
2058
+ if (!apiClient?.getMyPoints) {
2059
+ this.log("getMyPoints: apiClient does not implement getMyPoints \u2014 returning null");
2060
+ return null;
2061
+ }
2062
+ try {
2063
+ return await apiClient.getMyPoints();
2064
+ } catch (e) {
2065
+ this.log(`getMyPoints: failed \u2014 ${String(e)}`);
2066
+ return null;
2067
+ }
2068
+ }
2069
+ };
2070
+ // ── Debug log ring buffer ────────────────────────────────────────────────────
2071
+ // Holds the most recent LOG_BUFFER_MAX entries regardless of debugMode.
2072
+ // Console output stays gated by debugMode.
2073
+ _TesterPayKit.LOG_BUFFER_MAX = 200;
2074
+ var TesterPayKit = _TesterPayKit;
2075
+ function isProductionBuild() {
2076
+ try {
2077
+ return typeof process !== "undefined" && process.env?.NODE_ENV === "production";
2078
+ } catch {
2079
+ return false;
2080
+ }
2081
+ }
2082
+
2083
+ // src/index.ts
2084
+ var import_core7 = require("@testerpaykit/core");
2085
+ // Annotate the CommonJS export names for ESM import in node:
2086
+ 0 && (module.exports = {
2087
+ BUG_REPORT_CATEGORIES,
2088
+ BUG_REPORT_SEVERITIES,
2089
+ BUG_REPORT_TYPES,
2090
+ DeviceIdManager,
2091
+ EventTracker,
2092
+ MetricsAggregator,
2093
+ Outbox,
2094
+ SessionManager,
2095
+ TesterPayKit,
2096
+ ValidationConstants
2097
+ });