@uipath/test-manager-tool 1.204.0-preview.255 → 1.205.0-preview.256

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.
@@ -0,0 +1,1676 @@
1
+ import {
2
+ EXIT_CODES,
3
+ InvalidArgumentError,
4
+ LogLevel,
5
+ Option,
6
+ OutputFormatter,
7
+ Pagination,
8
+ PollOutcome,
9
+ RESULTS,
10
+ SuccessOutput,
11
+ catchError,
12
+ configureLogger,
13
+ createHiddenDeprecatedTenantOption,
14
+ extractErrorDetails,
15
+ getAuthContext,
16
+ getFileSystem,
17
+ instructionsFor,
18
+ isCliErrorCode,
19
+ isHtmlDocument,
20
+ isRetryHint,
21
+ logger,
22
+ mapPollFailure,
23
+ pollUntil,
24
+ processContext,
25
+ resolveDeprecatedOptionAlias,
26
+ warnDeprecatedOptionAlias
27
+ } from "./tool-e3prtphw.js";
28
+ import {
29
+ Configuration,
30
+ ProjectMigrationAttachmentApi,
31
+ ProjectMigrationJobApi,
32
+ ProjectsApi,
33
+ UiPathTestManagementHubProjectMigrationAbstractionsEnumsMigrationJobStatus,
34
+ UiPathTestManagementHubProjectMigrationAbstractionsEnumsMigrationJobType
35
+ } from "./tool-cpdm080k.js";
36
+
37
+ // src/utils/shared.ts
38
+ var ENCODING_MARKERS = [
39
+ "\uFEFF",
40
+ "￾",
41
+ "+/v8",
42
+ "+/v9",
43
+ "+/v+",
44
+ "+/v/"
45
+ ];
46
+ function stripEncodingMarkers(content) {
47
+ for (const marker of ENCODING_MARKERS) {
48
+ if (content.startsWith(marker)) {
49
+ return content.slice(marker.length);
50
+ }
51
+ }
52
+ return content;
53
+ }
54
+ var ROBOT_LOG_LEVELS = [
55
+ "Trace",
56
+ "Info",
57
+ "Warn",
58
+ "Error",
59
+ "Fatal"
60
+ ];
61
+ var TERMINAL_STATUSES = new Set(["finished", "cancelled"]);
62
+ function msToDuration(ms) {
63
+ const totalSec = Math.floor(ms / 1000);
64
+ const h = Math.floor(totalSec / 3600);
65
+ const m = Math.floor(totalSec % 3600 / 60);
66
+ const s = totalSec % 60;
67
+ return [h, m, s].map((v) => String(v).padStart(2, "0")).join(":");
68
+ }
69
+ function calcPassRate(passed, total) {
70
+ return total > 0 ? Math.round(passed / total * 1000) / 10 : 0;
71
+ }
72
+ var DEFAULT_TEST_CASE_VERSION = "1.0.0";
73
+ var PROJECT_CONFIG_FORBIDDEN_MESSAGE = "Forbidden (403). Exporting project configuration is a Test Cloud only feature, and this tenant is not a Test Cloud tenant. This is a licence limit, not a permissions problem.";
74
+ var SCHEMA_FORBIDDEN_MESSAGE = "Forbidden (403). Reading migration schemas needs the TM.Users or TM.Users.Read scope, which the other migration commands do not. Check the scopes on the token or external app you logged in with.";
75
+ var PROJECT_CONFIG_IMPORT_FORBIDDEN_MESSAGE = "Forbidden (403). Importing project configuration is a Test Cloud only feature, and this tenant is not a Test Cloud tenant. This is a licence limit, not a permissions problem.";
76
+ var TM_FORBIDDEN_MESSAGE = "Forbidden (403). The account lacks the Test Manager permission for this operation, or the token carries no Test Manager (TM.*) scope. Run `uip login status --detailed` to see the token's scopes; an external application needs the TM scopes granted on the app itself.";
77
+ var TM_LICENSED_USER_FORBIDDEN_MESSAGE = "Forbidden (403). This operation requires a Test Manager license. Contact your tenant admin to assign a license, or use a read-only command.";
78
+ var TM_TEST_CLOUD_FORBIDDEN_MESSAGE = "Forbidden (403). Group-by needs a Test Cloud licence for this account and the StructuredViewsGroupBy feature on the tenant, and the token must carry the TM.TestCases scope. On a tenant not yet on the current Test Manager build, an external application (client-credentials) token cannot call group-by at all; use a user login (`uip login`). Run `uip login status --detailed` to see the token's scopes, or ask your tenant admin about the licence.";
79
+ var TM_NOT_AVAILABLE_MESSAGE = "Test Manager is not enabled for this tenant.";
80
+ var TM_NOT_AVAILABLE_INSTRUCTIONS = "Enable Test Manager for this tenant, or rerun the command against a tenant where Test Manager is already provisioned.";
81
+ var TAGGED_UPLOAD_NOT_SUPPORTED_INSTRUCTIONS = "Test Manager refused the tagged upload with featureDisabled: --source and --attachment-type go to the tagged-upload endpoint, which needs a Test Manager feature the connected environment does not turn on. Drop --source and --attachment-type to attach the file untagged, or run the command against an environment where tagged uploads are turned on.";
82
+ function makeEnumParser(map) {
83
+ const allowed = Object.keys(map).join(", ");
84
+ return (raw) => {
85
+ if (!Object.hasOwn(map, raw)) {
86
+ throw new InvalidArgumentError(`Invalid value "${raw}". Must be one of: ${allowed}.`);
87
+ }
88
+ return map[raw];
89
+ };
90
+ }
91
+ var CUSTOMFIELD_OBJECT_TYPE_MAP = {
92
+ Requirement: "requirement",
93
+ TestCase: "testCase",
94
+ TestSet: "testSet"
95
+ };
96
+ var parseCustomFieldObjectType = makeEnumParser(CUSTOMFIELD_OBJECT_TYPE_MAP);
97
+ var CUSTOMFIELD_DATA_TYPE_MAP = {
98
+ Text: "text",
99
+ Label: "label"
100
+ };
101
+ var parseCustomFieldDataType = makeEnumParser(CUSTOMFIELD_DATA_TYPE_MAP);
102
+ function validateIdentity(spec) {
103
+ if (spec.naturalKey.length === 0) {
104
+ throw new Error("validateIdentity: naturalKey must contain at least one field.");
105
+ }
106
+ const hasPrimary = Array.isArray(spec.primary.value) ? spec.primary.value.length > 0 : spec.primary.value !== undefined && spec.primary.value !== "";
107
+ const naturalFlags = spec.naturalKey.map((f) => f.flag).join(" + ");
108
+ const supplied = spec.naturalKey.filter((f) => f.value !== undefined && f.value !== "");
109
+ const hasFullNatural = supplied.length === spec.naturalKey.length;
110
+ const hasAnyNatural = supplied.length > 0;
111
+ const hasPartialNatural = hasAnyNatural && !hasFullNatural;
112
+ if (!hasPrimary && !hasAnyNatural) {
113
+ return {
114
+ Result: "ValidationError",
115
+ Message: `Provide ${spec.primary.flag}, or ${naturalFlags}.`,
116
+ Instructions: `Pass ${spec.primary.flag}, or ${naturalFlags} to identify by natural key.`
117
+ };
118
+ }
119
+ if (hasPrimary && hasAnyNatural) {
120
+ return {
121
+ Result: "ValidationError",
122
+ Message: `${spec.primary.flag} and ${naturalFlags} are mutually exclusive identities.`,
123
+ Instructions: `Pass either ${spec.primary.flag}, or ${naturalFlags} — not both.`
124
+ };
125
+ }
126
+ if (hasPartialNatural) {
127
+ return {
128
+ Result: "ValidationError",
129
+ Message: `${naturalFlags} must all be supplied together.`,
130
+ Instructions: `Pass all of ${naturalFlags} to identify by natural key.`
131
+ };
132
+ }
133
+ return null;
134
+ }
135
+ async function findExactByNamePaged(fetchPage, match, options = {}) {
136
+ const pageSize = options.pageSize ?? 200;
137
+ const maxPages = options.maxPages ?? 20;
138
+ for (let pageIndex = 0;pageIndex < maxPages; pageIndex++) {
139
+ const page = await fetchPage(pageSize, pageIndex * pageSize);
140
+ const items = page.data ?? [];
141
+ const found = items.find(match);
142
+ if (found)
143
+ return found;
144
+ if (items.length < pageSize)
145
+ return null;
146
+ }
147
+ return null;
148
+ }
149
+ function splitKeys(raw) {
150
+ return raw.flatMap((k) => k.split(",")).map((k) => k.trim()).filter((k) => k.length > 0);
151
+ }
152
+ function parseTop(raw, flagName = "--top") {
153
+ const parsed = Number(raw);
154
+ if (raw.trim() === "" || Number.isNaN(parsed) || !Number.isInteger(parsed) || parsed < 0) {
155
+ throw new Error(`Invalid value for ${flagName}: "${raw}" must be a non-negative integer.`);
156
+ }
157
+ return parsed;
158
+ }
159
+ function parseSkip(raw, flagName = "--skip") {
160
+ const parsed = Number(raw);
161
+ if (raw.trim() === "" || Number.isNaN(parsed) || !Number.isInteger(parsed) || parsed < 0) {
162
+ throw new Error(`Invalid value for ${flagName}: "${raw}" must be a non-negative integer.`);
163
+ }
164
+ return parsed;
165
+ }
166
+ function resolvePaginationOptions(options, defaults = {
167
+ limit: "50",
168
+ offset: "0"
169
+ }) {
170
+ const limit = resolveDeprecatedOptionAlias({
171
+ preferredValue: options.limit,
172
+ deprecatedValue: options.top,
173
+ preferredFlag: "--limit",
174
+ deprecatedFlag: "--top"
175
+ });
176
+ if (limit.error) {
177
+ return { top: 0, skip: 0, error: limit.error };
178
+ }
179
+ const offset = resolveDeprecatedOptionAlias({
180
+ preferredValue: options.offset,
181
+ deprecatedValue: options.skip,
182
+ preferredFlag: "--offset",
183
+ deprecatedFlag: "--skip"
184
+ });
185
+ if (offset.error) {
186
+ return { top: 0, skip: 0, error: offset.error };
187
+ }
188
+ if (limit.usedDeprecated) {
189
+ warnDeprecatedOptionAlias("--top", "--limit");
190
+ }
191
+ if (offset.usedDeprecated) {
192
+ warnDeprecatedOptionAlias("--skip", "--offset");
193
+ }
194
+ const limitFlag = limit.usedDeprecated ? "--top" : "--limit";
195
+ const offsetFlag = offset.usedDeprecated ? "--skip" : "--offset";
196
+ try {
197
+ return {
198
+ top: parseTop(limit.value ?? defaults.limit, limitFlag),
199
+ skip: parseSkip(offset.value ?? defaults.offset, offsetFlag)
200
+ };
201
+ } catch (err) {
202
+ return {
203
+ top: 0,
204
+ skip: 0,
205
+ error: {
206
+ message: err instanceof Error ? err.message : String(err),
207
+ instructions: "Pass a non-negative integer, e.g. --limit 50 --offset 0."
208
+ }
209
+ };
210
+ }
211
+ }
212
+ function toPascalCase(key) {
213
+ if (!key)
214
+ return key;
215
+ return key.charAt(0).toUpperCase() + key.slice(1);
216
+ }
217
+ function toPascalCaseKeys(value) {
218
+ if (value === null || value === undefined)
219
+ return value;
220
+ if (Array.isArray(value))
221
+ return value.map(toPascalCaseKeys);
222
+ if (typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
223
+ const result = {};
224
+ for (const [k, v] of Object.entries(value)) {
225
+ result[toPascalCase(k)] = toPascalCaseKeys(v);
226
+ }
227
+ return result;
228
+ }
229
+ return value;
230
+ }
231
+ function hasText(value) {
232
+ return value !== null && value !== undefined && value.trim() !== "";
233
+ }
234
+ function sameGuid(a, b) {
235
+ return typeof a === "string" && typeof b === "string" && a.toLowerCase() === b.toLowerCase();
236
+ }
237
+ var TIMER_MAX_MS = 2147483647;
238
+ function resolveWaitTiming(options) {
239
+ const timeoutRaw = options.timeout ?? "";
240
+ const intervalRaw = options.pollInterval ?? "";
241
+ for (const [flag, raw] of [
242
+ ["--timeout", timeoutRaw],
243
+ ["--poll-interval", intervalRaw]
244
+ ]) {
245
+ if (raw.trim().length === 0) {
246
+ OutputFormatter.error({
247
+ Result: RESULTS.Failure,
248
+ Message: `${flag} was empty.`,
249
+ Instructions: `Pass a number of seconds, e.g. ${flag} ${flag === "--timeout" ? "1800" : "10"}.`,
250
+ ErrorCode: "invalid_argument",
251
+ Retry: "RetryWillNotFix"
252
+ });
253
+ processContext.exit(1);
254
+ return null;
255
+ }
256
+ }
257
+ const timeoutS = Number(timeoutRaw);
258
+ if (!Number.isFinite(timeoutS) || timeoutS < 0) {
259
+ OutputFormatter.error({
260
+ Result: RESULTS.Failure,
261
+ Message: `Invalid --timeout value: '${String(options.timeout)}'. Must be a non-negative number.`,
262
+ Instructions: "Pass seconds, e.g. --timeout 1800",
263
+ ErrorCode: "invalid_argument",
264
+ Retry: "RetryWillNotFix"
265
+ });
266
+ processContext.exit(1);
267
+ return null;
268
+ }
269
+ const intervalS = Number(intervalRaw);
270
+ if (!Number.isFinite(intervalS) || intervalS <= 0) {
271
+ OutputFormatter.error({
272
+ Result: RESULTS.Failure,
273
+ Message: `Invalid --poll-interval value: '${String(options.pollInterval)}'. Must be a positive number.`,
274
+ Instructions: "Pass seconds, e.g. --poll-interval 10",
275
+ ErrorCode: "invalid_argument",
276
+ Retry: "RetryWillNotFix"
277
+ });
278
+ processContext.exit(1);
279
+ return null;
280
+ }
281
+ const timeoutMs = timeoutS * 1000;
282
+ const intervalMs = intervalS * 1000;
283
+ if (intervalMs > TIMER_MAX_MS) {
284
+ OutputFormatter.error({
285
+ Result: RESULTS.Failure,
286
+ Message: `--poll-interval value '${intervalS}' is larger than the longest delay a timer can hold (${Math.floor(TIMER_MAX_MS / 1000)} seconds).`,
287
+ Instructions: "Pass a smaller number of seconds, e.g. --poll-interval 10.",
288
+ ErrorCode: "invalid_argument",
289
+ Retry: "RetryWillNotFix"
290
+ });
291
+ processContext.exit(1);
292
+ return null;
293
+ }
294
+ for (const [flag, seconds, ms] of [
295
+ ["--timeout", timeoutS, timeoutMs],
296
+ ["--poll-interval", intervalS, intervalMs]
297
+ ]) {
298
+ if (!Number.isFinite(ms)) {
299
+ OutputFormatter.error({
300
+ Result: RESULTS.Failure,
301
+ Message: `${flag} value '${seconds}' is too large to use as a duration.`,
302
+ Instructions: flag === "--timeout" ? "Pass a smaller number of seconds, e.g. --timeout 14400, or --timeout 0 for no ceiling." : "Pass a smaller number of seconds, e.g. --poll-interval 10.",
303
+ ErrorCode: "invalid_argument",
304
+ Retry: "RetryWillNotFix"
305
+ });
306
+ processContext.exit(1);
307
+ return null;
308
+ }
309
+ }
310
+ return { intervalMs, timeoutMs };
311
+ }
312
+
313
+ // src/utils/error-handler.ts
314
+ var TM_NOT_AVAILABLE_PATTERNS = [/testmanager not found in organization/i];
315
+ var FEATURE_DISABLED_PATTERN = /\bfeatureDisabled\b/i;
316
+ var TM_PORTAL_ROUTE_PATTERN = /\/portal_\//i;
317
+ var TM_PORTAL_SHELL_PATTERNS = [
318
+ /portalShellLoaded/i,
319
+ /window\.PortalShell\.initialize/i
320
+ ];
321
+ function hasKnownPortalShellMarkers(body) {
322
+ return TM_PORTAL_SHELL_PATTERNS.every((pattern) => pattern.test(body));
323
+ }
324
+ function isPortalShellDocument(body) {
325
+ return TM_PORTAL_ROUTE_PATTERN.test(body) && hasKnownPortalShellMarkers(body);
326
+ }
327
+ function shouldWarnAboutPortalShellDrift(result) {
328
+ return result.context?.httpStatus === 200 && isHtmlDocument(result.details) && TM_PORTAL_ROUTE_PATTERN.test(result.details) && !hasKnownPortalShellMarkers(result.details);
329
+ }
330
+ function isTmNotAvailableError(result) {
331
+ if (TM_NOT_AVAILABLE_PATTERNS.some((pattern) => pattern.test(result.details))) {
332
+ return true;
333
+ }
334
+ return result.context?.httpStatus === 200 && isHtmlDocument(result.details) && isPortalShellDocument(result.details);
335
+ }
336
+ function isFeatureDisabledError(result) {
337
+ return result.context?.httpStatus === 403 && FEATURE_DISABLED_PATTERN.test(`${result.context?.errorCode ?? ""} ${result.details}`);
338
+ }
339
+ async function extractErrorDetails2(error, options) {
340
+ const result = await extractErrorDetails(error, {
341
+ ...options,
342
+ forbiddenMessage: options?.forbiddenMessage ?? TM_FORBIDDEN_MESSAGE
343
+ });
344
+ if (isTmNotAvailableError(result)) {
345
+ return {
346
+ ...result,
347
+ message: TM_NOT_AVAILABLE_MESSAGE,
348
+ details: TM_NOT_AVAILABLE_INSTRUCTIONS
349
+ };
350
+ }
351
+ if (shouldWarnAboutPortalShellDrift(result)) {
352
+ logger.warn("Test Manager returned portal HTML with the expected route but without known shell markers. The Test Manager availability detector may need updating.");
353
+ }
354
+ return result;
355
+ }
356
+ async function emitTmFailure(error, exitCode = 1, options) {
357
+ const { instructionsSuffix, ...extractOptions } = options ?? {};
358
+ const classified = await extractErrorDetails2(error, {
359
+ ...extractOptions,
360
+ forbiddenMessage: extractOptions.forbiddenMessage ?? TM_FORBIDDEN_MESSAGE
361
+ });
362
+ emitTmFailureDetails(classified, exitCode, instructionsSuffix);
363
+ }
364
+ function emitTmFailureDetails(classified, exitCode = 1, instructionsSuffix) {
365
+ const { result, message, details, errorCode, retry } = classified;
366
+ const suffix = typeof instructionsSuffix === "function" ? instructionsSuffix(errorCode) : instructionsSuffix;
367
+ OutputFormatter.error({
368
+ Result: result,
369
+ ErrorCode: errorCode,
370
+ Message: message,
371
+ Instructions: suffix ? `${details} ${suffix}`.trim() : details,
372
+ Retry: retry
373
+ });
374
+ processContext.exit(EXIT_CODES[result] ?? exitCode);
375
+ }
376
+ async function refuseUnexpectedContentType(response, accept, expected, what) {
377
+ const contentType = response.raw.headers.get("content-type") ?? "";
378
+ if (contentType.trim() === "" || accept.test(contentType))
379
+ return false;
380
+ const responseError = Object.assign(new Error(`${what} returned content-type "${contentType || "<empty>"}"; expected ${expected}.`), { response: response.raw.clone() });
381
+ await emitTmFailure(responseError);
382
+ return true;
383
+ }
384
+ function emitInvalidArgument(message, instructions) {
385
+ OutputFormatter.error({
386
+ Result: RESULTS.ValidationError,
387
+ ErrorCode: "invalid_argument",
388
+ Message: message,
389
+ Instructions: instructions,
390
+ Retry: "RetryWillNotFix"
391
+ });
392
+ processContext.exit(1);
393
+ }
394
+ function emitAttachmentNotFound(attachmentId, objectType) {
395
+ OutputFormatter.error({
396
+ Result: RESULTS.Failure,
397
+ ErrorCode: "not_found",
398
+ Message: `Attachment '${attachmentId}' was not found for object type '${objectType}'.`,
399
+ Instructions: "Run 'uip tm attachment list' on the parent object to find its attachment ids, and check --object-type matches the object the file is attached to.",
400
+ Retry: "RetryWillNotFix"
401
+ });
402
+ processContext.exit(1);
403
+ }
404
+ function instructiveError(message, instructions, errorCode, retry = "RetryWillNotFix") {
405
+ const error = new Error(message);
406
+ error.instructions = instructions;
407
+ error.errorCode = errorCode;
408
+ error.retry = retry;
409
+ return error;
410
+ }
411
+ function readInstructions(error) {
412
+ const candidate = error;
413
+ return typeof candidate?.instructions === "string" ? candidate.instructions : undefined;
414
+ }
415
+ function readClassification(error) {
416
+ const candidate = error;
417
+ return {
418
+ errorCode: isCliErrorCode(candidate?.errorCode) ? candidate.errorCode : undefined,
419
+ retry: isRetryHint(candidate?.retry) ? candidate.retry : undefined
420
+ };
421
+ }
422
+
423
+ // src/utils/context.ts
424
+ function tmWebUrl(ctx) {
425
+ const org = encodeURIComponent(ctx.organizationName ?? ctx.organizationId);
426
+ const tenant = encodeURIComponent(ctx.tenantName);
427
+ return `${ctx.baseUrl}/${org}/${tenant}/testmanager_`;
428
+ }
429
+ function getStringField(record, key) {
430
+ const value = record[key];
431
+ if (typeof value !== "string") {
432
+ return;
433
+ }
434
+ const trimmed = value.trim();
435
+ return trimmed.length > 0 ? trimmed : undefined;
436
+ }
437
+ function stringifyProjectLookupPayload(payload) {
438
+ if (payload === undefined) {
439
+ return;
440
+ }
441
+ if (typeof payload === "string") {
442
+ return payload;
443
+ }
444
+ return JSON.stringify(payload);
445
+ }
446
+ function summarizeProjectLookupBody(body) {
447
+ const trimmed = body.trim();
448
+ if (trimmed.length === 0) {
449
+ return;
450
+ }
451
+ return trimmed.length > 500 ? `${trimmed.slice(0, 500)}...` : trimmed;
452
+ }
453
+ async function parseProjectLookupPayload(body) {
454
+ return JSON.parse(body);
455
+ }
456
+ async function getProjectLookupResult(projectKey, rawResponse) {
457
+ const responseBody = await rawResponse.text();
458
+ const trimmedBody = responseBody.trim();
459
+ if (trimmedBody.length === 0) {
460
+ return {
461
+ status: "failure",
462
+ failure: {
463
+ message: `Project lookup for '${projectKey}' returned an unexpected response.`,
464
+ instructions: "The service returned no project details."
465
+ }
466
+ };
467
+ }
468
+ const [parseError, project] = await catchError(parseProjectLookupPayload(trimmedBody));
469
+ if (parseError) {
470
+ return {
471
+ status: "failure",
472
+ failure: {
473
+ message: `Project lookup for '${projectKey}' returned a non-JSON success response.`,
474
+ instructions: summarizeProjectLookupBody(trimmedBody) ?? "The service returned a non-JSON payload."
475
+ }
476
+ };
477
+ }
478
+ if (!project || typeof project !== "object" || Array.isArray(project)) {
479
+ return {
480
+ status: "failure",
481
+ failure: {
482
+ message: `Project lookup for '${projectKey}' returned an unexpected response.`,
483
+ instructions: stringifyProjectLookupPayload(project) ?? "The service returned no project details."
484
+ }
485
+ };
486
+ }
487
+ const record = project;
488
+ const projectId = getStringField(record, "id");
489
+ if (projectId) {
490
+ return { status: "success", projectId };
491
+ }
492
+ const keys = Object.keys(record);
493
+ if (keys.length === 0) {
494
+ return {
495
+ status: "failure",
496
+ failure: {
497
+ message: `Project '${projectKey}' not found.`
498
+ }
499
+ };
500
+ }
501
+ const message = getStringField(record, "message") ?? getStringField(record, "errorMessage") ?? getStringField(record, "title");
502
+ const details = getStringField(record, "details");
503
+ const extraContext = Object.fromEntries(Object.entries(record).filter(([key, value]) => {
504
+ if (value === undefined) {
505
+ return false;
506
+ }
507
+ return ![
508
+ "id",
509
+ "message",
510
+ "errorMessage",
511
+ "title",
512
+ "details"
513
+ ].includes(key);
514
+ }));
515
+ const serializedExtraContext = Object.keys(extraContext).length > 0 ? JSON.stringify(extraContext) : undefined;
516
+ if (message) {
517
+ return {
518
+ status: "failure",
519
+ failure: {
520
+ message,
521
+ instructions: details ?? serializedExtraContext ?? message
522
+ }
523
+ };
524
+ }
525
+ return {
526
+ status: "failure",
527
+ failure: {
528
+ message: `Project lookup for '${projectKey}' returned an unexpected response.`,
529
+ instructions: details ?? serializedExtraContext ?? stringifyProjectLookupPayload(record)
530
+ }
531
+ };
532
+ }
533
+ function configureLoggerFromOptions(logLevel) {
534
+ const key = (logLevel ?? "Information").toUpperCase();
535
+ const lvl = LogLevel[key] ?? 1 /* INFO */;
536
+ configureLogger({ level: lvl });
537
+ }
538
+ async function resolveAuth(options) {
539
+ const authCtx = await getAuthContext({
540
+ tenant: options.tenant,
541
+ ensureTokenValidityMinutes: options.loginValidity,
542
+ requireOrganizationId: true,
543
+ requireTenantName: true
544
+ });
545
+ const organizationId = authCtx.organizationId;
546
+ const tenantName = authCtx.tenantName;
547
+ const tmBaseUrl = `${authCtx.baseUrl}/${organizationId}/${tenantName}/testmanager_`;
548
+ const tmConfig = new Configuration({
549
+ basePath: tmBaseUrl,
550
+ accessToken: authCtx.accessToken
551
+ });
552
+ return {
553
+ accessToken: authCtx.accessToken,
554
+ baseUrl: authCtx.baseUrl,
555
+ organizationId,
556
+ organizationName: authCtx.organizationName,
557
+ tenantName,
558
+ tmBaseUrl,
559
+ tmConfig
560
+ };
561
+ }
562
+ async function initializeContext(options) {
563
+ configureLoggerFromOptions(options.logLevel);
564
+ return resolveAuth(options);
565
+ }
566
+ function selectProject(options) {
567
+ if (options.projectId !== undefined) {
568
+ const projectId = options.projectId.trim();
569
+ if (projectId.length === 0) {
570
+ OutputFormatter.error({
571
+ Result: RESULTS.Failure,
572
+ Message: "--project-id was empty.",
573
+ Instructions: "Pass the project ID, or name the project with --project-key instead.",
574
+ ErrorCode: "invalid_argument",
575
+ Retry: "RetryWillNotFix"
576
+ });
577
+ processContext.exit(1);
578
+ return null;
579
+ }
580
+ return { kind: "id", projectId };
581
+ }
582
+ if (options.projectKey !== undefined) {
583
+ const projectKey = options.projectKey.trim();
584
+ if (projectKey.length === 0) {
585
+ OutputFormatter.error({
586
+ Result: RESULTS.Failure,
587
+ Message: "--project-key was empty.",
588
+ Instructions: "Pass the project key, or name the project with --project-id instead.",
589
+ ErrorCode: "invalid_argument",
590
+ Retry: "RetryWillNotFix"
591
+ });
592
+ processContext.exit(1);
593
+ return null;
594
+ }
595
+ return { kind: "key", projectKey };
596
+ }
597
+ const derivedKey = options.testSetKey?.split(":")[0]?.trim() || options.scenarioKey?.split(":")[0]?.trim();
598
+ if (!derivedKey) {
599
+ OutputFormatter.error({
600
+ Result: RESULTS.Failure,
601
+ Message: "No project was given.",
602
+ Instructions: "Pass --project-id or --project-key (or --test-set-key / --scenario-key, on the commands that take one).",
603
+ ErrorCode: "invalid_argument",
604
+ Retry: "RetryWillNotFix"
605
+ });
606
+ processContext.exit(1);
607
+ return null;
608
+ }
609
+ return { kind: "key", projectKey: derivedKey };
610
+ }
611
+ async function initializeContextWithProject(options) {
612
+ configureLoggerFromOptions(options.logLevel);
613
+ const selection = selectProject(options);
614
+ if (selection === null) {
615
+ return null;
616
+ }
617
+ const base = await resolveAuth(options);
618
+ if (selection.kind === "id") {
619
+ return {
620
+ ...base,
621
+ projectId: selection.projectId,
622
+ projectKey: undefined
623
+ };
624
+ }
625
+ const { projectKey } = selection;
626
+ const projectsApi = new ProjectsApi(base.tmConfig);
627
+ const [projectError, projectResponse] = await catchError(projectsApi.projectsGetProjectByProjectPrefixRaw({
628
+ projectPrefix: projectKey
629
+ }));
630
+ if (projectError) {
631
+ const { message, details } = await extractErrorDetails2(projectError, {
632
+ forbiddenMessage: TM_FORBIDDEN_MESSAGE
633
+ });
634
+ OutputFormatter.error({
635
+ Result: RESULTS.Failure,
636
+ Message: message,
637
+ Instructions: details
638
+ });
639
+ processContext.exit(1);
640
+ return null;
641
+ }
642
+ const projectLookup = await getProjectLookupResult(projectKey, projectResponse.raw);
643
+ if (projectLookup.status === "failure") {
644
+ OutputFormatter.error({
645
+ Result: RESULTS.Failure,
646
+ Message: projectLookup.failure.message,
647
+ ...projectLookup.failure.instructions ? { Instructions: projectLookup.failure.instructions } : {}
648
+ });
649
+ processContext.exit(1);
650
+ return null;
651
+ }
652
+ logger.info(`Resolved project '${projectKey}' → ${projectLookup.projectId}`);
653
+ return {
654
+ ...base,
655
+ projectId: projectLookup.projectId,
656
+ projectKey
657
+ };
658
+ }
659
+ async function resolveContextWithProject(options) {
660
+ const [authError, ctx] = await catchError(initializeContextWithProject(options));
661
+ if (authError) {
662
+ OutputFormatter.error({
663
+ Result: RESULTS.Failure,
664
+ Message: authError.message,
665
+ Instructions: instructionsFor("auth")
666
+ });
667
+ processContext.exit(1);
668
+ return null;
669
+ }
670
+ return ctx;
671
+ }
672
+ async function ensureProjectKey(ctx) {
673
+ if (ctx.projectKey !== undefined) {
674
+ return ctx.projectKey;
675
+ }
676
+ const projectsApi = new ProjectsApi(ctx.tmConfig);
677
+ const [error, project] = await catchError(projectsApi.projectsGetById({ id: ctx.projectId }));
678
+ if (error) {
679
+ const { result, errorCode, message, retry, details } = await extractErrorDetails2(error, {
680
+ forbiddenMessage: TM_FORBIDDEN_MESSAGE
681
+ });
682
+ OutputFormatter.error({
683
+ Result: result,
684
+ Message: message,
685
+ Instructions: details,
686
+ ErrorCode: errorCode,
687
+ Retry: retry
688
+ });
689
+ processContext.exit(1);
690
+ return null;
691
+ }
692
+ const projectKey = project.projectPrefix?.trim();
693
+ if (!projectKey) {
694
+ OutputFormatter.error({
695
+ Result: RESULTS.Failure,
696
+ Message: `Project '${ctx.projectId}' came back without a project key.`,
697
+ Instructions: "Name the project with --project-key instead of --project-id.",
698
+ ErrorCode: "server_error",
699
+ Retry: "RetryWillNotFix"
700
+ });
701
+ processContext.exit(1);
702
+ return null;
703
+ }
704
+ logger.info(`Resolved project ${ctx.projectId} → '${projectKey}'`);
705
+ return projectKey;
706
+ }
707
+
708
+ // src/mappers/input/migration.input.ts
709
+ var MIGRATION_TERMINAL_STATUSES = [
710
+ UiPathTestManagementHubProjectMigrationAbstractionsEnumsMigrationJobStatus.Completed,
711
+ UiPathTestManagementHubProjectMigrationAbstractionsEnumsMigrationJobStatus.Failed,
712
+ UiPathTestManagementHubProjectMigrationAbstractionsEnumsMigrationJobStatus.Cancelled
713
+ ];
714
+ function isMigrationTerminal(status) {
715
+ if (status === undefined)
716
+ return false;
717
+ const lowered = status.toLowerCase();
718
+ return MIGRATION_TERMINAL_STATUSES.some((terminal) => terminal.toLowerCase() === lowered);
719
+ }
720
+ function isMigrationCancelled(status) {
721
+ return status?.toLowerCase() === UiPathTestManagementHubProjectMigrationAbstractionsEnumsMigrationJobStatus.Cancelled.toString().toLowerCase();
722
+ }
723
+ function isMigrationCompleted(status) {
724
+ return status?.toLowerCase() === UiPathTestManagementHubProjectMigrationAbstractionsEnumsMigrationJobStatus.Completed.toString().toLowerCase();
725
+ }
726
+ var EXPORT_CONTENT = {
727
+ governance: {
728
+ field: "exportGovernanceInformation",
729
+ default: false
730
+ },
731
+ "project-config": {
732
+ field: "exportProjectConfiguration",
733
+ default: false
734
+ },
735
+ prompts: {
736
+ field: "exportUserDefinedPrompts",
737
+ default: false
738
+ },
739
+ automation: {
740
+ field: "includeAutomationInformation",
741
+ default: true
742
+ }
743
+ };
744
+ var EXPORT_CONTENT_CHOICES = Object.keys(EXPORT_CONTENT);
745
+ function toExportJobRequest(projectId, selection) {
746
+ const options = {};
747
+ for (const name of selection.include ?? []) {
748
+ options[EXPORT_CONTENT[name].field] = true;
749
+ }
750
+ for (const name of selection.exclude ?? []) {
751
+ options[EXPORT_CONTENT[name].field] = false;
752
+ }
753
+ return {
754
+ projectId,
755
+ uiPathTestManagementHubProjectMigrationAbstractionsRequestModelsCreateProjectExportJobRequest: { options }
756
+ };
757
+ }
758
+ function toJobGetRequest(projectId, jobId) {
759
+ return { id: jobId, projectId };
760
+ }
761
+ function toJobListRequest(filters) {
762
+ return {
763
+ ...filters.status ? {
764
+ jobStatus: filters.status
765
+ } : {},
766
+ ...filters.type ? { type: filters.type } : {},
767
+ ...filters.projectId ? { projectId: filters.projectId } : {},
768
+ ...filters.packageName ? { packageName: filters.packageName } : {},
769
+ ...filters.filter ? { search: filters.filter } : {},
770
+ ...filters.sortBy ? { orderby: filters.sortBy } : {},
771
+ top: filters.limit ?? 50,
772
+ skip: filters.offset ?? 0
773
+ };
774
+ }
775
+ var IMPORT_CONTENT = {
776
+ governance: {
777
+ field: "importGovernanceInformation",
778
+ default: false
779
+ },
780
+ "project-config": {
781
+ field: "importProjectConfiguration",
782
+ default: false
783
+ },
784
+ automation: {
785
+ field: "preserveAutomationInformation",
786
+ default: true
787
+ }
788
+ };
789
+ var IMPORT_CONTENT_CHOICES = Object.keys(IMPORT_CONTENT);
790
+ function toImportJobRequest(projectId, manifest, selection) {
791
+ const options = {};
792
+ for (const [name, row] of Object.entries(IMPORT_CONTENT)) {
793
+ const content = name;
794
+ options[row.field] = selection.include?.includes(content) ? true : selection.exclude?.includes(content) ? false : row.default;
795
+ }
796
+ return {
797
+ projectId,
798
+ uiPathTestManagementHubProjectMigrationAbstractionsRequestModelsCreateProjectImportJobRequest: {
799
+ manifest,
800
+ status: UiPathTestManagementHubProjectMigrationAbstractionsEnumsMigrationJobStatus.Uploading,
801
+ options
802
+ }
803
+ };
804
+ }
805
+ function toChunkUploadRequest(projectId, jobId, chunkName, bytes) {
806
+ const part = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
807
+ return {
808
+ projectId,
809
+ projectMigrationJobId: jobId,
810
+ file: new File([part], chunkName)
811
+ };
812
+ }
813
+ function toJobUpdateRequest(projectId, jobId, status) {
814
+ return {
815
+ projectId,
816
+ uiPathTestManagementHubProjectMigrationAbstractionsRequestModelsUpdateProjectMigrationJobRequest: { id: jobId, status }
817
+ };
818
+ }
819
+
820
+ // src/mappers/output/base.ts
821
+ function toOutput(value) {
822
+ return toPascalCaseKeys(value);
823
+ }
824
+ function toIsoDate(value) {
825
+ if (value === undefined || value === null)
826
+ return "";
827
+ return value instanceof Date ? value.toISOString() : String(value);
828
+ }
829
+
830
+ // src/mappers/output/migration.output.ts
831
+ function toMigrationJobOutput(job) {
832
+ return toOutput(job);
833
+ }
834
+ function toMigrationJobRows(jobs) {
835
+ return toOutput(jobs);
836
+ }
837
+ function toSchemaVersionRows(versions) {
838
+ return versions.map((version) => ({ SchemaVersion: version }));
839
+ }
840
+
841
+ // src/utils/migration-constants.ts
842
+ var PACKAGE_MEDIA_TYPES = new Set([
843
+ "application/octet-stream",
844
+ "application/zip",
845
+ "application/x-zip-compressed",
846
+ "application/vnd.uipath.tmh"
847
+ ]);
848
+ var ZIP_SIGNATURE = [80, 75, 3, 4];
849
+ var WRITE_FLUSH_BYTES = 8 * 1024 * 1024;
850
+ var BROWSER_MAX_PACKAGE_BYTES = 256 * 1024 * 1024;
851
+ var ERROR_BODY_PREFIX_BYTES = 1024;
852
+ var DEFAULT_JOB_SORT = "created desc";
853
+ var DEFAULT_EXPORT_TIMEOUT_MS = 1800000;
854
+ var DEFAULT_IMPORT_TIMEOUT_MS = 14400000;
855
+ var DEFAULT_MIGRATION_INTERVAL_MS = 1e4;
856
+ var CHUNK_UPLOAD_ATTEMPTS = 3;
857
+ var CHUNK_RETRY_BACKOFF_MS = 1000;
858
+ var CHUNK_SIZE_BYTES = 4 * 1024 * 1024;
859
+ var MAX_PACKAGE_NAME_LENGTH = 200;
860
+ var MAX_IMPORT_PACKAGE_BYTES = 2 ** 31 - 1;
861
+ var CHUNK_NOT_SENT_CODES = new Set([
862
+ "ECONNREFUSED",
863
+ "ENOTFOUND",
864
+ "EAI_AGAIN",
865
+ "ConnectionRefused"
866
+ ]);
867
+
868
+ // src/utils/refreshing-config.ts
869
+ var TOKEN_HEADROOM_MINUTES = 5;
870
+ function withRefreshingToken(base) {
871
+ return new Configuration({
872
+ basePath: base.basePath,
873
+ fetchApi: base.fetchApi,
874
+ middleware: base.middleware,
875
+ queryParamsStringify: base.queryParamsStringify,
876
+ headers: base.headers,
877
+ credentials: base.credentials,
878
+ accessToken: async () => (await getAuthContext({
879
+ ensureTokenValidityMinutes: TOKEN_HEADROOM_MINUTES
880
+ })).accessToken
881
+ });
882
+ }
883
+
884
+ // src/utils/filter-values.ts
885
+ function flagName(flag) {
886
+ return flag.startsWith("--") ? flag : `--${flag.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`;
887
+ }
888
+ function blankValueMessage(flag) {
889
+ return `${flagName(flag)} was given an empty value.`;
890
+ }
891
+ function findBlankFilter(options, flags) {
892
+ return flags.find((flag) => {
893
+ const value = options[flag];
894
+ if (typeof value === "string")
895
+ return value.trim() === "";
896
+ return Array.isArray(value) && value.some((entry) => typeof entry === "string" && entry.trim() === "");
897
+ });
898
+ }
899
+ function blankFilterGiven(options, flags) {
900
+ const blank = findBlankFilter(options, flags);
901
+ if (blank === undefined)
902
+ return false;
903
+ OutputFormatter.error({
904
+ Result: RESULTS.ValidationError,
905
+ ErrorCode: "invalid_argument",
906
+ Message: blankValueMessage(blank),
907
+ Instructions: `Pass a value, or leave ${flagName(blank)} out to match everything.`,
908
+ Retry: "RetryWillNotFix"
909
+ });
910
+ processContext.exit(EXIT_CODES.ValidationError);
911
+ return true;
912
+ }
913
+
914
+ // src/utils/output-target.ts
915
+ async function checkOutputTarget(outputFile, overwrite, wording) {
916
+ if (!outputFile?.trim()) {
917
+ emitInvalidArgument(`--output-file is required to write the ${wording.noun}.`, wording.missingHint);
918
+ return false;
919
+ }
920
+ const fs = getFileSystem();
921
+ const target = resolveOutputPath(outputFile);
922
+ const parent = fs.path.dirname(target);
923
+ if (!(await fs.stat(parent))?.isDirectory()) {
924
+ emitInvalidArgument(`Cannot write the ${wording.noun}: '${parent}' is not an existing directory.`, "Create the directory, or pass an --output-file inside one that already exists.");
925
+ return false;
926
+ }
927
+ const existing = await fs.stat(target);
928
+ if (existing?.isDirectory()) {
929
+ emitInvalidArgument(`'${outputFile}' is a directory; nothing was downloaded.`, `Pass a file path to --output-file, e.g. --output-file ${wording.example}.`);
930
+ return false;
931
+ }
932
+ if (existing && !overwrite) {
933
+ emitInvalidArgument(`'${outputFile}' already exists; nothing was downloaded.`, "Pass --overwrite to replace it, or choose another --output-file.");
934
+ return false;
935
+ }
936
+ return true;
937
+ }
938
+ function resolveOutputPath(outputFile) {
939
+ return getFileSystem().path.resolve(outputFile.trim());
940
+ }
941
+
942
+ // src/utils/project-scope.ts
943
+ function projectKeyOption(description = "Test Manager project key (e.g. DEMO)") {
944
+ return new Option("--project-key <key>", `${description}. Ignored if --project-id is also given.`);
945
+ }
946
+ function projectIdOption() {
947
+ return new Option("--project-id <id>", "Test Manager project ID. Use instead of --project-key, and wins if both are given.");
948
+ }
949
+
950
+ // src/commands/migration.ts
951
+ var MIGRATION_EXPORT_EXAMPLES = [
952
+ {
953
+ Description: "Export a whole project to a .tmh package, waiting for it and writing the file",
954
+ Command: "uip tm project export --project-id 9dfdc3ca-fc75-0100-2aae-0b46e318b723 --wait --output-file demo.tmh",
955
+ Output: {
956
+ Code: "MigrationExport",
957
+ Data: {
958
+ Id: "a1b2c3d4-0000-0000-0000-000000000001",
959
+ Type: "ExportProject",
960
+ Status: "Completed",
961
+ OutputFile: "demo.tmh",
962
+ Bytes: 481203
963
+ }
964
+ }
965
+ },
966
+ {
967
+ Description: "Export by project key instead of id, with governance information but without automation links, handing back the job id to poll yourself",
968
+ Command: "uip tm project export --project-key DEMO --include governance --exclude automation",
969
+ Output: {
970
+ Code: "MigrationExport",
971
+ Data: {
972
+ Id: "a1b2c3d4-0000-0000-0000-000000000001",
973
+ Type: "ExportProject",
974
+ Status: "Ready",
975
+ Created: "2026-09-17T10:00:00.000Z",
976
+ Updated: "2026-09-17T10:00:00.000Z",
977
+ CreatedBy: "c3d4e5f6-0000-0000-0000-000000000003",
978
+ UpdatedBy: "c3d4e5f6-0000-0000-0000-000000000003",
979
+ ProjectId: "b2c3d4e5-0000-0000-0000-000000000002",
980
+ TenantId: "d4e5f6a7-0000-0000-0000-000000000004"
981
+ }
982
+ }
983
+ }
984
+ ];
985
+ var MIGRATION_JOB_GET_EXAMPLES = [
986
+ {
987
+ Description: "Get the status of a migration job",
988
+ Command: "uip tm migration get --project-id 9dfdc3ca-fc75-0100-2aae-0b46e318b723 --job-id a1b2c3d4-0000-0000-0000-000000000001",
989
+ Output: {
990
+ Code: "MigrationJobGet",
991
+ Data: {
992
+ Id: "a1b2c3d4-0000-0000-0000-000000000001",
993
+ Type: "ExportProject",
994
+ Status: "Processing",
995
+ ProjectId: "b2c3d4e5-0000-0000-0000-000000000002",
996
+ TenantId: "d4e5f6a7-0000-0000-0000-000000000004",
997
+ PackageName: "DEMO.tmh",
998
+ PackageSize: 481203,
999
+ SchemaVersion: "1.4",
1000
+ TmPackageId: null,
1001
+ Created: "2026-09-17T10:00:00.000Z",
1002
+ CreatedBy: "c3d4e5f6-0000-0000-0000-000000000003",
1003
+ Updated: "2026-09-17T10:00:12.000Z",
1004
+ UpdatedBy: "c3d4e5f6-0000-0000-0000-000000000003",
1005
+ ExecutionStarted: "2026-09-17T10:00:05.000Z",
1006
+ ExecutionFinished: null
1007
+ }
1008
+ }
1009
+ }
1010
+ ];
1011
+ var MIGRATION_JOB_LIST_EXAMPLES = [
1012
+ {
1013
+ Description: "Find a project's most recent export jobs, newest first — how to recover a job id you no longer have",
1014
+ Command: "uip tm migration list --project-key DEMO --type exportProject --limit 10",
1015
+ Output: {
1016
+ Code: "MigrationJobList",
1017
+ Data: [
1018
+ {
1019
+ Id: "a1b2c3d4-0000-0000-0000-000000000001",
1020
+ Type: "ExportProject",
1021
+ Status: "Failed",
1022
+ ProjectId: "b2c3d4e5-0000-0000-0000-000000000002",
1023
+ TenantId: "d4e5f6a7-0000-0000-0000-000000000004",
1024
+ PackageName: "DEMO.tmh",
1025
+ PackageSize: null,
1026
+ SchemaVersion: "1.4",
1027
+ TmPackageId: null,
1028
+ Created: "2026-09-17T09:00:00.000Z",
1029
+ CreatedBy: "c3d4e5f6-0000-0000-0000-000000000003",
1030
+ Updated: "2026-09-17T09:01:00.000Z",
1031
+ UpdatedBy: "c3d4e5f6-0000-0000-0000-000000000003",
1032
+ ExecutionStarted: "2026-09-17T09:00:30.000Z",
1033
+ ExecutionFinished: "2026-09-17T09:01:00.000Z"
1034
+ }
1035
+ ]
1036
+ }
1037
+ }
1038
+ ];
1039
+ var MIGRATION_JOB_DOWNLOAD_EXAMPLES = [
1040
+ {
1041
+ Description: "Fetch the package from an export that already finished, without exporting again",
1042
+ Command: "uip tm migration download --project-id 9dfdc3ca-fc75-0100-2aae-0b46e318b723 --job-id a1b2c3d4-0000-0000-0000-000000000001 --output-file demo.tmh",
1043
+ Output: {
1044
+ Code: "MigrationJobDownload",
1045
+ Data: {
1046
+ JobId: "a1b2c3d4-0000-0000-0000-000000000001",
1047
+ OutputFile: "demo.tmh",
1048
+ Bytes: 481203
1049
+ }
1050
+ }
1051
+ }
1052
+ ];
1053
+ function describeContentDefaults(table) {
1054
+ const entries = Object.entries(table);
1055
+ const named = (on) => entries.filter(([, v]) => v.default === on).map(([k]) => k).join(", ");
1056
+ return `One or more of: ${Object.keys(table).join(", ")}. By default ${named(true)} is included and ${named(false)} are not. project-config needs a Test Cloud tenant; other tenants reject it with HTTP 403.`;
1057
+ }
1058
+ function checkContentSelection(selection) {
1059
+ const excluded = new Set(selection.exclude ?? []);
1060
+ const both = (selection.include ?? []).filter((name) => excluded.has(name));
1061
+ if (both.length === 0)
1062
+ return true;
1063
+ emitInvalidArgument(`${both.join(", ")} cannot be both included and excluded.`, "Name each piece of content in --include or --exclude, not both.");
1064
+ return false;
1065
+ }
1066
+ var PACKAGE_WORDING = {
1067
+ noun: "package",
1068
+ example: "demo.tmh",
1069
+ missingHint: "Pass --output-file <path>. For an export, drop --wait instead to get the job id and download it later."
1070
+ };
1071
+ async function emitPollFailure(result, projectId, jobId, kind, targetHint) {
1072
+ const mapped = mapPollFailure(result, `${kind} job '${jobId}'`);
1073
+ const lastStatus = String(result.data?.status ?? "unknown");
1074
+ const classified = mapped.errorCode || !result.error ? undefined : await extractErrorDetails2(result.error);
1075
+ const pollResult = mapped.errorCode ? RESULTS.Failure : classified?.result ?? RESULTS.Failure;
1076
+ OutputFormatter.error({
1077
+ Result: pollResult,
1078
+ Message: `${mapped.message} after ${Math.round(result.elapsedMs / 1000)}s. Last status: ${lastStatus}.`,
1079
+ Instructions: `${JOB_ENDINGS[kind].stoppedWatching} ${recheckJobHint(projectId, jobId)}${targetHint}`,
1080
+ ErrorCode: mapped.errorCode ?? classified?.errorCode,
1081
+ Retry: kind === "Import" ? "RetryWillNotFix" : mapped.retry ?? classified?.retry
1082
+ });
1083
+ processContext.exit(mapped.errorCode ? mapped.exitCode : EXIT_CODES[pollResult] ?? mapped.exitCode);
1084
+ }
1085
+ function emitJobEnding(kind, jobId, finalStatus, targetHint) {
1086
+ const ending = JOB_ENDINGS[kind];
1087
+ if (isMigrationCancelled(finalStatus)) {
1088
+ OutputFormatter.error({
1089
+ Result: RESULTS.Failure,
1090
+ Message: `${kind} job '${jobId}' ${ending.cancelled.message}.`,
1091
+ Instructions: `${ending.cancelled.instructions}${targetHint}`,
1092
+ Retry: "RetryWillNotFix"
1093
+ });
1094
+ } else {
1095
+ OutputFormatter.error({
1096
+ Result: RESULTS.Failure,
1097
+ Message: `${kind} job '${jobId}' ended as ${finalStatus || "an unknown state"} rather than Completed.`,
1098
+ Instructions: `${ending.failed.instructions}${targetHint}`,
1099
+ ErrorCode: "server_error",
1100
+ Retry: ending.failed.retry
1101
+ });
1102
+ }
1103
+ processContext.exit(1);
1104
+ }
1105
+ var JOB_ENDINGS = {
1106
+ Export: {
1107
+ stoppedWatching: "Nothing was written.",
1108
+ cancelled: {
1109
+ message: "was cancelled, so there is no package",
1110
+ instructions: "Nothing was written. Start a new export if you still need the package."
1111
+ },
1112
+ failed: {
1113
+ instructions: "Nothing was written. Re-run the export; if it fails again, the service logs hold the reason.",
1114
+ retry: "RetryLater"
1115
+ }
1116
+ },
1117
+ Import: {
1118
+ stoppedWatching: "The package is uploaded and the import carries on in the background.",
1119
+ cancelled: {
1120
+ message: "was cancelled: by a user, because the target project or tenant no longer exists, or because it waited too long to start",
1121
+ instructions: "Check the target project still exists and what it already holds before importing again."
1122
+ },
1123
+ failed: {
1124
+ instructions: "The target project may now hold part of the import. Check it, or delete it, before importing again, or import into a fresh project with --create-project and a new --new-project-key.",
1125
+ retry: "RetryWillNotFix"
1126
+ }
1127
+ }
1128
+ };
1129
+ async function emitImportPollError(error, projectId, jobId, targetHint) {
1130
+ const { result, message, details, errorCode } = await extractErrorDetails2(error, { forbiddenMessage: TM_FORBIDDEN_MESSAGE });
1131
+ OutputFormatter.error({
1132
+ Result: result,
1133
+ Message: message,
1134
+ Instructions: `${details} ${JOB_ENDINGS.Import.stoppedWatching} ${recheckJobHint(projectId, jobId)}${targetHint}`.trim(),
1135
+ ErrorCode: errorCode,
1136
+ Retry: "RetryWillNotFix"
1137
+ });
1138
+ processContext.exit(EXIT_CODES[result] ?? 1);
1139
+ }
1140
+ async function waitForMigrationJob(jobApi, projectId, jobId, timing, kind, targetHint = "") {
1141
+ const [pollError, result] = await catchError(pollUntil({
1142
+ fn: () => jobApi.projectMigrationJobGetById(toJobGetRequest(projectId, jobId)),
1143
+ until: (j) => isMigrationTerminal(j.status),
1144
+ getStatus: (j) => String(j.status ?? "None"),
1145
+ label: `migration job ${jobId}`,
1146
+ logPrefix: "migration",
1147
+ intervalMs: timing.intervalMs,
1148
+ timeoutMs: timing.timeoutMs,
1149
+ logIntervalMs: timing.intervalMs,
1150
+ maxConsecutiveErrors: 3,
1151
+ signal: processContext.pollSignal
1152
+ }));
1153
+ if (pollError) {
1154
+ if (kind === "Import") {
1155
+ await emitImportPollError(pollError, projectId, jobId, targetHint);
1156
+ } else {
1157
+ await emitTmFailure(pollError, undefined, {
1158
+ instructionsSuffix: recheckJobHint(projectId, jobId)
1159
+ });
1160
+ }
1161
+ return null;
1162
+ }
1163
+ if (result.outcome !== PollOutcome.Completed) {
1164
+ await emitPollFailure(result, projectId, jobId, kind, targetHint);
1165
+ return null;
1166
+ }
1167
+ const finished = result.data;
1168
+ const finalStatus = String(finished?.status ?? "");
1169
+ if (!isMigrationCompleted(finalStatus)) {
1170
+ emitJobEnding(kind, jobId, finalStatus, targetHint);
1171
+ return null;
1172
+ }
1173
+ return finished ?? null;
1174
+ }
1175
+ async function emitExportCreateFailure(error, askedForProjectConfig) {
1176
+ const { result, message, details, errorCode, retry } = await extractErrorDetails2(error, {
1177
+ forbiddenMessage: TM_FORBIDDEN_MESSAGE
1178
+ });
1179
+ const isProjectConfigGate = askedForProjectConfig && errorCode === "permission_denied" && /project configuration/i.test(details);
1180
+ OutputFormatter.error({
1181
+ Result: result,
1182
+ Message: isProjectConfigGate ? PROJECT_CONFIG_FORBIDDEN_MESSAGE : message,
1183
+ Instructions: isProjectConfigGate ? "Drop project-config from --include, or run this against a Test Cloud tenant." : details,
1184
+ ErrorCode: errorCode,
1185
+ Retry: retry
1186
+ });
1187
+ processContext.exit(EXIT_CODES[result] ?? 1);
1188
+ }
1189
+ function recheckJobHint(projectId, jobId) {
1190
+ return `Re-check it with: uip tm migration get --project-id ${projectId} --job-id ${jobId}`;
1191
+ }
1192
+ function nextStepHint(projectId, jobId) {
1193
+ return `The export runs in the background. Check it with: uip tm migration get --project-id ${projectId} --job-id ${jobId}. Once it reads Completed, fetch the package with: uip tm migration download --project-id ${projectId} --job-id ${jobId} --output-file <path>`;
1194
+ }
1195
+ function downloadRefusedHint(projectId, jobId) {
1196
+ return `Check the job with: uip tm migration get --project-id ${projectId} --job-id ${jobId}. If it reads Completed, the package has most likely expired, or the job was a partial export, which this command cannot fetch.`;
1197
+ }
1198
+ async function downloadPackage(tmConfig, projectId, jobId, outputFile, overwrite, hints = {}) {
1199
+ const fetchHint = hints.onFetchFailure ?? retryDownloadHint(jobId);
1200
+ const afterFetchHint = hints.afterFetch ?? retryDownloadHint(jobId);
1201
+ const attachmentApi = new ProjectMigrationAttachmentApi(tmConfig);
1202
+ const [downloadError, response] = await catchError(attachmentApi.projectMigrationAttachmentDownloadProjectPackageRaw({
1203
+ migrationJobId: jobId,
1204
+ projectId
1205
+ }));
1206
+ if (downloadError) {
1207
+ await emitTmFailure(downloadError, undefined, {
1208
+ instructionsSuffix: fetchHint
1209
+ });
1210
+ return null;
1211
+ }
1212
+ return writeZipResponse(response.raw, outputFile, {
1213
+ overwrite,
1214
+ what: `Package for job '${jobId}'`,
1215
+ refetchCommand: `uip tm migration download --project-id ${projectId} --job-id ${jobId} --output-file <path>`,
1216
+ afterFetchHint
1217
+ });
1218
+ }
1219
+ async function writeZipResponse(raw, outputFile, target) {
1220
+ const contentType = raw.headers.get("content-type") ?? "";
1221
+ const mediaType = contentType.split(";")[0].trim().toLowerCase();
1222
+ if (!PACKAGE_MEDIA_TYPES.has(mediaType)) {
1223
+ const [, bodyText] = await catchError(readBodyPrefix(raw));
1224
+ const snippet = (bodyText ?? "").trim().slice(0, 200);
1225
+ emitNotAPackage(`${target.what} came back as HTTP ${raw.status} with content-type "${contentType || "<empty>"}"; expected a zip.`, `${target.afterFetchHint}${snippet ? ` The response body began: ${snippet}` : ""}`);
1226
+ return null;
1227
+ }
1228
+ return writePackage(raw, outputFile, target);
1229
+ }
1230
+ async function writePackage(raw, outputFile, target) {
1231
+ const fs = getFileSystem();
1232
+ const partial = `${outputFile}.${crypto.randomUUID()}.partial`;
1233
+ const [streamError, streamed] = await catchError(streamZipTo(raw, partial));
1234
+ if (streamError || streamed.status !== "ok") {
1235
+ await catchError(fs.rm(partial));
1236
+ if (streamError) {
1237
+ await emitTmFailure(streamError, undefined, {
1238
+ instructionsSuffix: target.afterFetchHint
1239
+ });
1240
+ } else {
1241
+ emitUnwritable(streamed, target);
1242
+ }
1243
+ return null;
1244
+ }
1245
+ const moved = await movePartialIntoPlace(partial, outputFile, target);
1246
+ return moved ? streamed.bytes : null;
1247
+ }
1248
+ function emitUnwritable(streamed, target) {
1249
+ if (streamed.status === "too-large") {
1250
+ OutputFormatter.error({
1251
+ Result: RESULTS.Failure,
1252
+ Message: `${target.what} is larger than this browser host can hold (${BROWSER_MAX_PACKAGE_BYTES / (1024 * 1024)} MiB). Nothing was written.`,
1253
+ Instructions: `Download it with the uip CLI in a terminal: ${target.refetchCommand}`,
1254
+ Retry: "RetryWillNotFix"
1255
+ });
1256
+ processContext.exit(1);
1257
+ return;
1258
+ }
1259
+ emitNotAPackage(`${target.what} did not come back as a zip: it is ${streamed.bytes === 0 ? "empty" : "not a zip archive"}. Nothing was written.`, target.afterFetchHint);
1260
+ }
1261
+ async function readBodyPrefix(raw) {
1262
+ const parts = [];
1263
+ let length = 0;
1264
+ for await (const chunk of bodyChunks(raw)) {
1265
+ parts.push(chunk);
1266
+ length += chunk.byteLength;
1267
+ if (length >= ERROR_BODY_PREFIX_BYTES)
1268
+ break;
1269
+ }
1270
+ const prefix = concatChunks(parts, length).subarray(0, ERROR_BODY_PREFIX_BYTES);
1271
+ return new TextDecoder().decode(prefix);
1272
+ }
1273
+ async function* bodyChunks(raw) {
1274
+ const reader = raw.body?.getReader();
1275
+ if (!reader) {
1276
+ yield new Uint8Array(await raw.arrayBuffer());
1277
+ return;
1278
+ }
1279
+ let finished = false;
1280
+ try {
1281
+ for (;; ) {
1282
+ const { done, value } = await reader.read();
1283
+ if (done) {
1284
+ finished = true;
1285
+ return;
1286
+ }
1287
+ yield value;
1288
+ }
1289
+ } finally {
1290
+ if (!finished)
1291
+ await catchError(reader.cancel());
1292
+ }
1293
+ }
1294
+ async function streamZipTo(raw, partial) {
1295
+ const browser = inBrowser();
1296
+ const head = [];
1297
+ let headBytes = 0;
1298
+ let total = 0;
1299
+ let appender;
1300
+ for await (const chunk of bodyChunks(raw)) {
1301
+ total += chunk.byteLength;
1302
+ if (browser && total > BROWSER_MAX_PACKAGE_BYTES) {
1303
+ return { status: "too-large", bytes: total };
1304
+ }
1305
+ if (appender) {
1306
+ await appender.push(chunk);
1307
+ continue;
1308
+ }
1309
+ head.push(chunk);
1310
+ headBytes += chunk.byteLength;
1311
+ if (headBytes < ZIP_SIGNATURE.length)
1312
+ continue;
1313
+ const first = concatChunks(head, headBytes);
1314
+ if (!startsWithZipSignature(first)) {
1315
+ return { status: "not-zip", bytes: total };
1316
+ }
1317
+ appender = await ChunkAppender.start(partial, first, browser);
1318
+ }
1319
+ if (!appender)
1320
+ return { status: "not-zip", bytes: total };
1321
+ await appender.close();
1322
+ return { status: "ok", bytes: total };
1323
+ }
1324
+ function inBrowser() {
1325
+ const runtime = globalThis;
1326
+ return typeof runtime.window !== "undefined" && typeof runtime.document !== "undefined";
1327
+ }
1328
+
1329
+ class ChunkAppender {
1330
+ path;
1331
+ holdAll;
1332
+ pending = [];
1333
+ pendingBytes = 0;
1334
+ written = false;
1335
+ constructor(path, holdAll) {
1336
+ this.path = path;
1337
+ this.holdAll = holdAll;
1338
+ }
1339
+ static async start(path, first, holdAll) {
1340
+ const appender = new ChunkAppender(path, holdAll);
1341
+ await appender.push(first);
1342
+ if (!holdAll)
1343
+ await appender.flush();
1344
+ return appender;
1345
+ }
1346
+ async push(chunk) {
1347
+ this.pending.push(chunk);
1348
+ this.pendingBytes += chunk.byteLength;
1349
+ if (!this.holdAll && this.pendingBytes >= WRITE_FLUSH_BYTES) {
1350
+ await this.flush();
1351
+ }
1352
+ }
1353
+ async close() {
1354
+ await this.flush();
1355
+ }
1356
+ async flush() {
1357
+ if (this.pendingBytes === 0)
1358
+ return;
1359
+ const chunk = concatChunks(this.pending, this.pendingBytes);
1360
+ this.pending = [];
1361
+ this.pendingBytes = 0;
1362
+ const fs = getFileSystem();
1363
+ if (this.written) {
1364
+ await fs.appendFile(this.path, chunk);
1365
+ } else {
1366
+ await fs.writeFile(this.path, chunk);
1367
+ this.written = true;
1368
+ }
1369
+ }
1370
+ }
1371
+ async function movePartialIntoPlace(partial, outputFile, target) {
1372
+ const fs = getFileSystem();
1373
+ const [lockError, release] = await catchError(fs.acquireLock(outputFile));
1374
+ if (lockError) {
1375
+ await catchError(fs.rm(partial));
1376
+ await emitTmFailure(lockError, undefined, {
1377
+ instructionsSuffix: target.afterFetchHint
1378
+ });
1379
+ return false;
1380
+ }
1381
+ try {
1382
+ return await replaceOnlyIfAllowed(partial, outputFile, target);
1383
+ } finally {
1384
+ await catchError(release());
1385
+ }
1386
+ }
1387
+ async function replaceOnlyIfAllowed(partial, outputFile, target) {
1388
+ const fs = getFileSystem();
1389
+ if (!target.overwrite && await fs.exists(outputFile)) {
1390
+ await catchError(fs.rm(partial));
1391
+ emitInvalidArgument(`'${outputFile}' appeared during the download; nothing was replaced.`, `Pass --overwrite to replace it, or fetch it to another path with: ${target.refetchCommand}`);
1392
+ return false;
1393
+ }
1394
+ const [renameError] = await catchError(fs.rename(partial, outputFile));
1395
+ if (renameError) {
1396
+ await catchError(fs.rm(partial));
1397
+ await emitTmFailure(renameError, undefined, {
1398
+ instructionsSuffix: target.afterFetchHint
1399
+ });
1400
+ return false;
1401
+ }
1402
+ return true;
1403
+ }
1404
+ function concatChunks(chunks, length) {
1405
+ if (chunks.length === 1)
1406
+ return chunks[0];
1407
+ const out = new Uint8Array(length);
1408
+ let offset = 0;
1409
+ for (const chunk of chunks) {
1410
+ out.set(chunk, offset);
1411
+ offset += chunk.byteLength;
1412
+ }
1413
+ return out;
1414
+ }
1415
+ function startsWithZipSignature(bytes) {
1416
+ return ZIP_SIGNATURE.every((b, i) => bytes[i] === b);
1417
+ }
1418
+ function emitNotAPackage(message, instructions) {
1419
+ OutputFormatter.error({
1420
+ Result: RESULTS.Failure,
1421
+ Message: message,
1422
+ Instructions: instructions,
1423
+ ErrorCode: "server_error",
1424
+ Retry: "RetryLater"
1425
+ });
1426
+ processContext.exit(1);
1427
+ }
1428
+ function retryDownloadHint(jobId) {
1429
+ return `The export itself finished — job '${jobId}' still holds the package on the server.`;
1430
+ }
1431
+ function isExportJob(type) {
1432
+ return String(type ?? "").toLowerCase() === UiPathTestManagementHubProjectMigrationAbstractionsEnumsMigrationJobType.ExportProject.toString().toLowerCase();
1433
+ }
1434
+ async function readProjectJob(ctx, jobId) {
1435
+ if (await ensureProjectKey(ctx) === null)
1436
+ return null;
1437
+ const { tmConfig, projectId } = ctx;
1438
+ const [error, response] = await catchError(new ProjectMigrationJobApi(tmConfig).projectMigrationJobGetByIdRaw(toJobGetRequest(projectId, jobId)));
1439
+ if (error) {
1440
+ await emitTmFailure(error);
1441
+ return null;
1442
+ }
1443
+ let job;
1444
+ if (response.raw.status !== 204) {
1445
+ const [parseError, parsed] = await catchError(response.value());
1446
+ if (parseError) {
1447
+ await emitTmFailure(parseError);
1448
+ return null;
1449
+ }
1450
+ job = parsed;
1451
+ }
1452
+ if (!job || !sameGuid(job.projectId, projectId)) {
1453
+ OutputFormatter.error({
1454
+ Result: RESULTS.Failure,
1455
+ Message: `Migration job '${jobId}' was not found in project ${projectId}.`,
1456
+ Instructions: `Check the job id and the project. \`uip tm migration list --project-id ${projectId}\` shows this project's jobs.`,
1457
+ ErrorCode: "not_found",
1458
+ Retry: "RetryWillNotFix"
1459
+ });
1460
+ processContext.exit(1);
1461
+ return null;
1462
+ }
1463
+ return job;
1464
+ }
1465
+ var registerProjectExportCommand = (parent) => {
1466
+ parent.command("export").description("Export a project to a .tmh package. The service runs this as a background job with no push notification, so this returns the job id to poll yourself unless --wait is given, in which case it polls until the job finishes and writes the file.").addOption(projectKeyOption()).addOption(projectIdOption()).option("--output-file <path>", "Where to write the .tmh package. Required with --wait.").option("--overwrite", "Replace --output-file if it already exists. Without it, an existing file is refused before the export starts").addOption(new Option("--include <content...>", `Content to add to the package, space-separated. ${describeContentDefaults(EXPORT_CONTENT)}`).choices(EXPORT_CONTENT_CHOICES)).addOption(new Option("--exclude <content...>", `Content to leave out of the package, space-separated. ${describeContentDefaults(EXPORT_CONTENT)}`).choices(EXPORT_CONTENT_CHOICES)).option("--wait", "Poll until the export finishes and download the package to --output-file").option("--timeout <seconds>", "Maximum seconds to wait (0 = no timeout). Requires --wait.", String(DEFAULT_EXPORT_TIMEOUT_MS / 1000)).option("--poll-interval <seconds>", "Seconds between status checks. Requires --wait.", String(DEFAULT_MIGRATION_INTERVAL_MS / 1000)).addOption(createHiddenDeprecatedTenantOption("-t, --tenant <tenant-name>")).option("--log-level <level>", "Log verbosity: debug, info, warn, error", "Information").examples(MIGRATION_EXPORT_EXAMPLES).trackedAction(processContext, async (options) => {
1467
+ const selection = {
1468
+ include: options.include,
1469
+ exclude: options.exclude
1470
+ };
1471
+ if (!checkContentSelection(selection))
1472
+ return;
1473
+ const timing = await prepareWait(options);
1474
+ if (timing === null)
1475
+ return;
1476
+ const ctx = await resolveContextWithProject(options);
1477
+ if (!ctx)
1478
+ return;
1479
+ const { tmConfig, projectId } = ctx;
1480
+ if (!timing)
1481
+ warnIgnoredWaitOptions(options);
1482
+ const [startError, job] = await catchError(new ProjectMigrationJobApi(tmConfig).projectMigrationJobCreateProjectExportJob(toExportJobRequest(projectId, selection)));
1483
+ if (startError) {
1484
+ await emitExportCreateFailure(startError, selection.include?.includes("project-config") === true);
1485
+ return;
1486
+ }
1487
+ if (!job.id) {
1488
+ emitMissingJobId(projectId);
1489
+ return;
1490
+ }
1491
+ if (!timing) {
1492
+ const output = new SuccessOutput("MigrationExport", toMigrationJobOutput(job));
1493
+ output.Instructions = nextStepHint(projectId, job.id);
1494
+ OutputFormatter.success(output);
1495
+ return;
1496
+ }
1497
+ await finishWaitedExport(tmConfig, projectId, job.id, timing, options);
1498
+ });
1499
+ };
1500
+ async function prepareWait(options) {
1501
+ if (!options.wait)
1502
+ return;
1503
+ if (!await checkOutputTarget(options.outputFile, options.overwrite === true, PACKAGE_WORDING)) {
1504
+ return null;
1505
+ }
1506
+ return resolveWaitTiming(options);
1507
+ }
1508
+ function warnIgnoredWaitOptions(options) {
1509
+ const ignored = options.outputFile !== undefined || options.overwrite !== undefined || options.timeout !== String(DEFAULT_EXPORT_TIMEOUT_MS / 1000) || options.pollInterval !== String(DEFAULT_MIGRATION_INTERVAL_MS / 1000);
1510
+ if (ignored) {
1511
+ logger.warn("--output-file, --overwrite, --timeout and --poll-interval have no effect without --wait; the job id is returned instead.");
1512
+ }
1513
+ }
1514
+ function emitMissingJobId(projectId) {
1515
+ OutputFormatter.error({
1516
+ Result: RESULTS.Failure,
1517
+ Message: "The export job was created but the service did not return its id.",
1518
+ Instructions: `Find it with: uip tm migration list --project-id ${projectId} --type exportProject --sort-by "${DEFAULT_JOB_SORT}" --limit 5`,
1519
+ ErrorCode: "server_error",
1520
+ Retry: "RetryLater"
1521
+ });
1522
+ processContext.exit(1);
1523
+ }
1524
+ async function finishWaitedExport(tmConfig, projectId, jobId, timing, options) {
1525
+ const waitConfig = withRefreshingToken(tmConfig);
1526
+ const finished = await waitForMigrationJob(new ProjectMigrationJobApi(waitConfig), projectId, jobId, timing, "Export");
1527
+ if (!finished)
1528
+ return;
1529
+ const outputFile = String(options.outputFile);
1530
+ const bytes = await downloadPackage(waitConfig, projectId, jobId, resolveOutputPath(outputFile), options.overwrite === true);
1531
+ if (bytes === null)
1532
+ return;
1533
+ OutputFormatter.success(new SuccessOutput("MigrationExport", {
1534
+ Id: jobId,
1535
+ Type: finished.type ?? "",
1536
+ Status: String(finished.status ?? ""),
1537
+ OutputFile: outputFile,
1538
+ Bytes: bytes
1539
+ }));
1540
+ }
1541
+ var registerMigrationCommand = (program) => {
1542
+ const migrationCmd = program.command("migration").description("Inspect and download the migration jobs behind `project export`");
1543
+ migrationCmd.command("get").description("Get a migration job by id.").addOption(projectKeyOption()).addOption(projectIdOption()).requiredOption("--job-id <uuid>", "Migration job UUID").addOption(createHiddenDeprecatedTenantOption("-t, --tenant <tenant-name>")).option("--log-level <level>", "Log verbosity: debug, info, warn, error", "Information").examples(MIGRATION_JOB_GET_EXAMPLES).trackedAction(processContext, async (options) => {
1544
+ const jobId = String(options.jobId ?? "").trim();
1545
+ if (jobId === "") {
1546
+ emitInvalidArgument("--job-id cannot be blank.", "Pass the id of a migration job, e.g. --job-id a1b2c3d4-0000-0000-0000-000000000001.");
1547
+ return;
1548
+ }
1549
+ const ctx = await resolveContextWithProject(options);
1550
+ if (!ctx)
1551
+ return;
1552
+ const job = await readProjectJob(ctx, jobId);
1553
+ if (!job)
1554
+ return;
1555
+ OutputFormatter.success(new SuccessOutput("MigrationJobGet", toMigrationJobOutput(job)));
1556
+ });
1557
+ migrationCmd.command("download").description("Download the .tmh from an export job that already finished, without exporting again.").addOption(projectKeyOption()).addOption(projectIdOption()).requiredOption("--job-id <uuid>", "Export job UUID").requiredOption("--output-file <path>", "Where to write the package").option("--overwrite", "Replace --output-file if it already exists. Without it, an existing file is refused and nothing is written").addOption(createHiddenDeprecatedTenantOption("-t, --tenant <tenant-name>")).option("--log-level <level>", "Log verbosity: debug, info, warn, error", "Information").examples(MIGRATION_JOB_DOWNLOAD_EXAMPLES).trackedAction(processContext, async (options) => {
1558
+ const jobId = String(options.jobId ?? "").trim();
1559
+ if (jobId === "") {
1560
+ emitInvalidArgument("--job-id cannot be blank.", "Pass the job id an export returned, e.g. --job-id a1b2c3d4-0000-0000-0000-000000000001.");
1561
+ return;
1562
+ }
1563
+ const outputFile = String(options.outputFile ?? "").trim();
1564
+ const overwrite = options.overwrite === true;
1565
+ if (!await checkOutputTarget(outputFile, overwrite, PACKAGE_WORDING))
1566
+ return;
1567
+ const ctx = await resolveContextWithProject(options);
1568
+ if (!ctx)
1569
+ return;
1570
+ const { tmConfig, projectId } = ctx;
1571
+ const job = await readProjectJob(ctx, jobId);
1572
+ if (!job)
1573
+ return;
1574
+ if (!isExportJob(job.type)) {
1575
+ emitInvalidArgument(`Migration job '${jobId}' is a ${String(job.type ?? "migration")} job, not an export, so it has no package to download.`, `Pass the id of an export job. \`uip tm migration list --project-id ${projectId} --type exportProject\` lists this project's.`);
1576
+ return;
1577
+ }
1578
+ const status = String(job.status ?? "");
1579
+ if (!isMigrationCompleted(status)) {
1580
+ OutputFormatter.error({
1581
+ Result: RESULTS.Failure,
1582
+ Message: `Export job '${jobId}' is ${status || "in an unknown state"}, not Completed, so there is no package yet.`,
1583
+ Instructions: isMigrationTerminal(status) ? "Nothing was written. Start a new export if you still need the package." : `Nothing was written. ${recheckJobHint(projectId, jobId)}, and download once it reads Completed.`,
1584
+ ErrorCode: "invalid_argument",
1585
+ Retry: isMigrationTerminal(status) ? "RetryWillNotFix" : "RetryLater"
1586
+ });
1587
+ processContext.exit(1);
1588
+ return;
1589
+ }
1590
+ const bytes = await downloadPackage(tmConfig, projectId, jobId, resolveOutputPath(outputFile), overwrite, {
1591
+ onFetchFailure: downloadRefusedHint(projectId, jobId),
1592
+ afterFetch: "The job still holds the package, so this is the transfer or the write rather than the export. Run the command again."
1593
+ });
1594
+ if (bytes === null)
1595
+ return;
1596
+ OutputFormatter.success(new SuccessOutput("MigrationJobDownload", {
1597
+ JobId: jobId,
1598
+ OutputFile: outputFile,
1599
+ Bytes: bytes
1600
+ }));
1601
+ });
1602
+ migrationCmd.command("list").description("Find a migration job when you no longer have its id, newest first. Pass --project-key or --project-id to narrow it to one project: the service lists across the whole tenant, including projects you have no role on.").addOption(new Option("--status <status>", `Filter by job status (${Object.values(UiPathTestManagementHubProjectMigrationAbstractionsEnumsMigrationJobStatus).join(", ")})`).choices(Object.values(UiPathTestManagementHubProjectMigrationAbstractionsEnumsMigrationJobStatus))).addOption(new Option("--type <type>", `Filter by job type (${Object.values(UiPathTestManagementHubProjectMigrationAbstractionsEnumsMigrationJobType).join(", ")})`).choices(Object.values(UiPathTestManagementHubProjectMigrationAbstractionsEnumsMigrationJobType))).addOption(projectKeyOption("Only jobs for this project — a filter, not a scope")).addOption(projectIdOption()).option("--package-name <name>", "Filter by package name").option("--filter <text>", "Substring match on package name. --package-name matches the whole name").option("--sort-by <expression>", "Sort as '<property> asc|desc', e.g. 'updated asc'", DEFAULT_JOB_SORT).option("--limit <number>", "Maximum jobs to return", "50").option("--offset <number>", "Jobs to skip", "0").addOption(createHiddenDeprecatedTenantOption("-t, --tenant <tenant-name>")).option("--log-level <level>", "Log verbosity: debug, info, warn, error", "Information").examples(MIGRATION_JOB_LIST_EXAMPLES).trackedAction(processContext, async (options) => {
1603
+ if (blankFilterGiven(options, ["packageName", "filter", "sortBy"]))
1604
+ return;
1605
+ const paging = resolvePaginationOptions(options);
1606
+ if (paging.error) {
1607
+ OutputFormatter.error({
1608
+ Result: RESULTS.Failure,
1609
+ Message: paging.error.message,
1610
+ Instructions: paging.error.instructions,
1611
+ ErrorCode: "invalid_argument",
1612
+ Retry: "RetryWillNotFix"
1613
+ });
1614
+ processContext.exit(1);
1615
+ return;
1616
+ }
1617
+ let projectId;
1618
+ let tmConfig;
1619
+ if (options.projectId !== undefined || options.projectKey !== undefined) {
1620
+ const ctx = await resolveContextWithProject(options);
1621
+ if (!ctx)
1622
+ return;
1623
+ projectId = ctx.projectId;
1624
+ tmConfig = ctx.tmConfig;
1625
+ } else {
1626
+ const [authError, base] = await catchError(initializeContext(options));
1627
+ if (authError) {
1628
+ OutputFormatter.error({
1629
+ Result: RESULTS.Failure,
1630
+ Message: authError.message,
1631
+ Instructions: instructionsFor("auth"),
1632
+ ErrorCode: "authentication_required",
1633
+ Retry: "RetryWillNotFix"
1634
+ });
1635
+ processContext.exit(1);
1636
+ return;
1637
+ }
1638
+ tmConfig = base.tmConfig;
1639
+ }
1640
+ const [error, page] = await catchError(new ProjectMigrationJobApi(tmConfig).projectMigrationJobGet(toJobListRequest({
1641
+ status: options.status,
1642
+ type: options.type,
1643
+ projectId,
1644
+ packageName: options.packageName,
1645
+ filter: options.filter,
1646
+ sortBy: options.sortBy?.trim() || DEFAULT_JOB_SORT,
1647
+ limit: paging.top,
1648
+ offset: paging.skip
1649
+ })));
1650
+ if (error) {
1651
+ await emitTmFailure(error);
1652
+ return;
1653
+ }
1654
+ const jobs = page.data ?? [];
1655
+ const rows = toMigrationJobRows(jobs);
1656
+ const output = new SuccessOutput("MigrationJobList", rows);
1657
+ output.Pagination = new Pagination({
1658
+ returned: jobs.length,
1659
+ limit: paging.top,
1660
+ offset: paging.skip,
1661
+ total: page.paging?.total,
1662
+ ...page.paging?.total === undefined && page.paging?.nextPage !== undefined && {
1663
+ hasMore: page.paging.nextPage
1664
+ }
1665
+ });
1666
+ if (output.Pagination.HasMore) {
1667
+ output.Instructions = `More jobs: run again with --offset ${paging.skip + jobs.length}.`;
1668
+ }
1669
+ OutputFormatter.success(output);
1670
+ });
1671
+ return migrationCmd;
1672
+ };
1673
+
1674
+ export { stripEncodingMarkers, ROBOT_LOG_LEVELS, TERMINAL_STATUSES, msToDuration, calcPassRate, DEFAULT_TEST_CASE_VERSION, SCHEMA_FORBIDDEN_MESSAGE, PROJECT_CONFIG_IMPORT_FORBIDDEN_MESSAGE, TM_FORBIDDEN_MESSAGE, TM_LICENSED_USER_FORBIDDEN_MESSAGE, TM_TEST_CLOUD_FORBIDDEN_MESSAGE, TM_NOT_AVAILABLE_MESSAGE, TM_NOT_AVAILABLE_INSTRUCTIONS, TAGGED_UPLOAD_NOT_SUPPORTED_INSTRUCTIONS, parseCustomFieldObjectType, parseCustomFieldDataType, validateIdentity, findExactByNamePaged, splitKeys, resolvePaginationOptions, hasText, sameGuid, resolveWaitTiming, toOutput, toIsoDate, isPortalShellDocument, isFeatureDisabledError, extractErrorDetails2 as extractErrorDetails, emitTmFailure, emitTmFailureDetails, refuseUnexpectedContentType, emitInvalidArgument, emitAttachmentNotFound, instructiveError, readInstructions, readClassification, tmWebUrl, initializeContext, initializeContextWithProject, resolveContextWithProject, ensureProjectKey, projectKeyOption, projectIdOption, blankValueMessage, blankFilterGiven, IMPORT_CONTENT, IMPORT_CONTENT_CHOICES, toImportJobRequest, toChunkUploadRequest, toJobUpdateRequest, toMigrationJobOutput, toSchemaVersionRows, DEFAULT_IMPORT_TIMEOUT_MS, DEFAULT_MIGRATION_INTERVAL_MS, CHUNK_UPLOAD_ATTEMPTS, CHUNK_RETRY_BACKOFF_MS, CHUNK_SIZE_BYTES, MAX_PACKAGE_NAME_LENGTH, MAX_IMPORT_PACKAGE_BYTES, CHUNK_NOT_SENT_CODES, checkOutputTarget, resolveOutputPath, withRefreshingToken, describeContentDefaults, checkContentSelection, waitForMigrationJob, recheckJobHint, writeZipResponse, registerProjectExportCommand, registerMigrationCommand };
1675
+
1676
+ //# debugId=A7CC196F81BF701164756E2164756E21