@testerpaykit/api-client 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,563 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ TesterPayKitApiClient: () => TesterPayKitApiClient
34
+ });
35
+ module.exports = __toCommonJS(index_exports);
36
+
37
+ // src/TesterPayKitApiClient.ts
38
+ var import_axios = __toESM(require("axios"));
39
+ var import_core = require("@testerpaykit/core");
40
+ var TesterPayKitApiClient = class {
41
+ constructor(config) {
42
+ this.apiKey = config.apiKey;
43
+ this.tokenManager = config.tokenManager || new import_core.TokenManager();
44
+ this.client = import_axios.default.create({
45
+ baseURL: config.baseURL || "https://api.testerpaykit.com",
46
+ headers: {
47
+ "Content-Type": "application/json",
48
+ "X-API-Key": this.apiKey
49
+ }
50
+ });
51
+ this.setupInterceptors();
52
+ }
53
+ /**
54
+ * Setup request/response interceptors for JWT authentication.
55
+ */
56
+ setupInterceptors() {
57
+ this.client.interceptors.request.use(async (config) => {
58
+ const token = await this.tokenManager.ensureValidToken();
59
+ if (token) {
60
+ config.headers.Authorization = `Bearer ${token}`;
61
+ }
62
+ return config;
63
+ });
64
+ this.client.interceptors.response.use(
65
+ (response) => response,
66
+ async (error) => {
67
+ if (error.response?.status === 401) {
68
+ this.tokenManager.clear();
69
+ }
70
+ return Promise.reject(error);
71
+ }
72
+ );
73
+ }
74
+ /**
75
+ * Authenticate a tester with email/password.
76
+ * Stores tokens in TokenManager and sets up refresh callback.
77
+ */
78
+ async login(request) {
79
+ const response = await this.client.post("/auth/login", request);
80
+ if (response.data.accessToken && response.data.refreshToken) {
81
+ this.tokenManager.setTokens(response.data.accessToken, response.data.refreshToken);
82
+ this.tokenManager.setRefreshCallback(async (refreshToken) => {
83
+ const refreshResponse = await this.refreshToken(refreshToken);
84
+ return refreshResponse.accessToken;
85
+ });
86
+ }
87
+ return response.data;
88
+ }
89
+ /**
90
+ * Refresh access token using refresh token.
91
+ * Updates TokenManager with new access token.
92
+ */
93
+ async refreshToken(refreshToken) {
94
+ const response = await this.client.post("/v1/auth/refresh", {
95
+ refreshToken
96
+ });
97
+ if (response.data.accessToken) {
98
+ this.tokenManager.setTokens(response.data.accessToken, refreshToken);
99
+ }
100
+ return response.data;
101
+ }
102
+ /**
103
+ * Submit a weekly summary for payment.
104
+ * POST /v1/submissions
105
+ */
106
+ async submitSummary(summary) {
107
+ const response = await this.client.post(
108
+ "/v1/submissions",
109
+ summary
110
+ );
111
+ return response.data;
112
+ }
113
+ /**
114
+ * Get submissions for the authenticated tester.
115
+ * GET /v1/submissions
116
+ */
117
+ async getPendingSubmissions(params) {
118
+ const response = await this.client.get("/v1/submissions", { params });
119
+ return response.data;
120
+ }
121
+ /**
122
+ * Fetch the set of submission IDs the server already holds.
123
+ * GET /v1/submissions?limit=100
124
+ * Soft-fail: returns empty set on any error.
125
+ */
126
+ async fetchServerSubmissionIds() {
127
+ try {
128
+ const submissions = await this.getPendingSubmissions({ limit: 100 });
129
+ return new Set(submissions.map((s) => s.id));
130
+ } catch {
131
+ return /* @__PURE__ */ new Set();
132
+ }
133
+ }
134
+ /**
135
+ * Set access token manually (for testing or external auth flows).
136
+ */
137
+ setAccessToken(token) {
138
+ this.tokenManager.setTokens(token, "");
139
+ }
140
+ /**
141
+ * Acquire an anonymous tester JWT by trading a {projectId, code}
142
+ * pair for an access + refresh token. No email/password required.
143
+ *
144
+ * Server-side this hits POST /auth/tester/anonymous; a synthetic
145
+ * email derived from {projectId, code} is the dedup key so the
146
+ * same code resolves to the same tester row every time.
147
+ */
148
+ async loginAnonymous(projectId, code) {
149
+ const response = await this.client.post(
150
+ "/auth/tester/anonymous",
151
+ { projectId, code }
152
+ );
153
+ if (response.data.accessToken) {
154
+ this.tokenManager.setTokens(
155
+ response.data.accessToken,
156
+ response.data.refreshToken
157
+ );
158
+ }
159
+ return { ...response.data, testerId: response.data.tester?.id };
160
+ }
161
+ /**
162
+ * Request a passwordless magic-link sign-in for a tester (or coordinator).
163
+ * POST /auth/magic-link/request. The server emails a single-use link; when
164
+ * `returnUrl` is a first-party *.moinsen.dev origin the link returns there
165
+ * with the token, otherwise it points at the console. `country` (DE/AT/CH)
166
+ * enables open tester self-signup for unknown emails. Always resolves; the
167
+ * response is intentionally generic (no user enumeration).
168
+ */
169
+ async requestMagicLink(input) {
170
+ const response = await this.client.post("/auth/magic-link/request", {
171
+ email: input.email,
172
+ ...input.returnUrl && { returnUrl: input.returnUrl },
173
+ ...input.country && { country: input.country },
174
+ ...input.then && { then: input.then }
175
+ });
176
+ return response.data;
177
+ }
178
+ /**
179
+ * Consume a magic-link token (from the returned URL). POST
180
+ * /auth/magic-link/consume. On success stores the minted JWTs and returns
181
+ * the tester/coordinator payload.
182
+ */
183
+ async consumeMagicLink(token) {
184
+ const response = await this.client.post("/auth/magic-link/consume", { token });
185
+ const data = response.data;
186
+ if (data.accessToken) {
187
+ this.tokenManager.setTokens(data.accessToken, data.refreshToken ?? "");
188
+ }
189
+ return data;
190
+ }
191
+ /**
192
+ * Submit a bug report to the server. Hits
193
+ * POST /v1/testers/me/bug-reports with the tester JWT already
194
+ * attached by the request interceptor (call loginAnonymous /
195
+ * loginCoordinator first).
196
+ *
197
+ * Server-side enum constraints are enforced — see the typedef
198
+ * for valid {type, severity, category} values. Sending an
199
+ * out-of-band string returns 500 with a detail message in
200
+ * development mode.
201
+ */
202
+ async submitBugReport(payload, options) {
203
+ const headers = {};
204
+ if (options?.idempotencyKey) {
205
+ headers["X-Idempotency-Key"] = options.idempotencyKey;
206
+ }
207
+ const response = await this.client.post(
208
+ "/v1/testers/me/bug-reports",
209
+ payload,
210
+ Object.keys(headers).length ? { headers } : void 0
211
+ );
212
+ return response.data;
213
+ }
214
+ /**
215
+ * List the bug reports this tester submitted (newest first), with their
216
+ * current status. Hits GET /v1/testers/me/bug-reports. Mirrors the
217
+ * Flutter SDK's getMyBugReports — powers the "Meine Bugs" screen.
218
+ */
219
+ async listMyBugReports(params) {
220
+ const response = await this.client.get(
221
+ "/v1/testers/me/bug-reports",
222
+ { params }
223
+ );
224
+ return response.data;
225
+ }
226
+ /**
227
+ * The tester's in-app notifications (newest first) + the unread count.
228
+ * GET /v1/testers/me/notifications. Mirrors the Flutter SDK's
229
+ * getMyNotifications — powers the "Nachrichten" inbox.
230
+ */
231
+ async getMyNotifications(params) {
232
+ const response = await this.client.get(
233
+ "/v1/testers/me/notifications",
234
+ { params }
235
+ );
236
+ return response.data;
237
+ }
238
+ /**
239
+ * Mark notifications read. Pass an `id` to mark one, or omit to mark all.
240
+ * POST /v1/testers/me/notifications/read. Returns the new unread count.
241
+ */
242
+ async markNotificationsRead(params) {
243
+ const response = await this.client.post(
244
+ "/v1/testers/me/notifications/read",
245
+ params?.id ? { id: params.id } : {}
246
+ );
247
+ return response.data.unreadCount;
248
+ }
249
+ /**
250
+ * Attach a file (screenshot, log, voice note) to an already-
251
+ * submitted bug report. Hits POST /v1/testers/me/bug-reports/
252
+ * [id]/attachments. Base64-encoded payload, server stores blob
253
+ * + returns metadata.
254
+ */
255
+ async attachToBugReport(bugReportId, attachment) {
256
+ const response = await this.client.post(
257
+ `/v1/testers/me/bug-reports/${bugReportId}/attachments`,
258
+ attachment
259
+ );
260
+ return response.data;
261
+ }
262
+ /**
263
+ * Start a server-side tester session. The API uses snake_case
264
+ * field names here because this maps directly to the sessions
265
+ * table and existing Flutter SDK contract.
266
+ */
267
+ async startTesterSession(input) {
268
+ const body = {
269
+ project_id: input.projectId,
270
+ ...input.deviceInfo && { device_info: input.deviceInfo },
271
+ ...input.appVersion && { app_version: input.appVersion },
272
+ ...input.sdkVersion && { sdk_version: input.sdkVersion },
273
+ ...input.deviceId && { device_id: input.deviceId }
274
+ };
275
+ const response = await this.client.post("/v1/testers/sessions", body);
276
+ return response.data.session;
277
+ }
278
+ /** End a server-side tester session with optional counters. */
279
+ async endTesterSession(input) {
280
+ await this.client.put(`/v1/testers/sessions/${input.sessionId}`, {
281
+ ended_at: (input.endedAt ?? /* @__PURE__ */ new Date()).toISOString(),
282
+ ...input.bugsFound != null && { bugs_found: input.bugsFound },
283
+ ...input.tasksCompleted != null && {
284
+ tasks_completed: input.tasksCompleted
285
+ },
286
+ ...input.endReason && { end_reason: input.endReason },
287
+ ...input.foregroundSeconds != null && {
288
+ foreground_seconds: input.foregroundSeconds
289
+ }
290
+ });
291
+ }
292
+ /**
293
+ * Add one or more timeline events to an active tester session.
294
+ * Hits POST /v1/testers/sessions/:id/events in batch mode.
295
+ */
296
+ async addSessionEvents(sessionId, events) {
297
+ const response = await this.client.post(
298
+ `/v1/testers/sessions/${sessionId}/events`,
299
+ {
300
+ events: events.map((event) => ({
301
+ event_type: event.eventType,
302
+ ...event.eventData && { event_data: event.eventData },
303
+ ...event.screenRoute && { screen_route: event.screenRoute },
304
+ ...event.timestamp && {
305
+ timestamp: formatTimestamp(event.timestamp)
306
+ }
307
+ }))
308
+ }
309
+ );
310
+ return response.data;
311
+ }
312
+ /**
313
+ * Add one or more breadcrumbs to an active tester session.
314
+ * Hits POST /v1/testers/sessions/:id/breadcrumbs in batch mode.
315
+ */
316
+ async addSessionBreadcrumbs(sessionId, breadcrumbs) {
317
+ const response = await this.client.post(
318
+ `/v1/testers/sessions/${sessionId}/breadcrumbs`,
319
+ {
320
+ breadcrumbs: breadcrumbs.map((breadcrumb) => ({
321
+ breadcrumb_type: breadcrumb.breadcrumbType,
322
+ message: breadcrumb.message,
323
+ ...breadcrumb.metadata && { metadata: breadcrumb.metadata },
324
+ ...breadcrumb.timestamp && {
325
+ timestamp: formatTimestamp(breadcrumb.timestamp)
326
+ }
327
+ }))
328
+ }
329
+ );
330
+ return response.data;
331
+ }
332
+ /**
333
+ * Fetch the tester's assigned tasks. Server-side filter by
334
+ * status / project_id. Hits GET /v1/testers/tasks.
335
+ */
336
+ async getMyTasks(filter = {}) {
337
+ const response = await this.client.get(
338
+ "/v1/testers/tasks",
339
+ { params: filter }
340
+ );
341
+ return response.data;
342
+ }
343
+ /**
344
+ * Mark a task assignment in-progress. PUT /v1/testers/tasks/{id}/start.
345
+ * The server only completes an in-progress task, so callers start first.
346
+ */
347
+ async startTaskAssignment(assignmentId) {
348
+ await this.client.put(`/v1/testers/tasks/${assignmentId}/start`);
349
+ }
350
+ /** Complete a task assignment. PUT /v1/testers/tasks/{id}/complete. */
351
+ async completeTaskAssignment(assignmentId) {
352
+ await this.client.put(`/v1/testers/tasks/${assignmentId}/complete`);
353
+ }
354
+ /**
355
+ * Enroll the authenticated tester in a project. Idempotent —
356
+ * a second enroll on the same project resolves to the existing
357
+ * enrollment row. POST /v1/testers/projects/:id/enroll.
358
+ */
359
+ async enrollInProject(projectId) {
360
+ const response = await this.client.post(
361
+ `/v1/testers/projects/${projectId}/enroll`
362
+ );
363
+ return response.data;
364
+ }
365
+ /**
366
+ * Reverse of enrollInProject. POST /v1/testers/projects/:id/unenroll.
367
+ */
368
+ async unenrollFromProject(projectId) {
369
+ await this.client.post(`/v1/testers/projects/${projectId}/unenroll`);
370
+ }
371
+ /**
372
+ * Tester profile (handle, points, rating, etc.).
373
+ * GET /v1/testers/me/profile.
374
+ */
375
+ async getMyProfile() {
376
+ const response = await this.client.get(
377
+ "/v1/testers/me/profile"
378
+ );
379
+ return response.data;
380
+ }
381
+ /** GET /v1/testers/me/points — current point balance + breakdown. */
382
+ async getMyPoints() {
383
+ const response = await this.client.get(
384
+ "/v1/testers/me/points"
385
+ );
386
+ return response.data;
387
+ }
388
+ /** GET /v1/testers/earnings/summary — totals, current balance, this month. */
389
+ async getEarningsSummary() {
390
+ const response = await this.client.get(
391
+ "/v1/testers/earnings/summary"
392
+ );
393
+ return response.data;
394
+ }
395
+ /** GET /v1/testers/earnings/payouts — paginated payout history. */
396
+ async getMyPayouts(params) {
397
+ const response = await this.client.get("/v1/testers/earnings/payouts", { params });
398
+ return response.data;
399
+ }
400
+ /**
401
+ * GET /v1/testers/me/projects/:bundleIdOrUuid/knowledge-base
402
+ *
403
+ * Lists the markdown docs the coordinator attached to this project.
404
+ * Feeds the SDK widget's "ask a question about the project" flow.
405
+ * No content in the list response — call `getKnowledgeFile` for the
406
+ * full body. Accepts either the project's bundle id (what the host
407
+ * SDK already knows from its build) or its UUID.
408
+ */
409
+ async listKnowledgeFiles(bundleIdOrProjectId) {
410
+ const projectSegment = encodeURIComponent(bundleIdOrProjectId);
411
+ const response = await this.client.get(
412
+ `/v1/testers/me/projects/${projectSegment}/knowledge-base`
413
+ );
414
+ return response.data;
415
+ }
416
+ /**
417
+ * GET /v1/testers/me/projects/:bundleIdOrUuid/knowledge-base/:fileId
418
+ *
419
+ * Fetches one markdown doc's full content. Caller is expected to
420
+ * scope the fetch — passing the same `bundleIdOrProjectId` that
421
+ * `listKnowledgeFiles` was called with is the natural pattern.
422
+ */
423
+ async getKnowledgeFile(bundleIdOrProjectId, fileId) {
424
+ const projectSegment = encodeURIComponent(bundleIdOrProjectId);
425
+ const fileSegment = encodeURIComponent(fileId);
426
+ const response = await this.client.get(
427
+ `/v1/testers/me/projects/${projectSegment}/knowledge-base/${fileSegment}`
428
+ );
429
+ return response.data.file;
430
+ }
431
+ /**
432
+ * POST /v1/testers/me/projects/:bundleIdOrUuid/knowledge-base/query
433
+ *
434
+ * RAG over the project's knowledge-base markdown files. Embeds the
435
+ * question, retrieves top-K nearest chunks via pgvector cosine
436
+ * similarity, and asks gpt-4o-mini to synthesise an answer that
437
+ * STRICTLY cites those chunks. Answer language tracks the
438
+ * question (English / German).
439
+ *
440
+ * Returns {answer, citations}. The widget UI surfaces the answer
441
+ * + a "Sources" disclosure with the citations so the tester knows
442
+ * which doc the answer came from. `citations[*].content` is the
443
+ * exact span the model saw — ready to render as a snippet.
444
+ */
445
+ async askKnowledgeBase(bundleIdOrProjectId, question) {
446
+ const projectSegment = encodeURIComponent(bundleIdOrProjectId);
447
+ const response = await this.client.post(
448
+ `/v1/testers/me/projects/${projectSegment}/knowledge-base/query`,
449
+ { question }
450
+ );
451
+ return response.data;
452
+ }
453
+ /**
454
+ * GET /v1/tasks
455
+ * List available task presets for a project.
456
+ */
457
+ async getTasks(params) {
458
+ const response = await this.client.get("/v1/tasks", { params });
459
+ return response.data;
460
+ }
461
+ /**
462
+ * POST /v1/testers/me/devices
463
+ * Register (or upsert) this device for push notifications.
464
+ * Server keys on device_token — a second POST with the same token updates the row.
465
+ */
466
+ async registerDevice(input) {
467
+ const body = {
468
+ device_token: input.deviceToken,
469
+ device_type: input.deviceType
470
+ };
471
+ if (input.deviceModel) body.device_model = input.deviceModel;
472
+ if (input.osVersion) body.os_version = input.osVersion;
473
+ if (input.appVersion) body.app_version = input.appVersion;
474
+ const response = await this.client.post(
475
+ "/v1/testers/me/devices",
476
+ body
477
+ );
478
+ return response.data;
479
+ }
480
+ /**
481
+ * POST /v1/session-feedback
482
+ * Submit end-of-session feedback (rating, comments, etc.).
483
+ */
484
+ async submitSessionEndFeedback(payload) {
485
+ const response = await this.client.post(
486
+ "/v1/session-feedback",
487
+ payload
488
+ );
489
+ return response.data;
490
+ }
491
+ /**
492
+ * Upload an attachment directly (not tied to a specific bug report).
493
+ * POST /v1/attachments — alternate path from the contract alongside
494
+ * /v1/testers/me/bug-reports/{id}/attachments.
495
+ */
496
+ async uploadAttachment(attachment) {
497
+ const response = await this.client.post(
498
+ "/v1/attachments",
499
+ attachment
500
+ );
501
+ return response.data;
502
+ }
503
+ /**
504
+ * GET /v1/testers/me/retests
505
+ * List bug reports assigned to this tester for re-verification.
506
+ */
507
+ async getMyRetests(params) {
508
+ const response = await this.client.get(
509
+ "/v1/testers/me/retests",
510
+ { params }
511
+ );
512
+ return response.data;
513
+ }
514
+ /**
515
+ * POST /v1/testers/me/retests/{bugId}/verify
516
+ * Mark a retest as verified (bug is fixed).
517
+ */
518
+ async verifyRetest(bugId) {
519
+ await this.client.post(`/v1/testers/me/retests/${bugId}/verify`);
520
+ }
521
+ /**
522
+ * POST /v1/testers/me/retests/{bugId}/reopen
523
+ * Reopen a retest (bug is still present), optionally with a reason.
524
+ */
525
+ async reopenRetest(bugId, reason) {
526
+ await this.client.post(`/v1/testers/me/retests/${bugId}/reopen`, {
527
+ ...reason ? { reason } : {}
528
+ });
529
+ }
530
+ /**
531
+ * POST /v1/testers/me/bug-reports/voice-extract
532
+ * Contract: wire.bug_reports.voiceExtractBugFields
533
+ *
534
+ * Sends base64-encoded audio to the server. The server runs Whisper
535
+ * (transcription) + gpt-4o-mini (structured extraction) and returns
536
+ * pre-filled bug-report fields in the tester's language.
537
+ *
538
+ * Wire body uses snake_case per contract. Timeout is 60 s because
539
+ * Whisper + Chat round-trip can take 10-30 s on long recordings.
540
+ */
541
+ async voiceExtractBugFields(request) {
542
+ const body = {
543
+ audio_base64: request.audioBase64,
544
+ mime_type: request.mimeType
545
+ };
546
+ if (request.sourceLanguage) body.source_language = request.sourceLanguage;
547
+ if (request.projectId) body.project_id = request.projectId;
548
+ if (request.preClassification) body.pre_classification = request.preClassification;
549
+ const response = await this.client.post(
550
+ "/v1/testers/me/bug-reports/voice-extract",
551
+ body,
552
+ { timeout: 6e4 }
553
+ );
554
+ return response.data;
555
+ }
556
+ };
557
+ function formatTimestamp(timestamp) {
558
+ return timestamp instanceof Date ? timestamp.toISOString() : timestamp;
559
+ }
560
+ // Annotate the CommonJS export names for ESM import in node:
561
+ 0 && (module.exports = {
562
+ TesterPayKitApiClient
563
+ });