npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@wangyahao/monitor-sdk

v1.0.16

Published

一个全面的 Web 应用监控 SDK

Readme

Monitor SDK 使用指南

一个功能完整的前端监控 SDK,支持页面访问、性能监控、错误追踪、用户行为和网络请求监控。

安装

NPM 安装

npm install @wangyahao/monitor-sdk

CDN 引入

<!-- UMD 格式 -->
<script src="https://unpkg.com/@wangyahao/monitor-sdk/dist/monitor.umd.min.js"></script>

<!-- 或者使用未压缩版本用于调试 -->
<script src="https://unpkg.com/@wangyahao/monitor-sdk/dist/monitor.umd.js"></script>

使用方法

1. ES Module 方式

import { initMonitorSDK } from '@wangyahao/monitor-sdk';

// 初始化 SDK
const monitor = initMonitorSDK({
  reportUrl: 'https://your-server.com/api/monitor',
  appId: 'your-app-id',
  useBeacon: true,
  sampleRate: 1,
  autoClick: true,
  autoNetwork: true,
  debug: false,
});

// 设置用户ID(可选)
monitor.push(['setUserId', 'user123']);

2. UMD 方式(浏览器直接引入)

<script src="dist/monitor.umd.min.js"></script>
<script>
  // 手动初始化 SDK
  const monitor = initMonitorSDK({
    reportUrl: 'https://your-server.com/api/monitor',
    appId: 'your-app-id',
    useBeacon: true,
    sampleRate: 1,
    autoClick: true,
    autoNetwork: true,
    debug: false
  });
  
  // 也可以通过全局变量访问
  // const monitor = window.monitorSDK;
</script>

3. 命令队列方式(推荐)

<script>
  // 在 SDK 加载前就可以使用
  window._monitor = window._monitor || [];
  
  // 手动追踪页面访问
  _monitor.push(['trackPageView']);
  
  // 设置用户 ID
  _monitor.push(['setUserId', 'user123']);
  
  // 追踪自定义事件
  _monitor.push(['trackEvent', 'button_click', { button: 'submit' }]);
  
  // 设置自定义属性
  _monitor.push(['setCustom', 'version', '1.0.0']);
  
  // 手动上报
  _monitor.push(['flush']);
</script>

<!-- 异步加载 SDK -->
<script async src="dist/monitor.umd.min.js"></script>
<script>
  // SDK 加载完成后初始化
  window.addEventListener('load', function() {
    if (window.initMonitorSDK) {
      initMonitorSDK({
        reportUrl: 'https://your-server.com/api/monitor',
        appId: 'your-app-id',
        sampleRate: 0.1, // 10% 采样率
        debug: true
      });
    }
  });
</script>
## TypeScript 支持

```typescript
import { initMonitorSDK, type MonitorConfig } from '@wangyahao/monitor-sdk';

// 完整的类型支持
const config: MonitorConfig = {
  reportUrl: 'https://your-server.com/api/monitor',
  appId: 'your-app-id',
  sampleRate: 0.1
};

// 初始化 SDK
const monitor = initMonitorSDK(config);

配置选项

interface MonitorConfig {
  reportUrl: string;          // 上报接口地址(必填)
  appId: string;              // 应用 ID(必填)
  useBeacon?: boolean;        // 优先使用 sendBeacon(默认 true)
  sampleRate?: number;        // 采样率 0-1(默认 1)
  batchMax?: number;          // 单次批量上报最大条数(默认 20)
  flushIntervalMs?: number;   // 批量上报间隔毫秒(默认 10000)
  autoClick?: boolean;        // 自动点击事件追踪(默认 true)
  autoNetwork?: boolean;      // 自动网络请求监控(默认 true)
  beforeSend?: (payload) => payload | null; // 数据预处理函数
  debug?: boolean;            // 调试模式(默认 false)
}

API 方法

直接调用方式

// 设置用户 ID
monitor.identify('user123');

// 设置自定义属性
monitor.setCustom('version', '1.0.0');

// 追踪自定义事件
monitor.trackCustom('purchase', { 
  product: 'premium', 
  amount: 99.99 
});

命令队列方式

// 所有方法都可以通过命令队列调用
_monitor.push(['setUserId', 'user123']);
_monitor.push(['setCustom', 'version', '1.0.0']);
_monitor.push(['trackEvent', 'purchase', { product: 'premium' }]);
_monitor.push(['trackPageView']);
_monitor.push(['flush']);

// 获取统计信息(仅支持直接调用)
const stats = monitor.getSessionStats();
const userId = monitor.getUniqueUserId();

自动监控功能

SDK 会自动监控以下内容:

  • 页面访问:页面加载时自动发送 pageview 事件
  • 性能指标:FP、FCP、LCP、TTFB、DOM 加载时间等
  • 错误监控:JavaScript 错误、Promise 拒绝、资源加载错误
  • 用户行为:点击事件(可配置关闭)
  • 网络请求:Fetch 和 XMLHttpRequest 监控(可配置关闭)
  • 页面停留时间:页面卸载时自动上报

数据格式

上报的数据格式:

{
  "events": [
    {
      "appId": "your-app-id",
      "type": "pageview",
      "timestamp": 1640995200000,
      "sessionId": "session-uuid",
      "pageUrl": "https://example.com/page",
      "referrer": "https://google.com",
      "userAgent": "Mozilla/5.0...",
      "clientIP": "123.45.67.89",
      "data": {
        "pageTitle": "页面标题",
        "screenWidth": 1920,
        "screenHeight": 1080
      }
    }
  ]
}

IP 统计和用户访问统计

IP 地址统计

SDK 会自动获取并上报客户端 IP 地址,通过第三方 IP 查询服务实现:

// 上报数据中自动包含 clientIP 字段
{
  "clientIP": "123.45.67.89",
  "adcode": {
    "province": "上海市",
    "provinceCode": "310000",
    "city": "上海市",
    "cityCode": "310000",
    "region": "",
    "regionCode": "0"
  }
  // ... 其他字段
}

更新日志

2025-12-23

  • IP 接口更新:更换 IP 获取服务为 PCOnline 接口,提高国内访问稳定性。
  • 地理位置字段优化:规范化 adcode 字段结构,统一使用全称英文键名(如 province, city 等)。

用户访问统计

SDK 提供多种用户统计功能:

// 获取当前会话统计信息
const stats = monitor.getSessionStats();
console.log(stats);
// {
//   sessionId: "session-uuid",
//   userId: "user-uuid",
//   pageViews: 5,
//   totalEvents: 23,
//   sessionStart: 1640995200000
// }

// 获取用户唯一标识(用于统计用户数量)
const userId = monitor.getUniqueUserId();
console.log(userId); // "user-uuid"

用户识别机制

  • 会话 ID:基于 localStorage 的持久化会话标识
  • 用户 ID:支持自定义用户 ID,未设置时自动生成唯一标识
  • IP 地址:自动获取客户端 IP 用于地理位置分析

最佳实践

  1. 采样率设置:生产环境建议设置合适的采样率(如 0.1)以减少服务器压力
  2. 数据脱敏:使用 beforeSend 函数对敏感数据进行脱敏处理
  3. 错误处理:监控上报接口的可用性,避免影响主业务
  4. 性能优化:使用 CDN 加速 SDK 加载,采用异步加载方式
  5. 用户隐私:遵守 GDPR 等隐私法规,提供用户数据删除功能

构建命令

# 完整构建
npm run build

# 开发环境构建
npm run build:dev

# 生产环境构建
npm run build:prod

# 监听模式构建
npm run dev

# 清理构建产物
npm run clean

# 发布 
npm publish

输出文件

  • dist/monitor.esm.js - ES Module 格式
  • dist/monitor.esm.min.js - ES Module 压缩版
  • dist/monitor.umd.js - UMD 格式
  • dist/monitor.umd.min.js - UMD 压缩版
  • dist/monitor.d.ts - TypeScript 类型声明

故障排除

模块找不到问题

如果遇到 "找不到模块或其相应的类型声明" 错误:

  1. 确认包名正确

    // ✅ 正确
    import { MonitorSDK } from '@wangyahao/monitor-sdk';
       
    // ❌ 错误
    import { MonitorSDK } from 'monitor-sdk';
  2. 检查安装

    npm list @wangyahao/monitor-sdk
  3. TypeScript 配置: 确保 tsconfig.json 中的 moduleResolution 设置正确:

    {
      "compilerOptions": {
        "moduleResolution": "node"
      }
    }
  4. 重新安装

    npm uninstall @wangyahao/monitor-sdk
    npm install @wangyahao/monitor-sdk

构建工具配置

Webpack:无需额外配置,支持开箱即用

Vite:无需额外配置,支持开箱即用

Rollup:确保安装了 @rollup/plugin-node-resolve

浏览器兼容性

  • Chrome 60+
  • Firefox 55+
  • Safari 12+
  • Edge 79+

License

MIT

作者wx:wangyahao2020