sentry-miniapp 1.11.2 → 1.12.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.
Files changed (41) hide show
  1. package/README.en.md +83 -390
  2. package/README.md +83 -400
  3. package/dist/sentry-miniapp.cjs.js +13 -6
  4. package/dist/sentry-miniapp.cjs.js.map +1 -1
  5. package/dist/sentry-miniapp.esm.js +1680 -1507
  6. package/dist/sentry-miniapp.esm.js.map +1 -1
  7. package/dist/sentry-miniapp.umd.js +13 -6
  8. package/dist/sentry-miniapp.umd.js.map +1 -1
  9. package/dist/types/appLifecycle.d.ts +27 -0
  10. package/dist/types/appLifecycle.d.ts.map +1 -0
  11. package/dist/types/client.d.ts +5 -1
  12. package/dist/types/client.d.ts.map +1 -1
  13. package/dist/types/crossPlatform.d.ts +0 -4
  14. package/dist/types/crossPlatform.d.ts.map +1 -1
  15. package/dist/types/index.d.ts +1 -1
  16. package/dist/types/index.d.ts.map +1 -1
  17. package/dist/types/integrations/httpcontext.d.ts +0 -8
  18. package/dist/types/integrations/httpcontext.d.ts.map +1 -1
  19. package/dist/types/integrations/index.d.ts +2 -0
  20. package/dist/types/integrations/index.d.ts.map +1 -1
  21. package/dist/types/integrations/minigame-framerate.d.ts +9 -0
  22. package/dist/types/integrations/minigame-framerate.d.ts.map +1 -1
  23. package/dist/types/integrations/networkstatus.d.ts +1 -0
  24. package/dist/types/integrations/networkstatus.d.ts.map +1 -1
  25. package/dist/types/integrations/pagebreadcrumbs.d.ts +6 -4
  26. package/dist/types/integrations/pagebreadcrumbs.d.ts.map +1 -1
  27. package/dist/types/integrations/router.d.ts +6 -1
  28. package/dist/types/integrations/router.d.ts.map +1 -1
  29. package/dist/types/integrations/session.d.ts +9 -8
  30. package/dist/types/integrations/session.d.ts.map +1 -1
  31. package/dist/types/integrations/system.d.ts +6 -1
  32. package/dist/types/integrations/system.d.ts.map +1 -1
  33. package/dist/types/polyfills.d.ts.map +1 -1
  34. package/dist/types/sdk.d.ts +0 -12
  35. package/dist/types/sdk.d.ts.map +1 -1
  36. package/dist/types/transports/offlineStore.d.ts +1 -1
  37. package/dist/types/transports/offlineStore.d.ts.map +1 -1
  38. package/dist/types/types.d.ts +33 -2
  39. package/dist/types/types.d.ts.map +1 -1
  40. package/dist/types/version.d.ts +1 -1
  41. package/package.json +9 -6
package/README.en.md CHANGED
@@ -11,25 +11,27 @@
11
11
 
12
12
  [简体中文](./README.md) | English
13
13
 
14
- > **📖 Documentation**: [https://sentry-miniapp.pages.dev/](https://sentry-miniapp.pages.dev/) — getting started, capability matrix, FAQ, Source Map setup, and examples, with nav and search. (Chinese for now)
15
-
16
14
  A **mini program monitoring SDK** built on `@sentry/core`, providing **error monitoring**, **performance monitoring**, offline caching, and distributed tracing. Supports WeChat, Alipay, ByteDance, Baidu, QQ, DingTalk, Kuaishou mini programs, **WeChat / Douyin mini games**, and cross-platform frameworks (Taro / uni-app).
17
15
 
18
- > **What are Mini Programs?** Mini programs (小程序) are lightweight apps that run inside super-apps like WeChat, Alipay, and ByteDance/Douyin. They form a massive ecosystem in China with **hundreds of millions of daily active users**, but have no direct equivalent in the Western tech stack. Think of them as a hybrid between PWAs and native apps, but hosted within a platform's sandbox.
16
+ > **What are Mini Programs?** Mini programs (小程序) are lightweight apps that run inside super-apps like WeChat, Alipay, and ByteDance/Douyin. They form a massive ecosystem in China with **hundreds of millions of daily active users**, but have no direct equivalent in the Western stack think of them as a hybrid of PWAs and native apps, hosted within a platform's sandbox.
17
+
18
+ > **📖 Full docs live on the documentation site**: [sentry-miniapp.pages.dev](https://sentry-miniapp.pages.dev/) — getting started, capability matrix, per-framework setup, FAQ, Source Map config, and examples, with nav and search (Chinese for now). This README is a quick overview and entry point.
19
19
 
20
20
  > **📰 Featured Article (Chinese)**: [《我给 Sentry 提了个 PR,后来 sentry-miniapp 进了官方文档》](https://juejin.cn/post/7636106283963760681) — How sentry-miniapp got listed in Sentry's official community-supported SDKs documentation. If you find this project useful, please consider giving it a ⭐ Star.
21
21
 
22
22
  <details>
23
- <summary><b>🆕 What's New: v1.3 → v1.8 (click to expand)</b></summary>
23
+ <summary><b>🆕 What's New: v1.3 → v1.11 (click to expand)</b></summary>
24
24
 
25
25
  | Version | Highlights |
26
26
  |---|---|
27
+ | **v1.11** | Mini-game performance data reported as **independent transactions** (Sentry Performance page); API requests reported as `http.client` spans; launched the [documentation site](https://sentry-miniapp.pages.dev/), added Taro / uni-app examples and a [two-layer Source Map merge script](./scripts/merge-sourcemap.mjs) |
28
+ | **v1.10** | 🎮 **Mini game support**: auto-detects mini-game environments; adds cold-start first-frame timing and frame-rate / jank (FPS) monitoring |
27
29
  | **v1.8.0** | AI-assisted integration skill — auto onboarding via Claude Code / Cursor |
28
30
  | **v1.7.0** | New `tracesSampler` for dynamic sampling; complete Source Map configuration guide |
29
- | **v1.6.0** | 13 enhancements + 16 fixes; enabled esbuild minification — bundle size reduced by ~**59%** |
30
- | **v1.5.0** | Performance enhancements (configurable thresholds / slow `setData` detection / memory sampling); new page lifecycle, user interaction, and Console breadcrumbs; route integration covers all platforms |
31
- | **v1.4.0** | `NetworkBreadcrumbs` captures Request / Response body; configurable offline cache limit; deprecated `showReportDialog` in favor of `captureFeedback` |
32
- | **v1.3.0** | 🎯 Build pipeline rewrite (Vite + bundle-inline): **zero external deps**, fully resolves the `miniprogram_npm` module-resolution issue; 🎯 built-in Source Map path normalization across all platforms |
31
+ | **v1.6.0** | 13 enhancements + 16 fixes; build output minification — bundle size reduced by ~**59%** |
32
+ | **v1.5.0** | Performance enhancements (configurable thresholds / slow `setData` detection / memory sampling); new page lifecycle, user interaction, and Console breadcrumbs |
33
+ | **v1.4.0** | `NetworkBreadcrumbs` captures Request / Response body; configurable offline cache limit |
34
+ | **v1.3.0** | 🎯 Build pipeline rewrite (Vite + bundle-inline): **zero external deps**, resolves the `miniprogram_npm` module-resolution issue; built-in Source Map path normalization |
33
35
 
34
36
  See [CHANGELOG.md](./CHANGELOG.md) for full details.
35
37
 
@@ -37,472 +39,163 @@ See [CHANGELOG.md](./CHANGELOG.md) for full details.
37
39
 
38
40
  ---
39
41
 
40
- ## Core Features
41
-
42
- - **Modern Architecture**: Built on the latest Sentry JavaScript V10 SDK core modules.
43
- - **True Multi-Platform Support**: Built-in API abstraction engine — one codebase seamlessly supports **WeChat, Alipay, ByteDance, Baidu, QQ, DingTalk, and Kuaishou** mini program platforms.
44
- - **Mini Game Support**: Auto-detects mini-game environments — error / network / device monitoring works out of the box, plus mini-game-specific **cold-start first-frame timing** and **frame-rate / jank (FPS) monitoring** (see "Mini Game Support" below).
45
- - **Automatic Exception Capture**: No business code intrusion required. Automatically hooks into lifecycle error listeners (`onError`, `onUnhandledRejection`, `onPageNotFound`, `onMemoryWarning`).
46
- - **Rich Context Breadcrumbs**: Automatically records device info, user tap/touch interactions, network requests (XHR/Fetch), and page lifecycle events.
47
- - **Built-in SourceMap Path Normalization**: Handles virtual stack paths across WeChat, Alipay, ByteDance and other platforms. Works with sentry-cli for seamless SourceMap resolution.
48
- - **Offline Caching for Weak Networks**: Designed for mini program network conditions. Automatically caches events to local storage on network failure, silently retries when connectivity is restored.
49
- - **Deep Performance Monitoring**: Integrates mini program Performance API for navigation timing (FCP/LCP), render performance, resource loading, and custom performance marks.
50
- - **Smart Deduplication & Filtering**: Built-in error deduplication and sample rate controls to prevent log storms.
51
- - **Cross-Platform Framework Friendly**: Works seamlessly with Taro, uni-app, and other cross-platform compilation frameworks.
52
- - **Distributed Tracing**: Automatically injects `sentry-trace` / `baggage` headers into network requests and reports mini program API timing as `http.client` spans, connecting mini program and backend service call chains.
53
- - **Session Health Monitoring**: Automatic session lifecycle management with crash rate and session health data in the Sentry Release Health dashboard.
54
- - **Network Status Monitoring**: Real-time tracking of network changes (WiFi/4G/offline) to help diagnose network-related exceptions.
55
- - **Stack Trace Parsing**: Built-in multi-platform stack parser supporting V8/Safari/JavaScriptCore formats for precise error location with SourceMap.
42
+ ## Core Features
43
+
44
+ - **🚀 Modern Architecture**: Built on the latest Sentry JavaScript V10 SDK core modules.
45
+ - **📱 True Multi-Platform Support**: Built-in API abstraction engine — one codebase supports **WeChat, Alipay, ByteDance, Baidu, QQ, DingTalk, and Kuaishou** mini programs.
46
+ - **🎮 Mini Game Support**: Auto-detects mini-game environments — error / network / device monitoring out of the box, plus mini-game-specific **cold-start first-frame timing** and **frame-rate / jank monitoring**.
47
+ - **🎯 Automatic Exception Capture**: No business code intrusion. Hooks into lifecycle error listeners (`onError`, `onUnhandledRejection`, `onPageNotFound`, `onMemoryWarning`).
48
+ - **🍞 Rich Context Breadcrumbs**: Auto-records device info, user tap/touch, network requests (XHR), and page lifecycle.
49
+ - **🗺️ Built-in SourceMap Path Normalization**: Unifies virtual stack paths across platforms; works with sentry-cli for seamless resolution.
50
+ - **📡 Offline Caching for Weak Networks**: Caches events to local storage on failure, silently retries when connectivity returns.
51
+ - **⚡ Deep Performance Monitoring**: Navigation timing (FCP/LCP), render performance, resource loading, and custom marks.
52
+ - **🔗 Distributed Tracing**: Injects `sentry-trace` / `baggage` headers and reports API timing as `http.client` spans, connecting mini program and backend call chains.
53
+ - **📊 Session Health** & **📶 Network Status Monitoring**: Session lifecycle management + real-time network change tracking (WiFi/4G/offline).
54
+ - **🛡️ Smart Deduplication & Filtering**: Built-in dedup and sample rate controls to prevent log storms.
56
55
 
57
56
  ---
58
57
 
59
- ## Installation
58
+ ## 📦 Installation
60
59
 
61
60
  ```bash
62
61
  npm install sentry-miniapp
63
62
  ```
64
63
 
65
- *Tip: If you don't use npm, you can also copy `examples/wxapp/lib/sentry-miniapp.js` from this repository directly into your mini program project.*
64
+ > Not using npm? Copy `examples/wxapp/lib/sentry-miniapp.js` from this repo directly into your project.
66
65
 
67
- ---
66
+ ### 🤖 AI-Assisted Setup
68
67
 
69
- ## AI-Assisted Setup
70
-
71
- If you use [Claude Code](https://claude.ai/code) or [Cursor](https://cursor.com), get AI-guided setup with one command:
68
+ With [Claude Code](https://claude.ai/code) or [Cursor](https://cursor.com), get AI-guided setup:
72
69
 
73
70
  ```bash
74
71
  npx skills add https://github.com/lizhiyao/sentry-miniapp --skill sentry-miniapp-sdk
75
72
  ```
76
73
 
77
- After installation, just ask "help me set up Sentry monitoring" in your AI editor.
74
+ Then just ask "help me set up Sentry monitoring" in your AI editor.
78
75
 
79
76
  ---
80
77
 
81
- ## Quick Start
82
-
83
- ### 1. Prerequisites
84
-
85
- 1. Ensure you have a Sentry account ([Sentry SaaS](https://sentry.io/) or self-hosted).
86
- 2. **Important**: Add your Sentry reporting endpoint domain to the `request` trusted domain list in your mini program platform's admin console.
78
+ ## 🚀 Quick Start
87
79
 
88
- ### 2. Initialize the SDK
80
+ **Prerequisites**: ① a Sentry account ([SaaS](https://sentry.io/) or self-hosted); ② add your Sentry endpoint domain to the `request` trusted-domain list in your mini program console.
89
81
 
90
- Initialize Sentry at the **top** of your mini program entry file (e.g., `app.js` or `app.ts`), **before** calling `App()`.
82
+ Initialize at the **top** of your entry file (`app.js` / `app.ts`), **before** `App()`:
91
83
 
92
84
  ```javascript
93
85
  import * as Sentry from 'sentry-miniapp';
94
86
 
95
87
  Sentry.init({
96
88
  dsn: 'https://<key>@sentry.io/<project>',
89
+ release: 'my-project@1.0.0', // match the release you upload Source Maps with
97
90
  environment: 'production',
98
- release: 'my-project-name@1.0.0',
99
-
100
- // --- Mini Program Configuration ---
101
- platform: 'wechat', // Optional event platform label; runtime platform is auto-detected
102
- enableUserInteractionBreadcrumbs: true, // Auto-record user tap events
103
- enableConsoleBreadcrumbs: false, // Record console output as breadcrumbs (default: false)
104
- traceNetworkBody: false, // Record request/response bodies in breadcrumbs (default: false)
105
-
106
- // --- Offline Cache & Reliability ---
107
- enableOfflineCache: true, // Enable offline caching with retry (default: true)
108
- offlineCacheLimit: 30, // Max cached events (default: 30)
109
-
110
- // --- SourceMap Support ---
111
- enableSourceMap: true, // Normalize virtual stack paths for SourceMap resolution
112
-
113
- // --- Sampling ---
114
- sampleRate: 1.0, // Error reporting sample rate (0.0 - 1.0)
115
- tracesSampleRate: 1.0, // Performance tracing sample rate; API requests are reported as http.client spans
116
-
117
- // --- Distributed Tracing ---
118
- enableTracePropagation: true, // Auto-inject sentry-trace/baggage headers (default: true)
119
- tracePropagationTargets: ['api.example.com'], // Only inject tracing headers for specified domains; spans still follow tracing sampling
120
-
121
- // --- Session & Network Monitoring ---
122
- enableAutoSessionTracking: true, // Auto session lifecycle management (default: true)
123
- enableNetworkStatusMonitoring: true, // Real-time network status monitoring (default: true)
91
+ sampleRate: 1.0, // error sample rate
92
+ tracesSampleRate: 1.0, // performance sample rate; API requests become http.client spans
124
93
  });
125
94
 
126
- App({
127
- onLaunch() {
128
- // ...
129
- }
130
- });
95
+ App({ onLaunch() {} });
131
96
  ```
132
97
 
133
- Default integrations already include automatic exception capture, performance monitoring, SourceMap path normalization, network breadcrumbs, session tracking, and network status monitoring. Only pass `integrations` when you intentionally want to take over the full integration list, because it replaces the defaults.
98
+ Do not put `Sentry.init` inside `App.onLaunch`: by then `App()` has already been registered, so the SDK cannot wrap that first `onLaunch` call. App lifecycle breadcrumbs, the first session start, and cold-start timing which depends on the `onLaunch` start point may be missing. If you only need later errors, network breadcrumbs, and manual capture, initializing in `onLaunch` still works, but startup instrumentation is degraded.
134
99
 
135
- ---
136
-
137
- ## Advanced Usage
100
+ Default integrations already include **exception capture, performance monitoring, Source Map path normalization, network breadcrumbs, session and network status monitoring** — you usually don't pass `integrations` (doing so replaces the defaults). Full options (offline cache, trace propagation, breadcrumb toggles) are on the [docs site · Configuration](https://sentry-miniapp.pages.dev/guide/configuration).
138
101
 
139
- After initialization, the SDK works automatically in the background. You can also use the following APIs for manual instrumentation.
140
-
141
- ### Manual Exception & Message Reporting
102
+ **Verify it works** capture an event and check the Sentry "Issues" list:
142
103
 
143
104
  ```javascript
144
- // Manually capture and report an Error
145
- try {
146
- throw new Error('Payment API parsing failed');
147
- } catch (error) {
148
- Sentry.captureException(error);
149
- }
150
-
151
- // Log a message
152
- Sentry.captureMessage('User cancelled authorization', 'info');
105
+ Sentry.captureException(new Error('sentry test'));
153
106
  ```
154
107
 
155
- ### Context Enrichment (Context & Breadcrumbs)
156
-
157
- ```javascript
158
- // Set current user info
159
- Sentry.setUser({
160
- id: 'user_12345',
161
- username: 'John Doe'
162
- });
163
-
164
- // Set global tags for filtering and analytics
165
- Sentry.setTag('page_module', 'checkout_counter');
108
+ > ⚠️ `addBreadcrumb` is not reported on its own — it only ships with the next event. Calling it without capturing an event leaves your dashboard empty.
166
109
 
167
- // Manually add a breadcrumb
168
- Sentry.addBreadcrumb({
169
- message: 'User tapped [Confirm Payment] button',
170
- category: 'action',
171
- level: 'info',
172
- data: { cartId: 'c_888' }
173
- });
174
- ```
110
+ ---
175
111
 
176
- ### Custom Performance Measurement
112
+ ## 📚 Common APIs
177
113
 
178
114
  ```javascript
179
- await Sentry.startSpan(
180
- {
181
- name: 'fetch-user-data',
182
- op: 'http.client',
183
- },
184
- async () => {
185
- await fetchUserData();
186
- },
187
- );
188
- ```
115
+ // Manual capture
116
+ Sentry.captureException(new Error('Payment API parsing failed'));
117
+ Sentry.captureMessage('User cancelled authorization', 'info');
189
118
 
190
- ### Dynamic Sampling (tracesSampler)
119
+ // User & tags
120
+ Sentry.setUser({ id: 'user_12345', username: 'John Doe' });
121
+ Sentry.setTag('page_module', 'checkout');
191
122
 
192
- Beyond the global `sampleRate`, you can use the `tracesSampler` callback for fine-grained, per-page sampling control:
123
+ // Breadcrumb
124
+ Sentry.addBreadcrumb({ message: 'Tapped [Confirm Payment]', category: 'action', level: 'info' });
193
125
 
194
- ```javascript
195
- Sentry.init({
196
- dsn: '...',
197
- tracesSampler: ({ name, inheritOrSampleWith }) => {
198
- // 100% sampling for critical pages
199
- if (name.includes('pages/index') || name.includes('pages/pay')) {
200
- return 1;
201
- }
202
- // Lower sampling for low-priority pages
203
- if (name.includes('pages/about') || name.includes('pages/settings')) {
204
- return 0.1;
205
- }
206
- // Inherit upstream decision or fall back to 50%
207
- return inheritOrSampleWith(0.5);
208
- },
209
- });
126
+ // Custom span
127
+ await Sentry.startSpan({ name: 'fetch-user', op: 'http.client' }, async () => { /* ... */ });
210
128
  ```
211
129
 
212
- > **Note:** When `tracesSampler` is set, `tracesSampleRate` is ignored. `tracesSampler` takes priority.
130
+ For per-page / per-scenario sampling use the `tracesSampler` callback (it overrides `tracesSampleRate`); see the [docs site · Configuration](https://sentry-miniapp.pages.dev/guide/configuration).
213
131
 
214
132
  ---
215
133
 
216
- ## SourceMap Support
134
+ ## 🗺️ Source Map
217
135
 
218
- The SDK includes built-in multi-platform stack path normalization (`enableSourceMap: true`, enabled by default), automatically converting platform-specific virtual paths to the `app:///` prefix for seamless SourceMap resolution with sentry-cli.
219
-
220
- **Quick upload example:**
136
+ The SDK normalizes platform virtual stack paths to the `app:///` prefix by default (`enableSourceMap: true`). Upload with sentry-cli:
221
137
 
222
138
  ```bash
223
139
  sentry-cli releases files "my-miniapp@1.0.0" upload-sourcemaps ./dist \
224
- --url-prefix "app:///" \
225
- --ext js --ext map
140
+ --url-prefix "app:///" --ext js --ext map
226
141
  ```
227
142
 
228
- > For a complete end-to-end setup guide (build tool configs, CI/CD integration, verification & troubleshooting), see **[Source Map Configuration Guide](./docs/SOURCEMAP_GUIDE.md)**.
143
+ > Full end-to-end setup (build tools, CI/CD, two-layer map merging for cross-platform frameworks, verification) is in the **[Source Map Configuration Guide](./docs/SOURCEMAP_GUIDE.md)**.
229
144
 
230
145
  ---
231
146
 
232
- ## User Feedback
233
-
234
- In web environments, Sentry provides a built-in `showReportDialog()` popup. However, mini programs have no DOM, so this method is **not available**.
235
-
236
- Instead, build a **native mini program form or modal** to collect user feedback, then submit it via `Sentry.captureFeedback()`:
237
-
238
- ```javascript
239
- const userMessage = 'The page is frozen, nothing responds';
240
- const userName = 'John Doe';
241
- const userEmail = 'john@example.com';
242
-
243
- Sentry.captureFeedback({
244
- message: userMessage,
245
- name: userName,
246
- email: userEmail,
247
- // Optional: associate with a specific error event
248
- // associatedEventId: 'abc123xyz...'
249
- });
250
- ```
251
-
252
- ---
147
+ ## 🎮 Mini Game Support
253
148
 
254
- ## Bundle Size Optimization (Zero Main Package Overhead)
149
+ `sentry-miniapp` also works in WeChat / Douyin **mini games**: auto-detects the environment, error / network / device monitoring out of the box, plus **cold-start first-frame timing** and **frame-rate / jank monitoring**. Initialization is identical to mini programs; with `tracesSampleRate` enabled, performance data is reported as independent transactions on the Performance page.
255
150
 
256
- Mini program "main package" size is limited (typically 2MB). `sentry-miniapp` includes the full `@sentry/core` engine and multi-platform adapters, totaling ~100KB.
151
+ > Capability matrix and performance-reporting details: [docs site · Platforms & Capabilities](https://sentry-miniapp.pages.dev/guide/platforms).
257
152
 
258
- If main package size is a concern, use **subpackage async loading** or **dynamic loading** to move the SDK entirely into a subpackage.
153
+ ## 📦 Bundle Size Optimization
259
154
 
260
- ### Option A: WeChat / Alipay (Recommended)
155
+ The SDK is ~100KB. If main-package size matters, use platform "subpackage async" / "dynamic loading" to move the SDK into a subpackage and reduce main-package overhead; platforms with cross-subpackage async loading can reach zero main-package overhead.
261
156
 
262
- WeChat and Alipay natively support [subpackage async loading](https://developers.weixin.qq.com/miniprogram/dev/framework/subpackages/async.html).
263
-
264
- ```javascript
265
- // app.js
266
- App({
267
- onLaunch() {
268
- require.async('./subpackageA/sentry-miniapp.js').then((Sentry) => {
269
- Sentry.init({
270
- dsn: 'https://xxxxxxxx@sentry.io/12345',
271
- // ...other options
272
- });
273
- console.log('Sentry loaded and initialized successfully');
274
- }).catch(err => {
275
- console.error('Failed to load Sentry', err);
276
- });
277
- }
278
- });
279
- ```
280
-
281
- *This way, Sentry's ~100KB is counted against `subpackageA`'s size — zero main package overhead!*
282
-
283
- ### Option B: Other Platforms (ByteDance, Baidu, etc.)
284
-
285
- For platforms that don't support `require.async`, use **subpackage predownload + dynamic loading**:
286
-
287
- ```javascript
288
- // ByteDance mini program example
289
- App({
290
- onLaunch() {
291
- const loadTask = tt.loadSubpackage({
292
- name: 'subpackageA',
293
- success: () => {
294
- const Sentry = require('./subpackageA/sentry-miniapp.js');
295
- Sentry.init({ dsn: '...' });
296
- }
297
- });
298
- }
299
- });
300
- ```
301
-
302
- *Note: If using Taro / uni-app, you can use `import('sentry-miniapp')` dynamic import syntax — the framework handles cross-platform differences at compile time.*
157
+ > WeChat subpackage async loading and cross-platform verification guidance: [docs site · Bundle Size](https://sentry-miniapp.pages.dev/guide/bundle-size).
303
158
 
304
159
  ---
305
160
 
306
- ## Mini Game Support
307
-
308
- `sentry-miniapp` also works in **mini games** (WeChat / ByteDance mini games, etc.). Mini games have no `App()`/`Page()`/page routing, but expose platform APIs like `wx.onError`, `wx.request`, `wx.getDeviceInfo`, and `wx.getPerformance`. Most SDK capabilities work out of the box, plus mini-game-specific cold-start and frame-rate monitoring.
309
-
310
- **Initialization is identical to mini programs** — the SDK auto-detects the mini-game environment and enables the relevant features:
311
-
312
- ```js
313
- import * as Sentry from 'sentry-miniapp';
314
-
315
- Sentry.init({
316
- dsn: 'YOUR_DSN',
317
- // Enabled by default in mini-game environments; set to false to disable:
318
- // enableMinigameLifecycle: true, // cold-start first-frame timing + launch scene + onShow/onHide breadcrumbs
319
- // enableMinigameFrameRate: true, // FPS / jank monitoring
320
-
321
- // Fine-tune frame-rate monitoring (FPS warning threshold, jank threshold, report interval, etc.):
322
- // minigameFrameRateOptions: { fpsWarningThreshold: 45 },
323
- });
324
- ```
325
-
326
- ### Capability matrix
327
-
328
- | Capability | Mini Game | Notes |
329
- |------------|:---------:|-------|
330
- | Exception / unhandled rejection capture | ✅ | `wx.onError` / `wx.onUnhandledRejection` |
331
- | API request monitoring (count / duration / status) | ✅ | wraps `wx.request`; creates `http.client` spans when tracing is enabled |
332
- | Network status monitoring | ✅ | `wx.onNetworkStatusChange` |
333
- | Device info / context breadcrumbs | ✅ | `wx.getDeviceInfo` etc. |
334
- | Resource load timing | ✅ | `wx.getPerformance()` |
335
- | **Cold-start first-frame timing + launch scene** | ✅ New | `MinigameIntegration` (first `requestAnimationFrame` ≈ first frame) |
336
- | **Frame rate / jank monitoring** | ✅ New | `MinigameFrameRateIntegration` (RAF FPS sampling, long frames → jank, periodic `minigame.framerate` context) |
337
- | Page lifecycle / tap breadcrumbs | ➖ | No pages in mini games — auto-skipped; use `onShow/onHide` breadcrumbs or manual `addBreadcrumb` |
161
+ ## 💬 User Feedback
338
162
 
339
- > These two integrations are enabled by default only in mini-game environments. In particular, **frame-rate monitoring relies on a global `requestAnimationFrame`**: mini games have one (bound to the real render loop), whereas mini programs use a dual-thread architecture whose logic layer has no global `requestAnimationFrame` — so even if enabled there, it safely no-ops (it cannot measure page render frame rate).
163
+ Mini programs have no DOM, so `showReportDialog()` is deprecated. Build a native form to collect feedback, then submit via `Sentry.captureFeedback()`:
340
164
 
341
- #### Independent performance reporting (Performance page)
342
-
343
- Cold-start and frame-rate data are **not only attached to error events** — with tracing enabled they are reported as independent transactions, so you can aggregate trends / distributions / P95 across sessions on the Sentry Performance page:
344
-
345
- - **Cold start** → a `minigame.coldstart` transaction (with a `cold_start` measurement).
346
- - **Frame rate / jank** → accumulated per session and flushed as a single `minigame.framerate.summary` transaction on **background (onHide) / session end** (with `fps_avg` / `fps_p95` / `fps_min` / `jank_count` measurements) — no per-window events, quota-friendly.
347
-
348
- ```js
349
- Sentry.init({
350
- dsn: 'YOUR_DSN',
351
- tracesSampleRate: 1.0, // enable performance sampling (decoupled from error sampleRate)
352
- });
165
+ ```javascript
166
+ Sentry.captureFeedback({ message: 'The page is frozen', name: 'John Doe', email: 'john@example.com' });
353
167
  ```
354
168
 
355
- > Requires `tracesSampleRate` (or `tracesSampler`) for performance transactions to be sent; this sampling is **independent of** the error `sampleRate`. Without tracing enabled, it degrades to the original behavior: performance data is only attached to error events as `minigame` / `minigame.framerate` contexts + breadcrumbs.
356
-
357
169
  ---
358
170
 
359
- ## FAQ
171
+ ## FAQ (quick reference)
360
172
 
361
- ### 1. Do I need to manually report errors in `onError`?
173
+ - **Must I report manually in `onError`?** No `init` hooks the global error listeners automatically.
174
+ - **Are network requests included with errors?** Yes, on by default — recorded as `category: xhr` breadcrumbs shipped with the error.
175
+ - **uni-app (Vue) component errors rarely reported?** Vue swallows component errors; wire `app.config.errorHandler`. Taro (React) uses an Error Boundary.
176
+ - **Session Replay?** Not supported (no DOM); reconstruct via breadcrumbs.
177
+ - **H5 build?** Use official `@sentry/browser`, branched via conditional compilation.
362
178
 
363
- **No.** `sentry-miniapp` automatically hooks into platform-level global error listeners (e.g., `wx.onError`) during initialization. As long as `Sentry.init` is called **before** `App()`, it captures all unhandled JS exceptions automatically.
364
-
365
- If errors are not being reported, check:
366
- 1. Whether the Sentry domain is in the mini program's trusted domain list.
367
- 2. Whether `sampleRate` is set too low.
368
- 3. Some WeChat DevTools environments don't trigger `onError` — test on a **real device**.
369
-
370
- ### 2. Does this SDK support Session Replay?
371
-
372
- **Not currently.** Sentry's official Replay feature relies on standard browser DOM (via rrweb recording). Mini programs use a dual-thread architecture without standard DOM access. We recommend using **Breadcrumbs** combined with **custom logging** to reconstruct user action sequences.
373
-
374
- ### 3. How do I monitor the H5 build of a uni-app / Taro project?
375
-
376
- `sentry-miniapp` **only adapts mini program platforms** and does not implement browser-native signals (`window.onerror`, `fetch` / `XHR` interception, `PerformanceObserver`, etc.). For the H5 build, use Sentry's official [`@sentry/browser`](https://docs.sentry.io/platforms/javascript/) directly — full feature coverage, maintained upstream.
377
-
378
- > When this SDK is initialized in a browser environment, it logs a warning suggesting you switch to `@sentry/browser`.
379
-
380
- Recommended pattern: split SDKs by platform via **uni-app conditional compilation**:
381
-
382
- ```ts
383
- // utils/sentry.ts
384
- let Sentry: any;
385
-
386
- // #ifdef H5
387
- Sentry = require('@sentry/browser');
388
- Sentry.init({
389
- dsn: 'YOUR_DSN',
390
- environment: 'production',
391
- tracesSampleRate: 0.2,
392
- });
393
- // #endif
394
-
395
- // #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-QQ || MP-KUAISHOU || MP-DINGTALK
396
- Sentry = require('sentry-miniapp');
397
- Sentry.init({
398
- dsn: 'YOUR_DSN',
399
- environment: 'production',
400
- tracesSampleRate: 0.2,
401
- });
402
- // #endif
403
-
404
- export default Sentry;
405
- ```
406
-
407
- Both sides report to the same Sentry DSN so all errors land in a single project. For Taro, use `process.env.TARO_ENV === 'h5'` to branch similarly.
408
-
409
- ### 4. Are network requests included with error events?
410
-
411
- **Yes, and it's on by default.** The SDK enables `NetworkBreadcrumbs` out of the box, which patches `wx.request` / `my.httpRequest` and records each request as a `category: xhr` breadcrumb. Those breadcrumbs ride along with the **next captured error event** (same as `@sentry/browser`), so you'll see the request trail leading up to the error in the event's **Breadcrumbs** section.
412
-
413
- - **Fields by default:** `url` / `method` / `status_code` / `duration`; failed requests are `error` level, slow ones (>3s) are `warning`.
414
- - **Bodies are NOT included by default.** Enable `traceNetworkBody: true` to capture request/response bodies (with built-in sensitive-field scrubbing; use `denyBodyUrls` to exclude specific URLs):
415
-
416
- ```js
417
- Sentry.init({ dsn: '...', traceNetworkBody: true });
418
- ```
419
-
420
- - **No extra config for uni-app / Taro:** `uni.request` / `Taro.request` ultimately call the patched global `wx.request`, so they're captured too.
421
-
422
- If an error has no network breadcrumb, it's usually one of:
423
-
424
- 1. **No request happened before the error fired** (e.g. calling `captureException` right on page load). To verify, make a request first and trigger the error in its callback:
425
-
426
- ```js
427
- wx.request({
428
- url: 'https://httpbin.org/get',
429
- success() {
430
- Sentry.captureException(new Error('net test'));
431
- },
432
- });
433
- ```
434
-
435
- You should then see a `category: xhr` breadcrumb on the event.
436
-
437
- 2. **`Sentry.init` ran after the request.** The patch is installed during `init`, so requests fired before `init` aren't captured. Always call `Sentry.init` before `App()` / any business request.
438
-
439
- ### 5. Errors in uni-app (Vue) components aren't reported / reporting rate is very low?
440
-
441
- With **uni-app** (Vue under the hood) you may hit "`sampleRate` is 1 but only an occasional error shows up". The reason: **Vue catches errors thrown inside components (render / lifecycle / watchers / methods invoked from `@click`) with its own error handler — by default it only logs to console and does NOT bubble them to `wx.onError`**, so the SDK never sees them. Only errors that escape Vue (e.g. `setTimeout` callbacks, unhandled promises, hard crashes) get through, which is why reporting looks sporadic.
442
-
443
- Wire Vue's `errorHandler` to Sentry so component errors are reported:
444
-
445
- **uni-app Vue3 (`main.js` / `main.ts`, the current default):**
446
-
447
- ```js
448
- import Sentry from '@/utils/sentry'; // your sentry-miniapp init wrapper
449
- import { createSSRApp } from 'vue';
450
- import App from './App.vue';
451
-
452
- export function createApp() {
453
- const app = createSSRApp(App);
454
- app.config.errorHandler = (err, instance, info) => {
455
- Sentry.captureException(err, { extra: { lifecycleHook: info } });
456
- console.error(err);
457
- };
458
- return { app };
459
- }
460
- ```
461
-
462
- **Vue2 (older uni-app):**
463
-
464
- ```js
465
- Vue.config.errorHandler = (err, vm, info) => {
466
- Sentry.captureException(err);
467
- console.error(err);
468
- };
469
- ```
470
-
471
- > **Taro is not Vue.** Taro defaults to **React** (and also supports Vue). With **Vue**, wire `errorHandler` the same way; with **React**, React does not silently swallow component errors like Vue (an uncaught render error propagates upward), but you can add an **Error Boundary** to forward render errors to Sentry with richer context:
472
- >
473
- > ```jsx
474
- > class SentryBoundary extends React.Component {
475
- > componentDidCatch(error, info) {
476
- > Sentry.captureException(error, { extra: info });
477
- > }
478
- > render() {
479
- > return this.props.children;
480
- > }
481
- > }
482
- > // Wrap your root: <SentryBoundary><App /></SentryBoundary>
483
- > ```
484
-
485
- This also improves delivery: once `errorHandler` / the boundary catches the error the app keeps running, so the in-flight report request completes (a hard crash would otherwise kill it).
179
+ > Full answers on the **[docs site · FAQ](https://sentry-miniapp.pages.dev/guide/faq)**.
486
180
 
487
181
  ---
488
182
 
489
- ## Documentation
183
+ ## 📖 Documentation
490
184
 
491
185
  | Document | Description |
492
186
  |----------|-------------|
493
- | [SourceMap Configuration Guide](./docs/SOURCEMAP_GUIDE.md) | End-to-end SourceMap setup, build tools, CI/CD, verification & troubleshooting |
494
- | [Multi-Platform Compatibility Report](./docs/MultiPlatformCompatibilityReport.md) | Platform API compatibility matrix and differences |
495
- | [Example Project](./examples/wxapp/) | Complete WeChat mini program integration example |
496
- | [Development Guide](./DEVELOPMENT.md) | Local development setup and debugging |
497
- | [Contributing Guide](./CONTRIBUTING.md) | How to contribute to the project |
187
+ | [Documentation site](https://sentry-miniapp.pages.dev/) | Getting started / capability matrix / FAQ / Source Map / examples (recommended, with search) |
188
+ | [Taro guide](https://sentry-miniapp.pages.dev/guide/taro) · [uni-app guide](https://sentry-miniapp.pages.dev/guide/uniapp) | Cross-platform framework setup & component error handling |
189
+ | [Source Map Configuration Guide](./docs/SOURCEMAP_GUIDE.md) | End-to-end setup, build tools, CI/CD, verification |
190
+ | [Multi-Platform Compatibility Report](./docs/MultiPlatformCompatibilityReport.md) | Platform API differences |
191
+ | [Examples](./examples/) | wxapp (native) / taro (React) / uniapp (Vue) runnable examples |
192
+ | [Development Guide](./DEVELOPMENT.md) · [Contributing Guide](./CONTRIBUTING.md) | Local dev, debugging & contributing |
498
193
 
499
194
  ---
500
195
 
501
- ## Community
502
-
503
- Have questions or want to discuss mini program monitoring? Join our community.
196
+ ## 💬 Community
504
197
 
505
- Due to WeChat group QR code expiration (7-day limit), please add the author on WeChat (**note: sentry-miniapp**) to be invited to the group:
198
+ Have questions or want to discuss mini program monitoring? Due to WeChat group QR code expiration (7-day limit), please add the author on WeChat (**note: sentry-miniapp**) to be invited to the group:
506
199
 
507
200
  <img src="docs/qrcode/zhiyao.jpeg" alt="Author WeChat QR Code" width="200" style="border-radius: 8px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);" />
508
201