@uipath/authz-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 (3) hide show
  1. package/dist/index.js +889 -1924
  2. package/dist/tool.js +890 -1924
  3. package/package.json +2 -2
package/dist/tool.js CHANGED
@@ -19137,7 +19137,7 @@ var init_server = __esm(() => {
19137
19137
  var package_default = {
19138
19138
  name: "@uipath/authz-tool",
19139
19139
  license: "MIT",
19140
- version: "1.196.0",
19140
+ version: "1.197.0-preview.59",
19141
19141
  description: "CLI plugin for the UiPath Authorization service.",
19142
19142
  private: false,
19143
19143
  repository: {
@@ -19163,7 +19163,7 @@ var package_default = {
19163
19163
  "dist"
19164
19164
  ],
19165
19165
  scripts: {
19166
- build: "bun build ./src/tool.ts --outdir dist --format esm --target node --external commander && bun build ./src/index.ts --outdir dist --format esm --target node",
19166
+ build: "bun build ./src/tool.ts --outdir dist --format esm --target node --external commander --sourcemap=linked && bun build ./src/index.ts --outdir dist --format esm --target node --sourcemap=linked",
19167
19167
  package: "bun run build && bun pm pack",
19168
19168
  lint: "biome check .",
19169
19169
  "lint:fix": "biome check --write .",
@@ -19227,6 +19227,12 @@ var normalizeAndValidateBaseUrl = (rawUrl) => {
19227
19227
  }
19228
19228
  return url.pathname.length > 1 ? url.origin : baseUrl;
19229
19229
  };
19230
+ var resolveScopes = (isExternalAppAuth, customScopes, fileScopes) => {
19231
+ const requestedScopes = customScopes?.length ? customScopes : fileScopes ?? [];
19232
+ if (isExternalAppAuth)
19233
+ return requestedScopes;
19234
+ return [...new Set([...DEFAULT_SCOPES, ...requestedScopes])];
19235
+ };
19230
19236
  var resolveConfigAsync = async ({
19231
19237
  customAuthority,
19232
19238
  customClientId,
@@ -19257,7 +19263,7 @@ var resolveConfigAsync = async ({
19257
19263
  clientSecret = fileAuth.clientSecret;
19258
19264
  }
19259
19265
  const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID && Boolean(clientSecret);
19260
- const scopes = customScopes && customScopes.length > 0 ? customScopes : fileAuth.scopes && fileAuth.scopes.length > 0 ? fileAuth.scopes : isExternalAppAuth ? [] : DEFAULT_SCOPES;
19266
+ const scopes = resolveScopes(isExternalAppAuth, customScopes, fileAuth.scopes);
19261
19267
  return {
19262
19268
  clientId,
19263
19269
  clientSecret,
@@ -19272,6 +19278,76 @@ var resolveConfigAsync = async ({
19272
19278
  init_constants();
19273
19279
  // ../../auth/src/loginStatus.ts
19274
19280
  init_src();
19281
+
19282
+ // ../../auth/src/authProfile.ts
19283
+ init_src();
19284
+ init_constants();
19285
+ var DEFAULT_AUTH_PROFILE = "default";
19286
+ var PROFILE_DIR = "profiles";
19287
+ var PROFILE_NAME_RE = /^[A-Za-z0-9._-]+$/;
19288
+ var ACTIVE_AUTH_PROFILE_KEY = Symbol.for("@uipath/auth/ActiveAuthProfile");
19289
+ var AUTH_PROFILE_STORAGE_KEY = Symbol.for("@uipath/auth/ProfileStorage");
19290
+ var globalSlot2 = globalThis;
19291
+ function isAuthProfileStorage(value) {
19292
+ return value !== null && typeof value === "object" && "getStore" in value && "run" in value;
19293
+ }
19294
+ function createProfileStorage() {
19295
+ const [error, mod] = catchError(() => __require("node:async_hooks"));
19296
+ if (error || typeof mod?.AsyncLocalStorage !== "function") {
19297
+ return {
19298
+ getStore: () => {
19299
+ return;
19300
+ },
19301
+ run: (_store, fn) => fn()
19302
+ };
19303
+ }
19304
+ return new mod.AsyncLocalStorage;
19305
+ }
19306
+ function getProfileStorage() {
19307
+ const existing = globalSlot2[AUTH_PROFILE_STORAGE_KEY];
19308
+ if (isAuthProfileStorage(existing)) {
19309
+ return existing;
19310
+ }
19311
+ const storage = createProfileStorage();
19312
+ globalSlot2[AUTH_PROFILE_STORAGE_KEY] = storage;
19313
+ return storage;
19314
+ }
19315
+ var profileStorage = getProfileStorage();
19316
+
19317
+ class AuthProfileValidationError extends Error {
19318
+ constructor(message) {
19319
+ super(message);
19320
+ this.name = "AuthProfileValidationError";
19321
+ }
19322
+ }
19323
+ function normalizeAuthProfileName(profile) {
19324
+ if (profile === undefined || profile === DEFAULT_AUTH_PROFILE) {
19325
+ return;
19326
+ }
19327
+ if (profile.length === 0 || profile === "." || profile === ".." || !PROFILE_NAME_RE.test(profile)) {
19328
+ throw new AuthProfileValidationError(`Invalid profile name "${profile}". Profile names may contain only letters, numbers, '.', '_', and '-'.`);
19329
+ }
19330
+ return profile;
19331
+ }
19332
+ function getActiveAuthProfile() {
19333
+ const scopedState = profileStorage.getStore();
19334
+ if (scopedState !== undefined) {
19335
+ return scopedState.profile;
19336
+ }
19337
+ return globalSlot2[ACTIVE_AUTH_PROFILE_KEY]?.profile;
19338
+ }
19339
+ function resolveAuthProfileFilePath(profile) {
19340
+ const normalized = normalizeAuthProfileName(profile);
19341
+ if (normalized === undefined) {
19342
+ throw new AuthProfileValidationError(`"${DEFAULT_AUTH_PROFILE}" is the built-in profile and does not have a profile file path.`);
19343
+ }
19344
+ const fs7 = getFileSystem();
19345
+ return fs7.path.join(fs7.env.homedir(), UIPATH_HOME_DIR, PROFILE_DIR, normalized, AUTH_FILENAME);
19346
+ }
19347
+ function getActiveAuthProfileFilePath() {
19348
+ const profile = getActiveAuthProfile();
19349
+ return profile ? resolveAuthProfileFilePath(profile) : undefined;
19350
+ }
19275
19351
  // ../../auth/src/utils/jwt.ts
19276
19352
  class InvalidIssuerError extends Error {
19277
19353
  expected;
@@ -19400,23 +19476,74 @@ var readAuthFromEnv = () => {
19400
19476
  organizationId,
19401
19477
  tenantName,
19402
19478
  tenantId,
19403
- expiration
19479
+ expiration,
19480
+ source: "env" /* Env */
19404
19481
  };
19405
19482
  };
19406
19483
 
19484
+ // ../../auth/src/refreshCircuitBreaker.ts
19485
+ init_src();
19486
+ var BREAKER_SUFFIX = ".refresh-state";
19487
+ var BACKOFF_BASE_MS = 60000;
19488
+ var BACKOFF_CAP_MS = 60 * 60 * 1000;
19489
+ var SURFACE_WINDOW_MS = 60 * 60 * 1000;
19490
+ async function refreshTokenFingerprint(refreshToken) {
19491
+ const bytes = new TextEncoder().encode(refreshToken);
19492
+ if (globalThis.crypto?.subtle) {
19493
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
19494
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
19495
+ }
19496
+ const { createHash } = await import("node:crypto");
19497
+ return createHash("sha256").update(refreshToken).digest("hex").slice(0, 16);
19498
+ }
19499
+ function breakerPathFor(authPath) {
19500
+ return `${authPath}${BREAKER_SUFFIX}`;
19501
+ }
19502
+ async function loadRefreshBreaker(authPath) {
19503
+ const fs7 = getFileSystem();
19504
+ try {
19505
+ const content = await fs7.readFile(breakerPathFor(authPath), "utf-8");
19506
+ if (!content)
19507
+ return {};
19508
+ const parsed = JSON.parse(content);
19509
+ return parsed && typeof parsed === "object" ? parsed : {};
19510
+ } catch {
19511
+ return {};
19512
+ }
19513
+ }
19514
+ async function saveRefreshBreaker(authPath, state) {
19515
+ try {
19516
+ const fs7 = getFileSystem();
19517
+ const path3 = breakerPathFor(authPath);
19518
+ await fs7.mkdir(fs7.path.dirname(path3));
19519
+ const tempPath = `${path3}.tmp`;
19520
+ await fs7.writeFile(tempPath, JSON.stringify(state));
19521
+ await fs7.rename(tempPath, path3);
19522
+ } catch {}
19523
+ }
19524
+ async function clearRefreshBreaker(authPath) {
19525
+ const fs7 = getFileSystem();
19526
+ const path3 = breakerPathFor(authPath);
19527
+ try {
19528
+ if (await fs7.exists(path3)) {
19529
+ await fs7.rm(path3);
19530
+ }
19531
+ } catch {}
19532
+ }
19533
+ function nextBackoffMs(attempts) {
19534
+ const shift = Math.max(0, attempts - 1);
19535
+ return Math.min(BACKOFF_BASE_MS * 2 ** shift, BACKOFF_CAP_MS);
19536
+ }
19537
+ function shouldSurface(state, nowMs) {
19538
+ if (state.lastSurfacedAtMs === undefined)
19539
+ return true;
19540
+ return nowMs - state.lastSurfacedAtMs >= SURFACE_WINDOW_MS;
19541
+ }
19542
+
19407
19543
  // ../../auth/src/robotClientFallback.ts
19408
19544
  init_src();
19409
19545
  var DEFAULT_TIMEOUT_MS = 1000;
19410
19546
  var CLOSE_TIMEOUT_MS = 500;
19411
- var NOTICE_SENTINEL = Symbol.for("@uipath/auth/robotFallbackNoticePrinted");
19412
- var printNoticeOnce = () => {
19413
- const slot = globalThis;
19414
- if (slot[NOTICE_SENTINEL])
19415
- return;
19416
- slot[NOTICE_SENTINEL] = true;
19417
- catchError(() => process.stderr.write(`Using UiPath Robot credentials. Run 'uip login' for a dedicated session.
19418
- `));
19419
- };
19420
19547
  var ROBOT_USER_SERVICES_PIPE = "UiPathUserServices";
19421
19548
  var ROBOT_USER_SERVICES_ALTERNATE_PIPE = `${ROBOT_USER_SERVICES_PIPE}Alternate`;
19422
19549
  var PIPE_NAME_MAX_LENGTH = 103;
@@ -19532,7 +19659,6 @@ var tryRobotClientFallback = async (options = {}) => {
19532
19659
  issuerFromToken = issClaim;
19533
19660
  }
19534
19661
  }
19535
- printNoticeOnce();
19536
19662
  return {
19537
19663
  accessToken,
19538
19664
  baseUrl: parsedUrl.baseUrl,
@@ -19757,18 +19883,327 @@ var saveEnvFileAsync = async ({
19757
19883
  };
19758
19884
 
19759
19885
  // ../../auth/src/loginStatus.ts
19760
- function normalizeTokenRefreshFailure() {
19761
- return "stored refresh token is invalid or expired";
19886
+ var getLoginStatusAsync = async (options = {}) => {
19887
+ return getLoginStatusWithDeps(options);
19888
+ };
19889
+ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
19890
+ const {
19891
+ resolveEnvFilePath = resolveEnvFilePathAsync,
19892
+ loadEnvFile = loadEnvFileAsync,
19893
+ saveEnvFile = saveEnvFileAsync,
19894
+ getFs = getFileSystem,
19895
+ refreshToken: refreshTokenFn = refreshAccessToken,
19896
+ resolveConfig = resolveConfigAsync,
19897
+ robotFallback = tryRobotClientFallback,
19898
+ loadBreaker = loadRefreshBreaker,
19899
+ saveBreaker = saveRefreshBreaker,
19900
+ clearBreaker = clearRefreshBreaker
19901
+ } = deps;
19902
+ if (isRobotAuthEnforced()) {
19903
+ return resolveRobotEnforcedStatus(robotFallback);
19904
+ }
19905
+ if (isEnvAuthEnabled()) {
19906
+ return readAuthFromEnv();
19907
+ }
19908
+ const activeProfile = getActiveAuthProfile();
19909
+ const activeProfileFilePath = getActiveAuthProfileFilePath();
19910
+ const usingActiveProfile = activeProfile !== undefined && (options.envFilePath === undefined || options.envFilePath === activeProfileFilePath);
19911
+ const envFilePath = options.envFilePath ?? activeProfileFilePath ?? DEFAULT_ENV_FILENAME;
19912
+ const { ensureTokenValidityMinutes } = options;
19913
+ const { absolutePath } = await resolveEnvFilePath(envFilePath);
19914
+ if (absolutePath === undefined) {
19915
+ if (usingActiveProfile) {
19916
+ return {
19917
+ loginStatus: "Not logged in",
19918
+ hint: `No credentials found for profile "${activeProfile}". Run 'uip login --profile ${activeProfile}' to authenticate this profile.`
19919
+ };
19920
+ }
19921
+ return resolveBorrowedRobotStatus(robotFallback);
19922
+ }
19923
+ const loaded = await loadFileCredentials(loadEnvFile, absolutePath);
19924
+ if ("status" in loaded) {
19925
+ return loaded.status;
19926
+ }
19927
+ const { credentials } = loaded;
19928
+ const globalHint = () => usingActiveProfile ? Promise.resolve(undefined) : getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath);
19929
+ const expiration = getTokenExpiration(credentials.UIPATH_ACCESS_TOKEN);
19930
+ const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
19931
+ let tokens = {
19932
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
19933
+ refreshToken: credentials.UIPATH_REFRESH_TOKEN,
19934
+ expiration,
19935
+ lockReleaseFailed: false
19936
+ };
19937
+ const refreshToken = credentials.UIPATH_REFRESH_TOKEN;
19938
+ if (expiration && expiration <= outerThreshold && refreshToken) {
19939
+ const refreshed = await attemptRefresh({
19940
+ absolutePath,
19941
+ credentials,
19942
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
19943
+ refreshToken,
19944
+ expiration,
19945
+ ensureTokenValidityMinutes,
19946
+ getFs,
19947
+ loadEnvFile,
19948
+ saveEnvFile,
19949
+ refreshFn: refreshTokenFn,
19950
+ resolveConfig,
19951
+ loadBreaker,
19952
+ saveBreaker,
19953
+ clearBreaker,
19954
+ globalHint
19955
+ });
19956
+ if (refreshed.kind === "terminal") {
19957
+ return refreshed.status;
19958
+ }
19959
+ tokens = refreshed.tokens;
19960
+ }
19961
+ return buildFileStatus(tokens, credentials, globalHint);
19962
+ };
19963
+ async function resolveRobotEnforcedStatus(robotFallback) {
19964
+ if (isEnvAuthEnabled()) {
19965
+ throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
19966
+ }
19967
+ const robotCreds = await robotFallback({ force: true });
19968
+ if (!robotCreds) {
19969
+ return {
19970
+ loginStatus: "Not logged in",
19971
+ 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.`
19972
+ };
19973
+ }
19974
+ return buildRobotStatus(robotCreds);
19762
19975
  }
19763
- function normalizeTokenRefreshUnavailableFailure() {
19764
- return "token refresh failed before authentication completed";
19976
+ async function resolveBorrowedRobotStatus(robotFallback) {
19977
+ const robotCreds = await robotFallback();
19978
+ return robotCreds ? buildRobotStatus(robotCreds) : { loginStatus: "Not logged in" };
19765
19979
  }
19766
- function errorMessage(error) {
19767
- return error instanceof Error ? error.message : String(error);
19980
+ async function loadFileCredentials(loadEnvFile, absolutePath) {
19981
+ let credentials;
19982
+ try {
19983
+ credentials = await loadEnvFile({ envPath: absolutePath });
19984
+ } catch (error) {
19985
+ if (isFileNotFoundError(error)) {
19986
+ return { status: { loginStatus: "Not logged in" } };
19987
+ }
19988
+ throw error;
19989
+ }
19990
+ if (!credentials.UIPATH_ACCESS_TOKEN) {
19991
+ return { status: { loginStatus: "Not logged in" } };
19992
+ }
19993
+ return { credentials };
19994
+ }
19995
+ async function getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath) {
19996
+ const fs7 = getFs();
19997
+ const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
19998
+ if (absolutePath === globalPath)
19999
+ return;
20000
+ if (!await fs7.exists(globalPath))
20001
+ return;
20002
+ try {
20003
+ const globalCreds = await loadEnvFile({ envPath: globalPath });
20004
+ if (!globalCreds.UIPATH_ACCESS_TOKEN)
20005
+ return;
20006
+ const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
20007
+ if (globalExp && globalExp <= new Date)
20008
+ return;
20009
+ 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.`;
20010
+ } catch {
20011
+ return;
20012
+ }
19768
20013
  }
19769
20014
  function computeExpirationThreshold(ensureTokenValidityMinutes) {
19770
20015
  return new Date(Date.now() + (ensureTokenValidityMinutes ?? 0) * 60 * 1000);
19771
20016
  }
20017
+ async function attemptRefresh(ctx) {
20018
+ const shortCircuit = await circuitBreakerShortCircuit(ctx);
20019
+ if (shortCircuit) {
20020
+ return { kind: "terminal", status: shortCircuit };
20021
+ }
20022
+ let release;
20023
+ try {
20024
+ release = await ctx.getFs().acquireLock(ctx.absolutePath);
20025
+ } catch (error) {
20026
+ return {
20027
+ kind: "terminal",
20028
+ status: await lockAcquireFailureStatus(ctx, error)
20029
+ };
20030
+ }
20031
+ let lockedFailure;
20032
+ let lockReleaseFailed = false;
20033
+ let success;
20034
+ try {
20035
+ const outcome = await runRefreshLocked({
20036
+ absolutePath: ctx.absolutePath,
20037
+ refreshToken: ctx.refreshToken,
20038
+ customAuthority: ctx.credentials.UIPATH_URL,
20039
+ ensureTokenValidityMinutes: ctx.ensureTokenValidityMinutes,
20040
+ loadEnvFile: ctx.loadEnvFile,
20041
+ saveEnvFile: ctx.saveEnvFile,
20042
+ refreshFn: ctx.refreshFn,
20043
+ resolveConfig: ctx.resolveConfig,
20044
+ loadBreaker: ctx.loadBreaker,
20045
+ saveBreaker: ctx.saveBreaker,
20046
+ clearBreaker: ctx.clearBreaker
20047
+ });
20048
+ if (outcome.kind === "fail") {
20049
+ lockedFailure = outcome.status;
20050
+ } else {
20051
+ success = outcome;
20052
+ }
20053
+ } finally {
20054
+ try {
20055
+ await release();
20056
+ } catch {
20057
+ lockReleaseFailed = true;
20058
+ }
20059
+ }
20060
+ if (lockedFailure) {
20061
+ const globalHint = await ctx.globalHint();
20062
+ const base = globalHint ? { ...lockedFailure, loginStatus: "Expired", hint: globalHint } : lockedFailure;
20063
+ return {
20064
+ kind: "terminal",
20065
+ status: lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base
20066
+ };
20067
+ }
20068
+ return {
20069
+ kind: "refreshed",
20070
+ tokens: {
20071
+ accessToken: success?.accessToken,
20072
+ refreshToken: success?.refreshToken,
20073
+ expiration: success?.expiration,
20074
+ tokenRefresh: success?.tokenRefresh,
20075
+ persistenceWarning: success?.persistenceWarning,
20076
+ lockReleaseFailed
20077
+ }
20078
+ };
20079
+ }
20080
+ async function buildFileStatus(tokens, credentials, globalHint) {
20081
+ const result = {
20082
+ loginStatus: tokens.expiration && tokens.expiration <= new Date ? "Expired" : "Logged in",
20083
+ accessToken: tokens.accessToken,
20084
+ refreshToken: tokens.refreshToken,
20085
+ baseUrl: credentials.UIPATH_URL,
20086
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
20087
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
20088
+ tenantName: credentials.UIPATH_TENANT_NAME,
20089
+ tenantId: credentials.UIPATH_TENANT_ID,
20090
+ expiration: tokens.expiration,
20091
+ source: "file" /* File */,
20092
+ ...tokens.persistenceWarning ? { hint: tokens.persistenceWarning, persistenceFailed: true } : {},
20093
+ ...tokens.lockReleaseFailed ? { lockReleaseFailed: true } : {},
20094
+ ...tokens.tokenRefresh ? { tokenRefresh: tokens.tokenRefresh } : {}
20095
+ };
20096
+ if (result.loginStatus === "Expired") {
20097
+ const hint = await globalHint();
20098
+ if (hint) {
20099
+ result.hint = hint;
20100
+ }
20101
+ }
20102
+ return result;
20103
+ }
20104
+ function buildRobotStatus(robotCreds) {
20105
+ return {
20106
+ loginStatus: "Logged in",
20107
+ accessToken: robotCreds.accessToken,
20108
+ baseUrl: robotCreds.baseUrl,
20109
+ organizationName: robotCreds.organizationName,
20110
+ organizationId: robotCreds.organizationId,
20111
+ tenantName: robotCreds.tenantName,
20112
+ tenantId: robotCreds.tenantId,
20113
+ issuer: robotCreds.issuer,
20114
+ expiration: getTokenExpiration(robotCreds.accessToken),
20115
+ source: "robot" /* Robot */
20116
+ };
20117
+ }
20118
+ var isFileNotFoundError = (error) => {
20119
+ if (!(error instanceof Object))
20120
+ return false;
20121
+ return error.code === "ENOENT";
20122
+ };
20123
+ async function circuitBreakerShortCircuit(ctx) {
20124
+ const {
20125
+ absolutePath,
20126
+ refreshToken,
20127
+ accessToken,
20128
+ credentials,
20129
+ expiration,
20130
+ loadBreaker,
20131
+ saveBreaker,
20132
+ clearBreaker
20133
+ } = ctx;
20134
+ const fingerprint = await refreshTokenFingerprint(refreshToken);
20135
+ const breaker = await loadBreaker(absolutePath).catch(() => ({}));
20136
+ if (breaker.deadTokenFp && breaker.deadTokenFp !== fingerprint) {
20137
+ await clearBreaker(absolutePath);
20138
+ breaker.deadTokenFp = undefined;
20139
+ }
20140
+ const nowMs = Date.now();
20141
+ const tokenIsDead = breaker.deadTokenFp === fingerprint;
20142
+ const inBackoff = breaker.backoffUntilMs !== undefined && nowMs < breaker.backoffUntilMs;
20143
+ if (!tokenIsDead && !inBackoff)
20144
+ return;
20145
+ const globalHint = await ctx.globalHint();
20146
+ const suppressed = !shouldSurface(breaker, nowMs);
20147
+ if (!suppressed) {
20148
+ await saveBreaker(absolutePath, {
20149
+ ...breaker,
20150
+ lastSurfacedAtMs: nowMs
20151
+ });
20152
+ }
20153
+ 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>.";
20154
+ const backoffHint = "Token refresh is temporarily backed off after a recent network error and will retry automatically once the backoff window elapses.";
20155
+ return {
20156
+ loginStatus: globalHint ? "Expired" : "Refresh Failed",
20157
+ ...globalHint ? {
20158
+ accessToken,
20159
+ refreshToken,
20160
+ baseUrl: credentials.UIPATH_URL,
20161
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
20162
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
20163
+ tenantName: credentials.UIPATH_TENANT_NAME,
20164
+ tenantId: credentials.UIPATH_TENANT_ID,
20165
+ expiration,
20166
+ source: "file" /* File */
20167
+ } : {},
20168
+ hint: globalHint ?? (tokenIsDead ? deadHint : backoffHint),
20169
+ refreshCircuitOpen: true,
20170
+ refreshTelemetrySuppressed: suppressed,
20171
+ tokenRefresh: { attempted: false, success: false }
20172
+ };
20173
+ }
20174
+ async function lockAcquireFailureStatus(ctx, error) {
20175
+ const msg = errorMessage(error);
20176
+ const globalHint = await ctx.globalHint();
20177
+ if (globalHint) {
20178
+ return {
20179
+ loginStatus: "Expired",
20180
+ accessToken: ctx.accessToken,
20181
+ refreshToken: ctx.refreshToken,
20182
+ baseUrl: ctx.credentials.UIPATH_URL,
20183
+ organizationName: ctx.credentials.UIPATH_ORGANIZATION_NAME,
20184
+ organizationId: ctx.credentials.UIPATH_ORGANIZATION_ID,
20185
+ tenantName: ctx.credentials.UIPATH_TENANT_NAME,
20186
+ tenantId: ctx.credentials.UIPATH_TENANT_ID,
20187
+ expiration: ctx.expiration,
20188
+ source: "file" /* File */,
20189
+ hint: globalHint,
20190
+ tokenRefresh: {
20191
+ attempted: false,
20192
+ success: false,
20193
+ errorMessage: `lock acquisition failed: ${msg}`
20194
+ }
20195
+ };
20196
+ }
20197
+ return {
20198
+ loginStatus: "Refresh Failed",
20199
+ 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.",
20200
+ tokenRefresh: {
20201
+ attempted: false,
20202
+ success: false,
20203
+ errorMessage: `lock acquisition failed: ${msg}`
20204
+ }
20205
+ };
20206
+ }
19772
20207
  async function runRefreshLocked(inputs) {
19773
20208
  const {
19774
20209
  absolutePath,
@@ -19778,7 +20213,10 @@ async function runRefreshLocked(inputs) {
19778
20213
  loadEnvFile,
19779
20214
  saveEnvFile,
19780
20215
  refreshFn,
19781
- resolveConfig
20216
+ resolveConfig,
20217
+ loadBreaker,
20218
+ saveBreaker,
20219
+ clearBreaker
19782
20220
  } = inputs;
19783
20221
  const expirationThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
19784
20222
  let fresh;
@@ -19801,6 +20239,7 @@ async function runRefreshLocked(inputs) {
19801
20239
  const freshAccess = fresh.UIPATH_ACCESS_TOKEN;
19802
20240
  const freshExp = freshAccess ? getTokenExpiration(freshAccess) : undefined;
19803
20241
  if (freshAccess && freshExp && freshExp > expirationThreshold) {
20242
+ await clearBreaker(absolutePath);
19804
20243
  return {
19805
20244
  kind: "ok",
19806
20245
  accessToken: freshAccess,
@@ -19824,8 +20263,21 @@ async function runRefreshLocked(inputs) {
19824
20263
  refreshedRefresh = refreshed.refreshToken;
19825
20264
  } catch (error) {
19826
20265
  const isOAuthFailure = isTokenRefreshOAuthFailure(error);
19827
- 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.";
20266
+ 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.";
19828
20267
  const message = isOAuthFailure ? normalizeTokenRefreshFailure() : normalizeTokenRefreshUnavailableFailure();
20268
+ const fp = await refreshTokenFingerprint(tokenForIdP);
20269
+ if (isOAuthFailure) {
20270
+ await saveBreaker(absolutePath, { deadTokenFp: fp });
20271
+ } else {
20272
+ const prior = await loadBreaker(absolutePath).catch(() => ({}));
20273
+ const attempts = (prior.attempts ?? 0) + 1;
20274
+ await saveBreaker(absolutePath, {
20275
+ ...prior,
20276
+ deadTokenFp: undefined,
20277
+ attempts,
20278
+ backoffUntilMs: Date.now() + nextBackoffMs(attempts)
20279
+ });
20280
+ }
19829
20281
  return {
19830
20282
  kind: "fail",
19831
20283
  status: {
@@ -19854,6 +20306,7 @@ async function runRefreshLocked(inputs) {
19854
20306
  }
19855
20307
  };
19856
20308
  }
20309
+ await clearBreaker(absolutePath);
19857
20310
  try {
19858
20311
  await saveEnvFile({
19859
20312
  envPath: absolutePath,
@@ -19886,234 +20339,37 @@ async function runRefreshLocked(inputs) {
19886
20339
  };
19887
20340
  }
19888
20341
  }
19889
- var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
19890
- const {
19891
- resolveEnvFilePath = resolveEnvFilePathAsync,
19892
- loadEnvFile = loadEnvFileAsync,
19893
- saveEnvFile = saveEnvFileAsync,
19894
- getFs = getFileSystem,
19895
- refreshToken: refreshTokenFn = refreshAccessToken,
19896
- resolveConfig = resolveConfigAsync,
19897
- robotFallback = tryRobotClientFallback
19898
- } = deps;
19899
- if (isRobotAuthEnforced()) {
19900
- if (isEnvAuthEnabled()) {
19901
- throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
19902
- }
19903
- const robotCreds = await robotFallback({ force: true });
19904
- if (!robotCreds) {
19905
- return {
19906
- loginStatus: "Not logged in",
19907
- 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.`
19908
- };
19909
- }
19910
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
19911
- return {
19912
- loginStatus: "Logged in",
19913
- accessToken: robotCreds.accessToken,
19914
- baseUrl: robotCreds.baseUrl,
19915
- organizationName: robotCreds.organizationName,
19916
- organizationId: robotCreds.organizationId,
19917
- tenantName: robotCreds.tenantName,
19918
- tenantId: robotCreds.tenantId,
19919
- issuer: robotCreds.issuer,
19920
- expiration: expiration2,
19921
- source: "robot" /* Robot */
19922
- };
20342
+ function normalizeTokenRefreshFailure() {
20343
+ return "stored refresh token is invalid or expired";
20344
+ }
20345
+ function normalizeTokenRefreshUnavailableFailure() {
20346
+ return "token refresh failed before authentication completed";
20347
+ }
20348
+ function errorMessage(error) {
20349
+ return error instanceof Error ? error.message : String(error);
20350
+ }
20351
+
20352
+ // ../../auth/src/authContext.ts
20353
+ var getAuthContext = async (options = {}) => {
20354
+ const status = await getLoginStatusAsync({
20355
+ ensureTokenValidityMinutes: options.ensureTokenValidityMinutes,
20356
+ envFilePath: options.envFilePath
20357
+ });
20358
+ if (status.loginStatus !== "Logged in" || !status.baseUrl || !status.accessToken) {
20359
+ throw new Error(status.hint ? `Not logged in. ${status.hint}` : "Not logged in. Run 'uip login' first.");
19923
20360
  }
19924
- if (isEnvAuthEnabled()) {
19925
- return readAuthFromEnv();
20361
+ const tenantName = options.tenant ?? status.tenantName;
20362
+ if (options.requireOrganizationId && !status.organizationId) {
20363
+ throw new Error("Organization ID not available. Ensure you are logged in with an organization context.");
19926
20364
  }
19927
- const { envFilePath = DEFAULT_ENV_FILENAME, ensureTokenValidityMinutes } = options;
19928
- const { absolutePath } = await resolveEnvFilePath(envFilePath);
19929
- if (absolutePath === undefined) {
19930
- const robotCreds = await robotFallback();
19931
- if (robotCreds) {
19932
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
19933
- const status = {
19934
- loginStatus: "Logged in",
19935
- accessToken: robotCreds.accessToken,
19936
- baseUrl: robotCreds.baseUrl,
19937
- organizationName: robotCreds.organizationName,
19938
- organizationId: robotCreds.organizationId,
19939
- tenantName: robotCreds.tenantName,
19940
- tenantId: robotCreds.tenantId,
19941
- issuer: robotCreds.issuer,
19942
- expiration: expiration2,
19943
- source: "robot" /* Robot */
19944
- };
19945
- return status;
19946
- }
19947
- return { loginStatus: "Not logged in" };
20365
+ if (options.requireOrganizationName && !status.organizationName) {
20366
+ throw new Error("Organization name not available. Ensure you are logged in with an organization context.");
19948
20367
  }
19949
- let credentials;
19950
- try {
19951
- credentials = await loadEnvFile({ envPath: absolutePath });
19952
- } catch (error) {
19953
- if (isFileNotFoundError(error)) {
19954
- return { loginStatus: "Not logged in" };
19955
- }
19956
- throw error;
20368
+ if (options.requireTenantId && !status.tenantId) {
20369
+ throw new Error("Tenant ID not available. Ensure UIPATH_TENANT_ID is set.");
19957
20370
  }
19958
- if (!credentials.UIPATH_ACCESS_TOKEN) {
19959
- return { loginStatus: "Not logged in" };
19960
- }
19961
- let accessToken = credentials.UIPATH_ACCESS_TOKEN;
19962
- let refreshToken = credentials.UIPATH_REFRESH_TOKEN;
19963
- let expiration = getTokenExpiration(accessToken);
19964
- let persistenceWarning;
19965
- let lockReleaseFailed = false;
19966
- let tokenRefresh;
19967
- const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
19968
- const tryGlobalCredsHint = async () => {
19969
- const fs7 = getFs();
19970
- const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
19971
- if (absolutePath === globalPath)
19972
- return;
19973
- if (!await fs7.exists(globalPath))
19974
- return;
19975
- try {
19976
- const globalCreds = await loadEnvFile({ envPath: globalPath });
19977
- if (!globalCreds.UIPATH_ACCESS_TOKEN)
19978
- return;
19979
- const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
19980
- if (globalExp && globalExp <= new Date)
19981
- return;
19982
- 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.`;
19983
- } catch {
19984
- return;
19985
- }
19986
- };
19987
- if (expiration && expiration <= outerThreshold && refreshToken) {
19988
- let release;
19989
- try {
19990
- release = await getFs().acquireLock(absolutePath);
19991
- } catch (error) {
19992
- const msg = errorMessage(error);
19993
- const globalHint = await tryGlobalCredsHint();
19994
- if (globalHint) {
19995
- return {
19996
- loginStatus: "Expired",
19997
- accessToken,
19998
- refreshToken,
19999
- baseUrl: credentials.UIPATH_URL,
20000
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
20001
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
20002
- tenantName: credentials.UIPATH_TENANT_NAME,
20003
- tenantId: credentials.UIPATH_TENANT_ID,
20004
- expiration,
20005
- source: "file" /* File */,
20006
- hint: globalHint,
20007
- tokenRefresh: {
20008
- attempted: false,
20009
- success: false,
20010
- errorMessage: `lock acquisition failed: ${msg}`
20011
- }
20012
- };
20013
- }
20014
- return {
20015
- loginStatus: "Refresh Failed",
20016
- 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.",
20017
- tokenRefresh: {
20018
- attempted: false,
20019
- success: false,
20020
- errorMessage: `lock acquisition failed: ${msg}`
20021
- }
20022
- };
20023
- }
20024
- let lockedFailure;
20025
- try {
20026
- const outcome = await runRefreshLocked({
20027
- absolutePath,
20028
- refreshToken,
20029
- customAuthority: credentials.UIPATH_URL,
20030
- ensureTokenValidityMinutes,
20031
- loadEnvFile,
20032
- saveEnvFile,
20033
- refreshFn: refreshTokenFn,
20034
- resolveConfig
20035
- });
20036
- if (outcome.kind === "fail") {
20037
- lockedFailure = outcome.status;
20038
- } else {
20039
- accessToken = outcome.accessToken;
20040
- refreshToken = outcome.refreshToken;
20041
- expiration = outcome.expiration;
20042
- tokenRefresh = outcome.tokenRefresh;
20043
- if (outcome.persistenceWarning) {
20044
- persistenceWarning = outcome.persistenceWarning;
20045
- }
20046
- }
20047
- } finally {
20048
- try {
20049
- await release();
20050
- } catch {
20051
- lockReleaseFailed = true;
20052
- }
20053
- }
20054
- if (lockedFailure) {
20055
- const globalHint = await tryGlobalCredsHint();
20056
- const base = globalHint ? {
20057
- ...lockedFailure,
20058
- loginStatus: "Expired",
20059
- hint: globalHint
20060
- } : lockedFailure;
20061
- return lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base;
20062
- }
20063
- }
20064
- const result = {
20065
- loginStatus: expiration && expiration <= new Date ? "Expired" : "Logged in",
20066
- accessToken,
20067
- refreshToken,
20068
- baseUrl: credentials.UIPATH_URL,
20069
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
20070
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
20071
- tenantName: credentials.UIPATH_TENANT_NAME,
20072
- tenantId: credentials.UIPATH_TENANT_ID,
20073
- expiration,
20074
- source: "file" /* File */,
20075
- ...persistenceWarning ? { hint: persistenceWarning, persistenceFailed: true } : {},
20076
- ...lockReleaseFailed ? { lockReleaseFailed: true } : {},
20077
- ...tokenRefresh ? { tokenRefresh } : {}
20078
- };
20079
- if (result.loginStatus === "Expired") {
20080
- const globalHint = await tryGlobalCredsHint();
20081
- if (globalHint) {
20082
- result.hint = globalHint;
20083
- }
20084
- }
20085
- return result;
20086
- };
20087
- var isFileNotFoundError = (error) => {
20088
- if (!(error instanceof Object))
20089
- return false;
20090
- return error.code === "ENOENT";
20091
- };
20092
- var getLoginStatusAsync = async (options = {}) => {
20093
- return getLoginStatusWithDeps(options);
20094
- };
20095
-
20096
- // ../../auth/src/authContext.ts
20097
- var getAuthContext = async (options = {}) => {
20098
- const status = await getLoginStatusAsync({
20099
- ensureTokenValidityMinutes: options.ensureTokenValidityMinutes,
20100
- envFilePath: options.envFilePath
20101
- });
20102
- if (status.loginStatus !== "Logged in" || !status.baseUrl || !status.accessToken) {
20103
- throw new Error(status.hint ? `Not logged in. ${status.hint}` : "Not logged in. Run 'uip login' first.");
20104
- }
20105
- const tenantName = options.tenant ?? status.tenantName;
20106
- if (options.requireOrganizationId && !status.organizationId) {
20107
- throw new Error("Organization ID not available. Ensure you are logged in with an organization context.");
20108
- }
20109
- if (options.requireOrganizationName && !status.organizationName) {
20110
- throw new Error("Organization name not available. Ensure you are logged in with an organization context.");
20111
- }
20112
- if (options.requireTenantId && !status.tenantId) {
20113
- throw new Error("Tenant ID not available. Ensure UIPATH_TENANT_ID is set.");
20114
- }
20115
- if (options.requireTenantName && tenantName === undefined) {
20116
- throw new Error("Tenant not provided and UIPATH_TENANT_NAME not set. Run 'uip login' to select a tenant, or use 'uip login tenant set <tenant>' to switch tenants.");
20371
+ if (options.requireTenantName && tenantName === undefined) {
20372
+ throw new Error("Tenant not provided and UIPATH_TENANT_NAME not set. Run 'uip login' to select a tenant, or use 'uip login tenant set <tenant>' to switch tenants.");
20117
20373
  }
20118
20374
  return {
20119
20375
  baseUrl: status.baseUrl,
@@ -20126,6 +20382,14 @@ var getAuthContext = async (options = {}) => {
20126
20382
  };
20127
20383
  // ../../auth/src/interactive.ts
20128
20384
  init_src();
20385
+
20386
+ // ../../auth/src/selectTenant.ts
20387
+ var TENANT_SELECTION_REQUIRED_CODE = "TENANT_SELECTION_REQUIRED";
20388
+ var INVALID_TENANT_CODE = "INVALID_TENANT";
20389
+ var TENANT_SELECTION_CODES = new Set([
20390
+ TENANT_SELECTION_REQUIRED_CODE,
20391
+ INVALID_TENANT_CODE
20392
+ ]);
20129
20393
  // ../../auth/src/logout.ts
20130
20394
  init_src();
20131
20395
 
@@ -20162,6 +20426,12 @@ function singleton(ctorOrName) {
20162
20426
  };
20163
20427
  }
20164
20428
 
20429
+ // ../../common/src/telemetry/global-telemetry-properties.ts
20430
+ var telemetryPropsSlot = singleton("TelemetryDefaultProps");
20431
+ function getGlobalTelemetryProperties() {
20432
+ return telemetryPropsSlot.get();
20433
+ }
20434
+
20165
20435
  // ../../common/src/sdk-user-agent.ts
20166
20436
  var USER_AGENT_HEADER = "User-Agent";
20167
20437
  var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
@@ -20185,8 +20455,8 @@ function appendUserAgentToken(value, userAgent) {
20185
20455
  function getEffectiveUserAgent(userAgent) {
20186
20456
  return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent);
20187
20457
  }
20188
- function isHeadersLike(headers) {
20189
- return typeof headers === "object" && headers !== null && "get" in headers && typeof headers.get === "function" && "set" in headers && typeof headers.set === "function";
20458
+ function getHeaderName(headers, headerName) {
20459
+ return Object.keys(headers).find((key) => key.toLowerCase() === headerName.toLowerCase());
20190
20460
  }
20191
20461
  function getSdkUserAgentToken(pkg) {
20192
20462
  const packageName = pkg.name.replace(/^@uipath\//, "");
@@ -20194,59 +20464,31 @@ function getSdkUserAgentToken(pkg) {
20194
20464
  }
20195
20465
  function addSdkUserAgentHeader(headers, userAgent) {
20196
20466
  const result = { ...headers ?? {} };
20197
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
20198
- const headerName = Object.keys(result).find((key) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
20199
- if (headerName) {
20200
- result[headerName] = appendUserAgentToken(result[headerName], effectiveUserAgent);
20201
- } else {
20202
- result[USER_AGENT_HEADER] = effectiveUserAgent;
20203
- }
20467
+ const headerName = getHeaderName(result, USER_AGENT_HEADER);
20468
+ result[headerName ?? USER_AGENT_HEADER] = appendUserAgentToken(headerName ? result[headerName] : undefined, getEffectiveUserAgent(userAgent));
20204
20469
  return result;
20205
20470
  }
20206
- function withSdkUserAgentHeader(headers, userAgent) {
20207
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
20208
- if (isHeadersLike(headers)) {
20209
- headers.set(USER_AGENT_HEADER, appendUserAgentToken(headers.get(USER_AGENT_HEADER), effectiveUserAgent));
20210
- return headers;
20211
- }
20212
- if (Array.isArray(headers)) {
20213
- const result = headers.map((entry) => {
20214
- const [key, value] = entry;
20215
- return [key, value];
20216
- });
20217
- const headerIndex = result.findIndex(([key]) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
20218
- if (headerIndex >= 0) {
20219
- const [key, value] = result[headerIndex];
20220
- result[headerIndex] = [
20221
- key,
20222
- appendUserAgentToken(value, effectiveUserAgent)
20223
- ];
20224
- } else {
20225
- result.push([USER_AGENT_HEADER, effectiveUserAgent]);
20226
- }
20227
- return result;
20228
- }
20229
- return addSdkUserAgentHeader(typeof headers === "object" && headers !== null ? { ...headers } : {}, effectiveUserAgent);
20471
+ function asHeaderRecord(headers) {
20472
+ return typeof headers === "object" && headers !== null ? { ...headers } : {};
20230
20473
  }
20231
- function withUserAgentInitOverride(initOverrides, userAgent) {
20474
+ function withForwardedHeadersInitOverride(initOverrides, forward) {
20232
20475
  return async (requestContext) => {
20233
- const initWithUserAgent = {
20476
+ const initWithHeaders = {
20234
20477
  ...requestContext.init,
20235
- headers: withSdkUserAgentHeader(requestContext.init.headers, userAgent)
20478
+ headers: forward(asHeaderRecord(requestContext.init.headers))
20236
20479
  };
20237
20480
  const override = typeof initOverrides === "function" ? await initOverrides({
20238
20481
  ...requestContext,
20239
- init: initWithUserAgent
20482
+ init: initWithHeaders
20240
20483
  }) : initOverrides;
20241
20484
  return {
20242
20485
  ...override ?? {},
20243
- headers: withSdkUserAgentHeader(override?.headers ?? initWithUserAgent.headers, userAgent)
20486
+ headers: forward(asHeaderRecord(override?.headers ?? initWithHeaders.headers))
20244
20487
  };
20245
20488
  };
20246
20489
  }
20247
- function installSdkUserAgentHeader(BaseApiClass, userAgent) {
20490
+ function installRequestHeaderForwarding(BaseApiClass, patchKey, forward) {
20248
20491
  const prototype = BaseApiClass.prototype;
20249
- const patchKey = userAgentPatchKey(userAgent);
20250
20492
  if (prototype[patchKey]) {
20251
20493
  return;
20252
20494
  }
@@ -20254,13 +20496,16 @@ function installSdkUserAgentHeader(BaseApiClass, userAgent) {
20254
20496
  throw new Error("Generated BaseAPI request function not found.");
20255
20497
  }
20256
20498
  const originalRequest = prototype.request;
20257
- prototype.request = function requestWithUserAgent(context, initOverrides) {
20258
- return originalRequest.call(this, context, withUserAgentInitOverride(initOverrides, userAgent));
20499
+ prototype.request = function requestWithForwardedHeaders(context, initOverrides) {
20500
+ return originalRequest.call(this, context, withForwardedHeadersInitOverride(initOverrides, forward));
20259
20501
  };
20260
20502
  Object.defineProperty(prototype, patchKey, {
20261
20503
  value: true
20262
20504
  });
20263
20505
  }
20506
+ function installSdkUserAgentHeader(BaseApiClass, userAgent) {
20507
+ installRequestHeaderForwarding(BaseApiClass, userAgentPatchKey(userAgent), (headers) => addSdkUserAgentHeader(headers, userAgent));
20508
+ }
20264
20509
 
20265
20510
  // ../authz-sdk/generated/src/runtime.ts
20266
20511
  var BASE_PATH = "http://localhost".replace(/\/+$/, "");
@@ -20515,7 +20760,7 @@ class VoidApiResponse {
20515
20760
  var package_default2 = {
20516
20761
  name: "@uipath/authz-sdk",
20517
20762
  license: "MIT",
20518
- version: "1.196.0",
20763
+ version: "1.197.0",
20519
20764
  description: "SDK for the UiPath Authorization Service API.",
20520
20765
  repository: {
20521
20766
  type: "git",
@@ -20545,7 +20790,7 @@ var package_default2 = {
20545
20790
  ],
20546
20791
  private: true,
20547
20792
  scripts: {
20548
- build: "bun build ./src/index.ts --outdir dist --format esm --target node && tsc -p tsconfig.build.json --noCheck",
20793
+ build: "bun build ./src/index.ts --outdir dist --format esm --target node --sourcemap=linked && tsc -p tsconfig.build.json --noCheck",
20549
20794
  generate: "bun run src/scripts/generate-sdk.ts",
20550
20795
  lint: "biome check ."
20551
20796
  },
@@ -21159,27 +21404,54 @@ var NETWORK_ERROR_CODES = new Set([
21159
21404
  "ENETUNREACH",
21160
21405
  "EAI_FAIL"
21161
21406
  ]);
21162
- function isHtmlDocument(body) {
21163
- return /^\s*(<!doctype html|<html\b)/i.test(body);
21164
- }
21165
- function extractNetworkErrorCode(error) {
21166
- if (error === null || typeof error !== "object") {
21167
- return;
21168
- }
21169
- const err = error;
21170
- const code = typeof err.code === "string" ? err.code : undefined;
21171
- if (code && NETWORK_ERROR_CODES.has(code)) {
21172
- return code;
21173
- }
21174
- const cause = err.cause;
21175
- if (cause !== null && typeof cause === "object") {
21176
- const causeCode = cause.code;
21177
- if (typeof causeCode === "string" && NETWORK_ERROR_CODES.has(causeCode)) {
21178
- return causeCode;
21407
+ var TLS_ERROR_CODES = new Set([
21408
+ "SELF_SIGNED_CERT_IN_CHAIN",
21409
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
21410
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
21411
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
21412
+ "UNABLE_TO_GET_ISSUER_CERT",
21413
+ "CERT_HAS_EXPIRED",
21414
+ "CERT_UNTRUSTED",
21415
+ "ERR_TLS_CERT_ALTNAME_INVALID"
21416
+ ]);
21417
+ 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.";
21418
+ 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.";
21419
+ function describeConnectivityError(error) {
21420
+ let current = error;
21421
+ for (let depth = 0;depth < 5 && current !== null && typeof current === "object"; depth++) {
21422
+ const cur = current;
21423
+ const code = typeof cur.code === "string" ? cur.code : undefined;
21424
+ const message = typeof cur.message === "string" ? cur.message : undefined;
21425
+ if (code && TLS_ERROR_CODES.has(code)) {
21426
+ return {
21427
+ code,
21428
+ kind: "tls",
21429
+ message: message ?? code,
21430
+ instructions: TLS_INSTRUCTIONS
21431
+ };
21432
+ }
21433
+ if (code && NETWORK_ERROR_CODES.has(code)) {
21434
+ return {
21435
+ code,
21436
+ kind: "network",
21437
+ message: message ?? code,
21438
+ instructions: NETWORK_INSTRUCTIONS
21439
+ };
21179
21440
  }
21441
+ current = cur.cause;
21180
21442
  }
21181
21443
  return;
21182
21444
  }
21445
+ function parseHttpStatusFromMessage(message) {
21446
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
21447
+ if (!match)
21448
+ return;
21449
+ const status = Number(match[1]);
21450
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
21451
+ }
21452
+ function isHtmlDocument(body) {
21453
+ return /^\s*(<!doctype html|<html\b)/i.test(body);
21454
+ }
21183
21455
  function retryHintForRetryAfter(seconds) {
21184
21456
  if (seconds <= 1) {
21185
21457
  return "RetryAfter1Second";
@@ -21220,15 +21492,28 @@ function classifyError(status, error) {
21220
21492
  if (status !== undefined && status >= 500 && status < 600) {
21221
21493
  return { errorCode: "server_error", retry: "RetryLater" };
21222
21494
  }
21223
- if (extractNetworkErrorCode(error)) {
21224
- return { errorCode: "network_error", retry: "RetryLater" };
21495
+ const connectivity = describeConnectivityError(error);
21496
+ if (connectivity) {
21497
+ return {
21498
+ errorCode: "network_error",
21499
+ retry: connectivity.kind === "tls" ? "RetryWillNotFix" : "RetryLater"
21500
+ };
21225
21501
  }
21226
21502
  return { errorCode: "unknown_error", retry: "RetryWillNotFix" };
21227
21503
  }
21504
+ function formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus) {
21505
+ if (extractedMessage) {
21506
+ return `HTTP ${status}: ${extractedMessage}`;
21507
+ }
21508
+ return inferredStatus !== undefined ? rawMessage : `HTTP ${status}: ${rawMessage}`;
21509
+ }
21228
21510
  async function extractErrorDetails(error, options) {
21229
21511
  const err = error !== null && error !== undefined && typeof error === "object" ? error : {};
21230
21512
  const response = err.response;
21231
- const status = err.status ?? response?.status;
21513
+ const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
21514
+ const explicitStatus = err.status ?? response?.status;
21515
+ const inferredStatus = explicitStatus === undefined ? parseHttpStatusFromMessage(rawMessage) : undefined;
21516
+ const status = explicitStatus ?? inferredStatus;
21232
21517
  const isSuccessfulResponse = status !== undefined && status >= 200 && status < 300;
21233
21518
  let rawBody;
21234
21519
  let extractedMessage;
@@ -21263,7 +21548,6 @@ async function extractErrorDetails(error, options) {
21263
21548
  }
21264
21549
  }
21265
21550
  }
21266
- const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
21267
21551
  let message;
21268
21552
  let result = "Failure";
21269
21553
  const classification = classifyError(status, error);
@@ -21277,10 +21561,10 @@ async function extractErrorDetails(error, options) {
21277
21561
  } else if (status === 405) {
21278
21562
  message = DEFAULT_405;
21279
21563
  } else if (status === 400 || status === 422) {
21280
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
21564
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
21281
21565
  result = "ValidationError";
21282
21566
  } else if (status === 429) {
21283
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
21567
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
21284
21568
  } else if (extractedMessage) {
21285
21569
  if (isSuccessfulResponse && rawMessage !== "Unknown error") {
21286
21570
  message = rawMessage;
@@ -21288,7 +21572,9 @@ async function extractErrorDetails(error, options) {
21288
21572
  message = status ? `HTTP ${status}: ${extractedMessage}` : extractedMessage;
21289
21573
  }
21290
21574
  } else if (status) {
21291
- if (rawMessage === "Unknown error" && response) {
21575
+ if (inferredStatus !== undefined) {
21576
+ message = rawMessage;
21577
+ } else if (rawMessage === "Unknown error" && response) {
21292
21578
  const statusText = response.statusText;
21293
21579
  message = statusText ? `HTTP ${status} ${statusText}` : `HTTP ${status} - request failed`;
21294
21580
  } else {
@@ -21297,6 +21583,12 @@ async function extractErrorDetails(error, options) {
21297
21583
  } else {
21298
21584
  message = rawMessage;
21299
21585
  }
21586
+ if (status === undefined) {
21587
+ const connectivity = describeConnectivityError(error);
21588
+ if (connectivity && connectivity.message !== message && !message.includes(connectivity.message)) {
21589
+ message = `${message}: ${connectivity.message}`;
21590
+ }
21591
+ }
21300
21592
  let details = rawMessage;
21301
21593
  if (rawBody) {
21302
21594
  if (parsedBody) {
@@ -21419,6 +21711,7 @@ var CONSOLE_FALLBACK = {
21419
21711
  writeLog: (str) => process.stdout.write(str),
21420
21712
  capabilities: {
21421
21713
  isInteractive: false,
21714
+ canReadInput: false,
21422
21715
  supportsColor: false,
21423
21716
  outputWidth: 80
21424
21717
  }
@@ -26424,12 +26717,6 @@ class NodeContextStorage {
26424
26717
  return this.storage.getStore();
26425
26718
  }
26426
26719
  }
26427
- // ../../common/src/telemetry/global-telemetry-properties.ts
26428
- var telemetryPropsSlot = singleton("TelemetryDefaultProps");
26429
- function getGlobalTelemetryProperties() {
26430
- return telemetryPropsSlot.get();
26431
- }
26432
-
26433
26720
  // ../../common/src/telemetry/telemetry-service.ts
26434
26721
  class TelemetryService {
26435
26722
  telemetryProvider;
@@ -26619,6 +26906,29 @@ function isPlainRecord(value) {
26619
26906
  const prototype = Object.getPrototypeOf(value);
26620
26907
  return prototype === Object.prototype || prototype === null;
26621
26908
  }
26909
+ function extractPagedRows(value) {
26910
+ if (Array.isArray(value) || !isPlainRecord(value))
26911
+ return null;
26912
+ const entries = Object.values(value);
26913
+ if (entries.length === 0)
26914
+ return null;
26915
+ let rows = null;
26916
+ let hasScalarSibling = false;
26917
+ for (const entry of entries) {
26918
+ if (Array.isArray(entry)) {
26919
+ if (rows !== null)
26920
+ return null;
26921
+ rows = entry;
26922
+ } else if (entry !== null && typeof entry === "object") {
26923
+ return null;
26924
+ } else {
26925
+ hasScalarSibling = true;
26926
+ }
26927
+ }
26928
+ if (rows === null || !hasScalarSibling)
26929
+ return null;
26930
+ return rows;
26931
+ }
26622
26932
  function toLowerCamelCaseKey(key) {
26623
26933
  if (!key)
26624
26934
  return key;
@@ -26683,7 +26993,8 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
26683
26993
  break;
26684
26994
  case "plain": {
26685
26995
  if ("Data" in data && data.Data != null) {
26686
- const items = Array.isArray(data.Data) ? data.Data : [data.Data];
26996
+ const pagedRows = extractPagedRows(data.Data);
26997
+ const items = pagedRows ?? (Array.isArray(data.Data) ? data.Data : [data.Data]);
26687
26998
  items.forEach((item) => {
26688
26999
  const values = Object.values(item).map((v) => v ?? "").join("\t");
26689
27000
  logFn(values);
@@ -26695,10 +27006,13 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
26695
27006
  break;
26696
27007
  }
26697
27008
  default: {
26698
- if ("Data" in data && data.Data != null && !(Array.isArray(data.Data) && data.Data.length === 0)) {
27009
+ const hasData = "Data" in data && data.Data != null;
27010
+ const pagedRows = hasData ? extractPagedRows(data.Data) : null;
27011
+ const rows = pagedRows ? pagedRows : Array.isArray(data.Data) ? data.Data : null;
27012
+ if (hasData && !(rows !== null && rows.length === 0)) {
26699
27013
  const logValue = data.Log;
26700
- if (Array.isArray(data.Data)) {
26701
- printResizableTable(data.Data, logFn, logValue);
27014
+ if (rows !== null) {
27015
+ printResizableTable(rows, logFn, logValue);
26702
27016
  } else {
26703
27017
  printVerticalTable(data.Data, logFn, logValue);
26704
27018
  }
@@ -26886,6 +27200,44 @@ function defaultErrorCodeForResult(result) {
26886
27200
  return "unknown_error";
26887
27201
  }
26888
27202
  }
27203
+ function parseHttpStatusFromMessage2(message) {
27204
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
27205
+ if (!match)
27206
+ return;
27207
+ const status = Number(match[1]);
27208
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
27209
+ }
27210
+ function defaultErrorCodeForHttpStatus(status) {
27211
+ if (status === undefined)
27212
+ return;
27213
+ if (status === 400 || status === 409 || status === 422) {
27214
+ return "invalid_argument";
27215
+ }
27216
+ if (status === 401)
27217
+ return "authentication_required";
27218
+ if (status === 403)
27219
+ return "permission_denied";
27220
+ if (status === 404)
27221
+ return "not_found";
27222
+ if (status === 405)
27223
+ return "method_not_allowed";
27224
+ if (status === 408)
27225
+ return "timeout";
27226
+ if (status === 429)
27227
+ return "rate_limited";
27228
+ if (status >= 500 && status < 600)
27229
+ return "server_error";
27230
+ return;
27231
+ }
27232
+ function defaultErrorCodeForFailure(data) {
27233
+ if (data.Result === RESULTS.Failure) {
27234
+ const status = data.Context?.httpStatus ?? parseHttpStatusFromMessage2(data.Message);
27235
+ const errorCode2 = defaultErrorCodeForHttpStatus(status);
27236
+ if (errorCode2)
27237
+ return errorCode2;
27238
+ }
27239
+ return defaultErrorCodeForResult(data.Result);
27240
+ }
26889
27241
  function defaultRetryForErrorCode(errorCode2) {
26890
27242
  switch (errorCode2) {
26891
27243
  case "network_error":
@@ -26915,16 +27267,19 @@ var OutputFormatter;
26915
27267
  OutputFormatter.success = success;
26916
27268
  function error(data) {
26917
27269
  data.Log ??= getLogFilePath() || undefined;
26918
- data.ErrorCode ??= defaultErrorCodeForResult(data.Result);
27270
+ data.ErrorCode ??= defaultErrorCodeForFailure(data);
26919
27271
  data.Retry ??= defaultRetryForErrorCode(data.ErrorCode);
26920
27272
  process.exitCode = EXIT_CODES[data.Result] ?? 1;
26921
- telemetry.trackEvent(CommonTelemetryEvents.Error, {
26922
- result: data.Result,
26923
- errorCode: data.ErrorCode,
26924
- retry: data.Retry,
26925
- message: data.Message
26926
- });
26927
- logOutput(normalizeOutputKeys(data), getOutputFormat());
27273
+ const { SuppressTelemetry, ...envelope } = data;
27274
+ if (!SuppressTelemetry) {
27275
+ telemetry.trackEvent(CommonTelemetryEvents.Error, {
27276
+ result: data.Result,
27277
+ errorCode: data.ErrorCode,
27278
+ retry: data.Retry,
27279
+ message: data.Message
27280
+ });
27281
+ }
27282
+ logOutput(normalizeOutputKeys(envelope), getOutputFormat());
26928
27283
  }
26929
27284
  OutputFormatter.error = error;
26930
27285
  function emitList(code, items, opts) {
@@ -27003,1623 +27358,220 @@ var SENSITIVE_NAME_TOKENS = new Set([
27003
27358
  "certificate",
27004
27359
  "certificates"
27005
27360
  ]);
27006
- var SENSITIVE_KEY_PREFIXES = new Set([
27007
- "api",
27008
- "access",
27009
- "client",
27010
- "private",
27011
- "public",
27012
- "signing",
27013
- "encryption",
27014
- "session",
27015
- "master",
27016
- "shared",
27017
- "root",
27018
- "ssh",
27019
- "rsa",
27020
- "aes",
27021
- "hmac",
27022
- "oauth"
27023
- ]);
27024
- var UUID_PATTERN = /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi;
27025
- var EMAIL_PATTERN = /\b[^\s@]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
27026
- var JWT_PATTERN = /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g;
27027
- var LONG_TOKEN_PATTERN = /\b[A-Za-z0-9_-]{40,}\b/g;
27028
- var USER_HOME_PATTERN = /([/\\])(Users|home)([/\\])([^/\\]+)/gi;
27029
- var URL_PATTERN = /\bhttps?:\/\/[^\s,;]+/gi;
27030
- var URL_TRAILING_PUNCT = /[.,;:!?)\]}>'"]+$/;
27031
- function shortHash(input) {
27032
- let hash = 2166136261;
27033
- for (let i = 0;i < input.length; i++) {
27034
- hash ^= input.charCodeAt(i);
27035
- hash = Math.imul(hash, 16777619);
27036
- }
27037
- return (hash >>> 0).toString(16).padStart(8, "0");
27038
- }
27039
- function redactUrl(raw) {
27040
- try {
27041
- const url = new URL(raw);
27042
- return `${url.protocol}//${url.host}`;
27043
- } catch {
27044
- return `url#${shortHash(raw)}`;
27045
- }
27046
- }
27047
- function redactValueDetectors(value) {
27048
- let out = value;
27049
- out = out.replace(JWT_PATTERN, () => REDACTED);
27050
- out = out.replace(URL_PATTERN, (match) => {
27051
- const trailing = match.match(URL_TRAILING_PUNCT)?.[0] ?? "";
27052
- const core = trailing ? match.slice(0, -trailing.length) : match;
27053
- return `${redactUrl(core)}${trailing}`;
27054
- });
27055
- out = out.replace(USER_HOME_PATTERN, (_match, sep1, folder, sep2) => `${sep1}${folder}${sep2}<user>`);
27056
- out = out.replace(EMAIL_PATTERN, (match) => `email#${shortHash(match)}`);
27057
- out = out.replace(UUID_PATTERN, (match) => `uuid#${shortHash(match)}`);
27058
- out = out.replace(LONG_TOKEN_PATTERN, () => REDACTED);
27059
- if (out.length > MAX_VALUE_LENGTH) {
27060
- out = `${out.slice(0, MAX_VALUE_LENGTH)}…`;
27061
- }
27062
- return out;
27063
- }
27064
- function nameTokens(name) {
27065
- return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").split(/[\s_-]+/).map((t) => t.toLowerCase()).filter(Boolean);
27066
- }
27067
- function isSensitiveName(name) {
27068
- const tokens = nameTokens(name);
27069
- for (let i = 0;i < tokens.length; i++) {
27070
- const token = tokens[i];
27071
- if (SENSITIVE_NAME_TOKENS.has(token)) {
27072
- return true;
27073
- }
27074
- if (token === "key" || token === "keys") {
27075
- const prev = tokens[i - 1];
27076
- if (prev && SENSITIVE_KEY_PREFIXES.has(prev)) {
27077
- return true;
27078
- }
27079
- }
27080
- }
27081
- return false;
27082
- }
27083
- function redactProperty(name, value) {
27084
- if (value === undefined || value === null) {
27085
- return;
27086
- }
27087
- if (isSensitiveName(name)) {
27088
- return REDACTED;
27089
- }
27090
- if (typeof value === "boolean" || typeof value === "number") {
27091
- return value;
27092
- }
27093
- if (typeof value !== "string") {
27094
- return "[OBJECT]";
27095
- }
27096
- return redactValueDetectors(value);
27097
- }
27098
- function redactProperties(properties) {
27099
- const out = {};
27100
- for (const [name, value] of Object.entries(properties)) {
27101
- const redacted = redactProperty(name, value);
27102
- if (redacted !== undefined) {
27103
- out[name] = redacted;
27104
- }
27105
- }
27106
- return out;
27107
- }
27108
-
27109
- // ../../common/src/trackedAction.ts
27110
- var pollSignalSlot = singleton("PollSignal");
27111
- var cliErrorCodeValues = new Set(CLI_ERROR_CODES);
27112
- var retryHintValues = new Set(RETRY_HINTS);
27113
- var processContext = {
27114
- exit: (code) => {
27115
- process.exitCode = code;
27116
- },
27117
- get pollSignal() {
27118
- return pollSignalSlot.get();
27119
- }
27120
- };
27121
- function extractCommandParams(cmd) {
27122
- const params = {};
27123
- const registered = cmd.registeredArguments ?? [];
27124
- const processed = cmd.processedArgs ?? [];
27125
- for (let i = 0;i < registered.length; i++) {
27126
- const value = processed[i];
27127
- if (value === undefined) {
27128
- continue;
27129
- }
27130
- const name = registered[i].name();
27131
- if (name) {
27132
- params[name] = value;
27133
- }
27134
- }
27135
- for (const [key, value] of Object.entries(cmd.opts())) {
27136
- if (value !== undefined) {
27137
- params[key] = value;
27138
- }
27139
- }
27140
- return params;
27141
- }
27142
- function deriveCommandPath(cmd) {
27143
- const parts = [];
27144
- let current = cmd;
27145
- while (current) {
27146
- const name = current.name();
27147
- if (name) {
27148
- parts.unshift(name);
27149
- }
27150
- current = current.parent;
27151
- }
27152
- if (parts.length > 1) {
27153
- parts.shift();
27154
- }
27155
- return ["uip", ...parts.filter((p) => p !== "uip")].join(".");
27156
- }
27157
- function isCliErrorCode(value) {
27158
- return typeof value === "string" && cliErrorCodeValues.has(value);
27159
- }
27160
- function isRetryHint(value) {
27161
- return typeof value === "string" && retryHintValues.has(value);
27162
- }
27163
- function isErrorContext(value) {
27164
- return value !== null && typeof value === "object";
27165
- }
27166
- function commandHelpHint(commandPath) {
27167
- const command = commandPath.replace(/\./g, " ");
27168
- return `An unexpected error occurred. Run '${command} --help' to verify command syntax, or run with --log-level debug for details.`;
27169
- }
27170
- Command2.prototype.trackedAction = function(context, fn, properties) {
27171
- const command = this;
27172
- return this.action(async (...args) => {
27173
- const telemetryName = deriveCommandPath(command);
27174
- const props = typeof properties === "function" ? properties(...args) : properties;
27175
- const startTime = performance.now();
27176
- let errorMessage2;
27177
- const [error] = await catchError2(fn(...args));
27178
- if (error) {
27179
- errorMessage2 = error instanceof Error ? error.message : String(error);
27180
- logger.debug(`[trackedAction] ${telemetryName} failed: ${errorMessage2}`);
27181
- const typed = error;
27182
- const customInstructions = typeof typed.instructions === "string" ? typed.instructions : undefined;
27183
- const customResult = typeof typed.result === "string" && typed.result !== RESULTS.Success && Object.values(RESULTS).includes(typed.result) ? typed.result : undefined;
27184
- const finalResult = customResult ?? RESULTS.Failure;
27185
- const typedErrorCode = typed.errorCode ?? typed.ErrorCode;
27186
- const customErrorCode = isCliErrorCode(typedErrorCode) ? typedErrorCode : undefined;
27187
- const typedRetry = typed.retry ?? typed.Retry;
27188
- const customRetry = isRetryHint(typedRetry) ? typedRetry : undefined;
27189
- const typedContext = typed.context ?? typed.Context;
27190
- const customContext = isErrorContext(typedContext) ? typedContext : undefined;
27191
- OutputFormatter.error({
27192
- Result: finalResult,
27193
- ...customErrorCode ? { ErrorCode: customErrorCode } : {},
27194
- Message: errorMessage2,
27195
- Instructions: customInstructions ?? commandHelpHint(telemetryName),
27196
- ...customRetry ? { Retry: customRetry } : {},
27197
- ...customContext ? { Context: customContext } : {}
27198
- });
27199
- context.exit(EXIT_CODES[finalResult]);
27200
- }
27201
- const durationMs = performance.now() - startTime;
27202
- const success = !error && (process.exitCode === undefined || process.exitCode === 0);
27203
- telemetry.trackEvent(telemetryName, redactProperties({
27204
- ...extractCommandParams(command),
27205
- ...props,
27206
- command: "true",
27207
- duration: String(durationMs),
27208
- success: String(success),
27209
- ...errorMessage2 ? { errorMessage: errorMessage2 } : {}
27210
- }));
27211
- });
27212
- };
27213
- // ../../common/src/console-guard.ts
27214
- var guardInstalledSlot = singleton("ConsoleGuardInstalled");
27215
- var savedOriginalsSlot = singleton("ConsoleGuardOriginals");
27216
- // ../../common/src/constants.ts
27217
- var DEFAULT_AUTH_TIMEOUT_MS2 = 5 * 60 * 1000;
27218
- // ../../common/src/interactivity-context.ts
27219
- var modeSlot = singleton("InteractivityMode");
27220
- // ../../../node_modules/jsonpath-plus/dist/index-node-esm.js
27221
- import vm from "vm";
27222
-
27223
- class Hooks {
27224
- add(name, callback, first) {
27225
- if (typeof arguments[0] != "string") {
27226
- for (let name2 in arguments[0]) {
27227
- this.add(name2, arguments[0][name2], arguments[1]);
27228
- }
27229
- } else {
27230
- (Array.isArray(name) ? name : [name]).forEach(function(name2) {
27231
- this[name2] = this[name2] || [];
27232
- if (callback) {
27233
- this[name2][first ? "unshift" : "push"](callback);
27234
- }
27235
- }, this);
27236
- }
27237
- }
27238
- run(name, env) {
27239
- this[name] = this[name] || [];
27240
- this[name].forEach(function(callback) {
27241
- callback.call(env && env.context ? env.context : env, env);
27242
- });
27243
- }
27244
- }
27245
-
27246
- class Plugins {
27247
- constructor(jsep) {
27248
- this.jsep = jsep;
27249
- this.registered = {};
27250
- }
27251
- register(...plugins) {
27252
- plugins.forEach((plugin) => {
27253
- if (typeof plugin !== "object" || !plugin.name || !plugin.init) {
27254
- throw new Error("Invalid JSEP plugin format");
27255
- }
27256
- if (this.registered[plugin.name]) {
27257
- return;
27258
- }
27259
- plugin.init(this.jsep);
27260
- this.registered[plugin.name] = plugin;
27261
- });
27262
- }
27263
- }
27264
-
27265
- class Jsep {
27266
- static get version() {
27267
- return "1.4.0";
27268
- }
27269
- static toString() {
27270
- return "JavaScript Expression Parser (JSEP) v" + Jsep.version;
27271
- }
27272
- static addUnaryOp(op_name) {
27273
- Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);
27274
- Jsep.unary_ops[op_name] = 1;
27275
- return Jsep;
27276
- }
27277
- static addBinaryOp(op_name, precedence, isRightAssociative) {
27278
- Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);
27279
- Jsep.binary_ops[op_name] = precedence;
27280
- if (isRightAssociative) {
27281
- Jsep.right_associative.add(op_name);
27282
- } else {
27283
- Jsep.right_associative.delete(op_name);
27284
- }
27285
- return Jsep;
27286
- }
27287
- static addIdentifierChar(char) {
27288
- Jsep.additional_identifier_chars.add(char);
27289
- return Jsep;
27290
- }
27291
- static addLiteral(literal_name, literal_value) {
27292
- Jsep.literals[literal_name] = literal_value;
27293
- return Jsep;
27294
- }
27295
- static removeUnaryOp(op_name) {
27296
- delete Jsep.unary_ops[op_name];
27297
- if (op_name.length === Jsep.max_unop_len) {
27298
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
27299
- }
27300
- return Jsep;
27301
- }
27302
- static removeAllUnaryOps() {
27303
- Jsep.unary_ops = {};
27304
- Jsep.max_unop_len = 0;
27305
- return Jsep;
27306
- }
27307
- static removeIdentifierChar(char) {
27308
- Jsep.additional_identifier_chars.delete(char);
27309
- return Jsep;
27310
- }
27311
- static removeBinaryOp(op_name) {
27312
- delete Jsep.binary_ops[op_name];
27313
- if (op_name.length === Jsep.max_binop_len) {
27314
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
27315
- }
27316
- Jsep.right_associative.delete(op_name);
27317
- return Jsep;
27318
- }
27319
- static removeAllBinaryOps() {
27320
- Jsep.binary_ops = {};
27321
- Jsep.max_binop_len = 0;
27322
- return Jsep;
27323
- }
27324
- static removeLiteral(literal_name) {
27325
- delete Jsep.literals[literal_name];
27326
- return Jsep;
27327
- }
27328
- static removeAllLiterals() {
27329
- Jsep.literals = {};
27330
- return Jsep;
27331
- }
27332
- get char() {
27333
- return this.expr.charAt(this.index);
27334
- }
27335
- get code() {
27336
- return this.expr.charCodeAt(this.index);
27337
- }
27338
- constructor(expr) {
27339
- this.expr = expr;
27340
- this.index = 0;
27341
- }
27342
- static parse(expr) {
27343
- return new Jsep(expr).parse();
27344
- }
27345
- static getMaxKeyLen(obj) {
27346
- return Math.max(0, ...Object.keys(obj).map((k) => k.length));
27347
- }
27348
- static isDecimalDigit(ch) {
27349
- return ch >= 48 && ch <= 57;
27350
- }
27351
- static binaryPrecedence(op_val) {
27352
- return Jsep.binary_ops[op_val] || 0;
27353
- }
27354
- static isIdentifierStart(ch) {
27355
- 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));
27356
- }
27357
- static isIdentifierPart(ch) {
27358
- return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);
27359
- }
27360
- throwError(message) {
27361
- const error = new Error(message + " at character " + this.index);
27362
- error.index = this.index;
27363
- error.description = message;
27364
- throw error;
27365
- }
27366
- runHook(name, node) {
27367
- if (Jsep.hooks[name]) {
27368
- const env = {
27369
- context: this,
27370
- node
27371
- };
27372
- Jsep.hooks.run(name, env);
27373
- return env.node;
27374
- }
27375
- return node;
27376
- }
27377
- searchHook(name) {
27378
- if (Jsep.hooks[name]) {
27379
- const env = {
27380
- context: this
27381
- };
27382
- Jsep.hooks[name].find(function(callback) {
27383
- callback.call(env.context, env);
27384
- return env.node;
27385
- });
27386
- return env.node;
27387
- }
27388
- }
27389
- gobbleSpaces() {
27390
- let ch = this.code;
27391
- while (ch === Jsep.SPACE_CODE || ch === Jsep.TAB_CODE || ch === Jsep.LF_CODE || ch === Jsep.CR_CODE) {
27392
- ch = this.expr.charCodeAt(++this.index);
27393
- }
27394
- this.runHook("gobble-spaces");
27395
- }
27396
- parse() {
27397
- this.runHook("before-all");
27398
- const nodes = this.gobbleExpressions();
27399
- const node = nodes.length === 1 ? nodes[0] : {
27400
- type: Jsep.COMPOUND,
27401
- body: nodes
27402
- };
27403
- return this.runHook("after-all", node);
27404
- }
27405
- gobbleExpressions(untilICode) {
27406
- let nodes = [], ch_i, node;
27407
- while (this.index < this.expr.length) {
27408
- ch_i = this.code;
27409
- if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) {
27410
- this.index++;
27411
- } else {
27412
- if (node = this.gobbleExpression()) {
27413
- nodes.push(node);
27414
- } else if (this.index < this.expr.length) {
27415
- if (ch_i === untilICode) {
27416
- break;
27417
- }
27418
- this.throwError('Unexpected "' + this.char + '"');
27419
- }
27420
- }
27421
- }
27422
- return nodes;
27423
- }
27424
- gobbleExpression() {
27425
- const node = this.searchHook("gobble-expression") || this.gobbleBinaryExpression();
27426
- this.gobbleSpaces();
27427
- return this.runHook("after-expression", node);
27428
- }
27429
- gobbleBinaryOp() {
27430
- this.gobbleSpaces();
27431
- let to_check = this.expr.substr(this.index, Jsep.max_binop_len);
27432
- let tc_len = to_check.length;
27433
- while (tc_len > 0) {
27434
- 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)))) {
27435
- this.index += tc_len;
27436
- return to_check;
27437
- }
27438
- to_check = to_check.substr(0, --tc_len);
27439
- }
27440
- return false;
27441
- }
27442
- gobbleBinaryExpression() {
27443
- let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
27444
- left = this.gobbleToken();
27445
- if (!left) {
27446
- return left;
27447
- }
27448
- biop = this.gobbleBinaryOp();
27449
- if (!biop) {
27450
- return left;
27451
- }
27452
- biop_info = {
27453
- value: biop,
27454
- prec: Jsep.binaryPrecedence(biop),
27455
- right_a: Jsep.right_associative.has(biop)
27456
- };
27457
- right = this.gobbleToken();
27458
- if (!right) {
27459
- this.throwError("Expected expression after " + biop);
27460
- }
27461
- stack = [left, biop_info, right];
27462
- while (biop = this.gobbleBinaryOp()) {
27463
- prec = Jsep.binaryPrecedence(biop);
27464
- if (prec === 0) {
27465
- this.index -= biop.length;
27466
- break;
27467
- }
27468
- biop_info = {
27469
- value: biop,
27470
- prec,
27471
- right_a: Jsep.right_associative.has(biop)
27472
- };
27473
- cur_biop = biop;
27474
- const comparePrev = (prev) => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
27475
- while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
27476
- right = stack.pop();
27477
- biop = stack.pop().value;
27478
- left = stack.pop();
27479
- node = {
27480
- type: Jsep.BINARY_EXP,
27481
- operator: biop,
27482
- left,
27483
- right
27484
- };
27485
- stack.push(node);
27486
- }
27487
- node = this.gobbleToken();
27488
- if (!node) {
27489
- this.throwError("Expected expression after " + cur_biop);
27490
- }
27491
- stack.push(biop_info, node);
27492
- }
27493
- i = stack.length - 1;
27494
- node = stack[i];
27495
- while (i > 1) {
27496
- node = {
27497
- type: Jsep.BINARY_EXP,
27498
- operator: stack[i - 1].value,
27499
- left: stack[i - 2],
27500
- right: node
27501
- };
27502
- i -= 2;
27503
- }
27504
- return node;
27505
- }
27506
- gobbleToken() {
27507
- let ch, to_check, tc_len, node;
27508
- this.gobbleSpaces();
27509
- node = this.searchHook("gobble-token");
27510
- if (node) {
27511
- return this.runHook("after-token", node);
27512
- }
27513
- ch = this.code;
27514
- if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) {
27515
- return this.gobbleNumericLiteral();
27516
- }
27517
- if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) {
27518
- node = this.gobbleStringLiteral();
27519
- } else if (ch === Jsep.OBRACK_CODE) {
27520
- node = this.gobbleArray();
27521
- } else {
27522
- to_check = this.expr.substr(this.index, Jsep.max_unop_len);
27523
- tc_len = to_check.length;
27524
- while (tc_len > 0) {
27525
- 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)))) {
27526
- this.index += tc_len;
27527
- const argument = this.gobbleToken();
27528
- if (!argument) {
27529
- this.throwError("missing unaryOp argument");
27530
- }
27531
- return this.runHook("after-token", {
27532
- type: Jsep.UNARY_EXP,
27533
- operator: to_check,
27534
- argument,
27535
- prefix: true
27536
- });
27537
- }
27538
- to_check = to_check.substr(0, --tc_len);
27539
- }
27540
- if (Jsep.isIdentifierStart(ch)) {
27541
- node = this.gobbleIdentifier();
27542
- if (Jsep.literals.hasOwnProperty(node.name)) {
27543
- node = {
27544
- type: Jsep.LITERAL,
27545
- value: Jsep.literals[node.name],
27546
- raw: node.name
27547
- };
27548
- } else if (node.name === Jsep.this_str) {
27549
- node = {
27550
- type: Jsep.THIS_EXP
27551
- };
27552
- }
27553
- } else if (ch === Jsep.OPAREN_CODE) {
27554
- node = this.gobbleGroup();
27555
- }
27556
- }
27557
- if (!node) {
27558
- return this.runHook("after-token", false);
27559
- }
27560
- node = this.gobbleTokenProperty(node);
27561
- return this.runHook("after-token", node);
27562
- }
27563
- gobbleTokenProperty(node) {
27564
- this.gobbleSpaces();
27565
- let ch = this.code;
27566
- while (ch === Jsep.PERIOD_CODE || ch === Jsep.OBRACK_CODE || ch === Jsep.OPAREN_CODE || ch === Jsep.QUMARK_CODE) {
27567
- let optional;
27568
- if (ch === Jsep.QUMARK_CODE) {
27569
- if (this.expr.charCodeAt(this.index + 1) !== Jsep.PERIOD_CODE) {
27570
- break;
27571
- }
27572
- optional = true;
27573
- this.index += 2;
27574
- this.gobbleSpaces();
27575
- ch = this.code;
27576
- }
27577
- this.index++;
27578
- if (ch === Jsep.OBRACK_CODE) {
27579
- node = {
27580
- type: Jsep.MEMBER_EXP,
27581
- computed: true,
27582
- object: node,
27583
- property: this.gobbleExpression()
27584
- };
27585
- if (!node.property) {
27586
- this.throwError('Unexpected "' + this.char + '"');
27587
- }
27588
- this.gobbleSpaces();
27589
- ch = this.code;
27590
- if (ch !== Jsep.CBRACK_CODE) {
27591
- this.throwError("Unclosed [");
27592
- }
27593
- this.index++;
27594
- } else if (ch === Jsep.OPAREN_CODE) {
27595
- node = {
27596
- type: Jsep.CALL_EXP,
27597
- arguments: this.gobbleArguments(Jsep.CPAREN_CODE),
27598
- callee: node
27599
- };
27600
- } else if (ch === Jsep.PERIOD_CODE || optional) {
27601
- if (optional) {
27602
- this.index--;
27603
- }
27604
- this.gobbleSpaces();
27605
- node = {
27606
- type: Jsep.MEMBER_EXP,
27607
- computed: false,
27608
- object: node,
27609
- property: this.gobbleIdentifier()
27610
- };
27611
- }
27612
- if (optional) {
27613
- node.optional = true;
27614
- }
27615
- this.gobbleSpaces();
27616
- ch = this.code;
27617
- }
27618
- return node;
27619
- }
27620
- gobbleNumericLiteral() {
27621
- let number = "", ch, chCode;
27622
- while (Jsep.isDecimalDigit(this.code)) {
27623
- number += this.expr.charAt(this.index++);
27624
- }
27625
- if (this.code === Jsep.PERIOD_CODE) {
27626
- number += this.expr.charAt(this.index++);
27627
- while (Jsep.isDecimalDigit(this.code)) {
27628
- number += this.expr.charAt(this.index++);
27629
- }
27630
- }
27631
- ch = this.char;
27632
- if (ch === "e" || ch === "E") {
27633
- number += this.expr.charAt(this.index++);
27634
- ch = this.char;
27635
- if (ch === "+" || ch === "-") {
27636
- number += this.expr.charAt(this.index++);
27637
- }
27638
- while (Jsep.isDecimalDigit(this.code)) {
27639
- number += this.expr.charAt(this.index++);
27640
- }
27641
- if (!Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {
27642
- this.throwError("Expected exponent (" + number + this.char + ")");
27643
- }
27644
- }
27645
- chCode = this.code;
27646
- if (Jsep.isIdentifierStart(chCode)) {
27647
- this.throwError("Variable names cannot start with a number (" + number + this.char + ")");
27648
- } else if (chCode === Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === Jsep.PERIOD_CODE) {
27649
- this.throwError("Unexpected period");
27650
- }
27651
- return {
27652
- type: Jsep.LITERAL,
27653
- value: parseFloat(number),
27654
- raw: number
27655
- };
27656
- }
27657
- gobbleStringLiteral() {
27658
- let str = "";
27659
- const startIndex = this.index;
27660
- const quote = this.expr.charAt(this.index++);
27661
- let closed = false;
27662
- while (this.index < this.expr.length) {
27663
- let ch = this.expr.charAt(this.index++);
27664
- if (ch === quote) {
27665
- closed = true;
27666
- break;
27667
- } else if (ch === "\\") {
27668
- ch = this.expr.charAt(this.index++);
27669
- switch (ch) {
27670
- case "n":
27671
- str += `
27672
- `;
27673
- break;
27674
- case "r":
27675
- str += "\r";
27676
- break;
27677
- case "t":
27678
- str += "\t";
27679
- break;
27680
- case "b":
27681
- str += "\b";
27682
- break;
27683
- case "f":
27684
- str += "\f";
27685
- break;
27686
- case "v":
27687
- str += "\v";
27688
- break;
27689
- default:
27690
- str += ch;
27691
- }
27692
- } else {
27693
- str += ch;
27694
- }
27695
- }
27696
- if (!closed) {
27697
- this.throwError('Unclosed quote after "' + str + '"');
27698
- }
27699
- return {
27700
- type: Jsep.LITERAL,
27701
- value: str,
27702
- raw: this.expr.substring(startIndex, this.index)
27703
- };
27704
- }
27705
- gobbleIdentifier() {
27706
- let ch = this.code, start = this.index;
27707
- if (Jsep.isIdentifierStart(ch)) {
27708
- this.index++;
27709
- } else {
27710
- this.throwError("Unexpected " + this.char);
27711
- }
27712
- while (this.index < this.expr.length) {
27713
- ch = this.code;
27714
- if (Jsep.isIdentifierPart(ch)) {
27715
- this.index++;
27716
- } else {
27717
- break;
27718
- }
27719
- }
27720
- return {
27721
- type: Jsep.IDENTIFIER,
27722
- name: this.expr.slice(start, this.index)
27723
- };
27724
- }
27725
- gobbleArguments(termination) {
27726
- const args = [];
27727
- let closed = false;
27728
- let separator_count = 0;
27729
- while (this.index < this.expr.length) {
27730
- this.gobbleSpaces();
27731
- let ch_i = this.code;
27732
- if (ch_i === termination) {
27733
- closed = true;
27734
- this.index++;
27735
- if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {
27736
- this.throwError("Unexpected token " + String.fromCharCode(termination));
27737
- }
27738
- break;
27739
- } else if (ch_i === Jsep.COMMA_CODE) {
27740
- this.index++;
27741
- separator_count++;
27742
- if (separator_count !== args.length) {
27743
- if (termination === Jsep.CPAREN_CODE) {
27744
- this.throwError("Unexpected token ,");
27745
- } else if (termination === Jsep.CBRACK_CODE) {
27746
- for (let arg = args.length;arg < separator_count; arg++) {
27747
- args.push(null);
27748
- }
27749
- }
27750
- }
27751
- } else if (args.length !== separator_count && separator_count !== 0) {
27752
- this.throwError("Expected comma");
27753
- } else {
27754
- const node = this.gobbleExpression();
27755
- if (!node || node.type === Jsep.COMPOUND) {
27756
- this.throwError("Expected comma");
27757
- }
27758
- args.push(node);
27759
- }
27760
- }
27761
- if (!closed) {
27762
- this.throwError("Expected " + String.fromCharCode(termination));
27763
- }
27764
- return args;
27765
- }
27766
- gobbleGroup() {
27767
- this.index++;
27768
- let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);
27769
- if (this.code === Jsep.CPAREN_CODE) {
27770
- this.index++;
27771
- if (nodes.length === 1) {
27772
- return nodes[0];
27773
- } else if (!nodes.length) {
27774
- return false;
27775
- } else {
27776
- return {
27777
- type: Jsep.SEQUENCE_EXP,
27778
- expressions: nodes
27779
- };
27780
- }
27781
- } else {
27782
- this.throwError("Unclosed (");
27783
- }
27784
- }
27785
- gobbleArray() {
27786
- this.index++;
27787
- return {
27788
- type: Jsep.ARRAY_EXP,
27789
- elements: this.gobbleArguments(Jsep.CBRACK_CODE)
27790
- };
27791
- }
27792
- }
27793
- var hooks = new Hooks;
27794
- Object.assign(Jsep, {
27795
- hooks,
27796
- plugins: new Plugins(Jsep),
27797
- COMPOUND: "Compound",
27798
- SEQUENCE_EXP: "SequenceExpression",
27799
- IDENTIFIER: "Identifier",
27800
- MEMBER_EXP: "MemberExpression",
27801
- LITERAL: "Literal",
27802
- THIS_EXP: "ThisExpression",
27803
- CALL_EXP: "CallExpression",
27804
- UNARY_EXP: "UnaryExpression",
27805
- BINARY_EXP: "BinaryExpression",
27806
- ARRAY_EXP: "ArrayExpression",
27807
- TAB_CODE: 9,
27808
- LF_CODE: 10,
27809
- CR_CODE: 13,
27810
- SPACE_CODE: 32,
27811
- PERIOD_CODE: 46,
27812
- COMMA_CODE: 44,
27813
- SQUOTE_CODE: 39,
27814
- DQUOTE_CODE: 34,
27815
- OPAREN_CODE: 40,
27816
- CPAREN_CODE: 41,
27817
- OBRACK_CODE: 91,
27818
- CBRACK_CODE: 93,
27819
- QUMARK_CODE: 63,
27820
- SEMCOL_CODE: 59,
27821
- COLON_CODE: 58,
27822
- unary_ops: {
27823
- "-": 1,
27824
- "!": 1,
27825
- "~": 1,
27826
- "+": 1
27827
- },
27828
- binary_ops: {
27829
- "||": 1,
27830
- "??": 1,
27831
- "&&": 2,
27832
- "|": 3,
27833
- "^": 4,
27834
- "&": 5,
27835
- "==": 6,
27836
- "!=": 6,
27837
- "===": 6,
27838
- "!==": 6,
27839
- "<": 7,
27840
- ">": 7,
27841
- "<=": 7,
27842
- ">=": 7,
27843
- "<<": 8,
27844
- ">>": 8,
27845
- ">>>": 8,
27846
- "+": 9,
27847
- "-": 9,
27848
- "*": 10,
27849
- "/": 10,
27850
- "%": 10,
27851
- "**": 11
27852
- },
27853
- right_associative: new Set(["**"]),
27854
- additional_identifier_chars: new Set(["$", "_"]),
27855
- literals: {
27856
- true: true,
27857
- false: false,
27858
- null: null
27859
- },
27860
- this_str: "this"
27861
- });
27862
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
27863
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
27864
- var jsep = (expr) => new Jsep(expr).parse();
27865
- var stdClassProps = Object.getOwnPropertyNames(class Test {
27866
- });
27867
- Object.getOwnPropertyNames(Jsep).filter((prop) => !stdClassProps.includes(prop) && jsep[prop] === undefined).forEach((m) => {
27868
- jsep[m] = Jsep[m];
27869
- });
27870
- jsep.Jsep = Jsep;
27871
- var CONDITIONAL_EXP = "ConditionalExpression";
27872
- var ternary = {
27873
- name: "ternary",
27874
- init(jsep2) {
27875
- jsep2.hooks.add("after-expression", function gobbleTernary(env) {
27876
- if (env.node && this.code === jsep2.QUMARK_CODE) {
27877
- this.index++;
27878
- const test = env.node;
27879
- const consequent = this.gobbleExpression();
27880
- if (!consequent) {
27881
- this.throwError("Expected expression");
27882
- }
27883
- this.gobbleSpaces();
27884
- if (this.code === jsep2.COLON_CODE) {
27885
- this.index++;
27886
- const alternate = this.gobbleExpression();
27887
- if (!alternate) {
27888
- this.throwError("Expected expression");
27889
- }
27890
- env.node = {
27891
- type: CONDITIONAL_EXP,
27892
- test,
27893
- consequent,
27894
- alternate
27895
- };
27896
- if (test.operator && jsep2.binary_ops[test.operator] <= 0.9) {
27897
- let newTest = test;
27898
- while (newTest.right.operator && jsep2.binary_ops[newTest.right.operator] <= 0.9) {
27899
- newTest = newTest.right;
27900
- }
27901
- env.node.test = newTest.right;
27902
- newTest.right = env.node;
27903
- env.node = test;
27904
- }
27905
- } else {
27906
- this.throwError("Expected :");
27907
- }
27908
- }
27909
- });
27910
- }
27911
- };
27912
- jsep.plugins.register(ternary);
27913
- var FSLASH_CODE = 47;
27914
- var BSLASH_CODE = 92;
27915
- var index = {
27916
- name: "regex",
27917
- init(jsep2) {
27918
- jsep2.hooks.add("gobble-token", function gobbleRegexLiteral(env) {
27919
- if (this.code === FSLASH_CODE) {
27920
- const patternIndex = ++this.index;
27921
- let inCharSet = false;
27922
- while (this.index < this.expr.length) {
27923
- if (this.code === FSLASH_CODE && !inCharSet) {
27924
- const pattern = this.expr.slice(patternIndex, this.index);
27925
- let flags = "";
27926
- while (++this.index < this.expr.length) {
27927
- const code = this.code;
27928
- if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57) {
27929
- flags += this.char;
27930
- } else {
27931
- break;
27932
- }
27933
- }
27934
- let value;
27935
- try {
27936
- value = new RegExp(pattern, flags);
27937
- } catch (e) {
27938
- this.throwError(e.message);
27939
- }
27940
- env.node = {
27941
- type: jsep2.LITERAL,
27942
- value,
27943
- raw: this.expr.slice(patternIndex - 1, this.index)
27944
- };
27945
- env.node = this.gobbleTokenProperty(env.node);
27946
- return env.node;
27947
- }
27948
- if (this.code === jsep2.OBRACK_CODE) {
27949
- inCharSet = true;
27950
- } else if (inCharSet && this.code === jsep2.CBRACK_CODE) {
27951
- inCharSet = false;
27952
- }
27953
- this.index += this.code === BSLASH_CODE ? 2 : 1;
27954
- }
27955
- this.throwError("Unclosed Regex");
27956
- }
27957
- });
27958
- }
27959
- };
27960
- var PLUS_CODE = 43;
27961
- var MINUS_CODE = 45;
27962
- var plugin = {
27963
- name: "assignment",
27964
- assignmentOperators: new Set(["=", "*=", "**=", "/=", "%=", "+=", "-=", "<<=", ">>=", ">>>=", "&=", "^=", "|=", "||=", "&&=", "??="]),
27965
- updateOperators: [PLUS_CODE, MINUS_CODE],
27966
- assignmentPrecedence: 0.9,
27967
- init(jsep2) {
27968
- const updateNodeTypes = [jsep2.IDENTIFIER, jsep2.MEMBER_EXP];
27969
- plugin.assignmentOperators.forEach((op) => jsep2.addBinaryOp(op, plugin.assignmentPrecedence, true));
27970
- jsep2.hooks.add("gobble-token", function gobbleUpdatePrefix(env) {
27971
- const code = this.code;
27972
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
27973
- this.index += 2;
27974
- env.node = {
27975
- type: "UpdateExpression",
27976
- operator: code === PLUS_CODE ? "++" : "--",
27977
- argument: this.gobbleTokenProperty(this.gobbleIdentifier()),
27978
- prefix: true
27979
- };
27980
- if (!env.node.argument || !updateNodeTypes.includes(env.node.argument.type)) {
27981
- this.throwError(`Unexpected ${env.node.operator}`);
27982
- }
27983
- }
27984
- });
27985
- jsep2.hooks.add("after-token", function gobbleUpdatePostfix(env) {
27986
- if (env.node) {
27987
- const code = this.code;
27988
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
27989
- if (!updateNodeTypes.includes(env.node.type)) {
27990
- this.throwError(`Unexpected ${env.node.operator}`);
27991
- }
27992
- this.index += 2;
27993
- env.node = {
27994
- type: "UpdateExpression",
27995
- operator: code === PLUS_CODE ? "++" : "--",
27996
- argument: env.node,
27997
- prefix: false
27998
- };
27999
- }
28000
- }
28001
- });
28002
- jsep2.hooks.add("after-expression", function gobbleAssignment(env) {
28003
- if (env.node) {
28004
- updateBinariesToAssignments(env.node);
28005
- }
28006
- });
28007
- function updateBinariesToAssignments(node) {
28008
- if (plugin.assignmentOperators.has(node.operator)) {
28009
- node.type = "AssignmentExpression";
28010
- updateBinariesToAssignments(node.left);
28011
- updateBinariesToAssignments(node.right);
28012
- } else if (!node.operator) {
28013
- Object.values(node).forEach((val) => {
28014
- if (val && typeof val === "object") {
28015
- updateBinariesToAssignments(val);
28016
- }
28017
- });
28018
- }
28019
- }
28020
- }
28021
- };
28022
- jsep.plugins.register(index, plugin);
28023
- jsep.addUnaryOp("typeof");
28024
- jsep.addUnaryOp("void");
28025
- jsep.addLiteral("null", null);
28026
- jsep.addLiteral("undefined", undefined);
28027
- var BLOCKED_PROTO_PROPERTIES = new Set(["constructor", "__proto__", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"]);
28028
- var SafeEval = {
28029
- evalAst(ast, subs) {
28030
- switch (ast.type) {
28031
- case "BinaryExpression":
28032
- case "LogicalExpression":
28033
- return SafeEval.evalBinaryExpression(ast, subs);
28034
- case "Compound":
28035
- return SafeEval.evalCompound(ast, subs);
28036
- case "ConditionalExpression":
28037
- return SafeEval.evalConditionalExpression(ast, subs);
28038
- case "Identifier":
28039
- return SafeEval.evalIdentifier(ast, subs);
28040
- case "Literal":
28041
- return SafeEval.evalLiteral(ast, subs);
28042
- case "MemberExpression":
28043
- return SafeEval.evalMemberExpression(ast, subs);
28044
- case "UnaryExpression":
28045
- return SafeEval.evalUnaryExpression(ast, subs);
28046
- case "ArrayExpression":
28047
- return SafeEval.evalArrayExpression(ast, subs);
28048
- case "CallExpression":
28049
- return SafeEval.evalCallExpression(ast, subs);
28050
- case "AssignmentExpression":
28051
- return SafeEval.evalAssignmentExpression(ast, subs);
28052
- default:
28053
- throw SyntaxError("Unexpected expression", ast);
28054
- }
28055
- },
28056
- evalBinaryExpression(ast, subs) {
28057
- const result = {
28058
- "||": (a, b) => a || b(),
28059
- "&&": (a, b) => a && b(),
28060
- "|": (a, b) => a | b(),
28061
- "^": (a, b) => a ^ b(),
28062
- "&": (a, b) => a & b(),
28063
- "==": (a, b) => a == b(),
28064
- "!=": (a, b) => a != b(),
28065
- "===": (a, b) => a === b(),
28066
- "!==": (a, b) => a !== b(),
28067
- "<": (a, b) => a < b(),
28068
- ">": (a, b) => a > b(),
28069
- "<=": (a, b) => a <= b(),
28070
- ">=": (a, b) => a >= b(),
28071
- "<<": (a, b) => a << b(),
28072
- ">>": (a, b) => a >> b(),
28073
- ">>>": (a, b) => a >>> b(),
28074
- "+": (a, b) => a + b(),
28075
- "-": (a, b) => a - b(),
28076
- "*": (a, b) => a * b(),
28077
- "/": (a, b) => a / b(),
28078
- "%": (a, b) => a % b()
28079
- }[ast.operator](SafeEval.evalAst(ast.left, subs), () => SafeEval.evalAst(ast.right, subs));
28080
- return result;
28081
- },
28082
- evalCompound(ast, subs) {
28083
- let last;
28084
- for (let i = 0;i < ast.body.length; i++) {
28085
- if (ast.body[i].type === "Identifier" && ["var", "let", "const"].includes(ast.body[i].name) && ast.body[i + 1] && ast.body[i + 1].type === "AssignmentExpression") {
28086
- i += 1;
28087
- }
28088
- const expr = ast.body[i];
28089
- last = SafeEval.evalAst(expr, subs);
28090
- }
28091
- return last;
28092
- },
28093
- evalConditionalExpression(ast, subs) {
28094
- if (SafeEval.evalAst(ast.test, subs)) {
28095
- return SafeEval.evalAst(ast.consequent, subs);
28096
- }
28097
- return SafeEval.evalAst(ast.alternate, subs);
28098
- },
28099
- evalIdentifier(ast, subs) {
28100
- if (Object.hasOwn(subs, ast.name)) {
28101
- return subs[ast.name];
28102
- }
28103
- throw ReferenceError(`${ast.name} is not defined`);
28104
- },
28105
- evalLiteral(ast) {
28106
- return ast.value;
28107
- },
28108
- evalMemberExpression(ast, subs) {
28109
- const prop = String(ast.computed ? SafeEval.evalAst(ast.property) : ast.property.name);
28110
- const obj = SafeEval.evalAst(ast.object, subs);
28111
- if (obj === undefined || obj === null) {
28112
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
28113
- }
28114
- if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) {
28115
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
28116
- }
28117
- const result = obj[prop];
28118
- if (typeof result === "function") {
28119
- return result.bind(obj);
28120
- }
28121
- return result;
28122
- },
28123
- evalUnaryExpression(ast, subs) {
28124
- const result = {
28125
- "-": (a) => -SafeEval.evalAst(a, subs),
28126
- "!": (a) => !SafeEval.evalAst(a, subs),
28127
- "~": (a) => ~SafeEval.evalAst(a, subs),
28128
- "+": (a) => +SafeEval.evalAst(a, subs),
28129
- typeof: (a) => typeof SafeEval.evalAst(a, subs),
28130
- void: (a) => void SafeEval.evalAst(a, subs)
28131
- }[ast.operator](ast.argument);
28132
- return result;
28133
- },
28134
- evalArrayExpression(ast, subs) {
28135
- return ast.elements.map((el) => SafeEval.evalAst(el, subs));
28136
- },
28137
- evalCallExpression(ast, subs) {
28138
- const args = ast.arguments.map((arg) => SafeEval.evalAst(arg, subs));
28139
- const func = SafeEval.evalAst(ast.callee, subs);
28140
- if (func === Function) {
28141
- throw new Error("Function constructor is disabled");
28142
- }
28143
- return func(...args);
28144
- },
28145
- evalAssignmentExpression(ast, subs) {
28146
- if (ast.left.type !== "Identifier") {
28147
- throw SyntaxError("Invalid left-hand side in assignment");
28148
- }
28149
- const id = ast.left.name;
28150
- const value = SafeEval.evalAst(ast.right, subs);
28151
- subs[id] = value;
28152
- return subs[id];
28153
- }
28154
- };
28155
-
28156
- class SafeScript {
28157
- constructor(expr) {
28158
- this.code = expr;
28159
- this.ast = jsep(this.code);
28160
- }
28161
- runInNewContext(context) {
28162
- const keyMap = Object.assign(Object.create(null), context);
28163
- return SafeEval.evalAst(this.ast, keyMap);
27361
+ var SENSITIVE_KEY_PREFIXES = new Set([
27362
+ "api",
27363
+ "access",
27364
+ "client",
27365
+ "private",
27366
+ "public",
27367
+ "signing",
27368
+ "encryption",
27369
+ "session",
27370
+ "master",
27371
+ "shared",
27372
+ "root",
27373
+ "ssh",
27374
+ "rsa",
27375
+ "aes",
27376
+ "hmac",
27377
+ "oauth"
27378
+ ]);
27379
+ var UUID_PATTERN = /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi;
27380
+ var EMAIL_PATTERN = /\b[^\s@]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
27381
+ var JWT_PATTERN = /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g;
27382
+ var LONG_TOKEN_PATTERN = /\b[A-Za-z0-9_-]{40,}\b/g;
27383
+ var USER_HOME_PATTERN = /([/\\])(Users|home)([/\\])([^/\\]+)/gi;
27384
+ var URL_PATTERN = /\bhttps?:\/\/[^\s,;]+/gi;
27385
+ var URL_TRAILING_PUNCT = /[.,;:!?)\]}>'"]+$/;
27386
+ function shortHash(input) {
27387
+ let hash = 2166136261;
27388
+ for (let i = 0;i < input.length; i++) {
27389
+ hash ^= input.charCodeAt(i);
27390
+ hash = Math.imul(hash, 16777619);
28164
27391
  }
27392
+ return (hash >>> 0).toString(16).padStart(8, "0");
28165
27393
  }
28166
- function push(arr, item) {
28167
- arr = arr.slice();
28168
- arr.push(item);
28169
- return arr;
28170
- }
28171
- function unshift(item, arr) {
28172
- arr = arr.slice();
28173
- arr.unshift(item);
28174
- return arr;
27394
+ function redactUrl(raw) {
27395
+ try {
27396
+ const url = new URL(raw);
27397
+ return `${url.protocol}//${url.host}`;
27398
+ } catch {
27399
+ return `url#${shortHash(raw)}`;
27400
+ }
28175
27401
  }
28176
-
28177
- class NewError extends Error {
28178
- constructor(value) {
28179
- super('JSONPath should not be called with "new" (it prevents return ' + "of (unwrapped) scalar values)");
28180
- this.avoidNew = true;
28181
- this.value = value;
28182
- this.name = "NewError";
27402
+ function redactValueDetectors(value) {
27403
+ let out = value;
27404
+ out = out.replace(JWT_PATTERN, () => REDACTED);
27405
+ out = out.replace(URL_PATTERN, (match) => {
27406
+ const trailing = match.match(URL_TRAILING_PUNCT)?.[0] ?? "";
27407
+ const core = trailing ? match.slice(0, -trailing.length) : match;
27408
+ return `${redactUrl(core)}${trailing}`;
27409
+ });
27410
+ out = out.replace(USER_HOME_PATTERN, (_match, sep1, folder, sep2) => `${sep1}${folder}${sep2}<user>`);
27411
+ out = out.replace(EMAIL_PATTERN, (match) => `email#${shortHash(match)}`);
27412
+ out = out.replace(UUID_PATTERN, (match) => `uuid#${shortHash(match)}`);
27413
+ out = out.replace(LONG_TOKEN_PATTERN, () => REDACTED);
27414
+ if (out.length > MAX_VALUE_LENGTH) {
27415
+ out = `${out.slice(0, MAX_VALUE_LENGTH)}…`;
28183
27416
  }
27417
+ return out;
28184
27418
  }
28185
- function JSONPath(opts, expr, obj, callback, otherTypeCallback) {
28186
- if (!(this instanceof JSONPath)) {
28187
- try {
28188
- return new JSONPath(opts, expr, obj, callback, otherTypeCallback);
28189
- } catch (e) {
28190
- if (!e.avoidNew) {
28191
- throw e;
28192
- }
28193
- return e.value;
28194
- }
28195
- }
28196
- if (typeof opts === "string") {
28197
- otherTypeCallback = callback;
28198
- callback = obj;
28199
- obj = expr;
28200
- expr = opts;
28201
- opts = null;
28202
- }
28203
- const optObj = opts && typeof opts === "object";
28204
- opts = opts || {};
28205
- this.json = opts.json || obj;
28206
- this.path = opts.path || expr;
28207
- this.resultType = opts.resultType || "value";
28208
- this.flatten = opts.flatten || false;
28209
- this.wrap = Object.hasOwn(opts, "wrap") ? opts.wrap : true;
28210
- this.sandbox = opts.sandbox || {};
28211
- this.eval = opts.eval === undefined ? "safe" : opts.eval;
28212
- this.ignoreEvalErrors = typeof opts.ignoreEvalErrors === "undefined" ? false : opts.ignoreEvalErrors;
28213
- this.parent = opts.parent || null;
28214
- this.parentProperty = opts.parentProperty || null;
28215
- this.callback = opts.callback || callback || null;
28216
- this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function() {
28217
- throw new TypeError("You must supply an otherTypeCallback callback option " + "with the @other() operator.");
28218
- };
28219
- if (opts.autostart !== false) {
28220
- const args = {
28221
- path: optObj ? opts.path : expr
28222
- };
28223
- if (!optObj) {
28224
- args.json = obj;
28225
- } else if ("json" in opts) {
28226
- args.json = opts.json;
27419
+ function nameTokens(name) {
27420
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").split(/[\s_-]+/).map((t) => t.toLowerCase()).filter(Boolean);
27421
+ }
27422
+ function isSensitiveName(name) {
27423
+ const tokens = nameTokens(name);
27424
+ for (let i = 0;i < tokens.length; i++) {
27425
+ const token = tokens[i];
27426
+ if (SENSITIVE_NAME_TOKENS.has(token)) {
27427
+ return true;
28227
27428
  }
28228
- const ret = this.evaluate(args);
28229
- if (!ret || typeof ret !== "object") {
28230
- throw new NewError(ret);
27429
+ if (token === "key" || token === "keys") {
27430
+ const prev = tokens[i - 1];
27431
+ if (prev && SENSITIVE_KEY_PREFIXES.has(prev)) {
27432
+ return true;
27433
+ }
28231
27434
  }
28232
- return ret;
28233
27435
  }
27436
+ return false;
28234
27437
  }
28235
- JSONPath.prototype.evaluate = function(expr, json, callback, otherTypeCallback) {
28236
- let currParent = this.parent, currParentProperty = this.parentProperty;
28237
- let {
28238
- flatten,
28239
- wrap
28240
- } = this;
28241
- this.currResultType = this.resultType;
28242
- this.currEval = this.eval;
28243
- this.currSandbox = this.sandbox;
28244
- callback = callback || this.callback;
28245
- this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback;
28246
- json = json || this.json;
28247
- expr = expr || this.path;
28248
- if (expr && typeof expr === "object" && !Array.isArray(expr)) {
28249
- if (!expr.path && expr.path !== "") {
28250
- throw new TypeError('You must supply a "path" property when providing an object ' + "argument to JSONPath.evaluate().");
28251
- }
28252
- if (!Object.hasOwn(expr, "json")) {
28253
- throw new TypeError('You must supply a "json" property when providing an object ' + "argument to JSONPath.evaluate().");
28254
- }
28255
- ({
28256
- json
28257
- } = expr);
28258
- flatten = Object.hasOwn(expr, "flatten") ? expr.flatten : flatten;
28259
- this.currResultType = Object.hasOwn(expr, "resultType") ? expr.resultType : this.currResultType;
28260
- this.currSandbox = Object.hasOwn(expr, "sandbox") ? expr.sandbox : this.currSandbox;
28261
- wrap = Object.hasOwn(expr, "wrap") ? expr.wrap : wrap;
28262
- this.currEval = Object.hasOwn(expr, "eval") ? expr.eval : this.currEval;
28263
- callback = Object.hasOwn(expr, "callback") ? expr.callback : callback;
28264
- this.currOtherTypeCallback = Object.hasOwn(expr, "otherTypeCallback") ? expr.otherTypeCallback : this.currOtherTypeCallback;
28265
- currParent = Object.hasOwn(expr, "parent") ? expr.parent : currParent;
28266
- currParentProperty = Object.hasOwn(expr, "parentProperty") ? expr.parentProperty : currParentProperty;
28267
- expr = expr.path;
28268
- }
28269
- currParent = currParent || null;
28270
- currParentProperty = currParentProperty || null;
28271
- if (Array.isArray(expr)) {
28272
- expr = JSONPath.toPathString(expr);
28273
- }
28274
- if (!expr && expr !== "" || !json) {
27438
+ function redactProperty(name, value) {
27439
+ if (value === undefined || value === null) {
28275
27440
  return;
28276
27441
  }
28277
- const exprList = JSONPath.toPathArray(expr);
28278
- if (exprList[0] === "$" && exprList.length > 1) {
28279
- exprList.shift();
27442
+ if (isSensitiveName(name)) {
27443
+ return REDACTED;
28280
27444
  }
28281
- this._hasParentSelector = null;
28282
- const result = this._trace(exprList, json, ["$"], currParent, currParentProperty, callback).filter(function(ea) {
28283
- return ea && !ea.isParentSelector;
28284
- });
28285
- if (!result.length) {
28286
- return wrap ? [] : undefined;
27445
+ if (typeof value === "boolean" || typeof value === "number") {
27446
+ return value;
28287
27447
  }
28288
- if (!wrap && result.length === 1 && !result[0].hasArrExpr) {
28289
- return this._getPreferredOutput(result[0]);
27448
+ if (typeof value !== "string") {
27449
+ return "[OBJECT]";
28290
27450
  }
28291
- return result.reduce((rslt, ea) => {
28292
- const valOrPath = this._getPreferredOutput(ea);
28293
- if (flatten && Array.isArray(valOrPath)) {
28294
- rslt = rslt.concat(valOrPath);
28295
- } else {
28296
- rslt.push(valOrPath);
27451
+ return redactValueDetectors(value);
27452
+ }
27453
+ function redactProperties(properties) {
27454
+ const out = {};
27455
+ for (const [name, value] of Object.entries(properties)) {
27456
+ const redacted = redactProperty(name, value);
27457
+ if (redacted !== undefined) {
27458
+ out[name] = redacted;
28297
27459
  }
28298
- return rslt;
28299
- }, []);
28300
- };
28301
- JSONPath.prototype._getPreferredOutput = function(ea) {
28302
- const resultType = this.currResultType;
28303
- switch (resultType) {
28304
- case "all": {
28305
- const path3 = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path);
28306
- ea.pointer = JSONPath.toPointer(path3);
28307
- ea.path = typeof ea.path === "string" ? ea.path : JSONPath.toPathString(ea.path);
28308
- return ea;
28309
- }
28310
- case "value":
28311
- case "parent":
28312
- case "parentProperty":
28313
- return ea[resultType];
28314
- case "path":
28315
- return JSONPath.toPathString(ea[resultType]);
28316
- case "pointer":
28317
- return JSONPath.toPointer(ea.path);
28318
- default:
28319
- throw new TypeError("Unknown result type");
28320
27460
  }
28321
- };
28322
- JSONPath.prototype._handleCallback = function(fullRetObj, callback, type) {
28323
- if (callback) {
28324
- const preferredOutput = this._getPreferredOutput(fullRetObj);
28325
- fullRetObj.path = typeof fullRetObj.path === "string" ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path);
28326
- callback(preferredOutput, type, fullRetObj);
27461
+ return out;
27462
+ }
27463
+
27464
+ // ../../common/src/trackedAction.ts
27465
+ var pollSignalSlot = singleton("PollSignal");
27466
+ var cliErrorCodeValues = new Set(CLI_ERROR_CODES);
27467
+ var retryHintValues = new Set(RETRY_HINTS);
27468
+ var processContext = {
27469
+ exit: (code) => {
27470
+ process.exitCode = code;
27471
+ },
27472
+ get pollSignal() {
27473
+ return pollSignalSlot.get();
28327
27474
  }
28328
27475
  };
28329
- JSONPath.prototype._trace = function(expr, val, path3, parent, parentPropName, callback, hasArrExpr, literalPriority) {
28330
- let retObj;
28331
- if (!expr.length) {
28332
- retObj = {
28333
- path: path3,
28334
- value: val,
28335
- parent,
28336
- parentProperty: parentPropName,
28337
- hasArrExpr
28338
- };
28339
- this._handleCallback(retObj, callback, "value");
28340
- return retObj;
28341
- }
28342
- const loc = expr[0], x = expr.slice(1);
28343
- const ret = [];
28344
- function addRet(elems) {
28345
- if (Array.isArray(elems)) {
28346
- elems.forEach((t) => {
28347
- ret.push(t);
28348
- });
28349
- } else {
28350
- ret.push(elems);
28351
- }
28352
- }
28353
- if ((typeof loc !== "string" || literalPriority) && val && Object.hasOwn(val, loc)) {
28354
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr));
28355
- } else if (loc === "*") {
28356
- this._walk(val, (m) => {
28357
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true, true));
28358
- });
28359
- } else if (loc === "..") {
28360
- addRet(this._trace(x, val, path3, parent, parentPropName, callback, hasArrExpr));
28361
- this._walk(val, (m) => {
28362
- if (typeof val[m] === "object") {
28363
- addRet(this._trace(expr.slice(), val[m], push(path3, m), val, m, callback, true));
28364
- }
28365
- });
28366
- } else if (loc === "^") {
28367
- this._hasParentSelector = true;
28368
- return {
28369
- path: path3.slice(0, -1),
28370
- expr: x,
28371
- isParentSelector: true
28372
- };
28373
- } else if (loc === "~") {
28374
- retObj = {
28375
- path: push(path3, loc),
28376
- value: parentPropName,
28377
- parent,
28378
- parentProperty: null
28379
- };
28380
- this._handleCallback(retObj, callback, "property");
28381
- return retObj;
28382
- } else if (loc === "$") {
28383
- addRet(this._trace(x, val, path3, null, null, callback, hasArrExpr));
28384
- } else if (/^(-?\d*):(-?\d*):?(\d*)$/u.test(loc)) {
28385
- addRet(this._slice(loc, x, val, path3, parent, parentPropName, callback));
28386
- } else if (loc.indexOf("?(") === 0) {
28387
- if (this.currEval === false) {
28388
- throw new Error("Eval [?(expr)] prevented in JSONPath expression.");
28389
- }
28390
- const safeLoc = loc.replace(/^\?\((.*?)\)$/u, "$1");
28391
- const nested = /@.?([^?]*)[['](\??\(.*?\))(?!.\)\])[\]']/gu.exec(safeLoc);
28392
- if (nested) {
28393
- this._walk(val, (m) => {
28394
- const npath = [nested[2]];
28395
- const nvalue = nested[1] ? val[m][nested[1]] : val[m];
28396
- const filterResults = this._trace(npath, nvalue, path3, parent, parentPropName, callback, true);
28397
- if (filterResults.length > 0) {
28398
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
28399
- }
28400
- });
28401
- } else {
28402
- this._walk(val, (m) => {
28403
- if (this._eval(safeLoc, val[m], m, path3, parent, parentPropName)) {
28404
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
28405
- }
28406
- });
28407
- }
28408
- } else if (loc[0] === "(") {
28409
- if (this.currEval === false) {
28410
- throw new Error("Eval [(expr)] prevented in JSONPath expression.");
27476
+ function extractCommandParams(cmd) {
27477
+ const params = {};
27478
+ const registered = cmd.registeredArguments ?? [];
27479
+ const processed = cmd.processedArgs ?? [];
27480
+ for (let i = 0;i < registered.length; i++) {
27481
+ const value = processed[i];
27482
+ if (value === undefined) {
27483
+ continue;
28411
27484
  }
28412
- addRet(this._trace(unshift(this._eval(loc, val, path3.at(-1), path3.slice(0, -1), parent, parentPropName), x), val, path3, parent, parentPropName, callback, hasArrExpr));
28413
- } else if (loc[0] === "@") {
28414
- let addType = false;
28415
- const valueType = loc.slice(1, -2);
28416
- switch (valueType) {
28417
- case "scalar":
28418
- if (!val || !["object", "function"].includes(typeof val)) {
28419
- addType = true;
28420
- }
28421
- break;
28422
- case "boolean":
28423
- case "string":
28424
- case "undefined":
28425
- case "function":
28426
- if (typeof val === valueType) {
28427
- addType = true;
28428
- }
28429
- break;
28430
- case "integer":
28431
- if (Number.isFinite(val) && !(val % 1)) {
28432
- addType = true;
28433
- }
28434
- break;
28435
- case "number":
28436
- if (Number.isFinite(val)) {
28437
- addType = true;
28438
- }
28439
- break;
28440
- case "nonFinite":
28441
- if (typeof val === "number" && !Number.isFinite(val)) {
28442
- addType = true;
28443
- }
28444
- break;
28445
- case "object":
28446
- if (val && typeof val === valueType) {
28447
- addType = true;
28448
- }
28449
- break;
28450
- case "array":
28451
- if (Array.isArray(val)) {
28452
- addType = true;
28453
- }
28454
- break;
28455
- case "other":
28456
- addType = this.currOtherTypeCallback(val, path3, parent, parentPropName);
28457
- break;
28458
- case "null":
28459
- if (val === null) {
28460
- addType = true;
28461
- }
28462
- break;
28463
- default:
28464
- throw new TypeError("Unknown value type " + valueType);
28465
- }
28466
- if (addType) {
28467
- retObj = {
28468
- path: path3,
28469
- value: val,
28470
- parent,
28471
- parentProperty: parentPropName
28472
- };
28473
- this._handleCallback(retObj, callback, "value");
28474
- return retObj;
28475
- }
28476
- } else if (loc[0] === "`" && val && Object.hasOwn(val, loc.slice(1))) {
28477
- const locProp = loc.slice(1);
28478
- addRet(this._trace(x, val[locProp], push(path3, locProp), val, locProp, callback, hasArrExpr, true));
28479
- } else if (loc.includes(",")) {
28480
- const parts = loc.split(",");
28481
- for (const part of parts) {
28482
- addRet(this._trace(unshift(part, x), val, path3, parent, parentPropName, callback, true));
28483
- }
28484
- } else if (!literalPriority && val && Object.hasOwn(val, loc)) {
28485
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr, true));
28486
- }
28487
- if (this._hasParentSelector) {
28488
- for (let t = 0;t < ret.length; t++) {
28489
- const rett = ret[t];
28490
- if (rett && rett.isParentSelector) {
28491
- const tmp = this._trace(rett.expr, val, rett.path, parent, parentPropName, callback, hasArrExpr);
28492
- if (Array.isArray(tmp)) {
28493
- ret[t] = tmp[0];
28494
- const tl = tmp.length;
28495
- for (let tt = 1;tt < tl; tt++) {
28496
- t++;
28497
- ret.splice(t, 0, tmp[tt]);
28498
- }
28499
- } else {
28500
- ret[t] = tmp;
28501
- }
28502
- }
27485
+ const name = registered[i].name();
27486
+ if (name) {
27487
+ params[name] = value;
28503
27488
  }
28504
27489
  }
28505
- return ret;
28506
- };
28507
- JSONPath.prototype._walk = function(val, f) {
28508
- if (Array.isArray(val)) {
28509
- const n = val.length;
28510
- for (let i = 0;i < n; i++) {
28511
- f(i);
28512
- }
28513
- } else if (val && typeof val === "object") {
28514
- Object.keys(val).forEach((m) => {
28515
- f(m);
28516
- });
28517
- }
28518
- };
28519
- JSONPath.prototype._slice = function(loc, expr, val, path3, parent, parentPropName, callback) {
28520
- if (!Array.isArray(val)) {
28521
- return;
28522
- }
28523
- const len = val.length, parts = loc.split(":"), step = parts[2] && Number.parseInt(parts[2]) || 1;
28524
- let start = parts[0] && Number.parseInt(parts[0]) || 0, end = parts[1] && Number.parseInt(parts[1]) || len;
28525
- start = start < 0 ? Math.max(0, start + len) : Math.min(len, start);
28526
- end = end < 0 ? Math.max(0, end + len) : Math.min(len, end);
28527
- const ret = [];
28528
- for (let i = start;i < end; i += step) {
28529
- const tmp = this._trace(unshift(i, expr), val, path3, parent, parentPropName, callback, true);
28530
- tmp.forEach((t) => {
28531
- ret.push(t);
28532
- });
28533
- }
28534
- return ret;
28535
- };
28536
- JSONPath.prototype._eval = function(code, _v, _vname, path3, parent, parentPropName) {
28537
- this.currSandbox._$_parentProperty = parentPropName;
28538
- this.currSandbox._$_parent = parent;
28539
- this.currSandbox._$_property = _vname;
28540
- this.currSandbox._$_root = this.json;
28541
- this.currSandbox._$_v = _v;
28542
- const containsPath = code.includes("@path");
28543
- if (containsPath) {
28544
- this.currSandbox._$_path = JSONPath.toPathString(path3.concat([_vname]));
28545
- }
28546
- const scriptCacheKey = this.currEval + "Script:" + code;
28547
- if (!JSONPath.cache[scriptCacheKey]) {
28548
- let script = code.replaceAll("@parentProperty", "_$_parentProperty").replaceAll("@parent", "_$_parent").replaceAll("@property", "_$_property").replaceAll("@root", "_$_root").replaceAll(/@([.\s)[])/gu, "_$_v$1");
28549
- if (containsPath) {
28550
- script = script.replaceAll("@path", "_$_path");
28551
- }
28552
- if (this.currEval === "safe" || this.currEval === true || this.currEval === undefined) {
28553
- JSONPath.cache[scriptCacheKey] = new this.safeVm.Script(script);
28554
- } else if (this.currEval === "native") {
28555
- JSONPath.cache[scriptCacheKey] = new this.vm.Script(script);
28556
- } else if (typeof this.currEval === "function" && this.currEval.prototype && Object.hasOwn(this.currEval.prototype, "runInNewContext")) {
28557
- const CurrEval = this.currEval;
28558
- JSONPath.cache[scriptCacheKey] = new CurrEval(script);
28559
- } else if (typeof this.currEval === "function") {
28560
- JSONPath.cache[scriptCacheKey] = {
28561
- runInNewContext: (context) => this.currEval(script, context)
28562
- };
28563
- } else {
28564
- throw new TypeError(`Unknown "eval" property "${this.currEval}"`);
27490
+ for (const [key, value] of Object.entries(cmd.opts())) {
27491
+ if (value !== undefined) {
27492
+ params[key] = value;
28565
27493
  }
28566
27494
  }
28567
- try {
28568
- return JSONPath.cache[scriptCacheKey].runInNewContext(this.currSandbox);
28569
- } catch (e) {
28570
- if (this.ignoreEvalErrors) {
28571
- return false;
27495
+ return params;
27496
+ }
27497
+ function deriveCommandPath(cmd) {
27498
+ const parts = [];
27499
+ let current = cmd;
27500
+ while (current) {
27501
+ const name = current.name();
27502
+ if (name) {
27503
+ parts.unshift(name);
28572
27504
  }
28573
- throw new Error("jsonPath: " + e.message + ": " + code);
27505
+ current = current.parent;
28574
27506
  }
28575
- };
28576
- JSONPath.cache = {};
28577
- JSONPath.toPathString = function(pathArr) {
28578
- const x = pathArr, n = x.length;
28579
- let p = "$";
28580
- for (let i = 1;i < n; i++) {
28581
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
28582
- p += /^[0-9*]+$/u.test(x[i]) ? "[" + x[i] + "]" : "['" + x[i] + "']";
28583
- }
27507
+ if (parts.length > 1) {
27508
+ parts.shift();
28584
27509
  }
28585
- return p;
28586
- };
28587
- JSONPath.toPointer = function(pointer) {
28588
- const x = pointer, n = x.length;
28589
- let p = "";
28590
- for (let i = 1;i < n; i++) {
28591
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
28592
- p += "/" + x[i].toString().replaceAll("~", "~0").replaceAll("/", "~1");
27510
+ return ["uip", ...parts.filter((p) => p !== "uip")].join(".");
27511
+ }
27512
+ function isCliErrorCode(value) {
27513
+ return typeof value === "string" && cliErrorCodeValues.has(value);
27514
+ }
27515
+ function isRetryHint(value) {
27516
+ return typeof value === "string" && retryHintValues.has(value);
27517
+ }
27518
+ function isErrorContext(value) {
27519
+ return value !== null && typeof value === "object";
27520
+ }
27521
+ function commandHelpHint(commandPath) {
27522
+ const command = commandPath.replace(/\./g, " ");
27523
+ return `An unexpected error occurred. Run '${command} --help' to verify command syntax, or run with --log-level debug for details.`;
27524
+ }
27525
+ Command2.prototype.trackedAction = function(context, fn, properties) {
27526
+ const command = this;
27527
+ return this.action(async (...args) => {
27528
+ const telemetryName = deriveCommandPath(command);
27529
+ const props = typeof properties === "function" ? properties(...args) : properties;
27530
+ const startTime = performance.now();
27531
+ let errorMessage2;
27532
+ const [error] = await catchError2(fn(...args));
27533
+ if (error) {
27534
+ errorMessage2 = error instanceof Error ? error.message : String(error);
27535
+ logger.debug(`[trackedAction] ${telemetryName} failed: ${errorMessage2}`);
27536
+ const typed = error;
27537
+ const customInstructions = typeof typed.instructions === "string" ? typed.instructions : undefined;
27538
+ const customResult = typeof typed.result === "string" && typed.result !== RESULTS.Success && Object.values(RESULTS).includes(typed.result) ? typed.result : undefined;
27539
+ const finalResult = customResult ?? RESULTS.Failure;
27540
+ const typedErrorCode = typed.errorCode ?? typed.ErrorCode;
27541
+ const customErrorCode = isCliErrorCode(typedErrorCode) ? typedErrorCode : undefined;
27542
+ const typedRetry = typed.retry ?? typed.Retry;
27543
+ const customRetry = isRetryHint(typedRetry) ? typedRetry : undefined;
27544
+ const typedContext = typed.context ?? typed.Context;
27545
+ const customContext = isErrorContext(typedContext) ? typedContext : undefined;
27546
+ OutputFormatter.error({
27547
+ Result: finalResult,
27548
+ ...customErrorCode ? { ErrorCode: customErrorCode } : {},
27549
+ Message: errorMessage2,
27550
+ Instructions: customInstructions ?? commandHelpHint(telemetryName),
27551
+ ...customRetry ? { Retry: customRetry } : {},
27552
+ ...customContext ? { Context: customContext } : {}
27553
+ });
27554
+ context.exit(EXIT_CODES[finalResult]);
28593
27555
  }
28594
- }
28595
- return p;
28596
- };
28597
- JSONPath.toPathArray = function(expr) {
28598
- const {
28599
- cache
28600
- } = JSONPath;
28601
- if (cache[expr]) {
28602
- return cache[expr].concat();
28603
- }
28604
- const subx = [];
28605
- const normalized = expr.replaceAll(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/gu, ";$&;").replaceAll(/[['](\??\(.*?\))[\]'](?!.\])/gu, function($0, $1) {
28606
- return "[#" + (subx.push($1) - 1) + "]";
28607
- }).replaceAll(/\[['"]([^'\]]*)['"]\]/gu, function($0, prop) {
28608
- return "['" + prop.replaceAll(".", "%@%").replaceAll("~", "%%@@%%") + "']";
28609
- }).replaceAll("~", ";~;").replaceAll(/['"]?\.['"]?(?![^[]*\])|\[['"]?/gu, ";").replaceAll("%@%", ".").replaceAll("%%@@%%", "~").replaceAll(/(?:;)?(\^+)(?:;)?/gu, function($0, ups) {
28610
- return ";" + ups.split("").join(";") + ";";
28611
- }).replaceAll(/;;;|;;/gu, ";..;").replaceAll(/;$|'?\]|'$/gu, "");
28612
- const exprList = normalized.split(";").map(function(exp) {
28613
- const match = exp.match(/#(\d+)/u);
28614
- return !match || !match[1] ? exp : subx[match[1]];
27556
+ const durationMs = performance.now() - startTime;
27557
+ const success = !error && (process.exitCode === undefined || process.exitCode === 0);
27558
+ telemetry.trackEvent(telemetryName, redactProperties({
27559
+ ...extractCommandParams(command),
27560
+ ...props,
27561
+ command: "true",
27562
+ duration: String(durationMs),
27563
+ success: String(success),
27564
+ ...errorMessage2 ? { errorMessage: errorMessage2 } : {}
27565
+ }));
28615
27566
  });
28616
- cache[expr] = exprList;
28617
- return cache[expr].concat();
28618
27567
  };
28619
- JSONPath.prototype.safeVm = {
28620
- Script: SafeScript
28621
- };
28622
- JSONPath.prototype.vm = vm;
27568
+ // ../../common/src/console-guard.ts
27569
+ var guardInstalledSlot = singleton("ConsoleGuardInstalled");
27570
+ var savedOriginalsSlot = singleton("ConsoleGuardOriginals");
27571
+ // ../../common/src/constants.ts
27572
+ var DEFAULT_AUTH_TIMEOUT_MS2 = 5 * 60 * 1000;
27573
+ // ../../common/src/interactivity-context.ts
27574
+ var modeSlot = singleton("InteractivityMode");
28623
27575
  // ../../common/src/option-aliases.ts
28624
27576
  import { Option } from "commander";
28625
27577
  // ../../common/src/option-validators.ts
@@ -28658,6 +27610,18 @@ var FAILURE_STATUSES = new Set([
28658
27610
  "canceled",
28659
27611
  "stopped"
28660
27612
  ]);
27613
+ // ../../common/src/preview.ts
27614
+ import { Command as Command3 } from "commander";
27615
+ var previewSlot = singleton("PreviewBuild");
27616
+ function isPreviewBuild() {
27617
+ return previewSlot.get(false) ?? false;
27618
+ }
27619
+ Command3.prototype.previewCommand = function(nameAndArgs, opts) {
27620
+ if (isPreviewBuild()) {
27621
+ return this.command(nameAndArgs, opts);
27622
+ }
27623
+ return new Command3(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
27624
+ };
28661
27625
  // ../../common/src/screen-logger.ts
28662
27626
  var ScreenLogger;
28663
27627
  ((ScreenLogger) => {
@@ -28922,7 +27886,7 @@ class VoidApiResponse2 {
28922
27886
  var package_default3 = {
28923
27887
  name: "@uipath/identity-sdk",
28924
27888
  license: "MIT",
28925
- version: "1.196.0",
27889
+ version: "1.197.0",
28926
27890
  repository: {
28927
27891
  type: "git",
28928
27892
  url: "https://github.com/UiPath/cli.git",
@@ -28950,7 +27914,7 @@ var package_default3 = {
28950
27914
  ],
28951
27915
  private: true,
28952
27916
  scripts: {
28953
- build: "bun build ./src/index.ts --outdir dist --format esm --target node && tsc -p tsconfig.build.json --noCheck",
27917
+ build: "bun build ./src/index.ts --outdir dist --format esm --target node --sourcemap=linked && tsc -p tsconfig.build.json --noCheck",
28954
27918
  generate: "bun run src/scripts/generate-sdk.ts",
28955
27919
  lint: "biome check .",
28956
27920
  test: "vitest run",
@@ -30245,12 +29209,12 @@ async function resolveIdentityToId(identity, options) {
30245
29209
  const exact = users.find((u) => u.email?.toLowerCase() === lower2 || u.userName?.toLowerCase() === lower2);
30246
29210
  if (exact?.id !== undefined && exact.id !== "")
30247
29211
  return exact.id;
30248
- const preview = users.slice(0, 5).map(formatCandidate).join("; ");
29212
+ const preview2 = users.slice(0, 5).map(formatCandidate).join("; ");
30249
29213
  const more = users.length > 5 ? `; ... (+${users.length - 5} more)` : "";
30250
29214
  OutputFormatter.error({
30251
29215
  Result: RESULTS.Failure,
30252
29216
  Message: `Multiple users matched '${identity}'. Pass a UUID or a more specific value.`,
30253
- Instructions: `Candidates: ${preview}${more}.`
29217
+ Instructions: `Candidates: ${preview2}${more}.`
30254
29218
  });
30255
29219
  processContext.exit(1);
30256
29220
  return null;
@@ -31393,3 +30357,5 @@ export {
31393
30357
  registerCommands,
31394
30358
  metadata
31395
30359
  };
30360
+
30361
+ //# debugId=78F8FC6DE70A0A3E64756E2164756E21