@uipath/gov-tool 1.196.0 → 1.197.0-preview.59

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.
Files changed (2) hide show
  1. package/dist/tool.js +1293 -2073
  2. package/package.json +2 -2
package/dist/tool.js CHANGED
@@ -21230,7 +21230,7 @@ var require_commander = __commonJS((exports) => {
21230
21230
  var package_default = {
21231
21231
  name: "@uipath/gov-tool",
21232
21232
  license: "MIT",
21233
- version: "1.196.0",
21233
+ version: "1.197.0-preview.59",
21234
21234
  description: "Manage UiPath governance — AOps policies, Access policies, and compliance packs.",
21235
21235
  private: false,
21236
21236
  repository: {
@@ -21253,7 +21253,7 @@ var package_default = {
21253
21253
  "dist"
21254
21254
  ],
21255
21255
  scripts: {
21256
- build: "bun build ./src/tool.ts --outdir dist --format esm --target node",
21256
+ build: "bun build ./src/tool.ts --outdir dist --format esm --target node --sourcemap=linked",
21257
21257
  package: "bun run build && bun pm pack",
21258
21258
  lint: "biome check .",
21259
21259
  "lint:fix": "biome check --write .",
@@ -21302,6 +21302,12 @@ function singleton(ctorOrName) {
21302
21302
  };
21303
21303
  }
21304
21304
 
21305
+ // ../../common/src/telemetry/global-telemetry-properties.ts
21306
+ var telemetryPropsSlot = singleton("TelemetryDefaultProps");
21307
+ function getGlobalTelemetryProperties() {
21308
+ return telemetryPropsSlot.get();
21309
+ }
21310
+
21305
21311
  // ../../common/src/sdk-user-agent.ts
21306
21312
  var USER_AGENT_HEADER = "User-Agent";
21307
21313
  var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
@@ -21325,8 +21331,8 @@ function appendUserAgentToken(value, userAgent) {
21325
21331
  function getEffectiveUserAgent(userAgent) {
21326
21332
  return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent);
21327
21333
  }
21328
- function isHeadersLike(headers) {
21329
- return typeof headers === "object" && headers !== null && "get" in headers && typeof headers.get === "function" && "set" in headers && typeof headers.set === "function";
21334
+ function getHeaderName(headers, headerName) {
21335
+ return Object.keys(headers).find((key) => key.toLowerCase() === headerName.toLowerCase());
21330
21336
  }
21331
21337
  function getSdkUserAgentToken(pkg) {
21332
21338
  const packageName = pkg.name.replace(/^@uipath\//, "");
@@ -21334,59 +21340,31 @@ function getSdkUserAgentToken(pkg) {
21334
21340
  }
21335
21341
  function addSdkUserAgentHeader(headers, userAgent) {
21336
21342
  const result = { ...headers ?? {} };
21337
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
21338
- const headerName = Object.keys(result).find((key) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
21339
- if (headerName) {
21340
- result[headerName] = appendUserAgentToken(result[headerName], effectiveUserAgent);
21341
- } else {
21342
- result[USER_AGENT_HEADER] = effectiveUserAgent;
21343
- }
21343
+ const headerName = getHeaderName(result, USER_AGENT_HEADER);
21344
+ result[headerName ?? USER_AGENT_HEADER] = appendUserAgentToken(headerName ? result[headerName] : undefined, getEffectiveUserAgent(userAgent));
21344
21345
  return result;
21345
21346
  }
21346
- function withSdkUserAgentHeader(headers, userAgent) {
21347
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
21348
- if (isHeadersLike(headers)) {
21349
- headers.set(USER_AGENT_HEADER, appendUserAgentToken(headers.get(USER_AGENT_HEADER), effectiveUserAgent));
21350
- return headers;
21351
- }
21352
- if (Array.isArray(headers)) {
21353
- const result = headers.map((entry) => {
21354
- const [key, value] = entry;
21355
- return [key, value];
21356
- });
21357
- const headerIndex = result.findIndex(([key]) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
21358
- if (headerIndex >= 0) {
21359
- const [key, value] = result[headerIndex];
21360
- result[headerIndex] = [
21361
- key,
21362
- appendUserAgentToken(value, effectiveUserAgent)
21363
- ];
21364
- } else {
21365
- result.push([USER_AGENT_HEADER, effectiveUserAgent]);
21366
- }
21367
- return result;
21368
- }
21369
- return addSdkUserAgentHeader(typeof headers === "object" && headers !== null ? { ...headers } : {}, effectiveUserAgent);
21347
+ function asHeaderRecord(headers) {
21348
+ return typeof headers === "object" && headers !== null ? { ...headers } : {};
21370
21349
  }
21371
- function withUserAgentInitOverride(initOverrides, userAgent) {
21350
+ function withForwardedHeadersInitOverride(initOverrides, forward) {
21372
21351
  return async (requestContext) => {
21373
- const initWithUserAgent = {
21352
+ const initWithHeaders = {
21374
21353
  ...requestContext.init,
21375
- headers: withSdkUserAgentHeader(requestContext.init.headers, userAgent)
21354
+ headers: forward(asHeaderRecord(requestContext.init.headers))
21376
21355
  };
21377
21356
  const override = typeof initOverrides === "function" ? await initOverrides({
21378
21357
  ...requestContext,
21379
- init: initWithUserAgent
21358
+ init: initWithHeaders
21380
21359
  }) : initOverrides;
21381
21360
  return {
21382
21361
  ...override ?? {},
21383
- headers: withSdkUserAgentHeader(override?.headers ?? initWithUserAgent.headers, userAgent)
21362
+ headers: forward(asHeaderRecord(override?.headers ?? initWithHeaders.headers))
21384
21363
  };
21385
21364
  };
21386
21365
  }
21387
- function installSdkUserAgentHeader(BaseApiClass, userAgent) {
21366
+ function installRequestHeaderForwarding(BaseApiClass, patchKey, forward) {
21388
21367
  const prototype = BaseApiClass.prototype;
21389
- const patchKey = userAgentPatchKey(userAgent);
21390
21368
  if (prototype[patchKey]) {
21391
21369
  return;
21392
21370
  }
@@ -21394,13 +21372,16 @@ function installSdkUserAgentHeader(BaseApiClass, userAgent) {
21394
21372
  throw new Error("Generated BaseAPI request function not found.");
21395
21373
  }
21396
21374
  const originalRequest = prototype.request;
21397
- prototype.request = function requestWithUserAgent(context, initOverrides) {
21398
- return originalRequest.call(this, context, withUserAgentInitOverride(initOverrides, userAgent));
21375
+ prototype.request = function requestWithForwardedHeaders(context, initOverrides) {
21376
+ return originalRequest.call(this, context, withForwardedHeadersInitOverride(initOverrides, forward));
21399
21377
  };
21400
21378
  Object.defineProperty(prototype, patchKey, {
21401
21379
  value: true
21402
21380
  });
21403
21381
  }
21382
+ function installSdkUserAgentHeader(BaseApiClass, userAgent) {
21383
+ installRequestHeaderForwarding(BaseApiClass, userAgentPatchKey(userAgent), (headers) => addSdkUserAgentHeader(headers, userAgent));
21384
+ }
21404
21385
 
21405
21386
  // ../../admin/authz-sdk/generated/src/runtime.ts
21406
21387
  var BASE_PATH = "http://localhost".replace(/\/+$/, "");
@@ -21655,7 +21636,7 @@ class VoidApiResponse {
21655
21636
  var package_default2 = {
21656
21637
  name: "@uipath/authz-sdk",
21657
21638
  license: "MIT",
21658
- version: "1.196.0",
21639
+ version: "1.197.0",
21659
21640
  description: "SDK for the UiPath Authorization Service API.",
21660
21641
  repository: {
21661
21642
  type: "git",
@@ -21685,7 +21666,7 @@ var package_default2 = {
21685
21666
  ],
21686
21667
  private: true,
21687
21668
  scripts: {
21688
- build: "bun build ./src/index.ts --outdir dist --format esm --target node && tsc -p tsconfig.build.json --noCheck",
21669
+ build: "bun build ./src/index.ts --outdir dist --format esm --target node --sourcemap=linked && tsc -p tsconfig.build.json --noCheck",
21689
21670
  generate: "bun run src/scripts/generate-sdk.ts",
21690
21671
  lint: "biome check ."
21691
21672
  },
@@ -22334,6 +22315,12 @@ var normalizeAndValidateBaseUrl = (rawUrl) => {
22334
22315
  }
22335
22316
  return url.pathname.length > 1 ? url.origin : baseUrl;
22336
22317
  };
22318
+ var resolveScopes = (isExternalAppAuth, customScopes, fileScopes) => {
22319
+ const requestedScopes = customScopes?.length ? customScopes : fileScopes ?? [];
22320
+ if (isExternalAppAuth)
22321
+ return requestedScopes;
22322
+ return [...new Set([...DEFAULT_SCOPES, ...requestedScopes])];
22323
+ };
22337
22324
  var resolveConfigAsync = async ({
22338
22325
  customAuthority,
22339
22326
  customClientId,
@@ -22364,7 +22351,7 @@ var resolveConfigAsync = async ({
22364
22351
  clientSecret = fileAuth.clientSecret;
22365
22352
  }
22366
22353
  const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID && Boolean(clientSecret);
22367
- const scopes = customScopes && customScopes.length > 0 ? customScopes : fileAuth.scopes && fileAuth.scopes.length > 0 ? fileAuth.scopes : isExternalAppAuth ? [] : DEFAULT_SCOPES;
22354
+ const scopes = resolveScopes(isExternalAppAuth, customScopes, fileAuth.scopes);
22368
22355
  return {
22369
22356
  clientId,
22370
22357
  clientSecret,
@@ -22379,6 +22366,76 @@ var resolveConfigAsync = async ({
22379
22366
  init_constants();
22380
22367
  // ../../auth/src/loginStatus.ts
22381
22368
  init_src();
22369
+
22370
+ // ../../auth/src/authProfile.ts
22371
+ init_src();
22372
+ init_constants();
22373
+ var DEFAULT_AUTH_PROFILE = "default";
22374
+ var PROFILE_DIR = "profiles";
22375
+ var PROFILE_NAME_RE = /^[A-Za-z0-9._-]+$/;
22376
+ var ACTIVE_AUTH_PROFILE_KEY = Symbol.for("@uipath/auth/ActiveAuthProfile");
22377
+ var AUTH_PROFILE_STORAGE_KEY = Symbol.for("@uipath/auth/ProfileStorage");
22378
+ var globalSlot2 = globalThis;
22379
+ function isAuthProfileStorage(value) {
22380
+ return value !== null && typeof value === "object" && "getStore" in value && "run" in value;
22381
+ }
22382
+ function createProfileStorage() {
22383
+ const [error, mod] = catchError(() => __require("node:async_hooks"));
22384
+ if (error || typeof mod?.AsyncLocalStorage !== "function") {
22385
+ return {
22386
+ getStore: () => {
22387
+ return;
22388
+ },
22389
+ run: (_store, fn) => fn()
22390
+ };
22391
+ }
22392
+ return new mod.AsyncLocalStorage;
22393
+ }
22394
+ function getProfileStorage() {
22395
+ const existing = globalSlot2[AUTH_PROFILE_STORAGE_KEY];
22396
+ if (isAuthProfileStorage(existing)) {
22397
+ return existing;
22398
+ }
22399
+ const storage = createProfileStorage();
22400
+ globalSlot2[AUTH_PROFILE_STORAGE_KEY] = storage;
22401
+ return storage;
22402
+ }
22403
+ var profileStorage = getProfileStorage();
22404
+
22405
+ class AuthProfileValidationError extends Error {
22406
+ constructor(message) {
22407
+ super(message);
22408
+ this.name = "AuthProfileValidationError";
22409
+ }
22410
+ }
22411
+ function normalizeAuthProfileName(profile) {
22412
+ if (profile === undefined || profile === DEFAULT_AUTH_PROFILE) {
22413
+ return;
22414
+ }
22415
+ if (profile.length === 0 || profile === "." || profile === ".." || !PROFILE_NAME_RE.test(profile)) {
22416
+ throw new AuthProfileValidationError(`Invalid profile name "${profile}". Profile names may contain only letters, numbers, '.', '_', and '-'.`);
22417
+ }
22418
+ return profile;
22419
+ }
22420
+ function getActiveAuthProfile() {
22421
+ const scopedState = profileStorage.getStore();
22422
+ if (scopedState !== undefined) {
22423
+ return scopedState.profile;
22424
+ }
22425
+ return globalSlot2[ACTIVE_AUTH_PROFILE_KEY]?.profile;
22426
+ }
22427
+ function resolveAuthProfileFilePath(profile) {
22428
+ const normalized = normalizeAuthProfileName(profile);
22429
+ if (normalized === undefined) {
22430
+ throw new AuthProfileValidationError(`"${DEFAULT_AUTH_PROFILE}" is the built-in profile and does not have a profile file path.`);
22431
+ }
22432
+ const fs7 = getFileSystem();
22433
+ return fs7.path.join(fs7.env.homedir(), UIPATH_HOME_DIR, PROFILE_DIR, normalized, AUTH_FILENAME);
22434
+ }
22435
+ function getActiveAuthProfileFilePath() {
22436
+ const profile = getActiveAuthProfile();
22437
+ return profile ? resolveAuthProfileFilePath(profile) : undefined;
22438
+ }
22382
22439
  // ../../auth/src/utils/jwt.ts
22383
22440
  class InvalidIssuerError extends Error {
22384
22441
  expected;
@@ -22507,23 +22564,74 @@ var readAuthFromEnv = () => {
22507
22564
  organizationId,
22508
22565
  tenantName,
22509
22566
  tenantId,
22510
- expiration
22567
+ expiration,
22568
+ source: "env" /* Env */
22511
22569
  };
22512
22570
  };
22513
22571
 
22572
+ // ../../auth/src/refreshCircuitBreaker.ts
22573
+ init_src();
22574
+ var BREAKER_SUFFIX = ".refresh-state";
22575
+ var BACKOFF_BASE_MS = 60000;
22576
+ var BACKOFF_CAP_MS = 60 * 60 * 1000;
22577
+ var SURFACE_WINDOW_MS = 60 * 60 * 1000;
22578
+ async function refreshTokenFingerprint(refreshToken) {
22579
+ const bytes = new TextEncoder().encode(refreshToken);
22580
+ if (globalThis.crypto?.subtle) {
22581
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
22582
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
22583
+ }
22584
+ const { createHash } = await import("node:crypto");
22585
+ return createHash("sha256").update(refreshToken).digest("hex").slice(0, 16);
22586
+ }
22587
+ function breakerPathFor(authPath) {
22588
+ return `${authPath}${BREAKER_SUFFIX}`;
22589
+ }
22590
+ async function loadRefreshBreaker(authPath) {
22591
+ const fs7 = getFileSystem();
22592
+ try {
22593
+ const content = await fs7.readFile(breakerPathFor(authPath), "utf-8");
22594
+ if (!content)
22595
+ return {};
22596
+ const parsed = JSON.parse(content);
22597
+ return parsed && typeof parsed === "object" ? parsed : {};
22598
+ } catch {
22599
+ return {};
22600
+ }
22601
+ }
22602
+ async function saveRefreshBreaker(authPath, state) {
22603
+ try {
22604
+ const fs7 = getFileSystem();
22605
+ const path3 = breakerPathFor(authPath);
22606
+ await fs7.mkdir(fs7.path.dirname(path3));
22607
+ const tempPath = `${path3}.tmp`;
22608
+ await fs7.writeFile(tempPath, JSON.stringify(state));
22609
+ await fs7.rename(tempPath, path3);
22610
+ } catch {}
22611
+ }
22612
+ async function clearRefreshBreaker(authPath) {
22613
+ const fs7 = getFileSystem();
22614
+ const path3 = breakerPathFor(authPath);
22615
+ try {
22616
+ if (await fs7.exists(path3)) {
22617
+ await fs7.rm(path3);
22618
+ }
22619
+ } catch {}
22620
+ }
22621
+ function nextBackoffMs(attempts) {
22622
+ const shift = Math.max(0, attempts - 1);
22623
+ return Math.min(BACKOFF_BASE_MS * 2 ** shift, BACKOFF_CAP_MS);
22624
+ }
22625
+ function shouldSurface(state, nowMs) {
22626
+ if (state.lastSurfacedAtMs === undefined)
22627
+ return true;
22628
+ return nowMs - state.lastSurfacedAtMs >= SURFACE_WINDOW_MS;
22629
+ }
22630
+
22514
22631
  // ../../auth/src/robotClientFallback.ts
22515
22632
  init_src();
22516
22633
  var DEFAULT_TIMEOUT_MS = 1000;
22517
22634
  var CLOSE_TIMEOUT_MS = 500;
22518
- var NOTICE_SENTINEL = Symbol.for("@uipath/auth/robotFallbackNoticePrinted");
22519
- var printNoticeOnce = () => {
22520
- const slot = globalThis;
22521
- if (slot[NOTICE_SENTINEL])
22522
- return;
22523
- slot[NOTICE_SENTINEL] = true;
22524
- catchError(() => process.stderr.write(`Using UiPath Robot credentials. Run 'uip login' for a dedicated session.
22525
- `));
22526
- };
22527
22635
  var ROBOT_USER_SERVICES_PIPE = "UiPathUserServices";
22528
22636
  var ROBOT_USER_SERVICES_ALTERNATE_PIPE = `${ROBOT_USER_SERVICES_PIPE}Alternate`;
22529
22637
  var PIPE_NAME_MAX_LENGTH = 103;
@@ -22639,7 +22747,6 @@ var tryRobotClientFallback = async (options = {}) => {
22639
22747
  issuerFromToken = issClaim;
22640
22748
  }
22641
22749
  }
22642
- printNoticeOnce();
22643
22750
  return {
22644
22751
  accessToken,
22645
22752
  baseUrl: parsedUrl.baseUrl,
@@ -22864,18 +22971,327 @@ var saveEnvFileAsync = async ({
22864
22971
  };
22865
22972
 
22866
22973
  // ../../auth/src/loginStatus.ts
22867
- function normalizeTokenRefreshFailure() {
22868
- return "stored refresh token is invalid or expired";
22974
+ var getLoginStatusAsync = async (options = {}) => {
22975
+ return getLoginStatusWithDeps(options);
22976
+ };
22977
+ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
22978
+ const {
22979
+ resolveEnvFilePath = resolveEnvFilePathAsync,
22980
+ loadEnvFile = loadEnvFileAsync,
22981
+ saveEnvFile = saveEnvFileAsync,
22982
+ getFs = getFileSystem,
22983
+ refreshToken: refreshTokenFn = refreshAccessToken,
22984
+ resolveConfig = resolveConfigAsync,
22985
+ robotFallback = tryRobotClientFallback,
22986
+ loadBreaker = loadRefreshBreaker,
22987
+ saveBreaker = saveRefreshBreaker,
22988
+ clearBreaker = clearRefreshBreaker
22989
+ } = deps;
22990
+ if (isRobotAuthEnforced()) {
22991
+ return resolveRobotEnforcedStatus(robotFallback);
22992
+ }
22993
+ if (isEnvAuthEnabled()) {
22994
+ return readAuthFromEnv();
22995
+ }
22996
+ const activeProfile = getActiveAuthProfile();
22997
+ const activeProfileFilePath = getActiveAuthProfileFilePath();
22998
+ const usingActiveProfile = activeProfile !== undefined && (options.envFilePath === undefined || options.envFilePath === activeProfileFilePath);
22999
+ const envFilePath = options.envFilePath ?? activeProfileFilePath ?? DEFAULT_ENV_FILENAME;
23000
+ const { ensureTokenValidityMinutes } = options;
23001
+ const { absolutePath } = await resolveEnvFilePath(envFilePath);
23002
+ if (absolutePath === undefined) {
23003
+ if (usingActiveProfile) {
23004
+ return {
23005
+ loginStatus: "Not logged in",
23006
+ hint: `No credentials found for profile "${activeProfile}". Run 'uip login --profile ${activeProfile}' to authenticate this profile.`
23007
+ };
23008
+ }
23009
+ return resolveBorrowedRobotStatus(robotFallback);
23010
+ }
23011
+ const loaded = await loadFileCredentials(loadEnvFile, absolutePath);
23012
+ if ("status" in loaded) {
23013
+ return loaded.status;
23014
+ }
23015
+ const { credentials } = loaded;
23016
+ const globalHint = () => usingActiveProfile ? Promise.resolve(undefined) : getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath);
23017
+ const expiration = getTokenExpiration(credentials.UIPATH_ACCESS_TOKEN);
23018
+ const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
23019
+ let tokens = {
23020
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
23021
+ refreshToken: credentials.UIPATH_REFRESH_TOKEN,
23022
+ expiration,
23023
+ lockReleaseFailed: false
23024
+ };
23025
+ const refreshToken = credentials.UIPATH_REFRESH_TOKEN;
23026
+ if (expiration && expiration <= outerThreshold && refreshToken) {
23027
+ const refreshed = await attemptRefresh({
23028
+ absolutePath,
23029
+ credentials,
23030
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
23031
+ refreshToken,
23032
+ expiration,
23033
+ ensureTokenValidityMinutes,
23034
+ getFs,
23035
+ loadEnvFile,
23036
+ saveEnvFile,
23037
+ refreshFn: refreshTokenFn,
23038
+ resolveConfig,
23039
+ loadBreaker,
23040
+ saveBreaker,
23041
+ clearBreaker,
23042
+ globalHint
23043
+ });
23044
+ if (refreshed.kind === "terminal") {
23045
+ return refreshed.status;
23046
+ }
23047
+ tokens = refreshed.tokens;
23048
+ }
23049
+ return buildFileStatus(tokens, credentials, globalHint);
23050
+ };
23051
+ async function resolveRobotEnforcedStatus(robotFallback) {
23052
+ if (isEnvAuthEnabled()) {
23053
+ throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
23054
+ }
23055
+ const robotCreds = await robotFallback({ force: true });
23056
+ if (!robotCreds) {
23057
+ return {
23058
+ loginStatus: "Not logged in",
23059
+ hint: `${ENFORCE_ROBOT_AUTH_VAR}=true but the UiPath Robot ` + `session is unavailable. Start and sign in to the Assistant, ` + `or unset ${ENFORCE_ROBOT_AUTH_VAR} to fall back to file or ` + `env-var authentication.`
23060
+ };
23061
+ }
23062
+ return buildRobotStatus(robotCreds);
22869
23063
  }
22870
- function normalizeTokenRefreshUnavailableFailure() {
22871
- return "token refresh failed before authentication completed";
23064
+ async function resolveBorrowedRobotStatus(robotFallback) {
23065
+ const robotCreds = await robotFallback();
23066
+ return robotCreds ? buildRobotStatus(robotCreds) : { loginStatus: "Not logged in" };
22872
23067
  }
22873
- function errorMessage(error) {
22874
- return error instanceof Error ? error.message : String(error);
23068
+ async function loadFileCredentials(loadEnvFile, absolutePath) {
23069
+ let credentials;
23070
+ try {
23071
+ credentials = await loadEnvFile({ envPath: absolutePath });
23072
+ } catch (error) {
23073
+ if (isFileNotFoundError(error)) {
23074
+ return { status: { loginStatus: "Not logged in" } };
23075
+ }
23076
+ throw error;
23077
+ }
23078
+ if (!credentials.UIPATH_ACCESS_TOKEN) {
23079
+ return { status: { loginStatus: "Not logged in" } };
23080
+ }
23081
+ return { credentials };
23082
+ }
23083
+ async function getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath) {
23084
+ const fs7 = getFs();
23085
+ const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
23086
+ if (absolutePath === globalPath)
23087
+ return;
23088
+ if (!await fs7.exists(globalPath))
23089
+ return;
23090
+ try {
23091
+ const globalCreds = await loadEnvFile({ envPath: globalPath });
23092
+ if (!globalCreds.UIPATH_ACCESS_TOKEN)
23093
+ return;
23094
+ const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
23095
+ if (globalExp && globalExp <= new Date)
23096
+ return;
23097
+ return `Local credentials file at ${absolutePath} has expired credentials. Valid credentials exist in ${globalPath}. Remove the local file or run 'uip login' to re-authenticate.`;
23098
+ } catch {
23099
+ return;
23100
+ }
22875
23101
  }
22876
23102
  function computeExpirationThreshold(ensureTokenValidityMinutes) {
22877
23103
  return new Date(Date.now() + (ensureTokenValidityMinutes ?? 0) * 60 * 1000);
22878
23104
  }
23105
+ async function attemptRefresh(ctx) {
23106
+ const shortCircuit = await circuitBreakerShortCircuit(ctx);
23107
+ if (shortCircuit) {
23108
+ return { kind: "terminal", status: shortCircuit };
23109
+ }
23110
+ let release;
23111
+ try {
23112
+ release = await ctx.getFs().acquireLock(ctx.absolutePath);
23113
+ } catch (error) {
23114
+ return {
23115
+ kind: "terminal",
23116
+ status: await lockAcquireFailureStatus(ctx, error)
23117
+ };
23118
+ }
23119
+ let lockedFailure;
23120
+ let lockReleaseFailed = false;
23121
+ let success;
23122
+ try {
23123
+ const outcome = await runRefreshLocked({
23124
+ absolutePath: ctx.absolutePath,
23125
+ refreshToken: ctx.refreshToken,
23126
+ customAuthority: ctx.credentials.UIPATH_URL,
23127
+ ensureTokenValidityMinutes: ctx.ensureTokenValidityMinutes,
23128
+ loadEnvFile: ctx.loadEnvFile,
23129
+ saveEnvFile: ctx.saveEnvFile,
23130
+ refreshFn: ctx.refreshFn,
23131
+ resolveConfig: ctx.resolveConfig,
23132
+ loadBreaker: ctx.loadBreaker,
23133
+ saveBreaker: ctx.saveBreaker,
23134
+ clearBreaker: ctx.clearBreaker
23135
+ });
23136
+ if (outcome.kind === "fail") {
23137
+ lockedFailure = outcome.status;
23138
+ } else {
23139
+ success = outcome;
23140
+ }
23141
+ } finally {
23142
+ try {
23143
+ await release();
23144
+ } catch {
23145
+ lockReleaseFailed = true;
23146
+ }
23147
+ }
23148
+ if (lockedFailure) {
23149
+ const globalHint = await ctx.globalHint();
23150
+ const base = globalHint ? { ...lockedFailure, loginStatus: "Expired", hint: globalHint } : lockedFailure;
23151
+ return {
23152
+ kind: "terminal",
23153
+ status: lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base
23154
+ };
23155
+ }
23156
+ return {
23157
+ kind: "refreshed",
23158
+ tokens: {
23159
+ accessToken: success?.accessToken,
23160
+ refreshToken: success?.refreshToken,
23161
+ expiration: success?.expiration,
23162
+ tokenRefresh: success?.tokenRefresh,
23163
+ persistenceWarning: success?.persistenceWarning,
23164
+ lockReleaseFailed
23165
+ }
23166
+ };
23167
+ }
23168
+ async function buildFileStatus(tokens, credentials, globalHint) {
23169
+ const result = {
23170
+ loginStatus: tokens.expiration && tokens.expiration <= new Date ? "Expired" : "Logged in",
23171
+ accessToken: tokens.accessToken,
23172
+ refreshToken: tokens.refreshToken,
23173
+ baseUrl: credentials.UIPATH_URL,
23174
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
23175
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
23176
+ tenantName: credentials.UIPATH_TENANT_NAME,
23177
+ tenantId: credentials.UIPATH_TENANT_ID,
23178
+ expiration: tokens.expiration,
23179
+ source: "file" /* File */,
23180
+ ...tokens.persistenceWarning ? { hint: tokens.persistenceWarning, persistenceFailed: true } : {},
23181
+ ...tokens.lockReleaseFailed ? { lockReleaseFailed: true } : {},
23182
+ ...tokens.tokenRefresh ? { tokenRefresh: tokens.tokenRefresh } : {}
23183
+ };
23184
+ if (result.loginStatus === "Expired") {
23185
+ const hint = await globalHint();
23186
+ if (hint) {
23187
+ result.hint = hint;
23188
+ }
23189
+ }
23190
+ return result;
23191
+ }
23192
+ function buildRobotStatus(robotCreds) {
23193
+ return {
23194
+ loginStatus: "Logged in",
23195
+ accessToken: robotCreds.accessToken,
23196
+ baseUrl: robotCreds.baseUrl,
23197
+ organizationName: robotCreds.organizationName,
23198
+ organizationId: robotCreds.organizationId,
23199
+ tenantName: robotCreds.tenantName,
23200
+ tenantId: robotCreds.tenantId,
23201
+ issuer: robotCreds.issuer,
23202
+ expiration: getTokenExpiration(robotCreds.accessToken),
23203
+ source: "robot" /* Robot */
23204
+ };
23205
+ }
23206
+ var isFileNotFoundError = (error) => {
23207
+ if (!(error instanceof Object))
23208
+ return false;
23209
+ return error.code === "ENOENT";
23210
+ };
23211
+ async function circuitBreakerShortCircuit(ctx) {
23212
+ const {
23213
+ absolutePath,
23214
+ refreshToken,
23215
+ accessToken,
23216
+ credentials,
23217
+ expiration,
23218
+ loadBreaker,
23219
+ saveBreaker,
23220
+ clearBreaker
23221
+ } = ctx;
23222
+ const fingerprint = await refreshTokenFingerprint(refreshToken);
23223
+ const breaker = await loadBreaker(absolutePath).catch(() => ({}));
23224
+ if (breaker.deadTokenFp && breaker.deadTokenFp !== fingerprint) {
23225
+ await clearBreaker(absolutePath);
23226
+ breaker.deadTokenFp = undefined;
23227
+ }
23228
+ const nowMs = Date.now();
23229
+ const tokenIsDead = breaker.deadTokenFp === fingerprint;
23230
+ const inBackoff = breaker.backoffUntilMs !== undefined && nowMs < breaker.backoffUntilMs;
23231
+ if (!tokenIsDead && !inBackoff)
23232
+ return;
23233
+ const globalHint = await ctx.globalHint();
23234
+ const suppressed = !shouldSurface(breaker, nowMs);
23235
+ if (!suppressed) {
23236
+ await saveBreaker(absolutePath, {
23237
+ ...breaker,
23238
+ lastSurfacedAtMs: nowMs
23239
+ });
23240
+ }
23241
+ const deadHint = "Run 'uip login' to re-authenticate — the stored refresh token is invalid or expired. In a non-interactive context, authenticate with: uip login --client-id <id> --client-secret <secret> -t <tenant>.";
23242
+ const backoffHint = "Token refresh is temporarily backed off after a recent network error and will retry automatically once the backoff window elapses.";
23243
+ return {
23244
+ loginStatus: globalHint ? "Expired" : "Refresh Failed",
23245
+ ...globalHint ? {
23246
+ accessToken,
23247
+ refreshToken,
23248
+ baseUrl: credentials.UIPATH_URL,
23249
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
23250
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
23251
+ tenantName: credentials.UIPATH_TENANT_NAME,
23252
+ tenantId: credentials.UIPATH_TENANT_ID,
23253
+ expiration,
23254
+ source: "file" /* File */
23255
+ } : {},
23256
+ hint: globalHint ?? (tokenIsDead ? deadHint : backoffHint),
23257
+ refreshCircuitOpen: true,
23258
+ refreshTelemetrySuppressed: suppressed,
23259
+ tokenRefresh: { attempted: false, success: false }
23260
+ };
23261
+ }
23262
+ async function lockAcquireFailureStatus(ctx, error) {
23263
+ const msg = errorMessage(error);
23264
+ const globalHint = await ctx.globalHint();
23265
+ if (globalHint) {
23266
+ return {
23267
+ loginStatus: "Expired",
23268
+ accessToken: ctx.accessToken,
23269
+ refreshToken: ctx.refreshToken,
23270
+ baseUrl: ctx.credentials.UIPATH_URL,
23271
+ organizationName: ctx.credentials.UIPATH_ORGANIZATION_NAME,
23272
+ organizationId: ctx.credentials.UIPATH_ORGANIZATION_ID,
23273
+ tenantName: ctx.credentials.UIPATH_TENANT_NAME,
23274
+ tenantId: ctx.credentials.UIPATH_TENANT_ID,
23275
+ expiration: ctx.expiration,
23276
+ source: "file" /* File */,
23277
+ hint: globalHint,
23278
+ tokenRefresh: {
23279
+ attempted: false,
23280
+ success: false,
23281
+ errorMessage: `lock acquisition failed: ${msg}`
23282
+ }
23283
+ };
23284
+ }
23285
+ return {
23286
+ loginStatus: "Refresh Failed",
23287
+ hint: "Could not acquire the auth-file lock — too many concurrent `uip` processes, or a permission issue on the auth directory. Retry, or run 'uip login' to re-authenticate.",
23288
+ tokenRefresh: {
23289
+ attempted: false,
23290
+ success: false,
23291
+ errorMessage: `lock acquisition failed: ${msg}`
23292
+ }
23293
+ };
23294
+ }
22879
23295
  async function runRefreshLocked(inputs) {
22880
23296
  const {
22881
23297
  absolutePath,
@@ -22885,7 +23301,10 @@ async function runRefreshLocked(inputs) {
22885
23301
  loadEnvFile,
22886
23302
  saveEnvFile,
22887
23303
  refreshFn,
22888
- resolveConfig
23304
+ resolveConfig,
23305
+ loadBreaker,
23306
+ saveBreaker,
23307
+ clearBreaker
22889
23308
  } = inputs;
22890
23309
  const expirationThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
22891
23310
  let fresh;
@@ -22908,6 +23327,7 @@ async function runRefreshLocked(inputs) {
22908
23327
  const freshAccess = fresh.UIPATH_ACCESS_TOKEN;
22909
23328
  const freshExp = freshAccess ? getTokenExpiration(freshAccess) : undefined;
22910
23329
  if (freshAccess && freshExp && freshExp > expirationThreshold) {
23330
+ await clearBreaker(absolutePath);
22911
23331
  return {
22912
23332
  kind: "ok",
22913
23333
  accessToken: freshAccess,
@@ -22931,8 +23351,21 @@ async function runRefreshLocked(inputs) {
22931
23351
  refreshedRefresh = refreshed.refreshToken;
22932
23352
  } catch (error) {
22933
23353
  const isOAuthFailure = isTokenRefreshOAuthFailure(error);
22934
- const hint = isOAuthFailure ? "Run 'uip login' to re-authenticate — the stored refresh token is invalid or expired." : "Token refresh failed. Check your network connection, then retry or run 'uip login' to re-authenticate.";
23354
+ const hint = isOAuthFailure ? "Run 'uip login' to re-authenticate — the stored refresh token is invalid or expired. In a non-interactive context, authenticate with: uip login --client-id <id> --client-secret <secret> -t <tenant>." : "Token refresh failed. Check your network connection, then retry or run 'uip login' to re-authenticate.";
22935
23355
  const message = isOAuthFailure ? normalizeTokenRefreshFailure() : normalizeTokenRefreshUnavailableFailure();
23356
+ const fp = await refreshTokenFingerprint(tokenForIdP);
23357
+ if (isOAuthFailure) {
23358
+ await saveBreaker(absolutePath, { deadTokenFp: fp });
23359
+ } else {
23360
+ const prior = await loadBreaker(absolutePath).catch(() => ({}));
23361
+ const attempts = (prior.attempts ?? 0) + 1;
23362
+ await saveBreaker(absolutePath, {
23363
+ ...prior,
23364
+ deadTokenFp: undefined,
23365
+ attempts,
23366
+ backoffUntilMs: Date.now() + nextBackoffMs(attempts)
23367
+ });
23368
+ }
22936
23369
  return {
22937
23370
  kind: "fail",
22938
23371
  status: {
@@ -22961,6 +23394,7 @@ async function runRefreshLocked(inputs) {
22961
23394
  }
22962
23395
  };
22963
23396
  }
23397
+ await clearBreaker(absolutePath);
22964
23398
  try {
22965
23399
  await saveEnvFile({
22966
23400
  envPath: absolutePath,
@@ -22993,214 +23427,25 @@ async function runRefreshLocked(inputs) {
22993
23427
  };
22994
23428
  }
22995
23429
  }
22996
- var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
22997
- const {
22998
- resolveEnvFilePath = resolveEnvFilePathAsync,
22999
- loadEnvFile = loadEnvFileAsync,
23000
- saveEnvFile = saveEnvFileAsync,
23001
- getFs = getFileSystem,
23002
- refreshToken: refreshTokenFn = refreshAccessToken,
23003
- resolveConfig = resolveConfigAsync,
23004
- robotFallback = tryRobotClientFallback
23005
- } = deps;
23006
- if (isRobotAuthEnforced()) {
23007
- if (isEnvAuthEnabled()) {
23008
- throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
23009
- }
23010
- const robotCreds = await robotFallback({ force: true });
23011
- if (!robotCreds) {
23012
- return {
23013
- loginStatus: "Not logged in",
23014
- hint: `${ENFORCE_ROBOT_AUTH_VAR}=true but the UiPath Robot ` + `session is unavailable. Start and sign in to the Assistant, ` + `or unset ${ENFORCE_ROBOT_AUTH_VAR} to fall back to file or ` + `env-var authentication.`
23015
- };
23016
- }
23017
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
23018
- return {
23019
- loginStatus: "Logged in",
23020
- accessToken: robotCreds.accessToken,
23021
- baseUrl: robotCreds.baseUrl,
23022
- organizationName: robotCreds.organizationName,
23023
- organizationId: robotCreds.organizationId,
23024
- tenantName: robotCreds.tenantName,
23025
- tenantId: robotCreds.tenantId,
23026
- issuer: robotCreds.issuer,
23027
- expiration: expiration2,
23028
- source: "robot" /* Robot */
23029
- };
23030
- }
23031
- if (isEnvAuthEnabled()) {
23032
- return readAuthFromEnv();
23033
- }
23034
- const { envFilePath = DEFAULT_ENV_FILENAME, ensureTokenValidityMinutes } = options;
23035
- const { absolutePath } = await resolveEnvFilePath(envFilePath);
23036
- if (absolutePath === undefined) {
23037
- const robotCreds = await robotFallback();
23038
- if (robotCreds) {
23039
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
23040
- const status = {
23041
- loginStatus: "Logged in",
23042
- accessToken: robotCreds.accessToken,
23043
- baseUrl: robotCreds.baseUrl,
23044
- organizationName: robotCreds.organizationName,
23045
- organizationId: robotCreds.organizationId,
23046
- tenantName: robotCreds.tenantName,
23047
- tenantId: robotCreds.tenantId,
23048
- issuer: robotCreds.issuer,
23049
- expiration: expiration2,
23050
- source: "robot" /* Robot */
23051
- };
23052
- return status;
23053
- }
23054
- return { loginStatus: "Not logged in" };
23055
- }
23056
- let credentials;
23057
- try {
23058
- credentials = await loadEnvFile({ envPath: absolutePath });
23059
- } catch (error) {
23060
- if (isFileNotFoundError(error)) {
23061
- return { loginStatus: "Not logged in" };
23062
- }
23063
- throw error;
23064
- }
23065
- if (!credentials.UIPATH_ACCESS_TOKEN) {
23066
- return { loginStatus: "Not logged in" };
23067
- }
23068
- let accessToken = credentials.UIPATH_ACCESS_TOKEN;
23069
- let refreshToken = credentials.UIPATH_REFRESH_TOKEN;
23070
- let expiration = getTokenExpiration(accessToken);
23071
- let persistenceWarning;
23072
- let lockReleaseFailed = false;
23073
- let tokenRefresh;
23074
- const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
23075
- const tryGlobalCredsHint = async () => {
23076
- const fs7 = getFs();
23077
- const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
23078
- if (absolutePath === globalPath)
23079
- return;
23080
- if (!await fs7.exists(globalPath))
23081
- return;
23082
- try {
23083
- const globalCreds = await loadEnvFile({ envPath: globalPath });
23084
- if (!globalCreds.UIPATH_ACCESS_TOKEN)
23085
- return;
23086
- const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
23087
- if (globalExp && globalExp <= new Date)
23088
- return;
23089
- return `Local credentials file at ${absolutePath} has expired credentials. Valid credentials exist in ${globalPath}. Remove the local file or run 'uip login' to re-authenticate.`;
23090
- } catch {
23091
- return;
23092
- }
23093
- };
23094
- if (expiration && expiration <= outerThreshold && refreshToken) {
23095
- let release;
23096
- try {
23097
- release = await getFs().acquireLock(absolutePath);
23098
- } catch (error) {
23099
- const msg = errorMessage(error);
23100
- const globalHint = await tryGlobalCredsHint();
23101
- if (globalHint) {
23102
- return {
23103
- loginStatus: "Expired",
23104
- accessToken,
23105
- refreshToken,
23106
- baseUrl: credentials.UIPATH_URL,
23107
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
23108
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
23109
- tenantName: credentials.UIPATH_TENANT_NAME,
23110
- tenantId: credentials.UIPATH_TENANT_ID,
23111
- expiration,
23112
- source: "file" /* File */,
23113
- hint: globalHint,
23114
- tokenRefresh: {
23115
- attempted: false,
23116
- success: false,
23117
- errorMessage: `lock acquisition failed: ${msg}`
23118
- }
23119
- };
23120
- }
23121
- return {
23122
- loginStatus: "Refresh Failed",
23123
- hint: "Could not acquire the auth-file lock — too many concurrent `uip` processes, or a permission issue on the auth directory. Retry, or run 'uip login' to re-authenticate.",
23124
- tokenRefresh: {
23125
- attempted: false,
23126
- success: false,
23127
- errorMessage: `lock acquisition failed: ${msg}`
23128
- }
23129
- };
23130
- }
23131
- let lockedFailure;
23132
- try {
23133
- const outcome = await runRefreshLocked({
23134
- absolutePath,
23135
- refreshToken,
23136
- customAuthority: credentials.UIPATH_URL,
23137
- ensureTokenValidityMinutes,
23138
- loadEnvFile,
23139
- saveEnvFile,
23140
- refreshFn: refreshTokenFn,
23141
- resolveConfig
23142
- });
23143
- if (outcome.kind === "fail") {
23144
- lockedFailure = outcome.status;
23145
- } else {
23146
- accessToken = outcome.accessToken;
23147
- refreshToken = outcome.refreshToken;
23148
- expiration = outcome.expiration;
23149
- tokenRefresh = outcome.tokenRefresh;
23150
- if (outcome.persistenceWarning) {
23151
- persistenceWarning = outcome.persistenceWarning;
23152
- }
23153
- }
23154
- } finally {
23155
- try {
23156
- await release();
23157
- } catch {
23158
- lockReleaseFailed = true;
23159
- }
23160
- }
23161
- if (lockedFailure) {
23162
- const globalHint = await tryGlobalCredsHint();
23163
- const base = globalHint ? {
23164
- ...lockedFailure,
23165
- loginStatus: "Expired",
23166
- hint: globalHint
23167
- } : lockedFailure;
23168
- return lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base;
23169
- }
23170
- }
23171
- const result = {
23172
- loginStatus: expiration && expiration <= new Date ? "Expired" : "Logged in",
23173
- accessToken,
23174
- refreshToken,
23175
- baseUrl: credentials.UIPATH_URL,
23176
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
23177
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
23178
- tenantName: credentials.UIPATH_TENANT_NAME,
23179
- tenantId: credentials.UIPATH_TENANT_ID,
23180
- expiration,
23181
- source: "file" /* File */,
23182
- ...persistenceWarning ? { hint: persistenceWarning, persistenceFailed: true } : {},
23183
- ...lockReleaseFailed ? { lockReleaseFailed: true } : {},
23184
- ...tokenRefresh ? { tokenRefresh } : {}
23185
- };
23186
- if (result.loginStatus === "Expired") {
23187
- const globalHint = await tryGlobalCredsHint();
23188
- if (globalHint) {
23189
- result.hint = globalHint;
23190
- }
23191
- }
23192
- return result;
23193
- };
23194
- var isFileNotFoundError = (error) => {
23195
- if (!(error instanceof Object))
23196
- return false;
23197
- return error.code === "ENOENT";
23198
- };
23199
- var getLoginStatusAsync = async (options = {}) => {
23200
- return getLoginStatusWithDeps(options);
23201
- };
23430
+ function normalizeTokenRefreshFailure() {
23431
+ return "stored refresh token is invalid or expired";
23432
+ }
23433
+ function normalizeTokenRefreshUnavailableFailure() {
23434
+ return "token refresh failed before authentication completed";
23435
+ }
23436
+ function errorMessage(error) {
23437
+ return error instanceof Error ? error.message : String(error);
23438
+ }
23202
23439
  // ../../auth/src/interactive.ts
23203
23440
  init_src();
23441
+
23442
+ // ../../auth/src/selectTenant.ts
23443
+ var TENANT_SELECTION_REQUIRED_CODE = "TENANT_SELECTION_REQUIRED";
23444
+ var INVALID_TENANT_CODE = "INVALID_TENANT";
23445
+ var TENANT_SELECTION_CODES = new Set([
23446
+ TENANT_SELECTION_REQUIRED_CODE,
23447
+ INVALID_TENANT_CODE
23448
+ ]);
23204
23449
  // ../../auth/src/logout.ts
23205
23450
  init_src();
23206
23451
 
@@ -23293,27 +23538,54 @@ var NETWORK_ERROR_CODES = new Set([
23293
23538
  "ENETUNREACH",
23294
23539
  "EAI_FAIL"
23295
23540
  ]);
23296
- function isHtmlDocument(body) {
23297
- return /^\s*(<!doctype html|<html\b)/i.test(body);
23298
- }
23299
- function extractNetworkErrorCode(error) {
23300
- if (error === null || typeof error !== "object") {
23301
- return;
23302
- }
23303
- const err = error;
23304
- const code = typeof err.code === "string" ? err.code : undefined;
23305
- if (code && NETWORK_ERROR_CODES.has(code)) {
23306
- return code;
23307
- }
23308
- const cause = err.cause;
23309
- if (cause !== null && typeof cause === "object") {
23310
- const causeCode = cause.code;
23311
- if (typeof causeCode === "string" && NETWORK_ERROR_CODES.has(causeCode)) {
23312
- return causeCode;
23541
+ var TLS_ERROR_CODES = new Set([
23542
+ "SELF_SIGNED_CERT_IN_CHAIN",
23543
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
23544
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
23545
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
23546
+ "UNABLE_TO_GET_ISSUER_CERT",
23547
+ "CERT_HAS_EXPIRED",
23548
+ "CERT_UNTRUSTED",
23549
+ "ERR_TLS_CERT_ALTNAME_INVALID"
23550
+ ]);
23551
+ var TLS_INSTRUCTIONS = "The server's TLS certificate could not be verified. Most often a " + "corporate proxy/firewall re-signs HTTPS with a root CA that Node does " + "not trust — set NODE_EXTRA_CA_CERTS to that CA's PEM file (and HTTPS_PROXY " + "if you connect through a proxy). If the certificate is instead expired or " + "its hostname does not match, fix the endpoint URL or the system clock. " + "Then retry.";
23552
+ var NETWORK_INSTRUCTIONS = "Could not reach the UiPath service. Check your network connection and " + "VPN, confirm any HTTP_PROXY/HTTPS_PROXY/NO_PROXY settings are correct, " + "then retry.";
23553
+ function describeConnectivityError(error) {
23554
+ let current = error;
23555
+ for (let depth = 0;depth < 5 && current !== null && typeof current === "object"; depth++) {
23556
+ const cur = current;
23557
+ const code = typeof cur.code === "string" ? cur.code : undefined;
23558
+ const message = typeof cur.message === "string" ? cur.message : undefined;
23559
+ if (code && TLS_ERROR_CODES.has(code)) {
23560
+ return {
23561
+ code,
23562
+ kind: "tls",
23563
+ message: message ?? code,
23564
+ instructions: TLS_INSTRUCTIONS
23565
+ };
23566
+ }
23567
+ if (code && NETWORK_ERROR_CODES.has(code)) {
23568
+ return {
23569
+ code,
23570
+ kind: "network",
23571
+ message: message ?? code,
23572
+ instructions: NETWORK_INSTRUCTIONS
23573
+ };
23313
23574
  }
23575
+ current = cur.cause;
23314
23576
  }
23315
23577
  return;
23316
23578
  }
23579
+ function parseHttpStatusFromMessage(message) {
23580
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
23581
+ if (!match)
23582
+ return;
23583
+ const status = Number(match[1]);
23584
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
23585
+ }
23586
+ function isHtmlDocument(body) {
23587
+ return /^\s*(<!doctype html|<html\b)/i.test(body);
23588
+ }
23317
23589
  function retryHintForRetryAfter(seconds) {
23318
23590
  if (seconds <= 1) {
23319
23591
  return "RetryAfter1Second";
@@ -23354,15 +23626,28 @@ function classifyError(status, error) {
23354
23626
  if (status !== undefined && status >= 500 && status < 600) {
23355
23627
  return { errorCode: "server_error", retry: "RetryLater" };
23356
23628
  }
23357
- if (extractNetworkErrorCode(error)) {
23358
- return { errorCode: "network_error", retry: "RetryLater" };
23629
+ const connectivity = describeConnectivityError(error);
23630
+ if (connectivity) {
23631
+ return {
23632
+ errorCode: "network_error",
23633
+ retry: connectivity.kind === "tls" ? "RetryWillNotFix" : "RetryLater"
23634
+ };
23359
23635
  }
23360
23636
  return { errorCode: "unknown_error", retry: "RetryWillNotFix" };
23361
23637
  }
23638
+ function formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus) {
23639
+ if (extractedMessage) {
23640
+ return `HTTP ${status}: ${extractedMessage}`;
23641
+ }
23642
+ return inferredStatus !== undefined ? rawMessage : `HTTP ${status}: ${rawMessage}`;
23643
+ }
23362
23644
  async function extractErrorDetails(error, options) {
23363
23645
  const err = error !== null && error !== undefined && typeof error === "object" ? error : {};
23364
23646
  const response = err.response;
23365
- const status = err.status ?? response?.status;
23647
+ const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
23648
+ const explicitStatus = err.status ?? response?.status;
23649
+ const inferredStatus = explicitStatus === undefined ? parseHttpStatusFromMessage(rawMessage) : undefined;
23650
+ const status = explicitStatus ?? inferredStatus;
23366
23651
  const isSuccessfulResponse = status !== undefined && status >= 200 && status < 300;
23367
23652
  let rawBody;
23368
23653
  let extractedMessage;
@@ -23397,7 +23682,6 @@ async function extractErrorDetails(error, options) {
23397
23682
  }
23398
23683
  }
23399
23684
  }
23400
- const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
23401
23685
  let message;
23402
23686
  let result = "Failure";
23403
23687
  const classification = classifyError(status, error);
@@ -23411,10 +23695,10 @@ async function extractErrorDetails(error, options) {
23411
23695
  } else if (status === 405) {
23412
23696
  message = DEFAULT_405;
23413
23697
  } else if (status === 400 || status === 422) {
23414
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
23698
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
23415
23699
  result = "ValidationError";
23416
23700
  } else if (status === 429) {
23417
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
23701
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
23418
23702
  } else if (extractedMessage) {
23419
23703
  if (isSuccessfulResponse && rawMessage !== "Unknown error") {
23420
23704
  message = rawMessage;
@@ -23422,7 +23706,9 @@ async function extractErrorDetails(error, options) {
23422
23706
  message = status ? `HTTP ${status}: ${extractedMessage}` : extractedMessage;
23423
23707
  }
23424
23708
  } else if (status) {
23425
- if (rawMessage === "Unknown error" && response) {
23709
+ if (inferredStatus !== undefined) {
23710
+ message = rawMessage;
23711
+ } else if (rawMessage === "Unknown error" && response) {
23426
23712
  const statusText = response.statusText;
23427
23713
  message = statusText ? `HTTP ${status} ${statusText}` : `HTTP ${status} - request failed`;
23428
23714
  } else {
@@ -23431,6 +23717,12 @@ async function extractErrorDetails(error, options) {
23431
23717
  } else {
23432
23718
  message = rawMessage;
23433
23719
  }
23720
+ if (status === undefined) {
23721
+ const connectivity = describeConnectivityError(error);
23722
+ if (connectivity && connectivity.message !== message && !message.includes(connectivity.message)) {
23723
+ message = `${message}: ${connectivity.message}`;
23724
+ }
23725
+ }
23434
23726
  let details = rawMessage;
23435
23727
  if (rawBody) {
23436
23728
  if (parsedBody) {
@@ -23568,6 +23860,7 @@ var CONSOLE_FALLBACK = {
23568
23860
  writeLog: (str) => process.stdout.write(str),
23569
23861
  capabilities: {
23570
23862
  isInteractive: false,
23863
+ canReadInput: false,
23571
23864
  supportsColor: false,
23572
23865
  outputWidth: 80
23573
23866
  }
@@ -28573,12 +28866,6 @@ class NodeContextStorage {
28573
28866
  return this.storage.getStore();
28574
28867
  }
28575
28868
  }
28576
- // ../../common/src/telemetry/global-telemetry-properties.ts
28577
- var telemetryPropsSlot = singleton("TelemetryDefaultProps");
28578
- function getGlobalTelemetryProperties() {
28579
- return telemetryPropsSlot.get();
28580
- }
28581
-
28582
28869
  // ../../common/src/telemetry/telemetry-service.ts
28583
28870
  class TelemetryService {
28584
28871
  telemetryProvider;
@@ -28768,6 +29055,29 @@ function isPlainRecord(value) {
28768
29055
  const prototype = Object.getPrototypeOf(value);
28769
29056
  return prototype === Object.prototype || prototype === null;
28770
29057
  }
29058
+ function extractPagedRows(value) {
29059
+ if (Array.isArray(value) || !isPlainRecord(value))
29060
+ return null;
29061
+ const entries = Object.values(value);
29062
+ if (entries.length === 0)
29063
+ return null;
29064
+ let rows = null;
29065
+ let hasScalarSibling = false;
29066
+ for (const entry of entries) {
29067
+ if (Array.isArray(entry)) {
29068
+ if (rows !== null)
29069
+ return null;
29070
+ rows = entry;
29071
+ } else if (entry !== null && typeof entry === "object") {
29072
+ return null;
29073
+ } else {
29074
+ hasScalarSibling = true;
29075
+ }
29076
+ }
29077
+ if (rows === null || !hasScalarSibling)
29078
+ return null;
29079
+ return rows;
29080
+ }
28771
29081
  function toLowerCamelCaseKey(key) {
28772
29082
  if (!key)
28773
29083
  return key;
@@ -28832,7 +29142,8 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
28832
29142
  break;
28833
29143
  case "plain": {
28834
29144
  if ("Data" in data && data.Data != null) {
28835
- const items = Array.isArray(data.Data) ? data.Data : [data.Data];
29145
+ const pagedRows = extractPagedRows(data.Data);
29146
+ const items = pagedRows ?? (Array.isArray(data.Data) ? data.Data : [data.Data]);
28836
29147
  items.forEach((item) => {
28837
29148
  const values = Object.values(item).map((v) => v ?? "").join("\t");
28838
29149
  logFn(values);
@@ -28844,10 +29155,13 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
28844
29155
  break;
28845
29156
  }
28846
29157
  default: {
28847
- if ("Data" in data && data.Data != null && !(Array.isArray(data.Data) && data.Data.length === 0)) {
29158
+ const hasData = "Data" in data && data.Data != null;
29159
+ const pagedRows = hasData ? extractPagedRows(data.Data) : null;
29160
+ const rows = pagedRows ? pagedRows : Array.isArray(data.Data) ? data.Data : null;
29161
+ if (hasData && !(rows !== null && rows.length === 0)) {
28848
29162
  const logValue = data.Log;
28849
- if (Array.isArray(data.Data)) {
28850
- printResizableTable(data.Data, logFn, logValue);
29163
+ if (rows !== null) {
29164
+ printResizableTable(rows, logFn, logValue);
28851
29165
  } else {
28852
29166
  printVerticalTable(data.Data, logFn, logValue);
28853
29167
  }
@@ -29035,6 +29349,44 @@ function defaultErrorCodeForResult(result) {
29035
29349
  return "unknown_error";
29036
29350
  }
29037
29351
  }
29352
+ function parseHttpStatusFromMessage2(message) {
29353
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
29354
+ if (!match)
29355
+ return;
29356
+ const status = Number(match[1]);
29357
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
29358
+ }
29359
+ function defaultErrorCodeForHttpStatus(status) {
29360
+ if (status === undefined)
29361
+ return;
29362
+ if (status === 400 || status === 409 || status === 422) {
29363
+ return "invalid_argument";
29364
+ }
29365
+ if (status === 401)
29366
+ return "authentication_required";
29367
+ if (status === 403)
29368
+ return "permission_denied";
29369
+ if (status === 404)
29370
+ return "not_found";
29371
+ if (status === 405)
29372
+ return "method_not_allowed";
29373
+ if (status === 408)
29374
+ return "timeout";
29375
+ if (status === 429)
29376
+ return "rate_limited";
29377
+ if (status >= 500 && status < 600)
29378
+ return "server_error";
29379
+ return;
29380
+ }
29381
+ function defaultErrorCodeForFailure(data) {
29382
+ if (data.Result === RESULTS.Failure) {
29383
+ const status = data.Context?.httpStatus ?? parseHttpStatusFromMessage2(data.Message);
29384
+ const errorCode2 = defaultErrorCodeForHttpStatus(status);
29385
+ if (errorCode2)
29386
+ return errorCode2;
29387
+ }
29388
+ return defaultErrorCodeForResult(data.Result);
29389
+ }
29038
29390
  function defaultRetryForErrorCode(errorCode2) {
29039
29391
  switch (errorCode2) {
29040
29392
  case "network_error":
@@ -29064,16 +29416,19 @@ var OutputFormatter;
29064
29416
  OutputFormatter.success = success;
29065
29417
  function error(data) {
29066
29418
  data.Log ??= getLogFilePath() || undefined;
29067
- data.ErrorCode ??= defaultErrorCodeForResult(data.Result);
29419
+ data.ErrorCode ??= defaultErrorCodeForFailure(data);
29068
29420
  data.Retry ??= defaultRetryForErrorCode(data.ErrorCode);
29069
29421
  process.exitCode = EXIT_CODES[data.Result] ?? 1;
29070
- telemetry.trackEvent(CommonTelemetryEvents.Error, {
29071
- result: data.Result,
29072
- errorCode: data.ErrorCode,
29073
- retry: data.Retry,
29074
- message: data.Message
29075
- });
29076
- logOutput(normalizeOutputKeys(data), getOutputFormat());
29422
+ const { SuppressTelemetry, ...envelope } = data;
29423
+ if (!SuppressTelemetry) {
29424
+ telemetry.trackEvent(CommonTelemetryEvents.Error, {
29425
+ result: data.Result,
29426
+ errorCode: data.ErrorCode,
29427
+ retry: data.Retry,
29428
+ message: data.Message
29429
+ });
29430
+ }
29431
+ logOutput(normalizeOutputKeys(envelope), getOutputFormat());
29077
29432
  }
29078
29433
  OutputFormatter.error = error;
29079
29434
  function emitList(code, items, opts) {
@@ -29363,1409 +29718,6 @@ var savedOriginalsSlot = singleton("ConsoleGuardOriginals");
29363
29718
  var DEFAULT_AUTH_TIMEOUT_MS2 = 5 * 60 * 1000;
29364
29719
  // ../../common/src/interactivity-context.ts
29365
29720
  var modeSlot = singleton("InteractivityMode");
29366
- // ../../../node_modules/jsonpath-plus/dist/index-node-esm.js
29367
- import vm from "vm";
29368
-
29369
- class Hooks {
29370
- add(name, callback, first) {
29371
- if (typeof arguments[0] != "string") {
29372
- for (let name2 in arguments[0]) {
29373
- this.add(name2, arguments[0][name2], arguments[1]);
29374
- }
29375
- } else {
29376
- (Array.isArray(name) ? name : [name]).forEach(function(name2) {
29377
- this[name2] = this[name2] || [];
29378
- if (callback) {
29379
- this[name2][first ? "unshift" : "push"](callback);
29380
- }
29381
- }, this);
29382
- }
29383
- }
29384
- run(name, env) {
29385
- this[name] = this[name] || [];
29386
- this[name].forEach(function(callback) {
29387
- callback.call(env && env.context ? env.context : env, env);
29388
- });
29389
- }
29390
- }
29391
-
29392
- class Plugins {
29393
- constructor(jsep) {
29394
- this.jsep = jsep;
29395
- this.registered = {};
29396
- }
29397
- register(...plugins) {
29398
- plugins.forEach((plugin) => {
29399
- if (typeof plugin !== "object" || !plugin.name || !plugin.init) {
29400
- throw new Error("Invalid JSEP plugin format");
29401
- }
29402
- if (this.registered[plugin.name]) {
29403
- return;
29404
- }
29405
- plugin.init(this.jsep);
29406
- this.registered[plugin.name] = plugin;
29407
- });
29408
- }
29409
- }
29410
-
29411
- class Jsep {
29412
- static get version() {
29413
- return "1.4.0";
29414
- }
29415
- static toString() {
29416
- return "JavaScript Expression Parser (JSEP) v" + Jsep.version;
29417
- }
29418
- static addUnaryOp(op_name) {
29419
- Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);
29420
- Jsep.unary_ops[op_name] = 1;
29421
- return Jsep;
29422
- }
29423
- static addBinaryOp(op_name, precedence, isRightAssociative) {
29424
- Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);
29425
- Jsep.binary_ops[op_name] = precedence;
29426
- if (isRightAssociative) {
29427
- Jsep.right_associative.add(op_name);
29428
- } else {
29429
- Jsep.right_associative.delete(op_name);
29430
- }
29431
- return Jsep;
29432
- }
29433
- static addIdentifierChar(char) {
29434
- Jsep.additional_identifier_chars.add(char);
29435
- return Jsep;
29436
- }
29437
- static addLiteral(literal_name, literal_value) {
29438
- Jsep.literals[literal_name] = literal_value;
29439
- return Jsep;
29440
- }
29441
- static removeUnaryOp(op_name) {
29442
- delete Jsep.unary_ops[op_name];
29443
- if (op_name.length === Jsep.max_unop_len) {
29444
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
29445
- }
29446
- return Jsep;
29447
- }
29448
- static removeAllUnaryOps() {
29449
- Jsep.unary_ops = {};
29450
- Jsep.max_unop_len = 0;
29451
- return Jsep;
29452
- }
29453
- static removeIdentifierChar(char) {
29454
- Jsep.additional_identifier_chars.delete(char);
29455
- return Jsep;
29456
- }
29457
- static removeBinaryOp(op_name) {
29458
- delete Jsep.binary_ops[op_name];
29459
- if (op_name.length === Jsep.max_binop_len) {
29460
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
29461
- }
29462
- Jsep.right_associative.delete(op_name);
29463
- return Jsep;
29464
- }
29465
- static removeAllBinaryOps() {
29466
- Jsep.binary_ops = {};
29467
- Jsep.max_binop_len = 0;
29468
- return Jsep;
29469
- }
29470
- static removeLiteral(literal_name) {
29471
- delete Jsep.literals[literal_name];
29472
- return Jsep;
29473
- }
29474
- static removeAllLiterals() {
29475
- Jsep.literals = {};
29476
- return Jsep;
29477
- }
29478
- get char() {
29479
- return this.expr.charAt(this.index);
29480
- }
29481
- get code() {
29482
- return this.expr.charCodeAt(this.index);
29483
- }
29484
- constructor(expr) {
29485
- this.expr = expr;
29486
- this.index = 0;
29487
- }
29488
- static parse(expr) {
29489
- return new Jsep(expr).parse();
29490
- }
29491
- static getMaxKeyLen(obj) {
29492
- return Math.max(0, ...Object.keys(obj).map((k) => k.length));
29493
- }
29494
- static isDecimalDigit(ch) {
29495
- return ch >= 48 && ch <= 57;
29496
- }
29497
- static binaryPrecedence(op_val) {
29498
- return Jsep.binary_ops[op_val] || 0;
29499
- }
29500
- static isIdentifierStart(ch) {
29501
- return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 || ch >= 128 && !Jsep.binary_ops[String.fromCharCode(ch)] || Jsep.additional_identifier_chars.has(String.fromCharCode(ch));
29502
- }
29503
- static isIdentifierPart(ch) {
29504
- return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);
29505
- }
29506
- throwError(message) {
29507
- const error = new Error(message + " at character " + this.index);
29508
- error.index = this.index;
29509
- error.description = message;
29510
- throw error;
29511
- }
29512
- runHook(name, node) {
29513
- if (Jsep.hooks[name]) {
29514
- const env = {
29515
- context: this,
29516
- node
29517
- };
29518
- Jsep.hooks.run(name, env);
29519
- return env.node;
29520
- }
29521
- return node;
29522
- }
29523
- searchHook(name) {
29524
- if (Jsep.hooks[name]) {
29525
- const env = {
29526
- context: this
29527
- };
29528
- Jsep.hooks[name].find(function(callback) {
29529
- callback.call(env.context, env);
29530
- return env.node;
29531
- });
29532
- return env.node;
29533
- }
29534
- }
29535
- gobbleSpaces() {
29536
- let ch = this.code;
29537
- while (ch === Jsep.SPACE_CODE || ch === Jsep.TAB_CODE || ch === Jsep.LF_CODE || ch === Jsep.CR_CODE) {
29538
- ch = this.expr.charCodeAt(++this.index);
29539
- }
29540
- this.runHook("gobble-spaces");
29541
- }
29542
- parse() {
29543
- this.runHook("before-all");
29544
- const nodes = this.gobbleExpressions();
29545
- const node = nodes.length === 1 ? nodes[0] : {
29546
- type: Jsep.COMPOUND,
29547
- body: nodes
29548
- };
29549
- return this.runHook("after-all", node);
29550
- }
29551
- gobbleExpressions(untilICode) {
29552
- let nodes = [], ch_i, node;
29553
- while (this.index < this.expr.length) {
29554
- ch_i = this.code;
29555
- if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) {
29556
- this.index++;
29557
- } else {
29558
- if (node = this.gobbleExpression()) {
29559
- nodes.push(node);
29560
- } else if (this.index < this.expr.length) {
29561
- if (ch_i === untilICode) {
29562
- break;
29563
- }
29564
- this.throwError('Unexpected "' + this.char + '"');
29565
- }
29566
- }
29567
- }
29568
- return nodes;
29569
- }
29570
- gobbleExpression() {
29571
- const node = this.searchHook("gobble-expression") || this.gobbleBinaryExpression();
29572
- this.gobbleSpaces();
29573
- return this.runHook("after-expression", node);
29574
- }
29575
- gobbleBinaryOp() {
29576
- this.gobbleSpaces();
29577
- let to_check = this.expr.substr(this.index, Jsep.max_binop_len);
29578
- let tc_len = to_check.length;
29579
- while (tc_len > 0) {
29580
- if (Jsep.binary_ops.hasOwnProperty(to_check) && (!Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {
29581
- this.index += tc_len;
29582
- return to_check;
29583
- }
29584
- to_check = to_check.substr(0, --tc_len);
29585
- }
29586
- return false;
29587
- }
29588
- gobbleBinaryExpression() {
29589
- let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
29590
- left = this.gobbleToken();
29591
- if (!left) {
29592
- return left;
29593
- }
29594
- biop = this.gobbleBinaryOp();
29595
- if (!biop) {
29596
- return left;
29597
- }
29598
- biop_info = {
29599
- value: biop,
29600
- prec: Jsep.binaryPrecedence(biop),
29601
- right_a: Jsep.right_associative.has(biop)
29602
- };
29603
- right = this.gobbleToken();
29604
- if (!right) {
29605
- this.throwError("Expected expression after " + biop);
29606
- }
29607
- stack = [left, biop_info, right];
29608
- while (biop = this.gobbleBinaryOp()) {
29609
- prec = Jsep.binaryPrecedence(biop);
29610
- if (prec === 0) {
29611
- this.index -= biop.length;
29612
- break;
29613
- }
29614
- biop_info = {
29615
- value: biop,
29616
- prec,
29617
- right_a: Jsep.right_associative.has(biop)
29618
- };
29619
- cur_biop = biop;
29620
- const comparePrev = (prev) => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
29621
- while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
29622
- right = stack.pop();
29623
- biop = stack.pop().value;
29624
- left = stack.pop();
29625
- node = {
29626
- type: Jsep.BINARY_EXP,
29627
- operator: biop,
29628
- left,
29629
- right
29630
- };
29631
- stack.push(node);
29632
- }
29633
- node = this.gobbleToken();
29634
- if (!node) {
29635
- this.throwError("Expected expression after " + cur_biop);
29636
- }
29637
- stack.push(biop_info, node);
29638
- }
29639
- i = stack.length - 1;
29640
- node = stack[i];
29641
- while (i > 1) {
29642
- node = {
29643
- type: Jsep.BINARY_EXP,
29644
- operator: stack[i - 1].value,
29645
- left: stack[i - 2],
29646
- right: node
29647
- };
29648
- i -= 2;
29649
- }
29650
- return node;
29651
- }
29652
- gobbleToken() {
29653
- let ch, to_check, tc_len, node;
29654
- this.gobbleSpaces();
29655
- node = this.searchHook("gobble-token");
29656
- if (node) {
29657
- return this.runHook("after-token", node);
29658
- }
29659
- ch = this.code;
29660
- if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) {
29661
- return this.gobbleNumericLiteral();
29662
- }
29663
- if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) {
29664
- node = this.gobbleStringLiteral();
29665
- } else if (ch === Jsep.OBRACK_CODE) {
29666
- node = this.gobbleArray();
29667
- } else {
29668
- to_check = this.expr.substr(this.index, Jsep.max_unop_len);
29669
- tc_len = to_check.length;
29670
- while (tc_len > 0) {
29671
- if (Jsep.unary_ops.hasOwnProperty(to_check) && (!Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {
29672
- this.index += tc_len;
29673
- const argument = this.gobbleToken();
29674
- if (!argument) {
29675
- this.throwError("missing unaryOp argument");
29676
- }
29677
- return this.runHook("after-token", {
29678
- type: Jsep.UNARY_EXP,
29679
- operator: to_check,
29680
- argument,
29681
- prefix: true
29682
- });
29683
- }
29684
- to_check = to_check.substr(0, --tc_len);
29685
- }
29686
- if (Jsep.isIdentifierStart(ch)) {
29687
- node = this.gobbleIdentifier();
29688
- if (Jsep.literals.hasOwnProperty(node.name)) {
29689
- node = {
29690
- type: Jsep.LITERAL,
29691
- value: Jsep.literals[node.name],
29692
- raw: node.name
29693
- };
29694
- } else if (node.name === Jsep.this_str) {
29695
- node = {
29696
- type: Jsep.THIS_EXP
29697
- };
29698
- }
29699
- } else if (ch === Jsep.OPAREN_CODE) {
29700
- node = this.gobbleGroup();
29701
- }
29702
- }
29703
- if (!node) {
29704
- return this.runHook("after-token", false);
29705
- }
29706
- node = this.gobbleTokenProperty(node);
29707
- return this.runHook("after-token", node);
29708
- }
29709
- gobbleTokenProperty(node) {
29710
- this.gobbleSpaces();
29711
- let ch = this.code;
29712
- while (ch === Jsep.PERIOD_CODE || ch === Jsep.OBRACK_CODE || ch === Jsep.OPAREN_CODE || ch === Jsep.QUMARK_CODE) {
29713
- let optional;
29714
- if (ch === Jsep.QUMARK_CODE) {
29715
- if (this.expr.charCodeAt(this.index + 1) !== Jsep.PERIOD_CODE) {
29716
- break;
29717
- }
29718
- optional = true;
29719
- this.index += 2;
29720
- this.gobbleSpaces();
29721
- ch = this.code;
29722
- }
29723
- this.index++;
29724
- if (ch === Jsep.OBRACK_CODE) {
29725
- node = {
29726
- type: Jsep.MEMBER_EXP,
29727
- computed: true,
29728
- object: node,
29729
- property: this.gobbleExpression()
29730
- };
29731
- if (!node.property) {
29732
- this.throwError('Unexpected "' + this.char + '"');
29733
- }
29734
- this.gobbleSpaces();
29735
- ch = this.code;
29736
- if (ch !== Jsep.CBRACK_CODE) {
29737
- this.throwError("Unclosed [");
29738
- }
29739
- this.index++;
29740
- } else if (ch === Jsep.OPAREN_CODE) {
29741
- node = {
29742
- type: Jsep.CALL_EXP,
29743
- arguments: this.gobbleArguments(Jsep.CPAREN_CODE),
29744
- callee: node
29745
- };
29746
- } else if (ch === Jsep.PERIOD_CODE || optional) {
29747
- if (optional) {
29748
- this.index--;
29749
- }
29750
- this.gobbleSpaces();
29751
- node = {
29752
- type: Jsep.MEMBER_EXP,
29753
- computed: false,
29754
- object: node,
29755
- property: this.gobbleIdentifier()
29756
- };
29757
- }
29758
- if (optional) {
29759
- node.optional = true;
29760
- }
29761
- this.gobbleSpaces();
29762
- ch = this.code;
29763
- }
29764
- return node;
29765
- }
29766
- gobbleNumericLiteral() {
29767
- let number = "", ch, chCode;
29768
- while (Jsep.isDecimalDigit(this.code)) {
29769
- number += this.expr.charAt(this.index++);
29770
- }
29771
- if (this.code === Jsep.PERIOD_CODE) {
29772
- number += this.expr.charAt(this.index++);
29773
- while (Jsep.isDecimalDigit(this.code)) {
29774
- number += this.expr.charAt(this.index++);
29775
- }
29776
- }
29777
- ch = this.char;
29778
- if (ch === "e" || ch === "E") {
29779
- number += this.expr.charAt(this.index++);
29780
- ch = this.char;
29781
- if (ch === "+" || ch === "-") {
29782
- number += this.expr.charAt(this.index++);
29783
- }
29784
- while (Jsep.isDecimalDigit(this.code)) {
29785
- number += this.expr.charAt(this.index++);
29786
- }
29787
- if (!Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {
29788
- this.throwError("Expected exponent (" + number + this.char + ")");
29789
- }
29790
- }
29791
- chCode = this.code;
29792
- if (Jsep.isIdentifierStart(chCode)) {
29793
- this.throwError("Variable names cannot start with a number (" + number + this.char + ")");
29794
- } else if (chCode === Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === Jsep.PERIOD_CODE) {
29795
- this.throwError("Unexpected period");
29796
- }
29797
- return {
29798
- type: Jsep.LITERAL,
29799
- value: parseFloat(number),
29800
- raw: number
29801
- };
29802
- }
29803
- gobbleStringLiteral() {
29804
- let str = "";
29805
- const startIndex = this.index;
29806
- const quote = this.expr.charAt(this.index++);
29807
- let closed = false;
29808
- while (this.index < this.expr.length) {
29809
- let ch = this.expr.charAt(this.index++);
29810
- if (ch === quote) {
29811
- closed = true;
29812
- break;
29813
- } else if (ch === "\\") {
29814
- ch = this.expr.charAt(this.index++);
29815
- switch (ch) {
29816
- case "n":
29817
- str += `
29818
- `;
29819
- break;
29820
- case "r":
29821
- str += "\r";
29822
- break;
29823
- case "t":
29824
- str += "\t";
29825
- break;
29826
- case "b":
29827
- str += "\b";
29828
- break;
29829
- case "f":
29830
- str += "\f";
29831
- break;
29832
- case "v":
29833
- str += "\v";
29834
- break;
29835
- default:
29836
- str += ch;
29837
- }
29838
- } else {
29839
- str += ch;
29840
- }
29841
- }
29842
- if (!closed) {
29843
- this.throwError('Unclosed quote after "' + str + '"');
29844
- }
29845
- return {
29846
- type: Jsep.LITERAL,
29847
- value: str,
29848
- raw: this.expr.substring(startIndex, this.index)
29849
- };
29850
- }
29851
- gobbleIdentifier() {
29852
- let ch = this.code, start = this.index;
29853
- if (Jsep.isIdentifierStart(ch)) {
29854
- this.index++;
29855
- } else {
29856
- this.throwError("Unexpected " + this.char);
29857
- }
29858
- while (this.index < this.expr.length) {
29859
- ch = this.code;
29860
- if (Jsep.isIdentifierPart(ch)) {
29861
- this.index++;
29862
- } else {
29863
- break;
29864
- }
29865
- }
29866
- return {
29867
- type: Jsep.IDENTIFIER,
29868
- name: this.expr.slice(start, this.index)
29869
- };
29870
- }
29871
- gobbleArguments(termination) {
29872
- const args = [];
29873
- let closed = false;
29874
- let separator_count = 0;
29875
- while (this.index < this.expr.length) {
29876
- this.gobbleSpaces();
29877
- let ch_i = this.code;
29878
- if (ch_i === termination) {
29879
- closed = true;
29880
- this.index++;
29881
- if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {
29882
- this.throwError("Unexpected token " + String.fromCharCode(termination));
29883
- }
29884
- break;
29885
- } else if (ch_i === Jsep.COMMA_CODE) {
29886
- this.index++;
29887
- separator_count++;
29888
- if (separator_count !== args.length) {
29889
- if (termination === Jsep.CPAREN_CODE) {
29890
- this.throwError("Unexpected token ,");
29891
- } else if (termination === Jsep.CBRACK_CODE) {
29892
- for (let arg = args.length;arg < separator_count; arg++) {
29893
- args.push(null);
29894
- }
29895
- }
29896
- }
29897
- } else if (args.length !== separator_count && separator_count !== 0) {
29898
- this.throwError("Expected comma");
29899
- } else {
29900
- const node = this.gobbleExpression();
29901
- if (!node || node.type === Jsep.COMPOUND) {
29902
- this.throwError("Expected comma");
29903
- }
29904
- args.push(node);
29905
- }
29906
- }
29907
- if (!closed) {
29908
- this.throwError("Expected " + String.fromCharCode(termination));
29909
- }
29910
- return args;
29911
- }
29912
- gobbleGroup() {
29913
- this.index++;
29914
- let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);
29915
- if (this.code === Jsep.CPAREN_CODE) {
29916
- this.index++;
29917
- if (nodes.length === 1) {
29918
- return nodes[0];
29919
- } else if (!nodes.length) {
29920
- return false;
29921
- } else {
29922
- return {
29923
- type: Jsep.SEQUENCE_EXP,
29924
- expressions: nodes
29925
- };
29926
- }
29927
- } else {
29928
- this.throwError("Unclosed (");
29929
- }
29930
- }
29931
- gobbleArray() {
29932
- this.index++;
29933
- return {
29934
- type: Jsep.ARRAY_EXP,
29935
- elements: this.gobbleArguments(Jsep.CBRACK_CODE)
29936
- };
29937
- }
29938
- }
29939
- var hooks = new Hooks;
29940
- Object.assign(Jsep, {
29941
- hooks,
29942
- plugins: new Plugins(Jsep),
29943
- COMPOUND: "Compound",
29944
- SEQUENCE_EXP: "SequenceExpression",
29945
- IDENTIFIER: "Identifier",
29946
- MEMBER_EXP: "MemberExpression",
29947
- LITERAL: "Literal",
29948
- THIS_EXP: "ThisExpression",
29949
- CALL_EXP: "CallExpression",
29950
- UNARY_EXP: "UnaryExpression",
29951
- BINARY_EXP: "BinaryExpression",
29952
- ARRAY_EXP: "ArrayExpression",
29953
- TAB_CODE: 9,
29954
- LF_CODE: 10,
29955
- CR_CODE: 13,
29956
- SPACE_CODE: 32,
29957
- PERIOD_CODE: 46,
29958
- COMMA_CODE: 44,
29959
- SQUOTE_CODE: 39,
29960
- DQUOTE_CODE: 34,
29961
- OPAREN_CODE: 40,
29962
- CPAREN_CODE: 41,
29963
- OBRACK_CODE: 91,
29964
- CBRACK_CODE: 93,
29965
- QUMARK_CODE: 63,
29966
- SEMCOL_CODE: 59,
29967
- COLON_CODE: 58,
29968
- unary_ops: {
29969
- "-": 1,
29970
- "!": 1,
29971
- "~": 1,
29972
- "+": 1
29973
- },
29974
- binary_ops: {
29975
- "||": 1,
29976
- "??": 1,
29977
- "&&": 2,
29978
- "|": 3,
29979
- "^": 4,
29980
- "&": 5,
29981
- "==": 6,
29982
- "!=": 6,
29983
- "===": 6,
29984
- "!==": 6,
29985
- "<": 7,
29986
- ">": 7,
29987
- "<=": 7,
29988
- ">=": 7,
29989
- "<<": 8,
29990
- ">>": 8,
29991
- ">>>": 8,
29992
- "+": 9,
29993
- "-": 9,
29994
- "*": 10,
29995
- "/": 10,
29996
- "%": 10,
29997
- "**": 11
29998
- },
29999
- right_associative: new Set(["**"]),
30000
- additional_identifier_chars: new Set(["$", "_"]),
30001
- literals: {
30002
- true: true,
30003
- false: false,
30004
- null: null
30005
- },
30006
- this_str: "this"
30007
- });
30008
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
30009
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
30010
- var jsep = (expr) => new Jsep(expr).parse();
30011
- var stdClassProps = Object.getOwnPropertyNames(class Test {
30012
- });
30013
- Object.getOwnPropertyNames(Jsep).filter((prop) => !stdClassProps.includes(prop) && jsep[prop] === undefined).forEach((m) => {
30014
- jsep[m] = Jsep[m];
30015
- });
30016
- jsep.Jsep = Jsep;
30017
- var CONDITIONAL_EXP = "ConditionalExpression";
30018
- var ternary = {
30019
- name: "ternary",
30020
- init(jsep2) {
30021
- jsep2.hooks.add("after-expression", function gobbleTernary(env) {
30022
- if (env.node && this.code === jsep2.QUMARK_CODE) {
30023
- this.index++;
30024
- const test = env.node;
30025
- const consequent = this.gobbleExpression();
30026
- if (!consequent) {
30027
- this.throwError("Expected expression");
30028
- }
30029
- this.gobbleSpaces();
30030
- if (this.code === jsep2.COLON_CODE) {
30031
- this.index++;
30032
- const alternate = this.gobbleExpression();
30033
- if (!alternate) {
30034
- this.throwError("Expected expression");
30035
- }
30036
- env.node = {
30037
- type: CONDITIONAL_EXP,
30038
- test,
30039
- consequent,
30040
- alternate
30041
- };
30042
- if (test.operator && jsep2.binary_ops[test.operator] <= 0.9) {
30043
- let newTest = test;
30044
- while (newTest.right.operator && jsep2.binary_ops[newTest.right.operator] <= 0.9) {
30045
- newTest = newTest.right;
30046
- }
30047
- env.node.test = newTest.right;
30048
- newTest.right = env.node;
30049
- env.node = test;
30050
- }
30051
- } else {
30052
- this.throwError("Expected :");
30053
- }
30054
- }
30055
- });
30056
- }
30057
- };
30058
- jsep.plugins.register(ternary);
30059
- var FSLASH_CODE = 47;
30060
- var BSLASH_CODE = 92;
30061
- var index = {
30062
- name: "regex",
30063
- init(jsep2) {
30064
- jsep2.hooks.add("gobble-token", function gobbleRegexLiteral(env) {
30065
- if (this.code === FSLASH_CODE) {
30066
- const patternIndex = ++this.index;
30067
- let inCharSet = false;
30068
- while (this.index < this.expr.length) {
30069
- if (this.code === FSLASH_CODE && !inCharSet) {
30070
- const pattern = this.expr.slice(patternIndex, this.index);
30071
- let flags = "";
30072
- while (++this.index < this.expr.length) {
30073
- const code = this.code;
30074
- if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57) {
30075
- flags += this.char;
30076
- } else {
30077
- break;
30078
- }
30079
- }
30080
- let value;
30081
- try {
30082
- value = new RegExp(pattern, flags);
30083
- } catch (e) {
30084
- this.throwError(e.message);
30085
- }
30086
- env.node = {
30087
- type: jsep2.LITERAL,
30088
- value,
30089
- raw: this.expr.slice(patternIndex - 1, this.index)
30090
- };
30091
- env.node = this.gobbleTokenProperty(env.node);
30092
- return env.node;
30093
- }
30094
- if (this.code === jsep2.OBRACK_CODE) {
30095
- inCharSet = true;
30096
- } else if (inCharSet && this.code === jsep2.CBRACK_CODE) {
30097
- inCharSet = false;
30098
- }
30099
- this.index += this.code === BSLASH_CODE ? 2 : 1;
30100
- }
30101
- this.throwError("Unclosed Regex");
30102
- }
30103
- });
30104
- }
30105
- };
30106
- var PLUS_CODE = 43;
30107
- var MINUS_CODE = 45;
30108
- var plugin = {
30109
- name: "assignment",
30110
- assignmentOperators: new Set(["=", "*=", "**=", "/=", "%=", "+=", "-=", "<<=", ">>=", ">>>=", "&=", "^=", "|=", "||=", "&&=", "??="]),
30111
- updateOperators: [PLUS_CODE, MINUS_CODE],
30112
- assignmentPrecedence: 0.9,
30113
- init(jsep2) {
30114
- const updateNodeTypes = [jsep2.IDENTIFIER, jsep2.MEMBER_EXP];
30115
- plugin.assignmentOperators.forEach((op) => jsep2.addBinaryOp(op, plugin.assignmentPrecedence, true));
30116
- jsep2.hooks.add("gobble-token", function gobbleUpdatePrefix(env) {
30117
- const code = this.code;
30118
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
30119
- this.index += 2;
30120
- env.node = {
30121
- type: "UpdateExpression",
30122
- operator: code === PLUS_CODE ? "++" : "--",
30123
- argument: this.gobbleTokenProperty(this.gobbleIdentifier()),
30124
- prefix: true
30125
- };
30126
- if (!env.node.argument || !updateNodeTypes.includes(env.node.argument.type)) {
30127
- this.throwError(`Unexpected ${env.node.operator}`);
30128
- }
30129
- }
30130
- });
30131
- jsep2.hooks.add("after-token", function gobbleUpdatePostfix(env) {
30132
- if (env.node) {
30133
- const code = this.code;
30134
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
30135
- if (!updateNodeTypes.includes(env.node.type)) {
30136
- this.throwError(`Unexpected ${env.node.operator}`);
30137
- }
30138
- this.index += 2;
30139
- env.node = {
30140
- type: "UpdateExpression",
30141
- operator: code === PLUS_CODE ? "++" : "--",
30142
- argument: env.node,
30143
- prefix: false
30144
- };
30145
- }
30146
- }
30147
- });
30148
- jsep2.hooks.add("after-expression", function gobbleAssignment(env) {
30149
- if (env.node) {
30150
- updateBinariesToAssignments(env.node);
30151
- }
30152
- });
30153
- function updateBinariesToAssignments(node) {
30154
- if (plugin.assignmentOperators.has(node.operator)) {
30155
- node.type = "AssignmentExpression";
30156
- updateBinariesToAssignments(node.left);
30157
- updateBinariesToAssignments(node.right);
30158
- } else if (!node.operator) {
30159
- Object.values(node).forEach((val) => {
30160
- if (val && typeof val === "object") {
30161
- updateBinariesToAssignments(val);
30162
- }
30163
- });
30164
- }
30165
- }
30166
- }
30167
- };
30168
- jsep.plugins.register(index, plugin);
30169
- jsep.addUnaryOp("typeof");
30170
- jsep.addUnaryOp("void");
30171
- jsep.addLiteral("null", null);
30172
- jsep.addLiteral("undefined", undefined);
30173
- var BLOCKED_PROTO_PROPERTIES = new Set(["constructor", "__proto__", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"]);
30174
- var SafeEval = {
30175
- evalAst(ast, subs) {
30176
- switch (ast.type) {
30177
- case "BinaryExpression":
30178
- case "LogicalExpression":
30179
- return SafeEval.evalBinaryExpression(ast, subs);
30180
- case "Compound":
30181
- return SafeEval.evalCompound(ast, subs);
30182
- case "ConditionalExpression":
30183
- return SafeEval.evalConditionalExpression(ast, subs);
30184
- case "Identifier":
30185
- return SafeEval.evalIdentifier(ast, subs);
30186
- case "Literal":
30187
- return SafeEval.evalLiteral(ast, subs);
30188
- case "MemberExpression":
30189
- return SafeEval.evalMemberExpression(ast, subs);
30190
- case "UnaryExpression":
30191
- return SafeEval.evalUnaryExpression(ast, subs);
30192
- case "ArrayExpression":
30193
- return SafeEval.evalArrayExpression(ast, subs);
30194
- case "CallExpression":
30195
- return SafeEval.evalCallExpression(ast, subs);
30196
- case "AssignmentExpression":
30197
- return SafeEval.evalAssignmentExpression(ast, subs);
30198
- default:
30199
- throw SyntaxError("Unexpected expression", ast);
30200
- }
30201
- },
30202
- evalBinaryExpression(ast, subs) {
30203
- const result = {
30204
- "||": (a, b) => a || b(),
30205
- "&&": (a, b) => a && b(),
30206
- "|": (a, b) => a | b(),
30207
- "^": (a, b) => a ^ b(),
30208
- "&": (a, b) => a & b(),
30209
- "==": (a, b) => a == b(),
30210
- "!=": (a, b) => a != b(),
30211
- "===": (a, b) => a === b(),
30212
- "!==": (a, b) => a !== b(),
30213
- "<": (a, b) => a < b(),
30214
- ">": (a, b) => a > b(),
30215
- "<=": (a, b) => a <= b(),
30216
- ">=": (a, b) => a >= b(),
30217
- "<<": (a, b) => a << b(),
30218
- ">>": (a, b) => a >> b(),
30219
- ">>>": (a, b) => a >>> b(),
30220
- "+": (a, b) => a + b(),
30221
- "-": (a, b) => a - b(),
30222
- "*": (a, b) => a * b(),
30223
- "/": (a, b) => a / b(),
30224
- "%": (a, b) => a % b()
30225
- }[ast.operator](SafeEval.evalAst(ast.left, subs), () => SafeEval.evalAst(ast.right, subs));
30226
- return result;
30227
- },
30228
- evalCompound(ast, subs) {
30229
- let last;
30230
- for (let i = 0;i < ast.body.length; i++) {
30231
- if (ast.body[i].type === "Identifier" && ["var", "let", "const"].includes(ast.body[i].name) && ast.body[i + 1] && ast.body[i + 1].type === "AssignmentExpression") {
30232
- i += 1;
30233
- }
30234
- const expr = ast.body[i];
30235
- last = SafeEval.evalAst(expr, subs);
30236
- }
30237
- return last;
30238
- },
30239
- evalConditionalExpression(ast, subs) {
30240
- if (SafeEval.evalAst(ast.test, subs)) {
30241
- return SafeEval.evalAst(ast.consequent, subs);
30242
- }
30243
- return SafeEval.evalAst(ast.alternate, subs);
30244
- },
30245
- evalIdentifier(ast, subs) {
30246
- if (Object.hasOwn(subs, ast.name)) {
30247
- return subs[ast.name];
30248
- }
30249
- throw ReferenceError(`${ast.name} is not defined`);
30250
- },
30251
- evalLiteral(ast) {
30252
- return ast.value;
30253
- },
30254
- evalMemberExpression(ast, subs) {
30255
- const prop = String(ast.computed ? SafeEval.evalAst(ast.property) : ast.property.name);
30256
- const obj = SafeEval.evalAst(ast.object, subs);
30257
- if (obj === undefined || obj === null) {
30258
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
30259
- }
30260
- if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) {
30261
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
30262
- }
30263
- const result = obj[prop];
30264
- if (typeof result === "function") {
30265
- return result.bind(obj);
30266
- }
30267
- return result;
30268
- },
30269
- evalUnaryExpression(ast, subs) {
30270
- const result = {
30271
- "-": (a) => -SafeEval.evalAst(a, subs),
30272
- "!": (a) => !SafeEval.evalAst(a, subs),
30273
- "~": (a) => ~SafeEval.evalAst(a, subs),
30274
- "+": (a) => +SafeEval.evalAst(a, subs),
30275
- typeof: (a) => typeof SafeEval.evalAst(a, subs),
30276
- void: (a) => void SafeEval.evalAst(a, subs)
30277
- }[ast.operator](ast.argument);
30278
- return result;
30279
- },
30280
- evalArrayExpression(ast, subs) {
30281
- return ast.elements.map((el) => SafeEval.evalAst(el, subs));
30282
- },
30283
- evalCallExpression(ast, subs) {
30284
- const args = ast.arguments.map((arg) => SafeEval.evalAst(arg, subs));
30285
- const func = SafeEval.evalAst(ast.callee, subs);
30286
- if (func === Function) {
30287
- throw new Error("Function constructor is disabled");
30288
- }
30289
- return func(...args);
30290
- },
30291
- evalAssignmentExpression(ast, subs) {
30292
- if (ast.left.type !== "Identifier") {
30293
- throw SyntaxError("Invalid left-hand side in assignment");
30294
- }
30295
- const id = ast.left.name;
30296
- const value = SafeEval.evalAst(ast.right, subs);
30297
- subs[id] = value;
30298
- return subs[id];
30299
- }
30300
- };
30301
-
30302
- class SafeScript {
30303
- constructor(expr) {
30304
- this.code = expr;
30305
- this.ast = jsep(this.code);
30306
- }
30307
- runInNewContext(context) {
30308
- const keyMap = Object.assign(Object.create(null), context);
30309
- return SafeEval.evalAst(this.ast, keyMap);
30310
- }
30311
- }
30312
- function push(arr, item) {
30313
- arr = arr.slice();
30314
- arr.push(item);
30315
- return arr;
30316
- }
30317
- function unshift(item, arr) {
30318
- arr = arr.slice();
30319
- arr.unshift(item);
30320
- return arr;
30321
- }
30322
-
30323
- class NewError extends Error {
30324
- constructor(value) {
30325
- super('JSONPath should not be called with "new" (it prevents return ' + "of (unwrapped) scalar values)");
30326
- this.avoidNew = true;
30327
- this.value = value;
30328
- this.name = "NewError";
30329
- }
30330
- }
30331
- function JSONPath(opts, expr, obj, callback, otherTypeCallback) {
30332
- if (!(this instanceof JSONPath)) {
30333
- try {
30334
- return new JSONPath(opts, expr, obj, callback, otherTypeCallback);
30335
- } catch (e) {
30336
- if (!e.avoidNew) {
30337
- throw e;
30338
- }
30339
- return e.value;
30340
- }
30341
- }
30342
- if (typeof opts === "string") {
30343
- otherTypeCallback = callback;
30344
- callback = obj;
30345
- obj = expr;
30346
- expr = opts;
30347
- opts = null;
30348
- }
30349
- const optObj = opts && typeof opts === "object";
30350
- opts = opts || {};
30351
- this.json = opts.json || obj;
30352
- this.path = opts.path || expr;
30353
- this.resultType = opts.resultType || "value";
30354
- this.flatten = opts.flatten || false;
30355
- this.wrap = Object.hasOwn(opts, "wrap") ? opts.wrap : true;
30356
- this.sandbox = opts.sandbox || {};
30357
- this.eval = opts.eval === undefined ? "safe" : opts.eval;
30358
- this.ignoreEvalErrors = typeof opts.ignoreEvalErrors === "undefined" ? false : opts.ignoreEvalErrors;
30359
- this.parent = opts.parent || null;
30360
- this.parentProperty = opts.parentProperty || null;
30361
- this.callback = opts.callback || callback || null;
30362
- this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function() {
30363
- throw new TypeError("You must supply an otherTypeCallback callback option " + "with the @other() operator.");
30364
- };
30365
- if (opts.autostart !== false) {
30366
- const args = {
30367
- path: optObj ? opts.path : expr
30368
- };
30369
- if (!optObj) {
30370
- args.json = obj;
30371
- } else if ("json" in opts) {
30372
- args.json = opts.json;
30373
- }
30374
- const ret = this.evaluate(args);
30375
- if (!ret || typeof ret !== "object") {
30376
- throw new NewError(ret);
30377
- }
30378
- return ret;
30379
- }
30380
- }
30381
- JSONPath.prototype.evaluate = function(expr, json, callback, otherTypeCallback) {
30382
- let currParent = this.parent, currParentProperty = this.parentProperty;
30383
- let {
30384
- flatten,
30385
- wrap
30386
- } = this;
30387
- this.currResultType = this.resultType;
30388
- this.currEval = this.eval;
30389
- this.currSandbox = this.sandbox;
30390
- callback = callback || this.callback;
30391
- this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback;
30392
- json = json || this.json;
30393
- expr = expr || this.path;
30394
- if (expr && typeof expr === "object" && !Array.isArray(expr)) {
30395
- if (!expr.path && expr.path !== "") {
30396
- throw new TypeError('You must supply a "path" property when providing an object ' + "argument to JSONPath.evaluate().");
30397
- }
30398
- if (!Object.hasOwn(expr, "json")) {
30399
- throw new TypeError('You must supply a "json" property when providing an object ' + "argument to JSONPath.evaluate().");
30400
- }
30401
- ({
30402
- json
30403
- } = expr);
30404
- flatten = Object.hasOwn(expr, "flatten") ? expr.flatten : flatten;
30405
- this.currResultType = Object.hasOwn(expr, "resultType") ? expr.resultType : this.currResultType;
30406
- this.currSandbox = Object.hasOwn(expr, "sandbox") ? expr.sandbox : this.currSandbox;
30407
- wrap = Object.hasOwn(expr, "wrap") ? expr.wrap : wrap;
30408
- this.currEval = Object.hasOwn(expr, "eval") ? expr.eval : this.currEval;
30409
- callback = Object.hasOwn(expr, "callback") ? expr.callback : callback;
30410
- this.currOtherTypeCallback = Object.hasOwn(expr, "otherTypeCallback") ? expr.otherTypeCallback : this.currOtherTypeCallback;
30411
- currParent = Object.hasOwn(expr, "parent") ? expr.parent : currParent;
30412
- currParentProperty = Object.hasOwn(expr, "parentProperty") ? expr.parentProperty : currParentProperty;
30413
- expr = expr.path;
30414
- }
30415
- currParent = currParent || null;
30416
- currParentProperty = currParentProperty || null;
30417
- if (Array.isArray(expr)) {
30418
- expr = JSONPath.toPathString(expr);
30419
- }
30420
- if (!expr && expr !== "" || !json) {
30421
- return;
30422
- }
30423
- const exprList = JSONPath.toPathArray(expr);
30424
- if (exprList[0] === "$" && exprList.length > 1) {
30425
- exprList.shift();
30426
- }
30427
- this._hasParentSelector = null;
30428
- const result = this._trace(exprList, json, ["$"], currParent, currParentProperty, callback).filter(function(ea) {
30429
- return ea && !ea.isParentSelector;
30430
- });
30431
- if (!result.length) {
30432
- return wrap ? [] : undefined;
30433
- }
30434
- if (!wrap && result.length === 1 && !result[0].hasArrExpr) {
30435
- return this._getPreferredOutput(result[0]);
30436
- }
30437
- return result.reduce((rslt, ea) => {
30438
- const valOrPath = this._getPreferredOutput(ea);
30439
- if (flatten && Array.isArray(valOrPath)) {
30440
- rslt = rslt.concat(valOrPath);
30441
- } else {
30442
- rslt.push(valOrPath);
30443
- }
30444
- return rslt;
30445
- }, []);
30446
- };
30447
- JSONPath.prototype._getPreferredOutput = function(ea) {
30448
- const resultType = this.currResultType;
30449
- switch (resultType) {
30450
- case "all": {
30451
- const path3 = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path);
30452
- ea.pointer = JSONPath.toPointer(path3);
30453
- ea.path = typeof ea.path === "string" ? ea.path : JSONPath.toPathString(ea.path);
30454
- return ea;
30455
- }
30456
- case "value":
30457
- case "parent":
30458
- case "parentProperty":
30459
- return ea[resultType];
30460
- case "path":
30461
- return JSONPath.toPathString(ea[resultType]);
30462
- case "pointer":
30463
- return JSONPath.toPointer(ea.path);
30464
- default:
30465
- throw new TypeError("Unknown result type");
30466
- }
30467
- };
30468
- JSONPath.prototype._handleCallback = function(fullRetObj, callback, type) {
30469
- if (callback) {
30470
- const preferredOutput = this._getPreferredOutput(fullRetObj);
30471
- fullRetObj.path = typeof fullRetObj.path === "string" ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path);
30472
- callback(preferredOutput, type, fullRetObj);
30473
- }
30474
- };
30475
- JSONPath.prototype._trace = function(expr, val, path3, parent, parentPropName, callback, hasArrExpr, literalPriority) {
30476
- let retObj;
30477
- if (!expr.length) {
30478
- retObj = {
30479
- path: path3,
30480
- value: val,
30481
- parent,
30482
- parentProperty: parentPropName,
30483
- hasArrExpr
30484
- };
30485
- this._handleCallback(retObj, callback, "value");
30486
- return retObj;
30487
- }
30488
- const loc = expr[0], x = expr.slice(1);
30489
- const ret = [];
30490
- function addRet(elems) {
30491
- if (Array.isArray(elems)) {
30492
- elems.forEach((t) => {
30493
- ret.push(t);
30494
- });
30495
- } else {
30496
- ret.push(elems);
30497
- }
30498
- }
30499
- if ((typeof loc !== "string" || literalPriority) && val && Object.hasOwn(val, loc)) {
30500
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr));
30501
- } else if (loc === "*") {
30502
- this._walk(val, (m) => {
30503
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true, true));
30504
- });
30505
- } else if (loc === "..") {
30506
- addRet(this._trace(x, val, path3, parent, parentPropName, callback, hasArrExpr));
30507
- this._walk(val, (m) => {
30508
- if (typeof val[m] === "object") {
30509
- addRet(this._trace(expr.slice(), val[m], push(path3, m), val, m, callback, true));
30510
- }
30511
- });
30512
- } else if (loc === "^") {
30513
- this._hasParentSelector = true;
30514
- return {
30515
- path: path3.slice(0, -1),
30516
- expr: x,
30517
- isParentSelector: true
30518
- };
30519
- } else if (loc === "~") {
30520
- retObj = {
30521
- path: push(path3, loc),
30522
- value: parentPropName,
30523
- parent,
30524
- parentProperty: null
30525
- };
30526
- this._handleCallback(retObj, callback, "property");
30527
- return retObj;
30528
- } else if (loc === "$") {
30529
- addRet(this._trace(x, val, path3, null, null, callback, hasArrExpr));
30530
- } else if (/^(-?\d*):(-?\d*):?(\d*)$/u.test(loc)) {
30531
- addRet(this._slice(loc, x, val, path3, parent, parentPropName, callback));
30532
- } else if (loc.indexOf("?(") === 0) {
30533
- if (this.currEval === false) {
30534
- throw new Error("Eval [?(expr)] prevented in JSONPath expression.");
30535
- }
30536
- const safeLoc = loc.replace(/^\?\((.*?)\)$/u, "$1");
30537
- const nested = /@.?([^?]*)[['](\??\(.*?\))(?!.\)\])[\]']/gu.exec(safeLoc);
30538
- if (nested) {
30539
- this._walk(val, (m) => {
30540
- const npath = [nested[2]];
30541
- const nvalue = nested[1] ? val[m][nested[1]] : val[m];
30542
- const filterResults = this._trace(npath, nvalue, path3, parent, parentPropName, callback, true);
30543
- if (filterResults.length > 0) {
30544
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
30545
- }
30546
- });
30547
- } else {
30548
- this._walk(val, (m) => {
30549
- if (this._eval(safeLoc, val[m], m, path3, parent, parentPropName)) {
30550
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
30551
- }
30552
- });
30553
- }
30554
- } else if (loc[0] === "(") {
30555
- if (this.currEval === false) {
30556
- throw new Error("Eval [(expr)] prevented in JSONPath expression.");
30557
- }
30558
- addRet(this._trace(unshift(this._eval(loc, val, path3.at(-1), path3.slice(0, -1), parent, parentPropName), x), val, path3, parent, parentPropName, callback, hasArrExpr));
30559
- } else if (loc[0] === "@") {
30560
- let addType = false;
30561
- const valueType = loc.slice(1, -2);
30562
- switch (valueType) {
30563
- case "scalar":
30564
- if (!val || !["object", "function"].includes(typeof val)) {
30565
- addType = true;
30566
- }
30567
- break;
30568
- case "boolean":
30569
- case "string":
30570
- case "undefined":
30571
- case "function":
30572
- if (typeof val === valueType) {
30573
- addType = true;
30574
- }
30575
- break;
30576
- case "integer":
30577
- if (Number.isFinite(val) && !(val % 1)) {
30578
- addType = true;
30579
- }
30580
- break;
30581
- case "number":
30582
- if (Number.isFinite(val)) {
30583
- addType = true;
30584
- }
30585
- break;
30586
- case "nonFinite":
30587
- if (typeof val === "number" && !Number.isFinite(val)) {
30588
- addType = true;
30589
- }
30590
- break;
30591
- case "object":
30592
- if (val && typeof val === valueType) {
30593
- addType = true;
30594
- }
30595
- break;
30596
- case "array":
30597
- if (Array.isArray(val)) {
30598
- addType = true;
30599
- }
30600
- break;
30601
- case "other":
30602
- addType = this.currOtherTypeCallback(val, path3, parent, parentPropName);
30603
- break;
30604
- case "null":
30605
- if (val === null) {
30606
- addType = true;
30607
- }
30608
- break;
30609
- default:
30610
- throw new TypeError("Unknown value type " + valueType);
30611
- }
30612
- if (addType) {
30613
- retObj = {
30614
- path: path3,
30615
- value: val,
30616
- parent,
30617
- parentProperty: parentPropName
30618
- };
30619
- this._handleCallback(retObj, callback, "value");
30620
- return retObj;
30621
- }
30622
- } else if (loc[0] === "`" && val && Object.hasOwn(val, loc.slice(1))) {
30623
- const locProp = loc.slice(1);
30624
- addRet(this._trace(x, val[locProp], push(path3, locProp), val, locProp, callback, hasArrExpr, true));
30625
- } else if (loc.includes(",")) {
30626
- const parts = loc.split(",");
30627
- for (const part of parts) {
30628
- addRet(this._trace(unshift(part, x), val, path3, parent, parentPropName, callback, true));
30629
- }
30630
- } else if (!literalPriority && val && Object.hasOwn(val, loc)) {
30631
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr, true));
30632
- }
30633
- if (this._hasParentSelector) {
30634
- for (let t = 0;t < ret.length; t++) {
30635
- const rett = ret[t];
30636
- if (rett && rett.isParentSelector) {
30637
- const tmp = this._trace(rett.expr, val, rett.path, parent, parentPropName, callback, hasArrExpr);
30638
- if (Array.isArray(tmp)) {
30639
- ret[t] = tmp[0];
30640
- const tl = tmp.length;
30641
- for (let tt = 1;tt < tl; tt++) {
30642
- t++;
30643
- ret.splice(t, 0, tmp[tt]);
30644
- }
30645
- } else {
30646
- ret[t] = tmp;
30647
- }
30648
- }
30649
- }
30650
- }
30651
- return ret;
30652
- };
30653
- JSONPath.prototype._walk = function(val, f) {
30654
- if (Array.isArray(val)) {
30655
- const n = val.length;
30656
- for (let i = 0;i < n; i++) {
30657
- f(i);
30658
- }
30659
- } else if (val && typeof val === "object") {
30660
- Object.keys(val).forEach((m) => {
30661
- f(m);
30662
- });
30663
- }
30664
- };
30665
- JSONPath.prototype._slice = function(loc, expr, val, path3, parent, parentPropName, callback) {
30666
- if (!Array.isArray(val)) {
30667
- return;
30668
- }
30669
- const len = val.length, parts = loc.split(":"), step = parts[2] && Number.parseInt(parts[2]) || 1;
30670
- let start = parts[0] && Number.parseInt(parts[0]) || 0, end = parts[1] && Number.parseInt(parts[1]) || len;
30671
- start = start < 0 ? Math.max(0, start + len) : Math.min(len, start);
30672
- end = end < 0 ? Math.max(0, end + len) : Math.min(len, end);
30673
- const ret = [];
30674
- for (let i = start;i < end; i += step) {
30675
- const tmp = this._trace(unshift(i, expr), val, path3, parent, parentPropName, callback, true);
30676
- tmp.forEach((t) => {
30677
- ret.push(t);
30678
- });
30679
- }
30680
- return ret;
30681
- };
30682
- JSONPath.prototype._eval = function(code, _v, _vname, path3, parent, parentPropName) {
30683
- this.currSandbox._$_parentProperty = parentPropName;
30684
- this.currSandbox._$_parent = parent;
30685
- this.currSandbox._$_property = _vname;
30686
- this.currSandbox._$_root = this.json;
30687
- this.currSandbox._$_v = _v;
30688
- const containsPath = code.includes("@path");
30689
- if (containsPath) {
30690
- this.currSandbox._$_path = JSONPath.toPathString(path3.concat([_vname]));
30691
- }
30692
- const scriptCacheKey = this.currEval + "Script:" + code;
30693
- if (!JSONPath.cache[scriptCacheKey]) {
30694
- let script = code.replaceAll("@parentProperty", "_$_parentProperty").replaceAll("@parent", "_$_parent").replaceAll("@property", "_$_property").replaceAll("@root", "_$_root").replaceAll(/@([.\s)[])/gu, "_$_v$1");
30695
- if (containsPath) {
30696
- script = script.replaceAll("@path", "_$_path");
30697
- }
30698
- if (this.currEval === "safe" || this.currEval === true || this.currEval === undefined) {
30699
- JSONPath.cache[scriptCacheKey] = new this.safeVm.Script(script);
30700
- } else if (this.currEval === "native") {
30701
- JSONPath.cache[scriptCacheKey] = new this.vm.Script(script);
30702
- } else if (typeof this.currEval === "function" && this.currEval.prototype && Object.hasOwn(this.currEval.prototype, "runInNewContext")) {
30703
- const CurrEval = this.currEval;
30704
- JSONPath.cache[scriptCacheKey] = new CurrEval(script);
30705
- } else if (typeof this.currEval === "function") {
30706
- JSONPath.cache[scriptCacheKey] = {
30707
- runInNewContext: (context) => this.currEval(script, context)
30708
- };
30709
- } else {
30710
- throw new TypeError(`Unknown "eval" property "${this.currEval}"`);
30711
- }
30712
- }
30713
- try {
30714
- return JSONPath.cache[scriptCacheKey].runInNewContext(this.currSandbox);
30715
- } catch (e) {
30716
- if (this.ignoreEvalErrors) {
30717
- return false;
30718
- }
30719
- throw new Error("jsonPath: " + e.message + ": " + code);
30720
- }
30721
- };
30722
- JSONPath.cache = {};
30723
- JSONPath.toPathString = function(pathArr) {
30724
- const x = pathArr, n = x.length;
30725
- let p = "$";
30726
- for (let i = 1;i < n; i++) {
30727
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
30728
- p += /^[0-9*]+$/u.test(x[i]) ? "[" + x[i] + "]" : "['" + x[i] + "']";
30729
- }
30730
- }
30731
- return p;
30732
- };
30733
- JSONPath.toPointer = function(pointer) {
30734
- const x = pointer, n = x.length;
30735
- let p = "";
30736
- for (let i = 1;i < n; i++) {
30737
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
30738
- p += "/" + x[i].toString().replaceAll("~", "~0").replaceAll("/", "~1");
30739
- }
30740
- }
30741
- return p;
30742
- };
30743
- JSONPath.toPathArray = function(expr) {
30744
- const {
30745
- cache
30746
- } = JSONPath;
30747
- if (cache[expr]) {
30748
- return cache[expr].concat();
30749
- }
30750
- const subx = [];
30751
- const normalized = expr.replaceAll(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/gu, ";$&;").replaceAll(/[['](\??\(.*?\))[\]'](?!.\])/gu, function($0, $1) {
30752
- return "[#" + (subx.push($1) - 1) + "]";
30753
- }).replaceAll(/\[['"]([^'\]]*)['"]\]/gu, function($0, prop) {
30754
- return "['" + prop.replaceAll(".", "%@%").replaceAll("~", "%%@@%%") + "']";
30755
- }).replaceAll("~", ";~;").replaceAll(/['"]?\.['"]?(?![^[]*\])|\[['"]?/gu, ";").replaceAll("%@%", ".").replaceAll("%%@@%%", "~").replaceAll(/(?:;)?(\^+)(?:;)?/gu, function($0, ups) {
30756
- return ";" + ups.split("").join(";") + ";";
30757
- }).replaceAll(/;;;|;;/gu, ";..;").replaceAll(/;$|'?\]|'$/gu, "");
30758
- const exprList = normalized.split(";").map(function(exp) {
30759
- const match = exp.match(/#(\d+)/u);
30760
- return !match || !match[1] ? exp : subx[match[1]];
30761
- });
30762
- cache[expr] = exprList;
30763
- return cache[expr].concat();
30764
- };
30765
- JSONPath.prototype.safeVm = {
30766
- Script: SafeScript
30767
- };
30768
- JSONPath.prototype.vm = vm;
30769
29721
  // ../../common/src/option-validators.ts
30770
29722
  function parseNonNegativeInteger(raw) {
30771
29723
  return parseSafeInteger(raw, 0);
@@ -30815,6 +29767,17 @@ var FAILURE_STATUSES = new Set([
30815
29767
  "canceled",
30816
29768
  "stopped"
30817
29769
  ]);
29770
+ // ../../common/src/preview.ts
29771
+ var previewSlot = singleton("PreviewBuild");
29772
+ function isPreviewBuild() {
29773
+ return previewSlot.get(false) ?? false;
29774
+ }
29775
+ Command.prototype.previewCommand = function(nameAndArgs, opts) {
29776
+ if (isPreviewBuild()) {
29777
+ return this.command(nameAndArgs, opts);
29778
+ }
29779
+ return new Command(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
29780
+ };
30818
29781
  // ../../common/src/screen-logger.ts
30819
29782
  var ScreenLogger;
30820
29783
  ((ScreenLogger) => {
@@ -31493,7 +30456,7 @@ class TextApiResponse {
31493
30456
  var package_default3 = {
31494
30457
  name: "@uipath/aops-policy-sdk",
31495
30458
  license: "MIT",
31496
- version: "1.196.0",
30459
+ version: "1.197.0",
31497
30460
  description: "SDK for the UiPath AOps Governance API — policy management and deployment.",
31498
30461
  repository: {
31499
30462
  type: "git",
@@ -31523,7 +30486,7 @@ var package_default3 = {
31523
30486
  ],
31524
30487
  private: true,
31525
30488
  scripts: {
31526
- build: "bun build ./src/index.ts --outdir dist --format esm --target node && tsc -p tsconfig.build.json --noCheck",
30489
+ build: "bun build ./src/index.ts --outdir dist --format esm --target node --sourcemap=linked && tsc -p tsconfig.build.json --noCheck",
31527
30490
  generate: "bun run src/scripts/generate-sdk.ts",
31528
30491
  lint: "biome check ."
31529
30492
  },
@@ -34290,8 +33253,8 @@ async function readRawJson(raw) {
34290
33253
  return null;
34291
33254
  const contentType = raw.headers.get("content-type") ?? "";
34292
33255
  if (!contentType.toLowerCase().includes("json")) {
34293
- const preview = text.length > 500 ? `${text.slice(0, 500)}…` : text;
34294
- throw new Error(`Expected JSON response but got content-type '${contentType || "(none)"}' (HTTP ${raw.status}). Body: ${preview}`);
33256
+ const preview2 = text.length > 500 ? `${text.slice(0, 500)}…` : text;
33257
+ throw new Error(`Expected JSON response but got content-type '${contentType || "(none)"}' (HTTP ${raw.status}). Body: ${preview2}`);
34295
33258
  }
34296
33259
  return JSON.parse(text);
34297
33260
  }
@@ -34559,18 +33522,18 @@ function parseGroupPolicyInput(raw) {
34559
33522
  if (!Array.isArray(raw)) {
34560
33523
  throw new Error("Input must be a JSON array of {productIdentifier, policyIdentifier} entries.");
34561
33524
  }
34562
- return raw.map((entry, index2) => {
33525
+ return raw.map((entry, index) => {
34563
33526
  if (!entry || typeof entry !== "object") {
34564
- throw new Error(`Entry ${index2} must be an object.`);
33527
+ throw new Error(`Entry ${index} must be an object.`);
34565
33528
  }
34566
33529
  const record = entry;
34567
33530
  const productIdentifier = record.productIdentifier;
34568
33531
  if (typeof productIdentifier !== "string" || !productIdentifier) {
34569
- throw new Error(`Entry ${index2} is missing a string productIdentifier.`);
33532
+ throw new Error(`Entry ${index} is missing a string productIdentifier.`);
34570
33533
  }
34571
33534
  const policyIdentifier = record.policyIdentifier;
34572
33535
  if (policyIdentifier !== null && typeof policyIdentifier !== "string") {
34573
- throw new Error(`Entry ${index2} policyIdentifier must be a string or null.`);
33536
+ throw new Error(`Entry ${index} policyIdentifier must be a string or null.`);
34574
33537
  }
34575
33538
  return { productIdentifier, policyIdentifier };
34576
33539
  });
@@ -34752,6 +33715,13 @@ var registerDeploymentGroupCommands = (deployment) => {
34752
33715
  });
34753
33716
  };
34754
33717
 
33718
+ // src/commands/aops-policy/utils/tenant-sync.ts
33719
+ function syncTenants(api) {
33720
+ return api.tenantSyncAndGetAllTenants({
33721
+ governanceQueryOptions: { pageIndex: 0, pageSize: 10 }
33722
+ });
33723
+ }
33724
+
34755
33725
  // src/commands/aops-policy/deployment-tenant.ts
34756
33726
  var LOGIN_INSTRUCTIONS3 = "Ensure you are logged in with 'uip login' and have access to the governance service.";
34757
33727
  var LIST_EXAMPLES4 = [
@@ -34835,22 +33805,22 @@ function parseTenantPolicyInput(raw) {
34835
33805
  if (!Array.isArray(raw)) {
34836
33806
  throw new Error("Input must be a JSON array of {productIdentifier, licenseTypeIdentifier, policyIdentifier} entries.");
34837
33807
  }
34838
- return raw.map((entry, index2) => {
33808
+ return raw.map((entry, index) => {
34839
33809
  if (!entry || typeof entry !== "object") {
34840
- throw new Error(`Entry ${index2} must be an object.`);
33810
+ throw new Error(`Entry ${index} must be an object.`);
34841
33811
  }
34842
33812
  const record = entry;
34843
33813
  const productIdentifier = record.productIdentifier;
34844
33814
  if (typeof productIdentifier !== "string" || !productIdentifier) {
34845
- throw new Error(`Entry ${index2} is missing a string productIdentifier.`);
33815
+ throw new Error(`Entry ${index} is missing a string productIdentifier.`);
34846
33816
  }
34847
33817
  const licenseTypeIdentifier = record.licenseTypeIdentifier;
34848
33818
  if (typeof licenseTypeIdentifier !== "string" || !licenseTypeIdentifier) {
34849
- throw new Error(`Entry ${index2} is missing a string licenseTypeIdentifier.`);
33819
+ throw new Error(`Entry ${index} is missing a string licenseTypeIdentifier.`);
34850
33820
  }
34851
33821
  const policyIdentifier = record.policyIdentifier;
34852
33822
  if (policyIdentifier !== null && typeof policyIdentifier !== "string") {
34853
- throw new Error(`Entry ${index2} policyIdentifier must be a string or null.`);
33823
+ throw new Error(`Entry ${index} policyIdentifier must be a string or null.`);
34854
33824
  }
34855
33825
  return {
34856
33826
  productIdentifier,
@@ -34970,7 +33940,7 @@ var registerDeploymentTenantCommands = (deployment) => {
34970
33940
  const tenantApi = await createApiClient2(TenantApi, {
34971
33941
  loginValidity: options.loginValidity
34972
33942
  });
34973
- await tenantApi.tenantSyncAndGetAllTenants({});
33943
+ await syncTenants(tenantApi);
34974
33944
  const saved = await tenantApi.tenantSaveTenantPoliciesRaw({
34975
33945
  tenantPolicyDto
34976
33946
  });
@@ -35012,7 +33982,7 @@ var registerDeploymentTenantCommands = (deployment) => {
35012
33982
  const tenantApi = await createApiClient2(TenantApi, {
35013
33983
  loginValidity: options.loginValidity
35014
33984
  });
35015
- await tenantApi.tenantSyncAndGetAllTenants({});
33985
+ await syncTenants(tenantApi);
35016
33986
  const currentRaw = await tenantApi.tenantGetTenantByIdRaw({
35017
33987
  tenantIdentifier
35018
33988
  });
@@ -35131,18 +34101,18 @@ function parseUserPolicyInput(raw) {
35131
34101
  if (!Array.isArray(raw)) {
35132
34102
  throw new Error("Input must be a JSON array of {productIdentifier, policyIdentifier} entries.");
35133
34103
  }
35134
- return raw.map((entry, index2) => {
34104
+ return raw.map((entry, index) => {
35135
34105
  if (!entry || typeof entry !== "object") {
35136
- throw new Error(`Entry ${index2} must be an object.`);
34106
+ throw new Error(`Entry ${index} must be an object.`);
35137
34107
  }
35138
34108
  const record = entry;
35139
34109
  const productIdentifier = record.productIdentifier;
35140
34110
  if (typeof productIdentifier !== "string" || !productIdentifier) {
35141
- throw new Error(`Entry ${index2} is missing a string productIdentifier.`);
34111
+ throw new Error(`Entry ${index} is missing a string productIdentifier.`);
35142
34112
  }
35143
34113
  const policyIdentifier = record.policyIdentifier;
35144
34114
  if (policyIdentifier !== null && typeof policyIdentifier !== "string") {
35145
- throw new Error(`Entry ${index2} policyIdentifier must be a string or null.`);
34115
+ throw new Error(`Entry ${index} policyIdentifier must be a string or null.`);
35146
34116
  }
35147
34117
  return { productIdentifier, policyIdentifier };
35148
34118
  });
@@ -37492,13 +36462,13 @@ function toRecord(value) {
37492
36462
  function buildFormDataInner(components, data, result) {
37493
36463
  for (const raw of components) {
37494
36464
  const c = raw;
37495
- const type = String(c["type"] ?? "");
37496
- const key = String(c["key"] ?? "");
36465
+ const type = String(c.type ?? "");
36466
+ const key = String(c.key ?? "");
37497
36467
  if (DISPLAY_ONLY_TYPES.has(type))
37498
36468
  continue;
37499
36469
  if (type === "columns") {
37500
- for (const col of c["columns"] ?? []) {
37501
- const colComps = col["components"];
36470
+ for (const col of c.columns ?? []) {
36471
+ const colComps = col.components;
37502
36472
  if (Array.isArray(colComps)) {
37503
36473
  buildFormDataInner(colComps, data, result);
37504
36474
  }
@@ -37507,14 +36477,14 @@ function buildFormDataInner(components, data, result) {
37507
36477
  }
37508
36478
  if (type === "container" && key) {
37509
36479
  const containerResult = {};
37510
- if (Array.isArray(c["components"])) {
37511
- buildFormDataInner(c["components"], toRecord(data[key]), containerResult);
36480
+ if (Array.isArray(c.components)) {
36481
+ buildFormDataInner(c.components, toRecord(data[key]), containerResult);
37512
36482
  }
37513
36483
  result[key] = containerResult;
37514
36484
  continue;
37515
36485
  }
37516
- if (Array.isArray(c["components"]) && !LEAF_TYPES.has(type)) {
37517
- buildFormDataInner(c["components"], data, result);
36486
+ if (Array.isArray(c.components) && !LEAF_TYPES.has(type)) {
36487
+ buildFormDataInner(c.components, data, result);
37518
36488
  continue;
37519
36489
  }
37520
36490
  if (!key)
@@ -37542,36 +36512,36 @@ function resolveLocale(key, locale, productPrefix) {
37542
36512
  function buildAnnotatedFormData(components, formData, locale, productPrefix, result = {}) {
37543
36513
  for (const raw of components) {
37544
36514
  const c = raw;
37545
- const type = String(c["type"] ?? "");
36515
+ const type = String(c.type ?? "");
37546
36516
  if (DISPLAY_ONLY_TYPES.has(type))
37547
36517
  continue;
37548
36518
  if (type === "columns") {
37549
- for (const col of c["columns"] ?? []) {
37550
- const colComponents = col["components"];
36519
+ for (const col of c.columns ?? []) {
36520
+ const colComponents = col.components;
37551
36521
  if (Array.isArray(colComponents)) {
37552
36522
  buildAnnotatedFormData(colComponents, formData, locale, productPrefix, result);
37553
36523
  }
37554
36524
  }
37555
36525
  continue;
37556
36526
  }
37557
- const key = String(c["key"] ?? "");
36527
+ const key = String(c.key ?? "");
37558
36528
  if (type === "container" && key) {
37559
36529
  const nested = formData[key];
37560
36530
  const nestedData = nested !== null && nested !== undefined && typeof nested === "object" && !Array.isArray(nested) ? nested : {};
37561
- if (Array.isArray(c["components"])) {
37562
- buildAnnotatedFormData(c["components"], nestedData, locale, productPrefix, result);
36531
+ if (Array.isArray(c.components)) {
36532
+ buildAnnotatedFormData(c.components, nestedData, locale, productPrefix, result);
37563
36533
  }
37564
36534
  continue;
37565
36535
  }
37566
- if (Array.isArray(c["components"]) && !LEAF_TYPES.has(type)) {
37567
- buildAnnotatedFormData(c["components"], formData, locale, productPrefix, result);
36536
+ if (Array.isArray(c.components) && !LEAF_TYPES.has(type)) {
36537
+ buildAnnotatedFormData(c.components, formData, locale, productPrefix, result);
37568
36538
  continue;
37569
36539
  }
37570
36540
  if (!key)
37571
36541
  continue;
37572
- const label = resolveLocale(c["label"], locale, productPrefix) ?? key;
37573
- const description = resolveLocale(c["description"], locale, productPrefix);
37574
- const tooltip = resolveLocale(c["tooltip"], locale, productPrefix);
36542
+ const label = resolveLocale(c.label, locale, productPrefix) ?? key;
36543
+ const description = resolveLocale(c.description, locale, productPrefix);
36544
+ const tooltip = resolveLocale(c.tooltip, locale, productPrefix);
37575
36545
  const field = { value: formData[key], type, label };
37576
36546
  if (description !== undefined)
37577
36547
  field.description = description;
@@ -37630,21 +36600,21 @@ function pickKeys(obj, allowed) {
37630
36600
  }
37631
36601
  function buildTemplateLocaleResource(dto, locale, productPrefix) {
37632
36602
  const resolved = resolveLocaleStringsDeep(dto, locale, productPrefix);
37633
- const templateComponents = dto["template"]?.["components"];
36603
+ const templateComponents = dto.template?.components;
37634
36604
  const components = Array.isArray(templateComponents) ? templateComponents : [];
37635
36605
  const rawData = extractDefaultData(dto);
37636
36606
  const formData = buildFormData(components, rawData);
37637
36607
  const annotated = buildAnnotatedFormData(components, formData, locale, productPrefix);
37638
36608
  const pruned = pickKeys(resolved, TOPLEVEL_WHITELIST);
37639
- const template = pruned["template"];
36609
+ const template = pruned.template;
37640
36610
  if (template !== null && template !== undefined && typeof template === "object" && !Array.isArray(template)) {
37641
- pruned["template"] = pickKeys(template, TEMPLATE_WHITELIST);
36611
+ pruned.template = pickKeys(template, TEMPLATE_WHITELIST);
37642
36612
  }
37643
- const defaultData = pruned["defaultData"];
36613
+ const defaultData = pruned.defaultData;
37644
36614
  if (defaultData !== null && defaultData !== undefined && typeof defaultData === "object" && !Array.isArray(defaultData)) {
37645
36615
  const prunedDefaultData = pickKeys(defaultData, DEFAULTDATA_WHITELIST);
37646
- prunedDefaultData["data"] = annotated;
37647
- pruned["defaultData"] = prunedDefaultData;
36616
+ prunedDefaultData.data = annotated;
36617
+ pruned.defaultData = prunedDefaultData;
37648
36618
  }
37649
36619
  return pruned;
37650
36620
  }
@@ -37655,7 +36625,7 @@ function extractDefaultData(dto) {
37655
36625
  if (typeof raw !== "object" || Array.isArray(raw))
37656
36626
  return {};
37657
36627
  const submission = raw;
37658
- const inner = submission["data"];
36628
+ const inner = submission.data;
37659
36629
  if (inner !== null && inner !== undefined && typeof inner === "object" && !Array.isArray(inner)) {
37660
36630
  return inner;
37661
36631
  }
@@ -37707,7 +36677,7 @@ async function writeDataFile(filePath, data) {
37707
36677
  function extractTemplateArtifacts(dto, locale, fallbackProductIdentifier) {
37708
36678
  const safeDto = dto ?? {};
37709
36679
  const rawData = extractDefaultData(safeDto);
37710
- const templateComponents = safeDto.template?.["components"];
36680
+ const templateComponents = safeDto.template?.components;
37711
36681
  const components = Array.isArray(templateComponents) ? templateComponents : [];
37712
36682
  const formData = buildFormData(components, rawData);
37713
36683
  const productName = safeDto.product?.name ?? fallbackProductIdentifier;
@@ -37821,7 +36791,7 @@ var registerTemplateCommands = (aopsPolicy) => {
37821
36791
  const productList = Array.isArray(products) ? products : [];
37822
36792
  const results = [];
37823
36793
  for (const product of productList) {
37824
- const productIdentifier = product["name"] ?? "";
36794
+ const productIdentifier = product.name ?? "";
37825
36795
  if (!productIdentifier)
37826
36796
  continue;
37827
36797
  const [fetchError, dto] = await catchError2(contentApi.contentGetFormioTemplatesByProductIdentifier({
@@ -38039,7 +37009,14 @@ var registerAopsPolicyCommand = (program2) => {
38039
37009
  const api = await createApiClient2(PolicyApi, {
38040
37010
  loginValidity: options.loginValidity
38041
37011
  });
38042
- return await api.policyGetPolicyById({ policyIdentifier });
37012
+ const [policy, formData] = await Promise.all([
37013
+ api.policyGetPolicyById({ policyIdentifier }),
37014
+ api.policyGetFormDataByPolicyId({
37015
+ policyIdentifier
37016
+ })
37017
+ ]);
37018
+ policy.data = formData?.data?.data ?? null;
37019
+ return policy;
38043
37020
  })());
38044
37021
  if (error) {
38045
37022
  OutputFormatter.error({
@@ -49583,8 +48560,8 @@ var require_Subscription2 = __commonJS2((exports) => {
49583
48560
  if (_parentOrParents instanceof Subscription2) {
49584
48561
  _parentOrParents.remove(this);
49585
48562
  } else if (_parentOrParents !== null) {
49586
- for (var index2 = 0;index2 < _parentOrParents.length; ++index2) {
49587
- var parent_1 = _parentOrParents[index2];
48563
+ for (var index = 0;index < _parentOrParents.length; ++index) {
48564
+ var parent_1 = _parentOrParents[index];
49588
48565
  parent_1.remove(this);
49589
48566
  }
49590
48567
  }
@@ -49599,10 +48576,10 @@ var require_Subscription2 = __commonJS2((exports) => {
49599
48576
  }
49600
48577
  }
49601
48578
  if (isArray_1.isArray(_subscriptions)) {
49602
- var index2 = -1;
48579
+ var index = -1;
49603
48580
  var len = _subscriptions.length;
49604
- while (++index2 < len) {
49605
- var sub2 = _subscriptions[index2];
48581
+ while (++index < len) {
48582
+ var sub2 = _subscriptions[index];
49606
48583
  if (isObject_1.isObject(sub2)) {
49607
48584
  try {
49608
48585
  sub2.unsubscribe();
@@ -50998,13 +49975,13 @@ var require_AsyncAction2 = __commonJS2((exports) => {
50998
49975
  var id = this.id;
50999
49976
  var scheduler = this.scheduler;
51000
49977
  var actions = scheduler.actions;
51001
- var index2 = actions.indexOf(this);
49978
+ var index = actions.indexOf(this);
51002
49979
  this.work = null;
51003
49980
  this.state = null;
51004
49981
  this.pending = false;
51005
49982
  this.scheduler = null;
51006
- if (index2 !== -1) {
51007
- actions.splice(index2, 1);
49983
+ if (index !== -1) {
49984
+ actions.splice(index, 1);
51008
49985
  }
51009
49986
  if (id != null) {
51010
49987
  this.id = this.recycleAsyncId(scheduler, id, null);
@@ -51810,17 +50787,17 @@ var require_AsapScheduler2 = __commonJS2((exports) => {
51810
50787
  this.scheduled = undefined;
51811
50788
  var actions = this.actions;
51812
50789
  var error;
51813
- var index2 = -1;
50790
+ var index = -1;
51814
50791
  var count = actions.length;
51815
50792
  action = action || actions.shift();
51816
50793
  do {
51817
50794
  if (error = action.execute(action.state, action.delay)) {
51818
50795
  break;
51819
50796
  }
51820
- } while (++index2 < count && (action = actions.shift()));
50797
+ } while (++index < count && (action = actions.shift()));
51821
50798
  this.active = false;
51822
50799
  if (error) {
51823
- while (++index2 < count && (action = actions.shift())) {
50800
+ while (++index < count && (action = actions.shift())) {
51824
50801
  action.unsubscribe();
51825
50802
  }
51826
50803
  throw error;
@@ -51935,17 +50912,17 @@ var require_AnimationFrameScheduler2 = __commonJS2((exports) => {
51935
50912
  this.scheduled = undefined;
51936
50913
  var actions = this.actions;
51937
50914
  var error;
51938
- var index2 = -1;
50915
+ var index = -1;
51939
50916
  var count = actions.length;
51940
50917
  action = action || actions.shift();
51941
50918
  do {
51942
50919
  if (error = action.execute(action.state, action.delay)) {
51943
50920
  break;
51944
50921
  }
51945
- } while (++index2 < count && (action = actions.shift()));
50922
+ } while (++index < count && (action = actions.shift()));
51946
50923
  this.active = false;
51947
50924
  if (error) {
51948
- while (++index2 < count && (action = actions.shift())) {
50925
+ while (++index < count && (action = actions.shift())) {
51949
50926
  action.unsubscribe();
51950
50927
  }
51951
50928
  throw error;
@@ -52025,16 +51002,16 @@ var require_VirtualTimeScheduler2 = __commonJS2((exports) => {
52025
51002
  exports.VirtualTimeScheduler = VirtualTimeScheduler;
52026
51003
  var VirtualAction = function(_super) {
52027
51004
  __extends(VirtualAction2, _super);
52028
- function VirtualAction2(scheduler, work, index2) {
52029
- if (index2 === undefined) {
52030
- index2 = scheduler.index += 1;
51005
+ function VirtualAction2(scheduler, work, index) {
51006
+ if (index === undefined) {
51007
+ index = scheduler.index += 1;
52031
51008
  }
52032
51009
  var _this = _super.call(this, scheduler, work) || this;
52033
51010
  _this.scheduler = scheduler;
52034
51011
  _this.work = work;
52035
- _this.index = index2;
51012
+ _this.index = index;
52036
51013
  _this.active = true;
52037
- _this.index = scheduler.index = index2;
51014
+ _this.index = scheduler.index = index;
52038
51015
  return _this;
52039
51016
  }
52040
51017
  VirtualAction2.prototype.schedule = function(state, delay) {
@@ -53125,9 +52102,9 @@ var require_mergeMap2 = __commonJS2((exports) => {
53125
52102
  };
53126
52103
  MergeMapSubscriber2.prototype._tryNext = function(value) {
53127
52104
  var result;
53128
- var index2 = this.index++;
52105
+ var index = this.index++;
53129
52106
  try {
53130
- result = this.project(value, index2);
52107
+ result = this.project(value, index);
53131
52108
  } catch (err) {
53132
52109
  this.destination.error(err);
53133
52110
  return;
@@ -53677,12 +52654,12 @@ var require_pairs3 = __commonJS2((exports) => {
53677
52654
  }
53678
52655
  exports.pairs = pairs;
53679
52656
  function dispatch(state) {
53680
- var { keys, index: index2, subscriber, subscription, obj } = state;
52657
+ var { keys, index, subscriber, subscription, obj } = state;
53681
52658
  if (!subscriber.closed) {
53682
- if (index2 < keys.length) {
53683
- var key = keys[index2];
52659
+ if (index < keys.length) {
52660
+ var key = keys[index];
53684
52661
  subscriber.next([key, obj[key]]);
53685
- subscription.add(this.schedule({ keys, index: index2 + 1, subscriber, subscription, obj }));
52662
+ subscription.add(this.schedule({ keys, index: index + 1, subscriber, subscription, obj }));
53686
52663
  } else {
53687
52664
  subscriber.complete();
53688
52665
  }
@@ -53885,18 +52862,18 @@ var require_range2 = __commonJS2((exports) => {
53885
52862
  count = start;
53886
52863
  start = 0;
53887
52864
  }
53888
- var index2 = 0;
52865
+ var index = 0;
53889
52866
  var current = start;
53890
52867
  if (scheduler) {
53891
52868
  return scheduler.schedule(dispatch, 0, {
53892
- index: index2,
52869
+ index,
53893
52870
  count,
53894
52871
  start,
53895
52872
  subscriber
53896
52873
  });
53897
52874
  } else {
53898
52875
  do {
53899
- if (index2++ >= count) {
52876
+ if (index++ >= count) {
53900
52877
  subscriber.complete();
53901
52878
  break;
53902
52879
  }
@@ -53911,8 +52888,8 @@ var require_range2 = __commonJS2((exports) => {
53911
52888
  }
53912
52889
  exports.range = range;
53913
52890
  function dispatch(state) {
53914
- var { start, index: index2, count, subscriber } = state;
53915
- if (index2 >= count) {
52891
+ var { start, index, count, subscriber } = state;
52892
+ if (index >= count) {
53916
52893
  subscriber.complete();
53917
52894
  return;
53918
52895
  }
@@ -53920,7 +52897,7 @@ var require_range2 = __commonJS2((exports) => {
53920
52897
  if (subscriber.closed) {
53921
52898
  return;
53922
52899
  }
53923
- state.index = index2 + 1;
52900
+ state.index = index + 1;
53924
52901
  state.start = start + 1;
53925
52902
  this.schedule(state);
53926
52903
  }
@@ -53956,14 +52933,14 @@ var require_timer2 = __commonJS2((exports) => {
53956
52933
  }
53957
52934
  exports.timer = timer;
53958
52935
  function dispatch(state) {
53959
- var { index: index2, period, subscriber } = state;
53960
- subscriber.next(index2);
52936
+ var { index, period, subscriber } = state;
52937
+ subscriber.next(index);
53961
52938
  if (subscriber.closed) {
53962
52939
  return;
53963
52940
  } else if (period === -1) {
53964
52941
  return subscriber.complete();
53965
52942
  }
53966
- state.index = index2 + 1;
52943
+ state.index = index + 1;
53967
52944
  this.schedule(state, period);
53968
52945
  }
53969
52946
  });
@@ -56940,6 +55917,7 @@ function singleton3(ctorOrName) {
56940
55917
  }
56941
55918
  };
56942
55919
  }
55920
+ var telemetryPropsSlot2 = singleton3("TelemetryDefaultProps");
56943
55921
  var USER_AGENT_HEADER2 = "User-Agent";
56944
55922
  var sdkUserAgentHostToken2 = singleton3("SdkUserAgentHostToken");
56945
55923
  function userAgentPatchKey2(userAgent) {
@@ -56962,8 +55940,8 @@ function appendUserAgentToken2(value, userAgent) {
56962
55940
  function getEffectiveUserAgent2(userAgent) {
56963
55941
  return appendUserAgentToken2(sdkUserAgentHostToken2.get(), userAgent);
56964
55942
  }
56965
- function isHeadersLike2(headers) {
56966
- return typeof headers === "object" && headers !== null && "get" in headers && typeof headers.get === "function" && "set" in headers && typeof headers.set === "function";
55943
+ function getHeaderName2(headers, headerName) {
55944
+ return Object.keys(headers).find((key) => key.toLowerCase() === headerName.toLowerCase());
56967
55945
  }
56968
55946
  function getSdkUserAgentToken2(pkg) {
56969
55947
  const packageName = pkg.name.replace(/^@uipath\//, "");
@@ -56971,59 +55949,31 @@ function getSdkUserAgentToken2(pkg) {
56971
55949
  }
56972
55950
  function addSdkUserAgentHeader2(headers, userAgent) {
56973
55951
  const result = { ...headers ?? {} };
56974
- const effectiveUserAgent = getEffectiveUserAgent2(userAgent);
56975
- const headerName = Object.keys(result).find((key) => key.toLowerCase() === USER_AGENT_HEADER2.toLowerCase());
56976
- if (headerName) {
56977
- result[headerName] = appendUserAgentToken2(result[headerName], effectiveUserAgent);
56978
- } else {
56979
- result[USER_AGENT_HEADER2] = effectiveUserAgent;
56980
- }
55952
+ const headerName = getHeaderName2(result, USER_AGENT_HEADER2);
55953
+ result[headerName ?? USER_AGENT_HEADER2] = appendUserAgentToken2(headerName ? result[headerName] : undefined, getEffectiveUserAgent2(userAgent));
56981
55954
  return result;
56982
55955
  }
56983
- function withSdkUserAgentHeader2(headers, userAgent) {
56984
- const effectiveUserAgent = getEffectiveUserAgent2(userAgent);
56985
- if (isHeadersLike2(headers)) {
56986
- headers.set(USER_AGENT_HEADER2, appendUserAgentToken2(headers.get(USER_AGENT_HEADER2), effectiveUserAgent));
56987
- return headers;
56988
- }
56989
- if (Array.isArray(headers)) {
56990
- const result = headers.map((entry) => {
56991
- const [key, value] = entry;
56992
- return [key, value];
56993
- });
56994
- const headerIndex = result.findIndex(([key]) => key.toLowerCase() === USER_AGENT_HEADER2.toLowerCase());
56995
- if (headerIndex >= 0) {
56996
- const [key, value] = result[headerIndex];
56997
- result[headerIndex] = [
56998
- key,
56999
- appendUserAgentToken2(value, effectiveUserAgent)
57000
- ];
57001
- } else {
57002
- result.push([USER_AGENT_HEADER2, effectiveUserAgent]);
57003
- }
57004
- return result;
57005
- }
57006
- return addSdkUserAgentHeader2(typeof headers === "object" && headers !== null ? { ...headers } : {}, effectiveUserAgent);
55956
+ function asHeaderRecord2(headers) {
55957
+ return typeof headers === "object" && headers !== null ? { ...headers } : {};
57007
55958
  }
57008
- function withUserAgentInitOverride2(initOverrides, userAgent) {
55959
+ function withForwardedHeadersInitOverride2(initOverrides, forward) {
57009
55960
  return async (requestContext) => {
57010
- const initWithUserAgent = {
55961
+ const initWithHeaders = {
57011
55962
  ...requestContext.init,
57012
- headers: withSdkUserAgentHeader2(requestContext.init.headers, userAgent)
55963
+ headers: forward(asHeaderRecord2(requestContext.init.headers))
57013
55964
  };
57014
55965
  const override = typeof initOverrides === "function" ? await initOverrides({
57015
55966
  ...requestContext,
57016
- init: initWithUserAgent
55967
+ init: initWithHeaders
57017
55968
  }) : initOverrides;
57018
55969
  return {
57019
55970
  ...override ?? {},
57020
- headers: withSdkUserAgentHeader2(override?.headers ?? initWithUserAgent.headers, userAgent)
55971
+ headers: forward(asHeaderRecord2(override?.headers ?? initWithHeaders.headers))
57021
55972
  };
57022
55973
  };
57023
55974
  }
57024
- function installSdkUserAgentHeader2(BaseApiClass, userAgent) {
55975
+ function installRequestHeaderForwarding2(BaseApiClass, patchKey, forward) {
57025
55976
  const prototype = BaseApiClass.prototype;
57026
- const patchKey = userAgentPatchKey2(userAgent);
57027
55977
  if (prototype[patchKey]) {
57028
55978
  return;
57029
55979
  }
@@ -57031,13 +55981,16 @@ function installSdkUserAgentHeader2(BaseApiClass, userAgent) {
57031
55981
  throw new Error("Generated BaseAPI request function not found.");
57032
55982
  }
57033
55983
  const originalRequest = prototype.request;
57034
- prototype.request = function requestWithUserAgent(context, initOverrides) {
57035
- return originalRequest.call(this, context, withUserAgentInitOverride2(initOverrides, userAgent));
55984
+ prototype.request = function requestWithForwardedHeaders(context, initOverrides) {
55985
+ return originalRequest.call(this, context, withForwardedHeadersInitOverride2(initOverrides, forward));
57036
55986
  };
57037
55987
  Object.defineProperty(prototype, patchKey, {
57038
55988
  value: true
57039
55989
  });
57040
55990
  }
55991
+ function installSdkUserAgentHeader2(BaseApiClass, userAgent) {
55992
+ installRequestHeaderForwarding2(BaseApiClass, userAgentPatchKey2(userAgent), (headers) => addSdkUserAgentHeader2(headers, userAgent));
55993
+ }
57041
55994
  var BASE_PATH3 = "http://localhost".replace(/\/+$/, "");
57042
55995
 
57043
55996
  class Configuration3 {
@@ -57289,7 +56242,7 @@ class VoidApiResponse3 {
57289
56242
  var package_default4 = {
57290
56243
  name: "@uipath/compliance-packs-sdk",
57291
56244
  license: "MIT",
57292
- version: "1.196.0",
56245
+ version: "1.197.0",
57293
56246
  description: "SDK for the UiPath Governance Server Compliance Packs API.",
57294
56247
  repository: {
57295
56248
  type: "git",
@@ -57299,7 +56252,12 @@ var package_default4 = {
57299
56252
  publishConfig: {
57300
56253
  registry: "https://npm.pkg.github.com/@uipath"
57301
56254
  },
57302
- keywords: ["uipath", "governance", "compliance", "sdk"],
56255
+ keywords: [
56256
+ "uipath",
56257
+ "governance",
56258
+ "compliance",
56259
+ "sdk"
56260
+ ],
57303
56261
  type: "module",
57304
56262
  main: "./dist/index.js",
57305
56263
  types: "./dist/src/index.d.ts",
@@ -57309,10 +56267,12 @@ var package_default4 = {
57309
56267
  default: "./dist/index.js"
57310
56268
  }
57311
56269
  },
57312
- files: ["dist"],
56270
+ files: [
56271
+ "dist"
56272
+ ],
57313
56273
  private: true,
57314
56274
  scripts: {
57315
- build: "bun build ./src/index.ts --outdir dist --format esm --target node && tsc -p tsconfig.build.json --noCheck",
56275
+ build: "bun build ./src/index.ts --outdir dist --format esm --target node --sourcemap=linked && tsc -p tsconfig.build.json --noCheck",
57316
56276
  generate: "bun run src/scripts/generate-sdk.ts",
57317
56277
  lint: "biome check ."
57318
56278
  },
@@ -57816,8 +56776,8 @@ class StateApi extends BaseAPI3 {
57816
56776
  init_constants2();
57817
56777
  var DEFAULT_CLIENT_ID2 = "36dea5b8-e8bb-423d-8e7b-c808df8f1c00";
57818
56778
  var AUTH_FILE_CONFIG_KEY2 = Symbol.for("@uipath/auth/AuthFileConfig");
57819
- var globalSlot2 = globalThis;
57820
- var getAuthFileConfig2 = () => globalSlot2[AUTH_FILE_CONFIG_KEY2] ?? {};
56779
+ var globalSlot3 = globalThis;
56780
+ var getAuthFileConfig2 = () => globalSlot3[AUTH_FILE_CONFIG_KEY2] ?? {};
57821
56781
 
57822
56782
  class InvalidBaseUrlError2 extends Error {
57823
56783
  url;
@@ -57857,6 +56817,12 @@ var normalizeAndValidateBaseUrl2 = (rawUrl) => {
57857
56817
  }
57858
56818
  return url.pathname.length > 1 ? url.origin : baseUrl;
57859
56819
  };
56820
+ var resolveScopes2 = (isExternalAppAuth, customScopes, fileScopes) => {
56821
+ const requestedScopes = customScopes?.length ? customScopes : fileScopes ?? [];
56822
+ if (isExternalAppAuth)
56823
+ return requestedScopes;
56824
+ return [...new Set([...DEFAULT_SCOPES2, ...requestedScopes])];
56825
+ };
57860
56826
  var resolveConfigAsync2 = async ({
57861
56827
  customAuthority,
57862
56828
  customClientId,
@@ -57887,7 +56853,7 @@ var resolveConfigAsync2 = async ({
57887
56853
  clientSecret = fileAuth.clientSecret;
57888
56854
  }
57889
56855
  const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID2 && Boolean(clientSecret);
57890
- const scopes = customScopes && customScopes.length > 0 ? customScopes : fileAuth.scopes && fileAuth.scopes.length > 0 ? fileAuth.scopes : isExternalAppAuth ? [] : DEFAULT_SCOPES2;
56856
+ const scopes = resolveScopes2(isExternalAppAuth, customScopes, fileAuth.scopes);
57891
56857
  return {
57892
56858
  clientId,
57893
56859
  clientSecret,
@@ -57899,6 +56865,74 @@ var resolveConfigAsync2 = async ({
57899
56865
  };
57900
56866
  init_constants2();
57901
56867
  init_src2();
56868
+ init_src2();
56869
+ init_constants2();
56870
+ var DEFAULT_AUTH_PROFILE2 = "default";
56871
+ var PROFILE_DIR2 = "profiles";
56872
+ var PROFILE_NAME_RE2 = /^[A-Za-z0-9._-]+$/;
56873
+ var ACTIVE_AUTH_PROFILE_KEY2 = Symbol.for("@uipath/auth/ActiveAuthProfile");
56874
+ var AUTH_PROFILE_STORAGE_KEY2 = Symbol.for("@uipath/auth/ProfileStorage");
56875
+ var globalSlot22 = globalThis;
56876
+ function isAuthProfileStorage2(value) {
56877
+ return value !== null && typeof value === "object" && "getStore" in value && "run" in value;
56878
+ }
56879
+ function createProfileStorage2() {
56880
+ const [error, mod2] = catchError3(() => __require2("node:async_hooks"));
56881
+ if (error || typeof mod2?.AsyncLocalStorage !== "function") {
56882
+ return {
56883
+ getStore: () => {
56884
+ return;
56885
+ },
56886
+ run: (_store, fn) => fn()
56887
+ };
56888
+ }
56889
+ return new mod2.AsyncLocalStorage;
56890
+ }
56891
+ function getProfileStorage2() {
56892
+ const existing = globalSlot22[AUTH_PROFILE_STORAGE_KEY2];
56893
+ if (isAuthProfileStorage2(existing)) {
56894
+ return existing;
56895
+ }
56896
+ const storage = createProfileStorage2();
56897
+ globalSlot22[AUTH_PROFILE_STORAGE_KEY2] = storage;
56898
+ return storage;
56899
+ }
56900
+ var profileStorage2 = getProfileStorage2();
56901
+
56902
+ class AuthProfileValidationError2 extends Error {
56903
+ constructor(message) {
56904
+ super(message);
56905
+ this.name = "AuthProfileValidationError";
56906
+ }
56907
+ }
56908
+ function normalizeAuthProfileName2(profile) {
56909
+ if (profile === undefined || profile === DEFAULT_AUTH_PROFILE2) {
56910
+ return;
56911
+ }
56912
+ if (profile.length === 0 || profile === "." || profile === ".." || !PROFILE_NAME_RE2.test(profile)) {
56913
+ throw new AuthProfileValidationError2(`Invalid profile name "${profile}". Profile names may contain only letters, numbers, '.', '_', and '-'.`);
56914
+ }
56915
+ return profile;
56916
+ }
56917
+ function getActiveAuthProfile2() {
56918
+ const scopedState = profileStorage2.getStore();
56919
+ if (scopedState !== undefined) {
56920
+ return scopedState.profile;
56921
+ }
56922
+ return globalSlot22[ACTIVE_AUTH_PROFILE_KEY2]?.profile;
56923
+ }
56924
+ function resolveAuthProfileFilePath2(profile) {
56925
+ const normalized = normalizeAuthProfileName2(profile);
56926
+ if (normalized === undefined) {
56927
+ throw new AuthProfileValidationError2(`"${DEFAULT_AUTH_PROFILE2}" is the built-in profile and does not have a profile file path.`);
56928
+ }
56929
+ const fs72 = getFileSystem2();
56930
+ return fs72.path.join(fs72.env.homedir(), UIPATH_HOME_DIR2, PROFILE_DIR2, normalized, AUTH_FILENAME2);
56931
+ }
56932
+ function getActiveAuthProfileFilePath2() {
56933
+ const profile = getActiveAuthProfile2();
56934
+ return profile ? resolveAuthProfileFilePath2(profile) : undefined;
56935
+ }
57902
56936
 
57903
56937
  class InvalidIssuerError2 extends Error {
57904
56938
  expected;
@@ -58025,21 +57059,70 @@ var readAuthFromEnv2 = () => {
58025
57059
  organizationId,
58026
57060
  tenantName,
58027
57061
  tenantId,
58028
- expiration
57062
+ expiration,
57063
+ source: "env"
58029
57064
  };
58030
57065
  };
58031
57066
  init_src2();
57067
+ var BREAKER_SUFFIX2 = ".refresh-state";
57068
+ var BACKOFF_BASE_MS2 = 60000;
57069
+ var BACKOFF_CAP_MS2 = 60 * 60 * 1000;
57070
+ var SURFACE_WINDOW_MS2 = 60 * 60 * 1000;
57071
+ async function refreshTokenFingerprint2(refreshToken) {
57072
+ const bytes = new TextEncoder().encode(refreshToken);
57073
+ if (globalThis.crypto?.subtle) {
57074
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
57075
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
57076
+ }
57077
+ const { createHash } = await import("node:crypto");
57078
+ return createHash("sha256").update(refreshToken).digest("hex").slice(0, 16);
57079
+ }
57080
+ function breakerPathFor2(authPath) {
57081
+ return `${authPath}${BREAKER_SUFFIX2}`;
57082
+ }
57083
+ async function loadRefreshBreaker2(authPath) {
57084
+ const fs72 = getFileSystem2();
57085
+ try {
57086
+ const content = await fs72.readFile(breakerPathFor2(authPath), "utf-8");
57087
+ if (!content)
57088
+ return {};
57089
+ const parsed = JSON.parse(content);
57090
+ return parsed && typeof parsed === "object" ? parsed : {};
57091
+ } catch {
57092
+ return {};
57093
+ }
57094
+ }
57095
+ async function saveRefreshBreaker2(authPath, state) {
57096
+ try {
57097
+ const fs72 = getFileSystem2();
57098
+ const path32 = breakerPathFor2(authPath);
57099
+ await fs72.mkdir(fs72.path.dirname(path32));
57100
+ const tempPath = `${path32}.tmp`;
57101
+ await fs72.writeFile(tempPath, JSON.stringify(state));
57102
+ await fs72.rename(tempPath, path32);
57103
+ } catch {}
57104
+ }
57105
+ async function clearRefreshBreaker2(authPath) {
57106
+ const fs72 = getFileSystem2();
57107
+ const path32 = breakerPathFor2(authPath);
57108
+ try {
57109
+ if (await fs72.exists(path32)) {
57110
+ await fs72.rm(path32);
57111
+ }
57112
+ } catch {}
57113
+ }
57114
+ function nextBackoffMs2(attempts) {
57115
+ const shift = Math.max(0, attempts - 1);
57116
+ return Math.min(BACKOFF_BASE_MS2 * 2 ** shift, BACKOFF_CAP_MS2);
57117
+ }
57118
+ function shouldSurface2(state, nowMs) {
57119
+ if (state.lastSurfacedAtMs === undefined)
57120
+ return true;
57121
+ return nowMs - state.lastSurfacedAtMs >= SURFACE_WINDOW_MS2;
57122
+ }
57123
+ init_src2();
58032
57124
  var DEFAULT_TIMEOUT_MS2 = 1000;
58033
57125
  var CLOSE_TIMEOUT_MS2 = 500;
58034
- var NOTICE_SENTINEL2 = Symbol.for("@uipath/auth/robotFallbackNoticePrinted");
58035
- var printNoticeOnce2 = () => {
58036
- const slot = globalThis;
58037
- if (slot[NOTICE_SENTINEL2])
58038
- return;
58039
- slot[NOTICE_SENTINEL2] = true;
58040
- catchError3(() => process.stderr.write(`Using UiPath Robot credentials. Run 'uip login' for a dedicated session.
58041
- `));
58042
- };
58043
57126
  var ROBOT_USER_SERVICES_PIPE2 = "UiPathUserServices";
58044
57127
  var ROBOT_USER_SERVICES_ALTERNATE_PIPE2 = `${ROBOT_USER_SERVICES_PIPE2}Alternate`;
58045
57128
  var PIPE_NAME_MAX_LENGTH2 = 103;
@@ -58155,7 +57238,6 @@ var tryRobotClientFallback2 = async (options = {}) => {
58155
57238
  issuerFromToken = issClaim;
58156
57239
  }
58157
57240
  }
58158
- printNoticeOnce2();
58159
57241
  return {
58160
57242
  accessToken,
58161
57243
  baseUrl: parsedUrl.baseUrl,
@@ -58374,18 +57456,327 @@ var saveEnvFileAsync2 = async ({
58374
57456
  await fs72.writeFile(tempPath, content);
58375
57457
  await fs72.rename(tempPath, absolutePath);
58376
57458
  };
58377
- function normalizeTokenRefreshFailure2() {
58378
- return "stored refresh token is invalid or expired";
57459
+ var getLoginStatusAsync2 = async (options = {}) => {
57460
+ return getLoginStatusWithDeps2(options);
57461
+ };
57462
+ var getLoginStatusWithDeps2 = async (options = {}, deps = {}) => {
57463
+ const {
57464
+ resolveEnvFilePath = resolveEnvFilePathAsync2,
57465
+ loadEnvFile = loadEnvFileAsync2,
57466
+ saveEnvFile = saveEnvFileAsync2,
57467
+ getFs = getFileSystem2,
57468
+ refreshToken: refreshTokenFn = refreshAccessToken2,
57469
+ resolveConfig: resolveConfig2 = resolveConfigAsync2,
57470
+ robotFallback = tryRobotClientFallback2,
57471
+ loadBreaker = loadRefreshBreaker2,
57472
+ saveBreaker = saveRefreshBreaker2,
57473
+ clearBreaker = clearRefreshBreaker2
57474
+ } = deps;
57475
+ if (isRobotAuthEnforced2()) {
57476
+ return resolveRobotEnforcedStatus2(robotFallback);
57477
+ }
57478
+ if (isEnvAuthEnabled2()) {
57479
+ return readAuthFromEnv2();
57480
+ }
57481
+ const activeProfile = getActiveAuthProfile2();
57482
+ const activeProfileFilePath = getActiveAuthProfileFilePath2();
57483
+ const usingActiveProfile = activeProfile !== undefined && (options.envFilePath === undefined || options.envFilePath === activeProfileFilePath);
57484
+ const envFilePath = options.envFilePath ?? activeProfileFilePath ?? DEFAULT_ENV_FILENAME2;
57485
+ const { ensureTokenValidityMinutes } = options;
57486
+ const { absolutePath } = await resolveEnvFilePath(envFilePath);
57487
+ if (absolutePath === undefined) {
57488
+ if (usingActiveProfile) {
57489
+ return {
57490
+ loginStatus: "Not logged in",
57491
+ hint: `No credentials found for profile "${activeProfile}". Run 'uip login --profile ${activeProfile}' to authenticate this profile.`
57492
+ };
57493
+ }
57494
+ return resolveBorrowedRobotStatus2(robotFallback);
57495
+ }
57496
+ const loaded = await loadFileCredentials2(loadEnvFile, absolutePath);
57497
+ if ("status" in loaded) {
57498
+ return loaded.status;
57499
+ }
57500
+ const { credentials } = loaded;
57501
+ const globalHint = () => usingActiveProfile ? Promise.resolve(undefined) : getGlobalCredsHint2(getFs, loadEnvFile, absolutePath, envFilePath);
57502
+ const expiration = getTokenExpiration2(credentials.UIPATH_ACCESS_TOKEN);
57503
+ const outerThreshold = computeExpirationThreshold2(ensureTokenValidityMinutes);
57504
+ let tokens = {
57505
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
57506
+ refreshToken: credentials.UIPATH_REFRESH_TOKEN,
57507
+ expiration,
57508
+ lockReleaseFailed: false
57509
+ };
57510
+ const refreshToken = credentials.UIPATH_REFRESH_TOKEN;
57511
+ if (expiration && expiration <= outerThreshold && refreshToken) {
57512
+ const refreshed = await attemptRefresh2({
57513
+ absolutePath,
57514
+ credentials,
57515
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
57516
+ refreshToken,
57517
+ expiration,
57518
+ ensureTokenValidityMinutes,
57519
+ getFs,
57520
+ loadEnvFile,
57521
+ saveEnvFile,
57522
+ refreshFn: refreshTokenFn,
57523
+ resolveConfig: resolveConfig2,
57524
+ loadBreaker,
57525
+ saveBreaker,
57526
+ clearBreaker,
57527
+ globalHint
57528
+ });
57529
+ if (refreshed.kind === "terminal") {
57530
+ return refreshed.status;
57531
+ }
57532
+ tokens = refreshed.tokens;
57533
+ }
57534
+ return buildFileStatus2(tokens, credentials, globalHint);
57535
+ };
57536
+ async function resolveRobotEnforcedStatus2(robotFallback) {
57537
+ if (isEnvAuthEnabled2()) {
57538
+ throw new EnvAuthConfigError2(`${ENV_AUTH_ENABLE_VAR2}=true and ${ENFORCE_ROBOT_AUTH_VAR2}=true are mutually exclusive. Unset one of them and re-run.`);
57539
+ }
57540
+ const robotCreds = await robotFallback({ force: true });
57541
+ if (!robotCreds) {
57542
+ return {
57543
+ loginStatus: "Not logged in",
57544
+ hint: `${ENFORCE_ROBOT_AUTH_VAR2}=true but the UiPath Robot session is unavailable. Start and sign in to the Assistant, or unset ${ENFORCE_ROBOT_AUTH_VAR2} to fall back to file or env-var authentication.`
57545
+ };
57546
+ }
57547
+ return buildRobotStatus2(robotCreds);
58379
57548
  }
58380
- function normalizeTokenRefreshUnavailableFailure2() {
58381
- return "token refresh failed before authentication completed";
57549
+ async function resolveBorrowedRobotStatus2(robotFallback) {
57550
+ const robotCreds = await robotFallback();
57551
+ return robotCreds ? buildRobotStatus2(robotCreds) : { loginStatus: "Not logged in" };
58382
57552
  }
58383
- function errorMessage2(error) {
58384
- return error instanceof Error ? error.message : String(error);
57553
+ async function loadFileCredentials2(loadEnvFile, absolutePath) {
57554
+ let credentials;
57555
+ try {
57556
+ credentials = await loadEnvFile({ envPath: absolutePath });
57557
+ } catch (error) {
57558
+ if (isFileNotFoundError2(error)) {
57559
+ return { status: { loginStatus: "Not logged in" } };
57560
+ }
57561
+ throw error;
57562
+ }
57563
+ if (!credentials.UIPATH_ACCESS_TOKEN) {
57564
+ return { status: { loginStatus: "Not logged in" } };
57565
+ }
57566
+ return { credentials };
57567
+ }
57568
+ async function getGlobalCredsHint2(getFs, loadEnvFile, absolutePath, envFilePath) {
57569
+ const fs72 = getFs();
57570
+ const globalPath = fs72.path.join(fs72.env.homedir(), envFilePath);
57571
+ if (absolutePath === globalPath)
57572
+ return;
57573
+ if (!await fs72.exists(globalPath))
57574
+ return;
57575
+ try {
57576
+ const globalCreds = await loadEnvFile({ envPath: globalPath });
57577
+ if (!globalCreds.UIPATH_ACCESS_TOKEN)
57578
+ return;
57579
+ const globalExp = getTokenExpiration2(globalCreds.UIPATH_ACCESS_TOKEN);
57580
+ if (globalExp && globalExp <= new Date)
57581
+ return;
57582
+ return `Local credentials file at ${absolutePath} has expired credentials. Valid credentials exist in ${globalPath}. Remove the local file or run 'uip login' to re-authenticate.`;
57583
+ } catch {
57584
+ return;
57585
+ }
58385
57586
  }
58386
57587
  function computeExpirationThreshold2(ensureTokenValidityMinutes) {
58387
57588
  return new Date(Date.now() + (ensureTokenValidityMinutes ?? 0) * 60 * 1000);
58388
57589
  }
57590
+ async function attemptRefresh2(ctx) {
57591
+ const shortCircuit = await circuitBreakerShortCircuit2(ctx);
57592
+ if (shortCircuit) {
57593
+ return { kind: "terminal", status: shortCircuit };
57594
+ }
57595
+ let release;
57596
+ try {
57597
+ release = await ctx.getFs().acquireLock(ctx.absolutePath);
57598
+ } catch (error) {
57599
+ return {
57600
+ kind: "terminal",
57601
+ status: await lockAcquireFailureStatus2(ctx, error)
57602
+ };
57603
+ }
57604
+ let lockedFailure;
57605
+ let lockReleaseFailed = false;
57606
+ let success;
57607
+ try {
57608
+ const outcome = await runRefreshLocked2({
57609
+ absolutePath: ctx.absolutePath,
57610
+ refreshToken: ctx.refreshToken,
57611
+ customAuthority: ctx.credentials.UIPATH_URL,
57612
+ ensureTokenValidityMinutes: ctx.ensureTokenValidityMinutes,
57613
+ loadEnvFile: ctx.loadEnvFile,
57614
+ saveEnvFile: ctx.saveEnvFile,
57615
+ refreshFn: ctx.refreshFn,
57616
+ resolveConfig: ctx.resolveConfig,
57617
+ loadBreaker: ctx.loadBreaker,
57618
+ saveBreaker: ctx.saveBreaker,
57619
+ clearBreaker: ctx.clearBreaker
57620
+ });
57621
+ if (outcome.kind === "fail") {
57622
+ lockedFailure = outcome.status;
57623
+ } else {
57624
+ success = outcome;
57625
+ }
57626
+ } finally {
57627
+ try {
57628
+ await release();
57629
+ } catch {
57630
+ lockReleaseFailed = true;
57631
+ }
57632
+ }
57633
+ if (lockedFailure) {
57634
+ const globalHint = await ctx.globalHint();
57635
+ const base = globalHint ? { ...lockedFailure, loginStatus: "Expired", hint: globalHint } : lockedFailure;
57636
+ return {
57637
+ kind: "terminal",
57638
+ status: lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base
57639
+ };
57640
+ }
57641
+ return {
57642
+ kind: "refreshed",
57643
+ tokens: {
57644
+ accessToken: success?.accessToken,
57645
+ refreshToken: success?.refreshToken,
57646
+ expiration: success?.expiration,
57647
+ tokenRefresh: success?.tokenRefresh,
57648
+ persistenceWarning: success?.persistenceWarning,
57649
+ lockReleaseFailed
57650
+ }
57651
+ };
57652
+ }
57653
+ async function buildFileStatus2(tokens, credentials, globalHint) {
57654
+ const result = {
57655
+ loginStatus: tokens.expiration && tokens.expiration <= new Date ? "Expired" : "Logged in",
57656
+ accessToken: tokens.accessToken,
57657
+ refreshToken: tokens.refreshToken,
57658
+ baseUrl: credentials.UIPATH_URL,
57659
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
57660
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
57661
+ tenantName: credentials.UIPATH_TENANT_NAME,
57662
+ tenantId: credentials.UIPATH_TENANT_ID,
57663
+ expiration: tokens.expiration,
57664
+ source: "file",
57665
+ ...tokens.persistenceWarning ? { hint: tokens.persistenceWarning, persistenceFailed: true } : {},
57666
+ ...tokens.lockReleaseFailed ? { lockReleaseFailed: true } : {},
57667
+ ...tokens.tokenRefresh ? { tokenRefresh: tokens.tokenRefresh } : {}
57668
+ };
57669
+ if (result.loginStatus === "Expired") {
57670
+ const hint = await globalHint();
57671
+ if (hint) {
57672
+ result.hint = hint;
57673
+ }
57674
+ }
57675
+ return result;
57676
+ }
57677
+ function buildRobotStatus2(robotCreds) {
57678
+ return {
57679
+ loginStatus: "Logged in",
57680
+ accessToken: robotCreds.accessToken,
57681
+ baseUrl: robotCreds.baseUrl,
57682
+ organizationName: robotCreds.organizationName,
57683
+ organizationId: robotCreds.organizationId,
57684
+ tenantName: robotCreds.tenantName,
57685
+ tenantId: robotCreds.tenantId,
57686
+ issuer: robotCreds.issuer,
57687
+ expiration: getTokenExpiration2(robotCreds.accessToken),
57688
+ source: "robot"
57689
+ };
57690
+ }
57691
+ var isFileNotFoundError2 = (error) => {
57692
+ if (!(error instanceof Object))
57693
+ return false;
57694
+ return error.code === "ENOENT";
57695
+ };
57696
+ async function circuitBreakerShortCircuit2(ctx) {
57697
+ const {
57698
+ absolutePath,
57699
+ refreshToken,
57700
+ accessToken,
57701
+ credentials,
57702
+ expiration,
57703
+ loadBreaker,
57704
+ saveBreaker,
57705
+ clearBreaker
57706
+ } = ctx;
57707
+ const fingerprint = await refreshTokenFingerprint2(refreshToken);
57708
+ const breaker = await loadBreaker(absolutePath).catch(() => ({}));
57709
+ if (breaker.deadTokenFp && breaker.deadTokenFp !== fingerprint) {
57710
+ await clearBreaker(absolutePath);
57711
+ breaker.deadTokenFp = undefined;
57712
+ }
57713
+ const nowMs = Date.now();
57714
+ const tokenIsDead = breaker.deadTokenFp === fingerprint;
57715
+ const inBackoff = breaker.backoffUntilMs !== undefined && nowMs < breaker.backoffUntilMs;
57716
+ if (!tokenIsDead && !inBackoff)
57717
+ return;
57718
+ const globalHint = await ctx.globalHint();
57719
+ const suppressed = !shouldSurface2(breaker, nowMs);
57720
+ if (!suppressed) {
57721
+ await saveBreaker(absolutePath, {
57722
+ ...breaker,
57723
+ lastSurfacedAtMs: nowMs
57724
+ });
57725
+ }
57726
+ const deadHint = "Run 'uip login' to re-authenticate — the stored refresh token is invalid or expired. In a non-interactive context, authenticate with: uip login --client-id <id> --client-secret <secret> -t <tenant>.";
57727
+ const backoffHint = "Token refresh is temporarily backed off after a recent network error and will retry automatically once the backoff window elapses.";
57728
+ return {
57729
+ loginStatus: globalHint ? "Expired" : "Refresh Failed",
57730
+ ...globalHint ? {
57731
+ accessToken,
57732
+ refreshToken,
57733
+ baseUrl: credentials.UIPATH_URL,
57734
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
57735
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
57736
+ tenantName: credentials.UIPATH_TENANT_NAME,
57737
+ tenantId: credentials.UIPATH_TENANT_ID,
57738
+ expiration,
57739
+ source: "file"
57740
+ } : {},
57741
+ hint: globalHint ?? (tokenIsDead ? deadHint : backoffHint),
57742
+ refreshCircuitOpen: true,
57743
+ refreshTelemetrySuppressed: suppressed,
57744
+ tokenRefresh: { attempted: false, success: false }
57745
+ };
57746
+ }
57747
+ async function lockAcquireFailureStatus2(ctx, error) {
57748
+ const msg = errorMessage2(error);
57749
+ const globalHint = await ctx.globalHint();
57750
+ if (globalHint) {
57751
+ return {
57752
+ loginStatus: "Expired",
57753
+ accessToken: ctx.accessToken,
57754
+ refreshToken: ctx.refreshToken,
57755
+ baseUrl: ctx.credentials.UIPATH_URL,
57756
+ organizationName: ctx.credentials.UIPATH_ORGANIZATION_NAME,
57757
+ organizationId: ctx.credentials.UIPATH_ORGANIZATION_ID,
57758
+ tenantName: ctx.credentials.UIPATH_TENANT_NAME,
57759
+ tenantId: ctx.credentials.UIPATH_TENANT_ID,
57760
+ expiration: ctx.expiration,
57761
+ source: "file",
57762
+ hint: globalHint,
57763
+ tokenRefresh: {
57764
+ attempted: false,
57765
+ success: false,
57766
+ errorMessage: `lock acquisition failed: ${msg}`
57767
+ }
57768
+ };
57769
+ }
57770
+ return {
57771
+ loginStatus: "Refresh Failed",
57772
+ hint: "Could not acquire the auth-file lock — too many concurrent `uip` processes, or a permission issue on the auth directory. Retry, or run 'uip login' to re-authenticate.",
57773
+ tokenRefresh: {
57774
+ attempted: false,
57775
+ success: false,
57776
+ errorMessage: `lock acquisition failed: ${msg}`
57777
+ }
57778
+ };
57779
+ }
58389
57780
  async function runRefreshLocked2(inputs) {
58390
57781
  const {
58391
57782
  absolutePath,
@@ -58395,7 +57786,10 @@ async function runRefreshLocked2(inputs) {
58395
57786
  loadEnvFile,
58396
57787
  saveEnvFile,
58397
57788
  refreshFn,
58398
- resolveConfig: resolveConfig2
57789
+ resolveConfig: resolveConfig2,
57790
+ loadBreaker,
57791
+ saveBreaker,
57792
+ clearBreaker
58399
57793
  } = inputs;
58400
57794
  const expirationThreshold = computeExpirationThreshold2(ensureTokenValidityMinutes);
58401
57795
  let fresh;
@@ -58418,6 +57812,7 @@ async function runRefreshLocked2(inputs) {
58418
57812
  const freshAccess = fresh.UIPATH_ACCESS_TOKEN;
58419
57813
  const freshExp = freshAccess ? getTokenExpiration2(freshAccess) : undefined;
58420
57814
  if (freshAccess && freshExp && freshExp > expirationThreshold) {
57815
+ await clearBreaker(absolutePath);
58421
57816
  return {
58422
57817
  kind: "ok",
58423
57818
  accessToken: freshAccess,
@@ -58441,8 +57836,21 @@ async function runRefreshLocked2(inputs) {
58441
57836
  refreshedRefresh = refreshed.refreshToken;
58442
57837
  } catch (error) {
58443
57838
  const isOAuthFailure = isTokenRefreshOAuthFailure2(error);
58444
- const hint = isOAuthFailure ? "Run 'uip login' to re-authenticate — the stored refresh token is invalid or expired." : "Token refresh failed. Check your network connection, then retry or run 'uip login' to re-authenticate.";
57839
+ const hint = isOAuthFailure ? "Run 'uip login' to re-authenticate — the stored refresh token is invalid or expired. In a non-interactive context, authenticate with: uip login --client-id <id> --client-secret <secret> -t <tenant>." : "Token refresh failed. Check your network connection, then retry or run 'uip login' to re-authenticate.";
58445
57840
  const message = isOAuthFailure ? normalizeTokenRefreshFailure2() : normalizeTokenRefreshUnavailableFailure2();
57841
+ const fp = await refreshTokenFingerprint2(tokenForIdP);
57842
+ if (isOAuthFailure) {
57843
+ await saveBreaker(absolutePath, { deadTokenFp: fp });
57844
+ } else {
57845
+ const prior = await loadBreaker(absolutePath).catch(() => ({}));
57846
+ const attempts = (prior.attempts ?? 0) + 1;
57847
+ await saveBreaker(absolutePath, {
57848
+ ...prior,
57849
+ deadTokenFp: undefined,
57850
+ attempts,
57851
+ backoffUntilMs: Date.now() + nextBackoffMs2(attempts)
57852
+ });
57853
+ }
58446
57854
  return {
58447
57855
  kind: "fail",
58448
57856
  status: {
@@ -58471,6 +57879,7 @@ async function runRefreshLocked2(inputs) {
58471
57879
  }
58472
57880
  };
58473
57881
  }
57882
+ await clearBreaker(absolutePath);
58474
57883
  try {
58475
57884
  await saveEnvFile({
58476
57885
  envPath: absolutePath,
@@ -58503,213 +57912,22 @@ async function runRefreshLocked2(inputs) {
58503
57912
  };
58504
57913
  }
58505
57914
  }
58506
- var getLoginStatusWithDeps2 = async (options = {}, deps = {}) => {
58507
- const {
58508
- resolveEnvFilePath = resolveEnvFilePathAsync2,
58509
- loadEnvFile = loadEnvFileAsync2,
58510
- saveEnvFile = saveEnvFileAsync2,
58511
- getFs = getFileSystem2,
58512
- refreshToken: refreshTokenFn = refreshAccessToken2,
58513
- resolveConfig: resolveConfig2 = resolveConfigAsync2,
58514
- robotFallback = tryRobotClientFallback2
58515
- } = deps;
58516
- if (isRobotAuthEnforced2()) {
58517
- if (isEnvAuthEnabled2()) {
58518
- throw new EnvAuthConfigError2(`${ENV_AUTH_ENABLE_VAR2}=true and ${ENFORCE_ROBOT_AUTH_VAR2}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
58519
- }
58520
- const robotCreds = await robotFallback({ force: true });
58521
- if (!robotCreds) {
58522
- return {
58523
- loginStatus: "Not logged in",
58524
- hint: `${ENFORCE_ROBOT_AUTH_VAR2}=true but the UiPath Robot ` + `session is unavailable. Start and sign in to the Assistant, ` + `or unset ${ENFORCE_ROBOT_AUTH_VAR2} to fall back to file or ` + `env-var authentication.`
58525
- };
58526
- }
58527
- const expiration2 = getTokenExpiration2(robotCreds.accessToken);
58528
- return {
58529
- loginStatus: "Logged in",
58530
- accessToken: robotCreds.accessToken,
58531
- baseUrl: robotCreds.baseUrl,
58532
- organizationName: robotCreds.organizationName,
58533
- organizationId: robotCreds.organizationId,
58534
- tenantName: robotCreds.tenantName,
58535
- tenantId: robotCreds.tenantId,
58536
- issuer: robotCreds.issuer,
58537
- expiration: expiration2,
58538
- source: "robot"
58539
- };
58540
- }
58541
- if (isEnvAuthEnabled2()) {
58542
- return readAuthFromEnv2();
58543
- }
58544
- const { envFilePath = DEFAULT_ENV_FILENAME2, ensureTokenValidityMinutes } = options;
58545
- const { absolutePath } = await resolveEnvFilePath(envFilePath);
58546
- if (absolutePath === undefined) {
58547
- const robotCreds = await robotFallback();
58548
- if (robotCreds) {
58549
- const expiration2 = getTokenExpiration2(robotCreds.accessToken);
58550
- const status = {
58551
- loginStatus: "Logged in",
58552
- accessToken: robotCreds.accessToken,
58553
- baseUrl: robotCreds.baseUrl,
58554
- organizationName: robotCreds.organizationName,
58555
- organizationId: robotCreds.organizationId,
58556
- tenantName: robotCreds.tenantName,
58557
- tenantId: robotCreds.tenantId,
58558
- issuer: robotCreds.issuer,
58559
- expiration: expiration2,
58560
- source: "robot"
58561
- };
58562
- return status;
58563
- }
58564
- return { loginStatus: "Not logged in" };
58565
- }
58566
- let credentials;
58567
- try {
58568
- credentials = await loadEnvFile({ envPath: absolutePath });
58569
- } catch (error) {
58570
- if (isFileNotFoundError2(error)) {
58571
- return { loginStatus: "Not logged in" };
58572
- }
58573
- throw error;
58574
- }
58575
- if (!credentials.UIPATH_ACCESS_TOKEN) {
58576
- return { loginStatus: "Not logged in" };
58577
- }
58578
- let accessToken = credentials.UIPATH_ACCESS_TOKEN;
58579
- let refreshToken = credentials.UIPATH_REFRESH_TOKEN;
58580
- let expiration = getTokenExpiration2(accessToken);
58581
- let persistenceWarning;
58582
- let lockReleaseFailed = false;
58583
- let tokenRefresh2;
58584
- const outerThreshold = computeExpirationThreshold2(ensureTokenValidityMinutes);
58585
- const tryGlobalCredsHint = async () => {
58586
- const fs72 = getFs();
58587
- const globalPath = fs72.path.join(fs72.env.homedir(), envFilePath);
58588
- if (absolutePath === globalPath)
58589
- return;
58590
- if (!await fs72.exists(globalPath))
58591
- return;
58592
- try {
58593
- const globalCreds = await loadEnvFile({ envPath: globalPath });
58594
- if (!globalCreds.UIPATH_ACCESS_TOKEN)
58595
- return;
58596
- const globalExp = getTokenExpiration2(globalCreds.UIPATH_ACCESS_TOKEN);
58597
- if (globalExp && globalExp <= new Date)
58598
- return;
58599
- return `Local credentials file at ${absolutePath} has expired credentials. Valid credentials exist in ${globalPath}. Remove the local file or run 'uip login' to re-authenticate.`;
58600
- } catch {
58601
- return;
58602
- }
58603
- };
58604
- if (expiration && expiration <= outerThreshold && refreshToken) {
58605
- let release;
58606
- try {
58607
- release = await getFs().acquireLock(absolutePath);
58608
- } catch (error) {
58609
- const msg = errorMessage2(error);
58610
- const globalHint = await tryGlobalCredsHint();
58611
- if (globalHint) {
58612
- return {
58613
- loginStatus: "Expired",
58614
- accessToken,
58615
- refreshToken,
58616
- baseUrl: credentials.UIPATH_URL,
58617
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
58618
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
58619
- tenantName: credentials.UIPATH_TENANT_NAME,
58620
- tenantId: credentials.UIPATH_TENANT_ID,
58621
- expiration,
58622
- source: "file",
58623
- hint: globalHint,
58624
- tokenRefresh: {
58625
- attempted: false,
58626
- success: false,
58627
- errorMessage: `lock acquisition failed: ${msg}`
58628
- }
58629
- };
58630
- }
58631
- return {
58632
- loginStatus: "Refresh Failed",
58633
- hint: "Could not acquire the auth-file lock — too many concurrent `uip` processes, or a permission issue on the auth directory. Retry, or run 'uip login' to re-authenticate.",
58634
- tokenRefresh: {
58635
- attempted: false,
58636
- success: false,
58637
- errorMessage: `lock acquisition failed: ${msg}`
58638
- }
58639
- };
58640
- }
58641
- let lockedFailure;
58642
- try {
58643
- const outcome = await runRefreshLocked2({
58644
- absolutePath,
58645
- refreshToken,
58646
- customAuthority: credentials.UIPATH_URL,
58647
- ensureTokenValidityMinutes,
58648
- loadEnvFile,
58649
- saveEnvFile,
58650
- refreshFn: refreshTokenFn,
58651
- resolveConfig: resolveConfig2
58652
- });
58653
- if (outcome.kind === "fail") {
58654
- lockedFailure = outcome.status;
58655
- } else {
58656
- accessToken = outcome.accessToken;
58657
- refreshToken = outcome.refreshToken;
58658
- expiration = outcome.expiration;
58659
- tokenRefresh2 = outcome.tokenRefresh;
58660
- if (outcome.persistenceWarning) {
58661
- persistenceWarning = outcome.persistenceWarning;
58662
- }
58663
- }
58664
- } finally {
58665
- try {
58666
- await release();
58667
- } catch {
58668
- lockReleaseFailed = true;
58669
- }
58670
- }
58671
- if (lockedFailure) {
58672
- const globalHint = await tryGlobalCredsHint();
58673
- const base = globalHint ? {
58674
- ...lockedFailure,
58675
- loginStatus: "Expired",
58676
- hint: globalHint
58677
- } : lockedFailure;
58678
- return lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base;
58679
- }
58680
- }
58681
- const result = {
58682
- loginStatus: expiration && expiration <= new Date ? "Expired" : "Logged in",
58683
- accessToken,
58684
- refreshToken,
58685
- baseUrl: credentials.UIPATH_URL,
58686
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
58687
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
58688
- tenantName: credentials.UIPATH_TENANT_NAME,
58689
- tenantId: credentials.UIPATH_TENANT_ID,
58690
- expiration,
58691
- source: "file",
58692
- ...persistenceWarning ? { hint: persistenceWarning, persistenceFailed: true } : {},
58693
- ...lockReleaseFailed ? { lockReleaseFailed: true } : {},
58694
- ...tokenRefresh2 ? { tokenRefresh: tokenRefresh2 } : {}
58695
- };
58696
- if (result.loginStatus === "Expired") {
58697
- const globalHint = await tryGlobalCredsHint();
58698
- if (globalHint) {
58699
- result.hint = globalHint;
58700
- }
58701
- }
58702
- return result;
58703
- };
58704
- var isFileNotFoundError2 = (error) => {
58705
- if (!(error instanceof Object))
58706
- return false;
58707
- return error.code === "ENOENT";
58708
- };
58709
- var getLoginStatusAsync2 = async (options = {}) => {
58710
- return getLoginStatusWithDeps2(options);
58711
- };
57915
+ function normalizeTokenRefreshFailure2() {
57916
+ return "stored refresh token is invalid or expired";
57917
+ }
57918
+ function normalizeTokenRefreshUnavailableFailure2() {
57919
+ return "token refresh failed before authentication completed";
57920
+ }
57921
+ function errorMessage2(error) {
57922
+ return error instanceof Error ? error.message : String(error);
57923
+ }
58712
57924
  init_src2();
57925
+ var TENANT_SELECTION_REQUIRED_CODE2 = "TENANT_SELECTION_REQUIRED";
57926
+ var INVALID_TENANT_CODE2 = "INVALID_TENANT";
57927
+ var TENANT_SELECTION_CODES2 = new Set([
57928
+ TENANT_SELECTION_REQUIRED_CODE2,
57929
+ INVALID_TENANT_CODE2
57930
+ ]);
58713
57931
  init_src2();
58714
57932
  init_server2();
58715
57933
  async function createCompliancePacksConfig(options) {
@@ -59127,3 +58345,5 @@ export {
59127
58345
  registerCommands,
59128
58346
  metadata
59129
58347
  };
58348
+
58349
+ //# debugId=D37915939A795F4A64756E2164756E21