@cortexkit/opencode-anthropic-auth 1.23.0 → 2.0.1
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.
- package/README.md +239 -195
- package/dist/cli-failure.d.ts +69 -0
- package/dist/cli.d.ts +14 -9
- package/dist/cli.js +103 -80
- package/dist/custody-dimensions.d.ts +7 -24
- package/dist/custody-mode.d.ts +29 -169
- package/dist/effort-history.d.ts +6 -1
- package/dist/{index-xzbhzz0a.js → index-04syas8a.js} +2 -2
- package/dist/index-1jkyhgyr.js +2 -0
- package/dist/{index-8y2t4mwz.js → index-2arfb1y3.js} +1 -1
- package/dist/index-3xqv3rw3.js +2 -0
- package/dist/{index-0jfsxyn9.js → index-52r2e1h9.js} +1 -1
- package/dist/index-b3mxpp4w.js +2 -0
- package/dist/index-p4wvcwhh.js +3 -0
- package/dist/{index-1gr8v4fn.js → index-rqync0pc.js} +1 -1
- package/dist/index-ynq181e8.js +42 -0
- package/dist/index-yxtdke11.js +449 -0
- package/dist/index-zdgceztz.js +1 -0
- package/dist/index.js +1 -38
- package/dist/native-command.d.ts +19 -0
- package/dist/rpc/notifications.d.ts +2 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.d.ts +8 -4
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.d.ts +2 -0
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/rpc/rpc-server.d.ts +5 -1
- package/dist/setup/command.d.ts +12 -0
- package/dist/setup/command.test.d.ts +1 -0
- package/dist/setup/detect.d.ts +7 -4
- package/dist/setup/host-executable.d.ts +3 -0
- package/dist/setup/native-activation.d.ts +29 -0
- package/dist/setup/native-enrollment.d.ts +26 -0
- package/dist/setup/native-enrollment.test.d.ts +1 -0
- package/dist/setup/native-local.d.ts +20 -0
- package/dist/setup/native-login.d.ts +3 -0
- package/dist/setup/native-paths.d.ts +15 -0
- package/dist/setup/native-paths.test.d.ts +1 -0
- package/dist/setup/paths.d.ts +3 -2
- package/dist/setup/pi.d.ts +14 -4
- package/dist/setup/process-fence.d.ts +7 -1
- package/dist/setup/process-fence.test.d.ts +1 -0
- package/dist/sidebar-state.js +1 -1
- package/dist/tui/command-dialogs.d.ts +5 -0
- package/dist/tui-preferences.js +2 -2
- package/dist/v2/activation.d.ts +7 -0
- package/dist/v2/adapter.d.ts +276 -0
- package/dist/v2/install.d.ts +13 -0
- package/dist/v2/lifecycle.d.ts +8 -0
- package/dist/v2/menu-contract.d.ts +8 -0
- package/dist/v2/menu.d.ts +10 -0
- package/dist/v2/models.d.ts +6 -0
- package/dist/v2/ownership.d.ts +11 -0
- package/dist/v2/prime.d.ts +12 -0
- package/dist/v2/rpc.d.ts +50 -0
- package/dist/v2/server.d.ts +8 -0
- package/dist/v2/server.js +4 -0
- package/dist/v2/setup.d.ts +58 -0
- package/dist/v2/source.d.ts +41 -0
- package/dist/v2/tui.d.ts +13 -0
- package/dist/v2/tui.js +2 -0
- package/dist/v2/wire.d.ts +36 -0
- package/package.json +20 -5
- package/src/rpc/notifications.ts +9 -2
- package/src/rpc/protocol.ts +8 -7
- package/src/rpc/rpc-client.ts +17 -0
- package/src/rpc/rpc-server.ts +20 -3
- package/src/tui/command-dialogs.tsx +264 -0
- package/src/tui/entry.mjs +44 -18
- package/src/tui-compiled/rpc/protocol.ts +8 -7
- package/src/tui-compiled/rpc/rpc-client.ts +17 -0
- package/src/tui-compiled/tui/command-dialogs.tsx +315 -76
- package/src/tui-compiled/tui.tsx +24 -7
- package/src/tui.tsx +37 -9
- package/dist/claustrum-enrollment-registry.d.ts +0 -4
- package/dist/custody-enrollment.d.ts +0 -14
- package/dist/custody-live.d.ts +0 -111
- package/dist/custody-manifest-watcher.d.ts +0 -16
- package/dist/index-1fq7h6yd.js +0 -430
- package/dist/index-797pmamn.js +0 -2
- package/dist/index-a5d6v3ba.js +0 -5
- package/dist/index-n96q8pks.js +0 -2
- package/dist/index-xxhyhp98.js +0 -2
- package/dist/index-z7gfdyv3.js +0 -1
- package/dist/local-login.d.ts +0 -64
- package/dist/logger-kk9vyem9.js +0 -1
- package/dist/setup/claustrum.d.ts +0 -26
package/dist/cli.js
CHANGED
|
@@ -1,97 +1,120 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as NF,d as PF,g as IF}from"./index-797pmamn.js";import{$d as e1,Aa as LF,Ba as UF,G as YF,H as KF,Ia as kF,Ka as DF,Ld as w0,Na as e,Nd as o1,Oa as HF,Pd as l0,Rd as s1,Sa as q0,U as MF,Vd as t1,Wa as VF,Wf as wF,Ya as n1,_a as bF,_f as hF,dc as F1}from"./index-1fq7h6yd.js";import"./index-a5d6v3ba.js";import{nh as _3}from"./index-xxhyhp98.js";import{th as u0,uh as xF,vh as z0}from"./index-n96q8pks.js";var A0=xF((Df,L1)=>{var C0={to(F,f){if(!f)return`\x1B[${F+1}G`;return`\x1B[${f+1};${F+1}H`},move(F,f){let $="";if(F<0)$+=`\x1B[${-F}D`;else if(F>0)$+=`\x1B[${F}C`;if(f<0)$+=`\x1B[${-f}A`;else if(f>0)$+=`\x1B[${f}B`;return $},up:(F=1)=>`\x1B[${F}A`,down:(F=1)=>`\x1B[${F}B`,forward:(F=1)=>`\x1B[${F}C`,backward:(F=1)=>`\x1B[${F}D`,nextLine:(F=1)=>"\x1B[E".repeat(F),prevLine:(F=1)=>"\x1B[F".repeat(F),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},yF={up:(F=1)=>"\x1B[S".repeat(F),down:(F=1)=>"\x1B[T".repeat(F)},aF={screen:"\x1B[2J",up:(F=1)=>"\x1B[1J".repeat(F),down:(F=1)=>"\x1B[J".repeat(F),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(F){let f="";for(let $=0;$<F;$++)f+=this.line+($<F-1?C0.up():"");if(F)f+=C0.left;return f}};L1.exports={cursor:C0,scroll:yF,erase:aF,beep:"\x07"}});import{stdin as s3,stdout as t3}from"node:process";import{createInterface as e3}from"node:readline/promises";import{styleText as m0}from"node:util";import{stdout as p0,stdin as H1}from"node:process";import*as a from"node:readline";import TF from"node:readline";var f1=(()=>{let F=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(f)=>{let $=0;F.lastIndex=0;while(F.test(f))$+=1;return f.length-$}})(),$1=(F)=>{return F===12288||F>=65281&&F<=65376||F>=65504&&F<=65510},J1=(F)=>{return F===8987||F===9001||F>=12272&&F<=12287||F>=12289&&F<=12350||F>=12441&&F<=12543||F>=12549&&F<=12591||F>=12593&&F<=12686||F>=12688&&F<=12771||F>=12783&&F<=12830||F>=12832&&F<=12871||F>=12880&&F<=19903||F>=65040&&F<=65049||F>=65072&&F<=65106||F>=65108&&F<=65126||F>=65128&&F<=65131||F>=127488&&F<=127490||F>=127504&&F<=127547||F>=127552&&F<=127560||F>=131072&&F<=196605||F>=196608&&F<=262141};var OF=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,BF=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,j1=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,gF=/\t{1,1000}/y,W1=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,CF=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,AF=/\p{M}+/gu,RF={limit:1/0,ellipsis:""},Z1=(F,f={},$={})=>{let J=f.limit??1/0,j=f.ellipsis??"",W=f?.ellipsisWidth??(j?Z1(j,RF,$).width:0),Q=0,Z=$.controlWidth??0,z=$.tabWidth??8,Y=$.emojiWidth??2,X=2,G=$.regularWidth??1,K=$.wideWidth??2,L=[[CF,G],[OF,0],[BF,Z],[gF,z],[W1,Y],[j1,K]],M=0,k=0,h=F.length,E=0,B=!1,O=h,U=Math.max(0,J-W),D=0,v=0,P=0,H=0;F:while(!0){if(v>D||k>=h&&k>M){let V=F.slice(D,v)||F.slice(M,k);E=0;for(let m of V.replaceAll(AF,"")){let C=m.codePointAt(0)||0;if($1(C))H=2;else if(J1(C))H=K;else H=G;if(P+H>U)O=Math.min(O,Math.max(D,M)+E);if(P+H>J){B=!0;break F}E+=m.length,P+=H}D=v=0}if(k>=h)break F;for(let V=0,m=L.length;V<m;V++){let[C,G0]=L[V];if(C.lastIndex=k,C.test(F)){if(E=C===j1?f1(F.slice(k,C.lastIndex)):C===W1?1:C.lastIndex-k,H=E*G0,P+H>U)O=Math.min(O,k+Math.floor((U-P)/G0));if(P+H>J){B=!0;break F}P+=H,D=M,v=k,k=M=C.lastIndex;continue F}}k+=1}return{width:B?U:P,index:B?O:h,truncated:B,ellipsed:B&&J>=W}},Q1=Z1;var mF={limit:1/0,ellipsis:"",ellipsisWidth:0},SF=(F,f={})=>{return Q1(F,mF,f).width},R=SF;var K0="\x1B",X1="",uF=39,B0="\x07",K1="[",pF="]",M1="m",g0=`${pF}8;;`,z1=new RegExp(`(?:\\${K1}(?<code>\\d+)m|\\${g0}(?<uri>.*)${B0})`,"y"),Y1=(F)=>{if(F>=30&&F<=37)return 39;if(F>=90&&F<=97)return 39;if(F>=40&&F<=47)return 49;if(F>=100&&F<=107)return 49;if(F===1||F===2)return 22;if(F===3)return 23;if(F===4)return 24;if(F===7)return 27;if(F===8)return 28;if(F===9)return 29;if(F===0)return 0;return},q1=(F)=>`${K0}${K1}${F}${M1}`,G1=(F)=>`${K0}${g0}${F}${B0}`,O0=(F,f,$)=>{let J=f[Symbol.iterator](),j=!1,W=!1,Q=F.at(-1),Z=Q===void 0?0:R(Q),z=J.next(),Y=J.next(),X=0;while(!z.done){let G=z.value,K=R(G);if(Z+K<=$)F[F.length-1]+=G;else F.push(G),Z=0;if(G===K0||G===X1)j=!0,W=f.startsWith(g0,X+1);if(j){if(W){if(G===B0)j=!1,W=!1}else if(G===M1)j=!1}else if(Z+=K,Z===$&&!Y.done)F.push(""),Z=0;z=Y,Y=J.next(),X+=G.length}if(Q=F.at(-1),!Z&&Q!==void 0&&Q.length&&F.length>1)F[F.length-2]+=F.pop()},dF=(F)=>{let f=F.split(" "),$=f.length;while($){if(R(f[$-1]))break;$--}if($===f.length)return F;return f.slice(0,$).join(" ")+f.slice($).join("")},cF=(F,f,$={})=>{if($.trim!==!1&&F.trim()==="")return"";let J="",j,W,Q=F.split(" "),Z=[""],z=0;for(let G=0;G<Q.length;G++){let K=Q[G];if($.trim!==!1){let M=Z.at(-1)??"",k=M.trimStart();if(M.length!==k.length)Z[Z.length-1]=k,z=R(k)}if(G!==0){if(z>=f&&($.wordWrap===!1||$.trim===!1))Z.push(""),z=0;if(z||$.trim===!1)Z[Z.length-1]+=" ",z++}let L=R(K);if($.hard&&L>f){let M=f-z,k=1+Math.floor((L-M-1)/f);if(Math.floor((L-1)/f)<k)Z.push("");O0(Z,K,f),z=R(Z.at(-1)??"");continue}if(z+L>f&&z&&L){if($.wordWrap===!1&&z<f){O0(Z,K,f),z=R(Z.at(-1)??"");continue}Z.push(""),z=0}if(z+L>f&&$.wordWrap===!1){O0(Z,K,f),z=R(Z.at(-1)??"");continue}Z[Z.length-1]+=K,z+=L}if($.trim!==!1)Z=Z.map((G)=>dF(G));let Y=Z.join(`
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
`).
|
|
11
|
-
`)}function b1(F,f){if("~standard"in F){let $=F["~standard"].validate(f);return $ instanceof Promise?$.then((J)=>J.issues?.at(0)?.message):$.issues?.at(0)?.message}return F(f)}class l{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";get accessible(){return rF(this.opts.accessible)}constructor(F,f=!0){let{input:$=H1,output:J=p0,render:j,signal:W,...Q}=F;this.opts=Q,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=j.bind(this),this._track=f,this._abortSignal=W,this.input=$,this.output=J}unsubscribe(){this._subscribers.clear()}setSubscriber(F,f){let $=this._subscribers.get(F)??[];$.push(f),this._subscribers.set(F,$)}on(F,f){this.setSubscriber(F,{cb:f})}once(F,f){this.setSubscriber(F,{cb:f,once:!0})}emit(F,...f){let $=this._subscribers.get(F)??[],J=[];for(let j of $)j.cb(...f),j.once&&J.push(()=>$.splice($.indexOf(j),1));for(let j of J)j()}prompt(){return new Promise((F)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),F(k0);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=TF.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),L0(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(A.cursor.show),this.output.off("resize",this.render),L0(this.input,!1),F(this.value)}),this.once("cancel",()=>{this.output.write(A.cursor.show),this.output.off("resize",this.render),L0(this.input,!1),F(k0)})})}_isActionKey(F,f){return F==="\t"}_shouldSubmit(F,f){return!0}_setValue(F){this.value=F,this.emit("value",this.value)}_setUserInput(F,f){this.userInput=F??"",this.emit("userInput",this.userInput),f&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}async onKeypress(F,f){if(this.state!=="validating"){if(this._track&&f.name!=="return"&&(f.name&&this._isActionKey(F,f)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),f?.name&&(!this._track&&g.aliases.has(f.name)&&this.emit("cursor",g.aliases.get(f.name)),g.actions.has(f.name)&&this.emit("cursor",f.name)),F&&(F.toLowerCase()==="y"||F.toLowerCase()==="n")&&this.emit("confirm",F.toLowerCase()==="y"),this.emit("key",F,f),f?.name==="return"&&this._shouldSubmit(F,f)){if(this.opts.validate){let $=b1(this.opts.validate,this.value),J;$ instanceof Promise?(this.state="validating",this.render(),J=await $):J=$,J&&(this.error=J instanceof Error?J.message:J,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}d0([F,f?.name,f?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
12
|
-
`),L0(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let F=c(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
13
|
-
`).length-1;this.output.write(A.cursor.move(-999,F*-1))}render(){let F=c(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(F!==this._prevFrame){if(this.state==="initial")this.output.write(A.cursor.hide);else{let f=nF(this._prevFrame,F),$=c0(this.output);if(this.restoreCursor(),f){let J=Math.max(0,f.numLinesAfter-$),j=Math.max(0,f.numLinesBefore-$),W=f.lines.find((Q)=>Q>=J);if(W===void 0){this._prevFrame=F;return}if(f.lines.length===1){this.output.write(A.cursor.move(0,W-j)),this.output.write(A.erase.lines(1));let Q=F.split(`
|
|
14
|
-
`);this.output.write(Q[W]),this._prevFrame=F,this.output.write(A.cursor.move(0,Q.length-W-1));return}else if(f.lines.length>1){if(J<j)W=J;else{let Z=W-j;Z>0&&this.output.write(A.cursor.move(0,Z))}this.output.write(A.erase.down());let Q=F.split(`
|
|
15
|
-
`).slice(W);this.output.write(Q.join(`
|
|
16
|
-
`)),this._prevFrame=F;return}}this.output.write(A.erase.down())}this.output.write(F),this.state==="initial"&&(this.state="active"),this._prevFrame=F}}}function sF(F,f){if(F===void 0||f.length===0)return 0;let $=f.findIndex((J)=>J.value===F);return $!==-1?$:0}function tF(F,f){return(f.label??String(f.value)).toLowerCase().includes(F.toLowerCase())}function eF(F,f){if(f)return F?f:f[0]}var F3=class extends l{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#f=0;#j="";#F;#Z;#Q;#$;get cursor(){return this.#f}get userInputWithCursor(){if(!this.userInput)return m0(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let f=this.userInput.slice(0,this.cursor),$=this.userInput.slice(this.cursor,this.cursor+1),J=this.userInput.slice(this.cursor+1);return`${f}${m0("inverse",$)}${J}`}get options(){return typeof this.#Z=="function"?this.#Z():this.#Z}constructor(f){super(f),this.#Z=f.options,this.#Q=f.placeholder,this.#$=f.completeOnTab===!0;let $=this.options;this.filteredOptions=[...$],this.multiple=f.multiple===!0,this.#F=typeof f.options=="function"?f.filter:f.filter??tF;let J;if(f.initialValue&&Array.isArray(f.initialValue)?this.multiple?J=f.initialValue:J=f.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(J=[this.options[0]?.value]),J)for(let j of J){let W=$.findIndex((Q)=>Q.value===j);W!==-1&&(this.toggleSelected(j),this.#f=W)}this.focusedValue=this.options[this.#f]?.value,this.on("key",(j,W)=>this.#J(j,W)),this.on("userInput",(j)=>this.#W(j))}_isActionKey(f,$){return f==="\t"||this.multiple&&this.isNavigating&&$.name==="space"&&f!==void 0&&f!==""}#J(f,$){let J=$.name==="up",j=$.name==="down",W=$.name==="return",Q=this.userInput===""||this.userInput==="\t",Z=this.#Q,z=this.options,Y=Z!==void 0&&Z!==""&&z.some((X)=>!X.disabled&&(this.#F?this.#F(Z,X):!0));if($.name==="tab"&&Q&&Y){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(Z,!0),this.isNavigating=!1;return}if($.name==="tab"&&this.#$&&!this.multiple&&this.focusedValue!==void 0){let X=String(this.focusedValue);this._clearUserInput(),this._setUserInput(X,!0),this.isNavigating=!1;return}J||j?(this.#f=o(this.#f,J?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#f]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):W?this.value=eF(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&($.name==="tab"||this.isNavigating&&$.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(f){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(f)?this.selectedValues=this.selectedValues.filter(($)=>$!==f):this.selectedValues=[...this.selectedValues,f]:this.selectedValues=[f])}#W(f){if(f!==this.#j){this.#j=f;let $=this.options;f&&this.#F?this.filteredOptions=$.filter((W)=>this.#F?.(f,W)):this.filteredOptions=[...$];let J=sF(this.focusedValue,this.filteredOptions);this.#f=o(J,0,this.filteredOptions);let j=this.filteredOptions[this.#f];j&&!j.disabled?this.focusedValue=j.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class _0 extends l{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(F){super(F,!1),this.value=!!F.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(f)=>{this.output.write(A.cursor.move(0,-1)),this.value=f,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var f3={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function k1(F){return[...F].map((f)=>f3[f])}function $3(F){let f=new Intl.DateTimeFormat(F,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),$=[],J="/";for(let j of f)j.type==="literal"?J=j.value.trim()||j.value:(j.type==="year"||j.type==="month"||j.type==="day")&&$.push({type:j.type,len:j.type==="year"?4:2});return{segments:$,separator:J}}function R0(F){return Number.parseInt((F||"0").replace(/_/g,"0"),10)||0}function U0(F){return{year:R0(F.year),month:R0(F.month),day:R0(F.day)}}function S0(F,f){return new Date(F||2001,f||1,0).getDate()}function w1(F){let{year:f,month:$,day:J}=U0(F);if(!f||f<0||f>9999||!$||$<1||$>12||!J||J<1)return;let j=new Date(Date.UTC(f,$-1,J));if(!(j.getUTCFullYear()!==f||j.getUTCMonth()!==$-1||j.getUTCDate()!==J))return{year:f,month:$,day:J}}function D1(F){let f=w1(F);return f?new Date(Date.UTC(f.year,f.month-1,f.day)):void 0}function J3(F,f,$,J){let j=$?{year:$.getUTCFullYear(),month:$.getUTCMonth()+1,day:$.getUTCDate()}:null,W=J?{year:J.getUTCFullYear(),month:J.getUTCMonth()+1,day:J.getUTCDate()}:null;return F==="year"?{min:j?.year??1,max:W?.year??9999}:F==="month"?{min:j&&f.year===j.year?j.month:1,max:W&&f.year===W.year?W.month:12}:{min:j&&f.year===j.year&&f.month===j.month?j.day:1,max:W&&f.year===W.year&&f.month===W.month?W.day:S0(f.year,f.month)}}class h1 extends l{#f;#j;#F;#Z;#Q;#$={segmentIndex:0,positionInSegment:0};#J=!0;#W=null;inlineError="";get segmentCursor(){return{...this.#$}}get segmentValues(){return{...this.#F}}get segments(){return this.#f}get separator(){return this.#j}get formattedValue(){return this.#G(this.#F)}#G(F){return this.#f.map((f)=>F[f.type]).join(this.#j)}#z(){this._setUserInput(this.#G(this.#F)),this._setValue(D1(this.#F)??void 0)}constructor(F){let f=F.format?{segments:k1(F.format),separator:F.separator??"/"}:$3(F.locale),$=F.separator??f.separator,J=F.format?k1(F.format):f.segments,j=F.initialValue??F.defaultValue,W=j?{year:String(j.getUTCFullYear()).padStart(4,"0"),month:String(j.getUTCMonth()+1).padStart(2,"0"),day:String(j.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},Q=J.map((Z)=>W[Z.type]).join($);super({...F,initialUserInput:Q},!1),this.#f=J,this.#j=$,this.#F=W,this.#Z=F.minDate,this.#Q=F.maxDate,this.#z(),this.on("cursor",(Z)=>this.#M(Z)),this.on("key",(Z,z)=>this.#L(Z,z)),this.on("finalize",()=>this.#U(F))}#Y(){let F=Math.max(0,Math.min(this.#$.segmentIndex,this.#f.length-1)),f=this.#f[F];if(f)return this.#$.positionInSegment=Math.max(0,Math.min(this.#$.positionInSegment,f.len-1)),{segment:f,index:F}}#q(F){this.inlineError="",this.#W=null;let f=this.#Y();f&&(this.#$.segmentIndex=Math.max(0,Math.min(this.#f.length-1,f.index+F)),this.#$.positionInSegment=0,this.#J=!0)}#X(F){let f=this.#Y();if(!f)return;let{segment:$}=f,J=this.#F[$.type],j=!J||J.replace(/_/g,"")==="",W=Number.parseInt((J||"0").replace(/_/g,"0"),10)||0,Q=J3($.type,U0(this.#F),this.#Z,this.#Q),Z;j?Z=F===1?Q.min:Q.max:Z=Math.max(Math.min(Q.max,W+F),Q.min),this.#F={...this.#F,[$.type]:Z.toString().padStart($.len,"0")},this.#J=!0,this.#W=null,this.#z()}#M(F){if(F)switch(F){case"right":return this.#q(1);case"left":return this.#q(-1);case"up":return this.#X(1);case"down":return this.#X(-1)}}#L(F,f){if(f?.name==="backspace"||f?.sequence===""||f?.sequence==="\b"||F===""||F==="\b"){this.inlineError="";let $=this.#Y();if(!$)return;if(!this.#F[$.segment.type].replace(/_/g,"")){this.#q(-1);return}this.#F[$.segment.type]="_".repeat($.segment.len),this.#J=!0,this.#$.positionInSegment=0,this.#z();return}if(f?.name==="tab"){this.inlineError="";let $=this.#Y();if(!$)return;let J=f.shift?-1:1,j=$.index+J;j>=0&&j<this.#f.length&&(this.#$.segmentIndex=j,this.#$.positionInSegment=0,this.#J=!0);return}if(F&&/^[0-9]$/.test(F)){let $=this.#Y();if(!$)return;let{segment:J}=$,j=!this.#F[J.type].replace(/_/g,"");if(this.#J&&this.#W!==null&&!j){let K=this.#W+F,L={...this.#F,[J.type]:K},M=this.#K(L,J);if(M){this.inlineError=M,this.#W=null,this.#J=!1;return}this.inlineError="",this.#F[J.type]=K,this.#W=null,this.#J=!1,this.#z(),$.index<this.#f.length-1&&(this.#$.segmentIndex=$.index+1,this.#$.positionInSegment=0,this.#J=!0);return}this.#J&&!j&&(this.#F[J.type]="_".repeat(J.len),this.#$.positionInSegment=0),this.#J=!1,this.#W=null;let W=this.#F[J.type],Q=W.indexOf("_"),Z=Q>=0?Q:Math.min(this.#$.positionInSegment,J.len-1);if(Z<0||Z>=J.len)return;let z=W.slice(0,Z)+F+W.slice(Z+1),Y=!1;if(Z===0&&W==="__"&&(J.type==="month"||J.type==="day")){let K=Number.parseInt(F,10);z=`0${F}`,Y=K<=(J.type==="month"?1:2)}if(J.type==="year"&&(z=(W.replace(/_/g,"")+F).padStart(J.len,"_")),!z.includes("_")){let K={...this.#F,[J.type]:z},L=this.#K(K,J);if(L){this.inlineError=L;return}}this.inlineError="",this.#F[J.type]=z;let X=z.includes("_")?void 0:w1(this.#F);if(X){let{year:K,month:L}=X,M=S0(K,L);this.#F={year:String(Math.max(0,Math.min(9999,K))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,L))).padStart(2,"0"),day:String(Math.max(1,Math.min(M,X.day))).padStart(2,"0")}}this.#z();let G=z.indexOf("_");Y?(this.#J=!0,this.#W=F):G>=0?this.#$.positionInSegment=G:Q>=0&&$.index<this.#f.length-1?(this.#$.segmentIndex=$.index+1,this.#$.positionInSegment=0,this.#J=!0):this.#$.positionInSegment=Math.min(Z+1,J.len-1)}}#K(F,f){let{month:$,day:J}=U0(F);if(f.type==="month"&&($<0||$>12))return g.date.messages.invalidMonth;if(f.type==="day"&&(J<0||J>31))return g.date.messages.invalidDay(31,"any month")}#U(F){let{year:f,month:$,day:J}=U0(this.#F);if(f&&$&&J){let j=S0(f,$);this.#F={...this.#F,day:String(Math.min(J,j)).padStart(2,"0")}}this.value=D1(this.#F)??F.defaultValue??void 0}}var j3=class extends l{options;cursor=0;#f;getGroupItems(f){return this.options.filter(($)=>$.group===f)}isGroupSelected(f){let $=this.getGroupItems(f),J=this.value;return J===void 0?!1:$.every((j)=>J.includes(j.value))}toggleValue(){let f=this.options[this.cursor];if(f!==void 0)if(this.value===void 0&&(this.value=[]),f.group===!0){let $=f.value,J=this.getGroupItems($);this.isGroupSelected($)?this.value=this.value.filter((j)=>J.findIndex((W)=>W.value===j)===-1):this.value=[...this.value,...J.map((j)=>j.value)],this.value=Array.from(new Set(this.value))}else{let $=this.value.includes(f.value);this.value=$?this.value.filter((J)=>J!==f.value):[...this.value,f.value]}}constructor(f){super(f,!1);let{options:$}=f;this.#f=f.selectableGroups!==!1,this.options=Object.entries($).flatMap(([J,j])=>[{value:J,group:!0,label:J},...j.map((W)=>({...W,group:J}))]),this.value=[...f.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:J})=>J===f.cursorAt),this.#f?0:1),this.on("cursor",(J)=>{switch(J){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let j=this.options[this.cursor]?.group===!0;!this.#f&&j&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let j=this.options[this.cursor]?.group===!0;!this.#f&&j&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},W3=new Set(["up","down","left","right"]);class N1 extends l{#f=!1;#j;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let F=this.userInput;if(this.cursor>=F.length)return`${F}█`;let f=F.slice(0,this.cursor),$=F.slice(this.cursor,this.cursor+1),J=F.slice(this.cursor+1);return $===`
|
|
17
|
-
`?`${f}█
|
|
18
|
-
${J}`:`${f}${m0("inverse",$)}${J}`}get cursor(){return this._cursor}#F(F){if(this.userInput.length===0){this._setUserInput(F);return}this._setUserInput(this.userInput.slice(0,this.cursor)+F+this.userInput.slice(this.cursor))}#Z(F){let f=this.value??"";switch(F){case"up":this._cursor=M0(this._cursor,0,-1,f);return;case"down":this._cursor=M0(this._cursor,0,1,f);return;case"left":this._cursor=M0(this._cursor,-1,0,f);return;case"right":this._cursor=M0(this._cursor,1,0,f);return}}_shouldSubmit(F,f){if(this.#j)return this.focused==="submit"?!0:(this.#F(`
|
|
19
|
-
`),this._cursor++,!1);let $=this.#f;return this.#f=!0,$&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
|
|
20
|
-
`&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#F(`
|
|
21
|
-
`),this._cursor++,!1)}constructor(F){let f=F.initialUserInput??F.initialValue;super({...F,initialUserInput:f},!1),f!==void 0&&(this._cursor=f.length),this.#j=F.showSubmit??!1,this.on("key",($,J)=>{if(J?.name&&W3.has(J.name)){this.#f=!1,this.#Z(J.name);return}if($==="\t"&&this.#j){this.focused=this.focused==="editor"?"submit":"editor";return}if(J?.name!=="return"){if(this.#f=!1,J?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(J?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}$&&(this.#j&&this.focused==="submit"&&(this.focused="editor"),this.#F($??""),this._cursor++)}}),this.on("userInput",($)=>{this._setValue($)}),this.on("finalize",()=>{this.value||(this.value=F.defaultValue),this.value===void 0&&(this.value="")})}}class x0 extends l{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((F)=>F.disabled!==!0)}toggleAll(){let F=this._enabledOptions,f=this.value!==void 0&&this.value.length===F.length;this.value=f?[]:F.map(($)=>$.value)}toggleInvert(){let F=this.value;if(!F)return;let f=this._enabledOptions.filter(($)=>!F.includes($.value));this.value=f.map(($)=>$.value)}toggleValue(){this.value===void 0&&(this.value=[]);let F=this.value.includes(this._value);this.value=F?this.value.filter((f)=>f!==this._value):[...this.value,this._value]}constructor(F){super(F,!1),this.options=F.options,this.value=[...F.initialValues??[]];let f=Math.max(this.options.findIndex(({value:$})=>$===F.cursorAt),0);this.cursor=this.options[f]?.disabled?o(f,1,this.options):f,this.on("key",($,J)=>{J.name==="a"&&this.toggleAll(),J.name==="i"&&this.toggleInvert()}),this.on("cursor",($)=>{switch($){case"left":case"up":this.cursor=o(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=o(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}import{styleText as q,stripVTControlCharacters as Cf}from"node:util";import p from"node:process";var j0=u0(A0(),1);function Z3(){if(p.platform!=="win32")return p.env.TERM!=="linux";return Boolean(p.env.CI)||Boolean(p.env.WT_SESSION)||Boolean(p.env.TERMINUS_SUBLIME)||p.env.ConEmuTask==="{cmd::Cmder}"||p.env.TERM_PROGRAM==="Terminus-Sublime"||p.env.TERM_PROGRAM==="vscode"||p.env.TERM==="xterm-256color"||p.env.TERM==="alacritty"||p.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var y0=Z3(),Q3=()=>process.env.CI==="true";var b=(F,f)=>y0?F:f,P1=b("◆","*"),A1=b("■","x"),R1=b("▲","x"),D0=b("◇","o"),z3=b("┌","T"),w=b("│","|"),W0=b("└","—"),Sf=b("┐","T"),uf=b("┘","—"),I1=b("●",">"),E1=b("○"," "),Y3=b("◻","[•]"),v1=b("◼","[+]"),O1=b("◻","[ ]"),pf=b("▪","•"),B1=b("─","-"),q3=b("╮","+"),G3=b("├","+"),X3=b("╯","+"),K3=b("╰","+"),df=b("╭","+"),M3=b("●","•"),L3=b("◆","*"),U3=b("▲","!"),k3=b("■","x"),m1=(F)=>{switch(F){case"initial":case"active":return q("cyan",P1);case"cancel":return q("red",A1);case"error":return q("yellow",R1);case"submit":return q("green",D0);case"validating":return q("dim",P1)}},D3=(F)=>{switch(F){case"initial":case"active":return q("cyan",w);case"cancel":return q("red",w);case"error":return q("yellow",w);case"submit":return q("green",w)}};function H3(F,f){let $=[`${f?`${q("cyan",w)} `:""}${F.join(" • ")}`];return f&&$.push(q("cyan",W0)),$}var g1=(F,f,$,J,j,W=!1)=>{let Q=f,Z=0;if(W)for(let z=J-1;z>=$;z--){let Y=F[z];if(Y&&(Q-=Y.length),Z++,Q<=j)break}else for(let z=$;z<J;z++){let Y=F[z];if(Y&&(Q-=Y.length),Z++,Q<=j)break}return{lineCount:Q,removals:Z}},C1=({cursor:F,options:f,style:$,output:J=process.stdout,maxItems:j=Number.POSITIVE_INFINITY,columnPadding:W=0,rowPadding:Q=4})=>{let Z=f0(J)-W,z=c0(J),Y=q("dim","..."),X=Math.max(z-Q,0),G=Math.max(Math.min(j,X),5),K=0;F>=G-3&&(K=Math.max(Math.min(F-G+3,f.length-G),0));let L=G<f.length&&K>0,M=G<f.length&&K+G<f.length,k=Math.min(K+G,f.length),h=[],E=0;L&&E++,M&&E++;let B=K+(L?1:0),O=k-(M?1:0);for(let D=B;D<O;D++){let v=f[D],P=v?$(v,D===F):"",H=c(P,Z,{hard:!0,trim:!1}).split(`
|
|
22
|
-
`);h.push(H),E+=H.length}if(E>X){let D=0,v=0,P=E,H=F-B,V=X,m=()=>g1(h,P,0,H,V),C=()=>g1(h,P,H+1,h.length,V,!0);L?({lineCount:P,removals:D}=m(),P>V&&(M||(V-=1),{lineCount:P,removals:v}=C())):(M||(V-=1),{lineCount:P,removals:v}=C(),P>V&&(V-=1,{lineCount:P,removals:D}=m())),D>0&&(L=!0,h.splice(0,D)),v>0&&(M=!0,h.splice(h.length-v,v))}let U=[];L&&U.push(Y);for(let D of h)for(let v of D)U.push(v);return M&&U.push(Y),U};var a0=(F)=>{let f=F.active??"Yes",$=F.inactive??"No";return new _0({active:f,inactive:$,signal:F.signal,input:F.input,output:F.output,initialValue:F.initialValue??!0,render(){let J=F.withGuide??g.withGuide,j=`${m1(this.state)} `,W=J?`${q("gray",w)} `:"",Q=$0(F.output,F.message,W,j),Z=`${J?`${q("gray",w)}
|
|
23
|
-
`:""}${Q}
|
|
24
|
-
`,z=this.value?f:$;switch(this.state){case"submit":{let Y=J?`${q("gray",w)} `:"";return`${Z}${Y}${q("dim",z)}`}case"cancel":{let Y=J?`${q("gray",w)} `:"";return`${Z}${Y}${q(["strikethrough","dim"],z)}${J?`
|
|
25
|
-
${q("gray",w)}`:""}`}default:{let Y=J?`${q("cyan",w)} `:"",X=J?q("cyan",W0):"";return`${Z}${Y}${this.value?`${q("green",I1)} ${f}`:`${q("dim",E1)} ${q("dim",f)}`}${F.vertical?J?`
|
|
26
|
-
${q("cyan",w)} `:`
|
|
27
|
-
`:` ${q("dim","/")} `}${this.value?`${q("dim",E1)} ${q("dim",$)}`:`${q("green",I1)} ${$}`}
|
|
28
|
-
${X}
|
|
29
|
-
`}}}}).prompt()};var V3=[`${q("dim","↑/↓")} to navigate`,`${q("dim","Space:")} select`,`${q("dim","Enter:")} confirm`],J0=(F,f)=>F.split(`
|
|
30
|
-
`).map(($)=>f($)).join(`
|
|
31
|
-
`),S1=(F)=>{let f=(j,W)=>{let Q=j.label??String(j.value);return W==="disabled"?`${q("gray",O1)} ${J0(Q,(Z)=>q(["strikethrough","gray"],Z))}${j.hint?` ${q("dim",`(${j.hint??"disabled"})`)}`:""}`:W==="active"?`${q("cyan",Y3)} ${Q}${j.hint?` ${q("dim",`(${j.hint})`)}`:""}`:W==="selected"?`${q("green",v1)} ${J0(Q,(Z)=>q("dim",Z))}${j.hint?` ${q("dim",`(${j.hint})`)}`:""}`:W==="cancelled"?`${J0(Q,(Z)=>q(["strikethrough","dim"],Z))}`:W==="active-selected"?`${q("green",v1)} ${Q}${j.hint?` ${q("dim",`(${j.hint})`)}`:""}`:W==="submitted"?`${J0(Q,(Z)=>q("dim",Z))}`:`${q("dim",O1)} ${J0(Q,(Z)=>q("dim",Z))}`},$=F.required??!0,J=F.showInstructions??!0;return new x0({options:F.options,signal:F.signal,input:F.input,output:F.output,initialValues:F.initialValues,required:$,cursorAt:F.cursorAt,validate(j){if($&&(j===void 0||j.length===0))return`Please select at least one option.
|
|
32
|
-
${q("reset",q("dim",`Press ${q(["gray","bgWhite","inverse"]," space ")} to select, ${q("gray",q("bgWhite",q("inverse"," enter ")))} to submit`))}`},render(){let j=F.withGuide??g.withGuide,W=$0(F.output,F.message,j?`${D3(this.state)} `:"",`${m1(this.state)} `),Q=`${j?`${q("gray",w)}
|
|
33
|
-
`:""}${W}
|
|
34
|
-
`,Z=this.value??[],z=(Y,X)=>{if(Y.disabled)return f(Y,"disabled");let G=Z.includes(Y.value);return X&&G?f(Y,"active-selected"):G?f(Y,"selected"):f(Y,X?"active":"inactive")};switch(this.state){case"submit":{let Y=this.options.filter(({value:G})=>Z.includes(G)).map((G)=>f(G,"submitted")).join(q("dim",", "))||q("dim","none"),X=$0(F.output,Y,j?`${q("gray",w)} `:"");return`${Q}${X}`}case"cancel":{let Y=this.options.filter(({value:G})=>Z.includes(G)).map((G)=>f(G,"cancelled")).join(q("dim",", "));if(Y.trim()==="")return`${Q}${q("gray",w)}`;let X=$0(F.output,Y,j?`${q("gray",w)} `:"");return`${Q}${X}${j?`
|
|
35
|
-
${q("gray",w)}`:""}`}case"error":{let Y=j?`${q("yellow",w)} `:"",X=this.error.split(`
|
|
36
|
-
`).map((L,M)=>M===0?`${j?`${q("yellow",W0)} `:""}${q("yellow",L)}`:` ${L}`).join(`
|
|
37
|
-
`),G=Q.split(`
|
|
38
|
-
`).length,K=X.split(`
|
|
39
|
-
`).length+1;return`${Q}${Y}${C1({output:F.output,options:this.options,cursor:this.cursor,maxItems:F.maxItems,columnPadding:Y.length,rowPadding:G+K,style:z}).join(`
|
|
40
|
-
${Y}`)}
|
|
41
|
-
${X}
|
|
42
|
-
`}default:{let Y=j?`${q("cyan",w)} `:"",X=Q.split(`
|
|
43
|
-
`).length,G=J?H3(V3,j):j?[q("cyan",W0)]:[],K=G.join(`
|
|
44
|
-
`),L=G.length+1;return`${Q}${Y}${C1({output:F.output,options:this.options,cursor:this.cursor,maxItems:F.maxItems,columnPadding:Y.length,rowPadding:X+L,style:z}).join(`
|
|
45
|
-
${Y}`)}
|
|
46
|
-
${K}
|
|
47
|
-
`}}}}).prompt()};var N={message:(F=[],{symbol:f=q("gray",w),secondarySymbol:$=q("gray",w),output:J=process.stdout,spacing:j=1,withGuide:W}={})=>{let Q=[],Z=W??g.withGuide,z=Z?$:"",Y=Z?`${f} `:"",X=Z?`${$} `:"";for(let K=0;K<j;K++)Q.push(z);let G=Array.isArray(F)?F:F.split(`
|
|
48
|
-
`);if(G.length>0){let[K,...L]=G;K.length>0?Q.push(`${Y}${K}`):Q.push(Z?f:"");for(let M of L)M.length>0?Q.push(`${X}${M}`):Q.push(Z?$:"")}J.write(`${Q.join(`
|
|
49
|
-
`)}
|
|
50
|
-
`)},info:(F,f)=>{N.message(F,{...f,symbol:q("blue",M3)})},success:(F,f)=>{N.message(F,{...f,symbol:q("green",L3)})},step:(F,f)=>{N.message(F,{...f,symbol:q("green",D0)})},warn:(F,f)=>{N.message(F,{...f,symbol:q("yellow",U3)})},warning:(F,f)=>{N.warn(F,f)},error:(F,f)=>{N.message(F,{...f,symbol:q("red",k3)})}};var u1=(F="",f)=>{let $=f?.output??process.stdout,J=f?.withGuide??g.withGuide?`${q("gray",z3)} `:"";$.write(`${J}${F}
|
|
51
|
-
`)},y=(F="",f)=>{let $=f?.output??process.stdout,J=f?.withGuide??g.withGuide?`${q("gray",w)}
|
|
52
|
-
${q("gray",W0)} `:"";$.write(`${J}${F}
|
|
53
|
-
|
|
54
|
-
`)};var b3=(F)=>F,w3=(F,f,$)=>{let J={hard:!0,trim:!1},j=c(F,f,J).split(`
|
|
55
|
-
`),W=j.reduce((z,Y)=>Math.max(R(Y),z),0),Q=j.map($).reduce((z,Y)=>Math.max(R(Y),z),0),Z=f-(Q-W);return c(F,Z,J)},p1=(F="",f="",$)=>{let J=$?.output??p.stdout,j=$?.withGuide??g.withGuide,W=$?.format??b3,Q=["",...w3(F,f0(J)-6,W).split(`
|
|
56
|
-
`).map(W),""],Z=R(f),z=Math.max(Q.reduce((K,L)=>{let M=R(L);return M>K?M:K},0),Z)+2,Y=Q.map((K)=>`${q("gray",w)} ${K}${" ".repeat(z-R(K))}${q("gray",w)}`).join(`
|
|
57
|
-
`),X=j?`${q("gray",w)}
|
|
58
|
-
`:"",G=j?G3:K3;J.write(`${X}${q("green",D0)} ${q("reset",f)} ${q("gray",B1.repeat(Math.max(z-Z-1,1))+q3)}
|
|
59
|
-
${Y}
|
|
60
|
-
${q("gray",G+B1.repeat(z+2)+X3)}
|
|
61
|
-
`)};var h3=(F)=>q("magenta",F),d1=({indicator:F="dots",onCancel:f,output:$=process.stdout,cancelMessage:J,errorMessage:j,frames:W=y0?["◒","◐","◓","◑"]:["•","o","O","0"],delay:Q=y0?80:120,signal:Z,...z}={})=>{let Y=Q3(),X,G,K=!1,L=!1,M="",k,h=performance.now(),E=f0($),B=z?.styleFrame??h3,O=(I)=>{let u=I>1?j??g.messages.error:J??g.messages.cancel;L=I===1,K&&(F0(u,I),L&&typeof f=="function"&&f())},U=()=>O(2),D=()=>O(1),v=()=>{process.on("uncaughtExceptionMonitor",U),process.on("unhandledRejection",U),process.on("SIGINT",D),process.on("SIGTERM",D),process.on("exit",O),Z&&Z.addEventListener("abort",D)},P=()=>{process.removeListener("uncaughtExceptionMonitor",U),process.removeListener("unhandledRejection",U),process.removeListener("SIGINT",D),process.removeListener("SIGTERM",D),process.removeListener("exit",O),Z&&Z.removeEventListener("abort",D)},H=()=>{if(k===void 0)return;Y&&$.write(`
|
|
62
|
-
`);let I=c(k,E,{hard:!0,trim:!1}).split(`
|
|
63
|
-
`);I.length>1&&$.write(j0.cursor.up(I.length-1)),$.write(j0.cursor.to(0)),$.write(j0.erase.down())},V=(I)=>I.replace(/\.+$/,""),m=(I)=>{let u=(performance.now()-I)/1000,_=Math.floor(u/60),x=Math.floor(u%60);return _>0?`[${_}m ${x}s]`:`[${x}s]`},C=z.withGuide??g.withGuide,G0=(I="")=>{K=!0,X=V1({output:$}),M=V(I),h=performance.now(),C&&$.write(`${q("gray",w)}
|
|
64
|
-
`);let u=0,_=0;v(),G=setInterval(()=>{if(Y&&M===k)return;H(),k=M;let x=B(W[u]),X0;if(Y)X0=`${x} ${M}...`;else if(F==="timer")X0=`${x} ${M} ${m(h)}`;else{let vF=".".repeat(Math.floor(_)).slice(0,3);X0=`${x} ${M}${vF}`}let EF=c(X0,E,{hard:!0,trim:!1});$.write(EF),u=u+1<W.length?u+1:0,_=_<4?_+0.125:0},Q)},F0=(I="",u=0,_=!1)=>{if(!K)return;K=!1,clearInterval(G),H();let x=u===0?q("green",D0):u===1?q("red",A1):q("red",R1);M=I??M,_||(F==="timer"?$.write(`${x} ${M} ${m(h)}
|
|
65
|
-
`):$.write(`${x} ${M}
|
|
66
|
-
`)),P(),X()};return{start:G0,stop:(I="")=>F0(I,0),message:(I="")=>{M=V(I??M)},cancel:(I="")=>F0(I,1),error:(I="")=>F0(I,2),clear:()=>F0("",0,!0),get isCancelled(){return L}}},cf={light:b("─","-"),heavy:b("━","="),block:b("█","#")};var _f=[`${q("dim","↑/↓")} to navigate`,`${q("dim","Enter:")} confirm`];var xf=`${q("gray",w)} `;import{existsSync as c1}from"node:fs";import{mkdir as O3,readFile as _1,rename as B3,unlink as g3,writeFile as C3}from"node:fs/promises";import{dirname as A3,join as R3}from"node:path";import{execFile as N3}from"node:child_process";import{promisify as P3}from"node:util";var I3=P3(N3),S={async run(F,f,$={}){try{let J=$.env?{...process.env,...$.env}:process.env,{stdout:j,stderr:W}=await I3(F,f,{env:J,timeout:$.timeoutMs??15000,maxBuffer:10485760});return{exitCode:0,stdout:typeof j==="string"?j:String(j),stderr:typeof W==="string"?W:String(W)}}catch(J){let j=J;return{exitCode:typeof j?.code==="number"?j.code:1,stdout:typeof j?.stdout==="string"?j.stdout:j?.stdout!=null?String(j.stdout):"",stderr:typeof j?.stderr==="string"?j.stderr:j?.stderr!=null?String(j.stderr):String(j?.message??J)}}}};var E3=/(?:^|\/)(opencode|litecode|opencode2|pi)(?:$|\s)/i;class H0 extends Error{activeHosts;constructor(F){let f=F.map(($)=>` - PID ${$.pid}: ${$.command.slice(0,80)}`).join(`
|
|
2
|
+
import{A as k1,B as U9,C as q9,D as L9,E as f9,u as l0,v as X1,w as C9,x as E0,y as G2,z as v0}from"./index-b3mxpp4w.js";import{$ as o0,Aa as w9,Bd as d0,Cd as Y2,Dd as A1,Ed as L2,Fd as b9,Jb as F2,Pd as E1,Qd as T3,Wb as P9,Xb as Z2,_ as F1,aa as H3,ba as R1,fe as g9,he as h9,id as f1,jd as K2,kd as T9,md as N0,qa as i1,qd as j2,ra as a1,rb as k9,sa as S3,ta as z2,wd as x3,xa as x9,xb as M2,yb as D2}from"./index-yxtdke11.js";import"./index-p4wvcwhh.js";import{Se as p2,Te as p4,Ue as j1}from"./index-3xqv3rw3.js";var u3=p4((QJ,y2)=>{var d3={to($,Z){if(!Z)return`\x1B[${$+1}G`;return`\x1B[${Z+1};${$+1}H`},move($,Z){let J="";if($<0)J+=`\x1B[${-$}D`;else if($>0)J+=`\x1B[${$}C`;if(Z<0)J+=`\x1B[${-Z}A`;else if(Z>0)J+=`\x1B[${Z}B`;return J},up:($=1)=>`\x1B[${$}A`,down:($=1)=>`\x1B[${$}B`,forward:($=1)=>`\x1B[${$}C`,backward:($=1)=>`\x1B[${$}D`,nextLine:($=1)=>"\x1B[E".repeat($),prevLine:($=1)=>"\x1B[F".repeat($),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},d4={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},u4={screen:"\x1B[2J",up:($=1)=>"\x1B[1J".repeat($),down:($=1)=>"\x1B[J".repeat($),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines($){let Z="";for(let J=0;J<$;J++)Z+=this.line+(J<$-1?d3.up():"");if($)Z+=d3.left;return Z}};y2.exports={cursor:d3,scroll:d4,erase:u4,beep:"\x07"}});import{stdin as v8,stdout as c8}from"node:process";import{createInterface as p8}from"node:readline/promises";import{randomUUID as $4}from"node:crypto";import{constants as S1}from"node:fs";import{lstat as Z4,mkdir as J4,open as Q4}from"node:fs/promises";import{homedir as z4}from"node:os";import{isAbsolute as U2,join as h3}from"node:path";import{types as y3}from"node:util";import{readFile as t7}from"node:fs/promises";import{appendFileSync as a9,chmodSync as n9,existsSync as $3,renameSync as V$,statSync as s9}from"node:fs";import{open as o9}from"node:fs/promises";import{dirname as r9,resolve as t9}from"node:path";import{randomUUID as y9}from"node:crypto";import{lstat as j$,readFile as H$,rename as m9,unlink as W$}from"node:fs/promises";import{dirname as q0,resolve as t}from"node:path";var A=process.platform==="win32",X$=new Set;function t1($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var K$;function x0(){return K$??=import("./index-zdgceztz.js"),K$}class l extends Error{path;stage;code;win32Code;reason;published=!1;durabilityConfirmed=!1;fileDurable=!1;attempts=0;elapsedMs=0;orphanPath;constructor($,Z,J){let Q=J;super(`Private file refused at ${Z}: ${$} (${Q?.reason??Q?.code??"io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`,{cause:J});this.path=$,this.stage=Z,this.name="PrivateFileError",this.code=t1(Q),this.win32Code=Q?.win32Code,this.reason=Q?.reason}}async function r($,Z,J){try{return await J()}catch(Q){if(Q instanceof l)throw Q;throw new l($,Z,Q)}}var v9;async function H0($,Z){$=t($),Z??=v9,await r($,"safe-parent",async()=>{let J=await(await x0()).verifySafeParent($,Z);if(J.ok===!1){if(J.reason==="io-error"||J.reason==="wrong-kind")await j$($);throw new l(J.level??J.path,"safe-parent",{...J,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function n($,Z,J=!1){if($=t($),Z==="directory")return H0($);await r($,"verify",async()=>{let Q=await x0(),z=await Q.verifyOwnerOnly($),Y=!1;if(!z.ok){let{reason:G}=z.refusal;if(G==="io-error")await Q.verifyPrivatePath($,Z);if(J&&[Q.EXTRA_ACE,Q.NOT_PROTECTED,Q.NULL_DACL,Q.EMPTY_DACL].includes(G))await H0(q0($)),await Q.securePrivatePath($,Z),Y=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:G,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await Q.verifyPrivatePath($,Z),Y&&!X$.has($))X$.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function z0($,Z=!1,J){$=t($),await r($,"directory",async()=>{let Q=await x0();try{return await j$($),await H0($,J)}catch(Y){if(t1(Y)!=="ENOENT")throw Y}let z=q0($);if(z===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await z0(z,!1,J);try{await Q.createOwnerOnly($,{kind:"dir"})}catch(Y){if(t1(Y)!=="EEXIST")throw Y}await H0($,J)})}async function Y0($,Z=!1){if(!A)return H$($,"utf8");return(await c9($,Z)).toString("utf8")}async function c9($,Z=!1){if(!A)return H$($);if($=t($),Z)await H0(q0($)),await n($,"file",!0);return r($,"read",async()=>(await x0()).readOwnerOnly($))}async function w0($,Z){await H0(q0(t($))),await r($,"create",async()=>{await(await x0()).createPrivateFile(t($),Z)})}async function U$($){await H0(q0(t($))),await r($,"directory-create",async()=>{await(await x0()).createOwnerOnly(t($),{kind:"dir"})})}async function e1($,Z,J={}){$=t($),Z=t(Z);let Q=J.now??(()=>performance.now()),z=Q(),Y=Math.min(z+500,J.deadline??1/0),G=[0,10,20,40,80,100],W,X=0;for(let H of G){if(Q()>=Y)break;if(H)await(J.sleep??((j)=>new Promise((U)=>setTimeout(U,j))))(Math.min(H,Math.max(0,Y-Q())));if(Q()>=Y)break;if(await J.beforeRename?.(),Q()>=Y)break;X++;try{return await(J.rename??m9)($,Z),{attempts:X,elapsedMs:Q()-z}}catch(j){W??=j;let U=j;if(!(U.win32Code!==void 0?U.win32Code===32||U.win32Code===33:["EBUSY","EPERM","EACCES"].includes(U.code??"")&&!U.reason))break}}let K=new l(Z,"rename",W??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw K.attempts=X,K.elapsedMs=Q()-z,K}async function T0($,Z,J={}){$=t($),await z0(q0($));try{await n($,"file",!0)}catch(K){if(K.code!=="ENOENT")throw K}let Q=t(J.stagePath??`${$}.${y9()}.tmp`);if(q0(Q)!==q0($))throw new l($,"stage-directory",{code:"EXDEV"});let z=!1,Y=!1,G={attempts:0,elapsedMs:0},W="stage-create",X=(K)=>{try{J.onOutcome?.({path:$,stage:K?.stage??"published",published:Y,fileDurable:Y,durabilityConfirmed:!1,attempts:K?.attempts??G.attempts,elapsedMs:K?.elapsedMs??G.elapsedMs,...K&&{code:K.code,win32Code:K.win32Code}})}catch{}};try{if(await w0(Q,Z),z=!0,W="before-rename",G=await e1(Q,$,J),z=!1,Y=!0,W="published-callback",J.onRenamed?.(),W="published-verify",await n($,"file"),J.durable&&J.durability!=="file-only-on-windows")throw new l($,"directory-sync-unsupported",{code:"ENOTSUP"});X()}catch(K){let H=K instanceof l?K:new l($,W,K);if(H.published=Y,H.fileDurable=Y,Y)Object.assign(H,G);if(z){try{await W$(Q)}catch{H.orphanPath=Q}z=!1}throw X(H),H}finally{if(z)await W$(Q).catch(()=>{})}}var p9=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,d9=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function u9($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function g0($={}){let Z=[d9,...$.extraValuePatterns??[]].map((Y)=>new RegExp(Y.source,Y.flags.includes("g")?Y.flags:`${Y.flags}g`));function J(Y){let G=Y.toLowerCase().replace(/[-_]/g,"");return p9.test(Y)||G.includes("apikey")||G.endsWith("secret")||G.endsWith("password")||G.endsWith("token")&&!G.endsWith("tokens")||!!$.extraSecretKeys?.(G)}function Q(Y){let G=Y,W=[["name",Y.name],["message",Y.message],["stack",Y.stack]];for(let K of["code","status","cause"])if(G[K]!==void 0)W.push([K,G[K]]);let X=new Set(W.map(([K])=>K));for(let K of Object.entries(Y))if(!X.has(K[0]))W.push(K);return W}function z(Y,G,W,X=0){if(typeof Y==="string")return Z.reduce((K,H)=>K.replace(H,"***REDACTED***"),Y);if(!Y||typeof Y!=="object")return Y;if(W.has(Y))return"[Circular]";W.add(Y);try{if(Array.isArray(Y))return Y.map((j)=>z(j,G,W,X));let K=u9(Y);if(K&&X>=8)return"[Truncated]";let H=K?X+1:X;return Object.fromEntries((K?Q(Y):Object.entries(Y)).map(([j,U])=>[j,G&&J(j)?"***REDACTED***":z(U,G,W,H)]))}finally{W.delete(Y)}}return{redact:(Y)=>z(Y,!0,new WeakSet),redactStrings:(Y)=>z(Y,!1,new WeakSet)}}var q$=g0(),l9=q$.redact,i9=q$.redactStrings;var H1={error:0,warn:1,info:2,debug:3,trace:4},D$=5242880,F$=3;function Z3($){try{n9($,384)}catch{}}function e9($){try{if(!($3($)&&s9($).size>=D$))return;for(let J=F$-1;J>=1;J--)if($3(`${$}.${J}`)){let Q=`${$}.${J+1}`;V$(`${$}.${J}`,Q),Z3(Q)}let Z=`${$}.1`;V$($,Z),Z3(Z)}catch{}}async function U0($){let{file:Z,handle:J}=$;if($.file=void 0,$.handle=void 0,Z&&J)await r(Z,"log-close",()=>J.close())}async function M$($,Z){await z0(r9(Z));try{await n(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await w0(Z,"")}catch(Q){if(Q.code!=="EEXIST")throw Q;await n(Z,"file",!0)}}return $.handle=await r(Z,"log-open",()=>o9(Z,"a")),$.file=Z,$.handle}async function $7($,Z,J){Z=t9(Z);try{if($.file!==Z)await U0($);let Q=$.handle??await M$($,Z);if((await r(Z,"log-stat",()=>Q.stat())).size>=D$){await U0($);for(let Y=F$-1;Y>=0;Y--){let G=Y===0?Z:`${Z}.${Y}`,W=`${Z}.${Y+1}`;try{await n(G,"file",!0)}catch(X){if(X.code==="ENOENT")continue;throw X}try{await n(W,"file",!0)}catch(X){if(X.code!=="ENOENT")throw X}await e1(G,W),await n(W,"file")}Q=await M$($,Z)}await r(Z,"log-append",()=>Q.appendFile(J,"utf8"))}catch(Q){throw await U0($).catch(()=>{}),Q}}function Z7($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function J7($){let Z,J,Q,z=g0(),Y,G=[],W,X=Promise.resolve(),K,H={};function j(q){let P=X.then(q);return X=P.catch((O)=>{K=O}),P}function U(q){if(A&&q.file!==Z)j(()=>U0(H)).catch(()=>{});Z=q.file,J=q.level,z=g0(q),Y=q.captureSink}function M(q){if(q===void 0||q in H1)Q=q}function D(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function B(){if(Q)return Q;let q=typeof J==="function"?J():J;if(q&&q in H1)return q;return"info"}function I(q=!0){if(W)clearTimeout(W),W=void 0;if(!G.length){if(A)return j(async()=>{if(q)await U0(H);if(K)throw K});return}let P;try{P=D()}catch{if(G=[],A&&q)return j(()=>U0(H));return}let O=G.join("");if(G=[],!P){if(A&&q)return j(()=>U0(H));return}if(A)return j(async()=>{try{await $7(H,P,O)}finally{if(q)await U0(H)}});try{if(e9(P),$3(P))Z3(P);a9(P,O,{encoding:"utf8",mode:384})}catch{}}function T(){if(!W)W=setTimeout(()=>{W=void 0;let q=I(!1);if(q instanceof Promise)q.catch(()=>{})},500)}function m(q,P,O,E){if(Z===void 0&&Y===void 0)return;try{if(H1[P]>H1[B()])return;let S=z.redactStrings(O),h;try{h=z.redact(E)}catch{h="[unserializable]"}let w=`[${new Date().toISOString()}] ${P.toUpperCase()} [${q}] ${S}`+(E===void 0?"":Z7(h))+`
|
|
3
|
+
`;try{Y?.({channel:q,level:P,message:S,data:h})}catch{}if(Z===void 0)return;if(G.push(w),G.length>=50){let k=I(!1);if(k instanceof Promise)k.catch(()=>{})}else T()}catch{}}function p(q){return{error:(P,O)=>m(q,"error",P,O),warn:(P,O)=>m(q,"warn",P,O),info:(P,O)=>m(q,"info",P,O),debug:(P,O)=>m(q,"debug",P,O),trace:(P,O)=>m(q,"trace",P,O)}}function F(){if(A)j(()=>U0(H)).catch(()=>{});if(K=void 0,G=[],W)clearTimeout(W),W=void 0;Z=void 0,J=void 0,Q=void 0,z=g0(),Y=void 0}if($)U($);return{configure:U,createLogger:p,setLogLevel:M,flushLogs:I,reset:F}}var Q7=J7();function n0($){return Q7.createLogger($)}function J3($){let Z=new AbortController,J=[],Q=!1,z=()=>{if(Q)return;Q=!0;for(let{source:W,listener:X}of J)W.removeEventListener("abort",X);J.length=0},Y=(W)=>{if(Q||Z.signal.aborted)return;Z.abort(W),z()},G=$.find((W)=>W.aborted);if(G)return Z.abort(G.reason),{signal:Z.signal,dispose:z};for(let W of $){if(Z.signal.aborted)break;let X=()=>Y(W.reason);if(J.push({source:W,listener:X}),W.addEventListener("abort",X,{once:!0}),W.aborted)Y(W.reason)}return{signal:Z.signal,dispose:z}}import{createHash as U7,randomBytes as q7,randomUUID as V7}from"node:crypto";import{constants as k$}from"node:fs";import{chmod as M7,mkdir as D7,open as E$,readFile as K3,realpath as F7,rename as L7,stat as S$,unlink as x$}from"node:fs/promises";import{basename as N7,dirname as A0,extname as n6,isAbsolute as s6,join as B7,resolve as o6}from"node:path";import{randomUUID as L$}from"node:crypto";import{mkdir as z7,open as N$,rename as Y7,rm as G7}from"node:fs/promises";import{dirname as B$}from"node:path";class Q3 extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function z3($,Z,J={}){await W7($,Z,J)}async function W7($,Z,J,Q){if(A)return T0($,J.serialize?J.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
4
|
+
`,{beforeRename:J.beforeRename,stagePath:`${$}.${(J.stageName??L$)()}.tmp`,onRenamed:Q,durable:J.durable,durability:J.durability,onOutcome:J.onOutcome});await z7(B$($),{recursive:!0});let z=`${$}.${(J.stageName??L$)()}.tmp`,Y,G=!1;try{if(Y=await N$(z,"wx",384),G=!0,await Y.writeFile(J.serialize?J.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
5
|
+
`,"utf8"),await Y.chmod(384),J.durable)try{await Y.sync()}catch(W){throw new Q3(W)}if(await Y.close(),Y=void 0,await J.beforeRename?.(),await Y7(z,$),G=!1,Q?.(),J.durable){let W=await N$(B$($),"r");try{await W.sync()}catch(X){throw new Q3(X)}finally{await W.close()}}}finally{if(await Y?.close().catch(()=>{}),G)await G7(z,{force:!0}).catch(()=>{})}}var X7=Object.freeze({sidebar:Object.freeze({name:"sidebar-write",ttlMs:1e4,timeoutMs:15000,renew:!0}),preferences:Object.freeze({name:"preferences",ttlMs:1e4,timeoutMs:2000,renew:!0})});import{randomUUID as U1}from"node:crypto";import{mkdir as I$,open as K7,readFile as O$,rename as P$,rm as q1,stat as C$,writeFile as R$}from"node:fs/promises";import{dirname as X3,join as b$}from"node:path";function Y3($,Z){return`${$}.${Z}.lock`}class G3 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class h0 extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}async function W3($,Z,J){let Q=performance.now();for(;;){let z=await V0({path:$,name:Z.name,ttlMs:Z.ttlMs,renew:Z.renew??!1,...Z.onStep?{onStep:Z.onStep}:{},...Z.onRenewalTimer?{onRenewalTimer:Z.onRenewalTimer}:{}});if(z)try{return await J(z)}finally{await z.release()}let Y=Z.timeoutMs-(performance.now()-Q);if(Y<=0)throw new G3({target:$,name:Z.name,timeoutMs:Z.timeoutMs});await new Promise((G)=>setTimeout(G,Math.min(25,Math.ceil(Y))))}}var j7=globalThis.setTimeout.bind(globalThis),H7=globalThis.clearTimeout.bind(globalThis);function A$($){let Z=$?.code;return Z==="ENOENT"||!A&&(Z==="EINVAL"||Z==="ENOTDIR")}async function V0($){let Z=Y3($.path,$.name),J=b$(Z,"owner.json"),Q=U1(),z=$.now??Date.now,Y=null,G=!1,W=!1,X,K,H=new Promise((L)=>{K=L});function j(L){try{let N=$.onRenewalTimer?.(L);if(N&&(typeof N==="object"||typeof N==="function")&&"then"in N&&typeof N.then==="function")Promise.resolve(N).catch(()=>{})}catch{}}function U(){if(!Y)return;H7(Y),Y=null,j("cancelled")}function M(L,N){if(X||G)return;X=Object.freeze({reason:L,expectedOwnerId:Q,...typeof N?.ownerId==="string"?{observedOwnerId:N.ownerId}:{},...typeof N?.expiresAt==="number"?{observedExpiresAt:N.expiresAt}:{}}),U(),K(X)}let D,B=null,I=`${Z}.evicting`,T=b$(I,"owner.json"),m=U1(),p=5000,F=8;async function q(){if(A)try{return JSON.parse(await Y0(Z,!0))}catch(L){if(L.code!=="EISDIR"&&L.reason!=="wrong-kind")throw L;return await n(Z,"directory",!0),JSON.parse(await Y0(J,!0))}try{return JSON.parse(await O$(Z,"utf8"))}catch(L){if(L.code!=="EISDIR")throw L;return JSON.parse(await O$(J,"utf8"))}}async function P(){if(A){let v=await q(),u=Number(v?.expiresAt)-z();await T0(Z,`${JSON.stringify({ownerId:Q,expiresAt:z()+$.ttlMs})}
|
|
6
|
+
`,{deadline:performance.now()+Math.max(0,u),beforeRename:async()=>{let K1=await q();if(K1?.ownerId!==Q||!(Number(K1?.expiresAt)>z())||!await _())throw new h0({target:$.path,name:$.name})}});return}let L=`${Z}.${U1()}.tmp`,N,C=!1;try{N=await K7(L,"wx",384),C=!0,await N.writeFile(`${JSON.stringify({ownerId:Q,expiresAt:z()+$.ttlMs})}
|
|
7
|
+
`,"utf8"),await N.chmod(384),await N.close(),N=void 0;let v=await q();if(v?.ownerId!==Q||!(Number(v?.expiresAt)>z())||!await _())throw new h0({target:$.path,name:$.name});await P$(L,Z),C=!1}finally{if(await N?.close().catch(()=>{}),C)await q1(L,{force:!0}).catch(()=>{})}}async function O(){let L=`${JSON.stringify({ownerId:Q,expiresAt:z()+$.ttlMs})}
|
|
8
|
+
`;if(A)await w0(Z,L);else await R$(Z,L,{encoding:"utf8",mode:384,flag:"wx"})}async function E(L){let N=L.code;if(N==="EEXIST"){if(A)await q();return!0}if(N==="EISDIR"){if(A)await n(Z,"directory",!0),await Y0(J,!0);return!0}return!1}async function S(){if(A)await z0(X3(Z));try{return await O(),!0}catch(L){let N=L.code;if(await E(L))return!1;if(N==="ENOENT"){if(A)await z0(X3(Z));else await I$(X3(Z),{recursive:!0});try{return await O(),!0}catch(C){if(await E(C))return!1;throw C}}throw L}}async function h(){await new Promise((L)=>setTimeout(L,Math.floor(Math.random()*4)))}async function w(L=!0){if(L&&$.onStep)await $.onStep("lock-read-ready");let N;try{N=await q()}catch(v){if(A&&v.code!=="ENOENT")throw v}let C=Number(N?.expiresAt);if(Number.isFinite(C)&&C>z())return{status:"live"};if(typeof N?.ownerId==="string"&&Number.isFinite(C))return{status:"stale",identity:{kind:"owner",ownerId:N.ownerId,expiresAt:C}};try{let v=await C$(Z),u=Number.isFinite(C)?C:v.mtimeMs+$.ttlMs;if(u>z())return{status:"live"};return{status:"stale",identity:{kind:"stat",dev:v.dev,ino:v.ino,mtimeMs:v.mtimeMs,expiresAt:u}}}catch(v){if(v.code==="ENOENT"){if($.onStep)await $.onStep("lock-missing");return{status:"missing"}}throw v}}function k(L,N){if(N.status!=="stale")return!1;let C=N.identity;if(L.kind==="owner"&&C.kind==="owner")return L.ownerId===C.ownerId&&L.expiresAt===C.expiresAt;return L.kind==="stat"&&C.kind==="stat"&&L.dev===C.dev&&L.ino===C.ino&&L.mtimeMs===C.mtimeMs&&L.expiresAt===C.expiresAt}async function _(){try{return JSON.parse(await Y0(T,A))?.ownerId===m}catch(L){if(A&&L.code!=="ENOENT")throw L;return!1}}async function b(L){if(A)await r(L,"remove",()=>q1(L,{recursive:!0,force:!0}));else await q1(L,{recursive:!0,force:!0}).catch(()=>{})}async function c(){if(await _())await b(I)}async function o(){if(A)await U$(I);else await I$(I);try{let L=`${JSON.stringify({ownerId:m,createdAt:z()})}
|
|
9
|
+
`;if(A)await w0(T,L);else await R$(T,L,{encoding:"utf8",mode:384,flag:"wx"})}catch(L){if(A$(L))return!1;throw await c(),L}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function i(){let L;try{L=await C$(I)}catch(C){if(C.code==="ENOENT")return"missing";throw C}if(A)await n(I,"directory",!0);if(L.mtimeMs+p>z())return"fresh";if($.onStep)await $.onStep("stale-marker-stat");let N=`${I}.${U1()}`;try{await P$(I,N)}catch(C){if(C.code==="ENOENT")return"missing";throw C}if($.onStep)await $.onStep("stale-marker-claimed");return await b(N),"recovered"}async function j0(L){try{if(!await o())return!1}catch(N){if(N.code==="EEXIST"){if(A){await n(I,"directory",!0);try{await Y0(T,!0)}catch(C){if(C.code!=="ENOENT")throw C}}return!1}throw N}try{await L()}finally{await c()}return!0}async function x(){for(let L=0;L<F;L++){if($.onStep)await $.onStep("relinquish-read");let N;try{N=await q()}catch(C){if(A)throw C;return}if(N?.ownerId!==Q)return;try{await q1(Z,{recursive:!0,force:!0});return}catch(C){if(A)throw C;await h()}}}function J0(){if(!$.renew||G||X)return;let L=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(Y=j7(()=>{Y=null;let N=(async()=>{let C=!G;try{if(!await j0(async()=>{let u=await q(),K1=z();if(G||X){C=!1;return}if(u?.ownerId!==Q){M("taken-over",u),C=!1;return}if(!(Number(u?.expiresAt)>K1)){M("expired",u),C=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(G||X){C=!1;return}if(!await _())return;if($.onStep)await $.onStep("renewal-write-fenced");if(G||X){C=!1;return}if(!await _())return;if($.onStep)await $.onStep("renewal-write-ready");if(G||X){C=!1;return}if(await P(),$.onStep)await $.onStep("renewal-write-finished");if(!await _()){M("marker-lost"),C=!1,await x();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch(v){if(A&&v instanceof l)D=v,M("renewal-failed"),C=!1;try{let u=await q();if(u?.ownerId!==Q)M("taken-over",u);else if(!(Number(u?.expiresAt)>z()))M("expired",u)}catch{M("renewal-failed")}}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(C&&!G&&!X)J0()}})();B=N,N.finally(()=>{if(B===N)B=null})},L),"unref"in Y)Y.unref();j("scheduled")}function G$(){try{let L=$.onContended?.();if(L&&(typeof L==="object"||typeof L==="function")&&"then"in L&&typeof L.then==="function")Promise.resolve(L).catch(()=>{})}catch{}return null}let R0=await S();if(!R0)for(let L=0;L<F;L++){if(R0=await S(),R0)break;let N=await w();if(N.status==="live")return G$();if(N.status==="missing")continue;if($.onStep)await $.onStep("stale-lock-observed");try{if(!await o()){await h();continue}}catch(C){if(C.code!=="EEXIST")throw C;if(await i()==="fresh")return null;await h();continue}try{let C=await w();if(C.status==="live")return G$();if(!k(N.identity,C))continue;if(!await _())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await _())return null;let v=await w(!1);if(!k(N.identity,v))continue;if(await b(Z),!await _())return null;if($.onStep)await $.onStep("stale-lock-removed");if(R0=await S(),!R0)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await _())return await x(),R0=!1,null;break}finally{await c()}}if(!R0)return null;return J0(),{ownerId:Q,whenLost:()=>H,hasLost:()=>X!==void 0,assertOwned:async()=>{if(D)throw D;let L;try{let N=await q();if(L=N,!G&&!X&&N?.ownerId===Q&&Number(N?.expiresAt)>z())return;M(N?.ownerId!==Q?"taken-over":"expired",N)}catch(N){if(M("unreadable"),A&&N instanceof l)throw N}throw new h0({target:$.path,name:$.name,expectedOwnerId:Q,...typeof L?.ownerId==="string"?{observedOwnerId:L.ownerId}:{},...typeof L?.expiresAt==="number"?{observedExpiresAt:L.expiresAt}:{}})},release:async()=>{if(A&&W)return;G=!0,U(),await B;for(let L=0;L<F;L++){try{let N=!1;if(await j0(async()=>{let v;try{v=await q()}catch(u){if(A&&u.code==="ENOENT"){N=!0;return}throw u}if(v?.ownerId!==Q){N=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await _())return;await b(Z),N=!0})){if(A&&!N)throw new l(Z,"release-not-confirmed",{code:"EIO"});W=N;return}await i()}catch(N){if(A)throw N;return}await h()}if(A)throw new l(Z,"release-not-confirmed",{code:"ETIMEDOUT"})}}}class R extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var I7=1,M1=16384,w$=30000,U3=/^[0-9a-f]{64}$/,T$=new Set(["invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),g$=new Set(["pending_queue_full"]);function j3($){if(!($ instanceof o0))return;if(T$.has($.code))return{code:$.code,disposition:"terminal"};if(g$.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function q3($){return H3.connect($)}function h$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function V1($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function y$($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function s0(){return new R("invalid-state","invalid Claustrum enrollment state")}function V3($){if(!h$($)||$.version!==I7||typeof $.proposedName!=="string"||$.proposedName.length===0)throw s0();if($.phase==="pending"){if(!U3.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!V1($.createdAt)||!V1($.updatedAt))throw s0();return{version:1,phase:"pending",proposedName:$.proposedName,requestSecret:$.requestSecret,...$.requestId!==void 0&&{requestId:$.requestId},createdAt:$.createdAt,updatedAt:$.updatedAt}}if($.phase==="approved"){if($.approvedName!==void 0&&(typeof $.approvedName!=="string"||$.approvedName.length===0)||!y$($.tokenGeneration)||!V1($.updatedAt))throw s0();return{version:1,phase:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration,updatedAt:$.updatedAt}}if($.phase==="denied"||$.phase==="blocked"){if($.errorCode!==void 0&&typeof $.errorCode!=="string"||!V1($.updatedAt))throw s0();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw s0()}function M3($){if(!h$($)||!U3.test(String($.token??""))||!y$($.token_generation))throw new R("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function O7($){if(!$.isFile())throw new R("unsafe-file","Claustrum enrollment file must be a regular file");if(($.mode&63)!==0)throw new R("unsafe-file","Claustrum enrollment file must be owner-only");let Z=process.geteuid?.();if(Z!==void 0&&$.uid!==Z)throw new R("unsafe-file","Claustrum enrollment file must be owned by the current user")}function _$($){try{return JSON.parse($)}catch{throw new R("invalid-state","Claustrum enrollment file is not valid JSON")}}async function k0($){if(A)try{await z0(A0($));let J=await Y0($,!0);if(Buffer.byteLength(J)>M1)throw new R("unsafe-file","Claustrum enrollment file is too large");return _$(J)}catch(J){if(J.code==="ENOENT")return;throw J}let Z;try{Z=await E$($,k$.O_RDONLY|k$.O_NOFOLLOW)}catch(J){if(J.code==="ENOENT")return;throw new R("unsafe-file","Claustrum enrollment file could not be opened safely")}try{O7(await Z.stat());let J=Buffer.alloc(M1+1),{bytesRead:Q}=await Z.read(J,0,J.byteLength,0);if(Q>M1)throw new R("unsafe-file","Claustrum enrollment file is too large");return _$(J.subarray(0,Q).toString("utf8"))}finally{await Z.close()}}function f$($,Z){let J=[];for(let Q of $.split(`
|
|
10
|
+
`)){if(Q.trim()===""||Q.startsWith("#"))continue;let z=Q.split(":");if(z.length!==Z||!/^[^\s:,]+$/.test(z[0]??"")||!/^\d+$/.test(z[2]??"")||!Number.isSafeInteger(Number(z[2]))||Z===7&&(!/^\d+$/.test(z[3]??"")||!Number.isSafeInteger(Number(z[3])))||Z===4&&z[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(z[3]??""))return;J.push(z)}return J}async function P7($,Z,J){try{let[Q,z]=await Promise.all([K3(J.passwdPath??"/etc/passwd","utf8"),K3(J.groupPath??"/etc/group","utf8")]),Y=f$(Q,7),G=f$(z,4);if(!Y||!G)return!1;let W=Y.filter((j)=>Number(j[2])===$),X=G.filter((j)=>Number(j[2])===Z);if(W.length!==1||X.length!==1)return!1;let K=W[0]?.[0],H=X[0]?.[3]??"";return(H===""||H.split(",").every((j)=>j===K))&&!Y.some((j)=>Number(j[2])!==$&&Number(j[3])===Z)}catch{return!1}}function m$($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>K3(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function v$($,Z={}){if(!A){let J=process.geteuid?.();if(J===void 0)return;let Q=process.getegid?.(),z;try{z=await F7($)}catch{return}let Y;for(;;){let G=await S$(z).catch(()=>{return});if(G&&(G.mode&18)!==0&&(G.mode&512)===0){if(Y===void 0)Y=Q!==void 0&&await P7(J,Q,Z);if((G.mode&2)!==0||G.uid!==J||G.gid!==Q||!Y)throw new R("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${z}. Another user could replace it. Run: chmod g-w,o-w ${z}`)}let W=A0(z);if(W===z)return;z=W}}try{await H0($,m$(Z))}catch(J){if(!(J instanceof l))throw J;throw new R("unsafe-file",`Claustrum enrollment parent refused: ${J.path} (${J.reason??J.code}). Use a folder that other users cannot write or replace.`)}}async function D1($,Z={}){if(A){await z0($,!1,m$(Z));return}await D7($,{recursive:!0,mode:448});let J=await S$($),Q=process.geteuid?.();if(Q!==void 0&&J.uid!==Q)throw new R("unsafe-file","Claustrum enrollment directory must be owned by the current user");if((J.mode&63)!==0)await M7($,448)}async function b0($,Z,J={}){let Q=A0($);await D1(Q,J),await v$(Q,J);let z=`${JSON.stringify(Z)}
|
|
11
|
+
`;if(Buffer.byteLength(z)>M1)throw new R("invalid-state","Claustrum enrollment state is too large");if(A)return T0($,z);let Y=B7(Q,`.${N7($)}.${process.pid}.${V7()}.tmp`),G,W=!1;try{G=await E$(Y,"wx",384),W=!0,await G.writeFile(z,"utf8"),await G.chmod(384),await G.sync(),await G.close(),G=void 0,await L7(Y,$),W=!1}finally{if(await G?.close().catch(()=>{}),W)await x$(Y).catch(()=>{})}}async function L1($,Z){let J=await k0($.tokenPath),Q=J===void 0?void 0:M3(J),z=await k0($.statePath),Y=z===void 0?void 0:V3(z);if(Q)return{state:"approved",proposedName:Y?.proposedName??Z,...Y?.phase==="approved"&&Y.approvedName!==void 0&&{approvedName:Y.approvedName},tokenGeneration:Q.token_generation};if(!Y)return{state:"idle"};if(Y.phase==="approved")return{state:"blocked",proposedName:Y.proposedName,code:"missing_token"};return M0(Y)}async function D3($){let Z=await k0($);if(Z===void 0)throw new R("not-enrolled","Claustrum enrollment is not configured");return M3(Z)}function M0($){if($.phase==="pending")return{state:"pending",proposedName:$.proposedName,...$.requestId!==void 0&&{requestId:$.requestId}};if($.phase==="approved")return{state:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration};if($.phase==="denied")return{state:"denied",proposedName:$.proposedName};return{state:"blocked",proposedName:$.proposedName,code:$.errorCode??"unknown"}}function c$(){return new R("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class N1{#$;#J;#Z;#Y;#X;#z;#Q;constructor($){this.#Q=$.ancestorOptions??{},this.#$=$.client,this.#J=$.paths,this.#Z=$.proposedName,this.#Y=$.now??Date.now,this.#X=$.mintSecret??(()=>q7(32).toString("hex")),this.#z=$.writeTokenFile??F1}async status(){return L1(this.#J,this.#Z)}async resetTerminal(){return p$(this.#J,this.#Z)}async#G($,Z){let J={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#Y()};return await b0(this.#J.statePath,J,this.#Q),M0(J)}async reconcile(){await D1(A0(this.#J.statePath),this.#Q);let $=await V0({name:"ceremony",path:this.#J.statePath,ttlMs:w$,renew:!0});if(!$)return{state:"busy"};try{let Z=await k0(this.#J.tokenPath),J=Z===void 0?void 0:M3(Z),Q=await k0(this.#J.statePath),z=Q===void 0?void 0:V3(Q);if(z&&z.proposedName!==this.#Z)throw c$();if(J){if(!z||z.phase==="pending"){let G={version:1,phase:"approved",proposedName:z?.proposedName??this.#Z,tokenGeneration:J.token_generation,updatedAt:this.#Y()};await b0(this.#J.statePath,G,this.#Q),z=G}return{state:"approved",proposedName:z.proposedName,...z.phase==="approved"&&z.approvedName!==void 0&&{approvedName:z.approvedName},tokenGeneration:J.token_generation}}if(z?.phase==="approved"){let G={version:1,phase:"blocked",proposedName:z.proposedName,errorCode:"missing_token",updatedAt:this.#Y()};return await b0(this.#J.statePath,G,this.#Q),M0(G)}if(z&&z.phase!=="pending")return M0(z);if(!z){let G=this.#Y();if(z={version:1,phase:"pending",proposedName:this.#Z,requestSecret:this.#X(),createdAt:G,updatedAt:G},!U3.test(z.requestSecret))throw new R("invalid-state","invalid minted Claustrum enrollment secret");await b0(this.#J.statePath,z,this.#Q)}if(!z.requestId)try{let G=U7("sha256").update(Buffer.from(z.requestSecret,"hex")).digest("hex"),W=await this.#$.enrollPropose({name:z.proposedName,requestSecretHash:G});z={...z,requestId:W.requestId,updatedAt:this.#Y()},await b0(this.#J.statePath,z,this.#Q)}catch(G){let W=j3(G);if(!W)throw G;if(W.disposition==="retry")return{state:"pending",proposedName:z.proposedName,retryCode:W.code};return this.#G(z,W.code)}let Y=z.requestId;if(!Y)return M0(z);try{let G=await this.#$.enrollPoll({requestId:Y,requestSecret:z.requestSecret});if(G.status==="pending")return M0(z);if(G.status==="denied"){let X={version:1,phase:"denied",proposedName:z.proposedName,updatedAt:this.#Y()};return await b0(this.#J.statePath,X,this.#Q),M0(X)}await D1(A0(this.#J.tokenPath),this.#Q),await v$(A0(this.#J.tokenPath),this.#Q),await this.#z(this.#J.tokenPath,{token:G.token,token_generation:G.tokenGeneration});let W={version:1,phase:"approved",proposedName:z.proposedName,approvedName:G.name,tokenGeneration:G.tokenGeneration,updatedAt:this.#Y()};return await b0(this.#J.statePath,W,this.#Q),M0(W)}catch(G){let W=j3(G);if(!W)throw G;if(W.disposition==="retry")return{state:"pending",proposedName:z.proposedName,requestId:Y,retryCode:W.code};return this.#G(z,W.code)}}finally{await $.release()}}}async function p$($,Z){await D1(A0($.statePath));let J=await V0({name:"ceremony",path:$.statePath,ttlMs:w$,renew:!0});if(!J)return"busy";try{if(await k0($.tokenPath)!==void 0)return"refused-approved";let Q=await k0($.statePath);if(Q===void 0)return"idle";let z=V3(Q);if(z.proposedName!==Z)throw c$();if(z.phase==="pending")return"refused-pending";return await J.assertOwned(),await x$($.statePath),"reset"}finally{await J.release()}}var F3="claustrum-tombstone:v1:";function d$($,Z){return Z!==void 0&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function C7($,Z){if(Z===void 0)return"reauthorize-failed";if(Z.credentialId!==$.credentialId)return"credential-changed";if(Z.accountIdentity!==$.accountIdentity)return"account-changed";if(Z.recordVersion===$.recordVersion)return"version-unchanged";return"rotated"}var u$=n0("claustrum");function B3($,Z,J,Q=u$){let z=d$(Z,J);return Q.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:J?.recordVersion??null,retry:z,reason:C7(Z,J)}),z}var N3=300000;function L3(){return new R("invalid-material","Claustrum returned invalid credential material")}function R7($){let Z=$.trim();if(Z.startsWith("{")){let J;try{J=JSON.parse(Z)}catch{throw L3()}if(!J||typeof J!=="object")throw L3();let Q=J,z=Q.access_token??Q.access;Z=typeof z==="string"?z:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(F3))throw L3();return Z}function b7($,Z){if(!$.operations.includes("read"))return;if(!$.categories.includes(Z.category))return;if($.credentialType==="oauth")return $.refreshAdapter===Z.refreshAdapter?"oauth":void 0;if($.credentialType==="api_key"&&Z.apiKeys)return $.refreshAdapter===void 0?"api_key":void 0;return}class B1{#$;#J;#Z;#Y;#X;#z;#Q;#G=new WeakMap;#H=new WeakMap;#W=!1;constructor($){let Z=$.tokenPath;if($.readToken)this.#J=$.readToken;else if(Z)this.#J=()=>D3(Z);else throw new R("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#Y=$.family,this.#X=$.parseIdentity,this.#z=$.requireAssertion??!1,this.#Z=$.now??Date.now,this.#Q=$.logger??u$}#K($){if(this.#W)throw new R("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#j($){this.#K($);let Z=await this.#J();if(this.#K($),!/^[0-9a-f]{64}$/.test(Z.token)||!Number.isSafeInteger(Z.token_generation)||Z.token_generation<1)throw new R("invalid-token","Invalid Claustrum enrollment token");return Z.token}async#U($,Z){this.#K(Z);let J,Q;try{let z=$();J=Z?await Promise.race([z,new Promise((Y,G)=>{let W=()=>G(Z.reason);if(Z.addEventListener("abort",W,{once:!0}),Q=()=>Z.removeEventListener("abort",W),Z.aborted)W()})]):await z}catch(z){if(this.#K(Z),z instanceof o0)throw z;throw new R("unavailable","Claustrum scoped operation unavailable")}finally{Q?.()}return this.#K(Z),J}async discover($){let Z=await this.#j($),J=await this.#U(()=>this.#$.listScoped(Z),$),Q=[],z=[],Y=new Map;for(let W of J.rows){let X=b7(W,this.#Y);if(!X)continue;z.push({row:W,type:X}),Y.set(W.id,(Y.get(W.id)??0)+1)}let G=[];for(let{row:W,type:X}of z){let K;if(!W.id.trim())K="empty credential id";else if((Y.get(W.id)??0)>1)K="duplicate credential id";else if(W.accountId!==void 0&&!W.accountId.trim())K="blank account identity";else if(!W.state.trim())K="empty state";if(K){Q.push({...W.id.trim()&&{credentialId:W.id},reason:K});continue}G.push(Object.freeze({credentialId:W.id,credentialType:X,...W.accountId!==void 0&&{accountIdentity:W.accountId},state:W.state,...W.email!==void 0&&{email:W.email},...W.orgName!==void 0&&{orgName:W.orgName}}))}for(let W of Q)this.#Q.warn("skipped malformed vault record",W);return{view:J.view,credentials:Object.freeze(G),skipped:Object.freeze(Q)}}async authorize($,Z){if(!$.credentialId)throw new R("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:J,credentialType:Q,accountIdentity:z}=$;if(this.#z&&z===void 0)throw new R("identity-unasserted","Claustrum dispatch requires a known account identity");let Y=await this.#j(Z),G=await this.#U(()=>this.#$.getScoped({credentialId:J,enrollmentToken:Y,...Q==="oauth"&&{minTtlMs:N3}}),Z);if(G.credentialId!==void 0&&G.credentialId!==J)throw new R("identity-changed","Claustrum served credential identity changed");let W=G.expiresAtMs;if(!Number.isSafeInteger(G.recordVersion)||G.recordVersion<0||W===null&&Q==="oauth"||W!==null&&(!Number.isFinite(W)||W-this.#Z()<N3))throw new R("insufficient-validity","Claustrum served credential has insufficient validity");let X=R7(G.material),K=G.accountId?.trim()?G.accountId:void 0;if(this.#z&&(G.credentialId===void 0||K===void 0))throw new R("identity-unasserted","Claustrum served credential did not assert its identity");let H=K===void 0?this.#X?.(X):void 0,j=K??H;if(z!==void 0&&j!==void 0&&j!==z)throw new R("identity-changed","Claustrum served credential identity changed");let U=j??z,D=Object.freeze(Object.defineProperty({credentialId:J,credentialType:Q,...U!==void 0&&{accountIdentity:U},accountIdentitySource:K!==void 0?"asserted":H!==void 0?"parsed":z!==void 0?"expected":"none",...z!==void 0&&{expectedAccountIdentity:z},...G.credentialId!==void 0&&{assertedCredentialId:G.credentialId},...K!==void 0&&{assertedAccountIdentity:K},...G.projectId!==void 0&&{projectId:G.projectId},recordVersion:G.recordVersion,expiresAtMs:W},"accessToken",{value:X,enumerable:!1}));return this.#G.set(D,Y),D}async reportFailure($,Z,J){if(Z!==401)return;this.#K();let Q=this.#G.get($);if(!Q)throw new R("no-receipt","Claustrum failure report requires an original dispatch receipt");let z=this.#H.get($);if(z)return z;let Y=this.#U(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:Q,providerStatus:401,recordVersion:$.recordVersion,reporterSource:J}));this.#H.set($,Y);try{await Y,this.#Q.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:J})}catch(G){throw this.#H.delete($),G}}close(){if(this.#W)return;this.#W=!0,this.#$.close()}}import{createHash as h7}from"node:crypto";var _0="all",A7=Object.freeze(["primary"]);function i$($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function y0($,Z){return JSON.stringify([$,Z])}function O3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function Q0($){return typeof $==="number"&&Number.isFinite($)}function l$($){return typeof $==="string"&&$.length>0}function G0($,Z,J){return $[Z]===void 0||J($[Z])}function k7($){return Q0($)&&$>0}function I3($){return typeof $==="string"}function _7($){if(!O3($)||!l$($.scope)||!l$($.label))return!1;switch($.kind){case"reading":return Q0($.checkedAt)&&Q0($.usedPercent)&&G0($,"resetsAt",I3)&&G0($,"windowMinutes",k7);case"retired":return Q0($.retiredAt);case"absent":return Q0($.checkedAt);default:return!1}}function f7($){if(!O3($)||!Q0($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&G0($,"remainingPercent",Q0)&&G0($,"usedPercent",Q0)&&G0($,"resetsAt",I3)&&G0($,"limit",Q0)&&G0($,"used",Q0)&&G0($,"remaining",Q0)&&G0($,"unit",I3)}function f0($){if(!O3($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let J of $.limits){if(!_7(J))return!1;let Q=y0(J.scope,J.label);if(Z.has(Q))return!1;Z.add(Q)}return G0($,"budget",f7)}class I1 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function P1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function O1($){return typeof $==="number"&&Number.isFinite($)}function a$($){return $===void 0||typeof $==="string"&&$!==""}function n$($){return typeof $==="string"&&$!==""}function r0($,Z){return $[Z]===void 0||O1($[Z])}function P3($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function E7($){return P1($)&&a$($.scope)&&n$($.label)&&O1($.usedPercent)&&P3($,"resetsAt")&&($.windowMinutes===void 0||O1($.windowMinutes)&&$.windowMinutes>0)}function S7($){return P1($)&&a$($.scope)&&n$($.label)}function x7($){if(!P1($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&r0($,"remainingPercent")&&r0($,"usedPercent")&&P3($,"resetsAt")&&r0($,"limit")&&r0($,"used")&&r0($,"remaining")&&P3($,"unit")}function s$($){if(!P1($)||!O1($.checkedAt))return!1;let Z=$.readings??[],J=$.coverage??[];if(!Array.isArray(Z)||!Array.isArray(J))return!1;let Q=new Set;for(let z of Z){if(!E7(z))return!1;let Y=y0(z.scope??_0,z.label);if(Q.has(Y))return!1;Q.add(Y)}if(!J.every(S7))return!1;return $.budget===void 0||x7($.budget)}function w7($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function T7($,Z,J){if(Z===void 0)return $;if($!==void 0&&J<$.checkedAt)return $;return{...Z,checkedAt:J}}function t0($,Z){if($!==void 0&&!f0($))throw new I1("stored quota map is malformed");if(!s$(Z))throw new I1("quota observation is malformed");let J=$??{limits:[]},Q=Z.checkedAt,z=new Map;for(let j of J.limits)z.set(y0(j.scope,j.label),j);let Y=(j)=>{let U=z.get(j);return U===void 0||Q>=i$(U)},G=new Set;for(let j of Z.readings??[]){let U=j.scope??_0,M=y0(U,j.label);if(G.add(M),!Y(M))continue;z.set(M,{scope:U,label:j.label,kind:"reading",checkedAt:Q,usedPercent:j.usedPercent,...j.resetsAt===void 0?{}:{resetsAt:j.resetsAt},...j.windowMinutes===void 0?{}:{windowMinutes:j.windowMinutes}})}for(let j of Z.coverage??[]){let U=j.scope??_0,M=y0(U,j.label);if(G.has(M)||!Y(M))continue;let D=z.get(M);z.set(M,D===void 0||D.kind==="absent"?{scope:U,label:j.label,kind:"absent",checkedAt:Q}:{scope:U,label:j.label,kind:"retired",retiredAt:Q})}let{limits:W,budget:X,...K}=J,H=T7(J.budget,Z.budget,Q);return{...K,limits:[...z.values()].sort(w7),...H===void 0?{}:{budget:H}}}var g7=Object.freeze({validate:f0,merge:t0});function o$($,Z,J){if($.accountIdentity!==void 0&&J!==void 0)return $.accountIdentity===J;return $.credentialId===Z}function C3($,Z,J){return $.some((Q)=>o$(Q,Z,J))}function R3($,Z,J){let Q={credentialId:Z,...J!==void 0&&{accountIdentity:J}};return[...$.filter((z)=>z.credentialId!==Z||z.accountIdentity!==J),Q]}function b3($,Z,J){return $.filter((Q)=>!Z.some((z)=>o$(Q,z,J)))}var t$="vault:";function y7($){return h7("sha256").update($).digest("hex")}function m7($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function v7($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function D0($){return[$.credentialId,...$.aliases??[]]}function e$($,Z,J={}){let Q=J.now??Date.now(),z=J.routePrefix??t$,Y=J.reservedRouteIds??new Set,G=$?.rows??[],W=[...$?.declined??[]],X=Z.skipped.length===0,K=new Set(Z.credentials.map((F)=>F.credentialId)),H=new Set(Z.skipped.flatMap((F)=>F.credentialId===void 0?[]:[F.credentialId])),j=Z.skipped.some((F)=>F.credentialId===void 0),U=(F)=>!K.has(F)&&(H.has(F)||j),M=new Map;for(let F of G){if(F.accountIdentity===void 0)continue;for(let q of D0(F))if(!M.has(q))M.set(q,F.accountIdentity)}let D=new Map;for(let F of Z.credentials){let q=F.accountIdentity!==void 0?{credential:F,identity:F.accountIdentity,claimed:!0}:{credential:F,identity:M.get(F.credentialId),claimed:!1},P=v7(q),O=D.get(P)??[];O.push(q),D.set(P,O)}let B=new Set,I=new Set(Y),T=[],m=(F,q)=>F.credential.credentialId.localeCompare(q.credential.credentialId),p=[...D.values()].map((F)=>F.toSorted(m)).sort((F,q)=>F[0]&&q[0]?m(F[0],q[0]):0);for(let F of p){let q=F[0]?.identity,P=F.filter((x)=>x.credential.state==="active"),O=P.length?P:F,E=O.filter((x)=>x.claimed),S=E.length?E:O,h=new Set(F.map((x)=>x.credential.credentialId)),w=G.find((x)=>!B.has(x)&&D0(x).some((J0)=>h.has(J0))&&(x.accountIdentity===void 0||x.accountIdentity===q)),k=S.find((x)=>x.credential.credentialId===w?.credentialId)??S[0];if(!k)continue;let _=k.credential,b=w??(q===void 0?void 0:G.find((x)=>!B.has(x)&&x.accountIdentity===q));if(b)B.add(b);let c=b?.routeId;if(!c||Y.has(c)){let x=`${z}${_.credentialId}${q===void 0?"":`~${y7(q).slice(0,10)}`}`;c=x;for(let J0=2;I.has(c);J0++)c=`${x}~${J0}`}I.add(c);let o=b?D0(b).filter(U):[],i=[...new Set([...F.map((x)=>x.credential.credentialId),...o])].filter((x)=>x!==_.credentialId).sort((x,J0)=>x.localeCompare(J0)),j0=J.mapAccount?.(_)??{};T.push({previousIndex:b?G.indexOf(b):1/0,row:{routeId:c,credentialId:_.credentialId,credentialType:_.credentialType,...q!==void 0&&{accountIdentity:q},...i.length&&{aliases:i},state:_.state,label:j0.label?.trim()||m7(_),..._.email!==void 0&&{email:_.email},..._.orgName!==void 0&&{orgName:_.orgName},enabled:![_.credentialId,...i].some((x)=>C3(W,x,q)),addedAt:b?.addedAt??Q,...b?.quota!==void 0&&{quota:b.quota},...!k.claimed&&q!==void 0&&{unclaimed:!0}}})}return G.forEach((F,q)=>{if(B.has(F)||!D0(F).some(U))return;if(I.has(F.routeId))return;let[P,...O]=D0(F).filter((h)=>!K.has(h));if(P===void 0)return;I.add(F.routeId);let{aliases:E,...S}=F;T.push({previousIndex:q,row:{...S,credentialId:P,...O.length&&{aliases:O},stale:!0}})}),T.sort((F,q)=>F.previousIndex===q.previousIndex?F.row.credentialId.localeCompare(q.row.credentialId):F.previousIndex-q.previousIndex),{version:1,view:Z.view,complete:X,...!X&&{rejected:Z.skipped.map((F)=>({...F.credentialId!==void 0&&{credentialId:F.credentialId},reason:F.reason}))},rows:T.map((F)=>F.row),declined:W}}function A3($){return($?.rows??[]).filter((Z)=>Z.enabled&&Z.state==="active").map((Z)=>({id:Z.routeId,kind:Z.credentialType==="oauth"?"oauth":"api-key",...Z.quota!==void 0&&{quota:Z.quota}}))}function C1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function m0($){return $===void 0||typeof $==="string"}function c7($){if(!C1($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!m0($.accountIdentity)||!m0($.email)||!m0($.orgName)||$.aliases!==void 0&&(!Array.isArray($.aliases)||!$.aliases.every((Z)=>typeof Z==="string"))||$.quota!==void 0&&!f0($.quota)||$.stale!==void 0&&$.stale!==!0||$.unclaimed!==void 0&&$.unclaimed!==!0)return;return $}var p7=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function r$($){if(!Array.isArray($))return;let Z=[];for(let J of $){if(!C1(J)||!m0(J.credentialId)||typeof J.reason!=="string"||!p7.has(J.reason))return;Z.push(J)}return Z}function d7($){if(!C1($)||$.version!==1||!m0($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!r$($.rejected))throw new R("invalid-state","Claustrum roster file is not valid");let Z=[];for(let z of $.rows){let Y=c7(z);if(!Y)throw new R("invalid-state","Claustrum roster file is not valid");Z.push(Y)}let J=[];for(let z of $.declined){if(!C1(z)||typeof z.credentialId!=="string"||!m0(z.accountIdentity))throw new R("invalid-state","Claustrum roster file is not valid");J.push(z)}let Q=r$($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...Q&&{rejected:Q},rows:Z,declined:J}}async function F0($){let Z;try{Z=await Y0($,A)}catch(Q){if(Q.code==="ENOENT")return;throw Q}let J;try{J=JSON.parse(Z)}catch{throw new R("invalid-state","Claustrum roster file is not valid")}return d7(J)}var u7={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000},l7={name:"claustrum-roster",ttlMs:30000};async function e0($,Z,J={}){return W3($,u7,async(Q)=>{let z=await F0($),{next:Y,result:G}=await Z(z,{assertOwned:()=>Q.assertOwned()});if(Y)await Q.assertOwned(),await z3($,Y,{beforeRename:async()=>{await J.beforePublish?.(),await Q.assertOwned()}});return G})}function k3($,Z){return e0($,(J)=>{let Q=J?.rows.find((Y)=>Y.routeId===Z);if(!J||!Q)throw new R("route-unavailable","Claustrum route is not in the roster");let z=R3(J.declined,Q.credentialId,Q.accountIdentity);return{next:{...J,declined:z,rows:J.rows.map((Y)=>Y===Q?{...Y,enabled:!1}:Y)},result:void 0}})}function _3($,Z){return e0($,(J)=>{let Q=J?.rows.find((z)=>z.routeId===Z);if(!J||!Q)throw new R("route-unavailable","Claustrum route is not in the roster");return{next:{...J,declined:b3(J.declined,D0(Q),Q.accountIdentity),rows:J.rows.map((z)=>z===Q?{...z,enabled:!0}:z)},result:void 0}})}function i7($,Z){if(!D0($).includes(Z.credentialId))return"refuse";if($.unclaimed&&(Z.accountIdentitySource==="expected"||Z.accountIdentitySource==="none"))return"refuse";if($.accountIdentity===Z.accountIdentity)return"hold";if($.accountIdentity===void 0&&Z.expectedAccountIdentity===void 0&&Z.accountIdentity!==void 0&&(Z.accountIdentitySource==="asserted"||Z.accountIdentitySource==="parsed")&&D0($).length===1)return"bind";return"refuse"}function f3($,Z){return e0($,(J)=>{let Q=J?.rows.find((W)=>W.routeId===Z.routeId),z=!J||!Q?"refuse":i7(Q,Z);if(!J||!Q||z==="refuse")return{result:!1};let Y=t0(Q.quota,Z.observation),G=z==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{next:{...J,rows:J.rows.map((W)=>W===Q?{...W,...G,quota:Y}:W)},result:!0}})}async function E3($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z())return;let J=await V0({...l7,path:$.path,renew:!0});if(!J){let Q=await F0($.path);if($.signal?.throwIfAborted(),!Q?.view)throw new R("roster-busy","Claustrum account discovery is already in progress");return Q}try{let Q=await $.custody.discover($.signal);return $.signal?.throwIfAborted(),await e0($.path,async(z)=>{if(!await Z())return{result:void 0};$.signal?.throwIfAborted(),await J.assertOwned();let Y=typeof $.projection==="function"?$.projection():$.projection,G=e$(z,Q,Y);return{...JSON.stringify(z)!==JSON.stringify(G)&&{next:G},result:G}})}finally{await J.release()}}class $2{#$;#J=new AbortController;#Z;#Y;#X;#z;#Q;#G;#H=!1;constructor($){this.#$=$,this.#Z=$.logger??n0("claustrum")}#W($){this.#J.signal.throwIfAborted(),$?.throwIfAborted()}async#K(){return await this.#$.isCustodyActive?.()??!0}#j($,Z){let J=J3([this.#J.signal,...Z?[Z]:[]]);return new Promise((Q,z)=>{let Y=()=>{J.signal.removeEventListener("abort",G),J.dispose()},G=()=>{Y(),z(J.signal.reason)};if(J.signal.addEventListener("abort",G,{once:!0}),$.then((W)=>{if(Y(),J.signal.aborted)z(J.signal.reason);else Q(W)},(W)=>{Y(),z(W)}),J.signal.aborted)G()})}async#U(){if(this.#W(),this.#Y)return this.#Y;if(!this.#X)this.#X=this.#$.connect().then(($)=>{if(this.#J.signal.aborted)$.close(),this.#W();return this.#Y=new B1({client:$,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#Z}),this.#Y}).finally(()=>{this.#X=void 0});return this.#j(this.#X)}snapshot(){return this.#Q}routingRows(){return A3(this.#Q)}refresh(){if(this.#W(),this.#z)return this.#z;return this.#z=(async()=>{if(!await this.#K()){this.#Q=void 0,this.#Y?.close(),this.#Y=void 0;return}let $=await this.#U(),Z=await E3({path:this.#$.rosterPath,custody:$,isActive:()=>this.#K(),signal:this.#J.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#W();let J=Z?.view!==this.#Q?.view;if(this.#Q=Z,Z&&J)this.#$.onRoster?.(Z);return Z})().finally(()=>{this.#z=void 0}),this.#z}start(){if(this.#H)return;this.#W(),this.#H=!0;let $=async()=>{try{await this.refresh()}catch(J){if(!this.#J.signal.aborted)this.#$.onError?.(J)}if(this.#J.signal.aborted)return;let Z=this.#$.pollIntervalMs??5000;if(Z<=0)return;this.#G=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#G=void 0,$()},Z),this.#G.unref?.()};$()}async authorize($,Z){this.#W(Z);let J=this.#Q??await this.#j(this.refresh(),Z);if(!J||!await this.#K())throw new R("not-active","Claustrum scoped custody is not active");let Q=await F0(this.#$.rosterPath);this.#W(Z);let z=J.rows.find((X)=>X.routeId===$),Y=Q?.rows.find((X)=>X.routeId===$);if(Y&&!Y.enabled)throw new R("route-declined","Claustrum route is disabled");if(!z||!Y||Y.state!=="active"||Y.credentialId!==z.credentialId||Y.accountIdentity!==z.accountIdentity)throw new R("route-unavailable","Claustrum route is disabled, removed or changed");let G=await this.#j(this.#U(),Z),W=J3([this.#J.signal,...Z?[Z]:[]]);try{return await G.authorize({credentialId:Y.credentialId,credentialType:Y.credentialType,...Y.accountIdentity!==void 0&&{accountIdentity:Y.accountIdentity}},W.signal)}finally{W.dispose()}}async reportFailure($,Z,J){if(this.#W(),!this.#Y)throw new R("no-receipt","Claustrum dispatch receipt has no active owner");await this.#Y.reportFailure($,Z,J)}async send($,Z,J){let Q=J.signal,z=await this.authorize($,Q),Y=await Z(z,Q);if(Y.status===401&&!Q?.aborted){let G;try{G=await this.authorize($,Q)}catch{}if(B3(J.site,z,G,this.#Z))await Y.body?.cancel().catch(()=>{}),z=G,Y=await Z(G,Q)}if(Y.status===401)await this.reportFailure(z,401,J.reporterSource??"direct").catch((G)=>this.#$.onError?.(G)),Promise.resolve().then(()=>this.refresh()).catch((G)=>{if(!this.#J.signal.aborted)this.#$.onError?.(G)});return Y}async decline($){this.#W(),await k3(this.#$.rosterPath,$),this.#Q=await F0(this.#$.rosterPath)}async accept($){this.#W(),await _3(this.#$.rosterPath,$),this.#Q=await F0(this.#$.rosterPath)}async recordQuota($,Z,J){this.#W();let Q=await f3(this.#$.rosterPath,{routeId:$,observation:Z,credentialId:J.credentialId,accountIdentitySource:J.accountIdentitySource,...J.accountIdentity!==void 0&&{accountIdentity:J.accountIdentity},...J.expectedAccountIdentity!==void 0&&{expectedAccountIdentity:J.expectedAccountIdentity}});if(Q)this.#Q=await F0(this.#$.rosterPath);return Q}close(){if(this.#J.signal.aborted)return;if(this.#J.abort(new R("closed","Claustrum consumer is closed")),this.#G)(this.#$.clearTimeoutImpl??clearTimeout)(this.#G);this.#G=void 0,this.#Y?.close(),this.#Q=void 0}}class W0 extends Error{code;constructor($){super(`Native vault setup: ${$}`);this.code=$;this.name="NativeVaultEnrollmentError"}}async function J2($,Z){let J={...Z.env},Q=Z.paths??Z2($,J),z=`anthropic-auth-${$}`,Y=Z.processFence,G=Z.runner,W=Z.ckBinary??"ck",X,K=Z.client;try{await Y();let H=await L1(Q,z),j=new Set(["superseded","not_found","already_consumed"]);if(H.state==="idle"||H.state==="pending"||H.state==="blocked"&&j.has(H.code)){if(!K)X=await q3({connectionFile:R1(Z.connectionFile??($==="pi"?J.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0),$==="pi"?{...J,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0}:J)}),K=X;let M=K,D=new N1({paths:Q,proposedName:z,client:{enrollPropose:async(B)=>{return await Y(),M.enrollPropose(B)},enrollPoll:async(B)=>{return await Y(),M.enrollPoll(B)}},writeTokenFile:async(B,I)=>{await Y(),await F1(B,I)}});if(H.state==="blocked"){if(await Y(),await D.resetTerminal()!=="reset")throw new W0("enrollment-refused");throw new W0("enrollment-reset")}if(await Y(),H=await D.reconcile(),H.state==="pending"&&H.requestId){if(await Y(),(await G.run(W,["auth","enroll","approve","--request-id",H.requestId,"--name",z],{env:J})).exitCode!==0)throw new W0("approval-refused");await Y(),H=await D.reconcile()}}if(H.state!=="approved")throw new W0("enrollment-refused");if(await Y(),(await G.run(W,["auth","grant","--principal",`enrolled:${z}`,"--selector-kind","category","--selector","anthropic-native","--operation","read"],{env:J})).exitCode!==0)throw new W0("permission-refused")}catch(H){if(H instanceof W0)throw H;throw new W0("enrollment-refused")}finally{X?.close()}}import{dirname as a7,join as Q2,resolve as b1}from"node:path";async function c0($,Z){let J=$==="pi"?v0(Z):E0(Z),Q=$==="pi"?Z.PI_ANTHROPIC_AUTH_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_FILE?.trim(),z=b1(Q||Q2(J,S3)),Y=b1(Z.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim()||(z.endsWith(S3)?Q2(a7(z),z2):`${z}.state.json`)),G=await A1(z,Y),W=$==="pi"?Z.PI_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim();return{host:$,paths:G,legacyConfigPath:z,legacyStatePath:Y,hostAuthPath:$==="pi"?k1(Z):G2(Z),routingSourcePath:b1(W||x3(z)),routingDestinationPath:b1(W||x3(G.config))}}async function W2($){let Z=new Map;for(let J of $)for(let Q of[J.paths.legacyConfig,J.paths.legacyState,J.paths.config,J.paths.state,J.paths.runtime,J.paths.roster,J.paths.journal,J.hostAuthPath,J.routingSourcePath,J.routingDestinationPath]){let z=await Y2(Q),Y=Z.get(z);if(Y!==void 0&&Y!==J.host)throw Error("Native setup storage paths overlap between selected hosts");Z.set(z,J.host)}}import{execFile as n7}from"node:child_process";import{promisify as s7}from"node:util";var o7=s7(n7),e={async run($,Z,J={}){try{let Q=J.env?{...process.env,...J.env}:process.env,{stdout:z,stderr:Y}=await o7($,Z,{env:Q,timeout:J.timeoutMs??15000,maxBuffer:10485760});return{exitCode:0,stdout:typeof z==="string"?z:String(z),stderr:typeof Y==="string"?Y:String(Y)}}catch(Q){let z=Q;return{exitCode:typeof z?.code==="number"?z.code:1,stdout:typeof z?.stdout==="string"?z.stdout:z?.stdout!=null?String(z.stdout):"",stderr:typeof z?.stderr==="string"?z.stderr:z?.stderr!=null?String(z.stderr):String(z?.message??Q)}}}};var X2=/(?:^|[/\\])(opencode|litecode|opencode2|pi)(?:\.exe)?(?=$|\s|")/i;class L0 extends Error{code="process-inspection-failed";constructor(){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError"}}class _1 extends Error{activeHosts;constructor($){let Z=$.map((Q)=>({pid:Q.pid,command:X2.exec(Q.command)?.[1]??"host"})),J=Z.map((Q)=>` - PID ${Q.pid}: ${Q.command}`).join(`
|
|
67
12
|
`);super(`OpenCode or Pi processes are currently running:
|
|
68
|
-
${
|
|
13
|
+
${J}
|
|
69
14
|
|
|
70
|
-
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=
|
|
71
|
-
|
|
15
|
+
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=Z,this.name="ProcessFenceViolationError"}}function r7($=e,Z={}){let J=(Z.platform??process.platform)==="win32";return{async listRunningHosts(Q){let z=J?"tasklist":"ps",Y=J?["/fo","csv","/nh"]:["-eo","pid,command"],G;try{G=await $.run(z,Y,{env:Q})}catch{throw new L0}if(G.exitCode!==0)throw new L0;let W=G.stdout.split(/\r?\n/),X=[],K=process.pid;for(let H of W){let j=H.trim();if(!j)continue;let U,M;if(J){let D=j.split(",").map((B)=>B.replace(/^"|"$/g,""));if(D.length<2)throw new L0;M=D[0]??"",U=Number(D[1])}else{let D=/^(\d+)\s+(.+)$/.exec(j);if(!D){if(/^PID\s+COMMAND$/i.test(j))continue;throw new L0}U=Number(D[1]),M=D[2]??""}if(!Number.isInteger(U)||U<0)throw new L0;if(U===K)continue;if(X2.test(M))X.push({pid:U,command:M})}return X}}}var w3=r7(e);async function p0($=w3){let Z=await $.listRunningHosts();if(Z.length>0)throw new _1(Z)}class S0 extends Error{code;constructor($){super({"auth-content-refused":"Run setup without OPENCODE_AUTH_CONTENT in the environment.","host-auth-invalid":"The host auth file could not be read safely.","primary-conflict":"Pi has a stored Anthropic API key, which would take precedence over the vault account. Remove it in Pi, then rerun setup.","consent-required":"Pi has stored Anthropic authentication. Explicit consent is required to move it aside for vault use.","primary-unverified":"The vault has no verified default Claude account. Sign in through the vault and rerun setup."}[$]);this.code=$;this.name="NativeVaultActivationError"}}async function e7($){try{return JSON.parse(await t7($,"utf8"))}catch(Z){if(Z.code==="ENOENT")return;throw new S0("host-auth-invalid")}}async function H2($,Z){let J={...Z.env},Q=async()=>{try{f1(J)}catch{throw new S0("auth-content-refused")}await p0(Z.fence)};await Q();let z=Z.paths??await c0($,J);if($==="pi"){let X=K2("pi",await e7(z.hostAuthPath)),K=await T3({env:J,authPath:z.hostAuthPath}).inspect();if(K.slot==="placeholder"&&K.stash==="missing")throw new E1("missing-stash");if(X.kind!=="absent"&&K.slot!=="placeholder"&&!Z.removePiAnthropicAuth)throw new S0("consent-required")}let Y=await N0($,J);await J2($,{env:J,runner:Z.runner,processFence:Q,...Z.enrollment});let G=Z.discover??(()=>j2({paths:z.paths,host:$,env:$==="pi"?{...J,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:J.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE}:J})),W=d0({paths:z.paths,host:$,vault:{env:J,discover:G}});try{await Q(),await W.vault.refresh();let X=await W.read(),K=X.accounts.find((H)=>H.id==="main");if(X.mode!=="claustrum"||!K?.accountIdentity||K.source!=="vault")throw new S0("primary-unverified");if(await Q(),$==="pi")await T3({env:J,authPath:z.hostAuthPath}).enterVault();return Y==="claustrum"?"already-vault":"committed"}finally{W.close()}}var Y4={"setup-activation":"Vault custody setup","setup-opencode-config":"OpenCode configuration","setup-pi-install":"Pi extension installation","setup-pi":"Pi setup","setup-process-check":"Host process check","cli-setup":"Setup","cli-login":"Login","cli-api-add":"API route setup","cli-list":"Account listing","cli-relay-setup":"Relay setup","cli-relay-workers-dev":"Workers.dev enablement","cli-command":"Command"};function $1(){return($)=>$}var G4=$1()(["auth-content-refused","host-auth-invalid","primary-conflict","consent-required","primary-unverified"]),W4=$1()(["enrollment-refused","enrollment-reset","approval-refused","permission-refused"]),X4=$1()(["invalid-source","unsafe-source","consent-required","primary-unverified","migration-busy","ownership-lost","retirement-refused"]),K4=$1()(["invalid-options","invalid-auth","invalid-stash","unsafe-path","missing-stash","conflict","lock-timeout","lock-compromised","io"]),j4=$1()(["closed","not-enrolled","invalid-token","unavailable","identity-changed","identity-unasserted","insufficient-validity","invalid-material","not-active","route-unavailable","route-declined","no-receipt","unsafe-file","invalid-state","wrong-consumer","roster-busy","host-slot-login","host-slot-placeholder","placeholder-refresh"]),H4=new Set([new L0().message,...G4.map(($)=>new S0($).message),...W4.map(($)=>new W0($).message),...X4.map(($)=>new L2($).message),...K4.map(($)=>new E1($).message),...j4.map(($)=>`Native custody refused: ${$}`),"Disconnect from the vault first.","Native account changes require offline setup without OPENCODE_AUTH_CONTENT","Local login cannot be verified while OPENCODE_AUTH_CONTENT is set","Authentication failed","API fallback base URL must be an http(s) URL without embedded credentials","API key is required","Vault routes cannot be replaced with a local API key","Cloudflare API token is required","Cloudflare account ID is required","Relay Worker URL is required","Claude sign-in did not establish an account UUID","Native setup storage paths overlap between selected hosts","Anthropic account storage paths overlap; migration requires separate files","Anthropic account migration is required. Stop OpenCode, LiteCode and Pi, then run bunx @cortexkit/opencode-anthropic-auth@2.0.0 setup","Anthropic account migration is incomplete; resume setup","Anthropic account migration journal is invalid","Anthropic account migration journal changed","Anthropic runtime state is invalid","Anthropic runtime file is not owner-only regular storage","Anthropic runtime storage is unavailable","Anthropic runtime observation is older than persisted state","Anthropic runtime publication was refused","OAuth metadata read failed"]),U4=new Set(["opencode","litecode","opencode2","pi","host"]),q4=64,V4=256,M4=4096,g3=65536,D4=4096,F4=3,q2="[output beyond the diagnostic limit omitted]",L4="[output withheld: no line break within the inspected window]",N4="[detail withheld: the known credentials could not be read safely]",m3=new TextEncoder,N2=new TextDecoder;function $0($,Z){let J=Object.getOwnPropertyDescriptor($,Z);return J!==void 0&&"value"in J?J.value:void 0}function Z1($){return $!==null&&(typeof $==="object"||typeof $==="function")&&!y3.isProxy($)}function B2($,Z){if(!Z1($)||!Array.isArray($))return;let J=$0($,"length");if(typeof J!=="number"||J>Z)return;let Q=[];for(let z=0;z<J;z+=1){let Y=Object.getOwnPropertyDescriptor($,String(z));if(Y===void 0||!("value"in Y))return;Q.push(Y.value)}return Q}function B4($){let Z=B2($,q4);if(Z===void 0||Z.length===0)return;let J=[];for(let Q of Z){if(!Z1(Q))return;let z=$0(Q,"pid"),Y=$0(Q,"command");if(typeof z!=="number"||!Number.isSafeInteger(z)||z<0)return;if(typeof Y!=="string"||!U4.has(Y.toLowerCase()))return;J.push({pid:z,command:Y})}return J}function I4($){try{if(!Z1($))return;let Z=$0($,"message");if(typeof Z!=="string")return;if(H4.has(Z))return Z;let J=$0($,"status");if(typeof J==="number"&&Number.isInteger(J)&&J>=100&&J<=599&&Z===`OAuth metadata read failed: ${J}`)return Z;let Q=B4($0($,"activeHosts"));if(Q&&Z===new _1(Q).message)return Z}catch{}return}function O4($,Z=[]){try{let J=new Set,Q=B2(Z,V4);if(Q===void 0)return;for(let Y of Q){if(typeof Y!=="string")return;if(Y!=="")J.add(Y)}if(!Z1($))return;let z=Reflect.ownKeys($);if(z.length>M4)return;for(let Y of z){if(typeof Y!=="string"||!M2(Y))continue;let G=Object.getOwnPropertyDescriptor($,Y);if(G===void 0)continue;if(!("value"in G))return;if(G.value===void 0||G.value==="")continue;if(typeof G.value!=="string")return;J.add(G.value)}return[...J]}catch{return}}function P4($,Z){let J=m3.encode($);if(J.length<=Z)return $;let Q=Math.max(0,Z);while(Q>0&&((J[Q]??0)&192)===128)Q-=1;return N2.decode(J.subarray(0,Q))}function C4($,Z){let J=m3.encode($);if(J.length<=Z)return $;let Q=J.length-Math.max(0,Z);while(Q<J.length&&((J[Q]??0)&192)===128)Q+=1;return N2.decode(J.subarray(Q))}function R4($,Z,J){let Q=$,z=!1;if($.length>g3){if(z=!0,J==="tail"){let X=$.indexOf(`
|
|
16
|
+
`,$.length-g3);Q=X===-1?"":$.slice(X+1)}else{let X=$.lastIndexOf(`
|
|
17
|
+
`,g3);Q=X===-1?"":$.slice(0,X)}if(Q==="")return[L4]}let Y=Z.redactText(Q).split(/\r?\n/);if(Y.length>1&&Y[Y.length-1]==="")Y.pop();if(J==="tail")Y.reverse();let G=[],W=D4;for(let X of Y){let K=m3.encode(X).length+1;if(K<=W){G.push(X),W-=K;continue}if(G.length===0)G.push(J==="tail"?C4(X,W-1):P4(X,W-1));z=!0;break}if(J==="tail")G.reverse();if(z)if(J==="tail")G.unshift(q2);else G.push(q2);return G}function b4($){let Z=$;for(let J=0;Z!==null&&J<8;J+=1){if(y3.isProxy(Z))break;let Q=$0(Z,"name");if(typeof Q==="string")return Q;Z=Object.getPrototypeOf(Z)}return"object"}function I2($,Z){if($===null||typeof $!=="object"&&typeof $!=="function")return[`thrown ${typeof $}: ${String($)}`];if(y3.isProxy($))return["thrown proxy (not inspected)"];let J=[],Q=b4($),z=$0($,"message");J.push(typeof z==="string"?`${Q}: ${z}`:`${Q} (no message)`);let Y=$0($,"code");if(typeof Y==="string"||typeof Y==="number")J.push(`code: ${Y}`);let G=$0($,"stack");if(typeof G==="string")J.push(G);let W=$0($,"cause");if(W!==void 0)if(Z>=F4)J.push("caused by: [not described]");else J.push("caused by:",...I2(W,Z+1));return J}function V2($,Z){let J=$0($,Z);return typeof J==="string"&&J!==""?J:void 0}function A4($){if(!Z1($))return;let Z=V2($,"XDG_STATE_HOME"),J=V2($,"HOME"),Q=Z&&U2(Z)?Z:h3(J&&U2(J)?J:z4(),".local","state");return h3(Q,"cortexkit","anthropic-auth","diagnostics")}async function k4($,Z,J){try{let Q=A4($);if(Q===void 0)return;await J4(Q,{recursive:!0,mode:448});let z=await Z4(Q);if(!z.isDirectory())return;if(process.platform!=="win32"){if((z.mode&63)!==0)return;if(z.uid!==process.getuid?.())return}let Y=h3(Q,`${Z}-${Date.now()}-${process.pid}-${$4()}.log`),G=await Q4(Y,S1.O_WRONLY|S1.O_CREAT|S1.O_EXCL|(S1.O_NOFOLLOW??0),384);try{await G.writeFile(J,"utf8")}finally{await G.close()}return Y}catch{return}}async function O2($,Z,J,Q,z,Y){let G,W=O4(J,Q);if(W===void 0)G=[N4];else try{let j=F2(W);try{let{text:U,keep:M}=Y();G=R4(U,j,M)}finally{j.dispose()}}catch{G=["[failure detail could not be recorded]"]}let X=Y4[$],K=D2("error","cli",`${X} failed`,{stage:$,code:Z,...z}),H=await k4(J,$,`${[K,...G].join(`
|
|
18
|
+
`)}
|
|
19
|
+
`);return H===void 0?`${X} failed (${Z}). Details could not be saved to a private diagnostics file.`:`${X} failed (${Z}). Details were written to ${H}`}async function B0($,Z,J,Q=[]){let z=I4(Z);if(z!==void 0)return z;return O2($,`${$}/unexpected-error`,J,Q,{},()=>({text:I2(Z,0).join(`
|
|
20
|
+
`),keep:"head"}))}async function P2($,Z,J){return O2($,`${$}/installer-exit`,J,[],{exitCode:Number.isInteger(Z.exitCode)?Z.exitCode:null},()=>({text:typeof Z.stderr==="string"?Z.stderr:"",keep:"tail"}))}import{styleText as h1}from"node:util";import{stdout as a3,stdin as d2}from"node:process";import*as I0 from"node:readline";import l4 from"node:readline";var C2=(()=>{let $=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(Z)=>{let J=0;$.lastIndex=0;while($.test(Z))J+=1;return Z.length-J}})(),R2=($)=>{return $===12288||$>=65281&&$<=65376||$>=65504&&$<=65510},b2=($)=>{return $===8987||$===9001||$>=12272&&$<=12287||$>=12289&&$<=12350||$>=12441&&$<=12543||$>=12549&&$<=12591||$>=12593&&$<=12686||$>=12688&&$<=12771||$>=12783&&$<=12830||$>=12832&&$<=12871||$>=12880&&$<=19903||$>=65040&&$<=65049||$>=65072&&$<=65106||$>=65108&&$<=65126||$>=65128&&$<=65131||$>=127488&&$<=127490||$>=127504&&$<=127547||$>=127552&&$<=127560||$>=131072&&$<=196605||$>=196608&&$<=262141};var _4=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,f4=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,A2=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,E4=/\t{1,1000}/y,k2=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,S4=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,x4=/\p{M}+/gu,w4={limit:1/0,ellipsis:""},_2=($,Z={},J={})=>{let Q=Z.limit??1/0,z=Z.ellipsis??"",Y=Z?.ellipsisWidth??(z?_2(z,w4,J).width:0),G=0,W=J.controlWidth??0,X=J.tabWidth??8,K=J.emojiWidth??2,H=2,j=J.regularWidth??1,U=J.wideWidth??2,M=[[S4,j],[_4,0],[f4,W],[E4,X],[k2,K],[A2,U]],D=0,B=0,I=$.length,T=0,m=!1,p=I,F=Math.max(0,Q-Y),q=0,P=0,O=0,E=0;$:while(!0){if(P>q||B>=I&&B>D){let S=$.slice(q,P)||$.slice(D,B);T=0;for(let h of S.replaceAll(x4,"")){let w=h.codePointAt(0)||0;if(R2(w))E=2;else if(b2(w))E=U;else E=j;if(O+E>F)p=Math.min(p,Math.max(q,D)+T);if(O+E>Q){m=!0;break $}T+=h.length,O+=E}q=P=0}if(B>=I)break $;for(let S=0,h=M.length;S<h;S++){let[w,k]=M[S];if(w.lastIndex=B,w.test($)){if(T=w===A2?C2($.slice(B,w.lastIndex)):w===k2?1:w.lastIndex-B,E=T*k,O+E>F)p=Math.min(p,B+Math.floor((F-O)/k));if(O+E>Q){m=!0;break $}O+=E,q=D,P=B,B=D=w.lastIndex;continue $}}B+=1}return{width:m?F:O,index:m?p:I,truncated:m,ellipsed:m&&Q>=Y}},f2=_2;var T4={limit:1/0,ellipsis:"",ellipsisWidth:0},g4=($,Z={})=>{return f2($,T4,Z).width},s=g4;var x1="\x1B",T2="",h4=39,c3="\x07",g2="[",y4="]",h2="m",p3=`${y4}8;;`,E2=new RegExp(`(?:\\${g2}(?<code>\\d+)m|\\${p3}(?<uri>.*)${c3})`,"y"),S2=($)=>{if($>=30&&$<=37)return 39;if($>=90&&$<=97)return 39;if($>=40&&$<=47)return 49;if($>=100&&$<=107)return 49;if($===1||$===2)return 22;if($===3)return 23;if($===4)return 24;if($===7)return 27;if($===8)return 28;if($===9)return 29;if($===0)return 0;return},x2=($)=>`${x1}${g2}${$}${h2}`,w2=($)=>`${x1}${p3}${$}${c3}`,v3=($,Z,J)=>{let Q=Z[Symbol.iterator](),z=!1,Y=!1,G=$.at(-1),W=G===void 0?0:s(G),X=Q.next(),K=Q.next(),H=0;while(!X.done){let j=X.value,U=s(j);if(W+U<=J)$[$.length-1]+=j;else $.push(j),W=0;if(j===x1||j===T2)z=!0,Y=Z.startsWith(p3,H+1);if(z){if(Y){if(j===c3)z=!1,Y=!1}else if(j===h2)z=!1}else if(W+=U,W===J&&!K.done)$.push(""),W=0;X=K,K=Q.next(),H+=j.length}if(G=$.at(-1),!W&&G!==void 0&&G.length&&$.length>1)$[$.length-2]+=$.pop()},m4=($)=>{let Z=$.split(" "),J=Z.length;while(J){if(s(Z[J-1]))break;J--}if(J===Z.length)return $;return Z.slice(0,J).join(" ")+Z.slice(J).join("")},v4=($,Z,J={})=>{if(J.trim!==!1&&$.trim()==="")return"";let Q="",z,Y,G=$.split(" "),W=[""],X=0;for(let j=0;j<G.length;j++){let U=G[j];if(J.trim!==!1){let D=W.at(-1)??"",B=D.trimStart();if(D.length!==B.length)W[W.length-1]=B,X=s(B)}if(j!==0){if(X>=Z&&(J.wordWrap===!1||J.trim===!1))W.push(""),X=0;if(X||J.trim===!1)W[W.length-1]+=" ",X++}let M=s(U);if(J.hard&&M>Z){let D=Z-X,B=1+Math.floor((M-D-1)/Z);if(Math.floor((M-1)/Z)<B)W.push("");v3(W,U,Z),X=s(W.at(-1)??"");continue}if(X+M>Z&&X&&M){if(J.wordWrap===!1&&X<Z){v3(W,U,Z),X=s(W.at(-1)??"");continue}W.push(""),X=0}if(X+M>Z&&J.wordWrap===!1){v3(W,U,Z),X=s(W.at(-1)??"");continue}W[W.length-1]+=U,X+=M}if(J.trim!==!1)W=W.map((j)=>m4(j));let K=W.join(`
|
|
21
|
+
`),H=!1;for(let j=0;j<K.length;j++){let U=K[j];if(Q+=U,!H){if(H=U>="\uD800"&&U<="\uDBFF",H)continue}else H=!1;if(U===x1||U===T2){E2.lastIndex=j+1;let D=E2.exec(K)?.groups;if(D?.code!==void 0){let B=Number.parseFloat(D.code);z=B===h4?void 0:B}else if(D?.uri!==void 0)Y=D.uri.length===0?void 0:D.uri}if(K[j+1]===`
|
|
22
|
+
`){if(Y)Q+=w2("");let M=z?S2(z):void 0;if(z&&M)Q+=x2(M)}else if(U===`
|
|
23
|
+
`){if(z&&S2(z))Q+=x2(z);if(Y)Q+=w2(Y)}}return Q},c4=/\r?\n/;function X0($,Z,J){return String($).normalize().split(c4).map((Q)=>v4(Q,Z,J)).join(`
|
|
24
|
+
`)}var a=p2(u3(),1);import{ReadStream as m2}from"node:tty";function u0($,Z,J){if(!J.some((G)=>!G.disabled))return $;let Q=$+Z,z=Math.max(J.length-1,0),Y=Q<0?z:Q>z?0:Q;return J[Y]?.disabled?u0(Y,Z<0?-1:1,J):Y}function w1($,Z,J,Q){let z=Q.split(`
|
|
25
|
+
`),Y=0,G=$;for(let X of z){if(G<=X.length)break;G-=X.length+1,Y++}for(Y=Math.max(0,Math.min(z.length-1,Y+J)),G=Math.min(G,z[Y].length)+Z;G<0&&Y>0;)Y--,G+=z[Y].length+1;for(;G>z[Y].length&&Y<z.length-1;)G-=z[Y].length+1,Y++;G=Math.max(0,Math.min(z[Y].length,G));let W=0;for(let X=0;X<Y;X++)W+=z[X].length+1;return W+G}var i4=["up","down","left","right","space","enter","cancel"],a4=["January","February","March","April","May","June","July","August","September","October","November","December"],d={actions:new Set(i4),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,accessible:void 0,date:{monthNames:[...a4],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:($,Z)=>`There are only ${$} days in ${Z}`,afterMin:($)=>`Date must be on or after ${$.toISOString().slice(0,10)}`,beforeMax:($)=>`Date must be on or before ${$.toISOString().slice(0,10)}`}}};function n4($){if($!==void 0)return $;if(d.accessible!==void 0)return d.accessible;let Z=process.env.ACCESSIBLE;return Z!==void 0&&Z!==""&&Z!=="0"&&Z!=="false"}function n3($,Z){if(typeof $=="string")return d.aliases.get($)===Z;for(let J of $)if(J!==void 0&&n3(J,Z))return!0;return!1}function s4($,Z){if($===Z)return;let J=$.split(`
|
|
26
|
+
`),Q=Z.split(`
|
|
27
|
+
`),z=Math.max(J.length,Q.length),Y=[];for(let G=0;G<z;G++)J[G]!==Q[G]&&Y.push(G);return{lines:Y,numLinesBefore:J.length,numLinesAfter:Q.length,numLines:z}}var o4=globalThis.process.platform.startsWith("win"),y1=Symbol("clack:cancel");function O0($){return $===y1}function T1($,Z){let J=$;J.isTTY&&J.setRawMode(Z)}function u2({input:$=d2,output:Z=a3,overwrite:J=!0,hideCursor:Q=!0}={}){let z=I0.createInterface({input:$,output:Z,prompt:"",tabSize:1});I0.emitKeypressEvents($,z),$ instanceof m2&&$.isTTY&&$.setRawMode(!0);let Y=(G,{name:W,sequence:X})=>{let K=String(G);if(n3([K,W,X],"cancel")){Q&&Z.write(a.cursor.show),process.exit(0);return}if(!J)return;I0.moveCursor(Z,W==="return"?0:-1,W==="return"?-1:0,()=>{I0.clearLine(Z,1,()=>{$.once("keypress",Y)})})};return Q&&Z.write(a.cursor.hide),$.once("keypress",Y),()=>{$.off("keypress",Y),Q&&Z.write(a.cursor.show),$ instanceof m2&&$.isTTY&&!o4&&$.setRawMode(!1),z.terminal=!1,z.close()}}var J1=($)=>("columns"in $)&&typeof $.columns=="number"?$.columns:80,s3=($)=>("rows"in $)&&typeof $.rows=="number"?$.rows:20;function Q1($,Z,J,Q=J,z=J,Y){let G=J1($??a3);return X0(Z,G-J.length,{hard:!0,trim:!1}).split(`
|
|
28
|
+
`).map((W,X,K)=>{let H=Y?Y(W,X):W;return X===0?`${Q}${H}`:X===K.length-1?`${z}${H}`:`${J}${H}`}).join(`
|
|
29
|
+
`)}function l2($,Z){if("~standard"in $){let J=$["~standard"].validate(Z);return J instanceof Promise?J.then((Q)=>Q.issues?.at(0)?.message):J.issues?.at(0)?.message}return $(Z)}class P0{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";get accessible(){return n4(this.opts.accessible)}constructor($,Z=!0){let{input:J=d2,output:Q=a3,render:z,signal:Y,...G}=$;this.opts=G,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=z.bind(this),this._track=Z,this._abortSignal=Y,this.input=J,this.output=Q}unsubscribe(){this._subscribers.clear()}setSubscriber($,Z){let J=this._subscribers.get($)??[];J.push(Z),this._subscribers.set($,J)}on($,Z){this.setSubscriber($,{cb:Z})}once($,Z){this.setSubscriber($,{cb:Z,once:!0})}emit($,...Z){let J=this._subscribers.get($)??[],Q=[];for(let z of J)z.cb(...Z),z.once&&Q.push(()=>J.splice(J.indexOf(z),1));for(let z of Q)z()}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(y1);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=l4.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),T1(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(a.cursor.show),this.output.off("resize",this.render),T1(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(a.cursor.show),this.output.off("resize",this.render),T1(this.input,!1),$(y1)})})}_isActionKey($,Z){return $==="\t"}_shouldSubmit($,Z){return!0}_setValue($){this.value=$,this.emit("value",this.value)}_setUserInput($,Z){this.userInput=$??"",this.emit("userInput",this.userInput),Z&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}async onKeypress($,Z){if(this.state!=="validating"){if(this._track&&Z.name!=="return"&&(Z.name&&this._isActionKey($,Z)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),Z?.name&&(!this._track&&d.aliases.has(Z.name)&&this.emit("cursor",d.aliases.get(Z.name)),d.actions.has(Z.name)&&this.emit("cursor",Z.name)),$&&($.toLowerCase()==="y"||$.toLowerCase()==="n")&&this.emit("confirm",$.toLowerCase()==="y"),this.emit("key",$,Z),Z?.name==="return"&&this._shouldSubmit($,Z)){if(this.opts.validate){let J=l2(this.opts.validate,this.value),Q;J instanceof Promise?(this.state="validating",this.render(),Q=await J):Q=J,Q&&(this.error=Q instanceof Error?Q.message:Q,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}n3([$,Z?.name,Z?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
30
|
+
`),T1(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let $=X0(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
31
|
+
`).length-1;this.output.write(a.cursor.move(-999,$*-1))}render(){let $=X0(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if($!==this._prevFrame){if(this.state==="initial")this.output.write(a.cursor.hide);else{let Z=s4(this._prevFrame,$),J=s3(this.output);if(this.restoreCursor(),Z){let Q=Math.max(0,Z.numLinesAfter-J),z=Math.max(0,Z.numLinesBefore-J),Y=Z.lines.find((G)=>G>=Q);if(Y===void 0){this._prevFrame=$;return}if(Z.lines.length===1){this.output.write(a.cursor.move(0,Y-z)),this.output.write(a.erase.lines(1));let G=$.split(`
|
|
32
|
+
`);this.output.write(G[Y]),this._prevFrame=$,this.output.write(a.cursor.move(0,G.length-Y-1));return}else if(Z.lines.length>1){if(Q<z)Y=Q;else{let W=Y-z;W>0&&this.output.write(a.cursor.move(0,W))}this.output.write(a.erase.down());let G=$.split(`
|
|
33
|
+
`).slice(Y);this.output.write(G.join(`
|
|
34
|
+
`)),this._prevFrame=$;return}}this.output.write(a.erase.down())}this.output.write($),this.state==="initial"&&(this.state="active"),this._prevFrame=$}}}function r4($,Z){if($===void 0||Z.length===0)return 0;let J=Z.findIndex((Q)=>Q.value===$);return J!==-1?J:0}function t4($,Z){return(Z.label??String(Z.value)).toLowerCase().includes($.toLowerCase())}function e4($,Z){if(Z)return $?Z:Z[0]}var $8=class extends P0{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#J="";#Z;#Y;#X;#z;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return h1(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let Z=this.userInput.slice(0,this.cursor),J=this.userInput.slice(this.cursor,this.cursor+1),Q=this.userInput.slice(this.cursor+1);return`${Z}${h1("inverse",J)}${Q}`}get options(){return typeof this.#Y=="function"?this.#Y():this.#Y}constructor(Z){super(Z),this.#Y=Z.options,this.#X=Z.placeholder,this.#z=Z.completeOnTab===!0;let J=this.options;this.filteredOptions=[...J],this.multiple=Z.multiple===!0,this.#Z=typeof Z.options=="function"?Z.filter:Z.filter??t4;let Q;if(Z.initialValue&&Array.isArray(Z.initialValue)?this.multiple?Q=Z.initialValue:Q=Z.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(Q=[this.options[0]?.value]),Q)for(let z of Q){let Y=J.findIndex((G)=>G.value===z);Y!==-1&&(this.toggleSelected(z),this.#$=Y)}this.focusedValue=this.options[this.#$]?.value,this.on("key",(z,Y)=>this.#Q(z,Y)),this.on("userInput",(z)=>this.#G(z))}_isActionKey(Z,J){return Z==="\t"||this.multiple&&this.isNavigating&&J.name==="space"&&Z!==void 0&&Z!==""}#Q(Z,J){let Q=J.name==="up",z=J.name==="down",Y=J.name==="return",G=this.userInput===""||this.userInput==="\t",W=this.#X,X=this.options,K=W!==void 0&&W!==""&&X.some((H)=>!H.disabled&&(this.#Z?this.#Z(W,H):!0));if(J.name==="tab"&&G&&K){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(W,!0),this.isNavigating=!1;return}if(J.name==="tab"&&this.#z&&!this.multiple&&this.focusedValue!==void 0){let H=String(this.focusedValue);this._clearUserInput(),this._setUserInput(H,!0),this.isNavigating=!1;return}Q||z?(this.#$=u0(this.#$,Q?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):Y?this.value=e4(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(J.name==="tab"||this.isNavigating&&J.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(Z){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(Z)?this.selectedValues=this.selectedValues.filter((J)=>J!==Z):this.selectedValues=[...this.selectedValues,Z]:this.selectedValues=[Z])}#G(Z){if(Z!==this.#J){this.#J=Z;let J=this.options;Z&&this.#Z?this.filteredOptions=J.filter((Y)=>this.#Z?.(Z,Y)):this.filteredOptions=[...J];let Q=r4(this.focusedValue,this.filteredOptions);this.#$=u0(Q,0,this.filteredOptions);let z=this.filteredOptions[this.#$];z&&!z.disabled?this.focusedValue=z.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class o3 extends P0{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor($){super($,!1),this.value=!!$.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(Z)=>{this.output.write(a.cursor.move(0,-1)),this.value=Z,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var Z8={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function v2($){return[...$].map((Z)=>Z8[Z])}function J8($){let Z=new Intl.DateTimeFormat($,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),J=[],Q="/";for(let z of Z)z.type==="literal"?Q=z.value.trim()||z.value:(z.type==="year"||z.type==="month"||z.type==="day")&&J.push({type:z.type,len:z.type==="year"?4:2});return{segments:J,separator:Q}}function l3($){return Number.parseInt(($||"0").replace(/_/g,"0"),10)||0}function g1($){return{year:l3($.year),month:l3($.month),day:l3($.day)}}function i3($,Z){return new Date($||2001,Z||1,0).getDate()}function i2($){let{year:Z,month:J,day:Q}=g1($);if(!Z||Z<0||Z>9999||!J||J<1||J>12||!Q||Q<1)return;let z=new Date(Date.UTC(Z,J-1,Q));if(!(z.getUTCFullYear()!==Z||z.getUTCMonth()!==J-1||z.getUTCDate()!==Q))return{year:Z,month:J,day:Q}}function c2($){let Z=i2($);return Z?new Date(Date.UTC(Z.year,Z.month-1,Z.day)):void 0}function Q8($,Z,J,Q){let z=J?{year:J.getUTCFullYear(),month:J.getUTCMonth()+1,day:J.getUTCDate()}:null,Y=Q?{year:Q.getUTCFullYear(),month:Q.getUTCMonth()+1,day:Q.getUTCDate()}:null;return $==="year"?{min:z?.year??1,max:Y?.year??9999}:$==="month"?{min:z&&Z.year===z.year?z.month:1,max:Y&&Z.year===Y.year?Y.month:12}:{min:z&&Z.year===z.year&&Z.month===z.month?z.day:1,max:Y&&Z.year===Y.year&&Z.month===Y.month?Y.day:i3(Z.year,Z.month)}}class a2 extends P0{#$;#J;#Z;#Y;#X;#z={segmentIndex:0,positionInSegment:0};#Q=!0;#G=null;inlineError="";get segmentCursor(){return{...this.#z}}get segmentValues(){return{...this.#Z}}get segments(){return this.#$}get separator(){return this.#J}get formattedValue(){return this.#H(this.#Z)}#H($){return this.#$.map((Z)=>$[Z.type]).join(this.#J)}#W(){this._setUserInput(this.#H(this.#Z)),this._setValue(c2(this.#Z)??void 0)}constructor($){let Z=$.format?{segments:v2($.format),separator:$.separator??"/"}:J8($.locale),J=$.separator??Z.separator,Q=$.format?v2($.format):Z.segments,z=$.initialValue??$.defaultValue,Y=z?{year:String(z.getUTCFullYear()).padStart(4,"0"),month:String(z.getUTCMonth()+1).padStart(2,"0"),day:String(z.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},G=Q.map((W)=>Y[W.type]).join(J);super({...$,initialUserInput:G},!1),this.#$=Q,this.#J=J,this.#Z=Y,this.#Y=$.minDate,this.#X=$.maxDate,this.#W(),this.on("cursor",(W)=>this.#V(W)),this.on("key",(W,X)=>this.#M(W,X)),this.on("finalize",()=>this.#D($))}#K(){let $=Math.max(0,Math.min(this.#z.segmentIndex,this.#$.length-1)),Z=this.#$[$];if(Z)return this.#z.positionInSegment=Math.max(0,Math.min(this.#z.positionInSegment,Z.len-1)),{segment:Z,index:$}}#j($){this.inlineError="",this.#G=null;let Z=this.#K();Z&&(this.#z.segmentIndex=Math.max(0,Math.min(this.#$.length-1,Z.index+$)),this.#z.positionInSegment=0,this.#Q=!0)}#U($){let Z=this.#K();if(!Z)return;let{segment:J}=Z,Q=this.#Z[J.type],z=!Q||Q.replace(/_/g,"")==="",Y=Number.parseInt((Q||"0").replace(/_/g,"0"),10)||0,G=Q8(J.type,g1(this.#Z),this.#Y,this.#X),W;z?W=$===1?G.min:G.max:W=Math.max(Math.min(G.max,Y+$),G.min),this.#Z={...this.#Z,[J.type]:W.toString().padStart(J.len,"0")},this.#Q=!0,this.#G=null,this.#W()}#V($){if($)switch($){case"right":return this.#j(1);case"left":return this.#j(-1);case"up":return this.#U(1);case"down":return this.#U(-1)}}#M($,Z){if(Z?.name==="backspace"||Z?.sequence===""||Z?.sequence==="\b"||$===""||$==="\b"){this.inlineError="";let J=this.#K();if(!J)return;if(!this.#Z[J.segment.type].replace(/_/g,"")){this.#j(-1);return}this.#Z[J.segment.type]="_".repeat(J.segment.len),this.#Q=!0,this.#z.positionInSegment=0,this.#W();return}if(Z?.name==="tab"){this.inlineError="";let J=this.#K();if(!J)return;let Q=Z.shift?-1:1,z=J.index+Q;z>=0&&z<this.#$.length&&(this.#z.segmentIndex=z,this.#z.positionInSegment=0,this.#Q=!0);return}if($&&/^[0-9]$/.test($)){let J=this.#K();if(!J)return;let{segment:Q}=J,z=!this.#Z[Q.type].replace(/_/g,"");if(this.#Q&&this.#G!==null&&!z){let U=this.#G+$,M={...this.#Z,[Q.type]:U},D=this.#q(M,Q);if(D){this.inlineError=D,this.#G=null,this.#Q=!1;return}this.inlineError="",this.#Z[Q.type]=U,this.#G=null,this.#Q=!1,this.#W(),J.index<this.#$.length-1&&(this.#z.segmentIndex=J.index+1,this.#z.positionInSegment=0,this.#Q=!0);return}this.#Q&&!z&&(this.#Z[Q.type]="_".repeat(Q.len),this.#z.positionInSegment=0),this.#Q=!1,this.#G=null;let Y=this.#Z[Q.type],G=Y.indexOf("_"),W=G>=0?G:Math.min(this.#z.positionInSegment,Q.len-1);if(W<0||W>=Q.len)return;let X=Y.slice(0,W)+$+Y.slice(W+1),K=!1;if(W===0&&Y==="__"&&(Q.type==="month"||Q.type==="day")){let U=Number.parseInt($,10);X=`0${$}`,K=U<=(Q.type==="month"?1:2)}if(Q.type==="year"&&(X=(Y.replace(/_/g,"")+$).padStart(Q.len,"_")),!X.includes("_")){let U={...this.#Z,[Q.type]:X},M=this.#q(U,Q);if(M){this.inlineError=M;return}}this.inlineError="",this.#Z[Q.type]=X;let H=X.includes("_")?void 0:i2(this.#Z);if(H){let{year:U,month:M}=H,D=i3(U,M);this.#Z={year:String(Math.max(0,Math.min(9999,U))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,M))).padStart(2,"0"),day:String(Math.max(1,Math.min(D,H.day))).padStart(2,"0")}}this.#W();let j=X.indexOf("_");K?(this.#Q=!0,this.#G=$):j>=0?this.#z.positionInSegment=j:G>=0&&J.index<this.#$.length-1?(this.#z.segmentIndex=J.index+1,this.#z.positionInSegment=0,this.#Q=!0):this.#z.positionInSegment=Math.min(W+1,Q.len-1)}}#q($,Z){let{month:J,day:Q}=g1($);if(Z.type==="month"&&(J<0||J>12))return d.date.messages.invalidMonth;if(Z.type==="day"&&(Q<0||Q>31))return d.date.messages.invalidDay(31,"any month")}#D($){let{year:Z,month:J,day:Q}=g1(this.#Z);if(Z&&J&&Q){let z=i3(Z,J);this.#Z={...this.#Z,day:String(Math.min(Q,z)).padStart(2,"0")}}this.value=c2(this.#Z)??$.defaultValue??void 0}}var z8=class extends P0{options;cursor=0;#$;getGroupItems(Z){return this.options.filter((J)=>J.group===Z)}isGroupSelected(Z){let J=this.getGroupItems(Z),Q=this.value;return Q===void 0?!1:J.every((z)=>Q.includes(z.value))}toggleValue(){let Z=this.options[this.cursor];if(Z!==void 0)if(this.value===void 0&&(this.value=[]),Z.group===!0){let J=Z.value,Q=this.getGroupItems(J);this.isGroupSelected(J)?this.value=this.value.filter((z)=>Q.findIndex((Y)=>Y.value===z)===-1):this.value=[...this.value,...Q.map((z)=>z.value)],this.value=Array.from(new Set(this.value))}else{let J=this.value.includes(Z.value);this.value=J?this.value.filter((Q)=>Q!==Z.value):[...this.value,Z.value]}}constructor(Z){super(Z,!1);let{options:J}=Z;this.#$=Z.selectableGroups!==!1,this.options=Object.entries(J).flatMap(([Q,z])=>[{value:Q,group:!0,label:Q},...z.map((Y)=>({...Y,group:Q}))]),this.value=[...Z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Q})=>Q===Z.cursorAt),this.#$?0:1),this.on("cursor",(Q)=>{switch(Q){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let z=this.options[this.cursor]?.group===!0;!this.#$&&z&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let z=this.options[this.cursor]?.group===!0;!this.#$&&z&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},Y8=new Set(["up","down","left","right"]);class n2 extends P0{#$=!1;#J;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let $=this.userInput;if(this.cursor>=$.length)return`${$}█`;let Z=$.slice(0,this.cursor),J=$.slice(this.cursor,this.cursor+1),Q=$.slice(this.cursor+1);return J===`
|
|
35
|
+
`?`${Z}█
|
|
36
|
+
${Q}`:`${Z}${h1("inverse",J)}${Q}`}get cursor(){return this._cursor}#Z($){if(this.userInput.length===0){this._setUserInput($);return}this._setUserInput(this.userInput.slice(0,this.cursor)+$+this.userInput.slice(this.cursor))}#Y($){let Z=this.value??"";switch($){case"up":this._cursor=w1(this._cursor,0,-1,Z);return;case"down":this._cursor=w1(this._cursor,0,1,Z);return;case"left":this._cursor=w1(this._cursor,-1,0,Z);return;case"right":this._cursor=w1(this._cursor,1,0,Z);return}}_shouldSubmit($,Z){if(this.#J)return this.focused==="submit"?!0:(this.#Z(`
|
|
37
|
+
`),this._cursor++,!1);let J=this.#$;return this.#$=!0,J&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
|
|
38
|
+
`&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#Z(`
|
|
39
|
+
`),this._cursor++,!1)}constructor($){let Z=$.initialUserInput??$.initialValue;super({...$,initialUserInput:Z},!1),Z!==void 0&&(this._cursor=Z.length),this.#J=$.showSubmit??!1,this.on("key",(J,Q)=>{if(Q?.name&&Y8.has(Q.name)){this.#$=!1,this.#Y(Q.name);return}if(J==="\t"&&this.#J){this.focused=this.focused==="editor"?"submit":"editor";return}if(Q?.name!=="return"){if(this.#$=!1,Q?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(Q?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}J&&(this.#J&&this.focused==="submit"&&(this.focused="editor"),this.#Z(J??""),this._cursor++)}}),this.on("userInput",(J)=>{this._setValue(J)}),this.on("finalize",()=>{this.value||(this.value=$.defaultValue),this.value===void 0&&(this.value="")})}}class r3 extends P0{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter(($)=>$.disabled!==!0)}toggleAll(){let $=this._enabledOptions,Z=this.value!==void 0&&this.value.length===$.length;this.value=Z?[]:$.map((J)=>J.value)}toggleInvert(){let $=this.value;if(!$)return;let Z=this._enabledOptions.filter((J)=>!$.includes(J.value));this.value=Z.map((J)=>J.value)}toggleValue(){this.value===void 0&&(this.value=[]);let $=this.value.includes(this._value);this.value=$?this.value.filter((Z)=>Z!==this._value):[...this.value,this._value]}constructor($){super($,!1),this.options=$.options,this.value=[...$.initialValues??[]];let Z=Math.max(this.options.findIndex(({value:J})=>J===$.cursorAt),0);this.cursor=this.options[Z]?.disabled?u0(Z,1,this.options):Z,this.on("key",(J,Q)=>{Q.name==="a"&&this.toggleAll(),Q.name==="i"&&this.toggleInvert()}),this.on("cursor",(J)=>{switch(J){case"left":case"up":this.cursor=u0(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=u0(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}class t3 extends P0{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let $=this.userInput;if(this.cursor>=$.length)return`${this.userInput}█`;let Z=$.slice(0,this.cursor),J=$.slice(this.cursor,this.cursor+1),Q=$.slice(this.cursor+1);return`${Z}${h1("inverse",J)}${Q}`}get cursor(){return this._cursor}constructor($){super({...$,initialUserInput:$.initialUserInput??$.initialValue}),this.on("userInput",(Z)=>{this._setValue(Z)}),this.on("finalize",()=>{this.value||(this.value=$.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as V,stripVTControlCharacters as DJ}from"node:util";import Z0 from"node:process";var Y1=p2(u3(),1);function G8(){if(Z0.platform!=="win32")return Z0.env.TERM!=="linux";return Boolean(Z0.env.CI)||Boolean(Z0.env.WT_SESSION)||Boolean(Z0.env.TERMINUS_SUBLIME)||Z0.env.ConEmuTask==="{cmd::Cmder}"||Z0.env.TERM_PROGRAM==="Terminus-Sublime"||Z0.env.TERM_PROGRAM==="vscode"||Z0.env.TERM==="xterm-256color"||Z0.env.TERM==="alacritty"||Z0.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var e3=G8(),W8=()=>process.env.CI==="true";var g=($,Z)=>e3?$:Z,s2=g("◆","*"),Q9=g("■","x"),z9=g("▲","x"),m1=g("◇","o"),X8=g("┌","T"),f=g("│","|"),C0=g("└","—"),BJ=g("┐","T"),IJ=g("┘","—"),o2=g("●",">"),r2=g("○"," "),K8=g("◻","[•]"),t2=g("◼","[+]"),e2=g("◻","[ ]"),OJ=g("▪","•"),$9=g("─","-"),j8=g("╮","+"),H8=g("├","+"),U8=g("╯","+"),q8=g("╰","+"),PJ=g("╭","+"),V8=g("●","•"),M8=g("◆","*"),D8=g("▲","!"),F8=g("■","x"),$$=($)=>{switch($){case"initial":case"active":return V("cyan",s2);case"cancel":return V("red",Q9);case"error":return V("yellow",z9);case"submit":return V("green",m1);case"validating":return V("dim",s2)}},L8=($)=>{switch($){case"initial":case"active":return V("cyan",f);case"cancel":return V("red",f);case"error":return V("yellow",f);case"submit":return V("green",f)}};function N8($,Z){let J=[`${Z?`${V("cyan",f)} `:""}${$.join(" • ")}`];return Z&&J.push(V("cyan",C0)),J}var Z9=($,Z,J,Q,z,Y=!1)=>{let G=Z,W=0;if(Y)for(let X=Q-1;X>=J;X--){let K=$[X];if(K&&(G-=K.length),W++,G<=z)break}else for(let X=J;X<Q;X++){let K=$[X];if(K&&(G-=K.length),W++,G<=z)break}return{lineCount:G,removals:W}},J9=({cursor:$,options:Z,style:J,output:Q=process.stdout,maxItems:z=Number.POSITIVE_INFINITY,columnPadding:Y=0,rowPadding:G=4})=>{let W=J1(Q)-Y,X=s3(Q),K=V("dim","..."),H=Math.max(X-G,0),j=Math.max(Math.min(z,H),5),U=0;$>=j-3&&(U=Math.max(Math.min($-j+3,Z.length-j),0));let M=j<Z.length&&U>0,D=j<Z.length&&U+j<Z.length,B=Math.min(U+j,Z.length),I=[],T=0;M&&T++,D&&T++;let m=U+(M?1:0),p=B-(D?1:0);for(let q=m;q<p;q++){let P=Z[q],O=P?J(P,q===$):"",E=X0(O,W,{hard:!0,trim:!1}).split(`
|
|
40
|
+
`);I.push(E),T+=E.length}if(T>H){let q=0,P=0,O=T,E=$-m,S=H,h=()=>Z9(I,O,0,E,S),w=()=>Z9(I,O,E+1,I.length,S,!0);M?({lineCount:O,removals:q}=h(),O>S&&(D||(S-=1),{lineCount:O,removals:P}=w())):(D||(S-=1),{lineCount:O,removals:P}=w(),O>S&&(S-=1,{lineCount:O,removals:q}=h())),q>0&&(M=!0,I.splice(0,q)),P>0&&(D=!0,I.splice(I.length-P,P))}let F=[];M&&F.push(K);for(let q of I)for(let P of q)F.push(P);return D&&F.push(K),F};var Z$=($)=>{let Z=$.active??"Yes",J=$.inactive??"No";return new o3({active:Z,inactive:J,signal:$.signal,input:$.input,output:$.output,initialValue:$.initialValue??!0,render(){let Q=$.withGuide??d.withGuide,z=`${$$(this.state)} `,Y=Q?`${V("gray",f)} `:"",G=Q1($.output,$.message,Y,z),W=`${Q?`${V("gray",f)}
|
|
41
|
+
`:""}${G}
|
|
42
|
+
`,X=this.value?Z:J;switch(this.state){case"submit":{let K=Q?`${V("gray",f)} `:"";return`${W}${K}${V("dim",X)}`}case"cancel":{let K=Q?`${V("gray",f)} `:"";return`${W}${K}${V(["strikethrough","dim"],X)}${Q?`
|
|
43
|
+
${V("gray",f)}`:""}`}default:{let K=Q?`${V("cyan",f)} `:"",H=Q?V("cyan",C0):"";return`${W}${K}${this.value?`${V("green",o2)} ${Z}`:`${V("dim",r2)} ${V("dim",Z)}`}${$.vertical?Q?`
|
|
44
|
+
${V("cyan",f)} `:`
|
|
45
|
+
`:` ${V("dim","/")} `}${this.value?`${V("dim",r2)} ${V("dim",J)}`:`${V("green",o2)} ${J}`}
|
|
46
|
+
${H}
|
|
47
|
+
`}}}}).prompt()};var B8=[`${V("dim","↑/↓")} to navigate`,`${V("dim","Space:")} select`,`${V("dim","Enter:")} confirm`],z1=($,Z)=>$.split(`
|
|
48
|
+
`).map((J)=>Z(J)).join(`
|
|
49
|
+
`),Y9=($)=>{let Z=(z,Y)=>{let G=z.label??String(z.value);return Y==="disabled"?`${V("gray",e2)} ${z1(G,(W)=>V(["strikethrough","gray"],W))}${z.hint?` ${V("dim",`(${z.hint??"disabled"})`)}`:""}`:Y==="active"?`${V("cyan",K8)} ${G}${z.hint?` ${V("dim",`(${z.hint})`)}`:""}`:Y==="selected"?`${V("green",t2)} ${z1(G,(W)=>V("dim",W))}${z.hint?` ${V("dim",`(${z.hint})`)}`:""}`:Y==="cancelled"?`${z1(G,(W)=>V(["strikethrough","dim"],W))}`:Y==="active-selected"?`${V("green",t2)} ${G}${z.hint?` ${V("dim",`(${z.hint})`)}`:""}`:Y==="submitted"?`${z1(G,(W)=>V("dim",W))}`:`${V("dim",e2)} ${z1(G,(W)=>V("dim",W))}`},J=$.required??!0,Q=$.showInstructions??!0;return new r3({options:$.options,signal:$.signal,input:$.input,output:$.output,initialValues:$.initialValues,required:J,cursorAt:$.cursorAt,validate(z){if(J&&(z===void 0||z.length===0))return`Please select at least one option.
|
|
50
|
+
${V("reset",V("dim",`Press ${V(["gray","bgWhite","inverse"]," space ")} to select, ${V("gray",V("bgWhite",V("inverse"," enter ")))} to submit`))}`},render(){let z=$.withGuide??d.withGuide,Y=Q1($.output,$.message,z?`${L8(this.state)} `:"",`${$$(this.state)} `),G=`${z?`${V("gray",f)}
|
|
51
|
+
`:""}${Y}
|
|
52
|
+
`,W=this.value??[],X=(K,H)=>{if(K.disabled)return Z(K,"disabled");let j=W.includes(K.value);return H&&j?Z(K,"active-selected"):j?Z(K,"selected"):Z(K,H?"active":"inactive")};switch(this.state){case"submit":{let K=this.options.filter(({value:j})=>W.includes(j)).map((j)=>Z(j,"submitted")).join(V("dim",", "))||V("dim","none"),H=Q1($.output,K,z?`${V("gray",f)} `:"");return`${G}${H}`}case"cancel":{let K=this.options.filter(({value:j})=>W.includes(j)).map((j)=>Z(j,"cancelled")).join(V("dim",", "));if(K.trim()==="")return`${G}${V("gray",f)}`;let H=Q1($.output,K,z?`${V("gray",f)} `:"");return`${G}${H}${z?`
|
|
53
|
+
${V("gray",f)}`:""}`}case"error":{let K=z?`${V("yellow",f)} `:"",H=this.error.split(`
|
|
54
|
+
`).map((M,D)=>D===0?`${z?`${V("yellow",C0)} `:""}${V("yellow",M)}`:` ${M}`).join(`
|
|
55
|
+
`),j=G.split(`
|
|
56
|
+
`).length,U=H.split(`
|
|
57
|
+
`).length+1;return`${G}${K}${J9({output:$.output,options:this.options,cursor:this.cursor,maxItems:$.maxItems,columnPadding:K.length,rowPadding:j+U,style:X}).join(`
|
|
58
|
+
${K}`)}
|
|
59
|
+
${H}
|
|
60
|
+
`}default:{let K=z?`${V("cyan",f)} `:"",H=G.split(`
|
|
61
|
+
`).length,j=Q?N8(B8,z):z?[V("cyan",C0)]:[],U=j.join(`
|
|
62
|
+
`),M=j.length+1;return`${G}${K}${J9({output:$.output,options:this.options,cursor:this.cursor,maxItems:$.maxItems,columnPadding:K.length,rowPadding:H+M,style:X}).join(`
|
|
63
|
+
${K}`)}
|
|
64
|
+
${U}
|
|
65
|
+
`}}}}).prompt()};var y={message:($=[],{symbol:Z=V("gray",f),secondarySymbol:J=V("gray",f),output:Q=process.stdout,spacing:z=1,withGuide:Y}={})=>{let G=[],W=Y??d.withGuide,X=W?J:"",K=W?`${Z} `:"",H=W?`${J} `:"";for(let U=0;U<z;U++)G.push(X);let j=Array.isArray($)?$:$.split(`
|
|
66
|
+
`);if(j.length>0){let[U,...M]=j;U.length>0?G.push(`${K}${U}`):G.push(W?Z:"");for(let D of M)D.length>0?G.push(`${H}${D}`):G.push(W?J:"")}Q.write(`${G.join(`
|
|
67
|
+
`)}
|
|
68
|
+
`)},info:($,Z)=>{y.message($,{...Z,symbol:V("blue",V8)})},success:($,Z)=>{y.message($,{...Z,symbol:V("green",M8)})},step:($,Z)=>{y.message($,{...Z,symbol:V("green",m1)})},warn:($,Z)=>{y.message($,{...Z,symbol:V("yellow",D8)})},warning:($,Z)=>{y.warn($,Z)},error:($,Z)=>{y.message($,{...Z,symbol:V("red",F8)})}};var G9=($="",Z)=>{let J=Z?.output??process.stdout,Q=Z?.withGuide??d.withGuide?`${V("gray",X8)} `:"";J.write(`${Q}${$}
|
|
69
|
+
`)},K0=($="",Z)=>{let J=Z?.output??process.stdout,Q=Z?.withGuide??d.withGuide?`${V("gray",f)}
|
|
70
|
+
${V("gray",C0)} `:"";J.write(`${Q}${$}
|
|
71
|
+
|
|
72
|
+
`)};var I8=($)=>$,O8=($,Z,J)=>{let Q={hard:!0,trim:!1},z=X0($,Z,Q).split(`
|
|
73
|
+
`),Y=z.reduce((X,K)=>Math.max(s(K),X),0),G=z.map(J).reduce((X,K)=>Math.max(s(K),X),0),W=Z-(G-Y);return X0($,W,Q)},v1=($="",Z="",J)=>{let Q=J?.output??Z0.stdout,z=J?.withGuide??d.withGuide,Y=J?.format??I8,G=["",...O8($,J1(Q)-6,Y).split(`
|
|
74
|
+
`).map(Y),""],W=s(Z),X=Math.max(G.reduce((U,M)=>{let D=s(M);return D>U?D:U},0),W)+2,K=G.map((U)=>`${V("gray",f)} ${U}${" ".repeat(X-s(U))}${V("gray",f)}`).join(`
|
|
75
|
+
`),H=z?`${V("gray",f)}
|
|
76
|
+
`:"",j=z?H8:q8;Q.write(`${H}${V("green",m1)} ${V("reset",Z)} ${V("gray",$9.repeat(Math.max(X-W-1,1))+j8)}
|
|
77
|
+
${K}
|
|
78
|
+
${V("gray",j+$9.repeat(X+2)+U8)}
|
|
79
|
+
`)};var P8=($)=>V("magenta",$),W9=({indicator:$="dots",onCancel:Z,output:J=process.stdout,cancelMessage:Q,errorMessage:z,frames:Y=e3?["◒","◐","◓","◑"]:["•","o","O","0"],delay:G=e3?80:120,signal:W,...X}={})=>{let K=W8(),H,j,U=!1,M=!1,D="",B,I=performance.now(),T=J1(J),m=X?.styleFrame??P8,p=(b)=>{let c=b>1?z??d.messages.error:Q??d.messages.cancel;M=b===1,U&&(_(c,b),M&&typeof Z=="function"&&Z())},F=()=>p(2),q=()=>p(1),P=()=>{process.on("uncaughtExceptionMonitor",F),process.on("unhandledRejection",F),process.on("SIGINT",q),process.on("SIGTERM",q),process.on("exit",p),W&&W.addEventListener("abort",q)},O=()=>{process.removeListener("uncaughtExceptionMonitor",F),process.removeListener("unhandledRejection",F),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q),process.removeListener("exit",p),W&&W.removeEventListener("abort",q)},E=()=>{if(B===void 0)return;K&&J.write(`
|
|
80
|
+
`);let b=X0(B,T,{hard:!0,trim:!1}).split(`
|
|
81
|
+
`);b.length>1&&J.write(Y1.cursor.up(b.length-1)),J.write(Y1.cursor.to(0)),J.write(Y1.erase.down())},S=(b)=>b.replace(/\.+$/,""),h=(b)=>{let c=(performance.now()-b)/1000,o=Math.floor(c/60),i=Math.floor(c%60);return o>0?`[${o}m ${i}s]`:`[${i}s]`},w=X.withGuide??d.withGuide,k=(b="")=>{U=!0,H=u2({output:J}),D=S(b),I=performance.now(),w&&J.write(`${V("gray",f)}
|
|
82
|
+
`);let c=0,o=0;P(),j=setInterval(()=>{if(K&&D===B)return;E(),B=D;let i=m(Y[c]),j0;if(K)j0=`${i} ${D}...`;else if($==="timer")j0=`${i} ${D} ${h(I)}`;else{let J0=".".repeat(Math.floor(o)).slice(0,3);j0=`${i} ${D}${J0}`}let x=X0(j0,T,{hard:!0,trim:!1});J.write(x),c=c+1<Y.length?c+1:0,o=o<4?o+0.125:0},G)},_=(b="",c=0,o=!1)=>{if(!U)return;U=!1,clearInterval(j),E();let i=c===0?V("green",m1):c===1?V("red",Q9):V("red",z9);D=b??D,o||($==="timer"?J.write(`${i} ${D} ${h(I)}
|
|
83
|
+
`):J.write(`${i} ${D}
|
|
84
|
+
`)),O(),H()};return{start:k,stop:(b="")=>_(b,0),message:(b="")=>{D=S(b??D)},cancel:(b="")=>_(b,1),error:(b="")=>_(b,2),clear:()=>_("",0,!0),get isCancelled(){return M}}},CJ={light:g("─","-"),heavy:g("━","="),block:g("█","#")};var RJ=[`${V("dim","↑/↓")} to navigate`,`${V("dim","Enter:")} confirm`];var bJ=`${V("gray",f)} `;var X9=($)=>new t3({validate:$.validate,placeholder:$.placeholder,defaultValue:$.defaultValue,initialValue:$.initialValue,output:$.output,signal:$.signal,input:$.input,render(){let Z=$?.withGuide??d.withGuide,J=`${`${Z?`${V("gray",f)}
|
|
85
|
+
`:""}${$$(this.state)} `}${$.message}
|
|
86
|
+
`,Q=$.placeholder&&$.placeholder.length>0?V("inverse",$.placeholder[0])+V("dim",$.placeholder.slice(1)):V(["inverse","hidden"],"_"),z=this.userInput?this.userInputWithCursor:Q,Y=this.value??"";switch(this.state){case"validating":{let G=Z?`${V("cyan",f)} `:"",W=Z?V("cyan",C0):"",X=V("dim",z),K=V("dim","Validating...");return`${J}${G}${X}
|
|
87
|
+
${W} ${K}
|
|
88
|
+
`}case"error":{let G=this.error?` ${V("yellow",this.error)}`:"",W=Z?`${V("yellow",f)} `:"",X=Z?V("yellow",C0):"";return`${J.trim()}
|
|
89
|
+
${W}${z}
|
|
90
|
+
${X}${G}
|
|
91
|
+
`}case"submit":{let G=Y?`${Z?" ":""}${V("dim",Y)}`:"",W=Z?V("gray",f):"";return`${J}${W}${G}`}case"cancel":{let G=Y?` ${V(["strikethrough","dim"],Y)}`:"",W=Z?V("gray",f):"";return`${J}${W}${G}${Y.trim()?`
|
|
92
|
+
${W}`:""}`}default:{let G=Z?`${V("cyan",f)} `:"",W=Z?V("cyan",C0):"";return`${J}${G}${z}
|
|
93
|
+
${W}
|
|
94
|
+
`}}}}).prompt();import{existsSync as l1}from"node:fs";import{join as i0}from"node:path";import{accessSync as C8,constants as K9,statSync as R8}from"node:fs";import{delimiter as b8,extname as A8,resolve as k8}from"node:path";function G1($,Z,J){let Q=J==="win32",z=Q?[`${$}.exe`,`${$}.cmd`,`${$}.bat`,$]:[$];for(let Y of(Z.PATH??"").split(Q?";":b8)){if(!Y)continue;for(let G of z){let W=k8(Y,G);try{if(C8(W,Q?K9.F_OK:K9.X_OK),R8(W).isFile())return W}catch{}}}return null}async function c1($,Z,J,Q){if(!$)return null;let z=A8($).toLowerCase(),Y=Q==="win32"&&(z===".cmd"||z===".bat");try{return await J.run(Y?Z.ComSpec||Z.COMSPEC||"cmd.exe":$,Y?["/d","/s","/c",$,"--version"]:["--version"],{env:Z})}catch{return null}}import{existsSync as _8,readFileSync as f8}from"node:fs";import{applyEdits as j9,format as E8,modify as J$,parse as H9}from"jsonc-parser";function W1($){if(!_8($))return{value:null,text:"",exists:!1};let Z=f8($,"utf8"),J=[],Q=H9(Z,J,{allowTrailingComma:!0});return{value:J.length===0?Q:null,text:Z,exists:!0}}function Q$($,Z,J,Q){let Y=H9($,[],{allowTrailingComma:!0})??{};for(let j of Z)if(typeof Y==="object"&&Y!==null)Y=Y[j];else{Y=void 0;break}let G=Array.isArray(Y)?Y:[],W=G.findIndex((j)=>typeof j==="string"&&Q(j));if(W!==-1&&G[W]===J)return{text:$,changed:!1};let X;if(W!==-1)X=J$($,[...Z,W],J,{formattingOptions:{insertSpaces:!0,tabSize:2}});else if(!Array.isArray(Y))X=J$($,Z,[J],{formattingOptions:{insertSpaces:!0,tabSize:2}});else X=J$($,[...Z,G.length],J,{formattingOptions:{insertSpaces:!0,tabSize:2}});let K=j9($,X);return{text:j9(K,E8(K,void 0,{insertSpaces:!0,tabSize:2})),changed:!0}}import{existsSync as p1}from"node:fs";import{mkdir as V9,writeFile as d1}from"node:fs/promises";import{join as u1}from"node:path";function M9($){return $===l0||$.startsWith(`${l0}@`)}function z$($){let Z=u1($,"opencode.jsonc");if(p1(Z))return{path:Z,exists:!0};let J=u1($,"opencode.json");if(p1(J))return{path:J,exists:!0};return{path:Z,exists:!1}}function S8($){let Z=u1($,"tui.jsonc");if(p1(Z))return{path:Z,exists:!0};let J=u1($,"tui.json");if(p1(J))return{path:J,exists:!0};return{path:Z,exists:!1}}async function D9($,Z=process.env){let J=E0(Z);await V9(J,{recursive:!0});let{path:Q,exists:z}=z$(J),Y=U9($);if(!z){let K=`{
|
|
72
95
|
"$schema": "https://opencode.ai/config.json",
|
|
73
96
|
"plugin": [
|
|
74
|
-
"${
|
|
97
|
+
"${Y}"
|
|
75
98
|
]
|
|
76
99
|
}
|
|
77
|
-
`;return await
|
|
100
|
+
`;return await d1(Q,K,"utf8"),{configPath:Q,changed:!0,created:!0}}let{text:G}=W1(Q),{text:W,changed:X}=Q$(G,["plugin"],Y,M9);if(X)await d1(Q,W,"utf8");return{configPath:Q,changed:X,created:!1}}async function F9($,Z=process.env){let J=E0(Z);await V9(J,{recursive:!0});let{path:Q,exists:z}=S8(J),Y=q9($);if(!z){let K=`{
|
|
78
101
|
"plugin": [
|
|
79
|
-
"${
|
|
102
|
+
"${Y}"
|
|
80
103
|
]
|
|
81
104
|
}
|
|
82
|
-
`;return await N0(J,Y,"utf8"),{configPath:J,changed:!0,created:!0}}let{text:Q}=Y0(J),{text:Z,changed:z}=n0(Q,["plugin"],W,fF);if(z)await N0(J,Z,"utf8");return{configPath:J,changed:z,created:!1}}import{existsSync as s0}from"node:fs";import{readFile as jF,writeFile as T3}from"node:fs/promises";import{join as i3}from"node:path";function WF(F=process.env){let f=i3(n(F),"settings.json");if(!s0(f))return!1;try{let J=JSON.parse(l3(f))?.packages;if(!Array.isArray(J))return!1;return J.some((j)=>{let W=typeof j==="string"?j:typeof j==="object"&&j!==null?j.source:"";if(typeof W!=="string")return!1;return W===t||W.startsWith(`${t}@`)||W===`npm:${t}`||W.startsWith(`npm:${t}@`)})}catch{return!1}}function l3(F){return z0("node:fs").readFileSync(F,"utf8")}async function ZF(F=process.env){let f=i0(F);if(!s0(f))return!1;try{let $=await jF(f,"utf8"),J=JSON.parse($);return Boolean(J?.anthropic&&typeof J.anthropic==="object")}catch{return!1}}async function QF(F=process.env){let f=i0(F);if(!s0(f))return!1;try{let $=await jF(f,"utf8"),J=JSON.parse($);if(J?.anthropic)return delete J.anthropic,await T3(f,`${JSON.stringify(J,null,2)}
|
|
83
|
-
|
|
84
|
-
`),"Next Steps"),y("Setup complete!"),0}function Ff(){return{version:1,main:{type:"opencode",provider:"anthropic"},fallbackOn:[401,403,429],refresh:{enabled:!0,intervalMinutes:10,refreshBeforeExpiryMinutes:240},quota:{enabled:!0,checkIntervalMinutes:5,minimumRemaining:{five_hour:10,seven_day:20},failClosedOnUnknownQuota:!0},accounts:[]}}function XF(){console.log(`Usage:
|
|
105
|
+
`;return await d1(Q,K,"utf8"),{configPath:Q,changed:!0,created:!0}}let{text:G}=W1(Q),{text:W,changed:X}=Q$(G,["plugin"],Y,M9);if(X)await d1(Q,W,"utf8");return{configPath:Q,changed:X,created:!1}}import{existsSync as N9}from"node:fs";import{readFile as x8,writeFile as dJ}from"node:fs/promises";import{join as w8}from"node:path";function B9($=process.env,Z=v0($)){let J=w8(Z,"settings.json");if(!N9(J))return!1;try{let z=JSON.parse(T8(J))?.packages;if(!Array.isArray(z))return!1;return z.some((Y)=>{let G=typeof Y==="string"?Y:typeof Y==="object"&&Y!==null?Y.source:"";if(typeof G!=="string")return!1;return G===X1||G.startsWith(`${X1}@`)||G===`npm:${X1}`||G.startsWith(`npm:${X1}@`)})}catch{return!1}}function T8($){return j1("node:fs").readFileSync($,"utf8")}async function I9($=process.env){let Z=k1($);if(!N9(Z))return!1;try{let J=await x8(Z,"utf8"),Q=JSON.parse(J);return Boolean(Q?.anthropic&&typeof Q.anthropic==="object")}catch{return!1}}async function O9($,Z=e,J=process.env){let Q=L9($),z=await Z.run("pi",["install",Q],{env:J});if(z.exitCode!==0)return{ok:!1,exitCode:z.exitCode,stderr:z.stderr};return{ok:!0,message:`Installed ${Q}`}}function g8($,Z){let J=C9($,Z),Q;switch(Z){case"darwin":Q=["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",i0(J,"Applications","OpenCode.app"),i0(J,"Applications","OpenCode Beta.app")];break;case"win32":{let z=$.LOCALAPPDATA??i0(J,"AppData","Local");Q=[i0(z,"Programs","opencode"),i0(z,"opencode")];break}case"linux":Q=["/opt/OpenCode","/usr/lib/opencode",i0(J,".local","share","applications","opencode.desktop")];break;default:Q=[]}return Q.some((z)=>l1(z))}async function h8($=process.env,Z=e,J={}){let Q=J.platform??process.platform,z=E0($,Q),Y=l1(z)||g8($,Q),G=G1("opencode",$,Q)??G1("opencode2",$,Q),W=Y||G!==null,X=await c1(G,$,Z,Q),K=X?.exitCode===0?X.stdout.trim()||null:null,{path:H,exists:j}=z$(z),U=!1;if(j){let{value:M}=W1(H);if(Array.isArray(M?.plugin))U=M.plugin.some((D)=>typeof D==="string"&&(D===l0||D.startsWith(`${l0}@`)))}return{kind:"opencode",installed:W,version:K,configPath:H,pluginInstalled:U}}async function y8($=process.env,Z=e,J={}){let Q=J.platform??process.platform,z=v0($,Q),Y=l1(z),G=G1("pi",$,Q),W=Y||G!==null,X=await c1(G,$,Z,Q),K=null;if(X?.exitCode===0){let U=X.stdout.trim()||X.stderr.trim();K=U.split(/\r?\n/).find((D)=>/^\d+\.\d+\.\d+/.test(D.trim()))?.trim()||U||null}let H=B9($,z),j=await I9($);return{kind:"pi",installed:W,version:K,configPath:z,pluginInstalled:H,hasLocalAuth:j}}async function m8($=process.env,Z=e,J={}){let Q=J.platform??process.platform,z=G1("ck",$,Q),Y=z!==null,G=await c1(z,$,Z,Q),W=G?.exitCode===0?G.stdout.trim()||null:null,X=null,K=!1;try{if(X=R1(void 0,$),X&&l1(X)){let H=await P9({connectionFile:X,handshakeTimeoutMs:2000});K=!0,H.close()}}catch{K=!1}return{ckInstalled:Y,ckVersion:W,daemonRunning:K,connectionPath:X}}async function R9($=process.env,Z=e,J={}){let[Q,z,Y]=await Promise.all([h8($,Z,J),y8($,Z,J),m8($,Z,J)]);return{opencode:Q,pi:z,claustrum:Y}}async function A9($,Z){let J={...Z.env},Q=async()=>{if(f1(J),await p0(Z.fence),await N0($,J)!=="local")throw Error("Disconnect from the vault first.")};await Q();let z=Z.paths??await c0($,J),Y=await Z.login?.($);if(Y&&!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(Y.accountIdentity))throw Error("Claude sign-in did not establish an account UUID");if(await Q(),await b9({paths:z.paths,legacyConfigPath:z.legacyConfigPath,legacyStatePath:z.legacyStatePath,host:$,hostAuthPath:z.hostAuthPath,routingSourcePath:z.routingSourcePath,routingDestinationPath:z.routingDestinationPath,env:J,processFence:Q,removePiAnthropicAuth:Z.removePiAnthropicAuth}),Y){let G=d0({paths:z.paths,host:$,vault:{env:J},beforePoolWrite:Q});try{if((await G.read()).mode!=="local")throw Error("Disconnect from the vault first.");await Q(),await G.loginOAuth({routeId:"main",replace:!0,...Y})}finally{G.close()}}}async function _9($){let Z=await i1("max");v1(Z.url,`Claude sign-in for ${$==="pi"?"Pi":"OpenCode"}`);let J=await X9({message:"Paste the Claude callback URL or authorization code:"});if(O0(J))throw Error("Claude sign-in cancelled");let Q=await a1(J,Z.verifier,Z.redirectUri,Z.state);if(Q.type!=="success")throw Error("Claude sign-in failed");let z=await k9(Q.access,void 0,void 0);if(!z.accountUuid)throw Error("Claude sign-in did not establish an account UUID");return{accountIdentity:z.accountUuid,credential:{type:"oauth",access:Q.access,refresh:Q.refresh,expires:Q.expires}}}async function E9($=[],Z={}){let J=Z.env??process.env,Q=Z.runner??e,z=Z.fence??w3,Y=Z.activate??H2,G=Z.migrateLocal??A9,W={output:Z.output},X=$.includes("--yes")||$.includes("-y"),K=$.includes("--dry-run"),H=$.includes("--no-claustrum"),j=$.includes("--claustrum"),U=$.includes("--remove-pi-auth"),M=$.includes("--login"),D=M?Z.localLogin??_9:void 0;if(M&&j)return y.error("Local sign-in and vault setup are two separate choices. Use --login or --claustrum, not both.",W),1;G9("CortexKit Anthropic Auth Setup",W);let B=W9(W);B.start("Detecting installed environments…");let I=await(Z.detect??R9)(J,Q);B.stop("Environment detection complete.");let T=I.opencode.installed?`detected (${I.opencode.version??"version unknown"}, ${I.opencode.pluginInstalled?"plugin already configured":"plugin not configured"})`:"not found",m=I.pi.installed?`detected (${I.pi.version??"version unknown"}, ${I.pi.pluginInstalled?"extension already installed":"extension not installed"})`:"not found",p=I.claustrum.daemonRunning?`daemon running (${I.claustrum.ckVersion??"ck ready"})`:I.claustrum.ckInstalled?"ck installed, daemon not running":"not installed";if(y.info(`OpenCode: ${T}`,W),y.info(`Pi: ${m}`,W),y.info(`Claustrum: ${p}`,W),!I.opencode.installed&&!I.pi.installed)return y.error("Neither OpenCode nor Pi was detected on this system.",W),K0("Install OpenCode (https://opencode.ai) or Pi (https://github.com/badlogic/pi-mono) first.",W),1;let F=[];if(X){if(I.opencode.installed)F.push("opencode");if(I.pi.installed)F.push("pi")}else{let k=[];if(I.opencode.installed)k.push({value:"opencode",label:"OpenCode",hint:I.opencode.pluginInstalled?"already configured":"configure plugin + TUI sidebar"});if(I.pi.installed)k.push({value:"pi",label:"Pi",hint:I.pi.pluginInstalled?"already installed":"install provider extension"});let _=await Y9({message:"Select integrations to configure:",options:k,initialValues:k.map((b)=>b.value),required:!0,...W});if(O0(_))return K0("Setup cancelled.",W),0;F=_}if(F.length===0)return K0("No integrations selected.",W),0;let q=!1;if(I.claustrum.daemonRunning&&I.claustrum.ckInstalled&&!H){if(j)q=!0;else if(!X){let k=await Z$({message:"Use Claude accounts from the Claustrum vault? Local account files stay unchanged and are not used while connected.",initialValue:!1,...W});if(O0(k))return K0("Setup cancelled.",W),0;q=k}}if(D&&q)return y.error("Local sign-in and vault setup are two separate choices. Use --login or --claustrum, not both.",W),1;if(D||!q){for(let k of F)if(await N0(k,J)!=="local")return y.error("Disconnect from the vault first.",W),1}let O=!1;if(F.includes("pi")&&I.pi.hasLocalAuth)if(X){if(!U)return y.error(q?"Pi has stored Anthropic authentication. Rerun with --remove-pi-auth to preserve it privately during vault use and restore it on disconnect.":"Pi has a stored Anthropic login. Rerun with --remove-pi-auth to move it into the native account pool.",W),K0("Setup aborted.",W),1;O=!0}else{y.warn(q?"Pi has stored Anthropic authentication. Vault setup must preserve it privately and restore it on disconnect.":"Pi has a stored Anthropic OAuth token. Native account-pool setup moves credentials out of the host auth store.",W);let k=await Z$({message:q?"Move Pi authentication aside privately for vault use, then restore it on disconnect?":"Move the Pi Anthropic OAuth login into the native account pool and remove its stored copy?",initialValue:!1,...W});if(O0(k)||!k)return y.error("Native account-pool setup cannot finish while the stored Pi OAuth token takes precedence.",W),K0("Setup aborted.",W),1;O=!0}try{await p0(z)}catch(k){return y.error(await B0("setup-process-check",k,J),W),K0("Setup aborted — quit active hosts and rerun setup.",W),1}let E=[];for(let k of F)E.push(await c0(k,J));if(await W2(E),K){if(y.info("[dry-run] Planned actions:",W),y.info(` - Target integrations: ${F.join(", ")}`,W),y.info(` - Claustrum custody: ${q?"enabled":"disabled"}`,W),O)y.info(" - Pi local OAuth token will be removed",W);return K0("Dry run complete. No changes were made.",W),0}let S=await f9(),h=async(k,_)=>{B.start(`Switching ${_} to Claustrum vault custody…`);try{let b=await Y(k,{env:J,runner:Q,fence:z,removePiAnthropicAuth:k==="pi"&&O});return B.stop(b==="already-vault"?`${_} already uses Claustrum vault custody.`:`${_} now uses Claustrum vault custody.`),!0}catch(b){return B.stop(`${_} vault custody setup failed.`),y.error(await B0("setup-activation",b,J),W),!1}};if(F.includes("opencode")){B.start("Configuring OpenCode plugin and TUI sidebar…");try{await D9(S,J),await F9(S,J),B.stop("OpenCode configuration updated.")}catch(k){return B.stop("OpenCode setup failed."),y.error(await B0("setup-opencode-config",k,J),W),1}if(D||!q)await G("opencode",{env:J,fence:z,removePiAnthropicAuth:!1,login:D});if(q&&!await h("opencode","OpenCode"))return 1}if(F.includes("pi")){B.start("Installing Pi Anthropic extension…");try{let k=await O9(S,Q,J);if(!k.ok)return B.stop("Pi extension installation failed."),y.error(await P2("setup-pi-install",k,J),W),1;B.stop("Pi Anthropic extension installed.")}catch(k){return B.stop("Pi setup failed."),y.error(await B0("setup-pi",k,J),W),1}if(D||!q)await G("pi",{env:J,fence:z,removePiAnthropicAuth:O,login:D});if(q&&!await h("pi","Pi"))return 1}let w=[];if(F.includes("opencode"))w.push("• Start OpenCode normally (opencode).");if(F.includes("pi"))w.push("• Start Pi normally (pi).");if(q)w.push("• Manage accounts in Claustrum with: ck auth login --provider anthropic"),w.push(" Newly added accounts will be discovered automatically without restarting.");return v1(w.join(`
|
|
106
|
+
`),"Next Steps",W),K0("Setup complete!",W),0}async function a0($){if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Native account changes require offline setup without OPENCODE_AUTH_CONTENT");let Z=await A1(),J=d0({paths:Z,host:"opencode"});try{return await J.read(),await $(J)}finally{J.close()}}async function n1(){if(await N0("opencode",process.env)!=="local")throw Error("Disconnect from the vault first.")}function S9(){console.log(`Usage:
|
|
85
107
|
opencode-anthropic-auth setup [--yes] [--dry-run]
|
|
86
108
|
opencode-anthropic-auth login [label]
|
|
87
109
|
opencode-anthropic-auth api add [label]
|
|
88
110
|
opencode-anthropic-auth list
|
|
89
111
|
opencode-anthropic-auth relay setup
|
|
90
112
|
|
|
91
|
-
|
|
92
|
-
|
|
113
|
+
Native credentials are managed by the offline setup migration.
|
|
114
|
+
Legacy import source:
|
|
115
|
+
${w9()}`)}function Y$($,Z){let J=$?.trim();if(!J)throw Error(`${Z} is required`);return J}async function r1($){let J=await($.fetchImpl??fetch)(`https://api.cloudflare.com/client/v4${$.path}`,{method:$.method,headers:{authorization:`Bearer ${$.token}`,...$.body instanceof FormData?{}:{"content-type":"application/json"},...$.headers},body:$.body}),Q=await J.text(),z;try{z=JSON.parse(Q)}catch{throw Error(`Cloudflare API returned ${J.status}: ${Q}`)}if(!J.ok||z.success===!1){let Y=z.errors?.map((G)=>G.message).filter(Boolean).join("; ");throw Error(Y||`Cloudflare API returned ${J.status}`)}return z.result}async function d8($,Z,J,Q){return r1({token:$,method:"POST",path:`/accounts/${Z}/storage/kv/namespaces`,body:JSON.stringify({title:J}),fetchImpl:Q})}async function u8($){let Z={main_module:"worker.js",compatibility_date:"2026-04-28",bindings:[{type:"kv_namespace",name:"RELAY_STATE",namespace_id:$.kvNamespaceId},{type:"secret_text",name:"RELAY_TOKEN",text:$.relayToken}]},J=new FormData;return J.set("metadata",JSON.stringify(Z)),J.set("worker.js",new Blob([h9],{type:"application/javascript+module"}),"worker.js"),r1({token:$.token,method:"PUT",path:`/accounts/${$.accountId}/workers/scripts/${$.scriptName}`,body:J,fetchImpl:$.fetchImpl})}async function l8($,Z,J,Q){await r1({token:$,method:"POST",path:`/accounts/${Z}/workers/scripts/${J}/subdomain`,body:JSON.stringify({enabled:!0,previews_enabled:!1}),fetchImpl:Q})}async function i8($,Z,J){return r1({token:$,method:"GET",path:`/accounts/${Z}/workers/subdomain`,fetchImpl:J}).catch(()=>null)}async function a8($={}){await a0((M)=>M.read());let Z=$.fetchImpl??fetch,J=$.prompt??o1,Q=$.warn??((M)=>console.warn(M)),z=Y$(process.env.CLOUDFLARE_API_TOKEN?.trim()||await J("Cloudflare API token: "),"Cloudflare API token");$.secrets?.push(z);let Y=Y$(process.env.CLOUDFLARE_ACCOUNT_ID||await J("Cloudflare account ID: "),"Cloudflare account ID"),G=await J("Worker name [opencode-anthropic-relay]: ")||"opencode-anthropic-relay",W=`${G}-state`,X=g9();$.secrets?.push(X),console.log("Creating Cloudflare KV namespace...");let K=await d8(z,Y,W,Z);console.log("Uploading relay Worker..."),await u8({token:z,accountId:Y,scriptName:G,kvNamespaceId:K.id,relayToken:X,fetchImpl:Z}),await l8(z,Y,G,Z).catch(async(M)=>{Q(await B0("cli-relay-workers-dev",M,process.env,[z,X]))});let H=await i8(z,Y,Z),U=(H?.subdomain?`https://${G}.${H.subdomain}.workers.dev`:"")||Y$(await o1("Relay Worker URL: "),"Relay Worker URL");await a0((M)=>M.updateRelay({enabled:!0,url:U,token:X,fallbackToDirect:!0,transport:"http"})),console.log(`Relay enabled at ${U}`),console.log("Relay settings saved to the native account store.")}var s1=null;async function o1($){return s1??=p8({input:v8,output:c8}),(await s1.question($)).trim()}function n8(){s1?.close(),s1=null}async function s8($,Z={}){if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Local login cannot be verified while OPENCODE_AUTH_CONTENT is set");let J=Z.prompt??o1,Q=Z.authorize??i1,z=Z.exchange??a1;await n1(),await a0(async(Y)=>{let G=await Y.read(),W=$?.trim()||await J("Fallback account label (optional): "),X=await Q("max");console.log(`
|
|
93
116
|
Open this URL in your browser and complete Claude sign-in:
|
|
94
|
-
`),console.log(`${
|
|
95
|
-
`);let
|
|
96
|
-
Saved fallback account${W?` "${W}"`:""}.`)}async function
|
|
97
|
-
Saved API fallback route${
|
|
117
|
+
`),console.log(`${X.url}
|
|
118
|
+
`);let K=await J("Paste the full callback URL or authorization code here: ");Z.secrets?.push(K);let H=await z(K,X.verifier,X.redirectUri,X.state);if(H.type==="failed")throw Error("Authentication failed");if(Z.secrets?.push(H.access,H.refresh),process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Local login cannot be verified while OPENCODE_AUTH_CONTENT is set");await n1();let j=W&&W!=="main"?W:crypto.randomUUID(),U=G.accounts.some((M)=>M.id===j&&M.source==="local");await Y.loginOAuth({routeId:j,replace:U,label:W||void 0,credential:{access:H.access,refresh:H.refresh,expires:H.expires}}),console.log(`
|
|
119
|
+
Saved native fallback account${W?` "${W}"`:""}.`)})}async function o8($,Z={}){await n1(),await a0((X)=>X.read());let J=Z.prompt??o1,Q=$?.trim()||await J("API fallback label (optional): "),z=process.env.OPENCODE_ANTHROPIC_AUTH_API_BASE_URL?.trim()||(await J("Anthropic-compatible base URL [https://api.kie.ai/claude]: ")).trim()||"https://api.kie.ai/claude";if(!x9(z))throw Error("API fallback base URL must be an http(s) URL without embedded credentials");let Y=process.env.OPENCODE_ANTHROPIC_AUTH_API_KEY?.trim()||await J("API key: ");if(!Y.trim())throw Error("API key is required");Z.secrets?.push(Y.trim());let W=(process.env.OPENCODE_ANTHROPIC_AUTH_API_AUTH_HEADER?.trim()||await J("Auth header [authorization-bearer|x-api-key] (default authorization-bearer): ")).trim().toLowerCase()==="x-api-key"?"x-api-key":"authorization-bearer";await a0(async(X)=>{await n1();let K=await X.read(),H=Q&&Q!=="main"?Q:crypto.randomUUID(),j=K.accounts.find((U)=>U.id===H);if(j?.source==="vault")throw Error("Vault routes cannot be replaced with a local API key");await X.addApi({routeId:H,replace:Boolean(j),label:Q||void 0,apiKey:Y.trim(),baseURL:z,authHeader:W})}),console.log(`
|
|
120
|
+
Saved API fallback route${Q?` "${Q}"`:""} (${z}).`)}async function r8(){await a0(async($)=>{let Z=(await $.read()).accounts.filter((J)=>J.id!=="main");if(!Z.length){console.log("No native fallback accounts found.");return}for(let[J,Q]of Z.entries()){let z=Q.label||Q.id,Y=Q.enabled?"enabled":"disabled";if(Q.type==="api"){console.log(`${J+1}. ${z} (${Y}) — API route ${Q.baseURL}`);continue}let G=Q.quota?.five_hour?.remainingPercent,W=Q.quota?.seven_day?.remainingPercent,X=G===void 0&&W===void 0?"quota unknown":`5h ${G??"?"}%, 1w ${W??"?"}% remaining`;console.log(`${J+1}. ${z} (${Y}) — ${X}${Q.state?` — ${T9(Q)}`:""}`)}})}async function t8($){let[Z,J,Q]=process.argv.slice(2);if(!Z||Z==="help"||Z==="--help"||Z==="-h"){S9();return}if(Z==="setup"){$.stage="cli-setup";let z=await E9(process.argv.slice(3));if(z!==0)process.exitCode=z;return}if(Z==="login"){$.stage="cli-login",await s8(J,{secrets:$.secrets});return}if(Z==="api"&&J==="add"){$.stage="cli-api-add",await o8(Q,{secrets:$.secrets});return}if(Z==="list"){$.stage="cli-list",await r8();return}if(Z==="relay"&&J==="setup"){$.stage="cli-relay-setup",await a8({secrets:$.secrets});return}S9(),process.exitCode=1}if(j1.main==j1.module){let $={stage:"cli-command",secrets:[]};try{await t8($)}catch(Z){console.error(await B0($.stage,Z,process.env,$.secrets)),process.exitCode=1}finally{n8()}}export{E9 as runSetupCommand,a8 as relaySetup,s8 as login,o8 as addApiRoute};
|