testit-js-commons 5.0.9 → 5.1.0

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.
@@ -2,3 +2,4 @@ export * from "./utils";
2
2
  export * from "./html-escape.util";
3
3
  export * from "./tms-load-test-run-debug";
4
4
  export * from "./http-retry.util";
5
+ export * from "./log-sanitize.util";
@@ -18,3 +18,4 @@ __exportStar(require("./utils"), exports);
18
18
  __exportStar(require("./html-escape.util"), exports);
19
19
  __exportStar(require("./tms-load-test-run-debug"), exports);
20
20
  __exportStar(require("./http-retry.util"), exports);
21
+ __exportStar(require("./log-sanitize.util"), exports);
@@ -0,0 +1,12 @@
1
+ /** Redact Authorization / PrivateToken values from a string. */
2
+ export declare function redactSecretsInString(value: string): string;
3
+ /**
4
+ * Deep-redact secrets from any value before logging.
5
+ * Keeps structure; replaces sensitive header/token fields and string matches.
6
+ */
7
+ export declare function redactSecrets(value: unknown, depth?: number, seen?: WeakSet<object>): unknown;
8
+ /**
9
+ * Compact, header-free error summary for logs.
10
+ * Prefer body / error / message — never dump req._header.
11
+ */
12
+ export declare function formatLogError(err: unknown): Record<string, unknown> | string;
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.redactSecretsInString = redactSecretsInString;
4
+ exports.redactSecrets = redactSecrets;
5
+ exports.formatLogError = formatLogError;
6
+ const AUTH_HEADER_RE = /(Authorization\s*[:=]\s*)(["']?)(PrivateToken|Bearer)\s+\S+/gi;
7
+ const PRIVATE_TOKEN_RE = /(PrivateToken)\s+\S+/gi;
8
+ const SENSITIVE_KEYS = new Set([
9
+ "authorization",
10
+ "privatetoken",
11
+ "private_token",
12
+ "apitoken",
13
+ "api_token",
14
+ "token",
15
+ ]);
16
+ const REDACTED = "*****";
17
+ /** Redact Authorization / PrivateToken values from a string. */
18
+ function redactSecretsInString(value) {
19
+ return value
20
+ .replace(AUTH_HEADER_RE, `$1$2$3 ${REDACTED}`)
21
+ .replace(PRIVATE_TOKEN_RE, `$1 ${REDACTED}`);
22
+ }
23
+ function isPlainObject(value) {
24
+ return value !== null && typeof value === "object" && !Array.isArray(value);
25
+ }
26
+ /**
27
+ * Deep-redact secrets from any value before logging.
28
+ * Keeps structure; replaces sensitive header/token fields and string matches.
29
+ */
30
+ function redactSecrets(value, depth = 0, seen = new WeakSet()) {
31
+ if (value == null || depth > 8) {
32
+ return value;
33
+ }
34
+ if (typeof value === "string") {
35
+ return redactSecretsInString(value);
36
+ }
37
+ if (typeof value !== "object") {
38
+ return value;
39
+ }
40
+ if (seen.has(value)) {
41
+ return "[Circular]";
42
+ }
43
+ seen.add(value);
44
+ if (Array.isArray(value)) {
45
+ return value.map((item) => redactSecrets(item, depth + 1, seen));
46
+ }
47
+ // Prefer a safe HTTP-error shape when request/response with headers is present.
48
+ const err = value;
49
+ if (err.response != null || err.req != null || typeof err.statusCode === "number") {
50
+ return formatLogError(value);
51
+ }
52
+ const out = {};
53
+ for (const [key, nested] of Object.entries(err)) {
54
+ if (SENSITIVE_KEYS.has(key.toLowerCase())) {
55
+ out[key] = REDACTED;
56
+ continue;
57
+ }
58
+ // Drop raw request objects that carry headers.
59
+ if (key === "req" || key === "request") {
60
+ continue;
61
+ }
62
+ out[key] = redactSecrets(nested, depth + 1, seen);
63
+ }
64
+ return out;
65
+ }
66
+ /**
67
+ * Compact, header-free error summary for logs.
68
+ * Prefer body / error / message — never dump req._header.
69
+ */
70
+ function formatLogError(err) {
71
+ var _a, _b, _c, _d, _e, _f, _g, _h;
72
+ if (err == null) {
73
+ return String(err);
74
+ }
75
+ if (typeof err === "string") {
76
+ return redactSecretsInString(err);
77
+ }
78
+ if (typeof err !== "object") {
79
+ return String(err);
80
+ }
81
+ const e = err;
82
+ const nested = (_b = (_a = (isPlainObject(e.error) ? e.error : null)) !== null && _a !== void 0 ? _a : (isPlainObject(e.cause) ? e.cause : null)) !== null && _b !== void 0 ? _b : e;
83
+ const response = isPlainObject(nested.response) ? nested.response : undefined;
84
+ const status = (_e = (_d = (_c = nested.statusCode) !== null && _c !== void 0 ? _c : nested.status) !== null && _d !== void 0 ? _d : response === null || response === void 0 ? void 0 : response.status) !== null && _e !== void 0 ? _e : response === null || response === void 0 ? void 0 : response.statusCode;
85
+ const body = (_g = (_f = nested.body) !== null && _f !== void 0 ? _f : response === null || response === void 0 ? void 0 : response.body) !== null && _g !== void 0 ? _g : response === null || response === void 0 ? void 0 : response.text;
86
+ const message = (typeof nested.message === "string" && nested.message) ||
87
+ (typeof e.message === "string" && e.message) ||
88
+ undefined;
89
+ const code = (_h = nested.code) !== null && _h !== void 0 ? _h : e.code;
90
+ const safe = {};
91
+ if (status != null) {
92
+ safe.status = status;
93
+ }
94
+ if (code != null) {
95
+ safe.code = code;
96
+ }
97
+ if (message) {
98
+ safe.message = redactSecretsInString(message);
99
+ }
100
+ if (body != null) {
101
+ safe.body = typeof body === "string" ? redactSecretsInString(body) : redactSecrets(body);
102
+ }
103
+ if (Object.keys(safe).length === 0) {
104
+ try {
105
+ return redactSecretsInString(JSON.stringify(err));
106
+ }
107
+ catch (_j) {
108
+ return redactSecretsInString(String(err));
109
+ }
110
+ }
111
+ return safe;
112
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const log_sanitize_util_1 = require("./log-sanitize.util");
4
+ describe("log-sanitize", () => {
5
+ const token = "AvG6M3Vnc5SDZ0t4VlY0HqTG";
6
+ const header = "GET /api/v2/testRuns/7526aece-b91d-479a-98e2-2ced1c2a513c HTTP/1.1\r\n" +
7
+ `Authorization: PrivateToken ${token}\r\n` +
8
+ "Accept: application/json\r\n";
9
+ it("redacts Authorization PrivateToken in strings", () => {
10
+ const out = (0, log_sanitize_util_1.redactSecretsInString)(header);
11
+ expect(out).not.toContain(token);
12
+ expect(out).toContain("PrivateToken *****");
13
+ });
14
+ it("formatLogError drops req/_header and keeps status/body", () => {
15
+ const err = {
16
+ statusCode: 404,
17
+ message: "Not Found",
18
+ body: { error: { message: "Test run not found" } },
19
+ response: {
20
+ status: 404,
21
+ req: { _header: header },
22
+ },
23
+ req: { _header: header },
24
+ };
25
+ const safe = (0, log_sanitize_util_1.formatLogError)(err);
26
+ expect(JSON.stringify(safe)).not.toContain(token);
27
+ expect(safe).not.toHaveProperty("req");
28
+ expect(safe).not.toHaveProperty("response");
29
+ expect(safe.status).toBe(404);
30
+ expect(safe.message).toBe("Not Found");
31
+ });
32
+ it("redactSecrets sanitizes nested error objects used by logger", () => {
33
+ const err = {
34
+ response: { req: { _header: header }, status: 401 },
35
+ statusCode: 401,
36
+ message: `Unauthorized PrivateToken ${token}`,
37
+ };
38
+ const out = JSON.stringify((0, log_sanitize_util_1.redactSecrets)(err));
39
+ expect(out).not.toContain(token);
40
+ expect(out).toContain("*****");
41
+ });
42
+ it("formatLogError prefers body/error without headers", () => {
43
+ const err = {
44
+ error: {
45
+ statusCode: 401,
46
+ body: { title: "Unauthorized" },
47
+ response: { req: { _header: header } },
48
+ },
49
+ };
50
+ const safe = (0, log_sanitize_util_1.formatLogError)(err);
51
+ expect(JSON.stringify(safe)).not.toContain(token);
52
+ expect(safe.status).toBe(401);
53
+ expect(safe.body).toEqual({ title: "Unauthorized" });
54
+ });
55
+ });
@@ -1,4 +1,4 @@
1
- type LogLevel = 'error' | 'warn' | 'info' | 'debug';
1
+ type LogLevel = "error" | "warn" | "info" | "debug";
2
2
  declare class Logger {
3
3
  private readonly levels;
4
4
  private currentLevel;
@@ -1,65 +1,63 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ const log_sanitize_util_1 = require("../common/utils/log-sanitize.util");
3
4
  class Logger {
4
5
  constructor() {
5
6
  this.levels = {
6
7
  error: 0,
7
8
  warn: 1,
8
9
  info: 2,
9
- debug: 3
10
+ debug: 3,
10
11
  };
11
- // Уровень из переменной окружения или по умолчанию 'warn'
12
- const envLevel = (process.env.LOG_LEVEL || 'warn').toLowerCase();
13
- this.currentLevel = this.levels[envLevel] !== undefined
14
- ? this.levels[envLevel]
15
- : this.levels.info;
12
+ // Level from env or default 'warn'
13
+ const envLevel = (process.env.LOG_LEVEL || "warn").toLowerCase();
14
+ this.currentLevel =
15
+ this.levels[envLevel] !== undefined ? this.levels[envLevel] : this.levels.info;
16
16
  }
17
17
  log_(level, message, ...args) {
18
18
  if (this.levels[level] <= this.currentLevel) {
19
19
  const timestamp = new Date().toISOString();
20
20
  const prefix = `[${timestamp}] [${level.toUpperCase()}]`;
21
- if (level === 'error') {
22
- console.error(prefix, message, ...args);
21
+ const safeMessage = (0, log_sanitize_util_1.redactSecretsInString)(message);
22
+ const safeArgs = args.map((arg) => (0, log_sanitize_util_1.redactSecrets)(arg));
23
+ if (level === "error") {
24
+ console.error(prefix, safeMessage, ...safeArgs);
23
25
  }
24
- else if (level === 'warn') {
25
- console.warn(prefix, message, ...args);
26
+ else if (level === "warn") {
27
+ console.warn(prefix, safeMessage, ...safeArgs);
26
28
  }
27
29
  else {
28
- console.log(prefix, message, ...args);
30
+ console.log(prefix, safeMessage, ...safeArgs);
29
31
  }
30
32
  }
31
33
  }
32
34
  error(message, ...args) {
33
- this.log_('error', message, ...args);
35
+ this.log_("error", message, ...args);
34
36
  }
35
37
  warn(message, ...args) {
36
- this.log_('warn', message, ...args);
38
+ this.log_("warn", message, ...args);
37
39
  }
38
40
  info(message, ...args) {
39
- this.log_('info', message, ...args);
41
+ this.log_("info", message, ...args);
40
42
  }
41
43
  log(message, ...args) {
42
- this.log_('info', message, ...args);
44
+ this.log_("info", message, ...args);
43
45
  }
44
46
  debug(message, ...args) {
45
- this.log_('debug', message, ...args);
47
+ this.log_("debug", message, ...args);
46
48
  }
47
- // Проверка, включен ли уровень
48
49
  isLevelEnabled(level) {
49
50
  return this.levels[level] <= this.currentLevel;
50
51
  }
51
- // Получить текущий уровень логирования
52
52
  getCurrentLevel() {
53
53
  const level = Object.keys(this.levels).find((key) => this.levels[key] === this.currentLevel);
54
- return level || 'info';
54
+ return level || "info";
55
55
  }
56
- // Установить уровень логирования динамически
57
56
  setLevel(level) {
58
57
  if (this.levels[level] !== undefined) {
59
58
  this.currentLevel = this.levels[level];
60
59
  }
61
60
  }
62
61
  }
63
- // Синглтон
64
62
  const logger = new Logger();
65
63
  exports.default = logger;
@@ -114,13 +114,7 @@ class AttachmentsService extends common_1.BaseService {
114
114
  }
115
115
  }
116
116
  catch (error) {
117
- logger_1.default.error("Error uploading text attachment:", error);
118
- if (error.response) {
119
- logger_1.default.error("Response details:", {
120
- status: error.response.status,
121
- text: error.response.text,
122
- });
123
- }
117
+ logger_1.default.error("Error uploading text attachment:", (0, common_1.formatLogError)(error));
124
118
  throw error;
125
119
  }
126
120
  });
@@ -150,13 +144,7 @@ class AttachmentsService extends common_1.BaseService {
150
144
  attachmentIds.push(id);
151
145
  }
152
146
  catch (error) {
153
- logger_1.default.error(`Error uploading attachment ${path}:`, error);
154
- if (error.response) {
155
- logger_1.default.error("Response details:", {
156
- status: error.response.status,
157
- text: error.response.text,
158
- });
159
- }
147
+ logger_1.default.error(`Error uploading attachment ${path}:`, (0, common_1.formatLogError)(error));
160
148
  throw error;
161
149
  }
162
150
  }
@@ -109,13 +109,12 @@ class AutotestsService extends common_1.BaseService {
109
109
  linkToWorkItems(internalId, workItemIds) {
110
110
  return __awaiter(this, void 0, void 0, function* () {
111
111
  const promises = workItemIds.map((workItemId) => __awaiter(this, void 0, void 0, function* () {
112
- var _a, _b;
113
112
  try {
114
113
  yield this._client.adaptersAutoTestsIdWorkItemsPost(internalId, { workItemIdApiModel: { id: workItemId } });
115
114
  logger_1.default.log(`Link autotest ${internalId} to workitem ${workItemId} is successfully`);
116
115
  }
117
116
  catch (e) {
118
- logger_1.default.error(`Cannot link autotest ${internalId} to work item ${workItemId}`, (_b = (_a = e === null || e === void 0 ? void 0 : e.body) !== null && _a !== void 0 ? _a : e === null || e === void 0 ? void 0 : e.error) !== null && _b !== void 0 ? _b : e);
117
+ logger_1.default.error(`Cannot link autotest ${internalId} to work item ${workItemId}`, (0, common_1.formatLogError)(e));
119
118
  }
120
119
  }));
121
120
  yield Promise.all(promises);
@@ -354,7 +354,7 @@ class SyncStorageRunner {
354
354
  }
355
355
  }
356
356
  exports.SyncStorageRunner = SyncStorageRunner;
357
- SyncStorageRunner.VERSION = "v0.3.10";
357
+ SyncStorageRunner.VERSION = "v0.3.12";
358
358
  SyncStorageRunner.STARTUP_TIMEOUT_MS = 30000;
359
359
  SyncStorageRunner.STARTUP_POLL_MS = 1000;
360
360
  SyncStorageRunner.PROCESS_WARMUP_MS = 2000;
@@ -16,6 +16,11 @@ export declare class TestRunConverter extends BaseConverter implements ITestRunC
16
16
  toLocalState(state: any): RunState;
17
17
  toOriginState(state: RunState): any;
18
18
  mapToStatusType(status: Outcome): string;
19
+ /**
20
+ * Minimal InProgress stub. Must not include links/steps/attachments/message:
21
+ * TMS appends those on a later final POST for the same result slot (e.g. Jest
22
+ * first test in file → 2 links in stub + 2 in final = 4).
23
+ */
19
24
  toOriginAutotestResultInProgress(autotest: AutotestResult): any;
20
25
  toOriginAutotestResult(autotest: AutotestResult): any;
21
26
  toOriginTestResultUpdate(autotest: AutotestResult): any;
@@ -28,8 +28,25 @@ class TestRunConverter extends common_1.BaseConverter {
28
28
  };
29
29
  return statusMap[status];
30
30
  }
31
+ /**
32
+ * Minimal InProgress stub. Must not include links/steps/attachments/message:
33
+ * TMS appends those on a later final POST for the same result slot (e.g. Jest
34
+ * first test in file → 2 links in stub + 2 in final = 4).
35
+ */
31
36
  toOriginAutotestResultInProgress(autotest) {
32
- return Object.assign(Object.assign({}, this.toOriginAutotestResult(autotest)), { statusType: "InProgress" });
37
+ const model = {
38
+ configurationId: this.config.configurationId,
39
+ autoTestExternalId: autotest.autoTestExternalId,
40
+ statusType: "InProgress",
41
+ failureReasonNames: undefined,
42
+ };
43
+ if (autotest.startedOn !== undefined) {
44
+ model.startedOn = autotest.startedOn;
45
+ }
46
+ if (autotest.parameters !== undefined && Object.keys(autotest.parameters).length > 0) {
47
+ model.parameters = autotest.parameters;
48
+ }
49
+ return model;
33
50
  }
34
51
  toOriginAutotestResult(autotest) {
35
52
  var _a, _b, _c, _d;
@@ -10,6 +10,30 @@ function makeConfig() {
10
10
  testRunId: "33333333-3333-3333-3333-333333333333",
11
11
  };
12
12
  }
13
+ describe("TestRunConverter.toOriginAutotestResultInProgress", () => {
14
+ it("omits links/steps/attachments so final POST does not duplicate them", () => {
15
+ const converter = new testruns_converter_1.TestRunConverter(makeConfig());
16
+ const model = converter.toOriginAutotestResultInProgress({
17
+ autoTestExternalId: "ext-1",
18
+ outcome: "Passed",
19
+ links: [
20
+ { url: "https://a.example", title: "A" },
21
+ { url: "https://b.example", title: "B" },
22
+ ],
23
+ stepResults: [{ title: "step" }],
24
+ attachments: [{ id: "att-1" }],
25
+ message: "msg",
26
+ startedOn: new Date("2026-01-01T00:00:00.000Z"),
27
+ });
28
+ expect(model.statusType).toBe("InProgress");
29
+ expect(model.autoTestExternalId).toBe("ext-1");
30
+ expect(model.links).toBeUndefined();
31
+ expect(model.stepResults).toBeUndefined();
32
+ expect(model.attachments).toBeUndefined();
33
+ expect(model.message).toBeUndefined();
34
+ expect(model.startedOn).toEqual(new Date("2026-01-01T00:00:00.000Z"));
35
+ });
36
+ });
13
37
  describe("TestRunConverter.toOriginSetupTeardownUpdate", () => {
14
38
  it("includes only setupResults and teardownResults", () => {
15
39
  const converter = new testruns_converter_1.TestRunConverter(makeConfig());
@@ -15,7 +15,9 @@ export declare class TestRunsService extends BaseService implements ITestRunsSer
15
15
  startTestRun(testRunId: TestRunId): Promise<void>;
16
16
  completeTestRun(testRunId: TestRunId): Promise<void>;
17
17
  postInProgressAutotestResult(testRunId: string, result: AutotestResult): Promise<void>;
18
- loadAutotests(testRunId: string, results: Array<AutotestResult>): Promise<void>;
18
+ loadAutotests(testRunId: string, results: Array<AutotestResult>, options?: {
19
+ throwOnError?: boolean;
20
+ }): Promise<void>;
19
21
  updateSetupTeardown(results: Array<AutotestResult>): Promise<void>;
20
22
  private resolveExistingTestResultId;
21
23
  private rememberCreatedTestResultId;
@@ -64,7 +64,7 @@ class TestRunsService extends common_1.BaseService {
64
64
  return data.id;
65
65
  })
66
66
  .catch((err) => {
67
- logger_1.default.error("Error in createTestRun:", err);
67
+ logger_1.default.error("Error in createTestRun:", (0, utils_1.formatLogError)(err));
68
68
  throw err;
69
69
  });
70
70
  });
@@ -173,7 +173,7 @@ class TestRunsService extends common_1.BaseService {
173
173
  });
174
174
  });
175
175
  }
176
- loadAutotests(testRunId, results) {
176
+ loadAutotests(testRunId, results, options) {
177
177
  return __awaiter(this, void 0, void 0, function* () {
178
178
  var _a, _b;
179
179
  for (const result of results) {
@@ -187,23 +187,24 @@ class TestRunsService extends common_1.BaseService {
187
187
  statusCode: autotestResult.statusCode,
188
188
  stepCount: (_b = (_a = autotestResult.stepResults) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0,
189
189
  });
190
- yield this.sendAutotestResultWithRetry(testRunId, autotestResult)
191
- .then(() => {
190
+ try {
191
+ yield this.sendAutotestResultWithRetry(testRunId, autotestResult);
192
192
  (0, utils_1.logTmsLoadTestRun)("Finalized test result via sendTestResults", {
193
193
  testRunId,
194
194
  autoTestExternalId: externalId,
195
195
  testResultId: this.testResultIdsByExternalId.get(externalId),
196
196
  });
197
- })
198
- .catch((err) => {
199
- var _a, _b;
200
- const normalized = (_b = (_a = err === null || err === void 0 ? void 0 : err.body) !== null && _a !== void 0 ? _a : err === null || err === void 0 ? void 0 : err.error) !== null && _b !== void 0 ? _b : err;
197
+ }
198
+ catch (err) {
201
199
  logger_1.default.error("[testit-js-commons:loadTestRun] FAILED to post final result", {
202
200
  testRunId,
203
201
  autoTestExternalId: autotestResult.autoTestExternalId,
204
- error: normalized,
202
+ error: (0, utils_1.formatLogError)(err),
205
203
  });
206
- });
204
+ if (options === null || options === void 0 ? void 0 : options.throwOnError) {
205
+ throw err;
206
+ }
207
+ }
207
208
  }
208
209
  });
209
210
  }
@@ -235,11 +236,10 @@ class TestRunsService extends common_1.BaseService {
235
236
  teardownCount: (_h = (_g = model.teardownResults) === null || _g === void 0 ? void 0 : _g.length) !== null && _h !== void 0 ? _h : 0,
236
237
  });
237
238
  yield this.updateSetupTeardownWithRetry(testResultId, result, model).catch((err) => {
238
- var _a;
239
239
  logger_1.default.error("[testit-js-commons:loadTestRun] FAILED to update setup/teardown", {
240
240
  autoTestExternalId: result.autoTestExternalId,
241
241
  testResultId,
242
- error: (_a = err === null || err === void 0 ? void 0 : err.body) !== null && _a !== void 0 ? _a : err,
242
+ error: (0, utils_1.formatLogError)(err),
243
243
  });
244
244
  });
245
245
  }
@@ -62,7 +62,9 @@ export interface ITestRunsService {
62
62
  completeTestRun(testRunId: TestRunId): Promise<void>;
63
63
  /** First TMS write as InProgress (mirrors Python realtime in-progress before final load). */
64
64
  postInProgressAutotestResult(testRunId: string, result: AutotestResult): Promise<void>;
65
- loadAutotests(testRunId: string, autotests: Array<AutotestResult>): Promise<void>;
65
+ loadAutotests(testRunId: string, autotests: Array<AutotestResult>, options?: {
66
+ throwOnError?: boolean;
67
+ }): Promise<void>;
66
68
  /** PUT setup/teardown fixture steps onto an already finalized result (importRealtime session end). */
67
69
  updateSetupTeardown(results: Array<AutotestResult>): Promise<void>;
68
70
  }
@@ -15,6 +15,7 @@ export declare class BaseStrategy implements IStrategy {
15
15
  protected constructor(config: AdapterConfig);
16
16
  setup(): Promise<void>;
17
17
  teardown(): Promise<void>;
18
+ touchWorker(): Promise<void>;
18
19
  private flushDeferredResults;
19
20
  loadAutotest(autotest: AutotestPost, status: string): Promise<void>;
20
21
  private updateTestLinkToWorkItems;
@@ -52,25 +52,45 @@ class BaseStrategy {
52
52
  //await this.client.testRuns.completeTestRun(testRunId);
53
53
  });
54
54
  }
55
+ touchWorker() {
56
+ return __awaiter(this, void 0, void 0, function* () {
57
+ var _a;
58
+ if (!((_a = this.syncStorageRunner) === null || _a === void 0 ? void 0 : _a.isActive())) {
59
+ return;
60
+ }
61
+ yield this.syncStorageRunner.setWorkerStatus("in_progress");
62
+ });
63
+ }
55
64
  flushDeferredResults(testRunId) {
56
65
  return __awaiter(this, void 0, void 0, function* () {
57
66
  if (this.deferredResults.length === 0) {
58
67
  return;
59
68
  }
60
69
  const results = this.deferredResults.splice(0, this.deferredResults.length);
70
+ const externalId = this.deferredExternalId;
71
+ this.deferredExternalId = undefined;
61
72
  (0, utils_1.logTmsLoadTestRun)("flush deferred finals", {
62
73
  testRunId,
63
- autoTestExternalId: this.deferredExternalId,
74
+ autoTestExternalId: externalId,
64
75
  count: results.length,
65
76
  });
66
- yield this.client.testRuns.loadAutotests(testRunId, results).catch((err) => {
67
- var _a;
68
- logger_1.default.error("[strategy] FAILED to flush deferred results", {
69
- autoTestExternalId: this.deferredExternalId,
70
- error: (_a = err === null || err === void 0 ? void 0 : err.body) !== null && _a !== void 0 ? _a : err,
77
+ try {
78
+ yield this.client.testRuns.loadAutotests(testRunId, results, { throwOnError: true });
79
+ }
80
+ catch (err) {
81
+ logger_1.default.error("[strategy] FAILED to flush deferred results, retrying once", {
82
+ autoTestExternalId: externalId,
83
+ error: (0, utils_1.formatLogError)(err),
71
84
  });
72
- });
73
- this.deferredExternalId = undefined;
85
+ yield this.client.testRuns
86
+ .loadAutotests(testRunId, results, { throwOnError: true })
87
+ .catch((retryErr) => {
88
+ logger_1.default.error("[strategy] FAILED to flush deferred results on retry", {
89
+ autoTestExternalId: externalId,
90
+ error: (0, utils_1.formatLogError)(retryErr),
91
+ });
92
+ });
93
+ }
74
94
  });
75
95
  }
76
96
  loadAutotest(autotest, status) {
@@ -113,7 +133,7 @@ class BaseStrategy {
113
133
  }
114
134
  }
115
135
  yield this.client.autoTests.linkToWorkItems(existingAutotest, workItemIds).catch((err) => {
116
- logger_1.default.log("Failed link work items. \n", err);
136
+ logger_1.default.log("Failed link work items. \n", (0, utils_1.formatLogError)(err));
117
137
  });
118
138
  });
119
139
  }
@@ -204,11 +224,14 @@ class BaseStrategy {
204
224
  yield this.client.testRuns.postInProgressAutotestResult(testRunId, firstResult);
205
225
  }
206
226
  catch (err) {
207
- (0, utils_1.logTmsLoadTestRun)("postInProgressAutotestResult FAILED", {
227
+ // Cut is already in sync-storage; if TMS stub fails and we throw, the first
228
+ // test is never finalized and Work X ends with "test result not found".
229
+ (0, utils_1.logTmsLoadTestRun)("postInProgressAutotestResult FAILED; posting finals without deferral", {
208
230
  autoTestExternalId: firstResult.autoTestExternalId,
209
231
  message: err instanceof Error ? err.message : String(err),
210
232
  });
211
- throw err;
233
+ yield this.client.testRuns.loadAutotests(testRunId, autotests);
234
+ return;
212
235
  }
213
236
  this.deferredExternalId = firstResult.autoTestExternalId;
214
237
  this.enqueueDeferred([firstResult]);
@@ -294,7 +317,7 @@ class BaseStrategy {
294
317
  (hasLinks ? ` links=${(_h = (_g = testRun.links) === null || _g === void 0 ? void 0 : _g.length) !== null && _h !== void 0 ? _h : 0}` : ""));
295
318
  }
296
319
  catch (err) {
297
- logger_1.default.error(`Failed to apply test run tags/links for "${testRunId}"`, err);
320
+ logger_1.default.error(`Failed to apply test run tags/links for "${testRunId}"`, (0, utils_1.formatLogError)(err));
298
321
  }
299
322
  });
300
323
  }
@@ -4,6 +4,8 @@ export interface IStrategy {
4
4
  readonly testsInRun?: Promise<string[] | undefined>;
5
5
  setup(): Promise<void>;
6
6
  teardown(): Promise<void>;
7
+ /** Refresh sync-storage worker LastStatus so Force Work X does not fire mid-run. */
8
+ touchWorker(): Promise<void>;
7
9
  loadAutotest(autotest: AutotestPost, status: string): Promise<void>;
8
10
  loadTestRun(autotests: AutotestResult[]): Promise<void>;
9
11
  updateSetupTeardown(autotests: AutotestResult[]): Promise<void>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "testit-js-commons",
3
- "version": "5.0.9",
3
+ "version": "5.1.0",
4
4
  "description": "JavaScript commons for Test IT",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",