From e1fcc5e056061794136a106f3977d65b791703e1 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 30 Nov 2026 10:02:43 +0000 Subject: [PATCH 1/2] chore(examples): add click cell test app --- .../browser/click-cell-test-app/.env.example | 9 ++ .../browser/click-cell-test-app/.gitignore | 3 + .../browser/click-cell-test-app/README.md | 53 +++++++++ .../browser/click-cell-test-app/index.html | 70 +++++++++++ .../browser/click-cell-test-app/package.json | 16 +++ .../click-cell-test-app/scripts/setup.mjs | 16 +++ .../click-cell-test-app/scripts/verify.mjs | 83 +++++++++++++ .../click-cell-test-app/sdk-version.txt | 1 + .../browser/click-cell-test-app/src/main.js | 110 ++++++++++++++++++ .../click-cell-test-app/vite.config.js | 50 ++++++++ 10 files changed, 411 insertions(+) create mode 100644 examples/browser/click-cell-test-app/.env.example create mode 100644 examples/browser/click-cell-test-app/.gitignore create mode 100644 examples/browser/click-cell-test-app/README.md create mode 100644 examples/browser/click-cell-test-app/index.html create mode 100644 examples/browser/click-cell-test-app/package.json create mode 100644 examples/browser/click-cell-test-app/scripts/setup.mjs create mode 100644 examples/browser/click-cell-test-app/scripts/verify.mjs create mode 100644 examples/browser/click-cell-test-app/sdk-version.txt create mode 100644 examples/browser/click-cell-test-app/src/main.js create mode 100644 examples/browser/click-cell-test-app/vite.config.js diff --git a/examples/browser/click-cell-test-app/.env.example b/examples/browser/click-cell-test-app/.env.example new file mode 100644 index 0000000000..86e58e446e --- /dev/null +++ b/examples/browser/click-cell-test-app/.env.example @@ -0,0 +1,9 @@ +# Copy to .env (git-ignored) or export these in the shell / cloud agent secrets. +AMPLITUDE_API_KEY= +# US or EU +AMPLITUDE_SERVER_ZONE=US +# Optional: override the port (default 5180) +# PORT=5180 +# Optional, local mode only: checkout whose packages/analytics-browser is built (pnpm build). +# Default: this repository's own packages/analytics-browser. +# AMPLITUDE_SDK_LOCAL_PATH=/path/to/Amplitude-TypeScript/packages/analytics-browser diff --git a/examples/browser/click-cell-test-app/.gitignore b/examples/browser/click-cell-test-app/.gitignore new file mode 100644 index 0000000000..4daabc937d --- /dev/null +++ b/examples/browser/click-cell-test-app/.gitignore @@ -0,0 +1,3 @@ +verify.png +node_modules/ +package-lock.json diff --git a/examples/browser/click-cell-test-app/README.md b/examples/browser/click-cell-test-app/README.md new file mode 100644 index 0000000000..e1b5afed1d --- /dev/null +++ b/examples/browser/click-cell-test-app/README.md @@ -0,0 +1,53 @@ +# Click cell test app + +A minimal Browser SDK page for checking the `[Amplitude] Element Click Cell`, `... Cell Min Size` and `... Cell Max Per Axis` properties on `[Amplitude] Element Clicked` events (HM-39). It initializes the SDK with `autocapture.elementInteractions` on and `fetchRemoteConfig: true`, shows green click targets of many sizes, and lists every outgoing event in a side panel (payload, plus a table of the three properties; the page also logs each event to the console and shows the remote config response and upload status codes). A keyboard click (Enter) shows the properties as `absent`; that is expected. + +It is standalone (not part of the pnpm workspace) and uses `npm`. + +## Configuration + +Nothing secret is committed. Provide these as environment variables, in a git-ignored `.env` in this folder (see `.env.example`), or as cloud agent secrets: + +| Variable | Meaning | +|---|---| +| `AMPLITUDE_API_KEY` | API key of the Amplitude project to send to (required) | +| `AMPLITUDE_SERVER_ZONE` | `US` (default) or `EU` | +| `PORT` | dev server port, default `5180` | +| `AMPLITUDE_SDK_LOCAL_PATH` | local mode only: `packages/analytics-browser` of a built checkout; default is this repository's | + +Query parameters on the page override the first two (`?apiKey=...&serverZone=EU`), and `?clickCell=` sets a local `autocapture.elementInteractions.clickCell` (for example `?clickCell={"enabled":true,"minCellSizePx":32}`). Without `clickCell`, the option is left unset, so defaults or remote config decide. + +## Choosing the SDK: `sdk-version.txt` + +The whole choice is the single line in `sdk-version.txt`: + +- a published version, for example `2.51.0-cursorhm-39-click-cell-9eb2.0` (the real version is whatever the pre-release workflow printed), installs `@amplitude/analytics-browser@` from npm; +- `local` (the current value) uses the monorepo build instead. That checkout must be on `cursor/hm-39-click-cell-9eb2` (or contain the change) and built with `pnpm install && pnpm build` at the repository root. To use another checkout, set `AMPLITUDE_SDK_LOCAL_PATH`. + +After changing the line, re-run `npm run setup`. The page's first table row shows which SDK is in use (`npm @amplitude/analytics-browser@` or `local build ...`); check it before testing. + +## Run locally + +```bash +cd examples/browser/click-cell-test-app +export AMPLITUDE_API_KEY=... # or put it in .env +export AMPLITUDE_SERVER_ZONE=US # or EU +npm run setup +npm start # http://localhost:5180 +``` + +## Run in a cloud agent VM + +Same commands. The dev server listens on all interfaces and accepts any host, so a forwarded port or the VM's browser works. Supply the key as a secret environment variable (`AMPLITUDE_API_KEY`, `AMPLITUDE_SERVER_ZONE`) and never commit a `.env`. In local mode the repository must be built first (`pnpm install && pnpm build` at the root); with a published version nothing else is needed. + +## Headless check (no API key needed) + +`npm run verify` drives headless Chromium against the running dev server with remote config and the upload endpoint mocked, clicks the 24x24, 100x40, 300x200 and 700x400 targets near their bottom-right corner plus an Enter key click, and prints the properties seen on the events and in the upload requests. First time: `npx playwright install chromium`. + +```bash +npm run verify # defaults +npm run verify -- '{"enabled":true,"minCellSizePx":32,"maxCellsPerAxis":3}' # remote clickCell +npm run verify -- '{"enabled":false}' # remote disabled: no properties +``` + +Expected with defaults: `1x1:0,0` for 24x24 and 100x40 clicked at the corner, `4x3:3,2` for 300x200, `10x6:9,5` for 700x400, each with min size 64 and max per axis 10, and no properties on the keyboard click. diff --git a/examples/browser/click-cell-test-app/index.html b/examples/browser/click-cell-test-app/index.html new file mode 100644 index 0000000000..7f5827a90b --- /dev/null +++ b/examples/browser/click-cell-test-app/index.html @@ -0,0 +1,70 @@ + + + + + + Click cell test app + + + +
+

Click cell test app

+
Starting...
+

Click the elements below with the mouse. Each click sends [Amplitude] Element Clicked; the right panel shows the payload and the click cell properties. Pressing Enter on a focused element is a keyboard click and carries no click cell.

+
+ +

Click targets (CSS size in the label)

+
+ + + + 300x200 link + +
+
+ +
+ + +
+ + + + diff --git a/examples/browser/click-cell-test-app/package.json b/examples/browser/click-cell-test-app/package.json new file mode 100644 index 0000000000..ef25a091ca --- /dev/null +++ b/examples/browser/click-cell-test-app/package.json @@ -0,0 +1,16 @@ +{ + "name": "click-cell-test-app", + "version": "1.0.0", + "private": true, + "type": "module", + "description": "Minimal Browser SDK app for checking the [Amplitude] Element Click Cell properties on Element Clicked events.", + "scripts": { + "setup": "node scripts/setup.mjs", + "start": "vite", + "verify": "node scripts/verify.mjs" + }, + "devDependencies": { + "playwright": "^1.55.1", + "vite": "^7.3.7" + } +} diff --git a/examples/browser/click-cell-test-app/scripts/setup.mjs b/examples/browser/click-cell-test-app/scripts/setup.mjs new file mode 100644 index 0000000000..4d9dae2657 --- /dev/null +++ b/examples/browser/click-cell-test-app/scripts/setup.mjs @@ -0,0 +1,16 @@ +import { readFileSync } from 'node:fs'; +import { execSync } from 'node:child_process'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = join(dirname(fileURLToPath(import.meta.url)), '..'); +const version = readFileSync(join(root, 'sdk-version.txt'), 'utf8').trim(); +const run = (cmd) => execSync(cmd, { cwd: root, stdio: 'inherit' }); + +run('npm install --no-audit --no-fund'); +if (version === 'local') { + console.log('\nsdk-version.txt is "local": using the monorepo build (see README). Nothing else to install.'); +} else { + run(`npm install --no-save --no-audit --no-fund @amplitude/analytics-browser@${version}`); + console.log(`\nInstalled @amplitude/analytics-browser@${version} from npm.`); +} diff --git a/examples/browser/click-cell-test-app/scripts/verify.mjs b/examples/browser/click-cell-test-app/scripts/verify.mjs new file mode 100644 index 0000000000..ec9dfd62c3 --- /dev/null +++ b/examples/browser/click-cell-test-app/scripts/verify.mjs @@ -0,0 +1,83 @@ +// Headless check that a pointer click sends the three click cell properties. +// Network is mocked (remote config + event upload), so no real API key is needed: +// npm run verify # defaults +// npm run verify -- '{"enabled":true,"minCellSizePx":32,"maxCellsPerAxis":3}' # remote clickCell +// Requires the dev server to be running (npm start) and Chromium (npx playwright install chromium). +import { chromium } from 'playwright'; +import { gunzipSync } from 'node:zlib'; + +const base = process.env.APP_URL || `http://127.0.0.1:${process.env.PORT || 5180}`; +const remoteClickCell = process.argv[2] ? JSON.parse(process.argv[2]) : undefined; + +const browser = await chromium.launch(); +const page = await browser.newPage({ viewport: { width: 1500, height: 1100 } }); +const uploads = []; + +await page.route(/sr-client-cfg\.(eu\.)?amplitude\.com/, (route) => { + const elementInteractions = { pageViewsOnly: false }; + if (remoteClickCell !== undefined) elementInteractions.clickCell = remoteClickCell; + route.fulfill({ + status: 200, + contentType: 'application/json', + headers: { 'access-control-allow-origin': '*' }, + body: JSON.stringify({ + configs: { analyticsSDK: { browserSDK: { autocapture: { elementInteractions } } } }, + }), + }); +}); +await page.route(/api2?\.(eu\.)?amplitude\.com/, (route) => { + const cors = { 'access-control-allow-origin': '*', 'access-control-allow-headers': '*' }; + if (route.request().method() === 'OPTIONS') return route.fulfill({ status: 204, headers: cors }); + const raw = route.request().postDataBuffer() || Buffer.from('{}'); + const text = raw[0] === 0x1f && raw[1] === 0x8b ? gunzipSync(raw).toString() : raw.toString(); + uploads.push(JSON.parse(text)); + route.fulfill({ + status: 200, + contentType: 'application/json', + headers: cors, + body: JSON.stringify({ code: 200, events_ingested: 1, payload_size_bytes: 1, server_upload_time: Date.now() }), + }); +}); + +await page.goto(`${base}/?apiKey=${process.env.AMPLITUDE_API_KEY || 'verify-fake-key'}`); +await page.waitForFunction(() => window.__amplitudeReady === true); +await page.waitForTimeout(1500); + +const results = {}; +for (const id of ['t-tiny', 't-button', 't-medium', 't-large']) { + const before = await page.evaluate(() => window.__events.length); + await page.locator(`#${id}`).scrollIntoViewIfNeeded(); + const box = await page.locator(`#${id}`).boundingBox(); + await page.mouse.click(box.x + box.width - 2, box.y + box.height - 2); + await page.waitForTimeout(400); + results[id] = await page.evaluate( + (n) => window.__events.slice(n).filter((e) => e.event_type === '[Amplitude] Element Clicked').map((e) => e.event_properties), + before, + ); +} +await page.focus('#t-button'); +const kb = await page.evaluate(() => window.__events.length); +await page.keyboard.press('Enter'); +await page.waitForTimeout(400); +const keyboard = await page.evaluate((n) => window.__events.slice(n).map((e) => e.event_properties), kb); + +await page.waitForTimeout(2500); +const clickUploads = uploads.flatMap((u) => u.events || []).filter((e) => e.event_type === '[Amplitude] Element Clicked'); + +for (const [id, events] of Object.entries(results)) { + const p = events[0] || {}; + console.log(id, { + cell: p['[Amplitude] Element Click Cell'], + min: p['[Amplitude] Element Click Cell Min Size'], + max: p['[Amplitude] Element Click Cell Max Per Axis'], + }); +} +console.log('keyboard click props present:', Object.keys(keyboard[0] || {}).filter((k) => k.includes('Click Cell'))); +console.log('Element Clicked events in upload requests:', clickUploads.length); +console.log('first uploaded click event cell props:', clickUploads[0] && { + cell: clickUploads[0].event_properties['[Amplitude] Element Click Cell'], + min: clickUploads[0].event_properties['[Amplitude] Element Click Cell Min Size'], + max: clickUploads[0].event_properties['[Amplitude] Element Click Cell Max Per Axis'], +}); +await page.screenshot({ path: process.env.SCREENSHOT || 'verify.png' }); +await browser.close(); diff --git a/examples/browser/click-cell-test-app/sdk-version.txt b/examples/browser/click-cell-test-app/sdk-version.txt new file mode 100644 index 0000000000..4083037423 --- /dev/null +++ b/examples/browser/click-cell-test-app/sdk-version.txt @@ -0,0 +1 @@ +local diff --git a/examples/browser/click-cell-test-app/src/main.js b/examples/browser/click-cell-test-app/src/main.js new file mode 100644 index 0000000000..d1adf5ea1f --- /dev/null +++ b/examples/browser/click-cell-test-app/src/main.js @@ -0,0 +1,110 @@ +import * as amplitude from '@amplitude/analytics-browser'; + +const CLICKED = '[Amplitude] Element Clicked'; +const CELL_PROPS = [ + '[Amplitude] Element Click Cell', + '[Amplitude] Element Click Cell Min Size', + '[Amplitude] Element Click Cell Max Per Axis', +]; + +const params = new URLSearchParams(window.location.search); +const apiKey = params.get('apiKey') || __AMPLITUDE_API_KEY__; +const serverZone = (params.get('serverZone') || __AMPLITUDE_SERVER_ZONE__).toUpperCase(); +const localClickCell = params.get('clickCell'); + +const $ = (id) => document.getElementById(id); +const esc = (s) => String(s).replace(/[&<>]/g, (c) => ({ '&': '&', '<': '<', '>': '>' })[c]); +const setStatus = (text, warn) => { + $('status').textContent = text; + $('status').classList.toggle('warn', Boolean(warn)); +}; + +const network = []; +const renderSummary = (extra = '') => { + $('config-summary').innerHTML = ` + + + + + ${extra} + ${network.map((n) => ``).join('')} +
SDK${esc(__SDK_SOURCE__)}
Server zone${esc(serverZone)}
API key${apiKey ? esc(apiKey.slice(0, 4) + '...' + apiKey.slice(-2)) : 'NOT SET'}
Local clickCell option${localClickCell === null ? '(not set: defaults, or remote config)' : esc(localClickCell)}
${esc(n.label)}${esc(n.value)}
`; +}; + +// Surface the remote config response and event uploads on the page. +const originalFetch = window.fetch.bind(window); +window.fetch = async (input, init) => { + const url = typeof input === 'string' ? input : input.url; + const response = await originalFetch(input, init); + if (url.includes('sr-client-cfg')) { + const body = await response.clone().text(); + console.log('[click-cell-test-app] remote config', response.status, body); + network.push({ label: 'Remote config', value: `${response.status} ${body.slice(0, 300)}` }); + renderSummary(); + } else if (/amplitude\.com\/(2\/httpapi|batch)/.test(url) && init && init.body) { + console.log('[click-cell-test-app] upload', response.status, url); + network.push({ label: 'Event upload', value: `${response.status} ${url}` }); + renderSummary(); + } + return response; +}; + +const cellPlugin = { + name: 'click-cell-test-app-viewer', + type: 'destination', + async setup() {}, + async execute(context) { + show(context); + return { event: context, code: 200, message: 'viewed' }; + }, +}; + +function show(event) { + const isClick = event.event_type === CLICKED; + const props = event.event_properties || {}; + const rows = CELL_PROPS.map( + (name) => `${esc(name)}${name in props ? esc(JSON.stringify(props[name])) : 'absent'}`, + ).join(''); + const el = document.createElement('div'); + el.className = 'ev'; + el.innerHTML = `

${esc(event.event_type)} (${new Date().toLocaleTimeString()})

+ ${isClick ? `${rows}
+
element: ${esc(props['[Amplitude] Element Tag'] || '')}#${esc(props['[Amplitude] Element ID'] || '')}
` : ''} +
payload
${esc(JSON.stringify(event, null, 2))}
`; + $('events').prepend(el); + console.log(`[click-cell-test-app] ${event.event_type}`, JSON.parse(JSON.stringify(event))); + window.__events = window.__events || []; + window.__events.push(JSON.parse(JSON.stringify(event))); +} + +$('clear').addEventListener('click', () => { + $('events').innerHTML = ''; +}); + +function init() { + renderSummary(); + if (!apiKey) { + setStatus('No API key. Set AMPLITUDE_API_KEY (see README) or open with ?apiKey=...', true); + return; + } + const elementInteractions = {}; + if (localClickCell !== null) { + elementInteractions.clickCell = JSON.parse(localClickCell); + } + amplitude.add(cellPlugin); + const result = amplitude.init(apiKey, undefined, { + serverZone, + fetchRemoteConfig: true, + autocapture: { + elementInteractions: Object.keys(elementInteractions).length ? elementInteractions : true, + }, + }); + result.promise.then(() => { + renderSummary(`Device ID${esc(amplitude.getDeviceId())}`); + window.__amplitudeReady = true; + setStatus('Ready. Click the green elements.'); + }); + window.amplitude = amplitude; +} + +init(); diff --git a/examples/browser/click-cell-test-app/vite.config.js b/examples/browser/click-cell-test-app/vite.config.js new file mode 100644 index 0000000000..778faea238 --- /dev/null +++ b/examples/browser/click-cell-test-app/vite.config.js @@ -0,0 +1,50 @@ +import { defineConfig, loadEnv } from 'vite'; +import { existsSync, readFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = dirname(fileURLToPath(import.meta.url)); + +export default defineConfig(({ mode }) => { + const env = { ...loadEnv(mode, root, ''), ...process.env }; + const sdkVersion = readFileSync(join(root, 'sdk-version.txt'), 'utf8').trim(); + const isLocal = sdkVersion === 'local'; + + const localPath = resolve( + root, + env.AMPLITUDE_SDK_LOCAL_PATH || '../../../packages/analytics-browser', + ); + const localEntry = join(localPath, 'lib/esm/index.js'); + if (isLocal && !existsSync(localEntry)) { + throw new Error( + `sdk-version.txt is "local" but ${localEntry} does not exist. Run "pnpm build" in that checkout, ` + + 'or set AMPLITUDE_SDK_LOCAL_PATH, or put a published version in sdk-version.txt.', + ); + } + + const installedPkg = isLocal + ? join(localPath, 'package.json') + : join(root, 'node_modules/@amplitude/analytics-browser/package.json'); + const installedVersion = existsSync(installedPkg) + ? JSON.parse(readFileSync(installedPkg, 'utf8')).version + : 'not installed (run "npm run setup")'; + + return { + root, + resolve: isLocal ? { alias: { '@amplitude/analytics-browser': localEntry } } : {}, + define: { + __AMPLITUDE_API_KEY__: JSON.stringify(env.AMPLITUDE_API_KEY || ''), + __AMPLITUDE_SERVER_ZONE__: JSON.stringify((env.AMPLITUDE_SERVER_ZONE || 'US').toUpperCase()), + __SDK_SOURCE__: JSON.stringify( + isLocal ? `local build ${localPath} (${installedVersion})` : `npm @amplitude/analytics-browser@${installedVersion}`, + ), + }, + server: { + host: true, + port: Number(env.PORT) || 5180, + strictPort: true, + allowedHosts: true, + fs: { allow: [root, localPath, resolve(localPath, '../..')] }, + }, + }; +}); From 81397ca5f7dc2bbe87645a3e3abba01860651cb9 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Tue, 1 Dec 2026 02:42:57 +0000 Subject: [PATCH 2/2] chore(examples): use HM-39 click cell pre-release in test app Co-authored-by: Junjie Wang --- examples/browser/click-cell-test-app/README.md | 6 +++--- examples/browser/click-cell-test-app/sdk-version.txt | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/browser/click-cell-test-app/README.md b/examples/browser/click-cell-test-app/README.md index e1b5afed1d..f15ad9d962 100644 --- a/examples/browser/click-cell-test-app/README.md +++ b/examples/browser/click-cell-test-app/README.md @@ -19,10 +19,10 @@ Query parameters on the page override the first two (`?apiKey=...&serverZone=EU` ## Choosing the SDK: `sdk-version.txt` -The whole choice is the single line in `sdk-version.txt`: +The whole choice is the single line in `sdk-version.txt` (currently the HM-39 pre-release): -- a published version, for example `2.51.0-cursorhm-39-click-cell-9eb2.0` (the real version is whatever the pre-release workflow printed), installs `@amplitude/analytics-browser@` from npm; -- `local` (the current value) uses the monorepo build instead. That checkout must be on `cursor/hm-39-click-cell-9eb2` (or contain the change) and built with `pnpm install && pnpm build` at the repository root. To use another checkout, set `AMPLITUDE_SDK_LOCAL_PATH`. +- a published version, for example `2.51.0-cursorhm-39-click-cell-9eb2.0` (the HM-39 pre-release, npm tag `cursorhm-39-click-cell-9eb2`), installs `@amplitude/analytics-browser@` from npm; +- `local` uses the monorepo build instead. That checkout must be on `cursor/hm-39-click-cell-9eb2` (or contain the change) and built with `pnpm install && pnpm build` at the repository root. To use another checkout, set `AMPLITUDE_SDK_LOCAL_PATH`. After changing the line, re-run `npm run setup`. The page's first table row shows which SDK is in use (`npm @amplitude/analytics-browser@` or `local build ...`); check it before testing. diff --git a/examples/browser/click-cell-test-app/sdk-version.txt b/examples/browser/click-cell-test-app/sdk-version.txt index 4083037423..20239d078b 100644 --- a/examples/browser/click-cell-test-app/sdk-version.txt +++ b/examples/browser/click-cell-test-app/sdk-version.txt @@ -1 +1 @@ -local +2.51.0-cursorhm-39-click-cell-9eb2.0