@chromatic-com/vitest 0.1.8 → 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,9 @@ 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
+ import { version as vitestVersion } from "vitest/node";
240
241
  import colors2 from "tinyrainbow";
241
242
 
242
243
  // ../shared/src/utils/logger.ts
@@ -560,9 +561,9 @@ var ArchiveFile = class {
560
561
  }
561
562
  renameReservedPathnames(pathname) {
562
563
  if (this.url.origin === this.pageUrl.origin && RESERVED_PATHNAMES.includes(pathname)) {
563
- const hash2 = this.hash(this.url.toString());
564
+ const hash3 = this.hash(this.url.toString());
564
565
  const basename = path2.basename(pathname, path2.extname(pathname));
565
- return `${path2.dirname(pathname)}/${basename}-${hash2}${path2.extname(pathname)}`;
566
+ return `${path2.dirname(pathname)}/${basename}-${hash3}${path2.extname(pathname)}`;
566
567
  }
567
568
  return pathname;
568
569
  }
@@ -897,20 +898,295 @@ async function writeTestResult(e2eTestInfo, domSnapshots, archive, chromaticStor
897
898
  return { storiesFile };
898
899
  }
899
900
 
900
- // ../shared/src/utils/analytics.ts
901
- import { Analytics } from "@segment/analytics-node";
902
- var analytics = new Analytics({
903
- writeKey: process.env.SEGMENT_WRITE_KEY || "cwWhBWso2gwzyenW29CnCp30Kjz4DogE"
904
- });
905
-
906
901
  // ../shared/src/constants.ts
907
902
  var DEFAULT_GLOBAL_RESOURCE_ARCHIVE_TIMEOUT_MS = 1e4;
908
903
 
909
904
  // src/node/commands.ts
910
905
  import assert from "node:assert";
911
- import { resolve as resolve3 } from "node:path";
906
+ import { resolve as resolve7 } from "node:path";
912
907
  import { storyNameFromExport as storyNameFromExport2, toId as toId2 } from "storybook/internal/csf";
913
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
+
914
1190
  // src/node/NetworkIdleTracker.ts
915
1191
  var NetworkIdleTimeoutError = class extends Error {
916
1192
  name = "NetworkIdleTimeoutError";
@@ -946,12 +1222,12 @@ var NetworkIdleTracker = class _NetworkIdleTracker {
946
1222
  if (this.pending.size === 0 && this.idleTimer === null) {
947
1223
  return Promise.resolve();
948
1224
  }
949
- return new Promise((resolve5, reject) => {
1225
+ return new Promise((resolve9, reject) => {
950
1226
  const timeout = setTimeout(
951
1227
  () => reject(new NetworkIdleTimeoutError("Timed out waiting for network to be idle")),
952
1228
  rejectTimeout
953
1229
  );
954
- this.idleResolvers.push(resolve5, () => clearTimeout(timeout));
1230
+ this.idleResolvers.push(resolve9, () => clearTimeout(timeout));
955
1231
  });
956
1232
  }
957
1233
  onComplete = (params) => {
@@ -980,21 +1256,22 @@ var NetworkIdleTracker = class _NetworkIdleTracker {
980
1256
  };
981
1257
 
982
1258
  // src/node/reporter.ts
983
- import { relative, resolve } from "node:path";
1259
+ import { relative, resolve as resolve5 } from "node:path";
984
1260
  import colors from "tinyrainbow";
985
1261
 
986
1262
  // src/constants.ts
987
1263
  var DEFAULT_OUTPUT_DIR = ".vitest/chromatic";
988
1264
 
989
1265
  // src/node/reporter.ts
990
- var REPORTER_NAME = "chromatic-reporter";
1266
+ var REPORTER_NAME2 = "chromatic-reporter";
991
1267
  var ChromaticReporter = class _ChromaticReporter {
992
- constructor(ctx, options, snapshotCountPerEntity = /* @__PURE__ */ new Map()) {
1268
+ constructor(ctx, options, snapshotCountPerEntity = /* @__PURE__ */ new Map(), isPluginActivated = false) {
993
1269
  this.ctx = ctx;
994
1270
  this.options = options;
995
1271
  this.snapshotCountPerEntity = snapshotCountPerEntity;
1272
+ this.isPluginActivated = isPluginActivated;
996
1273
  }
997
- name = REPORTER_NAME;
1274
+ name = REPORTER_NAME2;
998
1275
  /**
999
1276
  * Add `ChromaticReporter` to Vitest reporters unless it's already included.
1000
1277
  */
@@ -1003,6 +1280,7 @@ var ChromaticReporter = class _ChromaticReporter {
1003
1280
  verbose: pluginOptions.reporter.verbose,
1004
1281
  outputDirectory: pluginOptions.outputDirectory,
1005
1282
  turboSnap: pluginOptions.turboSnap,
1283
+ logToFile: pluginOptions.telemetry.enabled && pluginOptions.telemetry.logToFile,
1006
1284
  builtInReporter: "default"
1007
1285
  };
1008
1286
  for (const reporter of ctx.config.reporters) {
@@ -1026,6 +1304,13 @@ var ChromaticReporter = class _ChromaticReporter {
1026
1304
  const reporter = ctx.config.reporters.find(isChromaticReporter);
1027
1305
  reporter?._onSnapshot(test);
1028
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
+ }
1029
1314
  onTestCaseResult(testCase) {
1030
1315
  if (this.options.builtInReporter !== "verbose") {
1031
1316
  return;
@@ -1057,11 +1342,25 @@ var ChromaticReporter = class _ChromaticReporter {
1057
1342
  onTestRunEnd() {
1058
1343
  const snapshotCount = [...this.snapshotCountPerEntity.values()].reduce((a, b) => a + b, 0);
1059
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
+ }
1060
1360
  if (snapshotCount === 0) {
1061
1361
  return;
1062
1362
  }
1063
- const output = resolve(this.ctx.config.root, this.options.outputDirectory);
1064
- const separator = colors.dim("\u2500".repeat(this.ctx.logger.getColumns()));
1363
+ const output = resolve5(this.ctx.config.root, this.options.outputDirectory);
1065
1364
  let uploadCommand = "chromatic --vitest --project-token=<TOKEN>";
1066
1365
  if (this.options.turboSnap) {
1067
1366
  uploadCommand += " --only-changed";
@@ -1069,6 +1368,8 @@ var ChromaticReporter = class _ChromaticReporter {
1069
1368
  if (this.options.outputDirectory !== DEFAULT_OUTPUT_DIR || this.ctx.config.root !== process.cwd()) {
1070
1369
  uploadCommand = `CHROMATIC_ARCHIVE_LOCATION=${relative(process.cwd(), output)} ${uploadCommand}`;
1071
1370
  }
1371
+ const telemetryInfo = this.options.logToFile ? `
1372
+ Telemetry events logged to ${colors.dim(resolve5(output, TELEMETRY_LOG_FILE))}` : "";
1072
1373
  this.ctx.logger.log(
1073
1374
  `${separator}`,
1074
1375
  `
@@ -1079,6 +1380,7 @@ ${colors.green("\u2713")} ${snapshotCount} ${pluralize(snapshotCount, "archive")
1079
1380
  `
1080
1381
 
1081
1382
  Archives saved in ${colors.dim(output)}`,
1383
+ telemetryInfo,
1082
1384
  `
1083
1385
  To upload archives into Chromatic run ${colors.green(uploadCommand)}`,
1084
1386
  `
@@ -1102,19 +1404,23 @@ ${separator}
1102
1404
  const previousCount = this.snapshotCountPerEntity.get(key) ?? 0;
1103
1405
  this.snapshotCountPerEntity.set(key, previousCount + 1);
1104
1406
  }
1407
+ _onPluginActivated() {
1408
+ this.isPluginActivated = true;
1409
+ }
1105
1410
  };
1106
1411
  function isChromaticReporter(reporter) {
1107
- return "name" in reporter && reporter.name === REPORTER_NAME;
1412
+ return "name" in reporter && reporter.name === REPORTER_NAME2;
1108
1413
  }
1109
1414
  function pluralize(count, text) {
1110
1415
  return count === 1 ? text : `${text}s`;
1111
1416
  }
1112
1417
 
1113
1418
  // src/node/webpack-stats-reporter.ts
1114
- import { existsSync as existsSync3, readFileSync } from "node:fs";
1115
- import { mkdir, readdir, readFile, rm, writeFile as writeFile2 } from "node:fs/promises";
1116
- import { dirname, relative as relative2, resolve as resolve2, sep } from "node:path";
1117
- var REPORTER_NAME2 = "chromatic-webpack-stats-reporter";
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";
1422
+ import { isCSSRequest } from "vitest/node";
1423
+ var REPORTER_NAME3 = "chromatic-webpack-stats-reporter";
1118
1424
  var VIRTUAL_MODULE_PREFIX = "\0";
1119
1425
  var WebpackStatsReporter = class _WebpackStatsReporter {
1120
1426
  constructor(ctx, options, moduleIdsToStoryFiles = /* @__PURE__ */ new Map()) {
@@ -1122,7 +1428,7 @@ var WebpackStatsReporter = class _WebpackStatsReporter {
1122
1428
  this.options = options;
1123
1429
  this.moduleIdsToStoryFiles = moduleIdsToStoryFiles;
1124
1430
  }
1125
- name = REPORTER_NAME2;
1431
+ name = REPORTER_NAME3;
1126
1432
  /**
1127
1433
  * Add `WebpackStatsReporter` to Vitest reporters unless it's already included.
1128
1434
  */
@@ -1134,8 +1440,8 @@ var WebpackStatsReporter = class _WebpackStatsReporter {
1134
1440
  ctx.config.shard && `-${ctx.config.shard.index}-${ctx.config.shard.count}`,
1135
1441
  ".json"
1136
1442
  ].filter(Boolean).join("");
1137
- const outputFile2 = resolve2(ctx.config.root, pluginOptions.outputDirectory, filename);
1138
- 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 }));
1139
1445
  }
1140
1446
  }
1141
1447
  /**
@@ -1161,10 +1467,26 @@ var WebpackStatsReporter = class _WebpackStatsReporter {
1161
1467
  await rm(this.options.outputFile, { force: true });
1162
1468
  this.moduleIdsToStoryFiles.clear();
1163
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
+ }
1164
1486
  /**
1165
1487
  * Generate `preview-stats.json` from collected Story files and their dependent test modules
1166
1488
  */
1167
- async onTestRunEnd(testModules) {
1489
+ async writePreviewStats(testModules) {
1168
1490
  const statsMap = /* @__PURE__ */ new Map();
1169
1491
  for (const testModule of testModules) {
1170
1492
  const storyFiles = this.moduleIdsToStoryFiles.get(testModule.moduleId);
@@ -1176,25 +1498,33 @@ var WebpackStatsReporter = class _WebpackStatsReporter {
1176
1498
  continue;
1177
1499
  }
1178
1500
  const id = this.normalize(testModule.moduleId);
1501
+ const additionalModules = [];
1179
1502
  statsMap.set(id, this.createStatsMapModule(id, [...storyFiles]));
1180
1503
  if (testModule.project.config.config) {
1181
- const configId = this.normalize(testModule.project.config.config);
1182
- const configEntry = statsMap.get(configId) || this.createStatsMapModule(configId, []);
1183
- configEntry.reasons.push({ moduleName: id });
1184
- statsMap.set(configId, configEntry);
1504
+ additionalModules.push({ id: testModule.project.config.config, isInModuleGraph: false });
1505
+ }
1506
+ for (const setupFile of testModule.project.config.setupFiles) {
1507
+ additionalModules.push({ id: setupFile, isInModuleGraph: true });
1185
1508
  }
1186
- this.addModule(testModule.moduleId, statsMap, vite.moduleGraph, vite.config.cacheDir);
1509
+ this.addModule(
1510
+ testModule.moduleId,
1511
+ statsMap,
1512
+ vite.moduleGraph,
1513
+ vite.config.cacheDir,
1514
+ /* @__PURE__ */ new Set(),
1515
+ additionalModules
1516
+ );
1187
1517
  }
1188
1518
  if (!existsSync3(dirname(this.options.outputFile))) {
1189
- await mkdir(dirname(this.options.outputFile), { recursive: true });
1519
+ await mkdir2(dirname(this.options.outputFile), { recursive: true });
1190
1520
  }
1191
- await writeFile2(
1521
+ await writeFile3(
1192
1522
  this.options.outputFile,
1193
1523
  JSON.stringify({ modules: Array.from(statsMap.values()) }, null, 2),
1194
1524
  "utf-8"
1195
1525
  );
1196
1526
  }
1197
- addModule(id, statsMap, moduleGraph, cacheDir, visited = /* @__PURE__ */ new Set()) {
1527
+ addModule(id, statsMap, moduleGraph, cacheDir, visited, additionalModules = []) {
1198
1528
  if (visited.has(id)) {
1199
1529
  return;
1200
1530
  }
@@ -1205,10 +1535,13 @@ var WebpackStatsReporter = class _WebpackStatsReporter {
1205
1535
  `[chromatic] Could not find module for id ${id}. Excluding from TurboSnap.`
1206
1536
  );
1207
1537
  }
1208
- const importedModules = [];
1538
+ const importedModules = [...additionalModules];
1209
1539
  for (const imported of mod.importedModules) {
1210
1540
  if (imported.id == null) {
1211
1541
  if (imported.file) {
1542
+ if (mod.file && isCSSRequest(mod.file) && !isCSSRequest(imported.file)) {
1543
+ continue;
1544
+ }
1212
1545
  importedModules.push({ id: imported.file, isInModuleGraph: false });
1213
1546
  }
1214
1547
  continue;
@@ -1247,11 +1580,11 @@ var WebpackStatsReporter = class _WebpackStatsReporter {
1247
1580
  };
1248
1581
  }
1249
1582
  normalize(filePath) {
1250
- return relative2(this.ctx.config.root, filePath).replaceAll(sep, "/").split("?")[0];
1583
+ return relative2(this.ctx.config.root, filePath).replaceAll(sep2, "/").split("?")[0];
1251
1584
  }
1252
1585
  };
1253
1586
  function isWebpackStatsReporter(reporter) {
1254
- return "name" in reporter && reporter.name === REPORTER_NAME2;
1587
+ return "name" in reporter && reporter.name === REPORTER_NAME3;
1255
1588
  }
1256
1589
  function resolveOptimizedDependencySources(mod, cacheDir, visited) {
1257
1590
  if (visited.has(mod.id)) {
@@ -1287,7 +1620,7 @@ function getChunkSources(mod, cacheDir) {
1287
1620
  return sources;
1288
1621
  }
1289
1622
  try {
1290
- 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"));
1291
1624
  return resolveMapSources(mod, diskMap, cacheDir);
1292
1625
  } catch {
1293
1626
  return [];
@@ -1301,7 +1634,7 @@ function resolveMapSources(mod, map, cacheDir) {
1301
1634
  if (typeof source !== "string" || source.startsWith(VIRTUAL_MODULE_PREFIX)) {
1302
1635
  return [];
1303
1636
  }
1304
- const resolved = resolve2(dirname(mod.id), source).replaceAll(sep, "/");
1637
+ const resolved = resolve6(dirname(mod.id), source).replaceAll(sep2, "/");
1305
1638
  if (resolved.startsWith(cacheDir)) {
1306
1639
  return [];
1307
1640
  }
@@ -1309,12 +1642,12 @@ function resolveMapSources(mod, map, cacheDir) {
1309
1642
  });
1310
1643
  }
1311
1644
  async function mergePreviewStats(options) {
1312
- const outputDirectory = resolve2(options.root, options.outputDirectory);
1645
+ const outputDirectory = resolve6(options.root, options.outputDirectory);
1313
1646
  const merged = /* @__PURE__ */ new Map();
1314
1647
  for (const filename of await readdir(outputDirectory)) {
1315
1648
  if (filename.startsWith("preview-stats") && filename.endsWith(".json")) {
1316
- const fullFilename = resolve2(outputDirectory, filename);
1317
- 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"));
1318
1651
  for (const mod of stats.modules) {
1319
1652
  const previous = merged.get(mod.id);
1320
1653
  if (previous) {
@@ -1330,8 +1663,8 @@ async function mergePreviewStats(options) {
1330
1663
  await rm(fullFilename);
1331
1664
  }
1332
1665
  }
1333
- await writeFile2(
1334
- resolve2(outputDirectory, "preview-stats.json"),
1666
+ await writeFile3(
1667
+ resolve6(outputDirectory, "preview-stats.json"),
1335
1668
  JSON.stringify({ modules: Array.from(merged.values()) }, null, 2),
1336
1669
  "utf-8"
1337
1670
  );
@@ -1342,20 +1675,14 @@ function createCommands(options) {
1342
1675
  const resourceArchivers = /* @__PURE__ */ new Map();
1343
1676
  const networkIdleTrackers = /* @__PURE__ */ new Map();
1344
1677
  const savedResults = /* @__PURE__ */ new Set();
1678
+ const trackedCommandFailures = /* @__PURE__ */ new Set();
1345
1679
  const snapshots = /* @__PURE__ */ new Map();
1346
- return {
1347
- /**
1348
- * Get resolved options on the client side.
1349
- * All options must be serializable at this point.
1350
- */
1351
- async __chromatic_getOptions() {
1352
- return options;
1353
- },
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,10 +1963,11 @@ 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
  );
@@ -1592,32 +1978,78 @@ function chromaticPlugin(userOptions = {}) {
1592
1978
  optimizeDeps: {
1593
1979
  entries: [setupFile]
1594
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" } },
1595
1983
  test: {
1984
+ provide: {
1985
+ __chromatic_options: options
1986
+ },
1596
1987
  browser: {
1597
1988
  commands: createCommands(options)
1598
1989
  }
1599
1990
  }
1600
1991
  };
1601
1992
  },
1602
- async configureVitest(context) {
1993
+ configureVitest: withErrorTracking(options, async (context) => {
1603
1994
  const project = context.project;
1604
1995
  const browser = project.config.browser;
1605
1996
  const sequence = context.vitest.config.sequence;
1606
1997
  const isMergeReports = project.globalConfig.mergeReports;
1607
- if (!browser.enabled || browser.name !== "chromium") {
1608
- 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
+ });
1609
2024
  }
1610
2025
  if (options.reporter.enabled) {
1611
2026
  ChromaticReporter.apply(context.vitest, options);
1612
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);
1613
2037
  if (options.turboSnap && !isMergeReports) {
1614
2038
  WebpackStatsReporter.apply(context.vitest, options);
1615
2039
  }
2040
+ if (options.telemetry.enabled) {
2041
+ TelemetryReporter.apply(context.vitest, options);
2042
+ }
1616
2043
  if (sequence.hooks === "stack") {
1617
2044
  project.config.setupFiles.push(setupFile);
1618
2045
  } else if (sequence.hooks === "list") {
1619
2046
  project.config.setupFiles.unshift(setupFile);
1620
2047
  } else {
2048
+ trackEvent2({
2049
+ eventType: "setup_files_parallel",
2050
+ level: "warn",
2051
+ payload: { setupFileCount: project.config.setupFiles.length }
2052
+ });
1621
2053
  project.config.setupFiles.push(setupFile);
1622
2054
  context.vitest.logger.warn(
1623
2055
  colors2.bgYellow(colors2.black(" chromatic ")),
@@ -1633,6 +2065,7 @@ function chromaticPlugin(userOptions = {}) {
1633
2065
  `Tags cannot be used with Vitest ${context.vitest.version}. Please upgrade to Vitest 4.1 or later to use this feature.`
1634
2066
  )
1635
2067
  );
2068
+ trackEvent2({ eventType: "tags_low_version", level: "warn", payload: {} });
1636
2069
  }
1637
2070
  if (options.tags) {
1638
2071
  project.config.tags ||= [];
@@ -1645,10 +2078,19 @@ function chromaticPlugin(userOptions = {}) {
1645
2078
  }
1646
2079
  if (isMergeReports) {
1647
2080
  if (options.turboSnap) {
1648
- await mergePreviewStats({
1649
- root: project.vitest.config.root,
1650
- outputDirectory: options.outputDirectory
1651
- });
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
+ }
1652
2094
  }
1653
2095
  } else {
1654
2096
  clean();
@@ -1658,16 +2100,34 @@ function chromaticPlugin(userOptions = {}) {
1658
2100
  await project.browser?.triggerCommand("__chromatic_reset", {});
1659
2101
  });
1660
2102
  function clean() {
1661
- const outputDirectory = resolve4(project.vitest.config.root, options.outputDirectory);
1662
- 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);
1663
2106
  if (existsSync4(outputDirectory)) {
1664
2107
  for (const file of readdirSync(outputDirectory)) {
1665
2108
  if (file.startsWith("preview-stats") && file.endsWith(".json")) {
1666
- rmSync(resolve4(outputDirectory, file), { force: true });
2109
+ rmSync2(resolve8(outputDirectory, file), { force: true });
1667
2110
  }
1668
2111
  }
1669
2112
  }
1670
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;
1671
2131
  }
1672
2132
  };
1673
2133
  }