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

@sensorswave/node-sdk

v1.0.1

Published

Sensors Wave Node.js server-side analytics SDK (event tracking, user profile, AB testing)

Readme

@sensorswave/node-sdk

Sensors Wave Node.js 服务端埋点上报 SDK:事件采集、用户身份管理、用户属性、AB 测试与异常采集。

基础功能严格对齐 sdk-go(服务端 Go SDK),跨 SDK 一致性由 golden 对拍套件锁定(187 case)。

特性

  • 同步 Fire-and-forget API:除 AB 查询与 close() 外全部同步返回,内部异步不泄漏到签名
  • 静默失败:任何对外 API 不向调用方抛异常;未初始化/关闭后调用为 no-op
  • 发送管线:默认单条直发(每次上报立即发起单事件请求);batchSend: true 切换内存队列批量(50 条 / 5 MiB / flushInterval 封批,队列满 5000 丢新);gzip 压缩,失败重试;不落盘
  • AB 测试:特性开关 / 特性配置 / 实验取值,ACS3 签名拉取元数据,sticky 缓存,快照导出与灌入
  • 异常采集:手动 trackException + unhandledRejection / uncaughtException 自动采集(按异常类型限流防洪;崩溃语义按 Node 启动模式门控,不改变宿主默认行为)
  • 公共属性:registerCommonProperties 一次注册附加到所有事件,支持动态 getter
  • 零运行时依赖,CJS + ESM 双格式,Node ≥ 16

安装

pnpm add @sensorswave/node-sdk

Quickstart

import { createClient } from "@sensorswave/node-sdk";

const client = createClient({
  endpoint: "https://your-data-endpoint.example.com",
  sourceToken: "your-source-token",
});

// 自定义事件(同步返回,内部异步发送:默认单条直发,batchSend: true 时批量封批)
client.trackEvent(
  { anonId: "anon-001", loginId: "user-001" }, // 身份:匿名 ID + 登录 ID
  "OrderPaid",
  { order_id: "o-1001", amount: 99.5 },        // 事件属性
  { first_order: true },                        // 用户属性(user_properties)
);

// 用户属性($UserSet 语义,七操作见下)
client.profileSet({ anonId: "anon-001", loginId: "user-001" }, { age: 25 });

// ⚠️ D11:进程退出前必须 await close(),否则在途请求(批量模式下还有队列余量)中的事件会丢失
await client.close();

close() 会:停止 AB 轮询与异常监听 → 排空队列余量(仅批量模式)→ 等待在途请求完成。幂等,二次调用返回同一 Promise。

身份模型

每个事件携带 anon_id(设备/进程维度匿名 ID)与可选 login_id(登录 ID):

client.trackEvent({ anonId: "anon-001", loginId: "user-001" }, "EventName");
  • identify:绑定匿名 ID 与登录 ID(两者都必须非空,对齐 go-sdk)
client.identify({ anonId: "anon-001", loginId: "user-001" });

用户属性七操作

均通过 $UserSet 事件上报:

| 方法 | 语义 | | --- | --- | | profileSet(user, props) | 覆盖写($set) | | profileSetOnce(user, props) | 首次写($set_once) | | profileIncrement(user, props) | 数值累加 | | profileAppend(user, props) | 列表追加(可重复) | | profileUnion(user, props) | 列表并集(去重) | | profileUnset(user, keys) | 删除指定属性 | | profileDelete(user) | 清空用户全部属性 |

预置属性

SDK 自动注入(仅补缺失键,调用方显式传同名值——含空串——不被覆盖):

| 属性 | 取值 | | --- | --- | | $lib | "node" | | $lib_version | SDK 包版本号 | | $os | Linux / macOS / Windows(未知平台回退原始 process.platform 值) | | $os_version | os.release() | | $timezone_offset | 时区偏移秒数(UTC+8 → 28800) | | $language | Intl 系统语言(BCP 47;取不到置空) |

其余预置属性($model / $screen_* / $url / $session_id / $browser 等)依赖客户端宿主能力,服务端不采集。

公共属性

一次性注册应用级属性(app_version / env / 机房等),附加到所有后续事件:

// 静态属性 + 动态属性(函数值每次事件发送现场调用)
client.registerCommonProperties({
  app_version: "2.3.1",
  env: "prod",
  in_flight: () => getInFlightCount(),
});

// 传 keys 仅移除指定键;不传清空全部
client.clearCommonProperties(["env"]);
client.clearCommonProperties();
  • 合并优先级:预置属性 < 公共属性 < 事件属性(公共属性可覆盖 $lib 等预置键)
  • 仅内存不持久化,进程重启后需重新注册
  • getter 抛异常 → 跳过该属性,事件照常发送

AB 测试

const client = createClient({
  endpoint: "https://your-data-endpoint.example.com",
  sourceToken: "your-source-token",
  ab: { projectSecret: "your-ab-project-secret" },
});

// 仅这三个 API 是 async(其余 API 全部同步)
const enabled = await client.checkFeatureGate(user, "new-checkout");   // vid === "pass" 视为 true
const config  = await client.getFeatureConfig(user, "search-config");  // 配置取值
const exp     = await client.getExperiment(user, "button-color-exp");  // 实验分组

// 公共结果字段(go 键 + 便利别名):
// { id, key, typ, vid, value, disable_impress, decision_rule_id,
//   check_gate, variant_id, variant_params }

命中且允许曝光时自动上报曝光事件($FeatureImpress / $ExpImpress),无需手动埋点。

Sticky 缓存

const client = createClient({
  // ...
  ab: {
    projectSecret: "...",
    stickyHandler: {
      get: (key) => cache.get(key),       // 返回 undefined 表示未命中
      set: (key, value) => void cache.set(key, value),
    },
  },
});

多实例快照传递

// 实例 A 导出(同步,未就绪返回 {})
const snapshot = clientA.getABSpecs();
// 实例 B 灌入:免首次远端拉取,构造后立即可用
const clientB = createClient({ ..., ab: { projectSecret: "...", loadABSpecs: snapshot } });

仅 AB(不上报 track 事件)

ab.metaLoader 提供时无需 projectSecret 与 track 端点;endpoint 留空但配置了 AB 元数据源时进入 trackingDisabled 模式(只查询不上报)。

异常采集

const client = createClient({
  endpoint: "...",
  sourceToken: "...",
  enableErrorTrack: true,   // 自动采集 unhandledRejection(error 级;仅在语义安全的 Node 启动模式下安装,见下)
  enableCrashTrack: true,   // 自动采集 uncaughtException(fatal 级:立即发送不等批量定时器,并复刻 Node 默认崩溃退出)
  exceptionConfig: {
    inAppExcludes: ["third-party/"],  // in_app 判定;excludes 优先于 includes
    inAppIncludes: ["app/"],
    // 自动采集限流(按异常类型的令牌桶,防 crash loop 打爆接收端):
    // 默认 10 条/类型、10s 补 1 条;false 关闭
    rateLimit: { bucketSize: 20, refillIntervalMs: 5000 },
  },
});

// 手动上报(不受开关与限流限制,固定 error 级;user 可省略,省略时用进程级匿名 ID)
client.trackException({ anonId: "anon-001", loginId: "user-001" }, new Error("boom"), { orderId: "o-1" });
client.trackException(undefined, "plain string error");

说明:

  • $Exception 事件属性:$exception_level(error/fatal)、$exception_type、$exception_message、$exception_frames(≤ 30 帧,platform: "node:javascript",含 filename/function/lineno/colno/abs_path/in_app)
  • enableErrorTrack 按 Node 启动模式门控:安装 unhandledRejection 监听会取消 Node(≥ 15)对未处理拒绝的默认崩溃行为,因此 SDK 只在 --unhandled-rejections=warn / none(进程本就不因拒绝崩溃)模式下安装并采集;默认的 throw 及其它会崩溃的模式下不安装(debug 日志说明),宿主语义零改变。需要 error 级采集时以 node --unhandled-rejections=warn app.js 启动(或写入 NODE_OPTIONS)。throw 模式下拒绝会以 uncaughtException 形态抛出,仍可被 enableCrashTrack 捕获为 fatal 级
  • enableCrashTrack 且 SDK 是进程内唯一 uncaughtException listener 时复刻 Node 默认崩溃:stderr 输出异常堆栈 → 立即触发发送(不等批量定时器)→ 最多等待 2s 发送预算 → process.exit(1)。宿主自有 listener 在场(含 SDK 启动后才挂的)时按 passthrough 处理,是否退出由宿主决定
  • 自动采集限流:同一异常类型按令牌桶限速(默认突发 10 条、10s 补 1 条,rateLimit: false 关闭),防 crash loop 打爆接收端;仅作用于自动采集,手动 trackException 不限流
  • close() 会移除全部已安装的 listener,还原宿主进程状态

配置

| 字段 | 默认值 | 说明 | | --- | --- | --- | | endpoint | —(必填¹) | 数据接收端地址;路径/query/fragment 自动剥离,仅保留 origin | | sourceToken | —(必填¹) | 接入方 token(请求头 SourceToken) | | batchSend | false | 发送模式:false 单条直发(每次上报立即发起单事件请求,flushInterval 不生效);true 内存队列批量(50 条 / 5 MiB / flushInterval 封批,队列满 5000 丢弃新事件并 warn) | | trackUriPath | "/in/track" | 上报路径 | | flushInterval | 10000 ms | 定时封批周期(仅批量模式生效) | | httpConcurrency | 1 | HTTP 并发上限 | | httpTimeout | 3000 ms | 单请求超时 | | httpRetry | 2 | 失败重试次数(指数退避;408 / 429 / 5xx / 网络错误重试,其余 4xx 不重试,对齐 js-sdk) | | gzipThresholdBytes | 1048576 | 批次体超过该阈值启用 gzip;0 强制禁用 | | debug | false | 调试日志开关:true 时输出 SDK 初始化信息、事件发送 POST body、AB 元数据请求与响应 | | logger | — | 自定义 Logger 实现(注入后 debug/info/warn/error 全量交给注入方,不受 debug 开关门控);不注入时使用默认 logger,仅 warn/error 输出到 stderr | | onTrackFail | — | 发送最终失败 / 校验丢弃回调 (events, error) => void | | enableErrorTrack | false | 自动采集 unhandledRejection(仅在 --unhandled-rejections=warn/none 模式下安装监听,见「异常采集」) | | enableCrashTrack | false | 自动采集 uncaughtException(fatal,立即发送;唯一 listener 时复刻崩溃并 exit(1)) | | exceptionConfig | — | in_app 判定的 inAppIncludes / inAppExcludes;自动采集限流 rateLimit(默认 10 条/类型、10s 补 1,false 关闭) | | ab | — | AB 配置,见下 |

¹ 构造期是唯一允许抛错的阶段(配置校验);ab.metaLoader 提供时两者皆可省略。

ab 配置

| 字段 | 默认值 | 说明 | | --- | --- | --- | | projectSecret | — | AB 项目密钥(签名用);提供 metaLoader 时可省略,否则必填 | | metaEndpoint | 同 endpoint | AB 元数据服务地址 | | metaUriPath | "/ab/all4eval" | 元数据路径 | | metaLoadInterval | 60000 ms | 元数据轮询周期(下限 30000) | | stickyHandler | — | sticky 缓存(进程内 Map 需自行传入以持久化) | | metaLoader | — | 自定义元数据加载器(测试/多实例共享用) | | loadABSpecs | — | 快照对象灌入(DC-10 格式,通常来自 getABSpecs()) |

行为保证

  • API 同步性:只有 checkFeatureGate / getFeatureConfig / getExperiment / close() 是异步;其余全部同步 fire-and-forget
  • 静默失败:非法入参、未初始化 AB、关闭后调用、批量模式队列满(5000 条)——均不抛异常;丢弃事件经 onTrackFail 或 debug 日志暴露
  • 事件必带字段:event / time(毫秒)/ trace_id(UUID)/ anon_id;已登录必带 login_id
  • 属性合并优先级:预置属性 < 公共属性 < 事件属性
  • $ 前缀保留:预置事件/属性专用,自定义事件与属性禁止使用
  • 仅批量模式(batchSend: true)存在内存队列:满 5000 条丢弃新事件并 warn;默认直发模式每次上报立即发起单事件请求,无队列积压丢弃

⚠️ 使用提示

  • D10 敏感字段:调用方对 properties 内容负全责——手机号、身份证号、邮箱等敏感信息请自行脱敏后再上报,SDK 不做检测与过滤
  • D11 退出前 close:队列纯内存、发送不落盘,进程退出前必须 await client.close(),否则队列余量(批量模式)与在途请求中的事件丢失。uncaughtException fatal 场景(SDK 唯一 listener)SDK 会立即触发发送并最多等待 2s 后强制退出进程(exit(1));process.exit() 等硬退出仍不经过 SDK
  • 定时器与重试句柄均已 unref,不会阻止宿主进程自然退出

与 go-sdk 的语义对齐

  • 事件 wire 模型(字段名/结构)与 go-sdk types.go 一致
  • AB:分桶哈希(sha256 前 8 字节)、规则链求值顺序(OVERRIDE → TRAFFIC → GATE → GROUP)、sticky 语义、快照 wire 格式(UpdateTime/ABEnv/ABSpecs)均对齐
  • ACS3 请求签名与 go-sdk 字节一致(golden 锁定)
  • 差异点:$lib: "node"(平台标识)、额外注入 4 个服务端环境预置属性($os / $os_version / $timezone_offset / $language,go-sdk 不注入)、异常采集为 Node 平台专属能力、trackException 身份方案(user 首参可省略 + 进程级兜底 anon_id)、公共属性 API 为 Node 新增(requirements 6)

跨 SDK 一致性由 __tests__/conformance/ 对拍套件锁定(读取 sdk-go 仓库 testdata/conformance/,187 case;SDK_GO_DIR 环境变量可指定 sdk-go 路径,目录缺失时自动 skip)。

开发

pnpm install        # 安装依赖
pnpm type-check     # tsc --noEmit
pnpm test           # jest
pnpm lint           # eslint
pnpm build          # tsup → dist/(CJS + ESM + .d.ts)
npm pack --dry-run  # 发布产物验证

提交前至少通过:pnpm type-check + pnpm test + pnpm lint。