@equinor/fusion-framework-cli 11.0.0-next.15 → 11.0.0-next.16

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 (212) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/bin/build/bin.mjs +1 -0
  3. package/bin/build/cli.mjs +7 -0
  4. package/bin/build/create-auth-client-Ds0jZb_X.js +1 -0
  5. package/bin/build/index-DZEz5jYv.js +1 -0
  6. package/bin/cli.mjs +1 -1
  7. package/dist/esm/lib/app/app-config.js.map +1 -1
  8. package/dist/esm/lib/app/app-manifest.js.map +1 -1
  9. package/dist/esm/lib/app/app-package.js +1 -1
  10. package/dist/esm/lib/app/app-package.js.map +1 -1
  11. package/dist/esm/lib/app/merge-app-config.js +11 -5
  12. package/dist/esm/lib/app/merge-app-config.js.map +1 -1
  13. package/dist/esm/lib/app/merge-app-manifest.js +2 -2
  14. package/dist/esm/lib/app/merge-app-manifest.js.map +1 -1
  15. package/dist/esm/lib/index.js +3 -1
  16. package/dist/esm/lib/index.js.map +1 -1
  17. package/dist/esm/lib/merge-dev-server-config.js +2 -20
  18. package/dist/esm/lib/merge-dev-server-config.js.map +1 -1
  19. package/dist/esm/lib/portal/create-portal-manifest.js.map +1 -1
  20. package/dist/esm/lib/portal/load-portal-manifest.js +2 -2
  21. package/dist/esm/lib/portal/load-portal-manifest.js.map +1 -1
  22. package/dist/esm/lib/portal/load-portal-schema.js.map +1 -1
  23. package/dist/esm/lib/utils/index.js +1 -0
  24. package/dist/esm/lib/utils/index.js.map +1 -1
  25. package/dist/esm/lib/utils/resolve-annotations.js +2 -2
  26. package/dist/esm/lib/utils/resolve-annotations.js.map +1 -1
  27. package/dist/esm/lib/utils/resolve-devops-annotations.js +2 -2
  28. package/dist/esm/lib/utils/resolve-devops-annotations.js.map +1 -1
  29. package/dist/esm/lib/utils/resolve-git-commit-sha.js +1 -0
  30. package/dist/esm/lib/utils/resolve-git-commit-sha.js.map +1 -1
  31. package/dist/esm/lib/utils/resolve-github-annotations.js +2 -2
  32. package/dist/esm/lib/utils/resolve-github-annotations.js.map +1 -1
  33. package/dist/esm/version.js +1 -1
  34. package/dist/types/bin/app-build.d.ts +2 -2
  35. package/dist/types/bin/app-check.d.ts +2 -2
  36. package/dist/types/bin/app-config-publish.d.ts +2 -2
  37. package/dist/types/bin/app-config.d.ts +3 -3
  38. package/dist/types/bin/app-dev.d.ts +1 -1
  39. package/dist/types/bin/app-manifest.d.ts +3 -3
  40. package/dist/types/bin/app-pack.d.ts +1 -1
  41. package/dist/types/bin/app-tag.d.ts +2 -2
  42. package/dist/types/bin/app-upload.d.ts +2 -2
  43. package/dist/types/bin/helpers/load-vite-config.d.ts +1 -2
  44. package/dist/types/bin/helpers/resolve-app-config.d.ts +3 -3
  45. package/dist/types/bin/helpers/resolve-app-manifest.d.ts +3 -3
  46. package/dist/types/bin/helpers/resolve-portal-config.d.ts +3 -3
  47. package/dist/types/bin/helpers/resolve-portal-manifest.d.ts +3 -4
  48. package/dist/types/bin/helpers/resolve-project-package.d.ts +2 -2
  49. package/dist/types/bin/index.d.ts +9 -0
  50. package/dist/types/bin/pack.d.ts +1 -1
  51. package/dist/types/bin/portal-build.d.ts +5 -5
  52. package/dist/types/bin/portal-config-publish.d.ts +2 -2
  53. package/dist/types/bin/portal-config.d.ts +4 -4
  54. package/dist/types/bin/portal-dev.d.ts +2 -2
  55. package/dist/types/bin/portal-manifest.d.ts +4 -4
  56. package/dist/types/bin/portal-pack.d.ts +3 -3
  57. package/dist/types/bin/portal-tag.d.ts +2 -2
  58. package/dist/types/bin/portal-upload.d.ts +2 -2
  59. package/dist/types/bin/utils/create-dev-server.d.ts +1 -1
  60. package/dist/types/cli/main.d.ts +0 -20
  61. package/dist/types/cli/options/env.d.ts +1 -2
  62. package/dist/types/lib/app/app-config.d.ts +2 -2
  63. package/dist/types/lib/app/app-manifest.d.ts +1 -1
  64. package/dist/types/lib/app/merge-app-config.d.ts +1 -1
  65. package/dist/types/lib/app/merge-app-manifest.d.ts +1 -1
  66. package/dist/types/lib/index.d.ts +3 -2
  67. package/dist/types/lib/legacy.d.ts +1 -1
  68. package/dist/types/lib/merge-dev-server-config.d.ts +1 -1
  69. package/dist/types/lib/portal/create-portal-manifest.d.ts +1 -1
  70. package/dist/types/lib/portal/load-portal-manifest.d.ts +1 -1
  71. package/dist/types/lib/portal/load-portal-schema.d.ts +1 -1
  72. package/dist/types/lib/portal/portal-config.d.ts +1 -1
  73. package/dist/types/lib/portal/portal-manifest.schema.d.ts +6 -6
  74. package/dist/types/lib/utils/index.d.ts +1 -0
  75. package/dist/types/lib/utils/resolve-devops-annotations.d.ts +2 -2
  76. package/dist/types/lib/utils/resolve-git-commit-sha.d.ts +1 -0
  77. package/dist/types/lib/utils/resolve-github-annotations.d.ts +2 -2
  78. package/dist/types/version.d.ts +1 -1
  79. package/package.json +45 -23
  80. package/bin/build/bin.js +0 -28
  81. package/bin/build/cli.js +0 -10099
  82. package/bin/build/create-auth-client-CUsaZifS.js +0 -1415
  83. package/bin/build/portal-config-publish-8-d0BD44.js +0 -29623
  84. package/dist/esm/bin/app-build.js +0 -34
  85. package/dist/esm/bin/app-build.js.map +0 -1
  86. package/dist/esm/bin/app-check.js +0 -63
  87. package/dist/esm/bin/app-check.js.map +0 -1
  88. package/dist/esm/bin/app-config-publish.js +0 -89
  89. package/dist/esm/bin/app-config-publish.js.map +0 -1
  90. package/dist/esm/bin/app-config.js +0 -48
  91. package/dist/esm/bin/app-config.js.map +0 -1
  92. package/dist/esm/bin/app-dev.js +0 -102
  93. package/dist/esm/bin/app-dev.js.map +0 -1
  94. package/dist/esm/bin/app-manifest.js +0 -38
  95. package/dist/esm/bin/app-manifest.js.map +0 -1
  96. package/dist/esm/bin/app-pack.js +0 -51
  97. package/dist/esm/bin/app-pack.js.map +0 -1
  98. package/dist/esm/bin/app-tag.js +0 -89
  99. package/dist/esm/bin/app-tag.js.map +0 -1
  100. package/dist/esm/bin/app-upload.js +0 -109
  101. package/dist/esm/bin/app-upload.js.map +0 -1
  102. package/dist/esm/bin/helpers/load-bundle-metadata.js +0 -32
  103. package/dist/esm/bin/helpers/load-bundle-metadata.js.map +0 -1
  104. package/dist/esm/bin/helpers/load-vite-config.js +0 -55
  105. package/dist/esm/bin/helpers/load-vite-config.js.map +0 -1
  106. package/dist/esm/bin/helpers/resolve-app-config.js +0 -46
  107. package/dist/esm/bin/helpers/resolve-app-config.js.map +0 -1
  108. package/dist/esm/bin/helpers/resolve-app-manifest.js +0 -55
  109. package/dist/esm/bin/helpers/resolve-app-manifest.js.map +0 -1
  110. package/dist/esm/bin/helpers/resolve-portal-config.js +0 -46
  111. package/dist/esm/bin/helpers/resolve-portal-config.js.map +0 -1
  112. package/dist/esm/bin/helpers/resolve-portal-manifest.js +0 -55
  113. package/dist/esm/bin/helpers/resolve-portal-manifest.js.map +0 -1
  114. package/dist/esm/bin/helpers/resolve-project-package.js +0 -32
  115. package/dist/esm/bin/helpers/resolve-project-package.js.map +0 -1
  116. package/dist/esm/bin/index.js +0 -12
  117. package/dist/esm/bin/index.js.map +0 -1
  118. package/dist/esm/bin/pack.js +0 -70
  119. package/dist/esm/bin/pack.js.map +0 -1
  120. package/dist/esm/bin/portal-build.js +0 -40
  121. package/dist/esm/bin/portal-build.js.map +0 -1
  122. package/dist/esm/bin/portal-config-publish.js +0 -74
  123. package/dist/esm/bin/portal-config-publish.js.map +0 -1
  124. package/dist/esm/bin/portal-config.js +0 -48
  125. package/dist/esm/bin/portal-config.js.map +0 -1
  126. package/dist/esm/bin/portal-dev.js +0 -61
  127. package/dist/esm/bin/portal-dev.js.map +0 -1
  128. package/dist/esm/bin/portal-manifest.js +0 -38
  129. package/dist/esm/bin/portal-manifest.js.map +0 -1
  130. package/dist/esm/bin/portal-pack.js +0 -60
  131. package/dist/esm/bin/portal-pack.js.map +0 -1
  132. package/dist/esm/bin/portal-tag.js +0 -96
  133. package/dist/esm/bin/portal-tag.js.map +0 -1
  134. package/dist/esm/bin/portal-upload.js +0 -99
  135. package/dist/esm/bin/portal-upload.js.map +0 -1
  136. package/dist/esm/bin/utils/ConsoleLogger.js +0 -112
  137. package/dist/esm/bin/utils/ConsoleLogger.js.map +0 -1
  138. package/dist/esm/bin/utils/create-dev-server.js +0 -171
  139. package/dist/esm/bin/utils/create-dev-server.js.map +0 -1
  140. package/dist/esm/bin/utils/format.js +0 -47
  141. package/dist/esm/bin/utils/format.js.map +0 -1
  142. package/dist/esm/bin/utils/index.js +0 -5
  143. package/dist/esm/bin/utils/index.js.map +0 -1
  144. package/dist/esm/bin/utils/spinner.js +0 -142
  145. package/dist/esm/bin/utils/spinner.js.map +0 -1
  146. package/dist/esm/cli/commands/app/alias.js +0 -42
  147. package/dist/esm/cli/commands/app/alias.js.map +0 -1
  148. package/dist/esm/cli/commands/app/build.js +0 -53
  149. package/dist/esm/cli/commands/app/build.js.map +0 -1
  150. package/dist/esm/cli/commands/app/check.js +0 -57
  151. package/dist/esm/cli/commands/app/check.js.map +0 -1
  152. package/dist/esm/cli/commands/app/config.js +0 -103
  153. package/dist/esm/cli/commands/app/config.js.map +0 -1
  154. package/dist/esm/cli/commands/app/dev.js +0 -67
  155. package/dist/esm/cli/commands/app/dev.js.map +0 -1
  156. package/dist/esm/cli/commands/app/index.js +0 -42
  157. package/dist/esm/cli/commands/app/index.js.map +0 -1
  158. package/dist/esm/cli/commands/app/manifest.js +0 -82
  159. package/dist/esm/cli/commands/app/manifest.js.map +0 -1
  160. package/dist/esm/cli/commands/app/pack.js +0 -71
  161. package/dist/esm/cli/commands/app/pack.js.map +0 -1
  162. package/dist/esm/cli/commands/app/publish.js +0 -130
  163. package/dist/esm/cli/commands/app/publish.js.map +0 -1
  164. package/dist/esm/cli/commands/app/tag.js +0 -113
  165. package/dist/esm/cli/commands/app/tag.js.map +0 -1
  166. package/dist/esm/cli/commands/app/upload.js +0 -85
  167. package/dist/esm/cli/commands/app/upload.js.map +0 -1
  168. package/dist/esm/cli/commands/auth/index.js +0 -22
  169. package/dist/esm/cli/commands/auth/index.js.map +0 -1
  170. package/dist/esm/cli/commands/auth/login.js +0 -72
  171. package/dist/esm/cli/commands/auth/login.js.map +0 -1
  172. package/dist/esm/cli/commands/auth/logout.js +0 -58
  173. package/dist/esm/cli/commands/auth/logout.js.map +0 -1
  174. package/dist/esm/cli/commands/auth/token.js +0 -78
  175. package/dist/esm/cli/commands/auth/token.js.map +0 -1
  176. package/dist/esm/cli/commands/disco/index.js +0 -6
  177. package/dist/esm/cli/commands/disco/index.js.map +0 -1
  178. package/dist/esm/cli/commands/disco/resolve.js +0 -58
  179. package/dist/esm/cli/commands/disco/resolve.js.map +0 -1
  180. package/dist/esm/cli/commands/index.js +0 -11
  181. package/dist/esm/cli/commands/index.js.map +0 -1
  182. package/dist/esm/cli/commands/portal/build.js +0 -27
  183. package/dist/esm/cli/commands/portal/build.js.map +0 -1
  184. package/dist/esm/cli/commands/portal/config.js +0 -101
  185. package/dist/esm/cli/commands/portal/config.js.map +0 -1
  186. package/dist/esm/cli/commands/portal/dev.js +0 -27
  187. package/dist/esm/cli/commands/portal/dev.js.map +0 -1
  188. package/dist/esm/cli/commands/portal/index.js +0 -23
  189. package/dist/esm/cli/commands/portal/index.js.map +0 -1
  190. package/dist/esm/cli/commands/portal/manifest.js +0 -48
  191. package/dist/esm/cli/commands/portal/manifest.js.map +0 -1
  192. package/dist/esm/cli/commands/portal/pack.js +0 -40
  193. package/dist/esm/cli/commands/portal/pack.js.map +0 -1
  194. package/dist/esm/cli/commands/portal/publish.js +0 -76
  195. package/dist/esm/cli/commands/portal/publish.js.map +0 -1
  196. package/dist/esm/cli/commands/portal/schema.js +0 -70
  197. package/dist/esm/cli/commands/portal/schema.js.map +0 -1
  198. package/dist/esm/cli/commands/portal/tag.js +0 -73
  199. package/dist/esm/cli/commands/portal/tag.js.map +0 -1
  200. package/dist/esm/cli/commands/portal/upload.js +0 -41
  201. package/dist/esm/cli/commands/portal/upload.js.map +0 -1
  202. package/dist/esm/cli/main.js +0 -52
  203. package/dist/esm/cli/main.js.map +0 -1
  204. package/dist/esm/cli/options/auth.js +0 -96
  205. package/dist/esm/cli/options/auth.js.map +0 -1
  206. package/dist/esm/cli/options/env.js +0 -30
  207. package/dist/esm/cli/options/env.js.map +0 -1
  208. package/dist/esm/lib/framework.node.js +0 -104
  209. package/dist/esm/lib/framework.node.js.map +0 -1
  210. package/dist/esm/version.js.map +0 -1
  211. package/dist/tsconfig.tsbuildinfo +0 -1
  212. /package/dist/types/{lib → bin}/framework.node.d.ts +0 -0
@@ -0,0 +1 @@
1
+ import{loadConfigFromFile as e,mergeConfig as t,build as r}from"vite";import n,{dirname as o,resolve as i,basename as s,extname as a,relative as c}from"node:path";import{readPackageUp as u}from"read-package-up";import l,{accessSync as h,constants as d,readFileSync as f,statSync as p,existsSync as m,mkdirSync as g,writeFileSync as y}from"node:fs";import v,{stat as E,mkdir as b,constants as w}from"node:fs/promises";import{importConfig as I,FileNotFoundError as C}from"@equinor/fusion-imports";import _ from"deepmerge";import T from"node:assert";import S,{execSync as A,execFile as O}from"node:child_process";import k,{z as R}from"zod";import P from"fs";import N from"path";import L from"zlib";import D from"crypto";import x from"ora";import{createDevServer as M,processServices as $}from"@equinor/fusion-framework-dev-server";import U from"http";import F from"https";import j from"buffer";import B from"stream";import q from"util";import{createServer as H}from"node:http";import G,{fileURLToPath as z}from"node:url";import K from"node:process";import{Buffer as V}from"node:buffer";import Y,{promisify as W}from"node:util";import Q from"node:os";const J=(e=0)=>t=>`[${t+e}m`,Z=(e=0)=>t=>`[${38+e};5;${t}m`,X=(e=0)=>(t,r,n)=>`[${38+e};2;${t};${r};${n}m`,ee={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(ee.modifier);Object.keys(ee.color),Object.keys(ee.bgColor);const te=function(){const e=new Map;for(const[t,r]of Object.entries(ee)){for(const[t,n]of Object.entries(r))ee[t]={open:`[${n[0]}m`,close:`[${n[1]}m`},r[t]=ee[t],e.set(n[0],n[1]);Object.defineProperty(ee,t,{value:r,enumerable:!1})}return Object.defineProperty(ee,"codes",{value:e,enumerable:!1}),ee.color.close="",ee.bgColor.close="",ee.color.ansi=J(),ee.color.ansi256=Z(),ee.color.ansi16m=X(),ee.bgColor.ansi=J(10),ee.bgColor.ansi256=Z(10),ee.bgColor.ansi16m=X(10),Object.defineProperties(ee,{rgbToAnsi256:{value:(e,t,r)=>e===t&&t===r?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(r/255*5),enumerable:!1},hexToRgb:{value(e){const t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[r]=t;3===r.length&&(r=[...r].map(e=>e+e).join(""));const n=Number.parseInt(r,16);return[n>>16&255,n>>8&255,255&n]},enumerable:!1},hexToAnsi256:{value:e=>ee.rgbToAnsi256(...ee.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return e-8+90;let t,r,n;if(e>=232)t=(10*(e-232)+8)/255,r=t,n=t;else{const o=(e-=16)%36;t=Math.floor(e/36)/5,r=Math.floor(o/6)/5,n=o%6/5}const o=2*Math.max(t,r,n);if(0===o)return 30;let i=30+(Math.round(n)<<2|Math.round(r)<<1|Math.round(t));return 2===o&&(i+=60),i},enumerable:!1},rgbToAnsi:{value:(e,t,r)=>ee.ansi256ToAnsi(ee.rgbToAnsi256(e,t,r)),enumerable:!1},hexToAnsi:{value:e=>ee.ansi256ToAnsi(ee.hexToAnsi256(e)),enumerable:!1}}),ee}(),re=(()=>{if(!("navigator"in globalThis))return 0;if(globalThis.navigator.userAgentData){const e=navigator.userAgentData.brands.find(({brand:e})=>"Chromium"===e);if(e&&e.version>93)return 3}return/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)?1:0})(),ne=0!==re&&{level:re},oe={stdout:ne,stderr:ne};function ie(e,t,r){let n=e.indexOf(t);if(-1===n)return e;const o=t.length;let i=0,s="";do{s+=e.slice(i,n)+t+r,i=n+o,n=e.indexOf(t,i)}while(-1!==n);return s+=e.slice(i),s}const{stdout:se,stderr:ae}=oe,ce=Symbol("GENERATOR"),ue=Symbol("STYLER"),le=Symbol("IS_EMPTY"),he=["ansi","ansi","ansi256","ansi16m"],de=Object.create(null),fe=e=>{const t=(...e)=>e.join(" ");return((e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const r=se?se.level:0;e.level=void 0===t.level?r:t.level})(t,e),Object.setPrototypeOf(t,pe.prototype),t};function pe(e){return fe(e)}Object.setPrototypeOf(pe.prototype,Function.prototype);for(const[e,t]of Object.entries(te))de[e]={get(){const r=Ee(this,ve(t.open,t.close,this[ue]),this[le]);return Object.defineProperty(this,e,{value:r}),r}};de.visible={get(){const e=Ee(this,this[ue],!0);return Object.defineProperty(this,"visible",{value:e}),e}};const me=(e,t,r,...n)=>"rgb"===e?"ansi16m"===t?te[r].ansi16m(...n):"ansi256"===t?te[r].ansi256(te.rgbToAnsi256(...n)):te[r].ansi(te.rgbToAnsi(...n)):"hex"===e?me("rgb",t,r,...te.hexToRgb(...n)):te[r][e](...n),ge=["rgb","hex","ansi256"];for(const e of ge){de[e]={get(){const{level:t}=this;return function(...r){const n=ve(me(e,he[t],"color",...r),te.color.close,this[ue]);return Ee(this,n,this[le])}}};de["bg"+e[0].toUpperCase()+e.slice(1)]={get(){const{level:t}=this;return function(...r){const n=ve(me(e,he[t],"bgColor",...r),te.bgColor.close,this[ue]);return Ee(this,n,this[le])}}}}const ye=Object.defineProperties(()=>{},{...de,level:{enumerable:!0,get(){return this[ce].level},set(e){this[ce].level=e}}}),ve=(e,t,r)=>{let n,o;return void 0===r?(n=e,o=t):(n=r.openAll+e,o=t+r.closeAll),{open:e,close:t,openAll:n,closeAll:o,parent:r}},Ee=(e,t,r)=>{const n=(...e)=>be(n,1===e.length?""+e[0]:e.join(" "));return Object.setPrototypeOf(n,ye),n[ce]=e,n[ue]=t,n[le]=r,n},be=(e,t)=>{if(e.level<=0||!t)return e[le]?"":t;let r=e[ue];if(void 0===r)return t;const{openAll:n,closeAll:o}=r;if(t.includes(""))for(;void 0!==r;)t=ie(t,r.close,r.open),r=r.parent;const i=t.indexOf("\n");return-1!==i&&(t=function(e,t,r,n){let o=0,i="";do{const s="\r"===e[n-1];i+=e.slice(o,s?n-1:n)+t+(s?"\r\n":"\n")+r,o=n+1,n=e.indexOf("\n",o)}while(-1!==n);return i+=e.slice(o),i}(t,o,n,i)),n+t+o};Object.defineProperties(pe.prototype,de);const we=pe();pe({level:ae?ae.level:0});const Ie=(e,t)=>{try{return h(e,d.F_OK),!0}catch(e){return!1}},Ce=["index.ts","index.tsx","main.ts","main.tsx"],_e=(e,t,r)=>{const n=i(e??process.cwd(),"src"),o=Ce,s=o.map(e=>i(n,e)).find(e=>Ie(e));if(!s)throw new Error(`Unable to resolve entry point, ensure ${o.join(", ")} exists in ${n}`);return s},Te=async(e,t,r)=>I("dev-server.config",{baseDir:e.root,extensions:r?.extensions,script:{resolve:async r=>{let n;if("function"==typeof r.default){const o={...t};n=await r.default(e,{base:o})}else n=r.default;return((e,t)=>_(e,t))(t,n??{})}}}),Se=async(r,n)=>{const{packageJson:i,root:c}=n,{config:u}=await e(r)??{},l=i.main??i.module??"./dist/bundle.js",h=_e(c);if(o(l)===c)throw new Error("outDir cannot be root, please specify package.main or package.module in package.json");if("src"===o(l))throw new Error("outDir cannot be src, please specify package.main or package.module in package.json");if(o(l)===process.cwd())throw new Error("outDir cannot be the current working directory, please specify package.main or package.module in package.json");return t({root:c,define:{"process.env.NODE_ENV":JSON.stringify(r.mode),"process.env.NODE_DEBUG":"production"!==r.mode,"process.env.FUSION_LOG_LEVEL":"production"===r.mode?1:3},build:{outDir:o(l),lib:{entry:h,fileName:s(l,a(l)),formats:["es"]},emptyOutDir:!0}},u??{})};function Ae(e,t){T("object"==typeof e,t)}const Oe=e=>{if(e.repository)return"string"==typeof e.repository?e.repository:e.repository.url},ke=()=>{try{return A("git remote get-url origin").toString().trim().replace("git@github.com:","https://github.com/").replace(/\.git$/,"")}catch(e){return}},Re=(e="HEAD")=>{try{return A(`git rev-parse ${e}`).toString().trim()}catch(e){return}};function Pe(e){const t={action:e.action,head_commit:e.head_commit?.id,after:e.after,ref:e.ref,workflow:e.workflow,release:{},pull_request:{}};return e.release&&(t.release={tag:e.release.tag_name,name:e.release.name,body:e.release.body,draft:!!e.release.draft,prerelease:!!e.release.prerelease,created_at:e.release.created_at,published_at:e.release.published_at,html_url:e.release.html_url}),e.pull_request&&(t.pull_request={number:e.pull_request.number,title:e.pull_request.title,user:e.pull_request.user?.login,head:{sha:e.pull_request.head?.sha,ref:e.pull_request.head?.ref},created_at:e.pull_request.created_at,updated_at:e.pull_request.updated_at,html_url:e.pull_request.html_url}),t}const Ne=()=>process.env.GITHUB_ACTIONS?(()=>{const e=process.env.GITHUB_EVENT_NAME||"unknown",t=process.env.GITHUB_ACTOR||"unknown",r=process.env.GITHUB_RUN_ID||"unknown",n=process.env.GITHUB_REPOSITORY||"unknown",o=process.env.GITHUB_SERVER_URL||"https://github.com";let i={};if(process.env.GITHUB_EVENT_PATH)try{const e=f(process.env.GITHUB_EVENT_PATH,"utf8");i=JSON.parse(e)}catch{i={}}let s="unknown";return"unknown"!==n&&"unknown"!==r&&(s=`${o.replace(/\/$/,"")}/${n}/actions/runs/${r}`),{eventName:e,actor:t,runId:r,repository:n,runUrl:s,...Pe(i)}})():process.env.SYSTEM_TEAMPROJECT?(()=>{const e=process.env.BUILD_BUILDID||"unknown",t=process.env.BUILD_REPOSITORY_NAME||"unknown",r=process.env.SYSTEM_TEAMPROJECT||"unknown",n=process.env.SYSTEM_COLLECTIONURI||"unknown",o=process.env.BUILD_REQUESTEDFOR||"unknown",i=process.env.BUILD_SOURCEBRANCH||"unknown",s=process.env.BUILD_SOURCEVERSION||"unknown";let a="unknown";return"unknown"!==n&&"unknown"!==r&&"unknown"!==e&&(a=`${n.replace(/\/$/,"")}${r}/_build/results?buildId=${e}`),{runId:e,repository:t,project:r,orgUrl:n,actor:o,branch:i,commitId:s,runUrl:a}})():{},Le=["png","jpg","jpeg","gif","svg","ico","webp","mp4","webm","mp3","woff2","woff","eot","ttf","otf","pdf","md","txt"],De=(e,t)=>{Ae(t,"expected packageJson"),T(t.name,"expected [name] in packageJson"),T(t.version,"expected [version] in packageJson");const r=((e,t)=>"build"===e.command||e.isPreview?t.main||t.module||"dist/app-bundle.js":_e(e.root))(e,t),n=t.name.replace(/^@|\w.*\//gm,""),o=t.version,i="build"===e.command?void 0:`/bundles/apps/${n}@${o}`,s=Oe(t)??ke();return{appKey:n,displayName:t.name,description:t.description||"",keywords:t.keywords,type:"standalone",build:{entryPoint:r,assetPath:i,githubRepo:s,version:o,timestamp:(new Date).toISOString(),commitSha:Re(),annotations:Ne(),projectPage:t.homepage,allowedExtensions:Le.map(e=>`.${e}`)}}},xe=(e,t)=>_(e,t),Me=R.object({environment:R.record(R.any()).describe("Key-value map of environment-specific variables for the application. Defaults to an empty object if not provided.").optional().default({}),endpoints:R.record(R.object({url:R.string().describe("The endpoint URL. This field is required."),scopes:R.array(R.string()).optional().default([]).describe("List of scopes required for accessing this endpoint. Defaults to an empty array.")})).describe("A mapping of endpoint names to their configuration objects. Each endpoint must specify a URL and may specify scopes.").optional()}).describe("The API application configuration schema, defining environment variables and endpoints for the application."),$e=["B","kB","MB","GB","TB","PB","EB","ZB","YB"],Ue=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"],Fe=["b","kbit","Mbit","Gbit","Tbit","Pbit","Ebit","Zbit","Ybit"],je=["b","kibit","Mibit","Gibit","Tibit","Pibit","Eibit","Zibit","Yibit"],Be=(e,t,r)=>{let n=e;return"string"==typeof t||Array.isArray(t)?n=e.toLocaleString(t,r):!0!==t&&void 0===r||(n=e.toLocaleString(void 0,r)),n},qe=e=>{if("number"==typeof e)return Math.log10(e);const t=e.toString(10);return t.length+Math.log10("0."+t.slice(0,15))};function He(e,t){if("bigint"!=typeof e&&!Number.isFinite(e))throw new TypeError(`Expected a finite number, got ${typeof e}: ${e}`);const r=(t={bits:!1,binary:!1,space:!0,...t}).bits?t.binary?je:Fe:t.binary?Ue:$e,n=t.space?" ":"";if(t.signed&&("number"==typeof e?0===e:0n===e))return` 0${n}${r[0]}`;const o=e<0,i=o?"-":t.signed?"+":"";let s;if(o&&(e=-e),void 0!==t.minimumFractionDigits&&(s={minimumFractionDigits:t.minimumFractionDigits}),void 0!==t.maximumFractionDigits&&(s={maximumFractionDigits:t.maximumFractionDigits,...s}),e<1){return i+Be(e,t.locale,s)+n+r[0]}const a=Math.min(Math.floor(t.binary?("number"==typeof(c=e)?Math.log(c):qe(c)*Math.log(10))/Math.log(1024):qe(e)/3),r.length-1);var c;e=((e,t)=>{if("number"==typeof e)return e/t;const r=e/BigInt(t),n=e%BigInt(t);return Number(r)+Number(n)/t})(e,(t.binary?1024:1e3)**a),s||(e=e.toPrecision(3));return i+Be(Number(e),t.locale,s)+n+r[a]}const Ge=(e,t)=>we.blueBright(t?.relative?`./${c(t?.cwd??process.cwd(),e)}`:e),ze=e=>"string"==typeof e?ze(p(e).size):we.yellowBright(He(e)),Ke=async(e,t,r)=>{const n=De(e,t.packageJson);try{r?.log?.start("loading application package...");const{manifest:t,path:o}=await(async(e,t)=>{const r=t?.file??[`app.manifest.${e.environment}`,"app.manifest","app.manifest.config"],n=await I(r,{baseDir:e.root,extensions:t?.extensions,script:{resolve:async r=>{const n=t?.base??{};if("function"==typeof r.default){const t=await r.default(e,{base:n});return xe(n,t??{})}return xe(n,r.default??{})}}});return{manifest:n.config,path:n.path,extension:n.extension}})(e,{base:n,file:r?.manifestPath});if(!t.build)throw new Error(`Application manifest for ${t.appKey} does not contain build information, please check the manifest file.`);return"serve"===e.command&&(t.build.assetPath=`/bundles/apps/${t.appKey}/${t.build.version}`),r?.log?.succeed("generated manifest from",Ge(o,{relative:!0})),t}catch(e){if(e instanceof C){if(r?.manifestPath){const t=new Error(`Failed to load manifest file ${Ge(r.manifestPath)}, please check the path.`,{cause:e});throw r?.log?.fail(t.message),t}return r?.log?.succeed(we.dim("no local manifest config applied, using default generated from package")),n}throw r?.log?.fail(`failed to resolve application manifest ${r?.manifestPath?Ge(r?.manifestPath):""}`),e}};async function Ve(e){e?.start("resolve project package");try{const t=await(async e=>{const t=await u(e);if(!t)throw Error("failed to find package.json");return{...t,root:o(t.path)}})();return e?.succeed("📦",we.yellowBright([t.packageJson.name,t.packageJson.version].join("@"))),e?.info("🏠",we.blueBright(t.root)),t}catch(t){throw e?.fail("☠️","failed to resolve project package"),t}}const Ye=async e=>{const{log:t}=e??{},r=await Ve(t);t?.debug("package",r);const n={command:"build",mode:process.env.NODE_ENV??"production",root:r.root,...e?.env};t?.debug("env:",n);const o=await Ke(n,r,{log:t,manifestPath:e?.manifest});return t?.debug("manifest:",o),{manifest:o,pkg:r,env:n}},We=async e=>{const{log:t}=e??{};t?.log(we.bold("Starting to build application"));const{manifest:n,pkg:o,env:i}=await Ye({log:t,manifest:e?.manifest});t?.start("loading vite config...");const s=await Se(i,o);t?.succeed("vite config applied"),t?.debug("vite config:",s),t?.start("🤞🏻","building application..."),t?.startNativeConsoleCapture(),await r(s),t?.stopNativeConsoleCapture(),t?.succeed("build completed 😘");return{pkg:o,manifest:n,outDir:s.build.outDir}};function Qe(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Je,Ze,Xe={exports:{}};function et(){return Ze?Je:(Ze=1,Je={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24})}var tt,rt,nt,ot,it,st,at,ct,ut={};function lt(){return tt||(tt=1,function(e){const t={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function r(e){return function(...t){return t.length&&(e=e.replace(/\{(\d)\}/g,(e,r)=>t[r]||"")),new Error("ADM-ZIP: "+e)}}for(const n of Object.keys(t))e[n]=r(t[n])}(ut)),ut}function ht(){return ct||(ct=1,Xe.exports=function(){if(nt)return rt;nt=1;const e=P,t=N,r=et(),n=lt(),o="object"==typeof process&&"win32"===process.platform,i=e=>"object"==typeof e&&null!==e,s=new Uint32Array(256).map((e,t)=>{for(let e=0;e<8;e++)1&t?t=3988292384^t>>>1:t>>>=1;return t>>>0});function a(r){this.sep=t.sep,this.fs=e,i(r)&&i(r.fs)&&"function"==typeof r.fs.statSync&&(this.fs=r.fs)}return rt=a,a.prototype.makeDir=function(e){const t=this;!function(e){let r=e.split(t.sep)[0];e.split(t.sep).forEach(function(e){if(e&&":"!==e.substr(-1,1)){var o;r+=t.sep+e;try{o=t.fs.statSync(r)}catch(e){t.fs.mkdirSync(r)}if(o&&o.isFile())throw n.FILE_IN_THE_WAY(`"${r}"`)}})}(e)},a.prototype.writeFileTo=function(e,r,n,o){const i=this;if(i.fs.existsSync(e)){if(!n)return!1;if(i.fs.statSync(e).isDirectory())return!1}var s,a=t.dirname(e);i.fs.existsSync(a)||i.makeDir(a);try{s=i.fs.openSync(e,"w",438)}catch(t){i.fs.chmodSync(e,438),s=i.fs.openSync(e,"w",438)}if(s)try{i.fs.writeSync(s,r,0,r.length,0)}finally{i.fs.closeSync(s)}return i.fs.chmodSync(e,o||438),!0},a.prototype.writeFileToAsync=function(e,r,n,o,i){"function"==typeof o&&(i=o,o=void 0);const s=this;s.fs.exists(e,function(a){if(a&&!n)return i(!1);s.fs.stat(e,function(n,c){if(a&&c.isDirectory())return i(!1);var u=t.dirname(e);s.fs.exists(u,function(t){t||s.makeDir(u),s.fs.open(e,"w",438,function(t,n){t?s.fs.chmod(e,438,function(){s.fs.open(e,"w",438,function(t,n){s.fs.write(n,r,0,r.length,0,function(){s.fs.close(n,function(){s.fs.chmod(e,o||438,function(){i(!0)})})})})}):n?s.fs.write(n,r,0,r.length,0,function(){s.fs.close(n,function(){s.fs.chmod(e,o||438,function(){i(!0)})})}):s.fs.chmod(e,o||438,function(){i(!0)})})})})})},a.prototype.findFiles=function(e){const r=this;return function e(n,o,i){let s=[];return r.fs.readdirSync(n).forEach(function(a){const c=t.join(n,a),u=r.fs.statSync(c);s.push(t.normalize(c)+(u.isDirectory()?r.sep:"")),u.isDirectory()&&i&&(s=s.concat(e(c,o,i)))}),s}(e,void 0,!0)},a.prototype.findFilesAsync=function(e,r){const n=this;let o=[];n.fs.readdir(e,function(i,s){if(i)return r(i);let a=s.length;if(!a)return r(null,o);s.forEach(function(i){i=t.join(e,i),n.fs.stat(i,function(e,s){if(e)return r(e);s&&(o.push(t.normalize(i)+(s.isDirectory()?n.sep:"")),s.isDirectory()?n.findFilesAsync(i,function(e,t){if(e)return r(e);o=o.concat(t),--a||r(null,o)}):--a||r(null,o))})})})},a.prototype.getAttributes=function(){},a.prototype.setAttributes=function(){},a.crc32update=function(e,t){return s[255&(e^t)]^e>>>8},a.crc32=function(e){"string"==typeof e&&(e=Buffer.from(e,"utf8"));let t=e.length,r=-1;for(let n=0;n<t;)r=a.crc32update(r,e[n++]);return~r>>>0},a.methodToString=function(e){switch(e){case r.STORED:return"STORED ("+e+")";case r.DEFLATED:return"DEFLATED ("+e+")";default:return"UNSUPPORTED ("+e+")"}},a.canonical=function(e){if(!e)return"";const r=t.posix.normalize("/"+e.split("\\").join("/"));return t.join(".",r)},a.zipnamefix=function(e){if(!e)return"";const r=t.posix.normalize("/"+e.split("\\").join("/"));return t.posix.join(".",r)},a.findLast=function(e,t){if(!Array.isArray(e))throw new TypeError("arr is not array");for(let r=(e.length>>>0)-1;r>=0;r--)if(t(e[r],r,e))return e[r]},a.sanitize=function(e,r){e=t.resolve(t.normalize(e));for(var n=r.split("/"),o=0,i=n.length;o<i;o++){var s=t.normalize(t.join(e,n.slice(o,i).join(t.sep)));if(0===s.indexOf(e))return s}return t.normalize(t.join(e,t.basename(r)))},a.toBuffer=function(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):"string"==typeof e?t(e):Buffer.alloc(0)},a.readBigUInt64LE=function(e,t){var r=Buffer.from(e.slice(t,t+8));return r.swap64(),parseInt(`0x${r.toString("hex")}`)},a.fromDOS2Date=function(e){return new Date(1980+(e>>25&127),Math.max((e>>21&15)-1,0),Math.max(e>>16&31,1),e>>11&31,e>>5&63,(31&e)<<1)},a.fromDate2DOS=function(e){let t=0,r=0;return e.getFullYear()>1979&&(t=(e.getFullYear()-1980&127)<<9|e.getMonth()+1<<5|e.getDate(),r=e.getHours()<<11|e.getMinutes()<<5|e.getSeconds()>>1),t<<16|r},a.isWin=o,a.crcTable=s,rt}(),Xe.exports.Constants=et(),Xe.exports.Errors=lt(),Xe.exports.FileAttr=function(){if(it)return ot;it=1;const e=N;return ot=function(t,{fs:r}){var n=t||"",o={directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0},i=null;return n&&r.existsSync(n)?(i=r.statSync(n),o.directory=i.isDirectory(),o.mtime=i.mtime,o.atime=i.atime,o.executable=!!(73&i.mode),o.readonly=!(128&i.mode),o.hidden="."===e.basename(n)[0]):console.warn("Invalid path: "+n),{get directory(){return o.directory},get readOnly(){return o.readonly},get hidden(){return o.hidden},get mtime(){return o.mtime},get atime(){return o.atime},get executable(){return o.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:n,isDirectory:o.directory,isReadOnly:o.readonly,isHidden:o.hidden,isExecutable:o.executable,mTime:o.mtime,aTime:o.atime}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}},ot}(),Xe.exports.decoder=at?st:(at=1,st={efs:!0,encode:e=>Buffer.from(e,"utf8"),decode:e=>e.toString("utf8")})),Xe.exports}var dt,ft,pt,mt,gt,yt={};function vt(){if(ft)return dt;ft=1;var e=ht(),t=e.Constants;return dt=function(){var r=20,n=10,o=0,i=0,s=0,a=0,c=0,u=0,l=0,h=0,d=0,f=0,p=0,m=0,g=0;r|=e.isWin?2560:768,o|=t.FLG_EFS;const y={extraLen:0},v=e=>Math.max(0,e)>>>0;return s=e.fromDate2DOS(new Date),{get made(){return r},set made(e){r=e},get version(){return n},set version(e){n=e},get flags(){return o},set flags(e){o=e},get flags_efs(){return(o&t.FLG_EFS)>0},set flags_efs(e){e?o|=t.FLG_EFS:o&=~t.FLG_EFS},get flags_desc(){return(o&t.FLG_DESC)>0},set flags_desc(e){e?o|=t.FLG_DESC:o&=~t.FLG_DESC},get method(){return i},set method(e){switch(e){case t.STORED:this.version=10;case t.DEFLATED:default:this.version=20}i=e},get time(){return e.fromDOS2Date(this.timeval)},set time(t){this.timeval=e.fromDate2DOS(t)},get timeval(){return s},set timeval(e){s=v(e)},get timeHighByte(){return e=s>>>8,255&Math.max(0,e);var e},get crc(){return a},set crc(e){a=v(e)},get compressedSize(){return c},set compressedSize(e){c=v(e)},get size(){return u},set size(e){u=v(e)},get fileNameLength(){return l},set fileNameLength(e){l=e},get extraLength(){return h},set extraLength(e){h=e},get extraLocalLength(){return y.extraLen},set extraLocalLength(e){y.extraLen=e},get commentLength(){return d},set commentLength(e){d=e},get diskNumStart(){return f},set diskNumStart(e){f=v(e)},get inAttr(){return p},set inAttr(e){p=v(e)},get attr(){return m},set attr(e){m=v(e)},get fileAttr(){return(m||0)>>16&4095},get offset(){return g},set offset(e){g=v(e)},get encrypted(){return(o&t.FLG_ENC)===t.FLG_ENC},get centralHeaderSize(){return t.CENHDR+l+h+d},get realDataOffset(){return g+t.LOCHDR+y.fnameLen+y.extraLen},get localHeader(){return y},loadLocalHeaderFromBinary:function(r){var n=r.slice(g,g+t.LOCHDR);if(n.readUInt32LE(0)!==t.LOCSIG)throw e.Errors.INVALID_LOC();y.version=n.readUInt16LE(t.LOCVER),y.flags=n.readUInt16LE(t.LOCFLG),y.method=n.readUInt16LE(t.LOCHOW),y.time=n.readUInt32LE(t.LOCTIM),y.crc=n.readUInt32LE(t.LOCCRC),y.compressedSize=n.readUInt32LE(t.LOCSIZ),y.size=n.readUInt32LE(t.LOCLEN),y.fnameLen=n.readUInt16LE(t.LOCNAM),y.extraLen=n.readUInt16LE(t.LOCEXT);const o=g+t.LOCHDR+y.fnameLen,i=o+y.extraLen;return r.slice(o,i)},loadFromBinary:function(y){if(y.length!==t.CENHDR||y.readUInt32LE(0)!==t.CENSIG)throw e.Errors.INVALID_CEN();r=y.readUInt16LE(t.CENVEM),n=y.readUInt16LE(t.CENVER),o=y.readUInt16LE(t.CENFLG),i=y.readUInt16LE(t.CENHOW),s=y.readUInt32LE(t.CENTIM),a=y.readUInt32LE(t.CENCRC),c=y.readUInt32LE(t.CENSIZ),u=y.readUInt32LE(t.CENLEN),l=y.readUInt16LE(t.CENNAM),h=y.readUInt16LE(t.CENEXT),d=y.readUInt16LE(t.CENCOM),f=y.readUInt16LE(t.CENDSK),p=y.readUInt16LE(t.CENATT),m=y.readUInt32LE(t.CENATX),g=y.readUInt32LE(t.CENOFF)},localHeaderToBinary:function(){var e=Buffer.alloc(t.LOCHDR);return e.writeUInt32LE(t.LOCSIG,0),e.writeUInt16LE(n,t.LOCVER),e.writeUInt16LE(o,t.LOCFLG),e.writeUInt16LE(i,t.LOCHOW),e.writeUInt32LE(s,t.LOCTIM),e.writeUInt32LE(a,t.LOCCRC),e.writeUInt32LE(c,t.LOCSIZ),e.writeUInt32LE(u,t.LOCLEN),e.writeUInt16LE(l,t.LOCNAM),e.writeUInt16LE(y.extraLen,t.LOCEXT),e},centralHeaderToBinary:function(){var e=Buffer.alloc(t.CENHDR+l+h+d);return e.writeUInt32LE(t.CENSIG,0),e.writeUInt16LE(r,t.CENVEM),e.writeUInt16LE(n,t.CENVER),e.writeUInt16LE(o,t.CENFLG),e.writeUInt16LE(i,t.CENHOW),e.writeUInt32LE(s,t.CENTIM),e.writeUInt32LE(a,t.CENCRC),e.writeUInt32LE(c,t.CENSIZ),e.writeUInt32LE(u,t.CENLEN),e.writeUInt16LE(l,t.CENNAM),e.writeUInt16LE(h,t.CENEXT),e.writeUInt16LE(d,t.CENCOM),e.writeUInt16LE(f,t.CENDSK),e.writeUInt16LE(p,t.CENATT),e.writeUInt32LE(m,t.CENATX),e.writeUInt32LE(g,t.CENOFF),e},toJSON:function(){const s=function(e){return e+" bytes"};return{made:r,version:n,flags:o,method:e.methodToString(i),time:this.time,crc:"0x"+a.toString(16).toUpperCase(),compressedSize:s(c),size:s(u),fileNameLength:s(l),extraLength:s(h),commentLength:s(d),diskNumStart:f,inAttr:p,attr:m,offset:g,centralHeaderSize:s(t.CENHDR+l+h+d)}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}}function Et(){return gt||(gt=1,yt.EntryHeader=vt(),yt.MainHeader=function(){if(mt)return pt;mt=1;var e=ht(),t=e.Constants;return pt=function(){var r=0,n=0,o=0,i=0,s=0;return{get diskEntries(){return r},set diskEntries(e){r=n=e},get totalEntries(){return n},set totalEntries(e){n=r=e},get size(){return o},set size(e){o=e},get offset(){return i},set offset(e){i=e},get commentLength(){return s},set commentLength(e){s=e},get mainHeaderSize(){return t.ENDHDR+s},loadFromBinary:function(a){if((a.length!==t.ENDHDR||a.readUInt32LE(0)!==t.ENDSIG)&&(a.length<t.ZIP64HDR||a.readUInt32LE(0)!==t.ZIP64SIG))throw e.Errors.INVALID_END();a.readUInt32LE(0)===t.ENDSIG?(r=a.readUInt16LE(t.ENDSUB),n=a.readUInt16LE(t.ENDTOT),o=a.readUInt32LE(t.ENDSIZ),i=a.readUInt32LE(t.ENDOFF),s=a.readUInt16LE(t.ENDCOM)):(r=e.readBigUInt64LE(a,t.ZIP64SUB),n=e.readBigUInt64LE(a,t.ZIP64TOT),o=e.readBigUInt64LE(a,t.ZIP64SIZE),i=e.readBigUInt64LE(a,t.ZIP64OFF),s=0)},toBinary:function(){var e=Buffer.alloc(t.ENDHDR+s);return e.writeUInt32LE(t.ENDSIG,0),e.writeUInt32LE(0,4),e.writeUInt16LE(r,t.ENDSUB),e.writeUInt16LE(n,t.ENDTOT),e.writeUInt32LE(o,t.ENDSIZ),e.writeUInt32LE(i,t.ENDOFF),e.writeUInt16LE(s,t.ENDCOM),e.fill(" ",t.ENDHDR),e},toJSON:function(){return{diskEntries:r,totalEntries:n,size:o+" bytes",offset:function(e,t){let r=e.toString(16).toUpperCase();for(;r.length<t;)r="0"+r;return"0x"+r}(i,4),commentLength:s}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}},pt}()),yt}var bt,wt,It,Ct,_t,Tt,St,At,Ot,kt,Rt,Pt,Nt,Lt={};function Dt(){if(Tt)return _t;Tt=1;const{randomFillSync:e}=D,t=lt(),r=new Uint32Array(256).map((e,t)=>{for(let e=0;e<8;e++)1&t?t=t>>>1^3988292384:t>>>=1;return t>>>0}),n=(e,t)=>Math.imul(e,t)>>>0,o=(e,t)=>r[255&(e^t)]^e>>>8,i=()=>"function"==typeof e?e(Buffer.alloc(12)):i.node();i.node=()=>{const e=Buffer.alloc(12),t=e.length;for(let r=0;r<t;r++)e[r]=256*Math.random()&255;return e};const s={genSalt:i};function a(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let e=0;e<t.length;e++)this.updateKeys(t[e])}return a.prototype.updateKeys=function(e){const t=this.keys;return t[0]=o(t[0],e),t[1]+=255&t[0],t[1]=n(t[1],134775813)+1,t[2]=o(t[2],t[1]>>>24),e},a.prototype.next=function(){const e=(2|this.keys[2])>>>0;return n(e,1^e)>>8&255},_t={decrypt:function(e,r,n){if(!e||!Buffer.isBuffer(e)||e.length<12)return Buffer.alloc(0);const o=function(e){const t=new a(e);return function(e){const r=Buffer.alloc(e.length);let n=0;for(let o of e)r[n++]=t.updateKeys(o^t.next());return r}}(n),i=o(e.slice(0,12)),s=8&~r.flags?r.crc>>>24:r.timeHighByte;if(i[11]!==s)throw t.WRONG_PASSWORD();return o(e.slice(12))},encrypt:function(e,t,r,n=!1){null==e&&(e=Buffer.alloc(0)),Buffer.isBuffer(e)||(e=Buffer.from(e.toString()));const o=function(e){const t=new a(e);return function(e,r,n=0){r||(r=Buffer.alloc(e.length));for(let o of e){const e=t.next();r[n++]=o^e,t.updateKeys(o)}return r}}(r),i=s.genSalt();i[11]=t.crc>>>24&255,n&&(i[10]=t.crc>>>16&255);const c=Buffer.alloc(e.length+12);return o(i,c),o(e,c,12)},_salter:function(e){Buffer.isBuffer(e)&&e.length>=12?s.genSalt=function(){return e.slice(0,12)}:s.genSalt="node"===e?i.node:i}},_t}function xt(){return St||(St=1,Lt.Deflater=(wt||(wt=1,bt=function(e){var t=L,r={chunkSize:1024*(parseInt(e.length/1024)+1)};return{deflate:function(){return t.deflateRawSync(e,r)},deflateAsync:function(n){var o=t.createDeflateRaw(r),i=[],s=0;o.on("data",function(e){i.push(e),s+=e.length}),o.on("end",function(){var e=Buffer.alloc(s),t=0;e.fill(0);for(var r=0;r<i.length;r++){var o=i[r];o.copy(e,t),t+=o.length}n&&n(e)}),o.end(e)}}}),bt),Lt.Inflater=function(){if(Ct)return It;Ct=1;const e=+(process.versions?process.versions.node:"").split(".")[0]||0;return It=function(t,r){var n=L;const o=e>=15&&r>0?{maxOutputLength:r}:{};return{inflate:function(){return n.inflateRawSync(t,o)},inflateAsync:function(e){var r=n.createInflateRaw(o),i=[],s=0;r.on("data",function(e){i.push(e),s+=e.length}),r.on("end",function(){var t=Buffer.alloc(s),r=0;t.fill(0);for(var n=0;n<i.length;n++){var o=i[n];o.copy(t,r),r+=o.length}e&&e(t)}),r.end(t)}}},It}(),Lt.ZipCrypto=Dt()),Lt}function Mt(){if(Ot)return At;Ot=1;var e=ht(),t=Et(),r=e.Constants,n=xt();return At=function(o,i){var s=new t.EntryHeader,a=Buffer.alloc(0),c=Buffer.alloc(0),u=!1,l=null,h=Buffer.alloc(0),d=Buffer.alloc(0),f=!0;const p=o,m="object"==typeof p.decoder?p.decoder:e.decoder;function g(){return i&&i instanceof Uint8Array?(d=s.loadLocalHeaderFromBinary(i),i.slice(s.realDataOffset,s.realDataOffset+s.compressedSize)):Buffer.alloc(0)}function y(t){if(s.flags_desc){const n={},o=s.realDataOffset+s.compressedSize;if(i.readUInt32LE(o)==r.LOCSIG||i.readUInt32LE(o)==r.CENSIG)throw e.Errors.DESCRIPTOR_NOT_EXIST();if(i.readUInt32LE(o)==r.EXTSIG)n.crc=i.readUInt32LE(o+r.EXTCRC),n.compressedSize=i.readUInt32LE(o+r.EXTSIZ),n.size=i.readUInt32LE(o+r.EXTLEN);else{if(19280!==i.readUInt16LE(o+12))throw e.Errors.DESCRIPTOR_UNKNOWN();n.crc=i.readUInt32LE(o+r.EXTCRC-4),n.compressedSize=i.readUInt32LE(o+r.EXTSIZ-4),n.size=i.readUInt32LE(o+r.EXTLEN-4)}if(n.compressedSize!==s.compressedSize||n.size!==s.size||n.crc!==s.crc)throw e.Errors.DESCRIPTOR_FAULTY();if(e.crc32(t)!==n.crc)return!1}else if(e.crc32(t)!==s.localHeader.crc)return!1;return!0}function v(t,r,o){if(void 0===r&&"string"==typeof t&&(o=t,t=void 0),u)return t&&r&&r(Buffer.alloc(0),e.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var i=g();if(0===i.length)return t&&r&&r(i),i;if(s.encrypted){if("string"!=typeof o&&!Buffer.isBuffer(o))throw e.Errors.INVALID_PASS_PARAM();i=n.ZipCrypto.decrypt(i,s,o)}var c=Buffer.alloc(s.size);switch(s.method){case e.Constants.STORED:if(i.copy(c),y(c))return t&&r&&r(c),c;throw t&&r&&r(c,e.Errors.BAD_CRC()),e.Errors.BAD_CRC();case e.Constants.DEFLATED:var l=new n.Inflater(i,s.size);if(!t){if(l.inflate(c).copy(c,0),!y(c))throw e.Errors.BAD_CRC(`"${m.decode(a)}"`);return c}l.inflateAsync(function(t){t.copy(t,0),r&&(y(t)?r(t):r(t,e.Errors.BAD_CRC()))});break;default:throw t&&r&&r(Buffer.alloc(0),e.Errors.UNKNOWN_METHOD()),e.Errors.UNKNOWN_METHOD()}}function E(t,r){if((!l||!l.length)&&Buffer.isBuffer(i))return t&&r&&r(g()),g();if(l.length&&!u){var o;switch(s.method){case e.Constants.STORED:return s.compressedSize=s.size,o=Buffer.alloc(l.length),l.copy(o),t&&r&&r(o),o;default:case e.Constants.DEFLATED:var a=new n.Deflater(l);if(!t){var c=a.deflate();return s.compressedSize=c.length,c}a.deflateAsync(function(e){o=Buffer.alloc(e.length),s.compressedSize=e.length,e.copy(o),r&&r(o)}),a=null}}else{if(!t||!r)return Buffer.alloc(0);r(Buffer.alloc(0))}}function b(e,t){return(e.readUInt32LE(t+4)<<4)+e.readUInt32LE(t)}function w(e){var t,n,o,i;e.length>=r.EF_ZIP64_SCOMP&&(t=b(e,r.EF_ZIP64_SUNCOMP),s.size===r.EF_ZIP64_OR_32&&(s.size=t)),e.length>=r.EF_ZIP64_RHO&&(n=b(e,r.EF_ZIP64_SCOMP),s.compressedSize===r.EF_ZIP64_OR_32&&(s.compressedSize=n)),e.length>=r.EF_ZIP64_DSN&&(o=b(e,r.EF_ZIP64_RHO),s.offset===r.EF_ZIP64_OR_32&&(s.offset=o)),e.length>=r.EF_ZIP64_DSN+4&&(i=e.readUInt32LE(r.EF_ZIP64_DSN),s.diskNumStart===r.EF_ZIP64_OR_16&&(s.diskNumStart=i))}return f=!!m.hasOwnProperty("efs")&&m.efs,{get entryName(){return m.decode(a)},get rawEntryName(){return a},set entryName(t){var r=(a=e.toBuffer(t,m.encode))[a.length-1];u=47===r||92===r,s.fileNameLength=a.length},get efs(){return"function"==typeof f?f(this.entryName):f},get extra(){return h},set extra(t){h=t,s.extraLength=t.length,function(t){try{for(var n,o,i,s=0;s+4<t.length;)n=t.readUInt16LE(s),s+=2,o=t.readUInt16LE(s),s+=2,i=t.slice(s,s+o),s+=o,r.ID_ZIP64===n&&w(i)}catch(t){throw e.Errors.EXTRA_FIELD_PARSE_ERROR()}}(t)},get comment(){return m.decode(c)},set comment(t){if(c=e.toBuffer(t,m.encode),s.commentLength=c.length,c.length>65535)throw e.Errors.COMMENT_TOO_LONG()},get name(){var e=m.decode(a);return u?e.substr(e.length-1).split("/").pop():e.split("/").pop()},get isDirectory(){return u},getCompressedData:function(){return E(!1,null)},getCompressedDataAsync:function(e){E(!0,e)},setData:function(t){l=e.toBuffer(t,e.decoder.encode),!u&&l.length?(s.size=l.length,s.method=e.Constants.DEFLATED,s.crc=e.crc32(t),s.changed=!0):s.method=e.Constants.STORED},getData:function(e){return s.changed?l:v(!1,null,e)},getDataAsync:function(e,t){s.changed?e(l):v(!0,e,t)},set attr(e){s.attr=e},get attr(){return s.attr},set header(e){s.loadFromBinary(e)},get header(){return s},packCentralHeader:function(){s.flags_efs=this.efs,s.extraLength=h.length;var t=s.centralHeaderToBinary(),r=e.Constants.CENHDR;return a.copy(t,r),r+=a.length,h.copy(t,r),r+=s.extraLength,c.copy(t,r),t},packLocalHeader:function(){let e=0;s.flags_efs=this.efs,s.extraLocalLength=d.length;const t=s.localHeaderToBinary(),r=Buffer.alloc(t.length+a.length+s.extraLocalLength);return t.copy(r,e),e+=t.length,a.copy(r,e),e+=a.length,d.copy(r,e),e+=d.length,r},toJSON:function(){const e=function(e){return"<"+(e&&e.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:s.toJSON(),compressedData:e(i),data:e(l)}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}},At}function $t(){if(Rt)return kt;Rt=1;const e=Mt(),t=Et(),r=ht();return kt=function(n,o){var i=[],s={},a=Buffer.alloc(0),c=new t.MainHeader,u=!1;const l=new Set,h=o,{noSort:d,decoder:f}=h;function p(){if(u=!0,s={},c.diskEntries>(n.length-c.offset)/r.Constants.CENHDR)throw r.Errors.DISK_ENTRY_TOO_LARGE();i=new Array(c.diskEntries);for(var t=c.offset,o=0;o<i.length;o++){var a=t,d=new e(h,n);d.header=n.slice(a,a+=r.Constants.CENHDR),d.entryName=n.slice(a,a+=d.header.fileNameLength),d.header.extraLength&&(d.extra=n.slice(a,a+=d.header.extraLength)),d.header.commentLength&&(d.comment=n.slice(a,a+d.header.commentLength)),t+=d.header.centralHeaderSize,i[o]=d,s[d.entryName]=d}l.clear(),function(){const t=new Set;for(const e of Object.keys(s)){const r=e.split("/");if(r.pop(),r.length)for(let e=0;e<r.length;e++){const n=r.slice(0,e+1).join("/")+"/";t.add(n)}}for(const r of t)if(!(r in s)){const t=new e(h);t.entryName=r,t.attr=16,t.temporary=!0,i.push(t),s[t.entryName]=t,l.add(t)}}()}function m(){i.length>1&&!d&&i.sort((e,t)=>e.entryName.toLowerCase().localeCompare(t.entryName.toLowerCase()))}return n?function(e){var t=n.length-r.Constants.ENDHDR,o=Math.max(0,t-65535),i=o,s=n.length,u=-1,l=0;"boolean"==typeof h.trailingSpace&&h.trailingSpace&&(o=0);for(;t>=i;t--)if(80===n[t])if(n.readUInt32LE(t)!==r.Constants.ENDSIG)if(n.readUInt32LE(t)!==r.Constants.END64SIG){if(n.readUInt32LE(t)===r.Constants.ZIP64SIG){u=t,s=t+r.readBigUInt64LE(n,t+r.Constants.ZIP64SIZE)+r.Constants.ZIP64LEAD;break}}else i=o;else u=t,l=t,s=t+r.Constants.ENDHDR,i=t-r.Constants.END64HDR;if(-1==u)throw r.Errors.INVALID_FORMAT();c.loadFromBinary(n.slice(u,s)),c.commentLength&&(a=n.slice(l+r.Constants.ENDHDR));e&&p()}(h.readEntries):u=!0,{get entries(){return u||p(),i.filter(e=>!l.has(e))},get comment(){return f.decode(a)},set comment(e){a=r.toBuffer(e,f.encode),c.commentLength=a.length},getEntryCount:function(){return u?i.length:c.diskEntries},forEach:function(e){this.entries.forEach(e)},getEntry:function(e){return u||p(),s[e]||null},setEntry:function(e){u||p(),i.push(e),s[e.entryName]=e,c.totalEntries=i.length},deleteFile:function(e,t=!0){u||p();const r=s[e];this.getEntryChildren(r,t).map(e=>e.entryName).forEach(this.deleteEntry)},deleteEntry:function(e){u||p();const t=s[e],r=i.indexOf(t);r>=0&&(i.splice(r,1),delete s[e],c.totalEntries=i.length)},getEntryChildren:function(e,t=!0){if(u||p(),"object"==typeof e){if(e.isDirectory&&t){const t=[],r=e.entryName;for(const e of i)e.entryName.startsWith(r)&&t.push(e);return t}return[e]}return[]},getChildCount:function(e){if(e&&e.isDirectory){const t=this.getEntryChildren(e);return t.includes(e)?t.length-1:t.length}return 0},compressToBuffer:function(){u||p(),m();const e=[],t=[];let o=0,i=0;c.size=0,c.offset=0;let s=0;for(const r of this.entries){const n=r.getCompressedData();r.header.offset=i;const a=r.packLocalHeader(),u=a.length+n.length;i+=u,e.push(a),e.push(n);const l=r.packCentralHeader();t.push(l),c.size+=l.length,o+=u+l.length,s++}o+=c.mainHeaderSize,c.offset=i,c.totalEntries=s,i=0;const l=Buffer.alloc(o);for(const t of e)t.copy(l,i),i+=t.length;for(const e of t)e.copy(l,i),i+=e.length;const h=c.toBinary();return a&&a.copy(h,r.Constants.ENDHDR),h.copy(l,i),n=l,u=!1,l},toAsyncBuffer:function(e,t,o,i){try{u||p(),m();const t=[],s=[];let l=0,h=0,d=0;c.size=0,c.offset=0;const f=function(p){if(p.length>0){const e=p.shift(),r=e.entryName+e.extra.toString();o&&o(r),e.getCompressedDataAsync(function(n){i&&i(r),e.header.offset=h;const o=e.packLocalHeader(),a=o.length+n.length;h+=a,t.push(o),t.push(n);const u=e.packCentralHeader();s.push(u),c.size+=u.length,l+=a+u.length,d++,f(p)})}else{l+=c.mainHeaderSize,c.offset=h,c.totalEntries=d,h=0;const o=Buffer.alloc(l);t.forEach(function(e){e.copy(o,h),h+=e.length}),s.forEach(function(e){e.copy(o,h),h+=e.length});const i=c.toBinary();a&&a.copy(i,r.Constants.ENDHDR),i.copy(o,h),n=o,u=!1,e(o)}};f(Array.from(this.entries))}catch(e){t(e)}}}},kt}var Ut=function(){if(Nt)return Pt;Nt=1;const e=ht(),t=N,r=Mt(),n=$t(),o=(...t)=>e.findLast(t,e=>"boolean"==typeof e),i=(...t)=>e.findLast(t,e=>"string"==typeof e),s={noSort:!1,readEntries:!1,method:e.Constants.NONE,fs:null};return Pt=function(a,c){let u=null;const l=Object.assign(Object.create(null),s);a&&"object"==typeof a&&(a instanceof Uint8Array||(Object.assign(l,a),a=l.input?l.input:void 0,l.input&&delete l.input),Buffer.isBuffer(a)&&(u=a,l.method=e.Constants.BUFFER,a=void 0)),Object.assign(l,c);const h=new e(l);if("object"==typeof l.decoder&&"function"==typeof l.decoder.encode&&"function"==typeof l.decoder.decode||(l.decoder=e.decoder),a&&"string"==typeof a){if(!h.fs.existsSync(a))throw e.Errors.INVALID_FILENAME();l.method=e.Constants.FILE,l.filename=a,u=h.fs.readFileSync(a)}const d=new n(u,l),{canonical:f,sanitize:p,zipnamefix:m}=e;function g(e){var r;if(e&&d&&("string"==typeof e&&(r=d.getEntry(t.posix.normalize(e))),"object"==typeof e&&void 0!==e.entryName&&void 0!==e.header&&(r=d.getEntry(e.entryName)),r))return r;return null}function y(e){const{join:r,normalize:n,sep:o}=t.posix;return r(".",n(o+e.split("\\").join(o)+o))}function v(e){return e instanceof RegExp?(t=e,function(e){return t.test(e)}):"function"!=typeof e?()=>!0:e;var t}const E=(e,r)=>{let n=r.slice(-1);return n=n===h.sep?h.sep:"",t.relative(e,r)+n};return{readFile:function(e,t){var r=g(e);return r&&r.getData(t)||null},childCount:function(e){const t=g(e);if(t)return d.getChildCount(t)},readFileAsync:function(e,t){var r=g(e);r?r.getDataAsync(t):t(null,"getEntry failed for:"+e)},readAsText:function(e,t){var r=g(e);if(r){var n=r.getData();if(n&&n.length)return n.toString(t||"utf8")}return""},readAsTextAsync:function(e,t,r){var n=g(e);n?n.getDataAsync(function(e,n){n?t(e,n):e&&e.length?t(e.toString(r||"utf8")):t("")}):t("")},deleteFile:function(e,t=!0){var r=g(e);r&&d.deleteFile(r.entryName,t)},deleteEntry:function(e){var t=g(e);t&&d.deleteEntry(t.entryName)},addZipComment:function(e){d.comment=e},getZipComment:function(){return d.comment||""},addZipEntryComment:function(e,t){var r=g(e);r&&(r.comment=t)},getZipEntryComment:function(e){var t=g(e);return t&&t.comment||""},updateFile:function(e,t){var r=g(e);r&&r.setData(t)},addLocalFile:function(r,n,o,i){if(!h.fs.existsSync(r))throw e.Errors.FILE_NOT_FOUND(r);{n=n?y(n):"";const e=t.win32.basename(t.win32.normalize(r));n+=o||e;const s=h.fs.statSync(r),a=s.isFile()?h.fs.readFileSync(r):Buffer.alloc(0);s.isDirectory()&&(n+=h.sep),this.addFile(n,a,i,s)}},addLocalFileAsync:function(e,r){e="object"==typeof e?e:{localPath:e};const n=t.resolve(e.localPath),{comment:o}=e;let{zipPath:i,zipName:s}=e;const a=this;h.fs.stat(n,function(e,c){if(e)return r(e,!1);i=i?y(i):"";const u=t.win32.basename(t.win32.normalize(n));if(i+=s||u,c.isFile())h.fs.readFile(n,function(e,t){return e?r(e,!1):(a.addFile(i,t,o,c),setImmediate(r,void 0,!0))});else if(c.isDirectory())return i+=h.sep,a.addFile(i,Buffer.alloc(0),o,c),setImmediate(r,void 0,!0)})},addLocalFolder:function(r,n,o){if(o=v(o),n=n?y(n):"",r=t.normalize(r),!h.fs.existsSync(r))throw e.Errors.FILE_NOT_FOUND(r);{const e=h.findFiles(r),i=this;if(e.length)for(const s of e){const e=t.join(n,E(r,s));o(e)&&i.addLocalFile(s,t.dirname(e))}}},addLocalFolderAsync:function(r,n,o,i){i=v(i),o=o?y(o):"",r=t.normalize(r);var s=this;h.fs.open(r,"r",function(t){if(t&&"ENOENT"===t.code)n(void 0,e.Errors.FILE_NOT_FOUND(r));else if(t)n(void 0,t);else{var a=h.findFiles(r),c=-1,u=function(){if((c+=1)<a.length){var e=a[c],t=E(r,e).split("\\").join("/");t=t.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),i(t)?h.fs.stat(e,function(r,i){r&&n(void 0,r),i.isFile()?h.fs.readFile(e,function(e,r){e?n(void 0,e):(s.addFile(o+t,r,"",i),u())}):(s.addFile(o+t+"/",Buffer.alloc(0),"",i),u())}):process.nextTick(()=>{u()})}else n(!0,void 0)};u()}})},addLocalFolderAsync2:function(r,n){const o=this;r="object"==typeof r?r:{localPath:r},localPath=t.resolve(y(r.localPath));let{zipPath:i,filter:s,namefix:a}=r;var c;s instanceof RegExp?(c=s,s=function(e){return c.test(e)}):"function"!=typeof s&&(s=function(){return!0}),i=i?y(i):"","latin1"==a&&(a=e=>e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),"function"!=typeof a&&(a=e=>e);const u=e=>t.join(i,a(E(localPath,e))),l=e=>t.win32.basename(t.win32.normalize(a(e)));h.fs.open(localPath,"r",function(r){r&&"ENOENT"===r.code?n(void 0,e.Errors.FILE_NOT_FOUND(localPath)):r?n(void 0,r):h.findFilesAsync(localPath,function(e,r){if(e)return n(e);(r=r.filter(e=>s(u(e)))).length||n(void 0,!1),setImmediate(r.reverse().reduce(function(e,r){return function(n,i){if(n||!1===i)return setImmediate(e,n,!1);o.addLocalFileAsync({localPath:r,zipPath:t.dirname(u(r)),zipName:l(r)},e)}},n))})})},addLocalFolderPromise:function(e,t){return new Promise((r,n)=>{this.addLocalFolderAsync2(Object.assign({localPath:e},t),(e,t)=>{e&&n(e),t&&r(this)})})},addFile:function(e,t,n,o){let i=g(e=m(e));const s=null!=i;s||(i=new r(l),i.entryName=e),i.comment=n||"";const a="object"==typeof o&&o instanceof h.fs.Stats;a&&(i.header.time=o.mtime);var c=i.isDirectory?16:0;let u=i.isDirectory?16384:32768;return u|=a?4095&o.mode:"number"==typeof o?4095&o:i.isDirectory?493:420,c=(c|u<<16)>>>0,i.attr=c,i.setData(t),s||d.setEntry(i),i},getEntries:function(e){return d.password=e,d?d.entries:[]},getEntry:function(e){return g(e)},getEntryCount:function(){return d.getEntryCount()},forEach:function(e){return d.forEach(e)},extractEntryTo:function(r,n,s,a,c,u){a=o(!1,a),c=o(!1,c),s=o(!0,s),u=i(c,u);var l=g(r);if(!l)throw e.Errors.NO_ENTRY();var m=f(l.entryName),y=p(n,u&&!l.isDirectory?u:s?m:t.basename(m));if(l.isDirectory)return d.getEntryChildren(l).forEach(function(r){if(r.isDirectory)return;var o=r.getData();if(!o)throw e.Errors.CANT_EXTRACT_FILE();var i=f(r.entryName),u=p(n,s?i:t.basename(i));const l=c?r.header.fileAttr:void 0;h.writeFileTo(u,o,a,l)}),!0;var v=l.getData(d.password);if(!v)throw e.Errors.CANT_EXTRACT_FILE();if(h.fs.existsSync(y)&&!a)throw e.Errors.CANT_OVERRIDE();const E=c?r.header.fileAttr:void 0;return h.writeFileTo(y,v,a,E),!0},test:function(e){if(!d)return!1;for(var t in d.entries)try{if(t.isDirectory)continue;if(!d.entries[t].getData(e))return!1}catch(e){return!1}return!0},extractAllTo:function(t,r,n,s){if(n=o(!1,n),s=i(n,s),r=o(!1,r),!d)throw e.Errors.NO_ZIP();d.entries.forEach(function(o){var i=p(t,f(o.entryName));if(o.isDirectory)return void h.makeDir(i);var a=o.getData(s);if(!a)throw e.Errors.CANT_EXTRACT_FILE();const c=n?o.header.fileAttr:void 0;h.writeFileTo(i,a,r,c);try{h.fs.utimesSync(i,o.header.time,o.header.time)}catch(t){throw e.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(r,n,i,s){if(s=((...t)=>e.findLast(t,e=>"function"==typeof e))(n,i,s),i=o(!1,i),n=o(!1,n),!s)return new Promise((e,t)=>{this.extractAllToAsync(r,n,i,function(r){r?t(r):e(this)})});if(!d)return void s(e.Errors.NO_ZIP());r=t.resolve(r);const a=e=>p(r,t.normalize(f(e.entryName))),c=(e,t)=>new Error(e+': "'+t+'"'),u=[],l=[];d.entries.forEach(e=>{e.isDirectory?u.push(e):l.push(e)});for(const e of u){const t=a(e),r=i?e.header.fileAttr:void 0;try{h.makeDir(t),r&&h.fs.chmodSync(t,r),h.fs.utimesSync(t,e.header.time,e.header.time)}catch(e){s(c("Unable to create folder",t))}}l.reverse().reduce(function(o,s){return function(a){if(a)o(a);else{const a=t.normalize(f(s.entryName)),u=p(r,a);s.getDataAsync(function(t,r){if(r)o(r);else if(t){const e=i?s.header.fileAttr:void 0;h.writeFileToAsync(u,t,n,e,function(e){e||o(c("Unable to write file",u)),h.fs.utimes(u,s.header.time,s.header.time,function(e){e?o(c("Unable to set times",u)):o()})})}else o(e.Errors.CANT_EXTRACT_FILE())})}}},s)()},writeZip:function(e,t){if(1===arguments.length&&"function"==typeof e&&(t=e,e=""),!e&&l.filename&&(e=l.filename),e){var r=d.compressToBuffer();if(r){var n=h.writeFileTo(e,r,!0);"function"==typeof t&&t(n?null:new Error("failed"),"")}}},writeZipPromise:function(e,t){const{overwrite:r,perm:n}=Object.assign({overwrite:!0},t);return new Promise((t,o)=>{!e&&l.filename&&(e=l.filename),e||o("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(i=>{h.writeFileToAsync(e,i,r,n,e=>e?t(e):o("ADM-ZIP: Wasn't able to write zip file"))},o)})},toBufferPromise:function(){return new Promise((e,t)=>{d.toAsyncBuffer(e,t)})},toBuffer:function(e,t,r,n){return"function"==typeof e?(d.toAsyncBuffer(e,t,r,n),null):d.compressToBuffer()}}},Pt}(),Ft=Qe(Ut);class jt{#e;get ora(){return this.#e}set attachConsole(e){e?(console.log=this.info.bind(this),console.info=this.info.bind(this)):console=Ht}static Global(e){return Bt=new jt(e),Bt}static Clone(e){const{prefixText:t}=e||Bt;return new jt({prefixText:t})}static get Current(){return Bt}static set Current(e){Bt=e}constructor(e){this.#e=x(e)}get prefixText(){return this.#e.prefixText}info(...e){this.#e.info(qt(e))}succeed(...e){this.#e.succeed(qt(e))}start(...e){this.#e.start(qt(e))}fail(...e){this.#e.fail(qt(e))}warn(...e){this.#e.warn(qt(e))}clear(){this.#e.clear()}stop(){this.#e.stop()}stopAndPersist(...e){this.#e.stopAndPersist(...e)}}let Bt=new jt;const qt=e=>e.length?e.join(" "):void 0,Ht=console;let Gt=class{spinner;debugMode;constructor(e,t){this.spinner=new jt({prefixText:e}),this.debugMode=t?.debug??!1}start(...e){this.spinner.start(...e)}succeed(...e){this.spinner.succeed(...e)}fail(...e){this.spinner.fail(...e)}error(...e){console.log(...e)}warn(...e){this.spinner.warn(...e)}info(...e){this.spinner.info(...e)}log(...e){this.spinner.info(...e)}debug(...e){this.debugMode&&console.debug(...e)}startNativeConsoleCapture(){this.spinner.attachConsole=!0}stopNativeConsoleCapture(){this.spinner.attachConsole=!1}};const zt=e=>{const t={spa:{templateEnv:(r=e.template,{portal:{id:"@equinor/fusion-framework-dev-portal"},title:"Fusion Dev Portal",serviceDiscovery:{url:"/@fusion-services",scopes:["5a842df8-3238-415d-b168-9f16a6a6031b/.default"]},msal:{clientId:"9b707e3a-3e90-41ed-a47e-652a1e3b53d0",tenantId:"3aa4a235-b6e2-48d5-9195-7fcf05b459b0",redirectUri:"/authentication/login-callback",requiresAuth:"true"},serviceWorker:{resources:[{url:"/apps-proxy",rewrite:"/@fusion-api/apps",scopes:["5a842df8-3238-415d-b168-9f16a6a6031b/.default"]},{url:"/help-proxy",rewrite:"/@fusion-api/help",scopes:["5a842df8-3238-415d-b168-9f16a6a6031b/.default"]}]},...r})},api:{serviceDiscoveryUrl:"https://discovery.fusion.equinor.com/service-registry/environments/ci/services/",processServices:(e,t)=>{const{data:r,routes:n}=$(e,t);return{data:r.concat({key:"portals",name:"Portal Service - MOCK",uri:"/@fusion-api/portals"}),routes:n}}}};var r;return e.app&&((e,t,r)=>{const{build:n,appKey:o}=t;if(!n)throw new Error("App manifest does not contain build information");e.api.routes??=[],e.api.routes.push({match:`/apps/bundles/apps/${o}@${n.version}/*path`,middleware:async(e,t,r)=>{const n=e.params?.path;!1===Array.isArray(n)&&r(),t.writeHead(302,{"content-type":"application/javascript",location:`/${n.join("/")}`}),t.end()}}),e.api.routes.push({match:`/apps/persons/me/apps/${o}`,middleware:async(e,r)=>{r.writeHead(200,{"content-type":"application/json"}),r.end(JSON.stringify({id:"dev-server-generated-id",...t}))}}),e.api.routes.push({match:`/apps/apps/${o}/builds/${n.version}/config`,middleware:async(e,t)=>{t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify(r))}})})(t,e.app.manifest,e.app.config),e.portal&&((e,t,r)=>{e.api.routes??=[];const n="portal-config";e.api.routes.push({match:`/${n}/portals/${t.name}{@:tag}`,middleware:async(e,r)=>{r.writeHead(200,{"content-type":"application/json"}),r.end(JSON.stringify(t))}}),r&&e.api.routes.push({match:`/${n}/portals/${t.name}{@:tag}/config`,middleware:async(e,t)=>{t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify(r))}})})(t,e.portal.manifest,e.portal.config),t},Kt=async(e,t,r)=>{const n=zt(t),o=await Te(e,n).catch(()=>({config:n}));return M(o.config,r)},Vt=(e,t,r)=>{const n=o(String(e));m(n)||g(n,{recursive:!0}),y(e,t,r)},Yt=["package.json","LICENSE.md","README.md","CHANGELOG.md"],Wt=async(e,t)=>{const{archive:r,log:n}=t??{},s=o(e.path),a=t?.buildDir??"dist",c=i(s,a);if(!(await E(c)).isDirectory())throw new Error(`Build directory ${a} does not exist`);n?.log(we.bold("Starting to pack bundle"));const u=new Ft;if(u.addLocalFolder(c,a),t?.content)for(const[e,r]of Object.entries(t.content))u.addFile(e,Buffer.from(r)),n?.info("📄",Ge(e,{relative:!0}));n?.info("📂",Ge(c,{relative:!0}));for(const t of Yt.concat(e.packageJson.files??[])){const e=i(s,t),r=o(e.replace(s,""));Ie(e)?(u.addLocalFile(e,r),n?.info("📄",Ge(e,{relative:!0}))):n?.warn(we.dim("📄",Ge(e,{relative:!0})))}return r&&(Ie(o(r))||await b(o(r),{recursive:!0}),n?.start("compressing content"),await u.writeZipPromise(r),n?.succeed("📚",Ge(r,{relative:!0}),ze(r))),u},Qt=async e=>{const{log:t,manifest:r}=e;process.env.NODE_ENV,process.cwd();const{pkg:n,manifest:o}=await We({log:t,manifest:r});if(!o.build)throw new Error("Manifest build config not found");return{archive:await Wt(n,{log:t,archive:e?.archive,content:{"app-manifest.json":JSON.stringify(o.build,null,2),"metadata.json":JSON.stringify({name:o.appKey,version:o.build.version})}}).catch(e=>{t?.error("Failed to create package:",e),process.exit(1)}),manifest:o}},Jt=async(e,t)=>{const{log:r}=t;try{r?.start("create application configuration"),r?.info(`generating config with ${we.red.dim(e.command)} command in ${we.green.dim(e.mode)} mode`);const n=await((e,t)=>{const r=t?.file??[`app.config.${e.environment}`,"app.config"];return I(r,{baseDir:e.root,extensions:t?.extensions,script:{resolve:async r=>{const n=t?.base??{environment:{}};if("function"==typeof r.default){const t=await r.default(e,{base:n})??n;return Me.parse(t??n)}return Me.parse(r.default??n)}}})})(e,{file:t?.config});return r?.succeed("⚙️ generated config from ",Ge(n.path,{relative:!0})),n.config}catch(e){if(e instanceof C){if(!t.config)return r?.succeed(we.dim("⚙️ no local application config applied, using built-in")),{environment:{}};r?.warn(`failed to load config file ${Ge(t.config)}, please check the path.`)}throw r?.fail("failed to resolve application config"),r?.debug(e),e}},Zt=async e=>{const{log:t}=e??{},r=await Ve(t),n={command:"build",mode:process.env.NODE_ENV??"production",root:r.root,...e?.env},o=await Jt(n,{log:t,config:e?.config});if(t?.debug("config:",o),e?.output){t?.start("writing config to file");try{await Vt(e.output,JSON.stringify(o,null,2)),t?.succeed("config written successfully",Ge(e.output,{relative:!0}))}catch(e){throw t?.fail("failed to write config"),e}}return{config:o,pkg:r}};class Xt extends Error{response;static Name="HttpResponseError";constructor(e,t,r){super(e,r),this.response=t}}class er extends Xt{static Name="HttpJsonResponseError";data;constructor(e,t,r){super(e,t,r),this.name=er.Name,this.data=r?.data}}class tr extends Xt{static Name="ServerSentEventResponseError";constructor(e,t,r){super(e,t,r),this.name=tr.Name}}var rr,nr,or,ir,sr,ar,cr,ur,lr,hr,dr,fr,pr,mr,gr,yr,vr,Er,br,wr,Ir,Cr,_r,Tr,Sr,Ar,Or,kr,Rr,Pr,Nr,Lr,Dr,xr,Mr,$r,Ur,Fr,jr,Br,qr,Hr,Gr,zr,Kr,Vr,Yr,Wr,Qr,Jr,Zr,Xr,en,tn,rn,nn,on,sn,an,cn,un,ln,hn,dn,fn,pn,mn,gn,yn,vn,En,bn,wn,In,Cn,_n,Tn,Sn,An,On,kn,Rn,Pn,Nn,Ln,Dn,xn,Mn,$n,Un={exports:{}};function Fn(){if(nr)return rr;nr=1;const e=Number.MAX_SAFE_INTEGER||9007199254740991;return rr={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:e,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}}function jn(){if(ir)return or;ir=1;const e="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};return or=e}function Bn(){return sr||(sr=1,function(e,t){const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:o}=Fn(),i=jn(),s=(t=e.exports={}).re=[],a=t.safeRe=[],c=t.src=[],u=t.safeSrc=[],l=t.t={};let h=0;const d="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",o],[d,n]],p=(e,t,r)=>{const n=(e=>{for(const[t,r]of f)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e})(t),o=h++;i(e,o,t),l[e]=o,c[o]=t,u[o]=n,s[o]=new RegExp(t,r?"g":void 0),a[o]=new RegExp(n,r?"g":void 0)};p("NUMERICIDENTIFIER","0|[1-9]\\d*"),p("NUMERICIDENTIFIERLOOSE","\\d+"),p("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${d}*`),p("MAINVERSION",`(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})`),p("MAINVERSIONLOOSE",`(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})`),p("PRERELEASEIDENTIFIER",`(?:${c[l.NONNUMERICIDENTIFIER]}|${c[l.NUMERICIDENTIFIER]})`),p("PRERELEASEIDENTIFIERLOOSE",`(?:${c[l.NONNUMERICIDENTIFIER]}|${c[l.NUMERICIDENTIFIERLOOSE]})`),p("PRERELEASE",`(?:-(${c[l.PRERELEASEIDENTIFIER]}(?:\\.${c[l.PRERELEASEIDENTIFIER]})*))`),p("PRERELEASELOOSE",`(?:-?(${c[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[l.PRERELEASEIDENTIFIERLOOSE]})*))`),p("BUILDIDENTIFIER",`${d}+`),p("BUILD",`(?:\\+(${c[l.BUILDIDENTIFIER]}(?:\\.${c[l.BUILDIDENTIFIER]})*))`),p("FULLPLAIN",`v?${c[l.MAINVERSION]}${c[l.PRERELEASE]}?${c[l.BUILD]}?`),p("FULL",`^${c[l.FULLPLAIN]}$`),p("LOOSEPLAIN",`[v=\\s]*${c[l.MAINVERSIONLOOSE]}${c[l.PRERELEASELOOSE]}?${c[l.BUILD]}?`),p("LOOSE",`^${c[l.LOOSEPLAIN]}$`),p("GTLT","((?:<|>)?=?)"),p("XRANGEIDENTIFIERLOOSE",`${c[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),p("XRANGEIDENTIFIER",`${c[l.NUMERICIDENTIFIER]}|x|X|\\*`),p("XRANGEPLAIN",`[v=\\s]*(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:${c[l.PRERELEASE]})?${c[l.BUILD]}?)?)?`),p("XRANGEPLAINLOOSE",`[v=\\s]*(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:${c[l.PRERELEASELOOSE]})?${c[l.BUILD]}?)?)?`),p("XRANGE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAIN]}$`),p("XRANGELOOSE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAINLOOSE]}$`),p("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),p("COERCE",`${c[l.COERCEPLAIN]}(?:$|[^\\d])`),p("COERCEFULL",c[l.COERCEPLAIN]+`(?:${c[l.PRERELEASE]})?`+`(?:${c[l.BUILD]})?(?:$|[^\\d])`),p("COERCERTL",c[l.COERCE],!0),p("COERCERTLFULL",c[l.COERCEFULL],!0),p("LONETILDE","(?:~>?)"),p("TILDETRIM",`(\\s*)${c[l.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",p("TILDE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAIN]}$`),p("TILDELOOSE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAINLOOSE]}$`),p("LONECARET","(?:\\^)"),p("CARETTRIM",`(\\s*)${c[l.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",p("CARET",`^${c[l.LONECARET]}${c[l.XRANGEPLAIN]}$`),p("CARETLOOSE",`^${c[l.LONECARET]}${c[l.XRANGEPLAINLOOSE]}$`),p("COMPARATORLOOSE",`^${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]})$|^$`),p("COMPARATOR",`^${c[l.GTLT]}\\s*(${c[l.FULLPLAIN]})$|^$`),p("COMPARATORTRIM",`(\\s*)${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]}|${c[l.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",p("HYPHENRANGE",`^\\s*(${c[l.XRANGEPLAIN]})\\s+-\\s+(${c[l.XRANGEPLAIN]})\\s*$`),p("HYPHENRANGELOOSE",`^\\s*(${c[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[l.XRANGEPLAINLOOSE]})\\s*$`),p("STAR","(<|>)?=?\\s*\\*"),p("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),p("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}(Un,Un.exports)),Un.exports}function qn(){if(cr)return ar;cr=1;const e=Object.freeze({loose:!0}),t=Object.freeze({});return ar=r=>r?"object"!=typeof r?e:r:t}function Hn(){if(lr)return ur;lr=1;const e=/^[0-9]+$/,t=(t,r)=>{const n=e.test(t),o=e.test(r);return n&&o&&(t=+t,r=+r),t===r?0:n&&!o?-1:o&&!n?1:t<r?-1:1};return ur={compareIdentifiers:t,rcompareIdentifiers:(e,r)=>t(r,e)},ur}function Gn(){if(dr)return hr;dr=1;const e=jn(),{MAX_LENGTH:t,MAX_SAFE_INTEGER:r}=Fn(),{safeRe:n,t:o}=Bn(),i=qn(),{compareIdentifiers:s}=Hn();class a{constructor(s,c){if(c=i(c),s instanceof a){if(s.loose===!!c.loose&&s.includePrerelease===!!c.includePrerelease)return s;s=s.version}else if("string"!=typeof s)throw new TypeError(`Invalid version. Must be a string. Got type "${typeof s}".`);if(s.length>t)throw new TypeError(`version is longer than ${t} characters`);e("SemVer",s,c),this.options=c,this.loose=!!c.loose,this.includePrerelease=!!c.includePrerelease;const u=s.trim().match(c.loose?n[o.LOOSE]:n[o.FULL]);if(!u)throw new TypeError(`Invalid Version: ${s}`);if(this.raw=s,this.major=+u[1],this.minor=+u[2],this.patch=+u[3],this.major>r||this.major<0)throw new TypeError("Invalid major version");if(this.minor>r||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>r||this.patch<0)throw new TypeError("Invalid patch version");u[4]?this.prerelease=u[4].split(".").map(e=>{if(/^[0-9]+$/.test(e)){const t=+e;if(t>=0&&t<r)return t}return e}):this.prerelease=[],this.build=u[5]?u[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(e("SemVer.compare",this.version,this.options,t),!(t instanceof a)){if("string"==typeof t&&t===this.version)return 0;t=new a(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(e){return e instanceof a||(e=new a(e,this.options)),s(this.major,e.major)||s(this.minor,e.minor)||s(this.patch,e.patch)}comparePre(t){if(t instanceof a||(t=new a(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{const n=this.prerelease[r],o=t.prerelease[r];if(e("prerelease compare",r,n,o),void 0===n&&void 0===o)return 0;if(void 0===o)return 1;if(void 0===n)return-1;if(n!==o)return s(n,o)}while(++r)}compareBuild(t){t instanceof a||(t=new a(t,this.options));let r=0;do{const n=this.build[r],o=t.build[r];if(e("build compare",r,n,o),void 0===n&&void 0===o)return 0;if(void 0===o)return 1;if(void 0===n)return-1;if(n!==o)return s(n,o)}while(++r)}inc(e,t,r){if(e.startsWith("pre")){if(!t&&!1===r)throw new Error("invalid increment argument: identifier is empty");if(t){const e=`-${t}`.match(this.options.loose?n[o.PRERELEASELOOSE]:n[o.PRERELEASE]);if(!e||e[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,r),this.inc("pre",t,r);break;case"prerelease":0===this.prerelease.length&&this.inc("patch",t,r),this.inc("pre",t,r);break;case"release":if(0===this.prerelease.length)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":0===this.minor&&0===this.patch&&0!==this.prerelease.length||this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":0===this.patch&&0!==this.prerelease.length||this.minor++,this.patch=0,this.prerelease=[];break;case"patch":0===this.prerelease.length&&this.patch++,this.prerelease=[];break;case"pre":{const e=Number(r)?1:0;if(0===this.prerelease.length)this.prerelease=[e];else{let n=this.prerelease.length;for(;--n>=0;)"number"==typeof this.prerelease[n]&&(this.prerelease[n]++,n=-2);if(-1===n){if(t===this.prerelease.join(".")&&!1===r)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(e)}}if(t){let n=[t,e];!1===r&&(n=[t]),0===s(this.prerelease[0],t)?isNaN(this.prerelease[1])&&(this.prerelease=n):this.prerelease=n}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return hr=a}function zn(){if(pr)return fr;pr=1;const e=Gn();return fr=(t,r,n=!1)=>{if(t instanceof e)return t;try{return new e(t,r)}catch(e){if(!n)return null;throw e}},fr}function Kn(){if(Nr)return Pr;Nr=1;const e=Gn();return Pr=(t,r,n)=>new e(t,n).compare(new e(r,n)),Pr}function Vn(){if(Ur)return $r;Ur=1;const e=Gn();return $r=(t,r,n)=>{const o=new e(t,n),i=new e(r,n);return o.compare(i)||o.compareBuild(i)},$r}function Yn(){if(Gr)return Hr;Gr=1;const e=Kn();return Hr=(t,r,n)=>e(t,r,n)>0,Hr}function Wn(){if(Kr)return zr;Kr=1;const e=Kn();return zr=(t,r,n)=>e(t,r,n)<0,zr}function Qn(){if(Yr)return Vr;Yr=1;const e=Kn();return Vr=(t,r,n)=>0===e(t,r,n),Vr}function Jn(){if(Qr)return Wr;Qr=1;const e=Kn();return Wr=(t,r,n)=>0!==e(t,r,n),Wr}function Zn(){if(Zr)return Jr;Zr=1;const e=Kn();return Jr=(t,r,n)=>e(t,r,n)>=0,Jr}function Xn(){if(en)return Xr;en=1;const e=Kn();return Xr=(t,r,n)=>e(t,r,n)<=0,Xr}function eo(){if(rn)return tn;rn=1;const e=Qn(),t=Jn(),r=Yn(),n=Zn(),o=Wn(),i=Xn();return tn=(s,a,c,u)=>{switch(a){case"===":return"object"==typeof s&&(s=s.version),"object"==typeof c&&(c=c.version),s===c;case"!==":return"object"==typeof s&&(s=s.version),"object"==typeof c&&(c=c.version),s!==c;case"":case"=":case"==":return e(s,c,u);case"!=":return t(s,c,u);case">":return r(s,c,u);case">=":return n(s,c,u);case"<":return o(s,c,u);case"<=":return i(s,c,u);default:throw new TypeError(`Invalid operator: ${a}`)}},tn}function to(){if(un)return cn;un=1;const e=/\s+/g;class t{constructor(r,i){if(i=n(i),r instanceof t)return r.loose===!!i.loose&&r.includePrerelease===!!i.includePrerelease?r:new t(r.raw,i);if(r instanceof o)return this.raw=r.value,this.set=[[r]],this.formatted=void 0,this;if(this.options=i,this.loose=!!i.loose,this.includePrerelease=!!i.includePrerelease,this.raw=r.trim().replace(e," "),this.set=this.raw.split("||").map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const e=this.set[0];if(this.set=this.set.filter(e=>!p(e[0])),0===this.set.length)this.set=[e];else if(this.set.length>1)for(const e of this.set)if(1===e.length&&m(e[0])){this.set=[e];break}}this.formatted=void 0}get range(){if(void 0===this.formatted){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");const t=this.set[e];for(let e=0;e<t.length;e++)e>0&&(this.formatted+=" "),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){const t=((this.options.includePrerelease&&d)|(this.options.loose&&f))+":"+e,n=r.get(t);if(n)return n;const s=this.options.loose,m=s?a[c.HYPHENRANGELOOSE]:a[c.HYPHENRANGE];e=e.replace(m,A(this.options.includePrerelease)),i("hyphen replace",e),e=e.replace(a[c.COMPARATORTRIM],u),i("comparator trim",e),e=e.replace(a[c.TILDETRIM],l),i("tilde trim",e),e=e.replace(a[c.CARETTRIM],h),i("caret trim",e);let g=e.split(" ").map(e=>y(e,this.options)).join(" ").split(/\s+/).map(e=>S(e,this.options));s&&(g=g.filter(e=>(i("loose invalid filter",e,this.options),!!e.match(a[c.COMPARATORLOOSE])))),i("range list",g);const v=new Map,E=g.map(e=>new o(e,this.options));for(const e of E){if(p(e))return[e];v.set(e.value,e)}v.size>1&&v.has("")&&v.delete("");const b=[...v.values()];return r.set(t,b),b}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some(t=>g(t,r)&&e.set.some(e=>g(e,r)&&t.every(t=>e.every(e=>t.intersects(e,r)))))}test(e){if(!e)return!1;if("string"==typeof e)try{e=new s(e,this.options)}catch(e){return!1}for(let t=0;t<this.set.length;t++)if(O(this.set[t],e,this.options))return!0;return!1}}cn=t;const r=new(an?sn:(an=1,sn=class{constructor(){this.max=1e3,this.map=new Map}get(e){const t=this.map.get(e);return void 0===t?void 0:(this.map.delete(e),this.map.set(e,t),t)}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&void 0!==t){if(this.map.size>=this.max){const e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}})),n=qn(),o=ro(),i=jn(),s=Gn(),{safeRe:a,t:c,comparatorTrimReplace:u,tildeTrimReplace:l,caretTrimReplace:h}=Bn(),{FLAG_INCLUDE_PRERELEASE:d,FLAG_LOOSE:f}=Fn(),p=e=>"<0.0.0-0"===e.value,m=e=>""===e.value,g=(e,t)=>{let r=!0;const n=e.slice();let o=n.pop();for(;r&&n.length;)r=n.every(e=>o.intersects(e,t)),o=n.pop();return r},y=(e,t)=>(i("comp",e,t),e=w(e,t),i("caret",e),e=E(e,t),i("tildes",e),e=C(e,t),i("xrange",e),e=T(e,t),i("stars",e),e),v=e=>!e||"x"===e.toLowerCase()||"*"===e,E=(e,t)=>e.trim().split(/\s+/).map(e=>b(e,t)).join(" "),b=(e,t)=>{const r=t.loose?a[c.TILDELOOSE]:a[c.TILDE];return e.replace(r,(t,r,n,o,s)=>{let a;return i("tilde",e,t,r,n,o,s),v(r)?a="":v(n)?a=`>=${r}.0.0 <${+r+1}.0.0-0`:v(o)?a=`>=${r}.${n}.0 <${r}.${+n+1}.0-0`:s?(i("replaceTilde pr",s),a=`>=${r}.${n}.${o}-${s} <${r}.${+n+1}.0-0`):a=`>=${r}.${n}.${o} <${r}.${+n+1}.0-0`,i("tilde return",a),a})},w=(e,t)=>e.trim().split(/\s+/).map(e=>I(e,t)).join(" "),I=(e,t)=>{i("caret",e,t);const r=t.loose?a[c.CARETLOOSE]:a[c.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(t,r,o,s,a)=>{let c;return i("caret",e,t,r,o,s,a),v(r)?c="":v(o)?c=`>=${r}.0.0${n} <${+r+1}.0.0-0`:v(s)?c="0"===r?`>=${r}.${o}.0${n} <${r}.${+o+1}.0-0`:`>=${r}.${o}.0${n} <${+r+1}.0.0-0`:a?(i("replaceCaret pr",a),c="0"===r?"0"===o?`>=${r}.${o}.${s}-${a} <${r}.${o}.${+s+1}-0`:`>=${r}.${o}.${s}-${a} <${r}.${+o+1}.0-0`:`>=${r}.${o}.${s}-${a} <${+r+1}.0.0-0`):(i("no pr"),c="0"===r?"0"===o?`>=${r}.${o}.${s}${n} <${r}.${o}.${+s+1}-0`:`>=${r}.${o}.${s}${n} <${r}.${+o+1}.0-0`:`>=${r}.${o}.${s} <${+r+1}.0.0-0`),i("caret return",c),c})},C=(e,t)=>(i("replaceXRanges",e,t),e.split(/\s+/).map(e=>_(e,t)).join(" ")),_=(e,t)=>{e=e.trim();const r=t.loose?a[c.XRANGELOOSE]:a[c.XRANGE];return e.replace(r,(r,n,o,s,a,c)=>{i("xRange",e,r,n,o,s,a,c);const u=v(o),l=u||v(s),h=l||v(a),d=h;return"="===n&&d&&(n=""),c=t.includePrerelease?"-0":"",u?r=">"===n||"<"===n?"<0.0.0-0":"*":n&&d?(l&&(s=0),a=0,">"===n?(n=">=",l?(o=+o+1,s=0,a=0):(s=+s+1,a=0)):"<="===n&&(n="<",l?o=+o+1:s=+s+1),"<"===n&&(c="-0"),r=`${n+o}.${s}.${a}${c}`):l?r=`>=${o}.0.0${c} <${+o+1}.0.0-0`:h&&(r=`>=${o}.${s}.0${c} <${o}.${+s+1}.0-0`),i("xRange return",r),r})},T=(e,t)=>(i("replaceStars",e,t),e.trim().replace(a[c.STAR],"")),S=(e,t)=>(i("replaceGTE0",e,t),e.trim().replace(a[t.includePrerelease?c.GTE0PRE:c.GTE0],"")),A=e=>(t,r,n,o,i,s,a,c,u,l,h,d)=>`${r=v(n)?"":v(o)?`>=${n}.0.0${e?"-0":""}`:v(i)?`>=${n}.${o}.0${e?"-0":""}`:s?`>=${r}`:`>=${r}${e?"-0":""}`} ${c=v(u)?"":v(l)?`<${+u+1}.0.0-0`:v(h)?`<${u}.${+l+1}.0-0`:d?`<=${u}.${l}.${h}-${d}`:e?`<${u}.${l}.${+h+1}-0`:`<=${c}`}`.trim(),O=(e,t,r)=>{for(let r=0;r<e.length;r++)if(!e[r].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let r=0;r<e.length;r++)if(i(e[r].semver),e[r].semver!==o.ANY&&e[r].semver.prerelease.length>0){const n=e[r].semver;if(n.major===t.major&&n.minor===t.minor&&n.patch===t.patch)return!0}return!1}return!0};return cn}function ro(){if(hn)return ln;hn=1;const e=Symbol("SemVer ANY");class t{static get ANY(){return e}constructor(n,o){if(o=r(o),n instanceof t){if(n.loose===!!o.loose)return n;n=n.value}n=n.trim().split(/\s+/).join(" "),s("comparator",n,o),this.options=o,this.loose=!!o.loose,this.parse(n),this.semver===e?this.value="":this.value=this.operator+this.semver.version,s("comp",this)}parse(t){const r=this.options.loose?n[o.COMPARATORLOOSE]:n[o.COMPARATOR],i=t.match(r);if(!i)throw new TypeError(`Invalid comparator: ${t}`);this.operator=void 0!==i[1]?i[1]:"","="===this.operator&&(this.operator=""),i[2]?this.semver=new a(i[2],this.options.loose):this.semver=e}toString(){return this.value}test(t){if(s("Comparator.test",t,this.options.loose),this.semver===e||t===e)return!0;if("string"==typeof t)try{t=new a(t,this.options)}catch(e){return!1}return i(t,this.operator,this.semver,this.options)}intersects(e,n){if(!(e instanceof t))throw new TypeError("a Comparator is required");return""===this.operator?""===this.value||new c(e.value,n).test(this.value):""===e.operator?""===e.value||new c(this.value,n).test(e.semver):(!(n=r(n)).includePrerelease||"<0.0.0-0"!==this.value&&"<0.0.0-0"!==e.value)&&(!(!n.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0")))&&(!(!this.operator.startsWith(">")||!e.operator.startsWith(">"))||(!(!this.operator.startsWith("<")||!e.operator.startsWith("<"))||(!(this.semver.version!==e.semver.version||!this.operator.includes("=")||!e.operator.includes("="))||(!!(i(this.semver,"<",e.semver,n)&&this.operator.startsWith(">")&&e.operator.startsWith("<"))||!!(i(this.semver,">",e.semver,n)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))))))}}ln=t;const r=qn(),{safeRe:n,t:o}=Bn(),i=eo(),s=jn(),a=Gn(),c=to();return ln}function no(){if(fn)return dn;fn=1;const e=to();return dn=(t,r,n)=>{try{r=new e(r,n)}catch(e){return!1}return r.test(t)},dn}function oo(){if(Cn)return In;Cn=1;const e=to();return In=(t,r)=>{try{return new e(t,r).range||"*"}catch(e){return null}},In}function io(){if(Tn)return _n;Tn=1;const e=Gn(),t=ro(),{ANY:r}=t,n=to(),o=no(),i=Yn(),s=Wn(),a=Xn(),c=Zn();return _n=(u,l,h,d)=>{let f,p,m,g,y;switch(u=new e(u,d),l=new n(l,d),h){case">":f=i,p=a,m=s,g=">",y=">=";break;case"<":f=s,p=c,m=i,g="<",y="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(o(u,l,d))return!1;for(let e=0;e<l.set.length;++e){const n=l.set[e];let o=null,i=null;if(n.forEach(e=>{e.semver===r&&(e=new t(">=0.0.0")),o=o||e,i=i||e,f(e.semver,o.semver,d)?o=e:m(e.semver,i.semver,d)&&(i=e)}),o.operator===g||o.operator===y)return!1;if((!i.operator||i.operator===g)&&p(u,i.semver))return!1;if(i.operator===y&&m(u,i.semver))return!1}return!0},_n}function so(){if($n)return Mn;$n=1;const e=Bn(),t=Fn(),r=Gn(),n=Hn(),o=zn(),i=function(){if(gr)return mr;gr=1;const e=zn();return mr=(t,r)=>{const n=e(t,r);return n?n.version:null},mr}(),s=function(){if(vr)return yr;vr=1;const e=zn();return yr=(t,r)=>{const n=e(t.trim().replace(/^[=v]+/,""),r);return n?n.version:null},yr}(),a=function(){if(br)return Er;br=1;const e=Gn();return Er=(t,r,n,o,i)=>{"string"==typeof n&&(i=o,o=n,n=void 0);try{return new e(t instanceof e?t.version:t,n).inc(r,o,i).version}catch(e){return null}},Er}(),c=function(){if(Ir)return wr;Ir=1;const e=zn();return wr=(t,r)=>{const n=e(t,null,!0),o=e(r,null,!0),i=n.compare(o);if(0===i)return null;const s=i>0,a=s?n:o,c=s?o:n,u=!!a.prerelease.length;if(c.prerelease.length&&!u){if(!c.patch&&!c.minor)return"major";if(0===c.compareMain(a))return c.minor&&!c.patch?"minor":"patch"}const l=u?"pre":"";return n.major!==o.major?l+"major":n.minor!==o.minor?l+"minor":n.patch!==o.patch?l+"patch":"prerelease"}}(),u=function(){if(_r)return Cr;_r=1;const e=Gn();return Cr=(t,r)=>new e(t,r).major,Cr}(),l=function(){if(Sr)return Tr;Sr=1;const e=Gn();return Tr=(t,r)=>new e(t,r).minor,Tr}(),h=function(){if(Or)return Ar;Or=1;const e=Gn();return Ar=(t,r)=>new e(t,r).patch,Ar}(),d=function(){if(Rr)return kr;Rr=1;const e=zn();return kr=(t,r)=>{const n=e(t,r);return n&&n.prerelease.length?n.prerelease:null},kr}(),f=Kn(),p=function(){if(Dr)return Lr;Dr=1;const e=Kn();return Lr=(t,r,n)=>e(r,t,n),Lr}(),m=function(){if(Mr)return xr;Mr=1;const e=Kn();return xr=(t,r)=>e(t,r,!0),xr}(),g=Vn(),y=function(){if(jr)return Fr;jr=1;const e=Vn();return Fr=(t,r)=>t.sort((t,n)=>e(t,n,r)),Fr}(),v=function(){if(qr)return Br;qr=1;const e=Vn();return Br=(t,r)=>t.sort((t,n)=>e(n,t,r)),Br}(),E=Yn(),b=Wn(),w=Qn(),I=Jn(),C=Zn(),_=Xn(),T=eo(),S=function(){if(on)return nn;on=1;const e=Gn(),t=zn(),{safeRe:r,t:n}=Bn();return nn=(o,i)=>{if(o instanceof e)return o;if("number"==typeof o&&(o=String(o)),"string"!=typeof o)return null;let s=null;if((i=i||{}).rtl){const e=i.includePrerelease?r[n.COERCERTLFULL]:r[n.COERCERTL];let t;for(;(t=e.exec(o))&&(!s||s.index+s[0].length!==o.length);)s&&t.index+t[0].length===s.index+s[0].length||(s=t),e.lastIndex=t.index+t[1].length+t[2].length;e.lastIndex=-1}else s=o.match(i.includePrerelease?r[n.COERCEFULL]:r[n.COERCE]);if(null===s)return null;const a=s[2],c=s[3]||"0",u=s[4]||"0",l=i.includePrerelease&&s[5]?`-${s[5]}`:"",h=i.includePrerelease&&s[6]?`+${s[6]}`:"";return t(`${a}.${c}.${u}${l}${h}`,i)},nn}(),A=ro(),O=to(),k=no(),R=function(){if(mn)return pn;mn=1;const e=to();return pn=(t,r)=>new e(t,r).set.map(e=>e.map(e=>e.value).join(" ").trim().split(" ")),pn}(),P=function(){if(yn)return gn;yn=1;const e=Gn(),t=to();return gn=(r,n,o)=>{let i=null,s=null,a=null;try{a=new t(n,o)}catch(e){return null}return r.forEach(t=>{a.test(t)&&(i&&-1!==s.compare(t)||(i=t,s=new e(i,o)))}),i},gn}(),N=function(){if(En)return vn;En=1;const e=Gn(),t=to();return vn=(r,n,o)=>{let i=null,s=null,a=null;try{a=new t(n,o)}catch(e){return null}return r.forEach(t=>{a.test(t)&&(i&&1!==s.compare(t)||(i=t,s=new e(i,o)))}),i},vn}(),L=function(){if(wn)return bn;wn=1;const e=Gn(),t=to(),r=Yn();return bn=(n,o)=>{n=new t(n,o);let i=new e("0.0.0");if(n.test(i))return i;if(i=new e("0.0.0-0"),n.test(i))return i;i=null;for(let t=0;t<n.set.length;++t){const o=n.set[t];let s=null;o.forEach(t=>{const n=new e(t.semver.version);switch(t.operator){case">":0===n.prerelease.length?n.patch++:n.prerelease.push(0),n.raw=n.format();case"":case">=":s&&!r(n,s)||(s=n);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${t.operator}`)}}),!s||i&&!r(i,s)||(i=s)}return i&&n.test(i)?i:null},bn}(),D=oo(),x=io(),M=function(){if(An)return Sn;An=1;const e=io();return Sn=(t,r,n)=>e(t,r,">",n),Sn}(),$=function(){if(kn)return On;kn=1;const e=io();return On=(t,r,n)=>e(t,r,"<",n),On}(),U=function(){if(Pn)return Rn;Pn=1;const e=to();return Rn=(t,r,n)=>(t=new e(t,n),r=new e(r,n),t.intersects(r,n))}(),F=function(){if(Ln)return Nn;Ln=1;const e=no(),t=Kn();return Nn=(r,n,o)=>{const i=[];let s=null,a=null;const c=r.sort((e,r)=>t(e,r,o));for(const t of c)e(t,n,o)?(a=t,s||(s=t)):(a&&i.push([s,a]),a=null,s=null);s&&i.push([s,null]);const u=[];for(const[e,t]of i)e===t?u.push(e):t||e!==c[0]?t?e===c[0]?u.push(`<=${t}`):u.push(`${e} - ${t}`):u.push(`>=${e}`):u.push("*");const l=u.join(" || "),h="string"==typeof n.raw?n.raw:String(n);return l.length<h.length?l:n},Nn}(),j=function(){if(xn)return Dn;xn=1;const e=to(),t=ro(),{ANY:r}=t,n=no(),o=Kn(),i=[new t(">=0.0.0-0")],s=[new t(">=0.0.0")],a=(e,t,a)=>{if(e===t)return!0;if(1===e.length&&e[0].semver===r){if(1===t.length&&t[0].semver===r)return!0;e=a.includePrerelease?i:s}if(1===t.length&&t[0].semver===r){if(a.includePrerelease)return!0;t=s}const l=new Set;let h,d,f,p,m,g,y;for(const t of e)">"===t.operator||">="===t.operator?h=c(h,t,a):"<"===t.operator||"<="===t.operator?d=u(d,t,a):l.add(t.semver);if(l.size>1)return null;if(h&&d){if(f=o(h.semver,d.semver,a),f>0)return null;if(0===f&&(">="!==h.operator||"<="!==d.operator))return null}for(const e of l){if(h&&!n(e,String(h),a))return null;if(d&&!n(e,String(d),a))return null;for(const r of t)if(!n(e,String(r),a))return!1;return!0}let v=!(!d||a.includePrerelease||!d.semver.prerelease.length)&&d.semver,E=!(!h||a.includePrerelease||!h.semver.prerelease.length)&&h.semver;v&&1===v.prerelease.length&&"<"===d.operator&&0===v.prerelease[0]&&(v=!1);for(const e of t){if(y=y||">"===e.operator||">="===e.operator,g=g||"<"===e.operator||"<="===e.operator,h)if(E&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===E.major&&e.semver.minor===E.minor&&e.semver.patch===E.patch&&(E=!1),">"===e.operator||">="===e.operator){if(p=c(h,e,a),p===e&&p!==h)return!1}else if(">="===h.operator&&!n(h.semver,String(e),a))return!1;if(d)if(v&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===v.major&&e.semver.minor===v.minor&&e.semver.patch===v.patch&&(v=!1),"<"===e.operator||"<="===e.operator){if(m=u(d,e,a),m===e&&m!==d)return!1}else if("<="===d.operator&&!n(d.semver,String(e),a))return!1;if(!e.operator&&(d||h)&&0!==f)return!1}return!(h&&g&&!d&&0!==f||d&&y&&!h&&0!==f||E||v)},c=(e,t,r)=>{if(!e)return t;const n=o(e.semver,t.semver,r);return n>0?e:n<0||">"===t.operator&&">="===e.operator?t:e},u=(e,t,r)=>{if(!e)return t;const n=o(e.semver,t.semver,r);return n<0?e:n>0||"<"===t.operator&&"<="===e.operator?t:e};return Dn=(t,r,n={})=>{if(t===r)return!0;t=new e(t,n),r=new e(r,n);let o=!1;e:for(const e of t.set){for(const t of r.set){const r=a(e,t,n);if(o=o||null!==r,r)continue e}if(o)return!1}return!0}}();return Mn={parse:o,valid:i,clean:s,inc:a,diff:c,major:u,minor:l,patch:h,prerelease:d,compare:f,rcompare:p,compareLoose:m,compareBuild:g,sort:y,rsort:v,gt:E,lt:b,eq:w,neq:I,gte:C,lte:_,cmp:T,coerce:S,Comparator:A,Range:O,satisfies:k,toComparators:R,maxSatisfying:P,minSatisfying:N,minVersion:L,validRange:D,outside:x,gtr:M,ltr:$,intersects:U,simplifyRange:F,subset:j,SemVer:r,re:e.re,src:e.src,tokens:e.t,SEMVER_SPEC_VERSION:t.SEMVER_SPEC_VERSION,RELEASE_TYPES:t.RELEASE_TYPES,compareIdentifiers:n.compareIdentifiers,rcompareIdentifiers:n.rcompareIdentifiers}}var ao=so();class co extends ao.SemVer{satisfies(e){return ao.satisfies(this,e)}}let uo=class{domain;level=Number(process.env.FUSION_LOG_LEVEL)||1;constructor(e){this.domain=e}_createMessage(e){return[`%c FUSION FRAMEWORK %c ${this.domain} %c %s`,"background: rgb(179, 13, 47); color: white; padding: 1px;","background: rgb(244, 244, 244); color: rgb(36, 55, 70); padding: 1px;","background: none; color: inherit",...e.reduce((e,t)=>e.concat(t,"\n"),[])]}debug(...e){this.level>3&&console.debug(...this._createMessage(e))}info(...e){this.level>2&&console.info(...this._createMessage(e))}warn(...e){this.level>1&&console.warn(...this._createMessage(e))}error(...e){this.level>0&&console.error(...this._createMessage(e))}};class lo extends uo{formatModuleName(e){return`📦${("string"==typeof e?e:e.name).replace(/([A-Z])/g," $1").toUpperCase()}`}}var ho=function(e,t){return ho=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},ho(e,t)};function fo(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}ho(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var po=function(){return po=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},po.apply(this,arguments)};function mo(e,t,r,n){return new(r||(r=Promise))(function(o,i){function s(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})}function go(e,t){var r,n,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(i=0)),i;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,n=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){i.label=a[1];break}if(6===a[0]&&i.label<o[1]){i.label=o[1],o=a;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(a);break}o[2]&&i.ops.pop(),i.trys.pop();continue}a=t.call(e,i)}catch(e){a=[6,e],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}function yo(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function vo(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s}function Eo(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))}function bo(e){return this instanceof bo?(this.v=e,this):new bo(e)}function wo(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=r.apply(e,t||[]),i=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",function(e){return function(t){return Promise.resolve(t).then(e,u)}}),n[Symbol.asyncIterator]=function(){return this},n;function s(e,t){o[e]&&(n[e]=function(t){return new Promise(function(r,n){i.push([e,t,r,n])>1||a(e,t)})},t&&(n[e]=t(n[e])))}function a(e,t){try{!function(e){e.value instanceof bo?Promise.resolve(e.value.v).then(c,u):l(i[0][2],e)}(o[e](t))}catch(e){l(i[0][3],e)}}function c(e){a("next",e)}function u(e){a("throw",e)}function l(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}}function Io(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=yo(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise(function(n,o){(function(e,t,r,n){Promise.resolve(n).then(function(t){e({value:t,done:r})},t)})(n,o,(t=e[r](t)).done,t.value)})}}}function Co(e){return"function"==typeof e}function _o(e){var t=e(function(e){Error.call(e),e.stack=(new Error).stack});return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}"function"==typeof SuppressedError&&SuppressedError;var To=_o(function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map(function(e,t){return t+1+") "+e.toString()}).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}});function So(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var Ao=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,r,n,o;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var s=yo(i),a=s.next();!a.done;a=s.next()){a.value.remove(this)}}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}else i.remove(this);var c=this.initialTeardown;if(Co(c))try{c()}catch(e){o=e instanceof To?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var l=yo(u),h=l.next();!h.done;h=l.next()){var d=h.value;try{Ro(d)}catch(e){o=null!=o?o:[],e instanceof To?o=Eo(Eo([],vo(o)),vo(e.errors)):o.push(e)}}}catch(e){r={error:e}}finally{try{h&&!h.done&&(n=l.return)&&n.call(l)}finally{if(r)throw r.error}}}if(o)throw new To(o)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)Ro(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(r=this._finalizers)&&void 0!==r?r:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&So(t,e)},e.prototype.remove=function(t){var r=this._finalizers;r&&So(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}(),Oo=Ao.EMPTY;function ko(e){return e instanceof Ao||e&&"closed"in e&&Co(e.remove)&&Co(e.add)&&Co(e.unsubscribe)}function Ro(e){Co(e)?e():e.unsubscribe()}var Po={Promise:void 0},No=function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setTimeout.apply(void 0,Eo([e,t],vo(r)))};function Lo(e){No(function(){throw e})}function Do(){}function xo(e){e()}var Mo=function(e){function t(t){var r=e.call(this)||this;return r.isStopped=!1,t?(r.destination=t,ko(t)&&t.add(r)):r.destination=jo,r}return fo(t,e),t.create=function(e,t,r){return new Uo(e,t,r)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(Ao),$o=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){Fo(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){Fo(e)}else Fo(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){Fo(e)}},e}(),Uo=function(e){function t(t,r,n){var o,i=e.call(this)||this;return o=Co(t)||!t?{next:null!=t?t:void 0,error:null!=r?r:void 0,complete:null!=n?n:void 0}:t,i.destination=new $o(o),i}return fo(t,e),t}(Mo);function Fo(e){Lo(e)}var jo={closed:!0,next:Do,error:function(e){throw e},complete:Do},Bo="function"==typeof Symbol&&Symbol.observable||"@@observable";function qo(e){return e}var Ho=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var r=new e;return r.source=this,r.operator=t,r},e.prototype.subscribe=function(e,t,r){var n,o=this,i=(n=e)&&n instanceof Mo||function(e){return e&&Co(e.next)&&Co(e.error)&&Co(e.complete)}(n)&&ko(n)?e:new Uo(e,t,r);return xo(function(){var e=o,t=e.operator,r=e.source;i.add(t?t.call(i,r):r?o._subscribe(i):o._trySubscribe(i))}),i},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var r=this;return new(t=Go(t))(function(t,n){var o=new Uo({next:function(t){try{e(t)}catch(e){n(e),o.unsubscribe()}},error:n,complete:t});r.subscribe(o)})},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[Bo]=function(){return this},e.prototype.pipe=function(){for(var e,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return(0===(e=t).length?qo:1===e.length?e[0]:function(t){return e.reduce(function(e,t){return t(e)},t)})(this)},e.prototype.toPromise=function(e){var t=this;return new(e=Go(e))(function(e,r){var n;t.subscribe(function(e){return n=e},function(e){return r(e)},function(){return e(n)})})},e.create=function(t){return new e(t)},e}();function Go(e){var t;return null!==(t=null!=e?e:Po.Promise)&&void 0!==t?t:Promise}function zo(e){return function(t){if(function(e){return Co(null==e?void 0:e.lift)}(t))return t.lift(function(t){try{return e(t,this)}catch(e){this.error(e)}});throw new TypeError("Unable to lift unknown Observable type")}}function Ko(e,t,r,n,o){return new Vo(e,t,r,n,o)}var Vo=function(e){function t(t,r,n,o,i,s){var a=e.call(this,t)||this;return a.onFinalize=i,a.shouldUnsubscribe=s,a._next=r?function(e){try{r(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=o?function(e){try{o(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=n?function(){try{n()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return fo(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;e.prototype.unsubscribe.call(this),!r&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(Mo),Yo=_o(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Wo=function(e){function t(){var t=e.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return fo(t,e),t.prototype.lift=function(e){var t=new Qo(this,this);return t.operator=e,t},t.prototype._throwIfClosed=function(){if(this.closed)throw new Yo},t.prototype.next=function(e){var t=this;xo(function(){var r,n;if(t._throwIfClosed(),!t.isStopped){t.currentObservers||(t.currentObservers=Array.from(t.observers));try{for(var o=yo(t.currentObservers),i=o.next();!i.done;i=o.next()){i.value.next(e)}}catch(e){r={error:e}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}}})},t.prototype.error=function(e){var t=this;xo(function(){if(t._throwIfClosed(),!t.isStopped){t.hasError=t.isStopped=!0,t.thrownError=e;for(var r=t.observers;r.length;)r.shift().error(e)}})},t.prototype.complete=function(){var e=this;xo(function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var t=e.observers;t.length;)t.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var e;return(null===(e=this.observers)||void 0===e?void 0:e.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,r=this,n=r.hasError,o=r.isStopped,i=r.observers;return n||o?Oo:(this.currentObservers=null,i.push(e),new Ao(function(){t.currentObservers=null,So(i,e)}))},t.prototype._checkFinalizedStatuses=function(e){var t=this,r=t.hasError,n=t.thrownError,o=t.isStopped;r?e.error(n):o&&e.complete()},t.prototype.asObservable=function(){var e=new Ho;return e.source=this,e},t.create=function(e,t){return new Qo(e,t)},t}(Ho),Qo=function(e){function t(t,r){var n=e.call(this)||this;return n.destination=t,n.source=r,n}return fo(t,e),t.prototype.next=function(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===r||r.call(t,e)},t.prototype.error=function(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===r||r.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,r;return null!==(r=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==r?r:Oo},t}(Wo),Jo=function(e){function t(t){var r=e.call(this)||this;return r._value=t,r}return fo(t,e),Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(t){var r=e.prototype._subscribe.call(this,t);return!r.closed&&t.next(this._value),r},t.prototype.getValue=function(){var e=this,t=e.hasError,r=e.thrownError,n=e._value;if(t)throw r;return this._throwIfClosed(),n},t.prototype.next=function(t){e.prototype.next.call(this,this._value=t)},t}(Wo),Zo={now:function(){return(Zo.delegate||Date).now()},delegate:void 0},Xo=function(e){function t(t,r,n){void 0===t&&(t=1/0),void 0===r&&(r=1/0),void 0===n&&(n=Zo);var o=e.call(this)||this;return o._bufferSize=t,o._windowTime=r,o._timestampProvider=n,o._buffer=[],o._infiniteTimeWindow=!0,o._infiniteTimeWindow=r===1/0,o._bufferSize=Math.max(1,t),o._windowTime=Math.max(1,r),o}return fo(t,e),t.prototype.next=function(t){var r=this,n=r.isStopped,o=r._buffer,i=r._infiniteTimeWindow,s=r._timestampProvider,a=r._windowTime;n||(o.push(t),!i&&o.push(s.now()+a)),this._trimBuffer(),e.prototype.next.call(this,t)},t.prototype._subscribe=function(e){this._throwIfClosed(),this._trimBuffer();for(var t=this._innerSubscribe(e),r=this._infiniteTimeWindow,n=this._buffer.slice(),o=0;o<n.length&&!e.closed;o+=r?1:2)e.next(n[o]);return this._checkFinalizedStatuses(e),t},t.prototype._trimBuffer=function(){var e=this,t=e._bufferSize,r=e._timestampProvider,n=e._buffer,o=e._infiniteTimeWindow,i=(o?1:2)*t;if(t<1/0&&i<n.length&&n.splice(0,n.length-i),!o){for(var s=r.now(),a=0,c=1;c<n.length&&n[c]<=s;c+=2)a=c;a&&n.splice(0,a+1)}},t}(Wo),ei=function(e){function t(t,r){return e.call(this)||this}return fo(t,e),t.prototype.schedule=function(e,t){return this},t}(Ao),ti=function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setInterval.apply(void 0,Eo([e,t],vo(r)))},ri=function(e){return clearInterval(e)},ni=function(e){function t(t,r){var n=e.call(this,t,r)||this;return n.scheduler=t,n.work=r,n.pending=!1,n}return fo(t,e),t.prototype.schedule=function(e,t){var r;if(void 0===t&&(t=0),this.closed)return this;this.state=e;var n=this.id,o=this.scheduler;return null!=n&&(this.id=this.recycleAsyncId(o,n,t)),this.pending=!0,this.delay=t,this.id=null!==(r=this.id)&&void 0!==r?r:this.requestAsyncId(o,this.id,t),this},t.prototype.requestAsyncId=function(e,t,r){return void 0===r&&(r=0),ti(e.flush.bind(e,this),r)},t.prototype.recycleAsyncId=function(e,t,r){if(void 0===r&&(r=0),null!=r&&this.delay===r&&!1===this.pending)return t;null!=t&&ri(t)},t.prototype.execute=function(e,t){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var r=this._execute(e,t);if(r)return r;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,t){var r,n=!1;try{this.work(e)}catch(e){n=!0,r=e||new Error("Scheduled action threw falsy error")}if(n)return this.unsubscribe(),r},t.prototype.unsubscribe=function(){if(!this.closed){var t=this.id,r=this.scheduler,n=r.actions;this.work=this.state=this.scheduler=null,this.pending=!1,So(n,this),null!=t&&(this.id=this.recycleAsyncId(r,t,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(ei),oi=function(){function e(t,r){void 0===r&&(r=e.now),this.schedulerActionCtor=t,this.now=r}return e.prototype.schedule=function(e,t,r){return void 0===t&&(t=0),new this.schedulerActionCtor(this,e).schedule(r,t)},e.now=Zo.now,e}(),ii=function(e){function t(t,r){void 0===r&&(r=oi.now);var n=e.call(this,t,r)||this;return n.actions=[],n._active=!1,n}return fo(t,e),t.prototype.flush=function(e){var t=this.actions;if(this._active)t.push(e);else{var r;this._active=!0;do{if(r=e.execute(e.state,e.delay))break}while(e=t.shift());if(this._active=!1,r){for(;e=t.shift();)e.unsubscribe();throw r}}},t}(oi),si=new ii(ni),ai=si,ci=new Ho(function(e){return e.complete()});function ui(e){return e&&Co(e.schedule)}function li(e){return e[e.length-1]}var hi=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function di(e){return Co(null==e?void 0:e.then)}function fi(e){return Co(e[Bo])}function pi(e){return Symbol.asyncIterator&&Co(null==e?void 0:e[Symbol.asyncIterator])}function mi(e){return new TypeError("You provided "+(null!==e&&"object"==typeof e?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}var gi="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function yi(e){return Co(null==e?void 0:e[gi])}function vi(e){return wo(this,arguments,function(){var t,r,n;return go(this,function(o){switch(o.label){case 0:t=e.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,bo(t.read())];case 3:return r=o.sent(),n=r.value,r.done?[4,bo(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,bo(n)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function Ei(e){return Co(null==e?void 0:e.getReader)}function bi(e){if(e instanceof Ho)return e;if(null!=e){if(fi(e))return o=e,new Ho(function(e){var t=o[Bo]();if(Co(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")});if(hi(e))return n=e,new Ho(function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()});if(di(e))return r=e,new Ho(function(e){r.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,Lo)});if(pi(e))return wi(e);if(yi(e))return t=e,new Ho(function(e){var r,n;try{for(var o=yo(t),i=o.next();!i.done;i=o.next()){var s=i.value;if(e.next(s),e.closed)return}}catch(e){r={error:e}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}e.complete()});if(Ei(e))return wi(vi(e))}var t,r,n,o;throw mi(e)}function wi(e){return new Ho(function(t){(function(e,t){var r,n,o,i;return mo(this,void 0,void 0,function(){var s,a;return go(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),r=Io(e),c.label=1;case 1:return[4,r.next()];case 2:if((n=c.sent()).done)return[3,4];if(s=n.value,t.next(s),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),o={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),n&&!n.done&&(i=r.return)?[4,i.call(r)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})})(e,t).catch(function(e){return t.error(e)})})}function Ii(e,t,r,n,o){void 0===n&&(n=0),void 0===o&&(o=!1);var i=t.schedule(function(){r(),o?e.add(this.schedule(null,n)):this.unsubscribe()},n);if(e.add(i),!o)return i}function Ci(e,t){return void 0===t&&(t=0),zo(function(r,n){r.subscribe(Ko(n,function(r){return Ii(n,e,function(){return n.next(r)},t)},function(){return Ii(n,e,function(){return n.complete()},t)},function(r){return Ii(n,e,function(){return n.error(r)},t)}))})}function _i(e,t){return void 0===t&&(t=0),zo(function(r,n){n.add(e.schedule(function(){return r.subscribe(n)},t))})}function Ti(e,t){if(!e)throw new Error("Iterable cannot be null");return new Ho(function(r){Ii(r,t,function(){var n=e[Symbol.asyncIterator]();Ii(r,t,function(){n.next().then(function(e){e.done?r.complete():r.next(e.value)})},0,!0)})})}function Si(e,t){if(null!=e){if(fi(e))return function(e,t){return bi(e).pipe(_i(t),Ci(t))}(e,t);if(hi(e))return function(e,t){return new Ho(function(r){var n=0;return t.schedule(function(){n===e.length?r.complete():(r.next(e[n++]),r.closed||this.schedule())})})}(e,t);if(di(e))return function(e,t){return bi(e).pipe(_i(t),Ci(t))}(e,t);if(pi(e))return Ti(e,t);if(yi(e))return function(e,t){return new Ho(function(r){var n;return Ii(r,t,function(){n=e[gi](),Ii(r,t,function(){var e,t,o;try{t=(e=n.next()).value,o=e.done}catch(e){return void r.error(e)}o?r.complete():r.next(t)},0,!0)}),function(){return Co(null==n?void 0:n.return)&&n.return()}})}(e,t);if(Ei(e))return function(e,t){return Ti(vi(e),t)}(e,t)}throw mi(e)}function Ai(e,t){return t?Si(e,t):bi(e)}function Oi(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=function(e){return ui(li(e))?e.pop():void 0}(e);return Ai(e,r)}var ki=_o(function(e){return function(){e(this),this.name="EmptyError",this.message="no elements in sequence"}});function Ri(e,t){var r="object"==typeof t;return new Promise(function(n,o){var i,s=!1;e.subscribe({next:function(e){i=e,s=!0},error:o,complete:function(){s?n(i):r?n(t.defaultValue):o(new ki)}})})}function Pi(e,t){var r="object"==typeof t;return new Promise(function(n,o){var i=new Uo({next:function(e){n(e),i.unsubscribe()},error:o,complete:function(){r?n(t.defaultValue):o(new ki)}});e.subscribe(i)})}function Ni(e){return e instanceof Date&&!isNaN(e)}var Li=_o(function(e){return function(t){void 0===t&&(t=null),e(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function Di(e){throw new Li(e)}function xi(e,t){return zo(function(r,n){var o=0;r.subscribe(Ko(n,function(r){n.next(e.call(t,r,o++))}))})}var Mi=Array.isArray;function $i(e){return xi(function(t){return function(e,t){return Mi(t)?e.apply(void 0,Eo([],vo(t))):e(t)}(e,t)})}function Ui(e,t,r,n,o,i,s,a){var c=[],u=0,l=0,h=!1,d=function(){!h||c.length||u||t.complete()},f=function(e){return u<n?p(e):c.push(e)},p=function(e){i&&t.next(e),u++;var a=!1;bi(r(e,l++)).subscribe(Ko(t,function(e){null==o||o(e),i?f(e):t.next(e)},function(){a=!0},void 0,function(){if(a)try{u--;for(var e=function(){var e=c.shift();s||p(e)};c.length&&u<n;)e();d()}catch(e){t.error(e)}}))};return e.subscribe(Ko(t,f,function(){h=!0,d()})),function(){null==a||a()}}function Fi(e,t,r){return void 0===r&&(r=1/0),Co(t)?Fi(function(r,n){return xi(function(e,o){return t(r,e,n,o)})(bi(e(r,n)))},r):("number"==typeof t&&(r=t),zo(function(t,n){return Ui(t,n,e,r)}))}var ji=["addListener","removeListener"],Bi=["addEventListener","removeEventListener"],qi=["on","off"];function Hi(e,t,r,n){if(Co(r)&&(n=r,r=void 0),n)return Hi(e,t,r).pipe($i(n));var o=vo(function(e){return Co(e.addEventListener)&&Co(e.removeEventListener)}(e)?Bi.map(function(n){return function(o){return e[n](t,o,r)}}):function(e){return Co(e.addListener)&&Co(e.removeListener)}(e)?ji.map(Gi(e,t)):function(e){return Co(e.on)&&Co(e.off)}(e)?qi.map(Gi(e,t)):[],2),i=o[0],s=o[1];if(!i&&hi(e))return Fi(function(e){return Hi(e,t,r)})(bi(e));if(!i)throw new TypeError("Invalid event target");return new Ho(function(e){var t=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return e.next(1<t.length?t:t[0])};return i(t),function(){return s(t)}})}function Gi(e,t){return function(r){return function(n){return e[r](t,n)}}}function zi(e,t,r){void 0===e&&(e=0),void 0===r&&(r=ai);var n=-1;return null!=t&&(ui(t)?r=t:n=t),new Ho(function(t){var o=Ni(e)?+e-r.now():e;o<0&&(o=0);var i=0;return r.schedule(function(){t.closed||(t.next(i++),0<=n?this.schedule(void 0,n):t.complete())},o)})}function Ki(e,t){return zo(function(r,n){var o=0;r.subscribe(Ko(n,function(r){return e.call(t,r,o++)&&n.next(r)}))})}function Vi(e){return zo(function(t,r){var n,o=null,i=!1;o=t.subscribe(Ko(r,void 0,void 0,function(s){n=bi(e(s,Vi(e)(t))),o?(o.unsubscribe(),o=null,n.subscribe(r)):i=!0})),i&&(o.unsubscribe(),o=null,n.subscribe(r))})}function Yi(e,t,r,n,o){return function(i,s){var a=r,c=t,u=0;i.subscribe(Ko(s,function(t){var r=u++;c=a?e(c,t,r):(a=!0,t),n&&s.next(c)},o&&function(){a&&s.next(c),s.complete()}))}}function Wi(e,t){return zo(Yi(e,t,arguments.length>=2,!1,!0))}function Qi(e,t){return void 0===t&&(t=qo),e=null!=e?e:Ji,zo(function(r,n){var o,i=!0;r.subscribe(Ko(n,function(r){var s=t(r);!i&&e(o,s)||(i=!1,o=s,n.next(r))}))})}function Ji(e,t){return e===t}function Zi(e){return void 0===e&&(e=Xi),zo(function(t,r){var n=!1;t.subscribe(Ko(r,function(e){n=!0,r.next(e)},function(){return n?r.complete():r.error(e())}))})}function Xi(){return new ki}function es(e){return zo(function(t,r){try{t.subscribe(r)}finally{r.add(e)}})}function ts(e,t){var r=arguments.length>=2;return function(e){return e.pipe(qo,(n=1)<=0?function(){return ci}:zo(function(e,t){var r=[];e.subscribe(Ko(t,function(e){r.push(e),n<r.length&&r.shift()},function(){var e,n;try{for(var o=yo(r),i=o.next();!i.done;i=o.next()){var s=i.value;t.next(s)}}catch(t){e={error:t}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(e)throw e.error}}t.complete()},void 0,function(){r=null}))}),r?function(e){return zo(function(t,r){var n=!1;t.subscribe(Ko(r,function(e){n=!0,r.next(e)},function(){n||r.next(e),r.complete()}))})}(t):Zi(function(){return new ki}));var n}}function rs(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];if(!0!==t){if(!1!==t){var o=new Uo({next:function(){o.unsubscribe(),e()}});return bi(t.apply(void 0,Eo([],vo(r)))).subscribe(o)}}else e()}function ns(e,t){return zo(function(r,n){var o=null,i=0,s=!1,a=function(){return s&&!o&&n.complete()};r.subscribe(Ko(n,function(r){null==o||o.unsubscribe();var s=0,c=i++;bi(e(r,c)).subscribe(o=Ko(n,function(e){return n.next(t?t(r,e,c,s++):e)},function(){o=null,a()}))},function(){s=!0,a()}))})}function os(e){return zo(function(t,r){bi(e).subscribe(Ko(r,function(){return r.complete()},Do)),!r.closed&&t.subscribe(r)})}function is(e,t,r){var n=Co(e)||t||r?{next:e,error:t,complete:r}:e;return n?zo(function(e,t){var r;null===(r=n.subscribe)||void 0===r||r.call(n);var o=!0;e.subscribe(Ko(t,function(e){var r;null===(r=n.next)||void 0===r||r.call(n,e),t.next(e)},function(){var e;o=!1,null===(e=n.complete)||void 0===e||e.call(n),t.complete()},function(e){var r;o=!1,null===(r=n.error)||void 0===r||r.call(n,e),t.error(e)},function(){var e,t;o&&(null===(e=n.unsubscribe)||void 0===e||e.call(n)),null===(t=n.finalize)||void 0===t||t.call(n)}))}):qo}function ss(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r,n=Co(li(r=e))?r.pop():void 0;return zo(function(t,r){for(var o=e.length,i=new Array(o),s=e.map(function(){return!1}),a=!1,c=function(t){bi(e[t]).subscribe(Ko(r,function(e){i[t]=e,a||s[t]||(s[t]=!0,(a=s.every(qo))&&(s=null))},Do))},u=0;u<o;u++)c(u);t.subscribe(Ko(r,function(e){if(a){var t=Eo([e],vo(i));r.next(n?n.apply(void 0,Eo([],vo(t))):t)}}))})}const as=(e,t,r)=>{const n="string"==typeof t?t.split("."):t,o=n.shift();return o&&(e[o]??={},n.length?as(e[o],n,r):Object.assign(e,{[o]:r})),e};class cs{#t={};createConfig(e,t){return Ai(this._createConfig(e,t))}async createConfigAsync(e,t){return Ri(this.createConfig(e,t))}_set(e,t){const r="function"==typeof t?t:async()=>t;this.#t[e]=r}_get(e){return this.#t[e]}_has(e){return e in this.#t}_createConfig(e,t){return Ai(this._buildConfig(e,t)).pipe(ns(t=>this._processConfig(t,e)))}_buildConfig(e,t){return Ai(Object.entries(this.#t)).pipe(Fi(([t,r])=>Ai(r(e)).pipe(Ki(e=>void 0!==e),xi(e=>({target:t,value:e})),Vi(e=>(console.error(`Failed to execute config callback: ${r.name} for attribute: '${t}'`,e),ci)))),Wi((e,{target:t,value:r})=>as(e,t,r),t??{}))}_processConfig(e,t){return Oi(e)}}class us{#r;#n;get version(){return this.#r}constructor(e){const{version:t}=e;this.#r=new co(t),this.#n=new Ao}_addTeardown(e){return this.#n.add(e),()=>this.#n.remove(e)}dispose(){this.#n.unsubscribe()}}class ls extends Error{constructor(){super("It was too slow"),this.name="RequiredModuleTimeoutError"}}class hs{logger=new lo("ModulesConfigurator");_configs=[];_afterConfiguration=[];_afterInit=[];_modules;constructor(e){this._modules=new Set(e)}get modules(){return[...this._modules]}configure(...e){for(const t of e)this.addConfig(t)}addConfig(e){const{module:t,afterConfig:r,afterInit:n,configure:o}=e;this._modules.add(t),o&&this._configs.push((e,r)=>o(e[t.name],r)),r&&this._afterConfiguration.push(e=>r(e[t.name])),n&&this._afterInit.push(e=>n(e[t.name]))}onConfigured(e){this._afterConfiguration.push(e)}onInitialized(e){this._afterInit.push(e)}async initialize(e){const t=await this._configure(e),r=await this._initialize(t,e);return await this._postInitialize(r,e),Object.seal(Object.assign({},r,{dispose:()=>this.dispose(r)}))}async _configure(e){const t=await this._createConfig(e);return await Promise.all(this._configs.map(r=>Promise.resolve(r(t,e)))),await this._postConfigure(t),t}_createConfig(e){const{modules:t,logger:r,_afterConfiguration:n,_afterInit:o}=this,i=Ai(t).pipe(Fi(async t=>{r.debug(`🛠 creating configurator ${r.formatModuleName(t)}`);try{const n=await(t.configure?.(e));return r.debug(`🛠 created configurator for ${r.formatModuleName(t)}`,n),{[t.name]:n}}catch(e){throw r.error(`🛠 Failed to created configurator for ${r.formatModuleName(t)}`,e),e}}),Wi((e,t)=>Object.assign(e,t),{onAfterConfiguration(e){n.push(e)},onAfterInit(e){o.push(e)}}));return Ri(i)}async _postConfigure(e){const{modules:t,logger:r,_afterConfiguration:n}=this;if(await Promise.allSettled(t.filter(e=>!!e.postConfigure).map(async t=>{try{await(t.postConfigure?.(e)),r.debug(`🏗📌 post configured ${r.formatModuleName(t)}`,t)}catch(e){r.warn(`🏗📌 post configure failed ${r.formatModuleName(t)}`)}})),n.length)try{r.debug(`🏗📌 post configure hooks [${n.length}]`),await Promise.allSettled(n.map(t=>Promise.resolve(t(e)))),r.debug("🏗📌 post configure hooks complete")}catch(e){r.warn("🏗📌 post configure hook failed",e)}}async _initialize(e,t){const{modules:r,logger:n}=this,o=r.map(e=>e.name),i=new Jo({}),s=e=>o.includes(e),a=(e,t=60)=>{if(!o.includes(e))throw n.error(`🚀⌛️ Cannot not require ${n.formatModuleName(String(e))} since module is not defined!`),Error(`cannot not require [${String(e)}] since module is not defined!`);return i.value[e]?(n.debug(`🚀⌛️ ${n.formatModuleName(String(e))} is initiated, skipping queue`),Promise.resolve(i.value[e])):(n.debug(`🚀⌛️ Awaiting init ${n.formatModuleName(String(e))}, timeout ${t}s`),Pi(i.pipe(Ki(t=>!!t[e]),xi(t=>t[e]),function(e){var t=Ni(e)?{first:e}:"number"==typeof e?{each:e}:e,r=t.first,n=t.each,o=t.with,i=void 0===o?Di:o,s=t.scheduler,a=void 0===s?si:s,c=t.meta,u=void 0===c?null:c;if(null==r&&null==n)throw new TypeError("No timeout provided.");return zo(function(e,t){var o,s,c=null,l=0,h=function(e){s=Ii(t,a,function(){try{o.unsubscribe(),bi(i({meta:u,lastValue:c,seen:l})).subscribe(t)}catch(e){t.error(e)}},e)};o=e.subscribe(Ko(t,function(e){null==s||s.unsubscribe(),l++,t.next(c=e),n>0&&h(n)},void 0,void 0,function(){(null==s?void 0:s.closed)||null==s||s.unsubscribe(),c=null})),!l&&h(null!=r?"number"==typeof r?r:+r-a.now():n)})}({each:1e3*t,with:()=>{return t=Co(e=()=>new ls)?e:function(){return e},new Ho(function(e){return e.error(t())});var e,t}}))))};Ai(r).pipe(Fi(r=>{const o=r.name;return n.debug(`🚀 initializing ${n.formatModuleName(r)}`),Ai(Promise.resolve(r.initialize({ref:t,config:e[o],requireInstance:a,hasModule:s}))).pipe(xi(e=>{if(!(e instanceof us||e.version instanceof co)){n.debug("🤷 module does not extends the [BaseModuleProvider] or exposes [SemanticVersion]");try{e.version=r.version instanceof co?r.version:new co(r.version??"0.0.0-unknown")}catch(e){n.error("🚨 failed to set module version")}}return n.debug(`🚀 initialized ${n.formatModuleName(r)}`),[o,e]}))})).subscribe({next:([e,t])=>{i.next(Object.assign(i.value,{[e]:t}))},error:e=>{n.error("🚨 failed to initialize",e),i.error(e)},complete:()=>i.complete()});const c=await Ri(i);return Object.seal(c),c}async _postInitialize(e,t){const{modules:r,logger:n,_afterInit:o}=this,i=Ai(r).pipe(Ki(e=>!!e.postInitialize),is(e=>n.debug(`🚀📌 post initializing moule ${n.formatModuleName(e)}`)),Fi(r=>Ai(r.postInitialize({ref:t,modules:e,instance:e[r.name]})).pipe(is(()=>{n.debug(`🚀📌 post initialized moule ${n.formatModuleName(r)}`)}),Vi(e=>(n.warn(`🚀📌 post initialize failed moule ${n.formatModuleName(r)}`,e),ci)))));if(await new Promise((e,t)=>{i.subscribe({complete:()=>e(!0),error:t})}),o.length)try{n.debug(`🚀📌 post configure hooks [${o.length}]`),await Promise.allSettled(o.map(t=>Promise.resolve(t(e)))),n.debug("🚀📌 post configure hooks complete")}catch(e){n.warn("🚀📌 post configure hook failed",e)}n.debug(`🎉 Modules initialized ${r.map(n.formatModuleName)}`,e),n.info("🟢 Modules initialized")}async dispose(e,t){const{modules:r}=this;await Promise.allSettled(r.filter(e=>!!e.dispose).map(async r=>{await(r.dispose?.({ref:t,modules:e,instance:e[r.name]}))}))}}class ds extends Error{static Name="NoAccountsError";constructor(e,t){super(e,t),this.name=ds.Name}}class fs extends Error{static Name="SilentTokenAcquisitionError";constructor(e,t){super(e,t),this.name=fs.Name}}class ps extends Error{static Name="AuthServerError";constructor(e,t){super(e,t),this.name=ps.Name}}class ms extends ps{static Name="AuthServerTimeoutError";constructor(e,t){super(e,t),this.name=ms.Name}}class gs{_client;constructor(e){this._client=e}async getAccount(){return(await this._client.getAllAccounts())[0]??null}async acquireAccessToken(e){const{accessToken:t}=await this.acquireToken(e);return t}async login(e){throw new ps("Login not supported, use AuthProviderInteractive instead")}async logout(){const e=this._client.getTokenCache(),t=await e.getAllAccounts();for(const r of t)await e.removeAccount(r);this._client.clearCache()}async acquireToken(e){const t=await this.getAccount();if(!t)throw new ds("No accounts found in cache");try{return await this._client.acquireTokenSilent({scopes:e.scopes,account:t})}catch(e){throw new fs("Error acquiring token",{cause:e})}}}class ys{static serializeJSONBlob(e){return JSON.stringify(e)}static serializeAccounts(e){const t={};return Object.keys(e).map(function(r){const n=e[r];t[r]={home_account_id:n.homeAccountId,environment:n.environment,realm:n.realm,local_account_id:n.localAccountId,username:n.username,authority_type:n.authorityType,name:n.name,client_info:n.clientInfo,last_modification_time:n.lastModificationTime,last_modification_app:n.lastModificationApp,tenantProfiles:n.tenantProfiles?.map(e=>JSON.stringify(e))}}),t}static serializeIdTokens(e){const t={};return Object.keys(e).map(function(r){const n=e[r];t[r]={home_account_id:n.homeAccountId,environment:n.environment,credential_type:n.credentialType,client_id:n.clientId,secret:n.secret,realm:n.realm}}),t}static serializeAccessTokens(e){const t={};return Object.keys(e).map(function(r){const n=e[r];t[r]={home_account_id:n.homeAccountId,environment:n.environment,credential_type:n.credentialType,client_id:n.clientId,secret:n.secret,realm:n.realm,target:n.target,cached_at:n.cachedAt,expires_on:n.expiresOn,extended_expires_on:n.extendedExpiresOn,refresh_on:n.refreshOn,key_id:n.keyId,token_type:n.tokenType,requestedClaims:n.requestedClaims,requestedClaimsHash:n.requestedClaimsHash,userAssertionHash:n.userAssertionHash}}),t}static serializeRefreshTokens(e){const t={};return Object.keys(e).map(function(r){const n=e[r];t[r]={home_account_id:n.homeAccountId,environment:n.environment,credential_type:n.credentialType,client_id:n.clientId,secret:n.secret,family_id:n.familyId,target:n.target,realm:n.realm}}),t}static serializeAppMetadata(e){const t={};return Object.keys(e).map(function(r){const n=e[r];t[r]={client_id:n.clientId,environment:n.environment,family_id:n.familyId}}),t}static serializeAllCache(e){return{Account:this.serializeAccounts(e.accounts),IdToken:this.serializeIdTokens(e.idTokens),AccessToken:this.serializeAccessTokens(e.accessTokens),RefreshToken:this.serializeRefreshTokens(e.refreshTokens),AppMetadata:this.serializeAppMetadata(e.appMetadata)}}}const vs={LIBRARY_NAME:"MSAL.JS",SKU:"msal.js.common",CACHE_PREFIX:"msal",DEFAULT_AUTHORITY:"https://login.microsoftonline.com/common/",DEFAULT_AUTHORITY_HOST:"login.microsoftonline.com",DEFAULT_COMMON_TENANT:"common",ADFS:"adfs",DSTS:"dstsv2",AAD_INSTANCE_DISCOVERY_ENDPT:"https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=",CIAM_AUTH_URL:".ciamlogin.com",AAD_TENANT_DOMAIN_SUFFIX:".onmicrosoft.com",RESOURCE_DELIM:"|",NO_ACCOUNT:"NO_ACCOUNT",CLAIMS:"claims",CONSUMER_UTID:"9188040d-6c67-4c5b-b112-36a304b66dad",OPENID_SCOPE:"openid",PROFILE_SCOPE:"profile",OFFLINE_ACCESS_SCOPE:"offline_access",EMAIL_SCOPE:"email",CODE_GRANT_TYPE:"authorization_code",RT_GRANT_TYPE:"refresh_token",S256_CODE_CHALLENGE_METHOD:"S256",URL_FORM_CONTENT_TYPE:"application/x-www-form-urlencoded;charset=utf-8",AUTHORIZATION_PENDING:"authorization_pending",NOT_DEFINED:"not_defined",EMPTY_STRING:"",NOT_APPLICABLE:"N/A",NOT_AVAILABLE:"Not Available",FORWARD_SLASH:"/",IMDS_ENDPOINT:"http://169.254.169.254/metadata/instance/compute/location",IMDS_VERSION:"2020-06-01",IMDS_TIMEOUT:2e3,AZURE_REGION_AUTO_DISCOVER_FLAG:"TryAutoDetect",REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX:"login.microsoft.com",KNOWN_PUBLIC_CLOUDS:["login.microsoftonline.com","login.windows.net","login.microsoft.com","sts.windows.net"],SHR_NONCE_VALIDITY:240,INVALID_INSTANCE:"invalid_instance"},Es=200,bs=299,ws=302,Is=400,Cs=499,_s=500,Ts=500,Ss=599,As=[vs.OPENID_SCOPE,vs.PROFILE_SCOPE,vs.OFFLINE_ACCESS_SCOPE],Os=[...As,vs.EMAIL_SCOPE],ks="Content-Type",Rs="Content-Length",Ps="Retry-After",Ns="X-AnchorMailbox",Ls="x-ms-request-id",Ds="x-ms-httpver",xs="common",Ms="organizations",$s="consumers",Us="access_token",Fs="xms_cc",js={LOGIN:"login",SELECT_ACCOUNT:"select_account",CONSENT:"consent",NONE:"none",CREATE:"create",NO_SESSION:"no_session"},Bs={PLAIN:"plain",S256:"S256"},qs="code",Hs="id_token token",Gs="query",zs="authorization_code",Ks="password",Vs="refresh_token",Ys="device_code",Ws="MSSTS",Qs="ADFS",Js="Generic",Zs="-",Xs=".",ea={ID_TOKEN:"IdToken",ACCESS_TOKEN:"AccessToken",ACCESS_TOKEN_WITH_AUTH_SCHEME:"AccessToken_With_AuthScheme",REFRESH_TOKEN:"RefreshToken"},ta="appmetadata",ra="1",na="authority-metadata",oa=86400,ia="config",sa="cache",aa="network",ca="hardcoded_values",ua={SCHEMA_VERSION:5,MAX_LAST_HEADER_BYTES:330,MAX_CACHED_ERRORS:50,CACHE_KEY:"server-telemetry",CATEGORY_SEPARATOR:"|",VALUE_SEPARATOR:",",OVERFLOW_TRUE:"1",OVERFLOW_FALSE:"0",UNKNOWN_ERROR:"unknown_error"},la={BEARER:"Bearer",POP:"pop",SSH:"ssh-cert"},ha=60,da=3600,fa="throttling",pa="retry-after, h429",ma="invalid_grant",ga="client_mismatch",ya="username",va="password",Ea=200,ba=400,wa="1",Ia="3",Ca="4",_a="2",Ta="4",Sa="5",Aa="0",Oa="1",ka="2",Ra="3",Pa="4",Na="unexpected_error",La="post_request_failed",Da={[Na]:"Unexpected error in authentication.",[La]:"Post request failed from the network, could be a 4xx/5xx or a network unavailability. Please check the exact error code for details."};class xa extends Error{constructor(e,t,r){super(t?`${e}: ${t}`:e),Object.setPrototypeOf(this,xa.prototype),this.errorCode=e||vs.EMPTY_STRING,this.errorMessage=t||vs.EMPTY_STRING,this.subError=r||vs.EMPTY_STRING,this.name="AuthError"}setCorrelationId(e){this.correlationId=e}}function Ma(e,t){return new xa(e,t?`${Da[e]} ${t}`:Da[e])}const $a="client_info_decoding_error",Ua="client_info_empty_error",Fa="token_parsing_error",ja="null_or_empty_token",Ba="endpoints_resolution_error",qa="network_error",Ha="openid_config_error",Ga="hash_not_deserialized",za="invalid_state",Ka="state_mismatch",Va="state_not_found",Ya="nonce_mismatch",Wa="auth_time_not_found",Qa="max_age_transpired",Ja="multiple_matching_tokens",Za="multiple_matching_accounts",Xa="multiple_matching_appMetadata",ec="request_cannot_be_made",tc="cannot_remove_empty_scope",rc="cannot_append_scopeset",nc="empty_input_scopeset",oc="device_code_polling_cancelled",ic="device_code_expired",sc="device_code_unknown_error",ac="no_account_in_silent_request",cc="invalid_cache_record",uc="invalid_cache_environment",lc="no_account_found",hc="no_crypto_object",dc="unexpected_credential_type",fc="invalid_assertion",pc="invalid_client_credential",mc="token_refresh_required",gc="user_timeout_reached",yc="token_claims_cnf_required_for_signedjwt",vc="authorization_code_missing_from_server_response",Ec="binding_key_not_removed",bc="end_session_endpoint_not_supported",wc="key_id_missing",Ic="no_network_connectivity",Cc="user_canceled",_c="missing_tenant_id_error",Tc="method_not_implemented",Sc="nested_app_auth_bridge_disabled",Ac={[$a]:"The client info could not be parsed/decoded correctly",[Ua]:"The client info was empty",[Fa]:"Token cannot be parsed",[ja]:"The token is null or empty",[Ba]:"Endpoints cannot be resolved",[qa]:"Network request failed",[Ha]:"Could not retrieve endpoints. Check your authority and verify the .well-known/openid-configuration endpoint returns the required endpoints.",[Ga]:"The hash parameters could not be deserialized",[za]:"State was not the expected format",[Ka]:"State mismatch error",[Va]:"State not found",[Ya]:"Nonce mismatch error",[Wa]:"Max Age was requested and the ID token is missing the auth_time variable. auth_time is an optional claim and is not enabled by default - it must be enabled. See https://aka.ms/msaljs/optional-claims for more information.",[Qa]:"Max Age is set to 0, or too much time has elapsed since the last end-user authentication.",[Ja]:"The cache contains multiple tokens satisfying the requirements. Call AcquireToken again providing more requirements such as authority or account.",[Za]:"The cache contains multiple accounts satisfying the given parameters. Please pass more info to obtain the correct account",[Xa]:"The cache contains multiple appMetadata satisfying the given parameters. Please pass more info to obtain the correct appMetadata",[ec]:"Token request cannot be made without authorization code or refresh token.",[tc]:"Cannot remove null or empty scope from ScopeSet",[rc]:"Cannot append ScopeSet",[nc]:"Empty input ScopeSet cannot be processed",[oc]:"Caller has cancelled token endpoint polling during device code flow by setting DeviceCodeRequest.cancel = true.",[ic]:"Device code is expired.",[sc]:"Device code stopped polling for unknown reasons.",[ac]:"Please pass an account object, silent flow is not supported without account information",[cc]:"Cache record object was null or undefined.",[uc]:"Invalid environment when attempting to create cache entry",[lc]:"No account found in cache for given key.",[hc]:"No crypto object detected.",[dc]:"Unexpected credential type.",[fc]:"Client assertion must meet requirements described in https://tools.ietf.org/html/rfc7515",[pc]:"Client credential (secret, certificate, or assertion) must not be empty when creating a confidential client. An application should at most have one credential",[mc]:"Cannot return token from cache because it must be refreshed. This may be due to one of the following reasons: forceRefresh parameter is set to true, claims have been requested, there is no cached access token or it is expired.",[gc]:"User defined timeout for device code polling reached",[yc]:"Cannot generate a POP jwt if the token_claims are not populated",[vc]:"Server response does not contain an authorization code to proceed",[Ec]:"Could not remove the credential's binding key from storage.",[bc]:"The provided authority does not support logout",[wc]:"A keyId value is missing from the requested bound token's cache record and is required to match the token to it's stored binding key.",[Ic]:"No network connectivity. Check your internet connection.",[Cc]:"User cancelled the flow.",[_c]:"A tenant id - not common, organizations, or consumers - must be specified when using the client_credentials flow.",[Tc]:"This method has not been implemented",[Sc]:"The nested app auth bridge is disabled"};class Oc extends xa{constructor(e,t){super(e,t?`${Ac[e]}: ${t}`:Ac[e]),this.name="ClientAuthError",Object.setPrototypeOf(this,Oc.prototype)}}function kc(e,t){return new Oc(e,t)}const Rc={createNewGuid:()=>{throw kc(Tc)},base64Decode:()=>{throw kc(Tc)},base64Encode:()=>{throw kc(Tc)},base64UrlEncode:()=>{throw kc(Tc)},encodeKid:()=>{throw kc(Tc)},async getPublicKeyThumbprint(){throw kc(Tc)},async removeTokenBindingKey(){throw kc(Tc)},async clearKeystore(){throw kc(Tc)},async signJwt(){throw kc(Tc)},async hashString(){throw kc(Tc)}};var Pc;!function(e){e[e.Error=0]="Error",e[e.Warning=1]="Warning",e[e.Info=2]="Info",e[e.Verbose=3]="Verbose",e[e.Trace=4]="Trace"}(Pc||(Pc={}));let Nc=class e{constructor(t,r,n){this.level=Pc.Info;const o=t||e.createDefaultLoggerOptions();this.localCallback=o.loggerCallback||(()=>{}),this.piiLoggingEnabled=o.piiLoggingEnabled||!1,this.level="number"==typeof o.logLevel?o.logLevel:Pc.Info,this.correlationId=o.correlationId||vs.EMPTY_STRING,this.packageName=r||vs.EMPTY_STRING,this.packageVersion=n||vs.EMPTY_STRING}static createDefaultLoggerOptions(){return{loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:Pc.Info}}clone(t,r,n){return new e({loggerCallback:this.localCallback,piiLoggingEnabled:this.piiLoggingEnabled,logLevel:this.level,correlationId:n||this.correlationId},t,r)}logMessage(e,t){if(t.logLevel>this.level||!this.piiLoggingEnabled&&t.containsPii)return;const r=`${`[${(new Date).toUTCString()}] : [${t.correlationId||this.correlationId||""}]`} : ${this.packageName}@${this.packageVersion} : ${Pc[t.logLevel]} - ${e}`;this.executeCallback(t.logLevel,r,t.containsPii||!1)}executeCallback(e,t,r){this.localCallback&&this.localCallback(e,t,r)}error(e,t){this.logMessage(e,{logLevel:Pc.Error,containsPii:!1,correlationId:t||vs.EMPTY_STRING})}errorPii(e,t){this.logMessage(e,{logLevel:Pc.Error,containsPii:!0,correlationId:t||vs.EMPTY_STRING})}warning(e,t){this.logMessage(e,{logLevel:Pc.Warning,containsPii:!1,correlationId:t||vs.EMPTY_STRING})}warningPii(e,t){this.logMessage(e,{logLevel:Pc.Warning,containsPii:!0,correlationId:t||vs.EMPTY_STRING})}info(e,t){this.logMessage(e,{logLevel:Pc.Info,containsPii:!1,correlationId:t||vs.EMPTY_STRING})}infoPii(e,t){this.logMessage(e,{logLevel:Pc.Info,containsPii:!0,correlationId:t||vs.EMPTY_STRING})}verbose(e,t){this.logMessage(e,{logLevel:Pc.Verbose,containsPii:!1,correlationId:t||vs.EMPTY_STRING})}verbosePii(e,t){this.logMessage(e,{logLevel:Pc.Verbose,containsPii:!0,correlationId:t||vs.EMPTY_STRING})}trace(e,t){this.logMessage(e,{logLevel:Pc.Trace,containsPii:!1,correlationId:t||vs.EMPTY_STRING})}tracePii(e,t){this.logMessage(e,{logLevel:Pc.Trace,containsPii:!0,correlationId:t||vs.EMPTY_STRING})}isPiiLoggingEnabled(){return this.piiLoggingEnabled||!1}};const Lc="@azure/msal-common",Dc="15.6.0",xc="none";function Mc(e,t){const r=function(e){if(!e)throw kc(ja);const t=/^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/.exec(e);if(!t||t.length<4)throw kc(Fa);return t[2]}(e);try{const e=t(r);return JSON.parse(e)}catch(e){throw kc(Fa)}}function $c(e,t){if(0===t||Date.now()-3e5>e+t)throw kc(Qa)}function Uc(){return Math.round((new Date).getTime()/1e3)}function Fc(e){return e?new Date(1e3*Number(e)):new Date}function jc(e,t){const r=Number(e)||0;return Uc()+t>r}function Bc(e,t){return new Promise(r=>setTimeout(()=>r(t),e))}function qc(e){return[Vc(e),Yc(e),Wc(e),Qc(e),Jc(e)].join(Zs).toLowerCase()}function Hc(e){return e.hasOwnProperty("homeAccountId")&&e.hasOwnProperty("environment")&&e.hasOwnProperty("credentialType")&&e.hasOwnProperty("clientId")&&e.hasOwnProperty("secret")}function Gc(e){return!!e&&(Hc(e)&&e.hasOwnProperty("realm")&&e.hasOwnProperty("target")&&(e.credentialType===ea.ACCESS_TOKEN||e.credentialType===ea.ACCESS_TOKEN_WITH_AUTH_SCHEME))}function zc(e){return!!e&&(Hc(e)&&e.hasOwnProperty("realm")&&e.credentialType===ea.ID_TOKEN)}function Kc(e){return!!e&&(Hc(e)&&e.credentialType===ea.REFRESH_TOKEN)}function Vc(e){return[e.homeAccountId,e.environment].join(Zs).toLowerCase()}function Yc(e){const t=e.credentialType===ea.REFRESH_TOKEN&&e.familyId||e.clientId;return[e.credentialType,t,e.realm||""].join(Zs).toLowerCase()}function Wc(e){return(e.target||"").toLowerCase()}function Qc(e){return(e.requestedClaimsHash||"").toLowerCase()}function Jc(e){return e.tokenType&&e.tokenType.toLowerCase()!==la.BEARER.toLowerCase()?e.tokenType.toLowerCase():""}function Zc(e,t){return!!t&&(0===e.indexOf(ta)&&t.hasOwnProperty("clientId")&&t.hasOwnProperty("environment"))}function Xc(){return Uc()+oa}function eu(e,t,r){e.authorization_endpoint=t.authorization_endpoint,e.token_endpoint=t.token_endpoint,e.end_session_endpoint=t.end_session_endpoint,e.issuer=t.issuer,e.endpointsFromNetwork=r,e.jwks_uri=t.jwks_uri}function tu(e,t,r){e.aliases=t.aliases,e.preferred_cache=t.preferred_cache,e.preferred_network=t.preferred_network,e.aliasesFromNetwork=r}function ru(e){return e.expiresAt<=Uc()}const nu="redirect_uri_empty",ou="claims_request_parsing_error",iu="authority_uri_insecure",su="url_parse_error",au="empty_url_error",cu="empty_input_scopes_error",uu="invalid_prompt_value",lu="invalid_claims",hu="token_request_empty",du="logout_request_empty",fu="invalid_code_challenge_method",pu="pkce_params_missing",mu="invalid_cloud_discovery_metadata",gu="invalid_authority_metadata",yu="untrusted_authority",vu="missing_ssh_jwk",Eu="missing_ssh_kid",bu="missing_nonce_authentication_header",wu="invalid_authentication_header",Iu="cannot_set_OIDCOptions",Cu="cannot_allow_platform_broker",_u="authority_mismatch",Tu={[nu]:"A redirect URI is required for all calls, and none has been set.",[ou]:"Could not parse the given claims request object.",[iu]:"Authority URIs must use https. Please see here for valid authority configuration options: https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-js-initializing-client-applications#configuration-options",[su]:"URL could not be parsed into appropriate segments.",[au]:"URL was empty or null.",[cu]:"Scopes cannot be passed as null, undefined or empty array because they are required to obtain an access token.",[uu]:"Please see here for valid configuration options: https://azuread.github.io/microsoft-authentication-library-for-js/ref/modules/_azure_msal_common.html#commonauthorizationurlrequest",[lu]:"Given claims parameter must be a stringified JSON object.",[hu]:"Token request was empty and not found in cache.",[du]:"The logout request was null or undefined.",[fu]:'code_challenge_method passed is invalid. Valid values are "plain" and "S256".',[pu]:"Both params: code_challenge and code_challenge_method are to be passed if to be sent in the request",[mu]:"Invalid cloudDiscoveryMetadata provided. Must be a stringified JSON object containing tenant_discovery_endpoint and metadata fields",[gu]:"Invalid authorityMetadata provided. Must by a stringified JSON object containing authorization_endpoint, token_endpoint, issuer fields.",[yu]:"The provided authority is not a trusted authority. Please include this authority in the knownAuthorities config parameter.",[vu]:"Missing sshJwk in SSH certificate request. A stringified JSON Web Key is required when using the SSH authentication scheme.",[Eu]:"Missing sshKid in SSH certificate request. A string that uniquely identifies the public SSH key is required when using the SSH authentication scheme.",[bu]:"Unable to find an authentication header containing server nonce. Either the Authentication-Info or WWW-Authenticate headers must be present in order to obtain a server nonce.",[wu]:"Invalid authentication header provided",[Iu]:"Cannot set OIDCOptions parameter. Please change the protocol mode to OIDC or use a non-Microsoft authority.",[Cu]:"Cannot set allowPlatformBroker parameter to true when not in AAD protocol mode.",[_u]:"Authority mismatch error. Authority provided in login request or PublicClientApplication config does not match the environment of the provided account. Please use a matching account or make an interactive request to login to this authority."};class Su extends xa{constructor(e){super(e,Tu[e]),this.name="ClientConfigurationError",Object.setPrototypeOf(this,Su.prototype)}}function Au(e){return new Su(e)}class Ou{static isEmptyObj(e){if(e)try{const t=JSON.parse(e);return 0===Object.keys(t).length}catch(e){}return!0}static startsWith(e,t){return 0===e.indexOf(t)}static endsWith(e,t){return e.length>=t.length&&e.lastIndexOf(t)===e.length-t.length}static queryStringToObject(e){const t={},r=e.split("&"),n=e=>decodeURIComponent(e.replace(/\+/g," "));return r.forEach(e=>{if(e.trim()){const[r,o]=e.split(/=(.+)/g,2);r&&o&&(t[n(r)]=n(o))}}),t}static trimArrayEntries(e){return e.map(e=>e.trim())}static removeEmptyStringsFromArray(e){return e.filter(e=>!!e)}static jsonParseHelper(e){try{return JSON.parse(e)}catch(e){return null}}static matchPattern(e,t){return new RegExp(e.replace(/\\/g,"\\\\").replace(/\*/g,"[^ ]*").replace(/\?/g,"\\?")).test(t)}}class ku{constructor(e){const t=e?Ou.trimArrayEntries([...e]):[],r=t?Ou.removeEmptyStringsFromArray(t):[];if(!r||!r.length)throw Au(cu);this.scopes=new Set,r.forEach(e=>this.scopes.add(e))}static fromString(e){const t=(e||vs.EMPTY_STRING).split(" ");return new ku(t)}static createSearchScopes(e){const t=new ku(e);return t.containsOnlyOIDCScopes()?t.removeScope(vs.OFFLINE_ACCESS_SCOPE):t.removeOIDCScopes(),t}containsScope(e){const t=this.printScopesLowerCase().split(" "),r=new ku(t);return!!e&&r.scopes.has(e.toLowerCase())}containsScopeSet(e){return!(!e||e.scopes.size<=0)&&(this.scopes.size>=e.scopes.size&&e.asArray().every(e=>this.containsScope(e)))}containsOnlyOIDCScopes(){let e=0;return Os.forEach(t=>{this.containsScope(t)&&(e+=1)}),this.scopes.size===e}appendScope(e){e&&this.scopes.add(e.trim())}appendScopes(e){try{e.forEach(e=>this.appendScope(e))}catch(e){throw kc(rc)}}removeScope(e){if(!e)throw kc(tc);this.scopes.delete(e.trim())}removeOIDCScopes(){Os.forEach(e=>{this.scopes.delete(e)})}unionScopeSets(e){if(!e)throw kc(nc);const t=new Set;return e.scopes.forEach(e=>t.add(e.toLowerCase())),this.scopes.forEach(e=>t.add(e.toLowerCase())),t}intersectingScopeSets(e){if(!e)throw kc(nc);e.containsOnlyOIDCScopes()||e.removeOIDCScopes();const t=this.unionScopeSets(e),r=e.getScopeCount(),n=this.getScopeCount();return t.size<n+r}getScopeCount(){return this.scopes.size}asArray(){const e=[];return this.scopes.forEach(t=>e.push(t)),e}printScopes(){if(this.scopes){return this.asArray().join(" ")}return vs.EMPTY_STRING}printScopesLowerCase(){return this.printScopes().toLowerCase()}}function Ru(e,t){if(!e)throw kc(Ua);try{const r=t(e);return JSON.parse(r)}catch(e){throw kc($a)}}function Pu(e){if(!e)throw kc($a);const t=e.split(Xs,2);return{uid:t[0],utid:t.length<2?vs.EMPTY_STRING:t[1]}}function Nu(e,t){return!!e&&!!t&&e===t.split(".")[1]}function Lu(e,t,r,n){if(n){const{oid:t,sub:r,tid:o,name:i,tfp:s,acr:a}=n,c=o||s||a||"";return{tenantId:c,localAccountId:t||r||"",name:i,isHomeTenant:Nu(c,e)}}return{tenantId:r,localAccountId:t,isHomeTenant:Nu(r,e)}}function Du(e,t,r,n){let o=e;if(t){const{isHomeTenant:r,...n}=t;o={...e,...n}}if(r){const{isHomeTenant:t,...i}=Lu(e.homeAccountId,e.localAccountId,e.tenantId,r);return o={...o,...i,idTokenClaims:r,idToken:n},o}return o}const xu=0,Mu=1,$u=2,Uu=3;function Fu(e){if(e){return e.tid||e.tfp||e.acr||null}return null}const ju="AAD",Bu="OIDC";class qu{generateAccountId(){return[this.homeAccountId,this.environment].join(Zs).toLowerCase()}generateAccountKey(){return qu.generateAccountCacheKey({homeAccountId:this.homeAccountId,environment:this.environment,tenantId:this.realm,username:this.username,localAccountId:this.localAccountId})}getAccountInfo(){return{homeAccountId:this.homeAccountId,environment:this.environment,tenantId:this.realm,username:this.username,localAccountId:this.localAccountId,name:this.name,nativeAccountId:this.nativeAccountId,authorityType:this.authorityType,tenantProfiles:new Map((this.tenantProfiles||[]).map(e=>[e.tenantId,e]))}}isSingleTenant(){return!this.tenantProfiles}static generateAccountCacheKey(e){const t=e.homeAccountId.split(".")[1];return[e.homeAccountId,e.environment||"",t||e.tenantId||""].join(Zs).toLowerCase()}static createAccount(e,t,r){const n=new qu;let o;t.authorityType===Mu?n.authorityType=Qs:t.protocolMode===Bu?n.authorityType=Js:n.authorityType=Ws,e.clientInfo&&r&&(o=Ru(e.clientInfo,r)),n.clientInfo=e.clientInfo,n.homeAccountId=e.homeAccountId,n.nativeAccountId=e.nativeAccountId;const i=e.environment||t&&t.getPreferredCache();if(!i)throw kc(uc);n.environment=i,n.realm=o?.utid||Fu(e.idTokenClaims)||"",n.localAccountId=o?.uid||e.idTokenClaims?.oid||e.idTokenClaims?.sub||"";const s=e.idTokenClaims?.preferred_username||e.idTokenClaims?.upn,a=e.idTokenClaims?.emails?e.idTokenClaims.emails[0]:null;if(n.username=s||a||"",n.name=e.idTokenClaims?.name||"",n.cloudGraphHostName=e.cloudGraphHostName,n.msGraphHost=e.msGraphHost,e.tenantProfiles)n.tenantProfiles=e.tenantProfiles;else{const t=Lu(e.homeAccountId,n.localAccountId,n.realm,e.idTokenClaims);n.tenantProfiles=[t]}return n}static createFromAccountInfo(e,t,r){const n=new qu;return n.authorityType=e.authorityType||Js,n.homeAccountId=e.homeAccountId,n.localAccountId=e.localAccountId,n.nativeAccountId=e.nativeAccountId,n.realm=e.tenantId,n.environment=e.environment,n.username=e.username,n.name=e.name,n.cloudGraphHostName=t,n.msGraphHost=r,n.tenantProfiles=Array.from(e.tenantProfiles?.values()||[]),n}static generateHomeAccountId(e,t,r,n,o){if(t!==Mu&&t!==$u){if(e)try{const t=Ru(e,n.base64Decode);if(t.uid&&t.utid)return`${t.uid}.${t.utid}`}catch(e){}r.warning("No client info in response")}return o?.sub||""}static isAccountEntity(e){return!!e&&(e.hasOwnProperty("homeAccountId")&&e.hasOwnProperty("environment")&&e.hasOwnProperty("realm")&&e.hasOwnProperty("localAccountId")&&e.hasOwnProperty("username")&&e.hasOwnProperty("authorityType"))}static accountInfoIsEqual(e,t,r){if(!e||!t)return!1;let n=!0;if(r){const r=e.idTokenClaims||{},o=t.idTokenClaims||{};n=r.iat===o.iat&&r.nonce===o.nonce}return e.homeAccountId===t.homeAccountId&&e.localAccountId===t.localAccountId&&e.username===t.username&&e.tenantId===t.tenantId&&e.environment===t.environment&&e.nativeAccountId===t.nativeAccountId&&n}}function Hu(e){if(!e||e.indexOf("=")<0)return null;try{const t=function(e){return e.startsWith("#/")?e.substring(2):e.startsWith("#")||e.startsWith("?")?e.substring(1):e}(e),r=Object.fromEntries(new URLSearchParams(t));if(r.code||r.ear_jwe||r.error||r.error_description||r.state)return r}catch(e){throw kc(Ga)}return null}function Gu(e,t=!0,r){const n=new Array;return e.forEach((e,o)=>{!t&&r&&o in r?n.push(`${o}=${e}`):n.push(`${o}=${encodeURIComponent(e)}`)}),n.join("&")}class zu{get urlString(){return this._urlString}constructor(e){if(this._urlString=e,!this._urlString)throw Au(au);e.includes("#")||(this._urlString=zu.canonicalizeUri(e))}static canonicalizeUri(e){if(e){let t=e.toLowerCase();return Ou.endsWith(t,"?")?t=t.slice(0,-1):Ou.endsWith(t,"?/")&&(t=t.slice(0,-2)),Ou.endsWith(t,"/")||(t+="/"),t}return e}validateAsUri(){let e;try{e=this.getUrlComponents()}catch(e){throw Au(su)}if(!e.HostNameAndPort||!e.PathSegments)throw Au(su);if(!e.Protocol||"https:"!==e.Protocol.toLowerCase())throw Au(iu)}static appendQueryString(e,t){return t?e.indexOf("?")<0?`${e}?${t}`:`${e}&${t}`:e}static removeHashFromUrl(e){return zu.canonicalizeUri(e.split("#")[0])}replaceTenantPath(e){const t=this.getUrlComponents(),r=t.PathSegments;return!e||0===r.length||r[0]!==xs&&r[0]!==Ms||(r[0]=e),zu.constructAuthorityUriFromObject(t)}getUrlComponents(){const e=RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"),t=this.urlString.match(e);if(!t)throw Au(su);const r={Protocol:t[1],HostNameAndPort:t[4],AbsolutePath:t[5],QueryString:t[7]};let n=r.AbsolutePath.split("/");return n=n.filter(e=>e&&e.length>0),r.PathSegments=n,r.QueryString&&r.QueryString.endsWith("/")&&(r.QueryString=r.QueryString.substring(0,r.QueryString.length-1)),r}static getDomainFromUrl(e){const t=RegExp("^([^:/?#]+://)?([^/?#]*)"),r=e.match(t);if(!r)throw Au(su);return r[2]}static getAbsoluteUrl(e,t){if(e[0]===vs.FORWARD_SLASH){const r=new zu(t).getUrlComponents();return r.Protocol+"//"+r.HostNameAndPort+e}return e}static constructAuthorityUriFromObject(e){return new zu(e.Protocol+"//"+e.HostNameAndPort+"/"+e.PathSegments.join("/"))}static hashContainsKnownProperties(e){return!!Hu(e)}}const Ku={"login.microsoftonline.com":{token_endpoint:"https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/token",jwks_uri:"https://login.microsoftonline.com/{tenantid}/discovery/v2.0/keys",issuer:"https://login.microsoftonline.com/{tenantid}/v2.0",authorization_endpoint:"https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/authorize",end_session_endpoint:"https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/logout"},"login.chinacloudapi.cn":{token_endpoint:"https://login.chinacloudapi.cn/{tenantid}/oauth2/v2.0/token",jwks_uri:"https://login.chinacloudapi.cn/{tenantid}/discovery/v2.0/keys",issuer:"https://login.partner.microsoftonline.cn/{tenantid}/v2.0",authorization_endpoint:"https://login.chinacloudapi.cn/{tenantid}/oauth2/v2.0/authorize",end_session_endpoint:"https://login.chinacloudapi.cn/{tenantid}/oauth2/v2.0/logout"},"login.microsoftonline.us":{token_endpoint:"https://login.microsoftonline.us/{tenantid}/oauth2/v2.0/token",jwks_uri:"https://login.microsoftonline.us/{tenantid}/discovery/v2.0/keys",issuer:"https://login.microsoftonline.us/{tenantid}/v2.0",authorization_endpoint:"https://login.microsoftonline.us/{tenantid}/oauth2/v2.0/authorize",end_session_endpoint:"https://login.microsoftonline.us/{tenantid}/oauth2/v2.0/logout"}},Vu={metadata:[{preferred_network:"login.microsoftonline.com",preferred_cache:"login.windows.net",aliases:["login.microsoftonline.com","login.windows.net","login.microsoft.com","sts.windows.net"]},{preferred_network:"login.partner.microsoftonline.cn",preferred_cache:"login.partner.microsoftonline.cn",aliases:["login.partner.microsoftonline.cn","login.chinacloudapi.cn"]},{preferred_network:"login.microsoftonline.de",preferred_cache:"login.microsoftonline.de",aliases:["login.microsoftonline.de"]},{preferred_network:"login.microsoftonline.us",preferred_cache:"login.microsoftonline.us",aliases:["login.microsoftonline.us","login.usgovcloudapi.net"]},{preferred_network:"login-us.microsoftonline.com",preferred_cache:"login-us.microsoftonline.com",aliases:["login-us.microsoftonline.com"]}]},Yu=new Set;function Wu(e,t,r,n){if(n?.trace(`getAliasesFromMetadata called with source: ${r}`),e&&t){const o=Qu(t,e);if(o)return n?.trace(`getAliasesFromMetadata: found cloud discovery metadata in ${r}, returning aliases`),o.aliases;n?.trace(`getAliasesFromMetadata: did not find cloud discovery metadata in ${r}`)}return null}function Qu(e,t){for(let r=0;r<e.length;r++){const n=e[r];if(n.aliases.includes(t))return n}return null}Vu.metadata.forEach(e=>{e.aliases.forEach(e=>{Yu.add(e)})});const Ju="cache_quota_exceeded",Zu="cache_error_unknown",Xu={[Ju]:"Exceeded cache storage capacity.",[Zu]:"Unexpected error occurred when using cache storage."};class el extends Error{constructor(e,t){const r=t||(Xu[e]?Xu[e]:Xu[Zu]);super(`${e}: ${r}`),Object.setPrototypeOf(this,el.prototype),this.name="CacheError",this.errorCode=e,this.errorMessage=r}}class tl{constructor(e,t,r,n){this.clientId=e,this.cryptoImpl=t,this.commonLogger=r.clone(Lc,Dc),this.staticAuthorityOptions=n}getAllAccounts(e){return this.buildTenantProfiles(this.getAccountsFilteredBy(e||{}),e)}getAccountInfoFilteredBy(e){const t=this.getAllAccounts(e);if(t.length>1){return t.sort(e=>e.idTokenClaims?-1:1)[0]}return 1===t.length?t[0]:null}getBaseAccountInfo(e){const t=this.getAccountsFilteredBy(e);return t.length>0?t[0].getAccountInfo():null}buildTenantProfiles(e,t){return e.flatMap(e=>this.getTenantProfilesFromAccountEntity(e,t?.tenantId,t))}getTenantedAccountInfoByFilter(e,t,r,n){let o,i=null;if(n&&!this.tenantProfileMatchesFilter(r,n))return null;const s=this.getIdToken(e,t,r.tenantId);return s&&(o=Mc(s.secret,this.cryptoImpl.base64Decode),!this.idTokenClaimsMatchTenantProfileFilter(o,n))?null:(i=Du(e,r,o,s?.secret),i)}getTenantProfilesFromAccountEntity(e,t,r){const n=e.getAccountInfo();let o=n.tenantProfiles||new Map;const i=this.getTokenKeys();if(t){const e=o.get(t);if(!e)return[];o=new Map([[t,e]])}const s=[];return o.forEach(e=>{const t=this.getTenantedAccountInfoByFilter(n,i,e,r);t&&s.push(t)}),s}tenantProfileMatchesFilter(e,t){return!(t.localAccountId&&!this.matchLocalAccountIdFromTenantProfile(e,t.localAccountId))&&((!t.name||e.name===t.name)&&(void 0===t.isHomeTenant||e.isHomeTenant===t.isHomeTenant))}idTokenClaimsMatchTenantProfileFilter(e,t){if(t){if(t.localAccountId&&!this.matchLocalAccountIdFromTokenClaims(e,t.localAccountId))return!1;if(t.loginHint&&!this.matchLoginHintFromTokenClaims(e,t.loginHint))return!1;if(t.username&&!this.matchUsername(e.preferred_username,t.username))return!1;if(t.name&&!this.matchName(e,t.name))return!1;if(t.sid&&!this.matchSid(e,t.sid))return!1}return!0}async saveCacheRecord(e,t,r){if(!e)throw kc(cc);try{e.account&&await this.setAccount(e.account,t),e.idToken&&!1!==r?.idToken&&await this.setIdTokenCredential(e.idToken,t),e.accessToken&&!1!==r?.accessToken&&await this.saveAccessToken(e.accessToken,t),e.refreshToken&&!1!==r?.refreshToken&&await this.setRefreshTokenCredential(e.refreshToken,t),e.appMetadata&&this.setAppMetadata(e.appMetadata)}catch(e){throw this.commonLogger?.error("CacheManager.saveCacheRecord: failed"),e instanceof Error?(this.commonLogger?.errorPii(`CacheManager.saveCacheRecord: ${e.message}`,t),"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name||e.message.includes("exceeded the quota")?(this.commonLogger?.error("CacheManager.saveCacheRecord: exceeded storage quota",t),new el(Ju)):new el(e.name,e.message)):(this.commonLogger?.errorPii(`CacheManager.saveCacheRecord: ${e}`,t),new el(Zu))}}async saveAccessToken(e,t){const r={clientId:e.clientId,credentialType:e.credentialType,environment:e.environment,homeAccountId:e.homeAccountId,realm:e.realm,tokenType:e.tokenType,requestedClaimsHash:e.requestedClaimsHash},n=this.getTokenKeys(),o=ku.fromString(e.target),i=[];n.accessToken.forEach(e=>{if(!this.accessTokenKeyMatchesFilter(e,r,!1))return;const t=this.getAccessTokenCredential(e);if(t&&this.credentialMatchesFilter(t,r)){ku.fromString(t.target).intersectingScopeSets(o)&&i.push(this.removeAccessToken(e))}}),await Promise.all(i),await this.setAccessTokenCredential(e,t)}getAccountsFilteredBy(e){const t=this.getAccountKeys(),r=[];return t.forEach(t=>{if(!this.isAccountKey(t,e.homeAccountId))return;const n=this.getAccount(t,this.commonLogger);if(!n)return;if(e.homeAccountId&&!this.matchHomeAccountId(n,e.homeAccountId))return;if(e.username&&!this.matchUsername(n.username,e.username))return;if(e.environment&&!this.matchEnvironment(n,e.environment))return;if(e.realm&&!this.matchRealm(n,e.realm))return;if(e.nativeAccountId&&!this.matchNativeAccountId(n,e.nativeAccountId))return;if(e.authorityType&&!this.matchAuthorityType(n,e.authorityType))return;const o={localAccountId:e?.localAccountId,name:e?.name},i=n.tenantProfiles?.filter(e=>this.tenantProfileMatchesFilter(e,o));i&&0===i.length||r.push(n)}),r}isAccountKey(e,t,r){return!(e.split(Zs).length<3)&&(!(t&&!e.toLowerCase().includes(t.toLowerCase()))&&!(r&&!e.toLowerCase().includes(r.toLowerCase())))}isCredentialKey(e){if(e.split(Zs).length<6)return!1;const t=e.toLowerCase();if(-1===t.indexOf(ea.ID_TOKEN.toLowerCase())&&-1===t.indexOf(ea.ACCESS_TOKEN.toLowerCase())&&-1===t.indexOf(ea.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase())&&-1===t.indexOf(ea.REFRESH_TOKEN.toLowerCase()))return!1;if(t.indexOf(ea.REFRESH_TOKEN.toLowerCase())>-1){const e=`${ea.REFRESH_TOKEN}${Zs}${this.clientId}${Zs}`,r=`${ea.REFRESH_TOKEN}${Zs}${ra}${Zs}`;if(-1===t.indexOf(e.toLowerCase())&&-1===t.indexOf(r.toLowerCase()))return!1}else if(-1===t.indexOf(this.clientId.toLowerCase()))return!1;return!0}credentialMatchesFilter(e,t){if(t.clientId&&!this.matchClientId(e,t.clientId))return!1;if(t.userAssertionHash&&!this.matchUserAssertionHash(e,t.userAssertionHash))return!1;if("string"==typeof t.homeAccountId&&!this.matchHomeAccountId(e,t.homeAccountId))return!1;if(t.environment&&!this.matchEnvironment(e,t.environment))return!1;if(t.realm&&!this.matchRealm(e,t.realm))return!1;if(t.credentialType&&!this.matchCredentialType(e,t.credentialType))return!1;if(t.familyId&&!this.matchFamilyId(e,t.familyId))return!1;if(t.target&&!this.matchTarget(e,t.target))return!1;if((t.requestedClaimsHash||e.requestedClaimsHash)&&e.requestedClaimsHash!==t.requestedClaimsHash)return!1;if(e.credentialType===ea.ACCESS_TOKEN_WITH_AUTH_SCHEME){if(t.tokenType&&!this.matchTokenType(e,t.tokenType))return!1;if(t.tokenType===la.SSH&&t.keyId&&!this.matchKeyId(e,t.keyId))return!1}return!0}getAppMetadataFilteredBy(e){const t=this.getKeys(),r={};return t.forEach(t=>{if(!this.isAppMetadata(t))return;const n=this.getAppMetadata(t);n&&(e.environment&&!this.matchEnvironment(n,e.environment)||e.clientId&&!this.matchClientId(n,e.clientId)||(r[t]=n))}),r}getAuthorityMetadataByAlias(e){const t=this.getAuthorityMetadataKeys();let r=null;return t.forEach(t=>{if(!this.isAuthorityMetadata(t)||-1===t.indexOf(this.clientId))return;const n=this.getAuthorityMetadata(t);n&&-1!==n.aliases.indexOf(e)&&(r=n)}),r}async removeAllAccounts(){const e=this.getAccountKeys(),t=[];e.forEach(e=>{t.push(this.removeAccount(e))}),await Promise.all(t)}async removeAccount(e){const t=this.getAccount(e,this.commonLogger);t&&(await this.removeAccountContext(t),this.removeItem(e))}async removeAccountContext(e){const t=this.getTokenKeys(),r=e.generateAccountId(),n=[];t.idToken.forEach(e=>{0===e.indexOf(r)&&this.removeIdToken(e)}),t.accessToken.forEach(e=>{0===e.indexOf(r)&&n.push(this.removeAccessToken(e))}),t.refreshToken.forEach(e=>{0===e.indexOf(r)&&this.removeRefreshToken(e)}),await Promise.all(n)}async removeAccessToken(e){const t=this.getAccessTokenCredential(e);if(t){if(t.credentialType.toLowerCase()===ea.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase()&&t.tokenType===la.POP){const e=t.keyId;if(e)try{await this.cryptoImpl.removeTokenBindingKey(e)}catch(e){throw kc(Ec)}}return this.removeItem(e)}}removeAppMetadata(){return this.getKeys().forEach(e=>{this.isAppMetadata(e)&&this.removeItem(e)}),!0}readAccountFromCache(e){const t=qu.generateAccountCacheKey(e);return this.getAccount(t,this.commonLogger)}getIdToken(e,t,r,n,o){this.commonLogger.trace("CacheManager - getIdToken called");const i={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:ea.ID_TOKEN,clientId:this.clientId,realm:r},s=this.getIdTokensByFilter(i,t),a=s.size;if(a<1)return this.commonLogger.info("CacheManager:getIdToken - No token found"),null;if(a>1){let t=s;if(!r){const r=new Map;s.forEach((t,n)=>{t.realm===e.tenantId&&r.set(n,t)});const n=r.size;if(n<1)return this.commonLogger.info("CacheManager:getIdToken - Multiple ID tokens found for account but none match account entity tenant id, returning first result"),s.values().next().value;if(1===n)return this.commonLogger.info("CacheManager:getIdToken - Multiple ID tokens found for account, defaulting to home tenant profile"),r.values().next().value;t=r}return this.commonLogger.info("CacheManager:getIdToken - Multiple matching ID tokens found, clearing them"),t.forEach((e,t)=>{this.removeIdToken(t)}),n&&o&&n.addFields({multiMatchedID:s.size},o),null}return this.commonLogger.info("CacheManager:getIdToken - Returning ID token"),s.values().next().value}getIdTokensByFilter(e,t){const r=t&&t.idToken||this.getTokenKeys().idToken,n=new Map;return r.forEach(t=>{if(!this.idTokenKeyMatchesFilter(t,{clientId:this.clientId,...e}))return;const r=this.getIdTokenCredential(t);r&&this.credentialMatchesFilter(r,e)&&n.set(t,r)}),n}idTokenKeyMatchesFilter(e,t){const r=e.toLowerCase();return(!t.clientId||-1!==r.indexOf(t.clientId.toLowerCase()))&&(!t.homeAccountId||-1!==r.indexOf(t.homeAccountId.toLowerCase()))}removeIdToken(e){this.removeItem(e)}removeRefreshToken(e){this.removeItem(e)}getAccessToken(e,t,r,n,o,i){this.commonLogger.trace("CacheManager - getAccessToken called");const s=ku.createSearchScopes(t.scopes),a=t.authenticationScheme||la.BEARER,c=a.toLowerCase()!==la.BEARER.toLowerCase()?ea.ACCESS_TOKEN_WITH_AUTH_SCHEME:ea.ACCESS_TOKEN,u={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:c,clientId:this.clientId,realm:n||e.tenantId,target:s,tokenType:a,keyId:t.sshKid,requestedClaimsHash:t.requestedClaimsHash},l=r&&r.accessToken||this.getTokenKeys().accessToken,h=[];l.forEach(e=>{if(this.accessTokenKeyMatchesFilter(e,u,!0)){const t=this.getAccessTokenCredential(e);t&&this.credentialMatchesFilter(t,u)&&h.push(t)}});const d=h.length;return d<1?(this.commonLogger.info("CacheManager:getAccessToken - No token found"),null):d>1?(this.commonLogger.info("CacheManager:getAccessToken - Multiple access tokens found, clearing them"),h.forEach(e=>{this.removeAccessToken(qc(e))}),o&&i&&o.addFields({multiMatchedAT:h.length},i),null):(this.commonLogger.info("CacheManager:getAccessToken - Returning access token"),h[0])}accessTokenKeyMatchesFilter(e,t,r){const n=e.toLowerCase();if(t.clientId&&-1===n.indexOf(t.clientId.toLowerCase()))return!1;if(t.homeAccountId&&-1===n.indexOf(t.homeAccountId.toLowerCase()))return!1;if(t.realm&&-1===n.indexOf(t.realm.toLowerCase()))return!1;if(t.requestedClaimsHash&&-1===n.indexOf(t.requestedClaimsHash.toLowerCase()))return!1;if(t.target){const e=t.target.asArray();for(let t=0;t<e.length;t++){if(r&&!n.includes(e[t].toLowerCase()))return!1;if(!r&&n.includes(e[t].toLowerCase()))return!0}}return!0}getAccessTokensByFilter(e){const t=this.getTokenKeys(),r=[];return t.accessToken.forEach(t=>{if(!this.accessTokenKeyMatchesFilter(t,e,!0))return;const n=this.getAccessTokenCredential(t);n&&this.credentialMatchesFilter(n,e)&&r.push(n)}),r}getRefreshToken(e,t,r,n,o){this.commonLogger.trace("CacheManager - getRefreshToken called");const i=t?ra:void 0,s={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:ea.REFRESH_TOKEN,clientId:this.clientId,familyId:i},a=r&&r.refreshToken||this.getTokenKeys().refreshToken,c=[];a.forEach(e=>{if(this.refreshTokenKeyMatchesFilter(e,s)){const t=this.getRefreshTokenCredential(e);t&&this.credentialMatchesFilter(t,s)&&c.push(t)}});const u=c.length;return u<1?(this.commonLogger.info("CacheManager:getRefreshToken - No refresh token found."),null):(u>1&&n&&o&&n.addFields({multiMatchedRT:u},o),this.commonLogger.info("CacheManager:getRefreshToken - returning refresh token"),c[0])}refreshTokenKeyMatchesFilter(e,t){const r=e.toLowerCase();return(!t.familyId||-1!==r.indexOf(t.familyId.toLowerCase()))&&(!(!t.familyId&&t.clientId&&-1===r.indexOf(t.clientId.toLowerCase()))&&(!t.homeAccountId||-1!==r.indexOf(t.homeAccountId.toLowerCase())))}readAppMetadataFromCache(e){const t={environment:e,clientId:this.clientId},r=this.getAppMetadataFilteredBy(t),n=Object.keys(r).map(e=>r[e]),o=n.length;if(o<1)return null;if(o>1)throw kc(Xa);return n[0]}isAppMetadataFOCI(e){const t=this.readAppMetadataFromCache(e);return!(!t||t.familyId!==ra)}matchHomeAccountId(e,t){return!("string"!=typeof e.homeAccountId||t!==e.homeAccountId)}matchLocalAccountIdFromTokenClaims(e,t){return t===(e.oid||e.sub)}matchLocalAccountIdFromTenantProfile(e,t){return e.localAccountId===t}matchName(e,t){return!(t.toLowerCase()!==e.name?.toLowerCase())}matchUsername(e,t){return!(!e||"string"!=typeof e||t?.toLowerCase()!==e.toLowerCase())}matchUserAssertionHash(e,t){return!(!e.userAssertionHash||t!==e.userAssertionHash)}matchEnvironment(e,t){if(this.staticAuthorityOptions){const r=function(e,t){let r;const n=e.canonicalAuthority;if(n){const o=new zu(n).getUrlComponents().HostNameAndPort;r=Wu(o,e.cloudDiscoveryMetadata?.metadata,ia,t)||Wu(o,Vu.metadata,ca,t)||e.knownAuthorities}return r||[]}(this.staticAuthorityOptions,this.commonLogger);if(r.includes(t)&&r.includes(e.environment))return!0}const r=this.getAuthorityMetadataByAlias(t);return!!(r&&r.aliases.indexOf(e.environment)>-1)}matchCredentialType(e,t){return e.credentialType&&t.toLowerCase()===e.credentialType.toLowerCase()}matchClientId(e,t){return!(!e.clientId||t!==e.clientId)}matchFamilyId(e,t){return!(!e.familyId||t!==e.familyId)}matchRealm(e,t){return!(e.realm?.toLowerCase()!==t.toLowerCase())}matchNativeAccountId(e,t){return!(!e.nativeAccountId||t!==e.nativeAccountId)}matchLoginHintFromTokenClaims(e,t){return e.login_hint===t||(e.preferred_username===t||e.upn===t)}matchSid(e,t){return e.sid===t}matchAuthorityType(e,t){return!(!e.authorityType||t.toLowerCase()!==e.authorityType.toLowerCase())}matchTarget(e,t){if(e.credentialType!==ea.ACCESS_TOKEN&&e.credentialType!==ea.ACCESS_TOKEN_WITH_AUTH_SCHEME||!e.target)return!1;return ku.fromString(e.target).containsScopeSet(t)}matchTokenType(e,t){return!(!e.tokenType||e.tokenType!==t)}matchKeyId(e,t){return!(!e.keyId||e.keyId!==t)}isAppMetadata(e){return-1!==e.indexOf(ta)}isAuthorityMetadata(e){return-1!==e.indexOf(na)}generateAuthorityMetadataCacheKey(e){return`${na}-${this.clientId}-${e}`}static toObject(e,t){for(const r in t)e[r]=t[r];return e}}class rl extends tl{async setAccount(){throw kc(Tc)}getAccount(){throw kc(Tc)}async setIdTokenCredential(){throw kc(Tc)}getIdTokenCredential(){throw kc(Tc)}async setAccessTokenCredential(){throw kc(Tc)}getAccessTokenCredential(){throw kc(Tc)}async setRefreshTokenCredential(){throw kc(Tc)}getRefreshTokenCredential(){throw kc(Tc)}setAppMetadata(){throw kc(Tc)}getAppMetadata(){throw kc(Tc)}setServerTelemetry(){throw kc(Tc)}getServerTelemetry(){throw kc(Tc)}setAuthorityMetadata(){throw kc(Tc)}getAuthorityMetadata(){throw kc(Tc)}getAuthorityMetadataKeys(){throw kc(Tc)}setThrottlingCache(){throw kc(Tc)}getThrottlingCache(){throw kc(Tc)}removeItem(){throw kc(Tc)}getKeys(){throw kc(Tc)}getAccountKeys(){throw kc(Tc)}getTokenKeys(){throw kc(Tc)}}const nl={tokenRenewalOffsetSeconds:300,preventCorsPreflight:!1},ol={loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:Pc.Info,correlationId:vs.EMPTY_STRING},il={claimsBasedCachingEnabled:!1},sl={async sendGetRequestAsync(){throw kc(Tc)},async sendPostRequestAsync(){throw kc(Tc)}},al={sku:vs.SKU,version:Dc,cpu:vs.EMPTY_STRING,os:vs.EMPTY_STRING},cl={clientSecret:vs.EMPTY_STRING,clientAssertion:void 0},ul={azureCloudInstance:xc,tenant:`${vs.DEFAULT_COMMON_TENANT}`},ll={application:{appName:"",appVersion:""}};function hl(e){return e.authOptions.authority.options.protocolMode===Bu}const dl="home_account_id",fl="UPN",pl="client_id",ml="redirect_uri",gl="token_type",yl="req_cnf",vl="return_spa_code",El="x-client-xtra-sku",bl="brk_client_id",wl="brk_redirect_uri",Il="instance_aware";function Cl(e,t,r){if(!t)return;const n=e.get(pl);n&&e.has(bl)&&r?.addFields({embeddedClientId:n,embeddedRedirectUri:e.get(ml)},t)}function _l(e,t){e.set("response_type",t)}function Tl(e,t,r=!0,n=As){!r||n.includes("openid")||t.includes("openid")||n.push("openid");const o=r?[...t||[],...n]:t||[],i=new ku(o);e.set("scope",i.printScopes())}function Sl(e,t){e.set(pl,t)}function Al(e,t){e.set(ml,t)}function Ol(e,t){e.set("login_hint",t)}function kl(e,t){e.set(Ns,`UPN:${t}`)}function Rl(e,t){e.set(Ns,`Oid:${t.uid}@${t.utid}`)}function Pl(e,t){e.set("sid",t)}function Nl(e,t,r){const n=function(e,t){let r;if(e)try{r=JSON.parse(e)}catch(e){throw Au(lu)}else r={};t&&t.length>0&&(r.hasOwnProperty(Us)||(r[Us]={}),r[Us][Fs]={values:t});return JSON.stringify(r)}(t,r);try{JSON.parse(n)}catch(e){throw Au(lu)}e.set("claims",n)}function Ll(e,t){e.set("client-request-id",t)}function Dl(e,t){e.set("x-client-SKU",t.sku),e.set("x-client-VER",t.version),t.os&&e.set("x-client-OS",t.os),t.cpu&&e.set("x-client-CPU",t.cpu)}function xl(e,t){t?.appName&&e.set("x-app-name",t.appName),t?.appVersion&&e.set("x-app-ver",t.appVersion)}function Ml(e,t){t&&e.set("state",t)}function $l(e,t){e.set("client_secret",t)}function Ul(e,t){t&&e.set("client_assertion",t)}function Fl(e,t){t&&e.set("client_assertion_type",t)}function jl(e,t){e.set("grant_type",t)}function Bl(e){e.set("client_info","1")}function ql(e){e.has(Il)||e.set(Il,"true")}function Hl(e,t){Object.entries(t).forEach(([t,r])=>{!e.has(t)&&r&&e.set(t,r)})}function Gl(e,t){t&&(e.set(gl,la.POP),e.set(yl,t))}function zl(e,t){t&&(e.set(gl,la.SSH),e.set(yl,t))}function Kl(e,t){e.set("x-client-current-telemetry",t.generateCurrentRequestHeaderValue()),e.set("x-client-last-telemetry",t.generateLastRequestHeaderValue())}function Vl(e){e.set("x-ms-lib-capability",pa)}function Yl(e,t,r){e.has(bl)||e.set(bl,t),e.has(wl)||e.set(wl,r)}const Wl="networkClientSendPostRequestAsync",Ql="refreshTokenClientExecutePostToTokenEndpoint",Jl="authorizationCodeClientExecutePostToTokenEndpoint",Zl="refreshTokenClientExecuteTokenRequest",Xl="refreshTokenClientAcquireToken",eh="refreshTokenClientAcquireTokenWithCachedRefreshToken",th="refreshTokenClientAcquireTokenByRefreshToken",rh="refreshTokenClientCreateTokenRequestBody",nh="silentFlowClientAcquireCachedToken",oh="silentFlowClientGenerateResultFromCacheRecord",ih="updateTokenEndpointAuthority",sh="authClientAcquireToken",ah="authClientExecuteTokenRequest",ch="authClientCreateTokenRequestBody",uh="popTokenGenerateCnf",lh="popTokenGenerateKid",hh="handleServerTokenResponse",dh="authorityFactoryCreateDiscoveredInstance",fh="authorityResolveEndpointsAsync",ph="authorityGetCloudDiscoveryMetadataFromNetwork",mh="authorityUpdateCloudDiscoveryMetadata",gh="authorityGetEndpointMetadataFromNetwork",yh="authorityUpdateEndpointMetadata",vh="authorityUpdateMetadataWithRegionalInformation",Eh="regionDiscoveryDetectRegion",bh="regionDiscoveryGetRegionFromIMDS",wh="regionDiscoveryGetCurrentVersion",Ih="cacheManagerGetRefreshToken",Ch=(e,t,r,n,o)=>(...i)=>{r.trace(`Executing function ${t}`);const s=n?.startMeasurement(t,o);if(o){const e=t+"CallCount";n?.incrementFields({[e]:1},o)}return n?.setPreQueueTime(t,o),e(...i).then(e=>(r.trace(`Returning result from ${t}`),s?.end({success:!0}),e)).catch(e=>{r.trace(`Error occurred in ${t}`);try{r.trace(JSON.stringify(e))}catch(e){r.trace("Unable to print error message.")}throw s?.end({success:!1},e),e})};class _h{constructor(e,t,r,n){this.networkInterface=e,this.logger=t,this.performanceClient=r,this.correlationId=n}async detectRegion(e,t){this.performanceClient?.addQueueMeasurement(Eh,this.correlationId);let r=e;if(r)t.region_source=Ia;else{const e=_h.IMDS_OPTIONS;try{const n=await Ch(this.getRegionFromIMDS.bind(this),bh,this.logger,this.performanceClient,this.correlationId)(vs.IMDS_VERSION,e);if(n.status===Ea&&(r=n.body,t.region_source=Ca),n.status===ba){const n=await Ch(this.getCurrentVersion.bind(this),wh,this.logger,this.performanceClient,this.correlationId)(e);if(!n)return t.region_source=wa,null;const o=await Ch(this.getRegionFromIMDS.bind(this),bh,this.logger,this.performanceClient,this.correlationId)(n,e);o.status===Ea&&(r=o.body,t.region_source=Ca)}}catch(e){return t.region_source=wa,null}}return r||(t.region_source=wa),r||null}async getRegionFromIMDS(e,t){return this.performanceClient?.addQueueMeasurement(bh,this.correlationId),this.networkInterface.sendGetRequestAsync(`${vs.IMDS_ENDPOINT}?api-version=${e}&format=text`,t,vs.IMDS_TIMEOUT)}async getCurrentVersion(e){this.performanceClient?.addQueueMeasurement(wh,this.correlationId);try{const t=await this.networkInterface.sendGetRequestAsync(`${vs.IMDS_ENDPOINT}?format=json`,e);return t.status===ba&&t.body&&t.body["newest-versions"]&&t.body["newest-versions"].length>0?t.body["newest-versions"][0]:null}catch(e){return null}}}_h.IMDS_OPTIONS={headers:{Metadata:"true"}};class Th{constructor(e,t,r,n,o,i,s,a){this.canonicalAuthority=e,this._canonicalAuthority.validateAsUri(),this.networkInterface=t,this.cacheManager=r,this.authorityOptions=n,this.regionDiscoveryMetadata={region_used:void 0,region_source:void 0,region_outcome:void 0},this.logger=o,this.performanceClient=s,this.correlationId=i,this.managedIdentity=a||!1,this.regionDiscovery=new _h(t,this.logger,this.performanceClient,this.correlationId)}getAuthorityType(e){if(e.HostNameAndPort.endsWith(vs.CIAM_AUTH_URL))return Uu;const t=e.PathSegments;if(t.length)switch(t[0].toLowerCase()){case vs.ADFS:return Mu;case vs.DSTS:return $u}return xu}get authorityType(){return this.getAuthorityType(this.canonicalAuthorityUrlComponents)}get protocolMode(){return this.authorityOptions.protocolMode}get options(){return this.authorityOptions}get canonicalAuthority(){return this._canonicalAuthority.urlString}set canonicalAuthority(e){this._canonicalAuthority=new zu(e),this._canonicalAuthority.validateAsUri(),this._canonicalAuthorityUrlComponents=null}get canonicalAuthorityUrlComponents(){return this._canonicalAuthorityUrlComponents||(this._canonicalAuthorityUrlComponents=this._canonicalAuthority.getUrlComponents()),this._canonicalAuthorityUrlComponents}get hostnameAndPort(){return this.canonicalAuthorityUrlComponents.HostNameAndPort.toLowerCase()}get tenant(){return this.canonicalAuthorityUrlComponents.PathSegments[0]}get authorizationEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.authorization_endpoint);throw kc(Ba)}get tokenEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.token_endpoint);throw kc(Ba)}get deviceCodeEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.token_endpoint.replace("/token","/devicecode"));throw kc(Ba)}get endSessionEndpoint(){if(this.discoveryComplete()){if(!this.metadata.end_session_endpoint)throw kc(bc);return this.replacePath(this.metadata.end_session_endpoint)}throw kc(Ba)}get selfSignedJwtAudience(){if(this.discoveryComplete())return this.replacePath(this.metadata.issuer);throw kc(Ba)}get jwksUri(){if(this.discoveryComplete())return this.replacePath(this.metadata.jwks_uri);throw kc(Ba)}canReplaceTenant(e){return 1===e.PathSegments.length&&!Th.reservedTenantDomains.has(e.PathSegments[0])&&this.getAuthorityType(e)===xu&&this.protocolMode!==Bu}replaceTenant(e){return e.replace(/{tenant}|{tenantid}/g,this.tenant)}replacePath(e){let t=e;const r=new zu(this.metadata.canonical_authority).getUrlComponents(),n=r.PathSegments;return this.canonicalAuthorityUrlComponents.PathSegments.forEach((e,o)=>{let i=n[o];if(0===o&&this.canReplaceTenant(r)){const e=new zu(this.metadata.authorization_endpoint).getUrlComponents().PathSegments[0];i!==e&&(this.logger.verbose(`Replacing tenant domain name ${i} with id ${e}`),i=e)}e!==i&&(t=t.replace(`/${i}/`,`/${e}/`))}),this.replaceTenant(t)}get defaultOpenIdConfigurationEndpoint(){const e=this.hostnameAndPort;return this.canonicalAuthority.endsWith("v2.0/")||this.authorityType===Mu||this.protocolMode===Bu&&!this.isAliasOfKnownMicrosoftAuthority(e)?`${this.canonicalAuthority}.well-known/openid-configuration`:`${this.canonicalAuthority}v2.0/.well-known/openid-configuration`}discoveryComplete(){return!!this.metadata}async resolveEndpointsAsync(){this.performanceClient?.addQueueMeasurement(fh,this.correlationId);const e=this.getCurrentMetadataEntity(),t=await Ch(this.updateCloudDiscoveryMetadata.bind(this),mh,this.logger,this.performanceClient,this.correlationId)(e);this.canonicalAuthority=this.canonicalAuthority.replace(this.hostnameAndPort,e.preferred_network);const r=await Ch(this.updateEndpointMetadata.bind(this),yh,this.logger,this.performanceClient,this.correlationId)(e);this.updateCachedMetadata(e,t,{source:r}),this.performanceClient?.addFields({cloudDiscoverySource:t,authorityEndpointSource:r},this.correlationId)}getCurrentMetadataEntity(){let e=this.cacheManager.getAuthorityMetadataByAlias(this.hostnameAndPort);return e||(e={aliases:[],preferred_cache:this.hostnameAndPort,preferred_network:this.hostnameAndPort,canonical_authority:this.canonicalAuthority,authorization_endpoint:"",token_endpoint:"",end_session_endpoint:"",issuer:"",aliasesFromNetwork:!1,endpointsFromNetwork:!1,expiresAt:Xc(),jwks_uri:""}),e}updateCachedMetadata(e,t,r){t!==sa&&r?.source!==sa&&(e.expiresAt=Xc(),e.canonical_authority=this.canonicalAuthority);const n=this.cacheManager.generateAuthorityMetadataCacheKey(e.preferred_cache);this.cacheManager.setAuthorityMetadata(n,e),this.metadata=e}async updateEndpointMetadata(e){this.performanceClient?.addQueueMeasurement(yh,this.correlationId);const t=this.updateEndpointMetadataFromLocalSources(e);if(t){if(t.source===ca&&this.authorityOptions.azureRegionConfiguration?.azureRegion&&t.metadata){eu(e,await Ch(this.updateMetadataWithRegionalInformation.bind(this),vh,this.logger,this.performanceClient,this.correlationId)(t.metadata),!1),e.canonical_authority=this.canonicalAuthority}return t.source}let r=await Ch(this.getEndpointMetadataFromNetwork.bind(this),gh,this.logger,this.performanceClient,this.correlationId)();if(r)return this.authorityOptions.azureRegionConfiguration?.azureRegion&&(r=await Ch(this.updateMetadataWithRegionalInformation.bind(this),vh,this.logger,this.performanceClient,this.correlationId)(r)),eu(e,r,!0),aa;throw kc(Ha,this.defaultOpenIdConfigurationEndpoint)}updateEndpointMetadataFromLocalSources(e){this.logger.verbose("Attempting to get endpoint metadata from authority configuration");const t=this.getEndpointMetadataFromConfig();if(t)return this.logger.verbose("Found endpoint metadata in authority configuration"),eu(e,t,!1),{source:ia};if(this.logger.verbose("Did not find endpoint metadata in the config... Attempting to get endpoint metadata from the hardcoded values."),this.authorityOptions.skipAuthorityMetadataCache)this.logger.verbose("Skipping hardcoded metadata cache since skipAuthorityMetadataCache is set to true. Attempting to get endpoint metadata from the network metadata cache.");else{const t=this.getEndpointMetadataFromHardcodedValues();if(t)return eu(e,t,!1),{source:ca,metadata:t};this.logger.verbose("Did not find endpoint metadata in hardcoded values... Attempting to get endpoint metadata from the network metadata cache.")}const r=ru(e);return this.isAuthoritySameType(e)&&e.endpointsFromNetwork&&!r?(this.logger.verbose("Found endpoint metadata in the cache."),{source:sa}):(r&&this.logger.verbose("The metadata entity is expired."),null)}isAuthoritySameType(e){return new zu(e.canonical_authority).getUrlComponents().PathSegments.length===this.canonicalAuthorityUrlComponents.PathSegments.length}getEndpointMetadataFromConfig(){if(this.authorityOptions.authorityMetadata)try{return JSON.parse(this.authorityOptions.authorityMetadata)}catch(e){throw Au(gu)}return null}async getEndpointMetadataFromNetwork(){this.performanceClient?.addQueueMeasurement(gh,this.correlationId);const e={},t=this.defaultOpenIdConfigurationEndpoint;this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: attempting to retrieve OAuth endpoints from ${t}`);try{const r=await this.networkInterface.sendGetRequestAsync(t,e),n=function(e){return e.hasOwnProperty("authorization_endpoint")&&e.hasOwnProperty("token_endpoint")&&e.hasOwnProperty("issuer")&&e.hasOwnProperty("jwks_uri")}(r.body);return n?r.body:(this.logger.verbose("Authority.getEndpointMetadataFromNetwork: could not parse response as OpenID configuration"),null)}catch(e){return this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: ${e}`),null}}getEndpointMetadataFromHardcodedValues(){return this.hostnameAndPort in Ku?Ku[this.hostnameAndPort]:null}async updateMetadataWithRegionalInformation(e){this.performanceClient?.addQueueMeasurement(vh,this.correlationId);const t=this.authorityOptions.azureRegionConfiguration?.azureRegion;if(t){if(t!==vs.AZURE_REGION_AUTO_DISCOVER_FLAG)return this.regionDiscoveryMetadata.region_outcome=_a,this.regionDiscoveryMetadata.region_used=t,Th.replaceWithRegionalInformation(e,t);const r=await Ch(this.regionDiscovery.detectRegion.bind(this.regionDiscovery),Eh,this.logger,this.performanceClient,this.correlationId)(this.authorityOptions.azureRegionConfiguration?.environmentRegion,this.regionDiscoveryMetadata);if(r)return this.regionDiscoveryMetadata.region_outcome=Ta,this.regionDiscoveryMetadata.region_used=r,Th.replaceWithRegionalInformation(e,r);this.regionDiscoveryMetadata.region_outcome=Sa}return e}async updateCloudDiscoveryMetadata(e){this.performanceClient?.addQueueMeasurement(mh,this.correlationId);const t=this.updateCloudDiscoveryMetadataFromLocalSources(e);if(t)return t;const r=await Ch(this.getCloudDiscoveryMetadataFromNetwork.bind(this),ph,this.logger,this.performanceClient,this.correlationId)();if(r)return tu(e,r,!0),aa;throw Au(yu)}updateCloudDiscoveryMetadataFromLocalSources(e){this.logger.verbose("Attempting to get cloud discovery metadata from authority configuration"),this.logger.verbosePii(`Known Authorities: ${this.authorityOptions.knownAuthorities||vs.NOT_APPLICABLE}`),this.logger.verbosePii(`Authority Metadata: ${this.authorityOptions.authorityMetadata||vs.NOT_APPLICABLE}`),this.logger.verbosePii(`Canonical Authority: ${e.canonical_authority||vs.NOT_APPLICABLE}`);const t=this.getCloudDiscoveryMetadataFromConfig();if(t)return this.logger.verbose("Found cloud discovery metadata in authority configuration"),tu(e,t,!1),ia;if(this.logger.verbose("Did not find cloud discovery metadata in the config... Attempting to get cloud discovery metadata from the hardcoded values."),this.options.skipAuthorityMetadataCache)this.logger.verbose("Skipping hardcoded cloud discovery metadata cache since skipAuthorityMetadataCache is set to true. Attempting to get cloud discovery metadata from the network metadata cache.");else{const t=(r=this.hostnameAndPort,Qu(Vu.metadata,r));if(t)return this.logger.verbose("Found cloud discovery metadata from hardcoded values."),tu(e,t,!1),ca;this.logger.verbose("Did not find cloud discovery metadata in hardcoded values... Attempting to get cloud discovery metadata from the network metadata cache.")}var r;const n=ru(e);return this.isAuthoritySameType(e)&&e.aliasesFromNetwork&&!n?(this.logger.verbose("Found cloud discovery metadata in the cache."),sa):(n&&this.logger.verbose("The metadata entity is expired."),null)}getCloudDiscoveryMetadataFromConfig(){if(this.authorityType===Uu)return this.logger.verbose("CIAM authorities do not support cloud discovery metadata, generate the aliases from authority host."),Th.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);if(this.authorityOptions.cloudDiscoveryMetadata){this.logger.verbose("The cloud discovery metadata has been provided as a network response, in the config.");try{this.logger.verbose("Attempting to parse the cloud discovery metadata.");const e=Qu(JSON.parse(this.authorityOptions.cloudDiscoveryMetadata).metadata,this.hostnameAndPort);if(this.logger.verbose("Parsed the cloud discovery metadata."),e)return this.logger.verbose("There is returnable metadata attached to the parsed cloud discovery metadata."),e;this.logger.verbose("There is no metadata attached to the parsed cloud discovery metadata.")}catch(e){throw this.logger.verbose("Unable to parse the cloud discovery metadata. Throwing Invalid Cloud Discovery Metadata Error."),Au(mu)}}return this.isInKnownAuthorities()?(this.logger.verbose("The host is included in knownAuthorities. Creating new cloud discovery metadata from the host."),Th.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort)):null}async getCloudDiscoveryMetadataFromNetwork(){this.performanceClient?.addQueueMeasurement(ph,this.correlationId);const e=`${vs.AAD_INSTANCE_DISCOVERY_ENDPT}${this.canonicalAuthority}oauth2/v2.0/authorize`,t={};let r=null;try{const n=await this.networkInterface.sendGetRequestAsync(e,t);let o,i;if(function(e){return e.hasOwnProperty("tenant_discovery_endpoint")&&e.hasOwnProperty("metadata")}(n.body))o=n.body,i=o.metadata,this.logger.verbosePii(`tenant_discovery_endpoint is: ${o.tenant_discovery_endpoint}`);else{if(!function(e){return e.hasOwnProperty("error")&&e.hasOwnProperty("error_description")}(n.body))return this.logger.error("AAD did not return a CloudInstanceDiscoveryResponse or CloudInstanceDiscoveryErrorResponse"),null;if(this.logger.warning(`A CloudInstanceDiscoveryErrorResponse was returned. The cloud instance discovery network request's status code is: ${n.status}`),o=n.body,o.error===vs.INVALID_INSTANCE)return this.logger.error("The CloudInstanceDiscoveryErrorResponse error is invalid_instance."),null;this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error is ${o.error}`),this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error description is ${o.error_description}`),this.logger.warning("Setting the value of the CloudInstanceDiscoveryMetadata (returned from the network) to []"),i=[]}this.logger.verbose("Attempting to find a match between the developer's authority and the CloudInstanceDiscoveryMetadata returned from the network request."),r=Qu(i,this.hostnameAndPort)}catch(e){if(e instanceof xa)this.logger.error(`There was a network error while attempting to get the cloud discovery instance metadata.\nError: ${e.errorCode}\nError Description: ${e.errorMessage}`);else{const t=e;this.logger.error(`A non-MSALJS error was thrown while attempting to get the cloud instance discovery metadata.\nError: ${t.name}\nError Description: ${t.message}`)}return null}return r||(this.logger.warning("The developer's authority was not found within the CloudInstanceDiscoveryMetadata returned from the network request."),this.logger.verbose("Creating custom Authority for custom domain scenario."),r=Th.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort)),r}isInKnownAuthorities(){return this.authorityOptions.knownAuthorities.filter(e=>e&&zu.getDomainFromUrl(e).toLowerCase()===this.hostnameAndPort).length>0}static generateAuthority(e,t){let r;if(t&&t.azureCloudInstance!==xc){const e=t.tenant?t.tenant:vs.DEFAULT_COMMON_TENANT;r=`${t.azureCloudInstance}/${e}/`}return r||e}static createCloudDiscoveryMetadataFromHost(e){return{preferred_network:e,preferred_cache:e,aliases:[e]}}getPreferredCache(){if(this.managedIdentity)return vs.DEFAULT_AUTHORITY_HOST;if(this.discoveryComplete())return this.metadata.preferred_cache;throw kc(Ba)}isAlias(e){return this.metadata.aliases.indexOf(e)>-1}isAliasOfKnownMicrosoftAuthority(e){return Yu.has(e)}static isPublicCloudAuthority(e){return vs.KNOWN_PUBLIC_CLOUDS.indexOf(e)>=0}static buildRegionalAuthorityString(e,t,r){const n=new zu(e);n.validateAsUri();const o=n.getUrlComponents();let i=`${t}.${o.HostNameAndPort}`;this.isPublicCloudAuthority(o.HostNameAndPort)&&(i=`${t}.${vs.REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX}`);const s=zu.constructAuthorityUriFromObject({...n.getUrlComponents(),HostNameAndPort:i}).urlString;return r?`${s}?${r}`:s}static replaceWithRegionalInformation(e,t){const r={...e};return r.authorization_endpoint=Th.buildRegionalAuthorityString(r.authorization_endpoint,t),r.token_endpoint=Th.buildRegionalAuthorityString(r.token_endpoint,t),r.end_session_endpoint&&(r.end_session_endpoint=Th.buildRegionalAuthorityString(r.end_session_endpoint,t)),r}static transformCIAMAuthority(e){let t=e;const r=new zu(e).getUrlComponents();if(0===r.PathSegments.length&&r.HostNameAndPort.endsWith(vs.CIAM_AUTH_URL)){t=`${t}${r.HostNameAndPort.split(".")[0]}${vs.AAD_TENANT_DOMAIN_SUFFIX}`}return t}}function Sh(e){return e.endsWith(vs.FORWARD_SLASH)?e:`${e}${vs.FORWARD_SLASH}`}async function Ah(e,t,r,n,o,i,s){s?.addQueueMeasurement(dh,i);const a=Th.transformCIAMAuthority(Sh(e)),c=new Th(a,t,r,n,o,i,s);try{return await Ch(c.resolveEndpointsAsync.bind(c),fh,o,s,i)(),c}catch(e){throw kc(Ba)}}Th.reservedTenantDomains=new Set(["{tenant}","{tenantid}",xs,$s,Ms]);class Oh extends xa{constructor(e,t,r,n,o){super(e,t,r),this.name="ServerError",this.errorNo=n,this.status=o,Object.setPrototypeOf(this,Oh.prototype)}}function kh(e,t,r){return{clientId:e,authority:t.authority,scopes:t.scopes,homeAccountIdentifier:r,claims:t.claims,authenticationScheme:t.authenticationScheme,resourceRequestMethod:t.resourceRequestMethod,resourceRequestUri:t.resourceRequestUri,shrClaims:t.shrClaims,sshKid:t.sshKid,embeddedClientId:t.embeddedClientId||t.tokenBodyParameters?.clientId}}class Rh{static generateThrottlingStorageKey(e){return`${fa}.${JSON.stringify(e)}`}static preProcess(e,t){const r=Rh.generateThrottlingStorageKey(t),n=e.getThrottlingCache(r);if(n){if(n.throttleTime<Date.now())return void e.removeItem(r);throw new Oh(n.errorCodes?.join(" ")||vs.EMPTY_STRING,n.errorMessage,n.subError)}}static postProcess(e,t,r){if(Rh.checkResponseStatus(r)||Rh.checkResponseForRetryAfter(r)){const n={throttleTime:Rh.calculateThrottleTime(parseInt(r.headers[Ps])),error:r.body.error,errorCodes:r.body.error_codes,errorMessage:r.body.error_description,subError:r.body.suberror};e.setThrottlingCache(Rh.generateThrottlingStorageKey(t),n)}}static checkResponseStatus(e){return 429===e.status||e.status>=500&&e.status<600}static checkResponseForRetryAfter(e){return!!e.headers&&(e.headers.hasOwnProperty(Ps)&&(e.status<200||e.status>=300))}static calculateThrottleTime(e){const t=e<=0?0:e,r=Date.now()/1e3;return Math.floor(1e3*Math.min(r+(t||ha),r+da))}static removeThrottle(e,t,r,n){const o=kh(t,r,n),i=this.generateThrottlingStorageKey(o);e.removeItem(i)}}class Ph extends xa{constructor(e,t,r){super(e.errorCode,e.errorMessage,e.subError),Object.setPrototypeOf(this,Ph.prototype),this.name="NetworkError",this.error=e,this.httpStatus=t,this.responseHeaders=r}}class Nh{constructor(e,t){this.config=function({authOptions:e,systemOptions:t,loggerOptions:r,cacheOptions:n,storageInterface:o,networkInterface:i,cryptoInterface:s,clientCredentials:a,libraryInfo:c,telemetry:u,serverTelemetryManager:l,persistencePlugin:h,serializableCache:d}){const f={...ol,...r};return{authOptions:(p=e,{clientCapabilities:[],azureCloudOptions:ul,skipAuthorityMetadataCache:!1,instanceAware:!1,encodeExtraQueryParams:!1,...p}),systemOptions:{...nl,...t},loggerOptions:f,cacheOptions:{...il,...n},storageInterface:o||new rl(e.clientId,Rc,new Nc(f)),networkInterface:i||sl,cryptoInterface:s||Rc,clientCredentials:a||cl,libraryInfo:{...al,...c},telemetry:{...ll,...u},serverTelemetryManager:l||null,persistencePlugin:h||null,serializableCache:d||null};var p}(e),this.logger=new Nc(this.config.loggerOptions,Lc,Dc),this.cryptoUtils=this.config.cryptoInterface,this.cacheManager=this.config.storageInterface,this.networkClient=this.config.networkInterface,this.serverTelemetryManager=this.config.serverTelemetryManager,this.authority=this.config.authOptions.authority,this.performanceClient=t}createTokenRequestHeaders(e){const t={};if(t[ks]=vs.URL_FORM_CONTENT_TYPE,!this.config.systemOptions.preventCorsPreflight&&e)switch(e.type){case dl:try{const r=Pu(e.credential);t[Ns]=`Oid:${r.uid}@${r.utid}`}catch(e){this.logger.verbose("Could not parse home account ID for CCS Header: "+e)}break;case fl:t[Ns]=`UPN: ${e.credential}`}return t}async executePostToTokenEndpoint(e,t,r,n,o,i){i&&this.performanceClient?.addQueueMeasurement(i,o);const s=await this.sendPostRequest(n,e,{body:t,headers:r},o);return this.config.serverTelemetryManager&&s.status<500&&429!==s.status&&this.config.serverTelemetryManager.clearTelemetryCache(),s}async sendPostRequest(e,t,r,n){let o;Rh.preProcess(this.cacheManager,e);try{o=await Ch(this.networkClient.sendPostRequestAsync.bind(this.networkClient),Wl,this.logger,this.performanceClient,n)(t,r);const e=o.headers||{};this.performanceClient?.addFields({refreshTokenSize:o.body.refresh_token?.length||0,httpVerToken:e[Ds]||"",requestId:e[Ls]||""},n)}catch(e){if(e instanceof Ph){const t=e.responseHeaders;throw t&&this.performanceClient?.addFields({httpVerToken:t[Ds]||"",requestId:t[Ls]||"",contentTypeHeader:t[ks]||void 0,contentLengthHeader:t[Rs]||void 0,httpStatus:e.httpStatus},n),e.error}throw e instanceof xa?e:kc(qa)}return Rh.postProcess(this.cacheManager,e,o),o}async updateAuthority(e,t){this.performanceClient?.addQueueMeasurement(ih,t);const r=`https://${e}/${this.authority.tenant}/`,n=await Ah(r,this.networkClient,this.cacheManager,this.authority.options,this.logger,t,this.performanceClient);this.authority=n}createTokenQueryParameters(e){const t=new Map;return e.embeddedClientId&&Yl(t,this.config.authOptions.clientId,this.config.authOptions.redirectUri),e.tokenQueryParameters&&Hl(t,e.tokenQueryParameters),Ll(t,e.correlationId),Cl(t,e.correlationId,this.performanceClient),Gu(t)}}const Lh="no_tokens_found",Dh="native_account_unavailable",xh="refresh_token_expired",Mh="bad_token",$h=["interaction_required","consent_required","login_required",Mh],Uh=["message_only","additional_action","basic_action","user_password_expired","consent_required","bad_token"],Fh={[Lh]:"No refresh token found in the cache. Please sign-in.",[Dh]:"The requested account is not available in the native broker. It may have been deleted or logged out. Please sign-in again using an interactive API.",[xh]:"Refresh token has expired.",[Mh]:"Identity provider returned bad_token due to an expired or invalid refresh token. Please invoke an interactive API to resolve."};class jh extends xa{constructor(e,t,r,n,o,i,s,a){super(e,t,r),Object.setPrototypeOf(this,jh.prototype),this.timestamp=n||vs.EMPTY_STRING,this.traceId=o||vs.EMPTY_STRING,this.correlationId=i||vs.EMPTY_STRING,this.claims=s||vs.EMPTY_STRING,this.name="InteractionRequiredAuthError",this.errorNo=a}}function Bh(e){return new jh(e,Fh[e])}class qh{static setRequestState(e,t,r){const n=qh.generateLibraryState(e,r);return t?`${n}${vs.RESOURCE_DELIM}${t}`:n}static generateLibraryState(e,t){if(!e)throw kc(hc);const r={id:e.createNewGuid()};t&&(r.meta=t);const n=JSON.stringify(r);return e.base64Encode(n)}static parseRequestState(e,t){if(!e)throw kc(hc);if(!t)throw kc(za);try{const r=t.split(vs.RESOURCE_DELIM),n=r[0],o=r.length>1?r.slice(1).join(vs.RESOURCE_DELIM):vs.EMPTY_STRING,i=e.base64Decode(n),s=JSON.parse(i);return{userRequestState:o||vs.EMPTY_STRING,libraryState:s}}catch(e){throw kc(za)}}}const Hh="sw";class Gh{constructor(e,t){this.cryptoUtils=e,this.performanceClient=t}async generateCnf(e,t){this.performanceClient?.addQueueMeasurement(uh,e.correlationId);const r=await Ch(this.generateKid.bind(this),uh,t,this.performanceClient,e.correlationId)(e),n=this.cryptoUtils.base64UrlEncode(JSON.stringify(r));return{kid:r.kid,reqCnfString:n}}async generateKid(e){this.performanceClient?.addQueueMeasurement(lh,e.correlationId);return{kid:await this.cryptoUtils.getPublicKeyThumbprint(e),xms_ksl:Hh}}async signPopToken(e,t,r){return this.signPayload(e,t,r)}async signPayload(e,t,r,n){const{resourceRequestMethod:o,resourceRequestUri:i,shrClaims:s,shrNonce:a,shrOptions:c}=r,u=i?new zu(i):void 0,l=u?.getUrlComponents();return this.cryptoUtils.signJwt({at:e,ts:Uc(),m:o?.toUpperCase(),u:l?.HostNameAndPort,nonce:a||this.cryptoUtils.createNewGuid(),p:l?.AbsolutePath,q:l?.QueryString?[[],l.QueryString]:void 0,client_claims:s||void 0,...n},t,c,r.correlationId)}}class zh{constructor(e,t){this.cache=e,this.hasChanged=t}get cacheHasChanged(){return this.hasChanged}get tokenCache(){return this.cache}}class Kh{constructor(e,t,r,n,o,i,s){this.clientId=e,this.cacheStorage=t,this.cryptoObj=r,this.logger=n,this.serializableCache=o,this.persistencePlugin=i,this.performanceClient=s}validateTokenResponse(e,t){if(e.error||e.error_description||e.suberror){const r=`Error(s): ${e.error_codes||vs.NOT_AVAILABLE} - Timestamp: ${e.timestamp||vs.NOT_AVAILABLE} - Description: ${e.error_description||vs.NOT_AVAILABLE} - Correlation ID: ${e.correlation_id||vs.NOT_AVAILABLE} - Trace ID: ${e.trace_id||vs.NOT_AVAILABLE}`,n=e.error_codes?.length?e.error_codes[0]:void 0,o=new Oh(e.error,r,e.suberror,n,e.status);if(t&&e.status&&e.status>=Ts&&e.status<=Ss)return void this.logger.warning(`executeTokenRequest:validateTokenResponse - AAD is currently unavailable and the access token is unable to be refreshed.\n${o}`);if(t&&e.status&&e.status>=Is&&e.status<=Cs)return void this.logger.warning(`executeTokenRequest:validateTokenResponse - AAD is currently available but is unable to refresh the access token.\n${o}`);if(function(e,t,r){const n=!!e&&$h.indexOf(e)>-1,o=!!r&&Uh.indexOf(r)>-1,i=!!t&&$h.some(e=>t.indexOf(e)>-1);return n||i||o}(e.error,e.error_description,e.suberror))throw new jh(e.error,e.error_description,e.suberror,e.timestamp||vs.EMPTY_STRING,e.trace_id||vs.EMPTY_STRING,e.correlation_id||vs.EMPTY_STRING,e.claims||vs.EMPTY_STRING,n);throw o}}async handleServerTokenResponse(e,t,r,n,o,i,s,a,c){let u,l;if(this.performanceClient?.addQueueMeasurement(hh,e.correlation_id),e.id_token){if(u=Mc(e.id_token||vs.EMPTY_STRING,this.cryptoObj.base64Decode),o&&o.nonce&&u.nonce!==o.nonce)throw kc(Ya);if(n.maxAge||0===n.maxAge){const e=u.auth_time;if(!e)throw kc(Wa);$c(e,n.maxAge)}}this.homeAccountIdentifier=qu.generateHomeAccountId(e.client_info||vs.EMPTY_STRING,t.authorityType,this.logger,this.cryptoObj,u),o&&o.state&&(l=qh.parseRequestState(this.cryptoObj,o.state)),e.key_id=e.key_id||n.sshKid||void 0;const h=this.generateCacheRecord(e,t,r,n,u,i,o);let d;try{if(this.persistencePlugin&&this.serializableCache&&(this.logger.verbose("Persistence enabled, calling beforeCacheAccess"),d=new zh(this.serializableCache,!0),await this.persistencePlugin.beforeCacheAccess(d)),s&&!a&&h.account){const e=h.account.generateAccountKey();if(!this.cacheStorage.getAccount(e))return this.logger.warning("Account used to refresh tokens not in persistence, refreshed tokens will not be stored in the cache"),await Kh.generateAuthenticationResult(this.cryptoObj,t,h,!1,n,u,l,void 0,c)}await this.cacheStorage.saveCacheRecord(h,n.correlationId,n.storeInCache)}finally{this.persistencePlugin&&this.serializableCache&&d&&(this.logger.verbose("Persistence enabled, calling afterCacheAccess"),await this.persistencePlugin.afterCacheAccess(d))}return Kh.generateAuthenticationResult(this.cryptoObj,t,h,!1,n,u,l,e,c)}generateCacheRecord(e,t,r,n,o,i,s){const a=t.getPreferredCache();if(!a)throw kc(uc);const c=Fu(o);let u,l;var h,d,f,p,m;e.id_token&&o&&(h=this.homeAccountIdentifier,d=a,f=e.id_token,p=this.clientId,m=c||"",u={credentialType:ea.ID_TOKEN,homeAccountId:h,environment:d,clientId:p,secret:f,realm:m},l=function(e,t,r,n,o,i,s,a,c,u,l){l?.verbose("setCachedAccount called");const h=e.getAccountKeys().find(e=>e.startsWith(r));let d=null;h&&(d=e.getAccount(h));const f=d||qu.createAccount({homeAccountId:r,idTokenClaims:o,clientInfo:i,environment:s,cloudGraphHostName:c?.cloud_graph_host_name,msGraphHost:c?.msgraph_host,nativeAccountId:u},t,n),p=f.tenantProfiles||[],m=a||f.realm;if(m&&!p.find(e=>e.tenantId===m)){const e=Lu(r,f.localAccountId,m,o);p.push(e)}return f.tenantProfiles=p,f}(this.cacheStorage,t,this.homeAccountIdentifier,this.cryptoObj.base64Decode,o,e.client_info,a,c,s,void 0,this.logger));let g=null;if(e.access_token){const o=e.scope?ku.fromString(e.scope):new ku(n.scopes||[]),s=("string"==typeof e.expires_in?parseInt(e.expires_in,10):e.expires_in)||0,u=("string"==typeof e.ext_expires_in?parseInt(e.ext_expires_in,10):e.ext_expires_in)||0,l=("string"==typeof e.refresh_in?parseInt(e.refresh_in,10):e.refresh_in)||void 0,h=r+s,d=h+u,f=l&&l>0?r+l:void 0;g=function(e,t,r,n,o,i,s,a,c,u,l,h,d,f,p){const m={homeAccountId:e,credentialType:ea.ACCESS_TOKEN,secret:r,cachedAt:Uc().toString(),expiresOn:s.toString(),extendedExpiresOn:a.toString(),environment:t,clientId:n,realm:o,target:i,tokenType:l||la.BEARER};if(h&&(m.userAssertionHash=h),u&&(m.refreshOn=u.toString()),f&&(m.requestedClaims=f,m.requestedClaimsHash=p),m.tokenType?.toLowerCase()!==la.BEARER.toLowerCase())switch(m.credentialType=ea.ACCESS_TOKEN_WITH_AUTH_SCHEME,m.tokenType){case la.POP:const e=Mc(r,c);if(!e?.cnf?.kid)throw kc(yc);m.keyId=e.cnf.kid;break;case la.SSH:m.keyId=d}return m}(this.homeAccountIdentifier,a,e.access_token,this.clientId,c||t.tenant||"",o.printScopes(),h,d,this.cryptoObj.base64Decode,f,e.token_type,i,e.key_id,n.claims,n.requestedClaimsHash)}let y=null;if(e.refresh_token){let t;if(e.refresh_token_expires_in){t=r+("string"==typeof e.refresh_token_expires_in?parseInt(e.refresh_token_expires_in,10):e.refresh_token_expires_in)}y=function(e,t,r,n,o,i,s){const a={credentialType:ea.REFRESH_TOKEN,homeAccountId:e,environment:t,clientId:n,secret:r};return i&&(a.userAssertionHash=i),o&&(a.familyId=o),s&&(a.expiresOn=s.toString()),a}(this.homeAccountIdentifier,a,e.refresh_token,this.clientId,e.foci,i,t)}let v=null;return e.foci&&(v={clientId:this.clientId,environment:a,familyId:e.foci}),{account:l,idToken:u,accessToken:g,refreshToken:y,appMetadata:v}}static async generateAuthenticationResult(e,t,r,n,o,i,s,a,c){let u,l,h=vs.EMPTY_STRING,d=[],f=null,p=vs.EMPTY_STRING;if(r.accessToken){if(r.accessToken.tokenType!==la.POP||o.popKid)h=r.accessToken.secret;else{const t=new Gh(e),{secret:n,keyId:i}=r.accessToken;if(!i)throw kc(wc);h=await t.signPopToken(n,i,o)}d=ku.fromString(r.accessToken.target).asArray(),f=Fc(r.accessToken.expiresOn),u=Fc(r.accessToken.extendedExpiresOn),r.accessToken.refreshOn&&(l=Fc(r.accessToken.refreshOn))}r.appMetadata&&(p=r.appMetadata.familyId===ra?ra:"");const m=i?.oid||i?.sub||"",g=i?.tid||"";a?.spa_accountid&&r.account&&(r.account.nativeAccountId=a?.spa_accountid);const y=r.account?Du(r.account.getAccountInfo(),void 0,i,r.idToken?.secret):null;return{authority:t.canonicalAuthority,uniqueId:m,tenantId:g,scopes:d,account:y,idToken:r?.idToken?.secret||"",idTokenClaims:i||{},accessToken:h,fromCache:n,expiresOn:f,extExpiresOn:u,refreshOn:l,correlationId:o.correlationId,requestId:c||vs.EMPTY_STRING,familyId:p,tokenType:r.accessToken?.tokenType||vs.EMPTY_STRING,state:s?s.userRequestState:vs.EMPTY_STRING,cloudGraphHostName:r.account?.cloudGraphHostName||vs.EMPTY_STRING,msGraphHost:r.account?.msGraphHost||vs.EMPTY_STRING,code:a?.spa_code,fromNativeBroker:!1}}}class Vh{static validateRedirectUri(e){if(!e)throw Au(nu)}static validatePrompt(e){const t=[];for(const e in js)t.push(js[e]);if(t.indexOf(e)<0)throw Au(uu)}static validateClaims(e){try{JSON.parse(e)}catch(e){throw Au(lu)}}static validateCodeChallengeParams(e,t){if(!e||!t)throw Au(pu);this.validateCodeChallengeMethod(t)}static validateCodeChallengeMethod(e){if([Bs.PLAIN,Bs.S256].indexOf(e)<0)throw Au(fu)}}async function Yh(e,t,r){if("string"==typeof e)return e;return e({clientId:t,tokenEndpoint:r})}class Wh extends Nh{constructor(e,t){super(e,t),this.includeRedirectUri=!0,this.oidcDefaultScopes=this.config.authOptions.authority.options.OIDCOptions?.defaultScopes}async acquireToken(e,t){if(this.performanceClient?.addQueueMeasurement(sh,e.correlationId),!e.code)throw kc(ec);const r=Uc(),n=await Ch(this.executeTokenRequest.bind(this),ah,this.logger,this.performanceClient,e.correlationId)(this.authority,e),o=n.headers?.[Ls],i=new Kh(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.config.serializableCache,this.config.persistencePlugin,this.performanceClient);return i.validateTokenResponse(n.body),Ch(i.handleServerTokenResponse.bind(i),hh,this.logger,this.performanceClient,e.correlationId)(n.body,this.authority,r,e,t,void 0,void 0,void 0,o)}getLogoutUri(e){if(!e)throw Au(du);const t=this.createLogoutUrlQueryString(e);return zu.appendQueryString(this.authority.endSessionEndpoint,t)}async executeTokenRequest(e,t){this.performanceClient?.addQueueMeasurement(ah,t.correlationId);const r=this.createTokenQueryParameters(t),n=zu.appendQueryString(e.tokenEndpoint,r),o=await Ch(this.createTokenRequestBody.bind(this),ch,this.logger,this.performanceClient,t.correlationId)(t);let i;if(t.clientInfo)try{const e=Ru(t.clientInfo,this.cryptoUtils.base64Decode);i={credential:`${e.uid}${Xs}${e.utid}`,type:dl}}catch(e){this.logger.verbose("Could not parse client info for CCS Header: "+e)}const s=this.createTokenRequestHeaders(i||t.ccsCredential),a=kh(this.config.authOptions.clientId,t);return Ch(this.executePostToTokenEndpoint.bind(this),Jl,this.logger,this.performanceClient,t.correlationId)(n,o,s,a,t.correlationId,Jl)}async createTokenRequestBody(e){this.performanceClient?.addQueueMeasurement(ch,e.correlationId);const t=new Map;if(Sl(t,e.embeddedClientId||e.tokenBodyParameters?.[pl]||this.config.authOptions.clientId),this.includeRedirectUri?Al(t,e.redirectUri):Vh.validateRedirectUri(e.redirectUri),Tl(t,e.scopes,!0,this.oidcDefaultScopes),function(e,t){e.set("code",t)}(t,e.code),Dl(t,this.config.libraryInfo),xl(t,this.config.telemetry.application),Vl(t),this.serverTelemetryManager&&!hl(this.config)&&Kl(t,this.serverTelemetryManager),e.codeVerifier&&function(e,t){e.set("code_verifier",t)}(t,e.codeVerifier),this.config.clientCredentials.clientSecret&&$l(t,this.config.clientCredentials.clientSecret),this.config.clientCredentials.clientAssertion){const r=this.config.clientCredentials.clientAssertion;Ul(t,await Yh(r.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),Fl(t,r.assertionType)}if(jl(t,zs),Bl(t),e.authenticationScheme===la.POP){const r=new Gh(this.cryptoUtils,this.performanceClient);let n;if(e.popKid)n=this.cryptoUtils.encodeKid(e.popKid);else{n=(await Ch(r.generateCnf.bind(r),uh,this.logger,this.performanceClient,e.correlationId)(e,this.logger)).reqCnfString}Gl(t,n)}else if(e.authenticationScheme===la.SSH){if(!e.sshJwk)throw Au(vu);zl(t,e.sshJwk)}let r;if((!Ou.isEmptyObj(e.claims)||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&Nl(t,e.claims,this.config.authOptions.clientCapabilities),e.clientInfo)try{const t=Ru(e.clientInfo,this.cryptoUtils.base64Decode);r={credential:`${t.uid}${Xs}${t.utid}`,type:dl}}catch(e){this.logger.verbose("Could not parse client info for CCS Header: "+e)}else r=e.ccsCredential;if(this.config.systemOptions.preventCorsPreflight&&r)switch(r.type){case dl:try{Rl(t,Pu(r.credential))}catch(e){this.logger.verbose("Could not parse home account ID for CCS Header: "+e)}break;case fl:kl(t,r.credential)}return e.embeddedClientId&&Yl(t,this.config.authOptions.clientId,this.config.authOptions.redirectUri),e.tokenBodyParameters&&Hl(t,e.tokenBodyParameters),!e.enableSpaAuthorizationCode||e.tokenBodyParameters&&e.tokenBodyParameters[vl]||Hl(t,{[vl]:"1"}),Cl(t,e.correlationId,this.performanceClient),Gu(t)}createLogoutUrlQueryString(e){const t=new Map;return e.postLogoutRedirectUri&&function(e,t){e.set("post_logout_redirect_uri",t)}(t,e.postLogoutRedirectUri),e.correlationId&&Ll(t,e.correlationId),e.idTokenHint&&function(e,t){e.set("id_token_hint",t)}(t,e.idTokenHint),e.state&&Ml(t,e.state),e.logoutHint&&function(e,t){e.set("logout_hint",t)}(t,e.logoutHint),e.extraQueryParameters&&Hl(t,e.extraQueryParameters),this.config.authOptions.instanceAware&&ql(t),Gu(t,this.config.authOptions.encodeExtraQueryParams,e.extraQueryParameters)}}class Qh extends Nh{constructor(e,t){super(e,t)}async acquireToken(e){this.performanceClient?.addQueueMeasurement(Xl,e.correlationId);const t=Uc(),r=await Ch(this.executeTokenRequest.bind(this),Zl,this.logger,this.performanceClient,e.correlationId)(e,this.authority),n=r.headers?.[Ls],o=new Kh(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.config.serializableCache,this.config.persistencePlugin);return o.validateTokenResponse(r.body),Ch(o.handleServerTokenResponse.bind(o),hh,this.logger,this.performanceClient,e.correlationId)(r.body,this.authority,t,e,void 0,void 0,!0,e.forceCache,n)}async acquireTokenByRefreshToken(e){if(!e)throw Au(hu);if(this.performanceClient?.addQueueMeasurement(th,e.correlationId),!e.account)throw kc(ac);if(this.cacheManager.isAppMetadataFOCI(e.account.environment))try{return await Ch(this.acquireTokenWithCachedRefreshToken.bind(this),eh,this.logger,this.performanceClient,e.correlationId)(e,!0)}catch(t){const r=t instanceof jh&&t.errorCode===Lh,n=t instanceof Oh&&t.errorCode===ma&&t.subError===ga;if(r||n)return Ch(this.acquireTokenWithCachedRefreshToken.bind(this),eh,this.logger,this.performanceClient,e.correlationId)(e,!1);throw t}return Ch(this.acquireTokenWithCachedRefreshToken.bind(this),eh,this.logger,this.performanceClient,e.correlationId)(e,!1)}async acquireTokenWithCachedRefreshToken(e,t){this.performanceClient?.addQueueMeasurement(eh,e.correlationId);const r=(n=this.cacheManager.getRefreshToken.bind(this.cacheManager),o=Ih,i=this.logger,s=this.performanceClient,a=e.correlationId,(...e)=>{i.trace(`Executing function ${o}`);const t=s?.startMeasurement(o,a);if(a){const e=o+"CallCount";s?.incrementFields({[e]:1},a)}try{const r=n(...e);return t?.end({success:!0}),i.trace(`Returning result from ${o}`),r}catch(e){i.trace(`Error occurred in ${o}`);try{i.trace(JSON.stringify(e))}catch(e){i.trace("Unable to print error message.")}throw t?.end({success:!1},e),e}})(e.account,t,void 0,this.performanceClient,e.correlationId);var n,o,i,s,a;if(!r)throw Bh(Lh);if(r.expiresOn&&jc(r.expiresOn,e.refreshTokenExpirationOffsetSeconds||300))throw this.performanceClient?.addFields({rtExpiresOnMs:Number(r.expiresOn)},e.correlationId),Bh(xh);const c={...e,refreshToken:r.secret,authenticationScheme:e.authenticationScheme||la.BEARER,ccsCredential:{credential:e.account.homeAccountId,type:dl}};try{return await Ch(this.acquireToken.bind(this),Xl,this.logger,this.performanceClient,e.correlationId)(c)}catch(t){if(t instanceof jh&&(this.performanceClient?.addFields({rtExpiresOnMs:Number(r.expiresOn)},e.correlationId),t.subError===Mh)){this.logger.verbose("acquireTokenWithRefreshToken: bad refresh token, removing from cache");const e=qc(r);this.cacheManager.removeRefreshToken(e)}throw t}}async executeTokenRequest(e,t){this.performanceClient?.addQueueMeasurement(Zl,e.correlationId);const r=this.createTokenQueryParameters(e),n=zu.appendQueryString(t.tokenEndpoint,r),o=await Ch(this.createTokenRequestBody.bind(this),rh,this.logger,this.performanceClient,e.correlationId)(e),i=this.createTokenRequestHeaders(e.ccsCredential),s=kh(this.config.authOptions.clientId,e);return Ch(this.executePostToTokenEndpoint.bind(this),Ql,this.logger,this.performanceClient,e.correlationId)(n,o,i,s,e.correlationId,Ql)}async createTokenRequestBody(e){this.performanceClient?.addQueueMeasurement(rh,e.correlationId);const t=new Map;if(Sl(t,e.embeddedClientId||e.tokenBodyParameters?.[pl]||this.config.authOptions.clientId),e.redirectUri&&Al(t,e.redirectUri),Tl(t,e.scopes,!0,this.config.authOptions.authority.options.OIDCOptions?.defaultScopes),jl(t,Vs),Bl(t),Dl(t,this.config.libraryInfo),xl(t,this.config.telemetry.application),Vl(t),this.serverTelemetryManager&&!hl(this.config)&&Kl(t,this.serverTelemetryManager),function(e,t){e.set("refresh_token",t)}(t,e.refreshToken),this.config.clientCredentials.clientSecret&&$l(t,this.config.clientCredentials.clientSecret),this.config.clientCredentials.clientAssertion){const r=this.config.clientCredentials.clientAssertion;Ul(t,await Yh(r.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),Fl(t,r.assertionType)}if(e.authenticationScheme===la.POP){const r=new Gh(this.cryptoUtils,this.performanceClient);let n;if(e.popKid)n=this.cryptoUtils.encodeKid(e.popKid);else{n=(await Ch(r.generateCnf.bind(r),uh,this.logger,this.performanceClient,e.correlationId)(e,this.logger)).reqCnfString}Gl(t,n)}else if(e.authenticationScheme===la.SSH){if(!e.sshJwk)throw Au(vu);zl(t,e.sshJwk)}if((!Ou.isEmptyObj(e.claims)||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&Nl(t,e.claims,this.config.authOptions.clientCapabilities),this.config.systemOptions.preventCorsPreflight&&e.ccsCredential)switch(e.ccsCredential.type){case dl:try{Rl(t,Pu(e.ccsCredential.credential))}catch(e){this.logger.verbose("Could not parse home account ID for CCS Header: "+e)}break;case fl:kl(t,e.ccsCredential.credential)}return e.embeddedClientId&&Yl(t,this.config.authOptions.clientId,this.config.authOptions.redirectUri),e.tokenBodyParameters&&Hl(t,e.tokenBodyParameters),Cl(t,e.correlationId,this.performanceClient),Gu(t)}}class Jh extends Nh{constructor(e,t){super(e,t)}async acquireCachedToken(e){this.performanceClient?.addQueueMeasurement(nh,e.correlationId);let t=Aa;if(e.forceRefresh||!this.config.cacheOptions.claimsBasedCachingEnabled&&!Ou.isEmptyObj(e.claims))throw this.setCacheOutcome(Oa,e.correlationId),kc(mc);if(!e.account)throw kc(ac);const r=e.account.tenantId||function(e){const t=new zu(e).getUrlComponents(),r=t.PathSegments.slice(-1)[0]?.toLowerCase();switch(r){case xs:case Ms:case $s:return;default:return r}}(e.authority),n=this.cacheManager.getTokenKeys(),o=this.cacheManager.getAccessToken(e.account,e,n,r,this.performanceClient,e.correlationId);if(!o)throw this.setCacheOutcome(ka,e.correlationId),kc(mc);if(i=o.cachedAt,Number(i)>Uc()||jc(o.expiresOn,this.config.systemOptions.tokenRenewalOffsetSeconds))throw this.setCacheOutcome(Ra,e.correlationId),kc(mc);var i;o.refreshOn&&jc(o.refreshOn,0)&&(t=Pa);const s=e.authority||this.authority.getPreferredCache(),a={account:this.cacheManager.readAccountFromCache(e.account),accessToken:o,idToken:this.cacheManager.getIdToken(e.account,n,r,this.performanceClient,e.correlationId),refreshToken:null,appMetadata:this.cacheManager.readAppMetadataFromCache(s)};return this.setCacheOutcome(t,e.correlationId),this.config.serverTelemetryManager&&this.config.serverTelemetryManager.incrementCacheHits(),[await Ch(this.generateResultFromCacheRecord.bind(this),oh,this.logger,this.performanceClient,e.correlationId)(a,e),t]}setCacheOutcome(e,t){this.serverTelemetryManager?.setCacheOutcome(e),this.performanceClient?.addFields({cacheOutcome:e},t),e!==Aa&&this.logger.info(`Token refresh is required due to cache outcome: ${e}`)}async generateResultFromCacheRecord(e,t){let r;if(this.performanceClient?.addQueueMeasurement(oh,t.correlationId),e.idToken&&(r=Mc(e.idToken.secret,this.config.cryptoInterface.base64Decode)),t.maxAge||0===t.maxAge){const e=r?.auth_time;if(!e)throw kc(Wa);$c(e,t.maxAge)}return Kh.generateAuthenticationResult(this.cryptoUtils,this.authority,e,!0,t,r)}}function Zh(e,t,r,n){const o=t.correlationId,i=new Map;Sl(i,t.embeddedClientId||t.extraQueryParameters?.[pl]||e.clientId);if(Tl(i,[...t.scopes||[],...t.extraScopesToConsent||[]],!0,e.authority.options.OIDCOptions?.defaultScopes),Al(i,t.redirectUri),Ll(i,o),function(e,t){e.set("response_mode",t||Gs)}(i,t.responseMode),Bl(i),t.prompt&&function(e,t){e.set("prompt",t)}(i,t.prompt),t.domainHint&&function(e,t){e.set("domain_hint",t)}(i,t.domainHint),t.prompt!==js.SELECT_ACCOUNT)if(t.sid&&t.prompt===js.NONE)r.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from request"),Pl(i,t.sid);else if(t.account){const e=(s=t.account,s.idTokenClaims?.sid||null);let n=function(e){return e.idTokenClaims?.login_hint||null}(t.account);if(n&&t.domainHint&&(r.warning('AuthorizationCodeClient.createAuthCodeUrlQueryString: "domainHint" param is set, skipping opaque "login_hint" claim. Please consider not passing domainHint'),n=null),n){r.verbose("createAuthCodeUrlQueryString: login_hint claim present on account"),Ol(i,n);try{Rl(i,Pu(t.account.homeAccountId))}catch(e){r.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header")}}else if(e&&t.prompt===js.NONE){r.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from account"),Pl(i,e);try{Rl(i,Pu(t.account.homeAccountId))}catch(e){r.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header")}}else if(t.loginHint)r.verbose("createAuthCodeUrlQueryString: Adding login_hint from request"),Ol(i,t.loginHint),kl(i,t.loginHint);else if(t.account.username){r.verbose("createAuthCodeUrlQueryString: Adding login_hint from account"),Ol(i,t.account.username);try{Rl(i,Pu(t.account.homeAccountId))}catch(e){r.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header")}}}else t.loginHint&&(r.verbose("createAuthCodeUrlQueryString: No account, adding login_hint from request"),Ol(i,t.loginHint),kl(i,t.loginHint));else r.verbose("createAuthCodeUrlQueryString: Prompt is select_account, ignoring account hints");var s;return t.nonce&&function(e,t){e.set("nonce",t)}(i,t.nonce),t.state&&Ml(i,t.state),(t.claims||e.clientCapabilities&&e.clientCapabilities.length>0)&&Nl(i,t.claims,e.clientCapabilities),t.embeddedClientId&&Yl(i,e.clientId,e.redirectUri),!e.instanceAware||t.extraQueryParameters&&Object.keys(t.extraQueryParameters).includes(Il)||ql(i),i}function Xh(e){const{skus:t,libraryName:r,libraryVersion:n,extensionName:o,extensionVersion:i}=e,s=new Map([[0,[r,n]],[2,[o,i]]]);let a=[];if(t?.length){if(a=t.split(","),a.length<4)return t}else a=Array.from({length:4},()=>"|");return s.forEach((e,t)=>{2===e.length&&e[0]?.length&&e[1]?.length&&function(e){const{skuArr:t,index:r,skuName:n,skuVersion:o}=e;if(r>=t.length)return;t[r]=[n,o].join("|")}({skuArr:a,index:t,skuName:e[0],skuVersion:e[1]})}),a.join(",")}class ed{constructor(e,t){this.cacheOutcome=Aa,this.cacheManager=t,this.apiId=e.apiId,this.correlationId=e.correlationId,this.wrapperSKU=e.wrapperSKU||vs.EMPTY_STRING,this.wrapperVer=e.wrapperVer||vs.EMPTY_STRING,this.telemetryCacheKey=ua.CACHE_KEY+Zs+e.clientId}generateCurrentRequestHeaderValue(){const e=`${this.apiId}${ua.VALUE_SEPARATOR}${this.cacheOutcome}`,t=[this.wrapperSKU,this.wrapperVer],r=this.getNativeBrokerErrorCode();r?.length&&t.push(`broker_error=${r}`);const n=t.join(ua.VALUE_SEPARATOR),o=[e,this.getRegionDiscoveryFields()].join(ua.VALUE_SEPARATOR);return[ua.SCHEMA_VERSION,o,n].join(ua.CATEGORY_SEPARATOR)}generateLastRequestHeaderValue(){const e=this.getLastRequests(),t=ed.maxErrorsToSend(e),r=e.failedRequests.slice(0,2*t).join(ua.VALUE_SEPARATOR),n=e.errors.slice(0,t).join(ua.VALUE_SEPARATOR),o=e.errors.length,i=[o,t<o?ua.OVERFLOW_TRUE:ua.OVERFLOW_FALSE].join(ua.VALUE_SEPARATOR);return[ua.SCHEMA_VERSION,e.cacheHits,r,n,i].join(ua.CATEGORY_SEPARATOR)}cacheFailedRequest(e){const t=this.getLastRequests();t.errors.length>=ua.MAX_CACHED_ERRORS&&(t.failedRequests.shift(),t.failedRequests.shift(),t.errors.shift()),t.failedRequests.push(this.apiId,this.correlationId),e instanceof Error&&e&&e.toString()?e instanceof xa?e.subError?t.errors.push(e.subError):e.errorCode?t.errors.push(e.errorCode):t.errors.push(e.toString()):t.errors.push(e.toString()):t.errors.push(ua.UNKNOWN_ERROR),this.cacheManager.setServerTelemetry(this.telemetryCacheKey,t)}incrementCacheHits(){const e=this.getLastRequests();return e.cacheHits+=1,this.cacheManager.setServerTelemetry(this.telemetryCacheKey,e),e.cacheHits}getLastRequests(){return this.cacheManager.getServerTelemetry(this.telemetryCacheKey)||{failedRequests:[],errors:[],cacheHits:0}}clearTelemetryCache(){const e=this.getLastRequests(),t=ed.maxErrorsToSend(e);if(t===e.errors.length)this.cacheManager.removeItem(this.telemetryCacheKey);else{const r={failedRequests:e.failedRequests.slice(2*t),errors:e.errors.slice(t),cacheHits:0};this.cacheManager.setServerTelemetry(this.telemetryCacheKey,r)}}static maxErrorsToSend(e){let t,r=0,n=0;const o=e.errors.length;for(t=0;t<o;t++){const o=e.failedRequests[2*t]||vs.EMPTY_STRING,i=e.failedRequests[2*t+1]||vs.EMPTY_STRING,s=e.errors[t]||vs.EMPTY_STRING;if(n+=o.toString().length+i.toString().length+s.length+3,!(n<ua.MAX_LAST_HEADER_BYTES))break;r+=1}return r}getRegionDiscoveryFields(){const e=[];return e.push(this.regionUsed||vs.EMPTY_STRING),e.push(this.regionSource||vs.EMPTY_STRING),e.push(this.regionOutcome||vs.EMPTY_STRING),e.join(",")}updateRegionDiscoveryMetadata(e){this.regionUsed=e.region_used,this.regionSource=e.region_source,this.regionOutcome=e.region_outcome}setCacheOutcome(e){this.cacheOutcome=e}setNativeBrokerErrorCode(e){const t=this.getLastRequests();t.nativeBrokerErrorCode=e,this.cacheManager.setServerTelemetry(this.telemetryCacheKey,t)}getNativeBrokerErrorCode(){return this.getLastRequests().nativeBrokerErrorCode}clearNativeBrokerErrorCode(){const e=this.getLastRequests();delete e.nativeBrokerErrorCode,this.cacheManager.setServerTelemetry(this.telemetryCacheKey,e)}static makeExtraSkuString(e){return Xh(e)}}class td{static deserializeJSONBlob(e){return e?JSON.parse(e):{}}static deserializeAccounts(e){const t={};return e&&Object.keys(e).map(function(r){const n=e[r],o={homeAccountId:n.home_account_id,environment:n.environment,realm:n.realm,localAccountId:n.local_account_id,username:n.username,authorityType:n.authority_type,name:n.name,clientInfo:n.client_info,lastModificationTime:n.last_modification_time,lastModificationApp:n.last_modification_app,tenantProfiles:n.tenantProfiles?.map(e=>JSON.parse(e))},i=new qu;tl.toObject(i,o),t[r]=i}),t}static deserializeIdTokens(e){const t={};return e&&Object.keys(e).map(function(r){const n=e[r],o={homeAccountId:n.home_account_id,environment:n.environment,credentialType:n.credential_type,clientId:n.client_id,secret:n.secret,realm:n.realm};t[r]=o}),t}static deserializeAccessTokens(e){const t={};return e&&Object.keys(e).map(function(r){const n=e[r],o={homeAccountId:n.home_account_id,environment:n.environment,credentialType:n.credential_type,clientId:n.client_id,secret:n.secret,realm:n.realm,target:n.target,cachedAt:n.cached_at,expiresOn:n.expires_on,extendedExpiresOn:n.extended_expires_on,refreshOn:n.refresh_on,keyId:n.key_id,tokenType:n.token_type,requestedClaims:n.requestedClaims,requestedClaimsHash:n.requestedClaimsHash,userAssertionHash:n.userAssertionHash};t[r]=o}),t}static deserializeRefreshTokens(e){const t={};return e&&Object.keys(e).map(function(r){const n=e[r],o={homeAccountId:n.home_account_id,environment:n.environment,credentialType:n.credential_type,clientId:n.client_id,secret:n.secret,familyId:n.family_id,target:n.target,realm:n.realm};t[r]=o}),t}static deserializeAppMetadata(e){const t={};return e&&Object.keys(e).map(function(r){const n=e[r];t[r]={clientId:n.client_id,environment:n.environment,familyId:n.family_id}}),t}static deserializeAllCache(e){return{accounts:e.Account?this.deserializeAccounts(e.Account):{},idTokens:e.IdToken?this.deserializeIdTokens(e.IdToken):{},accessTokens:e.AccessToken?this.deserializeAccessTokens(e.AccessToken):{},refreshTokens:e.RefreshToken?this.deserializeRefreshTokens(e.RefreshToken):{},appMetadata:e.AppMetadata?this.deserializeAppMetadata(e.AppMetadata):{}}}}const rd="get",nd="post",od={SUCCESS_RANGE_START:Es,SUCCESS_RANGE_END:bs,SERVER_ERROR:_s},id="sha256",sd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",ad="msal.js.node",cd="urn:ietf:params:oauth:client-assertion-type:jwt-bearer",ud="authorization_pending",ld="http://",hd="localhost",dd=62,fd=371,pd=671,md=871,gd=872,yd="RS256",vd="PS256",Ed="x5t#S256",bd="x5t",wd="x5c",Id="aud",Cd="exp",_d="iss",Td="sub",Sd="nbf",Ad="jti",Od=100,kd=5e3;class Rd{static getNetworkResponse(e,t,r){return{headers:e,body:t,status:r}}static urlToHttpOptions(e){const t={protocol:e.protocol,hostname:e.hostname&&e.hostname.startsWith("[")?e.hostname.slice(1,-1):e.hostname,hash:e.hash,search:e.search,pathname:e.pathname,path:`${e.pathname||""}${e.search||""}`,href:e.href};return""!==e.port&&(t.port=Number(e.port)),(e.username||e.password)&&(t.auth=`${decodeURIComponent(e.username)}:${decodeURIComponent(e.password)}`),t}}let Pd=class{constructor(e,t){this.proxyUrl=e||"",this.customAgentOptions=t||{}}async sendGetRequestAsync(e,t,r){return this.proxyUrl?Nd(e,this.proxyUrl,rd,t,this.customAgentOptions,r):Ld(e,rd,t,this.customAgentOptions,r)}async sendPostRequestAsync(e,t){return this.proxyUrl?Nd(e,this.proxyUrl,nd,t,this.customAgentOptions):Ld(e,nd,t,this.customAgentOptions)}};const Nd=(e,t,r,n,o,i)=>{const s=new URL(e),a=new URL(t),c=n?.headers||{},u={host:a.hostname,port:a.port,method:"CONNECT",path:s.hostname,headers:c};o&&Object.keys(o).length&&(u.agent=new U.Agent(o));let l="";if(r===nd){const e=n?.body||"";l=`Content-Type: application/x-www-form-urlencoded\r\nContent-Length: ${e.length}\r\n\r\n${e}`}else i&&(u.timeout=i);const h=`${r.toUpperCase()} ${s.href} HTTP/1.1\r\nHost: ${s.host}\r\nConnection: close\r\n`+l+"\r\n";return new Promise((e,t)=>{const r=U.request(u);i&&r.on("timeout",()=>{r.destroy(),t(new Error("Request time out"))}),r.end(),r.on("connect",(n,o)=>{const i=n?.statusCode||od.SERVER_ERROR;(i<od.SUCCESS_RANGE_START||i>od.SUCCESS_RANGE_END)&&(r.destroy(),o.destroy(),t(new Error(`Error connecting to proxy. Http status code: ${n.statusCode}. Http status message: ${n?.statusMessage||"Unknown"}`))),o.write(h);const s=[];o.on("data",e=>{s.push(e)}),o.on("end",()=>{const t=Buffer.concat([...s]).toString().split("\r\n"),n=parseInt(t[0].split(" ")[1]),o=t[0].split(" ").slice(2).join(" "),i=t[t.length-1],a=t.slice(1,t.length-2),c=new Map;a.forEach(e=>{const t=e.split(new RegExp(/:\s(.*)/s)),r=t[0];let n=t[1];try{const e=JSON.parse(n);e&&"object"==typeof e&&(n=e)}catch(e){}c.set(r,n)});const u=Object.fromEntries(c),l=Rd.getNetworkResponse(u,Dd(n,o,u,i),n);(n<Es||n>bs)&&l.body.error!==ud&&r.destroy(),e(l)}),o.on("error",e=>{r.destroy(),o.destroy(),t(new Error(e.toString()))})}),r.on("error",e=>{r.destroy(),t(new Error(e.toString()))})})},Ld=(e,t,r,n,o)=>{const i=t===nd,s=r?.body||"",a=new URL(e),c={method:t,headers:r?.headers||{},...Rd.urlToHttpOptions(a)};return n&&Object.keys(n).length&&(c.agent=new F.Agent(n)),i?c.headers={...c.headers,"Content-Length":s.length}:o&&(c.timeout=o),new Promise((e,t)=>{let r;r="http:"===c.protocol?U.request(c):F.request(c),i&&r.write(s),o&&r.on("timeout",()=>{r.destroy(),t(new Error("Request time out"))}),r.end(),r.on("response",t=>{const n=t.headers,o=t.statusCode,i=t.statusMessage,s=[];t.on("data",e=>{s.push(e)}),t.on("end",()=>{const t=Buffer.concat([...s]).toString(),a=n,c=Rd.getNetworkResponse(a,Dd(o,i,a,t),o);(o<Es||o>bs)&&c.body.error!==ud&&r.destroy(),e(c)})}),r.on("error",e=>{r.destroy(),t(new Error(e.toString()))})})},Dd=(e,t,r,n)=>{let o;try{o=JSON.parse(n)}catch(n){let i,s;e>=Is&&e<=Cs?(i="client_error",s="A client"):e>=Ts&&e<=Ss?(i="server_error",s="A server"):(i="unknown_error",s="An unknown"),o={error:i,error_description:`${s} error occured.\nHttp status code: ${e}\nHttp status message: ${t||"Unknown"}\nHeaders: ${JSON.stringify(r)}`}}return o},xd={code:"invalid_loopback_server_address_type",desc:"Loopback server address is not type string. This is unexpected."},Md={code:"unable_to_load_redirectUrl",desc:"Loopback server callback was invoked without a url. This is unexpected."},$d={code:"no_auth_code_in_response",desc:"No auth code found in the server response. Please check your network trace to determine what happened."},Ud={code:"no_loopback_server_exists",desc:"No loopback server exists yet."},Fd={code:"loopback_server_already_exists",desc:"Loopback server already exists. Cannot create another."},jd={code:"loopback_server_timeout",desc:"Timed out waiting for auth code listener to be registered."},Bd={code:"state_not_found",desc:"State not found. Please verify that the request originated from msal."},qd={code:"thumbprint_missing_from_client_certificate",desc:"Client certificate does not contain a SHA-1 or SHA-256 thumbprint."};class Hd extends xa{constructor(e,t){super(e,t),this.name="NodeAuthError"}static createInvalidLoopbackAddressTypeError(){return new Hd(xd.code,`${xd.desc}`)}static createUnableToLoadRedirectUrlError(){return new Hd(Md.code,`${Md.desc}`)}static createNoAuthCodeInResponseError(){return new Hd($d.code,`${$d.desc}`)}static createNoLoopbackServerExistsError(){return new Hd(Ud.code,`${Ud.desc}`)}static createLoopbackServerAlreadyExistsError(){return new Hd(Fd.code,`${Fd.desc}`)}static createLoopbackServerTimeoutError(){return new Hd(jd.code,`${jd.desc}`)}static createStateNotFoundError(){return new Hd(Bd.code,Bd.desc)}static createThumbprintMissingError(){return new Hd(qd.code,qd.desc)}}const Gd={clientId:vs.EMPTY_STRING,authority:vs.DEFAULT_AUTHORITY,clientSecret:vs.EMPTY_STRING,clientAssertion:vs.EMPTY_STRING,clientCertificate:{thumbprint:vs.EMPTY_STRING,thumbprintSha256:vs.EMPTY_STRING,privateKey:vs.EMPTY_STRING,x5c:vs.EMPTY_STRING},knownAuthorities:[],cloudDiscoveryMetadata:vs.EMPTY_STRING,authorityMetadata:vs.EMPTY_STRING,clientCapabilities:[],protocolMode:ju,azureCloudOptions:{azureCloudInstance:xc,tenant:vs.EMPTY_STRING},skipAuthorityMetadataCache:!1,encodeExtraQueryParams:!1},zd={claimsBasedCachingEnabled:!1},Kd={loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:Pc.Info},Vd={loggerOptions:Kd,networkClient:new Pd,proxyUrl:vs.EMPTY_STRING,customAgentOptions:{},disableInternalRetries:!1},Yd={application:{appName:vs.EMPTY_STRING,appVersion:vs.EMPTY_STRING}};var Wd,Qd=new Uint8Array(16);function Jd(){if(!Wd&&!(Wd="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Wd(Qd)}var Zd=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;for(var Xd=[],ef=0;ef<256;++ef)Xd.push((ef+256).toString(16).substr(1));function tf(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=(Xd[e[t+0]]+Xd[e[t+1]]+Xd[e[t+2]]+Xd[e[t+3]]+"-"+Xd[e[t+4]]+Xd[e[t+5]]+"-"+Xd[e[t+6]]+Xd[e[t+7]]+"-"+Xd[e[t+8]]+Xd[e[t+9]]+"-"+Xd[e[t+10]]+Xd[e[t+11]]+Xd[e[t+12]]+Xd[e[t+13]]+Xd[e[t+14]]+Xd[e[t+15]]).toLowerCase();if(!function(e){return"string"==typeof e&&Zd.test(e)}(r))throw TypeError("Stringified UUID is invalid");return r}function rf(e,t,r){var n=(e=e||{}).random||(e.rng||Jd)();return n[6]=15&n[6]|64,n[8]=63&n[8]|128,tf(n)}class nf{generateGuid(){return rf()}isGuid(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}}class of{static base64Encode(e,t){return Buffer.from(e,t).toString("base64")}static base64EncodeUrl(e,t){return of.base64Encode(e,t).replace(/=/g,vs.EMPTY_STRING).replace(/\+/g,"-").replace(/\//g,"_")}static base64Decode(e){return Buffer.from(e,"base64").toString("utf8")}static base64DecodeUrl(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4;)t+="=";return of.base64Decode(t)}}class sf{sha256(e){return D.createHash(id).update(e).digest()}}class af{constructor(){this.hashUtils=new sf}async generatePkceCodes(){const e=this.generateCodeVerifier();return{verifier:e,challenge:this.generateCodeChallengeFromVerifier(e)}}generateCodeVerifier(){const e=[],t=256-256%sd.length;for(;e.length<=32;){const r=D.randomBytes(1)[0];if(r>=t)continue;const n=r%sd.length;e.push(sd[n])}const r=e.join(vs.EMPTY_STRING);return of.base64EncodeUrl(r)}generateCodeChallengeFromVerifier(e){return of.base64EncodeUrl(this.hashUtils.sha256(e).toString("base64"),"base64")}}class cf{constructor(){this.pkceGenerator=new af,this.guidGenerator=new nf,this.hashUtils=new sf}base64UrlEncode(){throw new Error("Method not implemented.")}encodeKid(){throw new Error("Method not implemented.")}createNewGuid(){return this.guidGenerator.generateGuid()}base64Encode(e){return of.base64Encode(e)}base64Decode(e){return of.base64Decode(e)}generatePkceCodes(){return this.pkceGenerator.generatePkceCodes()}getPublicKeyThumbprint(){throw new Error("Method not implemented.")}removeTokenBindingKey(){throw new Error("Method not implemented.")}clearKeystore(){throw new Error("Method not implemented.")}signJwt(){throw new Error("Method not implemented.")}async hashString(e){return of.base64EncodeUrl(this.hashUtils.sha256(e).toString("base64"),"base64")}}class uf extends tl{constructor(e,t,r,n){super(t,r,e,n),this.cache={},this.changeEmitters=[],this.logger=e}registerChangeEmitter(e){this.changeEmitters.push(e)}emitChange(){this.changeEmitters.forEach(e=>e.call(null))}cacheToInMemoryCache(e){const t={accounts:{},idTokens:{},accessTokens:{},refreshTokens:{},appMetadata:{}};for(const r in e){const n=e[r];if("object"==typeof n)if(n instanceof qu)t.accounts[r]=n;else if(zc(n))t.idTokens[r]=n;else if(Gc(n))t.accessTokens[r]=n;else if(Kc(n))t.refreshTokens[r]=n;else{if(!Zc(r,n))continue;t.appMetadata[r]=n}}return t}inMemoryCacheToCache(e){let t=this.getCache();return t={...t,...e.accounts,...e.idTokens,...e.accessTokens,...e.refreshTokens,...e.appMetadata},t}getInMemoryCache(){this.logger.trace("Getting in-memory cache");return this.cacheToInMemoryCache(this.getCache())}setInMemoryCache(e){this.logger.trace("Setting in-memory cache");const t=this.inMemoryCacheToCache(e);this.setCache(t),this.emitChange()}getCache(){return this.logger.trace("Getting cache key-value store"),this.cache}setCache(e){this.logger.trace("Setting cache key value store"),this.cache=e,this.emitChange()}getItem(e){this.logger.tracePii(`Item key: ${e}`);return this.getCache()[e]}setItem(e,t){this.logger.tracePii(`Item key: ${e}`);const r=this.getCache();r[e]=t,this.setCache(r)}getAccountKeys(){const e=this.getInMemoryCache();return Object.keys(e.accounts)}getTokenKeys(){const e=this.getInMemoryCache();return{idToken:Object.keys(e.idTokens),accessToken:Object.keys(e.accessTokens),refreshToken:Object.keys(e.refreshTokens)}}getAccount(e){return this.getItem(e)?Object.assign(new qu,this.getItem(e)):null}async setAccount(e){const t=e.generateAccountKey();this.setItem(t,e)}getIdTokenCredential(e){const t=this.getItem(e);return zc(t)?t:null}async setIdTokenCredential(e){const t=qc(e);this.setItem(t,e)}getAccessTokenCredential(e){const t=this.getItem(e);return Gc(t)?t:null}async setAccessTokenCredential(e){const t=qc(e);this.setItem(t,e)}getRefreshTokenCredential(e){const t=this.getItem(e);return Kc(t)?t:null}async setRefreshTokenCredential(e){const t=qc(e);this.setItem(t,e)}getAppMetadata(e){const t=this.getItem(e);return Zc(e,t)?t:null}setAppMetadata(e){const t=function({environment:e,clientId:t}){return[ta,e,t].join(Zs).toLowerCase()}(e);this.setItem(t,e)}getServerTelemetry(e){const t=this.getItem(e);return t&&function(e,t){const r=0===e.indexOf(ua.CACHE_KEY);let n=!0;return t&&(n=t.hasOwnProperty("failedRequests")&&t.hasOwnProperty("errors")&&t.hasOwnProperty("cacheHits")),r&&n}(e,t)?t:null}setServerTelemetry(e,t){this.setItem(e,t)}getAuthorityMetadata(e){const t=this.getItem(e);return t&&function(e,t){return!!t&&0===e.indexOf(na)&&t.hasOwnProperty("aliases")&&t.hasOwnProperty("preferred_cache")&&t.hasOwnProperty("preferred_network")&&t.hasOwnProperty("canonical_authority")&&t.hasOwnProperty("authorization_endpoint")&&t.hasOwnProperty("token_endpoint")&&t.hasOwnProperty("issuer")&&t.hasOwnProperty("aliasesFromNetwork")&&t.hasOwnProperty("endpointsFromNetwork")&&t.hasOwnProperty("expiresAt")&&t.hasOwnProperty("jwks_uri")}(e,t)?t:null}getAuthorityMetadataKeys(){return this.getKeys().filter(e=>this.isAuthorityMetadata(e))}setAuthorityMetadata(e,t){this.setItem(e,t)}getThrottlingCache(e){const t=this.getItem(e);return t&&function(e,t){let r=!1;e&&(r=0===e.indexOf(fa));let n=!0;return t&&(n=t.hasOwnProperty("throttleTime")),r&&n}(e,t)?t:null}setThrottlingCache(e,t){this.setItem(e,t)}removeItem(e){this.logger.tracePii(`Item key: ${e}`);let t=!1;const r=this.getCache();return r[e]&&(delete r[e],t=!0),t&&(this.setCache(r),this.emitChange()),t}removeOutdatedAccount(e){this.removeItem(e)}containsKey(e){return this.getKeys().includes(e)}getKeys(){this.logger.trace("Retrieving all cache keys");const e=this.getCache();return[...Object.keys(e)]}clear(){this.logger.trace("Clearing cache entries created by MSAL");this.getKeys().forEach(e=>{this.removeItem(e)}),this.emitChange()}static generateInMemoryCache(e){return td.deserializeAllCache(td.deserializeJSONBlob(e))}static generateJsonCache(e){return ys.serializeAllCache(e)}updateCredentialCacheKey(e,t){const r=qc(t);if(e!==r){const n=this.getItem(e);if(n)return this.removeItem(e),this.setItem(r,n),this.logger.verbose(`Updated an outdated ${t.credentialType} cache key`),r;this.logger.error(`Attempted to update an outdated ${t.credentialType} cache key but no item matching the outdated key was found in storage`)}return e}}const lf={},hf={},df={},ff={},pf={};class mf{constructor(e,t,r){this.cacheHasChanged=!1,this.storage=e,this.storage.registerChangeEmitter(this.handleChangeEvent.bind(this)),r&&(this.persistence=r),this.logger=t}hasChanged(){return this.cacheHasChanged}serialize(){this.logger.trace("Serializing in-memory cache");let e=ys.serializeAllCache(this.storage.getInMemoryCache());return this.cacheSnapshot?(this.logger.trace("Reading cache snapshot from disk"),e=this.mergeState(JSON.parse(this.cacheSnapshot),e)):this.logger.trace("No cache snapshot to merge"),this.cacheHasChanged=!1,JSON.stringify(e)}deserialize(e){if(this.logger.trace("Deserializing JSON to in-memory cache"),this.cacheSnapshot=e,this.cacheSnapshot){this.logger.trace("Reading cache snapshot from disk");const e=td.deserializeAllCache(this.overlayDefaults(JSON.parse(this.cacheSnapshot)));this.storage.setInMemoryCache(e)}else this.logger.trace("No cache snapshot to deserialize")}getKVStore(){return this.storage.getCache()}getCacheSnapshot(){const e=uf.generateInMemoryCache(this.cacheSnapshot);return this.storage.inMemoryCacheToCache(e)}async getAllAccounts(){let e;this.logger.trace("getAllAccounts called");try{return this.persistence&&(e=new zh(this,!1),await this.persistence.beforeCacheAccess(e)),this.storage.getAllAccounts()}finally{this.persistence&&e&&await this.persistence.afterCacheAccess(e)}}async getAccountByHomeId(e){const t=await this.getAllAccounts();return e&&t&&t.length&&t.filter(t=>t.homeAccountId===e)[0]||null}async getAccountByLocalId(e){const t=await this.getAllAccounts();return e&&t&&t.length&&t.filter(t=>t.localAccountId===e)[0]||null}async removeAccount(e){let t;this.logger.trace("removeAccount called");try{this.persistence&&(t=new zh(this,!0),await this.persistence.beforeCacheAccess(t)),await this.storage.removeAccount(qu.generateAccountCacheKey(e))}finally{this.persistence&&t&&await this.persistence.afterCacheAccess(t)}}async overwriteCache(){if(!this.persistence)return void this.logger.info("No persistence layer specified, cache cannot be overwritten");this.logger.info("Overwriting in-memory cache with persistent cache"),this.storage.clear();const e=new zh(this,!1);await this.persistence.beforeCacheAccess(e);const t=this.getCacheSnapshot();this.storage.setCache(t),await this.persistence.afterCacheAccess(e)}handleChangeEvent(){this.cacheHasChanged=!0}mergeState(e,t){this.logger.trace("Merging in-memory cache with cache snapshot");const r=this.mergeRemovals(e,t);return this.mergeUpdates(r,t)}mergeUpdates(e,t){return Object.keys(t).forEach(r=>{const n=t[r];if(e.hasOwnProperty(r)){const t=null!==n,o="object"==typeof n,i=!Array.isArray(n),s=void 0!==e[r]&&null!==e[r];t&&o&&i&&s?this.mergeUpdates(e[r],n):e[r]=n}else null!==n&&(e[r]=n)}),e}mergeRemovals(e,t){this.logger.trace("Remove updated entries in cache");const r=e.Account?this.mergeRemovalsDict(e.Account,t.Account):e.Account,n=e.AccessToken?this.mergeRemovalsDict(e.AccessToken,t.AccessToken):e.AccessToken,o=e.RefreshToken?this.mergeRemovalsDict(e.RefreshToken,t.RefreshToken):e.RefreshToken,i=e.IdToken?this.mergeRemovalsDict(e.IdToken,t.IdToken):e.IdToken,s=e.AppMetadata?this.mergeRemovalsDict(e.AppMetadata,t.AppMetadata):e.AppMetadata;return{...e,Account:r,AccessToken:n,RefreshToken:o,IdToken:i,AppMetadata:s}}mergeRemovalsDict(e,t){const r={...e};return Object.keys(e).forEach(e=>{t&&t.hasOwnProperty(e)||delete r[e]}),r}overlayDefaults(e){return this.logger.trace("Overlaying input cache with the default cache"),{Account:{...lf,...e.Account},IdToken:{...hf,...e.IdToken},AccessToken:{...df,...e.AccessToken},RefreshToken:{...ff,...e.RefreshToken},AppMetadata:{...pf,...e.AppMetadata}}}}var gf,yf,vf,Ef,bf,wf,If,Cf,_f,Tf,Sf,Af,Of,kf,Rf,Pf,Nf,Lf,Df,xf,Mf,$f,Uf,Ff,jf,Bf,qf,Hf,Gf,zf,Kf,Vf,Yf,Wf,Qf,Jf,Zf,Xf,ep,tp,rp,np,op,ip,sp,ap,cp,up,lp,hp,dp,fp,pp,mp,gp,yp,vp,Ep,bp={},wp={exports:{}};function Ip(){return gf||(gf=1,function(e,t){var r=j,n=r.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function i(e,t,r){return n(e,t,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(o(r,t),t.Buffer=i),i.prototype=Object.create(n.prototype),o(n,i),i.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return n(e,t,r)},i.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var o=n(e);return void 0!==t?"string"==typeof r?o.fill(t,r):o.fill(t):o.fill(0),o},i.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n(e)},i.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}}(wp,wp.exports)),wp.exports}function Cp(){if(vf)return yf;vf=1;var e=Ip().Buffer,t=B;function r(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=e.alloc(0),this;if("function"==typeof t.pipe)return this.buffer=e.alloc(0),t.pipe(this),this;if(t.length||"object"==typeof t)return this.buffer=t,this.writable=!1,process.nextTick(function(){this.emit("end",t),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof t+")")}return q.inherits(r,t),r.prototype.write=function(t){this.buffer=e.concat([this.buffer,e.from(t)]),this.emit("data",t)},r.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1},yf=r}function _p(){if(If)return wf;If=1;var e=Ip().Buffer,t=function(){if(bf)return Ef;function e(e){return(e/8|0)+(e%8==0?0:1)}bf=1;var t={ES256:e(256),ES384:e(384),ES512:e(521)};return Ef=function(e){var r=t[e];if(r)return r;throw new Error('Unknown algorithm "'+e+'"')}}(),r=128;function n(t){if(e.isBuffer(t))return t;if("string"==typeof t)return e.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function o(e,t,n){for(var o=0;t+o<n&&0===e[t+o];)++o;return e[t+o]>=r&&--o,o}return wf={derToJose:function(r,o){r=n(r);var i=t(o),s=i+1,a=r.length,c=0;if(48!==r[c++])throw new Error('Could not find expected "seq"');var u=r[c++];if(129===u&&(u=r[c++]),a-c<u)throw new Error('"seq" specified length of "'+u+'", only "'+(a-c)+'" remaining');if(2!==r[c++])throw new Error('Could not find expected "int" for "r"');var l=r[c++];if(a-c-2<l)throw new Error('"r" specified length of "'+l+'", only "'+(a-c-2)+'" available');if(s<l)throw new Error('"r" specified length of "'+l+'", max of "'+s+'" is acceptable');var h=c;if(c+=l,2!==r[c++])throw new Error('Could not find expected "int" for "s"');var d=r[c++];if(a-c!==d)throw new Error('"s" specified length of "'+d+'", expected "'+(a-c)+'"');if(s<d)throw new Error('"s" specified length of "'+d+'", max of "'+s+'" is acceptable');var f=c;if((c+=d)!==a)throw new Error('Expected to consume entire buffer, but "'+(a-c)+'" bytes remain');var p=i-l,m=i-d,g=e.allocUnsafe(p+l+m+d);for(c=0;c<p;++c)g[c]=0;r.copy(g,c,h+Math.max(-p,0),h+l);for(var y=c=i;c<y+m;++c)g[c]=0;return r.copy(g,c,f+Math.max(-m,0),f+d),g=(g=g.toString("base64")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")},joseToDer:function(i,s){i=n(i);var a=t(s),c=i.length;if(c!==2*a)throw new TypeError('"'+s+'" signatures must be "'+2*a+'" bytes, saw "'+c+'"');var u=o(i,0,a),l=o(i,a,i.length),h=a-u,d=a-l,f=2+h+1+1+d,p=f<r,m=e.allocUnsafe((p?2:3)+f),g=0;return m[g++]=48,p?m[g++]=f:(m[g++]=129,m[g++]=255&f),m[g++]=2,m[g++]=h,u<0?(m[g++]=0,g+=i.copy(m,g,0,a)):g+=i.copy(m,g,u,a),m[g++]=2,m[g++]=d,l<0?(m[g++]=0,i.copy(m,g,a)):i.copy(m,g,a+l),m}},wf}function Tp(){if(Sf)return Tf;Sf=1;var e,t=Ip().Buffer,r=D,n=_p(),o=q,i="secret must be a string or buffer",s="key must be a string or a buffer",a="function"==typeof r.createPublicKey;function c(e){if(!t.isBuffer(e)&&"string"!=typeof e){if(!a)throw d(s);if("object"!=typeof e)throw d(s);if("string"!=typeof e.type)throw d(s);if("string"!=typeof e.asymmetricKeyType)throw d(s);if("function"!=typeof e.export)throw d(s)}}function u(e){if(!t.isBuffer(e)&&"string"!=typeof e&&"object"!=typeof e)throw d("key must be a string, a buffer or an object")}function l(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function h(e){var t=4-(e=e.toString()).length%4;if(4!==t)for(var r=0;r<t;++r)e+="=";return e.replace(/\-/g,"+").replace(/_/g,"/")}function d(e){var t=[].slice.call(arguments,1),r=o.format.bind(o,e).apply(null,t);return new TypeError(r)}function f(e){var r;return r=e,t.isBuffer(r)||"string"==typeof r||(e=JSON.stringify(e)),e}function p(e){return function(n,o){!function(e){if(!t.isBuffer(e)){if("string"==typeof e)return e;if(!a)throw d(i);if("object"!=typeof e)throw d(i);if("secret"!==e.type)throw d(i);if("function"!=typeof e.export)throw d(i)}}(o),n=f(n);var s=r.createHmac("sha"+e,o);return l((s.update(n),s.digest("base64")))}}a&&(s+=" or a KeyObject",i+="or a KeyObject");var m="timingSafeEqual"in r?function(e,t){return e.byteLength===t.byteLength&&r.timingSafeEqual(e,t)}:function(t,r){return e||(e=function(){if(_f)return Cf;_f=1;var e=j.Buffer,t=j.SlowBuffer;function r(t,r){if(!e.isBuffer(t)||!e.isBuffer(r))return!1;if(t.length!==r.length)return!1;for(var n=0,o=0;o<t.length;o++)n|=t[o]^r[o];return 0===n}Cf=r,r.install=function(){e.prototype.equal=t.prototype.equal=function(e){return r(this,e)}};var n=e.prototype.equal,o=t.prototype.equal;return r.restore=function(){e.prototype.equal=n,t.prototype.equal=o},Cf}()),e(t,r)};function g(e){return function(r,n,o){var i=p(e)(r,o);return m(t.from(n),t.from(i))}}function y(e){return function(t,n){u(n),t=f(t);var o=r.createSign("RSA-SHA"+e);return l((o.update(t),o.sign(n,"base64")))}}function v(e){return function(t,n,o){c(o),t=f(t),n=h(n);var i=r.createVerify("RSA-SHA"+e);return i.update(t),i.verify(o,n,"base64")}}function E(e){return function(t,n){u(n),t=f(t);var o=r.createSign("RSA-SHA"+e);return l((o.update(t),o.sign({key:n,padding:r.constants.RSA_PKCS1_PSS_PADDING,saltLength:r.constants.RSA_PSS_SALTLEN_DIGEST},"base64")))}}function b(e){return function(t,n,o){c(o),t=f(t),n=h(n);var i=r.createVerify("RSA-SHA"+e);return i.update(t),i.verify({key:o,padding:r.constants.RSA_PKCS1_PSS_PADDING,saltLength:r.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function w(e){var t=y(e);return function(){var r=t.apply(null,arguments);return r=n.derToJose(r,"ES"+e)}}function I(e){var t=v(e);return function(r,o,i){return o=n.joseToDer(o,"ES"+e).toString("base64"),t(r,o,i)}}function C(){return function(){return""}}function _(){return function(e,t){return""===t}}return Tf=function(e){var t={hs:p,rs:y,ps:E,es:w,none:C},r={hs:g,rs:v,ps:b,es:I,none:_},n=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/i);if(!n)throw d('"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".',e);var o=(n[1]||n[3]).toLowerCase(),i=n[2];return{sign:t[o](i),verify:r[o](i)}}}function Sp(){if(Of)return Af;Of=1;var e=j.Buffer;return Af=function(t){return"string"==typeof t?t:"number"==typeof t||e.isBuffer(t)?t.toString():JSON.stringify(t)}}function Ap(){if(Rf)return kf;Rf=1;var e=Ip().Buffer,t=Cp(),r=Tp(),n=B,o=Sp(),i=q;function s(t,r){return e.from(t,r).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function a(e){var t=e.header,n=e.payload,a=e.secret||e.privateKey,c=e.encoding,u=r(t.alg),l=function(e,t,r){r=r||"utf8";var n=s(o(e),"binary"),a=s(o(t),r);return i.format("%s.%s",n,a)}(t,n,c),h=u.sign(l,a);return i.format("%s.%s",l,h)}function c(e){var r=e.secret||e.privateKey||e.key,n=new t(r);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=n,this.payload=new t(e.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}return i.inherits(c,n),c.prototype.sign=function(){try{var e=a({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(e){this.readable=!1,this.emit("error",e),this.emit("close")}},c.sign=a,kf=c}function Op(){if(Nf)return Pf;Nf=1;var e=Ip().Buffer,t=Cp(),r=Tp(),n=B,o=Sp(),i=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function s(e){if(function(e){return"[object Object]"===Object.prototype.toString.call(e)}(e))return e;try{return JSON.parse(e)}catch(e){return}}function a(t){var r=t.split(".",1)[0];return s(e.from(r,"base64").toString("binary"))}function c(e){return e.split(".")[2]}function u(e){return i.test(e)&&!!a(e)}function l(e,t,n){if(!t){var i=new Error("Missing algorithm parameter for jws.verify");throw i.code="MISSING_ALGORITHM",i}var s=c(e=o(e)),a=function(e){return e.split(".",2).join(".")}(e);return r(t).verify(a,s,n)}function h(t,r){if(r=r||{},!u(t=o(t)))return null;var n=a(t);if(!n)return null;var i=function(t,r){r=r||"utf8";var n=t.split(".")[1];return e.from(n,"base64").toString(r)}(t);return("JWT"===n.typ||r.json)&&(i=JSON.parse(i,r.encoding)),{header:n,payload:i,signature:c(t)}}function d(e){var r=(e=e||{}).secret||e.publicKey||e.key,n=new t(r);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=n,this.signature=new t(e.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}return q.inherits(d,n),d.prototype.verify=function(){try{var e=l(this.signature.buffer,this.algorithm,this.key.buffer),t=h(this.signature.buffer,this.encoding);return this.emit("done",e,t),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(e){this.readable=!1,this.emit("error",e),this.emit("close")}},d.decode=h,d.isValid=u,d.verify=l,Pf=d}function kp(){if(Lf)return bp;Lf=1;var e=Ap(),t=Op();return bp.ALGORITHMS=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"],bp.sign=e.sign,bp.verify=t.verify,bp.decode=t.decode,bp.isValid=t.isValid,bp.createSign=function(t){return new e(t)},bp.createVerify=function(e){return new t(e)},bp}function Rp(){if(xf)return Df;xf=1;var e=kp();return Df=function(t,r){r=r||{};var n=e.decode(t,r);if(!n)return null;var o=n.payload;if("string"==typeof o)try{var i=JSON.parse(o);null!==i&&"object"==typeof i&&(o=i)}catch(e){}return!0===r.complete?{header:n.header,payload:o,signature:n.signature}:o},Df}function Pp(){if($f)return Mf;$f=1;var e=function(e,t){Error.call(this,e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="JsonWebTokenError",this.message=e,t&&(this.inner=t)};return(e.prototype=Object.create(Error.prototype)).constructor=e,Mf=e}function Np(){if(Ff)return Uf;Ff=1;var e=Pp(),t=function(t,r){e.call(this,t),this.name="NotBeforeError",this.date=r};return(t.prototype=Object.create(e.prototype)).constructor=t,Uf=t}function Lp(){if(Bf)return jf;Bf=1;var e=Pp(),t=function(t,r){e.call(this,t),this.name="TokenExpiredError",this.expiredAt=r};return(t.prototype=Object.create(e.prototype)).constructor=t,jf=t}function Dp(){if(Hf)return qf;Hf=1;var e=1e3,t=60*e,r=60*t,n=24*r,o=7*n,i=365.25*n;function s(e,t,r,n){var o=t>=1.5*r;return Math.round(e/r)+" "+n+(o?"s":"")}return qf=function(a,c){c=c||{};var u=typeof a;if("string"===u&&a.length>0)return function(s){if((s=String(s)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(s);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*i;case"weeks":case"week":case"w":return c*o;case"days":case"day":case"d":return c*n;case"hours":case"hour":case"hrs":case"hr":case"h":return c*r;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(a);if("number"===u&&isFinite(a))return c.long?function(o){var i=Math.abs(o);if(i>=n)return s(o,i,n,"day");if(i>=r)return s(o,i,r,"hour");if(i>=t)return s(o,i,t,"minute");if(i>=e)return s(o,i,e,"second");return o+" ms"}(a):function(o){var i=Math.abs(o);if(i>=n)return Math.round(o/n)+"d";if(i>=r)return Math.round(o/r)+"h";if(i>=t)return Math.round(o/t)+"m";if(i>=e)return Math.round(o/e)+"s";return o+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))},qf}function xp(){if(zf)return Gf;zf=1;var e=Dp();return Gf=function(t,r){var n=r||Math.floor(Date.now()/1e3);if("string"==typeof t){var o=e(t);if(void 0===o)return;return Math.floor(n+o/1e3)}return"number"==typeof t?n+t:void 0}}function Mp(){if(Jf)return Qf;Jf=1;const e=function(){if(Vf)return Kf;Vf=1;const e=so();return Kf=e.satisfies(process.version,">=15.7.0")}(),t=function(){if(Wf)return Yf;Wf=1;const e=so();return Yf=e.satisfies(process.version,">=16.9.0")}(),r={ec:["ES256","ES384","ES512"],rsa:["RS256","PS256","RS384","PS384","RS512","PS512"],"rsa-pss":["PS256","PS384","PS512"]},n={ES256:"prime256v1",ES384:"secp384r1",ES512:"secp521r1"};return Qf=function(o,i){if(!o||!i)return;const s=i.asymmetricKeyType;if(!s)return;const a=r[s];if(!a)throw new Error(`Unknown key type "${s}".`);if(!a.includes(o))throw new Error(`"alg" parameter for "${s}" key type must be one of: ${a.join(", ")}.`);if(e)switch(s){case"ec":const e=i.asymmetricKeyDetails.namedCurve,r=n[o];if(e!==r)throw new Error(`"alg" parameter "${o}" requires curve "${r}".`);break;case"rsa-pss":if(t){const e=parseInt(o.slice(-3),10),{hashAlgorithm:t,mgf1HashAlgorithm:r,saltLength:n}=i.asymmetricKeyDetails;if(t!==`sha${e}`||r!==t)throw new Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${o}.`);if(void 0!==n&&n>e>>3)throw new Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${o}.`)}}}}function $p(){if(Xf)return Zf;Xf=1;var e=so();return Zf=e.satisfies(process.version,"^6.12.0 || >=8.0.0")}function Up(){if(tp)return ep;tp=1;const e=Pp(),t=Np(),r=Lp(),n=Rp(),o=xp(),i=Mp(),s=$p(),a=kp(),{KeyObject:c,createSecretKey:u,createPublicKey:l}=D,h=["RS256","RS384","RS512"],d=["ES256","ES384","ES512"],f=["RS256","RS384","RS512"],p=["HS256","HS384","HS512"];return s&&(h.splice(h.length,0,"PS256","PS384","PS512"),f.splice(f.length,0,"PS256","PS384","PS512")),ep=function(s,m,g,y){let v;if("function"!=typeof g||y||(y=g,g={}),g||(g={}),g=Object.assign({},g),v=y||function(e,t){if(e)throw e;return t},g.clockTimestamp&&"number"!=typeof g.clockTimestamp)return v(new e("clockTimestamp must be a number"));if(void 0!==g.nonce&&("string"!=typeof g.nonce||""===g.nonce.trim()))return v(new e("nonce must be a non-empty string"));if(void 0!==g.allowInvalidAsymmetricKeyTypes&&"boolean"!=typeof g.allowInvalidAsymmetricKeyTypes)return v(new e("allowInvalidAsymmetricKeyTypes must be a boolean"));const E=g.clockTimestamp||Math.floor(Date.now()/1e3);if(!s)return v(new e("jwt must be provided"));if("string"!=typeof s)return v(new e("jwt must be a string"));const b=s.split(".");if(3!==b.length)return v(new e("jwt malformed"));let w;try{w=n(s,{complete:!0})}catch(e){return v(e)}if(!w)return v(new e("invalid token"));const I=w.header;let C;if("function"==typeof m){if(!y)return v(new e("verify must be called asynchronous if secret or public key is provided as a callback"));C=m}else C=function(e,t){return t(null,m)};return C(I,function(n,m){if(n)return v(new e("error in secret or public key callback: "+n.message));const y=""!==b[2].trim();if(!y&&m)return v(new e("jwt signature is required"));if(y&&!m)return v(new e("secret or public key must be provided"));if(!y&&!g.algorithms)return v(new e('please specify "none" in "algorithms" to verify unsigned tokens'));if(null!=m&&!(m instanceof c))try{m=l(m)}catch(t){try{m=u("string"==typeof m?Buffer.from(m):m)}catch(t){return v(new e("secretOrPublicKey is not valid key material"))}}if(g.algorithms||("secret"===m.type?g.algorithms=p:["rsa","rsa-pss"].includes(m.asymmetricKeyType)?g.algorithms=f:"ec"===m.asymmetricKeyType?g.algorithms=d:g.algorithms=h),-1===g.algorithms.indexOf(w.header.alg))return v(new e("invalid algorithm"));if(I.alg.startsWith("HS")&&"secret"!==m.type)return v(new e(`secretOrPublicKey must be a symmetric key when using ${I.alg}`));if(/^(?:RS|PS|ES)/.test(I.alg)&&"public"!==m.type)return v(new e(`secretOrPublicKey must be an asymmetric key when using ${I.alg}`));if(!g.allowInvalidAsymmetricKeyTypes)try{i(I.alg,m)}catch(e){return v(e)}let C;try{C=a.verify(s,w.header.alg,m)}catch(e){return v(e)}if(!C)return v(new e("invalid signature"));const _=w.payload;if(void 0!==_.nbf&&!g.ignoreNotBefore){if("number"!=typeof _.nbf)return v(new e("invalid nbf value"));if(_.nbf>E+(g.clockTolerance||0))return v(new t("jwt not active",new Date(1e3*_.nbf)))}if(void 0!==_.exp&&!g.ignoreExpiration){if("number"!=typeof _.exp)return v(new e("invalid exp value"));if(E>=_.exp+(g.clockTolerance||0))return v(new r("jwt expired",new Date(1e3*_.exp)))}if(g.audience){const t=Array.isArray(g.audience)?g.audience:[g.audience];if(!(Array.isArray(_.aud)?_.aud:[_.aud]).some(function(e){return t.some(function(t){return t instanceof RegExp?t.test(e):t===e})}))return v(new e("jwt audience invalid. expected: "+t.join(" or ")))}if(g.issuer){if("string"==typeof g.issuer&&_.iss!==g.issuer||Array.isArray(g.issuer)&&-1===g.issuer.indexOf(_.iss))return v(new e("jwt issuer invalid. expected: "+g.issuer))}if(g.subject&&_.sub!==g.subject)return v(new e("jwt subject invalid. expected: "+g.subject));if(g.jwtid&&_.jti!==g.jwtid)return v(new e("jwt jwtid invalid. expected: "+g.jwtid));if(g.nonce&&_.nonce!==g.nonce)return v(new e("jwt nonce invalid. expected: "+g.nonce));if(g.maxAge){if("number"!=typeof _.iat)return v(new e("iat required when maxAge is specified"));const t=o(g.maxAge,_.iat);if(void 0===t)return v(new e('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));if(E>=t+(g.clockTolerance||0))return v(new r("maxAge exceeded",new Date(1e3*t)))}if(!0===g.complete){const e=w.signature;return v(null,{header:I,payload:_,signature:e})}return v(null,_)})},ep}function Fp(){if(np)return rp;np=1;var e=1/0,t=9007199254740991,r=17976931348623157e292,n=NaN,o="[object Arguments]",i="[object Function]",s="[object GeneratorFunction]",a="[object String]",c="[object Symbol]",u=/^\s+|\s+$/g,l=/^[-+]0x[0-9a-f]+$/i,h=/^0b[01]+$/i,d=/^0o[0-7]+$/i,f=/^(?:0|[1-9]\d*)$/,p=parseInt;function m(e){return e!=e}function g(e,t){return function(e,t){for(var r=-1,n=e?e.length:0,o=Array(n);++r<n;)o[r]=t(e[r],r,e);return o}(t,function(t){return e[t]})}var y,v,E=Object.prototype,b=E.hasOwnProperty,w=E.toString,I=E.propertyIsEnumerable,C=(y=Object.keys,v=Object,function(e){return y(v(e))}),_=Math.max;function T(e,t){var r=O(e)||function(e){return function(e){return P(e)&&k(e)}(e)&&b.call(e,"callee")&&(!I.call(e,"callee")||w.call(e)==o)}(e)?function(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}(e.length,String):[],n=r.length,i=!!n;for(var s in e)!b.call(e,s)||i&&("length"==s||A(s,n))||r.push(s);return r}function S(e){if(!function(e){var t=e&&e.constructor,r="function"==typeof t&&t.prototype||E;return e===r}(e))return C(e);var t=[];for(var r in Object(e))b.call(e,r)&&"constructor"!=r&&t.push(r);return t}function A(e,r){return!!(r=null==r?t:r)&&("number"==typeof e||f.test(e))&&e>-1&&e%1==0&&e<r}var O=Array.isArray;function k(e){return null!=e&&function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=t}(e.length)&&!function(e){var t=R(e)?w.call(e):"";return t==i||t==s}(e)}function R(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function P(e){return!!e&&"object"==typeof e}return rp=function(t,o,i,s){var f;t=k(t)?t:(f=t)?g(f,function(e){return k(e)?T(e):S(e)}(f)):[],i=i&&!s?function(t){var o=function(t){if(!t)return 0===t?t:0;if(t=function(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||P(e)&&w.call(e)==c}(e))return n;if(R(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=R(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(u,"");var r=h.test(e);return r||d.test(e)?p(e.slice(2),r?2:8):l.test(e)?n:+e}(t),t===e||t===-1/0){return(t<0?-1:1)*r}return t==t?t:0}(t),i=o%1;return o==o?i?o-i:o:0}(i):0;var y=t.length;return i<0&&(i=_(y+i,0)),function(e){return"string"==typeof e||!O(e)&&P(e)&&w.call(e)==a}(t)?i<=y&&t.indexOf(o,i)>-1:!!y&&function(e,t,r){if(t!=t)return function(e,t,r){for(var n=e.length,o=r+-1;++o<n;)if(t(e[o],o,e))return o;return-1}(e,m,r);for(var n=r-1,o=e.length;++n<o;)if(e[n]===t)return n;return-1}(t,o,i)>-1}}function jp(){if(ap)return sp;ap=1;var e=1/0,t=17976931348623157e292,r=NaN,n="[object Symbol]",o=/^\s+|\s+$/g,i=/^[-+]0x[0-9a-f]+$/i,s=/^0b[01]+$/i,a=/^0o[0-7]+$/i,c=parseInt,u=Object.prototype.toString;function l(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}return sp=function(h){return"number"==typeof h&&h==function(h){var d=function(h){if(!h)return 0===h?h:0;if(h=function(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&u.call(e)==n}(e))return r;if(l(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=l(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(o,"");var h=s.test(e);return h||a.test(e)?c(e.slice(2),h?2:8):i.test(e)?r:+e}(h),h===e||h===-1/0){return(h<0?-1:1)*t}return h==h?h:0}(h),f=d%1;return d==d?f?d-f:d:0}(h)}}function Bp(){if(mp)return pp;mp=1;var e=1/0,t=17976931348623157e292,r=NaN,n="[object Symbol]",o=/^\s+|\s+$/g,i=/^[-+]0x[0-9a-f]+$/i,s=/^0b[01]+$/i,a=/^0o[0-7]+$/i,c=parseInt,u=Object.prototype.toString;function l(l,d){var f;if("function"!=typeof d)throw new TypeError("Expected a function");return l=function(l){var d=function(l){if(!l)return 0===l?l:0;if(l=function(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&u.call(e)==n}(e))return r;if(h(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=h(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(o,"");var l=s.test(e);return l||a.test(e)?c(e.slice(2),l?2:8):i.test(e)?r:+e}(l),l===e||l===-1/0){return(l<0?-1:1)*t}return l==l?l:0}(l),f=d%1;return d==d?f?d-f:d:0}(l),function(){return--l>0&&(f=d.apply(this,arguments)),l<=1&&(d=void 0),f}}function h(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}return pp=function(e){return l(2,e)}}function qp(){if(yp)return gp;yp=1;const e=xp(),t=$p(),r=Mp(),n=kp(),o=Fp(),i=function(){if(ip)return op;ip=1;var e=Object.prototype.toString;return op=function(t){return!0===t||!1===t||function(e){return!!e&&"object"==typeof e}(t)&&"[object Boolean]"==e.call(t)}}(),s=jp(),a=function(){if(up)return cp;up=1;var e=Object.prototype.toString;return cp=function(t){return"number"==typeof t||function(e){return!!e&&"object"==typeof e}(t)&&"[object Number]"==e.call(t)}}(),c=function(){if(hp)return lp;hp=1;var e,t,r=Function.prototype,n=Object.prototype,o=r.toString,i=n.hasOwnProperty,s=o.call(Object),a=n.toString,c=(e=Object.getPrototypeOf,t=Object,function(r){return e(t(r))});return lp=function(e){if(!function(e){return!!e&&"object"==typeof e}(e)||"[object Object]"!=a.call(e)||function(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}(e))return!1;var t=c(e);if(null===t)return!0;var r=i.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&o.call(r)==s},lp}(),u=function(){if(fp)return dp;fp=1;var e=Object.prototype.toString,t=Array.isArray;return dp=function(r){return"string"==typeof r||!t(r)&&function(e){return!!e&&"object"==typeof e}(r)&&"[object String]"==e.call(r)}}(),l=Bp(),{KeyObject:h,createSecretKey:d,createPrivateKey:f}=D,p=["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512","none"];t&&p.splice(3,0,"PS256","PS384","PS512");const m={expiresIn:{isValid:function(e){return s(e)||u(e)&&e},message:'"expiresIn" should be a number of seconds or string representing a timespan'},notBefore:{isValid:function(e){return s(e)||u(e)&&e},message:'"notBefore" should be a number of seconds or string representing a timespan'},audience:{isValid:function(e){return u(e)||Array.isArray(e)},message:'"audience" must be a string or array'},algorithm:{isValid:o.bind(null,p),message:'"algorithm" must be a valid string enum value'},header:{isValid:c,message:'"header" must be an object'},encoding:{isValid:u,message:'"encoding" must be a string'},issuer:{isValid:u,message:'"issuer" must be a string'},subject:{isValid:u,message:'"subject" must be a string'},jwtid:{isValid:u,message:'"jwtid" must be a string'},noTimestamp:{isValid:i,message:'"noTimestamp" must be a boolean'},keyid:{isValid:u,message:'"keyid" must be a string'},mutatePayload:{isValid:i,message:'"mutatePayload" must be a boolean'},allowInsecureKeySizes:{isValid:i,message:'"allowInsecureKeySizes" must be a boolean'},allowInvalidAsymmetricKeyTypes:{isValid:i,message:'"allowInvalidAsymmetricKeyTypes" must be a boolean'}},g={iat:{isValid:a,message:'"iat" should be a number of seconds'},exp:{isValid:a,message:'"exp" should be a number of seconds'},nbf:{isValid:a,message:'"nbf" should be a number of seconds'}};function y(e,t,r,n){if(!c(r))throw new Error('Expected "'+n+'" to be a plain object.');Object.keys(r).forEach(function(o){const i=e[o];if(i){if(!i.isValid(r[o]))throw new Error(i.message)}else if(!t)throw new Error('"'+o+'" is not allowed in "'+n+'"')})}const v={audience:"aud",issuer:"iss",subject:"sub",jwtid:"jti"},E=["expiresIn","notBefore","noTimestamp","audience","issuer","subject","jwtid"];return gp=function(t,o,i,s){"function"==typeof i?(s=i,i={}):i=i||{};const a="object"==typeof t&&!Buffer.isBuffer(t),c=Object.assign({alg:i.algorithm||"HS256",typ:a?"JWT":void 0,kid:i.keyid},i.header);function u(e){if(s)return s(e);throw e}if(!o&&"none"!==i.algorithm)return u(new Error("secretOrPrivateKey must have a value"));if(null!=o&&!(o instanceof h))try{o=f(o)}catch(e){try{o=d("string"==typeof o?Buffer.from(o):o)}catch(e){return u(new Error("secretOrPrivateKey is not valid key material"))}}if(c.alg.startsWith("HS")&&"secret"!==o.type)return u(new Error(`secretOrPrivateKey must be a symmetric key when using ${c.alg}`));if(/^(?:RS|PS|ES)/.test(c.alg)){if("private"!==o.type)return u(new Error(`secretOrPrivateKey must be an asymmetric key when using ${c.alg}`));if(!i.allowInsecureKeySizes&&!c.alg.startsWith("ES")&&void 0!==o.asymmetricKeyDetails&&o.asymmetricKeyDetails.modulusLength<2048)return u(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`))}if(void 0===t)return u(new Error("payload is required"));if(a){try{!function(e){y(g,!0,e,"payload")}(t)}catch(e){return u(e)}i.mutatePayload||(t=Object.assign({},t))}else{const e=E.filter(function(e){return void 0!==i[e]});if(e.length>0)return u(new Error("invalid "+e.join(",")+" option for "+typeof t+" payload"))}if(void 0!==t.exp&&void 0!==i.expiresIn)return u(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.'));if(void 0!==t.nbf&&void 0!==i.notBefore)return u(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.'));try{!function(e){y(m,!1,e,"options")}(i)}catch(e){return u(e)}if(!i.allowInvalidAsymmetricKeyTypes)try{r(c.alg,o)}catch(e){return u(e)}const p=t.iat||Math.floor(Date.now()/1e3);if(i.noTimestamp?delete t.iat:a&&(t.iat=p),void 0!==i.notBefore){try{t.nbf=e(i.notBefore,p)}catch(e){return u(e)}if(void 0===t.nbf)return u(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}if(void 0!==i.expiresIn&&"object"==typeof t){try{t.exp=e(i.expiresIn,p)}catch(e){return u(e)}if(void 0===t.exp)return u(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}Object.keys(v).forEach(function(e){const r=v[e];if(void 0!==i[e]){if(void 0!==t[r])return u(new Error('Bad "options.'+e+'" option. The payload already has an "'+r+'" property.'));t[r]=i[e]}});const b=i.encoding||"utf8";if("function"!=typeof s){let e=n.sign({header:c,payload:t,secret:o,encoding:b});if(!i.allowInsecureKeySizes&&/^(?:RS|PS)/.test(c.alg)&&e.length<256)throw new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`);return e}s=s&&l(s),n.createSign({header:c,privateKey:o,payload:t,encoding:b}).once("error",s).once("done",function(e){if(!i.allowInsecureKeySizes&&/^(?:RS|PS)/.test(c.alg)&&e.length<256)return s(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`));s(null,e)})}}var Hp=Qe(Ep?vp:(Ep=1,vp={decode:Rp(),verify:Up(),sign:qp(),JsonWebTokenError:Pp(),NotBeforeError:Np(),TokenExpiredError:Lp()}));class Gp{static fromAssertion(e){const t=new Gp;return t.jwt=e,t}static fromCertificate(e,t,r){const n=new Gp;return n.privateKey=t,n.thumbprint=e,n.useSha256=!1,r&&(n.publicCertificate=this.parseCertificate(r)),n}static fromCertificateWithSha256Thumbprint(e,t,r){const n=new Gp;return n.privateKey=t,n.thumbprint=e,n.useSha256=!0,r&&(n.publicCertificate=this.parseCertificate(r)),n}getJwt(e,t,r){if(this.privateKey&&this.thumbprint)return this.jwt&&!this.isExpired()&&t===this.issuer&&r===this.jwtAudience?this.jwt:this.createJwt(e,t,r);if(this.jwt)return this.jwt;throw kc(fc)}createJwt(e,t,r){this.issuer=t,this.jwtAudience=r;const n=Uc();this.expirationTime=n+600;const o={alg:this.useSha256?vd:yd},i=this.useSha256?Ed:bd;Object.assign(o,{[i]:of.base64EncodeUrl(this.thumbprint,"hex")}),this.publicCertificate&&Object.assign(o,{[wd]:this.publicCertificate});const s={[Id]:this.jwtAudience,[Cd]:this.expirationTime,[_d]:this.issuer,[Td]:this.issuer,[Sd]:n,[Ad]:e.createNewGuid()};return this.jwt=Hp.sign(s,this.privateKey,{header:o}),this.jwt}isExpired(){return this.expirationTime<Uc()}static parseCertificate(e){const t=/-----BEGIN CERTIFICATE-----\r*\n(.+?)\r*\n-----END CERTIFICATE-----/gs,r=[];let n;for(;null!==(n=t.exec(e));)r.push(n[1].replace(/\r*\n/g,vs.EMPTY_STRING));return r}}const zp="3.5.3";class Kp extends Nh{constructor(e){super(e)}async acquireToken(e){this.logger.info("in acquireToken call in username-password client");const t=Uc(),r=await this.executeTokenRequest(this.authority,e),n=new Kh(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.config.serializableCache,this.config.persistencePlugin);n.validateTokenResponse(r.body);return n.handleServerTokenResponse(r.body,this.authority,t,e)}async executeTokenRequest(e,t){const r=this.createTokenQueryParameters(t),n=zu.appendQueryString(e.tokenEndpoint,r),o=await this.createTokenRequestBody(t),i=this.createTokenRequestHeaders({credential:t.username,type:fl}),s={clientId:this.config.authOptions.clientId,authority:e.canonicalAuthority,scopes:t.scopes,claims:t.claims,authenticationScheme:t.authenticationScheme,resourceRequestMethod:t.resourceRequestMethod,resourceRequestUri:t.resourceRequestUri,shrClaims:t.shrClaims,sshKid:t.sshKid};return this.executePostToTokenEndpoint(n,o,i,s,t.correlationId)}async createTokenRequestBody(e){const t=new Map;Sl(t,this.config.authOptions.clientId),function(e,t){e.set(ya,t)}(t,e.username),function(e,t){e.set(va,t)}(t,e.password),Tl(t,e.scopes),_l(t,Hs),jl(t,Ks),Bl(t),Dl(t,this.config.libraryInfo),xl(t,this.config.telemetry.application),Vl(t),this.serverTelemetryManager&&Kl(t,this.serverTelemetryManager);Ll(t,e.correlationId||this.config.cryptoInterface.createNewGuid()),this.config.clientCredentials.clientSecret&&$l(t,this.config.clientCredentials.clientSecret);const r=this.config.clientCredentials.clientAssertion;return r&&(Ul(t,await Yh(r.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),Fl(t,r.assertionType)),(!Ou.isEmptyObj(e.claims)||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&Nl(t,e.claims,this.config.authOptions.clientCapabilities),this.config.systemOptions.preventCorsPreflight&&e.username&&kl(t,e.username),Gu(t)}}function Vp(e,t,r,n){const o=Zh({...e.auth,authority:t,redirectUri:r.redirectUri||""},r,n);return Dl(o,{sku:ad,version:zp,cpu:process.arch||"",os:process.platform||""}),e.auth.protocolMode!==Bu&&xl(o,e.telemetry.application),_l(o,qs),r.codeChallenge&&r.codeChallengeMethod&&function(e,t,r){if(!t||!r)throw Au(pu);e.set("code_challenge",t),e.set("code_challenge_method",r)}(o,r.codeChallenge,r.codeChallengeMethod),Hl(o,r.extraQueryParameters||{}),function(e,t,r,n){const o=Gu(t,r,n);return zu.appendQueryString(e.authorizationEndpoint,o)}(t,o,e.auth.encodeExtraQueryParams,r.extraQueryParameters)}class Yp{constructor(e){this.config=function({auth:e,broker:t,cache:r,system:n,telemetry:o}){const i={...Vd,networkClient:new Pd(n?.proxyUrl,n?.customAgentOptions),loggerOptions:n?.loggerOptions||Kd,disableInternalRetries:n?.disableInternalRetries||!1};if(e.clientCertificate&&!e.clientCertificate.thumbprint&&!e.clientCertificate.thumbprintSha256)throw Hd.createStateNotFoundError();return{auth:{...Gd,...e},broker:{...t},cache:{...zd,...r},system:{...i,...n},telemetry:{...Yd,...o}}}(e),this.cryptoProvider=new cf,this.logger=new Nc(this.config.system.loggerOptions,"@azure/msal-node",zp),this.storage=new uf(this.logger,this.config.auth.clientId,this.cryptoProvider,function(e){const t=e.cloudDiscoveryMetadata;let r;if(t)try{r=JSON.parse(t)}catch(e){throw Au(mu)}return{canonicalAuthority:e.authority?Sh(e.authority):void 0,knownAuthorities:e.knownAuthorities,cloudDiscoveryMetadata:r}}(this.config.auth)),this.tokenCache=new mf(this.storage,this.logger,this.config.cache.cachePlugin)}async getAuthCodeUrl(e){this.logger.info("getAuthCodeUrl called",e.correlationId);const t={...e,...await this.initializeBaseRequest(e),responseMode:e.responseMode||Gs,authenticationScheme:la.BEARER,state:e.state||"",nonce:e.nonce||""},r=await this.createAuthority(t.authority,t.correlationId,void 0,e.azureCloudOptions);return Vp(this.config,r,t,this.logger)}async acquireTokenByCode(e,t){this.logger.info("acquireTokenByCode called"),e.state&&t&&(this.logger.info("acquireTokenByCode - validating state"),this.validateState(e.state,t.state||""),t={...t,state:""});const r={...e,...await this.initializeBaseRequest(e),authenticationScheme:la.BEARER},n=this.initializeServerTelemetryManager(md,r.correlationId);try{const o=await this.createAuthority(r.authority,r.correlationId,void 0,e.azureCloudOptions),i=await this.buildOauthClientConfiguration(o,r.correlationId,r.redirectUri,n),s=new Wh(i);return this.logger.verbose("Auth code client created",r.correlationId),await s.acquireToken(r,t)}catch(e){throw e instanceof xa&&e.setCorrelationId(r.correlationId),n.cacheFailedRequest(e),e}}async acquireTokenByRefreshToken(e){this.logger.info("acquireTokenByRefreshToken called",e.correlationId);const t={...e,...await this.initializeBaseRequest(e),authenticationScheme:la.BEARER},r=this.initializeServerTelemetryManager(gd,t.correlationId);try{const n=await this.createAuthority(t.authority,t.correlationId,void 0,e.azureCloudOptions),o=await this.buildOauthClientConfiguration(n,t.correlationId,t.redirectUri||"",r),i=new Qh(o);return this.logger.verbose("Refresh token client created",t.correlationId),await i.acquireToken(t)}catch(e){throw e instanceof xa&&e.setCorrelationId(t.correlationId),r.cacheFailedRequest(e),e}}async acquireTokenSilent(e){const t={...e,...await this.initializeBaseRequest(e),forceRefresh:e.forceRefresh||!1},r=this.initializeServerTelemetryManager(dd,t.correlationId,t.forceRefresh);try{const n=await this.createAuthority(t.authority,t.correlationId,void 0,e.azureCloudOptions),o=await this.buildOauthClientConfiguration(n,t.correlationId,t.redirectUri||"",r),i=new Jh(o);this.logger.verbose("Silent flow client created",t.correlationId);try{return await this.tokenCache.overwriteCache(),await this.acquireCachedTokenSilent(t,i,o)}catch(e){if(e instanceof Oc&&e.errorCode===mc){return new Qh(o).acquireTokenByRefreshToken(t)}throw e}}catch(e){throw e instanceof xa&&e.setCorrelationId(t.correlationId),r.cacheFailedRequest(e),e}}async acquireCachedTokenSilent(e,t,r){const[n,o]=await t.acquireCachedToken({...e,scopes:e.scopes?.length?e.scopes:[...As]});if(o===Pa){this.logger.info("ClientApplication:acquireCachedTokenSilent - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed.");const t=new Qh(r);try{await t.acquireTokenByRefreshToken(e)}catch{}}return n}async acquireTokenByUsernamePassword(e){this.logger.info("acquireTokenByUsernamePassword called",e.correlationId);const t={...e,...await this.initializeBaseRequest(e)},r=this.initializeServerTelemetryManager(fd,t.correlationId);try{const n=await this.createAuthority(t.authority,t.correlationId,void 0,e.azureCloudOptions),o=await this.buildOauthClientConfiguration(n,t.correlationId,"",r),i=new Kp(o);return this.logger.verbose("Username password client created",t.correlationId),await i.acquireToken(t)}catch(e){throw e instanceof xa&&e.setCorrelationId(t.correlationId),r.cacheFailedRequest(e),e}}getTokenCache(){return this.logger.info("getTokenCache called"),this.tokenCache}validateState(e,t){if(!e)throw Hd.createStateNotFoundError();if(e!==t)throw kc(Ka)}getLogger(){return this.logger}setLogger(e){this.logger=e}async buildOauthClientConfiguration(e,t,r,n){this.logger.verbose("buildOauthClientConfiguration called",t),this.logger.info(`Building oauth client configuration with the following authority: ${e.tokenEndpoint}.`,t),n?.updateRegionDiscoveryMetadata(e.regionDiscoveryMetadata);return{authOptions:{clientId:this.config.auth.clientId,authority:e,clientCapabilities:this.config.auth.clientCapabilities,redirectUri:r},loggerOptions:{logLevel:this.config.system.loggerOptions.logLevel,loggerCallback:this.config.system.loggerOptions.loggerCallback,piiLoggingEnabled:this.config.system.loggerOptions.piiLoggingEnabled,correlationId:t},cacheOptions:{claimsBasedCachingEnabled:this.config.cache.claimsBasedCachingEnabled},cryptoInterface:this.cryptoProvider,networkInterface:this.config.system.networkClient,storageInterface:this.storage,serverTelemetryManager:n,clientCredentials:{clientSecret:this.clientSecret,clientAssertion:await this.getClientAssertion(e)},libraryInfo:{sku:ad,version:zp,cpu:process.arch||vs.EMPTY_STRING,os:process.platform||vs.EMPTY_STRING},telemetry:this.config.telemetry,persistencePlugin:this.config.cache.cachePlugin,serializableCache:this.tokenCache}}async getClientAssertion(e){return this.developerProvidedClientAssertion&&(this.clientAssertion=Gp.fromAssertion(await Yh(this.developerProvidedClientAssertion,this.config.auth.clientId,e.tokenEndpoint))),this.clientAssertion&&{assertion:this.clientAssertion.getJwt(this.cryptoProvider,this.config.auth.clientId,e.tokenEndpoint),assertionType:cd}}async initializeBaseRequest(e){return this.logger.verbose("initializeRequestScopes called",e.correlationId),e.authenticationScheme&&e.authenticationScheme===la.POP&&this.logger.verbose("Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request",e.correlationId),e.authenticationScheme=la.BEARER,this.config.cache.claimsBasedCachingEnabled&&e.claims&&!Ou.isEmptyObj(e.claims)&&(e.requestedClaimsHash=await this.cryptoProvider.hashString(e.claims)),{...e,scopes:[...e&&e.scopes||[],...As],correlationId:e&&e.correlationId||this.cryptoProvider.createNewGuid(),authority:e.authority||this.config.auth.authority}}initializeServerTelemetryManager(e,t,r){const n={clientId:this.config.auth.clientId,correlationId:t,apiId:e,forceRefresh:r||!1};return new ed(n,this.storage)}async createAuthority(e,t,r,n){this.logger.verbose("createAuthority called",t);const o=Th.generateAuthority(e,n||this.config.auth.azureCloudOptions),i={protocolMode:this.config.auth.protocolMode,knownAuthorities:this.config.auth.knownAuthorities,cloudDiscoveryMetadata:this.config.auth.cloudDiscoveryMetadata,authorityMetadata:this.config.auth.authorityMetadata,azureRegionConfiguration:r,skipAuthorityMetadataCache:this.config.auth.skipAuthorityMetadataCache};return Ah(o,this.config.system.networkClient,this.storage,i,this.logger,t)}clearCache(){this.storage.clear()}}class Wp{async listenForAuthCode(e,t){if(this.server)throw Hd.createLoopbackServerAlreadyExistsError();return new Promise((r,n)=>{this.server=U.createServer((o,i)=>{const s=o.url;if(!s)return i.end(t||"Error occurred loading redirectUrl"),void n(Hd.createUnableToLoadRedirectUrlError());if(s===vs.FORWARD_SLASH)return void i.end(e||"Auth code was successfully acquired. You can close this window now.");const a=this.getRedirectUri(),c=Hu(new URL(s,a).search)||{};c.code&&(i.writeHead(ws,{location:a}),i.end()),c.error&&i.end(t||`Error occurred: ${c.error}`),r(c)}),this.server.listen(0,"127.0.0.1")})}getRedirectUri(){if(!this.server||!this.server.listening)throw Hd.createNoLoopbackServerExistsError();const e=this.server.address();if(!e||"string"==typeof e||!e.port)throw this.closeServer(),Hd.createInvalidLoopbackAddressTypeError();const t=e&&e.port;return`${ld}${hd}:${t}`}closeServer(){this.server&&(this.server.close(),"function"==typeof this.server.closeAllConnections&&this.server.closeAllConnections(),this.server.unref(),this.server=void 0)}}class Qp extends Nh{constructor(e){super(e)}async acquireToken(e){const t=await this.getDeviceCode(e);e.deviceCodeCallback(t);const r=Uc(),n=await this.acquireTokenWithDeviceCode(e,t),o=new Kh(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.config.serializableCache,this.config.persistencePlugin);return o.validateTokenResponse(n),o.handleServerTokenResponse(n,this.authority,r,e)}async getDeviceCode(e){const t=this.createExtraQueryParameters(e),r=zu.appendQueryString(this.authority.deviceCodeEndpoint,t),n=this.createQueryString(e),o=this.createTokenRequestHeaders(),i={clientId:this.config.authOptions.clientId,authority:e.authority,scopes:e.scopes,claims:e.claims,authenticationScheme:e.authenticationScheme,resourceRequestMethod:e.resourceRequestMethod,resourceRequestUri:e.resourceRequestUri,shrClaims:e.shrClaims,sshKid:e.sshKid};return this.executePostRequestToDeviceCodeEndpoint(r,n,o,i,e.correlationId)}createExtraQueryParameters(e){const t=new Map;return e.extraQueryParameters&&Hl(t,e.extraQueryParameters),Gu(t)}async executePostRequestToDeviceCodeEndpoint(e,t,r,n,o){const{body:{user_code:i,device_code:s,verification_uri:a,expires_in:c,interval:u,message:l}}=await this.sendPostRequest(n,e,{body:t,headers:r},o);return{userCode:i,deviceCode:s,verificationUri:a,expiresIn:c,interval:u,message:l}}createQueryString(e){const t=new Map;return Tl(t,e.scopes),Sl(t,this.config.authOptions.clientId),e.extraQueryParameters&&Hl(t,e.extraQueryParameters),(e.claims||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&Nl(t,e.claims,this.config.authOptions.clientCapabilities),Gu(t)}continuePolling(e,t,r){if(r)throw this.logger.error("Token request cancelled by setting DeviceCodeRequest.cancel = true"),kc(oc);if(t&&t<e&&Uc()>t)throw this.logger.error(`User defined timeout for device code polling reached. The timeout was set for ${t}`),kc(gc);if(Uc()>e)throw t&&this.logger.verbose(`User specified timeout ignored as the device code has expired before the timeout elapsed. The user specified timeout was set for ${t}`),this.logger.error(`Device code expired. Expiration time of device code was ${e}`),kc(ic);return!0}async acquireTokenWithDeviceCode(e,t){const r=this.createTokenQueryParameters(e),n=zu.appendQueryString(this.authority.tokenEndpoint,r),o=this.createTokenRequestBody(e,t),i=this.createTokenRequestHeaders(),s=e.timeout?Uc()+e.timeout:void 0,a=Uc()+t.expiresIn,c=1e3*t.interval;for(;this.continuePolling(a,s,e.cancel);){const t={clientId:this.config.authOptions.clientId,authority:e.authority,scopes:e.scopes,claims:e.claims,authenticationScheme:e.authenticationScheme,resourceRequestMethod:e.resourceRequestMethod,resourceRequestUri:e.resourceRequestUri,shrClaims:e.shrClaims,sshKid:e.sshKid},r=await this.executePostToTokenEndpoint(n,o,i,t,e.correlationId);if(!r.body||!r.body.error)return this.logger.verbose("Authorization completed successfully. Polling stopped."),r.body;if(r.body.error!==vs.AUTHORIZATION_PENDING)throw this.logger.info("Unexpected error in polling from the server"),Ma(La,r.body.error);this.logger.info("Authorization pending. Continue polling."),await Bc(c)}throw this.logger.error("Polling stopped for unknown reasons."),kc(sc)}createTokenRequestBody(e,t){const r=new Map;Tl(r,e.scopes),Sl(r,this.config.authOptions.clientId),jl(r,Ys),function(e,t){e.set("device_code",t)}(r,t.deviceCode);return Ll(r,e.correlationId||this.config.cryptoInterface.createNewGuid()),Bl(r),Dl(r,this.config.libraryInfo),xl(r,this.config.telemetry.application),Vl(r),this.serverTelemetryManager&&Kl(r,this.serverTelemetryManager),(!Ou.isEmptyObj(e.claims)||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&Nl(r,e.claims,this.config.authOptions.clientCapabilities),Gu(r)}}class Jp extends Yp{constructor(e){super(e),this.config.broker.nativeBrokerPlugin&&(this.config.broker.nativeBrokerPlugin.isBrokerAvailable?(this.nativeBrokerPlugin=this.config.broker.nativeBrokerPlugin,this.nativeBrokerPlugin.setLogger(this.config.system.loggerOptions)):this.logger.warning("NativeBroker implementation was provided but the broker is unavailable.")),this.skus=ed.makeExtraSkuString({libraryName:ad,libraryVersion:zp})}async acquireTokenByDeviceCode(e){this.logger.info("acquireTokenByDeviceCode called",e.correlationId);const t=Object.assign(e,await this.initializeBaseRequest(e)),r=this.initializeServerTelemetryManager(pd,t.correlationId);try{const n=await this.createAuthority(t.authority,t.correlationId,void 0,e.azureCloudOptions),o=await this.buildOauthClientConfiguration(n,t.correlationId,"",r),i=new Qp(o);return this.logger.verbose("Device code client created",t.correlationId),await i.acquireToken(t)}catch(e){throw e instanceof xa&&e.setCorrelationId(t.correlationId),r.cacheFailedRequest(e),e}}async acquireTokenInteractive(e){const t=e.correlationId||this.cryptoProvider.createNewGuid();this.logger.trace("acquireTokenInteractive called",t);const{openBrowser:r,successTemplate:n,errorTemplate:o,windowHandle:i,loopbackClient:s,...a}=e;if(this.nativeBrokerPlugin){const r={...a,clientId:this.config.auth.clientId,scopes:e.scopes||As,redirectUri:`${ld}${hd}`,authority:e.authority||this.config.auth.authority,correlationId:t,extraParameters:{...a.extraQueryParameters,...a.tokenQueryParameters,[El]:this.skus},accountId:a.account?.nativeAccountId};return this.nativeBrokerPlugin.acquireTokenInteractive(r,i)}const{verifier:c,challenge:u}=await this.cryptoProvider.generatePkceCodes(),l=s||new Wp;let h={},d=null;try{const i=l.listenForAuthCode(n,o).then(e=>{h=e}).catch(e=>{d=e}),s=await this.waitForRedirectUri(l),f={...a,correlationId:t,scopes:e.scopes||As,redirectUri:s,responseMode:Gs,codeChallenge:u,codeChallengeMethod:Bs.S256},p=await this.getAuthCodeUrl(f);if(await r(p),await i,d)throw d;if(h.error)throw new Oh(h.error,h.error_description,h.suberror);if(!h.code)throw Hd.createNoAuthCodeInResponseError();const m=h.client_info,g={code:h.code,codeVerifier:c,clientInfo:m||vs.EMPTY_STRING,...f};return await this.acquireTokenByCode(g)}finally{l.closeServer()}}async acquireTokenSilent(e){const t=e.correlationId||this.cryptoProvider.createNewGuid();if(this.logger.trace("acquireTokenSilent called",t),this.nativeBrokerPlugin){const r={...e,clientId:this.config.auth.clientId,scopes:e.scopes||As,redirectUri:`${ld}${hd}`,authority:e.authority||this.config.auth.authority,correlationId:t,extraParameters:{...e.tokenQueryParameters,[El]:this.skus},accountId:e.account.nativeAccountId,forceRefresh:e.forceRefresh||!1};return this.nativeBrokerPlugin.acquireTokenSilent(r)}return super.acquireTokenSilent(e)}async signOut(e){if(this.nativeBrokerPlugin&&e.account.nativeAccountId){const t={clientId:this.config.auth.clientId,accountId:e.account.nativeAccountId,correlationId:e.correlationId||this.cryptoProvider.createNewGuid()};await this.nativeBrokerPlugin.signOut(t)}await this.getTokenCache().removeAccount(e.account)}async getAllAccounts(){if(this.nativeBrokerPlugin){const e=this.cryptoProvider.createNewGuid();return this.nativeBrokerPlugin.getAllAccounts(this.config.auth.clientId,e)}return this.getTokenCache().getAllAccounts()}async waitForRedirectUri(e){return new Promise((t,r)=>{let n=0;const o=setInterval(()=>{if(kd/Od<n)return clearInterval(o),void r(Hd.createLoopbackServerTimeoutError());try{const r=e.getRedirectUri();return clearInterval(o),void t(r)}catch(e){return e instanceof xa&&e.errorCode===Ud.code?void n++:(clearInterval(o),void r(e))}},Od)})}}process.env.ProgramData,process.env.ProgramFiles;class Zp extends cs{constructor(){super(),this.setMode("interactive")}setMode(e){this._set("mode",e)}setClient(e){this._set("client",e)}setClientConfig(e,t){this._set("client",async()=>{const{createAuthClient:r}=await import("./create-auth-client-Ds0jZb_X.js");return r(e,t)})}setServerPort(e){this._set("server.port",e)}setServerOnOpen(e){this._set("server.onOpen",e)}setAccessToken(e){this._set("accessToken",e)}_buildConfig(e,t){return this._set("parent",e.ref?.auth),super._buildConfig(e,t)}async _processConfig(e){switch(e.mode){case"interactive":if(e.client instanceof Jp==!1)throw new Error("Client is required when mode is interactive");if(!e.server)throw new Error("Server is required when mode is interactive");if("number"!=typeof e.server.port)throw new Error("Server port must be a number when mode is interactive");break;case"silent":if(e.client instanceof Jp==!1)throw new Error("Client is required when mode is silent");break;case"token_only":if("string"!=typeof e.accessToken)throw new Error("Access token is required when mode is token_only")}return e}}class Xp{#o;constructor(e){this.#o=e}login(){throw new Error("Method not supported in token mode")}logout(){throw new Error("Method not supported in token mode")}async acquireAccessToken(){return this.#o}}let em,tm;function rm(){return void 0===em&&(em=function(){try{return l.statSync("/.dockerenv"),!0}catch{return!1}}()||function(){try{return l.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}()),em}function nm(){return void 0===tm&&(tm=(()=>{try{return l.statSync("/run/.containerenv"),!0}catch{return!1}})()||rm()),tm}const om=()=>{if("linux"!==K.platform)return!1;if(Q.release().toLowerCase().includes("microsoft"))return!nm();try{return!!l.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")&&!nm()}catch{return!1}};var im=K.env.__IS_WSL_TEST__?om:om();function sm(e,t,r){const n=r=>Object.defineProperty(e,t,{value:r,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){const e=r();return n(e),e},set(e){n(e)}}),e}const am=W(O);const cm=W(O);async function um(e){return async function(e,{humanReadableOutput:t=!0}={}){if("darwin"!==K.platform)throw new Error("macOS only");const r=t?[]:["-ss"],{stdout:n}=await cm("osascript",["-e",e,r]);return n.trim()}(`tell application "Finder" to set app_path to application file id "${e}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}const lm=W(O),hm={AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},MSEdgeDHTML:{name:"Edge",id:"com.microsoft.edge"},MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"}};class dm extends Error{}const fm=W(O);async function pm(){if("darwin"===K.platform){const e=await async function(){if("darwin"!==K.platform)throw new Error("macOS only");const{stdout:e}=await am("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e);return t?.groups.id??"com.apple.Safari"}();return{name:await um(e),id:e}}if("linux"===K.platform){const{stdout:e}=await fm("xdg-mime",["query","default","x-scheme-handler/http"]),t=e.trim(),r=t.replace(/.desktop$/,"").replace("-"," ").toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());return{name:r,id:t}}if("win32"===K.platform)return async function(e=lm){const{stdout:t}=await e("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),r=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!r)throw new dm(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);const{id:n}=r.groups,o=hm[n];if(!o)throw new dm(`Unknown browser ID: ${n}`);return o}();throw new Error("Only macOS, Linux, and Windows are supported")}const mm=Y.promisify(S.execFile),gm=n.dirname(z(import.meta.url)),ym=n.join(gm,"xdg-open"),{platform:vm,arch:Em}=K,bm=(()=>{const e="/mnt/";let t;return async function(){if(t)return t;const r="/etc/wsl.conf";let n=!1;try{await v.access(r,w.F_OK),n=!0}catch{}if(!n)return e;const o=await v.readFile(r,{encoding:"utf8"}),i=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(o);return i?(t=i.groups.mountPoint.trim(),t=t.endsWith("/")?t:`${t}/`,t):e}})(),wm=async()=>`${await bm()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;const Im=async(e,t)=>{let r;for(const n of e)try{return await t(n)}catch(e){r=e}throw r},Cm=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return Im(e.app,t=>Cm({...e,app:t}));let t,{name:r,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(r))return Im(r,t=>Cm({...e,app:{name:t,arguments:n}}));if("browser"===r||"browserPrivate"===r){const t={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},o={chrome:"--incognito",firefox:"--private-window",edge:"--inPrivate"},i=im?await async function(){const e=await wm(),t=V.from('(Get-ItemProperty -Path "HKCU:\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice").ProgId',"utf16le").toString("base64"),{stdout:r}=await mm(e,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),n=r.trim(),o={ChromeHTML:"com.google.chrome",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return o[n]?{id:o[n]}:{}}():await pm();if(i.id in t){const s=t[i.id];return"browserPrivate"===r&&n.push(o[s]),Cm({...e,app:{name:Sm[s],arguments:n}})}throw new Error(`${i.name} is not supported as a default browser`)}const o=[],i={};if("darwin"===vm)t="open",e.wait&&o.push("--wait-apps"),e.background&&o.push("--background"),e.newInstance&&o.push("--new"),r&&o.push("-a",r);else if("win32"===vm||im&&!nm()&&!r){t=im?await wm():`${K.env.SYSTEMROOT||K.env.windir||"C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell`,o.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),im||(i.windowsVerbatimArguments=!0);const s=["Start"];e.wait&&s.push("-Wait"),r?(s.push(`"\`"${r}\`""`),e.target&&n.push(e.target)):e.target&&s.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),s.push("-ArgumentList",n.join(","))),e.target=V.from(s.join(" "),"utf16le").toString("base64")}else{if(r)t=r;else{const e=!gm||"/"===gm;let r=!1;try{await v.access(ym,w.X_OK),r=!0}catch{}t=K.versions.electron??("android"===vm||e||!r)?"xdg-open":ym}n.length>0&&o.push(...n),e.wait||(i.stdio="ignore",i.detached=!0)}"darwin"===vm&&n.length>0&&o.push("--args",...n),e.target&&o.push(e.target);const s=S.spawn(t,o,i);return e.wait?new Promise((t,r)=>{s.once("error",r),s.once("close",n=>{!e.allowNonzeroExitCode&&n>0?r(new Error(`Exited with code ${n}`)):t(s)})}):(s.unref(),s)};function _m(e){if("string"==typeof e||Array.isArray(e))return e;const{[Em]:t}=e;if(!t)throw new Error(`${Em} is not supported`);return t}function Tm({[vm]:e},{wsl:t}){if(t&&im)return _m(t);if(!e)throw new Error(`${vm} is not supported`);return _m(e)}const Sm={};sm(Sm,"chrome",()=>Tm({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}})),sm(Sm,"firefox",()=>Tm({darwin:"firefox",win32:"C:\\Program Files\\Mozilla Firefox\\firefox.exe",linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"})),sm(Sm,"edge",()=>Tm({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"})),sm(Sm,"browser",()=>"browser"),sm(Sm,"browserPrivate",()=>"browserPrivate");const Am=3e5;class Om extends gs{#i;constructor(e,t){super(e),this.#i=t}async login(e){const{scopes:t}=e,{port:r,onOpen:n}=this.#i.server,o=new cf,{verifier:i,challenge:s}=await o.generatePkceCodes(),a=await this._client.getAuthCodeUrl({scopes:t,redirectUri:`http://localhost:${r}`,codeChallenge:s,codeChallengeMethod:"S256"});return await((e,t)=>{if("string"!=typeof e)throw new TypeError("Expected a `target`");return Cm({...t,target:e})})(a),n&&n(a),((e,t,r)=>{const{port:n,timeout:o=Am}=r;return new Promise((i,s)=>{const a=setTimeout(()=>{c.close(),s(new ms("Authentication server timed out"))},o),c=H(async(o,u)=>{const l=G.parse(o.url??"",!0).query;if(!l.code){const e=new ps("No authorization code received");return u.writeHead(400,{"Content-Type":"text/html"}),u.end(e.message),c.close(),s(e)}try{const o=await e.acquireTokenByCode({code:Array.isArray(l.code)?l.code[0]:l.code,scopes:t,codeVerifier:r?.codeVerifier,redirectUri:`http://localhost:${n}`});u.writeHead(200,{"Content-Type":"text/html"}),u.end("Authentication successful! You can close this window."),i(o)}catch(e){const t=new ps("Authentication failed",{cause:e});u.writeHead(500,{"Content-Type":"text/html"}),u.end(`<b>${t.message}</b><br>${e.message}`),s(t)}finally{c.close(),clearTimeout(a)}}).listen(n)})})(this._client,t,{codeVerifier:i,port:r})}async acquireToken(e){const{scopes:t}=e??{scopes:[]};return null===await this.getAccount()?this.login({scopes:t}):super.acquireToken(e)}}const km={name:"auth",configure:()=>new Zp,initialize:async e=>{const t=await e.config.createConfigAsync(e);switch(t.mode){case"token_only":return new Xp(t.accessToken);case"interactive":{const{client:e,server:r}=t;if(!r)throw new Error("Server configuration is required for interactive mode");return new Om(e,{server:r})}default:return new gs(t.client)}}};class Rm{_operators;get operators(){return this._operators}constructor(e){this._operators=e&&"operators"in e?{...e.operators}:e??{}}add(e,t){if(Object.keys(this._operators).includes(e))throw Error(`Operator [${e}] already defined`);return this.set(e,t)}set(e,t){return this._operators[e]=t,this}remove(e){return delete this._operators[e],this}get(e){return this._operators[e]}process(e){return Object.values(this._operators).length?Ai(Object.values(this._operators)).pipe((t=(e,t)=>Promise.resolve(t(e)).then(t=>t??e),r=e,n=1,zo(function(e,o){var i=r;return Ui(e,o,function(e,r){return t(i,e,r)},n,function(e){i=e},!1,void 0,function(){return i=null})})),ts()):Oi(e);var t,r,n}}class Pm extends Rm{setHeader(e,t){const r=((e,t)=>r=>{const n=new Headers(r.headers);return n.append(e,t),{...r,headers:n}})(e,t);return this.set("header-"+e,r)}}class Nm extends Rm{}const Lm=()=>R.custom(e=>e===e?.toUpperCase(),e=>({code:R.ZodIssueCode.custom,validation:"uppercase",path:["method"],message:[`Provided HTTP method '${e}' must be in uppercase.`,"See RFC 7231 Section 4.1 for more information","https://www.rfc-editor.org/rfc/rfc7231#section-4.1"].join(" ")})),Dm=R.object({attributionReporting:R.object({eventSourceEligible:R.boolean().optional(),triggerEligible:R.boolean().optional()}).optional(),body:R.union([R.string(),R.instanceof(Blob),R.instanceof(ArrayBuffer),R.instanceof(FormData),R.instanceof(URLSearchParams),R.instanceof(ReadableStream)]).optional(),browsingTopics:R.boolean().optional(),cache:R.enum(["default","no-store","reload","no-cache","force-cache","only-if-cached"]).optional(),credentials:R.enum(["omit","same-origin","include"]).optional(),headers:R.record(R.string(),R.string()).optional().or(R.instanceof(Headers)),integrity:R.string().optional(),keepalive:R.boolean().optional(),method:Lm().pipe(R.enum(["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD","CONNECT","TRACE"],{errorMap:e=>{const{received:t,options:r}=e;return{message:["Invalid request method.",`Expected '${r.join(" | ")}', but received '${t}'.`,"See RFC 2615 Section 9 for more information","https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html"].join(" ")}}})).optional(),mode:R.enum(["same-origin","cors","no-cors","navigate","websocket"]).optional(),priority:R.enum(["low","high","auto"]).optional(),redirect:R.enum(["follow","error","manual"]).optional(),referrer:R.string().optional(),referrerPolicy:R.enum(["no-referrer","no-referrer-when-downgrade","origin","origin-when-cross-origin","same-origin","strict-origin","strict-origin-when-cross-origin","unsafe-url"]).optional(),signal:R.instanceof(AbortSignal).optional()}).extend({uri:R.string(),path:R.string().optional()}),xm=e=>e=>{const{error:t,success:r,data:n}=Lm().safeParse(e.method);if(e.method=r?n:e.method?.toUpperCase(),t)for(const e of t.errors)console.warn(e.message);return e},Mm=e=>e=>{const{strict:t,parse:r}={},n=t?Dm:Dm.passthrough();try{const t=n.parse(e);return r?t:void 0}catch(e){if(r)throw e;console.error("Invalid request options",e.message)}};class $m{_clients={};get clients(){return{...this._clients}}defaultHttpClientCtor;defaultHttpRequestHandler=new Pm({"capitalize-method":xm(),"request-validation":Mm()});constructor(e){this.defaultHttpClientCtor=e}hasClient(e){return Object.keys(this._clients).includes(e)}configureClient(e,t){const r="string"==typeof t?{baseUri:t}:t,n="function"==typeof r?{onCreate:r}:r;return this._clients[e]={...this._clients[e],...n},this}}class Um extends Error{}class Fm{config;get defaultHttpRequestHandler(){return this.config.defaultHttpRequestHandler}constructor(e){this.config=e}hasClient(e){return Object.keys(this.config.clients).includes(e)}createClient(e){const t=this._resolveConfig(e),{baseUri:r,defaultScopes:n=[],onCreate:o,ctor:i=this.config.defaultHttpClientCtor,requestHandler:s=this.defaultHttpRequestHandler}=t,a=new i(r||"",{requestHandler:s});return Object.assign(a,{defaultScopes:n}),o?.(a),a}createCustomClient(e){return this.createClient(e)}_resolveConfig(e){if("string"==typeof e){const r=this.config.clients[e];if(!r&&(t=e,new RegExp("^(https?:\\/\\/)?((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*(\\?[;&a-z\\d%_.~+=-]*)?(\\#[-a-z\\d_]*)?$","i").test(t)))return{baseUri:e};if(!r)throw new Um(`No registered http client for key [${e}]`);return r}var t;return e}}function jm(e,t){void 0===t&&(t={});var r=t.selector,n=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(r[n[o]]=e[n[o]])}return r}(t,["selector"]);return new Ho(function(t){var o=new AbortController,i=o.signal,s=!0,a=n.signal;if(a)if(a.aborted)o.abort();else{var c=function(){i.aborted||o.abort()};a.addEventListener("abort",c),t.add(function(){return a.removeEventListener("abort",c)})}var u=po(po({},n),{signal:i}),l=function(e){s=!1,t.error(e)};return fetch(e,u).then(function(e){r?bi(r(e)).subscribe(Ko(t,void 0,function(){s=!1,t.complete()},l)):(s=!1,t.next(e),t.complete())}).catch(l),function(){s&&o.abort()}})}const Bm=async e=>{if(204===e.status)return Promise.resolve();try{const t=await e.json();if(!e.ok)throw new er("network response was not OK",e,{data:t});return t}catch(t){if(t instanceof er)throw t;throw new er("failed to parse response",e,{cause:t})}},qm=async e=>{if(!e.ok)throw new Error("network response was not OK");if(204===e.status)throw new Error("no content");const t=e.headers.get("content-disposition")?.split(";").find(e=>e.includes("filename="))?.replace("filename=","")?.trim();try{return{filename:t,blob:await e.blob()}}catch(e){throw Error("failed to parse response")}},Hm=e=>{try{return JSON.parse(e)}catch{return e}};function*Gm(e,t){const r=e.split("\n\n"),n=t?.dataParser||Hm;for(const e of r){if(!e.trim())continue;const t=e.split("\n").reduce((e,t)=>{if(!t)return e;const r=t.indexOf(":");if(-1===r)return e;const o=t.slice(0,r).trim(),i=t.slice(r+1).trim();return"data"===o?e.data=n(i):e[o]=i,e},{});Object.keys(t).length&&(yield t)}}const zm=e=>t=>{if(!t.ok)throw new tr(`HTTP error! Status: ${t.status}`,t);if(!t.body)throw new tr("Response body is not readable",t);if(!t.headers.get("Content-Type")?.includes("text/event-stream"))throw new tr("Response is not a text/event-stream",t);const r=t.body.getReader();return Ai(async function*(e,t){const r=!!t?.skipHeartbeats,n=t?.eventFilter?Array.isArray(t.eventFilter)?t.eventFilter:[t.eventFilter]:null,o=new TextDecoder;for(;;){const{done:i,value:s}=await e.read();if(i)break;const a=Gm(o.decode(s,{stream:!0}),{dataParser:t?.dataParser});for(const e of a)if(e.retry)await new Promise(t=>setTimeout(t,Number.parseInt(e.retry??"300",10)));else{if(r){if(!e.event&&!e.data&&!e.id)continue;if(e.event&&["heartbeat","ping"].includes(e.event))continue}(!n||e.event&&n.includes(e.event))&&(yield e)}}}(r,{dataParser:e?.dataParser,skipHeartbeats:e?.skipHeartbeats,eventFilter:e?.eventFilter})).pipe(os(e?.abortSignal?Hi(e.abortSignal,"abort"):ci),es(async()=>{await r.cancel().catch(()=>{}),r.releaseLock()}))};class Km{uri;requestHandler;responseHandler;_request$=new Wo;_response$=new Wo;_abort$=new Wo;get request$(){return this._request$.asObservable()}get response$(){return this._response$.asObservable()}constructor(e,t){this.uri=e,this.requestHandler=new Pm(t?.requestHandler),this.responseHandler=new Nm(t?.responseHandler),this._init()}_init(){}fetch$(e,t){return this._fetch$(e,t)}fetch(e,t){return Pi(this.fetch$(e,t))}fetchAsync(e,t){return this.fetch(e,t)}json$(e,t){const r="object"==typeof t?.body?JSON.stringify(t?.body):t?.body,n=t?.selector??Bm,o=new Headers(t?.headers);return o.append("Accept","application/json"),o.append("Content-Type","application/json"),this.fetch$(e,{...t,body:r,selector:n,headers:o})}json(e,t){return Pi(this.json$(e,t))}blob$(e,t){const r=t?.selector??qm,n={...t,selector:r};return this.fetch$(e,n)}blob(e,t){return Pi(this.blob$(e,t))}sse$(e,t,r){const n=new Headers(t?.headers);n.append("Accept","text/event-stream"),n.append("Content-Type","text/event-stream"),n.append("Cache-Control","no-cache"),n.append("Connection","keep-alive");const o=zm({...r,abortSignal:t?.signal});return this._fetch$(e,{selector:o,...t,headers:n})}jsonAsync(e,t){return this.json(e,t)}execute(e,t,r){return this[e](t,r)}abort(){this._abort$.next()}_fetch$(e,t){const{selector:r,...n}=t||{},o=Oi({...n,uri:this._resolveUrl(e)}).pipe(ns(e=>this._prepareRequest(e)),is(e=>this._request$.next(e)),ns(({uri:e,path:t,...r})=>jm(e,r)),ns(e=>this._prepareResponse(e)),is(e=>this._response$.next(e)),ns(e=>{if(r)try{return r(e)}catch(t){throw new Xt("failed to execute response selector",e,{cause:t})}return Oi(e)}),os(this._abort$));return o}_prepareRequest(e){return this.requestHandler.process(e)}_prepareResponse(e){return this.responseHandler.process(e)}_resolveUrl(e){const{origin:t,pathname:r}=new URL(this.uri,this.uri.startsWith("http")?void 0:window.location.origin),n=[r,e].join("/").replace(/\/{2,}/g,"/");return new URL(n,t).href}}class Vm extends Km{defaultScopes=[];fetch$(e,t){const r=Object.assign(t||{},{scopes:this.defaultScopes.concat(t?.scopes||[])});return super._fetch$(e,r)}}const Ym={name:"http",configure:()=>new $m(Vm),initialize:async({config:e,hasModule:t,requireInstance:r})=>{const n=new Fm(e);if(t("auth")){const e=await r("auth");n.defaultHttpRequestHandler.set("MSAL",async t=>{const{scopes:r=[]}=t;if(r.length){const n=await e.acquireAccessToken({scopes:r});if(n){const e=new Headers(t.headers);return e.set("Authorization",`Bearer ${n}`),{...t,headers:e}}}})}return n}},Wm=(...e)=>t=>t.pipe(function(e,t){return Co(t)?Fi(e,t,1):Fi(e,1)}(...e)),Qm=(...e)=>t=>t.pipe(Fi(...e)),Jm=(...e)=>t=>t.pipe(ns(...e)),Zm=e=>e.pipe(xi(e=>e.value));var Xm=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function eg(e){if(!function(e){return"string"==typeof e&&Xm.test(e)}(e))throw TypeError("Invalid UUID");let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,255&t,(t=parseInt(e.slice(9,13),16))>>>8,255&t,(t=parseInt(e.slice(14,18),16))>>>8,255&t,(t=parseInt(e.slice(19,23),16))>>>8,255&t,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,255&t)}const tg=[];for(let e=0;e<256;++e)tg.push((e+256).toString(16).slice(1));function rg(e,t=0){return(tg[e[t+0]]+tg[e[t+1]]+tg[e[t+2]]+tg[e[t+3]]+"-"+tg[e[t+4]]+tg[e[t+5]]+"-"+tg[e[t+6]]+tg[e[t+7]]+"-"+tg[e[t+8]]+tg[e[t+9]]+"-"+tg[e[t+10]]+tg[e[t+11]]+tg[e[t+12]]+tg[e[t+13]]+tg[e[t+14]]+tg[e[t+15]]).toLowerCase()}let ng;const og=new Uint8Array(16);function ig(e,t,r,n,o,i){const s="string"==typeof r?function(e){e=unescape(encodeURIComponent(e));const t=new Uint8Array(e.length);for(let r=0;r<e.length;++r)t[r]=e.charCodeAt(r);return t}(r):r,a="string"==typeof n?eg(n):n;if("string"==typeof n&&(n=eg(n)),16!==n?.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+s.length);if(c.set(a),c.set(s,a.length),c=t(c),c[6]=15&c[6]|e,c[8]=63&c[8]|128,o){i=i||0;for(let e=0;e<16;++e)o[i+e]=c[e];return o}return rg(c)}var sg={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ag(e,t,r){if(sg.randomUUID&&!e)return sg.randomUUID();const n=(e=e||{}).random??e.rng?.()??function(){if(!ng){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ng=crypto.getRandomValues.bind(crypto)}return ng(og)}();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=15&n[6]|64,n[8]=63&n[8]|128,rg(n)}function cg(e,t,r,n){switch(e){case 0:return t&r^~t&n;case 1:case 3:return t^r^n;case 2:return t&r^t&n^r&n}}function ug(e,t){return e<<t|e>>>32-t}function lg(e){const t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520],n=new Uint8Array(e.length+1);n.set(e),n[e.length]=128;const o=(e=n).length/4+2,i=Math.ceil(o/16),s=new Array(i);for(let t=0;t<i;++t){const r=new Uint32Array(16);for(let n=0;n<16;++n)r[n]=e[64*t+4*n]<<24|e[64*t+4*n+1]<<16|e[64*t+4*n+2]<<8|e[64*t+4*n+3];s[t]=r}s[i-1][14]=8*(e.length-1)/Math.pow(2,32),s[i-1][14]=Math.floor(s[i-1][14]),s[i-1][15]=8*(e.length-1)&4294967295;for(let e=0;e<i;++e){const n=new Uint32Array(80);for(let t=0;t<16;++t)n[t]=s[e][t];for(let e=16;e<80;++e)n[e]=ug(n[e-3]^n[e-8]^n[e-14]^n[e-16],1);let o=r[0],i=r[1],a=r[2],c=r[3],u=r[4];for(let e=0;e<80;++e){const r=Math.floor(e/20),s=ug(o,5)+cg(r,i,a,c)+u+t[r]+n[e]>>>0;u=c,c=a,a=ug(i,30)>>>0,i=o,o=s}r[0]=r[0]+o>>>0,r[1]=r[1]+i>>>0,r[2]=r[2]+a>>>0,r[3]=r[3]+c>>>0,r[4]=r[4]+u>>>0}return Uint8Array.of(r[0]>>24,r[0]>>16,r[0]>>8,r[0],r[1]>>24,r[1]>>16,r[1]>>8,r[1],r[2]>>24,r[2]>>16,r[2]>>8,r[2],r[3]>>24,r[3]>>16,r[3]>>8,r[3],r[4]>>24,r[4]>>16,r[4]>>8,r[4])}function hg(e,t,r,n){return ig(80,lg,e,t,r,n)}hg.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",hg.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";class dg extends Error{type;request;constructor(e,t){super(t.message,{cause:t.cause}),this.type=e,this.name="QueryClientError",this.request=t.request}}function fg(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];if("production"!==process.env.NODE_ENV){var o=ey[e],i=o?"function"==typeof o?o.apply(null,r):o:"unknown error nr: "+e;throw Error("[Immer] "+i)}throw Error("[Immer] minified error nr: "+e+(r.length?" "+r.map(function(e){return"'"+e+"'"}).join(","):"")+". Find the full error at: https://bit.ly/3cXEKWf")}function pg(e){return!!e&&!!e[Xg]}function mg(e){var t;return!!e&&(function(e){if(!e||"object"!=typeof e)return!1;var t=Object.getPrototypeOf(e);if(null===t)return!0;var r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object||"function"==typeof r&&Function.toString.call(r)===ty}(e)||Array.isArray(e)||!!e[Zg]||!!(null===(t=e.constructor)||void 0===t?void 0:t[Zg])||bg(e)||wg(e))}function gg(e,t,r){void 0===r&&(r=!1),0===yg(e)?(r?Object.keys:ry)(e).forEach(function(n){r&&"symbol"==typeof n||t(n,e[n],e)}):e.forEach(function(r,n){return t(n,r,e)})}function yg(e){var t=e[Xg];return t?t.i>3?t.i-4:t.i:Array.isArray(e)?1:bg(e)?2:wg(e)?3:0}function vg(e,t){return 2===yg(e)?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Eg(e,t,r){var n=yg(e);2===n?e.set(t,r):3===n?e.add(r):e[t]=r}function bg(e){return Yg&&e instanceof Map}function wg(e){return Wg&&e instanceof Set}function Ig(e){return e.o||e.t}function Cg(e){if(Array.isArray(e))return Array.prototype.slice.call(e);var t=ny(e);delete t[Xg];for(var r=ry(t),n=0;n<r.length;n++){var o=r[n],i=t[o];!1===i.writable&&(i.writable=!0,i.configurable=!0),(i.get||i.set)&&(t[o]={configurable:!0,writable:!0,enumerable:i.enumerable,value:e[o]})}return Object.create(Object.getPrototypeOf(e),t)}function _g(e,t){return void 0===t&&(t=!1),Sg(e)||pg(e)||!mg(e)||(yg(e)>1&&(e.set=e.add=e.clear=e.delete=Tg),Object.freeze(e),t&&gg(e,function(e,t){return _g(t,!0)},!0)),e}function Tg(){fg(2)}function Sg(e){return null==e||"object"!=typeof e||Object.isFrozen(e)}function Ag(e){var t=oy[e];return t||fg(18,e),t}function Og(){return"production"===process.env.NODE_ENV||Kg||fg(0),Kg}function kg(e,t){t&&(Ag("Patches"),e.u=[],e.s=[],e.v=t)}function Rg(e){Pg(e),e.p.forEach(Lg),e.p=null}function Pg(e){e===Kg&&(Kg=e.l)}function Ng(e){return Kg={p:[],l:Kg,h:e,m:!0,_:0}}function Lg(e){var t=e[Xg];0===t.i||1===t.i?t.j():t.g=!0}function Dg(e,t){t._=t.p.length;var r=t.p[0],n=void 0!==e&&e!==r;return t.h.O||Ag("ES5").S(t,e,n),n?(r[Xg].P&&(Rg(t),fg(4)),mg(e)&&(e=xg(t,e),t.l||$g(t,e)),t.u&&Ag("Patches").M(r[Xg].t,e,t.u,t.s)):e=xg(t,r,[]),Rg(t),t.u&&t.v(t.u,t.s),e!==Jg?e:void 0}function xg(e,t,r){if(Sg(t))return t;var n=t[Xg];if(!n)return gg(t,function(o,i){return Mg(e,n,t,o,i,r)},!0),t;if(n.A!==e)return t;if(!n.P)return $g(e,n.t,!0),n.t;if(!n.I){n.I=!0,n.A._--;var o=4===n.i||5===n.i?n.o=Cg(n.k):n.o,i=o,s=!1;3===n.i&&(i=new Set(o),o.clear(),s=!0),gg(i,function(t,i){return Mg(e,n,o,t,i,r,s)}),$g(e,o,!1),r&&e.u&&Ag("Patches").N(n,r,e.u,e.s)}return n.o}function Mg(e,t,r,n,o,i,s){if("production"!==process.env.NODE_ENV&&o===r&&fg(5),pg(o)){var a=xg(e,o,i&&t&&3!==t.i&&!vg(t.R,n)?i.concat(n):void 0);if(Eg(r,n,a),!pg(a))return;e.m=!1}else s&&r.add(o);if(mg(o)&&!Sg(o)){if(!e.h.D&&e._<1)return;xg(e,o),t&&t.A.l||$g(e,o)}}function $g(e,t,r){void 0===r&&(r=!1),!e.l&&e.h.D&&e.m&&_g(t,r)}function Ug(e,t){var r=e[Xg];return(r?Ig(r):e)[t]}function Fg(e,t){if(t in e)for(var r=Object.getPrototypeOf(e);r;){var n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=Object.getPrototypeOf(r)}}function jg(e){e.P||(e.P=!0,e.l&&jg(e.l))}function Bg(e){e.o||(e.o=Cg(e.t))}function qg(e,t,r){var n=bg(t)?Ag("MapSet").F(t,r):wg(t)?Ag("MapSet").T(t,r):e.O?function(e,t){var r=Array.isArray(e),n={i:r?1:0,A:t?t.A:Og(),P:!1,I:!1,R:{},l:t,t:e,k:null,o:null,j:null,C:!1},o=n,i=iy;r&&(o=[n],i=sy);var s=Proxy.revocable(o,i),a=s.revoke,c=s.proxy;return n.k=c,n.j=a,c}(t,r):Ag("ES5").J(t,r);return(r?r.A:Og()).p.push(n),n}function Hg(e){return pg(e)||fg(22,e),function e(t){if(!mg(t))return t;var r,n=t[Xg],o=yg(t);if(n){if(!n.P&&(n.i<4||!Ag("ES5").K(n)))return n.t;n.I=!0,r=Gg(t,o),n.I=!1}else r=Gg(t,o);return gg(r,function(t,o){n&&function(e,t){return 2===yg(e)?e.get(t):e[t]}(n.t,t)===o||Eg(r,t,e(o))}),3===o?new Set(r):r}(e)}function Gg(e,t){switch(t){case 2:return new Map(e);case 3:return Array.from(e)}return Cg(e)}var zg,Kg,Vg="undefined"!=typeof Symbol&&"symbol"==typeof Symbol("x"),Yg="undefined"!=typeof Map,Wg="undefined"!=typeof Set,Qg="undefined"!=typeof Proxy&&void 0!==Proxy.revocable&&"undefined"!=typeof Reflect,Jg=Vg?Symbol.for("immer-nothing"):((zg={})["immer-nothing"]=!0,zg),Zg=Vg?Symbol.for("immer-draftable"):"__$immer_draftable",Xg=Vg?Symbol.for("immer-state"):"__$immer_state",ey={0:"Illegal state",1:"Immer drafts cannot have computed properties",2:"This object has been frozen and should not be mutated",3:function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},4:"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",5:"Immer forbids circular references",6:"The first or second argument to `produce` must be a function",7:"The third argument to `produce` must be a function or undefined",8:"First argument to `createDraft` must be a plain object, an array, or an immerable object",9:"First argument to `finishDraft` must be a draft returned by `createDraft`",10:"The given draft is already finalized",11:"Object.defineProperty() cannot be used on an Immer draft",12:"Object.setPrototypeOf() cannot be used on an Immer draft",13:"Immer only supports deleting array indices",14:"Immer only supports setting array indices and the 'length' property",15:function(e){return"Cannot apply patch, path doesn't resolve: "+e},16:'Sets cannot have "replace" patches.',17:function(e){return"Unsupported patch operation: "+e},18:function(e){return"The plugin for '"+e+"' has not been loaded into Immer. To enable the plugin, import and call `enable"+e+"()` when initializing your application."},20:"Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available",21:function(e){return"produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '"+e+"'"},22:function(e){return"'current' expects a draft, got: "+e},23:function(e){return"'original' expects a draft, got: "+e},24:"Patching reserved attributes like __proto__, prototype and constructor is not allowed"},ty=""+Object.prototype.constructor,ry="undefined"!=typeof Reflect&&Reflect.ownKeys?Reflect.ownKeys:void 0!==Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Object.getOwnPropertyNames,ny=Object.getOwnPropertyDescriptors||function(e){var t={};return ry(e).forEach(function(r){t[r]=Object.getOwnPropertyDescriptor(e,r)}),t},oy={},iy={get:function(e,t){if(t===Xg)return e;var r=Ig(e);if(!vg(r,t))return function(e,t,r){var n,o=Fg(t,r);return o?"value"in o?o.value:null===(n=o.get)||void 0===n?void 0:n.call(e.k):void 0}(e,r,t);var n=r[t];return e.I||!mg(n)?n:n===Ug(e.t,t)?(Bg(e),e.o[t]=qg(e.A.h,n,e)):n},has:function(e,t){return t in Ig(e)},ownKeys:function(e){return Reflect.ownKeys(Ig(e))},set:function(e,t,r){var n=Fg(Ig(e),t);if(null==n?void 0:n.set)return n.set.call(e.k,r),!0;if(!e.P){var o=Ug(Ig(e),t),i=null==o?void 0:o[Xg];if(i&&i.t===r)return e.o[t]=r,e.R[t]=!1,!0;if(function(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t}(r,o)&&(void 0!==r||vg(e.t,t)))return!0;Bg(e),jg(e)}return e.o[t]===r&&(void 0!==r||t in e.o)||Number.isNaN(r)&&Number.isNaN(e.o[t])||(e.o[t]=r,e.R[t]=!0),!0},deleteProperty:function(e,t){return void 0!==Ug(e.t,t)||t in e.t?(e.R[t]=!1,Bg(e),jg(e)):delete e.R[t],e.o&&delete e.o[t],!0},getOwnPropertyDescriptor:function(e,t){var r=Ig(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n?{writable:!0,configurable:1!==e.i||"length"!==t,enumerable:n.enumerable,value:r[t]}:n},defineProperty:function(){fg(11)},getPrototypeOf:function(e){return Object.getPrototypeOf(e.t)},setPrototypeOf:function(){fg(12)}},sy={};gg(iy,function(e,t){sy[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}}),sy.deleteProperty=function(e,t){return"production"!==process.env.NODE_ENV&&isNaN(parseInt(t))&&fg(13),sy.set.call(this,e,t,void 0)},sy.set=function(e,t,r){return"production"!==process.env.NODE_ENV&&"length"!==t&&isNaN(parseInt(t))&&fg(14),iy.set.call(this,e[0],t,r,e[0])};var ay=function(){function e(e){var t=this;this.O=Qg,this.D=!0,this.produce=function(e,r,n){if("function"==typeof e&&"function"!=typeof r){var o=r;r=e;var i=t;return function(e){var t=this;void 0===e&&(e=o);for(var n=arguments.length,s=Array(n>1?n-1:0),a=1;a<n;a++)s[a-1]=arguments[a];return i.produce(e,function(e){var n;return(n=r).call.apply(n,[t,e].concat(s))})}}var s;if("function"!=typeof r&&fg(6),void 0!==n&&"function"!=typeof n&&fg(7),mg(e)){var a=Ng(t),c=qg(t,e,void 0),u=!0;try{s=r(c),u=!1}finally{u?Rg(a):Pg(a)}return"undefined"!=typeof Promise&&s instanceof Promise?s.then(function(e){return kg(a,n),Dg(e,a)},function(e){throw Rg(a),e}):(kg(a,n),Dg(s,a))}if(!e||"object"!=typeof e){if(void 0===(s=r(e))&&(s=e),s===Jg&&(s=void 0),t.D&&_g(s,!0),n){var l=[],h=[];Ag("Patches").M(e,s,l,h),n(l,h)}return s}fg(21,e)},this.produceWithPatches=function(e,r){if("function"==typeof e)return function(r){for(var n=arguments.length,o=Array(n>1?n-1:0),i=1;i<n;i++)o[i-1]=arguments[i];return t.produceWithPatches(r,function(t){return e.apply(void 0,[t].concat(o))})};var n,o,i=t.produce(e,r,function(e,t){n=e,o=t});return"undefined"!=typeof Promise&&i instanceof Promise?i.then(function(e){return[e,n,o]}):[i,n,o]},"boolean"==typeof(null==e?void 0:e.useProxies)&&this.setUseProxies(e.useProxies),"boolean"==typeof(null==e?void 0:e.autoFreeze)&&this.setAutoFreeze(e.autoFreeze)}var t=e.prototype;return t.createDraft=function(e){mg(e)||fg(8),pg(e)&&(e=Hg(e));var t=Ng(this),r=qg(this,e,void 0);return r[Xg].C=!0,Pg(t),r},t.finishDraft=function(e,t){var r=e&&e[Xg];"production"!==process.env.NODE_ENV&&(r&&r.C||fg(9),r.I&&fg(10));var n=r.A;return kg(n,t),Dg(void 0,n)},t.setAutoFreeze=function(e){this.D=e},t.setUseProxies=function(e){e&&!Qg&&fg(20),this.O=e},t.applyPatches=function(e,t){var r;for(r=t.length-1;r>=0;r--){var n=t[r];if(0===n.path.length&&"replace"===n.op){e=n.value;break}}r>-1&&(t=t.slice(r+1));var o=Ag("Patches").$;return pg(e)?o(e,t):this.produce(e,function(e){return o(e,t)})},e}(),cy=new ay,uy=cy.produce;cy.produceWithPatches.bind(cy),cy.setAutoFreeze.bind(cy),cy.setUseProxies.bind(cy),cy.applyPatches.bind(cy),cy.createDraft.bind(cy),cy.finishDraft.bind(cy);const ly=(...e)=>Ki(t=>e.includes(t.type));class hy extends Ho{#s=new Wo;#a;get action$(){return this.#s.asObservable()}get value(){return this.#a.value}get closed(){return this.#a.closed||this.#s.closed}constructor(e,t){super(e=>this.#a.subscribe(e));const r="getInitialState"in e?e.getInitialState():t;this.#a=new Jo(r),this.#s.pipe(function(e,t){return zo(Yi(e,t,arguments.length>=2,!0))}(e,r),Qi()).subscribe(this.#a),this.reset=()=>this.#a.next(r)}reset;next(e){this.#s.next(e)}select(e,t){return this.#a.pipe(xi(e),Qi(t))}addEffect(e,t){const r="function"==typeof e?this.action$:Array.isArray(e)?this.action$.pipe(ly(...e)):this.action$.pipe(ly(e)),n=t||e;return r.pipe(Fi(e=>Ai(new Promise((t,r)=>{try{t(n(e,this.value))}catch(e){r(e)}})).pipe(Vi(e=>(console.warn("unhandled effect",e),ci)))),Ki(e=>!!e),Ci(si)).subscribe(this.#s)}addEpic(e){return this.addFlow(e)}addFlow(e){const t=e(this.action$,this);if(!t)throw new TypeError(`addEpic: one of the provided effects "${e.name||"<anonymous>"}" does not return a stream. Double check you're not missing a return statement!`);return t.pipe(Vi(e=>(console.trace("unhandled exception, epic closed!",e),ci)),Ci(si)).subscribe(this.#s)}unsubscribe(){this.#s.unsubscribe(),this.#a.unsubscribe()}complete(){this.#s.complete(),this.#a.complete()}asObservable(){return this.#a.asObservable()}}function dy(e,t){function r(...r){if(t){const n=t(...r);if(!n)throw new Error("prepareAction did not return an object");return{type:e,payload:n.payload,..."meta"in n&&{meta:n.meta},..."error"in n&&{error:n.error}}}return{type:e,payload:r[0]}}return r.toString=()=>`${e}`,r.type=e,r.match=t=>t.type===e,r}const fy="::";function py(e,t,r,n){const o=dy([e,"request"].join(fy),t);return r&&Object.assign(o,{success:dy([e,"success"].join(fy),r)}),n&&Object.assign(o,{failure:dy([e,"failure"].join(fy),n)}),o}function my(e){return mg(e)?uy(e,()=>{}):e}function gy(e,t){const[r,n,o]=function(e){const t={},r=[];let n;const o={addCase(e,i){if("production"!==process.env.NODE_ENV){if(r.length>0)throw new Error("`builder.addCase` should only be called before calling `builder.addMatcher`");if(n)throw new Error("`builder.addCase` should only be called before calling `builder.addDefaultCase`")}const s="string"==typeof e?e:e.type;if(s in t)throw new Error("addCase cannot be called with two reducers for the same action type");return t[s]=i,o},addMatcher(e,t){if("production"!==process.env.NODE_ENV&&n)throw new Error("`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");return r.push({matcher:e,reducer:t}),o},addDefaultCase(e){if("production"!==process.env.NODE_ENV&&n)throw new Error("`builder.addDefaultCase` can only be called once");return n=e,o}};return e(o),[t,r,n]}(t);let i;if(function(e){return"function"==typeof e}(e))i=()=>my(e());else{const t=my(e);i=()=>t}function s(e,t){let s=[r[t.type],...n.filter(({matcher:e})=>e(t)).map(({reducer:e})=>e)];return o&&0===s.filter(e=>!!e).length&&(s=[o]),s.reduce((e,r)=>{if(r){if(pg(e)){const n=r(e,t);return void 0===n?e:n}if(mg(e))return uy(e,e=>r(e,t));{const n=r(e,t);if(void 0===n){if(null===e)return e;throw Error("A case reducer on a non-draftable value must not return undefined")}return n}}return e},e??i())}return s.getInitialState=i,s}const yy={request:dy("client/request",(e,t)=>({payload:{args:e,options:t},meta:{transaction:ag(),created:Date.now()}})),execute:py("client/execute",e=>({payload:e,meta:{transaction:e,created:Date.now()}}),e=>({payload:e,meta:{transaction:e.transaction,created:Date.now()}}),(e,t)=>({payload:e,meta:{transaction:t,created:Date.now()}})),cancel:dy("client/cancel",(e,t)=>({payload:{transaction:e,reason:t},meta:{transaction:e,created:Date.now()}})),error:dy("client/error",(e,t)=>({payload:{transaction:e,error:t},meta:{transaction:e,created:Date.now()}}))},vy=e=>e.pipe(Ki(yy.request.match),xi(e=>yy.execute(e.meta.transaction))),Ey=e=>{const t=Number(e);if(Object.values(by).includes(t))return t;if(isNaN(t))return(e=>{if("string"!=typeof e)throw new Error("Expected LogLevel key to be a string.");const t=e.toLowerCase(),r=Object.keys(by).find(e=>e.toLowerCase()===t);if(!r)throw new Error(`Failed to parse LogLevel from string: ${e}.`);return by[r]})(e);throw Error(`Invalid log level: ${e}`)};var by;!function(e){e[e.None=0]="None",e[e.Error=1]="Error",e[e.Warning=2]="Warning",e[e.Info=3]="Info",e[e.Debug=4]="Debug"}(by||(by={}));const wy=(()=>{const e=process.env.FUSION_LOG_LEVEL;if(e)try{return Ey(e)}catch(e){return"development"===process.env.NODE_ENV?by.Debug:by.Error}return by.Error})();class Iy{level=wy;version="1.1.5-next.0";_log$=new Wo;get log(){return this._log$.pipe(Ki(e=>this.level>=e.lvl))}debug(...e){this._log$.next({lvl:by.Debug,msg:this._createMessage(by.Debug,...e)})}info(...e){this._log$.next({lvl:by.Info,msg:this._createMessage(by.Info,...e)})}warn(...e){this._log$.next({lvl:by.Warning,msg:this._createMessage(by.Warning,...e)})}error(...e){this._log$.next({lvl:by.Error,msg:this._createMessage(by.Error,...e)})}}class Cy extends Iy{title;subtitle;constructor(e,t){super(),this.title=e,this.subtitle=t,this.log.subscribe(({lvl:e,msg:t})=>{switch(e){case by.Debug:console.debug(...t);break;case by.Info:console.info(...t);break;case by.Warning:console.warn(...t);break;case by.Error:console.error(...t)}})}_createMessage(e,...t){return[this._formatTitle(e),...t]}_formatTitle(e){const t=we.magenta([this.title,this.subtitle].filter(e=>!!e).join(" - "));switch(e){case by.Warning:case by.Error:return we.bold(t)}return t}createSubLogger(e,t,r){const n=new Cy(`${this.title}::${e}`,t??this.subtitle);return n.level=void 0===r?this.level:r,n}}class _y extends Ho{#c=new Jo("idle");get status(){return this.#c.value}get status$(){return this.#c.asObservable()}#u;#l;get transaction(){return this.#l}created=Date.now();get closed(){return"complete"===this.status||"error"===this.status||"canceled"===this.status}constructor(e,t,r){super(t=>{const{transaction:n}=this,o=e.action$.pipe(Ki(e=>e.meta.transaction===n));t.add(e.state$.pipe(Ki(e=>!!e[n]),xi(e=>e[n])).subscribe(e=>{this.#c.next(e.status)})),t.add(o.pipe(Ki(yy.execute.success.match),xi(({payload:e})=>e)).subscribe(e=>{this.#c.next("complete"),t.next(e),t.complete()})),t.add(o.pipe(Ki(yy.error.match),xi(({payload:e})=>e)).subscribe(e=>{this.#c.next("error"),t.error(e.error)})),t.add(o.pipe(Ki(yy.cancel.match)).subscribe(e=>{this.#c.next("canceled"),t.error(new dg("abort",{message:e.payload.reason||`job: ${n} was canceled`,request:this.#u.getRequest(e.meta.transaction)}))})),r?.signal&&t.add(Hi(r?.signal,"abort").pipe(xi(()=>yy.cancel(n,`job: ${n} was aborted on signal from caller: ${r?.ref}`))).subscribe(t=>e.next(t))),t.add(()=>{this.complete()})}),this.#u=e;const n=yy.request(t,{ref:r?.ref,retry:r?.retry});this.#l=n.meta.transaction,this.#u.next(n)}complete(e){this.closed||this.cancel(e??`job: ${this.transaction} was completed`)}cancel(e){const t=this.transaction;this.#u.cancel(t,e??`job: ${t} was canceled`)}[Symbol.dispose](){this.complete()}}class Ty extends Ho{#a;#h;#d;get closed(){return this.#a.closed}get state$(){return this.#a.asObservable()}get action$(){return this.#a.action$}get success$(){return this.action$.pipe(Ki(yy.execute.success.match),xi(({payload:e})=>e))}get error$(){return this.action$.pipe(ly("client/error"),ss(this.#a),xi(([e,t])=>{const{payload:r,meta:{transaction:n}}=e,o=t[n];return new dg("error",{request:o,message:`job: ${n} failed`,cause:r})}))}constructor(e,t){super(e=>this.#a.subscribe(e)),this.#a=new hy(((e={})=>gy(e,e=>{e.addCase(yy.request,(e,t)=>{e[t.meta.transaction]={...t.payload,...t.meta,execution:[],errors:[],status:"idle"}}),e.addCase(yy.execute,(e,t)=>{const r=e[t.payload];r&&(r.execution.push(Date.now()),r.status="active")}),e.addCase(yy.execute.success,(e,t)=>{delete e[t.payload.transaction]}),e.addCase(yy.execute.failure,(e,t)=>{const r=e[t.meta.transaction];r&&(r.errors.push(t.payload),r.status="failed")}),e.addCase(yy.error,(e,t)=>{delete e[t.meta.transaction]}),e.addCase(yy.cancel,(e,t)=>{delete e[t.meta.transaction]})}))({})),this.#h=new Ao(()=>this.#a.complete()),this.#h.add(this.#a.addFlow(vy)),this.#h.add(this.#a.addFlow((e=>(t,r)=>t.pipe(Ki(yy.execute.match),ss(r),Fi(([r,n])=>{const o=r.payload,i=n[o],s=new AbortController,a=t.pipe(Ki(yy.cancel.match),Ki(e=>e.payload.transaction===o),is(()=>{s.signal.aborted||s.abort()}));try{return Ai(e(i.args,s.signal)).pipe(xi(e=>yy.execute.success({...i,status:"complete",completed:Date.now(),value:e})),Vi(e=>Oi(yy.execute.failure(e,o))),os(a))}catch(e){return Oi(yy.execute.failure(e,o))}})))(e))),this.#h.add(this.#a.addFlow((e=>(t,r)=>t.pipe(Ki(yy.execute.failure.match),ss(r),Fi(([t,n])=>{const{transaction:o}=t.meta,i=n[o];if(!i)return Oi(yy.error(o,new dg("error",{message:"request not found, cannot retry request, most likely removed while scheduled for retry!"})));const s=i.execution.length,a=Object.assign({},e,i.options?.retry),c=i.errors?.slice(-1)[0]??new dg("error",{message:"no errors registered for request!",request:i});if(s>a.count){const e=0===a.count?c:new dg("error",{message:"maximum retries executed!",cause:i.errors,request:i});return Oi(yy.error(o,e))}return("function"==typeof a.delay?Ai(a.delay(c)).pipe(Vi(e=>Oi(yy.error(o,new dg("error",{message:"retry delay callback failed!",cause:[...i.errors??[],e],request:i}))))):zi(a.delay)).pipe(ss(r),Ki(([e,t])=>!!t[o]),is(([,e])=>{if(!e[o])throw new dg("error",{message:"request not found, most likely removed while scheduled for retry",cause:i.errors,request:i})}),xi(()=>yy.execute(o)))})))(Object.assign({count:0,delay:0},t?.retry)))),this.#d=t?.logger??new Cy("QueryClient"),this.#a.addEffect(yy.request.type,({payload:e,meta:{transaction:t}})=>{this.#d.debug("Job requested",{transaction:t,payload:e})}),this.#a.addEffect(yy.execute.type,({payload:e,meta:{transaction:t}})=>{this.#d.debug("Job executing",{transaction:t,payload:e})}),this.#a.addEffect(yy.execute.success.type,({payload:e})=>{this.#d.info("Job complete",{...e})}),this.#a.addEffect(yy.execute.failure.type,({payload:e,meta:{transaction:t}})=>{this.#d.debug("Job failed",{transaction:t,payload:e})}),this.#a.addEffect(yy.cancel.type,({payload:{reason:e},meta:{transaction:t}})=>{this.#d.debug("Job canceled",{transaction:t,reason:e})}),this.#a.addEffect(yy.error.type,({payload:{transaction:e,error:t}})=>{this.#d.error("Job error",{transaction:e,error:t})})}next(e){this.#a.next(e)}query(e,t){const r=new _y(this,e,t),n=r.pipe(function(e){void 0===e&&(e={});var t=e.connector,r=void 0===t?function(){return new Wo}:t,n=e.resetOnError,o=void 0===n||n,i=e.resetOnComplete,s=void 0===i||i,a=e.resetOnRefCountZero,c=void 0===a||a;return function(e){var t,n,i,a=0,u=!1,l=!1,h=function(){null==n||n.unsubscribe(),n=void 0},d=function(){h(),t=i=void 0,u=l=!1},f=function(){var e=t;d(),null==e||e.unsubscribe()};return zo(function(e,p){a++,l||u||h();var m=i=null!=i?i:r();p.add(function(){0!==--a||l||u||(n=rs(f,c))}),m.subscribe(p),!t&&a>0&&(t=new Uo({next:function(e){return m.next(e)},error:function(e){l=!0,h(),n=rs(d,o,e),m.error(e)},complete:function(){u=!0,h(),n=rs(d,s),m.complete()}}),bi(e).subscribe(t))})(e)}}({connector:()=>new Xo,resetOnRefCountZero:!1}));return Object.defineProperties(n,{transaction:{get:()=>r.transaction},created:{get:()=>r.created},status:{get:()=>r.status},closed:{get:()=>r.closed},cancel:{value:e=>r.cancel(e)},complete:{value:()=>r.complete()}}),n}async nextAsync(e,t){return Pi(this.query(e,t))}getRequest(e){return this.#a.value[e]}getRequestByRef(e){return Object.values(this.#a.value).find(t=>t.ref===e)}cancelTaskByRef(e,t){const r=this.getRequestByRef(e);r?.ref&&this.cancel(r.transaction,t)}cancel(e,t){if(e)this.#a.value[e]?(t??=`cancelation requested for job: ${e}`,this.#a.next(yy.cancel(e,t))):this.#d.warn("Task not registered, nothing to cancel",{transaction:e,reason:t});else for(const e of Object.keys(this.#a.value))this.cancel(e,"all transactions requested canceled")}on(e,t){return this.#a.addEffect(yy[e].type,e=>{t(e,this)})}complete(){this.#h.unsubscribe()}}const Sy={set:dy("cache/set",(e,t)=>({payload:{key:e,record:t}})),insert:dy("cache/insert",(e,t)=>({payload:{key:e,entry:t}})),remove:dy("cache/remove",e=>({payload:e})),invalidate:dy("cache/invalidate",(e,t)=>({payload:e,meta:{item:t}})),mutate:dy("cache/mutate",(e,t,r)=>({payload:{...t,key:e},meta:{item:r}})),trim:dy("cache/trim",e=>({payload:e}))},Ay=(e,t)=>(t.updated??0)-(e.updated??0);class Oy{#a;get state(){return this.#a.value}get state$(){return this.#a.asObservable()}get action$(){return this.#a.action$}constructor(e){const{trimming:t,initial:r}=e??{};this.#a=new hy(function(e,t={}){return gy(t,t=>t.addCase(e.set,(e,t)=>{const{key:r,record:n}=t.payload;e[r]=n}).addCase(e.insert,(e,t)=>{const{key:r,entry:n}=t.payload,o=e[r];if(o)o.updated=Date.now(),o.updates??=0,o.updates++,o.value=n.value,o.transaction=n.transaction,o.mutated=void 0;else{const t=Date.now();e[r]={...n,created:t,updated:t}}}).addCase(e.remove,(e,t)=>{delete e[t.payload]}).addCase(e.invalidate,(e,t)=>{const r=t.payload?[t.payload]:Object.keys(e);for(const t of r){const r=e[t];r&&(r.updated=void 0)}}).addCase(e.mutate,(e,t)=>{const{key:r,value:n,updated:o}=t.payload,i=e[r];i&&(i.value=n,i.updated=o,i.mutated=Date.now(),i.updates??=0,i.updates++)}).addCase(e.trim,(e,t)=>{const{payload:r}=t,n=r.sort??Ay,o=Object.keys(e),i=Object.entries(e).filter(([e,t])=>!r.validate||r.validate(t)).sort((e,t)=>n(e[1],t[1])).slice(0,r.size??Number.MAX_SAFE_INTEGER).map(([e])=>e);if(o.length!==i.length)for(const t of o){const r=i.indexOf(t);-1!==r?i.splice(r,1):delete e[t]}}))}(Sy,r)),t&&this.#a.addEffect("cache/set",()=>this.#a.next(Sy.trim(t)))}has(e){return e in this.#a.value}setItem(e,t){const{args:r,transaction:n,value:o}=t;this.#a.next(Sy.insert(e,{args:r,transaction:n,value:o}))}getItem(e){return this.#a.value[e]}removeItem(e){this.#a.next(Sy.remove(e))}invalidate(e){const t=e?this.#a.value[e]:void 0;this.#a.next(Sy.invalidate(e,t))}mutate(e,t){const r=e in this.#a.value?this.#a.value[e]:void 0;if(!r)throw new Error(`Cannot mutate cache item with key ${e}: item not found`);const n="function"==typeof t?t(r?.value):t;return this.#a.next(Sy.mutate(e,n,r)),()=>this.#a.next(Sy.set(e,r))}trim(e){this.#a.next(Sy.trim(e))}reset(){this.#a.reset()}complete(){this.#a.complete()}}class ky extends Wo{key;args;options;#f=Date.now();get created(){return this.#f}#p=ag();get uuid(){return this.#p}constructor(e,t,r){super(),this.key=e,this.args=t,this.options=r}processJob(e,t){return e.pipe(xi(t=>{const{key:r,uuid:n,created:o}=this;return{key:r,uuid:n,created:o,status:"complete",transaction:e.transaction,complete:t.completed,value:t.value}}),es(()=>{t?.debug("QueryTask complete",{uuid:this.uuid,key:this.key,job:{status:e.status,transaction:e.transaction}}),e.complete()})).subscribe(this)}}class Ry{static extractQueryValue=Zm;#h=new Ao;#u;#m;#g=new Wo;#y={};#v;#E;#b=ag();#d;get client(){return this.#u}get cache(){return this.#m}constructor(e){this.#d=e.logger??new Cy("Query",this.#b),this.#v=t=>hg(e.key(t),this.#b),this.#E=e?.validate??((e=0)=>t=>(t.updated??0)+e>Date.now())(e?.expire),e.client instanceof Ty?this.#u=e.client:(this.#u=new Ty(e.client.fn,{logger:this.#d.createSubLogger("Client"),...e.client.options}),this.#h.add(()=>this.#u.complete())),e.cache instanceof Oy?this.#m=e.cache:(this.#m=new Oy(e.cache||{}),this.#h.add(()=>this.#m.complete()));const t=((e="switch")=>"function"==typeof e?e:(()=>{switch(e){case"concat":return Wm;case"merge":return Qm;case"switch":return Jm;default:throw new Error(`Invalid queue operator: ${e}`)}})())(e.queueOperator);var r,n;this.#h.add(()=>this.#g.complete()),this.#h.add(this.#g.pipe(is(e=>this.#d.debug("Task added to queue",{key:e})),Ki(e=>!!(e in this.#y)),t(e=>{const t=this.#y[e],{args:r,options:n,uuid:o}=t;if(this.#d.debug("Task selected from queue",{key:e,task:t.uuid,args:r,options:n}),!t?.observed)return this.#d.debug("Task skipped",{task:o}),delete this.#y[e],ci;const i=this.#u.query(r,{...n,ref:t.uuid});return new Ho(r=>{const{transaction:n}=i;var s,a;this.#d.info("Task stated",{task:o,transaction:n}),r.add(()=>{this.#d.debug("Task closed",{task:o,transaction:n,jobStatus:i.status}),i.complete("task closed"),delete this.#y[e]}),r.add((s=10,void 0===a&&(a=si),zi(s,s,a)).pipe(Ki(()=>!t.observed)).subscribe(()=>{i.cancel(`task: ${t.uuid} is not observed`),r.complete()})),r.add(t.processJob(i,this.#d)),i.pipe(xi(e=>({result:e,task:t})),Vi(()=>ci)).subscribe(r)})}),(r=()=>!this.#u.closed,void 0===n&&(n=!1),zo(function(e,t){var o=0;e.subscribe(Ko(t,function(e){var i=r(e,o++);(i||n)&&t.next(e),!i&&t.complete()}))}))).subscribe(e=>{const{value:t,transaction:r}=e.result,{args:n,key:o,uuid:i}=e.task;this.#d.debug("Task output added to cache",{uuid:i,args:n,key:o,transaction:r,value:t}),this.#m.setItem(o,{value:t,args:n,transaction:r})}))}query(e,t){return this._query(e,t)}queryAsync(e,t){const{skipResolve:r,...n}=t||{},o=r?Pi:Ri;return new Promise((r,i)=>{t?.signal&&t.signal.addEventListener("abort",()=>i(new Error("Query aborted"))),o(this._query(e,n).pipe(Zi())).then(r,i)})}persistentQuery(e,t){const r=this.#v(e),n=this._query(e,t);return new Ho(o=>{o.add(n.subscribe({next:o.next.bind(o),error:o.error.bind(o)}));const i=t?.cache?.validate||this.#E;o.add(this.cache.state$.pipe(Ki(e=>r in e),xi(t=>({...t[r],key:r,status:"cache",hasValidCache:i(t[r],e)}))).subscribe(o))}).pipe(Qi((e,t)=>e.transaction===t.transaction&&e.mutated===t.mutated))}generateCacheKey(e){return this.#v(e)}mutate(e,t,r){const n=this.#v(e);if(n in this.cache.state==!1){if(void 0===r?.allowCreation)throw new Error(`Cannot mutate cache item with key ${n}: item not found and option "allowCreation" is false`);if(!1===r.allowCreation)return()=>{};const{value:o}="function"==typeof t?t():t;this.cache.setItem(n,{args:e,transaction:ag(),value:o})}return this.#m.mutate(n,t)}invalidate(e){this.#m.invalidate(e&&this.#v(e))}complete(){this.#h.unsubscribe()}onInvalidate(e){const t=this.#m.action$.pipe(ly("cache/invalidate")).subscribe(t=>e({detail:{item:t.meta.item}}));return()=>t.unsubscribe()}onMutate(e){const t=this.#m.action$.pipe(ly("cache/mutate")).subscribe(t=>e({detail:{changes:t.payload,current:t.meta.item}}));return()=>t.unsubscribe()}_query(e,t){const r=this.#v(e),n=this._createTask(r,e,t);return this.#d.debug("New query created",{key:r,args:e,options:t}),n}_createTask(e,t,r){return new Ho(n=>{if(r?.signal){if(r?.signal.aborted)return this.#d.debug("Abort signal already triggered by caller",{key:e}),n.complete();n.add(Hi(r?.signal,"abort").subscribe(()=>{this.#d.debug("Abort signal triggered by caller",{key:e}),n.complete()}))}const o=this.#m.getItem(e);if(o){this.#d.debug("Query has cache",{key:e,cacheEntry:o});const i=r?.cache?.suppressInvalid??!1,s=(r?.cache?.validate||this.#E)(o,t),a={...o,key:e,status:"cache",hasValidCache:s};if(this.#d.info("Query cache valid, completing",{hasValidCache:s,suppressInvalid:i,record:a}),n.next(a),s||i)return n.complete();this.#d.debug("Query cache entry is invalid, proceeding to fetch new data",{key:e})}const i=e in this.#y;this.#y[e]??=new ky(e,t,r);const s=this.#y[e];n.add(s.subscribe(n)),this.#d.info(i?"Query connected to existing task":"Query started new task",{key:e}),i||this.#g.next(e)})}}const Py=k.object({key:k.string().describe("The key used to identify the service"),uri:k.string().describe("The URI of the service"),id:k.string().optional().describe("The ID of the service"),environment:k.string().optional().describe("The environment of the service"),name:k.string().optional().describe("The name of the service"),scopes:k.array(k.string()).optional().default([]).describe("Endpoint authentication scopes"),tags:k.array(k.string()).optional().describe("Tags for the service")}).describe("A service from the service discovery API").transform(e=>({...e,get defaultScopes(){return e.scopes??[]}})),Ny=k.array(Py).describe("A list of services from the service discovery API"),Ly=e=>Ai(Bm(e)).pipe(xi(e=>Ny.default([]).parse(e)));class Dy{#w;endpoint;http;constructor({http:e,endpoint:t}){this.http=e,this.endpoint=t,this.#w=new Ry({client:{fn:()=>e.fetch$(t??"",{selector:Ly})},key:()=>"services",expire:3e5})}resolveServices(e){return(e?Pi:Ri)(Ry.extractQueryValue(this.#w.query()))}async resolveService(e,t){const r=(await this.resolveServices(t)).find(t=>t.key===e);if(!r)throw Error(`Failed to resolve service, invalid key [${e}]`);return r}}class xy extends cs{async _createConfig(e,t){if(!e.hasModule("http"))throw new Error("http module is required");if(!this._has("discoveryClient")){(await e.requireInstance("http")).hasClient("service_discovery")&&this.configureServiceDiscoveryClientByClientKey("service_discovery")}return Ri(Ai(super._createConfig(e,t)))}_processConfig(e,t){if(!e.discoveryClient)throw new Error("discoveryClient is required, please configure it");return super._processConfig(e,t)}setServiceDiscoveryClient(e){this._set("discoveryClient","function"==typeof e?e:async()=>e)}configureServiceDiscoveryClient(e){this.setServiceDiscoveryClient(async t=>{const{httpClient:r,endpoint:n}=await Ri(Ai(e(t)))??{};if(r)return new Dy({http:r,endpoint:n});throw Error("httpClient is required")})}configureServiceDiscoveryClientByClientKey(e,t){this.configureServiceDiscoveryClient(async({requireInstance:r})=>({httpClient:(await r("http")).createClient(e),endpoint:t}))}}class My{config;_http;constructor(e,t){this.config=e,this._http=t}resolveServices(){return this.config.discoveryClient.resolveServices()}async resolveService(e){return this.config.discoveryClient.resolveService(e)}async createClient(e,t){const r=await this.resolveService(e);if(!r)throw Error(`Could not load configuration of service [${e}]`);return this._http.createClient({...t,baseUri:r.uri,defaultScopes:r.scopes})}async configureClient(e,t){const{key:r,alias:n}="string"==typeof e?{key:e,alias:e}:e,{uri:o,scopes:i}=await this.resolveService(r);t.addConfig(((e,t)=>({module:Ym,configure:r=>{r.configureClient(e,t)}}))(n,{baseUri:o,defaultScopes:i}))}}const $y={name:"serviceDiscovery",configure:()=>new xy,initialize:async e=>{const{requireInstance:t,ref:r}=e,n=await e.config.createConfigAsync(e,{...r?.serviceDiscovery?.config}),o=await t("http");return new My(n,o)}},Uy=(e,t)=>{e.addConfig((e=>({module:$y,configure:t=>e(t)}))(()=>Promise.resolve()))};var Fy,jy,By,qy={},Hy=[{name:"Agola CI",constant:"AGOLA",env:"AGOLA_GIT_REF",pr:"AGOLA_PULL_REQUEST_ID"},{name:"Appcircle",constant:"APPCIRCLE",env:"AC_APPCIRCLE",pr:{env:"AC_GIT_PR",ne:"false"}},{name:"AppVeyor",constant:"APPVEYOR",env:"APPVEYOR",pr:"APPVEYOR_PULL_REQUEST_NUMBER"},{name:"AWS CodeBuild",constant:"CODEBUILD",env:"CODEBUILD_BUILD_ARN",pr:{env:"CODEBUILD_WEBHOOK_EVENT",any:["PULL_REQUEST_CREATED","PULL_REQUEST_UPDATED","PULL_REQUEST_REOPENED"]}},{name:"Azure Pipelines",constant:"AZURE_PIPELINES",env:"TF_BUILD",pr:{BUILD_REASON:"PullRequest"}},{name:"Bamboo",constant:"BAMBOO",env:"bamboo_planKey"},{name:"Bitbucket Pipelines",constant:"BITBUCKET",env:"BITBUCKET_COMMIT",pr:"BITBUCKET_PR_ID"},{name:"Bitrise",constant:"BITRISE",env:"BITRISE_IO",pr:"BITRISE_PULL_REQUEST"},{name:"Buddy",constant:"BUDDY",env:"BUDDY_WORKSPACE_ID",pr:"BUDDY_EXECUTION_PULL_REQUEST_ID"},{name:"Buildkite",constant:"BUILDKITE",env:"BUILDKITE",pr:{env:"BUILDKITE_PULL_REQUEST",ne:"false"}},{name:"CircleCI",constant:"CIRCLE",env:"CIRCLECI",pr:"CIRCLE_PULL_REQUEST"},{name:"Cirrus CI",constant:"CIRRUS",env:"CIRRUS_CI",pr:"CIRRUS_PR"},{name:"Cloudflare Pages",constant:"CLOUDFLARE_PAGES",env:"CF_PAGES"},{name:"Codefresh",constant:"CODEFRESH",env:"CF_BUILD_ID",pr:{any:["CF_PULL_REQUEST_NUMBER","CF_PULL_REQUEST_ID"]}},{name:"Codemagic",constant:"CODEMAGIC",env:"CM_BUILD_ID",pr:"CM_PULL_REQUEST"},{name:"Codeship",constant:"CODESHIP",env:{CI_NAME:"codeship"}},{name:"Drone",constant:"DRONE",env:"DRONE",pr:{DRONE_BUILD_EVENT:"pull_request"}},{name:"dsari",constant:"DSARI",env:"DSARI"},{name:"Earthly",constant:"EARTHLY",env:"EARTHLY_CI"},{name:"Expo Application Services",constant:"EAS",env:"EAS_BUILD"},{name:"Gerrit",constant:"GERRIT",env:"GERRIT_PROJECT"},{name:"Gitea Actions",constant:"GITEA_ACTIONS",env:"GITEA_ACTIONS"},{name:"GitHub Actions",constant:"GITHUB_ACTIONS",env:"GITHUB_ACTIONS",pr:{GITHUB_EVENT_NAME:"pull_request"}},{name:"GitLab CI",constant:"GITLAB",env:"GITLAB_CI",pr:"CI_MERGE_REQUEST_ID"},{name:"GoCD",constant:"GOCD",env:"GO_PIPELINE_LABEL"},{name:"Google Cloud Build",constant:"GOOGLE_CLOUD_BUILD",env:"BUILDER_OUTPUT"},{name:"Harness CI",constant:"HARNESS",env:"HARNESS_BUILD_ID"},{name:"Heroku",constant:"HEROKU",env:{env:"NODE",includes:"/app/.heroku/node/bin/node"}},{name:"Hudson",constant:"HUDSON",env:"HUDSON_URL"},{name:"Jenkins",constant:"JENKINS",env:["JENKINS_URL","BUILD_ID"],pr:{any:["ghprbPullId","CHANGE_ID"]}},{name:"LayerCI",constant:"LAYERCI",env:"LAYERCI",pr:"LAYERCI_PULL_REQUEST"},{name:"Magnum CI",constant:"MAGNUM",env:"MAGNUM"},{name:"Netlify CI",constant:"NETLIFY",env:"NETLIFY",pr:{env:"PULL_REQUEST",ne:"false"}},{name:"Nevercode",constant:"NEVERCODE",env:"NEVERCODE",pr:{env:"NEVERCODE_PULL_REQUEST",ne:"false"}},{name:"Prow",constant:"PROW",env:"PROW_JOB_ID"},{name:"ReleaseHub",constant:"RELEASEHUB",env:"RELEASE_BUILD_ID"},{name:"Render",constant:"RENDER",env:"RENDER",pr:{IS_PULL_REQUEST:"true"}},{name:"Sail CI",constant:"SAIL",env:"SAILCI",pr:"SAIL_PULL_REQUEST_NUMBER"},{name:"Screwdriver",constant:"SCREWDRIVER",env:"SCREWDRIVER",pr:{env:"SD_PULL_REQUEST",ne:"false"}},{name:"Semaphore",constant:"SEMAPHORE",env:"SEMAPHORE",pr:"PULL_REQUEST_NUMBER"},{name:"Sourcehut",constant:"SOURCEHUT",env:{CI_NAME:"sourcehut"}},{name:"Strider CD",constant:"STRIDER",env:"STRIDER"},{name:"TaskCluster",constant:"TASKCLUSTER",env:["TASK_ID","RUN_ID"]},{name:"TeamCity",constant:"TEAMCITY",env:"TEAMCITY_VERSION"},{name:"Travis CI",constant:"TRAVIS",env:"TRAVIS",pr:{env:"TRAVIS_PULL_REQUEST",ne:"false"}},{name:"Vela",constant:"VELA",env:"VELA",pr:{VELA_PULL_REQUEST:"1"}},{name:"Vercel",constant:"VERCEL",env:{any:["NOW_BUILDER","VERCEL"]},pr:"VERCEL_GIT_PULL_REQUEST_ID"},{name:"Visual Studio App Center",constant:"APPCENTER",env:"APPCENTER_BUILD_ID"},{name:"Woodpecker",constant:"WOODPECKER",env:{CI:"woodpecker"},pr:{CI_BUILD_EVENT:"pull_request"}},{name:"Xcode Cloud",constant:"XCODE_CLOUD",env:"CI_XCODE_PROJECT",pr:"CI_PULL_REQUEST_NUMBER"},{name:"Xcode Server",constant:"XCODE_SERVER",env:"XCS"}];function Gy(){return Fy||(Fy=1,function(e){const t=Hy,r=process.env;function n(e){return"string"==typeof e?!!r[e]:"env"in e?r[e.env]&&r[e.env].includes(e.includes):"any"in e?e.any.some(function(e){return!!r[e]}):Object.keys(e).every(function(t){return r[t]===e[t]})}Object.defineProperty(e,"_vendors",{value:t.map(function(e){return e.constant})}),e.name=null,e.isPR=null,e.id=null,t.forEach(function(t){const o=(Array.isArray(t.env)?t.env:[t.env]).every(function(e){return n(e)});e[t.constant]=o,o&&(e.name=t.name,e.isPR=function(e){switch(typeof e.pr){case"string":return!!r[e.pr];case"object":return"env"in e.pr?"any"in e.pr?e.pr.any.some(function(t){return r[e.pr.env]===t}):e.pr.env in r&&r[e.pr.env]!==e.pr.ne:"any"in e.pr?e.pr.any.some(function(e){return!!r[e]}):n(e.pr);default:return null}}(t),e.id=t.constant)}),e.isCI=!("false"===r.CI||!(r.BUILD_ID||r.BUILD_NUMBER||r.CI||r.CI_APP_ID||r.CI_BUILD_ID||r.CI_BUILD_NUMBER||r.CI_NAME||r.CONTINUOUS_INTEGRATION||r.RUN_ID||e.name))}(qy)),qy}var zy=Qe(By?jy:(By=1,jy=Gy().isCI));const Ky=["5a842df8-3238-415d-b168-9f16a6a6031b/.default"];var Vy;!function(e){e.ContinuesIntegration="ci",e.QualityAssurance="fqa",e.Training="tr",e.Production="fprd",e.Development="dev"}(Vy||(Vy={}));const Yy=e=>e&&!zy?Vy.Development:Vy.ContinuesIntegration,Wy=async e=>{const t=new hs,r=e.env??Vy.ContinuesIntegration;t.addConfig({module:Ym,configure:t=>{const n=r===Vy.Development?Vy.ContinuesIntegration:r,o=e.serviceDiscovery?.url??new URL(`/service-registry/environments/${n}/services`,"https://discovery.fusion.equinor.com").toString(),i=e.serviceDiscovery?.scope??Ky;t.configureClient("service_discovery",{baseUri:o,defaultScopes:i})}}),Uy(t),((e,t)=>{e.addConfig({module:km,configure:t})})(t,t=>{const{auth:r}=e;if("token"in r&&r.token){const{token:e}=r;return t.setMode("token_only"),void t.setAccessToken(e)}const{clientId:n,tenantId:o,interactive:i}=r;if(!n||!o)throw new Error("clientId and tenantId are required for auth module");if(t.setClientConfig(o,n),t.setMode(i?"interactive":"silent"),i){const{server:e}=r;if(!e.port)throw new Error("server.port is required for interactive mode");t.setServerPort(e.port),t.setServerOnOpen(e.onOpen)}});return await t.initialize()},Qy=async e=>{const{log:t}=e,{config:r}=await Zt({log:t,config:e.config,env:{environment:e.environment}}),{manifest:n}=await Ye({log:t,manifest:e.manifest,env:{environment:e.environment}}),o=n.build?.version;if(!o){const e=new Error("No build version found in the manifest. Please make sure the manifest is valid.");throw t?.fail("🤪",e.message),e}t?.start("Initializing Fusion Framework...");const i=await Wy({env:e.environment,auth:e.auth});t?.succeed("Initialized Fusion Framework");const s=await i.serviceDiscovery.createClient("apps");s.request$.subscribe(e=>{t?.debug("Request:",e),t?.info("🌎","Executing request to:",Ge(e.uri))}),t?.start("Publishing application config"),t?.info("Using environment:",we.redBright(e.environment));try{const e=await s.json(`/apps/${n.appKey}/builds/${o}/config`,{method:"PUT",body:r});t?.debug("Response:",e),t?.succeed("Published application config")}catch(e){if(e instanceof er)switch(e.response.status){case 410:t?.fail("🤬",`App ${n.appKey} is deleted from apps-service. Please check the app key and try again.`);break;case 404:t?.fail("🤬",`App ${n.appKey} not found. Please check the app key and try again.`);break;case 403:case 401:t?.fail("🤬","You are not authorized to publish application config. Please check your permissions.");break;default:t?.fail("🤬","Failed to publish application config.",`Status code: ${e.response.status}`,`Message: ${e.response.statusText}`)}throw e}},Jy=async e=>{const{log:t}=e??{},r="@equinor/fusion-framework-dev-portal",n=await Ve(t),i={root:n.root,environment:"local",...e?.env,mode:"development",command:"serve"},s=await Ke(i,n,{log:t,manifestPath:e?.manifest}),a=await Jt(i,{log:t,config:e?.config});let c,l;const h=z(import.meta.resolve(r));Ie(h)?(c=h,l=await u({cwd:h}).then(e=>e?o(e?.path):void 0)):t?.info(`Portal ${r} is external, skipping entry point resolution`),t?.start("Starting app development server...");const d=await Kt(i,{template:{portal:{id:r}},...c?{portal:{manifest:{name:r,build:{templateEntry:c,assetPath:"/@fs"}},config:{}}}:{},app:{manifest:s,config:a}},{server:{port:e?.port||3e3,host:"localhost",fs:{allow:l?[n.root,l]:[n.root]}}});await d.listen(),t?.succeed("App development server started successfully");const f=d.config.server.https?"https":"http",p=d.config.server.host||"localhost",m=d.config.server.port||5173;return t?.info(`App development server is running at: ${f}://${p}:${m}/apps/${s.appKey}`),d},Zy=async e=>{const{log:t}=e,r=await Ve(t),n=await Ke({command:"build",mode:"production"},r,{log:t});t?.start("Initializing Fusion Framework...");const o=await Wy({env:e.environment,auth:"token"in e.auth?{token:e.auth.token}:e.auth});t?.succeed("Initialized Fusion Framework");const i=await o.serviceDiscovery.createClient("apps");i.request$.subscribe(e=>{t?.info("🌎","Executing request to:",e.uri),t?.debug("Request:",e)});try{t?.start(`Checking if ${n.appKey} is registered in app store`);const e=await i.fetch(`/apps/${n.appKey}`,{method:"HEAD"});if(e.ok)return t?.succeed("😃",`Application ${n.appKey} is registered in app store`);if(404===e.status)return t?.fail("😞",`Application ${n.appKey} is not registered in app store`);throw new Error(`Unexpected response status: ${e.status}`)}catch(e){t?.fail("🙅‍♂️","Error checking application registration"),t?.error("Error checking application registration:",e)}},Xy=e=>{const t=e.getEntry("metadata.json");if(!t)throw new Error("Metadata file not found in bundle");return new Promise((e,r)=>{t.getDataAsync((t,n)=>{if(n)return r(new Error("Failed to read metadata file",{cause:n}));try{return e(JSON.parse(String(t)))}catch(e){r(new Error("Failed to parse metadata file",{cause:e}))}})})},ev=async e=>{const{log:t,framework:r}=e,n="string"==typeof e.fileOrBundle?new Ft(e.fileOrBundle):e.fileOrBundle,{name:o}=e.appKey?{name:e.appKey}:await Xy(n).catch(e=>{t?.error("Failed to resolve manifest:",e),process.exit(1)}),i=await n.toBufferPromise().catch(e=>{t?.error("Failed to read bundle content:",e),process.exit(1)});try{const e=await r.serviceDiscovery.createClient("apps");e.request$.subscribe(e=>{t?.info("🌎","Executing request to:",e.uri),t?.debug("Request:",e)});const n=await e.fetch(`/bundles/apps/${o}`,{method:"POST",body:new Blob([i],{type:"application/zip"}),headers:{"Content-Type":"application/zip"}});if(!n.ok){try{const{error:e}=await n.json();t?.debug("Error:",e),e.message&&t?.warn(we.red(`🤯 error: ${e.code}\n`),we.yellowBright(e.message),"\n")}catch(e){t?.debug("Error:",n.statusText)}throw 409===n.status&&(t?.fail(`🤬 - ${n.status} - `,"Version is already published, please generate a new release"),process.exit(1)),410===n.status&&(t?.fail(`🤬 - ${n.status} - `,"Application is removed from Fusion app store, please check Application Admin"),process.exit(1)),404===n.status&&(t?.fail(`🤬 - ${n.status} - `,"Application not found, please add your application in App Admin before publishing"),process.exit(1)),401!==n.status&&403!==n.status||(t?.fail(`🤬 - ${n.status} - `,"This is not allowed for this role on this app"),process.exit(1)),500===n.status&&(t?.fail(`🤬 - ${n.status} - `,"Internal server error, please try again later or contact support"),process.exit(1)),new Error(`Failed to upload bundle. HTTP status ${n.status}, ${n.statusText}`)}t?.succeed("Successfully uploaded application bundle"),t?.debug("Response:",n);try{return{name:o,version:(await n.json()).version}}catch(e){throw new Error(`Failed to parse response from app service: ${e instanceof Error?e.message:e}`)}}catch(e){t?.fail("🙅‍♂️","Failed to upload application bundle"),t?.error(e),process.exit(1)}};var tv;!function(e){e.Latest="latest",e.Preview="preview"}(tv||(tv={}));const rv=async e=>{const{tag:t,appKey:r,version:n,framework:o,log:i}=e;["latest","preview"].includes(t)||(i?.fail("🤪",'Invalid tag. Use "latest" or "preview".'),process.exit(1)),r||(i?.fail("🤪","Application key is required."),process.exit(1)),n||(i?.fail("🤪","Version is required."),process.exit(1));const s=await o.serviceDiscovery.createClient("apps");s.request$.subscribe(e=>{i?.debug("Request:",e),i?.info("🌎","Executing request to:",Ge(e.uri))}),i?.start("Publishing application config");try{const e=await s.json(`/apps/${r}/tags/${t}`,{method:"PUT",body:{version:n}});return i?.debug("Response:",e),i?.succeed("Tagged application successfully",we.greenBright(`${r}@${n} - ${t}`)),e}catch(e){if(e instanceof er)switch(e.response.status){case 410:i?.fail("🤬",`App ${r} is deleted from apps-service. Please check the app key and try again.`);break;case 404:i?.fail("🤬",`App ${r} not found. Please check the app key and try again.`);break;case 403:case 401:i?.fail("🤬","You are not authorized to tag application. Please check your permissions.");break;default:i?.fail("🤬","Failed to tag application",`Status code: ${e.response.status}`,`Error: ${e.message}`)}throw e}},nv=R.object({templateEntry:R.string({required_error:"templateEntry is required in build section",invalid_type_error:"templateEntry must be a string"}).describe("Main entry point for the portal"),schemaEntry:R.string({required_error:"schemaEntry is required in build section",invalid_type_error:"schemaEntry must be a string"}).describe("Schema file for portal validation"),assetPath:R.string({invalid_type_error:"assetPath must be a string"}).optional().describe("Asset path for dev/preview builds"),githubRepo:R.string({invalid_type_error:"githubRepo must be a string"}).optional().describe("GitHub repo URL or local git remote"),version:R.string({required_error:"version is required in build section",invalid_type_error:"version must be a string"}).describe("Version from package.json"),timestamp:R.string({required_error:"timestamp is required in build section",invalid_type_error:"timestamp must be a string"}).describe("Current build timestamp (ISO8601)"),commitSha:R.string({required_error:"commitSha is required in build section",invalid_type_error:"commitSha must be a string"}).describe("Current git commit SHA"),annotations:R.record(R.string(),{invalid_type_error:"annotations must be a record of string values"}).optional().describe("Optional build annotations"),projectPage:R.string({invalid_type_error:"projectPage must be a string"}).optional().describe("Optional project homepage"),allowedExtensions:R.array(R.string({invalid_type_error:"Each allowed extension must be a string"}),{required_error:"allowedExtensions is required in build section",invalid_type_error:"allowedExtensions must be an array of strings"}).describe("List of allowed asset extensions (with leading dot)"),schema:R.record(R.unknown(),{invalid_type_error:"schema must be a record of unknown values"}).optional().describe("Optional schema for the portal"),config:R.record(R.unknown(),{invalid_type_error:"config must be a record of unknown values"}).optional().describe("Optional configuration for the portal")}),ov=R.object({name:R.string({required_error:"name is required in portal manifest",invalid_type_error:"name must be a string"}).describe("Short app key (unscoped, derived from package name)"),displayName:R.string({invalid_type_error:"displayName must be a string"}).optional().describe("Full package name, may include scope"),description:R.string({invalid_type_error:"description must be a string"}).optional().describe("Description of the portal"),build:nv}),iv=(e,t)=>{Ae(t,"expected packageJson"),T(t.name,"expected [name] in packageJson"),T(t.version,"expected [version] in packageJson");const r=((e,t)=>"build"===e.command||e.isPreview?t.main||t.module||"dist/bundle.js":_e(e.root))(e,t),n=t.name.replace(/^@|\w.*\//gm,""),o=t.version,i="build"===e.command?void 0:"/@fs",s=Oe(t)??ke(),a={name:n,displayName:t.name,description:t.description||"",build:{templateEntry:r,schemaEntry:"portal.schema.json",assetPath:i,githubRepo:s,version:o,timestamp:(new Date).toISOString(),commitSha:Re(),annotations:{...Ne()},projectPage:t.homepage,allowedExtensions:Le.map(e=>`.${e}`)}},c=ov.safeParse(a);if(!c.success){const e=c.error.issues.map(e=>`- ${e.path.join(".")}: ${e.message}`).join("\n");throw new Error(["Invalid portal manifest generated from package.json:",e].join("\n"))}return c.data},sv=async(e,t,r)=>{const n=iv(e,t.packageJson);try{r?.log?.start("loading manifest...");const t=await(async(e,t)=>{const r=t?.file??[`portal.manifest.${e.environment}`,"portal.manifest"],n=await I(r,{baseDir:e.root,extensions:t?.extensions,script:{resolve:async r=>{const n=t?.base??{};let o;return o="function"==typeof r.default?await r.default(e,{base:n})??void 0:r.default,o?_(n,o):n}}}),o=n.config,i=ov.safeParse(o);if(!i.success)throw new Error(`Invalid portal manifest: ${i.error.errors.map(e=>`${e.path.join(".")}: ${e.message}`).join("; ")}`);return{manifest:o,path:n.path,extension:n.extension}})(e,{base:n});return r?.log?.succeed("generated manifest from",Ge(t.path,{relative:!0})),t.manifest}catch(e){if(e instanceof C){if(r?.manifestPath){const t=new Error(`Failed to load manifest file ${Ge(r.manifestPath)}, please check the path.`,{cause:e});throw r?.log?.fail(t.message),t}return r?.log?.succeed(we.dim("no local manifest config applied, using default generated from package")),n}throw r?.log?.fail(`failed to resolve application manifest ${r?.manifestPath?Ge(r?.manifestPath):""}`),e}},av=async(e,t)=>{const{log:r}=t;try{r?.start("create portal configuration"),r?.info(`generating config with ${we.red.dim(e.command)} command in ${we.green.dim(e.mode)} mode`);const n=await((e,t)=>{const r=t?.file??[`portal.config.${e.environment}`,"portal.config"];return I(r,{baseDir:e.root,extensions:t?.extensions,script:{resolve:async r=>{const n=t?.schema??k.object({}).passthrough(),o=t?.base??{};if("function"==typeof r.default){const t=await r.default(o,e)??o;return n.parse(t??o)}return n.parse(r.default??o)}}})})(e,{file:t?.config});return r?.succeed("⚙️ generated config from ",Ge(n.path,{relative:!0})),n.config}catch(e){if(e instanceof C){if(!t.config)return r?.succeed(we.dim("⚙️ no local portal config applied, using built-in")),{};r?.warn(`failed to load config file ${Ge(t.config)}, please check the path.`)}throw r?.fail("failed to resolve portal config"),r?.debug(e),e}},cv=async e=>{const{log:t}=e??{},r=await Ve(t),n={root:r.root,environment:"local",...e?.env,mode:"development",command:"serve"},o=await sv(n,r,{log:t,manifestPath:e?.manifest}),i=await av(n,{log:t,config:e?.config});t?.start("Starting app development server...");const s=await Kt(n,{template:{portal:{id:o.name}},portal:{manifest:o,config:i}},{server:{port:e?.server?.port,fs:{allow:[r.root]}}});return await s.listen(),t?.succeed(`Started app development server on ${s.resolvedUrls?.local?.[0]}`),s},uv=async e=>{const{log:t}=e??{},r=await Ve(t);t?.debug("package",r);const n={command:"build",mode:process.env.NODE_ENV??"production",root:r.root,...e?.env};t?.debug("env:",n);const o=await sv(n,r,{log:t,manifestPath:e?.manifest});return t?.debug("manifest:",o),{manifest:o,pkg:r,env:n}},lv=async e=>{const{log:t}=e??{};t?.log(we.bold("Starting to build portal"));const{manifest:n,pkg:o,env:i}=await uv({log:t,manifest:e?.manifest});t?.start("loading vite config...");const s=await Se(i,o);t?.succeed("vite config applied"),t?.debug("vite config:",s),t?.start("🤞🏻","building portal..."),t?.startNativeConsoleCapture(),await r(s),t?.stopNativeConsoleCapture(),t?.succeed("build completed 😘");return{pkg:o,manifest:n,outDir:s.build.outDir}},hv=async e=>{const{log:t,manifest:r}=e,n={command:"build",mode:process.env.NODE_ENV??"production",environment:null,root:process.cwd()},{pkg:o,manifest:i}=await lv({log:t,manifest:r});if(!i.build)throw new Error("Manifest build config not found");const s=await(async(e,t)=>{const r=t?.file??[`portal.schema.${e.environment}`,"portal.schema"],n=await I(r,{baseDir:e.root,extensions:t?.extensions,script:{resolve:async t=>{const r="function"==typeof t.default?await Promise.resolve(t.default(e)):t.default;if(!r)throw new Error("Schema function did not return a valid schema");return r}}});return{schema:n.config,path:n.path,extension:n.extension}})(n,{file:e?.schema});t?.debug("Schema:",s);return{archive:await Wt(o,{log:t,archive:e?.archive,content:{"portal-template-manifest.json":JSON.stringify(i.build,null,2),"portal.schema.json":JSON.stringify(s.schema,null,2),"metadata.json":JSON.stringify({name:i.name,version:i.build.version})}}).catch(e=>{t?.error("Failed to create package:",e),process.exit(1)}),manifest:i,schema:s.schema}},dv=async e=>{const{log:t}=e??{},r=await Ve(t),n={command:"build",mode:process.env.NODE_ENV??"production",root:r.root,...e?.env},o=await av(n,{log:t,config:e?.config});if(t?.debug("config:",o),e?.output){t?.start("writing config to file");try{await Vt(e.output,JSON.stringify(o,null,2)),t?.succeed("config written successfully",Ge(e.output,{relative:!0}))}catch(e){throw t?.fail("failed to write config"),e}}return{config:o,pkg:r}},fv=async e=>{const{log:t,portal:r}=e,{config:n}=await dv({log:t,config:e.config,env:{environment:e.environment}});t?.start("Initializing Fusion Framework...");const o=await Wy({env:e.environment,auth:e.auth});t?.succeed("Initialized Fusion Framework");const i=await o.serviceDiscovery.createClient("portals");i.request$.subscribe(e=>{t?.debug("Request:",e),t?.info("🌎","Executing request to:",Ge(e.uri))}),t?.start("Publishing portal config"),t?.info("Using environment:",we.redBright(e.environment));try{const e=await i.json(`/portals/${r.name}@${r.version}/config`,{method:"PUT",body:n});t?.debug("Response:",e),t?.succeed("Published portal config")}catch(e){if(e instanceof er)switch(e.response.status){case 410:t?.fail("🤬",`Portal ${r.name} is deleted from portals-service. Please check the portal key and try again.`);break;case 404:t?.fail("🤬",`Portal ${r.name} not found. Please check the portal key and try again.`);break;case 403:case 401:t?.fail("🤬","You are not authorized to publish portal config. Please check your permissions.");break;default:t?.fail("🤬","Failed to publish portal config.",`Status code: ${e.response.status}`,`Message: ${e.response.statusText}`)}throw e}},pv=async e=>{const{log:t,framework:r}=e,n="string"==typeof e.fileOrBundle?new Ft(e.fileOrBundle):e.fileOrBundle,{name:o}=e.name?{name:e.name}:await Xy(n).catch(e=>{t?.error("Failed to resolve manifest:",e),process.exit(1)}),i=await n.toBufferPromise().catch(e=>{t?.error("Failed to read bundle content:",e),process.exit(1)});try{const e=await r.serviceDiscovery.createClient("portal-config");e.request$.subscribe(e=>{t?.info("🌎","Executing request to:",e.uri),t?.debug("Request:",e)});const n=await e.fetch(`/bundles/templates/${o}`,{method:"POST",body:new Blob([i],{type:"application/zip"}),headers:{"Content-Type":"application/zip"}});if(!n.ok){try{const{error:e}=await n.json();t?.debug("Error:",e),e.message&&t?.warn(we.red(`🤯 error: ${e.code}\n`),we.yellowBright(e.message),"\n")}catch(e){t?.debug("Error:",n.statusText)}throw 409===n.status&&(t?.fail(`🤬 - ${n.status} - `,"Version is already published, please generate a new release"),process.exit(1)),410===n.status&&(t?.fail(`🤬 - ${n.status} - `,`${o} is removed from Fusion`),process.exit(1)),404===n.status&&(t?.fail(`🤬 - ${n.status} - `,`${o} not found`),process.exit(1)),401!==n.status&&403!==n.status||(t?.fail(`🤬 - ${n.status} - `,`This is not allowed for your role on ${o}`),process.exit(1)),500===n.status&&(t?.fail(`🤬 - ${n.status} - `,"Internal server error, please try again later or contact support"),process.exit(1)),new Error(`Failed to upload bundle. HTTP status ${n.status}, ${n.statusText}`)}t?.succeed("Successfully uploaded application bundle"),t?.debug("Response:",n)}catch(e){t?.fail("🙅‍♂️","Failed to upload application bundle"),t?.error(e),process.exit(1)}};var mv;!function(e){e.Latest="latest",e.Preview="preview"}(mv||(mv={}));const gv=async e=>{const{tag:t,name:r,version:n,framework:o,log:i}=e;["latest","preview"].includes(t)||(i?.fail("🤪",'Invalid tag. Use "latest" or "preview".'),process.exit(1)),r||(i?.fail("🤪","Portal name is required."),process.exit(1)),n||(i?.fail("🤪","Version is required."),process.exit(1)),i?.info("Tagging portal:",we.greenBright(`${r}@${t}`,n));const s=await o.serviceDiscovery.createClient("portal-config");s.request$.subscribe(e=>{i?.debug("Request:",e),i?.info("🌎","Executing request to:",Ge(e.uri))}),i?.start("Tagging portal template...");try{const e=await s.json(`/templates/${r}/tags/${t}`,{method:"PUT",body:{version:n}});i?.debug("Response:",e),i?.succeed("Tagged portal template successfully"),i?.info("🚀",JSON.stringify(e))}catch(e){if(e instanceof er){const{data:t,response:n}=e;switch(i?.debug("Error:",t),t&&i?.warn(we.red(`🤯 error: ${t.code}\n`),we.yellowBright(t.message),"\n"),n?.status){case 410:i?.fail(`🤬 - ${n?.status} -`,`${r} is deleted. Please check the name and try again.`);break;case 404:i?.fail(`🤬 - ${n?.status} -`,`${r} not found. Please check the name and try again.`);break;case 403:case 401:i?.fail(`🤬 - ${n?.status} -`,"You are not authorized to tag. Please check your permissions.");break;default:i?.fail(`🤬 - ${n?.status} -`,"Failed to tag",`Error: ${e.message}`)}}throw e}};export{tv as A,Gt as C,Vy as F,Jp as P,Qt as a,We as b,Zy as c,cv as d,lv as e,hv as f,Zt as g,uv as h,dv as i,fv as j,pv as k,Ye as l,gv as m,mv as n,Wt as o,Qy as p,Wy as q,Yy as r,Jy as s,rv as t,ev as u};