miniapp-umami 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/GUIDE.md ADDED
@@ -0,0 +1,217 @@
1
+ # Umami 小程序 SDK
2
+
3
+ 应用通过 `umami.init(options)` 注入配置。以下示例业务说明来自示例仓库;独立包安装和通用接入见 [README](README.md)。SDK 不读取业务配置,也不复用业务请求层。
4
+
5
+ - `enabled` 为 `false` 时不会发送请求;开发联调时再显式开启。
6
+ - `debug` 只记录投递失败等 SDK 状态,不记录事件载荷或业务数据。
7
+ - 可选 `tag` 会附加到每个页面访问和自定义事件;联调使用 `test-audience`,可在 Umami 的 **Filter → Tag** 中筛选测试受众。它不会额外发送事件,因此不会改变跳出率。
8
+ - 页面统一用 `definePage` 注册,`onShow` 自动发送一次 PV;不要再手动发送 PV。
9
+ - `definePage` 还会在每个页面首次 `onReady` 后发送 `performance_page_ready`,其 `duration_ms` 是从该页面 `onLoad` 到业务 `onReady`(包括 `async onReady` 所等待工作)的耗时;首个就绪页面同时发送一次 `performance_app_startup`,表示 App `onLaunch` 到首屏就绪的耗时。
10
+ - SDK 会使用 `wx.getPerformance().createObserver()` 监听 `render` 条目:以 `firstRender.startTime` 为基准,分别上报 `firstContentfulPaint` 的 `performance_fcp` 和 `largestContentfulPaint` 的 `performance_lcp`,字段均为 `value_ms`。仅在三者时间戳有效且差值大于 0 时上报;旧基础库或不支持这些条目的设备会跳过,不影响业务。
11
+ - SDK 同时监听 `navigation` 和 `script` 条目:`appLaunch.duration` 上报为 `performance_app_launch`;分包页面的 `route.duration` 上报为 `performance_subpackage_route`;`evaluateScript.duration` 结合 `moduleName` 上报为 `performance_package_script`(主包记为 `main`)。在 `options.subpackages` 中维护 `app.json` 分包根目录与名称的映射。
12
+ - `performance_subpackage_route` 是用户实际等待的进入分包页面总耗时,可能包含下载、注入、初始化和页面切换;自动下载没有稳定的纯下载耗时 API,不能将该指标标记为纯下载时间。
13
+ - 微信小程序 Performance API 目前没有交互时序或布局偏移条目,因而不能据此计算真实 INP、CLS;SDK 不会用点击或 `setData` 耗时冒充这两个指标。
14
+ - 性能事件的自定义属性仅含白名单耗时/分包字段和当次入口场景;页面路由使用现有 Umami `url` 字段,不采集请求地址、设备唯一标识或业务数据。
15
+ - 只允许 `eventProperties` 配置声明的业务事件及属性,以及 SDK 内置的性能/实验事件。页面标题通过 `pageTitles` 配置。
16
+ - 队列最多 50 条;正常情况下最多合并 10 条、等待 1.5 秒后调用 `/api/batch`,以降低请求数。目标实例不支持批量接口时自动回退为逐条 `/api/send`。
17
+ - 网络和 5xx 最多重试两次,按指数退避并加入随机抖动;不会持久化或保证恰好一次投递。
18
+
19
+ 上线前须在真机验证 HTTPS request 合法域名、User-Agent 接受情况、referrer、语言展示及 UV 口径。当前局域网 endpoint 仅供开发环境联调。
20
+
21
+ ## 小程序发布版本
22
+
23
+ SDK 使用 `wx.getAccountInfoSync().miniProgram`,通过 `identify` 的会话属性上报:
24
+
25
+ | 属性 | 来源 | 示例 |
26
+ | --- | --- | --- |
27
+ | `miniapp_version` | `miniProgram.version` | `1.2.3` |
28
+ | `miniapp_env` | `miniProgram.envVersion` | `develop` / `trial` / `release` |
29
+
30
+ 版本信息在内存中缓存;接口缺失或调用失败时省略相应字段,不影响业务。版本字符串去空白并限制为 80 个 Unicode 字符;开发版返回空版本时省略,不使用 `package.json` 版本代替。不会采集 `appId`。`wx_version` 仍表示微信客户端版本,`wx_sdk_version` 仍表示基础库版本。错误协议保留现有的 `release` / `environment` 字段;热图协议未增加这些属性。
31
+
32
+ `miniapp_version`、`miniapp_env` 仅写入会话属性,供 **筛选器 → 会话属性** 按版本/环境筛选访问,不再重复附加到普通事件的 `data`。事件属性只包含该事件的业务、性能、实验数据及当次入口场景,可在支持事件属性的 **Events → Properties** 中分析。后台支持范围及实际入库仍须在目标实例验收,详见“会话属性”。
33
+
34
+ ## 会话属性
35
+
36
+ 默认开启(`options.sessionProperties: false` 可单独关闭),自动上报以下稳定字段:
37
+
38
+ - `miniapp_version`、`miniapp_env`:小程序发布版本、运行环境。
39
+ - `wx_brand`、`wx_model`、`wx_system`、`wx_platform`:设备品牌/型号、系统、平台。
40
+ - `wx_version`、`wx_sdk_version`、`wx_language`:微信版本、基础库版本、语言。
41
+
42
+ 仅从 SDK 内部的系统与版本上下文取白名单字段,缺失时省略;全部缺失时不发送。设备、版本和环境不再写入普通事件属性;屏幕/窗口尺寸和像素比也不再作为自定义属性发送,标准 `screen`、`language` 继续按协议上报。入口场景随当次事件记录,UTM 随 URL 记录,业务、性能和实验属性留在对应事件中;这些字段不写入会话属性。没有自定义字段时省略事件的 `data`。
43
+
44
+ 普通 `/api/send` 或 `/api/batch` 成功响应提供非空 `cache` 后,SDK 才通过独立 `/api/send` 发送 `{ type: 'identify', payload: { website, hostname, language, data } }`,请求头复用 `x-umami-cache`。不传 distinct ID、OpenID、设备 ID 或客户端 salt,不解析/伪造令牌,不改变匿名身份策略。只有机器人过滤响应或没有令牌时不会发送 `identify`。
45
+
46
+ 去重以真实服务端令牌为单位:同一令牌只启动一次属性投递,令牌更新后重新附加;这不保证每个后台会话恰好一次,令牌刷新可能产生额外属性写入。`identify` 响应更新令牌时不会循环触发自身;并发的旧响应不会覆盖已更新的普通采集令牌。该请求不会增加 PV 或业务事件,失败不阻塞普通统计。网络/5xx 最多重试两次并保留退避,4xx 不重试;同一令牌耗尽重试后不因每条新事件再次尝试。关闭统计会清空队列及去重状态,重新开启后等待新的真实令牌。
47
+
48
+ 验收时用真机触发访问,核对先收到真实 `cache`,再发送 `type: identify`。在 Umami **筛选器 → 会话属性** 中选择上述字段,验证对应页面访问及事件均能被筛选;注意时间范围与 `test-audience` 标签。HTTP 200 本身不代表入库成功,开发者工具机器人过滤仍适用。历史事件属性不会自动转换为会话属性,不做历史回填。通过异步网关采集时,网关还须同步返回真实会话令牌并转发 `identify` 及缓存头,仅有 `202 accepted` 的网关不足以支持此功能。
49
+
50
+ ## A/B 实验
51
+
52
+ SDK 提供本地稳定分组、显式曝光和转化事件归因。当前联调配置已开启首页发布按钮文案实验 `home_publish_cta`(revision 为 `v1`,A/B 各 50%):A 为“发布”,B 为“立即发布”,沿用相同点击事件与跳转。实验开关由 `options.experiments` 控制;关闭时不发送曝光或写入实验存储:
53
+
54
+ ```js
55
+ experiments: {
56
+ home_publish_cta: {
57
+ enabled: true,
58
+ revision: 'v1',
59
+ variants: { A: 50, B: 50 },
60
+ },
61
+ },
62
+ ```
63
+
64
+ - 实验 ID、revision、组名只允许 1–50 个英文字母、数字、下划线或连字符。每个实验 2–10 组,权重为正整数,按相对权重随机分配;配置无效则回退原界面。一次配置最多读取 20 个实验。
65
+ - 分组结果以 `umami:experiment:<websiteId>:<experimentId>:<revision>` 为键存入微信本地 storage,只保存组名,不生成或上传用户标识。相同本地存储、网站、实验及 revision 下跨启动保持分组;清理存储、换设备或变更 revision 后重新分组,不能保证跨设备或登录账户一致。旧 revision 的存储不会自动删除。
66
+ - 改变文案、权重或实验含义时递增 revision,并重新启动小程序;同一 revision 不应中途改组名或含义。关闭实验后恢复原按钮与普通业务事件;历史实验数据保留。
67
+ - 存储 API 不可用、读写抛错或 SDK 关闭时不参与实验,回退原界面。运行中 `setEnabled(false)` 会清空本次曝光状态;重新启用后需再次实际展示并上报曝光才能归因。
68
+
69
+ 业务接入使用三个方法:
70
+
71
+ ```js
72
+ const variant = umami.getVariant('home_publish_cta'); // 'A' / 'B',未参与时为 null;不自动曝光
73
+ // 将 variant 对应界面渲染出来,确认页面可见后调用:
74
+ umami.trackExposure('home_publish_cta');
75
+ // 替换原业务 track 调用,避免重复发送点击:
76
+ umami.trackExperiment('home_publish_cta', 'home_release_entry_click');
77
+ ```
78
+
79
+ `trackExposure` 发送 `experiment_exposure`,每个实验每次 App 启动最多一次(重新启用统计后可以再次曝光),不会增加 PV。示例首页在 `setData` 完成且页面未隐藏时记录曝光;这代表按钮渲染在可见页面上,不是按像素交叉观察确认的可见性。仅分组、打开其他页面或隐藏期间的渲染回调不会记录曝光。
80
+
81
+ 曝光与 `trackExperiment` 业务事件都使用 `exp_<实验ID>_<revision>: <组名>` 格式的事件属性。例如 B 组的曝光和点击均携带 `data: { exp_home_publish_cta_v1: 'B' }`(当次入口场景等事件属性仍可并存),不再发送 `experiment_id`、`experiment_revision`、`variant` 三个独立字段。实验属性由 SDK 生成,业务调用不能覆盖或伪造。未曝光、实验关闭或无效时,`trackExperiment` 仍发送原业务事件,但不带实验归因。普通 `track` 不自动归因,其他事件需显式使用 `trackExperiment`;事件及业务属性仍受 `sanitize.js` 白名单限制,不允许任意事件名或任意实验属性。多个实验分别记录,避免把未展示的分组附加到所有事件。
82
+
83
+ ### 查看结果与验收
84
+
85
+ 现有 `tag: test-audience` 保留为联调受众标签,实验分组通过独立属性记录,不覆盖 Tag。按以下方式验收:
86
+
87
+ 1. 启用示例实验并重新启动,在首页核对文案。检查 `/api/send` 或 `/api/batch` 中有 `experiment_exposure` 并携带 `exp_home_publish_cta_v1: 'A'` 或 `'B'`,版本/环境则通过独立 `identify` 写入会话属性;不能只凭 HTTP 200 判断入库,机器人过滤限制仍适用。
88
+ 2. 同一次启动多次进入首页,应只有一次曝光;点击发布应只有一个 `home_release_entry_click`,归因与曝光一致,且正常跳转发布页。再次启动应维持分组并产生新曝光;关闭实验后恢复“发布”,点击不携带实验属性。
89
+ 3. 在 Events → Properties 中分别查看曝光和点击事件,选择属性 `exp_home_publish_cta_v1`,按 `A` / `B` 组及相同时间窗口对比,环境使用会话属性过滤(须验证实例支持组合筛选)。revision 改为 `v2` 时属性名变为 `exp_home_publish_cta_v2`,不能混用不同 revision;目标实例若不支持属性筛选,需要升级或通过 API/导出分析。历史记录保持旧格式,不回填或改名。
90
+ 4. 当前可直接比较曝光次数和点击次数;重复点击会产生多条点击,点击次数/曝光次数可能超过 100%,不能当作用户转化率。按会话去重需要验证后台能按相同属性过滤并去重,且须接受 Umami 的匿名会话口径。若要“转化人数/曝光人数”,需另行设计稳定身份和去重方案。
91
+
92
+ 本实现不提供远程实验配置、跨设备分流、自动样本量计算、显著性检验或胜出方案发布。实验事件不会自动变成 Tag 全局总览筛选;如需用 Tag 对比整个访问过程,应另外设计其与测试受众标签的组合。历史事件不能补填实验归因,历史会话也不回填版本。本地回归运行 `npm test`,真机入库和后台展示仍需按上述步骤验收。
93
+
94
+ ## 系统与设备信息
95
+
96
+ SDK 使用微信 API 获取真实系统信息,稳定字段仅通过 `identify` 写入会话属性,不重复附加到 PV、业务和性能事件的 `data`,也不增加 PV 或业务事件。优先使用 `wx.getDeviceInfo`、`wx.getAppBaseInfo`、`wx.getWindowInfo`;接口不可用或抛错时回退 `wx.getSystemInfoSync`,全部失败时跳过缺失字段,不影响业务。官方已停止维护 `wx.getSystemInfo`,因此不新增对它的调用。
97
+
98
+ | 属性 | 微信 API 字段 |
99
+ | --- | --- |
100
+ | `wx_brand`、`wx_model` | `brand`、`model` |
101
+ | `wx_system`、`wx_platform` | `system`、`platform` |
102
+ | `wx_version`、`wx_sdk_version` | 微信 `version`、基础库 `SDKVersion` |
103
+ | `wx_language` | `language`,如 `zh_CN` 规范化为 `zh-CN` |
104
+
105
+ 字符串去首尾空白且最多 80 个 Unicode 字符。设备与客户端信息在内存中缓存;窗口信息每次构建普通采集载荷时更新,用于标准 `screen`(优先屏幕尺寸,缺失时使用窗口尺寸,仅接受有限正数)。Umami 标准 `language` 同步使用 API 语言。尺寸和像素比不再生成 `wx_*` 自定义属性。
106
+
107
+ 在 Umami 的“筛选器 → 会话属性”中查看设备与客户端 `wx_*` 字段。事件属性中的 `wx_scene`、`wx_scene_name`、`wx_scene_category` 仍表示当次入口归因。这些属性不会自动改写依赖请求 User-Agent 的标准浏览器/操作系统分类,也不会解除模拟器的机器人过滤。SDK 不生成设备 ID、不上传系统权限开关、宿主 appId 或系统信息完整对象。
108
+
109
+ ## UTM 渠道统计
110
+
111
+ 在推广二维码或分享入口的小程序页面路径中携带渠道参数,例如:
112
+
113
+ ```text
114
+ pages/home/index?utm_source=wechat&utm_medium=qrcode&utm_campaign=模拟拉新活动
115
+ ```
116
+
117
+ 开发者工具中可将启动页面设为 `pages/home/index`、场景值设为 `1047`、启动参数设为 `utm_campaign=模拟拉新活动`;SDK 会补齐 `utm_source=wechat`、`utm_medium=qrcode`。重新编译后检查请求与 Umami 的 **增长 → UTM**。构造实际二维码/分享 URL 时应将中文活动名 URL 编码一次;填写开发者工具的原始启动参数时可直接使用中文。
118
+
119
+ 目标实例可能将开发者工具 User-Agent 识别为机器人:`/api/send` 返回 `200` 和 `{"beep":"boop"}` 表示跳过入库,批量接口的 `processed` 也不保证已入库。应结合实际报表或真机验收;本次联调记录见 示例仓库的 `docs/umami-verification.md`。
120
+
121
+ - App 的 `onLaunch` / `onShow` 将完整入口参数交给 `setEntryOptions`。入口 `query` 仍只读取 `utm_source`、`utm_medium`、`utm_campaign`、`utm_term`、`utm_content`:只接受非空字符串,每项最多 80 个 Unicode 字符,编码后放入页面访问和自定义事件的 `payload.url` 查询串,供 Umami 解析。
122
+ - **显式 UTM 优先**:存在有效的微信顶层数字 `options.scene` 时,按场景补齐缺失的 Source(`wechat`)及 Medium;不覆盖入口已有的有效字段。无效或空值按缺失处理。场景只说明入口类型,无法推断活动名称,因此绝不自动生成 Campaign、Term、Content。
123
+ - 渠道与场景仅保存在内存中,本次前台访问的页面切换、业务和性能事件沿用同一入口;每次 App `onShow` 整体替换,无 UTM 时按新场景重新推导,无有效场景且无 UTM 时清空。不继承旧活动、不持久化,已入队记录保留发送时的入口快照。
124
+ - 页面和事件的 `payload.data` 都会附加 `wx_scene`(字符串)、`wx_scene_name`(简短中文说明)、`wx_scene_category`(分类)。它们与同一条记录 URL 中的 UTM 关联,可在数据细分/事件属性中按场景筛选并结合 UTM 分析;增长 UTM 面板本身仍显示 Source、Medium、Campaign 等标准维度。
125
+ - 页面的业务 query 仍全部移除。**顶层 `options.scene` 与二维码业务参数 `options.query.scene` 不同**:后者不会被当成官方场景值或解析成活动,也不上传原文。`referrerInfo`、`shareTicket`、手机号、Token 不上传。自定义小程序码活动需在业务侧定义可信映射后再提供白名单 UTM。
126
+ - `tag: test-audience` 只标记受众,不生成活动名称。不要把手机号、用户标识等个人信息填入 UTM 值。
127
+ - 不增加额外 PV 或业务事件;历史未采集 UTM 的访问不会自动补齐。
128
+
129
+ ### UTM 字段与“暂无数据”说明
130
+
131
+ Umami 的 **增长 → UTM** 分别统计以下五个字段。字段可按推广需要填写,不要求每次访问都包含全部五项。
132
+
133
+ | 参数 | 报表维度 | 用途 | 示例 |
134
+ | --- | --- | --- | --- |
135
+ | `utm_source` | Source(来源) | 区分推广来源或合作方 | `wechat`、`partner_a` |
136
+ | `utm_medium` | Medium(媒介) | 区分推广方式 | `qrcode`、`social`、`paid` |
137
+ | `utm_campaign` | Campaign(活动) | 区分具体推广活动 | `launch_2026` |
138
+ | `utm_content` | Content(内容) | 区分素材版本或投放位置 | `poster_a`、`home_banner` |
139
+ | `utm_term` | Term(关键词) | 区分投放关键词,无关键词推广时可留空 | `discount` |
140
+
141
+ **为什么还有两项“暂无数据”?** 如果入口只携带 Source、Medium、Campaign,则 Content 和 Term 没有可统计的值,显示“暂无数据”是正常情况,不表示采集失败。SDK 已支持这两个可选字段,但不会从设备信息、微信场景或活动名称中自动生成它们,也不应为了填满报表而填写无意义的值。
142
+
143
+ 需要同时区分素材和关键词时,可使用完整入口:
144
+
145
+ ```text
146
+ pages/home/index?utm_source=wechat&utm_medium=qrcode&utm_campaign=launch_2026&utm_content=poster_a&utm_term=discount
147
+ ```
148
+
149
+ 开发者工具启动页面填写 `pages/home/index`,启动参数填写:
150
+
151
+ ```text
152
+ utm_source=wechat&utm_medium=qrcode&utm_campaign=launch_2026&utm_content=poster_a&utm_term=discount
153
+ ```
154
+
155
+ 修改入口后,需要从该入口重新进入小程序并产生新访问;原有不含 Content / Term 的记录不会自动补齐。验收时检查 `/api/send` 或 `/api/batch` 中的 `payload.url` 是否包含这两个参数,再选择包含新访问时间的报表范围。若请求参数齐全但报表仍为空,继续检查服务端是否接受并入库;模拟器的机器人过滤限制见上文。
156
+
157
+ 品牌、型号、系统、微信版本等设备信息保存在 `identify` 的 `data.wx_*` 会话属性中,不属于 UTM,也不会填充这五个报表维度。
158
+
159
+ ### 场景分类示例
160
+
161
+ 场景值以[微信官方场景表](https://developers.weixin.qq.com/miniprogram/dev/reference/scene-list.html)为准;分类名是本项目的渠道约定,映射位于 `entry.js`。
162
+
163
+ | 微信场景值 | 入口 | 缺省 Medium |
164
+ | --- | --- | --- |
165
+ | `1007` / `1008` | 单聊 / 群聊小程序卡片 | `chat_share` / `group_share` |
166
+ | `1011`–`1013`、`1047`–`1049` | 二维码 / 小程序码 | `qrcode` |
167
+ | `1005`、`1006`、`1053` | 搜索结果 | `search` |
168
+ | `1035`、`1058` | 公众号菜单 / 文章 | `official_account` |
169
+ | `1045`、`1046`、`1067`、`1200` | 广告入口 | `ad` |
170
+ | `1001`、`1089`、`1090` | 最近使用 | `recent` |
171
+ | `1030`、`1101` | 自动化测试 / 远程调试 | `test` |
172
+ | `1065` / `1194` | URL Scheme / URL Link | `url_scheme` / `url_link` |
173
+ | 有效但映射未收录的四位整数 | 保留 `wx_scene`,名称为“未分类场景” | `other` |
174
+
175
+ 未提供合法顶层数字场景时不生成场景数据,也不推导 Source / Medium。这里只维护常用分类,不保证覆盖官方所有场景;新增场景不会因映射缺失中断业务。
176
+
177
+ 本地回归检查:`npm test`。
178
+
179
+ ## 错误监控
180
+
181
+ `options.errors.enabled: true` 启用错误采集。`app.js` 的 `onError` 和 `onUnhandledRejection` 分别上报运行异常和未处理的 Promise 拒绝,标记 `handled: false`。已捕获、仍需监控的错误可手动上报:
182
+
183
+ ```js
184
+ import umami from 'miniapp-umami';
185
+
186
+ try {
187
+ // 业务操作
188
+ } catch (error) {
189
+ umami.captureException(error); // handled: true;不改变业务自身的异常处理
190
+ }
191
+ ```
192
+
193
+ 错误采用目标实例公开采集脚本的独立协议:`POST /api/send`,请求体为 `{ type: 'error', payload }`,不会写成普通事件或增加 PV。可用 `errors.endpoint` 覆盖错误接收地址。请求复用真实服务端 `cache`,不生成用户/设备 ID;每次错误生成独立 UUID,重试保留同一个 ID,供服务端去重。没有会话令牌时仍可提交错误,会话归属和是否接受由服务端决定。
194
+
195
+ - 包含错误类型、首行消息、堆栈、去掉 query/hash 的当前页面、发生时间、`handled`、语言和屏幕尺寸;`tags.source` 区分 `runtime`、`unhandledrejection`、`manual`,设备标签只保留指定的 `wx_*` 字段。不上传原始拒绝事件、Promise、业务对象、表单或页面数据。
196
+ - `release` 默认读取 `wx.getAccountInfoSync().miniProgram.version`,`environment` 默认使用 `envVersion`(`develop` / `trial` / `release`);开发版没有版本号时保持为空,不生成虚假版本。可在 `errors` 下显式配置 `release`、`environment`,用于后台版本/环境筛选。
197
+ - 消息最多 2000 字符,堆栈最多 8000 字符;移除 URL 查询参数、fragment 和 URL 内认证信息,脱敏邮箱、常见手机号、JWT、Bearer 及密码/Token/OpenID 等键值。任意业务文本无法靠模式匹配完全脱敏,错误文案仍应避免包含用户输入或个人信息;未识别的拒绝对象只记为 `Non-Error exception`。
198
+ - 同页面、同内容、同处理状态的错误在 1 秒内抑制重复,每分钟最多 20 条,队列最多 20 条;只在内存中保留。错误逐条立即发送,网络/5xx 最多重试两次,遵守退避;`429` 清空待发队列并按 `Retry-After` 暂停(缺省 60 秒,范围 1–300 秒),其他 4xx 不重试。
199
+ - `umami.setEnabled(false)` 同时停止错误采集并清空队列;已交给网络层的请求无法撤回。监控自身失败不会向业务抛异常。`errors.enabled: false` 可单独在启动配置中关闭错误监控;不自动采集 `console.error` 或所有接口失败。
200
+
201
+ 在 **监控 → 错误** 按页面、版本、环境和时间筛选,进入问题查看堆栈与发生次数。堆栈保留微信提供的位置,当前没有源码映射上传功能。模拟器响应 `200` 且 `{ ok: false, reason: 'bot' }` 表示被过滤,不能视为入库成功。实际联调记录与真机验收步骤见 示例仓库的 `docs/umami-verification.md`;错误专项回归为 `tests/errors.test.cjs`,随 `npm test` 执行。
202
+
203
+ ## 行为热图(2026-11-20)
204
+
205
+ `options.heatmap.enabled: true` 启用小程序适配。启动后读取 `/api/websites/{websiteId}/recorder`,仅在服务端 `enabled`、`heatmapEnabled` 均为真且本次启动命中 `heatmapSampleRate` 时采集。采样按 App 启动决定,变更服务端设置后需重新进入小程序。
206
+
207
+ 热图使用独立协议:`POST /api/record`,请求体为 `{ type: 'heatmap', payload: { website, events } }`。普通 `/api/send` 或 `/api/batch` 返回的 `cache` 令牌仅保存在内存,并以 `x-umami-cache` 请求头复用;没有有效服务端令牌时不发送热图。热图最多缓冲 50 条,每批最多 20 条、等待 2 秒;网络/5xx 最多重试两次,页面隐藏或 App 切后台时尽力刷新队列。关闭 SDK 会清空队列和令牌。自定义网关需要分别转发 record/config 接口,可用 `heatmap.endpoint`、`heatmap.configEndpoint` 指定完整地址。
208
+
209
+ - 页面根节点用 `capture-bind:tap` 读取真实触摸点;不阻止业务事件。只保留坐标、视口/页面尺寸、时间和去掉 query/hash 的路由,不读取元素文字、dataset、表单值或聊天内容。仅有 `detail` 的组件语义事件不构造虚假的点击位置;自定义 TabBar 独立组件的点击未覆盖。
210
+ - 普通页面通过 `onPageScroll` 每 400ms 查询几何信息、记录新增的最大阅读深度。`scrollPct` 表示 `(scrollTop + viewportH) / pageH`,不是滑动距离占比。
211
+ - 消息/聊天的原生 `scroll-view` 单独测量内容和滚动偏移,点击与深度写入 `/pages/message/index/heatmap-scroll`、`/pages/chat/index/heatmap-scroll`,避免与外层页面坐标混用。
212
+ - 首页和“我的”使用组件/CSS 内部滚动,当前只统计可见视口的点击,不将这些点击解释为长页面上的内容位置,也不上报无法测得的内部滚动深度。其他内部滚动容器接入时需要独立适配,不能直接用 Page 的 `onPageScroll` 替代。
213
+ - `umami.getHeatmapStatus()` / 页面方法 `__umamiHeatmapStatus()` 只返回 `collecting`、`hasSession`、`queued`,供联调诊断,不返回令牌。
214
+
215
+ 当前部署的 Umami 热图背景采用“网站域名 + 路由”的 iframe,例如 `https://miniapp.xiaoanai.top/pages/home/index`。小程序没有对应网页,因此采集成功并不等于可以展示真实页面背景;需在远程部署适配静态页面/截图背景,并按视口宽度、路由、页面版本及滚动容器匹配。SDK 不自动截屏或上传页面内容。历史未采集的坐标不能回填。
216
+
217
+ 真机联调及当前限制见 示例仓库的 `docs/umami-verification.md`。热图专项测试位于 `tests/heatmap.test.cjs`,可运行 `npm test`。
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 leejimqiu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,79 @@
1
- # Temporary Holding Version
1
+ # miniapp-umami
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 用于微信小程序的 Umami SDK,零运行时依赖。支持页面访问、白名单事件、UTM/入口场景、性能指标、会话属性、A/B 实验,以及可选错误监控和行为热图。
4
+
5
+ ## 安装和接入
6
+
7
+ 发布后安装:
8
+
9
+ ```sh
10
+ npm install miniapp-umami
11
+ ```
12
+
13
+ 示例仓库使用 `file:packages/umami` 本地依赖;在仓库根目录安装依赖后,先执行 `npm run build:umami`,再在微信开发者工具构建 npm。
14
+
15
+ 本地验证可在本目录执行 `npm pack`,然后在目标项目中 `npm install /path/to/miniapp-umami-0.1.0.tgz`。微信开发者工具中执行「工具 → 构建 npm」。包的 `miniprogram` 入口为编译后的 CommonJS `lib/`,ES module 消费者使用 `src/`。
16
+
17
+ ```js
18
+ // app.js
19
+ import umami from 'miniapp-umami';
20
+
21
+ App({
22
+ onLaunch(options) {
23
+ umami.init({
24
+ enabled: true,
25
+ endpoint: 'https://analytics.example.com/api/send',
26
+ websiteId: 'your-website-id',
27
+ hostname: 'miniapp.example.com',
28
+ eventProperties: { purchase: ['amount', 'currency'] },
29
+ pageTitles: { '/pages/home/index': '首页' },
30
+ });
31
+ umami.setEntryOptions(options);
32
+ umami.markLaunch();
33
+ },
34
+ onShow(options) { umami.setEntryOptions(options); },
35
+ onHide() { umami.flush(); },
36
+ onError(error) {
37
+ umami.captureException(error, { handled: false, source: 'runtime' });
38
+ },
39
+ onUnhandledRejection(event) {
40
+ umami.captureException(event.error || event.reason, { handled: false, source: 'unhandledrejection' });
41
+ },
42
+ });
43
+ ```
44
+
45
+ ```js
46
+ // pages/home/index.js
47
+ import umami from 'miniapp-umami';
48
+ import { definePage } from 'miniapp-umami/page';
49
+
50
+ definePage({
51
+ onPurchase() {
52
+ umami.track('purchase', { amount: 99, currency: 'CNY' });
53
+ },
54
+ });
55
+ ```
56
+
57
+ `definePage` 代替 `Page`,自动统计页面访问与就绪耗时,保留业务生命周期及返回值;不要重复手动发送 PV。页面标题按规范化路由(带前导 `/`)从 `pageTitles` 读取,缺失时为空。
58
+
59
+ `eventProperties` 声明业务事件及允许的属性名;未声明的事件和属性会丢弃。SDK 自带性能/实验事件白名单,不包含示例项目的业务事件。属性仅允许字符串(最多 80 字符)、有限数字、布尔值,事件数据最多 512 字符。不上传任意对象、完整路由 query 或用户标识。
60
+
61
+ `init` 每个小程序运行周期只生效一次;须在启动时传入完整配置。`enabled`、`endpoint`、`websiteId`、`hostname` 均需有效才能启用。`setEnabled(false)` 停止采集,`setEnabled(true)` 恢复已初始化的统计。运行环境需提供微信的 `wx`、`Page`、`getCurrentPages`,不是浏览器或 Node 服务端 SDK。
62
+
63
+ 其他配置包括 `tag`、`debug`、`batchSize`、`batchDelay`、`batchEndpoint`、`sessionProperties`、`subpackages`、`experiments`、`errors`、`heatmap`。错误监控与热图默认关闭,需分别传入 `{ enabled: true }`;热图还需要目标服务端支持对应协议。生产接入需配置 HTTPS request 合法域名。详细协议、API、采集限制见 [使用指南](GUIDE.md)。
64
+
65
+ ## 开发和发布
66
+
67
+ 需要 Node.js 18+。
68
+
69
+ ```sh
70
+ npm ci
71
+ npm run build
72
+ npm test
73
+ npm pack --dry-run
74
+ npm pack
75
+ # 确认包名、版本和 npm 账户后发布
76
+ npm publish
77
+ ```
78
+
79
+ `prepack` 自动构建;发布内容仅包含源码、CommonJS 产物、说明和许可证,不包含示例应用、配置、测试或开发工具。ESM 使用默认导入;CommonJS 使用 `require('miniapp-umami').default`,页面包装器使用 `require('miniapp-umami/page').definePage`。同一应用保持一种模块格式,避免同时加载两个 SDK 实例。
package/lib/entry.js ADDED
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createEntryContext = createEntryContext;
4
+ const sanitize_js_1 = require("./sanitize.js");
5
+ // 常用入口按微信官方场景表分类;未列出的有效场景保留原值,归入 other。
6
+ // https://developers.weixin.qq.com/miniprogram/dev/reference/scene-list.html
7
+ const SCENES = {
8
+ 1000: ['其他', 'other'],
9
+ 1001: ['发现页小程序最近使用', 'recent'],
10
+ 1005: ['微信首页顶部搜索结果', 'search'],
11
+ 1006: ['发现栏小程序搜索结果', 'search'],
12
+ 1007: ['单聊小程序消息卡片', 'chat_share'],
13
+ 1008: ['群聊小程序消息卡片', 'group_share'],
14
+ 1010: ['收藏夹', 'favorites'],
15
+ 1011: ['扫描二维码', 'qrcode'],
16
+ 1012: ['长按图片识别二维码', 'qrcode'],
17
+ 1013: ['相册识别二维码', 'qrcode'],
18
+ 1014: ['小程序订阅消息', 'subscription_message'],
19
+ 1017: ['体验版入口', 'test'],
20
+ 1023: ['安卓桌面图标', 'desktop'],
21
+ 1025: ['扫描一维码', 'barcode'],
22
+ 1027: ['顶部搜索使用过的小程序', 'search'],
23
+ 1030: ['自动化测试', 'test'],
24
+ 1031: ['长按图片识别一维码', 'barcode'],
25
+ 1032: ['相册识别一维码', 'barcode'],
26
+ 1035: ['公众号自定义菜单', 'official_account'],
27
+ 1036: ['App分享消息卡片', 'app_share'],
28
+ 1037: ['小程序打开小程序', 'mini_program'],
29
+ 1038: ['从另一个小程序返回', 'mini_program'],
30
+ 1044: ['带shareTicket的小程序消息卡片', 'chat_share'],
31
+ 1045: ['朋友圈广告', 'ad'],
32
+ 1046: ['朋友圈广告详情页', 'ad'],
33
+ 1047: ['扫描小程序码', 'qrcode'],
34
+ 1048: ['长按图片识别小程序码', 'qrcode'],
35
+ 1049: ['相册识别小程序码', 'qrcode'],
36
+ 1053: ['搜一搜结果页', 'search'],
37
+ 1058: ['公众号文章', 'official_account'],
38
+ 1059: ['体验版绑定邀请页', 'test'],
39
+ 1065: ['URL Scheme', 'url_scheme'],
40
+ 1067: ['公众号文章广告', 'ad'],
41
+ 1069: ['移动应用OpenSDK', 'app'],
42
+ 1073: ['客服消息小程序卡片', 'customer_service'],
43
+ 1074: ['公众号消息小程序卡片', 'official_account'],
44
+ 1081: ['客服消息文字链', 'customer_service'],
45
+ 1082: ['公众号消息文字链', 'official_account'],
46
+ 1084: ['朋友圈广告原生页', 'ad'],
47
+ 1089: ['聊天主界面下拉最近使用', 'recent'],
48
+ 1090: ['右上角菜单最近使用', 'recent'],
49
+ 1095: ['小程序广告组件', 'ad'],
50
+ 1101: ['远程调试热更新', 'test'],
51
+ 1103: ['发现页我的小程序', 'favorites'],
52
+ 1104: ['聊天主界面下拉我的小程序', 'favorites'],
53
+ 1106: ['聊天主界面下拉搜索结果', 'search'],
54
+ 1107: ['订阅消息', 'subscription_message'],
55
+ 1129: ['微信爬虫访问', 'crawler'],
56
+ 1154: ['朋友圈单页模式', 'timeline'],
57
+ 1155: ['单页模式打开小程序', 'single_page'],
58
+ 1158: ['群工具', 'group_tools'],
59
+ 1167: ['H5开放标签', 'webview'],
60
+ 1189: ['表情雨广告', 'ad'],
61
+ 1194: ['URL Link', 'url_link'],
62
+ 1200: ['视频号广告', 'ad'],
63
+ 1223: ['安卓桌面Widget', 'desktop'],
64
+ 1286: ['明文Scheme', 'url_scheme'],
65
+ };
66
+ function createEntryContext(entryOptions = {}) {
67
+ const entry = entryOptions && typeof entryOptions === 'object' ? entryOptions : {};
68
+ const { scene } = entry;
69
+ const validScene = Number.isInteger(scene) && scene >= 1000 && scene <= 9999;
70
+ const data = {};
71
+ let defaults = {};
72
+ if (validScene) {
73
+ const [name, category] = SCENES[scene] || ['未分类场景', 'other'];
74
+ data.wx_scene = String(scene);
75
+ data.wx_scene_name = name;
76
+ data.wx_scene_category = category;
77
+ defaults = { utm_source: 'wechat', utm_medium: category };
78
+ }
79
+ // 先过滤显式参数;无效值不应覆盖场景推导出的默认渠道。
80
+ const explicitQuery = (0, sanitize_js_1.sanitizeUtmQuery)(entry.query);
81
+ const explicitKeys = explicitQuery.split('&').map((parameter) => parameter.split('=')[0]);
82
+ explicitKeys.forEach((key) => {
83
+ delete defaults[key];
84
+ });
85
+ const query = [(0, sanitize_js_1.sanitizeUtmQuery)(defaults), explicitQuery].filter(Boolean).join('&');
86
+ return { query, data };
87
+ }
package/lib/errors.js ADDED
@@ -0,0 +1,179 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.sanitizeErrorText = sanitizeErrorText;
7
+ const transport_js_1 = __importDefault(require("./transport.js"));
8
+ const sanitize_js_1 = require("./sanitize.js");
9
+ const MAX_ERRORS = 20;
10
+ const SOURCES = ['manual', 'runtime', 'unhandledrejection'];
11
+ const SYSTEM_TAGS = ['wx_platform', 'wx_system', 'wx_brand', 'wx_model', 'wx_version', 'wx_sdk_version'];
12
+ // Keep diagnostic text, never query strings, credentials or complete rejection objects.
13
+ function sanitizeErrorText(value, limit = 2000) {
14
+ if (typeof value !== 'string')
15
+ return '';
16
+ return value
17
+ .slice(0, limit)
18
+ .replace(/(?:https?|wxfile|file|weapp):\/\/[^\s)]+/gi, (url) => {
19
+ const position = (url.match(/:\d+(?::\d+)?$/) || [''])[0];
20
+ return url.split(/[?#]/)[0].replace(/(\/\/)[^/@\s]+@/, '$1') + (/[?#]/.test(url) ? position : '');
21
+ })
22
+ .replace(/(\/[\w./-]+)\?[^\s)]*/g, '$1')
23
+ .replace(/[\w.+-]+@[\w.-]+\.[a-z]{2,}/gi, '[email]')
24
+ .replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]+\b/g, '[token]')
25
+ .replace(/\bBearer\s+[^\s,;]+/gi, 'Bearer [redacted]')
26
+ .replace(/\b(password|secret|token|authorization|api[_-]?key|cookie|openid|unionid|phone|mobile|keyword)\b["']?\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1=[redacted]')
27
+ .replace(/\b(?:\+?86[- ]?)?1[3-9]\d{9}\b/g, '[phone]')
28
+ .slice(0, limit);
29
+ }
30
+ function eventId() {
31
+ // A per-occurrence id for server deduplication, never a device or user identifier.
32
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (char) => {
33
+ const random = Math.floor(Math.random() * 16);
34
+ return (char === 'x' ? random : (random % 4) + 8).toString(16);
35
+ });
36
+ }
37
+ function appVersion(config) {
38
+ let info = {};
39
+ try {
40
+ if (typeof wx.getAccountInfoSync === 'function')
41
+ info = wx.getAccountInfoSync().miniProgram || {};
42
+ }
43
+ catch (error) {
44
+ // Older base libraries may not expose account information.
45
+ }
46
+ return {
47
+ release: sanitizeErrorText(config.release || info.version, 100),
48
+ environment: sanitizeErrorText(config.environment || info.envVersion || 'unknown', 50),
49
+ };
50
+ }
51
+ class ErrorMonitor extends transport_js_1.default {
52
+ constructor(options, source, getContext) {
53
+ const config = options.errors;
54
+ super({
55
+ endpoint: config.endpoint || options.endpoint,
56
+ batchSize: 1,
57
+ debug: options.debug,
58
+ getHeaders: () => (source.sessionCache ? { 'x-umami-cache': source.sessionCache } : {}),
59
+ onResponse: (data) => {
60
+ if (data && typeof data.cache === 'string')
61
+ source.sessionCache = data.cache;
62
+ },
63
+ });
64
+ this.batchEndpoint = '';
65
+ this.website = options.websiteId;
66
+ this.source = source;
67
+ this.getContext = getContext;
68
+ this.version = appVersion(config);
69
+ this.recent = new Map();
70
+ this.minute = -1;
71
+ this.count = 0;
72
+ this.blockedUntil = 0;
73
+ this.capturing = false;
74
+ }
75
+ capture(error, context = {}) {
76
+ if (!this.enabled || this.capturing || this.queue.length >= MAX_ERRORS || Date.now() < this.blockedUntil)
77
+ return;
78
+ this.capturing = true;
79
+ try {
80
+ const now = Date.now();
81
+ const minute = Math.floor(now / 60000);
82
+ if (this.minute !== minute) {
83
+ this.minute = minute;
84
+ this.count = 0;
85
+ }
86
+ if (this.count >= MAX_ERRORS)
87
+ return;
88
+ const object = error && typeof error === 'object' ? error : {};
89
+ const rawMessage = typeof object.message === 'string' ? object.message : error;
90
+ let rawStack = typeof error === 'string' ? error : '';
91
+ if (typeof object.stack === 'string')
92
+ rawStack = object.stack;
93
+ let message = 'Non-Error exception';
94
+ if (typeof rawMessage === 'string')
95
+ [message] = rawMessage.split('\n');
96
+ else if (['number', 'boolean'].includes(typeof rawMessage))
97
+ message = String(rawMessage);
98
+ message = sanitizeErrorText(message);
99
+ const inferredName = (message.match(/^([\w.]*Error):/) || [])[1];
100
+ const name = sanitizeErrorText(object.name || inferredName || 'Error', 200) || 'Error';
101
+ const stack = sanitizeErrorText(rawStack, 8000);
102
+ const info = this.getContext();
103
+ const url = sanitizeErrorText((0, sanitize_js_1.normalizeRoute)((info.url || '').split(/[?#]/)[0]) || '/', 500);
104
+ const handled = context.handled !== false;
105
+ const key = JSON.stringify([name, message, stack, url, handled]);
106
+ this.recent.forEach((time, recentKey) => {
107
+ if (now - time >= 1000)
108
+ this.recent.delete(recentKey);
109
+ });
110
+ if (this.recent.has(key))
111
+ return;
112
+ const tags = {
113
+ source: SOURCES.includes(context.source) ? context.source : 'manual',
114
+ platform: 'wechat-miniprogram',
115
+ };
116
+ SYSTEM_TAGS.forEach((key) => {
117
+ const value = sanitizeErrorText(info.data && info.data[key], 80);
118
+ if (value)
119
+ tags[key] = value;
120
+ });
121
+ this.recent.set(key, now);
122
+ this.count += 1;
123
+ this.enqueue({
124
+ type: 'error',
125
+ payload: {
126
+ version: 1,
127
+ website: this.website,
128
+ eventId: eventId(),
129
+ timestamp: now,
130
+ name,
131
+ message: message || 'Unknown error',
132
+ stack,
133
+ handled,
134
+ url,
135
+ language: info.language,
136
+ ...(info.screen ? { screen: info.screen } : {}),
137
+ ...this.version,
138
+ tags,
139
+ },
140
+ });
141
+ }
142
+ catch (error) {
143
+ // Reporting must not throw, stringify arbitrary business objects, or recurse.
144
+ }
145
+ finally {
146
+ this.capturing = false;
147
+ }
148
+ }
149
+ request(url, items) {
150
+ try {
151
+ super.request(url, items, items[0].body, false);
152
+ }
153
+ catch (error) {
154
+ this.sending = false;
155
+ this.inFlightCount = 0;
156
+ this.retryOrDrop(items, true);
157
+ }
158
+ }
159
+ drain() {
160
+ // New errors and lifecycle flushes must still respect an earlier retry's backoff.
161
+ super.drain();
162
+ }
163
+ handleFailure(items, status, headers = {}) {
164
+ if (status === 429) {
165
+ const responseHeaders = headers || {};
166
+ const seconds = Number(responseHeaders['Retry-After'] || responseHeaders['retry-after']) || 60;
167
+ this.blockedUntil = Date.now() + Math.max(1, Math.min(seconds, 300)) * 1000;
168
+ this.clear();
169
+ return;
170
+ }
171
+ super.handleFailure(items, status, headers);
172
+ }
173
+ setEnabled(value) {
174
+ super.setEnabled(value);
175
+ if (!value)
176
+ this.recent.clear();
177
+ }
178
+ }
179
+ exports.default = ErrorMonitor;