@chromatic-com/vitest 0.1.9 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/plugin.js CHANGED
@@ -235,8 +235,8 @@ var require_srcset = __commonJS({
235
235
  });
236
236
 
237
237
  // src/node/plugin.ts
238
- import { existsSync as existsSync4, readdirSync, rmSync } from "node:fs";
239
- import { resolve as resolve4 } from "node:path";
238
+ import { existsSync as existsSync4, readdirSync, rmSync as rmSync2 } from "node:fs";
239
+ import { resolve as resolve8 } from "node:path";
240
240
  import { version as vitestVersion } from "vitest/node";
241
241
  import colors2 from "tinyrainbow";
242
242
 
@@ -561,9 +561,9 @@ var ArchiveFile = class {
561
561
  }
562
562
  renameReservedPathnames(pathname) {
563
563
  if (this.url.origin === this.pageUrl.origin && RESERVED_PATHNAMES.includes(pathname)) {
564
- const hash2 = this.hash(this.url.toString());
564
+ const hash3 = this.hash(this.url.toString());
565
565
  const basename = path2.basename(pathname, path2.extname(pathname));
566
- return `${path2.dirname(pathname)}/${basename}-${hash2}${path2.extname(pathname)}`;
566
+ return `${path2.dirname(pathname)}/${basename}-${hash3}${path2.extname(pathname)}`;
567
567
  }
568
568
  return pathname;
569
569
  }
@@ -903,9 +903,290 @@ var DEFAULT_GLOBAL_RESOURCE_ARCHIVE_TIMEOUT_MS = 1e4;
903
903
 
904
904
  // src/node/commands.ts
905
905
  import assert from "node:assert";
906
- import { resolve as resolve3 } from "node:path";
906
+ import { resolve as resolve7 } from "node:path";
907
907
  import { storyNameFromExport as storyNameFromExport2, toId as toId2 } from "storybook/internal/csf";
908
908
 
909
+ // src/node/telemetry/constants.ts
910
+ var EVENT_TYPE_PREFIX = "vitest_";
911
+ var TELEMETRY_FETCH_TIMEOUT_MS = 5e3;
912
+ var TELEMETRY_URL = "https://analytics.chromatic.com";
913
+ var TELEMETRY_LOG_FILE = "telemetry.jsonl";
914
+ var TELEMETRY_METADATA_FILE = "telemetry-metadata.json";
915
+
916
+ // src/node/telemetry/env.ts
917
+ import { readFileSync } from "node:fs";
918
+ import { resolve } from "node:path";
919
+ import util from "node:util";
920
+ import { env } from "std-env";
921
+ var dotEnv = void 0;
922
+ function getEnv(name) {
923
+ if (dotEnv === void 0) {
924
+ if (typeof util.parseEnv !== "function") {
925
+ dotEnv = {};
926
+ } else {
927
+ try {
928
+ dotEnv = util.parseEnv(readFileSync(resolve(process.cwd(), ".env"), "utf8"));
929
+ } catch {
930
+ dotEnv = {};
931
+ }
932
+ }
933
+ }
934
+ return env[name] ?? dotEnv[name];
935
+ }
936
+ function resolveTelemetryOptions() {
937
+ return {
938
+ // Enabled by default, disabled by env variables
939
+ enabled: isTruthyEnv(getEnv("CHROMATIC_DISABLE_TELEMETRY")) === false && isTruthyEnv(getEnv("DO_NOT_TRACK")) === false,
940
+ // Disabled by default, enabled by env variable
941
+ logToFile: isTruthyEnv(getEnv("CHROMATIC_TELEMETRY_LOG_TO_FILE"))
942
+ };
943
+ }
944
+ function isTruthyEnv(value) {
945
+ return value !== void 0 && value !== "" && value !== "0" && value !== "false";
946
+ }
947
+
948
+ // src/node/telemetry/track.ts
949
+ import { randomUUID as randomUUID2 } from "node:crypto";
950
+ import { appendFile, mkdir } from "node:fs/promises";
951
+ import { resolve as resolve4 } from "node:path";
952
+ import { isCI, nodeVersion } from "std-env";
953
+
954
+ // package.json
955
+ var version = "0.1.10";
956
+
957
+ // src/node/telemetry/metadata.ts
958
+ import { createHash as createHash3 } from "node:crypto";
959
+ import { writeFile as writeFile2, readFile } from "node:fs/promises";
960
+ import { createRequire } from "node:module";
961
+ import { join as join2, resolve as resolve2 } from "node:path";
962
+ import { x } from "tinyexec";
963
+ import { env as env2 } from "std-env";
964
+ var userAgentMatch = env2.npm_config_user_agent?.match(/^([^/\s]+)\/(\S+)/);
965
+ var packageManager = {
966
+ name: userAgentMatch?.[1] || "unknown",
967
+ version: userAgentMatch?.[2] || "unknown"
968
+ };
969
+ async function createProjectId(root) {
970
+ let remote = void 0;
971
+ try {
972
+ const result = await x("git", ["remote", "get-url", "origin"], { nodeOptions: { cwd: root } });
973
+ remote = result.exitCode === 0 ? result.stdout.trim().toLowerCase() : void 0;
974
+ } catch {
975
+ }
976
+ if (!remote) {
977
+ return hash2(root);
978
+ }
979
+ const hasProtocol = remote.includes("://");
980
+ remote = remote.replace(/^[a-z+]+:\/\//, "").replace(/^[^@/]+@/, "");
981
+ if (!hasProtocol) {
982
+ remote = remote.replace(":", "/");
983
+ }
984
+ remote = remote.replace(/\.git$/, "").replace(/\/+$/, "");
985
+ return hash2(remote);
986
+ }
987
+ function hash2(value) {
988
+ return createHash3("sha256").update(`chromatic-vitest-telemetry-v1:${value}`).digest("hex");
989
+ }
990
+ function getChromaticVersion(root) {
991
+ try {
992
+ const require2 = createRequire(join2(root, "package.json"));
993
+ return require2("chromatic/package.json").version || "unknown";
994
+ } catch {
995
+ return "unknown";
996
+ }
997
+ }
998
+ async function writeTelemetryMetadata(outputDirectory, data) {
999
+ await writeFile2(
1000
+ resolve2(outputDirectory, TELEMETRY_METADATA_FILE),
1001
+ JSON.stringify(data, null, 2),
1002
+ "utf8"
1003
+ );
1004
+ }
1005
+
1006
+ // src/node/telemetry/sanitize.ts
1007
+ import { sep } from "node:path";
1008
+ import { homedir } from "node:os";
1009
+ function sanitizeError(error) {
1010
+ if (error instanceof Error && error.stack) {
1011
+ const raw = error.stack.includes(error.message) ? error.stack : `${error.message}
1012
+ Stack: ${error.stack}`;
1013
+ return sanitizeString(raw).slice(0, 2e3);
1014
+ }
1015
+ return sanitizeString(error instanceof Error ? error.message : String(error)).slice(0, 1e3);
1016
+ }
1017
+ function sanitizeString(value) {
1018
+ return value.replaceAll(sep, "/").replace(toPathRegExp(process.cwd()), "<process-cwd>").replace(toPathRegExp(homedir()), "<homedir>");
1019
+ }
1020
+ function toPathRegExp(path3) {
1021
+ const normalized = path3.replaceAll(sep, "/");
1022
+ const escaped = normalized.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1023
+ return new RegExp(escaped, "gi");
1024
+ }
1025
+
1026
+ // src/node/telemetry/session.ts
1027
+ import { randomUUID } from "node:crypto";
1028
+ import { rmSync } from "node:fs";
1029
+ import { resolve as resolve3 } from "node:path";
1030
+ var session = {
1031
+ id: randomUUID(),
1032
+ projectId: void 0,
1033
+ chromaticVersion: void 0,
1034
+ /**
1035
+ * Directories used by `telemetry.logToFile`.
1036
+ * Held in session to avoid race conditions when Vitest projects are used.
1037
+ * Multiple projects could try to clean up the same directory while other one is writing there already.
1038
+ */
1039
+ cleanedLogFileDirectories: /* @__PURE__ */ new Set(),
1040
+ /** Promises to wait before Vitest exists */
1041
+ cleanups: /* @__PURE__ */ new Set(),
1042
+ /** Whether cleanup hooks were already registered for this session */
1043
+ cleanupRegistered: false,
1044
+ /** Whether internal `.vitest/chromatic/telemetry-metadata.json` has been written */
1045
+ isMetadataWritten: false,
1046
+ /** Contents of `.vitest/chromatic/telemetry-metadata.json` */
1047
+ telemetryMetadata: void 0
1048
+ };
1049
+ function cleanTelemetryLogFiles(outputDirectory) {
1050
+ if (session.cleanedLogFileDirectories.has(outputDirectory)) {
1051
+ return;
1052
+ }
1053
+ session.cleanedLogFileDirectories.add(outputDirectory);
1054
+ rmSync(resolve3(outputDirectory, TELEMETRY_LOG_FILE), { force: true });
1055
+ rmSync(resolve3(outputDirectory, TELEMETRY_METADATA_FILE), { force: true });
1056
+ }
1057
+ function setupTelemetryCleanup(vitest) {
1058
+ if (session.cleanupRegistered) {
1059
+ return;
1060
+ }
1061
+ session.cleanupRegistered = true;
1062
+ vitest.onClose(async () => {
1063
+ await Promise.all(Array.from(session.cleanups.values()));
1064
+ session.cleanups.clear();
1065
+ session.isMetadataWritten = false;
1066
+ session.cleanedLogFileDirectories.clear();
1067
+ session.cleanupRegistered = false;
1068
+ });
1069
+ }
1070
+
1071
+ // src/node/telemetry/track.ts
1072
+ function trackEvent(event, vitest, options) {
1073
+ if (!options.telemetry.enabled) {
1074
+ return;
1075
+ }
1076
+ const promise = _trackEvent(event, vitest, options).catch(() => {
1077
+ }).finally(() => session.cleanups.delete(promise));
1078
+ session.cleanups.add(promise);
1079
+ }
1080
+ async function _trackEvent(event, vitest, options) {
1081
+ const url = getEnv("CHROMATIC_TELEMETRY_URL") || TELEMETRY_URL;
1082
+ const root = vitest.config.root;
1083
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
1084
+ const outputDirectory = resolve4(root, options.outputDirectory);
1085
+ session.projectId ||= await createProjectId(root);
1086
+ session.chromaticVersion ||= getChromaticVersion(root);
1087
+ const wireEvent = {
1088
+ id: randomUUID2(),
1089
+ sessionId: session.id,
1090
+ projectId: session.projectId,
1091
+ timestamp,
1092
+ eventType: `${EVENT_TYPE_PREFIX}${event.eventType}`,
1093
+ level: event.level,
1094
+ payload: event.payload,
1095
+ metadata: {
1096
+ isCI,
1097
+ pluginVersion: version,
1098
+ nodeVersion: nodeVersion || "unknown",
1099
+ vitestVersion: vitest.version,
1100
+ isVitestProjects: vitest.projects.length > 1,
1101
+ packageManager: packageManager.name,
1102
+ packageManagerVersion: packageManager.version,
1103
+ chromaticVersion: session.chromaticVersion
1104
+ }
1105
+ };
1106
+ if (wireEvent.level === "error" && "error" in wireEvent.payload) {
1107
+ wireEvent.payload.error = sanitizeError(wireEvent.payload.error);
1108
+ }
1109
+ let error = void 0;
1110
+ try {
1111
+ await fetch(`${url}/telemetry/v1/vitest/events`, {
1112
+ method: "POST",
1113
+ headers: { "Content-Type": "application/json" },
1114
+ body: JSON.stringify(wireEvent),
1115
+ signal: AbortSignal.timeout(TELEMETRY_FETCH_TIMEOUT_MS)
1116
+ });
1117
+ } catch (err) {
1118
+ error = err instanceof Error ? err.message : String(err);
1119
+ }
1120
+ if (options.telemetry.logToFile) {
1121
+ const logFile = resolve4(outputDirectory, TELEMETRY_LOG_FILE);
1122
+ await mkdir(outputDirectory, { recursive: true });
1123
+ await appendFile(logFile, `${JSON.stringify(wireEvent)}
1124
+ `, "utf8");
1125
+ if (error) {
1126
+ await appendFile(logFile, `${JSON.stringify({ telemetryPostError: error })}
1127
+ `, "utf8");
1128
+ }
1129
+ }
1130
+ if (!session.isMetadataWritten) {
1131
+ session.isMetadataWritten = true;
1132
+ await writeTelemetryMetadata(outputDirectory, {
1133
+ ...wireEvent.metadata,
1134
+ sessionId: wireEvent.sessionId,
1135
+ projectId: wireEvent.projectId
1136
+ });
1137
+ }
1138
+ }
1139
+
1140
+ // src/node/telemetry/reporter.ts
1141
+ var REPORTER_NAME = "chromatic-telemetry-reporter";
1142
+ var TelemetryReporter = class _TelemetryReporter {
1143
+ constructor(ctx, options) {
1144
+ this.ctx = ctx;
1145
+ this.options = options;
1146
+ }
1147
+ name = REPORTER_NAME;
1148
+ snapshotCount = 0;
1149
+ /**
1150
+ * Add `TelemetryReporter` to Vitest reporters unless it's already included.
1151
+ */
1152
+ static apply(ctx, options) {
1153
+ if (!options.telemetry.enabled) {
1154
+ return;
1155
+ }
1156
+ for (const reporter of ctx.config.reporters) {
1157
+ if (isTelemetryReporter(reporter)) {
1158
+ return;
1159
+ }
1160
+ }
1161
+ ctx.config.reporters.push(new _TelemetryReporter(ctx, options));
1162
+ }
1163
+ /**
1164
+ * Custom reporter life-cycle called when `takeSnapshot()` is called.
1165
+ */
1166
+ static onSnapshot(ctx, payload) {
1167
+ const reporter = ctx.config.reporters.find(isTelemetryReporter);
1168
+ reporter?._onSnapshot(payload);
1169
+ }
1170
+ _onSnapshot(payload) {
1171
+ this.snapshotCount++;
1172
+ trackEvent({ eventType: "snapshot_captured", level: "info", payload }, this.ctx, this.options);
1173
+ }
1174
+ onTestRunStart() {
1175
+ this.snapshotCount = 0;
1176
+ trackEvent({ eventType: "run_started", level: "info", payload: {} }, this.ctx, this.options);
1177
+ }
1178
+ onTestRunEnd() {
1179
+ trackEvent(
1180
+ { eventType: "run_ended", level: "info", payload: { snapshotCount: this.snapshotCount } },
1181
+ this.ctx,
1182
+ this.options
1183
+ );
1184
+ }
1185
+ };
1186
+ function isTelemetryReporter(reporter) {
1187
+ return "name" in reporter && reporter.name === REPORTER_NAME;
1188
+ }
1189
+
909
1190
  // src/node/NetworkIdleTracker.ts
910
1191
  var NetworkIdleTimeoutError = class extends Error {
911
1192
  name = "NetworkIdleTimeoutError";
@@ -941,12 +1222,12 @@ var NetworkIdleTracker = class _NetworkIdleTracker {
941
1222
  if (this.pending.size === 0 && this.idleTimer === null) {
942
1223
  return Promise.resolve();
943
1224
  }
944
- return new Promise((resolve5, reject) => {
1225
+ return new Promise((resolve9, reject) => {
945
1226
  const timeout = setTimeout(
946
1227
  () => reject(new NetworkIdleTimeoutError("Timed out waiting for network to be idle")),
947
1228
  rejectTimeout
948
1229
  );
949
- this.idleResolvers.push(resolve5, () => clearTimeout(timeout));
1230
+ this.idleResolvers.push(resolve9, () => clearTimeout(timeout));
950
1231
  });
951
1232
  }
952
1233
  onComplete = (params) => {
@@ -975,21 +1256,22 @@ var NetworkIdleTracker = class _NetworkIdleTracker {
975
1256
  };
976
1257
 
977
1258
  // src/node/reporter.ts
978
- import { relative, resolve } from "node:path";
1259
+ import { relative, resolve as resolve5 } from "node:path";
979
1260
  import colors from "tinyrainbow";
980
1261
 
981
1262
  // src/constants.ts
982
1263
  var DEFAULT_OUTPUT_DIR = ".vitest/chromatic";
983
1264
 
984
1265
  // src/node/reporter.ts
985
- var REPORTER_NAME = "chromatic-reporter";
1266
+ var REPORTER_NAME2 = "chromatic-reporter";
986
1267
  var ChromaticReporter = class _ChromaticReporter {
987
- constructor(ctx, options, snapshotCountPerEntity = /* @__PURE__ */ new Map()) {
1268
+ constructor(ctx, options, snapshotCountPerEntity = /* @__PURE__ */ new Map(), isPluginActivated = false) {
988
1269
  this.ctx = ctx;
989
1270
  this.options = options;
990
1271
  this.snapshotCountPerEntity = snapshotCountPerEntity;
1272
+ this.isPluginActivated = isPluginActivated;
991
1273
  }
992
- name = REPORTER_NAME;
1274
+ name = REPORTER_NAME2;
993
1275
  /**
994
1276
  * Add `ChromaticReporter` to Vitest reporters unless it's already included.
995
1277
  */
@@ -998,6 +1280,7 @@ var ChromaticReporter = class _ChromaticReporter {
998
1280
  verbose: pluginOptions.reporter.verbose,
999
1281
  outputDirectory: pluginOptions.outputDirectory,
1000
1282
  turboSnap: pluginOptions.turboSnap,
1283
+ logToFile: pluginOptions.telemetry.enabled && pluginOptions.telemetry.logToFile,
1001
1284
  builtInReporter: "default"
1002
1285
  };
1003
1286
  for (const reporter of ctx.config.reporters) {
@@ -1021,6 +1304,13 @@ var ChromaticReporter = class _ChromaticReporter {
1021
1304
  const reporter = ctx.config.reporters.find(isChromaticReporter);
1022
1305
  reporter?._onSnapshot(test);
1023
1306
  }
1307
+ /**
1308
+ * Custom reporter life-cycle called when plugin is activated for a project.
1309
+ */
1310
+ static onPluginActivated(ctx) {
1311
+ const reporter = ctx.config.reporters.find(isChromaticReporter);
1312
+ reporter?._onPluginActivated();
1313
+ }
1024
1314
  onTestCaseResult(testCase) {
1025
1315
  if (this.options.builtInReporter !== "verbose") {
1026
1316
  return;
@@ -1052,11 +1342,25 @@ var ChromaticReporter = class _ChromaticReporter {
1052
1342
  onTestRunEnd() {
1053
1343
  const snapshotCount = [...this.snapshotCountPerEntity.values()].reduce((a, b) => a + b, 0);
1054
1344
  this.snapshotCountPerEntity.clear();
1345
+ const separator = colors.dim("\u2500".repeat(this.ctx.logger.getColumns()));
1346
+ if (!this.isPluginActivated) {
1347
+ return this.ctx.logger.log(
1348
+ `${separator}`,
1349
+ `
1350
+ ${colors.inverse(" Chromatic Visual Regression ")}`,
1351
+ `
1352
+
1353
+ ${colors.red("No archives captured. Chromatic plugin requires a browser mode project with Chromium project.")}`,
1354
+ `
1355
+
1356
+ ${separator}
1357
+ `
1358
+ );
1359
+ }
1055
1360
  if (snapshotCount === 0) {
1056
1361
  return;
1057
1362
  }
1058
- const output = resolve(this.ctx.config.root, this.options.outputDirectory);
1059
- const separator = colors.dim("\u2500".repeat(this.ctx.logger.getColumns()));
1363
+ const output = resolve5(this.ctx.config.root, this.options.outputDirectory);
1060
1364
  let uploadCommand = "chromatic --vitest --project-token=<TOKEN>";
1061
1365
  if (this.options.turboSnap) {
1062
1366
  uploadCommand += " --only-changed";
@@ -1064,6 +1368,8 @@ var ChromaticReporter = class _ChromaticReporter {
1064
1368
  if (this.options.outputDirectory !== DEFAULT_OUTPUT_DIR || this.ctx.config.root !== process.cwd()) {
1065
1369
  uploadCommand = `CHROMATIC_ARCHIVE_LOCATION=${relative(process.cwd(), output)} ${uploadCommand}`;
1066
1370
  }
1371
+ const telemetryInfo = this.options.logToFile ? `
1372
+ Telemetry events logged to ${colors.dim(resolve5(output, TELEMETRY_LOG_FILE))}` : "";
1067
1373
  this.ctx.logger.log(
1068
1374
  `${separator}`,
1069
1375
  `
@@ -1074,6 +1380,7 @@ ${colors.green("\u2713")} ${snapshotCount} ${pluralize(snapshotCount, "archive")
1074
1380
  `
1075
1381
 
1076
1382
  Archives saved in ${colors.dim(output)}`,
1383
+ telemetryInfo,
1077
1384
  `
1078
1385
  To upload archives into Chromatic run ${colors.green(uploadCommand)}`,
1079
1386
  `
@@ -1097,20 +1404,23 @@ ${separator}
1097
1404
  const previousCount = this.snapshotCountPerEntity.get(key) ?? 0;
1098
1405
  this.snapshotCountPerEntity.set(key, previousCount + 1);
1099
1406
  }
1407
+ _onPluginActivated() {
1408
+ this.isPluginActivated = true;
1409
+ }
1100
1410
  };
1101
1411
  function isChromaticReporter(reporter) {
1102
- return "name" in reporter && reporter.name === REPORTER_NAME;
1412
+ return "name" in reporter && reporter.name === REPORTER_NAME2;
1103
1413
  }
1104
1414
  function pluralize(count, text) {
1105
1415
  return count === 1 ? text : `${text}s`;
1106
1416
  }
1107
1417
 
1108
1418
  // src/node/webpack-stats-reporter.ts
1109
- import { existsSync as existsSync3, readFileSync } from "node:fs";
1110
- import { mkdir, readdir, readFile, rm, writeFile as writeFile2 } from "node:fs/promises";
1111
- import { dirname, relative as relative2, resolve as resolve2, sep } from "node:path";
1419
+ import { existsSync as existsSync3, readFileSync as readFileSync2 } from "node:fs";
1420
+ import { mkdir as mkdir2, readdir, readFile as readFile2, rm, writeFile as writeFile3 } from "node:fs/promises";
1421
+ import { dirname, relative as relative2, resolve as resolve6, sep as sep2 } from "node:path";
1112
1422
  import { isCSSRequest } from "vitest/node";
1113
- var REPORTER_NAME2 = "chromatic-webpack-stats-reporter";
1423
+ var REPORTER_NAME3 = "chromatic-webpack-stats-reporter";
1114
1424
  var VIRTUAL_MODULE_PREFIX = "\0";
1115
1425
  var WebpackStatsReporter = class _WebpackStatsReporter {
1116
1426
  constructor(ctx, options, moduleIdsToStoryFiles = /* @__PURE__ */ new Map()) {
@@ -1118,7 +1428,7 @@ var WebpackStatsReporter = class _WebpackStatsReporter {
1118
1428
  this.options = options;
1119
1429
  this.moduleIdsToStoryFiles = moduleIdsToStoryFiles;
1120
1430
  }
1121
- name = REPORTER_NAME2;
1431
+ name = REPORTER_NAME3;
1122
1432
  /**
1123
1433
  * Add `WebpackStatsReporter` to Vitest reporters unless it's already included.
1124
1434
  */
@@ -1130,8 +1440,8 @@ var WebpackStatsReporter = class _WebpackStatsReporter {
1130
1440
  ctx.config.shard && `-${ctx.config.shard.index}-${ctx.config.shard.count}`,
1131
1441
  ".json"
1132
1442
  ].filter(Boolean).join("");
1133
- const outputFile2 = resolve2(ctx.config.root, pluginOptions.outputDirectory, filename);
1134
- ctx.config.reporters.push(new _WebpackStatsReporter(ctx, { outputFile: outputFile2 }));
1443
+ const outputFile2 = resolve6(ctx.config.root, pluginOptions.outputDirectory, filename);
1444
+ ctx.config.reporters.push(new _WebpackStatsReporter(ctx, { outputFile: outputFile2, pluginOptions }));
1135
1445
  }
1136
1446
  }
1137
1447
  /**
@@ -1157,10 +1467,26 @@ var WebpackStatsReporter = class _WebpackStatsReporter {
1157
1467
  await rm(this.options.outputFile, { force: true });
1158
1468
  this.moduleIdsToStoryFiles.clear();
1159
1469
  }
1470
+ async onTestRunEnd(testModules) {
1471
+ try {
1472
+ await this.writePreviewStats(testModules);
1473
+ } catch (error) {
1474
+ trackEvent(
1475
+ {
1476
+ eventType: "turbosnap_error",
1477
+ level: "error",
1478
+ payload: { operation: "write-stats", error }
1479
+ },
1480
+ this.ctx,
1481
+ this.options.pluginOptions
1482
+ );
1483
+ throw error;
1484
+ }
1485
+ }
1160
1486
  /**
1161
1487
  * Generate `preview-stats.json` from collected Story files and their dependent test modules
1162
1488
  */
1163
- async onTestRunEnd(testModules) {
1489
+ async writePreviewStats(testModules) {
1164
1490
  const statsMap = /* @__PURE__ */ new Map();
1165
1491
  for (const testModule of testModules) {
1166
1492
  const storyFiles = this.moduleIdsToStoryFiles.get(testModule.moduleId);
@@ -1190,9 +1516,9 @@ var WebpackStatsReporter = class _WebpackStatsReporter {
1190
1516
  );
1191
1517
  }
1192
1518
  if (!existsSync3(dirname(this.options.outputFile))) {
1193
- await mkdir(dirname(this.options.outputFile), { recursive: true });
1519
+ await mkdir2(dirname(this.options.outputFile), { recursive: true });
1194
1520
  }
1195
- await writeFile2(
1521
+ await writeFile3(
1196
1522
  this.options.outputFile,
1197
1523
  JSON.stringify({ modules: Array.from(statsMap.values()) }, null, 2),
1198
1524
  "utf-8"
@@ -1254,11 +1580,11 @@ var WebpackStatsReporter = class _WebpackStatsReporter {
1254
1580
  };
1255
1581
  }
1256
1582
  normalize(filePath) {
1257
- return relative2(this.ctx.config.root, filePath).replaceAll(sep, "/").split("?")[0];
1583
+ return relative2(this.ctx.config.root, filePath).replaceAll(sep2, "/").split("?")[0];
1258
1584
  }
1259
1585
  };
1260
1586
  function isWebpackStatsReporter(reporter) {
1261
- return "name" in reporter && reporter.name === REPORTER_NAME2;
1587
+ return "name" in reporter && reporter.name === REPORTER_NAME3;
1262
1588
  }
1263
1589
  function resolveOptimizedDependencySources(mod, cacheDir, visited) {
1264
1590
  if (visited.has(mod.id)) {
@@ -1294,7 +1620,7 @@ function getChunkSources(mod, cacheDir) {
1294
1620
  return sources;
1295
1621
  }
1296
1622
  try {
1297
- const diskMap = JSON.parse(readFileSync(`${mod.id.split("?")[0]}.map`, "utf-8"));
1623
+ const diskMap = JSON.parse(readFileSync2(`${mod.id.split("?")[0]}.map`, "utf-8"));
1298
1624
  return resolveMapSources(mod, diskMap, cacheDir);
1299
1625
  } catch {
1300
1626
  return [];
@@ -1308,7 +1634,7 @@ function resolveMapSources(mod, map, cacheDir) {
1308
1634
  if (typeof source !== "string" || source.startsWith(VIRTUAL_MODULE_PREFIX)) {
1309
1635
  return [];
1310
1636
  }
1311
- const resolved = resolve2(dirname(mod.id), source).replaceAll(sep, "/");
1637
+ const resolved = resolve6(dirname(mod.id), source).replaceAll(sep2, "/");
1312
1638
  if (resolved.startsWith(cacheDir)) {
1313
1639
  return [];
1314
1640
  }
@@ -1316,12 +1642,12 @@ function resolveMapSources(mod, map, cacheDir) {
1316
1642
  });
1317
1643
  }
1318
1644
  async function mergePreviewStats(options) {
1319
- const outputDirectory = resolve2(options.root, options.outputDirectory);
1645
+ const outputDirectory = resolve6(options.root, options.outputDirectory);
1320
1646
  const merged = /* @__PURE__ */ new Map();
1321
1647
  for (const filename of await readdir(outputDirectory)) {
1322
1648
  if (filename.startsWith("preview-stats") && filename.endsWith(".json")) {
1323
- const fullFilename = resolve2(outputDirectory, filename);
1324
- const stats = JSON.parse(await readFile(fullFilename, "utf-8"));
1649
+ const fullFilename = resolve6(outputDirectory, filename);
1650
+ const stats = JSON.parse(await readFile2(fullFilename, "utf-8"));
1325
1651
  for (const mod of stats.modules) {
1326
1652
  const previous = merged.get(mod.id);
1327
1653
  if (previous) {
@@ -1337,8 +1663,8 @@ async function mergePreviewStats(options) {
1337
1663
  await rm(fullFilename);
1338
1664
  }
1339
1665
  }
1340
- await writeFile2(
1341
- resolve2(outputDirectory, "preview-stats.json"),
1666
+ await writeFile3(
1667
+ resolve6(outputDirectory, "preview-stats.json"),
1342
1668
  JSON.stringify({ modules: Array.from(merged.values()) }, null, 2),
1343
1669
  "utf-8"
1344
1670
  );
@@ -1349,13 +1675,14 @@ function createCommands(options) {
1349
1675
  const resourceArchivers = /* @__PURE__ */ new Map();
1350
1676
  const networkIdleTrackers = /* @__PURE__ */ new Map();
1351
1677
  const savedResults = /* @__PURE__ */ new Set();
1678
+ const trackedCommandFailures = /* @__PURE__ */ new Set();
1352
1679
  const snapshots = /* @__PURE__ */ new Map();
1353
- return {
1680
+ const commands = {
1354
1681
  /**
1355
1682
  * Store a `@rrweb` generated DOM snapshot for the test.
1356
1683
  * Can be called multiple times during a single test case.
1357
1684
  */
1358
- async __chromatic_uploadDOMSnapshot(context, id, snapshot, pseudoClassIds, name) {
1685
+ async __chromatic_uploadDOMSnapshot(context, id, snapshot, pseudoClassIds, name, snapshotOptions) {
1359
1686
  const entity = context.project.vitest.state.getReportedEntityById(id);
1360
1687
  assert(
1361
1688
  entity?.type === "test",
@@ -1366,6 +1693,7 @@ function createCommands(options) {
1366
1693
  sessionSnapshots = /* @__PURE__ */ new Map();
1367
1694
  snapshots.set(id, sessionSnapshots);
1368
1695
  }
1696
+ const isCustomName = name != void 0;
1369
1697
  name ||= `Snapshot #${sessionSnapshots.size + 1}`;
1370
1698
  const frame = await context.frame();
1371
1699
  const { viewport, colorScheme } = await frame.evaluate(
@@ -1376,6 +1704,11 @@ function createCommands(options) {
1376
1704
  );
1377
1705
  sessionSnapshots.set(name, { snapshot, viewport, colorScheme, pseudoClassIds });
1378
1706
  ChromaticReporter.onSnapshot(context.project.vitest, entity);
1707
+ TelemetryReporter.onSnapshot(context.project.vitest, {
1708
+ isCustomName,
1709
+ colorScheme,
1710
+ isAutomaticSnapshot: snapshotOptions?.isAutomaticSnapshot ?? false
1711
+ });
1379
1712
  },
1380
1713
  /**
1381
1714
  * Wait for network to be idle, meaning no new network requests for at least `idleNetworkInterval` ms.
@@ -1451,7 +1784,7 @@ function createCommands(options) {
1451
1784
  }
1452
1785
  const { storiesFile } = await writeTestResult(
1453
1786
  {
1454
- outputDir: resolve3(context.project.vitest.config.root, options.outputDirectory),
1787
+ outputDir: resolve7(context.project.vitest.config.root, options.outputDirectory),
1455
1788
  pageUrl: context.page.url(),
1456
1789
  titlePath
1457
1790
  },
@@ -1472,6 +1805,15 @@ function createCommands(options) {
1472
1805
  if (options.turboSnap) {
1473
1806
  WebpackStatsReporter.onStoryFileWrite(context.project.vitest, entity, storiesFile);
1474
1807
  }
1808
+ trackEvent(
1809
+ {
1810
+ eventType: "archives_created",
1811
+ level: "info",
1812
+ payload: { archiveCount: Object.keys(snapshotBuffers).length }
1813
+ },
1814
+ context.project.vitest,
1815
+ options
1816
+ );
1475
1817
  },
1476
1818
  /**
1477
1819
  * Clear test state without writing test results.
@@ -1479,6 +1821,12 @@ function createCommands(options) {
1479
1821
  async __chromatic_stopWithoutSnapshots(context, id) {
1480
1822
  await onTestCleanup(context, id);
1481
1823
  },
1824
+ /**
1825
+ * Forward a browser-side telemetry event to the Node side.
1826
+ */
1827
+ async __chromatic_telemetry(context, event) {
1828
+ void trackEvent(event, context.project.vitest, options);
1829
+ },
1482
1830
  /**
1483
1831
  * Reset all state of the plugin. Should be called between test runs.
1484
1832
  */
@@ -1490,6 +1838,7 @@ function createCommands(options) {
1490
1838
  networkIdleTrackers.clear();
1491
1839
  snapshots.clear();
1492
1840
  savedResults.clear();
1841
+ trackedCommandFailures.clear();
1493
1842
  },
1494
1843
  /**
1495
1844
  * Get currently save snapshots. Used only during testing.
@@ -1499,6 +1848,42 @@ function createCommands(options) {
1499
1848
  return Object.fromEntries(snapshots.get(id) || []);
1500
1849
  }
1501
1850
  };
1851
+ return withErrorTracking2(commands);
1852
+ function withErrorTracking2(_commands) {
1853
+ return Object.fromEntries(
1854
+ Object.entries(_commands).map(
1855
+ ([name, command]) => [
1856
+ name,
1857
+ async (context, ...args) => {
1858
+ try {
1859
+ return await command(context, ...args);
1860
+ } catch (error) {
1861
+ trackCommandFailure(name, error, context);
1862
+ throw error;
1863
+ }
1864
+ }
1865
+ ]
1866
+ )
1867
+ );
1868
+ }
1869
+ function trackCommandFailure(command, error, context) {
1870
+ if (command === "__chromatic_telemetry" || command === "__chromatic_getSnapshots") {
1871
+ return;
1872
+ }
1873
+ const key = `${command}:${error instanceof Error ? error.message : String(error)}`;
1874
+ if (trackedCommandFailures.has(key)) {
1875
+ return;
1876
+ }
1877
+ trackedCommandFailures.add(key);
1878
+ try {
1879
+ trackEvent(
1880
+ { eventType: "command_failed", level: "error", payload: { command, error } },
1881
+ context.project.vitest,
1882
+ options
1883
+ );
1884
+ } catch {
1885
+ }
1886
+ }
1502
1887
  async function onTestCleanup(context, id) {
1503
1888
  const resourceArchiver = resourceArchivers.get(context.sessionId);
1504
1889
  assert(resourceArchiver, `No resource archiver found for test ${id}`);
@@ -1578,26 +1963,23 @@ function chromaticPlugin(userOptions = {}) {
1578
1963
  idleNetworkInterval: 100,
1579
1964
  turboSnap: false,
1580
1965
  ...userOptions,
1581
- reporter: resolveReporterOptions(userOptions.reporter)
1966
+ reporter: resolveReporterOptions(userOptions.reporter),
1967
+ telemetry: resolveTelemetryOptions()
1582
1968
  };
1583
1969
  const isDist = import.meta.url.includes("dist/plugin.js");
1584
- const setupFile = resolve4(
1970
+ const setupFile = resolve8(
1585
1971
  import.meta.dirname,
1586
1972
  isDist ? "./setupFile.js" : "../browser/setupFile.ts"
1587
1973
  );
1588
1974
  return {
1589
1975
  name: "vitest:chromatic",
1590
- enforce: "pre",
1591
- resolveId(id) {
1592
- if (id === "vitest/suite" && !vitestVersion.startsWith("4.0")) {
1593
- return "vitest";
1594
- }
1595
- },
1596
1976
  config() {
1597
1977
  return {
1598
1978
  optimizeDeps: {
1599
1979
  entries: [setupFile]
1600
1980
  },
1981
+ // vitest/suite is available in 4.0 only. Importing it in 4.1 logs error, in 5.0 it's removed.
1982
+ resolve: vitestVersion.startsWith("4.0") ? void 0 : { alias: { "vitest/suite": "vitest" } },
1601
1983
  test: {
1602
1984
  provide: {
1603
1985
  __chromatic_options: options
@@ -1608,25 +1990,66 @@ function chromaticPlugin(userOptions = {}) {
1608
1990
  }
1609
1991
  };
1610
1992
  },
1611
- async configureVitest(context) {
1993
+ configureVitest: withErrorTracking(options, async (context) => {
1612
1994
  const project = context.project;
1613
1995
  const browser = project.config.browser;
1614
1996
  const sequence = context.vitest.config.sequence;
1615
1997
  const isMergeReports = project.globalConfig.mergeReports;
1616
- if (!browser.enabled || browser.name !== "chromium") {
1617
- return clean();
1998
+ if (options.telemetry.enabled) {
1999
+ setupTelemetryCleanup(context.vitest);
2000
+ trackEvent2({
2001
+ eventType: "plugin_configured",
2002
+ level: "info",
2003
+ payload: {
2004
+ isShardedRun: project.config.shard != null,
2005
+ cropToViewport: options.cropToViewport,
2006
+ delay: options.delay,
2007
+ diffIncludeAntiAliasing: options.diffIncludeAntiAliasing,
2008
+ diffThreshold: options.diffThreshold,
2009
+ disableAutoSnapshot: options.disableAutoSnapshot,
2010
+ forcedColors: options.forcedColors,
2011
+ idleNetworkInterval: options.idleNetworkInterval,
2012
+ pauseAnimationAtEnd: options.pauseAnimationAtEnd,
2013
+ prefersReducedMotion: options.prefersReducedMotion,
2014
+ resourceArchiveTimeout: options.resourceArchiveTimeout,
2015
+ turboSnap: options.turboSnap,
2016
+ reporter: !options.reporter.enabled ? "off" : options.reporter.verbose ? "verbose" : "non-verbose",
2017
+ // Don't attach any user-defined strings values:
2018
+ isCustomOutputDirectory: options.outputDirectory !== DEFAULT_OUTPUT_DIR,
2019
+ assetDomainsCount: options.assetDomains?.length ?? 0,
2020
+ ignoreSelectorsCount: options.ignoreSelectors?.length ?? 0,
2021
+ tagsCount: options.tags?.length ?? 0
2022
+ }
2023
+ });
1618
2024
  }
1619
2025
  if (options.reporter.enabled) {
1620
2026
  ChromaticReporter.apply(context.vitest, options);
1621
2027
  }
2028
+ if (!browser.enabled || browser.name !== "chromium") {
2029
+ trackEvent2({
2030
+ eventType: "project_ineligible",
2031
+ level: "warn",
2032
+ payload: { isBrowser: browser.enabled, isChromium: browser.name === "chromium" }
2033
+ });
2034
+ return clean();
2035
+ }
2036
+ ChromaticReporter.onPluginActivated(context.vitest);
1622
2037
  if (options.turboSnap && !isMergeReports) {
1623
2038
  WebpackStatsReporter.apply(context.vitest, options);
1624
2039
  }
2040
+ if (options.telemetry.enabled) {
2041
+ TelemetryReporter.apply(context.vitest, options);
2042
+ }
1625
2043
  if (sequence.hooks === "stack") {
1626
2044
  project.config.setupFiles.push(setupFile);
1627
2045
  } else if (sequence.hooks === "list") {
1628
2046
  project.config.setupFiles.unshift(setupFile);
1629
2047
  } else {
2048
+ trackEvent2({
2049
+ eventType: "setup_files_parallel",
2050
+ level: "warn",
2051
+ payload: { setupFileCount: project.config.setupFiles.length }
2052
+ });
1630
2053
  project.config.setupFiles.push(setupFile);
1631
2054
  context.vitest.logger.warn(
1632
2055
  colors2.bgYellow(colors2.black(" chromatic ")),
@@ -1642,6 +2065,7 @@ function chromaticPlugin(userOptions = {}) {
1642
2065
  `Tags cannot be used with Vitest ${context.vitest.version}. Please upgrade to Vitest 4.1 or later to use this feature.`
1643
2066
  )
1644
2067
  );
2068
+ trackEvent2({ eventType: "tags_low_version", level: "warn", payload: {} });
1645
2069
  }
1646
2070
  if (options.tags) {
1647
2071
  project.config.tags ||= [];
@@ -1654,10 +2078,19 @@ function chromaticPlugin(userOptions = {}) {
1654
2078
  }
1655
2079
  if (isMergeReports) {
1656
2080
  if (options.turboSnap) {
1657
- await mergePreviewStats({
1658
- root: project.vitest.config.root,
1659
- outputDirectory: options.outputDirectory
1660
- });
2081
+ try {
2082
+ await mergePreviewStats({
2083
+ root: project.vitest.config.root,
2084
+ outputDirectory: options.outputDirectory
2085
+ });
2086
+ } catch (error) {
2087
+ trackEvent2({
2088
+ eventType: "turbosnap_error",
2089
+ level: "error",
2090
+ payload: { operation: "merge-stats", error }
2091
+ });
2092
+ throw error;
2093
+ }
1661
2094
  }
1662
2095
  } else {
1663
2096
  clean();
@@ -1667,16 +2100,34 @@ function chromaticPlugin(userOptions = {}) {
1667
2100
  await project.browser?.triggerCommand("__chromatic_reset", {});
1668
2101
  });
1669
2102
  function clean() {
1670
- const outputDirectory = resolve4(project.vitest.config.root, options.outputDirectory);
1671
- rmSync(resolve4(outputDirectory, "chromatic-archives"), { recursive: true, force: true });
2103
+ const outputDirectory = resolve8(project.vitest.config.root, options.outputDirectory);
2104
+ rmSync2(resolve8(outputDirectory, "chromatic-archives"), { recursive: true, force: true });
2105
+ cleanTelemetryLogFiles(outputDirectory);
1672
2106
  if (existsSync4(outputDirectory)) {
1673
2107
  for (const file of readdirSync(outputDirectory)) {
1674
2108
  if (file.startsWith("preview-stats") && file.endsWith(".json")) {
1675
- rmSync(resolve4(outputDirectory, file), { force: true });
2109
+ rmSync2(resolve8(outputDirectory, file), { force: true });
1676
2110
  }
1677
2111
  }
1678
2112
  }
1679
2113
  }
2114
+ function trackEvent2(event) {
2115
+ trackEvent(event, context.vitest, options);
2116
+ }
2117
+ })
2118
+ };
2119
+ }
2120
+ function withErrorTracking(options, configureVitest) {
2121
+ return async (context) => {
2122
+ try {
2123
+ return await configureVitest(context);
2124
+ } catch (error) {
2125
+ trackEvent(
2126
+ { eventType: "plugin_error", level: "error", payload: { operation: "configure", error } },
2127
+ context.vitest,
2128
+ options
2129
+ );
2130
+ throw error;
1680
2131
  }
1681
2132
  };
1682
2133
  }