@testerpaykit/expo 0.4.1

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/CHANGELOG.md ADDED
@@ -0,0 +1,47 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@testerpaykit/expo` are documented here.
4
+
5
+ ## 0.2.0 — 2026-05-19
6
+
7
+ **Tier-4 — Ship-ready.**
8
+
9
+ ### Added
10
+ - vitest test-suite for the pure-logic modules (29 tests across
11
+ `drawing` / `breadcrumbs` / `network` / `queue`):
12
+ - `drawing` — Ramer-Douglas-Peucker simplification on near-straight
13
+ paths, sharp-corner preservation, SVG path serialiser, arrow-head
14
+ geometry, unique-id generation.
15
+ - `breadcrumbs` — ring-buffer cap, default size, clone-on-snapshot,
16
+ `clear()`.
17
+ - `network` — fetch interceptor records method/URL/status/duration,
18
+ skips ignore-patterns (default: testerpaykit.com + :18080),
19
+ surfaces errors, truncates long URLs, teardown stops capture.
20
+ - `queue` — enqueue + size, full drain on success, permanent skip
21
+ on 4xx, requeue on 5xx / network error, no-op on empty queue.
22
+ - `vitest.config.ts` (node environment, scoped to `src/__tests__/`).
23
+
24
+ ### Changed
25
+ - Removed two dead `eslint-disable-next-line react-hooks/exhaustive-deps`
26
+ comments in `TpkAnnotated.tsx` — the rule is not enabled in this
27
+ workspace's eslint config so the directives were reporting as
28
+ errors. Behaviour unchanged.
29
+
30
+ ### Verified
31
+ - `pnpm -F @testerpaykit/expo test` — 29/29 green
32
+ - `pnpm -F @testerpaykit/expo build` — green (cjs + esm + dts)
33
+ - `pnpm -F @testerpaykit/expo lint` — clean
34
+
35
+ ## 0.1.0 — 2026-05-19
36
+
37
+ **Tier-1 to Tier-3 — Feature parity with the Flutter SDK.**
38
+
39
+ - Tier 1: anonymous-tester JWT, `submitBug`, breadcrumbs ring buffer,
40
+ crash handler, offline queue, device + app snapshot, shake-to-report.
41
+ - Tier 2: task fetching, network capture, screenshot capture, tester
42
+ dashboard hook.
43
+ - Tier 3: widget-annotation registry, annotated-screenshot editor with
44
+ Ramer-Douglas-Peucker freehand simplification, screen recording,
45
+ earnings summary.
46
+
47
+ See `README.md` for the public API.
package/README.md ADDED
@@ -0,0 +1,290 @@
1
+ # @testerpaykit/expo
2
+
3
+ TesterPayKit bindings for Expo / React Native — anonymous bug-report
4
+ submission, device snapshots, shake-to-report hook, and a small
5
+ package-owned bug-report UI shell.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npx expo install \
11
+ @testerpaykit/expo \
12
+ @react-native-async-storage/async-storage \
13
+ expo-sensors expo-device expo-application expo-file-system expo-audio
14
+ ```
15
+
16
+ Native modules are peer-optional. Without them the related feature
17
+ no-ops or falls back: shake detection (`expo-sensors`), snapshots
18
+ (`expo-device`, `expo-application`), file upload helpers
19
+ (`expo-file-system`), and voice recording (`expo-audio`).
20
+
21
+ ## Quick start
22
+
23
+ ```tsx
24
+ import { TpkExpo, useShake } from '@testerpaykit/expo';
25
+ import { useEffect, useState } from 'react';
26
+ import { Alert } from 'react-native';
27
+
28
+ export function App() {
29
+ const [tpk, setTpk] = useState<TpkExpo | null>(null);
30
+
31
+ useEffect(() => {
32
+ (async () => {
33
+ const client = await TpkExpo.init({
34
+ projectId: '8980ca35-8697-4d8c-ae3f-0677c7d177d1',
35
+ testerCode: 'demo-tester-01',
36
+ // Point at local Mac during dev, omit for prod:
37
+ apiBaseUrl: __DEV__ ? 'http://192.168.178.69:18080' : undefined,
38
+ });
39
+ setTpk(client);
40
+ })();
41
+ }, []);
42
+
43
+ useShake({
44
+ enabled: !!tpk,
45
+ onShake: async () => {
46
+ if (!tpk) return;
47
+ const result = await tpk.submitBug({
48
+ title: 'Shake-reported bug',
49
+ description: 'User shook the device on the home screen.',
50
+ currentScreen: 'HomeScreen',
51
+ severity: 'medium',
52
+ });
53
+ Alert.alert('Bug reported', `Server id: ${result.id}`);
54
+ },
55
+ });
56
+
57
+ return null; // your real UI here
58
+ }
59
+ ```
60
+
61
+ End the session when the tester finishes:
62
+
63
+ ```tsx
64
+ await tpk.endSession({
65
+ reason: 'completed',
66
+ bugsFound: 1,
67
+ tasksCompleted: 2,
68
+ });
69
+ ```
70
+
71
+ For a logical restart, rotate to a fresh server session:
72
+
73
+ ```tsx
74
+ await tpk.rotateSession();
75
+ ```
76
+
77
+ ## Package-owned UI shell
78
+
79
+ Use the provider when you want the package to own initialization:
80
+
81
+ ```tsx
82
+ import {
83
+ BugReportSheet,
84
+ FloatingFeedbackButton,
85
+ TesterPayKitProvider,
86
+ useTesterPayKit,
87
+ } from '@testerpaykit/expo';
88
+ import { useState } from 'react';
89
+
90
+ function FeedbackControls() {
91
+ const { client, ready } = useTesterPayKit();
92
+ const [open, setOpen] = useState(false);
93
+
94
+ return (
95
+ <>
96
+ <FloatingFeedbackButton
97
+ disabled={!ready}
98
+ onPress={() => setOpen(true)}
99
+ />
100
+ <BugReportSheet
101
+ currentScreen="Home"
102
+ onClose={() => setOpen(false)}
103
+ tpk={client}
104
+ visible={open}
105
+ />
106
+ </>
107
+ );
108
+ }
109
+
110
+ export function App() {
111
+ return (
112
+ <TesterPayKitProvider
113
+ config={{
114
+ projectId: '8980ca35-8697-4d8c-ae3f-0677c7d177d1',
115
+ testerCode: 'demo-tester-01',
116
+ }}
117
+ >
118
+ <FeedbackControls />
119
+ </TesterPayKitProvider>
120
+ );
121
+ }
122
+ ```
123
+
124
+ If your app already owns `TpkExpo.init()`, pass the initialized client
125
+ into `TesterPayKitProvider` instead of `config`.
126
+
127
+ ## What `TpkExpo.init()` does
128
+
129
+ 1. Reads cached anonymous-tester JWT from AsyncStorage (key
130
+ `@testerpaykit/auth`). If the cached entry matches the current
131
+ `projectId` + `testerCode`, reuse it — skip the network round
132
+ trip.
133
+ 2. Otherwise POST `/auth/tester/anonymous` with the
134
+ `{ projectId, testerCode }` pair, store the response, and use
135
+ the returned access token for subsequent submits.
136
+ 3. Starts a real server-side tester session via
137
+ `POST /v1/testers/sessions`. `submitBug()` uses that server
138
+ session id so coordinator session timelines and fair-pay counters
139
+ stay connected.
140
+
141
+ Pass `storage` to use an app-owned persistence adapter (MMKV/SQLite)
142
+ instead of AsyncStorage for auth, queues, and cached crashes:
143
+
144
+ ```tsx
145
+ await TpkExpo.init({
146
+ projectId,
147
+ testerCode,
148
+ storage: myStorageAdapter, // { get, set, remove, keys? }
149
+ });
150
+ ```
151
+
152
+ ## What `submitBug()` does
153
+
154
+ `tpk.submitBug({ title, description, … })`:
155
+
156
+ - Auto-gathers `deviceSnapshot` via `expo-device` (model, manufacturer,
157
+ OS version, isPhysicalDevice) plus `appSnapshot` via
158
+ `expo-application` (app version, build number, bundle id).
159
+ - POSTs to `/v1/testers/me/bug-reports` with all required fields.
160
+ - Returns `{ id, status, createdAt, submittedAt }` from the server.
161
+
162
+ Server-side enum validation:
163
+ - `type` ∈ {bug, crash, uiIssue, performance, featureRequest, generalFeedback}
164
+ - `severity` ∈ {critical, high, medium, low}
165
+ - `category` ∈ {functional, ui, performance, security, compatibility, localization, accessibility}
166
+
167
+ Defaults: `type=bug`, `severity=medium`, `category=functional`.
168
+
169
+ ## Local-first dev
170
+
171
+ Point `apiBaseUrl` at your Mac's LAN IP when developing against the
172
+ local TPK stack. iOS simulator can use `http://localhost:18080`; real
173
+ device needs `http://<mac-lan-ip>:18080` (get via
174
+ `ipconfig getifaddr en0` on macOS).
175
+
176
+ The Flutter SDK's `TPK_LOCAL` flag has the same effect in Bonblick —
177
+ they share the same `tpk` CLI + same Docker stack defined under
178
+ `moinsen-workspace/TesterPayKit/`.
179
+
180
+ Run the package-level local API smoke test when the Docker stack is up:
181
+
182
+ ```bash
183
+ TPK_EXPO_RUN_LOCAL_API=1 \
184
+ TPK_EXPO_API_BASE_URL=http://localhost:18080 \
185
+ pnpm --filter @testerpaykit/expo exec vitest run src/__tests__/local-api.integration.test.ts
186
+ ```
187
+
188
+ ## Feature parity with the Flutter SDK
189
+
190
+ All three tiers ship today. Every peer-optional native module is
191
+ auto-detected at runtime — install only the ones you actually use.
192
+
193
+ ### Tier 1 — wired by `TpkExpo.init()`
194
+
195
+ | Feature | What it does |
196
+ |---|---|
197
+ | Anonymous-tester JWT | First call to `/auth/tester/anonymous`, cached in AsyncStorage |
198
+ | Server sessions | `init()` starts `/v1/testers/sessions`; `endSession()` closes it |
199
+ | `submitBug()` | POSTs `/v1/testers/me/bug-reports` with device + app + breadcrumbs |
200
+ | Breadcrumbs | Ring buffer (default 50) auto-attached to every bug report |
201
+ | `trackScreenView` / `trackTap` / `trackEvent` | Push breadcrumbs and session events |
202
+ | `flushTelemetry()` | POSTs pending timeline data to `/events` and `/breadcrumbs` |
203
+ | Crash handler | Global `ErrorUtils` hook + `unhandledrejection` listener, caches crash context before retry |
204
+ | `getPendingCrashes()` / `flushCachedCrashes()` | Post-crash review and retry surface |
205
+ | Offline queues | Failed bug submits and attachments (5xx / network) queued and retried |
206
+ | Device + app snapshot | Auto-gathered via `expo-device` + `expo-application` |
207
+ | Shake-to-report | `useShake({ onShake })` hook |
208
+
209
+ ### Tier 2 — task fetching, network, screenshots, dashboard
210
+
211
+ | Feature | API | Peer dep |
212
+ |---|---|---|
213
+ | Network capture | enabled by default in `init`; toggle via `captureNetwork: false` | none |
214
+ | Task fetching | `tpk.api.getMyTasks()` / `enrollInProject()` / `unenrollFromProject()` | none |
215
+ | Tester profile + points | `tpk.api.getMyProfile()` / `getMyPoints()` | none |
216
+ | Dashboard hook | `useTpkDashboard(tpk)` → `{tasks, summary, profile, points}` | none |
217
+ | Screenshot capture | `captureView(viewRef)` → base64 PNG | `react-native-view-shot` |
218
+ | Attachment upload | `tpk.attachToBugReport(...)` queues transient failures | `expo-file-system` for file helpers |
219
+
220
+ ### Tier 3 — annotations, recording, earnings
221
+
222
+ | Feature | API | Peer dep |
223
+ |---|---|---|
224
+ | Widget-annotation registry | `<TpkAnnotated task="…" labels={…}>` + `useTaskAnnotation()` + `tpk.annotations.subscribe(…)` | none |
225
+ | Annotated screenshot editor | `<TpkAnnotationOverlay tool="freehand" …>` with `finalize()` → base64 | `react-native-svg`, `react-native-view-shot` |
226
+ | Screen recording | `const rec = new ScreenRecorder(); await rec.start(); await rec.stop()` then `uploadAsAttachment(...)` | `react-native-record-screen`, `expo-file-system` |
227
+ | Voice notes | `VoiceNoteRecorder` wraps Expo Audio recorder output and uploads `voice_note` attachments | `expo-audio`, `expo-file-system` |
228
+ | Earnings summary | `tpk.api.getEarningsSummary()` / `getMyPayouts()` + `useTpkEarnings(tpk)` hook | none |
229
+
230
+ ### Annotated-screenshot example
231
+
232
+ ```tsx
233
+ import {
234
+ captureView, uploadScreenshotAttachment,
235
+ TpkAnnotationOverlay, type TpkAnnotationOverlayHandle,
236
+ } from '@testerpaykit/expo';
237
+
238
+ const rootRef = useRef<View>(null);
239
+ const editor = useRef<TpkAnnotationOverlayHandle>(null);
240
+
241
+ // 1. Capture the screen
242
+ const shot = await captureView(rootRef);
243
+ // 2. Show the editor with `imageUri={`data:image/png;base64,${shot.base64}`}`
244
+ // 3. When the user taps "Send":
245
+ const flat = await editor.current?.finalize();
246
+ const bug = await tpk.submitBug({ title: '...', description: '...' });
247
+ if (flat && bug) await uploadScreenshotAttachment(tpk.api, bug.id, flat);
248
+ ```
249
+
250
+ ### Screen-recording example
251
+
252
+ ```tsx
253
+ import { ScreenRecorder } from '@testerpaykit/expo';
254
+
255
+ const rec = new ScreenRecorder();
256
+ await rec.start({ maxDurationSeconds: 30 });
257
+ // …user reproduces the bug, then taps "Stop"…
258
+ const clip = await rec.stop();
259
+ if (clip) {
260
+ const bug = await tpk.submitBug({ title: '...', description: '...' });
261
+ await rec.uploadAsAttachment(tpk.api, bug.id, clip);
262
+ }
263
+ ```
264
+
265
+ ### Voice-note example
266
+
267
+ ```tsx
268
+ import { RecordingPresets, useAudioRecorder } from 'expo-audio';
269
+ import { VoiceNoteRecorder } from '@testerpaykit/expo';
270
+
271
+ const expoRecorder = useAudioRecorder(RecordingPresets.HIGH_QUALITY);
272
+ const voice = new VoiceNoteRecorder({ recorder: expoRecorder });
273
+
274
+ await voice.start();
275
+ // ...tester describes the bug...
276
+ const note = await voice.stop();
277
+ if (note) {
278
+ const bug = await tpk.submitBug({ title: '...', description: '...' });
279
+ await voice.uploadAsAttachment(tpk.api, bug.id, note);
280
+ }
281
+ ```
282
+
283
+ ## What this package is NOT
284
+
285
+ - **Not** a full console app. The provider, floating button, and
286
+ bug-report sheet are package primitives; app-specific navigation,
287
+ task workflows, and branding stay in your app.
288
+ - **Not** a video-editing tool. Recordings are uploaded as-is; if you
289
+ need trimming or thumbnails do it client-side with `expo-video-thumbnails`
290
+ before calling `uploadAsAttachment`.
@@ -0,0 +1,64 @@
1
+ // src/network.ts
2
+ var DEFAULT_IGNORE = [
3
+ /testerpaykit\.com/i,
4
+ /:18080\b/
5
+ ];
6
+ function installNetworkCapture(options) {
7
+ const { breadcrumbs, ignorePatterns = DEFAULT_IGNORE, recordSizes = true } = options;
8
+ const original = globalThis.fetch?.bind(globalThis);
9
+ if (typeof original !== "function") {
10
+ return () => {
11
+ };
12
+ }
13
+ const wrapped = async (input, init) => {
14
+ const startedAt = Date.now();
15
+ const method = (init?.method ?? "GET").toUpperCase();
16
+ const urlString = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
17
+ if (shouldIgnore(urlString, ignorePatterns)) {
18
+ return original(input, init);
19
+ }
20
+ try {
21
+ const response = await original(input, init);
22
+ const durationMs = Date.now() - startedAt;
23
+ const sizeHint = recordSizes ? Number(response.headers.get("content-length")) || void 0 : void 0;
24
+ breadcrumbs.record({
25
+ action: "http",
26
+ target: `${method} ${shortenUrl(urlString)}`,
27
+ data: {
28
+ status: response.status,
29
+ durationMs,
30
+ ...sizeHint != null && { bytes: sizeHint }
31
+ }
32
+ });
33
+ return response;
34
+ } catch (e) {
35
+ const durationMs = Date.now() - startedAt;
36
+ breadcrumbs.record({
37
+ action: "http",
38
+ target: `${method} ${shortenUrl(urlString)}`,
39
+ data: {
40
+ error: e instanceof Error ? e.message : String(e),
41
+ durationMs
42
+ }
43
+ });
44
+ throw e;
45
+ }
46
+ };
47
+ globalThis.fetch = wrapped;
48
+ return () => {
49
+ globalThis.fetch = original;
50
+ };
51
+ }
52
+ function shouldIgnore(url, patterns) {
53
+ return patterns.some((p) => p.test(url));
54
+ }
55
+ function shortenUrl(url) {
56
+ let stripped = url;
57
+ const q = url.indexOf("?");
58
+ if (q !== -1) stripped = url.slice(0, q);
59
+ return stripped.length > 80 ? `${stripped.slice(0, 79)}\u2026` : stripped;
60
+ }
61
+
62
+ export {
63
+ installNetworkCapture
64
+ };