@uipath/flow-tool 1.201.0 → 1.202.0-preview.136

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 (234) hide show
  1. package/dist/{authoring-7r6g06c7.js → authoring-wpa6d0vf.js} +74 -48
  2. package/dist/binding-service-dh91hw9e.js +141 -0
  3. package/dist/{browser-strategy-rkcvc6tn.js → browser-strategy-6atc7v8s.js} +3 -3
  4. package/dist/connector-service-d9ph9kx1.js +948 -0
  5. package/dist/{conversion-H2VEEYLB-ng48mbf7.js → conversion-QANACVCM-zs0hhfjv.js} +39 -33
  6. package/dist/{de-5KVP66U6-f7knj511.js → de-5KVP66U6-1bnf4zt5.js} +52 -52
  7. package/dist/de-6U7ECGHH-xwsw33fk.js +35 -0
  8. package/dist/{de-5HU6GFWV-4EZK6G7N-yrh21f52.js → de-7XQXX2DK-IDWR6CAR-n4z245kt.js} +857 -845
  9. package/dist/{de-5HU6GFWV-zheyw6d2.js → de-7XQXX2DK-tqdy5n2b.js} +857 -845
  10. package/dist/{de-HKTOVV4H-d5yw5j21.js → de-HKTOVV4H-pe9w0xn8.js} +46 -46
  11. package/dist/{de-XLT4QPIP-0rtw349w.js → de-XLT4QPIP-kj81dxjc.js} +9 -9
  12. package/dist/debug-conversation-trigger-452frzyz.js +41 -0
  13. package/dist/debug-http-client-wd6xb8v4.js +31 -0
  14. package/dist/debug-service-fvyexnb1.js +58 -0
  15. package/dist/edge-service-e77bndbe.js +162 -0
  16. package/dist/{elk.bundled-pydbzeez.js → elk.bundled-vpsbxz0p.js} +3 -3
  17. package/dist/{en-MABQK6C4-REWE2WG2-8dp4cqdg.js → en-5ZGC5VQ3-EWX7ILY7-rmtj70fk.js} +898 -898
  18. package/dist/{en-MABQK6C4-nkzq2j8t.js → en-5ZGC5VQ3-h581y30k.js} +897 -897
  19. package/dist/en-EPWMLP2N-2wvge238.js +28 -0
  20. package/dist/{en-UNT7BE26-rhh65jry.js → en-LQHKFSEY-vvbe8ve9.js} +13 -11
  21. package/dist/{en-P4AS26D7-szrzfxz1.js → en-P4AS26D7-zptp77bm.js} +45 -45
  22. package/dist/{en-4KXU7N7B-66fntxa2.js → en-X3S6IZ5J-nhkg6pwn.js} +54 -60
  23. package/dist/{es-MX-H2EAXLYI-qwnqt48x.js → es-MX-H2EAXLYI-j42kfkxy.js} +46 -46
  24. package/dist/es-MX-NHTIP5YM-ar6zfx95.js +35 -0
  25. package/dist/{es-MX-OKNDG2NH-c1k1s1tg.js → es-MX-OKNDG2NH-tcac6j4g.js} +9 -9
  26. package/dist/{es-MX-POESXYP2-UW6VP5QI-cd3a79g9.js → es-MX-U2VN3SZW-KYAJ2ONK-kdram1g1.js} +857 -845
  27. package/dist/{es-MX-POESXYP2-9538722k.js → es-MX-U2VN3SZW-anynsmd8.js} +857 -845
  28. package/dist/{es-MX-XAVLOQW3-9b3cp9n8.js → es-MX-XAVLOQW3-q00km2y7.js} +52 -52
  29. package/dist/{es-NQICVYSQ-aa9z3nhs.js → es-NQICVYSQ-3dtqgget.js} +9 -9
  30. package/dist/{es-O4PAV2CR-jwfaawwk.js → es-O4PAV2CR-0g23ve3v.js} +46 -46
  31. package/dist/es-PQ3RA33Q-y4kxhjfr.js +35 -0
  32. package/dist/{es-VFPNVMP5-thm0z9sr.js → es-VFPNVMP5-bx2c337j.js} +52 -52
  33. package/dist/{es-LUTYN7U7-IY5QWOUF-k2aefzc0.js → es-ZGCPPOME-24PJEGPV-rn86z9kn.js} +857 -845
  34. package/dist/{es-LUTYN7U7-ye5zn4sn.js → es-ZGCPPOME-8gazspjj.js} +857 -845
  35. package/dist/flow-api-wv8p8xbd.js +36 -0
  36. package/dist/flow-debug-service-tfbefas6.js +741 -0
  37. package/dist/flow-eval-node-target-c6wea7rz.js +44 -0
  38. package/dist/flow-eval-run-service-01kdky72.js +961 -0
  39. package/dist/flow-eval-service-ft8e16jz.js +1338 -0
  40. package/dist/flow-init-service-mva4crty.js +35 -0
  41. package/dist/flow-io-r318sjrw.js +36 -0
  42. package/dist/flow-migrate-service-rwcdx60q.js +119 -0
  43. package/dist/flow-pack-service-p4hxyj9e.js +280 -0
  44. package/dist/flow-validate-service-j25pxpwz.js +57 -0
  45. package/dist/{fr-5YRGHXF5-q6b63yg0.js → fr-5YRGHXF5-kz1ywpv6.js} +46 -46
  46. package/dist/{fr-E5MDO4EG-exvrs7ge.js → fr-E5MDO4EG-c3mkty2t.js} +52 -52
  47. package/dist/{fr-PFHIL7YZ-cxnshwa8.js → fr-PFHIL7YZ-2n589p47.js} +9 -9
  48. package/dist/fr-R4L3OAWI-30khpsmn.js +35 -0
  49. package/dist/{fr-LJIK56LW-STG6QR3T-cextvv8q.js → fr-T3G5GZCT-TU4IKBEG-k6xz1s1f.js} +857 -845
  50. package/dist/{fr-LJIK56LW-xf3xf2kh.js → fr-T3G5GZCT-y3f7xb1q.js} +857 -845
  51. package/dist/governance-fetcher-j9cx4f1d.js +391 -0
  52. package/dist/headless-h1myzz32.js +177196 -0
  53. package/dist/hitl-service-kvt5wms4.js +256 -0
  54. package/dist/index-1kgxzh8x.js +143 -0
  55. package/dist/index-4zrwgb3c.js +111 -0
  56. package/dist/index-ev4mdg5y.js +4801 -0
  57. package/dist/{index-er6vy3jk.js → index-eybzsdcc.js} +295 -317
  58. package/dist/{index-hsadteg4.js → index-h8cph72k.js} +4 -4
  59. package/dist/{index-p50kx6jv.js → index-k5tbd184.js} +276 -276
  60. package/dist/index-n33np76r.js +630 -0
  61. package/dist/{index-9f8q2ege.js → index-p3vk57z7.js} +27 -27
  62. package/dist/{index-dhcd9b82.js → index-w0z4s69j.js} +166 -81
  63. package/dist/index.js +29 -32
  64. package/dist/{index.umd.min-drpc57vn.js → index.umd.min-fqefd9kn.js} +3 -3
  65. package/dist/init.js +24 -25
  66. package/dist/input-reader-6pwhtp8v.js +11 -0
  67. package/dist/{ja-FGEGLBJ3-w9byjhze.js → ja-BI5K3JDZ-77zat4z2.js} +857 -845
  68. package/dist/{ja-FGEGLBJ3-MG3BSWXD-vq19zt2p.js → ja-BI5K3JDZ-GTIHISTZ-s6n3r2ab.js} +857 -845
  69. package/dist/{ja-DPO5PPLO-s2a7j3nj.js → ja-DPO5PPLO-mysfmznx.js} +52 -52
  70. package/dist/{ja-P4OSE367-8ywxep9a.js → ja-P4OSE367-srr3qypg.js} +9 -9
  71. package/dist/{ja-SDAPAVCR-943p5gx7.js → ja-SDAPAVCR-kg39dfap.js} +46 -46
  72. package/dist/ja-ZHKCBE5W-x73w6x3e.js +35 -0
  73. package/dist/{js-yaml-cggj6w7q.js → js-yaml-87cdx6bm.js} +27 -19
  74. package/dist/known-types-a20evmmg.js +20 -0
  75. package/dist/ko-6W7OGLLB-mnmqc584.js +35 -0
  76. package/dist/{ko-ITOPNIYI-qz39kamf.js → ko-ITOPNIYI-hmxd2asd.js} +52 -52
  77. package/dist/{ko-TUAK3G3A-s25w0ckg.js → ko-JOBF5V7N-4bv0mjje.js} +857 -845
  78. package/dist/{ko-TUAK3G3A-TBEBKOTM-ns78t2rv.js → ko-JOBF5V7N-O7T4HKIE-ape840y0.js} +857 -845
  79. package/dist/{ko-NAGOZLC3-wb3y9yhh.js → ko-NAGOZLC3-gaxxsnd2.js} +46 -46
  80. package/dist/{ko-PYOS2KJP-5sbj5bp8.js → ko-PYOS2KJP-e7dshyxy.js} +9 -9
  81. package/dist/localization-h8a53z6p.js +47 -0
  82. package/dist/{node-gd4469ea.js → node-cnrcrrb0.js} +7973 -7166
  83. package/dist/node-service-8g5x5d2y.js +70 -0
  84. package/dist/{node-strategy-8gzp67xs.js → node-strategy-gc4sg6a2.js} +132 -16
  85. package/dist/node-sync-service-e2reh33c.js +42 -0
  86. package/dist/{packager-tool-9qecd4wb.js → packager-tool-0gctz400.js} +5 -2
  87. package/dist/{packager-tool-1cb0d5e0.js → packager-tool-0v3s8r01.js} +2 -2
  88. package/dist/{packager-tool-wckvcay0.js → packager-tool-1yh8g550.js} +9 -7
  89. package/dist/packager-tool-27avrkyk.js +15 -0
  90. package/dist/packager-tool-2wefykg9.js +106 -0
  91. package/dist/packager-tool-4fhgws0x.js +757 -0
  92. package/dist/{packager-tool-7yjpwj92.js → packager-tool-4hx14snw.js} +49 -48
  93. package/dist/{packager-tool-3wygxefb.js → packager-tool-58q3tvh7.js} +10 -10
  94. package/dist/{packager-tool-cvwr40ax.js → packager-tool-5qaxht3k.js} +1425 -550
  95. package/dist/packager-tool-5z1eg3ea.js +33289 -0
  96. package/dist/{packager-tool-17cn3xb7.js → packager-tool-6m078z5s.js} +13388 -19366
  97. package/dist/packager-tool-7b6tpg7y.js +77 -0
  98. package/dist/packager-tool-7exrv6w7.js +23 -0
  99. package/dist/packager-tool-8dszjcg5.js +4892 -0
  100. package/dist/packager-tool-8j92afwp.js +58 -0
  101. package/dist/packager-tool-94w17vf8.js +85 -0
  102. package/dist/{packager-tool-vdd02vns.js → packager-tool-9bec251q.js} +543 -1493
  103. package/dist/packager-tool-a1hbfmws.js +399 -0
  104. package/dist/{packager-tool-tq9q9m77.js → packager-tool-a42jnpy5.js} +3 -9
  105. package/dist/packager-tool-abbtfk2v.js +54 -0
  106. package/dist/packager-tool-cdwpc9fh.js +4945 -0
  107. package/dist/packager-tool-e0p2zsyc.js +97 -0
  108. package/dist/packager-tool-eebq62fq.js +540 -0
  109. package/dist/{packager-tool-m6x5sczh.js → packager-tool-em5r6g6j.js} +14 -21
  110. package/dist/packager-tool-eypvc2kv.js +23 -0
  111. package/dist/packager-tool-f0kd5kq4.js +2327 -0
  112. package/dist/packager-tool-fjaa8d3v.js +289 -0
  113. package/dist/packager-tool-g0eha8ge.js +121 -0
  114. package/dist/packager-tool-g9y14b10.js +54 -0
  115. package/dist/packager-tool-gbgfwx8f.js +2 -0
  116. package/dist/packager-tool-jc34wvrw.js +64 -0
  117. package/dist/packager-tool-k99nf3pq.js +25 -0
  118. package/dist/{packager-tool-hr0xg6q8.js → packager-tool-kn91khp6.js} +17 -13
  119. package/dist/{packager-tool-jysvpt8p.js → packager-tool-m3wkcxf5.js} +2 -2
  120. package/dist/{packager-tool-78a3szsp.js → packager-tool-m5qfverj.js} +1720 -2014
  121. package/dist/packager-tool-mwvbq6ef.js +79 -0
  122. package/dist/packager-tool-nq4rcqqg.js +87 -0
  123. package/dist/packager-tool-nxx8naxv.js +4234 -0
  124. package/dist/{packager-tool-3y0k15sv.js → packager-tool-p9stswjj.js} +2858 -19342
  125. package/dist/packager-tool-r0xpcqwg.js +188 -0
  126. package/dist/packager-tool-raq2wbwp.js +18 -0
  127. package/dist/{packager-tool-y3dezh8k.js → packager-tool-rs6jm14d.js} +6 -4
  128. package/dist/packager-tool-s9ff3kk4.js +6 -0
  129. package/dist/{packager-tool-pbsghbmj.js → packager-tool-sykgshez.js} +2 -2
  130. package/dist/packager-tool-tf3d2y8z.js +31 -0
  131. package/dist/packager-tool-tn5e7wnb.js +384 -0
  132. package/dist/packager-tool-v2rkcehq.js +457 -0
  133. package/dist/packager-tool-v86fdwvs.js +262 -0
  134. package/dist/packager-tool-v9psxdy5.js +8185 -0
  135. package/dist/packager-tool-v9rrz038.js +602 -0
  136. package/dist/packager-tool-vpqyvh4c.js +304 -0
  137. package/dist/packager-tool-wcha0e5r.js +443 -0
  138. package/dist/{packager-tool-1gt6js73.js → packager-tool-xhzfwa5p.js} +6 -4
  139. package/dist/{packager-tool-5arsyj36.js → packager-tool-yc4kw997.js} +4 -2
  140. package/dist/{packager-tool-pkq70dec.js → packager-tool-ywqc9rtf.js} +31 -3
  141. package/dist/{packager-tool-0567pxpm.js → packager-tool-z9bfhmm5.js} +10 -10
  142. package/dist/{packager-tool-gmrwvnyh.js → packager-tool-zfrp8ecz.js} +8 -58
  143. package/dist/{packager-tool-3vdpx9ng.js → packager-tool-zke08y39.js} +1121 -1846
  144. package/dist/packager-tool.js +17 -17
  145. package/dist/{pt-7TR74ZMB-1g8my56g.js → pt-7TR74ZMB-bmphh4x2.js} +46 -46
  146. package/dist/{pt-BR-7XGDXRDJ-TR5D7JYL-533wvy7p.js → pt-BR-7DYX2YPT-LZYH4YFD-bx43vx3z.js} +857 -845
  147. package/dist/{pt-BR-7XGDXRDJ-espnkgrj.js → pt-BR-7DYX2YPT-fqxqzqtf.js} +857 -845
  148. package/dist/{pt-BR-BXURWX4W-dqr4dnf9.js → pt-BR-BXURWX4W-bwfcwhk1.js} +52 -52
  149. package/dist/{pt-BR-DXXSYJDO-bn84ewp7.js → pt-BR-DXXSYJDO-a2tp13v7.js} +46 -46
  150. package/dist/pt-BR-UQCYHKMJ-q78n7q70.js +35 -0
  151. package/dist/{pt-BR-Z3TUDJHM-n7ngej6s.js → pt-BR-Z3TUDJHM-8v73x9s7.js} +9 -9
  152. package/dist/pt-D6A6MVB2-yvxca8vz.js +35 -0
  153. package/dist/{pt-TMVOOITK-myha14p9.js → pt-HTXGGX6Y-97t21dty.js} +857 -845
  154. package/dist/{pt-TMVOOITK-H2ADYHSD-ezpggv33.js → pt-HTXGGX6Y-ZHQSDFKI-vehfxadc.js} +857 -845
  155. package/dist/{pt-KSBWHAVQ-hd52bpsz.js → pt-KSBWHAVQ-mhvhgr2p.js} +9 -9
  156. package/dist/{pt-YI4VE4YQ-v7gjeg82.js → pt-YI4VE4YQ-wdkn2dcf.js} +52 -52
  157. package/dist/ro-4TMBHS5M-jz0anpt6.js +35 -0
  158. package/dist/{ro-BJFER5OI-334n28rj.js → ro-BJFER5OI-83tq8vxh.js} +46 -46
  159. package/dist/{ro-2VALF3S5-NXBJUEZN-nqw1zs33.js → ro-KTNQ3MNU-XIE6YPQN-gen8p82z.js} +857 -845
  160. package/dist/{ro-2VALF3S5-cdz5afkr.js → ro-KTNQ3MNU-y08n1x5g.js} +857 -845
  161. package/dist/{ro-RKXZUG7Z-cm3xn3fj.js → ro-RKXZUG7Z-nndrrsq7.js} +52 -52
  162. package/dist/{ro-VZUZTAMR-tccygznf.js → ro-VZUZTAMR-f4q0g3em.js} +9 -9
  163. package/dist/{ru-GSCT4ARZ-qj8dm4dp.js → ru-GSCT4ARZ-1sa9wbr8.js} +1 -1
  164. package/dist/{ru-GSCT4ARZ-FTVCGQTL-5nh4jf2e.js → ru-GSCT4ARZ-FTVCGQTL-gee86v14.js} +1 -1
  165. package/dist/{ru-T73OPRTC-mp5gn7gs.js → ru-T73OPRTC-4knxw497.js} +1 -1
  166. package/dist/{ru-WBLQ5B2U-awt245ky.js → ru-WBLQ5B2U-8r3c7v6d.js} +1 -1
  167. package/dist/ru-WBLQ5B2U-kdey8qa4.js +10 -0
  168. package/dist/{ru-WBLQ5B2U-57ezmxzz.js → ru-WBLQ5B2U-wemdzdqd.js} +1 -1
  169. package/dist/{serialization-GAW7UFOK-9hkdmmd2.js → serialization-J5QK3HPY-bgewpt6f.js} +158 -152
  170. package/dist/services/expression-validator.d.ts +28 -0
  171. package/dist/services/flow-eval-schema/types.d.ts +17 -0
  172. package/dist/services/flow-validate-service.d.ts +26 -0
  173. package/dist/services/node-validators/js-expression-syntax-validator.d.ts +6 -3
  174. package/dist/services/tidy-service.d.ts +26 -0
  175. package/dist/services/vars-reference-rule.d.ts +156 -0
  176. package/dist/shared-utils-8xdq6f04.js +20 -0
  177. package/dist/tidy-service-ashgyfwj.js +34 -0
  178. package/dist/tool.js +30 -33
  179. package/dist/{tr-AA6O2WSR-ga1xnymp.js → tr-AA6O2WSR-86ba4bdf.js} +52 -52
  180. package/dist/tr-GSQQ6SOT-hv1gyeaa.js +35 -0
  181. package/dist/{tr-RQTZ2DMS-bpgd4kma.js → tr-RQTZ2DMS-w3cwv8s4.js} +46 -46
  182. package/dist/{tr-W4AVRSQ4-bt3qqqdy.js → tr-W4AVRSQ4-hjr81xzk.js} +9 -9
  183. package/dist/{tr-RIFCEXFH-BZS7S7QK-q465b62g.js → tr-XHSSPNK7-GW5KVXR3-2w3f1ss6.js} +857 -845
  184. package/dist/{tr-RIFCEXFH-hgkb4g8y.js → tr-XHSSPNK7-cmqyc4wd.js} +857 -845
  185. package/dist/utils/handle-expansion.d.ts +16 -0
  186. package/dist/validation.js +47 -27
  187. package/dist/variable-service-er7ph4br.js +152 -0
  188. package/dist/wait-for-flow-job-45p1a444.js +134 -0
  189. package/dist/{zh-CN-IP3FMXWM-H3JI2XUM-ta4yac7h.js → zh-CN-2EHQT23P-T5XRQCVS-ac17dpc1.js} +857 -845
  190. package/dist/{zh-CN-IP3FMXWM-1cfarhcp.js → zh-CN-2EHQT23P-mr63c4xz.js} +857 -845
  191. package/dist/{zh-CN-6YRAN57T-j7jp34ws.js → zh-CN-6YRAN57T-rd7x2tqs.js} +9 -9
  192. package/dist/zh-CN-EDFRBU32-vvj7tmaq.js +35 -0
  193. package/dist/{zh-CN-R2KLHXQV-wttmznep.js → zh-CN-R2KLHXQV-agqr45ds.js} +52 -52
  194. package/dist/{zh-CN-ZC6LT4IN-vty9mvv8.js → zh-CN-ZC6LT4IN-kbzvvzz5.js} +46 -46
  195. package/dist/zh-TW-HAICM6DE-rh7k3cq7.js +35 -0
  196. package/dist/{zh-TW-AGIDXIPF-R4XZRDJZ-cgxxz5k4.js → zh-TW-MGZCE5BT-P6FLIUAR-zmq07vhs.js} +857 -845
  197. package/dist/{zh-TW-AGIDXIPF-n6r6w7vy.js → zh-TW-MGZCE5BT-c4ekmrz9.js} +857 -845
  198. package/dist/{zh-TW-R7Y5KVMU-q81f4z2p.js → zh-TW-R7Y5KVMU-m61y07e3.js} +46 -46
  199. package/dist/{zh-TW-RJGCQANM-gqn0aca0.js → zh-TW-RJGCQANM-w0x3qc1p.js} +52 -52
  200. package/dist/{zh-TW-SO2245GN-m5kh88bg.js → zh-TW-SO2245GN-n2bn1gg4.js} +9 -9
  201. package/package.json +2 -2
  202. package/dist/de-5KVP66U6-t37qr521.js +0 -161
  203. package/dist/de-WMKOGI7B-6dc1zdnp.js +0 -143
  204. package/dist/en-4KXU7N7B-24v330b5.js +0 -118
  205. package/dist/en-X4DLPKLJ-1h9gj5c1.js +0 -110
  206. package/dist/es-BVPGJUWA-0k59eqfv.js +0 -143
  207. package/dist/es-MX-U6YL5KQX-k4qvpgd4.js +0 -143
  208. package/dist/es-MX-XAVLOQW3-47a405kf.js +0 -161
  209. package/dist/es-VFPNVMP5-6sftsdxe.js +0 -161
  210. package/dist/fr-E5MDO4EG-f3x1jeqw.js +0 -161
  211. package/dist/fr-EKTTDR7Z-m2t68j0m.js +0 -143
  212. package/dist/ja-DPO5PPLO-fmbg7zt2.js +0 -161
  213. package/dist/ja-Y2YBTXNN-5sszk2zv.js +0 -143
  214. package/dist/ko-ITOPNIYI-aqy82jk8.js +0 -161
  215. package/dist/ko-S33XAV26-rfsv9myd.js +0 -143
  216. package/dist/packager-tool-0sz8se22.js +0 -10671
  217. package/dist/packager-tool-8mqydhz8.js +0 -9850
  218. package/dist/packager-tool-p9j43p8h.js +0 -115
  219. package/dist/packager-tool-v74yk918.js +0 -107
  220. package/dist/packager-tool-xj0agqpk.js +0 -11
  221. package/dist/pt-BR-BXURWX4W-xzyndmrx.js +0 -161
  222. package/dist/pt-BR-JO45SCNI-mt93s33c.js +0 -143
  223. package/dist/pt-W3NA4LIZ-fwd1q4j0.js +0 -143
  224. package/dist/pt-YI4VE4YQ-521681zf.js +0 -161
  225. package/dist/ro-RKXZUG7Z-pdztdafr.js +0 -161
  226. package/dist/ro-WLKX6HF5-b9tj8q67.js +0 -143
  227. package/dist/ru-WBLQ5B2U-8xd4gpv2.js +0 -10
  228. package/dist/ru-WBLQ5B2U-mswqs9wc.js +0 -10
  229. package/dist/tr-3U2W2XCA-43ptfc0m.js +0 -143
  230. package/dist/tr-AA6O2WSR-bj9n80k8.js +0 -161
  231. package/dist/zh-CN-IPZYQR3P-egjmvyjf.js +0 -143
  232. package/dist/zh-CN-R2KLHXQV-x6gnk2n0.js +0 -161
  233. package/dist/zh-TW-RJGCQANM-tt8j5wv2.js +0 -161
  234. package/dist/zh-TW-YPVSQVGT-b378ztph.js +0 -143
@@ -0,0 +1,2327 @@
1
+ import {
2
+ getGlobalThis,
3
+ isBrowser
4
+ } from "./packager-tool-0gctz400.js";
5
+ import {
6
+ catchError
7
+ } from "./packager-tool-qa9gftnj.js";
8
+ import {
9
+ AUTH_FILENAME,
10
+ DEFAULT_BASE_URL,
11
+ DEFAULT_REDIRECT_URI,
12
+ UIPATH_HOME_DIR
13
+ } from "./packager-tool-yc4kw997.js";
14
+ import {
15
+ getFileSystem
16
+ } from "./packager-tool-0v3s8r01.js";
17
+ import {
18
+ __require
19
+ } from "./packager-tool-1yh8g550.js";
20
+
21
+ // ../auth/src/config.ts
22
+ var DEFAULT_CLIENT_ID = "36dea5b8-e8bb-423d-8e7b-c808df8f1c00";
23
+ var AUTH_FILE_CONFIG_KEY = Symbol.for("@uipath/auth/AuthFileConfig");
24
+ var globalSlot = globalThis;
25
+ var setAuthFileConfig = (cfg) => {
26
+ globalSlot[AUTH_FILE_CONFIG_KEY] = cfg ?? {};
27
+ };
28
+ var getAuthFileConfig = () => globalSlot[AUTH_FILE_CONFIG_KEY] ?? {};
29
+
30
+ class InvalidBaseUrlError extends Error {
31
+ url;
32
+ reason;
33
+ constructor(url, reason) {
34
+ super(`Invalid base URL: "${url}"
35
+ ` + `Reason: ${reason}
36
+
37
+ ` + `Expected format: an https:// URL (or bare host — https:// is assumed), e.g. https://cloud.uipath.com (commercial), https://govcloud.uipath.us (Public Sector), or your Automation Suite host (https://<your-host>).
38
+ ` + `You can specify the URL via:
39
+ ` + ` • --authority flag
40
+ ` + ` • UIPATH_URL environment variable
41
+ ` + ` • auth.authority in config file`);
42
+ this.url = url;
43
+ this.reason = reason;
44
+ this.name = "InvalidBaseUrlError";
45
+ }
46
+ }
47
+ var DEFAULT_SCOPES = ["openid", "profile", "offline_access"];
48
+ var normalizeAndValidateBaseUrl = (rawUrl) => {
49
+ let baseUrl = rawUrl;
50
+ if (baseUrl.endsWith("/identity_/")) {
51
+ baseUrl = baseUrl.slice(0, -11);
52
+ } else if (baseUrl.endsWith("/identity_")) {
53
+ baseUrl = baseUrl.slice(0, -10);
54
+ }
55
+ while (baseUrl.endsWith("/")) {
56
+ baseUrl = baseUrl.slice(0, -1);
57
+ }
58
+ const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(baseUrl);
59
+ const [hostCandidate] = baseUrl.split(/[/?#]/, 1);
60
+ if (!hasScheme && hostCandidate.includes(".")) {
61
+ baseUrl = `https://${baseUrl}`;
62
+ }
63
+ const resolvedBaseUrl = baseUrl;
64
+ const [urlError, url] = catchError(() => new URL(resolvedBaseUrl));
65
+ if (urlError) {
66
+ const shapeHint = !hasScheme && !hostCandidate.includes(".") ? ` "${rawUrl.trim()}" is not a URL or a host name. Pass the full authority URL — https://<host>, or just <host> (https:// is assumed).` : ` ${urlError instanceof Error ? urlError.message : "Unknown error"}`;
67
+ throw new InvalidBaseUrlError(baseUrl, `Malformed URL.${shapeHint}`);
68
+ }
69
+ if (url.protocol !== "https:") {
70
+ throw new InvalidBaseUrlError(baseUrl, `Authority must use https:// scheme, got ${url.protocol}//. OIDC token exchange requires TLS end-to-end.`);
71
+ }
72
+ return url.pathname.length > 1 ? url.origin : baseUrl;
73
+ };
74
+ var resolveScopes = (isExternalAppAuth, customScopes, fileScopes) => {
75
+ const requestedScopes = customScopes?.length ? customScopes : fileScopes ?? [];
76
+ if (isExternalAppAuth)
77
+ return requestedScopes;
78
+ return [...new Set([...DEFAULT_SCOPES, ...requestedScopes])];
79
+ };
80
+ var resolveConfigAsync = async ({
81
+ customAuthority,
82
+ customClientId,
83
+ customClientSecret,
84
+ customClientAssertion,
85
+ customScopes
86
+ } = {}) => {
87
+ const fileAuth = getAuthFileConfig();
88
+ let baseUrl = customAuthority;
89
+ if (!baseUrl) {
90
+ baseUrl = process.env.UIPATH_URL;
91
+ }
92
+ if (!baseUrl && fileAuth.authority) {
93
+ baseUrl = fileAuth.authority;
94
+ }
95
+ if (!baseUrl) {
96
+ baseUrl = DEFAULT_BASE_URL;
97
+ }
98
+ baseUrl = normalizeAndValidateBaseUrl(baseUrl);
99
+ let clientId = customClientId;
100
+ if (!clientId && fileAuth.clientId) {
101
+ clientId = fileAuth.clientId;
102
+ }
103
+ if (!clientId) {
104
+ clientId = DEFAULT_CLIENT_ID;
105
+ }
106
+ let clientSecret = customClientSecret;
107
+ if (!clientSecret && fileAuth.clientSecret) {
108
+ clientSecret = fileAuth.clientSecret;
109
+ }
110
+ const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID && (Boolean(clientSecret) || Boolean(customClientAssertion));
111
+ const scopes = resolveScopes(isExternalAppAuth, customScopes, fileAuth.scopes);
112
+ return {
113
+ clientId,
114
+ clientSecret,
115
+ scopes,
116
+ baseUrl,
117
+ authorizationEndpoint: `${baseUrl}/identity_/connect/authorize`,
118
+ tokenEndpoint: `${baseUrl}/identity_/connect/token`
119
+ };
120
+ };
121
+
122
+ // ../../node_modules/oauth4webapi/build/index.js
123
+ var USER_AGENT;
124
+ if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
125
+ const NAME = "oauth4webapi";
126
+ const VERSION = "v3.8.6";
127
+ USER_AGENT = `${NAME}/${VERSION}`;
128
+ }
129
+ var ERR_INVALID_ARG_VALUE = "ERR_INVALID_ARG_VALUE";
130
+ var ERR_INVALID_ARG_TYPE = "ERR_INVALID_ARG_TYPE";
131
+ function CodedTypeError(message, code, cause) {
132
+ const err = new TypeError(message, { cause });
133
+ Object.assign(err, { code });
134
+ return err;
135
+ }
136
+ var allowInsecureRequests = Symbol();
137
+ var clockSkew = Symbol();
138
+ var clockTolerance = Symbol();
139
+ var customFetch = Symbol();
140
+ var modifyAssertion = Symbol();
141
+ var jweDecrypt = Symbol();
142
+ var jwksCache = Symbol();
143
+ var encoder = new TextEncoder;
144
+ var decoder = new TextDecoder;
145
+ function buf(input) {
146
+ if (typeof input === "string") {
147
+ return encoder.encode(input);
148
+ }
149
+ return decoder.decode(input);
150
+ }
151
+ var encodeBase64Url;
152
+ if (Uint8Array.prototype.toBase64) {
153
+ encodeBase64Url = (input) => {
154
+ if (input instanceof ArrayBuffer) {
155
+ input = new Uint8Array(input);
156
+ }
157
+ return input.toBase64({ alphabet: "base64url", omitPadding: true });
158
+ };
159
+ } else {
160
+ const CHUNK_SIZE = 32768;
161
+ encodeBase64Url = (input) => {
162
+ if (input instanceof ArrayBuffer) {
163
+ input = new Uint8Array(input);
164
+ }
165
+ const arr = [];
166
+ for (let i = 0;i < input.byteLength; i += CHUNK_SIZE) {
167
+ arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
168
+ }
169
+ return btoa(arr.join("")).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
170
+ };
171
+ }
172
+ var decodeBase64Url;
173
+ if (Uint8Array.fromBase64) {
174
+ decodeBase64Url = (input) => {
175
+ try {
176
+ return Uint8Array.fromBase64(input, { alphabet: "base64url" });
177
+ } catch (cause) {
178
+ throw CodedTypeError("The input to be decoded is not correctly encoded.", ERR_INVALID_ARG_VALUE, cause);
179
+ }
180
+ };
181
+ } else {
182
+ decodeBase64Url = (input) => {
183
+ try {
184
+ const binary = atob(input.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""));
185
+ const bytes = new Uint8Array(binary.length);
186
+ for (let i = 0;i < binary.length; i++) {
187
+ bytes[i] = binary.charCodeAt(i);
188
+ }
189
+ return bytes;
190
+ } catch (cause) {
191
+ throw CodedTypeError("The input to be decoded is not correctly encoded.", ERR_INVALID_ARG_VALUE, cause);
192
+ }
193
+ };
194
+ }
195
+ function b64u(input) {
196
+ if (typeof input === "string") {
197
+ return decodeBase64Url(input);
198
+ }
199
+ return encodeBase64Url(input);
200
+ }
201
+ class OperationProcessingError extends Error {
202
+ code;
203
+ constructor(message, options) {
204
+ super(message, options);
205
+ this.name = this.constructor.name;
206
+ if (options?.code) {
207
+ this.code = options?.code;
208
+ }
209
+ Error.captureStackTrace?.(this, this.constructor);
210
+ }
211
+ }
212
+ function OPE(message, code, cause) {
213
+ return new OperationProcessingError(message, { code, cause });
214
+ }
215
+ function assertString(input, it, code, cause) {
216
+ try {
217
+ if (typeof input !== "string") {
218
+ throw CodedTypeError(`${it} must be a string`, ERR_INVALID_ARG_TYPE, cause);
219
+ }
220
+ if (input.length === 0) {
221
+ throw CodedTypeError(`${it} must not be empty`, ERR_INVALID_ARG_VALUE, cause);
222
+ }
223
+ } catch (err) {
224
+ if (code) {
225
+ throw OPE(err.message, code, cause);
226
+ }
227
+ throw err;
228
+ }
229
+ }
230
+ function randomBytes() {
231
+ return b64u(crypto.getRandomValues(new Uint8Array(32)));
232
+ }
233
+ function generateRandomCodeVerifier() {
234
+ return randomBytes();
235
+ }
236
+ function generateRandomState() {
237
+ return randomBytes();
238
+ }
239
+ async function calculatePKCECodeChallenge(codeVerifier) {
240
+ assertString(codeVerifier, "codeVerifier");
241
+ return b64u(await crypto.subtle.digest("SHA-256", buf(codeVerifier)));
242
+ }
243
+ function ClientSecretPost(clientSecret) {
244
+ assertString(clientSecret, '"clientSecret"');
245
+ return (_as, client, body, _headers) => {
246
+ body.set("client_id", client.client_id);
247
+ body.set("client_secret", clientSecret);
248
+ };
249
+ }
250
+ function None() {
251
+ return (_as, client, body, _headers) => {
252
+ body.set("client_id", client.client_id);
253
+ };
254
+ }
255
+ var URLParse = URL.parse ? (url, base) => URL.parse(url, base) : (url, base) => {
256
+ try {
257
+ return new URL(url, base);
258
+ } catch {
259
+ return null;
260
+ }
261
+ };
262
+ var tokenMatch = "[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+";
263
+ var token68Match = "[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}";
264
+ var quotedMatch = '"((?:[^"\\\\]|\\\\[\\s\\S])*)"';
265
+ var quotedParamMatcher = "(" + tokenMatch + ")\\s*=\\s*" + quotedMatch;
266
+ var paramMatcher = "(" + tokenMatch + ")\\s*=\\s*(" + tokenMatch + ")";
267
+ var schemeRE = new RegExp("^[,\\s]*(" + tokenMatch + ")");
268
+ var quotedParamRE = new RegExp("^[,\\s]*" + quotedParamMatcher + "[,\\s]*(.*)");
269
+ var unquotedParamRE = new RegExp("^[,\\s]*" + paramMatcher + "[,\\s]*(.*)");
270
+ var token68ParamRE = new RegExp("^(" + token68Match + ")(?:$|[,\\s])(.*)");
271
+ var skipSubjectCheck = Symbol();
272
+ var idTokenClaims = new WeakMap;
273
+ var jwtRefs = new WeakMap;
274
+ var branded = new WeakSet;
275
+ var nopkce = Symbol();
276
+ var expectNoNonce = Symbol();
277
+ var skipAuthTimeCheck = Symbol();
278
+ var skipStateCheck = Symbol();
279
+ var expectNoState = Symbol();
280
+ var _nodiscoverycheck = Symbol();
281
+ var _expectedIssuer = Symbol();
282
+
283
+ // ../../node_modules/openid-client/build/index.js
284
+ var headers;
285
+ var USER_AGENT2;
286
+ if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
287
+ const NAME = "openid-client";
288
+ const VERSION = "v6.8.4";
289
+ USER_AGENT2 = `${NAME}/${VERSION}`;
290
+ headers = { "user-agent": USER_AGENT2 };
291
+ }
292
+ var int = (config) => {
293
+ return props.get(config);
294
+ };
295
+ var props;
296
+ var tbi;
297
+ function ClientSecretPost2(clientSecret) {
298
+ if (clientSecret !== undefined) {
299
+ return ClientSecretPost(clientSecret);
300
+ }
301
+ tbi ||= new WeakMap;
302
+ return (as, client, body, headers2) => {
303
+ let auth;
304
+ if (!(auth = tbi.get(client))) {
305
+ assertString2(client.client_secret, '"metadata.client_secret"');
306
+ auth = ClientSecretPost(client.client_secret);
307
+ tbi.set(client, auth);
308
+ }
309
+ return auth(as, client, body, headers2);
310
+ };
311
+ }
312
+ function assertString2(input, it) {
313
+ if (typeof input !== "string") {
314
+ throw CodedTypeError2(`${it} must be a string`, ERR_INVALID_ARG_TYPE2);
315
+ }
316
+ if (input.length === 0) {
317
+ throw CodedTypeError2(`${it} must not be empty`, ERR_INVALID_ARG_VALUE2);
318
+ }
319
+ }
320
+ function None2() {
321
+ return None();
322
+ }
323
+ var customFetch2 = customFetch;
324
+ var ERR_INVALID_ARG_VALUE2 = "ERR_INVALID_ARG_VALUE";
325
+ var ERR_INVALID_ARG_TYPE2 = "ERR_INVALID_ARG_TYPE";
326
+ function CodedTypeError2(message, code, cause) {
327
+ const err = new TypeError(message, { cause });
328
+ Object.assign(err, { code });
329
+ return err;
330
+ }
331
+ function calculatePKCECodeChallenge2(codeVerifier) {
332
+ return calculatePKCECodeChallenge(codeVerifier);
333
+ }
334
+ function randomPKCECodeVerifier() {
335
+ return generateRandomCodeVerifier();
336
+ }
337
+ function randomState() {
338
+ return generateRandomState();
339
+ }
340
+ var decoder2 = new TextDecoder;
341
+ function getServerHelpers(metadata) {
342
+ return {
343
+ supportsPKCE: {
344
+ __proto__: null,
345
+ value(method = "S256") {
346
+ return metadata.code_challenge_methods_supported?.includes(method) === true;
347
+ }
348
+ }
349
+ };
350
+ }
351
+ function addServerHelpers(metadata) {
352
+ Object.defineProperties(metadata, getServerHelpers(metadata));
353
+ }
354
+ var kEntraId = Symbol();
355
+
356
+ class Configuration {
357
+ constructor(server, clientId, metadata, clientAuthentication) {
358
+ if (typeof clientId !== "string" || !clientId.length) {
359
+ throw CodedTypeError2('"clientId" must be a non-empty string', ERR_INVALID_ARG_TYPE2);
360
+ }
361
+ if (typeof metadata === "string") {
362
+ metadata = { client_secret: metadata };
363
+ }
364
+ if (metadata?.client_id !== undefined && clientId !== metadata.client_id) {
365
+ throw CodedTypeError2('"clientId" and "metadata.client_id" must be the same', ERR_INVALID_ARG_VALUE2);
366
+ }
367
+ const client = {
368
+ ...structuredClone(metadata),
369
+ client_id: clientId
370
+ };
371
+ client[clockSkew] = metadata?.[clockSkew] ?? 0;
372
+ client[clockTolerance] = metadata?.[clockTolerance] ?? 30;
373
+ let auth;
374
+ if (clientAuthentication) {
375
+ auth = clientAuthentication;
376
+ } else {
377
+ if (typeof client.client_secret === "string" && client.client_secret.length) {
378
+ auth = ClientSecretPost2(client.client_secret);
379
+ } else {
380
+ auth = None2();
381
+ }
382
+ }
383
+ let c = Object.freeze(client);
384
+ const clone = structuredClone(server);
385
+ if (kEntraId in server) {
386
+ clone[_expectedIssuer] = ({ claims: { tid } }) => server.issuer.replace("{tenantid}", tid);
387
+ }
388
+ let as = Object.freeze(clone);
389
+ props ||= new WeakMap;
390
+ props.set(this, {
391
+ __proto__: null,
392
+ as,
393
+ c,
394
+ auth,
395
+ tlsOnly: true,
396
+ jwksCache: {}
397
+ });
398
+ }
399
+ serverMetadata() {
400
+ const metadata = structuredClone(int(this).as);
401
+ addServerHelpers(metadata);
402
+ return metadata;
403
+ }
404
+ clientMetadata() {
405
+ const metadata = structuredClone(int(this).c);
406
+ return metadata;
407
+ }
408
+ get timeout() {
409
+ return int(this).timeout;
410
+ }
411
+ set timeout(value) {
412
+ int(this).timeout = value;
413
+ }
414
+ get [customFetch2]() {
415
+ return int(this).fetch;
416
+ }
417
+ set [customFetch2](value) {
418
+ int(this).fetch = value;
419
+ }
420
+ }
421
+ Object.freeze(Configuration.prototype);
422
+ var retry = Symbol();
423
+
424
+ // ../auth/src/oidc.ts
425
+ var getOidcParams = async () => {
426
+ const code_verifier = randomPKCECodeVerifier();
427
+ const code_challenge = await calculatePKCECodeChallenge2(code_verifier);
428
+ const state = randomState();
429
+ return {
430
+ code_verifier,
431
+ code_challenge,
432
+ state
433
+ };
434
+ };
435
+
436
+ // ../auth/src/tokenExchange.ts
437
+ var exchangeCodeForTokens = async ({
438
+ code,
439
+ codeVerifier,
440
+ redirectUri,
441
+ clientId,
442
+ clientSecret,
443
+ tokenEndpoint
444
+ }) => {
445
+ const params = {
446
+ grant_type: "authorization_code",
447
+ code,
448
+ redirect_uri: redirectUri.toString(),
449
+ client_id: clientId,
450
+ code_verifier: codeVerifier
451
+ };
452
+ if (clientSecret) {
453
+ params.client_secret = clientSecret;
454
+ }
455
+ const tokenParams = new URLSearchParams(params);
456
+ const tokenResponse = await fetch(tokenEndpoint, {
457
+ method: "POST",
458
+ headers: {
459
+ "Content-Type": "application/x-www-form-urlencoded"
460
+ },
461
+ body: tokenParams
462
+ });
463
+ const tokenData = await tokenResponse.json();
464
+ if (!tokenResponse.ok) {
465
+ throw new Error(`Token exchange failed: ${String(tokenData.error ?? "unknown_error")} — ${String(tokenData.error_description ?? "no description")}`);
466
+ }
467
+ const accessToken = tokenData.access_token;
468
+ const refreshToken = tokenData.refresh_token;
469
+ if (typeof accessToken !== "string" || typeof refreshToken !== "string") {
470
+ throw new Error("Token exchange response is missing access_token or refresh_token");
471
+ }
472
+ return { accessToken, refreshToken };
473
+ };
474
+
475
+ // ../auth/src/authProfile.ts
476
+ var DEFAULT_AUTH_PROFILE = "default";
477
+ var PROFILE_DIR = "profiles";
478
+ var PROFILE_NAME_RE = /^[A-Za-z0-9._-]+$/;
479
+ var ACTIVE_AUTH_PROFILE_KEY = Symbol.for("@uipath/auth/ActiveAuthProfile");
480
+ var AUTH_PROFILE_STORAGE_KEY = Symbol.for("@uipath/auth/ProfileStorage");
481
+ var globalSlot2 = globalThis;
482
+ function isAuthProfileStorage(value) {
483
+ return value !== null && typeof value === "object" && "getStore" in value && "run" in value;
484
+ }
485
+ function createProfileStorage() {
486
+ const [error, mod] = catchError(() => __require("node:async_hooks"));
487
+ if (error || typeof mod?.AsyncLocalStorage !== "function") {
488
+ return {
489
+ getStore: () => {
490
+ return;
491
+ },
492
+ run: (_store, fn) => fn()
493
+ };
494
+ }
495
+ return new mod.AsyncLocalStorage;
496
+ }
497
+ function getProfileStorage() {
498
+ const existing = globalSlot2[AUTH_PROFILE_STORAGE_KEY];
499
+ if (isAuthProfileStorage(existing)) {
500
+ return existing;
501
+ }
502
+ const storage = createProfileStorage();
503
+ globalSlot2[AUTH_PROFILE_STORAGE_KEY] = storage;
504
+ return storage;
505
+ }
506
+ var profileStorage = getProfileStorage();
507
+
508
+ class AuthProfileValidationError extends Error {
509
+ constructor(message) {
510
+ super(message);
511
+ this.name = "AuthProfileValidationError";
512
+ }
513
+ }
514
+ function normalizeAuthProfileName(profile) {
515
+ if (profile === undefined || profile === DEFAULT_AUTH_PROFILE) {
516
+ return;
517
+ }
518
+ if (profile.length === 0 || profile === "." || profile === ".." || !PROFILE_NAME_RE.test(profile)) {
519
+ throw new AuthProfileValidationError(`Invalid profile name "${profile}". Profile names may contain only letters, numbers, '.', '_', and '-'.`);
520
+ }
521
+ return profile;
522
+ }
523
+ function setActiveAuthProfile(profile) {
524
+ const normalized = normalizeAuthProfileName(profile);
525
+ const scopedState = profileStorage.getStore();
526
+ if (scopedState !== undefined) {
527
+ if (normalized === undefined) {
528
+ delete scopedState.profile;
529
+ return;
530
+ }
531
+ scopedState.profile = normalized;
532
+ return;
533
+ }
534
+ if (normalized === undefined) {
535
+ delete globalSlot2[ACTIVE_AUTH_PROFILE_KEY];
536
+ return;
537
+ }
538
+ globalSlot2[ACTIVE_AUTH_PROFILE_KEY] = { profile: normalized };
539
+ }
540
+ function clearActiveAuthProfile() {
541
+ const scopedState = profileStorage.getStore();
542
+ if (scopedState !== undefined) {
543
+ delete scopedState.profile;
544
+ return;
545
+ }
546
+ delete globalSlot2[ACTIVE_AUTH_PROFILE_KEY];
547
+ }
548
+ function getActiveAuthProfile() {
549
+ const scopedState = profileStorage.getStore();
550
+ if (scopedState !== undefined) {
551
+ return scopedState.profile;
552
+ }
553
+ return globalSlot2[ACTIVE_AUTH_PROFILE_KEY]?.profile;
554
+ }
555
+ function runWithAuthProfile(profile, fn) {
556
+ const normalized = normalizeAuthProfileName(profile);
557
+ return profileStorage.run(normalized === undefined ? {} : { profile: normalized }, fn);
558
+ }
559
+ function resolveAuthProfileFilePath(profile) {
560
+ const normalized = normalizeAuthProfileName(profile);
561
+ if (normalized === undefined) {
562
+ throw new AuthProfileValidationError(`"${DEFAULT_AUTH_PROFILE}" is the built-in profile and does not have a profile file path.`);
563
+ }
564
+ const fs = getFileSystem();
565
+ return fs.path.join(fs.env.homedir(), UIPATH_HOME_DIR, PROFILE_DIR, normalized, AUTH_FILENAME);
566
+ }
567
+ function getActiveAuthProfileFilePath() {
568
+ const profile = getActiveAuthProfile();
569
+ return profile ? resolveAuthProfileFilePath(profile) : undefined;
570
+ }
571
+
572
+ // ../auth/src/utils/jwt.ts
573
+ class InvalidIssuerError extends Error {
574
+ expected;
575
+ actual;
576
+ constructor(expected, actual) {
577
+ const actualText = actual ?? "<missing>";
578
+ super(`Token issuer does not match the authority used to log in.
579
+ ` + `Expected: ${expected}
580
+ ` + `Actual: ${actualText}
581
+
582
+ ` + `The identity server that issued this token is not the one ` + `you pointed --authority at. Refusing to save credentials.`);
583
+ this.expected = expected;
584
+ this.actual = actual;
585
+ this.name = "InvalidIssuerError";
586
+ }
587
+ }
588
+ var parseJWT = (token) => {
589
+ try {
590
+ const parts = token.split(".");
591
+ const base64Url = parts[1];
592
+ if (!base64Url) {
593
+ throw new Error("Invalid JWT token format - missing payload section");
594
+ }
595
+ const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
596
+ let decodedString;
597
+ if (isBrowser() && typeof atob !== "undefined") {
598
+ decodedString = atob(base64);
599
+ } else {
600
+ decodedString = Buffer.from(base64, "base64").toString();
601
+ }
602
+ const jsonPayload = decodeURIComponent(decodedString.split("").map((c) => `%${`00${c.charCodeAt(0).toString(16)}`.slice(-2)}`).join(""));
603
+ const parsed = JSON.parse(jsonPayload);
604
+ return parsed;
605
+ } catch (error) {
606
+ throw new Error(`Failed to parse JWT: ${error instanceof Error ? error.message : "Unknown error"}`);
607
+ }
608
+ };
609
+ var assertIssuerMatchesAuthority = (token, authority) => {
610
+ let payload;
611
+ try {
612
+ payload = parseJWT(token);
613
+ } catch (error) {
614
+ throw new InvalidIssuerError(`${authority.replace(/\/+$/, "")}/identity_`, `<unparseable: ${error instanceof Error ? error.message : "unknown error"}>`);
615
+ }
616
+ const stripTrailingSlash = (s) => s.replace(/\/+$/, "");
617
+ const expected = `${stripTrailingSlash(authority)}/identity_`;
618
+ const actual = typeof payload.iss === "string" ? stripTrailingSlash(payload.iss) : undefined;
619
+ if (actual !== expected) {
620
+ throw new InvalidIssuerError(expected, payload.iss);
621
+ }
622
+ };
623
+ var getTokenExpiration = (accessToken) => {
624
+ try {
625
+ const parts = accessToken.split(".");
626
+ if (parts.length !== 3) {
627
+ return;
628
+ }
629
+ const payload = parts[1];
630
+ const base64 = payload.replace(/-/g, "+").replace(/_/g, "/");
631
+ const padded = base64 + "=".repeat((4 - base64.length % 4) % 4);
632
+ const decoded = atob(padded);
633
+ const claims = JSON.parse(decoded);
634
+ if (typeof claims.exp !== "number") {
635
+ return;
636
+ }
637
+ return new Date(claims.exp * 1000);
638
+ } catch {
639
+ return;
640
+ }
641
+ };
642
+
643
+ // ../auth/src/sessionIdentity.ts
644
+ var parseAuthFlow = (value) => value === "authorization_code" || value === "client_credentials" || value === "federated_credentials" ? value : undefined;
645
+ var decodeClaims = (accessToken) => {
646
+ const [error, claims] = catchError(() => parseJWT(accessToken));
647
+ return error ? undefined : claims;
648
+ };
649
+ var asString = (value) => typeof value === "string" && value.length > 0 ? value : undefined;
650
+ var resolveIdentityType = (claims, authFlow, email) => {
651
+ const subType = asString(claims?.sub_type);
652
+ if (subType) {
653
+ return subType.startsWith("service") ? "Application" : "User";
654
+ }
655
+ if (authFlow) {
656
+ return authFlow === "authorization_code" ? "User" : "Application";
657
+ }
658
+ if (email)
659
+ return "User";
660
+ if (asString(claims?.client_id) && !asString(claims?.sub)) {
661
+ return "Application";
662
+ }
663
+ return;
664
+ };
665
+ var looksLikeEmail = (value) => value?.includes("@") ?? false;
666
+ var pickEmail = (claims) => {
667
+ for (const candidate of [claims?.email, claims?.preferred_username]) {
668
+ const value = asString(candidate);
669
+ if (looksLikeEmail(value))
670
+ return value;
671
+ }
672
+ return;
673
+ };
674
+ var pickName = (claims) => {
675
+ const username = asString(claims?.preferred_username);
676
+ return asString(claims?.name) ?? (looksLikeEmail(username) ? undefined : username);
677
+ };
678
+ var resolveSessionIdentity = (accessToken, authFlow) => {
679
+ const claims = accessToken ? decodeClaims(accessToken) : undefined;
680
+ const email = pickEmail(claims);
681
+ const type = resolveIdentityType(claims, authFlow, email);
682
+ if (!type)
683
+ return;
684
+ const identity = { type };
685
+ if (authFlow)
686
+ identity.authFlow = authFlow;
687
+ if (type === "User") {
688
+ const userId = asString(claims?.sub);
689
+ if (userId)
690
+ identity.userId = userId;
691
+ if (email)
692
+ identity.userEmail = email;
693
+ const name = pickName(claims);
694
+ if (name)
695
+ identity.userName = name;
696
+ return identity;
697
+ }
698
+ const clientId = asString(claims?.client_id);
699
+ if (clientId)
700
+ identity.clientId = clientId;
701
+ return identity;
702
+ };
703
+
704
+ // ../auth/src/envAuth.ts
705
+ var ENV_AUTH_ENABLE_VAR = "UIPATH_CLI_ENABLE_ENV_AUTH";
706
+ var ENFORCE_ROBOT_AUTH_VAR = "UIPATH_CLI_ENFORCE_ROBOT_AUTH";
707
+ var ENV_AUTH_VARS = {
708
+ token: "UIPATH_CLI_AUTH_TOKEN",
709
+ organizationName: "UIPATH_CLI_ORGANIZATION_NAME",
710
+ organizationId: "UIPATH_CLI_ORGANIZATION_ID",
711
+ tenantName: "UIPATH_CLI_TENANT_NAME",
712
+ tenantId: "UIPATH_CLI_TENANT_ID"
713
+ };
714
+
715
+ class EnvAuthConfigError extends Error {
716
+ constructor(message) {
717
+ super(message);
718
+ this.name = "EnvAuthConfigError";
719
+ }
720
+ }
721
+ var isEnvAuthEnabled = () => process.env[ENV_AUTH_ENABLE_VAR] === "true";
722
+ var isRobotAuthEnforced = () => process.env[ENFORCE_ROBOT_AUTH_VAR] === "true";
723
+ var requireEnv = (name) => {
724
+ const value = process.env[name];
725
+ if (!value) {
726
+ throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true but ${name} is not set. ` + `Set ${name} to enable env-var authentication.`);
727
+ }
728
+ return value;
729
+ };
730
+ var OPAQUE_TOKEN_BASE_URL_VAR = "UIPATH_URL";
731
+ var resolveBaseUrl = (rawUrl, failureContext) => {
732
+ const [baseUrlError, baseUrl] = catchError(() => normalizeAndValidateBaseUrl(rawUrl));
733
+ if (baseUrlError) {
734
+ if (baseUrlError instanceof InvalidBaseUrlError) {
735
+ throw baseUrlError;
736
+ }
737
+ throw new EnvAuthConfigError(`${failureContext}: ` + `${baseUrlError instanceof Error ? baseUrlError.message : String(baseUrlError)}`);
738
+ }
739
+ return baseUrl;
740
+ };
741
+ var readAuthFromEnv = () => {
742
+ const accessToken = requireEnv(ENV_AUTH_VARS.token);
743
+ const organizationName = requireEnv(ENV_AUTH_VARS.organizationName);
744
+ const organizationId = requireEnv(ENV_AUTH_VARS.organizationId);
745
+ const tenantName = requireEnv(ENV_AUTH_VARS.tenantName);
746
+ const tenantId = requireEnv(ENV_AUTH_VARS.tenantId);
747
+ const [parseError, payload] = catchError(() => parseJWT(accessToken));
748
+ if (parseError) {
749
+ const parseErrorMessage = parseError instanceof Error ? parseError.message : String(parseError);
750
+ const rawUrl = process.env[OPAQUE_TOKEN_BASE_URL_VAR];
751
+ if (!rawUrl) {
752
+ throw new EnvAuthConfigError(`${ENV_AUTH_VARS.token} is not a JWT (treating it as an opaque token, ` + `e.g. a Personal Access Token). Set ${OPAQUE_TOKEN_BASE_URL_VAR} to the ` + `UiPath base URL if this is a PAT, or fix the token if it was meant to ` + `be a JWT (parse error: ${parseErrorMessage}).`);
753
+ }
754
+ const baseUrl2 = resolveBaseUrl(rawUrl, `Failed to validate ${OPAQUE_TOKEN_BASE_URL_VAR}`);
755
+ return {
756
+ loginStatus: "Logged in",
757
+ accessToken,
758
+ baseUrl: baseUrl2,
759
+ organizationName,
760
+ organizationId,
761
+ tenantName,
762
+ tenantId,
763
+ source: "env-vars" /* EnvironmentVariables */,
764
+ hint: "Token is opaque (not a JWT) - expiration and identity cannot be " + "determined locally. Commands will fail with 401 once it is revoked or " + `expired. If this was meant to be a JWT instead of a PAT, note: ${parseErrorMessage}`
765
+ };
766
+ }
767
+ const iss = payload.iss;
768
+ if (typeof iss !== "string" || iss.length === 0) {
769
+ throw new EnvAuthConfigError(`${ENV_AUTH_VARS.token} has no 'iss' claim; cannot determine ` + `the UiPath server. Ensure the token was issued by a UiPath identity server.`);
770
+ }
771
+ const baseUrl = resolveBaseUrl(iss, "Failed to derive server URL from token 'iss' claim");
772
+ const expiration = getTokenExpiration(accessToken);
773
+ const loginStatus = expiration && expiration <= new Date ? "Expired" : "Logged in";
774
+ const identity = resolveSessionIdentity(accessToken);
775
+ return {
776
+ loginStatus,
777
+ accessToken,
778
+ baseUrl,
779
+ organizationName,
780
+ organizationId,
781
+ tenantName,
782
+ tenantId,
783
+ expiration,
784
+ source: "env-vars" /* EnvironmentVariables */,
785
+ ...identity ? { identity } : {}
786
+ };
787
+ };
788
+
789
+ // ../auth/src/refreshCircuitBreaker.ts
790
+ var BREAKER_SUFFIX = ".refresh-state";
791
+ var BACKOFF_BASE_MS = 60000;
792
+ var BACKOFF_CAP_MS = 60 * 60 * 1000;
793
+ var SURFACE_WINDOW_MS = 60 * 60 * 1000;
794
+ async function refreshTokenFingerprint(refreshToken) {
795
+ const bytes = new TextEncoder().encode(refreshToken);
796
+ if (globalThis.crypto?.subtle) {
797
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
798
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
799
+ }
800
+ const { createHash } = await import("node:crypto");
801
+ return createHash("sha256").update(refreshToken).digest("hex").slice(0, 16);
802
+ }
803
+ function breakerPathFor(authPath) {
804
+ return `${authPath}${BREAKER_SUFFIX}`;
805
+ }
806
+ async function loadRefreshBreaker(authPath) {
807
+ const fs = getFileSystem();
808
+ try {
809
+ const content = await fs.readFile(breakerPathFor(authPath), "utf-8");
810
+ if (!content)
811
+ return {};
812
+ const parsed = JSON.parse(content);
813
+ return parsed && typeof parsed === "object" ? parsed : {};
814
+ } catch {
815
+ return {};
816
+ }
817
+ }
818
+ async function saveRefreshBreaker(authPath, state) {
819
+ try {
820
+ const fs = getFileSystem();
821
+ const path = breakerPathFor(authPath);
822
+ await fs.mkdir(fs.path.dirname(path));
823
+ const tempPath = `${path}.tmp`;
824
+ await fs.writeFile(tempPath, JSON.stringify(state));
825
+ await fs.rename(tempPath, path);
826
+ } catch {}
827
+ }
828
+ async function clearRefreshBreaker(authPath) {
829
+ const fs = getFileSystem();
830
+ const path = breakerPathFor(authPath);
831
+ try {
832
+ if (await fs.exists(path)) {
833
+ await fs.rm(path);
834
+ }
835
+ } catch {}
836
+ }
837
+ function nextBackoffMs(attempts) {
838
+ const shift = Math.max(0, attempts - 1);
839
+ return Math.min(BACKOFF_BASE_MS * 2 ** shift, BACKOFF_CAP_MS);
840
+ }
841
+ function shouldSurface(state, nowMs) {
842
+ if (state.lastSurfacedAtMs === undefined)
843
+ return true;
844
+ return nowMs - state.lastSurfacedAtMs >= SURFACE_WINDOW_MS;
845
+ }
846
+
847
+ // ../auth/src/robotClientFallback.ts
848
+ var DEFAULT_TIMEOUT_MS = 1000;
849
+ var CLOSE_TIMEOUT_MS = 500;
850
+ var ROBOT_USER_SERVICES_PIPE = "UiPathUserServices";
851
+ var ROBOT_USER_SERVICES_ALTERNATE_PIPE = `${ROBOT_USER_SERVICES_PIPE}Alternate`;
852
+ var PIPE_NAME_MAX_LENGTH = 103;
853
+ var getRobotIpcPipeNames = async () => {
854
+ const fs = getFileSystem();
855
+ const username = fs.env.getenv("USER") ?? fs.env.getenv("USERNAME");
856
+ if (!username) {
857
+ throw new Error("Unable to determine current username");
858
+ }
859
+ const tempPath = fs.env.getenv("TMPDIR") ?? "/tmp/";
860
+ return [ROBOT_USER_SERVICES_PIPE, ROBOT_USER_SERVICES_ALTERNATE_PIPE].map((baseName) => fs.path.join(tempPath, `${baseName}_${username}`).substring(0, PIPE_NAME_MAX_LENGTH));
861
+ };
862
+ var defaultIsRobotIpcAvailable = async () => {
863
+ if (process.platform === "win32") {
864
+ return true;
865
+ }
866
+ const [pipeNamesError, pipeNames] = await catchError(getRobotIpcPipeNames());
867
+ if (pipeNamesError || !pipeNames) {
868
+ return false;
869
+ }
870
+ const fs = getFileSystem();
871
+ for (const pipeName of pipeNames) {
872
+ const [existsError, exists] = await catchError(fs.exists(pipeName));
873
+ if (!existsError && exists === true) {
874
+ return true;
875
+ }
876
+ }
877
+ return false;
878
+ };
879
+ var withTimeout = (promise, timeoutMs) => new Promise((resolve, reject) => {
880
+ const timer = setTimeout(() => reject(new Error(`Robot IPC call timed out after ${timeoutMs}ms`)), timeoutMs);
881
+ promise.then((value) => {
882
+ clearTimeout(timer);
883
+ resolve(value);
884
+ }, (error) => {
885
+ clearTimeout(timer);
886
+ reject(error);
887
+ });
888
+ });
889
+ var parseResourceUrl = (url) => {
890
+ const [error, parsed] = catchError(() => new URL(url));
891
+ if (error || !parsed)
892
+ return;
893
+ const segments = parsed.pathname.split("/").filter(Boolean);
894
+ return {
895
+ baseUrl: parsed.origin,
896
+ organizationName: segments[0],
897
+ tenantName: segments[1]
898
+ };
899
+ };
900
+ var ROBOT_CLIENT_LOADER_KEY = Symbol.for("@uipath/auth/RobotClientLoader");
901
+ var registerRobotClientLoader = (loader) => {
902
+ globalThis[ROBOT_CLIENT_LOADER_KEY] = loader;
903
+ };
904
+ var getRegisteredRobotClientLoader = () => {
905
+ const loader = globalThis[ROBOT_CLIENT_LOADER_KEY];
906
+ return typeof loader === "function" ? loader : undefined;
907
+ };
908
+ var defaultLoadModule = async () => {
909
+ const hostLoader = getRegisteredRobotClientLoader();
910
+ if (!hostLoader) {
911
+ return;
912
+ }
913
+ const [error, mod] = await catchError(() => hostLoader());
914
+ if (error || !mod) {
915
+ return;
916
+ }
917
+ return mod;
918
+ };
919
+ var tryRobotClientFallback = async (options = {}) => {
920
+ if (isBrowser())
921
+ return;
922
+ if (!options.force) {
923
+ if (process.env.CI || process.env.GITHUB_ACTIONS) {
924
+ return;
925
+ }
926
+ if (process.env.UIPATH_URL) {
927
+ return;
928
+ }
929
+ }
930
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
931
+ const isRobotIpcAvailable = options.isRobotIpcAvailable ?? defaultIsRobotIpcAvailable;
932
+ const loadModule = options.loadModule ?? defaultLoadModule;
933
+ if (!await isRobotIpcAvailable()) {
934
+ return;
935
+ }
936
+ const mod = await loadModule();
937
+ if (!mod)
938
+ return;
939
+ const [ctorError, proxy] = catchError(() => new mod.RobotProxyConstructor);
940
+ if (ctorError || !proxy) {
941
+ return;
942
+ }
943
+ try {
944
+ const enabled = await withTimeout(proxy.interactiveConnectFlow.IsEnabled(), timeoutMs);
945
+ if (!enabled) {
946
+ return;
947
+ }
948
+ const [resourceUrl, accessToken] = await Promise.all([
949
+ withTimeout(proxy.accessProvider.GetResourceUrl("Orchestrator"), timeoutMs),
950
+ withTimeout(proxy.accessProvider.GetAccessToken("Orchestrator", false), timeoutMs)
951
+ ]);
952
+ if (!accessToken) {
953
+ return;
954
+ }
955
+ const parsedUrl = parseResourceUrl(resourceUrl);
956
+ if (!parsedUrl) {
957
+ return;
958
+ }
959
+ let organizationIdFromToken;
960
+ let tenantIdFromToken;
961
+ let issuerFromToken;
962
+ const [jwtError, claims] = catchError(() => parseJWT(accessToken));
963
+ if (!jwtError && claims) {
964
+ const rawOrgId = claims.prtId ?? claims.organizationId ?? claims.prt_id;
965
+ if (typeof rawOrgId === "string" && rawOrgId.length > 0) {
966
+ organizationIdFromToken = rawOrgId;
967
+ }
968
+ const tenantClaim = claims.tenantId ?? claims.tenant_id;
969
+ if (typeof tenantClaim === "string" && tenantClaim.length > 0) {
970
+ tenantIdFromToken = tenantClaim;
971
+ }
972
+ const issClaim = claims.iss;
973
+ if (typeof issClaim === "string" && issClaim.length > 0) {
974
+ issuerFromToken = issClaim;
975
+ }
976
+ }
977
+ return {
978
+ accessToken,
979
+ baseUrl: parsedUrl.baseUrl,
980
+ organizationName: parsedUrl.organizationName,
981
+ organizationId: organizationIdFromToken ?? parsedUrl.organizationName,
982
+ tenantName: parsedUrl.tenantName,
983
+ tenantId: tenantIdFromToken,
984
+ issuer: issuerFromToken
985
+ };
986
+ } catch {
987
+ return;
988
+ } finally {
989
+ await catchError(() => withTimeout(proxy.CloseAsync(), CLOSE_TIMEOUT_MS));
990
+ }
991
+ };
992
+
993
+ // ../auth/src/tokenRefresh.ts
994
+ var TOKEN_REFRESH_REAUTHENTICATE_MESSAGE = "Token refresh failed. Run 'uip login' to re-authenticate.";
995
+
996
+ class TokenRefreshOAuthError extends Error {
997
+ __brand = "TokenRefreshOAuthError";
998
+ constructor() {
999
+ super(TOKEN_REFRESH_REAUTHENTICATE_MESSAGE);
1000
+ this.name = "TokenRefreshOAuthError";
1001
+ }
1002
+ }
1003
+ function isTokenRefreshOAuthFailure(error) {
1004
+ return error instanceof TokenRefreshOAuthError;
1005
+ }
1006
+ var refreshAccessToken = async ({
1007
+ refreshToken,
1008
+ tokenEndpoint,
1009
+ clientId,
1010
+ expectedAuthority
1011
+ }) => {
1012
+ const tokenParams = new URLSearchParams({
1013
+ grant_type: "refresh_token",
1014
+ refresh_token: refreshToken,
1015
+ client_id: clientId
1016
+ });
1017
+ const tokenResponse = await fetch(tokenEndpoint, {
1018
+ method: "POST",
1019
+ headers: {
1020
+ "Content-Type": "application/x-www-form-urlencoded"
1021
+ },
1022
+ body: tokenParams
1023
+ });
1024
+ const tokenData = await tokenResponse.json();
1025
+ if (!tokenResponse.ok) {
1026
+ throw new TokenRefreshOAuthError;
1027
+ }
1028
+ const newAccessToken = tokenData.access_token;
1029
+ const newRefreshToken = tokenData.refresh_token;
1030
+ if (typeof newAccessToken !== "string" || typeof newRefreshToken !== "string") {
1031
+ throw new Error("Token refresh response is missing access_token or refresh_token");
1032
+ }
1033
+ if (expectedAuthority) {
1034
+ assertIssuerMatchesAuthority(newAccessToken, expectedAuthority);
1035
+ }
1036
+ return { accessToken: newAccessToken, refreshToken: newRefreshToken };
1037
+ };
1038
+
1039
+ // ../auth/src/types.ts
1040
+ var AUTH_FLOW_ENV_VAR = "UIPATH_AUTH_FLOW";
1041
+
1042
+ // ../auth/src/utils/envFile.ts
1043
+ var DEFAULT_AUTH_FILENAME = AUTH_FILENAME;
1044
+ var DEFAULT_ENV_FILENAME = `${UIPATH_HOME_DIR}/${AUTH_FILENAME}`;
1045
+ var KNOWN_ERROR_CODES = new Set([
1046
+ "EISDIR",
1047
+ "EACCES",
1048
+ "EPERM",
1049
+ "ELOOP",
1050
+ "ENOTDIR",
1051
+ "EUNKNOWN"
1052
+ ]);
1053
+ var errorCode = (err) => {
1054
+ if (err !== null && typeof err === "object" && "code" in err && typeof err.code === "string") {
1055
+ const raw = err.code;
1056
+ return KNOWN_ERROR_CODES.has(raw) ? raw : "EUNKNOWN";
1057
+ }
1058
+ return "EUNKNOWN";
1059
+ };
1060
+ var probeAsync = async (fs, candidate) => {
1061
+ try {
1062
+ const stats = await fs.stat(candidate);
1063
+ if (stats === null) {
1064
+ return { exists: false };
1065
+ }
1066
+ if (!stats.isFile()) {
1067
+ return {
1068
+ exists: false,
1069
+ unusable: {
1070
+ reason: "not-a-file",
1071
+ code: "EISDIR",
1072
+ message: `Path is not a regular file: ${candidate}`
1073
+ }
1074
+ };
1075
+ }
1076
+ return { exists: true };
1077
+ } catch (err) {
1078
+ return {
1079
+ exists: false,
1080
+ unusable: {
1081
+ reason: "unreadable",
1082
+ code: errorCode(err),
1083
+ message: err instanceof Error ? err.message : String(err)
1084
+ }
1085
+ };
1086
+ }
1087
+ };
1088
+ var resolveEnvFileLocationAsync = async (envFilePath = DEFAULT_ENV_FILENAME, opts) => {
1089
+ const fs = getFileSystem();
1090
+ if (fs.path.isAbsolute(envFilePath)) {
1091
+ const probe2 = await probeAsync(fs, envFilePath);
1092
+ return probe2.exists ? { exists: true, absolutePath: envFilePath, source: "absolute" } : {
1093
+ exists: false,
1094
+ absolutePath: envFilePath,
1095
+ source: "absolute",
1096
+ ...probe2.unusable ? { unusable: probe2.unusable } : {}
1097
+ };
1098
+ }
1099
+ const cwd = opts?.cwd ?? fs.env.cwd();
1100
+ let searchDir = cwd;
1101
+ while (true) {
1102
+ const candidate = fs.path.join(searchDir, envFilePath);
1103
+ const probe2 = await probeAsync(fs, candidate);
1104
+ if (probe2.exists) {
1105
+ return {
1106
+ exists: true,
1107
+ absolutePath: candidate,
1108
+ source: searchDir === cwd ? "cwd" : "ancestor"
1109
+ };
1110
+ }
1111
+ const parentDir = fs.path.dirname(searchDir);
1112
+ if (parentDir === searchDir) {
1113
+ break;
1114
+ }
1115
+ searchDir = parentDir;
1116
+ }
1117
+ const homePath = fs.path.join(fs.env.homedir(), envFilePath);
1118
+ const probe = await probeAsync(fs, homePath);
1119
+ if (probe.exists) {
1120
+ return { exists: true, absolutePath: homePath, source: "home" };
1121
+ }
1122
+ return {
1123
+ exists: false,
1124
+ absolutePath: homePath,
1125
+ source: "default",
1126
+ ...probe.unusable ? { unusable: probe.unusable } : {}
1127
+ };
1128
+ };
1129
+ var resolveEnvFilePathAsync = async (envFilePath = DEFAULT_ENV_FILENAME, opts) => {
1130
+ const location = await resolveEnvFileLocationAsync(envFilePath, opts);
1131
+ if (location.exists) {
1132
+ return { absolutePath: location.absolutePath };
1133
+ }
1134
+ return {
1135
+ absolutePath: undefined,
1136
+ errorMessage: location.source === "absolute" ? `Environment file not found: ${envFilePath}` : `Unable to locate environment file: ${envFilePath}. Run 'uip login' to authenticate.`
1137
+ };
1138
+ };
1139
+ var loadEnvFileAsync = async ({ envPath }) => {
1140
+ const fs = getFileSystem();
1141
+ const absolutePath = fs.path.isAbsolute(envPath) ? envPath : fs.path.join(fs.env.cwd(), envPath);
1142
+ if (!await fs.exists(absolutePath)) {
1143
+ throw new Error(`Environment file not found: ${envPath}`);
1144
+ }
1145
+ const content = await fs.readFile(absolutePath, "utf-8");
1146
+ if (content === null) {
1147
+ throw new Error(`Environment file not found: ${envPath}`);
1148
+ }
1149
+ const env = {};
1150
+ for (const line of content.split(`
1151
+ `)) {
1152
+ const trimmed = line.trim();
1153
+ if (!trimmed || trimmed.startsWith("#")) {
1154
+ continue;
1155
+ }
1156
+ const equalIndex = trimmed.indexOf("=");
1157
+ if (equalIndex === -1) {
1158
+ continue;
1159
+ }
1160
+ const key = trimmed.slice(0, equalIndex).trim();
1161
+ let value = trimmed.slice(equalIndex + 1).trim();
1162
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
1163
+ value = value.slice(1, -1);
1164
+ }
1165
+ env[key] = value;
1166
+ }
1167
+ return env;
1168
+ };
1169
+ var saveEnvFileAsync = async ({
1170
+ envPath,
1171
+ data,
1172
+ merge = true
1173
+ }) => {
1174
+ const fs = getFileSystem();
1175
+ const absolutePath = fs.path.isAbsolute(envPath) ? envPath : fs.path.join(fs.env.homedir(), envPath);
1176
+ let existingData = {};
1177
+ if (merge && await fs.exists(absolutePath)) {
1178
+ try {
1179
+ existingData = await loadEnvFileAsync({ envPath: absolutePath });
1180
+ } catch {}
1181
+ }
1182
+ const finalData = { ...existingData, ...data };
1183
+ const lines = [];
1184
+ for (const [key, value] of Object.entries(finalData)) {
1185
+ if (value === undefined) {
1186
+ continue;
1187
+ }
1188
+ const needsQuotes = value.includes(" ") || value.includes("#");
1189
+ const finalValue = needsQuotes ? `"${value}"` : value;
1190
+ lines.push(`${key}=${finalValue}`);
1191
+ }
1192
+ const content = `${lines.join(`
1193
+ `)}
1194
+ `;
1195
+ const dir = fs.path.dirname(absolutePath);
1196
+ await fs.mkdir(dir);
1197
+ const tempPath = `${absolutePath}.tmp`;
1198
+ await fs.writeFile(tempPath, content);
1199
+ await fs.rename(tempPath, absolutePath);
1200
+ };
1201
+
1202
+ // ../auth/src/loginStatus.ts
1203
+ var CredentialSource;
1204
+ ((CredentialSource2) => {
1205
+ CredentialSource2["SavedLogin"] = "saved-login";
1206
+ CredentialSource2["Robot"] = "robot";
1207
+ CredentialSource2["EnvironmentVariables"] = "env-vars";
1208
+ })(CredentialSource ||= {});
1209
+ var getLoginStatusAsync = async (options = {}) => {
1210
+ return getLoginStatusWithDeps(options);
1211
+ };
1212
+ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
1213
+ const {
1214
+ resolveEnvFilePath = resolveEnvFilePathAsync,
1215
+ loadEnvFile = loadEnvFileAsync,
1216
+ saveEnvFile = saveEnvFileAsync,
1217
+ getFs = getFileSystem,
1218
+ refreshToken: refreshTokenFn = refreshAccessToken,
1219
+ resolveConfig = resolveConfigAsync,
1220
+ robotFallback = tryRobotClientFallback,
1221
+ loadBreaker = loadRefreshBreaker,
1222
+ saveBreaker = saveRefreshBreaker,
1223
+ clearBreaker = clearRefreshBreaker
1224
+ } = deps;
1225
+ if (isRobotAuthEnforced()) {
1226
+ return resolveRobotEnforcedStatus(robotFallback);
1227
+ }
1228
+ if (isEnvAuthEnabled()) {
1229
+ return readAuthFromEnv();
1230
+ }
1231
+ const activeProfile = getActiveAuthProfile();
1232
+ const activeProfileFilePath = getActiveAuthProfileFilePath();
1233
+ const usingActiveProfile = activeProfile !== undefined && (options.envFilePath === undefined || options.envFilePath === activeProfileFilePath);
1234
+ const envFilePath = options.envFilePath ?? activeProfileFilePath ?? DEFAULT_ENV_FILENAME;
1235
+ const { ensureTokenValidityMinutes } = options;
1236
+ const { absolutePath } = await resolveEnvFilePath(envFilePath);
1237
+ if (absolutePath === undefined) {
1238
+ if (usingActiveProfile) {
1239
+ return {
1240
+ loginStatus: "Not logged in",
1241
+ hint: `No credentials found for profile "${activeProfile}". Run 'uip login --profile ${activeProfile}' to authenticate this profile.`
1242
+ };
1243
+ }
1244
+ return resolveBorrowedRobotStatus(robotFallback);
1245
+ }
1246
+ const loaded = await loadFileCredentials(loadEnvFile, absolutePath);
1247
+ if ("status" in loaded) {
1248
+ return loaded.status;
1249
+ }
1250
+ const { credentials } = loaded;
1251
+ const globalHint = () => usingActiveProfile ? Promise.resolve(undefined) : getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath);
1252
+ const expiration = getTokenExpiration(credentials.UIPATH_ACCESS_TOKEN);
1253
+ const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
1254
+ let tokens = {
1255
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
1256
+ refreshToken: credentials.UIPATH_REFRESH_TOKEN,
1257
+ expiration,
1258
+ lockReleaseFailed: false
1259
+ };
1260
+ const refreshToken = credentials.UIPATH_REFRESH_TOKEN;
1261
+ if (expiration && expiration <= outerThreshold && refreshToken) {
1262
+ const refreshed = await attemptRefresh({
1263
+ absolutePath,
1264
+ credentials,
1265
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
1266
+ refreshToken,
1267
+ expiration,
1268
+ ensureTokenValidityMinutes,
1269
+ getFs,
1270
+ loadEnvFile,
1271
+ saveEnvFile,
1272
+ refreshFn: refreshTokenFn,
1273
+ resolveConfig,
1274
+ loadBreaker,
1275
+ saveBreaker,
1276
+ clearBreaker,
1277
+ globalHint
1278
+ });
1279
+ if (refreshed.kind === "terminal") {
1280
+ return refreshed.status;
1281
+ }
1282
+ tokens = refreshed.tokens;
1283
+ }
1284
+ return buildFileStatus(tokens, credentials, globalHint);
1285
+ };
1286
+ async function resolveRobotEnforcedStatus(robotFallback) {
1287
+ if (isEnvAuthEnabled()) {
1288
+ throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
1289
+ }
1290
+ const robotCreds = await robotFallback({ force: true });
1291
+ if (!robotCreds) {
1292
+ return {
1293
+ loginStatus: "Not logged in",
1294
+ 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.`
1295
+ };
1296
+ }
1297
+ return buildRobotStatus(robotCreds);
1298
+ }
1299
+ async function resolveBorrowedRobotStatus(robotFallback) {
1300
+ const robotCreds = await robotFallback();
1301
+ return robotCreds ? buildRobotStatus(robotCreds) : { loginStatus: "Not logged in" };
1302
+ }
1303
+ async function loadFileCredentials(loadEnvFile, absolutePath) {
1304
+ let credentials;
1305
+ try {
1306
+ credentials = await loadEnvFile({ envPath: absolutePath });
1307
+ } catch (error) {
1308
+ if (isFileNotFoundError(error)) {
1309
+ return { status: { loginStatus: "Not logged in" } };
1310
+ }
1311
+ throw error;
1312
+ }
1313
+ if (!credentials.UIPATH_ACCESS_TOKEN) {
1314
+ return { status: { loginStatus: "Not logged in" } };
1315
+ }
1316
+ return { credentials };
1317
+ }
1318
+ async function getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath) {
1319
+ const fs = getFs();
1320
+ const globalPath = fs.path.join(fs.env.homedir(), envFilePath);
1321
+ if (absolutePath === globalPath)
1322
+ return;
1323
+ if (!await fs.exists(globalPath))
1324
+ return;
1325
+ try {
1326
+ const globalCreds = await loadEnvFile({ envPath: globalPath });
1327
+ if (!globalCreds.UIPATH_ACCESS_TOKEN)
1328
+ return;
1329
+ const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
1330
+ if (globalExp && globalExp <= new Date)
1331
+ return;
1332
+ 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.`;
1333
+ } catch {
1334
+ return;
1335
+ }
1336
+ }
1337
+ function computeExpirationThreshold(ensureTokenValidityMinutes) {
1338
+ return new Date(Date.now() + (ensureTokenValidityMinutes ?? 0) * 60 * 1000);
1339
+ }
1340
+ async function attemptRefresh(ctx) {
1341
+ const shortCircuit = await circuitBreakerShortCircuit(ctx);
1342
+ if (shortCircuit) {
1343
+ return { kind: "terminal", status: shortCircuit };
1344
+ }
1345
+ let release;
1346
+ try {
1347
+ release = await ctx.getFs().acquireLock(ctx.absolutePath);
1348
+ } catch (error) {
1349
+ return {
1350
+ kind: "terminal",
1351
+ status: await lockAcquireFailureStatus(ctx, error)
1352
+ };
1353
+ }
1354
+ let lockedFailure;
1355
+ let lockReleaseFailed = false;
1356
+ let success;
1357
+ try {
1358
+ const outcome = await runRefreshLocked({
1359
+ absolutePath: ctx.absolutePath,
1360
+ refreshToken: ctx.refreshToken,
1361
+ customAuthority: ctx.credentials.UIPATH_URL,
1362
+ ensureTokenValidityMinutes: ctx.ensureTokenValidityMinutes,
1363
+ loadEnvFile: ctx.loadEnvFile,
1364
+ saveEnvFile: ctx.saveEnvFile,
1365
+ refreshFn: ctx.refreshFn,
1366
+ resolveConfig: ctx.resolveConfig,
1367
+ loadBreaker: ctx.loadBreaker,
1368
+ saveBreaker: ctx.saveBreaker,
1369
+ clearBreaker: ctx.clearBreaker
1370
+ });
1371
+ if (outcome.kind === "fail") {
1372
+ lockedFailure = outcome.status;
1373
+ } else {
1374
+ success = outcome;
1375
+ }
1376
+ } finally {
1377
+ try {
1378
+ await release();
1379
+ } catch {
1380
+ lockReleaseFailed = true;
1381
+ }
1382
+ }
1383
+ if (lockedFailure) {
1384
+ const globalHint = await ctx.globalHint();
1385
+ const base = globalHint ? { ...lockedFailure, loginStatus: "Expired", hint: globalHint } : lockedFailure;
1386
+ return {
1387
+ kind: "terminal",
1388
+ status: lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base
1389
+ };
1390
+ }
1391
+ return {
1392
+ kind: "refreshed",
1393
+ tokens: {
1394
+ accessToken: success?.accessToken,
1395
+ refreshToken: success?.refreshToken,
1396
+ expiration: success?.expiration,
1397
+ tokenRefresh: success?.tokenRefresh,
1398
+ persistenceWarning: success?.persistenceWarning,
1399
+ lockReleaseFailed
1400
+ }
1401
+ };
1402
+ }
1403
+ async function buildFileStatus(tokens, credentials, globalHint) {
1404
+ const result = {
1405
+ loginStatus: tokens.expiration && tokens.expiration <= new Date ? "Expired" : "Logged in",
1406
+ accessToken: tokens.accessToken,
1407
+ refreshToken: tokens.refreshToken,
1408
+ baseUrl: credentials.UIPATH_URL,
1409
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
1410
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
1411
+ tenantName: credentials.UIPATH_TENANT_NAME,
1412
+ tenantId: credentials.UIPATH_TENANT_ID,
1413
+ expiration: tokens.expiration,
1414
+ source: "saved-login" /* SavedLogin */,
1415
+ ...identityFields(tokens.accessToken, credentials),
1416
+ ...tokens.persistenceWarning ? { hint: tokens.persistenceWarning, persistenceFailed: true } : {},
1417
+ ...tokens.lockReleaseFailed ? { lockReleaseFailed: true } : {},
1418
+ ...tokens.tokenRefresh ? { tokenRefresh: tokens.tokenRefresh } : {}
1419
+ };
1420
+ if (result.loginStatus === "Expired") {
1421
+ const hint = await globalHint();
1422
+ if (hint) {
1423
+ result.hint = hint;
1424
+ }
1425
+ }
1426
+ return result;
1427
+ }
1428
+ function identityFields(accessToken, credentials) {
1429
+ const identity = resolveSessionIdentity(accessToken, parseAuthFlow(credentials[AUTH_FLOW_ENV_VAR]));
1430
+ return identity ? { identity } : {};
1431
+ }
1432
+ function buildRobotStatus(robotCreds) {
1433
+ const identity = resolveSessionIdentity(robotCreds.accessToken);
1434
+ return {
1435
+ loginStatus: "Logged in",
1436
+ accessToken: robotCreds.accessToken,
1437
+ baseUrl: robotCreds.baseUrl,
1438
+ organizationName: robotCreds.organizationName,
1439
+ organizationId: robotCreds.organizationId,
1440
+ tenantName: robotCreds.tenantName,
1441
+ tenantId: robotCreds.tenantId,
1442
+ issuer: robotCreds.issuer,
1443
+ expiration: getTokenExpiration(robotCreds.accessToken),
1444
+ source: "robot" /* Robot */,
1445
+ ...identity ? { identity } : {}
1446
+ };
1447
+ }
1448
+ var isFileNotFoundError = (error) => {
1449
+ if (!(error instanceof Object))
1450
+ return false;
1451
+ return error.code === "ENOENT";
1452
+ };
1453
+ async function circuitBreakerShortCircuit(ctx) {
1454
+ const {
1455
+ absolutePath,
1456
+ refreshToken,
1457
+ accessToken,
1458
+ credentials,
1459
+ expiration,
1460
+ loadBreaker,
1461
+ saveBreaker,
1462
+ clearBreaker
1463
+ } = ctx;
1464
+ const fingerprint = await refreshTokenFingerprint(refreshToken);
1465
+ const breaker = await loadBreaker(absolutePath).catch(() => ({}));
1466
+ if (breaker.deadTokenFp && breaker.deadTokenFp !== fingerprint) {
1467
+ await clearBreaker(absolutePath);
1468
+ breaker.deadTokenFp = undefined;
1469
+ }
1470
+ const nowMs = Date.now();
1471
+ const tokenIsDead = breaker.deadTokenFp === fingerprint;
1472
+ const inBackoff = breaker.backoffUntilMs !== undefined && nowMs < breaker.backoffUntilMs;
1473
+ if (!tokenIsDead && !inBackoff)
1474
+ return;
1475
+ const globalHint = await ctx.globalHint();
1476
+ const suppressed = !shouldSurface(breaker, nowMs);
1477
+ if (!suppressed) {
1478
+ await saveBreaker(absolutePath, {
1479
+ ...breaker,
1480
+ lastSurfacedAtMs: nowMs
1481
+ });
1482
+ }
1483
+ 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>.";
1484
+ const backoffHint = "Token refresh is temporarily backed off after a recent network error and will retry automatically once the backoff window elapses.";
1485
+ return {
1486
+ loginStatus: globalHint ? "Expired" : "Refresh Failed",
1487
+ ...globalHint ? {
1488
+ accessToken,
1489
+ refreshToken,
1490
+ baseUrl: credentials.UIPATH_URL,
1491
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
1492
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
1493
+ tenantName: credentials.UIPATH_TENANT_NAME,
1494
+ tenantId: credentials.UIPATH_TENANT_ID,
1495
+ expiration,
1496
+ source: "saved-login" /* SavedLogin */,
1497
+ ...identityFields(accessToken, credentials)
1498
+ } : {},
1499
+ hint: globalHint ?? (tokenIsDead ? deadHint : backoffHint),
1500
+ refreshCircuitOpen: true,
1501
+ refreshTelemetrySuppressed: suppressed,
1502
+ tokenRefresh: { attempted: false, success: false }
1503
+ };
1504
+ }
1505
+ async function lockAcquireFailureStatus(ctx, error) {
1506
+ const msg = errorMessage(error);
1507
+ const globalHint = await ctx.globalHint();
1508
+ if (globalHint) {
1509
+ return {
1510
+ loginStatus: "Expired",
1511
+ accessToken: ctx.accessToken,
1512
+ refreshToken: ctx.refreshToken,
1513
+ baseUrl: ctx.credentials.UIPATH_URL,
1514
+ organizationName: ctx.credentials.UIPATH_ORGANIZATION_NAME,
1515
+ organizationId: ctx.credentials.UIPATH_ORGANIZATION_ID,
1516
+ tenantName: ctx.credentials.UIPATH_TENANT_NAME,
1517
+ tenantId: ctx.credentials.UIPATH_TENANT_ID,
1518
+ expiration: ctx.expiration,
1519
+ source: "saved-login" /* SavedLogin */,
1520
+ ...identityFields(ctx.accessToken, ctx.credentials),
1521
+ hint: globalHint,
1522
+ tokenRefresh: {
1523
+ attempted: false,
1524
+ success: false,
1525
+ errorMessage: `lock acquisition failed: ${msg}`
1526
+ }
1527
+ };
1528
+ }
1529
+ return {
1530
+ loginStatus: "Refresh Failed",
1531
+ 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.",
1532
+ tokenRefresh: {
1533
+ attempted: false,
1534
+ success: false,
1535
+ errorMessage: `lock acquisition failed: ${msg}`
1536
+ }
1537
+ };
1538
+ }
1539
+ async function runRefreshLocked(inputs) {
1540
+ const {
1541
+ absolutePath,
1542
+ refreshToken: callerRefreshToken,
1543
+ customAuthority,
1544
+ ensureTokenValidityMinutes,
1545
+ loadEnvFile,
1546
+ saveEnvFile,
1547
+ refreshFn,
1548
+ resolveConfig,
1549
+ loadBreaker,
1550
+ saveBreaker,
1551
+ clearBreaker
1552
+ } = inputs;
1553
+ const expirationThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
1554
+ let fresh;
1555
+ try {
1556
+ fresh = await loadEnvFile({ envPath: absolutePath });
1557
+ } catch (error) {
1558
+ return {
1559
+ kind: "fail",
1560
+ status: {
1561
+ loginStatus: "Refresh Failed",
1562
+ hint: "Could not read the auth file while refreshing. Retry, or run 'uip login' to re-authenticate.",
1563
+ tokenRefresh: {
1564
+ attempted: false,
1565
+ success: false,
1566
+ errorMessage: `auth file read failed: ${errorMessage(error)}`
1567
+ }
1568
+ }
1569
+ };
1570
+ }
1571
+ const freshAccess = fresh.UIPATH_ACCESS_TOKEN;
1572
+ const freshExp = freshAccess ? getTokenExpiration(freshAccess) : undefined;
1573
+ if (freshAccess && freshExp && freshExp > expirationThreshold) {
1574
+ await clearBreaker(absolutePath);
1575
+ return {
1576
+ kind: "ok",
1577
+ accessToken: freshAccess,
1578
+ refreshToken: fresh.UIPATH_REFRESH_TOKEN ?? callerRefreshToken,
1579
+ expiration: freshExp,
1580
+ tokenRefresh: { attempted: false, success: true }
1581
+ };
1582
+ }
1583
+ const tokenForIdP = fresh.UIPATH_REFRESH_TOKEN ?? callerRefreshToken;
1584
+ let refreshedAccess;
1585
+ let refreshedRefresh;
1586
+ try {
1587
+ const config = await resolveConfig({ customAuthority });
1588
+ const refreshed = await refreshFn({
1589
+ refreshToken: tokenForIdP,
1590
+ tokenEndpoint: config.tokenEndpoint,
1591
+ clientId: config.clientId,
1592
+ expectedAuthority: customAuthority
1593
+ });
1594
+ refreshedAccess = refreshed.accessToken;
1595
+ refreshedRefresh = refreshed.refreshToken;
1596
+ } catch (error) {
1597
+ const isOAuthFailure = isTokenRefreshOAuthFailure(error);
1598
+ 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.";
1599
+ const message = isOAuthFailure ? normalizeTokenRefreshFailure() : normalizeTokenRefreshUnavailableFailure();
1600
+ const fp = await refreshTokenFingerprint(tokenForIdP);
1601
+ if (isOAuthFailure) {
1602
+ await saveBreaker(absolutePath, { deadTokenFp: fp });
1603
+ } else {
1604
+ const prior = await loadBreaker(absolutePath).catch(() => ({}));
1605
+ const attempts = (prior.attempts ?? 0) + 1;
1606
+ await saveBreaker(absolutePath, {
1607
+ ...prior,
1608
+ deadTokenFp: undefined,
1609
+ attempts,
1610
+ backoffUntilMs: Date.now() + nextBackoffMs(attempts)
1611
+ });
1612
+ }
1613
+ return {
1614
+ kind: "fail",
1615
+ status: {
1616
+ loginStatus: "Refresh Failed",
1617
+ hint,
1618
+ tokenRefresh: {
1619
+ attempted: true,
1620
+ success: false,
1621
+ errorMessage: message
1622
+ }
1623
+ }
1624
+ };
1625
+ }
1626
+ const refreshedExp = getTokenExpiration(refreshedAccess);
1627
+ if (!refreshedExp || refreshedExp <= new Date) {
1628
+ return {
1629
+ kind: "fail",
1630
+ status: {
1631
+ loginStatus: "Refresh Failed",
1632
+ hint: "The identity server returned an unusable token. Run 'uip login' to re-authenticate.",
1633
+ tokenRefresh: {
1634
+ attempted: true,
1635
+ success: false,
1636
+ errorMessage: "refreshed token has no valid expiration claim"
1637
+ }
1638
+ }
1639
+ };
1640
+ }
1641
+ await clearBreaker(absolutePath);
1642
+ try {
1643
+ await saveEnvFile({
1644
+ envPath: absolutePath,
1645
+ data: {
1646
+ UIPATH_ACCESS_TOKEN: refreshedAccess,
1647
+ UIPATH_REFRESH_TOKEN: refreshedRefresh
1648
+ },
1649
+ merge: true
1650
+ });
1651
+ return {
1652
+ kind: "ok",
1653
+ accessToken: refreshedAccess,
1654
+ refreshToken: refreshedRefresh,
1655
+ expiration: refreshedExp,
1656
+ tokenRefresh: { attempted: true, success: true }
1657
+ };
1658
+ } catch (error) {
1659
+ const msg = errorMessage(error);
1660
+ return {
1661
+ kind: "ok",
1662
+ accessToken: refreshedAccess,
1663
+ refreshToken: refreshedRefresh,
1664
+ expiration: refreshedExp,
1665
+ persistenceWarning: `Access token refreshed in memory but could not be written to ${absolutePath}: ${msg}. The next CLI invocation will fail until the file can be updated — run 'uip login' to re-authenticate.`,
1666
+ tokenRefresh: {
1667
+ attempted: true,
1668
+ success: true,
1669
+ errorMessage: `persistence failed: ${msg}`
1670
+ }
1671
+ };
1672
+ }
1673
+ }
1674
+ function normalizeTokenRefreshFailure() {
1675
+ return "stored refresh token is invalid or expired";
1676
+ }
1677
+ function normalizeTokenRefreshUnavailableFailure() {
1678
+ return "token refresh failed before authentication completed";
1679
+ }
1680
+ function errorMessage(error) {
1681
+ return error instanceof Error ? error.message : String(error);
1682
+ }
1683
+
1684
+ // ../auth/src/authContext.ts
1685
+ var getAuthContext = async (options = {}) => {
1686
+ const status = await getLoginStatusAsync({
1687
+ ensureTokenValidityMinutes: options.ensureTokenValidityMinutes,
1688
+ envFilePath: options.envFilePath
1689
+ });
1690
+ if (status.loginStatus !== "Logged in" || !status.baseUrl || !status.accessToken) {
1691
+ throw new Error(status.hint ? `Not logged in. ${status.hint}` : "Not logged in. Run 'uip login' first.");
1692
+ }
1693
+ const tenantName = options.tenant ?? status.tenantName;
1694
+ if (options.requireOrganizationId && !status.organizationId) {
1695
+ throw new Error("Organization ID not available. Ensure you are logged in with an organization context.");
1696
+ }
1697
+ if (options.requireOrganizationName && !status.organizationName) {
1698
+ throw new Error("Organization name not available. Ensure you are logged in with an organization context.");
1699
+ }
1700
+ if (options.requireTenantId && !status.tenantId) {
1701
+ throw new Error("Tenant ID not available. Ensure UIPATH_TENANT_ID is set.");
1702
+ }
1703
+ if (options.requireTenantName && tenantName === undefined) {
1704
+ 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.");
1705
+ }
1706
+ return {
1707
+ baseUrl: status.baseUrl,
1708
+ accessToken: status.accessToken,
1709
+ organizationId: status.organizationId,
1710
+ organizationName: status.organizationName,
1711
+ tenantId: status.tenantId,
1712
+ tenantName
1713
+ };
1714
+ };
1715
+ var getAuthEnv = async (options = {}) => {
1716
+ const authEnv = {};
1717
+ let status;
1718
+ try {
1719
+ status = await getLoginStatusAsync(options);
1720
+ } catch {
1721
+ return { authEnv };
1722
+ }
1723
+ if (status.loginStatus === "Logged in" && status.accessToken) {
1724
+ authEnv.UIPATH_ACCESS_TOKEN = status.accessToken;
1725
+ if (status.baseUrl) {
1726
+ const org = status.organizationName || status.organizationId;
1727
+ const tenant = status.tenantName || status.tenantId;
1728
+ if (org && tenant) {
1729
+ authEnv.UIPATH_URL = `${status.baseUrl.replace(/\/+$/, "")}/${org}/${tenant}`;
1730
+ }
1731
+ }
1732
+ if (status.organizationId)
1733
+ authEnv.UIPATH_ORGANIZATION_ID = status.organizationId;
1734
+ if (status.organizationName)
1735
+ authEnv.UIPATH_ORGANIZATION_NAME = status.organizationName;
1736
+ if (status.tenantId)
1737
+ authEnv.UIPATH_TENANT_ID = status.tenantId;
1738
+ if (status.tenantName)
1739
+ authEnv.UIPATH_TENANT_NAME = status.tenantName;
1740
+ }
1741
+ return { authEnv, loginStatus: status };
1742
+ };
1743
+ // ../auth/src/tokenGrant.ts
1744
+ var requestClientCredentialsToken = async ({
1745
+ tokenEndpoint,
1746
+ baseUrl,
1747
+ params,
1748
+ buildError
1749
+ }) => {
1750
+ const tokenResponse = await fetch(tokenEndpoint, {
1751
+ method: "POST",
1752
+ headers: {
1753
+ "Content-Type": "application/x-www-form-urlencoded"
1754
+ },
1755
+ body: new URLSearchParams(params)
1756
+ });
1757
+ const [parseError, tokenData] = await catchError(tokenResponse.json());
1758
+ if (!tokenResponse.ok) {
1759
+ const data = parseError ? {} : tokenData ?? {};
1760
+ throw buildError({
1761
+ status: tokenResponse.status,
1762
+ errorType: data.error || "authentication_failed",
1763
+ errorDesc: data.error_description || "Unknown error"
1764
+ });
1765
+ }
1766
+ if (parseError || !tokenData) {
1767
+ throw buildError({
1768
+ status: tokenResponse.status,
1769
+ errorType: "invalid_response",
1770
+ errorDesc: "Token endpoint returned a non-JSON response."
1771
+ });
1772
+ }
1773
+ if (!tokenData.access_token) {
1774
+ throw buildError({
1775
+ status: tokenResponse.status,
1776
+ errorType: "invalid_response",
1777
+ errorDesc: "Token endpoint response did not include an access_token."
1778
+ });
1779
+ }
1780
+ return {
1781
+ UIPATH_ACCESS_TOKEN: tokenData.access_token,
1782
+ UIPATH_URL: baseUrl
1783
+ };
1784
+ };
1785
+
1786
+ // ../auth/src/clientCredentials.ts
1787
+ class ClientCredentialsAuthenticationError extends Error {
1788
+ status;
1789
+ constructor(message, status) {
1790
+ super(message);
1791
+ this.name = "ClientCredentialsAuthenticationError";
1792
+ this.status = status;
1793
+ }
1794
+ }
1795
+ var buildClientCredentialsError = ({
1796
+ status,
1797
+ errorType,
1798
+ errorDesc
1799
+ }) => {
1800
+ let troubleshooting = "";
1801
+ if (errorType === "invalid_client" || status === 401) {
1802
+ troubleshooting = `
1803
+
1804
+ Troubleshooting:` + `
1805
+ • Verify your Client ID is correct` + `
1806
+ • Ensure your Client Secret hasn't expired` + `
1807
+ • Check that the external application is enabled in UiPath` + `
1808
+ • Confirm you're using the correct authority URL`;
1809
+ } else if (errorType === "invalid_scope") {
1810
+ troubleshooting = `
1811
+
1812
+ Troubleshooting:` + `
1813
+ • The requested scopes may not be available for your account` + `
1814
+ • Try using default scopes or contact your UiPath administrator`;
1815
+ }
1816
+ return new ClientCredentialsAuthenticationError(`Client Credentials authentication failed (${status})
1817
+ ` + `Error: ${errorType}
1818
+ ` + `Details: ${errorDesc}${troubleshooting}`, status);
1819
+ };
1820
+ var clientCredentialsLogin = async ({
1821
+ clientId,
1822
+ clientSecret,
1823
+ scope,
1824
+ authority
1825
+ }) => {
1826
+ const config = await resolveConfigAsync({
1827
+ customAuthority: authority,
1828
+ customClientId: clientId,
1829
+ customClientSecret: clientSecret,
1830
+ customScopes: scope
1831
+ });
1832
+ const params = {
1833
+ grant_type: "client_credentials",
1834
+ client_id: config.clientId,
1835
+ client_secret: config.clientSecret ?? ""
1836
+ };
1837
+ if (config.scopes.length > 0) {
1838
+ params.scope = config.scopes.join(" ");
1839
+ }
1840
+ return await requestClientCredentialsToken({
1841
+ tokenEndpoint: config.tokenEndpoint,
1842
+ baseUrl: config.baseUrl,
1843
+ params,
1844
+ buildError: buildClientCredentialsError
1845
+ });
1846
+ };
1847
+ // ../auth/src/federatedCredentials.ts
1848
+ var JWT_BEARER_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
1849
+
1850
+ class FederatedCredentialsAuthenticationError extends Error {
1851
+ status;
1852
+ constructor(message, status) {
1853
+ super(message);
1854
+ this.name = "FederatedCredentialsAuthenticationError";
1855
+ this.status = status;
1856
+ }
1857
+ }
1858
+ var buildFederatedError = ({
1859
+ status,
1860
+ errorType,
1861
+ errorDesc
1862
+ }) => {
1863
+ let troubleshooting = "";
1864
+ if (errorType === "invalid_client" || errorType === "invalid_grant" || errorType === "invalid_request" || status === 401) {
1865
+ troubleshooting = `
1866
+
1867
+ Troubleshooting:` + `
1868
+ • Verify your Client ID matches the external application` + `
1869
+ • Confirm a federated credential is registered on the app whose` + `
1870
+ issuer, audience, and subject exactly match the token's claims` + `
1871
+ (list them: uip admin external-apps federated-credentials list <client-id>)` + `
1872
+ • Check the token was issued by the expected provider and has not expired` + `
1873
+ • Confirm you're using the correct authority URL`;
1874
+ } else if (errorType === "invalid_scope") {
1875
+ troubleshooting = `
1876
+
1877
+ Troubleshooting:` + `
1878
+ • The requested scopes may not be available for your application` + `
1879
+ • Try using default scopes or contact your UiPath administrator`;
1880
+ }
1881
+ return new FederatedCredentialsAuthenticationError(`Federated Credentials authentication failed (${status})
1882
+ ` + `Error: ${errorType}
1883
+ ` + `Details: ${errorDesc}${troubleshooting}`, status);
1884
+ };
1885
+ var federatedCredentialsLogin = async ({
1886
+ clientId,
1887
+ clientAssertion,
1888
+ scope,
1889
+ authority
1890
+ }) => {
1891
+ const config = await resolveConfigAsync({
1892
+ customAuthority: authority,
1893
+ customClientId: clientId,
1894
+ customClientAssertion: clientAssertion,
1895
+ customScopes: scope
1896
+ });
1897
+ const params = {
1898
+ grant_type: "client_credentials",
1899
+ client_id: config.clientId,
1900
+ client_assertion: clientAssertion,
1901
+ client_assertion_type: JWT_BEARER_ASSERTION_TYPE
1902
+ };
1903
+ if (config.scopes.length > 0) {
1904
+ params.scope = config.scopes.join(" ");
1905
+ }
1906
+ return await requestClientCredentialsToken({
1907
+ tokenEndpoint: config.tokenEndpoint,
1908
+ baseUrl: config.baseUrl,
1909
+ params,
1910
+ buildError: buildFederatedError
1911
+ });
1912
+ };
1913
+ // ../auth/src/tenantSelection.ts
1914
+ var LOGIN_STATUS_HINT = "Run 'uip login status' to see the organization the CLI is signed in to.";
1915
+ var organizationHint = (organizationId) => `The request used '${organizationId}' as the organization. ${LOGIN_STATUS_HINT}`;
1916
+ var IDENTIFIER_STATUSES = new Set([400, 403, 404]);
1917
+ var describeNonJsonResponse = (organizationId, response, parseError) => {
1918
+ if (response.redirected) {
1919
+ return `Could not find organization '${organizationId}': the request was ` + `redirected to a sign-in page instead of the organization's tenant ` + `list. ${LOGIN_STATUS_HINT}`;
1920
+ }
1921
+ const contentType = response.headers.get("content-type") ?? "unknown";
1922
+ return `The organization service returned a '${contentType}' response instead ` + `of JSON: ${parseError.message}. ${organizationHint(organizationId)}`;
1923
+ };
1924
+ var fetchTenantsAndOrganizations = async (baseUrl, accessToken, organizationId) => {
1925
+ const url = `${baseUrl}/${organizationId}/portal_/api/filtering/leftnav/tenantsAndOrganizationInfo`;
1926
+ const response = await fetch(url, {
1927
+ headers: {
1928
+ Authorization: `Bearer ${accessToken}`
1929
+ }
1930
+ });
1931
+ if (!response.ok) {
1932
+ if (response.status === 401) {
1933
+ throw new Error(`Unauthorized: the access token was rejected, it was not ` + `issued for organization '${organizationId}', or ` + `'${organizationId}' was not accepted as an organization ` + `URL segment in this environment. ` + LOGIN_STATUS_HINT);
1934
+ }
1935
+ const errorText = await response.text();
1936
+ const message = `Failed to get tenants and organizations: ${response.status} ${errorText}`;
1937
+ throw new Error(IDENTIFIER_STATUSES.has(response.status) ? `${message}. ${organizationHint(organizationId)}` : message);
1938
+ }
1939
+ const [parseError, data] = await catchError(response.json());
1940
+ if (parseError) {
1941
+ throw new Error(describeNonJsonResponse(organizationId, response, parseError));
1942
+ }
1943
+ return data;
1944
+ };
1945
+
1946
+ // ../auth/src/selectTenant.ts
1947
+ var TENANT_SELECTION_REQUIRED_CODE = "TENANT_SELECTION_REQUIRED";
1948
+ var INVALID_TENANT_CODE = "INVALID_TENANT";
1949
+
1950
+ class TenantSelectionError extends Error {
1951
+ availableTenants;
1952
+ organizationName;
1953
+ constructor(message, organizationName, availableTenants) {
1954
+ super(message);
1955
+ this.organizationName = organizationName;
1956
+ this.availableTenants = availableTenants;
1957
+ }
1958
+ }
1959
+
1960
+ class TenantSelectionRequiredError extends TenantSelectionError {
1961
+ code = TENANT_SELECTION_REQUIRED_CODE;
1962
+ constructor(organizationName, availableTenants) {
1963
+ super(`Multiple tenants available in organization "${organizationName}"; none selected.`, organizationName, availableTenants);
1964
+ this.name = "TenantSelectionRequiredError";
1965
+ }
1966
+ }
1967
+
1968
+ class InvalidTenantError extends TenantSelectionError {
1969
+ code = INVALID_TENANT_CODE;
1970
+ requestedTenant;
1971
+ constructor(requestedTenant, organizationName, availableTenants) {
1972
+ super(`Invalid tenant requested: "${requestedTenant}"
1973
+ ` + `Organization: ${organizationName}
1974
+ ` + `Available tenants: ${availableTenants.join(", ")}`, organizationName, availableTenants);
1975
+ this.name = "InvalidTenantError";
1976
+ this.requestedTenant = requestedTenant;
1977
+ }
1978
+ }
1979
+ var TENANT_SELECTION_CODES = new Set([
1980
+ TENANT_SELECTION_REQUIRED_CODE,
1981
+ INVALID_TENANT_CODE
1982
+ ]);
1983
+ function isTenantSelectionError(error) {
1984
+ if (!(error instanceof Object) || !("code" in error)) {
1985
+ return false;
1986
+ }
1987
+ const code = error.code;
1988
+ return typeof code === "string" && TENANT_SELECTION_CODES.has(code) && Array.isArray(error.availableTenants);
1989
+ }
1990
+ var selectTenantWithDeps = async (baseUrl, accessToken, organizationId, targetTenantName, interactive, deps = {}) => {
1991
+ const {
1992
+ fetchTenantsAndOrgs = fetchTenantsAndOrganizations,
1993
+ selectFromList
1994
+ } = deps;
1995
+ const data = await fetchTenantsAndOrgs(baseUrl, accessToken, organizationId);
1996
+ const { tenants, organization } = data;
1997
+ if (!tenants || tenants.length === 0) {
1998
+ throw new Error("No tenants found for this organization");
1999
+ }
2000
+ const tenantNames = tenants.map((tenant) => tenant.name);
2001
+ let selectedIndex;
2002
+ if (targetTenantName !== undefined) {
2003
+ selectedIndex = tenants.findIndex((tenant) => tenant.name === targetTenantName);
2004
+ if (selectedIndex === -1) {
2005
+ throw new InvalidTenantError(targetTenantName, organization.name, tenantNames);
2006
+ }
2007
+ } else if (tenants.length === 1) {
2008
+ selectedIndex = 0;
2009
+ } else if (interactive) {
2010
+ if (!selectFromList) {
2011
+ throw new Error("Interactive tenant selection requires a `selectFromList` callback. " + "Pass one via the `deps` argument of `selectTenantWithDeps`.");
2012
+ }
2013
+ selectedIndex = await selectFromList(tenantNames, "Select a tenant:");
2014
+ } else {
2015
+ throw new TenantSelectionRequiredError(organization.name, tenantNames);
2016
+ }
2017
+ const selectedTenant = tenants[selectedIndex];
2018
+ return [selectedTenant.name, selectedTenant.id, organization.name];
2019
+ };
2020
+
2021
+ // ../auth/src/interactive.ts
2022
+ var interactiveLoginWithDeps = async (options, deps) => {
2023
+ const {
2024
+ resolveConfig = resolveConfigAsync,
2025
+ clientCredentials = clientCredentialsLogin,
2026
+ federatedCredentials = federatedCredentialsLogin,
2027
+ auth = authenticate,
2028
+ saveEnvFile = saveEnvFileAsync,
2029
+ loadEnvFile = loadEnvFileAsync,
2030
+ getFs = getFileSystem,
2031
+ jwtParser = parseJWT,
2032
+ issuerAsserter = assertIssuerMatchesAuthority,
2033
+ tenantSelector = (baseUrl, accessToken, organizationId, tenantName, interactive2) => selectTenantWithDeps(baseUrl, accessToken, organizationId, tenantName, interactive2, { selectFromList: options.selectFromList })
2034
+ } = deps;
2035
+ const {
2036
+ envFilePath,
2037
+ scope,
2038
+ authority,
2039
+ clientId,
2040
+ clientSecret,
2041
+ clientAssertion,
2042
+ tenant,
2043
+ organization,
2044
+ interactive,
2045
+ onEvent,
2046
+ timeoutMs,
2047
+ noBrowser,
2048
+ signal
2049
+ } = options;
2050
+ const emit = (event) => {
2051
+ if (!onEvent)
2052
+ return;
2053
+ try {
2054
+ onEvent(event);
2055
+ } catch {}
2056
+ };
2057
+ const deliverAuthUrl = (url) => {
2058
+ try {
2059
+ onEvent?.({ type: "auth-url", url });
2060
+ } catch (error) {
2061
+ throw new Error("Failed to deliver the authorize URL to the onEvent subscriber; " + "cannot continue headless login.", { cause: error });
2062
+ }
2063
+ };
2064
+ const config = await resolveConfig({
2065
+ customAuthority: authority,
2066
+ customClientId: clientId,
2067
+ customClientSecret: clientSecret,
2068
+ customClientAssertion: clientAssertion
2069
+ });
2070
+ const { clientSecret: resolvedSecret } = config;
2071
+ if (noBrowser && !resolvedSecret && !clientAssertion && !onEvent) {
2072
+ throw new Error("noBrowser login requires an onEvent subscriber to receive the " + "auth-url event — the authorize URL is delivered through it.");
2073
+ }
2074
+ const authFlow = clientAssertion ? "federated_credentials" : resolvedSecret ? "client_credentials" : "authorization_code";
2075
+ const authPromise = clientAssertion ? (async () => {
2076
+ return await federatedCredentials({
2077
+ clientId: config.clientId,
2078
+ clientAssertion,
2079
+ authority: config.baseUrl,
2080
+ scope
2081
+ });
2082
+ })() : resolvedSecret ? (async () => {
2083
+ return await clientCredentials({
2084
+ clientId: config.clientId,
2085
+ clientSecret: resolvedSecret,
2086
+ authority: config.baseUrl,
2087
+ scope
2088
+ });
2089
+ })() : (async () => {
2090
+ const authTokens = await auth({
2091
+ baseUrl: authority,
2092
+ clientId,
2093
+ clientSecret,
2094
+ scope,
2095
+ organization,
2096
+ timeoutMs,
2097
+ noBrowser,
2098
+ signal,
2099
+ onAuthUrl: noBrowser ? (url) => deliverAuthUrl(url) : undefined,
2100
+ onPortReclaimed: ({ pid }) => emit({
2101
+ type: "port-reclaimed",
2102
+ message: `A previous 'uip login'${pid === undefined ? "" : ` (PID ${pid})`} was still holding the callback port ` + `(${new URL(DEFAULT_REDIRECT_URI).port}) and was released; continuing with this login.`
2103
+ })
2104
+ });
2105
+ return {
2106
+ UIPATH_ACCESS_TOKEN: authTokens.accessToken,
2107
+ UIPATH_REFRESH_TOKEN: authTokens.refreshToken
2108
+ };
2109
+ })();
2110
+ const [authError, tokens] = await catchError(authPromise);
2111
+ if (authError) {
2112
+ throw authError;
2113
+ }
2114
+ issuerAsserter(tokens.UIPATH_ACCESS_TOKEN, config.baseUrl);
2115
+ const credentials = {
2116
+ ...tokens,
2117
+ UIPATH_URL: config.baseUrl,
2118
+ [AUTH_FLOW_ENV_VAR]: authFlow
2119
+ };
2120
+ if (authFlow !== "authorization_code") {
2121
+ credentials.UIPATH_REFRESH_TOKEN = undefined;
2122
+ }
2123
+ try {
2124
+ const tokenData = jwtParser(tokens.UIPATH_ACCESS_TOKEN);
2125
+ const orgId = tokenData.prtId || tokenData.organizationId || tokenData.prt_id;
2126
+ if (typeof orgId !== "string" || orgId.length === 0) {
2127
+ throw new Error("Organization ID not available from login token. Cannot establish an active tenant.");
2128
+ }
2129
+ credentials.UIPATH_ORGANIZATION_ID = orgId;
2130
+ if (organization) {
2131
+ credentials.UIPATH_ORGANIZATION_NAME = organization;
2132
+ }
2133
+ const [tenantName, tenantId, orgName] = await tenantSelector(config.baseUrl, tokens.UIPATH_ACCESS_TOKEN, orgId, tenant, interactive);
2134
+ credentials.UIPATH_ORGANIZATION_NAME = orgName;
2135
+ credentials.UIPATH_TENANT_NAME = tenantName;
2136
+ credentials.UIPATH_TENANT_ID = tenantId;
2137
+ } catch (error) {
2138
+ if (!isTenantSelectionError(error)) {
2139
+ emit({
2140
+ type: "tenant-fetch-failed",
2141
+ message: error instanceof Error ? error.message : String(error)
2142
+ });
2143
+ }
2144
+ throw error;
2145
+ }
2146
+ const fs = getFs();
2147
+ const requestedPath = envFilePath ?? DEFAULT_ENV_FILENAME;
2148
+ let savePath = requestedPath;
2149
+ let savedLocally = false;
2150
+ if (!fs.path.isAbsolute(savePath)) {
2151
+ let searchDir = fs.env.cwd();
2152
+ while (true) {
2153
+ const candidate = fs.path.join(searchDir, savePath);
2154
+ if (await fs.exists(candidate)) {
2155
+ try {
2156
+ const existing = await loadEnvFile({
2157
+ envPath: candidate
2158
+ });
2159
+ if (existing.UIPATH_ACCESS_TOKEN) {
2160
+ savePath = candidate;
2161
+ savedLocally = true;
2162
+ break;
2163
+ }
2164
+ } catch {}
2165
+ }
2166
+ const parentDir = fs.path.dirname(searchDir);
2167
+ if (parentDir === searchDir) {
2168
+ break;
2169
+ }
2170
+ searchDir = parentDir;
2171
+ }
2172
+ }
2173
+ let saveRelease;
2174
+ try {
2175
+ if (typeof fs.acquireLock === "function") {
2176
+ saveRelease = await fs.acquireLock(savePath);
2177
+ }
2178
+ } catch {
2179
+ saveRelease = undefined;
2180
+ }
2181
+ try {
2182
+ await saveEnvFile({
2183
+ envPath: savePath,
2184
+ data: credentials,
2185
+ merge: true
2186
+ });
2187
+ } finally {
2188
+ if (saveRelease) {
2189
+ await saveRelease().catch(() => {});
2190
+ }
2191
+ }
2192
+ const reportedPath = fs.path.isAbsolute(savePath) ? savePath : fs.path.join(fs.env.homedir(), savePath);
2193
+ emit({
2194
+ type: "saved",
2195
+ path: reportedPath,
2196
+ locality: savedLocally ? "local" : "global"
2197
+ });
2198
+ return credentials;
2199
+ };
2200
+ var interactiveLogin = async (options) => {
2201
+ return interactiveLoginWithDeps(options, {});
2202
+ };
2203
+ // ../auth/src/logout.ts
2204
+ async function logoutWithDeps(options, deps = {}) {
2205
+ const {
2206
+ resolveEnvFilePath = resolveEnvFilePathAsync,
2207
+ getFileSystem: getFs = getFileSystem,
2208
+ clearBreaker = clearRefreshBreaker,
2209
+ getActiveProfileFilePath = getActiveAuthProfileFilePath
2210
+ } = deps;
2211
+ const fs = getFs();
2212
+ const { absolutePath } = await resolveEnvFilePath(options.file ?? getActiveProfileFilePath());
2213
+ if (absolutePath && await fs.exists(absolutePath)) {
2214
+ let release;
2215
+ try {
2216
+ if (typeof fs.acquireLock === "function") {
2217
+ release = await fs.acquireLock(absolutePath);
2218
+ }
2219
+ } catch {
2220
+ release = undefined;
2221
+ }
2222
+ try {
2223
+ await fs.rm(absolutePath);
2224
+ await clearBreaker(absolutePath);
2225
+ } finally {
2226
+ if (release) {
2227
+ await release().catch(() => {});
2228
+ }
2229
+ }
2230
+ return {
2231
+ success: true,
2232
+ message: `Logged out successfully. Removed ${absolutePath}`,
2233
+ removedPath: absolutePath
2234
+ };
2235
+ }
2236
+ return {
2237
+ success: false,
2238
+ message: "No credentials file found. You are already logged out.",
2239
+ reason: "no_credentials_file"
2240
+ };
2241
+ }
2242
+ async function logout(options) {
2243
+ return logoutWithDeps(options);
2244
+ }
2245
+
2246
+ // ../auth/src/index.ts
2247
+ var authenticate = async ({
2248
+ baseUrl,
2249
+ clientId,
2250
+ clientSecret,
2251
+ redirectUri,
2252
+ scope,
2253
+ organization,
2254
+ timeoutMs,
2255
+ noBrowser,
2256
+ onAuthUrl,
2257
+ signal,
2258
+ onPortReclaimed
2259
+ }) => {
2260
+ const config = await resolveConfigAsync({
2261
+ customAuthority: baseUrl,
2262
+ customClientId: clientId,
2263
+ customClientSecret: clientSecret,
2264
+ customScopes: scope
2265
+ });
2266
+ const {
2267
+ authorizationEndpoint,
2268
+ tokenEndpoint,
2269
+ clientId: resolvedClientId,
2270
+ clientSecret: resolvedClientSecret,
2271
+ scopes: resolvedScopes
2272
+ } = config;
2273
+ const { code_challenge, code_verifier, state } = await getOidcParams();
2274
+ let effectiveRedirectUri;
2275
+ if (redirectUri) {
2276
+ effectiveRedirectUri = redirectUri.toString();
2277
+ } else if (isBrowser()) {
2278
+ const origin = getGlobalThis()?.window?.location?.origin ?? "";
2279
+ effectiveRedirectUri = `${origin}/oidc/login`;
2280
+ } else {
2281
+ effectiveRedirectUri = DEFAULT_REDIRECT_URI;
2282
+ }
2283
+ const effectiveRedirectUriUrl = new URL(effectiveRedirectUri);
2284
+ const authParams = new URLSearchParams({
2285
+ client_id: resolvedClientId,
2286
+ redirect_uri: effectiveRedirectUriUrl.toString(),
2287
+ response_type: "code",
2288
+ scope: resolvedScopes.join(" "),
2289
+ code_challenge,
2290
+ code_challenge_method: "S256",
2291
+ state
2292
+ });
2293
+ if (organization) {
2294
+ if (/[\s:]/.test(organization)) {
2295
+ throw new Error(`Invalid organization name: "${organization}". Whitespace and colons are not allowed; use the organization's logical name (e.g. "my-org").`);
2296
+ }
2297
+ authParams.set("acr_values", `tenantName:${organization}`);
2298
+ }
2299
+ const authUrl = `${authorizationEndpoint}?${authParams.toString()}`;
2300
+ let strategy;
2301
+ if (isBrowser()) {
2302
+ const { BrowserAuthStrategy } = await import("./browser-strategy-6atc7v8s.js");
2303
+ strategy = new BrowserAuthStrategy;
2304
+ } else {
2305
+ const { NodeAuthStrategy } = await import("./node-strategy-gc4sg6a2.js");
2306
+ strategy = new NodeAuthStrategy;
2307
+ }
2308
+ const code = await strategy.execute(authUrl, effectiveRedirectUriUrl, state, {
2309
+ timeoutMs,
2310
+ noBrowser,
2311
+ onAuthUrl,
2312
+ signal,
2313
+ onPortReclaimed
2314
+ });
2315
+ return await exchangeCodeForTokens({
2316
+ code,
2317
+ codeVerifier: code_verifier,
2318
+ redirectUri: effectiveRedirectUriUrl,
2319
+ clientId: resolvedClientId,
2320
+ clientSecret: resolvedClientSecret,
2321
+ tokenEndpoint
2322
+ });
2323
+ };
2324
+
2325
+ export { setAuthFileConfig, InvalidBaseUrlError, DEFAULT_AUTH_PROFILE, AuthProfileValidationError, normalizeAuthProfileName, setActiveAuthProfile, clearActiveAuthProfile, getActiveAuthProfile, runWithAuthProfile, resolveAuthProfileFilePath, getActiveAuthProfileFilePath, parseJWT, parseAuthFlow, resolveSessionIdentity, ENV_AUTH_ENABLE_VAR, ENFORCE_ROBOT_AUTH_VAR, ENV_AUTH_VARS, EnvAuthConfigError, isEnvAuthEnabled, isRobotAuthEnforced, readAuthFromEnv, refreshTokenFingerprint, loadRefreshBreaker, saveRefreshBreaker, clearRefreshBreaker, registerRobotClientLoader, TokenRefreshOAuthError, isTokenRefreshOAuthFailure, refreshAccessToken, AUTH_FLOW_ENV_VAR, DEFAULT_AUTH_FILENAME, DEFAULT_ENV_FILENAME, resolveEnvFileLocationAsync, resolveEnvFilePathAsync, loadEnvFileAsync, saveEnvFileAsync, CredentialSource, getLoginStatusAsync, getLoginStatusWithDeps, getAuthContext, getAuthEnv, ClientCredentialsAuthenticationError, clientCredentialsLogin, JWT_BEARER_ASSERTION_TYPE, FederatedCredentialsAuthenticationError, federatedCredentialsLogin, fetchTenantsAndOrganizations, TENANT_SELECTION_REQUIRED_CODE, INVALID_TENANT_CODE, TenantSelectionError, TenantSelectionRequiredError, InvalidTenantError, isTenantSelectionError, selectTenantWithDeps, interactiveLoginWithDeps, interactiveLogin, logoutWithDeps, logout, authenticate };
2326
+
2327
+ //# debugId=E193A5CF0DF55D1D64756E2164756E21