yaver-feedback-react-native 0.5.2 → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +8 -0
  2. package/dist/AuthOverlay.d.ts +16 -0
  3. package/dist/AuthOverlay.js +104 -0
  4. package/dist/BlackBox.d.ts +154 -0
  5. package/dist/BlackBox.js +395 -0
  6. package/dist/ConnectionScreen.d.ts +13 -0
  7. package/dist/ConnectionScreen.js +373 -0
  8. package/dist/Discovery.d.ts +59 -0
  9. package/dist/Discovery.js +293 -0
  10. package/dist/FeedbackModal.d.ts +11 -0
  11. package/dist/FeedbackModal.js +623 -0
  12. package/dist/FixReport.d.ts +23 -0
  13. package/dist/FixReport.js +282 -0
  14. package/dist/FloatingButton.d.ts +71 -0
  15. package/dist/FloatingButton.js +778 -0
  16. package/dist/LoginScreen.d.ts +14 -0
  17. package/dist/LoginScreen.js +317 -0
  18. package/dist/MachinePickerScreen.d.ts +19 -0
  19. package/dist/MachinePickerScreen.js +175 -0
  20. package/dist/P2PClient.d.ts +136 -0
  21. package/dist/P2PClient.js +357 -0
  22. package/dist/ShakeDetector.d.ts +39 -0
  23. package/dist/ShakeDetector.js +111 -0
  24. package/dist/YaverFeedback.d.ts +198 -0
  25. package/dist/YaverFeedback.js +679 -0
  26. package/dist/YaverUpdates.d.ts +78 -0
  27. package/dist/YaverUpdates.js +272 -0
  28. package/dist/__tests__/Discovery.test.d.ts +1 -0
  29. package/dist/__tests__/Discovery.test.js +164 -0
  30. package/dist/__tests__/P2PClient.test.d.ts +1 -0
  31. package/dist/__tests__/P2PClient.test.js +169 -0
  32. package/dist/__tests__/SDKToken.test.d.ts +1 -0
  33. package/dist/__tests__/SDKToken.test.js +215 -0
  34. package/dist/__tests__/YaverFeedback.test.d.ts +1 -0
  35. package/dist/__tests__/YaverFeedback.test.js +161 -0
  36. package/dist/__tests__/types.test.d.ts +1 -0
  37. package/dist/__tests__/types.test.js +219 -0
  38. package/dist/auth.d.ts +105 -0
  39. package/dist/auth.js +282 -0
  40. package/dist/capture.d.ts +27 -0
  41. package/dist/capture.js +74 -0
  42. package/dist/expo.d.ts +15 -0
  43. package/dist/expo.js +62 -0
  44. package/dist/index.d.ts +48 -0
  45. package/dist/index.js +80 -0
  46. package/dist/types.d.ts +282 -0
  47. package/dist/types.js +2 -0
  48. package/dist/upload.d.ts +13 -0
  49. package/dist/upload.js +59 -0
  50. package/package.json +10 -6
@@ -0,0 +1,679 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.YaverFeedback = void 0;
4
+ const Discovery_1 = require("./Discovery");
5
+ const BlackBox_1 = require("./BlackBox");
6
+ const P2PClient_1 = require("./P2PClient");
7
+ const ShakeDetector_1 = require("./ShakeDetector");
8
+ const auth_1 = require("./auth");
9
+ let config = null;
10
+ let enabled = false;
11
+ let p2pClient = null;
12
+ let shakeDetector = null;
13
+ /** Ring buffer of captured errors. */
14
+ let errorBuffer = [];
15
+ let maxErrors = 5;
16
+ /** Track whether BlackBox was running before disable (to restart on enable). */
17
+ let blackBoxWasStreaming = false;
18
+ /**
19
+ * Flag evaluation cache — 30s TTL per `userId|key`. Prevents a
20
+ * tight render loop from hammering /flags/eval when the dev calls
21
+ * `YaverFeedback.getFlag()` every frame.
22
+ */
23
+ const flagCache = new Map();
24
+ /**
25
+ * Main entry point for the Yaver Feedback SDK.
26
+ * Call `YaverFeedback.init()` once at app startup.
27
+ */
28
+ class YaverFeedback {
29
+ /**
30
+ * Initialize the feedback SDK with the given configuration.
31
+ * Typically called in your app's root component or entry file.
32
+ *
33
+ * If no `agentUrl` is provided, the SDK will attempt auto-discovery
34
+ * via `YaverDiscovery` on the first `startReport()` call.
35
+ */
36
+ static init(cfg) {
37
+ config = {
38
+ trigger: 'shake',
39
+ maxRecordingDuration: 120,
40
+ feedbackMode: 'batch',
41
+ agentCommentaryLevel: 0,
42
+ autoLogin: true,
43
+ ...cfg,
44
+ };
45
+ // Route the in-SDK login screen to prod yaver.io by default; callers may
46
+ // override for staging via authConvexSiteUrl / authWebBaseUrl.
47
+ (0, auth_1.configureAuthEndpoints)({
48
+ convexSiteUrl: cfg.authConvexSiteUrl,
49
+ webBaseUrl: cfg.authWebBaseUrl,
50
+ });
51
+ // If no explicit convexUrl was set but we have an auth site URL, use it
52
+ // so Discovery.discoverFromConvex() has somewhere to look up the user's
53
+ // machines (works for both LAN-direct and off-LAN relay paths).
54
+ if (!config.convexUrl) {
55
+ config.convexUrl = cfg.authConvexSiteUrl ?? auth_1.DEFAULT_CONVEX_SITE_URL;
56
+ }
57
+ // Default: enabled only in dev mode
58
+ if (cfg.enabled !== undefined) {
59
+ enabled = cfg.enabled;
60
+ }
61
+ else {
62
+ enabled = typeof __DEV__ !== 'undefined' ? __DEV__ : false;
63
+ }
64
+ // Hydrate cached auth token + preferred device from AsyncStorage so the
65
+ // SDK reconnects silently on subsequent launches. If autoLogin is false
66
+ // the caller is responsible for providing authToken themselves.
67
+ if (config.autoLogin !== false && enabled) {
68
+ void YaverFeedback.hydrateSession();
69
+ }
70
+ // Create P2P client if we have a URL
71
+ if (config.agentUrl) {
72
+ p2pClient = new P2PClient_1.P2PClient(config.agentUrl, config.authToken ?? '');
73
+ }
74
+ else {
75
+ p2pClient = null;
76
+ // Auto-discover agent in the background when convexUrl or LAN is available
77
+ if (enabled && (config.authToken || config.preferredDeviceId)) {
78
+ YaverFeedback.discoverAgent();
79
+ }
80
+ }
81
+ // Set up error capture buffer size
82
+ maxErrors = cfg.maxCapturedErrors ?? 5;
83
+ errorBuffer = [];
84
+ // Wire up shake detection when trigger is 'shake'
85
+ if (shakeDetector) {
86
+ shakeDetector.stop();
87
+ shakeDetector = null;
88
+ }
89
+ if (enabled && config.trigger === 'shake') {
90
+ shakeDetector = new ShakeDetector_1.ShakeDetector();
91
+ shakeDetector.start(() => {
92
+ if (config?.reportingOnly) {
93
+ YaverFeedback.sendAutoReport();
94
+ }
95
+ else {
96
+ YaverFeedback.startReport();
97
+ }
98
+ });
99
+ }
100
+ // Wire up BlackBox command handlers for reload signals from the agent.
101
+ // This enables the vibe coder to trigger reload from the Yaver mobile app
102
+ // and have the third-party app (with this SDK) automatically reload.
103
+ if (enabled) {
104
+ BlackBox_1.BlackBox.onCommand((cmd) => {
105
+ if (cmd.command === 'reload') {
106
+ if (cfg.onReload) {
107
+ cfg.onReload();
108
+ }
109
+ else {
110
+ YaverFeedback.defaultReload();
111
+ }
112
+ }
113
+ else if (cmd.command === 'reload_bundle' && cmd.data) {
114
+ const bundleUrl = cmd.data.bundleUrl;
115
+ const assetsUrl = cmd.data.assetsUrl;
116
+ if (cfg.onReloadBundle) {
117
+ cfg.onReloadBundle(bundleUrl, assetsUrl);
118
+ }
119
+ else {
120
+ YaverFeedback.defaultReloadBundle(bundleUrl, assetsUrl);
121
+ }
122
+ }
123
+ });
124
+ }
125
+ // NOTE: We intentionally do NOT hook ErrorUtils.setGlobalHandler().
126
+ // Sentry, Crashlytics, Bugsnag, and other tools all compete for that
127
+ // single slot. Hijacking it would break whichever tool the developer
128
+ // already has installed, depending on init order.
129
+ //
130
+ // Instead, developers use:
131
+ // - YaverFeedback.attachError(err) in catch blocks
132
+ // - YaverFeedback.wrapErrorHandler(existingHandler) to create a
133
+ // pass-through wrapper they insert into their own error chain
134
+ }
135
+ /**
136
+ * Run agent discovery in the background.
137
+ * Called automatically from init() when no agentUrl is provided.
138
+ * Sets config.agentUrl and creates P2PClient on success.
139
+ */
140
+ static async discoverAgent() {
141
+ if (!config || !enabled)
142
+ return;
143
+ if (config.agentUrl)
144
+ return; // already have a URL
145
+ if (!config.authToken)
146
+ return; // need auth before discovery can succeed
147
+ try {
148
+ const result = await Discovery_1.YaverDiscovery.discover({
149
+ convexUrl: config.convexUrl,
150
+ authToken: config.authToken,
151
+ preferredDeviceId: config.preferredDeviceId,
152
+ });
153
+ if (result && config) {
154
+ config.agentUrl = result.url;
155
+ p2pClient = new P2PClient_1.P2PClient(result.url, config.authToken ?? '');
156
+ }
157
+ }
158
+ catch {
159
+ // Discovery failed — FloatingButton will show disconnected, user can retry
160
+ }
161
+ }
162
+ /**
163
+ * Pull a cached session token + selected device from AsyncStorage (populated
164
+ * by the in-SDK login + machine-picker screens). When present the SDK can
165
+ * reconnect silently on launch without re-prompting the user. Safe to call
166
+ * multiple times — it only overrides values the caller did not already set.
167
+ */
168
+ static async hydrateSession() {
169
+ if (!config)
170
+ return;
171
+ try {
172
+ if (!config.authToken) {
173
+ const cached = await (0, auth_1.getToken)();
174
+ if (cached) {
175
+ config.authToken = cached;
176
+ }
177
+ }
178
+ if (!config.preferredDeviceId) {
179
+ const cachedDevice = await (0, auth_1.getSelectedDeviceId)();
180
+ if (cachedDevice) {
181
+ config.preferredDeviceId = cachedDevice;
182
+ }
183
+ }
184
+ if (config.authToken && !config.agentUrl) {
185
+ await YaverFeedback.discoverAgent();
186
+ }
187
+ }
188
+ catch {
189
+ // hydration best-effort
190
+ }
191
+ }
192
+ /**
193
+ * Update the signed-in session token (e.g. after the in-SDK login screen
194
+ * succeeds). Rebuilds the P2P client and kicks off agent discovery.
195
+ */
196
+ static async setAuthToken(token) {
197
+ if (!config)
198
+ return;
199
+ config.authToken = token;
200
+ if (config.agentUrl) {
201
+ p2pClient = new P2PClient_1.P2PClient(config.agentUrl, token);
202
+ }
203
+ else {
204
+ await YaverFeedback.discoverAgent();
205
+ }
206
+ }
207
+ /** Returns true once the SDK has a session token it can use. */
208
+ static isAuthed() {
209
+ return Boolean(config?.authToken);
210
+ }
211
+ /**
212
+ * Request the embedded FeedbackModal to show the login screen. Works by
213
+ * emitting an event the modal listens for — avoids forcing the host app
214
+ * to mount a second navigator.
215
+ */
216
+ static showLogin() {
217
+ const { DeviceEventEmitter } = require('react-native');
218
+ DeviceEventEmitter.emit('yaverFeedback:startLogin');
219
+ }
220
+ /**
221
+ * Request the embedded FeedbackModal to show the machine picker. Requires
222
+ * an active session; no-ops otherwise.
223
+ */
224
+ static showMachinePicker() {
225
+ if (!YaverFeedback.isAuthed())
226
+ return;
227
+ const { DeviceEventEmitter } = require('react-native');
228
+ DeviceEventEmitter.emit('yaverFeedback:startMachinePicker');
229
+ }
230
+ /**
231
+ * Update the selected remote device. Resets the cached agent URL so the
232
+ * next `startReport()` (or FloatingButton press) rediscovers against the
233
+ * newly-selected machine.
234
+ */
235
+ static async setPreferredDevice(deviceId) {
236
+ if (!config)
237
+ return;
238
+ config.preferredDeviceId = deviceId;
239
+ config.agentUrl = undefined;
240
+ p2pClient = null;
241
+ await YaverFeedback.discoverAgent();
242
+ }
243
+ /**
244
+ * Sign out: clear cached token + device, tear down the P2P client. The
245
+ * SDK stays enabled; the next feedback trigger will re-prompt for login.
246
+ */
247
+ static async signOut() {
248
+ await (0, auth_1.clearToken)();
249
+ await (0, auth_1.clearSelectedDeviceId)();
250
+ if (config) {
251
+ config.authToken = undefined;
252
+ config.preferredDeviceId = undefined;
253
+ config.agentUrl = undefined;
254
+ }
255
+ p2pClient = null;
256
+ }
257
+ /**
258
+ * Manually trigger the feedback collection flow.
259
+ * Opens the feedback modal if the SDK is initialized and enabled.
260
+ *
261
+ * If no agentUrl was configured, runs auto-discovery first.
262
+ */
263
+ static async startReport() {
264
+ if (!config) {
265
+ console.warn('[YaverFeedback] SDK not initialized. Call YaverFeedback.init() first.');
266
+ return;
267
+ }
268
+ if (!enabled) {
269
+ return;
270
+ }
271
+ // If the caller has autoLogin enabled and we have no session yet, show
272
+ // the in-SDK login flow instead of a failing discovery + warning spam.
273
+ if (!config.authToken) {
274
+ if (config.autoLogin !== false) {
275
+ await YaverFeedback.hydrateSession();
276
+ }
277
+ if (!config.authToken) {
278
+ YaverFeedback.showLogin();
279
+ return;
280
+ }
281
+ }
282
+ // Auto-discover if no agent URL was provided
283
+ if (!config.agentUrl) {
284
+ try {
285
+ const result = await Discovery_1.YaverDiscovery.discover({
286
+ convexUrl: config.convexUrl,
287
+ authToken: config.authToken,
288
+ preferredDeviceId: config.preferredDeviceId,
289
+ });
290
+ if (result) {
291
+ config.agentUrl = result.url;
292
+ p2pClient = new P2PClient_1.P2PClient(result.url, config.authToken ?? '');
293
+ }
294
+ else if (config.autoLogin !== false && !config.preferredDeviceId) {
295
+ // No agent discovered and no device picked yet — prompt the user
296
+ // to pick one of their machines (handles the non-LAN case where
297
+ // relay discovery requires knowing which deviceId to target).
298
+ YaverFeedback.showMachinePicker();
299
+ return;
300
+ }
301
+ else {
302
+ console.warn('[YaverFeedback] No agent found. Check that `yaver serve` is running on the selected machine.');
303
+ }
304
+ }
305
+ catch (err) {
306
+ console.warn('[YaverFeedback] Auto-discovery failed:', err);
307
+ }
308
+ }
309
+ // Emit event that the FeedbackModal listens for
310
+ const { DeviceEventEmitter } = require('react-native');
311
+ DeviceEventEmitter.emit('yaverFeedback:startReport');
312
+ }
313
+ /** Returns true if the SDK has been initialized. */
314
+ static isInitialized() {
315
+ return config !== null;
316
+ }
317
+ /**
318
+ * Enable or disable the entire feedback SDK at runtime.
319
+ *
320
+ * **Disable (false):**
321
+ * - Stops BlackBox streaming (flushes remaining events first)
322
+ * - Restores console.log/warn/error if wrapped
323
+ * - Clears error buffer
324
+ * - All methods become no-ops (attachError, wrapErrorHandler still safe to call but do nothing)
325
+ * - P2P client is kept alive (no reconnection cost on re-enable)
326
+ *
327
+ * **Enable (true):**
328
+ * - Restarts BlackBox streaming if it was running before disable
329
+ * - Error buffer starts collecting again
330
+ * - All methods become active
331
+ */
332
+ static setEnabled(value) {
333
+ if (enabled === value)
334
+ return; // No-op if already in desired state
335
+ if (!value) {
336
+ // === DISABLE ===
337
+ blackBoxWasStreaming = BlackBox_1.BlackBox.isStreaming;
338
+ if (BlackBox_1.BlackBox.isStreaming) {
339
+ BlackBox_1.BlackBox.stop(); // flush + stop timer + unwrap console
340
+ }
341
+ BlackBox_1.BlackBox.unwrapConsole(); // ensure console is restored even if BlackBox wasn't started
342
+ errorBuffer = [];
343
+ if (shakeDetector) {
344
+ shakeDetector.stop();
345
+ shakeDetector = null;
346
+ }
347
+ }
348
+ else {
349
+ // === ENABLE ===
350
+ if (blackBoxWasStreaming) {
351
+ BlackBox_1.BlackBox.start(); // restart with previous config
352
+ }
353
+ // Restart shake detector if trigger is 'shake'
354
+ if (config?.trigger === 'shake' && !shakeDetector) {
355
+ shakeDetector = new ShakeDetector_1.ShakeDetector();
356
+ shakeDetector.start(() => {
357
+ if (config?.reportingOnly) {
358
+ YaverFeedback.sendAutoReport();
359
+ }
360
+ else {
361
+ YaverFeedback.startReport();
362
+ }
363
+ });
364
+ }
365
+ }
366
+ enabled = value;
367
+ }
368
+ /** Returns whether the SDK is currently enabled. */
369
+ static isEnabled() {
370
+ return enabled;
371
+ }
372
+ /** Returns the current config, or null if not initialized. */
373
+ static getConfig() {
374
+ return config;
375
+ }
376
+ /**
377
+ * Manually attach an error with optional metadata.
378
+ * Use this in catch blocks to give the agent extra context.
379
+ */
380
+ static attachError(error, metadata) {
381
+ if (!enabled)
382
+ return; // No-op when disabled
383
+ const captured = {
384
+ message: error.message,
385
+ stack: (error.stack ?? '').split('\n').filter((l) => l.trim()),
386
+ isFatal: false,
387
+ timestamp: Date.now(),
388
+ metadata,
389
+ };
390
+ errorBuffer.push(captured);
391
+ if (errorBuffer.length > maxErrors) {
392
+ errorBuffer.shift();
393
+ }
394
+ }
395
+ /**
396
+ * Returns the current captured errors buffer.
397
+ * Called internally when building a FeedbackBundle.
398
+ */
399
+ static getCapturedErrors() {
400
+ return [...errorBuffer];
401
+ }
402
+ /** Clears the captured errors buffer. */
403
+ static clearCapturedErrors() {
404
+ errorBuffer = [];
405
+ }
406
+ /**
407
+ * Returns a pass-through error handler that records the error in Yaver's
408
+ * buffer and then calls `next`. Use this to insert Yaver into your
409
+ * existing error handler chain without replacing anything.
410
+ *
411
+ * @example
412
+ * // Works alongside Sentry, Crashlytics, or any other tool:
413
+ * const originalHandler = ErrorUtils.getGlobalHandler();
414
+ * ErrorUtils.setGlobalHandler(
415
+ * YaverFeedback.wrapErrorHandler(originalHandler)
416
+ * );
417
+ * // Sentry can still be initialized after this — it will wrap our
418
+ * // wrapper, and the chain stays intact.
419
+ */
420
+ static wrapErrorHandler(next) {
421
+ return (error, isFatal) => {
422
+ YaverFeedback.attachError(error);
423
+ if (errorBuffer.length > 0) {
424
+ errorBuffer[errorBuffer.length - 1].isFatal = isFatal ?? false;
425
+ }
426
+ next?.(error, isFatal);
427
+ };
428
+ }
429
+ /**
430
+ * Returns the P2P client instance.
431
+ * Available after init if agentUrl is set, or after first successful discovery.
432
+ */
433
+ static getP2PClient() {
434
+ return p2pClient;
435
+ }
436
+ /** Returns the current feedback mode. */
437
+ static getFeedbackMode() {
438
+ return config?.feedbackMode ?? 'batch';
439
+ }
440
+ /** Returns the agent commentary level (0-10). */
441
+ static getCommentaryLevel() {
442
+ return config?.agentCommentaryLevel ?? 0;
443
+ }
444
+ // ─── One-stop SaaS replacement methods ─────────────────────────
445
+ //
446
+ // These are the three solo-dev SaaS-replacement entry points
447
+ // wired into YaverFeedback so there's exactly one import path
448
+ // for the dev's app code: track / getFlag / checkUpdate.
449
+ /**
450
+ * Record a business event. Routes through BlackBox so the agent
451
+ * persists it to the analytics ledger (no dashboards — export
452
+ * via CSV or webhook into PostHog).
453
+ *
454
+ * @example
455
+ * ```ts
456
+ * YaverFeedback.track('purchase_completed', { amount: '9.99' });
457
+ * ```
458
+ */
459
+ static track(name, props, route) {
460
+ if (!enabled)
461
+ return;
462
+ BlackBox_1.BlackBox.track(name, props, route);
463
+ }
464
+ /**
465
+ * Evaluate a single feature flag for a user. Results are cached
466
+ * for 30 seconds inside YaverFeedback so a tight loop evaluating
467
+ * the same key doesn't hammer the agent.
468
+ *
469
+ * @param key — flag key (must exist on the agent)
470
+ * @param defaultValue — returned if the flag is missing / offline
471
+ * @param userId — stable user identifier for rollout bucketing
472
+ */
473
+ static async getFlag(key, defaultValue, userId = 'anonymous') {
474
+ if (!enabled || !p2pClient)
475
+ return defaultValue;
476
+ const cacheKey = `${userId}|${key}`;
477
+ const now = Date.now();
478
+ const cached = flagCache.get(cacheKey);
479
+ if (cached && now - cached.at < 30000) {
480
+ return cached.value ?? defaultValue;
481
+ }
482
+ try {
483
+ const val = await p2pClient.flagsEvaluateOne(key, userId);
484
+ flagCache.set(cacheKey, { value: val ?? defaultValue, at: now });
485
+ return val ?? defaultValue;
486
+ }
487
+ catch {
488
+ return defaultValue;
489
+ }
490
+ }
491
+ /**
492
+ * Bulk evaluate every flag for a user. Cached on the same 30s
493
+ * window as getFlag — use this when boot needs a handful of
494
+ * flags in one roundtrip.
495
+ */
496
+ static async getFlags(userId = 'anonymous') {
497
+ if (!enabled || !p2pClient)
498
+ return {};
499
+ const cacheKey = `all|${userId}`;
500
+ const now = Date.now();
501
+ const cached = flagCache.get(cacheKey);
502
+ if (cached && now - cached.at < 30000) {
503
+ return cached.value ?? {};
504
+ }
505
+ try {
506
+ const flags = await p2pClient.flagsEvaluate(userId);
507
+ flagCache.set(cacheKey, { value: flags, at: now });
508
+ return flags;
509
+ }
510
+ catch {
511
+ return {};
512
+ }
513
+ }
514
+ /**
515
+ * Ask what bundle this device should run. Returns the latest
516
+ * release manifest in the configured channel plus a rollout
517
+ * gate. The dev can then compare against what's currently
518
+ * running and prompt the user to reload.
519
+ *
520
+ * On-disk bundle swap is platform-specific — see
521
+ * `YaverFeedback.onUpdateAvailable` if you want a hook.
522
+ */
523
+ static async checkUpdate(channel = 'production', deviceId) {
524
+ if (!enabled || !p2pClient)
525
+ return null;
526
+ return p2pClient.releasesLatest(channel, deviceId);
527
+ }
528
+ /** Clear the in-memory flag cache. Useful for tests or after sign-out. */
529
+ static clearFlagCache() {
530
+ flagCache.clear();
531
+ }
532
+ /**
533
+ * Reporting-only mode: auto-capture screenshot + errors and send
534
+ * to the agent's /feedback endpoint. No modal UI — just shake and go.
535
+ *
536
+ * This is triggered by shake when `reportingOnly: true` is set.
537
+ * The agent receives the report via the same P2P channel and logs it.
538
+ */
539
+ static async sendAutoReport() {
540
+ if (!config || !enabled)
541
+ return;
542
+ // Resolve agent URL if needed
543
+ if (!config.agentUrl) {
544
+ try {
545
+ const result = await Discovery_1.YaverDiscovery.discover({
546
+ convexUrl: config.convexUrl,
547
+ authToken: config.authToken,
548
+ preferredDeviceId: config.preferredDeviceId,
549
+ });
550
+ if (result) {
551
+ config.agentUrl = result.url;
552
+ p2pClient = new P2PClient_1.P2PClient(result.url, config.authToken ?? '');
553
+ }
554
+ }
555
+ catch { }
556
+ }
557
+ if (!config.agentUrl) {
558
+ console.warn('[YaverFeedback] No agent URL — cannot send auto report.');
559
+ return;
560
+ }
561
+ try {
562
+ const { Platform, Dimensions } = require('react-native');
563
+ const { captureScreenshot } = require('./capture');
564
+ const { uploadFeedback } = require('./upload');
565
+ const { width, height } = Dimensions.get('window');
566
+ // Auto-capture screenshot
567
+ let screenshotPath;
568
+ try {
569
+ screenshotPath = await captureScreenshot();
570
+ }
571
+ catch {
572
+ // Screenshot capture may fail (e.g. no view ref) — continue without it
573
+ }
574
+ const bundle = {
575
+ metadata: {
576
+ timestamp: new Date().toISOString(),
577
+ device: {
578
+ platform: Platform.OS,
579
+ osVersion: String(Platform.Version),
580
+ model: Platform.OS === 'ios' ? 'iOS Device' : 'Android Device',
581
+ screenWidth: width,
582
+ screenHeight: height,
583
+ },
584
+ app: {},
585
+ userNote: '[Auto-report via shake]',
586
+ },
587
+ screenshots: screenshotPath ? [screenshotPath] : [],
588
+ errors: errorBuffer.length > 0 ? [...errorBuffer] : undefined,
589
+ };
590
+ await uploadFeedback(config.agentUrl, config.authToken ?? '', bundle);
591
+ console.log('[YaverFeedback] Auto-report sent');
592
+ }
593
+ catch (err) {
594
+ console.warn('[YaverFeedback] Auto-report failed:', err);
595
+ }
596
+ }
597
+ /**
598
+ * Default reload handler. Tries three strategies in order:
599
+ *
600
+ * 1. **YaverBundleLoader** — running inside Yaver's native container.
601
+ * Pulls fresh Hermes bundle from agent and reloads the RN bridge.
602
+ *
603
+ * 2. **YaverHotReload** — standalone app with feedback SDK's native module
604
+ * (added via Expo config plugin). Downloads Hermes bundle from agent,
605
+ * saves to Documents, and reloads the RN bridge.
606
+ *
607
+ * 3. **DevSettings.reload()** — standalone dev build connected to Metro.
608
+ */
609
+ static defaultReload() {
610
+ if (!config?.agentUrl)
611
+ return;
612
+ const bundleUrl = `${config.agentUrl}/dev/native-bundle`;
613
+ const headers = { Authorization: `Bearer ${config.authToken ?? ''}` };
614
+ YaverFeedback.loadBundleAndReload(bundleUrl, headers);
615
+ }
616
+ /**
617
+ * Default reload_bundle handler. Receives a compiled Hermes bundle URL
618
+ * from the agent and loads it via the best available native mechanism.
619
+ */
620
+ static defaultReloadBundle(bundleUrl, _assetsUrl) {
621
+ if (!config?.agentUrl)
622
+ return;
623
+ const fullUrl = bundleUrl.startsWith('http')
624
+ ? bundleUrl
625
+ : `${config.agentUrl}${bundleUrl}`;
626
+ const headers = { Authorization: `Bearer ${config.authToken ?? ''}` };
627
+ YaverFeedback.loadBundleAndReload(fullUrl, headers);
628
+ }
629
+ /**
630
+ * Core bundle reload logic. Tries native loaders in order:
631
+ *
632
+ * 1. YaverBundleLoader (Yaver container — full validation + bridge reload)
633
+ * 2. YaverHotReload (SDK's own native module — download + bridge reload)
634
+ * 3. DevSettings.reload() (Metro dev server fallback)
635
+ */
636
+ static loadBundleAndReload(bundleUrl, headers) {
637
+ const { NativeModules } = require('react-native');
638
+ // Strategy 1: YaverBundleLoader (running inside Yaver container)
639
+ if (NativeModules.YaverBundleLoader) {
640
+ NativeModules.YaverBundleLoader.loadBundle(bundleUrl, 'main', headers)
641
+ .catch((err) => {
642
+ console.warn('[YaverFeedback] YaverBundleLoader reload failed:', err);
643
+ });
644
+ return;
645
+ }
646
+ // Strategy 2: YaverHotReload (SDK's native module, added by Expo config plugin)
647
+ if (NativeModules.YaverHotReload) {
648
+ NativeModules.YaverHotReload.loadBundle(bundleUrl, headers)
649
+ .catch((err) => {
650
+ console.warn('[YaverFeedback] YaverHotReload reload failed:', err);
651
+ });
652
+ return;
653
+ }
654
+ // Strategy 3: DevSettings.reload() for Metro dev builds
655
+ console.warn('[YaverFeedback] No native bundle loader available. ' +
656
+ 'Add "yaver-feedback-react-native" to your app.json plugins to enable hot reload.');
657
+ try {
658
+ const { DevSettings } = require('react-native');
659
+ if (typeof DevSettings?.reload === 'function') {
660
+ DevSettings.reload();
661
+ }
662
+ }
663
+ catch {
664
+ // Not in dev mode
665
+ }
666
+ }
667
+ /** Tear down the SDK (stop shake detector, clear state). */
668
+ static destroy() {
669
+ if (shakeDetector) {
670
+ shakeDetector.stop();
671
+ shakeDetector = null;
672
+ }
673
+ enabled = false;
674
+ config = null;
675
+ p2pClient = null;
676
+ errorBuffer = [];
677
+ }
678
+ }
679
+ exports.YaverFeedback = YaverFeedback;