analytics-tracking-automation

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Analytics Tracking Automation

分析追踪自动化

Skill by ara.so — Data Skills collection.
This skill enables AI agents to plan, implement, and deploy GA4 + GTM tracking setups. It automates site analysis, page grouping, event schema design, GTM container synchronization, preview verification, and publishing—supporting both generic websites and Shopify storefronts.
ara.so提供的Skill——数据技能合集。
本Skill支持AI Agent规划、实施并部署GA4 + GTM追踪配置。它可自动化完成网站分析、页面分组、事件Schema设计、GTM容器同步、预览验证及发布操作,同时支持通用网站与Shopify店铺前端。

What This Skill Does

本Skill的功能

The
analytics-tracking-automation
project provides a local-first workflow that:
  1. Analyzes a website by crawling pages and identifying business intent
  2. Groups pages by purpose (e.g., product, pricing, contact)
  3. Designs event schemas (GA4 events, parameters, triggers) based on site structure
  4. Syncs to GTM by creating/updating tags, triggers, variables via Google Tag Manager API
  5. Verifies in preview using automated Playwright-based checks
  6. Publishes the GTM container version when verification passes
  7. Supports Shopify with specialized tracking for cart, checkout, and purchase flows
  8. Maintains artifacts for resumable, reviewable tracking work
analytics-tracking-automation
项目提供本地优先的工作流,可完成以下操作:
  1. 分析网站:爬取页面并识别业务意图
  2. 页面分组:按用途(如产品页、定价页、联系页)对页面进行分组
  3. 设计事件Schema:基于网站结构生成GA4事件、参数及触发器
  4. 同步至GTM:通过Google Tag Manager API创建/更新标签、触发器及变量
  5. 预览验证:使用基于Playwright的自动化检查进行验证
  6. 发布容器:验证通过后发布GTM容器版本
  7. 支持Shopify:针对购物车、结账及购买流程提供专属追踪方案
  8. 保留工件:支持可恢复、可审核的追踪工作流程

Installation

安装

For Use in AI Agent Environments

用于AI Agent环境

The recommended installation is to clone the repository and install the skill bundle:
bash
git clone https://github.com/jtrackingai/analytics-tracking-automation.git
cd analytics-tracking-automation
npm install
npm run install:skills
This installs the umbrella skill into your agent's skills directory and makes the
event-tracking
CLI available.
推荐安装方式为克隆仓库并安装Skill包:
bash
git clone https://github.com/jtrackingai/analytics-tracking-automation.git
cd analytics-tracking-automation
npm install
npm run install:skills
此操作会将总括Skill安装至Agent的技能目录,并启用
event-tracking
CLI工具。

No-Clone Alternative

免克隆安装方案

bash
npx skills add jtrackingai/analytics-tracking-automation
bash
npx skills add jtrackingai/analytics-tracking-automation

Verify Installation

验证安装

bash
npx event-tracking --version
The CLI requires Node.js 18+ and will auto-install Playwright Chromium on first
npm install
.
bash
npx event-tracking --version
该CLI需要Node.js 18+版本,首次执行
npm install
时会自动安装Playwright Chromium。

Core CLI Commands

核心CLI命令

The
event-tracking
CLI is the primary interface. All commands accept
--help
for detailed options.
event-tracking
CLI是主要操作界面,所有命令均可添加
--help
查看详细选项。

Start a New Tracking Setup

启动新的追踪配置

bash
npx event-tracking init \
  --url https://www.example.com \
  --output ./output \
  --ga4-measurement-id G-XXXXXXXXXX
This creates a site artifact directory under
./output/
(e.g.,
./output/www_example_com/
) and runs:
  • Site crawl and page classification
  • Business intent page grouping
  • Event schema generation
  • Schema review checkpoint
bash
npx event-tracking init \
  --url https://www.example.com \
  --output ./output \
  --ga4-measurement-id G-XXXXXXXXXX
此命令会在
./output/
下创建网站工件目录(如
./output/www_example_com/
),并执行以下步骤:
  • 网站爬取与页面分类
  • 业务意图页面分组
  • 事件Schema生成
  • Schema审核检查点

Resume an Existing Run

恢复已中断的运行

bash
npx event-tracking resume \
  --artifact-dir ./output/www_example_com \
  --continue-through sync
Resumes from the last checkpoint and continues through the specified stage (
schema
,
sync
,
preview
,
publish
).
bash
npx event-tracking resume \
  --artifact-dir ./output/www_example_com \
  --continue-through sync
从上次检查点恢复运行,并继续执行指定阶段(
schema
sync
preview
publish
)。

Audit an Existing GTM Setup

审核现有GTM配置

bash
npx event-tracking audit \
  --url https://www.example.com \
  --gtm-account-id 123456789 \
  --gtm-container-id 12345678 \
  --output ./output
Compares live GTM configuration against recommended tracking plan and produces a health report.
bash
npx event-tracking audit \
  --url https://www.example.com \
  --gtm-account-id 123456789 \
  --gtm-container-id 12345678 \
  --output ./output
将当前GTM配置与推荐追踪方案进行对比,并生成健康报告。

Sync Schema to GTM

将Schema同步至GTM

bash
npx event-tracking sync \
  --artifact-dir ./output/www_example_com \
  --gtm-account-id 123456789 \
  --gtm-container-id 12345678
Creates/updates tags, triggers, and variables in GTM based on
event-schema.json
. Requires Google OAuth (prompted interactively).
bash
npx event-tracking sync \
  --artifact-dir ./output/www_example_com \
  --gtm-account-id 123456789 \
  --gtm-container-id 12345678
基于
event-schema.json
在GTM中创建/更新标签、触发器及变量。需要Google OAuth授权(会交互式提示)。

Verify GTM Preview

验证GTM预览

bash
npx event-tracking verify \
  --artifact-dir ./output/www_example_com \
  --gtm-preview-url "https://tagmanager.google.com/?gtm_preview=..."
Runs automated browser checks against GTM preview mode, validates event firing, and produces a verification report.
bash
npx event-tracking verify \
  --artifact-dir ./output/www_example_com \
  --gtm-preview-url "https://tagmanager.google.com/?gtm_preview=..."
针对GTM预览模式运行自动化浏览器检查,验证事件触发情况并生成验证报告。

Publish GTM Container

发布GTM容器

bash
npx event-tracking publish \
  --artifact-dir ./output/www_example_com \
  --gtm-account-id 123456789 \
  --gtm-container-id 12345678 \
  --version-name "v1.0 - Initial tracking"
Publishes the current workspace version to live.
bash
npx event-tracking publish \
  --artifact-dir ./output/www_example_com \
  --gtm-account-id 123456789 \
  --gtm-container-id 12345678 \
  --version-name "v1.0 - Initial tracking"
将当前工作区版本发布至线上环境。

Shopify-Specific Setup

Shopify专属配置

bash
npx event-tracking init \
  --url https://store.example.com \
  --output ./output \
  --platform shopify \
  --ga4-measurement-id G-XXXXXXXXXX
Uses Shopify-optimized tracking (cart, checkout, purchase events).
bash
npx event-tracking init \
  --url https://store.example.com \
  --output ./output \
  --platform shopify \
  --ga4-measurement-id G-XXXXXXXXXX
使用Shopify优化版追踪方案(购物车、结账、购买事件)。

Configuration

配置

Environment Variables

环境变量

bash
undefined
bash
undefined

Google OAuth credentials (create in Google Cloud Console)

Google OAuth凭证(在Google Cloud Console创建)

export GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com export GOOGLE_CLIENT_SECRET=your-client-secret
export GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com export GOOGLE_CLIENT_SECRET=your-client-secret

Optional: GA4 Measurement ID

可选:GA4测量ID

export GA4_MEASUREMENT_ID=G-XXXXXXXXXX
export GA4_MEASUREMENT_ID=G-XXXXXXXXXX

Optional: GTM Account/Container IDs

可选:GTM账户/容器ID

export GTM_ACCOUNT_ID=123456789 export GTM_CONTAINER_ID=12345678
undefined
export GTM_ACCOUNT_ID=123456789 export GTM_CONTAINER_ID=12345678
undefined

OAuth Setup

OAuth配置

To sync with GTM, you need Google OAuth credentials:
  1. Go to Google Cloud Console
  2. Create a project and enable Tag Manager API
  3. Create OAuth 2.0 credentials (Desktop app type)
  4. Set redirect URI to
    http://localhost:3000/oauth/callback
  5. Export
    GOOGLE_CLIENT_ID
    and
    GOOGLE_CLIENT_SECRET
First sync will open a browser for OAuth consent. Credentials are cached in the artifact directory (
oauth-tokens.json
).
要与GTM同步,需获取Google OAuth凭证:
  1. 访问Google Cloud Console
  2. 创建项目并启用Tag Manager API
  3. 创建OAuth 2.0凭证(桌面应用类型)
  4. 设置重定向URI为
    http://localhost:3000/oauth/callback
  5. 导出
    GOOGLE_CLIENT_ID
    GOOGLE_CLIENT_SECRET
首次同步会打开浏览器进行OAuth授权,凭证会缓存至工件目录(
oauth-tokens.json
)。

Artifact Directory Structure

工件目录结构

Each site run creates an artifact directory like
./output/www_example_com/
:
www_example_com/
├── site-analysis.json          # Crawl results, page inventory
├── page-groups.json            # Business intent groupings
├── event-schema.json           # GA4 events, parameters, triggers
├── gtm-sync-result.json        # GTM API operation results
├── verification-report.json    # Preview verification checks
├── oauth-tokens.json           # Cached OAuth credentials
└── checkpoint.json             # Last completed stage
These files are reviewable, editable, and resumable.
每个网站运行实例会创建类似
./output/www_example_com/
的工件目录:
www_example_com/
├── site-analysis.json          # 爬取结果、页面清单
├── page-groups.json            # 业务意图分组
├── event-schema.json           # GA4事件、参数、触发器
├── gtm-sync-result.json        # GTM API操作结果
├── verification-report.json    # 预览验证检查报告
├── oauth-tokens.json           # 缓存的OAuth凭证
└── checkpoint.json             # 最后完成的阶段
这些文件可审核、编辑,且支持恢复运行。

TypeScript API Examples

TypeScript API示例

Programmatic Site Analysis

程序化网站分析

typescript
import { analyzeSite } from 'analytics-tracking-automation';

async function analyzeSiteExample() {
  const result = await analyzeSite({
    url: 'https://www.example.com',
    outputDir: './output',
    maxPages: 100,
    includeSubdomains: false,
  });

  console.log('Pages discovered:', result.pages.length);
  console.log('Page groups:', result.pageGroups);
  console.log('Recommended events:', result.events.length);
}
typescript
import { analyzeSite } from 'analytics-tracking-automation';

async function analyzeSiteExample() {
  const result = await analyzeSite({
    url: 'https://www.example.com',
    outputDir: './output',
    maxPages: 100,
    includeSubdomains: false,
  });

  console.log('Pages discovered:', result.pages.length);
  console.log('Page groups:', result.pageGroups);
  console.log('Recommended events:', result.events.length);
}

Generate Event Schema

生成事件Schema

typescript
import { generateEventSchema } from 'analytics-tracking-automation';

async function generateSchemaExample() {
  const schema = await generateEventSchema({
    artifactDir: './output/www_example_com',
    pageGroups: ['home', 'product', 'pricing', 'contact'],
    businessGoals: ['signup', 'purchase', 'demo_request'],
  });

  console.log('Generated events:', schema.events);
  console.log('Event parameters:', schema.parameters);
  console.log('GTM triggers:', schema.triggers);
}
typescript
import { generateEventSchema } from 'analytics-tracking-automation';

async function generateSchemaExample() {
  const schema = await generateEventSchema({
    artifactDir: './output/www_example_com',
    pageGroups: ['home', 'product', 'pricing', 'contact'],
    businessGoals: ['signup', 'purchase', 'demo_request'],
  });

  console.log('Generated events:', schema.events);
  console.log('Event parameters:', schema.parameters);
  console.log('GTM triggers:', schema.triggers);
}

Sync to GTM

同步至GTM

typescript
import { syncToGTM } from 'analytics-tracking-automation';

async function syncExample() {
  const syncResult = await syncToGTM({
    artifactDir: './output/www_example_com',
    gtmAccountId: process.env.GTM_ACCOUNT_ID!,
    gtmContainerId: process.env.GTM_CONTAINER_ID!,
    oauthCredentials: {
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    },
  });

  console.log('Tags created:', syncResult.tagsCreated);
  console.log('Triggers created:', syncResult.triggersCreated);
  console.log('Variables created:', syncResult.variablesCreated);
}
typescript
import { syncToGTM } from 'analytics-tracking-automation';

async function syncExample() {
  const syncResult = await syncToGTM({
    artifactDir: './output/www_example_com',
    gtmAccountId: process.env.GTM_ACCOUNT_ID!,
    gtmContainerId: process.env.GTM_CONTAINER_ID!,
    oauthCredentials: {
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    },
  });

  console.log('Tags created:', syncResult.tagsCreated);
  console.log('Triggers created:', syncResult.triggersCreated);
  console.log('Variables created:', syncResult.variablesCreated);
}

Verify Preview

验证预览

typescript
import { verifyPreview } from 'analytics-tracking-automation';

async function verifyExample() {
  const report = await verifyPreview({
    artifactDir: './output/www_example_com',
    gtmPreviewUrl: 'https://tagmanager.google.com/?gtm_preview=...',
    testPages: [
      { url: 'https://www.example.com/', expectedEvents: ['page_view'] },
      { url: 'https://www.example.com/pricing', expectedEvents: ['page_view', 'view_pricing'] },
      { url: 'https://www.example.com/contact', expectedEvents: ['page_view', 'contact_intent'] },
    ],
  });

  console.log('Checks passed:', report.passed);
  console.log('Checks failed:', report.failed);
  console.log('Issues:', report.issues);
}
typescript
import { verifyPreview } from 'analytics-tracking-automation';

async function verifyExample() {
  const report = await verifyPreview({
    artifactDir: './output/www_example_com',
    gtmPreviewUrl: 'https://tagmanager.google.com/?gtm_preview=...',
    testPages: [
      { url: 'https://www.example.com/', expectedEvents: ['page_view'] },
      { url: 'https://www.example.com/pricing', expectedEvents: ['page_view', 'view_pricing'] },
      { url: 'https://www.example.com/contact', expectedEvents: ['page_view', 'contact_intent'] },
    ],
  });

  console.log('Checks passed:', report.passed);
  console.log('Checks failed:', report.failed);
  console.log('Issues:', report.issues);
}

Publish Container

发布容器

typescript
import { publishContainer } from 'analytics-tracking-automation';

async function publishExample() {
  const result = await publishContainer({
    gtmAccountId: process.env.GTM_ACCOUNT_ID!,
    gtmContainerId: process.env.GTM_CONTAINER_ID!,
    versionName: 'v1.0 - Initial tracking setup',
    versionDescription: 'GA4 events for core user journeys',
    oauthCredentials: {
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    },
  });

  console.log('Published version:', result.publishedVersion);
  console.log('Live container URL:', result.containerUrl);
}
typescript
import { publishContainer } from 'analytics-tracking-automation';

async function publishExample() {
  const result = await publishContainer({
    gtmAccountId: process.env.GTM_ACCOUNT_ID!,
    gtmContainerId: process.env.GTM_CONTAINER_ID!,
    versionName: 'v1.0 - Initial tracking setup',
    versionDescription: 'GA4 events for core user journeys',
    oauthCredentials: {
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    },
  });

  console.log('Published version:', result.publishedVersion);
  console.log('Live container URL:', result.containerUrl);
}

Common Patterns

常见模式

Full End-to-End Setup

完整端到端配置

typescript
import {
  analyzeSite,
  generateEventSchema,
  syncToGTM,
  verifyPreview,
  publishContainer,
} from 'analytics-tracking-automation';

async function fullSetup(url: string, outputRoot: string) {
  // 1. Analyze site
  const analysis = await analyzeSite({ url, outputDir: outputRoot });
  const artifactDir = analysis.artifactDir;

  // 2. Generate schema
  const schema = await generateEventSchema({ artifactDir });

  // 3. Review (manual checkpoint)
  console.log('Review schema before syncing:', schema);
  // User reviews and edits event-schema.json if needed

  // 4. Sync to GTM
  const syncResult = await syncToGTM({
    artifactDir,
    gtmAccountId: process.env.GTM_ACCOUNT_ID!,
    gtmContainerId: process.env.GTM_CONTAINER_ID!,
    oauthCredentials: {
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    },
  });

  // 5. Enter GTM preview mode manually, then verify
  const previewUrl = '...'; // GTM preview URL from user
  const verifyReport = await verifyPreview({ artifactDir, gtmPreviewUrl: previewUrl });

  if (verifyReport.passed === verifyReport.total) {
    // 6. Publish
    await publishContainer({
      gtmAccountId: process.env.GTM_ACCOUNT_ID!,
      gtmContainerId: process.env.GTM_CONTAINER_ID!,
      versionName: 'v1.0 - Automated setup',
      oauthCredentials: {
        clientId: process.env.GOOGLE_CLIENT_ID!,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
      },
    });
    console.log('Published successfully');
  } else {
    console.error('Verification failed, fix issues before publishing');
  }
}
typescript
import {
  analyzeSite,
  generateEventSchema,
  syncToGTM,
  verifyPreview,
  publishContainer,
} from 'analytics-tracking-automation';

async function fullSetup(url: string, outputRoot: string) {
  // 1. 分析网站
  const analysis = await analyzeSite({ url, outputDir: outputRoot });
  const artifactDir = analysis.artifactDir;

  // 2. 生成Schema
  const schema = await generateEventSchema({ artifactDir });

  // 3. 审核(手动检查点)
  console.log('Review schema before syncing:', schema);
  // 用户可按需审核并编辑event-schema.json

  // 4. 同步至GTM
  const syncResult = await syncToGTM({
    artifactDir,
    gtmAccountId: process.env.GTM_ACCOUNT_ID!,
    gtmContainerId: process.env.GTM_CONTAINER_ID!,
    oauthCredentials: {
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    },
  });

  // 5. 手动进入GTM预览模式,然后验证
  const previewUrl = '...'; // 用户提供的GTM预览URL
  const verifyReport = await verifyPreview({ artifactDir, gtmPreviewUrl: previewUrl });

  if (verifyReport.passed === verifyReport.total) {
    // 6. 发布
    await publishContainer({
      gtmAccountId: process.env.GTM_ACCOUNT_ID!,
      gtmContainerId: process.env.GTM_CONTAINER_ID!,
      versionName: 'v1.0 - Automated setup',
      oauthCredentials: {
        clientId: process.env.GOOGLE_CLIENT_ID!,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
      },
    });
    console.log('Published successfully');
  } else {
    console.error('Verification failed, fix issues before publishing');
  }
}

Shopify Tracking Setup

Shopify追踪配置

typescript
import { analyzeSite, generateEventSchema, syncToGTM } from 'analytics-tracking-automation';

async function shopifySetup(storeUrl: string) {
  const analysis = await analyzeSite({
    url: storeUrl,
    outputDir: './output',
    platform: 'shopify',
  });

  const schema = await generateEventSchema({
    artifactDir: analysis.artifactDir,
    platform: 'shopify',
    shopifyEvents: ['add_to_cart', 'begin_checkout', 'purchase'],
  });

  await syncToGTM({
    artifactDir: analysis.artifactDir,
    gtmAccountId: process.env.GTM_ACCOUNT_ID!,
    gtmContainerId: process.env.GTM_CONTAINER_ID!,
    platform: 'shopify',
    oauthCredentials: {
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    },
  });

  console.log('Shopify tracking synced. Manual verification required in Shopify admin.');
}
typescript
import { analyzeSite, generateEventSchema, syncToGTM } from 'analytics-tracking-automation';

async function shopifySetup(storeUrl: string) {
  const analysis = await analyzeSite({
    url: storeUrl,
    outputDir: './output',
    platform: 'shopify',
  });

  const schema = await generateEventSchema({
    artifactDir: analysis.artifactDir,
    platform: 'shopify',
    shopifyEvents: ['add_to_cart', 'begin_checkout', 'purchase'],
  });

  await syncToGTM({
    artifactDir: analysis.artifactDir,
    gtmAccountId: process.env.GTM_ACCOUNT_ID!,
    gtmContainerId: process.env.GTM_CONTAINER_ID!,
    platform: 'shopify',
    oauthCredentials: {
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    },
  });

  console.log('Shopify tracking synced. Manual verification required in Shopify admin.');
}

Audit Existing Setup

审核现有配置

typescript
import { auditGTM } from 'analytics-tracking-automation';

async function auditExample(url: string) {
  const auditReport = await auditGTM({
    url,
    gtmAccountId: process.env.GTM_ACCOUNT_ID!,
    gtmContainerId: process.env.GTM_CONTAINER_ID!,
    outputDir: './output',
    oauthCredentials: {
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    },
  });

  console.log('Healthy tags:', auditReport.healthy);
  console.log('Drifted tags:', auditReport.drifted);
  console.log('Missing events:', auditReport.missing);
  console.log('Recommendations:', auditReport.recommendations);
}
typescript
import { auditGTM } from 'analytics-tracking-automation';

async function auditExample(url: string) {
  const auditReport = await auditGTM({
    url,
    gtmAccountId: process.env.GTM_ACCOUNT_ID!,
    gtmContainerId: process.env.GTM_CONTAINER_ID!,
    outputDir: './output',
    oauthCredentials: {
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    },
  });

  console.log('Healthy tags:', auditReport.healthy);
  console.log('Drifted tags:', auditReport.drifted);
  console.log('Missing events:', auditReport.missing);
  console.log('Recommendations:', auditReport.recommendations);
}

Resume from Checkpoint

从检查点恢复

typescript
import { resumeWorkflow } from 'analytics-tracking-automation';

async function resumeExample(artifactDir: string) {
  const result = await resumeWorkflow({
    artifactDir,
    continueThrough: 'publish', // 'schema' | 'sync' | 'preview' | 'publish'
  });

  console.log('Resumed from:', result.lastCheckpoint);
  console.log('Completed through:', result.completedStage);
}
typescript
import { resumeWorkflow } from 'analytics-tracking-automation';

async function resumeExample(artifactDir: string) {
  const result = await resumeWorkflow({
    artifactDir,
    continueThrough: 'publish', // 'schema' | 'sync' | 'preview' | 'publish'
  });

  console.log('Resumed from:', result.lastCheckpoint);
  console.log('Completed through:', result.completedStage);
}

Debugging and Troubleshooting

调试与故障排除

Selector Debugging with Playwright

使用Playwright调试选择器

If preview verification reports selector mismatches or events not firing:
bash
undefined
如果预览验证报告显示选择器不匹配或事件未触发:
bash
undefined

Open site in headed browser for visual inspection

打开带界面的浏览器进行可视化检查

npm run debug:open -- https://www.example.com
npm run debug:open -- https://www.example.com

Launch codegen to capture correct selectors

启动代码生成工具捕获正确选择器

npm run debug:codegen -- https://www.example.com

Then update selectors in `event-schema.json`:

```json
{
  "events": [
    {
      "eventName": "click_cta",
      "trigger": {
        "type": "click",
        "selector": "button.cta-button" // Updated selector
      }
    }
  ]
}
npm run debug:codegen -- https://www.example.com

然后更新`event-schema.json`中的选择器:

```json
{
  "events": [
    {
      "eventName": "click_cta",
      "trigger": {
        "type": "click",
        "selector": "button.cta-button" // 更新后的选择器
      }
    }
  ]
}

OAuth Token Issues

OAuth令牌问题

If OAuth fails or tokens are stale:
bash
undefined
如果OAuth失败或令牌过期:
bash
undefined

Remove cached tokens

删除缓存的令牌

rm ./output/www_example_com/oauth-tokens.json
rm ./output/www_example_com/oauth-tokens.json

Re-run sync to trigger new OAuth flow

重新运行同步以触发新的OAuth流程

npx event-tracking sync --artifact-dir ./output/www_example_com
undefined
npx event-tracking sync --artifact-dir ./output/www_example_com
undefined

GTM API Errors

GTM API错误

Common GTM API issues:
  • 401 Unauthorized: OAuth credentials invalid or expired
  • 403 Forbidden: User lacks GTM account/container permissions
  • 404 Not Found: GTM account or container ID incorrect
  • 429 Rate Limit: Too many API requests; add delays between operations
Check GTM permissions: User must have at least "Publish" access to the container.
常见GTM API问题:
  • 401 Unauthorized:OAuth凭证无效或过期
  • 403 Forbidden:用户缺少GTM账户/容器权限
  • 404 Not Found:GTM账户或容器ID错误
  • 429 Rate Limit:API请求过多;在操作之间添加延迟
检查GTM权限:用户必须至少拥有容器的“发布”权限。

Preview Verification Failures

预览验证失败

If automated verification fails:
  1. Check GTM Preview URL: Must be active and match container
  2. Inspect browser logs: Add
    --verbose
    flag for detailed Playwright logs
  3. Test manually: Open preview URL in browser, check dataLayer in console
  4. Validate selectors: Use
    npm run debug:codegen
    to verify element targeting
  5. Network issues: Ensure site is accessible and not behind VPN/firewall
如果自动化验证失败:
  1. 检查GTM预览URL:必须处于激活状态且匹配容器
  2. 查看浏览器日志:添加
    --verbose
    标志获取详细Playwright日志
  3. 手动测试:在浏览器中打开预览URL,检查控制台中的dataLayer
  4. 验证选择器:使用
    npm run debug:codegen
    验证元素定位
  5. 网络问题:确保网站可访问,且未处于VPN/防火墙后方

Shopify Manual Verification

Shopify手动验证

Shopify tracking requires manual verification in Shopify admin:
  1. Install GTM via Shopify admin (Settings → Online Store → Preferences)
  2. Add GTM container ID
  3. Test checkout flow in preview mode
  4. Verify
    add_to_cart
    ,
    begin_checkout
    ,
    purchase
    events in GTM debug view
Shopify追踪需要在Shopify后台进行手动验证:
  1. 通过Shopify后台安装GTM(设置→在线商店→偏好设置)
  2. 添加GTM容器ID
  3. 在预览模式下测试结账流程
  4. 在GTM调试视图中验证
    add_to_cart
    begin_checkout
    purchase
    事件

Common Event Schema Fixes

常见事件Schema修复

Fix missing events:
json
{
  "events": [
    {
      "eventName": "form_submit",
      "trigger": {
        "type": "formSubmit",
        "selector": "form#contact-form"
      },
      "parameters": {
        "form_id": "contact-form",
        "form_destination": "contact"
      }
    }
  ]
}
Fix parameter mapping:
json
{
  "parameters": {
    "page_type": {
      "type": "dataLayer",
      "source": "pageType"
    },
    "user_id": {
      "type": "cookie",
      "source": "user_id"
    }
  }
}
修复缺失事件:
json
{
  "events": [
    {
      "eventName": "form_submit",
      "trigger": {
        "type": "formSubmit",
        "selector": "form#contact-form"
      },
      "parameters": {
        "form_id": "contact-form",
        "form_destination": "contact"
      }
    }
  ]
}
修复参数映射:
json
{
  "parameters": {
    "page_type": {
      "type": "dataLayer",
      "source": "pageType"
    },
    "user_id": {
      "type": "cookie",
      "source": "user_id"
    }
  }
}

Telemetry Configuration

遥测配置

Anonymous startup signals are sent by default. Opt out:
bash
npx event-tracking config telemetry --disable
Richer diagnostics (opt-in):
bash
npx event-tracking config telemetry --enable-diagnostics
Check current preference:
bash
npx event-tracking config telemetry --show
默认会发送匿名启动信号,可选择退出:
bash
npx event-tracking config telemetry --disable
启用更丰富的诊断信息(可选):
bash
npx event-tracking config telemetry --enable-diagnostics
查看当前偏好设置:
bash
npx event-tracking config telemetry --show

Advanced Configuration

高级配置

Custom Crawler Settings

自定义爬虫设置

Edit artifact
site-analysis.json
before schema generation:
json
{
  "crawlConfig": {
    "maxPages": 200,
    "includeSubdomains": true,
    "excludePatterns": ["/blog/*", "/admin/*"],
    "followExternalLinks": false
  }
}
在生成Schema前编辑工件
site-analysis.json
json
{
  "crawlConfig": {
    "maxPages": 200,
    "includeSubdomains": true,
    "excludePatterns": ["/blog/*", "/admin/*"],
    "followExternalLinks": false
  }
}

Custom Page Grouping

自定义页面分组

Override auto-generated page groups in
page-groups.json
:
json
{
  "groups": [
    {
      "name": "conversion",
      "intent": "purchase",
      "patterns": ["/checkout/*", "/cart", "/order-confirmation"]
    },
    {
      "name": "support",
      "intent": "help",
      "patterns": ["/help/*", "/faq", "/contact"]
    }
  ]
}
page-groups.json
中覆盖自动生成的页面分组:
json
{
  "groups": [
    {
      "name": "conversion",
      "intent": "purchase",
      "patterns": ["/checkout/*", "/cart", "/order-confirmation"]
    },
    {
      "name": "support",
      "intent": "help",
      "patterns": ["/help/*", "/faq", "/contact"]
    }
  ]
}

Event Schema Customization

事件Schema定制

Manually edit
event-schema.json
for fine-grained control:
json
{
  "events": [
    {
      "eventName": "custom_conversion",
      "trigger": {
        "type": "click",
        "selector": "button[data-track='conversion']"
      },
      "parameters": {
        "conversion_type": {
          "type": "element",
          "source": "data-conversion-type"
        },
        "conversion_value": {
          "type": "element",
          "source": "data-value"
        }
      },
      "conditions": {
        "pagePathContains": "/pricing"
      }
    }
  ]
}
手动编辑
event-schema.json
实现精细化控制:
json
{
  "events": [
    {
      "eventName": "custom_conversion",
      "trigger": {
        "type": "click",
        "selector": "button[data-track='conversion']"
      },
      "parameters": {
        "conversion_type": {
          "type": "element",
          "source": "data-conversion-type"
        },
        "conversion_value": {
          "type": "element",
          "source": "data-value"
        }
      },
      "conditions": {
        "pagePathContains": "/pricing"
      }
    }
  ]
}

When to Use This Skill

适用场景

This skill is ideal when:
  • Setting up GA4 + GTM tracking from scratch
  • Auditing or refactoring existing tracking implementations
  • Implementing Shopify storefront tracking
  • Automating repetitive tracking tasks across multiple sites
  • Needing reviewable, resumable tracking workflows
  • Working with non-technical stakeholders who need business-friendly artifacts
This skill is NOT ideal for:
  • Real-time production debugging (use GTM Debug View instead)
  • Server-side tracking or custom measurement protocols
  • Multi-destination tracking (Adobe, Segment, etc.) without GTM
  • Sites requiring authentication or complex session flows
本Skill适用于以下场景:
  • 从零开始设置GA4 + GTM追踪
  • 审核或重构现有追踪实施方案
  • 实施Shopify店铺前端追踪
  • 跨多个网站自动化重复追踪任务
  • 需要可审核、可恢复的追踪工作流
  • 与非技术利益相关方协作,需要业务友好型工件
本Skill不适用于:
  • 实时生产调试(建议使用GTM调试视图)
  • 服务器端追踪或自定义测量协议
  • 不通过GTM的多目标追踪(如Adobe、Segment等)
  • 需要身份验证或复杂会话流程的网站

Key Files and Extension Points

关键文件与扩展点

  • src/core/analyzer.ts
    : Site crawl and page classification logic
  • src/core/schema-generator.ts
    : Event schema generation
  • src/core/gtm-sync.ts
    : GTM API integration
  • src/core/verifier.ts
    : Automated preview verification
  • src/platforms/shopify.ts
    : Shopify-specific tracking
  • event-schema.json
    : Editable event schema artifact
  • page-groups.json
    : Editable page grouping artifact
Extend by forking and modifying these files, or by editing artifacts between CLI stages.
  • src/core/analyzer.ts
    :网站爬取与页面分类逻辑
  • src/core/schema-generator.ts
    :事件Schema生成逻辑
  • src/core/gtm-sync.ts
    :GTM API集成逻辑
  • src/core/verifier.ts
    :自动化预览验证逻辑
  • src/platforms/shopify.ts
    :Shopify专属追踪逻辑
  • event-schema.json
    :可编辑的事件Schema工件
  • page-groups.json
    :可编辑的页面分组工件
可通过克隆并修改这些文件,或在CLI阶段之间编辑工件进行扩展。

Further Reading

进一步阅读

  • Skill contract: See
    SKILL.md
    in repository for agent-facing workflow details
  • Developer guide: See
    DEVELOPING.md
    for CLI internals and maintainer workflow
  • Skill installation: See
    docs/README.install.md
    for advanced install options
  • JTracking website: https://www.jtracking.ai/skills
  • Skill契约:查看仓库中的
    SKILL.md
    获取面向Agent的工作流详情
  • 开发者指南:查看
    DEVELOPING.md
    了解CLI内部机制与维护者工作流
  • Skill安装:查看
    docs/README.install.md
    获取高级安装选项
  • JTracking官网https://www.jtracking.ai/skills

Support

支持

For issues, questions, or feature requests, contact support@jtracking.ai or open an issue on GitHub.
如有问题、疑问或功能请求,请联系support@jtracking.ai或在GitHub上提交Issue。