@happyvertical/smrt-analytics

中文文档
0.62.1发布于 2026/11/17MITTypeScriptES Module近 30 天下载 1.5万

Analytics integration models for SMRT framework

原始使用文档
文档目录13 节
  1. Installation
  2. Usage
  3. Server-Side Event Lifecycle
  4. Report Scheduling
  5. API
  6. Models
  7. Collections
  8. Enums
  9. SDK Types
  10. Dependencies
  11. Contributor guide
  12. Browser tracking
  13. OpenObserve project metrics (server-only)

@happyvertical/smrt-analytics

Analytics integration models for the s-m-r-t framework. Manages analytics properties (GA4, Plausible, Matomo), data streams, server-side event tracking with retry support, and AI-powered report generation with scheduling.

Installation

pnpm add @happyvertical/smrt-analytics

Usage

import {
  AnalyticsProperty, AnalyticsPropertyCollection,
  AnalyticsDataStream, AnalyticsDataStreamCollection,
  AnalyticsEvent, AnalyticsEventCollection,
  AnalyticsReport, AnalyticsReportCollection,
  AnalyticsProvider, DataStreamType, ReportFrequency
} from '@happyvertical/smrt-analytics';

// Create a GA4 property
const properties = await AnalyticsPropertyCollection.create({ db });
const property = await properties.create({
  name: 'main-site',
  displayName: 'Main Site Analytics',
  provider: AnalyticsProvider.GA4,
  externalId: 'properties/123456789',
  measurementId: 'G-XXXXXXXXXX',
  apiSecret: 'server-side-secret',
  status: 'active',
});

// Add a web data stream
const streams = await AnalyticsDataStreamCollection.create({ db });
await streams.create({
  propertyId: property.id,
  displayName: 'Web Traffic',
  streamType: DataStreamType.WEB,
  measurementId: 'G-XXXXXXXXXX',
  defaultUri: 'https://example.com',
  status: 'active',
});

// Track a server-side event with retry support
const events = await AnalyticsEventCollection.create({ db });
const event = await events.create({
  propertyId: property.id,
  eventName: 'purchase',
  clientId: 'client-uuid',
  params: JSON.stringify({ value: 99.99, currency: 'USD' }),
  status: 'pending',
});
// After sending: event.markSent() or event.markFailed('timeout')
// Retry logic: event.shouldRetry(3) checks retryCount < maxRetries

// Create a scheduled report with dimensions and metrics
const reports = await AnalyticsReportCollection.create({ db });
const report = await reports.create({
  propertyId: property.id,
  name: 'Weekly Traffic Report',
  dimensions: JSON.stringify([{ name: 'country' }, { name: 'deviceCategory' }]),
  metrics: JSON.stringify([{ name: 'activeUsers' }, { name: 'sessions' }]),
  dateRangeStart: '7daysAgo',
  dateRangeEnd: 'today',
  frequency: ReportFrequency.WEEKLY,
});

// AI-powered operations (uses do() and is() from SmrtObject)
const analysis = await property.analyzePerformance({ period: '30 days' });
const isHealthy = await property.isPerformingWell();
const insights = await report.analyzeResults();
const trending = await report.hasPositiveTrends();

hasPositiveTrends() keeps that boolean API. When decisions: { type: 'typesafe' } is configured and no AI tools are registered, it sends the resolved report prompt plus only the selected metrics and persisted aggregate rows to the typed-decision route. Its threshold defaults to 0.5; a configured uncertainty band uses the same resolved prompt on the generative route, matching the framework's decision fallback behavior. The route treats higher user-growth, engagement, and conversion values as favorable, and higher bounce or error rates as adverse. Unknown metric directions, incomplete comparison periods, and insufficient or ambiguous data are not inferred as positive. Configured decision failures propagate. Without a decision provider, the existing prompt-driven yes/no behavior remains in use. resultData retains the documented caller-managed PII limitation in either route.

The framework website's analytics guide should add a worked decision-provider configuration example; this package README documents the runtime contract until that guide is updated.

Server-Side Event Lifecycle

Events track their delivery status with built-in retry support:

  1. PENDING -- created, not yet sent to provider
  2. SENT -- successfully delivered (markSent() sets sentAt timestamp)
  3. FAILED -- delivery failed (markFailed(error) increments retryCount)

Use shouldRetry(maxRetries) to check if a failed event should be retried, and resetForRetry() to reset it to PENDING.

Report Scheduling

Reports support automatic scheduling via ReportFrequency:

  • ONCE -- single run, no rescheduling
  • DAILY / WEEKLY / MONTHLY -- calculateNextRun() sets nextRunAt after each run

Use isDue() to check if a scheduled report needs to run.

API

Models

ExportDescription
AnalyticsPropertyGA4 property, Plausible site, or Matomo site. AI methods: analyzePerformance(), isPerformingWell()
AnalyticsDataStreamData stream within a property (web/iOS/Android). getPlatformId() returns measurementId or firebaseAppId
AnalyticsEventServer-side tracking event with retry queue. toTrackEvent() builds SDK payload
AnalyticsReportSaved report config with dimensions/metrics, scheduling, result caching. AI methods: analyzeResults(), hasPositiveTrends()

Collections

AnalyticsPropertyCollection, AnalyticsDataStreamCollection, AnalyticsEventCollection, AnalyticsReportCollection

Enums

ExportDescription
AnalyticsProviderga4, plausible, matomo
AnalyticsPropertyStatusactive, inactive, pending
DataStreamTypeWEB_DATA_STREAM, ANDROID_APP_DATA_STREAM, IOS_APP_DATA_STREAM
DataStreamStatusactive, inactive
TrackingEventStatuspending, sent, failed
ReportStatusdraft, scheduled, running, completed, failed
ReportFrequencyonce, daily, weekly, monthly
CountingMethodONCE_PER_EVENT, ONCE_PER_SESSION
CustomDimensionScopeEVENT, USER, ITEM

SDK Types

Re-exported from ./types for SDK compatibility: AnalyticsInterface, AnalyticsCapabilities, SDKProperty, SDKDataStream, SDKTrackEvent, SDKPageviewEvent, SDKReportOptions, SDKReportResult, SDKCustomDimension, SDKCustomMetric, SDKKeyEvent, PropertyStatsWithTrend.

Dependencies

  • @happyvertical/smrt-core -- ORM and code generation
  • Peer: svelte (optional, for Svelte components via @happyvertical/smrt-analytics/svelte)

Contributor guide

See AGENTS.md for package architecture, invariants, validation, and contributor guidance.

Browser tracking

Use the isolated @happyvertical/smrt-analytics/browser entry for opt-in browser/SPA tracking and the Matomo adapter. Shared components emit static standard events through the optional @happyvertical/smrt-ui/analytics context. See browser integration and privacy contract.

OpenObserve project metrics (server-only)

@happyvertical/smrt-analytics/observability exports OpenObserveStreamReader for the default/project_observability stream: latestPerProject() and queryWindow() return typed per-project snapshots and collector records. The read-only credential comes from your secrets store at call time and never reaches a client bundle. See agents/observability.md.

版本与发布记录

@happyvertical/smrt-analytics 共发布 366 个版本,首次发布于 2026/06/23;过去 12 个月发布了 366 个版本。

版本发布日期距今
0.62.1latest2026/11/17今天
0.62.02026/11/17今天
0.61.62026/11/161 天前
0.61.52026/11/161 天前
0.61.42026/11/161 天前
0.61.32026/11/152 天前

关于 @happyvertical/smrt-analytics 的常见问题

@happyvertical/smrt-analytics 是什么?

Analytics integration models for SMRT framework

如何安装 @happyvertical/smrt-analytics?

在项目目录运行 npm install @happyvertical/smrt-analytics,或使用 pnpm add / yarn add / bun add。

@happyvertical/smrt-analytics 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@happyvertical/smrt-analytics 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@happyvertical/smrt-analytics 可以商用吗?

@happyvertical/smrt-analytics 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@happyvertical/smrt-analytics 的下载量有多少?

根据 npm 官方下载统计,@happyvertical/smrt-analytics 在 2026/10/17 – 2026/11/15 这 30 天内被下载 14,819 次,日均约 494 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@happyvertical/smrt-analytics 还在维护吗?

最新版本 0.62.1 发布于 2026/11/17(今天);至今共发布 366 个版本,其中过去 12 个月发布了 366 个;首次发布于 2026/06/23。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。