sentry-miniapp 1.6.0 → 1.8.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/README.en.md ADDED
@@ -0,0 +1,336 @@
1
+ # Sentry Miniapp SDK — Mini Program Monitoring SDK
2
+
3
+ ![npm version](https://img.shields.io/npm/v/sentry-miniapp)
4
+ ![npm downloads/month](https://img.shields.io/npm/dm/sentry-miniapp)
5
+ ![github forks](https://img.shields.io/github/forks/lizhiyao/sentry-miniapp?style=social)
6
+ ![github stars](https://img.shields.io/github/stars/lizhiyao/sentry-miniapp?style=social)
7
+ ![test coverage](https://img.shields.io/badge/test%20coverage-100%25-brightgreen.svg)
8
+ ![license](https://img.shields.io/github/license/lizhiyao/sentry-miniapp)
9
+
10
+ [简体中文](./README.md) | English
11
+
12
+ A **mini program monitoring SDK** built on `@sentry/core` (v10.45.0), providing **error monitoring**, **performance monitoring**, offline caching, and distributed tracing. Supports WeChat, Alipay, ByteDance, Baidu, QQ, DingTalk, Kuaishou mini programs and cross-platform frameworks (Taro / uni-app).
13
+
14
+ > **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.
15
+
16
+ > **Version Notes**
17
+ >
18
+ > - `v1.x.x`: New architecture based on Sentry V10 core. Full support for WeChat, Alipay, ByteDance, Baidu, QQ, DingTalk, Kuaishou mini programs and cross-platform frameworks (Taro / uni-app).
19
+ > - `v0.x.x`: Legacy version, no longer maintained.
20
+
21
+ ---
22
+
23
+ ## Core Features
24
+
25
+ - **Modern Architecture**: Built on the latest Sentry JavaScript V10 SDK core modules.
26
+ - **True Multi-Platform Support**: Built-in API abstraction engine — one codebase seamlessly supports **WeChat, Alipay, ByteDance, Baidu, QQ, DingTalk, and Kuaishou** mini program platforms.
27
+ - **Automatic Exception Capture**: No business code intrusion required. Automatically hooks into lifecycle error listeners (`onError`, `onUnhandledRejection`, `onPageNotFound`, `onMemoryWarning`).
28
+ - **Rich Context Breadcrumbs**: Automatically records device info, user tap/touch interactions, network requests (XHR/Fetch), and page navigation paths.
29
+ - **Built-in SourceMap Path Normalization**: Handles virtual stack paths across WeChat, Alipay, ByteDance and other platforms. Works with sentry-cli for seamless SourceMap resolution.
30
+ - **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.
31
+ - **Deep Performance Monitoring**: Integrates mini program Performance API for navigation timing (FCP/LCP), render performance, resource loading, and custom performance marks.
32
+ - **Smart Deduplication & Filtering**: Built-in error deduplication and sample rate controls to prevent log storms.
33
+ - **Cross-Platform Framework Friendly**: Works seamlessly with Taro, uni-app, and other cross-platform compilation frameworks.
34
+ - **Distributed Tracing**: Automatically injects `sentry-trace` / `baggage` headers into network requests, connecting mini program and backend service call chains.
35
+ - **Session Health Monitoring**: Automatic session lifecycle management with crash rate and session health data in the Sentry Release Health dashboard.
36
+ - **Network Status Monitoring**: Real-time tracking of network changes (WiFi/4G/offline) to help diagnose network-related exceptions.
37
+ - **Stack Trace Parsing**: Built-in multi-platform stack parser supporting V8/Safari/JavaScriptCore formats for precise error location with SourceMap.
38
+
39
+ ---
40
+
41
+ ## Installation
42
+
43
+ ```bash
44
+ npm install sentry-miniapp
45
+ ```
46
+
47
+ > **Note:** Starting from `v1.1.0`, the build strategy has been optimized (dependencies are inlined), so there is **no need** to install `@sentry/core` separately.
48
+
49
+ *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.*
50
+
51
+ ---
52
+
53
+ ## AI-Assisted Setup
54
+
55
+ If you use [Claude Code](https://claude.ai/code) or [Cursor](https://cursor.com), get AI-guided setup with one command:
56
+
57
+ ```bash
58
+ npx skills add https://github.com/lizhiyao/sentry-miniapp --skill sentry-miniapp-sdk
59
+ ```
60
+
61
+ After installation, just ask "help me set up Sentry monitoring" in your AI editor.
62
+
63
+ ---
64
+
65
+ ## Quick Start
66
+
67
+ ### 1. Prerequisites
68
+
69
+ 1. Ensure you have a Sentry account ([Sentry SaaS](https://sentry.io/) or self-hosted).
70
+ 2. **Important**: Add your Sentry reporting endpoint domain to the `request` trusted domain list in your mini program platform's admin console.
71
+
72
+ ### 2. Initialize the SDK
73
+
74
+ Initialize Sentry at the **top** of your mini program entry file (e.g., `app.js` or `app.ts`), **before** calling `App()`.
75
+
76
+ ```javascript
77
+ import * as Sentry from 'sentry-miniapp';
78
+
79
+ Sentry.init({
80
+ dsn: 'https://<key>@sentry.io/<project>',
81
+ environment: 'production',
82
+ release: 'my-project-name@1.0.0',
83
+
84
+ // --- Mini Program Configuration ---
85
+ platform: 'wechat', // Current platform (wechat | alipay | bytedance | dd | swan, etc.)
86
+ enableSystemInfo: true, // Auto-collect system and device info
87
+ enableUserInteractionBreadcrumbs: true, // Auto-record user tap events
88
+ enableNavigationBreadcrumbs: true, // Auto-record page navigation
89
+ traceNetworkBody: true, // Record request/response bodies in breadcrumbs (default: false)
90
+
91
+ // --- Offline Cache & Reliability ---
92
+ enableOfflineCache: true, // Enable offline caching with retry (default: true)
93
+ offlineCacheLimit: 30, // Max cached events (default: 30)
94
+
95
+ // --- SourceMap Support ---
96
+ enableSourceMap: true, // Normalize virtual stack paths for SourceMap resolution
97
+
98
+ // --- Sampling ---
99
+ sampleRate: 1.0, // Error reporting sample rate (0.0 - 1.0)
100
+
101
+ // --- Distributed Tracing ---
102
+ enableTracePropagation: true, // Auto-inject sentry-trace/baggage headers (default: true)
103
+ tracePropagationTargets: ['api.example.com'], // Only inject tracing headers for specified domains
104
+
105
+ // --- Session & Network Monitoring ---
106
+ enableAutoSessionTracking: true, // Auto session lifecycle management (default: true)
107
+ enableNetworkStatusMonitoring: true, // Real-time network status monitoring (default: true)
108
+
109
+ // Optional: Performance monitoring
110
+ integrations: [
111
+ Sentry.performanceIntegration({
112
+ enableNavigation: true, // Navigation timing
113
+ enableRender: true, // Render timing
114
+ enableResource: true, // Resource loading timing
115
+ }),
116
+ ]
117
+ });
118
+
119
+ App({
120
+ onLaunch() {
121
+ // ...
122
+ }
123
+ });
124
+ ```
125
+
126
+ ---
127
+
128
+ ## Advanced Usage
129
+
130
+ After initialization, the SDK works automatically in the background. You can also use the following APIs for manual instrumentation.
131
+
132
+ ### Manual Exception & Message Reporting
133
+
134
+ ```javascript
135
+ // Manually capture and report an Error
136
+ try {
137
+ throw new Error('Payment API parsing failed');
138
+ } catch (error) {
139
+ Sentry.captureException(error);
140
+ }
141
+
142
+ // Log a message
143
+ Sentry.captureMessage('User cancelled authorization', 'info');
144
+ ```
145
+
146
+ ### Context Enrichment (Context & Breadcrumbs)
147
+
148
+ ```javascript
149
+ // Set current user info
150
+ Sentry.setUser({
151
+ id: 'user_12345',
152
+ username: 'John Doe'
153
+ });
154
+
155
+ // Set global tags for filtering and analytics
156
+ Sentry.setTag('page_module', 'checkout_counter');
157
+
158
+ // Manually add a breadcrumb
159
+ Sentry.addBreadcrumb({
160
+ message: 'User tapped [Confirm Payment] button',
161
+ category: 'action',
162
+ level: 'info',
163
+ data: { cartId: 'c_888' }
164
+ });
165
+ ```
166
+
167
+ ### Custom Performance Measurement
168
+
169
+ ```javascript
170
+ // Mark start point
171
+ Sentry.addPerformanceMark('api-request-start');
172
+ // ... perform operation
173
+ Sentry.addPerformanceMark('api-request-end');
174
+
175
+ // Measure the interval
176
+ Sentry.measurePerformance('fetch-user-data', 'api-request-start', 'api-request-end');
177
+ ```
178
+
179
+ ### Dynamic Sampling (tracesSampler)
180
+
181
+ Beyond the global `sampleRate`, you can use the `tracesSampler` callback for fine-grained, per-page sampling control:
182
+
183
+ ```javascript
184
+ Sentry.init({
185
+ dsn: '...',
186
+ tracesSampler: ({ name, inheritOrSampleWith }) => {
187
+ // 100% sampling for critical pages
188
+ if (name.includes('pages/index') || name.includes('pages/pay')) {
189
+ return 1;
190
+ }
191
+ // Lower sampling for low-priority pages
192
+ if (name.includes('pages/about') || name.includes('pages/settings')) {
193
+ return 0.1;
194
+ }
195
+ // Inherit upstream decision or fall back to 50%
196
+ return inheritOrSampleWith(0.5);
197
+ },
198
+ });
199
+ ```
200
+
201
+ > **Note:** When `tracesSampler` is set, `tracesSampleRate` is ignored. `tracesSampler` takes priority.
202
+
203
+ ---
204
+
205
+ ## SourceMap Support
206
+
207
+ 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.
208
+
209
+ **Quick upload example:**
210
+
211
+ ```bash
212
+ sentry-cli releases files "my-miniapp@1.0.0" upload-sourcemaps ./dist \
213
+ --url-prefix "app:///" \
214
+ --ext js --ext map
215
+ ```
216
+
217
+ > 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)**.
218
+
219
+ ---
220
+
221
+ ## User Feedback
222
+
223
+ In web environments, Sentry provides a built-in `showReportDialog()` popup. However, mini programs have no DOM, so this method is **not available**.
224
+
225
+ Instead, build a **native mini program form or modal** to collect user feedback, then submit it via `Sentry.captureFeedback()`:
226
+
227
+ ```javascript
228
+ const userMessage = 'The page is frozen, nothing responds';
229
+ const userName = 'John Doe';
230
+ const userEmail = 'john@example.com';
231
+
232
+ Sentry.captureFeedback({
233
+ message: userMessage,
234
+ name: userName,
235
+ email: userEmail,
236
+ // Optional: associate with a specific error event
237
+ // associatedEventId: 'abc123xyz...'
238
+ });
239
+ ```
240
+
241
+ ---
242
+
243
+ ## Bundle Size Optimization (Zero Main Package Overhead)
244
+
245
+ Mini program "main package" size is limited (typically 2MB). `sentry-miniapp` includes the full `@sentry/core` engine and multi-platform adapters, totaling ~100KB.
246
+
247
+ If main package size is a concern, use **subpackage async loading** or **dynamic loading** to move the SDK entirely into a subpackage.
248
+
249
+ ### Option A: WeChat / Alipay (Recommended)
250
+
251
+ WeChat and Alipay natively support [subpackage async loading](https://developers.weixin.qq.com/miniprogram/dev/framework/subpackages/async.html).
252
+
253
+ ```javascript
254
+ // app.js
255
+ App({
256
+ onLaunch() {
257
+ require.async('./subpackageA/sentry-miniapp.js').then((Sentry) => {
258
+ Sentry.init({
259
+ dsn: 'https://xxxxxxxx@sentry.io/12345',
260
+ // ...other options
261
+ });
262
+ console.log('Sentry loaded and initialized successfully');
263
+ }).catch(err => {
264
+ console.error('Failed to load Sentry', err);
265
+ });
266
+ }
267
+ });
268
+ ```
269
+
270
+ *This way, Sentry's ~100KB is counted against `subpackageA`'s size — zero main package overhead!*
271
+
272
+ ### Option B: Other Platforms (ByteDance, Baidu, etc.)
273
+
274
+ For platforms that don't support `require.async`, use **subpackage predownload + dynamic loading**:
275
+
276
+ ```javascript
277
+ // ByteDance mini program example
278
+ App({
279
+ onLaunch() {
280
+ const loadTask = tt.loadSubpackage({
281
+ name: 'subpackageA',
282
+ success: () => {
283
+ const Sentry = require('./subpackageA/sentry-miniapp.js');
284
+ Sentry.init({ dsn: '...' });
285
+ }
286
+ });
287
+ }
288
+ });
289
+ ```
290
+
291
+ *Note: If using Taro / uni-app, you can use `import('sentry-miniapp')` dynamic import syntax — the framework handles cross-platform differences at compile time.*
292
+
293
+ ---
294
+
295
+ ## FAQ
296
+
297
+ ### 1. Do I need to manually report errors in `onError`?
298
+
299
+ **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.
300
+
301
+ If errors are not being reported, check:
302
+ 1. Whether the Sentry domain is in the mini program's trusted domain list.
303
+ 2. Whether `sampleRate` is set too low.
304
+ 3. Some WeChat DevTools environments don't trigger `onError` — test on a **real device**.
305
+
306
+ ### 2. Does this SDK support Session Replay?
307
+
308
+ **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.
309
+
310
+ ---
311
+
312
+ ## Documentation
313
+
314
+ | Document | Description |
315
+ |----------|-------------|
316
+ | [SourceMap Configuration Guide](./docs/SOURCEMAP_GUIDE.md) | End-to-end SourceMap setup, build tools, CI/CD, verification & troubleshooting |
317
+ | [Multi-Platform Compatibility Report](./docs/MultiPlatformCompatibilityReport.md) | Platform API compatibility matrix and differences |
318
+ | [Example Project](./examples/wxapp/) | Complete WeChat mini program integration example |
319
+ | [Development Guide](./DEVELOPMENT.md) | Local development setup and debugging |
320
+ | [Contributing Guide](./CONTRIBUTING.md) | How to contribute to the project |
321
+
322
+ ---
323
+
324
+ ## Community
325
+
326
+ Have questions or want to discuss mini program monitoring? Join our community.
327
+
328
+ 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:
329
+
330
+ <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);" />
331
+
332
+ ---
333
+
334
+ ## License
335
+
336
+ [MIT](./LICENSE)
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # Sentry Miniapp SDK
1
+ # Sentry Miniapp SDK — 小程序监控 SDK
2
2
 
3
3
  ![npm version](https://img.shields.io/npm/v/sentry-miniapp)
4
4
  ![npm download](https://img.shields.io/npm/dm/sentry-miniapp)
@@ -7,7 +7,9 @@
7
7
  ![test coverage](https://img.shields.io/badge/test%20coverage-100%25-brightgreen.svg)
8
8
  ![license](https://img.shields.io/github/license/lizhiyao/sentry-miniapp)
9
9
 
10
- 一个基于 `@sentry/core` (v10.45.0) 核心构建的**多端小程序异常与性能监控 SDK**。旨在为小程序开发者提供与 Web 端一致的、强大且现代的 Sentry 监控体验。
10
+ 简体中文 | [English](./README.en.md)
11
+
12
+ 一个基于 `@sentry/core` (v10.45.0) 核心构建的**小程序监控 SDK**,提供**异常监控**、**性能监控**、离线缓存、分布式追踪等能力。支持微信、支付宝、字节跳动、百度、QQ、钉钉、快手等多端小程序及 Taro / uni-app 等跨端框架。
11
13
 
12
14
  > **💡 版本说明**
13
15
  >
@@ -39,7 +41,7 @@
39
41
  推荐使用 `npm` 进行安装。
40
42
 
41
43
  ```bash
42
- npm install sentry-miniapp --save
44
+ npm install sentry-miniapp
43
45
  ```
44
46
 
45
47
  > **注意:** `v1.1.0` 及以上版本已优化构建策略(内联依赖),**无需**再额外安装 `@sentry/core`。
@@ -48,6 +50,18 @@ npm install sentry-miniapp --save
48
50
 
49
51
  ---
50
52
 
53
+ ## 🤖 AI 辅助接入
54
+
55
+ 如果你使用 [Claude Code](https://claude.ai/code) 或 [Cursor](https://cursor.com),AI 可以自动引导你完成接入:
56
+
57
+ ```bash
58
+ npx skills add https://github.com/lizhiyao/sentry-miniapp --skill sentry-miniapp-sdk
59
+ ```
60
+
61
+ 安装后,在 AI 编辑器中输入"帮我接入 Sentry 监控"即可触发向导。
62
+
63
+ ---
64
+
51
65
  ## 🚀 快速接入
52
66
 
53
67
  ### 1. 前置准备
@@ -163,26 +177,45 @@ Sentry.addPerformanceMark('api-request-end');
163
177
  Sentry.measurePerformance('fetch-user-data', 'api-request-start', 'api-request-end');
164
178
  ```
165
179
 
166
- ---
180
+ ### 动态采样 (tracesSampler)
167
181
 
168
- ## 🗺️ Source Map 支持与配置
182
+ 除了全局 `sampleRate`,你还可以通过 `tracesSampler` 回调实现按页面、按场景的精细化采样控制:
169
183
 
170
- 在小程序中,报错堆栈的路径通常是各种虚拟路径(如 `appservice/pages/index.js`),这导致直接上传的 Source Map 无法被 Sentry 正确解析。
184
+ ```javascript
185
+ Sentry.init({
186
+ dsn: '...',
187
+ tracesSampler: ({ name, inheritOrSampleWith }) => {
188
+ // 核心页面 100% 采样
189
+ if (name.includes('pages/index') || name.includes('pages/pay')) {
190
+ return 1;
191
+ }
192
+ // 低优先级页面降低采样率
193
+ if (name.includes('pages/about') || name.includes('pages/settings')) {
194
+ return 0.1;
195
+ }
196
+ // 继承上游采样决策,或使用默认 50% 采样率
197
+ return inheritOrSampleWith(0.5);
198
+ },
199
+ });
200
+ ```
201
+
202
+ > **注意:** 设置 `tracesSampler` 后,`tracesSampleRate` 将被忽略。`tracesSampler` 的优先级更高。
171
203
 
172
- SDK 内部已经为您解决了这个痛点:
173
- 只要在 `Sentry.init` 时开启了 `enableSourceMap: true`(默认开启),SDK 会在报错时自动拦截并抹平各平台的虚拟路径,统一替换为标准前缀 `app:///`。
204
+ ---
205
+
206
+ ## 🗺️ Source Map 支持与配置
174
207
 
175
- 您**只需要在打包上传 Source Map 时,确保配置的 `url-prefix` `app:///` 即可**。
208
+ SDK 内置了多端堆栈路径归一化能力(`enableSourceMap: true`,默认开启),自动将各平台虚拟路径转换为统一的 `app:///` 前缀,配合 sentry-cli 即可实现 Source Map 解析。
176
209
 
177
- **使用 sentry-cli 上传示例:**
210
+ **快速上传示例:**
178
211
 
179
212
  ```bash
180
- sentry-cli releases files "your-project-release-id" upload-sourcemaps ./dist \
181
- --url-prefix "app:///" \
182
- --ext .js --ext .map
213
+ sentry-cli releases files “my-miniapp@1.0.0” upload-sourcemaps ./dist \
214
+ --url-prefix app:///” \
215
+ --ext js --ext map
183
216
  ```
184
217
 
185
- *(注:在微信开发者工具上传代码时,请**务必关闭**工具自带的“ES6转ES5”和“代码压缩”功能,将这些工作交给 Webpack/Vite 等构建工具,以防行列号错位。)*
218
+ > 详细的端到端配置指南(包括各构建工具配置、CI/CD 集成、验证与排查),请参阅 **[Source Map 完整配置指南](./docs/SOURCEMAP_GUIDE.md)**。
186
219
 
187
220
  ---
188
221
 
@@ -291,15 +324,15 @@ Sentry 官方的 Replay 功能强依赖于浏览器标准 DOM 环境(通过 rr
291
324
 
292
325
  ---
293
326
 
294
- ## 🤝 参与贡献
295
-
296
- 我们非常欢迎开发者提交 `Pull Request` 或通过 `Issues` 提出宝贵意见!
297
-
298
- 要参与本地开发:
327
+ ## 📖 文档导航
299
328
 
300
- 1. `npm install` 安装依赖
301
- 2. `npm run dev` 启动监听编译
302
- 3. `npm run test:all` 运行完整的单元测试与集成测试套件
329
+ | 文档 | 说明 |
330
+ |------|------|
331
+ | [Source Map 完整配置指南](./docs/SOURCEMAP_GUIDE.md) | 端到端 Source Map 配置,覆盖各构建工具、CI/CD 集成、验证与排查 |
332
+ | [多端兼容性报告](./docs/MultiPlatformCompatibilityReport.md) | 各小程序平台 API 兼容性矩阵与差异说明 |
333
+ | [示例项目](./examples/wxapp/) | 微信小程序完整接入示例 |
334
+ | [开发指南](./DEVELOPMENT.md) | 本地开发环境搭建与调试 |
335
+ | [贡献指南](./CONTRIBUTING.md) | 如何参与项目贡献 |
303
336
 
304
337
  ---
305
338