The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.
TypeScript b2b-marketplacecomposable-commerceecommerceenterpriseheadless-commercemarketplacemedusamedusajsmulti-vendortypescript
feat(telemetry): anonymous server heartbeats, milestones and CLI command events (#1718)
Viktor Holikddac75c573e7
diff --git a/apps/docs/telemetry.mdx b/apps/docs/telemetry.mdxindex 2f687afb2..50e8425f0 100644--- a/apps/docs/telemetry.mdx+++ b/apps/docs/telemetry.mdx@@ -1,67 +1,121 @@---title: "Telemetry"-description: "Learn about the anonymous usage data collected by the Mercur CLI"+description: "What anonymous usage data Mercur collects, why, and how to turn it off"---## Overview-The Mercur CLI collects **anonymous usage data** to help us understand how the CLI is used and improve the developer experience. This data is collected by default but can be easily disabled.+Mercur collects **anonymous usage data** from the CLI tools and from running+Mercur servers. It tells the maintainers how many installations exist, which+versions of Mercur, Medusa and Node they run, which first-party plugins they+use, and whether new installations keep running. That is what decides which+upgrade paths to keep working and which features to invest in.++Collection is on by default and can be turned off in one line. Nothing that+identifies a company, a person, a shop or a URL ever leaves your machine.++## Principles++- **Random ids only.** A running server is identified by a random UUID stored+ in its own database. A developer machine is identified by a random UUID in+ the CLI config file. No hardware ids, no hostnames, no IP geolocation+ (`$geoip_disable` is set on every event).+- **Counts are ranges.** Entity counts are sent as one of `0`, `1-10`,+ `11-100`, `101-1k`, `1k-10k`, `10k-100k`, `100k+`. Exact numbers never leave.+- **Only first-party names.** Plugin, module and provider names are reported+ only when they start with `@mercurjs/` or `@medusajs/`. Anything else is+ counted (`custom_plugin_count`), never named. Block names are reported only+ for the official `@mercurjs` registry.+- **Never in the way.** Every request has a 2 s timeout and every failure is+ swallowed. Nothing is sent from CI, from test runs, or from Medusa worker+ processes.+- **Auditable.** Set `MERCUR_TELEMETRY_DEBUG=true` and every payload is+ printed instead of sent, so you can see exactly what would leave your+ machine.++## How to opt out++Any one of these disables telemetry everywhere (CLI and server):-## What We Collect+```bash+export MERCUR_DISABLE_TELEMETRY=true+# or the cross-tool convention+export DO_NOT_TRACK=1+```-When you run CLI commands (`create`, `init`, `add`, `registry:build`), the following data is sent:+For the server only, in `medusa-config.ts`:-| Data | Description |-|------|-------------|-| Event type | Which command was run and its outcome |-| Node.js version | Your Node.js runtime version |-| Node environment | The `NODE_ENV` value |-| Mercur version | Version of `@mercurjs/cli` in your project |-| Medusa version | Version of `@medusajs/framework` in your project |-| Package manager | npm, yarn, pnpm, or bun |-| Project structure | Whether `src/` directory is used, alias prefix |-| System info | OS, platform, architecture, CPU model/speed/count, RAM |-| Environment | Whether running in WSL, Docker, or a TTY |-| Deployment vendor | Detected hosting platform (Railway, Fly.io, Heroku, etc.) |-| Project ID | SHA-256 hash (base64) of your git remote URL — **not the URL itself** |-| Project config | Contents of your `blocks.json` configuration |-| Email | **Only** if you voluntarily provided it during `create-mercur-app` |+```ts+module.exports = withMercur({+ projectConfig: {+ mercur: { telemetry: false },+ },+})+```-## What We Do NOT Collect+For the CLI only:-- Source code or file contents-- File names or directory structure-- Git history or commit messages-- Personal data (beyond the optional email above)+```bash+bunx @mercurjs/cli@latest telemetry --disable # persists in ~/.config/mercur/config.json+bunx @mercurjs/cli@latest telemetry # show current status+bunx @mercurjs/cli@latest telemetry --enable+```-## How to Opt Out+## Where data goes-### Using the CLI+Events are sent to `https://telemetry.mercurjs.com`, a service operated by the+Mercur team. The data is stored securely, used only in aggregate to guide+development, and never shared with third parties or used to identify an+installation or a person.-```bash-bunx @mercurjs/cli@latest telemetry --disable-```+## What the server sends-### Using an environment variable+### Events-```bash-export MERCUR_DISABLE_TELEMETRY=true-```+| Event | When |+| --- | --- |+| `instance_started` | A few seconds after the HTTP server starts. Not sent by worker processes, migrations or `medusa exec`. |+| `instance_heartbeat` | Once every 24 hours (plus up to an hour of jitter). With several replicas on one database only one of them sends. |+| `instance_upgraded` | When a heartbeat sees a different `@mercurjs/core` version than the previous one. Carries `from_version` and `to_version`. |+| `installation_milestone` | The first time an installation reaches one of the milestones below. Carries `milestone` and `days_since_install`. Never carries ids, names or amounts. |-This is useful for CI/CD environments or shared configurations.+Milestones: `first_production_boot`, `first_seller`, `first_seller_approved`,+`first_member_invited`, `first_offer`, `first_product_published`,+`first_order`, `first_payout_account`, `first_payout_paid`,+`first_commission_rule`.-### Check current status+### Properties-```bash-bunx @mercurjs/cli@latest telemetry-```+| Group | Properties |+| --- | --- |+| Identity | `schema_version`, `source` (`server`), `installation_id` (random UUID), `project_id` (salted SHA-256 of the git remote URL, or of the working directory when there is no remote), `instance_age_days` |+| Versions | `mercur_version`, `medusa_version`, `node_version`, `runtime` (`node` or `bun`), `package_manager`, `postgres_version` (major only) |+| Environment | `node_env`, `os`, `arch`, `cpu_count`, `total_memory_gb`, `containerized`, `cloud_provider` (detected from well-known environment variables), `worker_mode`, `redis_enabled`, `uptime_seconds` |+| Stack | `plugins`, `custom_plugin_count`, `modules`, `custom_module_count`, `payment_providers`, `payout_provider`, `notification_providers`, `file_provider`, `search_provider`, `feature_flags`, `admin_disabled` |+| Marketplace (ranges) | `sellers_total`, `sellers_pending`, `sellers_open`, `sellers_suspended`, `members_total`, `products_total`, `products_published`, `products_proposed`, `offers_total`, `product_changes_pending`, `order_groups_total`, `order_groups_last_30d`, `orders_total`, `payouts_paid`, `payouts_failed`, `payout_accounts_active`, `commission_rules_total`, `regions_total`, `currencies_total`, `sales_channels_total` |-## Where Data Goes+## What the CLI sends-Telemetry events are sent to `https://telemetry.mercurjs.com`. The data is used exclusively by the Mercur team to prioritize features and fix issues.+Applies to `@mercurjs/cli` and `create-mercur-app`.-## Re-enabling Telemetry+| Event | When | Extra properties |+| --- | --- | --- |+| `cli_command_executed` | Every command | `command`, `flags` (flag names; values kept only for booleans and fixed choices, otherwise `<redacted>`), `exit_code`, `duration_ms`, `error_category` (`network`, `fs`, `validation`, `registry`, `install`, `database`, `unknown`) |+| `project_created` | `create-mercur-app` finished | `template`, `package_manager`, `with_storefront`, `skip_db` |+| `block_added` | `mercurjs add` succeeded | `block` (official registry only, otherwise `<custom-registry>`), `registry_kind`, `overwrite` |-```bash-bunx @mercurjs/cli@latest telemetry --enable-```+Properties on every CLI event: `schema_version`, `source`, `cli_version`,+`mercur_version`, `medusa_version`, `node_version`, `runtime`,+`package_manager`, `os`, `arch`, `is_src_dir`, `is_ci`, `is_tty`, `is_agent`+(whether an AI coding agent is driving the terminal), `is_docker`, `is_wsl`,+`cloud_provider`, `project_id`.++## What is never collected++- Source code, file names, directory structure or configuration files+- Email addresses or any personal data (the optional email prompt was removed)+- URLs, hostnames, IP addresses or geolocation+- Names of custom plugins, modules, providers, routes or blocks from private+ registries+- Exact entity counts, order values, or anything tied to a seller, customer or+ orderdiff --git a/integration-tests/http/telemetry/admin/telemetry.spec.ts b/integration-tests/http/telemetry/admin/telemetry.spec.tsnew file mode 100644index 000000000..157dc6084--- /dev/null+++ b/integration-tests/http/telemetry/admin/telemetry.spec.ts@@ -0,0 +1,161 @@+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"+import { MedusaContainer } from "@medusajs/framework/types"+import { MercurModules } from "@mercurjs/types"+import { approveSellerWorkflow } from "@mercurjs/core/workflows"+import http from "node:http"++import { createSellerUser } from "../../../helpers/create-seller-user"++jest.setTimeout(60000)++type CapturedEvent = {+ event: string+ distinct_id: string+ properties: Record<string, unknown>+}++const captured: CapturedEvent[] = []+const CAPTURE_PORT = 48127++// Listening before the runner boots the app, because `instance_started` is+// sent right after the HTTP server comes up.+const captureServer = http+ .createServer((req, res) => {+ let body = ""+ req.on("data", (chunk) => (body += chunk))+ req.on("end", () => {+ try {+ const parsed = JSON.parse(body)+ expect(req.url).toBe("/batch")+ expect(parsed.api_key).toBe("mercur")+ captured.push(...parsed.batch)+ } catch {+ // Malformed bodies surface as missing events in the assertions below.+ }+ res.writeHead(200, { "content-type": "application/json" })+ res.end("{}")+ })+ })+ .listen(CAPTURE_PORT, "127.0.0.1")++const waitFor = async (predicate: () => boolean, timeoutMs = 15000) => {+ const started = Date.now()+ while (!predicate()) {+ if (Date.now() - started > timeoutMs) {+ throw new Error(`Timed out waiting for telemetry. Captured: ${JSON.stringify(captured.map((e) => e.event))}`)+ }+ await new Promise((resolve) => setTimeout(resolve, 100))+ }+}++const FORBIDDEN_KEYS = ["email", "config", "url", "cwd", "hostname", "aliasPrefix", "systemInfo"]+const BUCKETS = ["0", "1-10", "11-100", "101-1k", "1k-10k", "10k-100k", "100k+"]++const milestoneEvents = (name: string) =>+ captured.filter((e) => e.event === "installation_milestone" && e.properties.milestone === name)++medusaIntegrationTestRunner({+ env: {+ MERCUR_TELEMETRY_FORCE_ENABLED: "true",+ MERCUR_TELEMETRY_PROXY_URL: `http://127.0.0.1:${CAPTURE_PORT}`,+ MERCUR_TELEMETRY_STARTUP_DELAY_MS: "0",+ },+ testSuite: ({ getContainer }) => {+ describe("Telemetry", () => {+ let container: MedusaContainer++ beforeAll(async () => {+ container = getContainer()+ await waitFor(() => captured.some((e) => e.event === "instance_started"))+ })++ afterAll(() => {+ captureServer.close()+ })++ it("sends instance_started for the installation stored in the database", async () => {+ const service = container.resolve<{+ getOrCreateInstallation: () => Promise<{ installation_id: string }>+ }>(MercurModules.TELEMETRY)+ const installation = await service.getOrCreateInstallation()++ const started = captured.find((e) => e.event === "instance_started")!+ expect(started.distinct_id).toBe(installation.installation_id)++ const props = started.properties+ expect(props.schema_version).toBe(1)+ expect(props.source).toBe("server")+ expect(props.installation_id).toBe(installation.installation_id)+ expect(props.$groups).toEqual({ installation: installation.installation_id, project: props.project_id })+ expect(props.$geoip_disable).toBe(true)+ expect(typeof props.project_id).toBe("string")+ expect(props.node_version).toBe(process.version)+ expect(typeof props.mercur_version).toBe("string")+ expect(Array.isArray(props.plugins)).toBe(true)+ expect(props.plugins).toContain("@mercurjs/core")+ expect(typeof props.custom_plugin_count).toBe("number")++ for (const key of ["sellers_total", "offers_total", "order_groups_total", "regions_total"]) {+ expect(BUCKETS).toContain(props[key])+ }+ for (const key of FORBIDDEN_KEYS) {+ expect(props).not.toHaveProperty(key)+ }++ const identify = captured.find((e) => e.event === "$groupidentify")!+ expect(identify.properties.$group_type).toBe("installation")+ expect(identify.properties.$group_key).toBe(installation.installation_id)+ })++ it("never names custom plugins", () => {+ const started = captured.find((e) => e.event === "instance_started")!+ for (const name of started.properties.plugins as string[]) {+ expect(name.startsWith("@mercurjs/") || name.startsWith("@medusajs/")).toBe(true)+ }+ for (const name of started.properties.modules as string[]) {+ expect(name.startsWith("@mercurjs/") || name.startsWith("@medusajs/")).toBe(true)+ }+ })++ it("reuses the installation id and lets only one heartbeat claim through", async () => {+ const service = container.resolve<{+ getOrCreateInstallation: () => Promise<{ installation_id: string }>+ claimHeartbeat: (gap: number) => Promise<boolean>+ updateTelemetryInstallations: (data: { id: string; last_heartbeat_at: Date | null }) => Promise<unknown>+ }>(MercurModules.TELEMETRY)+ const DAY = 23 * 60 * 60++ const first = await service.getOrCreateInstallation()+ const second = await service.getOrCreateInstallation()+ expect(second.installation_id).toBe(first.installation_id)++ // Boot already claimed the slot, so a 23 h gap is not due yet.+ expect(await service.claimHeartbeat(DAY)).toBe(false)++ await service.updateTelemetryInstallations({ id: "singleton", last_heartbeat_at: null })+ const [a, b] = await Promise.all([service.claimHeartbeat(DAY), service.claimHeartbeat(DAY)])+ expect([a, b].filter(Boolean)).toHaveLength(1)+ })++ it("records each milestone exactly once", async () => {+ const { seller } = await createSellerUser(container, { email: "[email protected]", name: "First" })+ await waitFor(() => milestoneEvents("first_seller").length === 1)++ await approveSellerWorkflow(container).run({ input: { seller_id: seller.id } })+ await waitFor(() => milestoneEvents("first_seller_approved").length === 1)++ const milestone = milestoneEvents("first_seller")[0]+ expect(milestone.properties.days_since_install).toBe(0)+ expect(milestone.properties).not.toHaveProperty("seller_id")+ expect(milestone.properties).not.toHaveProperty("id")++ const { seller: another } = await createSellerUser(container, { email: "[email protected]", name: "Second" })+ await approveSellerWorkflow(container).run({ input: { seller_id: another.id } })+ await new Promise((resolve) => setTimeout(resolve, 1500))++ expect(milestoneEvents("first_seller")).toHaveLength(1)+ expect(milestoneEvents("first_seller_approved")).toHaveLength(1)+ })+ })+ },+})diff --git a/packages/cli/src/commands/add.ts b/packages/cli/src/commands/add.tsindex 77260345f..8291595ec 100644--- a/packages/cli/src/commands/add.ts+++ b/packages/cli/src/commands/add.ts@@ -12,6 +12,7 @@ import { logger } from "../utils/logger";import { runInit } from "./init";import { handleError } from "../utils/handle-error";import { sendTelemetryEvent, showTelemetryNoticeIfNeeded } from "../telemetry";+import { describeBlock } from "../telemetry/blocks";export const addOptionsSchema = z.object({blocks: z.array(z.string()).optional(),@@ -94,15 +95,15 @@ export const add = new Command()path: options.cwd,});- await sendTelemetryEvent({- type: 'add',- payload: {- outcome: 'success',- blocks: options.blocks,- }- }, {- cwd: options.cwd,- })+ for (const block of options.blocks) {+ await sendTelemetryEvent(+ {+ event: "block_added",+ properties: { ...describeBlock(block), overwrite: options.overwrite },+ },+ { cwd: options.cwd }+ );+ }} catch (error) {logger.break();handleError(error);diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.tsindex 0cff83892..8fb46fbb4 100644--- a/packages/cli/src/commands/init.ts+++ b/packages/cli/src/commands/init.ts@@ -12,7 +12,7 @@ import { handleError } from "../utils/handle-error";import { highlighter } from "../utils/highlighter";import { logger } from "../utils/logger";import { spinner } from "../utils/spinner";-import { sendTelemetryEvent, showTelemetryNoticeIfNeeded } from "../telemetry";+import { showTelemetryNoticeIfNeeded } from "../telemetry";export const initOptionsSchema = z.object({cwd: z.string(),@@ -48,15 +48,6 @@ export const init = new Command())} Project initialization completed.\nYou may now add blocks.`);logger.break();-- await sendTelemetryEvent({- type: 'init',- payload: {- outcome: 'success'- }- }, {- cwd: options.cwd,- })} catch (error) {logger.break();handleError(error);diff --git a/packages/cli/src/commands/registry-build.ts b/packages/cli/src/commands/registry-build.tsindex 3466c9c52..c71d9979d 100644--- a/packages/cli/src/commands/registry-build.ts+++ b/packages/cli/src/commands/registry-build.ts@@ -13,7 +13,8 @@ import { spinner } from "@/src/utils/spinner";import { Command } from "commander";import { z } from "zod";import { REGISTRY_ITEM_SCHEMA_URL } from "../registry";-import { sendTelemetryEvent, showTelemetryNoticeIfNeeded } from "../telemetry";+import { showTelemetryNoticeIfNeeded } from "../telemetry";+import { finishCommand } from "../telemetry/command-tracking";export const buildOptionsSchema = z.object({cwd: z.string(),@@ -65,14 +66,7 @@ async function buildRegistry(opts: z.infer<typeof buildOptionsSchema>) {)} to create one.`);logger.break();- await sendTelemetryEvent({- type: 'build',- payload: {- outcome: 'missing_config',- }- }, {- cwd: options.cwd,- })+ await finishCommand(1);process.exit(1);}@@ -83,14 +77,7 @@ async function buildRegistry(opts: z.infer<typeof buildOptionsSchema>) {)}.`);logger.break();- await sendTelemetryEvent({- type: 'build',- payload: {- outcome: 'missing_registry_file',- }- }, {- cwd: options.cwd,- })+ await finishCommand(1);process.exit(1);}@@ -200,14 +187,6 @@ async function buildRegistry(opts: z.infer<typeof buildOptionsSchema>) {}}- await sendTelemetryEvent({- type: 'build',- payload: {- outcome: 'success',- }- }, {- cwd: options.cwd,- })} catch (error) {logger.break();handleError(error);diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex 2345e1ce0..22b72e5f1 100755--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -13,6 +13,7 @@ import { telemetry } from "./commands/telemetry";import { view } from "./commands/view";import { pluginBuild } from "./commands/plugin-build";import { dashboardBuild } from "./commands/dashboard-build";+import { registerCommandTracking } from "./telemetry/command-tracking";process.on("SIGINT", () => process.exit(0));process.on("SIGTERM", () => process.exit(0));@@ -27,6 +28,8 @@ async function main() {"display the version number");+ registerCommandTracking(program);+program.addCommand(add).addCommand(registryBuild)diff --git a/packages/cli/src/telemetry/blocks.ts b/packages/cli/src/telemetry/blocks.tsnew file mode 100644index 000000000..d17dc5ecc--- /dev/null+++ b/packages/cli/src/telemetry/blocks.ts@@ -0,0 +1,17 @@+const OFFICIAL_REGISTRY = "@mercurjs";++/**+ * Block names from other registries can reveal a company's internal tooling,+ * so only official blocks are named.+ */+export const describeBlock = (block: string) => {+ const match = block.match(/^(@[^/]+)\/(.+)$/);+ const registry = match ? match[1] : OFFICIAL_REGISTRY;+ const name = match ? match[2] : block;+ const official = registry === OFFICIAL_REGISTRY;++ return {+ block: official ? name : "<custom-registry>",+ registry_kind: official ? "official" : "custom",+ };+};diff --git a/packages/cli/src/telemetry/command-tracking.ts b/packages/cli/src/telemetry/command-tracking.tsnew file mode 100644index 000000000..96514f920--- /dev/null+++ b/packages/cli/src/telemetry/command-tracking.ts@@ -0,0 +1,72 @@+import type { Command } from "commander";+import { categorizeError, sendTelemetryEvent } from "./index";++/**+ * Flag values are only kept when they cannot carry user data: booleans, and+ * the enumerated choices listed here. Everything else is redacted.+ */+const SAFE_FLAG_VALUES: Record<string, string[]> = {+ template: ["basic", "plugin", "registry"],+ tag: ["latest", "rc", "canary"],+};++type RunningCommand = {+ name: string;+ flags: Record<string, unknown>;+ cwd: string;+ startedAt: number;+};++let running: RunningCommand | null = null;++const redactFlags = (command: Command): Record<string, unknown> => {+ const flags: Record<string, unknown> = {};+ for (const [key, value] of Object.entries(command.opts())) {+ if (command.getOptionValueSource(key) !== "cli") continue;+ if (typeof value === "boolean") {+ flags[key] = value;+ } else if (typeof value === "string" && SAFE_FLAG_VALUES[key]?.includes(value)) {+ flags[key] = value;+ } else {+ flags[key] = "<redacted>";+ }+ }+ return flags;+};++export const beginCommand = (command: Command) => {+ const opts = command.opts() as { cwd?: string };+ running = {+ name: command.name(),+ flags: redactFlags(command),+ cwd: typeof opts.cwd === "string" ? opts.cwd : process.cwd(),+ startedAt: Date.now(),+ };+};++export const finishCommand = async (exitCode: number, error?: unknown) => {+ if (!running) return;+ const current = running;+ running = null;++ await sendTelemetryEvent(+ {+ event: "cli_command_executed",+ properties: {+ command: current.name,+ flags: current.flags,+ exit_code: exitCode,+ duration_ms: Date.now() - current.startedAt,+ ...(exitCode !== 0 ? { error_category: categorizeError(error) } : {}),+ },+ },+ { cwd: current.cwd }+ );+};++export const registerCommandTracking = (program: Command) => {+ program.hook("preAction", (_this, actionCommand) => beginCommand(actionCommand));+ program.hook("postAction", async () => {+ await finishCommand(0);+ });+};diff --git a/packages/cli/src/telemetry/hash.ts b/packages/cli/src/telemetry/hash.tsindex a3bab2416..3e5b8d0d3 100644--- a/packages/cli/src/telemetry/hash.ts+++ b/packages/cli/src/telemetry/hash.ts@@ -1,5 +1,10 @@import { createHash } from "crypto";-export const hashToBase64 = (input: string): string => {- return createHash("sha256").update(input).digest("base64");-};+const PROJECT_ID_SALT = "mercur-telemetry-v1";++/**+ * Same salt and encoding as `@mercurjs/core`, so a scaffolded project and the+ * server later built from it share one `project_id`.+ */+export const hashProjectKey = (input: string): string =>+ createHash("sha256").update(`${PROJECT_ID_SALT}:${input}`).digest("base64url");diff --git a/packages/cli/src/telemetry/index.ts b/packages/cli/src/telemetry/index.tsindex 00b317113..47d668428 100644--- a/packages/cli/src/telemetry/index.ts+++ b/packages/cli/src/telemetry/index.ts@@ -1,123 +1,180 @@-import { configStore } from "./store";import { execSync } from "child_process";-import { getConfig } from "../utils/get-config";+import { configStore } from "./store";import { detectSystemInfo } from "./detect-system-info";import { getPackageManager } from "../utils/get-package-manager";-import { hashToBase64 } from "./hash";-import { getProjectInfo, type PackageJson } from "../utils/get-project-info";+import { hashProjectKey } from "./hash";+import { getProjectInfo } from "../utils/get-project-info";import { highlighter } from "../utils/highlighter";+import packageJson from "../../package.json";-const TELEMETRY_URL = process.env.MERCUR_TELEMETRY_PROXY_URL || 'https://telemetry.mercurjs.com/api/v1/events'+const DEFAULT_TELEMETRY_HOST = "https://telemetry.mercurjs.com";+const REQUEST_TIMEOUT_MS = 2_000;+const SCHEMA_VERSION = 1;+const PLACEHOLDER_API_KEY = "mercur";-export interface TelemetryEvent {- type: string;- payload?: Record<string, any>;-}+export const TELEMETRY_DOCS_URL = "https://docs.mercurjs.com/telemetry";+const CI_ENV_KEYS = ["CI", "GITHUB_ACTIONS", "GITLAB_CI", "CIRCLECI", "BUILDKITE", "JENKINS_URL", "TF_BUILD", "TEAMCITY_VERSION", "DRONE"];+const AGENT_ENV_KEYS = ["CLAUDECODE", "CLAUDE_CODE", "CURSOR_AGENT", "CODEX_SANDBOX", "GEMINI_CLI", "COPILOT_AGENT", "OPENCODE_CLIENT"];-export const setTelemetryEmail = (email: string) => {- configStore.set("telemetry_email", email)-}+export const ErrorCategory = {+ NETWORK: "network",+ FS: "fs",+ VALIDATION: "validation",+ REGISTRY: "registry",+ INSTALL: "install",+ DATABASE: "database",+ UNKNOWN: "unknown",+} as const;-export const toggleTelemetry = (enabled: boolean) => {- configStore.set("telemetry_enabled", enabled)-}+export type ErrorCategory = (typeof ErrorCategory)[keyof typeof ErrorCategory];-export const TELEMETRY_DOCS_URL = 'https://docs.mercurjs.com/telemetry'+export interface TelemetryEvent {+ event: string;+ properties?: Record<string, unknown>;+}-export const showTelemetryNoticeIfNeeded = () => {- if (configStore.get("notice_shown")) {- return;- }+const isTruthy = (value: string | undefined) =>+ value !== undefined && ["1", "true", "yes"].includes(value.toLowerCase());- configStore.set("notice_shown", true);+export const isCi = () => CI_ENV_KEYS.some((key) => Boolean(process.env[key]));- if (process.env.MERCUR_DISABLE_TELEMETRY === 'true') {- return;- }+export const toggleTelemetry = (enabled: boolean) => {+ configStore.set("telemetry_enabled", enabled);+};- console.error(- [- "",- "Mercur collects anonymous usage data to improve the CLI experience.",- `You can disable this at any time by running: ${highlighter.info("mercurjs telemetry --disable")}`,- `Or by setting ${highlighter.info("MERCUR_DISABLE_TELEMETRY=true")}`,- `Learn more: ${highlighter.info(TELEMETRY_DOCS_URL)}`,- "",- ].join("\n")- );-}+export const isTelemetryEnabled = () => {+ if (isTruthy(process.env.MERCUR_TELEMETRY_FORCE_ENABLED)) return true;+ if (isTruthy(process.env.MERCUR_DISABLE_TELEMETRY)) return false;+ if (isTruthy(process.env.DO_NOT_TRACK)) return false;+ if (isCi()) return false;+ return configStore.get("telemetry_enabled");+};-const isTelemetryEnabled = () => {- return configStore.get("telemetry_enabled") && process.env.MERCUR_DISABLE_TELEMETRY !== 'true'-}+export const showTelemetryNoticeIfNeeded = () => {+ if (configStore.get("notice_shown")) {+ return;+ }++ configStore.set("notice_shown", true);++ if (!isTelemetryEnabled()) {+ return;+ }++ console.error(+ [+ "",+ "Mercur collects anonymous usage data to improve the CLI experience.",+ `You can disable this at any time by running: ${highlighter.info("mercurjs telemetry --disable")}`,+ `Or by setting ${highlighter.info("MERCUR_DISABLE_TELEMETRY=true")}`,+ `Learn more: ${highlighter.info(TELEMETRY_DOCS_URL)}`,+ "",+ ].join("\n")+ );+};++const getGitRemote = (cwd: string) => {+ try {+ return execSync("git config --local --get remote.origin.url", {+ cwd,+ stdio: "pipe",+ timeout: 1000,+ })+ .toString()+ .trim();+ } catch {+ return null;+ }+};++export const getProjectId = (cwd: string): string => hashProjectKey(getGitRemote(cwd) || cwd);++const baseProperties = async (cwd: string) => {+ const [projectInfo, systemInfo, packageManager] = await Promise.all([+ getProjectInfo(cwd).catch(() => null),+ detectSystemInfo(),+ getPackageManager(cwd).catch(() => undefined),+ ]);+ const projectId = getProjectId(cwd);++ return {+ schema_version: SCHEMA_VERSION,+ source: "cli",+ cli_version: packageJson.version,+ mercur_version: projectInfo?.mercurVersion ?? undefined,+ medusa_version: projectInfo?.medusaVersion ?? undefined,+ node_version: process.version,+ runtime: process.versions.bun ? "bun" : "node",+ package_manager: packageManager,+ os: systemInfo.systemPlatform,+ arch: systemInfo.systemArchitecture,+ is_src_dir: projectInfo?.isSrcDir,+ is_ci: isCi(),+ is_tty: Boolean(process.stdout.isTTY),+ is_agent: AGENT_ENV_KEYS.some((key) => Boolean(process.env[key])),+ is_docker: systemInfo.isDocker,+ is_wsl: systemInfo.isWSL,+ cloud_provider: systemInfo.deploymentVendor,+ project_id: projectId,+ $groups: { project: projectId },+ $geoip_disable: true,+ };+};export const sendTelemetryEvent = async (event: TelemetryEvent, options: { cwd: string }) => {- try {- if (!isTelemetryEnabled()) {- return;- }-- const projectInfo = await getProjectInfo(options.cwd)-- const { projectId } = getProjectId(projectInfo.packageJson!)-- const baseEvent = {- nodeEnv: detectEnvironment(),- nodeVersion: process.version,- mercurVersion: projectInfo.mercurVersion,- medusaVersion: projectInfo.medusaVersion,- isSrcDir: projectInfo.isSrcDir,- aliasPrefix: projectInfo.aliasPrefix,- config: await getConfig(options.cwd),- projectId,- systemInfo: await detectSystemInfo(),- packageManager: await getPackageManager(options.cwd),- email: getTelemetryEmail(),- }-- await fetch(TELEMETRY_URL, {- body: JSON.stringify({ ...baseEvent, ...event }),- headers: {- 'Content-Type': 'application/json',- },- method: 'post',- })- } catch {- // Eat any errors in sending telemetry event+ try {+ if (!isTelemetryEnabled()) {+ return;}-}-export function detectEnvironment() {- return process.env.NODE_ENV || 'development'-}+ const body = {+ api_key: PLACEHOLDER_API_KEY,+ batch: [+ {+ event: event.event,+ distinct_id: configStore.deviceId(),+ timestamp: new Date().toISOString(),+ properties: { ...(await baseProperties(options.cwd)), ...event.properties },+ },+ ],+ };++ if (isTruthy(process.env.MERCUR_TELEMETRY_DEBUG)) {+ console.error(`[telemetry] ${JSON.stringify(body.batch, null, 2)}`);+ return;+ }-const getGitID = () => {+ const host = (process.env.MERCUR_TELEMETRY_PROXY_URL || DEFAULT_TELEMETRY_HOST).replace(/\/+$/, "");+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);try {- const originBuffer = execSync('git config --local --get remote.origin.url', {- stdio: 'pipe',- timeout: 1000,- })-- return String(originBuffer).trim()- } catch {- return null+ await fetch(`${host}/batch`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),+ signal: controller.signal,+ });+ } finally {+ clearTimeout(timer);}-}--const getProjectId = (- _packageJson: PackageJson,-): { projectId: string; } => {- const gitID = getGitID()- if (gitID) {- return { projectId: hashToBase64(gitID), }+ } catch {+ // Telemetry must never fail a command.+ }+};++export const categorizeError = (error: unknown): ErrorCategory => {+ if (error && typeof error === "object") {+ const name = (error as { name?: string }).name ?? "";+ const code = (error as { code?: string }).code ?? "";+ const message = (error as { message?: string }).message ?? "";+ if ((Object.values(ErrorCategory) as string[]).includes(name)) return name as ErrorCategory;+ if (name === "ZodError") return ErrorCategory.VALIDATION;+ if (name.startsWith("Registry")) return ErrorCategory.REGISTRY;+ if (["ENOTFOUND", "ECONNREFUSED", "ECONNRESET", "ETIMEDOUT", "EAI_AGAIN"].includes(code) || /fetch failed/i.test(message)) {+ return ErrorCategory.NETWORK;}-- const cwd = process.cwd()- return { projectId: hashToBase64(cwd), }-}---export const getTelemetryEmail = () => {- return configStore.get("telemetry_email") || undefined-}+ if (["ENOENT", "EACCES", "EPERM", "EEXIST", "ENOTDIR", "EISDIR"].includes(code)) return ErrorCategory.FS;+ }+ return ErrorCategory.UNKNOWN;+};diff --git a/packages/cli/src/telemetry/store.ts b/packages/cli/src/telemetry/store.tsindex 6b6fca13b..36c930d21 100644--- a/packages/cli/src/telemetry/store.ts+++ b/packages/cli/src/telemetry/store.ts@@ -1,26 +1,44 @@import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";import { homedir } from "os";import { join } from "path";+import { randomUUID } from "crypto";interface TelemetryConfig {telemetry_enabled: boolean;- telemetry_email: string | null;notice_shown: boolean;+ device_id: string | null;}-const CONFIG_DIR = join(homedir(), ".mercur");-const CONFIG_PATH = join(CONFIG_DIR, "config.json");-const DEFAULTS: TelemetryConfig = {telemetry_enabled: true,- telemetry_email: null,notice_shown: false,+ device_id: null,};+/**+ * XDG config location, the same convention `@medusajs/telemetry` follows for+ * `~/.config/medusa/config.json`.+ */+export const resolveConfigDir = (env: NodeJS.ProcessEnv = process.env, platform = process.platform) => {+ if (platform === "win32") {+ return join(env.APPDATA || join(homedir(), "AppData", "Roaming"), "mercur");+ }+ return join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "mercur");+};++const LEGACY_CONFIG_PATH = join(homedir(), ".mercur", "config.json");+class ConfigStore {+ private readonly path: string;+ private readonly dir: string;++ constructor(dir = resolveConfigDir()) {+ this.dir = dir;+ this.path = join(dir, "config.json");+ }+get<K extends keyof TelemetryConfig>(key: K): TelemetryConfig[K] {- const config = this.read();- return config[key];+ return this.read()[key];}set<K extends keyof TelemetryConfig>(key: K, value: TelemetryConfig[K]): void {@@ -29,27 +47,53 @@ class ConfigStore {this.write(config);}+ deviceId(): string {+ const existing = this.get("device_id");+ if (existing) {+ return existing;+ }+ const id = randomUUID();+ this.set("device_id", id);+ return id;+ }+private read(): TelemetryConfig {try {- if (!existsSync(CONFIG_PATH)) {- return { ...DEFAULTS };+ if (existsSync(this.path)) {+ return { ...DEFAULTS, ...JSON.parse(readFileSync(this.path, "utf-8")) };}- const raw = readFileSync(CONFIG_PATH, "utf-8");- const parsed = JSON.parse(raw);- return { ...DEFAULTS, ...parsed };+ return this.migrateLegacy();} catch {return { ...DEFAULTS };}}+ // Carries an opt-out made under the old ~/.mercur location across the move.+ private migrateLegacy(): TelemetryConfig {+ const config = { ...DEFAULTS };+ try {+ if (existsSync(LEGACY_CONFIG_PATH)) {+ const legacy = JSON.parse(readFileSync(LEGACY_CONFIG_PATH, "utf-8"));+ if (typeof legacy.telemetry_enabled === "boolean") {+ config.telemetry_enabled = legacy.telemetry_enabled;+ }+ if (typeof legacy.notice_shown === "boolean") {+ config.notice_shown = legacy.notice_shown;+ }+ this.write(config);+ }+ } catch {+ // Unreadable legacy file: fall back to defaults.+ }+ return config;+ }+private write(config: TelemetryConfig): void {try {- mkdirSync(CONFIG_DIR, { recursive: true });- writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2) + "\n", {- mode: 0o600,- });+ mkdirSync(this.dir, { recursive: true, mode: 0o700 });+ writeFileSync(this.path, JSON.stringify(config, null, 2) + "\n", { mode: 0o600 });} catch {- // Silently fail — telemetry config is non-critical+ // Telemetry config is non-critical.}}}diff --git a/packages/cli/src/utils/handle-error.ts b/packages/cli/src/utils/handle-error.tsindex 56f9f234a..a275c1a00 100644--- a/packages/cli/src/utils/handle-error.ts+++ b/packages/cli/src/utils/handle-error.ts@@ -2,8 +2,10 @@ import { z } from "zod";import { RegistryError } from "../registry/errors";import { highlighter } from "./highlighter";import { logger } from "./logger";+import { finishCommand } from "../telemetry/command-tracking";-export function handleError(error: unknown) {+export async function handleError(error: unknown) {+ await finishCommand(1, error);logger.break();logger.error(`Something went wrong. Please check the error below for more details.`diff --git a/packages/core/src/api/middlewares.ts b/packages/core/src/api/middlewares.tsindex 209e67c21..4579990f6 100644--- a/packages/core/src/api/middlewares.ts+++ b/packages/core/src/api/middlewares.ts@@ -9,6 +9,11 @@ import { MercurModules } from "@mercurjs/types"import VendorUIModuleService from "../modules/vendor-ui/services/vendor-ui-module-service"import AdminUIModuleService from "../modules/admin-ui/services/admin-ui-module-service"import { DashboardBase } from "../utils/dashboard/dashboard-base"+import { scheduleTelemetryBoot } from "../utils/telemetry/boot"++// Medusa imports this file only in processes that serve HTTP, which is the+// signal that a real server (not a worker, migration or exec script) came up.+scheduleTelemetryBoot()function dashboardMiddleware(service: DashboardBase) {return (req: MedusaRequest, res: MedusaResponse, next: MedusaNextFunction) => {diff --git a/packages/core/src/modules/telemetry/index.ts b/packages/core/src/modules/telemetry/index.tsnew file mode 100644index 000000000..eca05774c--- /dev/null+++ b/packages/core/src/modules/telemetry/index.ts@@ -0,0 +1,8 @@+import { Module } from "@medusajs/framework/utils"+import { MercurModules } from "@mercurjs/types"++import TelemetryModuleService from "./service"++export default Module(MercurModules.TELEMETRY, {+ service: TelemetryModuleService,+})diff --git a/packages/core/src/modules/telemetry/migrations/Migration20261029000000.ts b/packages/core/src/modules/telemetry/migrations/Migration20261029000000.tsnew file mode 100644index 000000000..a8df7a843--- /dev/null+++ b/packages/core/src/modules/telemetry/migrations/Migration20261029000000.ts@@ -0,0 +1,30 @@+import { Migration } from "@medusajs/framework/mikro-orm/migrations"++export class Migration20261029000000 extends Migration {+ override async up(): Promise<void> {+ this.addSql(+ `CREATE TABLE IF NOT EXISTS "telemetry_installation" (+ "id" text NOT NULL,+ "installation_id" text NOT NULL,+ "last_heartbeat_at" timestamptz NULL,+ "last_reported_version" text NULL,+ "milestones" jsonb NOT NULL DEFAULT '{}',+ "created_at" timestamptz NOT NULL DEFAULT now(),+ "updated_at" timestamptz NOT NULL DEFAULT now(),+ "deleted_at" timestamptz NULL,+ CONSTRAINT "telemetry_installation_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "telemetry_installation_singleton" CHECK ("id" = 'singleton')+ );`,+ )+ this.addSql(+ `CREATE UNIQUE INDEX IF NOT EXISTS "IDX_telemetry_installation_installation_id_unique" ON "telemetry_installation" ("installation_id") WHERE deleted_at IS NULL;`,+ )+ this.addSql(+ `CREATE INDEX IF NOT EXISTS "IDX_telemetry_installation_deleted_at" ON "telemetry_installation" ("deleted_at") WHERE deleted_at IS NULL;`,+ )+ }++ override async down(): Promise<void> {+ this.addSql(`DROP TABLE IF EXISTS "telemetry_installation" CASCADE;`)+ }+}diff --git a/packages/core/src/modules/telemetry/models/index.ts b/packages/core/src/modules/telemetry/models/index.tsnew file mode 100644index 000000000..4a0ac2bc1--- /dev/null+++ b/packages/core/src/modules/telemetry/models/index.ts@@ -0,0 +1 @@+export { default as TelemetryInstallation, TELEMETRY_INSTALLATION_ID } from "./installation"diff --git a/packages/core/src/modules/telemetry/models/installation.ts b/packages/core/src/modules/telemetry/models/installation.tsnew file mode 100644index 000000000..3620e6926--- /dev/null+++ b/packages/core/src/modules/telemetry/models/installation.ts@@ -0,0 +1,13 @@+import { model } from "@medusajs/framework/utils"++export const TELEMETRY_INSTALLATION_ID = "singleton"++const TelemetryInstallation = model.define("telemetry_installation", {+ id: model.id().primaryKey(),+ installation_id: model.text().unique(),+ last_heartbeat_at: model.dateTime().nullable(),+ last_reported_version: model.text().nullable(),+ milestones: model.json().nullable(),+})++export default TelemetryInstallationdiff --git a/packages/core/src/modules/telemetry/repositories/index.ts b/packages/core/src/modules/telemetry/repositories/index.tsnew file mode 100644index 000000000..7c686666c--- /dev/null+++ b/packages/core/src/modules/telemetry/repositories/index.ts@@ -0,0 +1 @@+export * from "./telemetry-heartbeat"diff --git a/packages/core/src/modules/telemetry/repositories/telemetry-heartbeat.ts b/packages/core/src/modules/telemetry/repositories/telemetry-heartbeat.tsnew file mode 100644index 000000000..28aada684--- /dev/null+++ b/packages/core/src/modules/telemetry/repositories/telemetry-heartbeat.ts@@ -0,0 +1,33 @@+import { SqlEntityManager } from "@medusajs/framework/mikro-orm/postgresql"+import { Context } from "@medusajs/framework/types"+import { DALUtils } from "@medusajs/framework/utils"++import { TELEMETRY_INSTALLATION_ID } from "../models"++export class TelemetryHeartbeatRepository extends DALUtils.MikroOrmBase {+ constructor() {+ // @ts-ignore+ // eslint-disable-next-line prefer-rest-params+ super(...arguments)+ }++ /**+ * Conditional update so that, with several replicas sharing one database,+ * exactly one of them sends a heartbeat per interval.+ */+ async claimHeartbeat(minGapSeconds: number, sharedContext: Context = {}): Promise<boolean> {+ const knex = this.getActiveManager<SqlEntityManager>(sharedContext).getKnex()++ const updated = await knex("telemetry_installation")+ .where({ id: TELEMETRY_INSTALLATION_ID })+ .andWhere((qb) => {+ qb.whereNull("last_heartbeat_at").orWhereRaw(+ "last_heartbeat_at <= now() - make_interval(secs => ?)",+ [minGapSeconds],+ )+ })+ .update({ last_heartbeat_at: knex.fn.now(), updated_at: knex.fn.now() })++ return updated > 0+ }+}diff --git a/packages/core/src/modules/telemetry/service.ts b/packages/core/src/modules/telemetry/service.tsnew file mode 100644index 000000000..55ad7b620--- /dev/null+++ b/packages/core/src/modules/telemetry/service.ts@@ -0,0 +1,75 @@+import { InferEntityType } from "@medusajs/framework/types"+import { MedusaService } from "@medusajs/framework/utils"+import { randomUUID } from "node:crypto"++import { TelemetryInstallation, TELEMETRY_INSTALLATION_ID } from "./models"+import { TelemetryHeartbeatRepository } from "./repositories"++type Installation = InferEntityType<typeof TelemetryInstallation>++type InjectedDependencies = {+ telemetryHeartbeatRepository: TelemetryHeartbeatRepository+}++class TelemetryModuleService extends MedusaService({ TelemetryInstallation }) {+ protected readonly heartbeatRepository_: TelemetryHeartbeatRepository++ constructor({ telemetryHeartbeatRepository }: InjectedDependencies) {+ // @ts-ignore+ // eslint-disable-next-line prefer-rest-params+ super(...arguments)+ this.heartbeatRepository_ = telemetryHeartbeatRepository+ }++ async getOrCreateInstallation(): Promise<Installation> {+ const [existing] = await this.listTelemetryInstallations(+ { id: TELEMETRY_INSTALLATION_ID },+ { take: 1 },+ )+ if (existing) {+ return existing+ }++ try {+ return await this.createTelemetryInstallations({+ id: TELEMETRY_INSTALLATION_ID,+ installation_id: randomUUID(),+ milestones: {},+ })+ } catch {+ // Another replica won the insert race; read its row.+ const [row] = await this.listTelemetryInstallations(+ { id: TELEMETRY_INSTALLATION_ID },+ { take: 1 },+ )+ return row+ }+ }++ async claimHeartbeat(minGapSeconds: number): Promise<boolean> {+ return this.heartbeatRepository_.claimHeartbeat(minGapSeconds)+ }++ async recordMilestone(name: string): Promise<boolean> {+ const installation = await this.getOrCreateInstallation()+ const milestones = (installation.milestones ?? {}) as Record<string, string>+ if (milestones[name]) {+ return false+ }++ await this.updateTelemetryInstallations({+ id: TELEMETRY_INSTALLATION_ID,+ milestones: { ...milestones, [name]: new Date().toISOString() },+ })+ return true+ }++ async setReportedVersion(version: string): Promise<void> {+ await this.updateTelemetryInstallations({+ id: TELEMETRY_INSTALLATION_ID,+ last_reported_version: version,+ })+ }+}++export default TelemetryModuleServicediff --git a/packages/core/src/subscribers/telemetry-first-member-invited.ts b/packages/core/src/subscribers/telemetry-first-member-invited.tsnew file mode 100644index 000000000..4eec56464--- /dev/null+++ b/packages/core/src/subscribers/telemetry-first-member-invited.ts@@ -0,0 +1,13 @@+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"++import { recordMilestone, TelemetryMilestones } from "../utils/telemetry/milestones"+import { MemberInviteWorkflowEvents } from "../workflows/events"++export default async function telemetryFirstMemberInvitedHandler({ container }: SubscriberArgs<unknown>) {+ await recordMilestone(container, TelemetryMilestones.FIRST_MEMBER_INVITED)+}++export const config: SubscriberConfig = {+ event: MemberInviteWorkflowEvents.CREATED,+ context: { subscriberId: "telemetry-first-member-invited" },+}diff --git a/packages/core/src/subscribers/telemetry-first-offer.ts b/packages/core/src/subscribers/telemetry-first-offer.tsnew file mode 100644index 000000000..fa8e30fbf--- /dev/null+++ b/packages/core/src/subscribers/telemetry-first-offer.ts@@ -0,0 +1,13 @@+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"++import { recordMilestone, TelemetryMilestones } from "../utils/telemetry/milestones"+import { OfferWorkflowEvents } from "../workflows/events"++export default async function telemetryFirstOfferHandler({ container }: SubscriberArgs<unknown>) {+ await recordMilestone(container, TelemetryMilestones.FIRST_OFFER)+}++export const config: SubscriberConfig = {+ event: OfferWorkflowEvents.CREATED,+ context: { subscriberId: "telemetry-first-offer" },+}diff --git a/packages/core/src/subscribers/telemetry-first-order.ts b/packages/core/src/subscribers/telemetry-first-order.tsnew file mode 100644index 000000000..6c554b49a--- /dev/null+++ b/packages/core/src/subscribers/telemetry-first-order.ts@@ -0,0 +1,13 @@+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"++import { recordMilestone, TelemetryMilestones } from "../utils/telemetry/milestones"+import { OrderGroupWorkflowEvents } from "../workflows/events"++export default async function telemetryFirstOrderHandler({ container }: SubscriberArgs<unknown>) {+ await recordMilestone(container, TelemetryMilestones.FIRST_ORDER)+}++export const config: SubscriberConfig = {+ event: OrderGroupWorkflowEvents.CREATED,+ context: { subscriberId: "telemetry-first-order" },+}diff --git a/packages/core/src/subscribers/telemetry-first-payout-account.ts b/packages/core/src/subscribers/telemetry-first-payout-account.tsnew file mode 100644index 000000000..e4c3bdd33--- /dev/null+++ b/packages/core/src/subscribers/telemetry-first-payout-account.ts@@ -0,0 +1,26 @@+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"+import { IPayoutModuleService, MercurModules, PayoutAccountStatus, PayoutModuleEvents } from "@mercurjs/types"++import { recordMilestone, TelemetryMilestones } from "../utils/telemetry/milestones"++export default async function telemetryFirstPayoutAccountHandler({+ event,+ container,+}: SubscriberArgs<{ id: string }>) {+ try {+ const payoutService = container.resolve<IPayoutModuleService>(MercurModules.PAYOUT)+ const account = await payoutService.retrievePayoutAccount(event.data.id)+ if (account.status !== PayoutAccountStatus.ACTIVE) {+ return+ }+ } catch {+ return+ }++ await recordMilestone(container, TelemetryMilestones.FIRST_PAYOUT_ACCOUNT)+}++export const config: SubscriberConfig = {+ event: PayoutModuleEvents.ACCOUNT_UPDATED,+ context: { subscriberId: "telemetry-first-payout-account" },+}diff --git a/packages/core/src/subscribers/telemetry-first-product-published.ts b/packages/core/src/subscribers/telemetry-first-product-published.tsnew file mode 100644index 000000000..bb0f11f53--- /dev/null+++ b/packages/core/src/subscribers/telemetry-first-product-published.ts@@ -0,0 +1,13 @@+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"++import { recordMilestone, TelemetryMilestones } from "../utils/telemetry/milestones"+import { ProductWorkflowEvents } from "../workflows/product/events"++export default async function telemetryFirstProductPublishedHandler({ container }: SubscriberArgs<unknown>) {+ await recordMilestone(container, TelemetryMilestones.FIRST_PRODUCT_PUBLISHED)+}++export const config: SubscriberConfig = {+ event: ProductWorkflowEvents.PUBLISHED,+ context: { subscriberId: "telemetry-first-product-published" },+}diff --git a/packages/core/src/subscribers/telemetry-first-seller-approved.ts b/packages/core/src/subscribers/telemetry-first-seller-approved.tsnew file mode 100644index 000000000..c4537b4b2--- /dev/null+++ b/packages/core/src/subscribers/telemetry-first-seller-approved.ts@@ -0,0 +1,13 @@+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"++import { recordMilestone, TelemetryMilestones } from "../utils/telemetry/milestones"+import { SellerWorkflowEvents } from "../workflows/events"++export default async function telemetryFirstSellerApprovedHandler({ container }: SubscriberArgs<unknown>) {+ await recordMilestone(container, TelemetryMilestones.FIRST_SELLER_APPROVED)+}++export const config: SubscriberConfig = {+ event: SellerWorkflowEvents.APPROVED,+ context: { subscriberId: "telemetry-first-seller-approved" },+}diff --git a/packages/core/src/subscribers/telemetry-first-seller.ts b/packages/core/src/subscribers/telemetry-first-seller.tsnew file mode 100644index 000000000..5b1859220--- /dev/null+++ b/packages/core/src/subscribers/telemetry-first-seller.ts@@ -0,0 +1,13 @@+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"++import { recordMilestone, TelemetryMilestones } from "../utils/telemetry/milestones"+import { SellerWorkflowEvents } from "../workflows/events"++export default async function telemetryFirstSellerHandler({ container }: SubscriberArgs<unknown>) {+ await recordMilestone(container, TelemetryMilestones.FIRST_SELLER)+}++export const config: SubscriberConfig = {+ event: SellerWorkflowEvents.CREATED,+ context: { subscriberId: "telemetry-first-seller" },+}diff --git a/packages/core/src/utils/telemetry/__tests__/buckets.unit.spec.ts b/packages/core/src/utils/telemetry/__tests__/buckets.unit.spec.tsnew file mode 100644index 000000000..cd04e064e--- /dev/null+++ b/packages/core/src/utils/telemetry/__tests__/buckets.unit.spec.ts@@ -0,0 +1,27 @@+import { toBucket } from "../buckets"++describe("toBucket", () => {+ it.each([+ [0, "0"],+ [1, "1-10"],+ [10, "1-10"],+ [11, "11-100"],+ [100, "11-100"],+ [101, "101-1k"],+ [1_000, "101-1k"],+ [1_001, "1k-10k"],+ [10_000, "1k-10k"],+ [10_001, "10k-100k"],+ [100_000, "10k-100k"],+ [100_001, "100k+"],+ ])("maps %i to %s", (count, bucket) => {+ expect(toBucket(count)).toBe(bucket)+ })++ it("drops unknown counts instead of inventing a bucket", () => {+ expect(toBucket(undefined)).toBeUndefined()+ expect(toBucket(null)).toBeUndefined()+ expect(toBucket(-1)).toBeUndefined()+ expect(toBucket(Number.NaN)).toBeUndefined()+ })+})diff --git a/packages/core/src/utils/telemetry/__tests__/config.unit.spec.ts b/packages/core/src/utils/telemetry/__tests__/config.unit.spec.tsnew file mode 100644index 000000000..c79aff4fa--- /dev/null+++ b/packages/core/src/utils/telemetry/__tests__/config.unit.spec.ts@@ -0,0 +1,40 @@+import { telemetryDisabledReason, telemetryHost } from "../config"++const base: NodeJS.ProcessEnv = { NODE_ENV: "production" }++describe("telemetryDisabledReason", () => {+ it("is enabled by default", () => {+ expect(telemetryDisabledReason({ env: base })).toBeNull()+ })++ it.each([+ [{ MERCUR_DISABLE_TELEMETRY: "true" }, "env"],+ [{ MERCUR_DISABLE_TELEMETRY: "1" }, "env"],+ [{ DO_NOT_TRACK: "1" }, "do_not_track"],+ [{ CI: "true" }, "ci"],+ [{ GITHUB_ACTIONS: "true" }, "ci"],+ [{ NODE_ENV: "test" }, "test"],+ [{ MEDUSA_WORKER_MODE: "worker" }, "worker"],+ ])("returns the reason for %o", (env, reason) => {+ expect(telemetryDisabledReason({ env: { ...base, ...env } })).toBe(reason)+ })++ it("honours the config key and the worker mode argument", () => {+ expect(telemetryDisabledReason({ env: base, configEnabled: false })).toBe("config")+ expect(telemetryDisabledReason({ env: base, workerMode: "worker" })).toBe("worker")+ expect(telemetryDisabledReason({ env: base, workerMode: "server" })).toBeNull()+ })++ it("lets an explicit opt-out win over the test override", () => {+ expect(+ telemetryDisabledReason({ env: { NODE_ENV: "test", MERCUR_TELEMETRY_FORCE_ENABLED: "true" } }),+ ).toBeNull()+ })+})++describe("telemetryHost", () => {+ it("defaults to the Mercur proxy and strips trailing slashes", () => {+ expect(telemetryHost({})).toBe("https://telemetry.mercurjs.com")+ expect(telemetryHost({ MERCUR_TELEMETRY_PROXY_URL: "http://localhost:4000/" })).toBe("http://localhost:4000")+ })+})diff --git a/packages/core/src/utils/telemetry/__tests__/first-party.unit.spec.ts b/packages/core/src/utils/telemetry/__tests__/first-party.unit.spec.tsnew file mode 100644index 000000000..b17d75eff--- /dev/null+++ b/packages/core/src/utils/telemetry/__tests__/first-party.unit.spec.ts@@ -0,0 +1,33 @@+import { providerIdLabel, splitFirstParty } from "../first-party"++describe("splitFirstParty", () => {+ it("names Mercur and Medusa packages and only counts everything else", () => {+ expect(+ splitFirstParty([+ "@mercurjs/core",+ "@mercurjs/stripe-connector-plugin",+ "@medusajs/medusa/payment",+ "my-company-plugin",+ "@acme/internal",+ undefined,+ ]),+ ).toEqual({+ first_party: ["@medusajs/medusa/payment", "@mercurjs/core", "@mercurjs/stripe-connector-plugin"],+ custom_count: 2,+ })+ })++ it("deduplicates first-party names", () => {+ expect(splitFirstParty(["@mercurjs/core", "@mercurjs/core"]).first_party).toEqual(["@mercurjs/core"])+ })+})++describe("providerIdLabel", () => {+ it("keeps first-party provider ids and hides custom ones", () => {+ expect(providerIdLabel("@mercurjs/stripe-connector-plugin/providers/payout-stripe-connect", "stripe")).toBe(+ "@mercurjs/stripe-connector-plugin/providers/payout-stripe-connect#stripe",+ )+ expect(providerIdLabel("./src/providers/acme-payouts", "acme")).toBe("custom")+ expect(providerIdLabel(undefined, "x")).toBeUndefined()+ })+})diff --git a/packages/core/src/utils/telemetry/__tests__/sender.unit.spec.ts b/packages/core/src/utils/telemetry/__tests__/sender.unit.spec.tsnew file mode 100644index 000000000..6d377028b--- /dev/null+++ b/packages/core/src/utils/telemetry/__tests__/sender.unit.spec.ts@@ -0,0 +1,47 @@+import { createTelemetrySender } from "../sender"++describe("createTelemetrySender", () => {+ it("posts a PostHog batch to the proxy with a placeholder key", async () => {+ const fetchImpl = jest.fn().mockResolvedValue({ ok: true })+ const sender = createTelemetrySender({+ env: { MERCUR_TELEMETRY_PROXY_URL: "http://proxy.test" },+ fetchImpl: fetchImpl as unknown as typeof fetch,+ })++ await sender.capture([{ event: "instance_started", distinct_id: "inst", properties: { a: 1 } }])++ expect(fetchImpl).toHaveBeenCalledTimes(1)+ const [url, init] = fetchImpl.mock.calls[0]+ expect(url).toBe("http://proxy.test/batch")+ const body = JSON.parse(init.body)+ expect(body.api_key).toBe("mercur")+ expect(body.batch).toHaveLength(1)+ expect(body.batch[0].event).toBe("instance_started")+ expect(body.batch[0].properties).toEqual({ a: 1, $geoip_disable: true })+ expect(body.batch[0].timestamp).toBeDefined()+ })++ it("swallows network failures", async () => {+ const fetchImpl = jest.fn().mockRejectedValue(new Error("boom"))+ const sender = createTelemetrySender({ env: {}, fetchImpl: fetchImpl as unknown as typeof fetch })++ await expect(+ sender.capture([{ event: "x", distinct_id: "y", properties: {} }]),+ ).resolves.toBeUndefined()+ })++ it("logs instead of sending in debug mode", async () => {+ const fetchImpl = jest.fn()+ const info = jest.fn()+ const sender = createTelemetrySender({+ env: { MERCUR_TELEMETRY_DEBUG: "true" },+ fetchImpl: fetchImpl as unknown as typeof fetch,+ logger: { info } as never,+ })++ await sender.capture([{ event: "x", distinct_id: "y", properties: {} }])++ expect(fetchImpl).not.toHaveBeenCalled()+ expect(info).toHaveBeenCalledTimes(1)+ })+})diff --git a/packages/core/src/utils/telemetry/boot.ts b/packages/core/src/utils/telemetry/boot.tsnew file mode 100644index 000000000..ab30eb274--- /dev/null+++ b/packages/core/src/utils/telemetry/boot.ts@@ -0,0 +1,137 @@+import { container as globalContainer } from "@medusajs/framework"+import { Logger, MedusaContainer } from "@medusajs/framework/types"+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"+import { MercurModules } from "@mercurjs/types"++import type TelemetryModuleService from "../../modules/telemetry/service"+import {+ HEARTBEAT_INTERVAL_MS,+ HEARTBEAT_JITTER_MS,+ HEARTBEAT_MIN_GAP_SECONDS,+ startupDelayMs,+ TELEMETRY_DOCS_URL,+ telemetryDisabledReason,+} from "./config"+import { isTelemetryConfigEnabled, TelemetryMilestones } from "./milestones"+import { createTelemetrySender, TelemetryEvent } from "./sender"+import { collectSnapshot, InstallationRecord } from "./snapshot"++let scheduled = false+const startedAt = Date.now()++const uptimeSeconds = () => Math.floor((Date.now() - startedAt) / 1_000)++const groupIdentify = (installation: InstallationRecord, snapshot: Record<string, unknown>): TelemetryEvent => {+ const { $groups: _groups, ...properties } = snapshot+ return {+ event: "$groupidentify",+ distinct_id: installation.installation_id,+ properties: {+ $group_type: "installation",+ $group_key: installation.installation_id,+ $group_set: properties,+ },+ }+}++const bucketMilestones: Array<[string, (typeof TelemetryMilestones)[keyof typeof TelemetryMilestones]]> = [+ ["payouts_paid", TelemetryMilestones.FIRST_PAYOUT_PAID],+ ["commission_rules_total", TelemetryMilestones.FIRST_COMMISSION_RULE],+]++async function report(container: MedusaContainer, event: "instance_started" | "instance_heartbeat") {+ const logger = container.resolve<Logger>(ContainerRegistrationKeys.LOGGER)+ const service = container.resolve<TelemetryModuleService>(MercurModules.TELEMETRY)+ const sender = createTelemetrySender({ logger })++ const installation = await service.getOrCreateInstallation()+ const snapshot = await collectSnapshot(container, installation, uptimeSeconds())+ const events: TelemetryEvent[] = [+ { event, distinct_id: installation.installation_id, properties: snapshot },+ groupIdentify(installation, snapshot),+ ]++ const version = snapshot.mercur_version as string | undefined+ if (version && installation.last_reported_version && installation.last_reported_version !== version) {+ events.push({+ event: "instance_upgraded",+ distinct_id: installation.installation_id,+ properties: { ...snapshot, from_version: installation.last_reported_version, to_version: version },+ })+ }++ const milestones = (installation.milestones ?? {}) as Record<string, string>+ const dueMilestones = [+ ...(snapshot.node_env === "production" ? [TelemetryMilestones.FIRST_PRODUCTION_BOOT] : []),+ ...bucketMilestones.filter(([key]) => snapshot[key] && snapshot[key] !== "0").map(([, m]) => m),+ ].filter((m) => !milestones[m])++ for (const milestone of dueMilestones) {+ if (await service.recordMilestone(milestone)) {+ events.push({+ event: "installation_milestone",+ distinct_id: installation.installation_id,+ properties: { ...snapshot, milestone, days_since_install: snapshot.instance_age_days },+ })+ }+ }++ await sender.capture(events)++ if (version && installation.last_reported_version !== version) {+ await service.setReportedVersion(version)+ }+}++function scheduleHeartbeat(container: MedusaContainer) {+ const delay = HEARTBEAT_INTERVAL_MS + Math.floor(Math.random() * HEARTBEAT_JITTER_MS)+ const timer = setTimeout(async () => {+ try {+ const service = container.resolve<TelemetryModuleService>(MercurModules.TELEMETRY)+ if (await service.claimHeartbeat(HEARTBEAT_MIN_GAP_SECONDS)) {+ await report(container, "instance_heartbeat")+ }+ } catch (error) {+ container.resolve<Logger>(ContainerRegistrationKeys.LOGGER).debug(`[telemetry] heartbeat skipped: ${(error as Error)?.message}`)+ } finally {+ scheduleHeartbeat(container)+ }+ }, delay)+ timer.unref()+}++async function run(container: MedusaContainer) {+ const logger = container.resolve<Logger>(ContainerRegistrationKeys.LOGGER)+ const reason = telemetryDisabledReason({ configEnabled: isTelemetryConfigEnabled(container) })++ if (reason) {+ logger.debug(`[telemetry] disabled (${reason}). ${TELEMETRY_DOCS_URL}`)+ return+ }++ try {+ const service = container.resolve<TelemetryModuleService>(MercurModules.TELEMETRY)+ await service.getOrCreateInstallation()+ await service.claimHeartbeat(0)+ await report(container, "instance_started")+ } catch (error) {+ logger.debug(`[telemetry] boot report skipped: ${(error as Error)?.message}`)+ }++ scheduleHeartbeat(container)+}++/**+ * Called from the plugin's API middleware file, which Medusa only loads in+ * processes that serve HTTP. Worker processes, `medusa exec` and migrations+ * never import it, so a boot event means a real server came up.+ */+export function scheduleTelemetryBoot(container: MedusaContainer = globalContainer as MedusaContainer) {+ if (scheduled) return+ scheduled = true++ const timer = setTimeout(() => {+ run(container).catch(() => undefined)+ }, startupDelayMs())+ timer.unref()+}diff --git a/packages/core/src/utils/telemetry/buckets.ts b/packages/core/src/utils/telemetry/buckets.tsnew file mode 100644index 000000000..982ec23c2--- /dev/null+++ b/packages/core/src/utils/telemetry/buckets.ts@@ -0,0 +1,14 @@+export type CountBucket = "0" | "1-10" | "11-100" | "101-1k" | "1k-10k" | "10k-100k" | "100k+"++export function toBucket(count: number | null | undefined): CountBucket | undefined {+ if (count === null || count === undefined || !Number.isFinite(count) || count < 0) {+ return undefined+ }+ if (count === 0) return "0"+ if (count <= 10) return "1-10"+ if (count <= 100) return "11-100"+ if (count <= 1_000) return "101-1k"+ if (count <= 10_000) return "1k-10k"+ if (count <= 100_000) return "10k-100k"+ return "100k+"+}diff --git a/packages/core/src/utils/telemetry/config.ts b/packages/core/src/utils/telemetry/config.tsnew file mode 100644index 000000000..ce44765cb--- /dev/null+++ b/packages/core/src/utils/telemetry/config.ts@@ -0,0 +1,80 @@+export const TELEMETRY_SCHEMA_VERSION = 1+export const TELEMETRY_DOCS_URL = "https://docs.mercurjs.com/telemetry"+export const DEFAULT_TELEMETRY_HOST = "https://telemetry.mercurjs.com"+export const TELEMETRY_REQUEST_TIMEOUT_MS = 2_000+export const HEARTBEAT_INTERVAL_MS = 24 * 60 * 60 * 1_000+export const HEARTBEAT_JITTER_MS = 60 * 60 * 1_000+export const HEARTBEAT_MIN_GAP_SECONDS = 23 * 60 * 60+export const DEFAULT_STARTUP_DELAY_MS = 5_000++const CI_ENV_KEYS = [+ "CI",+ "GITHUB_ACTIONS",+ "GITLAB_CI",+ "CIRCLECI",+ "BUILDKITE",+ "JENKINS_URL",+ "TF_BUILD",+ "TEAMCITY_VERSION",+ "DRONE",+]++const isTruthy = (value: string | undefined) =>+ value !== undefined && ["1", "true", "yes"].includes(value.toLowerCase())++export const isCi = (env: NodeJS.ProcessEnv = process.env) =>+ CI_ENV_KEYS.some((key) => Boolean(env[key]))++export type TelemetryEnablementInput = {+ env?: NodeJS.ProcessEnv+ configEnabled?: boolean+ workerMode?: string+}++export type TelemetryDisabledReason =+ | "env"+ | "do_not_track"+ | "config"+ | "ci"+ | "test"+ | "worker"++export function telemetryDisabledReason({+ env = process.env,+ configEnabled = true,+ workerMode,+}: TelemetryEnablementInput = {}): TelemetryDisabledReason | null {+ if (isTruthy(env.MERCUR_TELEMETRY_FORCE_ENABLED)) {+ return null+ }+ if (isTruthy(env.MERCUR_DISABLE_TELEMETRY)) {+ return "env"+ }+ if (isTruthy(env.DO_NOT_TRACK)) {+ return "do_not_track"+ }+ if (!configEnabled) {+ return "config"+ }+ if (env.NODE_ENV === "test") {+ return "test"+ }+ if (isCi(env)) {+ return "ci"+ }+ if (workerMode === "worker" || env.MEDUSA_WORKER_MODE === "worker") {+ return "worker"+ }+ return null+}++export const isTelemetryDebug = (env: NodeJS.ProcessEnv = process.env) =>+ isTruthy(env.MERCUR_TELEMETRY_DEBUG)++export const telemetryHost = (env: NodeJS.ProcessEnv = process.env) =>+ (env.MERCUR_TELEMETRY_PROXY_URL || DEFAULT_TELEMETRY_HOST).replace(/\/+$/, "")++export const startupDelayMs = (env: NodeJS.ProcessEnv = process.env) => {+ const parsed = Number(env.MERCUR_TELEMETRY_STARTUP_DELAY_MS)+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : DEFAULT_STARTUP_DELAY_MS+}diff --git a/packages/core/src/utils/telemetry/first-party.ts b/packages/core/src/utils/telemetry/first-party.tsnew file mode 100644index 000000000..b1fe06955--- /dev/null+++ b/packages/core/src/utils/telemetry/first-party.ts@@ -0,0 +1,34 @@+const FIRST_PARTY_PREFIXES = ["@mercurjs/", "@medusajs/"]++export const isFirstPartyName = (name: string) =>+ FIRST_PARTY_PREFIXES.some((prefix) => name.startsWith(prefix))++export type NameSplit = {+ first_party: string[]+ custom_count: number+}++/**+ * Keeps only package names Mercur or Medusa publish. Anything else is counted,+ * never named, because a custom plugin or provider name can identify a company.+ */+export function splitFirstParty(names: Array<string | undefined | null>): NameSplit {+ const first_party = new Set<string>()+ let custom_count = 0++ for (const name of names) {+ if (!name) continue+ if (isFirstPartyName(name)) {+ first_party.add(name)+ } else {+ custom_count += 1+ }+ }++ return { first_party: [...first_party].sort(), custom_count }+}++export const providerIdLabel = (resolve: string | undefined, id: string | undefined) => {+ if (!resolve || !id) return undefined+ return isFirstPartyName(resolve) ? `${resolve}#${id}` : "custom"+}diff --git a/packages/core/src/utils/telemetry/identity.ts b/packages/core/src/utils/telemetry/identity.tsnew file mode 100644index 000000000..def2e2b56--- /dev/null+++ b/packages/core/src/utils/telemetry/identity.ts@@ -0,0 +1,30 @@+import { execSync } from "node:child_process"+import { createHash } from "node:crypto"++const PROJECT_ID_SALT = "mercur-telemetry-v1"++export const hashProjectKey = (input: string) =>+ createHash("sha256").update(`${PROJECT_ID_SALT}:${input}`).digest("base64url")++const gitRemote = (cwd: string) => {+ try {+ return execSync("git config --local --get remote.origin.url", {+ cwd,+ stdio: "pipe",+ timeout: 1_000,+ })+ .toString()+ .trim()+ } catch {+ return null+ }+}++/**+ * Stable, irreversible id for the codebase an instance was built from. Shared+ * with the CLI so a scaffolded project can be matched to its running server.+ */+export function resolveProjectId(cwd = process.cwd()): string {+ const remote = gitRemote(cwd)+ return hashProjectKey(remote || cwd)+}diff --git a/packages/core/src/utils/telemetry/index.ts b/packages/core/src/utils/telemetry/index.tsnew file mode 100644index 000000000..7e8c14bc7--- /dev/null+++ b/packages/core/src/utils/telemetry/index.ts@@ -0,0 +1,8 @@+export * from "./buckets"+export * from "./config"+export * from "./first-party"+export * from "./identity"+export * from "./milestones"+export * from "./sender"+export * from "./snapshot"+export { scheduleTelemetryBoot } from "./boot"diff --git a/packages/core/src/utils/telemetry/milestones.ts b/packages/core/src/utils/telemetry/milestones.tsnew file mode 100644index 000000000..a8c951094--- /dev/null+++ b/packages/core/src/utils/telemetry/milestones.ts@@ -0,0 +1,64 @@+import { ConfigModule, Logger, MedusaContainer } from "@medusajs/framework/types"+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"+import { MercurModules } from "@mercurjs/types"++import type TelemetryModuleService from "../../modules/telemetry/service"+import { telemetryDisabledReason } from "./config"+import { createTelemetrySender } from "./sender"+import { collectBaseProperties } from "./snapshot"++export const TelemetryMilestones = {+ FIRST_PRODUCTION_BOOT: "first_production_boot",+ FIRST_SELLER: "first_seller",+ FIRST_SELLER_APPROVED: "first_seller_approved",+ FIRST_MEMBER_INVITED: "first_member_invited",+ FIRST_OFFER: "first_offer",+ FIRST_PRODUCT_PUBLISHED: "first_product_published",+ FIRST_ORDER: "first_order",+ FIRST_PAYOUT_ACCOUNT: "first_payout_account",+ FIRST_PAYOUT_PAID: "first_payout_paid",+ FIRST_COMMISSION_RULE: "first_commission_rule",+} as const++export type TelemetryMilestone = (typeof TelemetryMilestones)[keyof typeof TelemetryMilestones]++export const isTelemetryConfigEnabled = (container: MedusaContainer) => {+ const configModule = container.resolve<ConfigModule>(ContainerRegistrationKeys.CONFIG_MODULE)+ const mercur = (configModule.projectConfig as { mercur?: { telemetry?: boolean } }).mercur+ return mercur?.telemetry !== false+}++/**+ * Milestones are recorded from subscribers, which in a split deployment run in+ * the worker, so the worker-process rule that gates boot events does not apply.+ */+export async function recordMilestone(container: MedusaContainer, milestone: TelemetryMilestone): Promise<boolean> {+ try {+ const reason = telemetryDisabledReason({ configEnabled: isTelemetryConfigEnabled(container) })+ if (reason && reason !== "worker") {+ return false+ }++ const service = container.resolve<TelemetryModuleService>(MercurModules.TELEMETRY)+ const installation = await service.getOrCreateInstallation()+ const isNew = await service.recordMilestone(milestone)+ if (!isNew) {+ return false+ }++ const logger = container.resolve<Logger>(ContainerRegistrationKeys.LOGGER)+ const sender = createTelemetrySender({ logger })+ const base = collectBaseProperties(container, installation)++ await sender.capture([+ {+ event: "installation_milestone",+ distinct_id: installation.installation_id,+ properties: { ...base, milestone, days_since_install: base.instance_age_days },+ },+ ])+ return true+ } catch {+ return false+ }+}diff --git a/packages/core/src/utils/telemetry/sender.ts b/packages/core/src/utils/telemetry/sender.tsnew file mode 100644index 000000000..1c1e28039--- /dev/null+++ b/packages/core/src/utils/telemetry/sender.ts@@ -0,0 +1,70 @@+import { Logger } from "@medusajs/framework/types"++import { isTelemetryDebug, telemetryHost, TELEMETRY_REQUEST_TIMEOUT_MS } from "./config"++/**+ * The proxy swaps this for the real project key, so no PostHog credential+ * ships inside the package.+ */+const PLACEHOLDER_API_KEY = "mercur"++export type TelemetryEvent = {+ event: string+ distinct_id: string+ properties: Record<string, unknown>+ timestamp?: string+}++export type TelemetrySender = {+ capture: (events: TelemetryEvent[]) => Promise<void>+}++type SenderOptions = {+ logger?: Logger+ env?: NodeJS.ProcessEnv+ fetchImpl?: typeof fetch+}++export function createTelemetrySender({+ logger,+ env = process.env,+ fetchImpl = fetch,+}: SenderOptions = {}): TelemetrySender {+ const url = `${telemetryHost(env)}/batch`+ const debug = isTelemetryDebug(env)++ return {+ async capture(events) {+ if (!events.length) return++ const body = {+ api_key: PLACEHOLDER_API_KEY,+ batch: events.map((event) => ({+ ...event,+ timestamp: event.timestamp ?? new Date().toISOString(),+ properties: { ...event.properties, $geoip_disable: true },+ })),+ }++ if (debug) {+ logger?.info(`[telemetry] ${JSON.stringify(body.batch, null, 2)}`)+ return+ }++ const controller = new AbortController()+ const timer = setTimeout(() => controller.abort(), TELEMETRY_REQUEST_TIMEOUT_MS)+ try {+ await fetchImpl(url, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),+ signal: controller.signal,+ })+ } catch (error) {+ logger?.debug(`[telemetry] send failed: ${(error as Error)?.message}`)+ } finally {+ clearTimeout(timer)+ }+ },+ }+}diff --git a/packages/core/src/utils/telemetry/snapshot.ts b/packages/core/src/utils/telemetry/snapshot.tsnew file mode 100644index 000000000..a00fcba07--- /dev/null+++ b/packages/core/src/utils/telemetry/snapshot.ts@@ -0,0 +1,248 @@+import { ConfigModule, MedusaContainer, RemoteQueryFunction } from "@medusajs/framework/types"+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"+import { PayoutStatus, SellerStatus } from "@mercurjs/types"+import { existsSync } from "node:fs"+import os from "node:os"++import { toBucket } from "./buckets"+import { TELEMETRY_SCHEMA_VERSION } from "./config"+import { providerIdLabel, splitFirstParty } from "./first-party"+import { resolveProjectId } from "./identity"++export type InstallationRecord = {+ installation_id: string+ created_at: Date | string+}++type ModuleDeclaration = {+ resolve?: string+ options?: Record<string, unknown> & {+ providers?: Array<{ resolve?: string; id?: string }>+ }+ disable?: boolean+}++const MERCUR_FEATURE_FLAGS = ["seller_registration", "product_request"]++const CLOUD_PROVIDERS: Array<[string, string[]]> = [+ ["medusa-cloud", ["MEDUSA_CLOUD_ENVIRONMENT_HANDLE", "MEDUSA_CLOUD_API_KEY"]],+ ["render", ["RENDER", "RENDER_SERVICE_ID"]],+ ["fly-io", ["FLY_APP_NAME", "FLY_ALLOC_ID"]],+ ["railway", ["RAILWAY_ENVIRONMENT_NAME", "RAILWAY_STATIC_URL"]],+ ["heroku", ["DYNO", "HEROKU_APP_NAME"]],+ ["digitalocean", ["DO_DEPLOYMENT_ID", "DO_APP_NAME"]],+ ["koyeb", ["KOYEB_DEPLOYMENT_ID", "KOYEB_APP_NAME"]],+ ["vercel", ["VERCEL", "VERCEL_ENV"]],+ ["aws", ["AWS_EXECUTION_ENV", "ECS_CONTAINER_METADATA_URI", "AWS_REGION"]],+ ["gcp", ["K_SERVICE", "GOOGLE_CLOUD_PROJECT", "GCE_METADATA_HOST"]],+ ["azure", ["WEBSITE_SITE_NAME", "AZURE_FUNCTIONS_ENVIRONMENT"]],+]++const packageVersion = (name: string): string | undefined => {+ try {+ return (require(`${name}/package.json`) as { version?: string }).version+ } catch {+ return undefined+ }+}++const detectRuntime = () => (process.versions.bun ? "bun" : "node")++const detectPackageManager = (env: NodeJS.ProcessEnv) => {+ const agent = env.npm_config_user_agent ?? ""+ const match = agent.match(/^(bun|pnpm|yarn|npm)\//)+ return match?.[1]+}++const detectCloudProvider = (env: NodeJS.ProcessEnv) =>+ CLOUD_PROVIDERS.find(([, keys]) => keys.some((key) => Boolean(env[key])))?.[0] ?? null++const detectContainerized = (env: NodeJS.ProcessEnv) =>+ Boolean(env.KUBERNETES_SERVICE_HOST) || existsSync("/.dockerenv") || existsSync("/run/.containerenv")++const daysBetween = (from: Date | string, to = new Date()) =>+ Math.max(0, Math.floor((to.getTime() - new Date(from).getTime()) / 86_400_000))++const asModuleList = (modules: ConfigModule["modules"]): ModuleDeclaration[] => {+ if (!modules) return []+ const values = Array.isArray(modules) ? modules : Object.values(modules)+ return values.filter((m): m is ModuleDeclaration => typeof m === "object" && m !== null)+}++const findModule = (modules: ModuleDeclaration[], suffix: string) =>+ modules.find((m) => m.resolve?.endsWith(suffix))++const providerLabels = (module: ModuleDeclaration | undefined) =>+ (module?.options?.providers ?? [])+ .map((p) => providerIdLabel(p.resolve, p.id))+ .filter((p): p is string => Boolean(p))++export function collectBaseProperties(+ container: MedusaContainer,+ installation: InstallationRecord,+ env: NodeJS.ProcessEnv = process.env,+): Record<string, unknown> {+ const configModule = container.resolve<ConfigModule>(ContainerRegistrationKeys.CONFIG_MODULE)+ const projectId = resolveProjectId()++ return {+ schema_version: TELEMETRY_SCHEMA_VERSION,+ source: "server",+ installation_id: installation.installation_id,+ project_id: projectId,+ instance_age_days: daysBetween(installation.created_at),+ node_env: env.NODE_ENV ?? "development",+ mercur_version: packageVersion("@mercurjs/core"),+ medusa_version: packageVersion("@medusajs/medusa") ?? packageVersion("@medusajs/framework"),+ node_version: process.version,+ runtime: detectRuntime(),+ os: os.platform(),+ arch: os.arch(),+ worker_mode: configModule.projectConfig.workerMode ?? "shared",+ $groups: { installation: installation.installation_id, project: projectId },+ }+}++export function collectStackProperties(+ container: MedusaContainer,+ env: NodeJS.ProcessEnv = process.env,+): Record<string, unknown> {+ const configModule = container.resolve<ConfigModule>(ContainerRegistrationKeys.CONFIG_MODULE)+ const modules = asModuleList(configModule.modules)++ const pluginNames = (configModule.plugins ?? []).map((p) =>+ typeof p === "string" ? p : p.resolve,+ )+ const plugins = splitFirstParty(pluginNames)+ const moduleNames = splitFirstParty(modules.filter((m) => !m.disable).map((m) => m.resolve))++ const payoutProviders = providerLabels(findModule(modules, "/payout"))+ const searchProvider = pluginNames.some((p) => p?.includes("algolia"))+ ? "algolia"+ : pluginNames.some((p) => p?.includes("meilisearch"))+ ? "meilisearch"+ : "none"++ const featureFlags = Object.entries(configModule.featureFlags ?? {})+ .filter(([key, value]) => MERCUR_FEATURE_FLAGS.includes(key) && Boolean(value))+ .map(([key]) => key)++ const cpus = os.cpus()++ return {+ package_manager: detectPackageManager(env),+ cpu_count: cpus.length || undefined,+ total_memory_gb: Math.round(os.totalmem() / 1024 ** 3),+ containerized: detectContainerized(env),+ cloud_provider: detectCloudProvider(env),+ redis_enabled: Boolean(configModule.projectConfig.redisUrl),+ plugins: plugins.first_party,+ custom_plugin_count: plugins.custom_count,+ modules: moduleNames.first_party,+ custom_module_count: moduleNames.custom_count,+ payment_providers: providerLabels(findModule(modules, "/payment")),+ payout_provider: payoutProviders[0] ?? "system",+ notification_providers: providerLabels(findModule(modules, "/notification")),+ file_provider: providerLabels(findModule(modules, "/file"))[0],+ search_provider: searchProvider,+ feature_flags: featureFlags,+ admin_disabled: configModule.admin?.disable ?? true,+ }+}++type CountSpec = {+ key: string+ entity: string+ filters?: Record<string, unknown>+}++const thirtyDaysAgo = () => new Date(Date.now() - 30 * 86_400_000).toISOString()++const COUNT_SPECS: CountSpec[] = [+ { key: "sellers_total", entity: "seller" },+ { key: "sellers_pending", entity: "seller", filters: { status: SellerStatus.PENDING_APPROVAL } },+ { key: "sellers_open", entity: "seller", filters: { status: SellerStatus.OPEN } },+ { key: "sellers_suspended", entity: "seller", filters: { status: SellerStatus.SUSPENDED } },+ { key: "members_total", entity: "member" },+ { key: "products_total", entity: "product" },+ { key: "products_published", entity: "product", filters: { status: "published" } },+ { key: "products_proposed", entity: "product", filters: { status: "proposed" } },+ { key: "offers_total", entity: "offer" },+ { key: "product_changes_pending", entity: "product_change", filters: { status: "pending" } },+ { key: "order_groups_total", entity: "order_group" },+ { key: "order_groups_last_30d", entity: "order_group", filters: { created_at: { $gte: thirtyDaysAgo() } } },+ { key: "orders_total", entity: "order" },+ { key: "payouts_paid", entity: "payout", filters: { status: PayoutStatus.PAID } },+ { key: "payouts_failed", entity: "payout", filters: { status: PayoutStatus.FAILED } },+ { key: "payout_accounts_active", entity: "payout_account", filters: { status: "active" } },+ { key: "commission_rules_total", entity: "commission_rule" },+ { key: "regions_total", entity: "region" },+ { key: "sales_channels_total", entity: "sales_channel" },+]++async function countEntity(query: RemoteQueryFunction, spec: CountSpec): Promise<number | undefined> {+ try {+ const { metadata } = await query.graph({+ entity: spec.entity,+ fields: ["id"],+ filters: spec.filters,+ pagination: { skip: 0, take: 1 },+ } as never)+ return metadata?.count+ } catch {+ return undefined+ }+}++async function postgresMajorVersion(container: MedusaContainer): Promise<string | undefined> {+ try {+ const knex = container.resolve<{ raw: (sql: string) => Promise<{ rows: Array<{ v: string }> }> }>(+ ContainerRegistrationKeys.PG_CONNECTION,+ )+ const { rows } = await knex.raw("SELECT current_setting('server_version') AS v")+ return rows[0]?.v?.split(".")[0]+ } catch {+ return undefined+ }+}++/**+ * Counts run one at a time on purpose: a heartbeat must never compete with+ * request traffic for the connection pool.+ */+export async function collectMarketplaceProperties(container: MedusaContainer): Promise<Record<string, unknown>> {+ const query = container.resolve<RemoteQueryFunction>(ContainerRegistrationKeys.QUERY)+ const result: Record<string, unknown> = {}++ for (const spec of COUNT_SPECS) {+ result[spec.key] = toBucket(await countEntity(query, spec))+ }++ try {+ const { data: stores } = await query.graph({+ entity: "store",+ fields: ["supported_currencies.currency_code"],+ } as never)+ const store = (stores as Array<{ supported_currencies?: unknown[] }>)[0]+ result.currencies_total = toBucket(store?.supported_currencies?.length)+ } catch {+ result.currencies_total = undefined+ }++ result.postgres_version = await postgresMajorVersion(container)++ return result+}++export async function collectSnapshot(+ container: MedusaContainer,+ installation: InstallationRecord,+ uptimeSeconds: number,+): Promise<Record<string, unknown>> {+ return {+ ...collectBaseProperties(container, installation),+ ...collectStackProperties(container),+ ...(await collectMarketplaceProperties(container)),+ uptime_seconds: uptimeSeconds,+ }+}diff --git a/packages/core/src/with-mercur.ts b/packages/core/src/with-mercur.tsindex 35918aab5..51e74d9a1 100644--- a/packages/core/src/with-mercur.ts+++ b/packages/core/src/with-mercur.ts@@ -20,6 +20,12 @@ export type MercurInputConfig = Omit<InputConfigWithArrayModules, "projectConfig* here fails the boot.*/disabledPatches?: string[]+ /**+ * Anonymous usage telemetry (https://docs.mercurjs.com/telemetry).+ * Defaults to `true`; `MERCUR_DISABLE_TELEMETRY=true` or `DO_NOT_TRACK=1`+ * also turn it off.+ */+ telemetry?: boolean}}}diff --git a/packages/create-mercur-app/src/commands/create.ts b/packages/create-mercur-app/src/commands/create.tsindex 9db410d82..b9d5ac448 100644--- a/packages/create-mercur-app/src/commands/create.ts+++ b/packages/create-mercur-app/src/commands/create.ts@@ -16,11 +16,8 @@ import validateProjectName from "validate-npm-package-name";import waitOn from "wait-on";import packageJson from "../../package.json";-import {- sendTelemetryEvent,- setTelemetryEmail,- showTelemetryNoticeIfNeeded,-} from "../telemetry";+import { ErrorCategory, sendTelemetryEvent, showTelemetryNoticeIfNeeded } from "../telemetry";+import { finishCommand } from "../telemetry/command-tracking";import { setupDatabase, type SetupDatabaseResult } from "../utils/create-db";import {resolveProjectPackageManager,@@ -73,7 +70,7 @@ export const create = new Command().option("--no-deps", "skip installing dependencies.").option("--skip-storefront", "skip adding the Next.js storefront.", false).option("--skip-db", "skip database configuration.", false)- .option("--skip-email", "skip email prompt.", false)+ .option("--skip-email", "deprecated: the email prompt was removed, this flag has no effect.", false).option("--tag <tag>","the release channel to pin @mercurjs/* packages to: latest, rc, or canary. defaults to the channel of this CLI."@@ -150,28 +147,6 @@ export const create = new Command()addStorefront = Boolean(wantsStorefront);}- if (!opts.skipEmail) {- const { wantsEmail } = await prompts({- type: "confirm",- name: "wantsEmail",- message: "Mind sharing your email? We reach out for priority support, community events, and invite-only meetups. We never spam.",- initial: false,- });-- if (wantsEmail) {- const { email } = await prompts({- type: "text",- name: "email",- message: "Enter your email:",- format: (value: string) => value.trim(),- });-- if (email) {- setTelemetryEmail(email);- }- }- }-const projectDir = path.resolve(opts.cwd, projectName);await createOrFindProjectDir(projectDir);@@ -232,15 +207,7 @@ export const create = new Command()initialInstallSpinner.succeed(`Dependencies installed successfully in ${installDuration}s.`);} else {initialInstallSpinner.fail(`Failed to install dependencies`);- await sendTelemetryEvent({- type: 'create',- payload: {- outcome: 'dependency_installation_failed',- packageManager,- }- }, {- cwd: projectDir,- })+ await finishCommand(1, { name: ErrorCategory.INSTALL });process.exit(1);}}@@ -273,12 +240,7 @@ export const create = new Command()} else {dbSpinner.fail("Failed to setup database.");logger.log(feedbackOutro());- await sendTelemetryEvent({- type: 'create',- payload: {- outcome: 'database_setup_failed',- }- }, { cwd: projectDir });+ await finishCommand(1, { name: ErrorCategory.DATABASE });process.exit(1);}} else {@@ -292,14 +254,18 @@ export const create = new Command()await initGit(projectDir);- await sendTelemetryEvent({- type: 'create',- payload: {- outcome: 'created'- }- }, {- cwd: projectDir,- });+ await sendTelemetryEvent(+ {+ event: "project_created",+ properties: {+ template,+ package_manager: packageManager,+ with_storefront: addStorefront,+ skip_db: Boolean(opts.skipDb),+ },+ },+ { cwd: projectDir }+ );const totalDuration = ((Date.now() - createStart) / 1000).toFixed(1);spinner(`Mercur project successfully created! (${totalDuration}s)`).succeed();diff --git a/packages/create-mercur-app/src/index.ts b/packages/create-mercur-app/src/index.tsindex ffb24dbc6..68b18858e 100644--- a/packages/create-mercur-app/src/index.ts+++ b/packages/create-mercur-app/src/index.ts@@ -3,6 +3,7 @@ import { Command } from "commander";import packageJson from "../package.json";import { create } from "./commands/create";+import { registerCommandTracking } from "./telemetry/command-tracking";process.on("SIGINT", () => process.exit(0));process.on("SIGTERM", () => process.exit(0));@@ -16,6 +17,7 @@ const program = new Command()"display the version number");+registerCommandTracking(program);program.addCommand(create, { isDefault: true });program.parse();diff --git a/packages/create-mercur-app/src/telemetry/command-tracking.ts b/packages/create-mercur-app/src/telemetry/command-tracking.tsnew file mode 100644index 000000000..96514f920--- /dev/null+++ b/packages/create-mercur-app/src/telemetry/command-tracking.ts@@ -0,0 +1,72 @@+import type { Command } from "commander";+import { categorizeError, sendTelemetryEvent } from "./index";++/**+ * Flag values are only kept when they cannot carry user data: booleans, and+ * the enumerated choices listed here. Everything else is redacted.+ */+const SAFE_FLAG_VALUES: Record<string, string[]> = {+ template: ["basic", "plugin", "registry"],+ tag: ["latest", "rc", "canary"],+};++type RunningCommand = {+ name: string;+ flags: Record<string, unknown>;+ cwd: string;+ startedAt: number;+};++let running: RunningCommand | null = null;++const redactFlags = (command: Command): Record<string, unknown> => {+ const flags: Record<string, unknown> = {};+ for (const [key, value] of Object.entries(command.opts())) {+ if (command.getOptionValueSource(key) !== "cli") continue;+ if (typeof value === "boolean") {+ flags[key] = value;+ } else if (typeof value === "string" && SAFE_FLAG_VALUES[key]?.includes(value)) {+ flags[key] = value;+ } else {+ flags[key] = "<redacted>";+ }+ }+ return flags;+};++export const beginCommand = (command: Command) => {+ const opts = command.opts() as { cwd?: string };+ running = {+ name: command.name(),+ flags: redactFlags(command),+ cwd: typeof opts.cwd === "string" ? opts.cwd : process.cwd(),+ startedAt: Date.now(),+ };+};++export const finishCommand = async (exitCode: number, error?: unknown) => {+ if (!running) return;+ const current = running;+ running = null;++ await sendTelemetryEvent(+ {+ event: "cli_command_executed",+ properties: {+ command: current.name,+ flags: current.flags,+ exit_code: exitCode,+ duration_ms: Date.now() - current.startedAt,+ ...(exitCode !== 0 ? { error_category: categorizeError(error) } : {}),+ },+ },+ { cwd: current.cwd }+ );+};++export const registerCommandTracking = (program: Command) => {+ program.hook("preAction", (_this, actionCommand) => beginCommand(actionCommand));+ program.hook("postAction", async () => {+ await finishCommand(0);+ });+};diff --git a/packages/create-mercur-app/src/telemetry/hash.ts b/packages/create-mercur-app/src/telemetry/hash.tsindex a3bab2416..3e5b8d0d3 100644--- a/packages/create-mercur-app/src/telemetry/hash.ts+++ b/packages/create-mercur-app/src/telemetry/hash.ts@@ -1,5 +1,10 @@import { createHash } from "crypto";-export const hashToBase64 = (input: string): string => {- return createHash("sha256").update(input).digest("base64");-};+const PROJECT_ID_SALT = "mercur-telemetry-v1";++/**+ * Same salt and encoding as `@mercurjs/core`, so a scaffolded project and the+ * server later built from it share one `project_id`.+ */+export const hashProjectKey = (input: string): string =>+ createHash("sha256").update(`${PROJECT_ID_SALT}:${input}`).digest("base64url");diff --git a/packages/create-mercur-app/src/telemetry/index.ts b/packages/create-mercur-app/src/telemetry/index.tsindex caa8ec77c..566a8075c 100644--- a/packages/create-mercur-app/src/telemetry/index.ts+++ b/packages/create-mercur-app/src/telemetry/index.ts@@ -3,26 +3,52 @@ import path from "path";import fs from "fs-extra";+import packageJson from "../../package.json";+import { getPackageManagerFromUserAgent } from "../utils/get-package-manager";import { highlighter } from "../utils/highlighter";-import { getPackageManager } from "../utils/get-package-manager";import { detectSystemInfo } from "./detect-system-info";-import { hashToBase64 } from "./hash";+import { hashProjectKey } from "./hash";import { configStore } from "./store";-const TELEMETRY_URL =- process.env.MERCUR_TELEMETRY_PROXY_URL ||- "https://telemetry.mercurjs.com/api/v1/events";+const DEFAULT_TELEMETRY_HOST = "https://telemetry.mercurjs.com";+const REQUEST_TIMEOUT_MS = 2_000;+const SCHEMA_VERSION = 1;+const PLACEHOLDER_API_KEY = "mercur";++export const TELEMETRY_DOCS_URL = "https://docs.mercurjs.com/telemetry";++const CI_ENV_KEYS = ["CI", "GITHUB_ACTIONS", "GITLAB_CI", "CIRCLECI", "BUILDKITE", "JENKINS_URL", "TF_BUILD", "TEAMCITY_VERSION", "DRONE"];+const AGENT_ENV_KEYS = ["CLAUDECODE", "CLAUDE_CODE", "CURSOR_AGENT", "CODEX_SANDBOX", "GEMINI_CLI", "COPILOT_AGENT", "OPENCODE_CLIENT"];++export const ErrorCategory = {+ NETWORK: "network",+ FS: "fs",+ VALIDATION: "validation",+ REGISTRY: "registry",+ INSTALL: "install",+ DATABASE: "database",+ UNKNOWN: "unknown",+} as const;++export type ErrorCategory = (typeof ErrorCategory)[keyof typeof ErrorCategory];export interface TelemetryEvent {- type: string;- payload?: Record<string, unknown>;+ event: string;+ properties?: Record<string, unknown>;}-export const setTelemetryEmail = (email: string) => {- configStore.set("telemetry_email", email);-};+const isTruthy = (value: string | undefined) =>+ value !== undefined && ["1", "true", "yes"].includes(value.toLowerCase());-export const TELEMETRY_DOCS_URL = "https://docs.mercurjs.com/telemetry";+export const isCi = () => CI_ENV_KEYS.some((key) => Boolean(process.env[key]));++export const isTelemetryEnabled = () => {+ if (isTruthy(process.env.MERCUR_TELEMETRY_FORCE_ENABLED)) return true;+ if (isTruthy(process.env.MERCUR_DISABLE_TELEMETRY)) return false;+ if (isTruthy(process.env.DO_NOT_TRACK)) return false;+ if (isCi()) return false;+ return configStore.get("telemetry_enabled");+};export const showTelemetryNoticeIfNeeded = () => {if (configStore.get("notice_shown")) {@@ -31,7 +57,7 @@ export const showTelemetryNoticeIfNeeded = () => {configStore.set("notice_shown", true);- if (process.env.MERCUR_DISABLE_TELEMETRY === "true") {+ if (!isTelemetryEnabled()) {return;}@@ -47,132 +73,127 @@ export const showTelemetryNoticeIfNeeded = () => {);};-const isTelemetryEnabled = () => {- return (- configStore.get("telemetry_enabled") &&- process.env.MERCUR_DISABLE_TELEMETRY !== "true"- );-};--export const sendTelemetryEvent = async (- event: TelemetryEvent,- options: { cwd: string }-) => {+const getGitRemote = (cwd: string) => {try {- if (!isTelemetryEnabled()) {- return;- }-- const projectInfo = await getProjectInfo(options.cwd);-- const baseEvent = {- nodeEnv: process.env.NODE_ENV || "development",- nodeVersion: process.version,- mercurVersion: projectInfo.mercurVersion,- medusaVersion: projectInfo.medusaVersion,- isSrcDir: projectInfo.isSrcDir,- aliasPrefix: projectInfo.aliasPrefix,- config: projectInfo.config,- projectId: getProjectId(options.cwd),- systemInfo: await detectSystemInfo(),- packageManager: await getPackageManager(options.cwd),- email: getTelemetryEmail(),- };-- await fetch(TELEMETRY_URL, {- body: JSON.stringify({ ...baseEvent, ...event }),- headers: {- "Content-Type": "application/json",- },- method: "post",- });+ return execSync("git config --local --get remote.origin.url", {+ cwd,+ stdio: "pipe",+ timeout: 1000,+ })+ .toString()+ .trim();} catch {- // Eat any errors in sending telemetry event+ return null;}};-const getGitID = () => {+export const getProjectId = (cwd: string): string => hashProjectKey(getGitRemote(cwd) || cwd);++const readJson = async (file: string): Promise<Record<string, unknown> | null> => {try {- const originBuffer = execSync(- "git config --local --get remote.origin.url",- {- stdio: "pipe",- timeout: 1000,- }- );-- return String(originBuffer).trim();+ return await fs.readJSON(file);} catch {return null;}};-const getProjectId = (cwd: string): string => {- const gitID = getGitID();- if (gitID) {- return hashToBase64(gitID);- }+/**+ * The scaffolded project always has the template layout, so plain reads at+ * known paths are enough to pick up the pinned framework versions.+ */+const readVersions = async (cwd: string) => {+ const [rootPkg, apiPkg] = await Promise.all([+ readJson(path.join(cwd, "package.json")),+ readJson(path.join(cwd, "packages/api/package.json")),+ ]);+ const deps = (pkg: Record<string, unknown> | null) =>+ (pkg?.dependencies ?? {}) as Record<string, string | undefined>;+ const find = (name: string) => deps(rootPkg)[name] ?? deps(apiPkg)[name];- return hashToBase64(cwd);+ return {+ mercur_version: find("@mercurjs/core") ?? find("@mercurjs/cli"),+ medusa_version: find("@medusajs/framework"),+ };};-export const getTelemetryEmail = () => {- return configStore.get("telemetry_email") || undefined;-};+const baseProperties = async (cwd: string) => {+ const [versions, systemInfo] = await Promise.all([readVersions(cwd), detectSystemInfo()]);+ const projectId = getProjectId(cwd);-interface ProjectInfo {- isSrcDir: boolean;- aliasPrefix: string | null;- medusaVersion: string | null;- config: unknown;- mercurVersion: string | null;-}--/**- * Lightweight project introspection for freshly scaffolded projects. The full- * CLI resolves this via tsconfig-paths/fast-glob/cosmiconfig; here the project- * always has the template layout, so plain file reads at known paths suffice- * and keep this package's dependency tree minimal.- */-async function getProjectInfo(cwd: string): Promise<ProjectInfo> {- const readJson = async (relPath: string): Promise<Record<string, unknown> | null> => {- try {- return await fs.readJSON(path.join(cwd, relPath));- } catch {- return null;- }+ return {+ schema_version: SCHEMA_VERSION,+ source: "create-mercur-app",+ cli_version: packageJson.version,+ ...versions,+ node_version: process.version,+ runtime: process.versions.bun ? "bun" : "node",+ package_manager: getPackageManagerFromUserAgent(),+ os: systemInfo.systemPlatform,+ arch: systemInfo.systemArchitecture,+ is_ci: isCi(),+ is_tty: Boolean(process.stdout.isTTY),+ is_agent: AGENT_ENV_KEYS.some((key) => Boolean(process.env[key])),+ is_docker: systemInfo.isDocker,+ is_wsl: systemInfo.isWSL,+ cloud_provider: systemInfo.deploymentVendor,+ project_id: projectId,+ $groups: { project: projectId },+ $geoip_disable: true,};+};- const [isSrcDir, rootPkg, apiPkg, config, tsconfig] = await Promise.all([- fs.pathExists(path.join(cwd, "src")),- readJson("package.json"),- readJson("packages/api/package.json"),- readJson("blocks.json"),- readJson("tsconfig.json"),- ]);+export const sendTelemetryEvent = async (event: TelemetryEvent, options: { cwd: string }) => {+ try {+ if (!isTelemetryEnabled()) {+ return;+ }- const dependenciesOf = (pkg: Record<string, unknown> | null) =>- (pkg?.dependencies ?? {}) as Record<string, string | undefined>;+ const body = {+ api_key: PLACEHOLDER_API_KEY,+ batch: [+ {+ event: event.event,+ distinct_id: configStore.deviceId(),+ timestamp: new Date().toISOString(),+ properties: { ...(await baseProperties(options.cwd)), ...event.properties },+ },+ ],+ };- const findDep = (name: string): string | null =>- dependenciesOf(rootPkg)[name] ?? dependenciesOf(apiPkg)[name] ?? null;+ if (isTruthy(process.env.MERCUR_TELEMETRY_DEBUG)) {+ console.error(`[telemetry] ${JSON.stringify(body.batch, null, 2)}`);+ return;+ }- const compilerOptions = (tsconfig?.compilerOptions ?? {}) as {- paths?: Record<string, unknown>;- };- const paths = compilerOptions.paths ?? {};- const firstPath = Object.keys(paths)[0];- const aliasPrefix = firstPath- ? firstPath.includes("*")- ? firstPath.replace("/*", "")- : firstPath.replace("/", "")- : null;+ const host = (process.env.MERCUR_TELEMETRY_PROXY_URL || DEFAULT_TELEMETRY_HOST).replace(/\/+$/, "");+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);+ try {+ await fetch(`${host}/batch`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),+ signal: controller.signal,+ });+ } finally {+ clearTimeout(timer);+ }+ } catch {+ // Telemetry must never fail a command.+ }+};- return {- isSrcDir,- aliasPrefix,- medusaVersion: findDep("@medusajs/framework"),- mercurVersion: findDep("@mercurjs/cli"),- config,- };-}+export const categorizeError = (error: unknown): ErrorCategory => {+ if (error && typeof error === "object") {+ const name = (error as { name?: string }).name ?? "";+ const code = (error as { code?: string }).code ?? "";+ const message = (error as { message?: string }).message ?? "";+ if ((Object.values(ErrorCategory) as string[]).includes(name)) return name as ErrorCategory;+ if (name === "ZodError") return ErrorCategory.VALIDATION;+ if (["ENOTFOUND", "ECONNREFUSED", "ECONNRESET", "ETIMEDOUT", "EAI_AGAIN"].includes(code) || /fetch failed/i.test(message)) {+ return ErrorCategory.NETWORK;+ }+ if (["ENOENT", "EACCES", "EPERM", "EEXIST", "ENOTDIR", "EISDIR"].includes(code)) return ErrorCategory.FS;+ }+ return ErrorCategory.UNKNOWN;+};diff --git a/packages/create-mercur-app/src/telemetry/store.ts b/packages/create-mercur-app/src/telemetry/store.tsindex 6b6fca13b..36c930d21 100644--- a/packages/create-mercur-app/src/telemetry/store.ts+++ b/packages/create-mercur-app/src/telemetry/store.ts@@ -1,26 +1,44 @@import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";import { homedir } from "os";import { join } from "path";+import { randomUUID } from "crypto";interface TelemetryConfig {telemetry_enabled: boolean;- telemetry_email: string | null;notice_shown: boolean;+ device_id: string | null;}-const CONFIG_DIR = join(homedir(), ".mercur");-const CONFIG_PATH = join(CONFIG_DIR, "config.json");-const DEFAULTS: TelemetryConfig = {telemetry_enabled: true,- telemetry_email: null,notice_shown: false,+ device_id: null,};+/**+ * XDG config location, the same convention `@medusajs/telemetry` follows for+ * `~/.config/medusa/config.json`.+ */+export const resolveConfigDir = (env: NodeJS.ProcessEnv = process.env, platform = process.platform) => {+ if (platform === "win32") {+ return join(env.APPDATA || join(homedir(), "AppData", "Roaming"), "mercur");+ }+ return join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "mercur");+};++const LEGACY_CONFIG_PATH = join(homedir(), ".mercur", "config.json");+class ConfigStore {+ private readonly path: string;+ private readonly dir: string;++ constructor(dir = resolveConfigDir()) {+ this.dir = dir;+ this.path = join(dir, "config.json");+ }+get<K extends keyof TelemetryConfig>(key: K): TelemetryConfig[K] {- const config = this.read();- return config[key];+ return this.read()[key];}set<K extends keyof TelemetryConfig>(key: K, value: TelemetryConfig[K]): void {@@ -29,27 +47,53 @@ class ConfigStore {this.write(config);}+ deviceId(): string {+ const existing = this.get("device_id");+ if (existing) {+ return existing;+ }+ const id = randomUUID();+ this.set("device_id", id);+ return id;+ }+private read(): TelemetryConfig {try {- if (!existsSync(CONFIG_PATH)) {- return { ...DEFAULTS };+ if (existsSync(this.path)) {+ return { ...DEFAULTS, ...JSON.parse(readFileSync(this.path, "utf-8")) };}- const raw = readFileSync(CONFIG_PATH, "utf-8");- const parsed = JSON.parse(raw);- return { ...DEFAULTS, ...parsed };+ return this.migrateLegacy();} catch {return { ...DEFAULTS };}}+ // Carries an opt-out made under the old ~/.mercur location across the move.+ private migrateLegacy(): TelemetryConfig {+ const config = { ...DEFAULTS };+ try {+ if (existsSync(LEGACY_CONFIG_PATH)) {+ const legacy = JSON.parse(readFileSync(LEGACY_CONFIG_PATH, "utf-8"));+ if (typeof legacy.telemetry_enabled === "boolean") {+ config.telemetry_enabled = legacy.telemetry_enabled;+ }+ if (typeof legacy.notice_shown === "boolean") {+ config.notice_shown = legacy.notice_shown;+ }+ this.write(config);+ }+ } catch {+ // Unreadable legacy file: fall back to defaults.+ }+ return config;+ }+private write(config: TelemetryConfig): void {try {- mkdirSync(CONFIG_DIR, { recursive: true });- writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2) + "\n", {- mode: 0o600,- });+ mkdirSync(this.dir, { recursive: true, mode: 0o700 });+ writeFileSync(this.path, JSON.stringify(config, null, 2) + "\n", { mode: 0o600 });} catch {- // Silently fail — telemetry config is non-critical+ // Telemetry config is non-critical.}}}diff --git a/packages/create-mercur-app/src/utils/handle-error.ts b/packages/create-mercur-app/src/utils/handle-error.tsindex 0a66e79d1..666ac5d9b 100644--- a/packages/create-mercur-app/src/utils/handle-error.ts+++ b/packages/create-mercur-app/src/utils/handle-error.ts@@ -1,6 +1,8 @@import { logger } from "./logger";+import { finishCommand } from "../telemetry/command-tracking";-export function handleError(error: unknown) {+export async function handleError(error: unknown) {+ await finishCommand(1, error);logger.break();logger.error(`Something went wrong. Please check the error below for more details.`diff --git a/packages/types/src/modules.ts b/packages/types/src/modules.tsindex b710054bc..0c45f6656 100644--- a/packages/types/src/modules.ts+++ b/packages/types/src/modules.ts@@ -12,4 +12,5 @@ export enum MercurModules {CODEGEN = "codegen",PROMOTION_COST = "promotion_cost",REVIEW = "review",+ TELEMETRY = "telemetry",}