@sourcegraph/amp 0.0.1774876048-g0dfb1c → 0.0.1774880298-g3dd925
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/dist/main.js +9 -9
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -4664,7 +4664,7 @@ function E8({initialBufferLength:J=1024,maxBufferLength:Z=33554432}){if(n9)F9(wJ
|
|
|
4664
4664
|
${F}`);else throw new RZ0(`${Y.statusText} (${Y.status}):
|
|
4665
4665
|
${F}`)}}if(J.skipParseResponse)return;try{let X=new Uint8Array(await Y.arrayBuffer());return jZ0(J.encoding,X,J.responseVersionedDataHandler,J.responseZodSchema,J.responseFromJson,J.responseFromBare)}catch(X){throw new RZ0(`Failed to parse response: ${X}`,{cause:X})}}function Uw4(J){async function Z(Q,Y,X){let K=(X==null?void 0:X.wait)??!1,V=X==null?void 0:X.timeout,z=await jc0({url:`http://actor/queue/${encodeURIComponent(Q)}`,method:"POST",headers:{[Jc0]:J.encoding,...J.params!==void 0?{[MZ0]:JSON.stringify(J.params)}:{}},body:{body:Y,wait:K,timeout:V},encoding:J.encoding,customFetch:J.customFetch,signal:X==null?void 0:X.signal,requestVersion:gA,requestVersionedDataHandler:vN4,responseVersion:gA,responseVersionedDataHandler:yN4,requestZodSchema:hN4,responseZodSchema:gN4,requestToJson:(G)=>({...G,name:Q}),requestToBare:(G)=>({name:G.name??Q,body:vA(D2(G.body)),wait:G.wait??!1,timeout:G.timeout!==void 0?BigInt(G.timeout):null}),responseFromJson:(G)=>{if(G.response===void 0)return{status:G.status};return{status:G.status,response:G.response}},responseFromBare:(G)=>{if(G.response===null||G.response===void 0)return{status:G.status};return{status:G.status,response:LJ(new Uint8Array(G.response))}}});if(K)return z;return}return{send:Z}}async function zr5(J,Z,Q,Y,X){let K,V=X||{};if(typeof Y==="string")K=Y;else if(Y instanceof URL)K=Y.pathname+Y.search;else if(Y instanceof Request){let z=new URL(Y.url);K=z.pathname+z.search;let G=new Headers(Y.headers),F=new Headers((X==null?void 0:X.headers)||{}),q=new Headers(G);if(F.forEach((W,U)=>{q.set(U,W)}),V={method:Y.method,body:Y.body,mode:Y.mode,credentials:Y.credentials,redirect:Y.redirect,referrer:Y.referrer,referrerPolicy:Y.referrerPolicy,integrity:Y.integrity,keepalive:Y.keepalive,signal:Y.signal,...V,headers:q},V.body)V.duplex="half"}else throw TypeError("Invalid input type for fetch");try{let{actorId:z}=await $l(void 0,Z,J);g4().debug({msg:"found actor for raw http",actorId:z}),Rc0.default(z,"Missing actor ID");let G=K.startsWith("/")?K.slice(1):K,F=new URL(`http://actor/request/${G}`),q=new Headers(V.headers);if(Q)q.set(MZ0,JSON.stringify(Q));let W=new Request(F,{...V,headers:q});return J.sendRequest(z,W)}catch(z){let{group:G,code:F,message:q,metadata:W}=rS(z,g4(),{},!0);throw new hY(G,F,q,W)}}async function Gr5(J,Z,Q,Y,X){let{actorId:V}=await $l(void 0,Z,J);g4().debug({msg:"found actor for action",actorId:V}),Rc0.default(V,"Missing actor ID");let z="",G="";if(Y){let W=Y.indexOf("?");if(W!==-1)z=Y.substring(0,W),G=Y.substring(W);else z=Y;if(z.startsWith("/"))z=z.slice(1)}let F=`${ON4}${z}${G}`;return g4().debug({msg:"opening websocket",actorId:V,encoding:"bare",path:F}),await J.openWebSocket(F,V,"bare",Q)}var Fr5=class{#$;#J;#Z;#Q;#Y;#X;#V;constructor(J,Z,Q,Y,X,K){this.#$=J,this.#J=Z,this.#Z=X,this.#Q=K,this.#Y=Q,this.#X=Y,this.#V=Uw4({encoding:this.#Z,params:this.#Y,customFetch:async(V)=>{let z=await iN(this.#Q,this.#J);return await this.#J.sendRequest(z,V)}})}async#W(){if(this.#X)return await this.#X();return this.#Y}send(J,Z,Q){return this.#F(J,Z,Q)}async#F(J,Z,Q){return await Bk(this.#Q,async()=>{return await this.#V.send(J,Z,Q)})}async action(J){if(typeof J==="string"||typeof J!=="object"||J===null||!("name"in J))throw Error(`Invalid action call: expected an options object { name, args }, got ${typeof J}. Use handle.actionName(...args) for the shorthand API.`);let Z;try{return await Bk(this.#Q,async()=>{return Z=await iN(this.#Q,this.#J),g4().debug({msg:"found actor for action",actorId:Z}),qw4.default(Z,"Missing actor ID"),g4().debug({msg:"handling action",name:J.name,encoding:this.#Z}),await jc0({url:`http://actor/action/${encodeURIComponent(J.name)}`,method:"POST",headers:{[Jc0]:this.#Z,...this.#Y!==void 0?{[MZ0]:JSON.stringify(this.#Y)}:{}},body:J.args,encoding:this.#Z,customFetch:this.#J.sendRequest.bind(this.#J,Z),signal:J==null?void 0:J.signal,requestVersion:gA,requestVersionedDataHandler:SN4,responseVersion:gA,responseVersionedDataHandler:kN4,requestZodSchema:uN4,responseZodSchema:bN4,requestToJson:(Q)=>({args:Q}),requestToBare:(Q)=>({args:vA(D2(Q))}),responseFromJson:(Q)=>Q.output,responseFromBare:(Q)=>LJ(new Uint8Array(Q.output))})})}catch(Q){let{group:Y,code:X,message:K,metadata:V}=rS(Q,g4(),{},!0);if(Z&&wc0(Y,X)){let z=await Mc0(Y,X,Z,this.#Q.actorQuery,this.#J);if(z)throw z}throw new hY(Y,X,K,V)}}connect(){g4().debug({msg:"establishing connection from handle",query:this.#Q.actorQuery});let J=new Wr5(this.#$,this.#J,this.#Y,this.#X,this.#Z,this.#Q);return this.#$[Hw4](J)}fetch(J,Z){return this.#D(J,Z)}async#D(J,Z){return await Bk(this.#Q,async()=>{let Q=await iN(this.#Q,this.#J);return await zr5(this.#J,{getForId:{name:Oc0(this.#Q.actorQuery),actorId:Q}},this.#Y,J,Z)})}async webSocket(J,Z){let Q=await this.#W();return await Bk(this.#Q,async()=>{let Y=await iN(this.#Q,this.#J);return await Gr5(this.#J,{getForId:{name:Oc0(this.#Q.actorQuery),actorId:Y}},Q,J,Z)})}async resolve(){return await iN(this.#Q,this.#J)}async getGatewayUrl(){return await Bk(this.#Q,async()=>{let J=await iN(this.#Q,this.#J);return await this.#J.buildGatewayUrl(J)})}},IZ0=Symbol("actorConns"),Hw4=Symbol("createActorConnProxy"),qr5=class{#$=!1;[IZ0]=new Set;#J;#Z;constructor(J,Z){this.#J=J,this.#Z=Z??"bare"}getForId(J,Z,Q){g4().debug({msg:"get handle to actor with id",name:J,actorId:Z,params:Q==null?void 0:Q.params});let Y={getForId:{name:J,actorId:Z}},X=this.#Q(Q==null?void 0:Q.params,Q==null?void 0:Q.getParams,Y);return tc(X)}get(J,Z,Q){let Y=typeof Z==="string"?[Z]:Z||[];g4().debug({msg:"get handle to actor",name:J,key:Y,parameters:Q==null?void 0:Q.params});let X={getForKey:{name:J,key:Y}},K=this.#Q(Q==null?void 0:Q.params,Q==null?void 0:Q.getParams,X);return tc(K)}getOrCreate(J,Z,Q){let Y=typeof Z==="string"?[Z]:Z||[];g4().debug({msg:"get or create handle to actor",name:J,key:Y,parameters:Q==null?void 0:Q.params,createInRegion:Q==null?void 0:Q.createInRegion});let X={getOrCreateForKey:{name:J,key:Y,input:Q==null?void 0:Q.createWithInput,region:Q==null?void 0:Q.createInRegion}},K=this.#Q(Q==null?void 0:Q.params,Q==null?void 0:Q.getParams,X);return tc(K)}async create(J,Z,Q){let Y=typeof Z==="string"?[Z]:Z||[],X={create:{...Q,name:J,key:Y}};g4().debug({msg:"create actor handle",name:J,key:Y,parameters:Q==null?void 0:Q.params,create:X.create});let{actorId:K}=await $l(void 0,X,this.#J);g4().debug({msg:"created actor with ID",name:J,key:Y,actorId:K});let V={getForId:{name:J,actorId:K}},z=this.#Q(Q==null?void 0:Q.params,Q==null?void 0:Q.getParams,V);return tc(z)}#Q(J,Z,Q){return new Fr5(this,this.#J,J,Z,this.#Z,Qr5(Q))}[Hw4](J){return this[IZ0].add(J),J[Bw4](),tc(J)}async dispose(){if(this.#$){g4().warn({msg:"client already disconnected"});return}this.#$=!0,g4().debug({msg:"disposing client"});let J=[];for(let Z of this[IZ0].values())J.push(Z.dispose());await Promise.all(J)}};function Dw4(J,Z={}){let Q=new qr5(J,Z.encoding);return new Proxy(Q,{get:(Y,X,K)=>{if(typeof X==="symbol"||X in Y){let V=Reflect.get(Y,X,K);if(typeof V==="function")return V.bind(Y);return V}if(typeof X==="string")return{get:(V,z)=>{return Y.get(X,V,z)},getOrCreate:(V,z)=>{return Y.getOrCreate(X,V,z)},getForId:(V,z)=>{return Y.getForId(X,V,z)},create:async(V,z={})=>{return await Y.create(X,V,z)}};return}})}function tc(J){let Z=new Map;return new Proxy(J,{get(Q,Y,X){if(typeof Y==="symbol")return Reflect.get(Q,Y,X);if(Y==="constructor"||Y in Q){let K=Reflect.get(Q,Y,Q);if(typeof K==="function")return K.bind(Q);return K}if(typeof Y==="string"){if(Y==="then")return;let K=Z.get(Y);if(!K)K=(...V)=>Q.action({name:Y,args:V}),Z.set(Y,K);return K}},has(Q,Y){if(typeof Y==="string")return!0;return Reflect.has(Q,Y)},getPrototypeOf(Q){return Reflect.getPrototypeOf(Q)},ownKeys(Q){return Reflect.ownKeys(Q)},getOwnPropertyDescriptor(Q,Y){let X=Reflect.getOwnPropertyDescriptor(Q,Y);if(X)return X;if(typeof Y==="string")return{configurable:!0,enumerable:!1,writable:!1,value:(...K)=>Q.action({name:Y,args:K})};return}})}var Bw4=Symbol("connect"),Wr5=class{#$=!1;#J=new AbortController;#Z="idle";#Q;#Y;#X=[];#V=new Map;#W=new Map;#F=new Set;#D=new Set;#U=!1;#G=new Set;#K=new Set;#M=0;#j;#w;#z;#H;#B;#L;#R;#A;#O;#N;constructor(J,Z,Q,Y,X,K){this.#B=J,this.#L=Z,this.#R=Q,this.#A=Y,this.#O=X,this.#N=K,this.#j=Uw4({encoding:this.#O,params:this.#R,customFetch:async(V)=>{let z=await iN(this.#N,this.#L);return this.#Q=z,await this.#L.sendRequest(z,V)}}),this.#w=setInterval(()=>60000)}#S(){this.#Q=void 0,this.#Y=void 0}#E(J,Z){if(!Ec0(J,Z))return!1;return Fw4(this.#N),this.#S(),!0}async#y(J){return await Bk(this.#N,J,()=>this.#S())}#h(J,Z){return Ec0(J,Z)&&this.#z!==void 0&&this.#Z!=="connected"}send(J,Z,Q){return this.#x(J,Z,Q)}async#x(J,Z,Q){return await this.#y(async()=>{return await this.#j.send(J,Z,Q)})}async action(J){if(typeof J==="string"||typeof J!=="object"||J===null||!("name"in J))throw Error(`Invalid action call: expected an options object { name, args }, got ${typeof J}. Use conn.actionName(...args) for the shorthand API.`);g4().debug({msg:"action",name:J.name,args:J.args});let Z=this.#M;this.#M+=1;let{promise:Q,resolve:Y,reject:X}=kA((z)=>g4().warn({msg:"unhandled action promise rejection",reason:z}));this.#V.set(Z,{name:J.name,resolve:Y,reject:X}),g4().debug({msg:"added action to in-flight map",actionId:Z,actionName:J.name,inFlightCount:this.#V.size}),this.#C({body:{tag:"ActionRequest",val:{id:BigInt(Z),name:J.name,args:J.args}}});let{id:K,output:V}=await Q;if(K!==BigInt(Z))throw Error(`Request ID ${Z} does not match response ID ${K}`);return V}[Bw4](){this.#g()}#P(J){let Z=this.#Z;if(Z===J)return;this.#Z=J;for(let Q of[...this.#K])try{Q(J)}catch(Y){g4().error({msg:"error in status change handler",error:k$(Y)})}if(J==="connected")for(let Q of[...this.#D])try{Q()}catch(Y){g4().error({msg:"error in open handler",error:k$(Y)})}if((J==="disconnected"||J==="idle")&&Z==="connected")for(let Q of[...this.#G])try{Q()}catch(Y){g4().error({msg:"error in close handler",error:k$(Y)})}}#g(){this.#P("connecting"),sc(this.#I.bind(this),{forever:!0,minTimeout:250,maxTimeout:30000,onFailedAttempt:(J)=>{g4().warn({msg:"failed to reconnect",attempt:J.attemptNumber,error:k$(J)})},signal:this.#J.signal}).catch((J)=>{if(J.name==="AbortError")g4().info({msg:"connection retry aborted"});else g4().error({msg:"unexpected error in connection retry",error:k$(J)})})}async#I(){try{if(this.#z)throw Error("#onOpenPromise already defined");this.#z=kA((J)=>g4().warn({msg:"unhandled open promise rejection",reason:J})),await this.#m(),await this.#z.promise}finally{this.#z=void 0}}#l(){if(this.#X.length===0)return;g4().debug({msg:"clearing queued connection messages",queueLength:this.#X.length}),this.#X=[]}async#f(){if(!this.#A)return this.#R;try{return await this.#A()}catch(J){let Z=k$(J),Q=new hY("client","get_params_failed",`Failed to resolve connection params: ${Z}`,{error:Z});throw this.#l(),this.#k(Q,!1),this.#b(Q),Q}}async#m(){let J;await this.#y(async()=>{let Z=await this.#f(),Q=await iN(this.#N,this.#L);this.#Q=Q,J=await this.#L.openWebSocket(LN4,Q,this.#O,Z)}),Lc0.default(J,"websocket should have been created"),g4().debug({msg:"opened websocket",connId:this.#Y,readyState:J.readyState,messageQueueLength:this.#X.length}),this.#H=J,J.addEventListener("open",()=>{g4().debug({msg:"client websocket open",connId:this.#Y})}),J.addEventListener("message",async(Z)=>{try{await this.#T(Z.data)}catch(Q){g4().error({msg:"error in websocket message handler",error:k$(Q)})}}),J.addEventListener("close",async(Z)=>{try{await this.#_(Z)}catch(Q){g4().error({msg:"error in websocket close handler",error:k$(Q)})}}),J.addEventListener("error",()=>{try{this.#p()}catch(Z){g4().error({msg:"error in websocket error handler",error:k$(Z)})}})}#d(){if(this.#$){if(g4().debug({msg:"handleOnOpen called after dispose, closing websocket"}),this.#H)this.#H.close(1000,"Disposed"),this.#H=void 0;return}if(this.#Z==="connected"||this.#U)return;this.#U=!0,queueMicrotask(()=>{if(this.#U=!1,this.#$){if(g4().debug({msg:"handleOnOpen scheduled after dispose, closing websocket"}),this.#H)this.#H.close(1000,"Disposed"),this.#H=void 0;return}if(g4().debug({msg:"socket open",messageQueueLength:this.#X.length,connId:this.#Y}),this.#P("connected"),this.#z)this.#z.resolve(void 0);else g4().warn({msg:"#onOpenPromise is undefined"});for(let Z of this.#W.keys())this.#i(Z,!0);let J=this.#X;this.#X=[],g4().debug({msg:"flushing message queue",queueLength:J.length});for(let Z of J)this.#C(Z)})}async#T(J){var Z;g4().trace({msg:"received message",dataType:typeof J,isBlob:J instanceof Blob,isArrayBuffer:J instanceof ArrayBuffer});let Q=await this.#c(J);if(g4().trace(UH4()?{msg:"parsed message",message:Kc0(Q).substring(0,100)+"..."}:{msg:"parsed message"}),Q.body.tag==="Init")this.#Q=Q.body.val.actorId,this.#Y=Q.body.val.connectionId,Yr5(this.#N,this.#Q),g4().trace({msg:"received init message",actorId:this.#Q,connId:this.#Y}),this.#d();else if(Q.body.tag==="Error"){let{group:Y,code:X,message:K,metadata:V,actionId:z}=Q.body.val;if(z){let G=this.#u(Number(z));this.#E(Y,X),g4().warn({msg:"action error",actionId:z,actionName:G==null?void 0:G.name,group:Y,code:X,message:K,metadata:V}),G.reject(new hY(Y,X,K,V))}else{if(g4().warn({msg:"connection error",group:Y,code:X,message:K,metadata:V}),this.#E(Y,X),this.#h(Y,X)){(Z=this.#z)==null||Z.reject(new hY(Y,X,K,V));return}let G=new hY(Y,X,K,V);if(wc0(Y,X)&&this.#Q){let F=await Mc0(Y,X,this.#Q,this.#N.actorQuery,this.#L);if(F)G=F}if(this.#z)this.#z.reject(G);for(let[F,q]of this.#V.entries())q.reject(G),this.#V.delete(F);this.#b(G)}}else if(Q.body.tag==="ActionResponse"){let{id:Y}=Q.body.val;g4().debug({msg:"received action response",actionId:Number(Y),inFlightCount:this.#V.size,inFlightIds:Array.from(this.#V.keys())});let X=this.#u(Number(Y));g4().trace({msg:"resolving action promise",actionId:Y,actionName:X==null?void 0:X.name}),X.resolve(Q.body.val)}else if(Q.body.tag==="Event")g4().trace({msg:"received event",name:Q.body.val.name}),this.#q(Q.body.val);else SA(Q.body)}async#_(J){var Z;let Q=J,Y=Q.wasClean,X=this.#Z==="connected";if(g4().info({msg:"socket closed",code:Q.code,reason:Q.reason,wasClean:Y,disposed:this.#$,connId:this.#Y}),this.#H=void 0,this.#$)this.#k(new Bc0,!0);else{this.#P("disconnected");let K,V=Q.reason||"",z=Kr5(V);if(z){let{group:G,code:F}=z;if(this.#E(G,F),this.#h(G,F)){(Z=this.#z)==null||Z.reject(new hY(G,F,`Connection closed: ${V}`,void 0));return}if(wc0(G,F)&&this.#Q){let q=await Mc0(G,F,this.#Q,this.#N.actorQuery,this.#L);if(q)K=q;else K=new hY(G,F,`Connection closed: ${V}`,void 0)}else K=new hY(G,F,`Connection closed: ${V}`,void 0)}else K=Error(`${Y?"Connection closed":"Connection lost"} (code: ${Q.code}, reason: ${V})`);if(this.#k(K,!1),K instanceof hY)this.#b(K);if(X)g4().debug({msg:"triggering reconnect",connId:this.#Y}),this.#g()}}#k(J,Z){if(this.#z){if(Z)this.#z.promise.catch(()=>{});this.#z.reject(J)}for(let Q of this.#V.values())Q.reject(J);this.#V.clear()}#p(){if(this.#$)return;g4().warn("socket error")}#u(J){let Z=this.#V.get(J);if(!Z)throw g4().error({msg:"action not found in in-flight map",lookupId:J,inFlightCount:this.#V.size,inFlightIds:Array.from(this.#V.keys()),inFlightActions:Array.from(this.#V.entries()).map(([Q,Y])=>({id:Q,name:Y.name}))}),new Jr5(`No in flight response for ${J}`);return this.#V.delete(J),g4().debug({msg:"removed action from in-flight map",actionId:J,actionName:Z.name,inFlightCount:this.#V.size}),Z}#q(J){let{name:Z,args:Q}=J,Y=this.#W.get(Z);if(!Y)return;for(let X of[...Y])if(X.callback(...Q),X.once)Y.delete(X);if(Y.size===0)this.#W.delete(Z)}#b(J){for(let Z of[...this.#F])try{Z(J)}catch(Q){g4().error({msg:"error in connection error handler",error:k$(Q)})}}#v(J,Z,Q){let Y={callback:Z,once:Q},X=this.#W.get(J);if(X===void 0)X=new Set,this.#W.set(J,X),this.#i(J,!0);return X.add(Y),()=>{let K=this.#W.get(J);if(K){if(K.delete(Y),K.size===0)this.#W.delete(J),this.#i(J,!1)}}}on(J,Z){return this.#v(J,Z,!1)}once(J,Z){return this.#v(J,Z,!0)}onError(J){return this.#F.add(J),()=>{this.#F.delete(J)}}get connStatus(){return this.#Z}get isConnected(){return this.#Z==="connected"}onOpen(J){return this.#D.add(J),()=>{this.#D.delete(J)}}onClose(J){return this.#G.add(J),()=>{this.#G.delete(J)}}onStatusChange(J){return this.#K.add(J),()=>{this.#K.delete(J)}}#C(J,Z){var Q,Y;if(this.#$)if(Z==null?void 0:Z.ephemeral)return;else throw new Bc0;let X=!1;if(this.#H){let K=this.#H.readyState;if(g4().debug({msg:"websocket send attempt",readyState:K,readyStateString:K===0?"CONNECTING":K===1?"OPEN":K===2?"CLOSING":"CLOSED",connId:this.#Y,messageType:J.body.tag,actionName:(Q=J.body.val)==null?void 0:Q.name}),this.#Z!=="connected")g4().debug({msg:"websocket init pending, queueing message",connStatus:this.#Z,messageType:J.body.tag}),X=!0;else if(K===1)try{let V=AZ0(this.#O,J,_N4,gA,fN4,(z)=>z,(z)=>{if(z.body.tag==="ActionRequest")return{body:{tag:"ActionRequest",val:{id:z.body.val.id,name:z.body.val.name,args:vA(D2(z.body.val.args))}}};else return z});this.#H.send(V),g4().trace({msg:"sent websocket message",len:Vr5(V)})}catch(V){g4().warn({msg:"failed to send message, added to queue",error:V,connId:this.#Y}),X=!0}else g4().debug({msg:"websocket not open, queueing message",readyState:K}),X=!0}else g4().debug({msg:"no websocket, queueing message"}),X=!0;if(!(Z==null?void 0:Z.ephemeral)&&X)this.#X.push(J),g4().debug({msg:"queued connection message",queueLength:this.#X.length,connId:this.#Y,messageType:J.body.tag,actionName:(Y=J.body.val)==null?void 0:Y.name})}async#c(J){Lc0.default(this.#H,"websocket must be defined");let Z=await dN4(J);return jZ0(this.#O,Z,Gc0,qc0,(Q)=>Q,(Q)=>{if(Q.body.tag==="Error")return{body:{tag:"Error",val:{group:Q.body.val.group,code:Q.body.val.code,message:Q.body.val.message,metadata:Q.body.val.metadata?LJ(new Uint8Array(Q.body.val.metadata)):null,actionId:Q.body.val.actionId}}};else if(Q.body.tag==="ActionResponse")return{body:{tag:"ActionResponse",val:{id:Q.body.val.id,output:LJ(new Uint8Array(Q.body.val.output))}}};else if(Q.body.tag==="Event")return{body:{tag:"Event",val:{name:Q.body.val.name,args:LJ(new Uint8Array(Q.body.val.args))}}};else return Q})}get actorId(){return this.#Q}get connId(){return this.#Y}get connectionId(){return this.#Y}async dispose(){if(this.#$){g4().warn({msg:"connection already disconnected"});return}if(this.#$=!0,g4().debug({msg:"disposing actor conn"}),this.#P("idle"),clearInterval(this.#w),this.#J.abort(),this.#B[IZ0].delete(this),this.#H){let J=this.#H;if(J.readyState!==2&&J.readyState!==3){let{promise:Z,resolve:Q}=kA((Y)=>g4().warn({msg:"unhandled websocket close promise rejection",reason:Y}));J.addEventListener("close",()=>Q(void 0)),J.close(1000,"Disposed"),await Z}}else this.#k(new Bc0,!0);this.#H=void 0}#i(J,Z){this.#C({body:{tag:"SubscriptionRequest",val:{eventName:J,subscribe:Z}}},{ephemeral:!0})}},Kw4="http://localhost:6420",Vw4=!1,Ur5=_X.object({endpoint:_X.string().optional().transform((J)=>{let Z=J??hJ0()??gJ0();if(!Z&&!Vw4)Vw4=!0,console.warn(`[rivetkit] No endpoint provided to client. Defaulting to ${Kw4}. Starting in 2.2.0, an explicit endpoint will be required. Pass an endpoint to createClient() or createRivetKit(), or set the RIVET_ENDPOINT environment variable.`);return Z??Kw4}),token:_X.string().optional().transform((J)=>J??mJ0()),namespace:_X.string().optional().transform((J)=>J??pJ0()),runnerName:_X.string().default(()=>dJ0()??"default"),encoding:AN4.default("bare"),headers:_X.record(_X.string(),_X.string()).optional().default(()=>({})),getUpgradeWebSocket:_X.custom().optional(),disableMetadataLookup:_X.boolean().optional().default(!1),devtools:_X.boolean().default(()=>{var J,Z;return typeof window<"u"&&(((J=window==null?void 0:window.location)==null?void 0:J.hostname)==="127.0.0.1"||((Z=window.location)==null?void 0:Z.hostname)==="localhost")})}),Nw4=Ur5.transform((J,Z)=>Hr5(J,Z));function Hr5(J,Z){let Q=LZ0(Z,{endpoint:J.endpoint,path:["endpoint"],namespace:J.namespace,token:J.token});return{...J,endpoint:Q==null?void 0:Q.endpoint,namespace:(Q==null?void 0:Q.namespace)??J.namespace??"default",token:(Q==null?void 0:Q.token)??J.token}}function H3(){return EK("remote-manager-driver")}var Dr5=class extends Error{constructor(J,Z,Q){super(Q||`Engine API error: ${J}/${Z}`);this.group=J,this.code=Z,this.name="EngineApiError"}};function Nk(J){return J.endpoint??"http://127.0.0.1:6420"}async function nN(J,Z,Q,Y){let X=Nk(J),K=nJ0(X,Q,{namespace:J.namespace});H3().debug({msg:"making api call",method:Z,url:K});let V={...J.headers};if(J.token)V.Authorization=`Bearer ${J.token}`;return await jc0({method:Z,url:K,headers:V,body:Y,encoding:"json",skipParseResponse:!1,requestVersionedDataHandler:void 0,requestVersion:void 0,responseVersionedDataHandler:void 0,responseVersion:void 0,requestZodSchema:v.any(),responseZodSchema:v.any(),requestToJson:(z)=>z,requestToBare:(z)=>z,responseFromJson:(z)=>z,responseFromBare:(z)=>z})}function Ic0(J,Z,Q,Y=""){let X=Q!==void 0?`@${encodeURIComponent(Q)}`:"",K=`/gateway/${encodeURIComponent(Z)}${X}${Y}`;return nJ0(J,K)}async function Br5(J,Z,Q,Y,X){let K=await pp0(),V=Nk(J),z=Ic0(V,Q,J.token,Z);H3().debug({msg:"opening websocket to actor via guard",actorId:Q,path:Z,guardUrl:z});let G=new K(z,Lw4(J,Y,X));return G.binaryType="arraybuffer",H3().debug({msg:"websocket connection opened",actorId:Q}),G}function Lw4(J,Z,Q){let Y=[];if(Y.push(EN4),Y.push(`${Qc0}${Z}`),Q)Y.push(`${Yc0}${encodeURIComponent(JSON.stringify(Q))}`);return Y}async function zw4(J,Z,Q){let Y=new URL(Q.url),X=Nk(J),K=Ic0(X,Z,J.token,`${Y.pathname}${Y.search}`),V=null,z=wr5(J,Q,Z);if(Q.method!=="GET"&&Q.method!=="HEAD"){if(Q.bodyUsed)throw Error("Request body has already been consumed");let F=await Q.arrayBuffer();if(F.byteLength!==0)V=F,z.delete("transfer-encoding"),z.set("content-length",String(V.byteLength))}let G=new Request(K,{method:Q.method,headers:z,body:V,signal:Q.signal});return Nr5(await fetch(G))}function Nr5(J){return new Response(J.body,J)}function wr5(J,Z,Q){let Y=new Headers;Z.headers.forEach((X,K)=>{Y.set(K,X)});for(let[X,K]of Object.entries(J.headers))Y.set(X,K);if(J.token)Y.set(Zc0,J.token);return Y}async function Lr5(J,Z,Q){return nN(J,"GET",`/actors?actor_ids=${encodeURIComponent(Q)}`)}async function Or5(J,Z,Q){let Y=rc(Q);return nN(J,"GET",`/actors?name=${encodeURIComponent(Z)}&key=${encodeURIComponent(Y)}`)}async function Er5(J,Z){return nN(J,"GET",`/actors?name=${encodeURIComponent(Z)}`)}async function Mr5(J,Z){return nN(J,"PUT","/actors",Z)}async function Ar5(J,Z){return nN(J,"POST","/actors",Z)}async function jr5(J,Z){return nN(J,"DELETE",`/actors/${encodeURIComponent(Z)}`)}async function Rr5(J){return nN(J,"GET","/metadata")}async function Ir5(J,Z,Q){return nN(J,"GET",`/actors/${encodeURIComponent(Z)}/kv/keys/${encodeURIComponent(Q)}`)}var Gw4=new Map;async function Pr5(J){let Z=Nk(J),Q=Gw4.get(Z);if(Q)return Q;let Y=sc(async()=>{H3().debug({msg:"fetching metadata",endpoint:Z});let X=await Rr5(J);return H3().debug({msg:"received metadata",endpoint:Z,clientEndpoint:X.clientEndpoint}),X},{forever:!0,minTimeout:500,maxTimeout:15000,onFailedAttempt:(X)=>{if(X.attemptNumber>1)H3().warn({msg:"failed to fetch metadata, retrying",endpoint:Z,attempt:X.attemptNumber,error:k$(X)})}});return Gw4.set(Z,Y),Y}async function Cr5(J,Z,Q){let Y=await pp0(),X={};return{onOpen:async(K,V)=>{if(H3().debug({msg:"client websocket connected",targetUrl:Z}),V.readyState!==1){H3().warn({msg:"client websocket not open on connection",targetUrl:Z,readyState:V.readyState});return}let z=new Y(Z,Q);X.targetWs=z,X.connectPromise=new Promise((G,F)=>{z.addEventListener("open",()=>{if(H3().debug({msg:"target websocket connected",targetUrl:Z}),V.readyState!==1){H3().warn({msg:"client websocket closed before target connected",targetUrl:Z,clientReadyState:V.readyState}),z.close(1001,"Client disconnected"),F(Error("Client disconnected"));return}G()}),z.addEventListener("error",(q)=>{H3().warn({msg:"target websocket error during connection",targetUrl:Z}),F(q)})}),X.targetWs.addEventListener("message",(G)=>{if(typeof G.data==="string"||G.data instanceof ArrayBuffer)V.send(G.data);else if(G.data instanceof Blob)G.data.arrayBuffer().then((F)=>{V.send(F)})}),X.targetWs.addEventListener("close",(G)=>{H3().debug({msg:"target websocket closed",targetUrl:Z,code:G.code,reason:G.reason}),Nc0(V,G.code,G.reason)}),X.targetWs.addEventListener("error",(G)=>{H3().error({msg:"target websocket error",targetUrl:Z,error:k$(G)}),Nc0(V,1011,"Target WebSocket error")})},onMessage:async(K,V)=>{if(!X.targetWs||!X.connectPromise){H3().error({msg:"websocket state not initialized",targetUrl:Z});return}try{if(await X.connectPromise,X.targetWs.readyState===Y.OPEN)X.targetWs.send(K.data);else H3().warn({msg:"target websocket not open",targetUrl:Z,readyState:X.targetWs.readyState})}catch(z){H3().error({msg:"failed to connect to target websocket",targetUrl:Z,error:z}),Nc0(V,1011,"Failed to connect to target")}},onClose:(K,V)=>{if(H3().debug({msg:"client websocket closed",targetUrl:Z,code:K.code,reason:K.reason,wasClean:K.wasClean}),X.targetWs){if(X.targetWs.readyState===Y.OPEN||X.targetWs.readyState===Y.CONNECTING)X.targetWs.close(1000,K.reason||"Client disconnected")}},onError:(K,V)=>{if(H3().error({msg:"client websocket error",targetUrl:Z,event:K}),X.targetWs){if(X.targetWs.readyState===Y.OPEN)X.targetWs.close(1011,"Client WebSocket error");else if(X.targetWs.readyState===Y.CONNECTING)X.targetWs.close()}}}}function Nc0(J,Z,Q){if(J.readyState===1)J.close(Z,Q);else if("close"in J&&J.readyState===WebSocket.OPEN)J.close(Z,Q)}var Ow4=class{#$;#J;constructor(J){if(HH4()==="phase-production-build")H3().info("detected next.js build phase, disabling health check"),J.disableMetadataLookup=!0;if(this.#$={...J},!J.disableMetadataLookup)this.#J=Pr5(this.#$).then((Z)=>{if(Z.clientEndpoint){if(this.#$.endpoint=Z.clientEndpoint,Z.clientNamespace)this.#$.namespace=Z.clientNamespace;if(Z.clientToken)this.#$.token=Z.clientToken;H3().info({msg:"overriding client endpoint",endpoint:Z.clientEndpoint,namespace:Z.clientNamespace,token:Z.clientToken})}H3().info({msg:"connected to rivetkit manager",runtime:Z.runtime,version:Z.version,runner:Z.runner})})}async getForId({c:J,name:Z,actorId:Q}){if(this.#J)await this.#J;let X=(await Lr5(this.#$,Z,Q)).actors[0];if(!X)return;if(X.name!==Z){H3().debug({msg:"actor name mismatch from api",actorId:Q,apiName:X.name,requestedName:Z});return}return ec(X)}async getWithKey({c:J,name:Z,key:Q}){if(this.#J)await this.#J;H3().debug({msg:"getWithKey: searching for actor",name:Z,key:Q});try{let X=(await Or5(this.#$,Z,Q)).actors[0];if(!X)return;return H3().debug({msg:"getWithKey: found actor via api",actorId:X.actor_id,name:Z,key:Q}),ec(X)}catch(Y){if(Y instanceof Dr5&&Y.group==="actor"&&Y.code==="not_found")return;throw Y}}async getOrCreateWithKey(J){if(this.#J)await this.#J;let{c:Z,name:Q,key:Y,input:X,region:K}=J;H3().info({msg:"getOrCreateWithKey: getting or creating actor via engine api",name:Q,key:Y});let{actor:V,created:z}=await Mr5(this.#$,{datacenter:K,name:Q,key:rc(Y),runner_name_selector:this.#$.runnerName,input:X?Xc0(D2(X)):void 0,crash_policy:"sleep"});return H3().info({msg:"getOrCreateWithKey: actor ready",actorId:V.actor_id,name:Q,key:Y,created:z}),ec(V)}async createActor({c:J,name:Z,key:Q,input:Y,region:X}){if(this.#J)await this.#J;H3().info({msg:"creating actor via engine api",name:Z,key:Q});let K=await Ar5(this.#$,{datacenter:X,name:Z,runner_name_selector:this.#$.runnerName,key:rc(Q),input:Y?Xc0(D2(Y)):void 0,crash_policy:"sleep"});return H3().info({msg:"actor created",actorId:K.actor.actor_id,name:Z,key:Q}),ec(K.actor)}async listActors({c:J,name:Z}){if(this.#J)await this.#J;return H3().debug({msg:"listing actors via engine api",name:Z}),(await Er5(this.#$,Z)).actors.map(ec)}async destroyActor(J){if(this.#J)await this.#J;H3().info({msg:"destroying actor via engine api",actorId:J}),await jr5(this.#$,J),H3().info({msg:"actor destroyed",actorId:J})}async sendRequest(J,Z){if(this.#J)await this.#J;return await zw4(this.#$,J,Z)}async openWebSocket(J,Z,Q,Y){if(this.#J)await this.#J;return await Br5(this.#$,J,Z,Q,Y)}async buildGatewayUrl(J){if(this.#J)await this.#J;let Z=Nk(this.#$);return Ic0(Z,J,this.#$.token)}async proxyRequest(J,Z,Q){if(this.#J)await this.#J;return await zw4(this.#$,Q,Z)}async proxyWebSocket(J,Z,Q,Y,X){var K,V;if(this.#J)await this.#J;let z=(V=(K=this.#$).getUpgradeWebSocket)==null?void 0:V.call(K);ww4.default(z,"missing getUpgradeWebSocket");let G=Nk(this.#$),F=nJ0(G,Z),q=F.replace("http://","ws://");H3().debug({msg:"forwarding websocket to actor via guard",actorId:Q,path:Z,guardUrl:F});let W=Lw4(this.#$,Y,X),U=await Cr5(J,q,W);return await z(()=>U)(J,mp0())}async kvGet(J,Z){if(this.#J)await this.#J;return H3().debug({msg:"getting kv value via engine api",key:Z}),(await Ir5(this.#$,J,new TextDecoder("utf8").decode(Z))).value}displayInformation(){return{properties:{}}}setGetUpgradeWebSocket(J){this.#$.getUpgradeWebSocket=J}};function ec(J){return{actorId:J.actor_id,name:J.name,key:Hc0(J.key),createTs:J.create_ts,startTs:J.start_ts??null,connectableTs:J.connectable_ts??null,sleepTs:J.sleep_ts??null,destroyTs:J.destroy_ts??null,error:J.error??void 0}}function Tr5(){return EK("devtools")}var _r5=(J=sS)=>`https://releases.rivet.dev/rivet/latest/devtools/mod.js?v=${J}`,Ew4="rivetkit-devtools-script";function Sr5(J){if(!window){Tr5().warn("devtools not available outside browser environment");return}if(!document.getElementById(Ew4)){let Z=document.createElement("script");Z.id=Ew4,Z.src=_r5(),Z.async=!0,document.head.appendChild(Z)}window.__rivetkit=window.__rivetkit||[],window.__rivetkit.push(J)}function Pc0(J){let Z=J===void 0?{}:typeof J==="string"?{endpoint:J}:J,Q=Nw4.parse(Z),Y=new Ow4(Q);if(Q.devtools)Sr5(Q);return Dw4(Y,Q)}function Lk(J,Z){var Q={};for(var Y in J)if(Object.prototype.hasOwnProperty.call(J,Y)&&Z.indexOf(Y)<0)Q[Y]=J[Y];if(J!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var X=0,Y=Object.getOwnPropertySymbols(J);X<Y.length;X++)if(Z.indexOf(Y[X])<0&&Object.prototype.propertyIsEnumerable.call(J,Y[X]))Q[Y[X]]=J[Y[X]]}return Q}var kr5={ZodAny:"any",ZodArray:"array",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDefault:"default",ZodPrefault:"prefault",ZodTransform:"transform",ZodEnum:"enum",ZodIntersection:"intersection",ZodLazy:"lazy",ZodLiteral:"literal",ZodNever:"never",ZodNull:"null",ZodNullable:"nullable",ZodNumber:"number",ZodNonOptional:"nonoptional",ZodObject:"object",ZodOptional:"optional",ZodPipe:"pipe",ZodReadonly:"readonly",ZodRecord:"record",ZodString:"string",ZodTuple:"tuple",ZodType:"type",ZodUnion:"union",ZodDiscriminatedUnion:"union",ZodUnknown:"unknown",ZodVoid:"void",ZodDate:"date",ZodTemplateLiteral:"template_literal"};function tU(J,Z){return(Array.isArray(Z)?Z:[Z]).some((Y)=>{var X;let K=((X=J===null||J===void 0?void 0:J.def)===null||X===void 0?void 0:X.type)===kr5[Y];if(Y==="ZodDiscriminatedUnion")return K&&"discriminator"in J.def;return K})}function wk(J){return J&&"def"in J}class Aw4{constructor(){this._map=new Map,this._idmap=new Map}add(J,...Z){let Q=Z[0];if(this._map.set(J,Q),Q&&typeof Q==="object"&&"id"in Q){if(this._idmap.has(Q.id))throw Error(`ID ${Q.id} already exists in the registry`);this._idmap.set(Q.id,J)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(J){let Z=this._map.get(J);if(Z&&typeof Z==="object"&&"id"in Z)this._idmap.delete(Z.id);return this._map.delete(J),this}get(J){let Z=J._zod.parent;if(Z){let Q={...this.get(Z)??{}};return delete Q.id,{...Q,...this._map.get(J)}}return this._map.get(J)}has(J){return this._map.has(J)}}function vr5(){return new Aw4}function Cc0(J){return J===void 0}function yr5(J,Z){let Q={};return Object.entries(J).forEach(([Y,X])=>{if(!Z.some((K)=>K===Y))Q[Y]=X}),Q}function Tc0(J,Z){let Q={};return Object.entries(J).forEach(([Y,X])=>{if(!Z(X,Y))Q[Y]=X}),Q}var Mw4=vr5();class eU{static collectMetadata(J,Z){let Q=this.getMetadataFromRegistry(J),Y=Object.assign(Object.assign({},Q===null||Q===void 0?void 0:Q._internal),Z===null||Z===void 0?void 0:Z._internal),X=Object.assign(Object.assign({},Q===null||Q===void 0?void 0:Q.param),Z===null||Z===void 0?void 0:Z.param),K=Object.assign(Object.assign(Object.assign(Object.assign({},Object.keys(Y).length>0?{_internal:Y}:{}),Q),Z),Object.keys(X).length>0?{param:X}:{});if(tU(J,["ZodOptional","ZodNullable","ZodDefault","ZodPrefault","ZodReadonly","ZodNonOptional"])&&wk(J._zod.def.innerType))return this.collectMetadata(J._zod.def.innerType,K);if(tU(J,"ZodPipe")){let V=J._zod.def.in,z=J._zod.def.out;if(tU(V,"ZodTransform")&&wk(z))return this.collectMetadata(z,K);if(wk(V))return this.collectMetadata(V,K)}return K}static getMetadata(J){return this.collectMetadata(J)}static getOpenApiMetadata(J){let Z=this.collectMetadata(J),Q=Z!==null&&Z!==void 0?Z:{},{_internal:Y}=Q;return Lk(Q,["_internal"])}static getInternalMetadata(J){var Z;return(Z=this.collectMetadata(J))===null||Z===void 0?void 0:Z._internal}static getParamMetadata(J){let Z=this.collectMetadata(J);return Object.assign(Object.assign({},Z),{param:Object.assign(Object.assign({},(Z===null||Z===void 0?void 0:Z.description)?{description:Z.description}:{}),Z===null||Z===void 0?void 0:Z.param)})}static buildSchemaMetadata(J){return Tc0(yr5(J,["param","_internal"]),Cc0)}static buildParameterMetadata(J){return Tc0(J,Cc0)}static applySchemaMetadata(J,Z){return Tc0(Object.assign(Object.assign({},J),this.buildSchemaMetadata(Z)),Cc0)}static getRefId(J){var Z;return(Z=this.getInternalMetadata(J))===null||Z===void 0?void 0:Z.refId}static unwrapChained(J){return this.unwrapUntil(J)}static getDefaultValue(J){var Z;let Q=(Z=this.unwrapUntil(J,"ZodDefault"))!==null&&Z!==void 0?Z:this.unwrapUntil(J,"ZodPrefault");return Q===null||Q===void 0?void 0:Q._zod.def.defaultValue}static unwrapUntil(J,Z){if(Z&&tU(J,Z))return J;if(tU(J,["ZodOptional","ZodNullable","ZodDefault","ZodPrefault","ZodReadonly","ZodNonOptional"])&&wk(J._zod.def.innerType))return this.unwrapUntil(J._zod.def.innerType,Z);if(tU(J,"ZodPipe")){let Q=J._zod.def.in,Y=J._zod.def.out;if(tU(Q,"ZodTransform")&&wk(Y))return this.unwrapUntil(Y,Z);if(wk(Q))return this.unwrapUntil(Q,Z)}return Z?void 0:J}static getMetadataFromInternalRegistry(J){return Mw4.get(J)}static getMetadataFromRegistry(J){let Z=this.getMetadataFromInternalRegistry(J),Q=J.meta();if(!Z)return Q;let{_internal:Y}=Z,X=Lk(Z,["_internal"]),K=Q!==null&&Q!==void 0?Q:{},{id:V,title:z}=K,G=Lk(K,["id","title"]);return Object.assign(Object.assign(Object.assign({_internal:Object.assign(Object.assign({},V?{refId:V}:{}),Y)},X),z?{description:z}:{}),G)}static setMetadataInRegistry(J,Z){Mw4.add(J,Z)}}function sU(J,Z){let Q=J[Z];if(typeof Q!=="function")return;J[Z]=function(...Y){let X=Q.apply(this,Y),K=eU.getMetadataFromRegistry(this);if(K)eU.setMetadataInRegistry(X,K);return X}}function xr5(J){if(typeof J.ZodType.prototype.openapi<"u")return;J.ZodType.prototype.openapi=function(...Z){let{refId:Q,metadata:Y,options:X}=fr5(...Z),K=Y!==null&&Y!==void 0?Y:{},{param:V}=K,z=Lk(K,["param"]),G=eU.getMetadataFromRegistry(this),F=G!==null&&G!==void 0?G:{},{_internal:q}=F,W=Lk(F,["_internal"]),U=Object.assign(Object.assign(Object.assign({},q),X),Q?{refId:Q}:void 0),H=Object.assign(Object.assign(Object.assign({},W),z),(W===null||W===void 0?void 0:W.param)||V?{param:Object.assign(Object.assign({},W===null||W===void 0?void 0:W.param),V)}:void 0),D=new this.constructor(this._def);function B(w){eU.setMetadataInRegistry(w,Object.assign(Object.assign({},Object.keys(U).length>0?{_internal:U}:void 0),H))}if(B(D),tU(D,"ZodLazy"))B(this);if(tU(D,"ZodObject")){let w=eU.getMetadataFromRegistry(D),L=D.extend;D.extend=function(...O){let E=L.apply(D,O),M=w!==null&&w!==void 0?w:{},{_internal:A}=M,j=Lk(M,["_internal"]);return eU.setMetadataInRegistry(E,{_internal:{extendedFrom:(A===null||A===void 0?void 0:A.refId)?{refId:A.refId,schema:D}:A===null||A===void 0?void 0:A.extendedFrom}}),E.openapi(j)},sU(D,"catchall")}sU(D,"optional"),sU(D,"nullable"),sU(D,"default"),sU(D,"transform"),sU(D,"refine"),sU(D,"length"),sU(D,"min"),sU(D,"max");let N=D.meta;return D.meta=function(...w){let L=N.apply(this,w);if(w[0]){let O=eU.getMetadataFromInternalRegistry(this);if(O)eU.setMetadataInRegistry(L,Object.assign(Object.assign({},O),w[0]))}return L},D}}function fr5(J,Z,Q){if(typeof J==="string")return{refId:J,metadata:Z,options:Q};return{refId:void 0,metadata:J,options:Z}}var _c0=xr5;oN();var yc0=(J,Z,Q)=>{return(Y,X)=>{let K=-1;return V(0);async function V(z){if(z<=K)throw Error("next() called multiple times");K=z;let G,F=!1,q;if(J[z])q=J[z][0][0],Y.req.routeIndex=z;else q=z===J.length&&X||void 0;if(q)try{G=await q(Y,()=>V(z+1))}catch(W){if(W instanceof Error&&Z)Y.error=W,G=await Z(W,Y),F=!0;else throw W}else if(Y.finalized===!1&&Q)G=await Q(Y);if(G&&(Y.finalized===!1||F))Y.res=G;return Y}}};var _w4=Symbol();var Sw4=async(J,Z=Object.create(null))=>{let{all:Q=!1,dot:Y=!1}=Z,K=(J instanceof SZ0?J.raw.headers:J.headers).get("Content-Type");if(K?.startsWith("multipart/form-data")||K?.startsWith("application/x-www-form-urlencoded"))return pr5(J,{all:Q,dot:Y});return{}};async function pr5(J,Z){let Q=await J.formData();if(Q)return dr5(Q,Z);return{}}function dr5(J,Z){let Q=Object.create(null);if(J.forEach((Y,X)=>{if(!(Z.all||X.endsWith("[]")))Q[X]=Y;else cr5(Q,X,Y)}),Z.dot)Object.entries(Q).forEach(([Y,X])=>{if(Y.includes("."))lr5(Q,Y,X),delete Q[Y]});return Q}var cr5=(J,Z,Q)=>{if(J[Z]!==void 0)if(Array.isArray(J[Z]))J[Z].push(Q);else J[Z]=[J[Z],Q];else if(!Z.endsWith("[]"))J[Z]=Q;else J[Z]=[Q]},lr5=(J,Z,Q)=>{if(/(?:^|\.)__proto__\./.test(Z))return;let Y=J,X=Z.split(".");X.forEach((K,V)=>{if(V===X.length-1)Y[K]=Q;else{if(!Y[K]||typeof Y[K]!=="object"||Array.isArray(Y[K])||Y[K]instanceof File)Y[K]=Object.create(null);Y=Y[K]}})};oN();var kw4=(J)=>Jl(J,_Z0),SZ0=class{raw;#$;#J;routeIndex=0;path;bodyCache={};constructor(J,Z="/",Q=[[]]){this.raw=J,this.path=Z,this.#J=Q,this.#$={}}param(J){return J?this.#Z(J):this.#Q()}#Z(J){let Z=this.#J[0][this.routeIndex][1][J],Q=this.#Y(Z);return Q&&/\%/.test(Q)?kw4(Q):Q}#Q(){let J={},Z=Object.keys(this.#J[0][this.routeIndex][1]);for(let Q of Z){let Y=this.#Y(this.#J[0][this.routeIndex][1][Q]);if(Y!==void 0)J[Q]=/\%/.test(Y)?kw4(Y):Y}return J}#Y(J){return this.#J[1]?this.#J[1][J]:J}query(J){return Cw4(this.url,J)}queries(J){return Tw4(this.url,J)}header(J){if(J)return this.raw.headers.get(J)??void 0;let Z={};return this.raw.headers.forEach((Q,Y)=>{Z[Y]=Q}),Z}async parseBody(J){return this.bodyCache.parsedBody??=await Sw4(this,J)}#X=(J)=>{let{bodyCache:Z,raw:Q}=this,Y=Z[J];if(Y)return Y;let X=Object.keys(Z)[0];if(X)return Z[X].then((K)=>{if(X==="json")K=JSON.stringify(K);return new Response(K)[J]()});return Z[J]=Q[J]()};json(){return this.#X("text").then((J)=>JSON.parse(J))}text(){return this.#X("text")}arrayBuffer(){return this.#X("arrayBuffer")}blob(){return this.#X("blob")}formData(){return this.#X("formData")}addValidatedData(J,Z){this.#$[J]=Z}valid(J){return this.#$[J]}get url(){return this.raw.url}get method(){return this.raw.method}get[_w4](){return this.#J}get matchedRoutes(){return this.#J[0].map(([[,J]])=>J)}get routePath(){return this.#J[0].map(([[,J]])=>J)[this.routeIndex].path}};yw4();var nr5="text/plain; charset=UTF-8",fc0=(J,Z)=>{return{"Content-Type":J,...Z}},Zl=(J,Z)=>new Response(J,Z),xw4=class{#$;#J;env={};#Z;finalized=!1;error;#Q;#Y;#X;#V;#W;#F;#D;#U;#G;constructor(J,Z){if(this.#$=J,Z)this.#Y=Z.executionCtx,this.env=Z.env,this.#F=Z.notFoundHandler,this.#G=Z.path,this.#U=Z.matchResult}get req(){return this.#J??=new SZ0(this.#$,this.#G,this.#U),this.#J}get event(){if(this.#Y&&"respondWith"in this.#Y)return this.#Y;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#Y)return this.#Y;else throw Error("This context has no ExecutionContext")}get res(){return this.#X||=Zl(null,{headers:this.#D??=new Headers})}set res(J){if(this.#X&&J){J=Zl(J.body,J);for(let[Z,Q]of this.#X.headers.entries()){if(Z==="content-type")continue;if(Z==="set-cookie"){let Y=this.#X.headers.getSetCookie();J.headers.delete("set-cookie");for(let X of Y)J.headers.append("set-cookie",X)}else J.headers.set(Z,Q)}}this.#X=J,this.finalized=!0}render=(...J)=>{return this.#W??=(Z)=>this.html(Z),this.#W(...J)};setLayout=(J)=>this.#V=J;getLayout=()=>this.#V;setRenderer=(J)=>{this.#W=J};header=(J,Z,Q)=>{if(this.finalized)this.#X=Zl(this.#X.body,this.#X);let Y=this.#X?this.#X.headers:this.#D??=new Headers;if(Z===void 0)Y.delete(J);else if(Q?.append)Y.append(J,Z);else Y.set(J,Z)};status=(J)=>{this.#Q=J};set=(J,Z)=>{this.#Z??=new Map,this.#Z.set(J,Z)};get=(J)=>{return this.#Z?this.#Z.get(J):void 0};get var(){if(!this.#Z)return{};return Object.fromEntries(this.#Z)}#K(J,Z,Q){let Y=this.#X?new Headers(this.#X.headers):this.#D??new Headers;if(typeof Z==="object"&&"headers"in Z){let K=Z.headers instanceof Headers?Z.headers:new Headers(Z.headers);for(let[V,z]of K)if(V.toLowerCase()==="set-cookie")Y.append(V,z);else Y.set(V,z)}if(Q)for(let[K,V]of Object.entries(Q))if(typeof V==="string")Y.set(K,V);else{Y.delete(K);for(let z of V)Y.append(K,z)}let X=typeof Z==="number"?Z:Z?.status??this.#Q;return Zl(J,{status:X,headers:Y})}newResponse=(...J)=>this.#K(...J);body=(J,Z,Q)=>this.#K(J,Z,Q);text=(J,Z,Q)=>{return!this.#D&&!this.#Q&&!Z&&!Q&&!this.finalized?new Response(J):this.#K(J,Z,fc0(nr5,Q))};json=(J,Z,Q)=>{return this.#K(JSON.stringify(J),Z,fc0("application/json",Q))};html=(J,Z,Q)=>{let Y=(X)=>this.#K(X,Z,fc0("text/html; charset=UTF-8",Q));return typeof J==="object"?xc0(J,vw4.Stringify,!1,{}).then(Y):Y(J)};redirect=(J,Z)=>{let Q=String(J);return this.header("Location",!/[^\x00-\xFF]/.test(Q)?Q:encodeURI(Q)),this.newResponse(null,Z??302)};notFound=()=>{return this.#F??=()=>Zl(),this.#F(this)}};mA();hw4();oN();var ar5=(J)=>{return J.text("404 Not Found",404)},gw4=(J,Z)=>{if("getResponse"in J){let Q=J.getResponse();return Z.newResponse(Q.body,Q)}return console.error(J),Z.text("Internal Server Error",500)},mw4=class J{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#$="/";routes=[];constructor(Z={}){[...uw4,fw4].forEach((K)=>{this[K]=(V,...z)=>{if(typeof V==="string")this.#$=V;else this.#Q(K,this.#$,V);return z.forEach((G)=>{this.#Q(K,this.#$,G)}),this}}),this.on=(K,V,...z)=>{for(let G of[V].flat()){this.#$=G;for(let F of[K].flat())z.map((q)=>{this.#Q(F.toUpperCase(),this.#$,q)})}return this},this.use=(K,...V)=>{if(typeof K==="string")this.#$=K;else this.#$="*",V.unshift(K);return V.forEach((z)=>{this.#Q(M8,this.#$,z)}),this};let{strict:Y,...X}=Z;Object.assign(this,X),this.getPath=Y??!0?Z.getPath??vc0:Iw4}#J(){let Z=new J({router:this.router,getPath:this.getPath});return Z.errorHandler=this.errorHandler,Z.#Z=this.#Z,Z.routes=this.routes,Z}#Z=ar5;errorHandler=gw4;route(Z,Q){let Y=this.basePath(Z);return Q.routes.map((X)=>{let K;if(Q.errorHandler===gw4)K=X.handler;else K=async(V,z)=>(await yc0([],Q.errorHandler)(V,()=>X.handler(V,z))).res,K[bw4]=X.handler;Y.#Q(X.method,X.path,K)}),this}basePath(Z){let Q=this.#J();return Q._basePath=aN(this._basePath,Z),Q}onError=(Z)=>{return this.errorHandler=Z,this};notFound=(Z)=>{return this.#Z=Z,this};mount(Z,Q,Y){let X,K;if(Y)if(typeof Y==="function")K=Y;else if(K=Y.optionHandler,Y.replaceRequest===!1)X=(G)=>G;else X=Y.replaceRequest;let V=K?(G)=>{let F=K(G);return Array.isArray(F)?F:[F]}:(G)=>{let F=void 0;try{F=G.executionCtx}catch{}return[G.env,F]};X||=(()=>{let G=aN(this._basePath,Z),F=G==="/"?0:G.length;return(q)=>{let W=new URL(q.url);return W.pathname=W.pathname.slice(F)||"/",new Request(W,q)}})();let z=async(G,F)=>{let q=await Q(X(G.req.raw),...V(G));if(q)return q;await F()};return this.#Q(M8,aN(Z,"*"),z),this}#Q(Z,Q,Y){Z=Z.toUpperCase(),Q=aN(this._basePath,Q);let X={basePath:this._basePath,path:Q,method:Z,handler:Y};this.router.add(Z,Q,[Y,X]),this.routes.push(X)}#Y(Z,Q){if(Z instanceof Error)return this.errorHandler(Z,Q);throw Z}#X(Z,Q,Y,X){if(X==="HEAD")return(async()=>new Response(null,await this.#X(Z,Q,Y,"GET")))();let K=this.getPath(Z,{env:Y}),V=this.router.match(X,K),z=new xw4(Z,{path:K,matchResult:V,env:Y,executionCtx:Q,notFoundHandler:this.#Z});if(V[0].length===1){let F;try{F=V[0][0][0][0](z,async()=>{z.res=await this.#Z(z)})}catch(q){return this.#Y(q,z)}return F instanceof Promise?F.then((q)=>q||(z.finalized?z.res:this.#Z(z))).catch((q)=>this.#Y(q,z)):F??this.#Z(z)}let G=yc0(V[0],this.errorHandler,this.#Z);return(async()=>{try{let F=await G(z);if(!F.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return F.res}catch(F){return this.#Y(F,z)}})()}fetch=(Z,...Q)=>{return this.#X(Z,Q[1],Q[0],Z.method)};request=(Z,Q,Y,X)=>{if(Z instanceof Request)return this.fetch(Q?new Request(Z,Q):Z,Y,X);return Z=Z.toString(),this.fetch(new Request(/^https?:\/\//.test(Z)?Z:`http://localhost${aN("/",Z)}`,Q),Y,X)};fire=()=>{addEventListener("fetch",(Z)=>{Z.respondWith(this.#X(Z.request,Z,void 0,Z.request.method))})}};mA();oN();mA();var Ql=[];function yZ0(J,Z){let Q=this.buildAllMatchers(),Y=(X,K)=>{let V=Q[X]||Q[M8],z=V[2][K];if(z)return z;let G=K.match(V[0]);if(!G)return[[],Ql];let F=G.indexOf("",1);return[V[1][F],G]};return this.match=Y,Y(J,Z)}var xZ0="[^/]+",Yl=".*",Xl="(?:|/.*)",pA=Symbol(),or5=new Set(".\\+*[^]$()");function rr5(J,Z){if(J.length===1)return Z.length===1?J<Z?-1:1:-1;if(Z.length===1)return 1;if(J===Yl||J===Xl)return 1;else if(Z===Yl||Z===Xl)return-1;if(J===xZ0)return 1;else if(Z===xZ0)return-1;return J.length===Z.length?J<Z?-1:1:Z.length-J.length}var pw4=class J{#$;#J;#Z=Object.create(null);insert(Z,Q,Y,X,K){if(Z.length===0){if(this.#$!==void 0)throw pA;if(K)return;this.#$=Q;return}let[V,...z]=Z,G=V==="*"?z.length===0?["","",Yl]:["","",xZ0]:V==="/*"?["","",Xl]:V.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),F;if(G){let q=G[1],W=G[2]||xZ0;if(q&&G[2]){if(W===".*")throw pA;if(W=W.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(W))throw pA}if(F=this.#Z[W],!F){if(Object.keys(this.#Z).some((U)=>U!==Yl&&U!==Xl))throw pA;if(K)return;if(F=this.#Z[W]=new J,q!=="")F.#J=X.varIndex++}if(!K&&q!=="")Y.push([q,F.#J])}else if(F=this.#Z[V],!F){if(Object.keys(this.#Z).some((q)=>q.length>1&&q!==Yl&&q!==Xl))throw pA;if(K)return;F=this.#Z[V]=new J}F.insert(z,Q,Y,X,K)}buildRegExpStr(){let Q=Object.keys(this.#Z).sort(rr5).map((Y)=>{let X=this.#Z[Y];return(typeof X.#J==="number"?`(${Y})@${X.#J}`:or5.has(Y)?`\\${Y}`:Y)+X.buildRegExpStr()});if(typeof this.#$==="number")Q.unshift(`#${this.#$}`);if(Q.length===0)return"";if(Q.length===1)return Q[0];return"(?:"+Q.join("|")+")"}};var dw4=class{#$={varIndex:0};#J=new pw4;insert(J,Z,Q){let Y=[],X=[];for(let V=0;;){let z=!1;if(J=J.replace(/\{[^}]+\}/g,(G)=>{let F=`@\\${V}`;return X[V]=[F,G],V++,z=!0,F}),!z)break}let K=J.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let V=X.length-1;V>=0;V--){let[z]=X[V];for(let G=K.length-1;G>=0;G--)if(K[G].indexOf(z)!==-1){K[G]=K[G].replace(z,X[V][1]);break}}return this.#J.insert(K,Z,Y,this.#$,Q),Y}buildRegExp(){let J=this.#J.buildRegExpStr();if(J==="")return[/^$/,[],[]];let Z=0,Q=[],Y=[];return J=J.replace(/#(\d+)|@(\d+)|\.\*\$/g,(X,K,V)=>{if(K!==void 0)return Q[++Z]=Number(K),"$()";if(V!==void 0)return Y[Number(V)]=++Z,"";return""}),[new RegExp(`^${J}`),Q,Y]}};var sr5=[/^$/,[],Object.create(null)],cw4=Object.create(null);function lw4(J){return cw4[J]??=new RegExp(J==="*"?"":`^${J.replace(/\/\*$|([.\\+*[^\]$()])/g,(Z,Q)=>Q?`\\${Q}`:"(?:|/.*)")}$`)}function tr5(){cw4=Object.create(null)}function er5(J){let Z=new dw4,Q=[];if(J.length===0)return sr5;let Y=J.map((F)=>[!/\*|\/:/.test(F[0]),...F]).sort(([F,q],[W,U])=>F?1:W?-1:q.length-U.length),X=Object.create(null);for(let F=0,q=-1,W=Y.length;F<W;F++){let[U,H,D]=Y[F];if(U)X[H]=[D.map(([N])=>[N,Object.create(null)]),Ql];else q++;let B;try{B=Z.insert(H,q,U)}catch(N){throw N===pA?new vZ0(H):N}if(U)continue;Q[q]=D.map(([N,w])=>{let L=Object.create(null);w-=1;for(;w>=0;w--){let[O,E]=B[w];L[O]=E}return[N,L]})}let[K,V,z]=Z.buildRegExp();for(let F=0,q=Q.length;F<q;F++)for(let W=0,U=Q[F].length;W<U;W++){let H=Q[F][W]?.[1];if(!H)continue;let D=Object.keys(H);for(let B=0,N=D.length;B<N;B++)H[D[B]]=z[H[D[B]]]}let G=[];for(let F in V)G[F]=Q[V[F]];return[K,G,X]}function Ok(J,Z){if(!J)return;for(let Q of Object.keys(J).sort((Y,X)=>X.length-Y.length))if(lw4(Q).test(Z))return[...J[Q]];return}var fZ0=class{name="RegExpRouter";#$;#J;constructor(){this.#$={[M8]:Object.create(null)},this.#J={[M8]:Object.create(null)}}add(J,Z,Q){let Y=this.#$,X=this.#J;if(!Y||!X)throw Error(kZ0);if(!Y[J])[Y,X].forEach((z)=>{z[J]=Object.create(null),Object.keys(z[M8]).forEach((G)=>{z[J][G]=[...z[M8][G]]})});if(Z==="/*")Z="*";let K=(Z.match(/\/:/g)||[]).length;if(/\*$/.test(Z)){let z=lw4(Z);if(J===M8)Object.keys(Y).forEach((G)=>{Y[G][Z]||=Ok(Y[G],Z)||Ok(Y[M8],Z)||[]});else Y[J][Z]||=Ok(Y[J],Z)||Ok(Y[M8],Z)||[];Object.keys(Y).forEach((G)=>{if(J===M8||J===G)Object.keys(Y[G]).forEach((F)=>{z.test(F)&&Y[G][F].push([Q,K])})}),Object.keys(X).forEach((G)=>{if(J===M8||J===G)Object.keys(X[G]).forEach((F)=>z.test(F)&&X[G][F].push([Q,K]))});return}let V=TZ0(Z)||[Z];for(let z=0,G=V.length;z<G;z++){let F=V[z];Object.keys(X).forEach((q)=>{if(J===M8||J===q)X[q][F]||=[...Ok(Y[q],F)||Ok(Y[M8],F)||[]],X[q][F].push([Q,K-G+z+1])})}}match=yZ0;buildAllMatchers(){let J=Object.create(null);return Object.keys(this.#J).concat(Object.keys(this.#$)).forEach((Z)=>{J[Z]||=this.#Z(Z)}),this.#$=this.#J=void 0,tr5(),J}#Z(J){let Z=[],Q=J===M8;if([this.#$,this.#J].forEach((Y)=>{let X=Y[J]?Object.keys(Y[J]).map((K)=>[K,Y[J][K]]):[];if(X.length!==0)Q||=!0,Z.push(...X);else if(J!==M8)Z.push(...Object.keys(Y[M8]).map((K)=>[K,Y[M8][K]]))}),!Q)return null;else return er5(Z)}};mA();var $s5=class{name="PreparedRegExpRouter";#$;#J;constructor(J,Z){this.#$=J,this.#J=Z}#Z(J,Z){let Q=this.#$[J];Q[1].forEach((Y)=>Y&&Y.push(Z)),Object.values(Q[2]).forEach((Y)=>Y[0].push(Z))}#Q(J,Z,Q,Y,X){let K=this.#$[J];if(!X)K[2][Z][0].push([Q,{}]);else Y.forEach((V)=>{if(typeof V==="number")K[1][V].push([Q,X]);else K[2][V||Z][0].push([Q,X])})}add(J,Z,Q){if(!this.#$[J]){let X=this.#$[M8],K={};for(let V in X[2])K[V]=[X[2][V][0].slice(),Ql];this.#$[J]=[X[0],X[1].map((V)=>Array.isArray(V)?V.slice():0),K]}if(Z==="/*"||Z==="*"){let X=[Q,{}];if(J===M8)for(let K in this.#$)this.#Z(K,X);else this.#Z(J,X);return}let Y=this.#J[Z];if(!Y)throw Error(`Path ${Z} is not registered`);for(let[X,K]of Y)if(J===M8)for(let V in this.#$)this.#Q(V,Z,Q,X,K);else this.#Q(J,Z,Q,X,K)}buildAllMatchers(){return this.#$}match=yZ0};mA();var uc0=class{name="SmartRouter";#$=[];#J=[];constructor(J){this.#$=J.routers}add(J,Z,Q){if(!this.#J)throw Error(kZ0);this.#J.push([J,Z,Q])}match(J,Z){if(!this.#J)throw Error("Fatal error");let Q=this.#$,Y=this.#J,X=Q.length,K=0,V;for(;K<X;K++){let z=Q[K];try{for(let G=0,F=Y.length;G<F;G++)z.add(...Y[G]);V=z.match(J,Z)}catch(G){if(G instanceof vZ0)continue;throw G}this.match=z.match.bind(z),this.#$=[z],this.#J=void 0;break}if(K===X)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,V}get activeRouter(){if(this.#J||this.#$.length!==1)throw Error("No active router has been determined yet.");return this.#$[0]}};oN();mA();oN();var Kl=Object.create(null),Js5=(J)=>{for(let Z in J)return!0;return!1},iw4=class J{#$;#J;#Z;#Q=0;#Y=Kl;constructor(Z,Q,Y){if(this.#J=Y||Object.create(null),this.#$=[],Z&&Q){let X=Object.create(null);X[Z]={handler:Q,possibleKeys:[],score:0},this.#$=[X]}this.#Z=[]}insert(Z,Q,Y){this.#Q=++this.#Q;let X=this,K=jw4(Q),V=[];for(let z=0,G=K.length;z<G;z++){let F=K[z],q=K[z+1],W=Rw4(F,q),U=Array.isArray(W)?W[0]:F;if(U in X.#J){if(X=X.#J[U],W)V.push(W[1]);continue}if(X.#J[U]=new J,W)X.#Z.push(W),V.push(W[1]);X=X.#J[U]}return X.#$.push({[Z]:{handler:Y,possibleKeys:V.filter((z,G,F)=>F.indexOf(z)===G),score:this.#Q}}),X}#X(Z,Q,Y,X,K){for(let V=0,z=Q.#$.length;V<z;V++){let G=Q.#$[V],F=G[Y]||G[M8],q={};if(F!==void 0){if(F.params=Object.create(null),Z.push(F),X!==Kl||K&&K!==Kl)for(let W=0,U=F.possibleKeys.length;W<U;W++){let H=F.possibleKeys[W],D=q[F.score];F.params[H]=K?.[H]&&!D?K[H]:X[H]??K?.[H],q[F.score]=!0}}}}search(Z,Q){let Y=[];this.#Y=Kl;let K=[this],V=kc0(Q),z=[],G=V.length,F=null;for(let q=0;q<G;q++){let W=V[q],U=q===G-1,H=[];for(let B=0,N=K.length;B<N;B++){let w=K[B],L=w.#J[W];if(L)if(L.#Y=w.#Y,U){if(L.#J["*"])this.#X(Y,L.#J["*"],Z,w.#Y);this.#X(Y,L,Z,w.#Y)}else H.push(L);for(let O=0,E=w.#Z.length;O<E;O++){let M=w.#Z[O],A=w.#Y===Kl?{}:{...w.#Y};if(M==="*"){let u=w.#J["*"];if(u)this.#X(Y,u,Z,w.#Y),u.#Y=A,H.push(u);continue}let[j,R,_]=M;if(!W&&!(_ instanceof RegExp))continue;let T=w.#J[j];if(_ instanceof RegExp){if(F===null){F=Array(G);let y=Q[0]==="/"?1:0;for(let k=0;k<G;k++)F[k]=y,y+=V[k].length+1}let u=Q.substring(F[q]),m=_.exec(u);if(m){if(A[R]=m[0],this.#X(Y,T,Z,w.#Y,A),Js5(T.#J)){T.#Y=A;let y=m[0].match(/\//)?.length??0;(z[y]||=[]).push(T)}continue}}if(_===!0||_.test(W))if(A[R]=W,U){if(this.#X(Y,T,Z,A,w.#Y),T.#J["*"])this.#X(Y,T.#J["*"],Z,A,w.#Y)}else T.#Y=A,H.push(T)}}let D=z.shift();K=D?H.concat(D):H}if(Y.length>1)Y.sort((q,W)=>{return q.score-W.score});return[Y.map(({handler:q,params:W})=>[q,W])]}};var bc0=class{name="TrieRouter";#$;constructor(){this.#$=new iw4}add(J,Z,Q){let Y=TZ0(Z);if(Y){for(let X=0,K=Y.length;X<K;X++)this.#$.insert(J,Y[X],Q);return}this.#$.insert(J,Z,Q)}match(J,Z){return this.#$.search(J,Z)}};var uZ0=class extends mw4{constructor(J={}){super(J);this.router=J.router??new uc0({routers:[new fZ0,new bc0]})}};oN();t$();_c0(v);var Fe5=B4(wz(),1);import Ys5 from"events";import PQ from"fs";import{EventEmitter as vl0}from"node:events";import RL4 from"node:stream";import{StringDecoder as Xs5}from"node:string_decoder";import CL4 from"node:path";import Tk from"node:fs";import{dirname as ws5,parse as Ls5}from"path";import{EventEmitter as Ps5}from"events";import Hl0 from"assert";import{Buffer as eA}from"buffer";import*as sw4 from"zlib";import Cs5 from"zlib";import{posix as Mk}from"node:path";import{basename as Jt5}from"node:path";import FQ0 from"fs";import Zq from"fs";import YL4 from"path";import{win32 as Wt5}from"node:path";import qL4 from"path";import pL4 from"node:fs";import Tt5 from"node:assert";import{randomBytes as dL4}from"node:crypto";import K3 from"node:fs";import B2 from"node:path";import cL4 from"fs";import OQ0 from"node:fs";import Al from"node:path";import pY from"node:fs";import gt5 from"node:fs/promises";import UQ0 from"node:path";import{join as sL4}from"node:path";import mY from"node:fs";import eL4 from"node:path";var Zs5=Object.defineProperty,Qs5=(J,Z)=>{for(var Q in Z)Zs5(J,Q,{get:Z[Q],enumerable:!0})},nw4=typeof process=="object"&&process?process:{stdout:null,stderr:null},Ks5=(J)=>!!J&&typeof J=="object"&&(J instanceof Zj||J instanceof RL4||Vs5(J)||zs5(J)),Vs5=(J)=>!!J&&typeof J=="object"&&J instanceof vl0&&typeof J.pipe=="function"&&J.pipe!==RL4.Writable.prototype.pipe,zs5=(J)=>!!J&&typeof J=="object"&&J instanceof vl0&&typeof J.write=="function"&&typeof J.end=="function",$H=Symbol("EOF"),JH=Symbol("maybeEmitEnd"),rN=Symbol("emittedEnd"),bZ0=Symbol("emittingEnd"),Vl=Symbol("emittedError"),hZ0=Symbol("closed"),aw4=Symbol("read"),gZ0=Symbol("flush"),ow4=Symbol("flushChunk"),Oz=Symbol("encoding"),Ek=Symbol("decoder"),l2=Symbol("flowing"),zl=Symbol("paused"),Ik=Symbol("resume"),i2=Symbol("buffer"),BZ=Symbol("pipes"),n2=Symbol("bufferLength"),hc0=Symbol("bufferPush"),mZ0=Symbol("bufferShift"),OJ=Symbol("objectMode"),L7=Symbol("destroyed"),gc0=Symbol("error"),mc0=Symbol("emitData"),rw4=Symbol("emitEnd"),pc0=Symbol("emitEnd2"),eF=Symbol("async"),dc0=Symbol("abort"),pZ0=Symbol("aborted"),Gl=Symbol("signal"),dA=Symbol("dataListeners"),gY=Symbol("discarded"),Fl=(J)=>Promise.resolve().then(J),Gs5=(J)=>J(),Fs5=(J)=>J==="end"||J==="finish"||J==="prefinish",qs5=(J)=>J instanceof ArrayBuffer||!!J&&typeof J=="object"&&J.constructor&&J.constructor.name==="ArrayBuffer"&&J.byteLength>=0,Ws5=(J)=>!Buffer.isBuffer(J)&&ArrayBuffer.isView(J),IL4=class{src;dest;opts;ondrain;constructor(J,Z,Q){this.src=J,this.dest=Z,this.opts=Q,this.ondrain=()=>J[Ik](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(J){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Us5=class extends IL4{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(J,Z,Q){super(J,Z,Q),this.proxyErrors=(Y)=>this.dest.emit("error",Y),J.on("error",this.proxyErrors)}},Hs5=(J)=>!!J.objectMode,Ds5=(J)=>!J.objectMode&&!!J.encoding&&J.encoding!=="buffer",Zj=class extends vl0{[l2]=!1;[zl]=!1;[BZ]=[];[i2]=[];[OJ];[Oz];[eF];[Ek];[$H]=!1;[rN]=!1;[bZ0]=!1;[hZ0]=!1;[Vl]=null;[n2]=0;[L7]=!1;[Gl];[pZ0]=!1;[dA]=0;[gY]=!1;writable=!0;readable=!0;constructor(...J){let Z=J[0]||{};if(super(),Z.objectMode&&typeof Z.encoding=="string")throw TypeError("Encoding and objectMode may not be used together");Hs5(Z)?(this[OJ]=!0,this[Oz]=null):Ds5(Z)?(this[Oz]=Z.encoding,this[OJ]=!1):(this[OJ]=!1,this[Oz]=null),this[eF]=!!Z.async,this[Ek]=this[Oz]?new Xs5(this[Oz]):null,Z&&Z.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[i2]}),Z&&Z.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[BZ]});let{signal:Q}=Z;Q&&(this[Gl]=Q,Q.aborted?this[dc0]():Q.addEventListener("abort",()=>this[dc0]()))}get bufferLength(){return this[n2]}get encoding(){return this[Oz]}set encoding(J){throw Error("Encoding must be set at instantiation time")}setEncoding(J){throw Error("Encoding must be set at instantiation time")}get objectMode(){return this[OJ]}set objectMode(J){throw Error("objectMode must be set at instantiation time")}get async(){return this[eF]}set async(J){this[eF]=this[eF]||!!J}[dc0](){this[pZ0]=!0,this.emit("abort",this[Gl]?.reason),this.destroy(this[Gl]?.reason)}get aborted(){return this[pZ0]}set aborted(J){}write(J,Z,Q){if(this[pZ0])return!1;if(this[$H])throw Error("write after end");if(this[L7])return this.emit("error",Object.assign(Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof Z=="function"&&(Q=Z,Z="utf8"),Z||(Z="utf8");let Y=this[eF]?Fl:Gs5;if(!this[OJ]&&!Buffer.isBuffer(J)){if(Ws5(J))J=Buffer.from(J.buffer,J.byteOffset,J.byteLength);else if(qs5(J))J=Buffer.from(J);else if(typeof J!="string")throw Error("Non-contiguous data written to non-objectMode stream")}return this[OJ]?(this[l2]&&this[n2]!==0&&this[gZ0](!0),this[l2]?this.emit("data",J):this[hc0](J),this[n2]!==0&&this.emit("readable"),Q&&Y(Q),this[l2]):J.length?(typeof J=="string"&&!(Z===this[Oz]&&!this[Ek]?.lastNeed)&&(J=Buffer.from(J,Z)),Buffer.isBuffer(J)&&this[Oz]&&(J=this[Ek].write(J)),this[l2]&&this[n2]!==0&&this[gZ0](!0),this[l2]?this.emit("data",J):this[hc0](J),this[n2]!==0&&this.emit("readable"),Q&&Y(Q),this[l2]):(this[n2]!==0&&this.emit("readable"),Q&&Y(Q),this[l2])}read(J){if(this[L7])return null;if(this[gY]=!1,this[n2]===0||J===0||J&&J>this[n2])return this[JH](),null;this[OJ]&&(J=null),this[i2].length>1&&!this[OJ]&&(this[i2]=[this[Oz]?this[i2].join(""):Buffer.concat(this[i2],this[n2])]);let Z=this[aw4](J||null,this[i2][0]);return this[JH](),Z}[aw4](J,Z){if(this[OJ])this[mZ0]();else{let Q=Z;J===Q.length||J===null?this[mZ0]():typeof Q=="string"?(this[i2][0]=Q.slice(J),Z=Q.slice(0,J),this[n2]-=J):(this[i2][0]=Q.subarray(J),Z=Q.subarray(0,J),this[n2]-=J)}return this.emit("data",Z),!this[i2].length&&!this[$H]&&this.emit("drain"),Z}end(J,Z,Q){return typeof J=="function"&&(Q=J,J=void 0),typeof Z=="function"&&(Q=Z,Z="utf8"),J!==void 0&&this.write(J,Z),Q&&this.once("end",Q),this[$H]=!0,this.writable=!1,(this[l2]||!this[zl])&&this[JH](),this}[Ik](){this[L7]||(!this[dA]&&!this[BZ].length&&(this[gY]=!0),this[zl]=!1,this[l2]=!0,this.emit("resume"),this[i2].length?this[gZ0]():this[$H]?this[JH]():this.emit("drain"))}resume(){return this[Ik]()}pause(){this[l2]=!1,this[zl]=!0,this[gY]=!1}get destroyed(){return this[L7]}get flowing(){return this[l2]}get paused(){return this[zl]}[hc0](J){this[OJ]?this[n2]+=1:this[n2]+=J.length,this[i2].push(J)}[mZ0](){return this[OJ]?this[n2]-=1:this[n2]-=this[i2][0].length,this[i2].shift()}[gZ0](J=!1){do;while(this[ow4](this[mZ0]())&&this[i2].length);!J&&!this[i2].length&&!this[$H]&&this.emit("drain")}[ow4](J){return this.emit("data",J),this[l2]}pipe(J,Z){if(this[L7])return J;this[gY]=!1;let Q=this[rN];return Z=Z||{},J===nw4.stdout||J===nw4.stderr?Z.end=!1:Z.end=Z.end!==!1,Z.proxyErrors=!!Z.proxyErrors,Q?Z.end&&J.end():(this[BZ].push(Z.proxyErrors?new Us5(this,J,Z):new IL4(this,J,Z)),this[eF]?Fl(()=>this[Ik]()):this[Ik]()),J}unpipe(J){let Z=this[BZ].find((Q)=>Q.dest===J);Z&&(this[BZ].length===1?(this[l2]&&this[dA]===0&&(this[l2]=!1),this[BZ]=[]):this[BZ].splice(this[BZ].indexOf(Z),1),Z.unpipe())}addListener(J,Z){return this.on(J,Z)}on(J,Z){let Q=super.on(J,Z);if(J==="data")this[gY]=!1,this[dA]++,!this[BZ].length&&!this[l2]&&this[Ik]();else if(J==="readable"&&this[n2]!==0)super.emit("readable");else if(Fs5(J)&&this[rN])super.emit(J),this.removeAllListeners(J);else if(J==="error"&&this[Vl]){let Y=Z;this[eF]?Fl(()=>Y.call(this,this[Vl])):Y.call(this,this[Vl])}return Q}removeListener(J,Z){return this.off(J,Z)}off(J,Z){let Q=super.off(J,Z);return J==="data"&&(this[dA]=this.listeners("data").length,this[dA]===0&&!this[gY]&&!this[BZ].length&&(this[l2]=!1)),Q}removeAllListeners(J){let Z=super.removeAllListeners(J);return(J==="data"||J===void 0)&&(this[dA]=0,!this[gY]&&!this[BZ].length&&(this[l2]=!1)),Z}get emittedEnd(){return this[rN]}[JH](){!this[bZ0]&&!this[rN]&&!this[L7]&&this[i2].length===0&&this[$H]&&(this[bZ0]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[hZ0]&&this.emit("close"),this[bZ0]=!1)}emit(J,...Z){let Q=Z[0];if(J!=="error"&&J!=="close"&&J!==L7&&this[L7])return!1;if(J==="data")return!this[OJ]&&!Q?!1:this[eF]?(Fl(()=>this[mc0](Q)),!0):this[mc0](Q);if(J==="end")return this[rw4]();if(J==="close"){if(this[hZ0]=!0,!this[rN]&&!this[L7])return!1;let X=super.emit("close");return this.removeAllListeners("close"),X}else if(J==="error"){this[Vl]=Q,super.emit(gc0,Q);let X=!this[Gl]||this.listeners("error").length?super.emit("error",Q):!1;return this[JH](),X}else if(J==="resume"){let X=super.emit("resume");return this[JH](),X}else if(J==="finish"||J==="prefinish"){let X=super.emit(J);return this.removeAllListeners(J),X}let Y=super.emit(J,...Z);return this[JH](),Y}[mc0](J){for(let Q of this[BZ])Q.dest.write(J)===!1&&this.pause();let Z=this[gY]?!1:super.emit("data",J);return this[JH](),Z}[rw4](){return this[rN]?!1:(this[rN]=!0,this.readable=!1,this[eF]?(Fl(()=>this[pc0]()),!0):this[pc0]())}[pc0](){if(this[Ek]){let Z=this[Ek].end();if(Z){for(let Q of this[BZ])Q.dest.write(Z);this[gY]||super.emit("data",Z)}}for(let Z of this[BZ])Z.end();let J=super.emit("end");return this.removeAllListeners("end"),J}async collect(){let J=Object.assign([],{dataLength:0});this[OJ]||(J.dataLength=0);let Z=this.promise();return this.on("data",(Q)=>{J.push(Q),this[OJ]||(J.dataLength+=Q.length)}),await Z,J}async concat(){if(this[OJ])throw Error("cannot concat in objectMode");let J=await this.collect();return this[Oz]?J.join(""):Buffer.concat(J,J.dataLength)}async promise(){return new Promise((J,Z)=>{this.on(L7,()=>Z(Error("stream destroyed"))),this.on("error",(Q)=>Z(Q)),this.on("end",()=>J())})}[Symbol.asyncIterator](){this[gY]=!1;let J=!1,Z=async()=>(this.pause(),J=!0,{value:void 0,done:!0});return{next:()=>{if(J)return Z();let Q=this.read();if(Q!==null)return Promise.resolve({done:!1,value:Q});if(this[$H])return Z();let Y,X,K=(F)=>{this.off("data",V),this.off("end",z),this.off(L7,G),Z(),X(F)},V=(F)=>{this.off("error",K),this.off("end",z),this.off(L7,G),this.pause(),Y({value:F,done:!!this[$H]})},z=()=>{this.off("error",K),this.off("data",V),this.off(L7,G),Z(),Y({done:!0,value:void 0})},G=()=>K(Error("stream destroyed"));return new Promise((F,q)=>{X=q,Y=F,this.once(L7,G),this.once("error",K),this.once("end",z),this.once("data",V)})},throw:Z,return:Z,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[gY]=!1;let J=!1,Z=()=>(this.pause(),this.off(gc0,Z),this.off(L7,Z),this.off("end",Z),J=!0,{done:!0,value:void 0}),Q=()=>{if(J)return Z();let Y=this.read();return Y===null?Z():{done:!1,value:Y}};return this.once("end",Z),this.once(gc0,Z),this.once(L7,Z),{next:Q,throw:Z,return:Z,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(J){if(this[L7])return J?this.emit("error",J):this.emit(L7),this;this[L7]=!0,this[gY]=!0,this[i2].length=0,this[n2]=0;let Z=this;return typeof Z.close=="function"&&!this[hZ0]&&Z.close(),J?this.emit("error",J):this.emit(L7),this}static get isStream(){return Ks5}},Bs5=PQ.writev,Xw=Symbol("_autoClose"),jz=Symbol("_close"),ql=Symbol("_ended"),x3=Symbol("_fd"),cc0=Symbol("_finished"),XH=Symbol("_flags"),lc0=Symbol("_flush"),Wl0=Symbol("_handleChunk"),Ul0=Symbol("_makeBuf"),El=Symbol("_mode"),dZ0=Symbol("_needDrain"),_k=Symbol("_onerror"),Sk=Symbol("_onopen"),ic0=Symbol("_onread"),Pk=Symbol("_onwrite"),Kw=Symbol("_open"),Az=Symbol("_path"),$w=Symbol("_pos"),$q=Symbol("_queue"),Ck=Symbol("_read"),nc0=Symbol("_readSize"),YH=Symbol("_reading"),Wl=Symbol("_remain"),ac0=Symbol("_size"),tZ0=Symbol("_write"),cA=Symbol("_writing"),eZ0=Symbol("_defaultFlag"),tA=Symbol("_errored"),yl0=class extends Zj{[tA]=!1;[x3];[Az];[nc0];[YH]=!1;[ac0];[Wl];[Xw];constructor(J,Z){if(Z=Z||{},super(Z),this.readable=!0,this.writable=!1,typeof J!="string")throw TypeError("path must be a string");this[tA]=!1,this[x3]=typeof Z.fd=="number"?Z.fd:void 0,this[Az]=J,this[nc0]=Z.readSize||16777216,this[YH]=!1,this[ac0]=typeof Z.size=="number"?Z.size:1/0,this[Wl]=this[ac0],this[Xw]=typeof Z.autoClose=="boolean"?Z.autoClose:!0,typeof this[x3]=="number"?this[Ck]():this[Kw]()}get fd(){return this[x3]}get path(){return this[Az]}write(){throw TypeError("this is a readable stream")}end(){throw TypeError("this is a readable stream")}[Kw](){PQ.open(this[Az],"r",(J,Z)=>this[Sk](J,Z))}[Sk](J,Z){J?this[_k](J):(this[x3]=Z,this.emit("open",Z),this[Ck]())}[Ul0](){return Buffer.allocUnsafe(Math.min(this[nc0],this[Wl]))}[Ck](){if(!this[YH]){this[YH]=!0;let J=this[Ul0]();if(J.length===0)return process.nextTick(()=>this[ic0](null,0,J));PQ.read(this[x3],J,0,J.length,null,(Z,Q,Y)=>this[ic0](Z,Q,Y))}}[ic0](J,Z,Q){this[YH]=!1,J?this[_k](J):this[Wl0](Z,Q)&&this[Ck]()}[jz](){if(this[Xw]&&typeof this[x3]=="number"){let J=this[x3];this[x3]=void 0,PQ.close(J,(Z)=>Z?this.emit("error",Z):this.emit("close"))}}[_k](J){this[YH]=!0,this[jz](),this.emit("error",J)}[Wl0](J,Z){let Q=!1;return this[Wl]-=J,J>0&&(Q=super.write(J<Z.length?Z.subarray(0,J):Z)),(J===0||this[Wl]<=0)&&(Q=!1,this[jz](),super.end()),Q}emit(J,...Z){switch(J){case"prefinish":case"finish":return!1;case"drain":return typeof this[x3]=="number"&&this[Ck](),!1;case"error":return this[tA]?!1:(this[tA]=!0,super.emit(J,...Z));default:return super.emit(J,...Z)}}},Ns5=class extends yl0{[Kw](){let J=!0;try{this[Sk](null,PQ.openSync(this[Az],"r")),J=!1}finally{J&&this[jz]()}}[Ck](){let J=!0;try{if(!this[YH]){this[YH]=!0;do{let Z=this[Ul0](),Q=Z.length===0?0:PQ.readSync(this[x3],Z,0,Z.length,null);if(!this[Wl0](Q,Z))break}while(!0);this[YH]=!1}J=!1}finally{J&&this[jz]()}}[jz](){if(this[Xw]&&typeof this[x3]=="number"){let J=this[x3];this[x3]=void 0,PQ.closeSync(J),this.emit("close")}}},HQ0=class extends Ys5{readable=!1;writable=!0;[tA]=!1;[cA]=!1;[ql]=!1;[$q]=[];[dZ0]=!1;[Az];[El];[Xw];[x3];[eZ0];[XH];[cc0]=!1;[$w];constructor(J,Z){Z=Z||{},super(Z),this[Az]=J,this[x3]=typeof Z.fd=="number"?Z.fd:void 0,this[El]=Z.mode===void 0?438:Z.mode,this[$w]=typeof Z.start=="number"?Z.start:void 0,this[Xw]=typeof Z.autoClose=="boolean"?Z.autoClose:!0;let Q=this[$w]!==void 0?"r+":"w";this[eZ0]=Z.flags===void 0,this[XH]=Z.flags===void 0?Q:Z.flags,this[x3]===void 0&&this[Kw]()}emit(J,...Z){if(J==="error"){if(this[tA])return!1;this[tA]=!0}return super.emit(J,...Z)}get fd(){return this[x3]}get path(){return this[Az]}[_k](J){this[jz](),this[cA]=!0,this.emit("error",J)}[Kw](){PQ.open(this[Az],this[XH],this[El],(J,Z)=>this[Sk](J,Z))}[Sk](J,Z){this[eZ0]&&this[XH]==="r+"&&J&&J.code==="ENOENT"?(this[XH]="w",this[Kw]()):J?this[_k](J):(this[x3]=Z,this.emit("open",Z),this[cA]||this[lc0]())}end(J,Z){return J&&this.write(J,Z),this[ql]=!0,!this[cA]&&!this[$q].length&&typeof this[x3]=="number"&&this[Pk](null,0),this}write(J,Z){return typeof J=="string"&&(J=Buffer.from(J,Z)),this[ql]?(this.emit("error",Error("write() after end()")),!1):this[x3]===void 0||this[cA]||this[$q].length?(this[$q].push(J),this[dZ0]=!0,!1):(this[cA]=!0,this[tZ0](J),!0)}[tZ0](J){PQ.write(this[x3],J,0,J.length,this[$w],(Z,Q)=>this[Pk](Z,Q))}[Pk](J,Z){J?this[_k](J):(this[$w]!==void 0&&typeof Z=="number"&&(this[$w]+=Z),this[$q].length?this[lc0]():(this[cA]=!1,this[ql]&&!this[cc0]?(this[cc0]=!0,this[jz](),this.emit("finish")):this[dZ0]&&(this[dZ0]=!1,this.emit("drain"))))}[lc0](){if(this[$q].length===0)this[ql]&&this[Pk](null,0);else if(this[$q].length===1)this[tZ0](this[$q].pop());else{let J=this[$q];this[$q]=[],Bs5(this[x3],J,this[$w],(Z,Q)=>this[Pk](Z,Q))}}[jz](){if(this[Xw]&&typeof this[x3]=="number"){let J=this[x3];this[x3]=void 0,PQ.close(J,(Z)=>Z?this.emit("error",Z):this.emit("close"))}}},PL4=class extends HQ0{[Kw](){let J;if(this[eZ0]&&this[XH]==="r+")try{J=PQ.openSync(this[Az],this[XH],this[El])}catch(Z){if(Z?.code==="ENOENT")return this[XH]="w",this[Kw]();throw Z}else J=PQ.openSync(this[Az],this[XH],this[El]);this[Sk](null,J)}[jz](){if(this[Xw]&&typeof this[x3]=="number"){let J=this[x3];this[x3]=void 0,PQ.closeSync(J),this.emit("close")}}[tZ0](J){let Z=!0;try{this[Pk](null,PQ.writeSync(this[x3],J,0,J.length,this[$w])),Z=!1}finally{if(Z)try{this[jz]()}catch{}}}},Os5=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"],["onentry","onReadEntry"]]),Es5=(J)=>!!J.sync&&!!J.file,Ms5=(J)=>!J.sync&&!!J.file,As5=(J)=>!!J.sync&&!J.file,js5=(J)=>!J.sync&&!J.file,Rs5=(J)=>!!J.file,Is5=(J)=>{return Os5.get(J)||J},xl0=(J={})=>{if(!J)return{};let Z={};for(let[Q,Y]of Object.entries(J)){let X=Is5(Q);Z[X]=Y}return Z.chmod===void 0&&Z.noChmod===!1&&(Z.chmod=!0),delete Z.noChmod,Z},_l=(J,Z,Q,Y,X)=>Object.assign((K=[],V,z)=>{Array.isArray(K)&&(V=K,K={}),typeof V=="function"&&(z=V,V=void 0),V?V=Array.from(V):V=[];let G=xl0(K);if(X?.(G,V),Es5(G)){if(typeof z=="function")throw TypeError("callback not supported for sync tar functions");return J(G,V)}else if(Ms5(G)){let F=Z(G,V),q=z||void 0;return q?F.then(()=>q(),q):F}else if(As5(G)){if(typeof z=="function")throw TypeError("callback not supported for sync tar functions");return Q(G,V)}else if(js5(G)){if(typeof z=="function")throw TypeError("callback only supported with file option");return Y(G,V)}else throw Error("impossible options??")},{syncFile:J,asyncFile:Z,syncNoFile:Q,asyncNoFile:Y,validate:X}),Ts5=Cs5.constants||{ZLIB_VERNUM:4736},Yq=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},Ts5)),_s5=eA.concat,tw4=Object.getOwnPropertyDescriptor(eA,"concat"),Ss5=(J)=>J,oc0=tw4?.writable===!0||tw4?.set!==void 0?(J)=>{eA.concat=J?Ss5:_s5}:(J)=>{},$j=Symbol("_superWrite"),cZ0=class extends Error{code;errno;constructor(J,Z){super("zlib: "+J.message,{cause:J}),this.code=J.code,this.errno=J.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+J.message,Error.captureStackTrace(this,Z??this.constructor)}get name(){return"ZlibError"}},rc0=Symbol("flushFlag"),fl0=class extends Zj{#$=!1;#J=!1;#Z;#Q;#Y;#X;#V;get sawError(){return this.#$}get handle(){return this.#X}get flushFlag(){return this.#Z}constructor(J,Z){if(!J||typeof J!="object")throw TypeError("invalid options for ZlibBase constructor");if(super(J),this.#Z=J.flush??0,this.#Q=J.finishFlush??0,this.#Y=J.fullFlushFlag??0,typeof sw4[Z]!="function")throw TypeError("Compression method not supported: "+Z);try{this.#X=new sw4[Z](J)}catch(Q){throw new cZ0(Q,this.constructor)}this.#V=(Q)=>{this.#$||(this.#$=!0,this.close(),this.emit("error",Q))},this.#X?.on("error",(Q)=>this.#V(new cZ0(Q))),this.once("end",()=>this.close)}close(){this.#X&&(this.#X.close(),this.#X=void 0,this.emit("close"))}reset(){if(!this.#$)return Hl0(this.#X,"zlib binding closed"),this.#X.reset?.()}flush(J){this.ended||(typeof J!="number"&&(J=this.#Y),this.write(Object.assign(eA.alloc(0),{[rc0]:J})))}end(J,Z,Q){return typeof J=="function"&&(Q=J,Z=void 0,J=void 0),typeof Z=="function"&&(Q=Z,Z=void 0),J&&(Z?this.write(J,Z):this.write(J)),this.flush(this.#Q),this.#J=!0,super.end(Q)}get ended(){return this.#J}[$j](J){return super.write(J)}write(J,Z,Q){if(typeof Z=="function"&&(Q=Z,Z="utf8"),typeof J=="string"&&(J=eA.from(J,Z)),this.#$)return;Hl0(this.#X,"zlib binding closed");let Y=this.#X._handle,X=Y.close;Y.close=()=>{};let K=this.#X.close;this.#X.close=()=>{},oc0(!0);let V;try{let G=typeof J[rc0]=="number"?J[rc0]:this.#Z;V=this.#X._processChunk(J,G),oc0(!1)}catch(G){oc0(!1),this.#V(new cZ0(G,this.write))}finally{this.#X&&(this.#X._handle=Y,Y.close=X,this.#X.close=K,this.#X.removeAllListeners("error"))}this.#X&&this.#X.on("error",(G)=>this.#V(new cZ0(G,this.write)));let z;if(V)if(Array.isArray(V)&&V.length>0){let G=V[0];z=this[$j](eA.from(G));for(let F=1;F<V.length;F++)z=this[$j](V[F])}else z=this[$j](eA.from(V));return Q&&Q(),z}},TL4=class extends fl0{#$;#J;constructor(J,Z){J=J||{},J.flush=J.flush||Yq.Z_NO_FLUSH,J.finishFlush=J.finishFlush||Yq.Z_FINISH,J.fullFlushFlag=Yq.Z_FULL_FLUSH,super(J,Z),this.#$=J.level,this.#J=J.strategy}params(J,Z){if(!this.sawError){if(!this.handle)throw Error("cannot switch params when binding is closed");if(!this.handle.params)throw Error("not supported in this implementation");if(this.#$!==J||this.#J!==Z){this.flush(Yq.Z_SYNC_FLUSH),Hl0(this.handle,"zlib binding closed");let Q=this.handle.flush;this.handle.flush=(Y,X)=>{typeof Y=="function"&&(X=Y,Y=this.flushFlag),this.flush(Y),X?.()};try{this.handle.params(J,Z)}finally{this.handle.flush=Q}this.handle&&(this.#$=J,this.#J=Z)}}}},ks5=class extends TL4{#$;constructor(J){super(J,"Gzip"),this.#$=J&&!!J.portable}[$j](J){return this.#$?(this.#$=!1,J[9]=255,super[$j](J)):super[$j](J)}},vs5=class extends TL4{constructor(J){super(J,"Unzip")}},_L4=class extends fl0{constructor(J,Z){J=J||{},J.flush=J.flush||Yq.BROTLI_OPERATION_PROCESS,J.finishFlush=J.finishFlush||Yq.BROTLI_OPERATION_FINISH,J.fullFlushFlag=Yq.BROTLI_OPERATION_FLUSH,super(J,Z)}},ys5=class extends _L4{constructor(J){super(J,"BrotliCompress")}},xs5=class extends _L4{constructor(J){super(J,"BrotliDecompress")}},SL4=class extends fl0{constructor(J,Z){J=J||{},J.flush=J.flush||Yq.ZSTD_e_continue,J.finishFlush=J.finishFlush||Yq.ZSTD_e_end,J.fullFlushFlag=Yq.ZSTD_e_flush,super(J,Z)}},fs5=class extends SL4{constructor(J){super(J,"ZstdCompress")}},us5=class extends SL4{constructor(J){super(J,"ZstdDecompress")}},bs5=(J,Z)=>{if(Number.isSafeInteger(J))J<0?gs5(J,Z):hs5(J,Z);else throw Error("cannot encode number outside of javascript safe integer range");return Z},hs5=(J,Z)=>{Z[0]=128;for(var Q=Z.length;Q>1;Q--)Z[Q-1]=J&255,J=Math.floor(J/256)},gs5=(J,Z)=>{Z[0]=255;var Q=!1;J=J*-1;for(var Y=Z.length;Y>1;Y--){var X=J&255;J=Math.floor(J/256),Q?Z[Y-1]=kL4(X):X===0?Z[Y-1]=0:(Q=!0,Z[Y-1]=vL4(X))}},ms5=(J)=>{let Z=J[0],Q=Z===128?ds5(J.subarray(1,J.length)):Z===255?ps5(J):null;if(Q===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(Q))throw Error("parsed number outside of javascript safe integer range");return Q},ps5=(J)=>{for(var Z=J.length,Q=0,Y=!1,X=Z-1;X>-1;X--){var K=Number(J[X]),V;Y?V=kL4(K):K===0?V=K:(Y=!0,V=vL4(K)),V!==0&&(Q-=V*Math.pow(256,Z-X-1))}return Q},ds5=(J)=>{for(var Z=J.length,Q=0,Y=Z-1;Y>-1;Y--){var X=Number(J[Y]);X!==0&&(Q+=X*Math.pow(256,Z-Y-1))}return Q},kL4=(J)=>(255^J)&255,vL4=(J)=>(255^J)+1&255,cs5={};Qs5(cs5,{code:()=>ul0,isCode:()=>$Q0,isName:()=>ls5,name:()=>DQ0});var $Q0=(J)=>DQ0.has(J),ls5=(J)=>ul0.has(J),DQ0=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),ul0=new Map(Array.from(DQ0).map((J)=>[J[1],J[0]])),Jj=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#$="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(J,Z=0,Q,Y){Buffer.isBuffer(J)?this.decode(J,Z||0,Q,Y):J&&this.#J(J)}decode(J,Z,Q,Y){if(Z||(Z=0),!J||!(J.length>=Z+512))throw Error("need 512 bytes for header");this.path=Q?.path??lA(J,Z,100),this.mode=Q?.mode??Y?.mode??Jw(J,Z+100,8),this.uid=Q?.uid??Y?.uid??Jw(J,Z+108,8),this.gid=Q?.gid??Y?.gid??Jw(J,Z+116,8),this.size=Q?.size??Y?.size??Jw(J,Z+124,12),this.mtime=Q?.mtime??Y?.mtime??sc0(J,Z+136,12),this.cksum=Jw(J,Z+148,12),Y&&this.#J(Y,!0),Q&&this.#J(Q);let X=lA(J,Z+156,1);if($Q0(X)&&(this.#$=X||"0"),this.#$==="0"&&this.path.slice(-1)==="/"&&(this.#$="5"),this.#$==="5"&&(this.size=0),this.linkpath=lA(J,Z+157,100),J.subarray(Z+257,Z+265).toString()==="ustar\x0000")if(this.uname=Q?.uname??Y?.uname??lA(J,Z+265,32),this.gname=Q?.gname??Y?.gname??lA(J,Z+297,32),this.devmaj=Q?.devmaj??Y?.devmaj??Jw(J,Z+329,8)??0,this.devmin=Q?.devmin??Y?.devmin??Jw(J,Z+337,8)??0,J[Z+475]!==0){let V=lA(J,Z+345,155);this.path=V+"/"+this.path}else{let V=lA(J,Z+345,130);V&&(this.path=V+"/"+this.path),this.atime=Q?.atime??Y?.atime??sc0(J,Z+476,12),this.ctime=Q?.ctime??Y?.ctime??sc0(J,Z+488,12)}let K=256;for(let V=Z;V<Z+148;V++)K+=J[V];for(let V=Z+156;V<Z+512;V++)K+=J[V];this.cksumValid=K===this.cksum,this.cksum===void 0&&K===256&&(this.nullBlock=!0)}#J(J,Z=!1){Object.assign(this,Object.fromEntries(Object.entries(J).filter(([Q,Y])=>!(Y==null||Q==="path"&&Z||Q==="linkpath"&&Z||Q==="global"))))}encode(J,Z=0){if(J||(J=this.block=Buffer.alloc(512)),this.#$==="Unsupported"&&(this.#$="0"),!(J.length>=Z+512))throw Error("need 512 bytes for header");let Q=this.ctime||this.atime?130:155,Y=is5(this.path||"",Q),X=Y[0],K=Y[1];this.needPax=!!Y[2],this.needPax=iA(J,Z,100,X)||this.needPax,this.needPax=Zw(J,Z+100,8,this.mode)||this.needPax,this.needPax=Zw(J,Z+108,8,this.uid)||this.needPax,this.needPax=Zw(J,Z+116,8,this.gid)||this.needPax,this.needPax=Zw(J,Z+124,12,this.size)||this.needPax,this.needPax=tc0(J,Z+136,12,this.mtime)||this.needPax,J[Z+156]=this.#$.charCodeAt(0),this.needPax=iA(J,Z+157,100,this.linkpath)||this.needPax,J.write("ustar\x0000",Z+257,8),this.needPax=iA(J,Z+265,32,this.uname)||this.needPax,this.needPax=iA(J,Z+297,32,this.gname)||this.needPax,this.needPax=Zw(J,Z+329,8,this.devmaj)||this.needPax,this.needPax=Zw(J,Z+337,8,this.devmin)||this.needPax,this.needPax=iA(J,Z+345,Q,K)||this.needPax,J[Z+475]!==0?this.needPax=iA(J,Z+345,155,K)||this.needPax:(this.needPax=iA(J,Z+345,130,K)||this.needPax,this.needPax=tc0(J,Z+476,12,this.atime)||this.needPax,this.needPax=tc0(J,Z+488,12,this.ctime)||this.needPax);let V=256;for(let z=Z;z<Z+148;z++)V+=J[z];for(let z=Z+156;z<Z+512;z++)V+=J[z];return this.cksum=V,Zw(J,Z+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#$==="Unsupported"?this.#$:DQ0.get(this.#$)}get typeKey(){return this.#$}set type(J){let Z=String(ul0.get(J));if($Q0(Z)||Z==="Unsupported")this.#$=Z;else if($Q0(J))this.#$=J;else throw TypeError("invalid entry type: "+J)}},is5=(J,Z)=>{let Q=J,Y="",X,K=Mk.parse(J).root||".";if(Buffer.byteLength(Q)<100)X=[Q,Y,!1];else{Y=Mk.dirname(Q),Q=Mk.basename(Q);do Buffer.byteLength(Q)<=100&&Buffer.byteLength(Y)<=Z?X=[Q,Y,!1]:Buffer.byteLength(Q)>100&&Buffer.byteLength(Y)<=Z?X=[Q.slice(0,99),Y,!0]:(Q=Mk.join(Mk.basename(Y),Q),Y=Mk.dirname(Y));while(Y!==K&&X===void 0);X||(X=[J.slice(0,99),"",!0])}return X},lA=(J,Z,Q)=>J.subarray(Z,Z+Q).toString("utf8").replace(/\0.*/,""),sc0=(J,Z,Q)=>ns5(Jw(J,Z,Q)),ns5=(J)=>J===void 0?void 0:new Date(J*1000),Jw=(J,Z,Q)=>Number(J[Z])&128?ms5(J.subarray(Z,Z+Q)):os5(J,Z,Q),as5=(J)=>isNaN(J)?void 0:J,os5=(J,Z,Q)=>as5(parseInt(J.subarray(Z,Z+Q).toString("utf8").replace(/\0.*$/,"").trim(),8)),rs5={12:8589934591,8:2097151},Zw=(J,Z,Q,Y)=>Y===void 0?!1:Y>rs5[Q]||Y<0?(bs5(Y,J.subarray(Z,Z+Q)),!0):(ss5(J,Z,Q,Y),!1),ss5=(J,Z,Q,Y)=>J.write(ts5(Y,Q),Z,Q,"ascii"),ts5=(J,Z)=>es5(Math.floor(J).toString(8),Z),es5=(J,Z)=>(J.length===Z-1?J:Array(Z-J.length-1).join("0")+J+" ")+"\x00",tc0=(J,Z,Q,Y)=>Y===void 0?!1:Zw(J,Z,Q,Y.getTime()/1000),$t5=Array(156).join("\x00"),iA=(J,Z,Q,Y)=>Y===void 0?!1:(J.write(Y+$t5,Z,Q,"utf8"),Y.length!==Buffer.byteLength(Y)||Y.length>Q),GQ0=class J{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(Z,Q=!1){this.atime=Z.atime,this.charset=Z.charset,this.comment=Z.comment,this.ctime=Z.ctime,this.dev=Z.dev,this.gid=Z.gid,this.global=Q,this.gname=Z.gname,this.ino=Z.ino,this.linkpath=Z.linkpath,this.mtime=Z.mtime,this.nlink=Z.nlink,this.path=Z.path,this.size=Z.size,this.uid=Z.uid,this.uname=Z.uname}encode(){let Z=this.encodeBody();if(Z==="")return Buffer.allocUnsafe(0);let Q=Buffer.byteLength(Z),Y=512*Math.ceil(1+Q/512),X=Buffer.allocUnsafe(Y);for(let K=0;K<512;K++)X[K]=0;new Jj({path:("PaxHeader/"+Jt5(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:Q,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(X),X.write(Z,512,Q,"utf8");for(let K=Q+512;K<X.length;K++)X[K]=0;return X}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(Z){if(this[Z]===void 0)return"";let Q=this[Z],Y=Q instanceof Date?Q.getTime()/1000:Q,X=" "+(Z==="dev"||Z==="ino"||Z==="nlink"?"SCHILY.":"")+Z+"="+Y+`
|
|
4666
4666
|
`,K=Buffer.byteLength(X),V=Math.floor(Math.log(K)/Math.log(10))+1;return K+V>=Math.pow(10,V)&&(V+=1),V+K+X}static parse(Z,Q,Y=!1){return new J(Zt5(Qt5(Z),Q),Y)}},Zt5=(J,Z)=>Z?Object.assign({},Z,J):J,Qt5=(J)=>J.replace(/\n$/,"").split(`
|
|
4667
|
-
`).reduce(Yt5,Object.create(null)),Yt5=(J,Z)=>{let Q=parseInt(Z,10);if(Q!==Buffer.byteLength(Z)+1)return J;Z=Z.slice((Q+" ").length);let Y=Z.split("="),X=Y.shift();if(!X)return J;let K=X.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),V=Y.join("=");return J[K]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(K)?new Date(Number(V)*1000):/^[0-9]+$/.test(V)?+V:V,J},Xt5=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,A5=Xt5!=="win32"?(J)=>J:(J)=>J&&J.replace(/\\/g,"/"),yL4=class extends Zj{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(J,Z,Q){switch(super({}),this.pause(),this.extended=Z,this.globalExtended=Q,this.header=J,this.remain=J.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=J.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!J.path)throw Error("no path provided for tar.ReadEntry");this.path=A5(J.path),this.mode=J.mode,this.mode&&(this.mode=this.mode&4095),this.uid=J.uid,this.gid=J.gid,this.uname=J.uname,this.gname=J.gname,this.size=this.remain,this.mtime=J.mtime,this.atime=J.atime,this.ctime=J.ctime,this.linkpath=J.linkpath?A5(J.linkpath):void 0,this.uname=J.uname,this.gname=J.gname,Z&&this.#$(Z),Q&&this.#$(Q,!0)}write(J){let Z=J.length;if(Z>this.blockRemain)throw Error("writing more to entry than is appropriate");let Q=this.remain,Y=this.blockRemain;return this.remain=Math.max(0,Q-Z),this.blockRemain=Math.max(0,Y-Z),this.ignore?!0:Q>=Z?super.write(J):super.write(J.subarray(0,Q))}#$(J,Z=!1){J.path&&(J.path=A5(J.path)),J.linkpath&&(J.linkpath=A5(J.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(J).filter(([Q,Y])=>!(Y==null||Q==="path"&&Z))))}},BQ0=(J,Z,Q,Y={})=>{J.file&&(Y.file=J.file),J.cwd&&(Y.cwd=J.cwd),Y.code=Q instanceof Error&&Q.code||Z,Y.tarCode=Z,!J.strict&&Y.recoverable!==!1?(Q instanceof Error&&(Y=Object.assign(Q,Y),Q=Q.message),J.emit("warn",Z,Q,Y)):Q instanceof Error?J.emit("error",Object.assign(Q,Y)):J.emit("error",Object.assign(Error(`${Z}: ${Q}`),Y))},Kt5=1048576,Dl0=Buffer.from([31,139]),Bl0=Buffer.from([40,181,47,253]),Vt5=Math.max(Dl0.length,Bl0.length),TK=Symbol("state"),nA=Symbol("writeEntry"),ZH=Symbol("readEntry"),ec0=Symbol("nextEntry"),ew4=Symbol("processEntry"),Jq=Symbol("extendedHeader"),Ul=Symbol("globalExtendedHeader"),sN=Symbol("meta"),$L4=Symbol("emitMeta"),g8=Symbol("buffer"),QH=Symbol("queue"),tN=Symbol("ended"),$l0=Symbol("emittedEnd"),aA=Symbol("emit"),l7=Symbol("unzip"),lZ0=Symbol("consumeChunk"),iZ0=Symbol("consumeChunkSub"),Jl0=Symbol("consumeBody"),JL4=Symbol("consumeMeta"),ZL4=Symbol("consumeHeader"),Hl=Symbol("consuming"),Zl0=Symbol("bufferConcat"),nZ0=Symbol("maybeEnd"),Ak=Symbol("writing"),eN=Symbol("aborted"),aZ0=Symbol("onDone"),oA=Symbol("sawValidEntry"),oZ0=Symbol("sawNullBlock"),rZ0=Symbol("sawEOF"),QL4=Symbol("closeStream"),zt5=()=>!0,Tl=class extends Ps5{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[QH]=[];[g8];[ZH];[nA];[TK]="begin";[sN]="";[Jq];[Ul];[tN]=!1;[l7];[eN]=!1;[oA];[oZ0]=!1;[rZ0]=!1;[Ak]=!1;[Hl]=!1;[$l0]=!1;constructor(J={}){super(),this.file=J.file||"",this.on(aZ0,()=>{(this[TK]==="begin"||this[oA]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),J.ondone?this.on(aZ0,J.ondone):this.on(aZ0,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!J.strict,this.maxMetaEntrySize=J.maxMetaEntrySize||Kt5,this.filter=typeof J.filter=="function"?J.filter:zt5;let Z=J.file&&(J.file.endsWith(".tar.br")||J.file.endsWith(".tbr"));this.brotli=!(J.gzip||J.zstd)&&J.brotli!==void 0?J.brotli:Z?void 0:!1;let Q=J.file&&(J.file.endsWith(".tar.zst")||J.file.endsWith(".tzst"));this.zstd=!(J.gzip||J.brotli)&&J.zstd!==void 0?J.zstd:Q?!0:void 0,this.on("end",()=>this[QL4]()),typeof J.onwarn=="function"&&this.on("warn",J.onwarn),typeof J.onReadEntry=="function"&&this.on("entry",J.onReadEntry)}warn(J,Z,Q={}){BQ0(this,J,Z,Q)}[ZL4](J,Z){this[oA]===void 0&&(this[oA]=!1);let Q;try{Q=new Jj(J,Z,this[Jq],this[Ul])}catch(Y){return this.warn("TAR_ENTRY_INVALID",Y)}if(Q.nullBlock)this[oZ0]?(this[rZ0]=!0,this[TK]==="begin"&&(this[TK]="header"),this[aA]("eof")):(this[oZ0]=!0,this[aA]("nullBlock"));else if(this[oZ0]=!1,!Q.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:Q});else if(!Q.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:Q});else{let Y=Q.type;if(/^(Symbolic)?Link$/.test(Y)&&!Q.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:Q});else if(!/^(Symbolic)?Link$/.test(Y)&&!/^(Global)?ExtendedHeader$/.test(Y)&&Q.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:Q});else{let X=this[nA]=new yL4(Q,this[Jq],this[Ul]);if(!this[oA])if(X.remain){let K=()=>{X.invalid||(this[oA]=!0)};X.on("end",K)}else this[oA]=!0;X.meta?X.size>this.maxMetaEntrySize?(X.ignore=!0,this[aA]("ignoredEntry",X),this[TK]="ignore",X.resume()):X.size>0&&(this[sN]="",X.on("data",(K)=>this[sN]+=K),this[TK]="meta"):(this[Jq]=void 0,X.ignore=X.ignore||!this.filter(X.path,X),X.ignore?(this[aA]("ignoredEntry",X),this[TK]=X.remain?"ignore":"header",X.resume()):(X.remain?this[TK]="body":(this[TK]="header",X.end()),this[ZH]?this[QH].push(X):(this[QH].push(X),this[ec0]())))}}}[QL4](){queueMicrotask(()=>this.emit("close"))}[ew4](J){let Z=!0;if(!J)this[ZH]=void 0,Z=!1;else if(Array.isArray(J)){let[Q,...Y]=J;this.emit(Q,...Y)}else this[ZH]=J,this.emit("entry",J),J.emittedEnd||(J.on("end",()=>this[ec0]()),Z=!1);return Z}[ec0](){do;while(this[ew4](this[QH].shift()));if(!this[QH].length){let J=this[ZH];!J||J.flowing||J.size===J.remain?this[Ak]||this.emit("drain"):J.once("drain",()=>this.emit("drain"))}}[Jl0](J,Z){let Q=this[nA];if(!Q)throw Error("attempt to consume body without entry??");let Y=Q.blockRemain??0,X=Y>=J.length&&Z===0?J:J.subarray(Z,Z+Y);return Q.write(X),Q.blockRemain||(this[TK]="header",this[nA]=void 0,Q.end()),X.length}[JL4](J,Z){let Q=this[nA],Y=this[Jl0](J,Z);return!this[nA]&&Q&&this[$L4](Q),Y}[aA](J,Z,Q){!this[QH].length&&!this[ZH]?this.emit(J,Z,Q):this[QH].push([J,Z,Q])}[$L4](J){switch(this[aA]("meta",this[sN]),J.type){case"ExtendedHeader":case"OldExtendedHeader":this[Jq]=GQ0.parse(this[sN],this[Jq],!1);break;case"GlobalExtendedHeader":this[Ul]=GQ0.parse(this[sN],this[Ul],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let Z=this[Jq]??Object.create(null);this[Jq]=Z,Z.path=this[sN].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let Z=this[Jq]||Object.create(null);this[Jq]=Z,Z.linkpath=this[sN].replace(/\0.*/,"");break}default:throw Error("unknown meta: "+J.type)}}abort(J){this[eN]=!0,this.emit("abort",J),this.warn("TAR_ABORT",J,{recoverable:!1})}write(J,Z,Q){if(typeof Z=="function"&&(Q=Z,Z=void 0),typeof J=="string"&&(J=Buffer.from(J,typeof Z=="string"?Z:"utf8")),this[eN])return Q?.(),!1;if((this[l7]===void 0||this.brotli===void 0&&this[l7]===!1)&&J){if(this[g8]&&(J=Buffer.concat([this[g8],J]),this[g8]=void 0),J.length<Vt5)return this[g8]=J,Q?.(),!0;for(let V=0;this[l7]===void 0&&V<Dl0.length;V++)J[V]!==Dl0[V]&&(this[l7]=!1);let X=!1;if(this[l7]===!1&&this.zstd!==!1){X=!0;for(let V=0;V<Bl0.length;V++)if(J[V]!==Bl0[V]){X=!1;break}}let K=this.brotli===void 0&&!X;if(this[l7]===!1&&K)if(J.length<512)if(this[tN])this.brotli=!0;else return this[g8]=J,Q?.(),!0;else try{new Jj(J.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[l7]===void 0||this[l7]===!1&&(this.brotli||X)){let V=this[tN];this[tN]=!1,this[l7]=this[l7]===void 0?new vs5({}):X?new us5({}):new xs5({}),this[l7].on("data",(G)=>this[lZ0](G)),this[l7].on("error",(G)=>this.abort(G)),this[l7].on("end",()=>{this[tN]=!0,this[lZ0]()}),this[Ak]=!0;let z=!!this[l7][V?"end":"write"](J);return this[Ak]=!1,Q?.(),z}}this[Ak]=!0,this[l7]?this[l7].write(J):this[lZ0](J),this[Ak]=!1;let Y=this[QH].length?!1:this[ZH]?this[ZH].flowing:!0;return!Y&&!this[QH].length&&this[ZH]?.once("drain",()=>this.emit("drain")),Q?.(),Y}[Zl0](J){J&&!this[eN]&&(this[g8]=this[g8]?Buffer.concat([this[g8],J]):J)}[nZ0](){if(this[tN]&&!this[$l0]&&!this[eN]&&!this[Hl]){this[$l0]=!0;let J=this[nA];if(J&&J.blockRemain){let Z=this[g8]?this[g8].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${J.blockRemain} more bytes, only ${Z} available)`,{entry:J}),this[g8]&&J.write(this[g8]),J.end()}this[aA](aZ0)}}[lZ0](J){if(this[Hl]&&J)this[Zl0](J);else if(!J&&!this[g8])this[nZ0]();else if(J){if(this[Hl]=!0,this[g8]){this[Zl0](J);let Z=this[g8];this[g8]=void 0,this[iZ0](Z)}else this[iZ0](J);for(;this[g8]&&this[g8]?.length>=512&&!this[eN]&&!this[rZ0];){let Z=this[g8];this[g8]=void 0,this[iZ0](Z)}this[Hl]=!1}(!this[g8]||this[tN])&&this[nZ0]()}[iZ0](J){let Z=0,Q=J.length;for(;Z+512<=Q&&!this[eN]&&!this[rZ0];)switch(this[TK]){case"begin":case"header":this[ZL4](J,Z),Z+=512;break;case"ignore":case"body":Z+=this[Jl0](J,Z);break;case"meta":Z+=this[JL4](J,Z);break;default:throw Error("invalid state: "+this[TK])}Z<Q&&(this[g8]?this[g8]=Buffer.concat([J.subarray(Z),this[g8]]):this[g8]=J.subarray(Z))}end(J,Z,Q){return typeof J=="function"&&(Q=J,Z=void 0,J=void 0),typeof Z=="function"&&(Q=Z,Z=void 0),typeof J=="string"&&(J=Buffer.from(J,Z)),Q&&this.once("finish",Q),this[eN]||(this[l7]?(J&&this[l7].write(J),this[l7].end()):(this[tN]=!0,(this.brotli===void 0||this.zstd===void 0)&&(J=J||Buffer.alloc(0)),J&&this.write(J),this[nZ0]())),this}},Ml=(J)=>{let Z=J.length-1,Q=-1;for(;Z>-1&&J.charAt(Z)==="/";)Q=Z,Z--;return Q===-1?J:J.slice(0,Q)},Gt5=(J)=>{let Z=J.onReadEntry;J.onReadEntry=Z?(Q)=>{Z(Q),Q.resume()}:(Q)=>Q.resume()},xL4=(J,Z)=>{let Q=new Map(Z.map((K)=>[Ml(K),!0])),Y=J.filter,X=(K,V="")=>{let z=V||Ls5(K).root||".",G;if(K===z)G=!1;else{let F=Q.get(K);F!==void 0?G=F:G=X(ws5(K),z)}return Q.set(K,G),G};J.filter=Y?(K,V)=>Y(K,V)&&X(Ml(K)):(K)=>X(Ml(K))},Ft5=(J)=>{let Z=new Tl(J),Q=J.file,Y;try{Y=Tk.openSync(Q,"r");let X=Tk.fstatSync(Y),K=J.maxReadSize||16777216;if(X.size<K){let V=Buffer.allocUnsafe(X.size),z=Tk.readSync(Y,V,0,X.size,0);Z.end(z===V.byteLength?V:V.subarray(0,z))}else{let V=0,z=Buffer.allocUnsafe(K);for(;V<X.size;){let G=Tk.readSync(Y,z,0,K,V);if(G===0)break;V+=G,Z.write(z.subarray(0,G))}Z.end()}}finally{if(typeof Y=="number")try{Tk.closeSync(Y)}catch{}}},qt5=(J,Z)=>{let Q=new Tl(J),Y=J.maxReadSize||16777216,X=J.file;return new Promise((K,V)=>{Q.on("error",V),Q.on("end",K),Tk.stat(X,(z,G)=>{if(z)V(z);else{let F=new yl0(X,{readSize:Y,size:G.size});F.on("error",V),F.pipe(Q)}})})},NQ0=_l(Ft5,qt5,(J)=>new Tl(J),(J)=>new Tl(J),(J,Z)=>{Z?.length&&xL4(J,Z),J.noResume||Gt5(J)}),fL4=(J,Z,Q)=>(J&=4095,Q&&(J=(J|384)&-19),Z&&(J&256&&(J|=64),J&32&&(J|=8),J&4&&(J|=1)),J),{isAbsolute:Ut5,parse:XL4}=Wt5,bl0=(J)=>{let Z="",Q=XL4(J);for(;Ut5(J)||Q.root;){let Y=J.charAt(0)==="/"&&J.slice(0,4)!=="//?/"?"/":Q.root;J=J.slice(Y.length),Z+=Y,Q=XL4(J)}return[Z,J]},wQ0=["|","<",">","?",":"],hl0=wQ0.map((J)=>String.fromCharCode(61440+J.charCodeAt(0))),Ht5=new Map(wQ0.map((J,Z)=>[J,hl0[Z]])),Dt5=new Map(hl0.map((J,Z)=>[J,wQ0[Z]])),KL4=(J)=>wQ0.reduce((Z,Q)=>Z.split(Q).join(Ht5.get(Q)),J),Bt5=(J)=>hl0.reduce((Z,Q)=>Z.split(Q).join(Dt5.get(Q)),J),uL4=(J,Z)=>Z?(J=A5(J).replace(/^\.(\/|$)/,""),Ml(Z)+"/"+J):A5(J),Nt5=16777216,VL4=Symbol("process"),zL4=Symbol("file"),GL4=Symbol("directory"),Nl0=Symbol("symlink"),FL4=Symbol("hardlink"),Dl=Symbol("header"),JQ0=Symbol("read"),wl0=Symbol("lstat"),ZQ0=Symbol("onlstat"),Ll0=Symbol("onread"),Ol0=Symbol("onreadlink"),El0=Symbol("openfile"),Ml0=Symbol("onopenfile"),Qw=Symbol("close"),qQ0=Symbol("mode"),Al0=Symbol("awaitDrain"),Ql0=Symbol("ondrain"),Qq=Symbol("prefix"),bL4=class extends Zj{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#$=!1;constructor(J,Z={}){let Q=xl0(Z);super(),this.path=A5(J),this.portable=!!Q.portable,this.maxReadSize=Q.maxReadSize||Nt5,this.linkCache=Q.linkCache||new Map,this.statCache=Q.statCache||new Map,this.preservePaths=!!Q.preservePaths,this.cwd=A5(Q.cwd||process.cwd()),this.strict=!!Q.strict,this.noPax=!!Q.noPax,this.noMtime=!!Q.noMtime,this.mtime=Q.mtime,this.prefix=Q.prefix?A5(Q.prefix):void 0,this.onWriteEntry=Q.onWriteEntry,typeof Q.onwarn=="function"&&this.on("warn",Q.onwarn);let Y=!1;if(!this.preservePaths){let[K,V]=bl0(this.path);K&&typeof V=="string"&&(this.path=V,Y=K)}this.win32=!!Q.win32||process.platform==="win32",this.win32&&(this.path=Bt5(this.path.replace(/\\/g,"/")),J=J.replace(/\\/g,"/")),this.absolute=A5(Q.absolute||YL4.resolve(this.cwd,J)),this.path===""&&(this.path="./"),Y&&this.warn("TAR_ENTRY_INFO",`stripping ${Y} from absolute path`,{entry:this,path:Y+this.path});let X=this.statCache.get(this.absolute);X?this[ZQ0](X):this[wl0]()}warn(J,Z,Q={}){return BQ0(this,J,Z,Q)}emit(J,...Z){return J==="error"&&(this.#$=!0),super.emit(J,...Z)}[wl0](){Zq.lstat(this.absolute,(J,Z)=>{if(J)return this.emit("error",J);this[ZQ0](Z)})}[ZQ0](J){this.statCache.set(this.absolute,J),this.stat=J,J.isFile()||(J.size=0),this.type=Ot5(J),this.emit("stat",J),this[VL4]()}[VL4](){switch(this.type){case"File":return this[zL4]();case"Directory":return this[GL4]();case"SymbolicLink":return this[Nl0]();default:return this.end()}}[qQ0](J){return fL4(J,this.type==="Directory",this.portable)}[Qq](J){return uL4(J,this.prefix)}[Dl](){if(!this.stat)throw Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new Jj({path:this[Qq](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Qq](this.linkpath):this.linkpath,mode:this[qQ0](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new GQ0({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[Qq](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Qq](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let J=this.header?.block;if(!J)throw Error("failed to encode header");super.write(J)}[GL4](){if(!this.stat)throw Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Dl](),this.end()}[Nl0](){Zq.readlink(this.absolute,(J,Z)=>{if(J)return this.emit("error",J);this[Ol0](Z)})}[Ol0](J){this.linkpath=A5(J),this[Dl](),this.end()}[FL4](J){if(!this.stat)throw Error("cannot create link entry without stat");this.type="Link",this.linkpath=A5(YL4.relative(this.cwd,J)),this.stat.size=0,this[Dl](),this.end()}[zL4](){if(!this.stat)throw Error("cannot create file entry without stat");if(this.stat.nlink>1){let J=`${this.stat.dev}:${this.stat.ino}`,Z=this.linkCache.get(J);if(Z?.indexOf(this.cwd)===0)return this[FL4](Z);this.linkCache.set(J,this.absolute)}if(this[Dl](),this.stat.size===0)return this.end();this[El0]()}[El0](){Zq.open(this.absolute,"r",(J,Z)=>{if(J)return this.emit("error",J);this[Ml0](Z)})}[Ml0](J){if(this.fd=J,this.#$)return this[Qw]();if(!this.stat)throw Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let Z=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(Z),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[JQ0]()}[JQ0](){let{fd:J,buf:Z,offset:Q,length:Y,pos:X}=this;if(J===void 0||Z===void 0)throw Error("cannot read file without first opening");Zq.read(J,Z,Q,Y,X,(K,V)=>{if(K)return this[Qw](()=>this.emit("error",K));this[Ll0](V)})}[Qw](J=()=>{}){this.fd!==void 0&&Zq.close(this.fd,J)}[Ll0](J){if(J<=0&&this.remain>0){let Q=Object.assign(Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[Qw](()=>this.emit("error",Q))}if(J>this.remain){let Q=Object.assign(Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[Qw](()=>this.emit("error",Q))}if(!this.buf)throw Error("should have created buffer prior to reading");if(J===this.remain)for(let Q=J;Q<this.length&&J<this.blockRemain;Q++)this.buf[Q+this.offset]=0,J++,this.remain++;let Z=this.offset===0&&J===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+J);this.write(Z)?this[Ql0]():this[Al0](()=>this[Ql0]())}[Al0](J){this.once("drain",J)}write(J,Z,Q){if(typeof Z=="function"&&(Q=Z,Z=void 0),typeof J=="string"&&(J=Buffer.from(J,typeof Z=="string"?Z:"utf8")),this.blockRemain<J.length){let Y=Object.assign(Error("writing more data than expected"),{path:this.absolute});return this.emit("error",Y)}return this.remain-=J.length,this.blockRemain-=J.length,this.pos+=J.length,this.offset+=J.length,super.write(J,null,Q)}[Ql0](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[Qw]((J)=>J?this.emit("error",J):this.end());if(!this.buf)throw Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[JQ0]()}},wt5=class extends bL4{sync=!0;[wl0](){this[ZQ0](Zq.lstatSync(this.absolute))}[Nl0](){this[Ol0](Zq.readlinkSync(this.absolute))}[El0](){this[Ml0](Zq.openSync(this.absolute,"r"))}[JQ0](){let J=!0;try{let{fd:Z,buf:Q,offset:Y,length:X,pos:K}=this;if(Z===void 0||Q===void 0)throw Error("fd and buf must be set in READ method");let V=Zq.readSync(Z,Q,Y,X,K);this[Ll0](V),J=!1}finally{if(J)try{this[Qw](()=>{})}catch{}}}[Al0](J){J()}[Qw](J=()=>{}){this.fd!==void 0&&Zq.closeSync(this.fd),J()}},Lt5=class extends Zj{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(J,Z,Q={}){return BQ0(this,J,Z,Q)}constructor(J,Z={}){let Q=xl0(Z);super(),this.preservePaths=!!Q.preservePaths,this.portable=!!Q.portable,this.strict=!!Q.strict,this.noPax=!!Q.noPax,this.noMtime=!!Q.noMtime,this.onWriteEntry=Q.onWriteEntry,this.readEntry=J;let{type:Y}=J;if(Y==="Unsupported")throw Error("writing entry that should be ignored");this.type=Y,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=Q.prefix,this.path=A5(J.path),this.mode=J.mode!==void 0?this[qQ0](J.mode):void 0,this.uid=this.portable?void 0:J.uid,this.gid=this.portable?void 0:J.gid,this.uname=this.portable?void 0:J.uname,this.gname=this.portable?void 0:J.gname,this.size=J.size,this.mtime=this.noMtime?void 0:Q.mtime||J.mtime,this.atime=this.portable?void 0:J.atime,this.ctime=this.portable?void 0:J.ctime,this.linkpath=J.linkpath!==void 0?A5(J.linkpath):void 0,typeof Q.onwarn=="function"&&this.on("warn",Q.onwarn);let X=!1;if(!this.preservePaths){let[V,z]=bl0(this.path);V&&typeof z=="string"&&(this.path=z,X=V)}this.remain=J.size,this.blockRemain=J.startBlockSize,this.onWriteEntry?.(this),this.header=new Jj({path:this[Qq](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Qq](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),X&&this.warn("TAR_ENTRY_INFO",`stripping ${X} from absolute path`,{entry:this,path:X+this.path}),this.header.encode()&&!this.noPax&&super.write(new GQ0({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[Qq](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Qq](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let K=this.header?.block;if(!K)throw Error("failed to encode header");super.write(K),J.pipe(this)}[Qq](J){return uL4(J,this.prefix)}[qQ0](J){return fL4(J,this.type==="Directory",this.portable)}write(J,Z,Q){typeof Z=="function"&&(Q=Z,Z=void 0),typeof J=="string"&&(J=Buffer.from(J,typeof Z=="string"?Z:"utf8"));let Y=J.length;if(Y>this.blockRemain)throw Error("writing more to entry than is appropriate");return this.blockRemain-=Y,super.write(J,Q)}end(J,Z,Q){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof J=="function"&&(Q=J,Z=void 0,J=void 0),typeof Z=="function"&&(Q=Z,Z=void 0),typeof J=="string"&&(J=Buffer.from(J,Z??"utf8")),Q&&this.once("finish",Q),J?super.end(J,Q):super.end(Q),this}},Ot5=(J)=>J.isFile()?"File":J.isDirectory()?"Directory":J.isSymbolicLink()?"SymbolicLink":"Unsupported",Et5=class J{tail;head;length=0;static create(Z=[]){return new J(Z)}constructor(Z=[]){for(let Q of Z)this.push(Q)}*[Symbol.iterator](){for(let Z=this.head;Z;Z=Z.next)yield Z.value}removeNode(Z){if(Z.list!==this)throw Error("removing node which does not belong to this list");let{next:Q,prev:Y}=Z;return Q&&(Q.prev=Y),Y&&(Y.next=Q),Z===this.head&&(this.head=Q),Z===this.tail&&(this.tail=Y),this.length--,Z.next=void 0,Z.prev=void 0,Z.list=void 0,Q}unshiftNode(Z){if(Z===this.head)return;Z.list&&Z.list.removeNode(Z);let Q=this.head;Z.list=this,Z.next=Q,Q&&(Q.prev=Z),this.head=Z,this.tail||(this.tail=Z),this.length++}pushNode(Z){if(Z===this.tail)return;Z.list&&Z.list.removeNode(Z);let Q=this.tail;Z.list=this,Z.prev=Q,Q&&(Q.next=Z),this.tail=Z,this.head||(this.head=Z),this.length++}push(...Z){for(let Q=0,Y=Z.length;Q<Y;Q++)At5(this,Z[Q]);return this.length}unshift(...Z){for(var Q=0,Y=Z.length;Q<Y;Q++)jt5(this,Z[Q]);return this.length}pop(){if(!this.tail)return;let Z=this.tail.value,Q=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,Q.list=void 0,this.length--,Z}shift(){if(!this.head)return;let Z=this.head.value,Q=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,Q.list=void 0,this.length--,Z}forEach(Z,Q){Q=Q||this;for(let Y=this.head,X=0;Y;X++)Z.call(Q,Y.value,X,this),Y=Y.next}forEachReverse(Z,Q){Q=Q||this;for(let Y=this.tail,X=this.length-1;Y;X--)Z.call(Q,Y.value,X,this),Y=Y.prev}get(Z){let Q=0,Y=this.head;for(;Y&&Q<Z;Q++)Y=Y.next;if(Q===Z&&Y)return Y.value}getReverse(Z){let Q=0,Y=this.tail;for(;Y&&Q<Z;Q++)Y=Y.prev;if(Q===Z&&Y)return Y.value}map(Z,Q){Q=Q||this;let Y=new J;for(let X=this.head;X;)Y.push(Z.call(Q,X.value,this)),X=X.next;return Y}mapReverse(Z,Q){Q=Q||this;var Y=new J;for(let X=this.tail;X;)Y.push(Z.call(Q,X.value,this)),X=X.prev;return Y}reduce(Z,Q){let Y,X=this.head;if(arguments.length>1)Y=Q;else if(this.head)X=this.head.next,Y=this.head.value;else throw TypeError("Reduce of empty list with no initial value");for(var K=0;X;K++)Y=Z(Y,X.value,K),X=X.next;return Y}reduceReverse(Z,Q){let Y,X=this.tail;if(arguments.length>1)Y=Q;else if(this.tail)X=this.tail.prev,Y=this.tail.value;else throw TypeError("Reduce of empty list with no initial value");for(let K=this.length-1;X;K--)Y=Z(Y,X.value,K),X=X.prev;return Y}toArray(){let Z=Array(this.length);for(let Q=0,Y=this.head;Y;Q++)Z[Q]=Y.value,Y=Y.next;return Z}toArrayReverse(){let Z=Array(this.length);for(let Q=0,Y=this.tail;Y;Q++)Z[Q]=Y.value,Y=Y.prev;return Z}slice(Z=0,Q=this.length){Q<0&&(Q+=this.length),Z<0&&(Z+=this.length);let Y=new J;if(Q<Z||Q<0)return Y;Z<0&&(Z=0),Q>this.length&&(Q=this.length);let X=this.head,K=0;for(K=0;X&&K<Z;K++)X=X.next;for(;X&&K<Q;K++,X=X.next)Y.push(X.value);return Y}sliceReverse(Z=0,Q=this.length){Q<0&&(Q+=this.length),Z<0&&(Z+=this.length);let Y=new J;if(Q<Z||Q<0)return Y;Z<0&&(Z=0),Q>this.length&&(Q=this.length);let X=this.length,K=this.tail;for(;K&&X>Q;X--)K=K.prev;for(;K&&X>Z;X--,K=K.prev)Y.push(K.value);return Y}splice(Z,Q=0,...Y){Z>this.length&&(Z=this.length-1),Z<0&&(Z=this.length+Z);let X=this.head;for(let V=0;X&&V<Z;V++)X=X.next;let K=[];for(let V=0;X&&V<Q;V++)K.push(X.value),X=this.removeNode(X);X?X!==this.tail&&(X=X.prev):X=this.tail;for(let V of Y)X=Mt5(this,X,V);return K}reverse(){let Z=this.head,Q=this.tail;for(let Y=Z;Y;Y=Y.prev){let X=Y.prev;Y.prev=Y.next,Y.next=X}return this.head=Q,this.tail=Z,this}};function Mt5(J,Z,Q){let Y=Z,X=Z?Z.next:J.head,K=new gl0(Q,Y,X,J);return K.next===void 0&&(J.tail=K),K.prev===void 0&&(J.head=K),J.length++,K}function At5(J,Z){J.tail=new gl0(Z,J.tail,void 0,J),J.head||(J.head=J.tail),J.length++}function jt5(J,Z){J.head=new gl0(Z,void 0,J.head,J),J.tail||(J.tail=J.head),J.length++}var gl0=class{list;next;prev;value;constructor(J,Z,Q,Y){this.list=Y,this.value=J,Z?(Z.next=this,this.prev=Z):this.prev=void 0,Q?(Q.prev=this,this.next=Q):this.next=void 0}},WL4=class{path;absolute;entry;stat;readdir;pending=!1;ignore=!1;piped=!1;constructor(J,Z){this.path=J||"./",this.absolute=Z}},UL4=Buffer.alloc(1024),QQ0=Symbol("onStat"),Bl=Symbol("ended"),Ez=Symbol("queue"),rA=Symbol("current"),sA=Symbol("process"),Nl=Symbol("processing"),Yl0=Symbol("processJob"),Mz=Symbol("jobs"),Xl0=Symbol("jobDone"),YQ0=Symbol("addFSEntry"),HL4=Symbol("addTarEntry"),jl0=Symbol("stat"),Rl0=Symbol("readdir"),XQ0=Symbol("onreaddir"),KQ0=Symbol("pipe"),DL4=Symbol("entry"),Kl0=Symbol("entryOpt"),VQ0=Symbol("writeEntryClass"),hL4=Symbol("write"),Vl0=Symbol("ondrain"),LQ0=class extends Zj{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[VQ0];onWriteEntry;[Ez];[Mz]=0;[Nl]=!1;[Bl]=!1;constructor(J={}){if(super(),this.opt=J,this.file=J.file||"",this.cwd=J.cwd||process.cwd(),this.maxReadSize=J.maxReadSize,this.preservePaths=!!J.preservePaths,this.strict=!!J.strict,this.noPax=!!J.noPax,this.prefix=A5(J.prefix||""),this.linkCache=J.linkCache||new Map,this.statCache=J.statCache||new Map,this.readdirCache=J.readdirCache||new Map,this.onWriteEntry=J.onWriteEntry,this[VQ0]=bL4,typeof J.onwarn=="function"&&this.on("warn",J.onwarn),this.portable=!!J.portable,J.gzip||J.brotli||J.zstd){if((J.gzip?1:0)+(J.brotli?1:0)+(J.zstd?1:0)>1)throw TypeError("gzip, brotli, zstd are mutually exclusive");if(J.gzip&&(typeof J.gzip!="object"&&(J.gzip={}),this.portable&&(J.gzip.portable=!0),this.zip=new ks5(J.gzip)),J.brotli&&(typeof J.brotli!="object"&&(J.brotli={}),this.zip=new ys5(J.brotli)),J.zstd&&(typeof J.zstd!="object"&&(J.zstd={}),this.zip=new fs5(J.zstd)),!this.zip)throw Error("impossible");let Z=this.zip;Z.on("data",(Q)=>super.write(Q)),Z.on("end",()=>super.end()),Z.on("drain",()=>this[Vl0]()),this.on("resume",()=>Z.resume())}else this.on("drain",this[Vl0]);this.noDirRecurse=!!J.noDirRecurse,this.follow=!!J.follow,this.noMtime=!!J.noMtime,J.mtime&&(this.mtime=J.mtime),this.filter=typeof J.filter=="function"?J.filter:()=>!0,this[Ez]=new Et5,this[Mz]=0,this.jobs=Number(J.jobs)||4,this[Nl]=!1,this[Bl]=!1}[hL4](J){return super.write(J)}add(J){return this.write(J),this}end(J,Z,Q){return typeof J=="function"&&(Q=J,J=void 0),typeof Z=="function"&&(Q=Z,Z=void 0),J&&this.add(J),this[Bl]=!0,this[sA](),Q&&Q(),this}write(J){if(this[Bl])throw Error("write after end");return J instanceof yL4?this[HL4](J):this[YQ0](J),this.flowing}[HL4](J){let Z=A5(qL4.resolve(this.cwd,J.path));if(!this.filter(J.path,J))J.resume();else{let Q=new WL4(J.path,Z);Q.entry=new Lt5(J,this[Kl0](Q)),Q.entry.on("end",()=>this[Xl0](Q)),this[Mz]+=1,this[Ez].push(Q)}this[sA]()}[YQ0](J){let Z=A5(qL4.resolve(this.cwd,J));this[Ez].push(new WL4(J,Z)),this[sA]()}[jl0](J){J.pending=!0,this[Mz]+=1;let Z=this.follow?"stat":"lstat";FQ0[Z](J.absolute,(Q,Y)=>{J.pending=!1,this[Mz]-=1,Q?this.emit("error",Q):this[QQ0](J,Y)})}[QQ0](J,Z){this.statCache.set(J.absolute,Z),J.stat=Z,this.filter(J.path,Z)?Z.isFile()&&Z.nlink>1&&J===this[rA]&&!this.linkCache.get(`${Z.dev}:${Z.ino}`)&&!this.sync&&this[Yl0](J):J.ignore=!0,this[sA]()}[Rl0](J){J.pending=!0,this[Mz]+=1,FQ0.readdir(J.absolute,(Z,Q)=>{if(J.pending=!1,this[Mz]-=1,Z)return this.emit("error",Z);this[XQ0](J,Q)})}[XQ0](J,Z){this.readdirCache.set(J.absolute,Z),J.readdir=Z,this[sA]()}[sA](){if(!this[Nl]){this[Nl]=!0;for(let J=this[Ez].head;J&&this[Mz]<this.jobs;J=J.next)if(this[Yl0](J.value),J.value.ignore){let Z=J.next;this[Ez].removeNode(J),J.next=Z}this[Nl]=!1,this[Bl]&&!this[Ez].length&&this[Mz]===0&&(this.zip?this.zip.end(UL4):(super.write(UL4),super.end()))}}get[rA](){return this[Ez]&&this[Ez].head&&this[Ez].head.value}[Xl0](J){this[Ez].shift(),this[Mz]-=1,this[sA]()}[Yl0](J){if(!J.pending){if(J.entry){J===this[rA]&&!J.piped&&this[KQ0](J);return}if(!J.stat){let Z=this.statCache.get(J.absolute);Z?this[QQ0](J,Z):this[jl0](J)}if(J.stat&&!J.ignore){if(!this.noDirRecurse&&J.stat.isDirectory()&&!J.readdir){let Z=this.readdirCache.get(J.absolute);if(Z?this[XQ0](J,Z):this[Rl0](J),!J.readdir)return}if(J.entry=this[DL4](J),!J.entry){J.ignore=!0;return}J===this[rA]&&!J.piped&&this[KQ0](J)}}}[Kl0](J){return{onwarn:(Z,Q,Y)=>this.warn(Z,Q,Y),noPax:this.noPax,cwd:this.cwd,absolute:J.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[DL4](J){this[Mz]+=1;try{return new this[VQ0](J.path,this[Kl0](J)).on("end",()=>this[Xl0](J)).on("error",(Z)=>this.emit("error",Z))}catch(Z){this.emit("error",Z)}}[Vl0](){this[rA]&&this[rA].entry&&this[rA].entry.resume()}[KQ0](J){J.piped=!0,J.readdir&&J.readdir.forEach((Y)=>{let X=J.path,K=X==="./"?"":X.replace(/\/*$/,"/");this[YQ0](K+Y)});let Z=J.entry,Q=this.zip;if(!Z)throw Error("cannot pipe without source");Q?Z.on("data",(Y)=>{Q.write(Y)||Z.pause()}):Z.on("data",(Y)=>{super.write(Y)||Z.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(J,Z,Q={}){BQ0(this,J,Z,Q)}},ml0=class extends LQ0{sync=!0;constructor(J){super(J),this[VQ0]=wt5}pause(){}resume(){}[jl0](J){let Z=this.follow?"statSync":"lstatSync";this[QQ0](J,FQ0[Z](J.absolute))}[Rl0](J){this[XQ0](J,FQ0.readdirSync(J.absolute))}[KQ0](J){let Z=J.entry,Q=this.zip;if(J.readdir&&J.readdir.forEach((Y)=>{let X=J.path,K=X==="./"?"":X.replace(/\/*$/,"/");this[YQ0](K+Y)}),!Z)throw Error("Cannot pipe without source");Q?Z.on("data",(Y)=>{Q.write(Y)}):Z.on("data",(Y)=>{super[hL4](Y)})}},Rt5=(J,Z)=>{let Q=new ml0(J),Y=new PL4(J.file,{mode:J.mode||438});Q.pipe(Y),gL4(Q,Z)},It5=(J,Z)=>{let Q=new LQ0(J),Y=new HQ0(J.file,{mode:J.mode||438});Q.pipe(Y);let X=new Promise((K,V)=>{Y.on("error",V),Y.on("close",K),Q.on("error",V)});return mL4(Q,Z),X},gL4=(J,Z)=>{Z.forEach((Q)=>{Q.charAt(0)==="@"?NQ0({file:CL4.resolve(J.cwd,Q.slice(1)),sync:!0,noResume:!0,onReadEntry:(Y)=>J.add(Y)}):J.add(Q)}),J.end()},mL4=async(J,Z)=>{for(let Q=0;Q<Z.length;Q++){let Y=String(Z[Q]);Y.charAt(0)==="@"?await NQ0({file:CL4.resolve(String(J.cwd),Y.slice(1)),noResume:!0,onReadEntry:(X)=>{J.add(X)}}):J.add(Y)}J.end()},Pt5=(J,Z)=>{let Q=new ml0(J);return gL4(Q,Z),Q},Ct5=(J,Z)=>{let Q=new LQ0(J);return mL4(Q,Z),Q},R59=_l(Rt5,It5,Pt5,Ct5,(J,Z)=>{if(!Z?.length)throw TypeError("no paths specified to add to archive")}),_t5=process.env.__FAKE_PLATFORM__||process.platform,St5=_t5==="win32",{O_CREAT:kt5,O_TRUNC:vt5,O_WRONLY:yt5}=cL4.constants,lL4=Number(process.env.__FAKE_FS_O_FILENAME__)||cL4.constants.UV_FS_O_FILEMAP||0,xt5=St5&&!!lL4,ft5=524288,ut5=lL4|vt5|kt5|yt5,iL4=xt5?(J)=>J<ft5?ut5:"w":()=>"w",Il0=(J,Z,Q)=>{try{return OQ0.lchownSync(J,Z,Q)}catch(Y){if(Y?.code!=="ENOENT")throw Y}},WQ0=(J,Z,Q,Y)=>{OQ0.lchown(J,Z,Q,(X)=>{Y(X&&X?.code!=="ENOENT"?X:null)})},bt5=(J,Z,Q,Y,X)=>{if(Z.isDirectory())nL4(Al.resolve(J,Z.name),Q,Y,(K)=>{if(K)return X(K);let V=Al.resolve(J,Z.name);WQ0(V,Q,Y,X)});else{let K=Al.resolve(J,Z.name);WQ0(K,Q,Y,X)}},nL4=(J,Z,Q,Y)=>{OQ0.readdir(J,{withFileTypes:!0},(X,K)=>{if(X){if(X.code==="ENOENT")return Y();if(X.code!=="ENOTDIR"&&X.code!=="ENOTSUP")return Y(X)}if(X||!K.length)return WQ0(J,Z,Q,Y);let V=K.length,z=null,G=(F)=>{if(!z){if(F)return Y(z=F);if(--V===0)return WQ0(J,Z,Q,Y)}};for(let F of K)bt5(J,F,Z,Q,G)})},ht5=(J,Z,Q,Y)=>{Z.isDirectory()&&aL4(Al.resolve(J,Z.name),Q,Y),Il0(Al.resolve(J,Z.name),Q,Y)},aL4=(J,Z,Q)=>{let Y;try{Y=OQ0.readdirSync(J,{withFileTypes:!0})}catch(X){let K=X;if(K?.code==="ENOENT")return;if(K?.code==="ENOTDIR"||K?.code==="ENOTSUP")return Il0(J,Z,Q);throw K}for(let X of Y)ht5(J,X,Z,Q);return Il0(J,Z,Q)},oL4=class extends Error{path;code;syscall="chdir";constructor(J,Z){super(`${Z}: Cannot cd into '${J}'`),this.path=J,this.code=Z}get name(){return"CwdError"}},EQ0=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(J,Z){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=J,this.path=Z}get name(){return"SymlinkError"}},mt5=(J,Z)=>{pY.stat(J,(Q,Y)=>{(Q||!Y.isDirectory())&&(Q=new oL4(J,Q?.code||"ENOTDIR")),Z(Q)})},pt5=(J,Z,Q)=>{J=A5(J);let Y=Z.umask??18,X=Z.mode|448,K=(X&Y)!==0,V=Z.uid,z=Z.gid,G=typeof V=="number"&&typeof z=="number"&&(V!==Z.processUid||z!==Z.processGid),F=Z.preserve,q=Z.unlink,W=A5(Z.cwd),U=(D,B)=>{D?Q(D):B&&G?nL4(B,V,z,(N)=>U(N)):K?pY.chmod(J,X,Q):Q()};if(J===W)return mt5(J,U);if(F)return gt5.mkdir(J,{mode:X,recursive:!0}).then((D)=>U(null,D??void 0),U);let H=A5(UQ0.relative(W,J)).split("/");Pl0(W,H,X,q,W,void 0,U)},Pl0=(J,Z,Q,Y,X,K,V)=>{if(!Z.length)return V(null,K);let z=Z.shift(),G=A5(UQ0.resolve(J+"/"+z));pY.mkdir(G,Q,rL4(G,Z,Q,Y,X,K,V))},rL4=(J,Z,Q,Y,X,K,V)=>(z)=>{z?pY.lstat(J,(G,F)=>{if(G)G.path=G.path&&A5(G.path),V(G);else if(F.isDirectory())Pl0(J,Z,Q,Y,X,K,V);else if(Y)pY.unlink(J,(q)=>{if(q)return V(q);pY.mkdir(J,Q,rL4(J,Z,Q,Y,X,K,V))});else{if(F.isSymbolicLink())return V(new EQ0(J,J+"/"+Z.join("/")));V(z)}}):(K=K||J,Pl0(J,Z,Q,Y,X,K,V))},dt5=(J)=>{let Z=!1,Q;try{Z=pY.statSync(J).isDirectory()}catch(Y){Q=Y?.code}finally{if(!Z)throw new oL4(J,Q??"ENOTDIR")}},ct5=(J,Z)=>{J=A5(J);let Q=Z.umask??18,Y=Z.mode|448,X=(Y&Q)!==0,K=Z.uid,V=Z.gid,z=typeof K=="number"&&typeof V=="number"&&(K!==Z.processUid||V!==Z.processGid),G=Z.preserve,F=Z.unlink,q=A5(Z.cwd),W=(D)=>{D&&z&&aL4(D,K,V),X&&pY.chmodSync(J,Y)};if(J===q)return dt5(q),W();if(G)return W(pY.mkdirSync(J,{mode:Y,recursive:!0})??void 0);let U=A5(UQ0.relative(q,J)).split("/"),H;for(let D=U.shift(),B=q;D&&(B+="/"+D);D=U.shift()){B=A5(UQ0.resolve(B));try{pY.mkdirSync(B,Y),H=H||B}catch{let N=pY.lstatSync(B);if(N.isDirectory())continue;if(F){pY.unlinkSync(B),pY.mkdirSync(B,Y),H=H||B;continue}else if(N.isSymbolicLink())return new EQ0(B,B+"/"+U.join("/"))}}return W(H)},zl0=Object.create(null),BL4=1e4,jk=new Set,lt5=(J)=>{jk.has(J)?jk.delete(J):zl0[J]=J.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),jk.add(J);let Z=zl0[J],Q=jk.size-BL4;if(Q>BL4/10){for(let Y of jk)if(jk.delete(Y),delete zl0[Y],--Q<=0)break}return Z},it5=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,nt5=it5==="win32",at5=(J)=>J.split("/").slice(0,-1).reduce((Z,Q)=>{let Y=Z[Z.length-1];return Y!==void 0&&(Q=sL4(Y,Q)),Z.push(Q||"/"),Z},[]),ot5=class{#$=new Map;#J=new Map;#Z=new Set;reserve(J,Z){J=nt5?["win32 parallelization disabled"]:J.map((Y)=>Ml(sL4(lt5(Y))));let Q=new Set(J.map((Y)=>at5(Y)).reduce((Y,X)=>Y.concat(X)));this.#J.set(Z,{dirs:Q,paths:J});for(let Y of J){let X=this.#$.get(Y);X?X.push(Z):this.#$.set(Y,[Z])}for(let Y of Q){let X=this.#$.get(Y);if(!X)this.#$.set(Y,[new Set([Z])]);else{let K=X[X.length-1];K instanceof Set?K.add(Z):X.push(new Set([Z]))}}return this.#Y(Z)}#Q(J){let Z=this.#J.get(J);if(!Z)throw Error("function does not have any path reservations");return{paths:Z.paths.map((Q)=>this.#$.get(Q)),dirs:[...Z.dirs].map((Q)=>this.#$.get(Q))}}check(J){let{paths:Z,dirs:Q}=this.#Q(J);return Z.every((Y)=>Y&&Y[0]===J)&&Q.every((Y)=>Y&&Y[0]instanceof Set&&Y[0].has(J))}#Y(J){return this.#Z.has(J)||!this.check(J)?!1:(this.#Z.add(J),J(()=>this.#X(J)),!0)}#X(J){if(!this.#Z.has(J))return!1;let Z=this.#J.get(J);if(!Z)throw Error("invalid reservation");let{paths:Q,dirs:Y}=Z,X=new Set;for(let K of Q){let V=this.#$.get(K);if(!V||V?.[0]!==J)continue;let z=V[1];if(!z){this.#$.delete(K);continue}if(V.shift(),typeof z=="function")X.add(z);else for(let G of z)X.add(G)}for(let K of Y){let V=this.#$.get(K),z=V?.[0];if(!(!V||!(z instanceof Set)))if(z.size===1&&V.length===1){this.#$.delete(K);continue}else if(z.size===1){V.shift();let G=V[0];typeof G=="function"&&X.add(G)}else z.delete(J)}return this.#Z.delete(J),X.forEach((K)=>this.#Y(K)),!0}},rt5=()=>process.umask(),NL4=Symbol("onEntry"),Cl0=Symbol("checkFs"),wL4=Symbol("checkFs2"),Tl0=Symbol("isReusable"),_K=Symbol("makeFs"),_l0=Symbol("file"),Sl0=Symbol("directory"),zQ0=Symbol("link"),LL4=Symbol("symlink"),OL4=Symbol("hardlink"),Ol=Symbol("ensureNoSymlink"),EL4=Symbol("unsupported"),ML4=Symbol("checkPath"),Gl0=Symbol("stripAbsolutePath"),Yw=Symbol("mkdir"),a2=Symbol("onError"),sZ0=Symbol("pending"),AL4=Symbol("pend"),Rk=Symbol("unpend"),Fl0=Symbol("ended"),ql0=Symbol("maybeClose"),kl0=Symbol("skip"),jl=Symbol("doChown"),Rl=Symbol("uid"),Il=Symbol("gid"),Pl=Symbol("checkedCwd"),st5=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Cl=st5==="win32",tt5=1024,et5=(J,Z)=>{if(!Cl)return K3.unlink(J,Z);let Q=J+".DELETE."+dL4(16).toString("hex");K3.rename(J,Q,(Y)=>{if(Y)return Z(Y);K3.unlink(Q,Z)})},$e5=(J)=>{if(!Cl)return K3.unlinkSync(J);let Z=J+".DELETE."+dL4(16).toString("hex");K3.renameSync(J,Z),K3.unlinkSync(Z)},jL4=(J,Z,Q)=>J!==void 0&&J===J>>>0?J:Z!==void 0&&Z===Z>>>0?Z:Q,pl0=class extends Tl{[Fl0]=!1;[Pl]=!1;[sZ0]=0;reservations=new ot5;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(J={}){if(J.ondone=()=>{this[Fl0]=!0,this[ql0]()},super(J),this.transform=J.transform,this.chmod=!!J.chmod,typeof J.uid=="number"||typeof J.gid=="number"){if(typeof J.uid!="number"||typeof J.gid!="number")throw TypeError("cannot set owner without number uid and gid");if(J.preserveOwner)throw TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=J.uid,this.gid=J.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;J.preserveOwner===void 0&&typeof J.uid!="number"?this.preserveOwner=!!(process.getuid&&process.getuid()===0):this.preserveOwner=!!J.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof J.maxDepth=="number"?J.maxDepth:tt5,this.forceChown=J.forceChown===!0,this.win32=!!J.win32||Cl,this.newer=!!J.newer,this.keep=!!J.keep,this.noMtime=!!J.noMtime,this.preservePaths=!!J.preservePaths,this.unlink=!!J.unlink,this.cwd=A5(B2.resolve(J.cwd||process.cwd())),this.strip=Number(J.strip)||0,this.processUmask=this.chmod?typeof J.processUmask=="number"?J.processUmask:rt5():0,this.umask=typeof J.umask=="number"?J.umask:this.processUmask,this.dmode=J.dmode||511&~this.umask,this.fmode=J.fmode||438&~this.umask,this.on("entry",(Z)=>this[NL4](Z))}warn(J,Z,Q={}){return(J==="TAR_BAD_ARCHIVE"||J==="TAR_ABORT")&&(Q.recoverable=!1),super.warn(J,Z,Q)}[ql0](){this[Fl0]&&this[sZ0]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Gl0](J,Z){let Q=J[Z],{type:Y}=J;if(!Q||this.preservePaths)return!0;let[X,K]=bl0(Q),V=K.replace(/\\/g,"/").split("/");if(V.includes("..")||Cl&&/^[a-z]:\.\.$/i.test(V[0]??"")){if(Z==="path"||Y==="Link")return this.warn("TAR_ENTRY_ERROR",`${Z} contains '..'`,{entry:J,[Z]:Q}),!1;{let z=B2.posix.dirname(J.path),G=B2.posix.normalize(B2.posix.join(z,Q));if(G.startsWith("../")||G==="..")return this.warn("TAR_ENTRY_ERROR",`${Z} escapes extraction directory`,{entry:J,[Z]:Q}),!1}}return X&&(J[Z]=String(K),this.warn("TAR_ENTRY_INFO",`stripping ${X} from absolute ${Z}`,{entry:J,[Z]:Q})),!0}[ML4](J){let Z=A5(J.path),Q=Z.split("/");if(this.strip){if(Q.length<this.strip)return!1;if(J.type==="Link"){let Y=A5(String(J.linkpath)).split("/");if(Y.length>=this.strip)J.linkpath=Y.slice(this.strip).join("/");else return!1}Q.splice(0,this.strip),J.path=Q.join("/")}if(isFinite(this.maxDepth)&&Q.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:J,path:Z,depth:Q.length,maxDepth:this.maxDepth}),!1;if(!this[Gl0](J,"path")||!this[Gl0](J,"linkpath"))return!1;if(B2.isAbsolute(J.path)?J.absolute=A5(B2.resolve(J.path)):J.absolute=A5(B2.resolve(this.cwd,J.path)),!this.preservePaths&&typeof J.absolute=="string"&&J.absolute.indexOf(this.cwd+"/")!==0&&J.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:J,path:A5(J.path),resolvedPath:J.absolute,cwd:this.cwd}),!1;if(J.absolute===this.cwd&&J.type!=="Directory"&&J.type!=="GNUDumpDir")return!1;if(this.win32){let{root:Y}=B2.win32.parse(String(J.absolute));J.absolute=Y+KL4(String(J.absolute).slice(Y.length));let{root:X}=B2.win32.parse(J.path);J.path=X+KL4(J.path.slice(X.length))}return!0}[NL4](J){if(!this[ML4](J))return J.resume();switch(Tt5.equal(typeof J.absolute,"string"),J.type){case"Directory":case"GNUDumpDir":J.mode&&(J.mode=J.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[Cl0](J);default:return this[EL4](J)}}[a2](J,Z){J.name==="CwdError"?this.emit("error",J):(this.warn("TAR_ENTRY_ERROR",J,{entry:Z}),this[Rk](),Z.resume())}[Yw](J,Z,Q){pt5(A5(J),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:Z},Q)}[jl](J){return this.forceChown||this.preserveOwner&&(typeof J.uid=="number"&&J.uid!==this.processUid||typeof J.gid=="number"&&J.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Rl](J){return jL4(this.uid,J.uid,this.processUid)}[Il](J){return jL4(this.gid,J.gid,this.processGid)}[_l0](J,Z){let Q=typeof J.mode=="number"?J.mode&4095:this.fmode,Y=new HQ0(String(J.absolute),{flags:iL4(J.size),mode:Q,autoClose:!1});Y.on("error",(z)=>{Y.fd&&K3.close(Y.fd,()=>{}),Y.write=()=>!0,this[a2](z,J),Z()});let X=1,K=(z)=>{if(z){Y.fd&&K3.close(Y.fd,()=>{}),this[a2](z,J),Z();return}--X===0&&Y.fd!==void 0&&K3.close(Y.fd,(G)=>{G?this[a2](G,J):this[Rk](),Z()})};Y.on("finish",()=>{let z=String(J.absolute),G=Y.fd;if(typeof G=="number"&&J.mtime&&!this.noMtime){X++;let F=J.atime||new Date,q=J.mtime;K3.futimes(G,F,q,(W)=>W?K3.utimes(z,F,q,(U)=>K(U&&W)):K())}if(typeof G=="number"&&this[jl](J)){X++;let F=this[Rl](J),q=this[Il](J);typeof F=="number"&&typeof q=="number"&&K3.fchown(G,F,q,(W)=>W?K3.chown(z,F,q,(U)=>K(U&&W)):K())}K()});let V=this.transform&&this.transform(J)||J;V!==J&&(V.on("error",(z)=>{this[a2](z,J),Z()}),J.pipe(V)),V.pipe(Y)}[Sl0](J,Z){let Q=typeof J.mode=="number"?J.mode&4095:this.dmode;this[Yw](String(J.absolute),Q,(Y)=>{if(Y){this[a2](Y,J),Z();return}let X=1,K=()=>{--X===0&&(Z(),this[Rk](),J.resume())};J.mtime&&!this.noMtime&&(X++,K3.utimes(String(J.absolute),J.atime||new Date,J.mtime,K)),this[jl](J)&&(X++,K3.chown(String(J.absolute),Number(this[Rl](J)),Number(this[Il](J)),K)),K()})}[EL4](J){J.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${J.type}`,{entry:J}),J.resume()}[LL4](J,Z){let Q=A5(B2.relative(this.cwd,B2.resolve(B2.dirname(String(J.absolute)),String(J.linkpath)))).split("/");this[Ol](J,this.cwd,Q,()=>this[zQ0](J,String(J.linkpath),"symlink",Z),(Y)=>{this[a2](Y,J),Z()})}[OL4](J,Z){let Q=A5(B2.resolve(this.cwd,String(J.linkpath))),Y=A5(String(J.linkpath)).split("/");this[Ol](J,this.cwd,Y,()=>this[zQ0](J,Q,"link",Z),(X)=>{this[a2](X,J),Z()})}[Ol](J,Z,Q,Y,X){let K=Q.shift();if(this.preservePaths||K===void 0)return Y();let V=B2.resolve(Z,K);K3.lstat(V,(z,G)=>{if(z)return Y();if(G?.isSymbolicLink())return X(new EQ0(V,B2.resolve(V,Q.join("/"))));this[Ol](J,V,Q,Y,X)})}[AL4](){this[sZ0]++}[Rk](){this[sZ0]--,this[ql0]()}[kl0](J){this[Rk](),J.resume()}[Tl0](J,Z){return J.type==="File"&&!this.unlink&&Z.isFile()&&Z.nlink<=1&&!Cl}[Cl0](J){this[AL4]();let Z=[J.path];J.linkpath&&Z.push(J.linkpath),this.reservations.reserve(Z,(Q)=>this[wL4](J,Q))}[wL4](J,Z){let Q=(V)=>{Z(V)},Y=()=>{this[Yw](this.cwd,this.dmode,(V)=>{if(V){this[a2](V,J),Q();return}this[Pl]=!0,X()})},X=()=>{if(J.absolute!==this.cwd){let V=A5(B2.dirname(String(J.absolute)));if(V!==this.cwd)return this[Yw](V,this.dmode,(z)=>{if(z){this[a2](z,J),Q();return}K()})}K()},K=()=>{K3.lstat(String(J.absolute),(V,z)=>{if(z&&(this.keep||this.newer&&z.mtime>(J.mtime??z.mtime))){this[kl0](J),Q();return}if(V||this[Tl0](J,z))return this[_K](null,J,Q);if(z.isDirectory()){if(J.type==="Directory"){let G=this.chmod&&J.mode&&(z.mode&4095)!==J.mode,F=(q)=>this[_K](q??null,J,Q);return G?K3.chmod(String(J.absolute),Number(J.mode),F):F()}if(J.absolute!==this.cwd)return K3.rmdir(String(J.absolute),(G)=>this[_K](G??null,J,Q))}if(J.absolute===this.cwd)return this[_K](null,J,Q);et5(String(J.absolute),(G)=>this[_K](G??null,J,Q))})};this[Pl]?X():Y()}[_K](J,Z,Q){if(J){this[a2](J,Z),Q();return}switch(Z.type){case"File":case"OldFile":case"ContiguousFile":return this[_l0](Z,Q);case"Link":return this[OL4](Z,Q);case"SymbolicLink":return this[LL4](Z,Q);case"Directory":case"GNUDumpDir":return this[Sl0](Z,Q)}}[zQ0](J,Z,Q,Y){K3[Q](Z,String(J.absolute),(X)=>{X?this[a2](X,J):(this[Rk](),J.resume()),Y()})}},wl=(J)=>{try{return[null,J()]}catch(Z){return[Z,null]}},tL4=class extends pl0{sync=!0;[_K](J,Z){return super[_K](J,Z,()=>{})}[Cl0](J){if(!this[Pl]){let X=this[Yw](this.cwd,this.dmode);if(X)return this[a2](X,J);this[Pl]=!0}if(J.absolute!==this.cwd){let X=A5(B2.dirname(String(J.absolute)));if(X!==this.cwd){let K=this[Yw](X,this.dmode);if(K)return this[a2](K,J)}}let[Z,Q]=wl(()=>K3.lstatSync(String(J.absolute)));if(Q&&(this.keep||this.newer&&Q.mtime>(J.mtime??Q.mtime)))return this[kl0](J);if(Z||this[Tl0](J,Q))return this[_K](null,J);if(Q.isDirectory()){if(J.type==="Directory"){let K=this.chmod&&J.mode&&(Q.mode&4095)!==J.mode,[V]=K?wl(()=>{K3.chmodSync(String(J.absolute),Number(J.mode))}):[];return this[_K](V,J)}let[X]=wl(()=>K3.rmdirSync(String(J.absolute)));this[_K](X,J)}let[Y]=J.absolute===this.cwd?[]:wl(()=>$e5(String(J.absolute)));this[_K](Y,J)}[_l0](J,Z){let Q=typeof J.mode=="number"?J.mode&4095:this.fmode,Y=(V)=>{let z;try{K3.closeSync(X)}catch(G){z=G}(V||z)&&this[a2](V||z,J),Z()},X;try{X=K3.openSync(String(J.absolute),iL4(J.size),Q)}catch(V){return Y(V)}let K=this.transform&&this.transform(J)||J;K!==J&&(K.on("error",(V)=>this[a2](V,J)),J.pipe(K)),K.on("data",(V)=>{try{K3.writeSync(X,V,0,V.length)}catch(z){Y(z)}}),K.on("end",()=>{let V=null;if(J.mtime&&!this.noMtime){let z=J.atime||new Date,G=J.mtime;try{K3.futimesSync(X,z,G)}catch(F){try{K3.utimesSync(String(J.absolute),z,G)}catch{V=F}}}if(this[jl](J)){let z=this[Rl](J),G=this[Il](J);try{K3.fchownSync(X,Number(z),Number(G))}catch(F){try{K3.chownSync(String(J.absolute),Number(z),Number(G))}catch{V=V||F}}}Y(V)})}[Sl0](J,Z){let Q=typeof J.mode=="number"?J.mode&4095:this.dmode,Y=this[Yw](String(J.absolute),Q);if(Y){this[a2](Y,J),Z();return}if(J.mtime&&!this.noMtime)try{K3.utimesSync(String(J.absolute),J.atime||new Date,J.mtime)}catch{}if(this[jl](J))try{K3.chownSync(String(J.absolute),Number(this[Rl](J)),Number(this[Il](J)))}catch{}Z(),J.resume()}[Yw](J,Z){try{return ct5(A5(J),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:Z})}catch(Q){return Q}}[Ol](J,Z,Q,Y,X){if(this.preservePaths||!Q.length)return Y();let K=Z;for(let V of Q){K=B2.resolve(K,V);let[z,G]=wl(()=>K3.lstatSync(K));if(z)return Y();if(G.isSymbolicLink())return X(new EQ0(K,B2.resolve(Z,Q.join("/"))))}Y()}[zQ0](J,Z,Q,Y){let X=`${Q}Sync`;try{K3[X](Z,String(J.absolute)),Y(),J.resume()}catch(K){return this[a2](K,J)}}},Je5=(J)=>{let Z=new tL4(J),Q=J.file,Y=pL4.statSync(Q),X=J.maxReadSize||16777216;new Ns5(Q,{readSize:X,size:Y.size}).pipe(Z)},Ze5=(J,Z)=>{let Q=new pl0(J),Y=J.maxReadSize||16777216,X=J.file;return new Promise((K,V)=>{Q.on("error",V),Q.on("close",K),pL4.stat(X,(z,G)=>{if(z)V(z);else{let F=new yl0(X,{readSize:Y,size:G.size});F.on("error",V),F.pipe(Q)}})})},Qe5=_l(Je5,Ze5,(J)=>new tL4(J),(J)=>new pl0(J),(J,Z)=>{Z?.length&&xL4(J,Z)}),Ye5=(J,Z)=>{let Q=new ml0(J),Y=!0,X,K;try{try{X=mY.openSync(J.file,"r+")}catch(G){if(G?.code==="ENOENT")X=mY.openSync(J.file,"w+");else throw G}let V=mY.fstatSync(X),z=Buffer.alloc(512);$:for(K=0;K<V.size;K+=512){for(let q=0,W=0;q<512;q+=W){if(W=mY.readSync(X,z,q,z.length-q,K+q),K===0&&z[0]===31&&z[1]===139)throw Error("cannot append to compressed archives");if(!W)break $}let G=new Jj(z);if(!G.cksumValid)break;let F=512*Math.ceil((G.size||0)/512);if(K+F+512>V.size)break;K+=F,J.mtimeCache&&G.mtime&&J.mtimeCache.set(String(G.path),G.mtime)}Y=!1,Xe5(J,Q,K,X,Z)}finally{if(Y)try{mY.closeSync(X)}catch{}}},Xe5=(J,Z,Q,Y,X)=>{let K=new PL4(J.file,{fd:Y,start:Q});Z.pipe(K),Ve5(Z,X)},Ke5=(J,Z)=>{Z=Array.from(Z);let Q=new LQ0(J),Y=(X,K,V)=>{let z=(U,H)=>{U?mY.close(X,(D)=>V(U)):V(null,H)},G=0;if(K===0)return z(null,0);let F=0,q=Buffer.alloc(512),W=(U,H)=>{if(U||typeof H>"u")return z(U);if(F+=H,F<512&&H)return mY.read(X,q,F,q.length-F,G+F,W);if(G===0&&q[0]===31&&q[1]===139)return z(Error("cannot append to compressed archives"));if(F<512)return z(null,G);let D=new Jj(q);if(!D.cksumValid)return z(null,G);let B=512*Math.ceil((D.size??0)/512);if(G+B+512>K||(G+=B+512,G>=K))return z(null,G);J.mtimeCache&&D.mtime&&J.mtimeCache.set(String(D.path),D.mtime),F=0,mY.read(X,q,0,512,G,W)};mY.read(X,q,0,512,G,W)};return new Promise((X,K)=>{Q.on("error",K);let V="r+",z=(G,F)=>{if(G&&G.code==="ENOENT"&&V==="r+")return V="w+",mY.open(J.file,V,z);if(G||!F)return K(G);mY.fstat(F,(q,W)=>{if(q)return mY.close(F,()=>K(q));Y(F,W.size,(U,H)=>{if(U)return K(U);let D=new HQ0(J.file,{fd:F,start:H});Q.pipe(D),D.on("error",K),D.on("close",X),ze5(Q,Z)})})};mY.open(J.file,V,z)})},Ve5=(J,Z)=>{Z.forEach((Q)=>{Q.charAt(0)==="@"?NQ0({file:eL4.resolve(J.cwd,Q.slice(1)),sync:!0,noResume:!0,onReadEntry:(Y)=>J.add(Y)}):J.add(Q)}),J.end()},ze5=async(J,Z)=>{for(let Q=0;Q<Z.length;Q++){let Y=String(Z[Q]);Y.charAt(0)==="@"?await NQ0({file:eL4.resolve(String(J.cwd),Y.slice(1)),noResume:!0,onReadEntry:(X)=>J.add(X)}):J.add(Y)}J.end()},Ll=_l(Ye5,Ke5,()=>{throw TypeError("file is required")},()=>{throw TypeError("file is required")},(J,Z)=>{if(!Rs5(J))throw TypeError("file is required");if(J.gzip||J.brotli||J.zstd||J.file.endsWith(".br")||J.file.endsWith(".tbr"))throw TypeError("cannot append to compressed archives");if(!Z?.length)throw TypeError("no paths specified to add/replace")}),g59=_l(Ll.syncFile,Ll.asyncFile,Ll.syncNoFile,Ll.asyncNoFile,(J,Z=[])=>{Ll.validate?.(J,Z),Ge5(J)}),Ge5=(J)=>{let Z=J.filter;J.mtimeCache||(J.mtimeCache=new Map),J.filter=Z?(Q,Y)=>Z(Q,Y)&&!((J.mtimeCache?.get(Q)??Y.mtime??0)>(Y.mtime??0)):(Q,Y)=>!((J.mtimeCache?.get(Q)??Y.mtime??0)>(Y.mtime??0))};j9();j9();var M39=class{initApp;#$;constructor(J){this.initApp=J?.initApp,this.#$=J?.defaultAppOptions}createApp=(J)=>{let Z=new uZ0(J&&this.#$?{...this.#$,...J}:J??this.#$);if(this.initApp)this.initApp(Z);return Z};createMiddleware=(J)=>J;createHandlers=(...J)=>{return J.filter((Z)=>Z!==void 0)}};var We5=B4(wz(),1);var $O4=v.string(),dl0=v.object({actor_id:$O4,name:v.string(),key:v.string(),namespace_id:$O4,runner_name_selector:v.string(),create_ts:v.number(),connectable_ts:v.number().nullable().optional(),destroy_ts:v.number().nullable().optional(),sleep_ts:v.number().nullable().optional(),start_ts:v.number().nullable().optional(),error:v.unknown().nullable().optional()}),qe5=v.object({metadata:v.record(v.string(),v.unknown())}),J89=v.object({actors:v.array(dl0)}),Z89=v.object({datacenter:v.string().optional(),name:v.string(),runner_name_selector:v.string(),crash_policy:v.string(),key:v.string().nullable().optional(),input:v.string().nullable().optional()}),Q89=v.object({actor:dl0}),Y89=v.object({datacenter:v.string().optional(),name:v.string(),key:v.string(),runner_name_selector:v.string(),crash_policy:v.string(),input:v.string().nullable().optional()}),X89=v.object({actor:dl0,created:v.boolean()}),K89=v.object({}),V89=v.object({names:v.record(v.string(),qe5)}),z89=v.object({value:v.string().nullable()});var q89=class{#$;#J;constructor(J){this.#J=J}async acquire(J){if(!this.#$){let Q=this.#J.sqlitePool,Y=["@rivetkit","sqlite-vfs"].join("/");this.#$=import(Y).then(({SqliteVfsPool:X})=>new X({actorsPerInstance:Q.actorsPerInstance,idleDestroyMs:Q.idleDestroyMs}))}return await(await this.#$).acquire(J)}async shutdown(){if(this.#$)await(await this.#$).shutdown()}};function kk(J){return Pc0(J)}var Ue5="https://production.ampworkers.com",He5="https://staging.ampworkers.com";function i7(J){if(J.includes("staging.ampcodedev.org"))return He5;return Ue5}var De5="https://thread-actors-prod-us-east1-935747076731.us-east1.run.app",Be5="https://thread-actors-staging-us-east1-739316246630.us-east1.run.app";function vk(J){if(J.includes("staging.ampcodedev.org"))return Be5;return De5}async function JO4(J){let Z=J.workerURL??i7(J.ampURL),Q=await J.configService.getLatest(J.signal),Y=await Q.secrets.getToken("apiKey",Q.settings.url);if(!Y)throw Error("API key required. Please run `amp login` first.");let X=await fetch(`${Z}/threads/${J.threadID}/context-analysis`,{method:"GET",headers:{Authorization:`Bearer ${Y}`},signal:J.signal});if(!X.ok){let V=await X.text();throw Error(`Context analysis request failed (${X.status}): ${V}`)}let K=await X.json();if(!K.ok||!K.analysis)throw Error(K.error??"Invalid context analysis response from DTW");return K.analysis}async function ZO4(J){let Z=vk(J.ampURL),Q=kk({endpoint:Z}),Y=await J.configService.getLatest(J.signal),X=await Y.secrets.getToken("apiKey",Y.settings.url);if(!X)throw Error("API key required. Please run `amp login` first.");let K=await Q.threadActor.get([J.threadID]).fetch("/context-analysis",{method:"GET",headers:{Authorization:`Bearer ${X}`},signal:J.signal});if(!K.ok){let z=await K.text();throw Error(`Context analysis request failed (${K.status}): ${z}`)}let V=await K.json();if(!V.ok||!V.analysis)throw Error(V.error??"Invalid context analysis response from DTW");return V.analysis}var QO4=process.hrtime.bigint(),cl0=null;function YO4(){cl0=process.hrtime.bigint()}function XO4(){if(cl0===null)return null;return Number(process.hrtime.bigint()-cl0)/1e6}PX();m0();var Wj4=B4(O4(),1),dY=B4(Fj4(),1),Uj4=B4(zj(),1);import rQ0 from"node:fs";import Pn0 from"node:path";var qj4=Object.keys(P),Y83=Pn0.join(nZ,"logs"),Cn0=Pn0.join(Y83,"cli.log"),X83=10485760;function K83(J){try{if(rQ0.statSync(J).size>X83)rQ0.truncateSync(J,0)}catch{}}var Zi,Tn0=!1,Ji=null;function V83(J){return J instanceof Error&&J.message.includes("write after end")}function $i(J,Z,Q,Y){if(Tn0)return;try{J[Z](Q,...Y)}catch(X){if(!V83(X))throw X}}function Hj4(J){Tn0=!1,Ji=null;let{logFile:Z,logLevel:Q}=J;if(!qj4.includes(Q))console.warn(`Invalid log level: ${Q}. Using 'info' instead.`);try{rQ0.mkdirSync(Pn0.dirname(Z),{recursive:!0})}catch(z){console.error(`Failed to create log directory: ${z}`)}K83(Z);let Y=dY.default.format((z)=>{for(let G of Object.keys(z)){let F=z[G];if(F instanceof Error)z[G]={name:F.name,message:F.message,stack:F.stack}}return z}),X=dY.default.format((z)=>{return z.pid=process.pid,z}),K=[new dY.default.transports.File({filename:Z}),new Dj4];if(process.env.AMP_CLI_STDOUT_DEBUG==="true")K.push(new dY.default.transports.Console({level:"debug",format:dY.default.format.combine(dY.default.format.colorize(),dY.default.format.simple())}));Zi=dY.default.createLogger({level:qj4.includes(Q)?Q:"info",format:dY.default.format.combine(dY.default.format.timestamp(),X(),Y(),dY.default.format.json(),dY.default.format.errors({stack:!0})),transports:K});let V=Zi;return My1({error:(z,...G)=>{$i(V,"error",z,G)},warn:(z,...G)=>{$i(V,"warn",z,G)},info:(z,...G)=>{$i(V,"info",z,G)},debug:(z,...G)=>{$i(V,"debug",z,G)},audit:(z,...G)=>{let F=typeof G[0]==="object"&&G[0]!==null?{audit:!0,...G[0]}:{audit:!0};$i(V,"info",z,[F])}}),Z}class Dj4 extends Uj4.default{log({message:J,...Z},Q){Wj4.trace.getActiveSpan()?.addEvent(J,Z),Q()}}function VH(){if(Ji)return Ji;let J=Zi;if(!J)return Promise.resolve();return Tn0=!0,Ji=new Promise((Z)=>{let Q=!1,Y=()=>{if(!Q){if(Q=!0,Zi===J)Zi=void 0;Z()}};setImmediate(()=>{try{J.once("finish",Y).once("error",Y).end()}catch{Y()}}),setTimeout(Y,500)}),Ji}m0();import{execFile as z83}from"node:child_process";import{promisify as G83}from"node:util";var F83=G83(z83),q83=["private","public","workspace"];function _n0(J){return J.endsWith("/")?J.slice(0,-1):J}function W83(J){let Z=HJ0(J);try{let X=new URL(Z);return _n0(`${X.host}${X.pathname}`).replace(/^\//,"")}catch{}let Q=Z.match(/^[^@]+@([^:/]+)[:/](.+)$/);if(Q?.[1]&&Q[2])return _n0(`${Q[1]}/${Q[2]}`).replace(/\.git$/,"");let Y=Z.match(/^([^:]+):(.+)$/);if(Y?.[1]&&Y[2])return _n0(`${Y[1]}/${Y[2]}`).replace(/\.git$/,"");return null}async function wj4(J){try{let{stdout:Z}=await F83("git",["remote","get-url","origin"],{cwd:J}),Q=Z.trim();if(!Q)return null;return W83(Q)}catch{return null}}function U83(J){let Z=[...q83];if(J?.team?.disablePrivateThreads){let Q=Z.indexOf("private");if(Q!==-1)Z.splice(Q,1)}if(J?.team?.groups&&J.team.groups.length>0)Z.push("group");return Z}function Bj4(J){let Z=J?.team?.disablePrivateThreads??!1,Q=J?.team?.defaultThreadVisibility;if(!Q||Q==="private")return Z?"workspace":"private";if(Q==="thread_workspace_shared")return"workspace";if(Q==="creator_groups_fallback_private"){if(J?.team?.groups?.length)return"group";return Z?"workspace":"private"}return Z?"workspace":"private"}function H83(J){if(J?.team?.groups!==void 0)return Error(["Group visibility is not available. ",`You are not a member of any group in this workspace.
|
|
4667
|
+
`).reduce(Yt5,Object.create(null)),Yt5=(J,Z)=>{let Q=parseInt(Z,10);if(Q!==Buffer.byteLength(Z)+1)return J;Z=Z.slice((Q+" ").length);let Y=Z.split("="),X=Y.shift();if(!X)return J;let K=X.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),V=Y.join("=");return J[K]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(K)?new Date(Number(V)*1000):/^[0-9]+$/.test(V)?+V:V,J},Xt5=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,A5=Xt5!=="win32"?(J)=>J:(J)=>J&&J.replace(/\\/g,"/"),yL4=class extends Zj{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(J,Z,Q){switch(super({}),this.pause(),this.extended=Z,this.globalExtended=Q,this.header=J,this.remain=J.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=J.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!J.path)throw Error("no path provided for tar.ReadEntry");this.path=A5(J.path),this.mode=J.mode,this.mode&&(this.mode=this.mode&4095),this.uid=J.uid,this.gid=J.gid,this.uname=J.uname,this.gname=J.gname,this.size=this.remain,this.mtime=J.mtime,this.atime=J.atime,this.ctime=J.ctime,this.linkpath=J.linkpath?A5(J.linkpath):void 0,this.uname=J.uname,this.gname=J.gname,Z&&this.#$(Z),Q&&this.#$(Q,!0)}write(J){let Z=J.length;if(Z>this.blockRemain)throw Error("writing more to entry than is appropriate");let Q=this.remain,Y=this.blockRemain;return this.remain=Math.max(0,Q-Z),this.blockRemain=Math.max(0,Y-Z),this.ignore?!0:Q>=Z?super.write(J):super.write(J.subarray(0,Q))}#$(J,Z=!1){J.path&&(J.path=A5(J.path)),J.linkpath&&(J.linkpath=A5(J.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(J).filter(([Q,Y])=>!(Y==null||Q==="path"&&Z))))}},BQ0=(J,Z,Q,Y={})=>{J.file&&(Y.file=J.file),J.cwd&&(Y.cwd=J.cwd),Y.code=Q instanceof Error&&Q.code||Z,Y.tarCode=Z,!J.strict&&Y.recoverable!==!1?(Q instanceof Error&&(Y=Object.assign(Q,Y),Q=Q.message),J.emit("warn",Z,Q,Y)):Q instanceof Error?J.emit("error",Object.assign(Q,Y)):J.emit("error",Object.assign(Error(`${Z}: ${Q}`),Y))},Kt5=1048576,Dl0=Buffer.from([31,139]),Bl0=Buffer.from([40,181,47,253]),Vt5=Math.max(Dl0.length,Bl0.length),TK=Symbol("state"),nA=Symbol("writeEntry"),ZH=Symbol("readEntry"),ec0=Symbol("nextEntry"),ew4=Symbol("processEntry"),Jq=Symbol("extendedHeader"),Ul=Symbol("globalExtendedHeader"),sN=Symbol("meta"),$L4=Symbol("emitMeta"),g8=Symbol("buffer"),QH=Symbol("queue"),tN=Symbol("ended"),$l0=Symbol("emittedEnd"),aA=Symbol("emit"),l7=Symbol("unzip"),lZ0=Symbol("consumeChunk"),iZ0=Symbol("consumeChunkSub"),Jl0=Symbol("consumeBody"),JL4=Symbol("consumeMeta"),ZL4=Symbol("consumeHeader"),Hl=Symbol("consuming"),Zl0=Symbol("bufferConcat"),nZ0=Symbol("maybeEnd"),Ak=Symbol("writing"),eN=Symbol("aborted"),aZ0=Symbol("onDone"),oA=Symbol("sawValidEntry"),oZ0=Symbol("sawNullBlock"),rZ0=Symbol("sawEOF"),QL4=Symbol("closeStream"),zt5=()=>!0,Tl=class extends Ps5{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[QH]=[];[g8];[ZH];[nA];[TK]="begin";[sN]="";[Jq];[Ul];[tN]=!1;[l7];[eN]=!1;[oA];[oZ0]=!1;[rZ0]=!1;[Ak]=!1;[Hl]=!1;[$l0]=!1;constructor(J={}){super(),this.file=J.file||"",this.on(aZ0,()=>{(this[TK]==="begin"||this[oA]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),J.ondone?this.on(aZ0,J.ondone):this.on(aZ0,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!J.strict,this.maxMetaEntrySize=J.maxMetaEntrySize||Kt5,this.filter=typeof J.filter=="function"?J.filter:zt5;let Z=J.file&&(J.file.endsWith(".tar.br")||J.file.endsWith(".tbr"));this.brotli=!(J.gzip||J.zstd)&&J.brotli!==void 0?J.brotli:Z?void 0:!1;let Q=J.file&&(J.file.endsWith(".tar.zst")||J.file.endsWith(".tzst"));this.zstd=!(J.gzip||J.brotli)&&J.zstd!==void 0?J.zstd:Q?!0:void 0,this.on("end",()=>this[QL4]()),typeof J.onwarn=="function"&&this.on("warn",J.onwarn),typeof J.onReadEntry=="function"&&this.on("entry",J.onReadEntry)}warn(J,Z,Q={}){BQ0(this,J,Z,Q)}[ZL4](J,Z){this[oA]===void 0&&(this[oA]=!1);let Q;try{Q=new Jj(J,Z,this[Jq],this[Ul])}catch(Y){return this.warn("TAR_ENTRY_INVALID",Y)}if(Q.nullBlock)this[oZ0]?(this[rZ0]=!0,this[TK]==="begin"&&(this[TK]="header"),this[aA]("eof")):(this[oZ0]=!0,this[aA]("nullBlock"));else if(this[oZ0]=!1,!Q.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:Q});else if(!Q.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:Q});else{let Y=Q.type;if(/^(Symbolic)?Link$/.test(Y)&&!Q.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:Q});else if(!/^(Symbolic)?Link$/.test(Y)&&!/^(Global)?ExtendedHeader$/.test(Y)&&Q.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:Q});else{let X=this[nA]=new yL4(Q,this[Jq],this[Ul]);if(!this[oA])if(X.remain){let K=()=>{X.invalid||(this[oA]=!0)};X.on("end",K)}else this[oA]=!0;X.meta?X.size>this.maxMetaEntrySize?(X.ignore=!0,this[aA]("ignoredEntry",X),this[TK]="ignore",X.resume()):X.size>0&&(this[sN]="",X.on("data",(K)=>this[sN]+=K),this[TK]="meta"):(this[Jq]=void 0,X.ignore=X.ignore||!this.filter(X.path,X),X.ignore?(this[aA]("ignoredEntry",X),this[TK]=X.remain?"ignore":"header",X.resume()):(X.remain?this[TK]="body":(this[TK]="header",X.end()),this[ZH]?this[QH].push(X):(this[QH].push(X),this[ec0]())))}}}[QL4](){queueMicrotask(()=>this.emit("close"))}[ew4](J){let Z=!0;if(!J)this[ZH]=void 0,Z=!1;else if(Array.isArray(J)){let[Q,...Y]=J;this.emit(Q,...Y)}else this[ZH]=J,this.emit("entry",J),J.emittedEnd||(J.on("end",()=>this[ec0]()),Z=!1);return Z}[ec0](){do;while(this[ew4](this[QH].shift()));if(!this[QH].length){let J=this[ZH];!J||J.flowing||J.size===J.remain?this[Ak]||this.emit("drain"):J.once("drain",()=>this.emit("drain"))}}[Jl0](J,Z){let Q=this[nA];if(!Q)throw Error("attempt to consume body without entry??");let Y=Q.blockRemain??0,X=Y>=J.length&&Z===0?J:J.subarray(Z,Z+Y);return Q.write(X),Q.blockRemain||(this[TK]="header",this[nA]=void 0,Q.end()),X.length}[JL4](J,Z){let Q=this[nA],Y=this[Jl0](J,Z);return!this[nA]&&Q&&this[$L4](Q),Y}[aA](J,Z,Q){!this[QH].length&&!this[ZH]?this.emit(J,Z,Q):this[QH].push([J,Z,Q])}[$L4](J){switch(this[aA]("meta",this[sN]),J.type){case"ExtendedHeader":case"OldExtendedHeader":this[Jq]=GQ0.parse(this[sN],this[Jq],!1);break;case"GlobalExtendedHeader":this[Ul]=GQ0.parse(this[sN],this[Ul],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let Z=this[Jq]??Object.create(null);this[Jq]=Z,Z.path=this[sN].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let Z=this[Jq]||Object.create(null);this[Jq]=Z,Z.linkpath=this[sN].replace(/\0.*/,"");break}default:throw Error("unknown meta: "+J.type)}}abort(J){this[eN]=!0,this.emit("abort",J),this.warn("TAR_ABORT",J,{recoverable:!1})}write(J,Z,Q){if(typeof Z=="function"&&(Q=Z,Z=void 0),typeof J=="string"&&(J=Buffer.from(J,typeof Z=="string"?Z:"utf8")),this[eN])return Q?.(),!1;if((this[l7]===void 0||this.brotli===void 0&&this[l7]===!1)&&J){if(this[g8]&&(J=Buffer.concat([this[g8],J]),this[g8]=void 0),J.length<Vt5)return this[g8]=J,Q?.(),!0;for(let V=0;this[l7]===void 0&&V<Dl0.length;V++)J[V]!==Dl0[V]&&(this[l7]=!1);let X=!1;if(this[l7]===!1&&this.zstd!==!1){X=!0;for(let V=0;V<Bl0.length;V++)if(J[V]!==Bl0[V]){X=!1;break}}let K=this.brotli===void 0&&!X;if(this[l7]===!1&&K)if(J.length<512)if(this[tN])this.brotli=!0;else return this[g8]=J,Q?.(),!0;else try{new Jj(J.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[l7]===void 0||this[l7]===!1&&(this.brotli||X)){let V=this[tN];this[tN]=!1,this[l7]=this[l7]===void 0?new vs5({}):X?new us5({}):new xs5({}),this[l7].on("data",(G)=>this[lZ0](G)),this[l7].on("error",(G)=>this.abort(G)),this[l7].on("end",()=>{this[tN]=!0,this[lZ0]()}),this[Ak]=!0;let z=!!this[l7][V?"end":"write"](J);return this[Ak]=!1,Q?.(),z}}this[Ak]=!0,this[l7]?this[l7].write(J):this[lZ0](J),this[Ak]=!1;let Y=this[QH].length?!1:this[ZH]?this[ZH].flowing:!0;return!Y&&!this[QH].length&&this[ZH]?.once("drain",()=>this.emit("drain")),Q?.(),Y}[Zl0](J){J&&!this[eN]&&(this[g8]=this[g8]?Buffer.concat([this[g8],J]):J)}[nZ0](){if(this[tN]&&!this[$l0]&&!this[eN]&&!this[Hl]){this[$l0]=!0;let J=this[nA];if(J&&J.blockRemain){let Z=this[g8]?this[g8].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${J.blockRemain} more bytes, only ${Z} available)`,{entry:J}),this[g8]&&J.write(this[g8]),J.end()}this[aA](aZ0)}}[lZ0](J){if(this[Hl]&&J)this[Zl0](J);else if(!J&&!this[g8])this[nZ0]();else if(J){if(this[Hl]=!0,this[g8]){this[Zl0](J);let Z=this[g8];this[g8]=void 0,this[iZ0](Z)}else this[iZ0](J);for(;this[g8]&&this[g8]?.length>=512&&!this[eN]&&!this[rZ0];){let Z=this[g8];this[g8]=void 0,this[iZ0](Z)}this[Hl]=!1}(!this[g8]||this[tN])&&this[nZ0]()}[iZ0](J){let Z=0,Q=J.length;for(;Z+512<=Q&&!this[eN]&&!this[rZ0];)switch(this[TK]){case"begin":case"header":this[ZL4](J,Z),Z+=512;break;case"ignore":case"body":Z+=this[Jl0](J,Z);break;case"meta":Z+=this[JL4](J,Z);break;default:throw Error("invalid state: "+this[TK])}Z<Q&&(this[g8]?this[g8]=Buffer.concat([J.subarray(Z),this[g8]]):this[g8]=J.subarray(Z))}end(J,Z,Q){return typeof J=="function"&&(Q=J,Z=void 0,J=void 0),typeof Z=="function"&&(Q=Z,Z=void 0),typeof J=="string"&&(J=Buffer.from(J,Z)),Q&&this.once("finish",Q),this[eN]||(this[l7]?(J&&this[l7].write(J),this[l7].end()):(this[tN]=!0,(this.brotli===void 0||this.zstd===void 0)&&(J=J||Buffer.alloc(0)),J&&this.write(J),this[nZ0]())),this}},Ml=(J)=>{let Z=J.length-1,Q=-1;for(;Z>-1&&J.charAt(Z)==="/";)Q=Z,Z--;return Q===-1?J:J.slice(0,Q)},Gt5=(J)=>{let Z=J.onReadEntry;J.onReadEntry=Z?(Q)=>{Z(Q),Q.resume()}:(Q)=>Q.resume()},xL4=(J,Z)=>{let Q=new Map(Z.map((K)=>[Ml(K),!0])),Y=J.filter,X=(K,V="")=>{let z=V||Ls5(K).root||".",G;if(K===z)G=!1;else{let F=Q.get(K);F!==void 0?G=F:G=X(ws5(K),z)}return Q.set(K,G),G};J.filter=Y?(K,V)=>Y(K,V)&&X(Ml(K)):(K)=>X(Ml(K))},Ft5=(J)=>{let Z=new Tl(J),Q=J.file,Y;try{Y=Tk.openSync(Q,"r");let X=Tk.fstatSync(Y),K=J.maxReadSize||16777216;if(X.size<K){let V=Buffer.allocUnsafe(X.size),z=Tk.readSync(Y,V,0,X.size,0);Z.end(z===V.byteLength?V:V.subarray(0,z))}else{let V=0,z=Buffer.allocUnsafe(K);for(;V<X.size;){let G=Tk.readSync(Y,z,0,K,V);if(G===0)break;V+=G,Z.write(z.subarray(0,G))}Z.end()}}finally{if(typeof Y=="number")try{Tk.closeSync(Y)}catch{}}},qt5=(J,Z)=>{let Q=new Tl(J),Y=J.maxReadSize||16777216,X=J.file;return new Promise((K,V)=>{Q.on("error",V),Q.on("end",K),Tk.stat(X,(z,G)=>{if(z)V(z);else{let F=new yl0(X,{readSize:Y,size:G.size});F.on("error",V),F.pipe(Q)}})})},NQ0=_l(Ft5,qt5,(J)=>new Tl(J),(J)=>new Tl(J),(J,Z)=>{Z?.length&&xL4(J,Z),J.noResume||Gt5(J)}),fL4=(J,Z,Q)=>(J&=4095,Q&&(J=(J|384)&-19),Z&&(J&256&&(J|=64),J&32&&(J|=8),J&4&&(J|=1)),J),{isAbsolute:Ut5,parse:XL4}=Wt5,bl0=(J)=>{let Z="",Q=XL4(J);for(;Ut5(J)||Q.root;){let Y=J.charAt(0)==="/"&&J.slice(0,4)!=="//?/"?"/":Q.root;J=J.slice(Y.length),Z+=Y,Q=XL4(J)}return[Z,J]},wQ0=["|","<",">","?",":"],hl0=wQ0.map((J)=>String.fromCharCode(61440+J.charCodeAt(0))),Ht5=new Map(wQ0.map((J,Z)=>[J,hl0[Z]])),Dt5=new Map(hl0.map((J,Z)=>[J,wQ0[Z]])),KL4=(J)=>wQ0.reduce((Z,Q)=>Z.split(Q).join(Ht5.get(Q)),J),Bt5=(J)=>hl0.reduce((Z,Q)=>Z.split(Q).join(Dt5.get(Q)),J),uL4=(J,Z)=>Z?(J=A5(J).replace(/^\.(\/|$)/,""),Ml(Z)+"/"+J):A5(J),Nt5=16777216,VL4=Symbol("process"),zL4=Symbol("file"),GL4=Symbol("directory"),Nl0=Symbol("symlink"),FL4=Symbol("hardlink"),Dl=Symbol("header"),JQ0=Symbol("read"),wl0=Symbol("lstat"),ZQ0=Symbol("onlstat"),Ll0=Symbol("onread"),Ol0=Symbol("onreadlink"),El0=Symbol("openfile"),Ml0=Symbol("onopenfile"),Qw=Symbol("close"),qQ0=Symbol("mode"),Al0=Symbol("awaitDrain"),Ql0=Symbol("ondrain"),Qq=Symbol("prefix"),bL4=class extends Zj{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#$=!1;constructor(J,Z={}){let Q=xl0(Z);super(),this.path=A5(J),this.portable=!!Q.portable,this.maxReadSize=Q.maxReadSize||Nt5,this.linkCache=Q.linkCache||new Map,this.statCache=Q.statCache||new Map,this.preservePaths=!!Q.preservePaths,this.cwd=A5(Q.cwd||process.cwd()),this.strict=!!Q.strict,this.noPax=!!Q.noPax,this.noMtime=!!Q.noMtime,this.mtime=Q.mtime,this.prefix=Q.prefix?A5(Q.prefix):void 0,this.onWriteEntry=Q.onWriteEntry,typeof Q.onwarn=="function"&&this.on("warn",Q.onwarn);let Y=!1;if(!this.preservePaths){let[K,V]=bl0(this.path);K&&typeof V=="string"&&(this.path=V,Y=K)}this.win32=!!Q.win32||process.platform==="win32",this.win32&&(this.path=Bt5(this.path.replace(/\\/g,"/")),J=J.replace(/\\/g,"/")),this.absolute=A5(Q.absolute||YL4.resolve(this.cwd,J)),this.path===""&&(this.path="./"),Y&&this.warn("TAR_ENTRY_INFO",`stripping ${Y} from absolute path`,{entry:this,path:Y+this.path});let X=this.statCache.get(this.absolute);X?this[ZQ0](X):this[wl0]()}warn(J,Z,Q={}){return BQ0(this,J,Z,Q)}emit(J,...Z){return J==="error"&&(this.#$=!0),super.emit(J,...Z)}[wl0](){Zq.lstat(this.absolute,(J,Z)=>{if(J)return this.emit("error",J);this[ZQ0](Z)})}[ZQ0](J){this.statCache.set(this.absolute,J),this.stat=J,J.isFile()||(J.size=0),this.type=Ot5(J),this.emit("stat",J),this[VL4]()}[VL4](){switch(this.type){case"File":return this[zL4]();case"Directory":return this[GL4]();case"SymbolicLink":return this[Nl0]();default:return this.end()}}[qQ0](J){return fL4(J,this.type==="Directory",this.portable)}[Qq](J){return uL4(J,this.prefix)}[Dl](){if(!this.stat)throw Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new Jj({path:this[Qq](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Qq](this.linkpath):this.linkpath,mode:this[qQ0](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new GQ0({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[Qq](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Qq](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let J=this.header?.block;if(!J)throw Error("failed to encode header");super.write(J)}[GL4](){if(!this.stat)throw Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Dl](),this.end()}[Nl0](){Zq.readlink(this.absolute,(J,Z)=>{if(J)return this.emit("error",J);this[Ol0](Z)})}[Ol0](J){this.linkpath=A5(J),this[Dl](),this.end()}[FL4](J){if(!this.stat)throw Error("cannot create link entry without stat");this.type="Link",this.linkpath=A5(YL4.relative(this.cwd,J)),this.stat.size=0,this[Dl](),this.end()}[zL4](){if(!this.stat)throw Error("cannot create file entry without stat");if(this.stat.nlink>1){let J=`${this.stat.dev}:${this.stat.ino}`,Z=this.linkCache.get(J);if(Z?.indexOf(this.cwd)===0)return this[FL4](Z);this.linkCache.set(J,this.absolute)}if(this[Dl](),this.stat.size===0)return this.end();this[El0]()}[El0](){Zq.open(this.absolute,"r",(J,Z)=>{if(J)return this.emit("error",J);this[Ml0](Z)})}[Ml0](J){if(this.fd=J,this.#$)return this[Qw]();if(!this.stat)throw Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let Z=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(Z),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[JQ0]()}[JQ0](){let{fd:J,buf:Z,offset:Q,length:Y,pos:X}=this;if(J===void 0||Z===void 0)throw Error("cannot read file without first opening");Zq.read(J,Z,Q,Y,X,(K,V)=>{if(K)return this[Qw](()=>this.emit("error",K));this[Ll0](V)})}[Qw](J=()=>{}){this.fd!==void 0&&Zq.close(this.fd,J)}[Ll0](J){if(J<=0&&this.remain>0){let Q=Object.assign(Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[Qw](()=>this.emit("error",Q))}if(J>this.remain){let Q=Object.assign(Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[Qw](()=>this.emit("error",Q))}if(!this.buf)throw Error("should have created buffer prior to reading");if(J===this.remain)for(let Q=J;Q<this.length&&J<this.blockRemain;Q++)this.buf[Q+this.offset]=0,J++,this.remain++;let Z=this.offset===0&&J===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+J);this.write(Z)?this[Ql0]():this[Al0](()=>this[Ql0]())}[Al0](J){this.once("drain",J)}write(J,Z,Q){if(typeof Z=="function"&&(Q=Z,Z=void 0),typeof J=="string"&&(J=Buffer.from(J,typeof Z=="string"?Z:"utf8")),this.blockRemain<J.length){let Y=Object.assign(Error("writing more data than expected"),{path:this.absolute});return this.emit("error",Y)}return this.remain-=J.length,this.blockRemain-=J.length,this.pos+=J.length,this.offset+=J.length,super.write(J,null,Q)}[Ql0](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[Qw]((J)=>J?this.emit("error",J):this.end());if(!this.buf)throw Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[JQ0]()}},wt5=class extends bL4{sync=!0;[wl0](){this[ZQ0](Zq.lstatSync(this.absolute))}[Nl0](){this[Ol0](Zq.readlinkSync(this.absolute))}[El0](){this[Ml0](Zq.openSync(this.absolute,"r"))}[JQ0](){let J=!0;try{let{fd:Z,buf:Q,offset:Y,length:X,pos:K}=this;if(Z===void 0||Q===void 0)throw Error("fd and buf must be set in READ method");let V=Zq.readSync(Z,Q,Y,X,K);this[Ll0](V),J=!1}finally{if(J)try{this[Qw](()=>{})}catch{}}}[Al0](J){J()}[Qw](J=()=>{}){this.fd!==void 0&&Zq.closeSync(this.fd),J()}},Lt5=class extends Zj{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(J,Z,Q={}){return BQ0(this,J,Z,Q)}constructor(J,Z={}){let Q=xl0(Z);super(),this.preservePaths=!!Q.preservePaths,this.portable=!!Q.portable,this.strict=!!Q.strict,this.noPax=!!Q.noPax,this.noMtime=!!Q.noMtime,this.onWriteEntry=Q.onWriteEntry,this.readEntry=J;let{type:Y}=J;if(Y==="Unsupported")throw Error("writing entry that should be ignored");this.type=Y,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=Q.prefix,this.path=A5(J.path),this.mode=J.mode!==void 0?this[qQ0](J.mode):void 0,this.uid=this.portable?void 0:J.uid,this.gid=this.portable?void 0:J.gid,this.uname=this.portable?void 0:J.uname,this.gname=this.portable?void 0:J.gname,this.size=J.size,this.mtime=this.noMtime?void 0:Q.mtime||J.mtime,this.atime=this.portable?void 0:J.atime,this.ctime=this.portable?void 0:J.ctime,this.linkpath=J.linkpath!==void 0?A5(J.linkpath):void 0,typeof Q.onwarn=="function"&&this.on("warn",Q.onwarn);let X=!1;if(!this.preservePaths){let[V,z]=bl0(this.path);V&&typeof z=="string"&&(this.path=z,X=V)}this.remain=J.size,this.blockRemain=J.startBlockSize,this.onWriteEntry?.(this),this.header=new Jj({path:this[Qq](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Qq](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),X&&this.warn("TAR_ENTRY_INFO",`stripping ${X} from absolute path`,{entry:this,path:X+this.path}),this.header.encode()&&!this.noPax&&super.write(new GQ0({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[Qq](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Qq](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let K=this.header?.block;if(!K)throw Error("failed to encode header");super.write(K),J.pipe(this)}[Qq](J){return uL4(J,this.prefix)}[qQ0](J){return fL4(J,this.type==="Directory",this.portable)}write(J,Z,Q){typeof Z=="function"&&(Q=Z,Z=void 0),typeof J=="string"&&(J=Buffer.from(J,typeof Z=="string"?Z:"utf8"));let Y=J.length;if(Y>this.blockRemain)throw Error("writing more to entry than is appropriate");return this.blockRemain-=Y,super.write(J,Q)}end(J,Z,Q){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof J=="function"&&(Q=J,Z=void 0,J=void 0),typeof Z=="function"&&(Q=Z,Z=void 0),typeof J=="string"&&(J=Buffer.from(J,Z??"utf8")),Q&&this.once("finish",Q),J?super.end(J,Q):super.end(Q),this}},Ot5=(J)=>J.isFile()?"File":J.isDirectory()?"Directory":J.isSymbolicLink()?"SymbolicLink":"Unsupported",Et5=class J{tail;head;length=0;static create(Z=[]){return new J(Z)}constructor(Z=[]){for(let Q of Z)this.push(Q)}*[Symbol.iterator](){for(let Z=this.head;Z;Z=Z.next)yield Z.value}removeNode(Z){if(Z.list!==this)throw Error("removing node which does not belong to this list");let{next:Q,prev:Y}=Z;return Q&&(Q.prev=Y),Y&&(Y.next=Q),Z===this.head&&(this.head=Q),Z===this.tail&&(this.tail=Y),this.length--,Z.next=void 0,Z.prev=void 0,Z.list=void 0,Q}unshiftNode(Z){if(Z===this.head)return;Z.list&&Z.list.removeNode(Z);let Q=this.head;Z.list=this,Z.next=Q,Q&&(Q.prev=Z),this.head=Z,this.tail||(this.tail=Z),this.length++}pushNode(Z){if(Z===this.tail)return;Z.list&&Z.list.removeNode(Z);let Q=this.tail;Z.list=this,Z.prev=Q,Q&&(Q.next=Z),this.tail=Z,this.head||(this.head=Z),this.length++}push(...Z){for(let Q=0,Y=Z.length;Q<Y;Q++)At5(this,Z[Q]);return this.length}unshift(...Z){for(var Q=0,Y=Z.length;Q<Y;Q++)jt5(this,Z[Q]);return this.length}pop(){if(!this.tail)return;let Z=this.tail.value,Q=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,Q.list=void 0,this.length--,Z}shift(){if(!this.head)return;let Z=this.head.value,Q=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,Q.list=void 0,this.length--,Z}forEach(Z,Q){Q=Q||this;for(let Y=this.head,X=0;Y;X++)Z.call(Q,Y.value,X,this),Y=Y.next}forEachReverse(Z,Q){Q=Q||this;for(let Y=this.tail,X=this.length-1;Y;X--)Z.call(Q,Y.value,X,this),Y=Y.prev}get(Z){let Q=0,Y=this.head;for(;Y&&Q<Z;Q++)Y=Y.next;if(Q===Z&&Y)return Y.value}getReverse(Z){let Q=0,Y=this.tail;for(;Y&&Q<Z;Q++)Y=Y.prev;if(Q===Z&&Y)return Y.value}map(Z,Q){Q=Q||this;let Y=new J;for(let X=this.head;X;)Y.push(Z.call(Q,X.value,this)),X=X.next;return Y}mapReverse(Z,Q){Q=Q||this;var Y=new J;for(let X=this.tail;X;)Y.push(Z.call(Q,X.value,this)),X=X.prev;return Y}reduce(Z,Q){let Y,X=this.head;if(arguments.length>1)Y=Q;else if(this.head)X=this.head.next,Y=this.head.value;else throw TypeError("Reduce of empty list with no initial value");for(var K=0;X;K++)Y=Z(Y,X.value,K),X=X.next;return Y}reduceReverse(Z,Q){let Y,X=this.tail;if(arguments.length>1)Y=Q;else if(this.tail)X=this.tail.prev,Y=this.tail.value;else throw TypeError("Reduce of empty list with no initial value");for(let K=this.length-1;X;K--)Y=Z(Y,X.value,K),X=X.prev;return Y}toArray(){let Z=Array(this.length);for(let Q=0,Y=this.head;Y;Q++)Z[Q]=Y.value,Y=Y.next;return Z}toArrayReverse(){let Z=Array(this.length);for(let Q=0,Y=this.tail;Y;Q++)Z[Q]=Y.value,Y=Y.prev;return Z}slice(Z=0,Q=this.length){Q<0&&(Q+=this.length),Z<0&&(Z+=this.length);let Y=new J;if(Q<Z||Q<0)return Y;Z<0&&(Z=0),Q>this.length&&(Q=this.length);let X=this.head,K=0;for(K=0;X&&K<Z;K++)X=X.next;for(;X&&K<Q;K++,X=X.next)Y.push(X.value);return Y}sliceReverse(Z=0,Q=this.length){Q<0&&(Q+=this.length),Z<0&&(Z+=this.length);let Y=new J;if(Q<Z||Q<0)return Y;Z<0&&(Z=0),Q>this.length&&(Q=this.length);let X=this.length,K=this.tail;for(;K&&X>Q;X--)K=K.prev;for(;K&&X>Z;X--,K=K.prev)Y.push(K.value);return Y}splice(Z,Q=0,...Y){Z>this.length&&(Z=this.length-1),Z<0&&(Z=this.length+Z);let X=this.head;for(let V=0;X&&V<Z;V++)X=X.next;let K=[];for(let V=0;X&&V<Q;V++)K.push(X.value),X=this.removeNode(X);X?X!==this.tail&&(X=X.prev):X=this.tail;for(let V of Y)X=Mt5(this,X,V);return K}reverse(){let Z=this.head,Q=this.tail;for(let Y=Z;Y;Y=Y.prev){let X=Y.prev;Y.prev=Y.next,Y.next=X}return this.head=Q,this.tail=Z,this}};function Mt5(J,Z,Q){let Y=Z,X=Z?Z.next:J.head,K=new gl0(Q,Y,X,J);return K.next===void 0&&(J.tail=K),K.prev===void 0&&(J.head=K),J.length++,K}function At5(J,Z){J.tail=new gl0(Z,J.tail,void 0,J),J.head||(J.head=J.tail),J.length++}function jt5(J,Z){J.head=new gl0(Z,void 0,J.head,J),J.tail||(J.tail=J.head),J.length++}var gl0=class{list;next;prev;value;constructor(J,Z,Q,Y){this.list=Y,this.value=J,Z?(Z.next=this,this.prev=Z):this.prev=void 0,Q?(Q.prev=this,this.next=Q):this.next=void 0}},WL4=class{path;absolute;entry;stat;readdir;pending=!1;ignore=!1;piped=!1;constructor(J,Z){this.path=J||"./",this.absolute=Z}},UL4=Buffer.alloc(1024),QQ0=Symbol("onStat"),Bl=Symbol("ended"),Ez=Symbol("queue"),rA=Symbol("current"),sA=Symbol("process"),Nl=Symbol("processing"),Yl0=Symbol("processJob"),Mz=Symbol("jobs"),Xl0=Symbol("jobDone"),YQ0=Symbol("addFSEntry"),HL4=Symbol("addTarEntry"),jl0=Symbol("stat"),Rl0=Symbol("readdir"),XQ0=Symbol("onreaddir"),KQ0=Symbol("pipe"),DL4=Symbol("entry"),Kl0=Symbol("entryOpt"),VQ0=Symbol("writeEntryClass"),hL4=Symbol("write"),Vl0=Symbol("ondrain"),LQ0=class extends Zj{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[VQ0];onWriteEntry;[Ez];[Mz]=0;[Nl]=!1;[Bl]=!1;constructor(J={}){if(super(),this.opt=J,this.file=J.file||"",this.cwd=J.cwd||process.cwd(),this.maxReadSize=J.maxReadSize,this.preservePaths=!!J.preservePaths,this.strict=!!J.strict,this.noPax=!!J.noPax,this.prefix=A5(J.prefix||""),this.linkCache=J.linkCache||new Map,this.statCache=J.statCache||new Map,this.readdirCache=J.readdirCache||new Map,this.onWriteEntry=J.onWriteEntry,this[VQ0]=bL4,typeof J.onwarn=="function"&&this.on("warn",J.onwarn),this.portable=!!J.portable,J.gzip||J.brotli||J.zstd){if((J.gzip?1:0)+(J.brotli?1:0)+(J.zstd?1:0)>1)throw TypeError("gzip, brotli, zstd are mutually exclusive");if(J.gzip&&(typeof J.gzip!="object"&&(J.gzip={}),this.portable&&(J.gzip.portable=!0),this.zip=new ks5(J.gzip)),J.brotli&&(typeof J.brotli!="object"&&(J.brotli={}),this.zip=new ys5(J.brotli)),J.zstd&&(typeof J.zstd!="object"&&(J.zstd={}),this.zip=new fs5(J.zstd)),!this.zip)throw Error("impossible");let Z=this.zip;Z.on("data",(Q)=>super.write(Q)),Z.on("end",()=>super.end()),Z.on("drain",()=>this[Vl0]()),this.on("resume",()=>Z.resume())}else this.on("drain",this[Vl0]);this.noDirRecurse=!!J.noDirRecurse,this.follow=!!J.follow,this.noMtime=!!J.noMtime,J.mtime&&(this.mtime=J.mtime),this.filter=typeof J.filter=="function"?J.filter:()=>!0,this[Ez]=new Et5,this[Mz]=0,this.jobs=Number(J.jobs)||4,this[Nl]=!1,this[Bl]=!1}[hL4](J){return super.write(J)}add(J){return this.write(J),this}end(J,Z,Q){return typeof J=="function"&&(Q=J,J=void 0),typeof Z=="function"&&(Q=Z,Z=void 0),J&&this.add(J),this[Bl]=!0,this[sA](),Q&&Q(),this}write(J){if(this[Bl])throw Error("write after end");return J instanceof yL4?this[HL4](J):this[YQ0](J),this.flowing}[HL4](J){let Z=A5(qL4.resolve(this.cwd,J.path));if(!this.filter(J.path,J))J.resume();else{let Q=new WL4(J.path,Z);Q.entry=new Lt5(J,this[Kl0](Q)),Q.entry.on("end",()=>this[Xl0](Q)),this[Mz]+=1,this[Ez].push(Q)}this[sA]()}[YQ0](J){let Z=A5(qL4.resolve(this.cwd,J));this[Ez].push(new WL4(J,Z)),this[sA]()}[jl0](J){J.pending=!0,this[Mz]+=1;let Z=this.follow?"stat":"lstat";FQ0[Z](J.absolute,(Q,Y)=>{J.pending=!1,this[Mz]-=1,Q?this.emit("error",Q):this[QQ0](J,Y)})}[QQ0](J,Z){this.statCache.set(J.absolute,Z),J.stat=Z,this.filter(J.path,Z)?Z.isFile()&&Z.nlink>1&&J===this[rA]&&!this.linkCache.get(`${Z.dev}:${Z.ino}`)&&!this.sync&&this[Yl0](J):J.ignore=!0,this[sA]()}[Rl0](J){J.pending=!0,this[Mz]+=1,FQ0.readdir(J.absolute,(Z,Q)=>{if(J.pending=!1,this[Mz]-=1,Z)return this.emit("error",Z);this[XQ0](J,Q)})}[XQ0](J,Z){this.readdirCache.set(J.absolute,Z),J.readdir=Z,this[sA]()}[sA](){if(!this[Nl]){this[Nl]=!0;for(let J=this[Ez].head;J&&this[Mz]<this.jobs;J=J.next)if(this[Yl0](J.value),J.value.ignore){let Z=J.next;this[Ez].removeNode(J),J.next=Z}this[Nl]=!1,this[Bl]&&!this[Ez].length&&this[Mz]===0&&(this.zip?this.zip.end(UL4):(super.write(UL4),super.end()))}}get[rA](){return this[Ez]&&this[Ez].head&&this[Ez].head.value}[Xl0](J){this[Ez].shift(),this[Mz]-=1,this[sA]()}[Yl0](J){if(!J.pending){if(J.entry){J===this[rA]&&!J.piped&&this[KQ0](J);return}if(!J.stat){let Z=this.statCache.get(J.absolute);Z?this[QQ0](J,Z):this[jl0](J)}if(J.stat&&!J.ignore){if(!this.noDirRecurse&&J.stat.isDirectory()&&!J.readdir){let Z=this.readdirCache.get(J.absolute);if(Z?this[XQ0](J,Z):this[Rl0](J),!J.readdir)return}if(J.entry=this[DL4](J),!J.entry){J.ignore=!0;return}J===this[rA]&&!J.piped&&this[KQ0](J)}}}[Kl0](J){return{onwarn:(Z,Q,Y)=>this.warn(Z,Q,Y),noPax:this.noPax,cwd:this.cwd,absolute:J.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[DL4](J){this[Mz]+=1;try{return new this[VQ0](J.path,this[Kl0](J)).on("end",()=>this[Xl0](J)).on("error",(Z)=>this.emit("error",Z))}catch(Z){this.emit("error",Z)}}[Vl0](){this[rA]&&this[rA].entry&&this[rA].entry.resume()}[KQ0](J){J.piped=!0,J.readdir&&J.readdir.forEach((Y)=>{let X=J.path,K=X==="./"?"":X.replace(/\/*$/,"/");this[YQ0](K+Y)});let Z=J.entry,Q=this.zip;if(!Z)throw Error("cannot pipe without source");Q?Z.on("data",(Y)=>{Q.write(Y)||Z.pause()}):Z.on("data",(Y)=>{super.write(Y)||Z.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(J,Z,Q={}){BQ0(this,J,Z,Q)}},ml0=class extends LQ0{sync=!0;constructor(J){super(J),this[VQ0]=wt5}pause(){}resume(){}[jl0](J){let Z=this.follow?"statSync":"lstatSync";this[QQ0](J,FQ0[Z](J.absolute))}[Rl0](J){this[XQ0](J,FQ0.readdirSync(J.absolute))}[KQ0](J){let Z=J.entry,Q=this.zip;if(J.readdir&&J.readdir.forEach((Y)=>{let X=J.path,K=X==="./"?"":X.replace(/\/*$/,"/");this[YQ0](K+Y)}),!Z)throw Error("Cannot pipe without source");Q?Z.on("data",(Y)=>{Q.write(Y)}):Z.on("data",(Y)=>{super[hL4](Y)})}},Rt5=(J,Z)=>{let Q=new ml0(J),Y=new PL4(J.file,{mode:J.mode||438});Q.pipe(Y),gL4(Q,Z)},It5=(J,Z)=>{let Q=new LQ0(J),Y=new HQ0(J.file,{mode:J.mode||438});Q.pipe(Y);let X=new Promise((K,V)=>{Y.on("error",V),Y.on("close",K),Q.on("error",V)});return mL4(Q,Z),X},gL4=(J,Z)=>{Z.forEach((Q)=>{Q.charAt(0)==="@"?NQ0({file:CL4.resolve(J.cwd,Q.slice(1)),sync:!0,noResume:!0,onReadEntry:(Y)=>J.add(Y)}):J.add(Q)}),J.end()},mL4=async(J,Z)=>{for(let Q=0;Q<Z.length;Q++){let Y=String(Z[Q]);Y.charAt(0)==="@"?await NQ0({file:CL4.resolve(String(J.cwd),Y.slice(1)),noResume:!0,onReadEntry:(X)=>{J.add(X)}}):J.add(Y)}J.end()},Pt5=(J,Z)=>{let Q=new ml0(J);return gL4(Q,Z),Q},Ct5=(J,Z)=>{let Q=new LQ0(J);return mL4(Q,Z),Q},R59=_l(Rt5,It5,Pt5,Ct5,(J,Z)=>{if(!Z?.length)throw TypeError("no paths specified to add to archive")}),_t5=process.env.__FAKE_PLATFORM__||process.platform,St5=_t5==="win32",{O_CREAT:kt5,O_TRUNC:vt5,O_WRONLY:yt5}=cL4.constants,lL4=Number(process.env.__FAKE_FS_O_FILENAME__)||cL4.constants.UV_FS_O_FILEMAP||0,xt5=St5&&!!lL4,ft5=524288,ut5=lL4|vt5|kt5|yt5,iL4=xt5?(J)=>J<ft5?ut5:"w":()=>"w",Il0=(J,Z,Q)=>{try{return OQ0.lchownSync(J,Z,Q)}catch(Y){if(Y?.code!=="ENOENT")throw Y}},WQ0=(J,Z,Q,Y)=>{OQ0.lchown(J,Z,Q,(X)=>{Y(X&&X?.code!=="ENOENT"?X:null)})},bt5=(J,Z,Q,Y,X)=>{if(Z.isDirectory())nL4(Al.resolve(J,Z.name),Q,Y,(K)=>{if(K)return X(K);let V=Al.resolve(J,Z.name);WQ0(V,Q,Y,X)});else{let K=Al.resolve(J,Z.name);WQ0(K,Q,Y,X)}},nL4=(J,Z,Q,Y)=>{OQ0.readdir(J,{withFileTypes:!0},(X,K)=>{if(X){if(X.code==="ENOENT")return Y();if(X.code!=="ENOTDIR"&&X.code!=="ENOTSUP")return Y(X)}if(X||!K.length)return WQ0(J,Z,Q,Y);let V=K.length,z=null,G=(F)=>{if(!z){if(F)return Y(z=F);if(--V===0)return WQ0(J,Z,Q,Y)}};for(let F of K)bt5(J,F,Z,Q,G)})},ht5=(J,Z,Q,Y)=>{Z.isDirectory()&&aL4(Al.resolve(J,Z.name),Q,Y),Il0(Al.resolve(J,Z.name),Q,Y)},aL4=(J,Z,Q)=>{let Y;try{Y=OQ0.readdirSync(J,{withFileTypes:!0})}catch(X){let K=X;if(K?.code==="ENOENT")return;if(K?.code==="ENOTDIR"||K?.code==="ENOTSUP")return Il0(J,Z,Q);throw K}for(let X of Y)ht5(J,X,Z,Q);return Il0(J,Z,Q)},oL4=class extends Error{path;code;syscall="chdir";constructor(J,Z){super(`${Z}: Cannot cd into '${J}'`),this.path=J,this.code=Z}get name(){return"CwdError"}},EQ0=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(J,Z){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=J,this.path=Z}get name(){return"SymlinkError"}},mt5=(J,Z)=>{pY.stat(J,(Q,Y)=>{(Q||!Y.isDirectory())&&(Q=new oL4(J,Q?.code||"ENOTDIR")),Z(Q)})},pt5=(J,Z,Q)=>{J=A5(J);let Y=Z.umask??18,X=Z.mode|448,K=(X&Y)!==0,V=Z.uid,z=Z.gid,G=typeof V=="number"&&typeof z=="number"&&(V!==Z.processUid||z!==Z.processGid),F=Z.preserve,q=Z.unlink,W=A5(Z.cwd),U=(D,B)=>{D?Q(D):B&&G?nL4(B,V,z,(N)=>U(N)):K?pY.chmod(J,X,Q):Q()};if(J===W)return mt5(J,U);if(F)return gt5.mkdir(J,{mode:X,recursive:!0}).then((D)=>U(null,D??void 0),U);let H=A5(UQ0.relative(W,J)).split("/");Pl0(W,H,X,q,W,void 0,U)},Pl0=(J,Z,Q,Y,X,K,V)=>{if(!Z.length)return V(null,K);let z=Z.shift(),G=A5(UQ0.resolve(J+"/"+z));pY.mkdir(G,Q,rL4(G,Z,Q,Y,X,K,V))},rL4=(J,Z,Q,Y,X,K,V)=>(z)=>{z?pY.lstat(J,(G,F)=>{if(G)G.path=G.path&&A5(G.path),V(G);else if(F.isDirectory())Pl0(J,Z,Q,Y,X,K,V);else if(Y)pY.unlink(J,(q)=>{if(q)return V(q);pY.mkdir(J,Q,rL4(J,Z,Q,Y,X,K,V))});else{if(F.isSymbolicLink())return V(new EQ0(J,J+"/"+Z.join("/")));V(z)}}):(K=K||J,Pl0(J,Z,Q,Y,X,K,V))},dt5=(J)=>{let Z=!1,Q;try{Z=pY.statSync(J).isDirectory()}catch(Y){Q=Y?.code}finally{if(!Z)throw new oL4(J,Q??"ENOTDIR")}},ct5=(J,Z)=>{J=A5(J);let Q=Z.umask??18,Y=Z.mode|448,X=(Y&Q)!==0,K=Z.uid,V=Z.gid,z=typeof K=="number"&&typeof V=="number"&&(K!==Z.processUid||V!==Z.processGid),G=Z.preserve,F=Z.unlink,q=A5(Z.cwd),W=(D)=>{D&&z&&aL4(D,K,V),X&&pY.chmodSync(J,Y)};if(J===q)return dt5(q),W();if(G)return W(pY.mkdirSync(J,{mode:Y,recursive:!0})??void 0);let U=A5(UQ0.relative(q,J)).split("/"),H;for(let D=U.shift(),B=q;D&&(B+="/"+D);D=U.shift()){B=A5(UQ0.resolve(B));try{pY.mkdirSync(B,Y),H=H||B}catch{let N=pY.lstatSync(B);if(N.isDirectory())continue;if(F){pY.unlinkSync(B),pY.mkdirSync(B,Y),H=H||B;continue}else if(N.isSymbolicLink())return new EQ0(B,B+"/"+U.join("/"))}}return W(H)},zl0=Object.create(null),BL4=1e4,jk=new Set,lt5=(J)=>{jk.has(J)?jk.delete(J):zl0[J]=J.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),jk.add(J);let Z=zl0[J],Q=jk.size-BL4;if(Q>BL4/10){for(let Y of jk)if(jk.delete(Y),delete zl0[Y],--Q<=0)break}return Z},it5=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,nt5=it5==="win32",at5=(J)=>J.split("/").slice(0,-1).reduce((Z,Q)=>{let Y=Z[Z.length-1];return Y!==void 0&&(Q=sL4(Y,Q)),Z.push(Q||"/"),Z},[]),ot5=class{#$=new Map;#J=new Map;#Z=new Set;reserve(J,Z){J=nt5?["win32 parallelization disabled"]:J.map((Y)=>Ml(sL4(lt5(Y))));let Q=new Set(J.map((Y)=>at5(Y)).reduce((Y,X)=>Y.concat(X)));this.#J.set(Z,{dirs:Q,paths:J});for(let Y of J){let X=this.#$.get(Y);X?X.push(Z):this.#$.set(Y,[Z])}for(let Y of Q){let X=this.#$.get(Y);if(!X)this.#$.set(Y,[new Set([Z])]);else{let K=X[X.length-1];K instanceof Set?K.add(Z):X.push(new Set([Z]))}}return this.#Y(Z)}#Q(J){let Z=this.#J.get(J);if(!Z)throw Error("function does not have any path reservations");return{paths:Z.paths.map((Q)=>this.#$.get(Q)),dirs:[...Z.dirs].map((Q)=>this.#$.get(Q))}}check(J){let{paths:Z,dirs:Q}=this.#Q(J);return Z.every((Y)=>Y&&Y[0]===J)&&Q.every((Y)=>Y&&Y[0]instanceof Set&&Y[0].has(J))}#Y(J){return this.#Z.has(J)||!this.check(J)?!1:(this.#Z.add(J),J(()=>this.#X(J)),!0)}#X(J){if(!this.#Z.has(J))return!1;let Z=this.#J.get(J);if(!Z)throw Error("invalid reservation");let{paths:Q,dirs:Y}=Z,X=new Set;for(let K of Q){let V=this.#$.get(K);if(!V||V?.[0]!==J)continue;let z=V[1];if(!z){this.#$.delete(K);continue}if(V.shift(),typeof z=="function")X.add(z);else for(let G of z)X.add(G)}for(let K of Y){let V=this.#$.get(K),z=V?.[0];if(!(!V||!(z instanceof Set)))if(z.size===1&&V.length===1){this.#$.delete(K);continue}else if(z.size===1){V.shift();let G=V[0];typeof G=="function"&&X.add(G)}else z.delete(J)}return this.#Z.delete(J),X.forEach((K)=>this.#Y(K)),!0}},rt5=()=>process.umask(),NL4=Symbol("onEntry"),Cl0=Symbol("checkFs"),wL4=Symbol("checkFs2"),Tl0=Symbol("isReusable"),_K=Symbol("makeFs"),_l0=Symbol("file"),Sl0=Symbol("directory"),zQ0=Symbol("link"),LL4=Symbol("symlink"),OL4=Symbol("hardlink"),Ol=Symbol("ensureNoSymlink"),EL4=Symbol("unsupported"),ML4=Symbol("checkPath"),Gl0=Symbol("stripAbsolutePath"),Yw=Symbol("mkdir"),a2=Symbol("onError"),sZ0=Symbol("pending"),AL4=Symbol("pend"),Rk=Symbol("unpend"),Fl0=Symbol("ended"),ql0=Symbol("maybeClose"),kl0=Symbol("skip"),jl=Symbol("doChown"),Rl=Symbol("uid"),Il=Symbol("gid"),Pl=Symbol("checkedCwd"),st5=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Cl=st5==="win32",tt5=1024,et5=(J,Z)=>{if(!Cl)return K3.unlink(J,Z);let Q=J+".DELETE."+dL4(16).toString("hex");K3.rename(J,Q,(Y)=>{if(Y)return Z(Y);K3.unlink(Q,Z)})},$e5=(J)=>{if(!Cl)return K3.unlinkSync(J);let Z=J+".DELETE."+dL4(16).toString("hex");K3.renameSync(J,Z),K3.unlinkSync(Z)},jL4=(J,Z,Q)=>J!==void 0&&J===J>>>0?J:Z!==void 0&&Z===Z>>>0?Z:Q,pl0=class extends Tl{[Fl0]=!1;[Pl]=!1;[sZ0]=0;reservations=new ot5;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(J={}){if(J.ondone=()=>{this[Fl0]=!0,this[ql0]()},super(J),this.transform=J.transform,this.chmod=!!J.chmod,typeof J.uid=="number"||typeof J.gid=="number"){if(typeof J.uid!="number"||typeof J.gid!="number")throw TypeError("cannot set owner without number uid and gid");if(J.preserveOwner)throw TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=J.uid,this.gid=J.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;J.preserveOwner===void 0&&typeof J.uid!="number"?this.preserveOwner=!!(process.getuid&&process.getuid()===0):this.preserveOwner=!!J.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof J.maxDepth=="number"?J.maxDepth:tt5,this.forceChown=J.forceChown===!0,this.win32=!!J.win32||Cl,this.newer=!!J.newer,this.keep=!!J.keep,this.noMtime=!!J.noMtime,this.preservePaths=!!J.preservePaths,this.unlink=!!J.unlink,this.cwd=A5(B2.resolve(J.cwd||process.cwd())),this.strip=Number(J.strip)||0,this.processUmask=this.chmod?typeof J.processUmask=="number"?J.processUmask:rt5():0,this.umask=typeof J.umask=="number"?J.umask:this.processUmask,this.dmode=J.dmode||511&~this.umask,this.fmode=J.fmode||438&~this.umask,this.on("entry",(Z)=>this[NL4](Z))}warn(J,Z,Q={}){return(J==="TAR_BAD_ARCHIVE"||J==="TAR_ABORT")&&(Q.recoverable=!1),super.warn(J,Z,Q)}[ql0](){this[Fl0]&&this[sZ0]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Gl0](J,Z){let Q=J[Z],{type:Y}=J;if(!Q||this.preservePaths)return!0;let[X,K]=bl0(Q),V=K.replace(/\\/g,"/").split("/");if(V.includes("..")||Cl&&/^[a-z]:\.\.$/i.test(V[0]??"")){if(Z==="path"||Y==="Link")return this.warn("TAR_ENTRY_ERROR",`${Z} contains '..'`,{entry:J,[Z]:Q}),!1;{let z=B2.posix.dirname(J.path),G=B2.posix.normalize(B2.posix.join(z,Q));if(G.startsWith("../")||G==="..")return this.warn("TAR_ENTRY_ERROR",`${Z} escapes extraction directory`,{entry:J,[Z]:Q}),!1}}return X&&(J[Z]=String(K),this.warn("TAR_ENTRY_INFO",`stripping ${X} from absolute ${Z}`,{entry:J,[Z]:Q})),!0}[ML4](J){let Z=A5(J.path),Q=Z.split("/");if(this.strip){if(Q.length<this.strip)return!1;if(J.type==="Link"){let Y=A5(String(J.linkpath)).split("/");if(Y.length>=this.strip)J.linkpath=Y.slice(this.strip).join("/");else return!1}Q.splice(0,this.strip),J.path=Q.join("/")}if(isFinite(this.maxDepth)&&Q.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:J,path:Z,depth:Q.length,maxDepth:this.maxDepth}),!1;if(!this[Gl0](J,"path")||!this[Gl0](J,"linkpath"))return!1;if(B2.isAbsolute(J.path)?J.absolute=A5(B2.resolve(J.path)):J.absolute=A5(B2.resolve(this.cwd,J.path)),!this.preservePaths&&typeof J.absolute=="string"&&J.absolute.indexOf(this.cwd+"/")!==0&&J.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:J,path:A5(J.path),resolvedPath:J.absolute,cwd:this.cwd}),!1;if(J.absolute===this.cwd&&J.type!=="Directory"&&J.type!=="GNUDumpDir")return!1;if(this.win32){let{root:Y}=B2.win32.parse(String(J.absolute));J.absolute=Y+KL4(String(J.absolute).slice(Y.length));let{root:X}=B2.win32.parse(J.path);J.path=X+KL4(J.path.slice(X.length))}return!0}[NL4](J){if(!this[ML4](J))return J.resume();switch(Tt5.equal(typeof J.absolute,"string"),J.type){case"Directory":case"GNUDumpDir":J.mode&&(J.mode=J.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[Cl0](J);default:return this[EL4](J)}}[a2](J,Z){J.name==="CwdError"?this.emit("error",J):(this.warn("TAR_ENTRY_ERROR",J,{entry:Z}),this[Rk](),Z.resume())}[Yw](J,Z,Q){pt5(A5(J),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:Z},Q)}[jl](J){return this.forceChown||this.preserveOwner&&(typeof J.uid=="number"&&J.uid!==this.processUid||typeof J.gid=="number"&&J.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Rl](J){return jL4(this.uid,J.uid,this.processUid)}[Il](J){return jL4(this.gid,J.gid,this.processGid)}[_l0](J,Z){let Q=typeof J.mode=="number"?J.mode&4095:this.fmode,Y=new HQ0(String(J.absolute),{flags:iL4(J.size),mode:Q,autoClose:!1});Y.on("error",(z)=>{Y.fd&&K3.close(Y.fd,()=>{}),Y.write=()=>!0,this[a2](z,J),Z()});let X=1,K=(z)=>{if(z){Y.fd&&K3.close(Y.fd,()=>{}),this[a2](z,J),Z();return}--X===0&&Y.fd!==void 0&&K3.close(Y.fd,(G)=>{G?this[a2](G,J):this[Rk](),Z()})};Y.on("finish",()=>{let z=String(J.absolute),G=Y.fd;if(typeof G=="number"&&J.mtime&&!this.noMtime){X++;let F=J.atime||new Date,q=J.mtime;K3.futimes(G,F,q,(W)=>W?K3.utimes(z,F,q,(U)=>K(U&&W)):K())}if(typeof G=="number"&&this[jl](J)){X++;let F=this[Rl](J),q=this[Il](J);typeof F=="number"&&typeof q=="number"&&K3.fchown(G,F,q,(W)=>W?K3.chown(z,F,q,(U)=>K(U&&W)):K())}K()});let V=this.transform&&this.transform(J)||J;V!==J&&(V.on("error",(z)=>{this[a2](z,J),Z()}),J.pipe(V)),V.pipe(Y)}[Sl0](J,Z){let Q=typeof J.mode=="number"?J.mode&4095:this.dmode;this[Yw](String(J.absolute),Q,(Y)=>{if(Y){this[a2](Y,J),Z();return}let X=1,K=()=>{--X===0&&(Z(),this[Rk](),J.resume())};J.mtime&&!this.noMtime&&(X++,K3.utimes(String(J.absolute),J.atime||new Date,J.mtime,K)),this[jl](J)&&(X++,K3.chown(String(J.absolute),Number(this[Rl](J)),Number(this[Il](J)),K)),K()})}[EL4](J){J.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${J.type}`,{entry:J}),J.resume()}[LL4](J,Z){let Q=A5(B2.relative(this.cwd,B2.resolve(B2.dirname(String(J.absolute)),String(J.linkpath)))).split("/");this[Ol](J,this.cwd,Q,()=>this[zQ0](J,String(J.linkpath),"symlink",Z),(Y)=>{this[a2](Y,J),Z()})}[OL4](J,Z){let Q=A5(B2.resolve(this.cwd,String(J.linkpath))),Y=A5(String(J.linkpath)).split("/");this[Ol](J,this.cwd,Y,()=>this[zQ0](J,Q,"link",Z),(X)=>{this[a2](X,J),Z()})}[Ol](J,Z,Q,Y,X){let K=Q.shift();if(this.preservePaths||K===void 0)return Y();let V=B2.resolve(Z,K);K3.lstat(V,(z,G)=>{if(z)return Y();if(G?.isSymbolicLink())return X(new EQ0(V,B2.resolve(V,Q.join("/"))));this[Ol](J,V,Q,Y,X)})}[AL4](){this[sZ0]++}[Rk](){this[sZ0]--,this[ql0]()}[kl0](J){this[Rk](),J.resume()}[Tl0](J,Z){return J.type==="File"&&!this.unlink&&Z.isFile()&&Z.nlink<=1&&!Cl}[Cl0](J){this[AL4]();let Z=[J.path];J.linkpath&&Z.push(J.linkpath),this.reservations.reserve(Z,(Q)=>this[wL4](J,Q))}[wL4](J,Z){let Q=(V)=>{Z(V)},Y=()=>{this[Yw](this.cwd,this.dmode,(V)=>{if(V){this[a2](V,J),Q();return}this[Pl]=!0,X()})},X=()=>{if(J.absolute!==this.cwd){let V=A5(B2.dirname(String(J.absolute)));if(V!==this.cwd)return this[Yw](V,this.dmode,(z)=>{if(z){this[a2](z,J),Q();return}K()})}K()},K=()=>{K3.lstat(String(J.absolute),(V,z)=>{if(z&&(this.keep||this.newer&&z.mtime>(J.mtime??z.mtime))){this[kl0](J),Q();return}if(V||this[Tl0](J,z))return this[_K](null,J,Q);if(z.isDirectory()){if(J.type==="Directory"){let G=this.chmod&&J.mode&&(z.mode&4095)!==J.mode,F=(q)=>this[_K](q??null,J,Q);return G?K3.chmod(String(J.absolute),Number(J.mode),F):F()}if(J.absolute!==this.cwd)return K3.rmdir(String(J.absolute),(G)=>this[_K](G??null,J,Q))}if(J.absolute===this.cwd)return this[_K](null,J,Q);et5(String(J.absolute),(G)=>this[_K](G??null,J,Q))})};this[Pl]?X():Y()}[_K](J,Z,Q){if(J){this[a2](J,Z),Q();return}switch(Z.type){case"File":case"OldFile":case"ContiguousFile":return this[_l0](Z,Q);case"Link":return this[OL4](Z,Q);case"SymbolicLink":return this[LL4](Z,Q);case"Directory":case"GNUDumpDir":return this[Sl0](Z,Q)}}[zQ0](J,Z,Q,Y){K3[Q](Z,String(J.absolute),(X)=>{X?this[a2](X,J):(this[Rk](),J.resume()),Y()})}},wl=(J)=>{try{return[null,J()]}catch(Z){return[Z,null]}},tL4=class extends pl0{sync=!0;[_K](J,Z){return super[_K](J,Z,()=>{})}[Cl0](J){if(!this[Pl]){let X=this[Yw](this.cwd,this.dmode);if(X)return this[a2](X,J);this[Pl]=!0}if(J.absolute!==this.cwd){let X=A5(B2.dirname(String(J.absolute)));if(X!==this.cwd){let K=this[Yw](X,this.dmode);if(K)return this[a2](K,J)}}let[Z,Q]=wl(()=>K3.lstatSync(String(J.absolute)));if(Q&&(this.keep||this.newer&&Q.mtime>(J.mtime??Q.mtime)))return this[kl0](J);if(Z||this[Tl0](J,Q))return this[_K](null,J);if(Q.isDirectory()){if(J.type==="Directory"){let K=this.chmod&&J.mode&&(Q.mode&4095)!==J.mode,[V]=K?wl(()=>{K3.chmodSync(String(J.absolute),Number(J.mode))}):[];return this[_K](V,J)}let[X]=wl(()=>K3.rmdirSync(String(J.absolute)));this[_K](X,J)}let[Y]=J.absolute===this.cwd?[]:wl(()=>$e5(String(J.absolute)));this[_K](Y,J)}[_l0](J,Z){let Q=typeof J.mode=="number"?J.mode&4095:this.fmode,Y=(V)=>{let z;try{K3.closeSync(X)}catch(G){z=G}(V||z)&&this[a2](V||z,J),Z()},X;try{X=K3.openSync(String(J.absolute),iL4(J.size),Q)}catch(V){return Y(V)}let K=this.transform&&this.transform(J)||J;K!==J&&(K.on("error",(V)=>this[a2](V,J)),J.pipe(K)),K.on("data",(V)=>{try{K3.writeSync(X,V,0,V.length)}catch(z){Y(z)}}),K.on("end",()=>{let V=null;if(J.mtime&&!this.noMtime){let z=J.atime||new Date,G=J.mtime;try{K3.futimesSync(X,z,G)}catch(F){try{K3.utimesSync(String(J.absolute),z,G)}catch{V=F}}}if(this[jl](J)){let z=this[Rl](J),G=this[Il](J);try{K3.fchownSync(X,Number(z),Number(G))}catch(F){try{K3.chownSync(String(J.absolute),Number(z),Number(G))}catch{V=V||F}}}Y(V)})}[Sl0](J,Z){let Q=typeof J.mode=="number"?J.mode&4095:this.dmode,Y=this[Yw](String(J.absolute),Q);if(Y){this[a2](Y,J),Z();return}if(J.mtime&&!this.noMtime)try{K3.utimesSync(String(J.absolute),J.atime||new Date,J.mtime)}catch{}if(this[jl](J))try{K3.chownSync(String(J.absolute),Number(this[Rl](J)),Number(this[Il](J)))}catch{}Z(),J.resume()}[Yw](J,Z){try{return ct5(A5(J),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:Z})}catch(Q){return Q}}[Ol](J,Z,Q,Y,X){if(this.preservePaths||!Q.length)return Y();let K=Z;for(let V of Q){K=B2.resolve(K,V);let[z,G]=wl(()=>K3.lstatSync(K));if(z)return Y();if(G.isSymbolicLink())return X(new EQ0(K,B2.resolve(Z,Q.join("/"))))}Y()}[zQ0](J,Z,Q,Y){let X=`${Q}Sync`;try{K3[X](Z,String(J.absolute)),Y(),J.resume()}catch(K){return this[a2](K,J)}}},Je5=(J)=>{let Z=new tL4(J),Q=J.file,Y=pL4.statSync(Q),X=J.maxReadSize||16777216;new Ns5(Q,{readSize:X,size:Y.size}).pipe(Z)},Ze5=(J,Z)=>{let Q=new pl0(J),Y=J.maxReadSize||16777216,X=J.file;return new Promise((K,V)=>{Q.on("error",V),Q.on("close",K),pL4.stat(X,(z,G)=>{if(z)V(z);else{let F=new yl0(X,{readSize:Y,size:G.size});F.on("error",V),F.pipe(Q)}})})},Qe5=_l(Je5,Ze5,(J)=>new tL4(J),(J)=>new pl0(J),(J,Z)=>{Z?.length&&xL4(J,Z)}),Ye5=(J,Z)=>{let Q=new ml0(J),Y=!0,X,K;try{try{X=mY.openSync(J.file,"r+")}catch(G){if(G?.code==="ENOENT")X=mY.openSync(J.file,"w+");else throw G}let V=mY.fstatSync(X),z=Buffer.alloc(512);$:for(K=0;K<V.size;K+=512){for(let q=0,W=0;q<512;q+=W){if(W=mY.readSync(X,z,q,z.length-q,K+q),K===0&&z[0]===31&&z[1]===139)throw Error("cannot append to compressed archives");if(!W)break $}let G=new Jj(z);if(!G.cksumValid)break;let F=512*Math.ceil((G.size||0)/512);if(K+F+512>V.size)break;K+=F,J.mtimeCache&&G.mtime&&J.mtimeCache.set(String(G.path),G.mtime)}Y=!1,Xe5(J,Q,K,X,Z)}finally{if(Y)try{mY.closeSync(X)}catch{}}},Xe5=(J,Z,Q,Y,X)=>{let K=new PL4(J.file,{fd:Y,start:Q});Z.pipe(K),Ve5(Z,X)},Ke5=(J,Z)=>{Z=Array.from(Z);let Q=new LQ0(J),Y=(X,K,V)=>{let z=(U,H)=>{U?mY.close(X,(D)=>V(U)):V(null,H)},G=0;if(K===0)return z(null,0);let F=0,q=Buffer.alloc(512),W=(U,H)=>{if(U||typeof H>"u")return z(U);if(F+=H,F<512&&H)return mY.read(X,q,F,q.length-F,G+F,W);if(G===0&&q[0]===31&&q[1]===139)return z(Error("cannot append to compressed archives"));if(F<512)return z(null,G);let D=new Jj(q);if(!D.cksumValid)return z(null,G);let B=512*Math.ceil((D.size??0)/512);if(G+B+512>K||(G+=B+512,G>=K))return z(null,G);J.mtimeCache&&D.mtime&&J.mtimeCache.set(String(D.path),D.mtime),F=0,mY.read(X,q,0,512,G,W)};mY.read(X,q,0,512,G,W)};return new Promise((X,K)=>{Q.on("error",K);let V="r+",z=(G,F)=>{if(G&&G.code==="ENOENT"&&V==="r+")return V="w+",mY.open(J.file,V,z);if(G||!F)return K(G);mY.fstat(F,(q,W)=>{if(q)return mY.close(F,()=>K(q));Y(F,W.size,(U,H)=>{if(U)return K(U);let D=new HQ0(J.file,{fd:F,start:H});Q.pipe(D),D.on("error",K),D.on("close",X),ze5(Q,Z)})})};mY.open(J.file,V,z)})},Ve5=(J,Z)=>{Z.forEach((Q)=>{Q.charAt(0)==="@"?NQ0({file:eL4.resolve(J.cwd,Q.slice(1)),sync:!0,noResume:!0,onReadEntry:(Y)=>J.add(Y)}):J.add(Q)}),J.end()},ze5=async(J,Z)=>{for(let Q=0;Q<Z.length;Q++){let Y=String(Z[Q]);Y.charAt(0)==="@"?await NQ0({file:eL4.resolve(String(J.cwd),Y.slice(1)),noResume:!0,onReadEntry:(X)=>J.add(X)}):J.add(Y)}J.end()},Ll=_l(Ye5,Ke5,()=>{throw TypeError("file is required")},()=>{throw TypeError("file is required")},(J,Z)=>{if(!Rs5(J))throw TypeError("file is required");if(J.gzip||J.brotli||J.zstd||J.file.endsWith(".br")||J.file.endsWith(".tbr"))throw TypeError("cannot append to compressed archives");if(!Z?.length)throw TypeError("no paths specified to add/replace")}),g59=_l(Ll.syncFile,Ll.asyncFile,Ll.syncNoFile,Ll.asyncNoFile,(J,Z=[])=>{Ll.validate?.(J,Z),Ge5(J)}),Ge5=(J)=>{let Z=J.filter;J.mtimeCache||(J.mtimeCache=new Map),J.filter=Z?(Q,Y)=>Z(Q,Y)&&!((J.mtimeCache?.get(Q)??Y.mtime??0)>(Y.mtime??0)):(Q,Y)=>!((J.mtimeCache?.get(Q)??Y.mtime??0)>(Y.mtime??0))};j9();j9();var M39=class{initApp;#$;constructor(J){this.initApp=J?.initApp,this.#$=J?.defaultAppOptions}createApp=(J)=>{let Z=new uZ0(J&&this.#$?{...this.#$,...J}:J??this.#$);if(this.initApp)this.initApp(Z);return Z};createMiddleware=(J)=>J;createHandlers=(...J)=>{return J.filter((Z)=>Z!==void 0)}};var We5=B4(wz(),1);var $O4=v.string(),dl0=v.object({actor_id:$O4,name:v.string(),key:v.string(),namespace_id:$O4,runner_name_selector:v.string(),create_ts:v.number(),connectable_ts:v.number().nullable().optional(),destroy_ts:v.number().nullable().optional(),sleep_ts:v.number().nullable().optional(),start_ts:v.number().nullable().optional(),error:v.unknown().nullable().optional()}),qe5=v.object({metadata:v.record(v.string(),v.unknown())}),J89=v.object({actors:v.array(dl0)}),Z89=v.object({datacenter:v.string().optional(),name:v.string(),runner_name_selector:v.string(),crash_policy:v.string(),key:v.string().nullable().optional(),input:v.string().nullable().optional()}),Q89=v.object({actor:dl0}),Y89=v.object({datacenter:v.string().optional(),name:v.string(),key:v.string(),runner_name_selector:v.string(),crash_policy:v.string(),input:v.string().nullable().optional()}),X89=v.object({actor:dl0,created:v.boolean()}),K89=v.object({}),V89=v.object({names:v.record(v.string(),qe5)}),z89=v.object({value:v.string().nullable()});var q89=class{#$;#J;constructor(J){this.#J=J}async acquire(J){if(!this.#$){let Q=this.#J.sqlitePool,Y=["@rivetkit","sqlite-vfs"].join("/");this.#$=import(Y).then(({SqliteVfsPool:X})=>new X({actorsPerInstance:Q.actorsPerInstance,idleDestroyMs:Q.idleDestroyMs}))}return await(await this.#$).acquire(J)}async shutdown(){if(this.#$)await(await this.#$).shutdown()}};function kk(J){return Pc0(J)}var Ue5="https://production.ampworkers.com",He5="https://staging.ampworkers.com";function i7(J){if(J.includes("staging.ampcodedev.org"))return He5;return Ue5}var De5="https://thread-actors-prod-us-east1-935747076731.us-east1.run.app/api/rivet",Be5="https://thread-actors-staging-us-east1-739316246630.us-east1.run.app/api/rivet";function vk(J){if(J.includes("staging.ampcodedev.org"))return Be5;return De5}async function JO4(J){let Z=J.workerURL??i7(J.ampURL),Q=await J.configService.getLatest(J.signal),Y=await Q.secrets.getToken("apiKey",Q.settings.url);if(!Y)throw Error("API key required. Please run `amp login` first.");let X=await fetch(`${Z}/threads/${J.threadID}/context-analysis`,{method:"GET",headers:{Authorization:`Bearer ${Y}`},signal:J.signal});if(!X.ok){let V=await X.text();throw Error(`Context analysis request failed (${X.status}): ${V}`)}let K=await X.json();if(!K.ok||!K.analysis)throw Error(K.error??"Invalid context analysis response from DTW");return K.analysis}async function ZO4(J){let Z=vk(J.ampURL),Q=kk({endpoint:Z}),Y=await J.configService.getLatest(J.signal),X=await Y.secrets.getToken("apiKey",Y.settings.url);if(!X)throw Error("API key required. Please run `amp login` first.");let K=await Q.threadActor.get([J.threadID]).fetch("/context-analysis",{method:"GET",headers:{Authorization:`Bearer ${X}`},signal:J.signal});if(!K.ok){let z=await K.text();throw Error(`Context analysis request failed (${K.status}): ${z}`)}let V=await K.json();if(!V.ok||!V.analysis)throw Error(V.error??"Invalid context analysis response from DTW");return V.analysis}var QO4=process.hrtime.bigint(),cl0=null;function YO4(){cl0=process.hrtime.bigint()}function XO4(){if(cl0===null)return null;return Number(process.hrtime.bigint()-cl0)/1e6}PX();m0();var Wj4=B4(O4(),1),dY=B4(Fj4(),1),Uj4=B4(zj(),1);import rQ0 from"node:fs";import Pn0 from"node:path";var qj4=Object.keys(P),Y83=Pn0.join(nZ,"logs"),Cn0=Pn0.join(Y83,"cli.log"),X83=10485760;function K83(J){try{if(rQ0.statSync(J).size>X83)rQ0.truncateSync(J,0)}catch{}}var Zi,Tn0=!1,Ji=null;function V83(J){return J instanceof Error&&J.message.includes("write after end")}function $i(J,Z,Q,Y){if(Tn0)return;try{J[Z](Q,...Y)}catch(X){if(!V83(X))throw X}}function Hj4(J){Tn0=!1,Ji=null;let{logFile:Z,logLevel:Q}=J;if(!qj4.includes(Q))console.warn(`Invalid log level: ${Q}. Using 'info' instead.`);try{rQ0.mkdirSync(Pn0.dirname(Z),{recursive:!0})}catch(z){console.error(`Failed to create log directory: ${z}`)}K83(Z);let Y=dY.default.format((z)=>{for(let G of Object.keys(z)){let F=z[G];if(F instanceof Error)z[G]={name:F.name,message:F.message,stack:F.stack}}return z}),X=dY.default.format((z)=>{return z.pid=process.pid,z}),K=[new dY.default.transports.File({filename:Z}),new Dj4];if(process.env.AMP_CLI_STDOUT_DEBUG==="true")K.push(new dY.default.transports.Console({level:"debug",format:dY.default.format.combine(dY.default.format.colorize(),dY.default.format.simple())}));Zi=dY.default.createLogger({level:qj4.includes(Q)?Q:"info",format:dY.default.format.combine(dY.default.format.timestamp(),X(),Y(),dY.default.format.json(),dY.default.format.errors({stack:!0})),transports:K});let V=Zi;return My1({error:(z,...G)=>{$i(V,"error",z,G)},warn:(z,...G)=>{$i(V,"warn",z,G)},info:(z,...G)=>{$i(V,"info",z,G)},debug:(z,...G)=>{$i(V,"debug",z,G)},audit:(z,...G)=>{let F=typeof G[0]==="object"&&G[0]!==null?{audit:!0,...G[0]}:{audit:!0};$i(V,"info",z,[F])}}),Z}class Dj4 extends Uj4.default{log({message:J,...Z},Q){Wj4.trace.getActiveSpan()?.addEvent(J,Z),Q()}}function VH(){if(Ji)return Ji;let J=Zi;if(!J)return Promise.resolve();return Tn0=!0,Ji=new Promise((Z)=>{let Q=!1,Y=()=>{if(!Q){if(Q=!0,Zi===J)Zi=void 0;Z()}};setImmediate(()=>{try{J.once("finish",Y).once("error",Y).end()}catch{Y()}}),setTimeout(Y,500)}),Ji}m0();import{execFile as z83}from"node:child_process";import{promisify as G83}from"node:util";var F83=G83(z83),q83=["private","public","workspace"];function _n0(J){return J.endsWith("/")?J.slice(0,-1):J}function W83(J){let Z=HJ0(J);try{let X=new URL(Z);return _n0(`${X.host}${X.pathname}`).replace(/^\//,"")}catch{}let Q=Z.match(/^[^@]+@([^:/]+)[:/](.+)$/);if(Q?.[1]&&Q[2])return _n0(`${Q[1]}/${Q[2]}`).replace(/\.git$/,"");let Y=Z.match(/^([^:]+):(.+)$/);if(Y?.[1]&&Y[2])return _n0(`${Y[1]}/${Y[2]}`).replace(/\.git$/,"");return null}async function wj4(J){try{let{stdout:Z}=await F83("git",["remote","get-url","origin"],{cwd:J}),Q=Z.trim();if(!Q)return null;return W83(Q)}catch{return null}}function U83(J){let Z=[...q83];if(J?.team?.disablePrivateThreads){let Q=Z.indexOf("private");if(Q!==-1)Z.splice(Q,1)}if(J?.team?.groups&&J.team.groups.length>0)Z.push("group");return Z}function Bj4(J){let Z=J?.team?.disablePrivateThreads??!1,Q=J?.team?.defaultThreadVisibility;if(!Q||Q==="private")return Z?"workspace":"private";if(Q==="thread_workspace_shared")return"workspace";if(Q==="creator_groups_fallback_private"){if(J?.team?.groups?.length)return"group";return Z?"workspace":"private"}return Z?"workspace":"private"}function H83(J){if(J?.team?.groups!==void 0)return Error(["Group visibility is not available. ",`You are not a member of any group in this workspace.
|
|
4668
4668
|
`].join(""));return Error(`Group visibility is not available.
|
|
4669
4669
|
`)}function Nj4(J,Z){let Y=[`Invalid ${J?`visibility for amp.defaultVisibility.${J}`:"visibility"}. `,`Must be one of: ${Z.join(", ")}.
|
|
4670
4670
|
`].join("");return Error(Y)}function D83(J,Z){return Z.includes(J)}function B83(J){return J?.team?.billingMode==="enterprise"||J?.team?.billingMode==="enterprise.selfserve"}function Lj4(J,Z,Q){if(J===void 0||J===null)return;let Y=U83(Z);if(typeof J!=="string")return Nj4(Q,Y);if(J==="group"&&!Y.includes("group"))return H83(Z);if(D83(J,Y))return J;return Nj4(Q,Y)}async function N83(J,Z,Q){let Y=await wj4(Z);if(!Y)return;let X;try{X=await J.get("defaultVisibility")}catch(V){P.warn("Failed to read defaultVisibility setting",{error:V});return}let K=X?.[Y];return Lj4(K,Q,Y)}async function sQ0(J,Z,Q,Y){if(Y)return Y;if(!B83(Q))return Bj4(Q);let X=await N83(J,Z,Q);if(X instanceof Error)return X;return X??Bj4(Q)}function Oj4(J,Z){return Lj4(J,Z)}async function Ej4(J,Z,Q){let Y=await wj4(Z);if(!Y)return Error("No git origin remote found for this repository.");let K={...await J.get("defaultVisibility","global")??{},[Y]:Q};return await J.set("defaultVisibility",K,"global"),{repoKey:Y}}t$();function tQ0(J){let Z=J.replace(/-/g,"");if(Z.length!==32)throw Error(`Invalid UUID hex length: ${Z.length}`);let Q=BigInt("0x"+Z),Y="";while(Q>0n)Y="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[Number(Q%62n)]+Y,Q=Q/62n;return Y.padStart(22,"0")}y3();N4();fA0();t$();var z8=v.string().min(1),eQ0=z8.brand(),kn0=v.string().regex(/^[0-9A-Za-z]{22}$/),w83=v.templateLiteral([v.string().regex(/^[0-9a-f]{8}$/),"-",v.string().regex(/^[0-9a-f]{4}$/),"-",v.string().regex(/^[0-9a-f]{4}$/),"-",v.string().regex(/^[0-9a-f]{4}$/),"-",v.string().regex(/^[0-9a-f]{12}$/)]),Qi=v.templateLiteral(["T-",w83]),L83=v.enum(["fork","handoff","mention"]),O83=v.enum(["parent","child"]),Mj4=v.object({threadID:Qi,type:L83,role:O83,messageIndex:v.number().int().nonnegative().optional(),blockIndex:v.number().int().nonnegative().optional(),createdAt:v.number().int().nonnegative(),comment:v.string().optional()}),s6=v.templateLiteral(["M-",kn0]);function Gq(){return`M-${tQ0(iO())}`}var r8=v.templateLiteral(["TU-",kn0]);function Aj4(){return`TU-${tQ0(iO())}`}var Yi=v.templateLiteral(["E-",kn0]);function vn0(){return`E-${tQ0(iO())}`}var E83=v.looseObject({type:v.literal("object"),properties:v.record(v.string(),v.unknown()),required:v.array(v.string()).optional(),additionalProperties:v.boolean().optional()}),M83=v.union([v.literal("builtin"),v.object({toolbox:z8}).strict(),v.object({mcp:z8,target:v.enum(["global","workspace","flag","default"]).optional()}).strict(),v.object({plugin:z8}).strict(),v.object({remote:z8}).strict()]),A83=v.object({serial:v.boolean().optional(),deferred:v.boolean().optional(),skillNames:v.array(z8).optional()}),jj4=v.looseObject({name:z8,description:v.string(),inputSchema:E83,source:M83,meta:A83.optional()}),f79=v.object({id:z8,category:z8,title:z8,description:v.string().optional(),pluginName:z8}),yn0=v.strictObject({"agent.deepReasoningEffort":v.enum(["medium","high","xhigh"]).optional(),"agent.skipTitleGenerationIfMessageContains":v.array(v.string()).optional(),"anthropic.thinking.enabled":v.boolean().optional(),"anthropic.interleavedThinking.enabled":v.boolean().optional(),"anthropic.temperature":v.number().optional(),"anthropic.effort":v.enum(["low","medium","high","max"]).optional(),"anthropic.speed":v.enum(["standard","fast"]).optional(),"anthropic.provider":v.enum(["anthropic","vertex"]).optional(),"openai.speed":v.enum(["standard","fast"]).optional(),"internal.compactionThresholdPercent":v.number().min(0).max(100).optional(),"internal.model":v.union([v.string(),v.record(v.string(),v.string())]).optional(),"internal.oracleReasoningEffort":v.enum(["none","minimal","low","medium","high","xhigh"]).optional(),"gemini.thinkingLevel":v.enum(["minimal","low","medium","high"]).optional(),"tools.disable":v.array(v.string()).optional(),"tools.enable":v.array(v.string()).optional()}),Rj4=v.object({settings:yn0,workspaceId:v.string(),workingDirectory:v.string(),environment:v.object({os:v.enum(["darwin","linux","windows"]),hasDocker:v.boolean().optional(),hasBrowser:v.boolean().optional()}).strict(),tags:v.array(v.string())}).strict(),Ij4=v.enum(["sandbox","local-client"]),Xi=v.any().and(v.object({status:v.string()})),Pj4=v.discriminatedUnion("type",[v.object({type:v.literal("delta"),blocks:v.array(v.unknown()).optional(),state:v.enum(["start","generating","tool_use","complete","error"])}),v.object({type:v.literal("snapshot"),value:v.unknown()})]),Fq=z8,Cj4=30000,lk=CG,j83=v.enum(["file","directory"]),R83=v.object({mtimeMs:v.number().nonnegative().optional()}),Ki=v.tuple([v.string(),j83,R83.nullish()]),I83=v.enum(["INVALID_URI","EXECUTOR_NOT_CONNECTED","NOT_FOUND","NOT_DIRECTORY","IS_DIRECTORY","ACCESS_DENIED","INTERNAL_ERROR"]),Ww=v.object({code:I83,message:v.string()}),P83=v.object({ok:v.literal(!0),entries:v.array(Ki)}),C83=v.object({ok:v.literal(!1),error:Ww}),u79=v.discriminatedUnion("ok",[P83,C83]),T83=v.object({ok:v.literal(!0),contentBase64:v.string()}),_83=v.object({ok:v.literal(!1),error:Ww}),b79=v.discriminatedUnion("ok",[T83,_83]),S83=z8,xn0=v.object({key:z8,dataType:S83,contentBase64:v.string()}),fn0=xn0.extend({toolCallId:r8.optional(),updatedAt:v.string()}),ik=v.looseObject({uri:CG,content:v.string().optional(),lineCount:v.int().optional(),hash:v.string().optional()}),Tj4=v.object({name:z8,description:v.string(),baseDir:CG,frontmatter:v.object({name:z8,description:v.string()}).catchall(v.unknown()),files:v.array(v.string()).optional()}),un0=v.object({type:v.literal("text"),text:v.string(),hidden:v.boolean().optional()}),_j4=v.looseObject({type:v.literal("image"),source:v.discriminatedUnion("type",[v.object({type:v.literal("base64"),mediaType:v.literal(["image/jpeg","image/png","image/gif","image/webp"]),data:v.string()}),v.object({type:v.literal("url"),url:v.string()})]),sourcePath:v.string()}),nk=v.array(v.discriminatedUnion("type",[un0,_j4])),ck=v.record(v.string(),v.unknown()),Sj4=v.object({type:v.literal("tool_use"),id:v.string().min(1),name:v.string().min(1),normalizedName:v.string().optional(),metadata:v.record(v.string(),v.unknown()).optional()}),k83=Sj4.extend({complete:v.literal(!0),input:ck,normalizedInput:ck.optional()}),v83=Sj4.extend({complete:v.literal(!1),input:ck,inputIncomplete:ck,inputPartialJSON:v.object({json:v.string()}),normalizedInput:ck.optional()}),y83=v.object({accepted:v.boolean(),askAnswers:v.record(v.string(),v.string()).optional(),denyFeedback:v.string().optional()}),x83=v.object({type:v.literal("tool_result"),toolUseID:v.string().min(1),run:Xi,userInput:y83.optional()}),f83=v.object({type:v.literal("thinking"),thinking:v.string(),signature:v.string()}),u83=v.object({type:v.literal("redacted_thinking"),data:v.string()}),b83=v.object({type:v.literal("server_tool_use"),id:v.string().min(1),name:v.string().min(1),input:ck}),h83=v.object({type:v.literal("manual_bash_invocation"),args:v.object({cmd:v.string(),args:v.array(v.string()).readonly().optional(),cwd:v.string().optional()}),toolRun:Xi,hidden:v.boolean().optional()}),g83=v.object({sentAt:v.number().int().nonnegative().optional(),fromAggman:v.boolean().optional(),fromExecutorThreadID:Qi.optional()}),m83=v.object({uri:CG,lineCount:v.number().int().nonnegative(),content:v.string().optional()}),p83=v.union([un0,_j4,x83]),d83=v.union([un0,f83,u83,k83,v83,b83]),bn0=v.array(p83),hn0=v.array(d83),c83=v.array(h83),Sn0=v.looseObject({line:v.number().int(),column:v.number().int()}),l83=v.looseObject({start:Sn0,end:Sn0}),i83=v.looseObject({name:v.string(),repositoryURL:v.string()}),n83=v.looseObject({currentURL:v.string(),availableProjects:v.array(i83).optional()}),a83=v.object({treeOID:v.string(),repoRoot:v.string()}),gn0=v.looseObject({currentlyVisibleFiles:v.array(CG),runningTerminalCommands:v.array(v.string()).optional(),activeEditor:v.any().optional(),cursorLocation:Sn0.optional(),cursorLocationLine:v.string().optional(),selectionRange:l83.optional(),snapshotOIDs:v.array(a83).optional(),aggmanContext:n83.optional()}),mn0=v.custom((J)=>typeof J==="string"&&B$(J)!==void 0),o83=v.object({threadId:Qi,role:v.literal("user"),content:bn0,agentMode:mn0.optional(),discoveredGuidanceFiles:v.array(m83).optional(),meta:g83.optional(),userState:gn0.optional(),readAt:v.string().nullable().optional(),messageId:s6,createdAt:v.string().optional()}),pn0=v.object({model:v.string().optional(),maxInputTokens:v.number(),inputTokens:v.number(),outputTokens:v.number(),cacheCreationInputTokens:v.number().nullable(),cacheReadInputTokens:v.number().nullable(),totalInputTokens:v.number(),thinkingBudget:v.number().optional(),timestamp:v.string().optional()}),r83=v.union([v.object({type:v.literal("complete")}),v.object({type:v.literal("cancelled")})]),s83=v.object({threadId:Qi,role:v.literal("assistant"),content:hn0,state:r83.optional(),usage:pn0.optional(),readAt:v.string().nullable().optional(),messageId:s6,createdAt:v.string().optional()}),t83=v.object({threadId:Qi,role:v.literal("info"),content:c83,messageId:s6,createdAt:v.string().optional()}),kj4=v.discriminatedUnion("role",[o83,s83,t83]),Vi=v.object({workspaceRoot:CG.optional(),workingDirectory:CG.optional(),rootDirectoryListing:v.string().nullable().optional(),trees:v.array(v.any()).optional(),platform:v.any().optional(),tags:v.array(v.string()).optional(),updatedAt:v.string().optional()}),e83=v.object({added:v.number().int().nonnegative(),deleted:v.number().int().nonnegative(),changed:v.number().int().nonnegative()}),$93=v.object({path:v.string(),previousPath:v.string().optional(),changeType:v.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","untracked"]),created:v.boolean(),diff:v.string(),fullFileDiff:v.string().optional(),oldContent:v.string().optional(),newContent:v.string().optional(),diffStat:e83}),J93=v.object({hash:v.string(),shortHash:v.string(),subject:v.string()}),vj4=v.object({provider:v.literal("git"),capturedAt:v.number(),available:v.boolean(),repositoryRoot:v.string().nullable(),repositoryName:v.string().nullable(),branch:v.string().nullable(),head:v.string().nullable(),baseRef:v.string().nullable().optional(),baseRefHead:v.string().nullable().optional(),aheadCount:v.number().int().nonnegative().optional(),behindCount:v.number().int().nonnegative().optional(),aheadCommits:v.array(J93).optional(),files:v.array($93),unavailableReason:v.string().optional(),unchanged:v.boolean().optional()}),$Y0=v.object({id:v.string(),toolCallId:r8,toolName:v.string(),args:v.record(v.string(),v.unknown()),reason:v.string().optional(),toAllow:v.array(v.string()).optional(),context:v.enum(["thread","subagent"]),subagentToolName:v.string().optional(),parentToolCallId:r8.optional(),timestamp:v.number(),matchedRule:v.object({tool:v.string(),action:v.string(),matches:v.record(v.string(),v.unknown()).optional()}).optional(),ruleSource:v.enum(["user","built-in"]).optional()}),Z93=v.object({type:v.literal("request"),id:z8,method:z8,params:v.unknown()}),Q93=v.object({type:v.literal("response"),id:z8,result:v.unknown().optional(),error:v.string().optional()}),Y93=v.object({type:v.literal("event"),event:z8,data:v.unknown(),span:v.string().optional()}),JY0=v.discriminatedUnion("type",[Z93,Q93,Y93]);var X93=v.object({type:v.literal("executor_connect"),clientId:eQ0,capabilities:Rj4,executorType:Ij4.optional()}),K93=v.object({type:v.literal("executor_settings_update"),settings:yn0}),V93=v.object({type:v.literal("executor_tools_register"),tools:v.array(jj4)}),z93=v.object({type:v.literal("executor_tools_unregister"),toolNames:v.array(z8)}),G93=v.object({type:v.literal("executor_tools_bootstrap_complete"),ok:v.boolean(),error:v.string().optional()}),F93=v.object({type:v.literal("executor_tool_lease_ack"),toolCallId:r8}),dn0=v.object({type:v.literal("tool_progress"),toolCallId:r8,progress:v.union([Pj4,v.unknown()]).optional(),parentToolCallId:r8.optional()}),q93=v.object({type:v.literal("executor_tool_result"),toolCallId:r8,run:Xi}),W93=v.object({type:v.literal("executor_guidance_snapshot"),snapshotId:z8,files:v.array(ik),isLast:v.boolean(),userConfigDir:v.any().optional()}),U93=v.object({type:v.literal("executor_guidance_discovery"),toolCallId:r8,files:v.array(ik),isLast:v.boolean()}),H93=v.object({type:v.literal("executor_skill_snapshot"),snapshotId:z8,skills:v.array(Tj4),isLast:v.boolean()}),D93=v.object({type:v.literal("executor_rollback_ack"),editId:Yi,ok:v.boolean(),error:v.string().optional()}),B93=v.object({type:v.literal("executor_revocation_ack"),toolCallId:r8}),N93=v.object({type:v.literal("executor_environment_snapshot"),environment:Vi}),w93=v.object({type:v.literal("executor_environment_update"),environment:Vi}),L93=v.object({type:v.literal("executor_artifact_upsert"),artifact:xn0,toolCallId:r8.optional()}),O93=v.object({type:v.literal("executor_artifact_delete"),key:z8}),E93=v.object({type:v.literal("executor_tool_approval_request"),approval:$Y0}),M93=v.object({type:v.literal("executor_plugin_message"),message:JY0}),A93=v.object({type:v.literal("client_append_user_msg"),content:nk,userState:gn0.optional(),discoveredGuidanceFiles:v.array(ik).optional(),agentMode:v.string().optional(),messageId:s6}),j93=v.object({type:v.literal("client_remove_queued_msg"),queuedMessageId:s6}),R93=v.object({type:v.literal("client_interrupt_queued_msg"),queuedMessageId:s6}),I93=v.object({type:v.literal("client_edit_message"),messageId:s6,editId:Yi,content:nk,agentMode:v.string().optional()}),P93=v.object({type:v.literal("client_mark_message_read"),messageId:s6}),C93=v.object({type:v.literal("client_mark_message_unread"),messageId:s6}),T93=v.object({type:v.literal("client_set_thread_title"),title:v.string().trim().min(1).max(256)}),_93=v.object({auth:v.string().min(1),p256dh:v.string().min(1)}),S93=v.object({endpoint:v.string().url(),keys:_93}),k93=v.object({type:v.literal("client_upsert_notification_subscription"),subscription:S93,threadURL:v.string().min(1)}),v93=v.object({type:v.literal("client_filesystem_read_directory"),requestId:Fq,uri:lk}),y93=v.object({type:v.literal("client_filesystem_read_file"),requestId:Fq,uri:lk}),x93=v.object({type:v.literal("executor_filesystem_read_directory_result"),requestId:Fq,ok:v.boolean(),entries:v.array(Ki).optional(),error:Ww.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),f93=v.object({type:v.literal("executor_filesystem_read_file_result"),requestId:Fq,ok:v.boolean(),contentBase64:v.string().optional(),error:Ww.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),u93=v.object({type:v.literal("client_resume"),version:v.number()}),b93=v.object({type:v.literal("client_retry")}),h93=v.object({type:v.literal("client_cancel")}),g93=v.object({type:v.literal("client_append_manual_bash_invocation"),args:v.object({cmd:v.string().trim().min(1,"cmd must contain at least one non-whitespace character"),args:v.array(v.string()).optional(),cwd:v.string().optional()}),run:Xi,hidden:v.boolean().optional()}),m93=v.object({type:v.literal("client_tool_approval_response"),toolCallId:r8,accepted:v.boolean(),input:v.object({askAnswers:v.record(v.string(),v.string()).optional(),denyFeedback:v.string().optional()}).optional()}),p93=v.object({type:v.literal("client_spawn_executor"),requestId:v.string().optional(),repositoryURL:v.string().optional(),projectID:v.uuid().optional(),additionalRepositories:v.array(v.object({name:v.string(),url:v.string()})).optional()}),p79=v.enum(["agg-man"]),yj4=v.discriminatedUnion("type",[X93,K93,V93,z93,G93,F93,dn0,q93,W93,U93,H93,D93,B93,N93,w93,L93,O93,E93,M93,A93,j93,R93,I93,P93,C93,T93,k93,v93,y93,x93,f93,u93,b93,h93,g93,m93,p93]);t$();t$();var d93=v.enum(["idle","working","streaming","tool_use","running_tools","awaiting_approval","error"]),c93=v.enum(["start","generating","tool_use","complete","error"]),l93=v.object({message:v.string(),code:v.string().optional(),stack:v.string().optional(),retryAt:v.number().optional(),attempt:v.number().optional()}),i93=v.object({userId:v.string(),name:v.string(),avatarURL:v.string().optional()}),n93=v.enum(["starting","running","failed"]),a93=v.object({cutMessageId:s6,createdAt:v.string()}),xj4=v.object({interrupt:v.boolean(),queuedMessage:v.object({role:v.literal("user"),messageId:s6,content:nk,userState:v.any().optional(),discoveredGuidanceFiles:v.array(ik).optional(),createdAt:v.string().optional()})}),o93=v.object({type:v.literal("agent_state"),state:d93,messageId:s6.optional()}),r93=v.object({type:v.literal("error"),message:v.string(),code:v.enum(["ACCESS_DENIED","CONNECTION_ERROR","MAX_RECONNECT_EXCEEDED","MESSAGE_ERROR","LOOP_RUNNING","NO_THREAD_ID","NO_ERROR","INVALID_MESSAGE","PARSE_ERROR","UNKNOWN_TYPE","INTERNAL_ERROR"]).optional()}),s93=v.object({type:v.literal("error_set"),seq:v.number(),error:l93}),t93=v.object({type:v.literal("error_cleared"),seq:v.number()}),e93=v.object({type:v.literal("cancelled"),seq:v.number(),messageId:s6.optional()}),$73=v.object({type:v.literal("retry_scheduled"),retryAt:v.number(),attempt:v.number(),maxAttempts:v.number(),reason:v.string()}),J73=v.object({type:v.literal("retry_started")}),Z73=v.object({type:v.literal("retry_cancelled")}),Q73=v.object({type:v.literal("executor_connected"),executorId:eQ0,registeredToolCount:v.number(),rejectedTools:v.array(v.object({name:v.string(),reason:v.string()})).optional()}),Y73=v.object({type:v.literal("tool_lease"),toolCallId:r8,toolName:v.string(),args:v.unknown(),messageId:s6,parentToolCallId:r8.optional()}),X73=v.object({type:v.literal("executor_filesystem_read_directory"),requestId:Fq,uri:lk}),K73=v.object({type:v.literal("executor_filesystem_read_file"),requestId:Fq,uri:lk}),V73=v.object({type:v.literal("client_filesystem_read_directory_result"),requestId:Fq,ok:v.boolean(),entries:v.array(Ki).optional(),error:Ww.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),z73=v.object({type:v.literal("client_filesystem_read_file_result"),requestId:Fq,ok:v.boolean(),contentBase64:v.string().optional(),error:Ww.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),G73=v.object({type:v.literal("tool_approval_queue"),approvals:v.array($Y0)}),F73=v.object({type:v.literal("executor_rollback_request"),editId:Yi,messageId:s6,reason:v.literal("message_edit"),toolUseIdsToRevert:v.array(r8)}),q73=v.object({type:v.literal("executor_tool_lease_revoked"),toolCallId:r8,reason:v.enum(["executor_disconnected","reassigned","user_canceled"])}),W73=v.object({type:v.literal("plugin_message"),message:JY0}),U73=v.object({type:v.literal("executor_tool_approval_response"),toolCallId:r8,accepted:v.boolean(),input:v.object({askAnswers:v.record(v.string(),v.string()).optional(),denyFeedback:v.string().optional()}).optional()}),H73=v.object({type:v.literal("executor_error"),message:v.string(),code:v.enum(["NOT_CONNECTED","ACCESS_DENIED","INVALID_MESSAGE","TOOL_NOT_FOUND","LEASE_NOT_FOUND","DUPLICATE_TOOL","INTERNAL_ERROR"])}),D73=v.object({type:v.literal("delta"),messageId:s6,role:v.literal("assistant"),blocks:hn0.optional(),state:c93,usage:pn0.optional(),parentToolCallId:r8.optional()}),B73=v.object({type:v.literal("delta"),messageId:s6,role:v.literal("user"),blocks:bn0.optional(),state:v.literal("complete"),parentToolCallId:r8.optional()}),N73=v.discriminatedUnion("role",[D73,B73]),w73=v.object({type:v.literal("queued_messages"),messages:v.array(xj4)}),L73=v.object({type:v.literal("queued_message_added"),message:xj4,seq:v.number()}),O73=v.object({type:v.literal("queued_message_removed"),queuedMessageId:s6,seq:v.number()}),E73=v.object({type:v.literal("message_added"),message:kj4,seq:v.number(),parentToolUseId:z8.optional()}),M73=v.object({type:v.literal("edit_rejected"),editId:v.string(),message:v.string()}),A73=v.object({type:v.literal("message_edited"),seq:v.number(),editId:v.string(),messageId:s6,content:nk,truncateToMessageId:s6,reason:v.literal("message_edit"),agentMode:mn0.optional()}),j73=v.looseObject({type:v.literal("cf_agent_state")}),R73=v.looseObject({type:v.literal("cf_agent_mcp_servers")}),I73=v.looseObject({type:v.literal("cf_agent_identity")}),P73=v.object({type:v.literal("observers"),count:v.number(),observers:v.array(i93),hasExecutor:v.boolean().optional()}),C73=v.object({type:v.literal("executor_status"),spawnId:v.string(),status:n93,message:v.string().optional(),executorId:v.string().optional()}),T73=v.object({type:v.literal("environment_update"),environment:Vi}),_73=v.object({type:v.literal("artifacts_snapshot"),artifacts:v.array(fn0)}),S73=v.object({type:v.literal("artifact_upserted"),artifact:fn0}),k73=v.object({type:v.literal("artifact_deleted"),key:z8}),v73=v.object({type:v.literal("thread_title"),title:v.string().nullable()}),y73=v.object({type:v.literal("thread_status"),status:v.union([v.literal("merging"),v.literal("merged"),v.null()])}),x73=v.object({type:v.literal("thread_relationships"),seq:v.number(),relationships:v.array(Mj4)}),f73=v.object({type:v.literal("compaction_started")}),u73=v.object({type:v.literal("compaction_complete"),cutMessageId:s6}),b73=v.object({type:v.literal("compaction_records"),records:v.array(a93)}),ZY0=v.discriminatedUnion("type",[o93,r93,s93,t93,e93,$73,J73,Z73,Q73,Y73,X73,K73,V73,z73,G73,F73,q73,W73,U73,dn0,H73,N73,w73,L73,O73,E73,M73,A73,j73,R73,I73,P73,C73,T73,_73,S73,k73,v73,y73,x73,f73,u73,b73]);var cn0=(J)=>v.codec(v.string(),J,{decode:(Z,Q)=>{try{return JSON.parse(Z)}catch(Y){return Q.issues.push({code:"invalid_format",format:"json",input:Z,message:Y.message}),v.NEVER}},encode:(Z)=>JSON.stringify(Z)}),fj4=cn0(yj4),h73=v.union([ZY0,v.array(ZY0)]),uj4=cn0(ZY0),bj4=cn0(h73);N4();function hj4(J,Z={}){let Y=(Z.mode??"lenient")==="strict";if(!Array.isArray(J))return Y?null:[];let X=[];for(let K of J){if(typeof K!=="object"||K===null){if(Y)return null;continue}let V=K;if(typeof V.uri!=="string"||V.uri.length===0){if(Y)return null;continue}let z;try{z=n1(V1.parse(V.uri))}catch{if(Y)return null;continue}let G={uri:z};if(typeof V.content==="string")G.content=V.content;if(typeof V.lineCount==="number"&&Number.isFinite(V.lineCount))G.lineCount=V.lineCount;if(typeof V.hash==="string")G.hash=V.hash;X.push(G)}return X}var gj4=["invalid_json","missing_type","invalid_type","unknown_type","invalid_shape"];function ln0(J,Z){if(J.length<=Z)return J;return`${J.slice(0,Z)}...<truncated>`}function g73(J){return J.replace(/\s+/g," ").trim()}function m73(J){if(!J||typeof J!=="object")return[];let Z=J.issues;return Array.isArray(Z)?Z.slice(0,5):[]}function p73(J){if(J===void 0)return null;if(typeof J==="string")return JSON.stringify(J);if(typeof J==="number"||typeof J==="boolean"||J===null)return JSON.stringify(J);try{return ln0(JSON.stringify(J),120)}catch{return ln0(String(J),120)}}function mj4(J){if(!Array.isArray(J)||J.length===0)return null;let Z=J.map((Q)=>typeof Q==="number"?`[${Q}]`:String(Q)).join(".").replace(/\.\[/g,"[");return Z.length>0?Z:null}function d73(J){if(!J||typeof J!=="object")return null;let Z=J,Q=typeof Z.message==="string"?Z.message:null,Y=typeof Z.note==="string"?Z.note:null,X=mj4(Z.path);if(X&&Q&&Q!=="Invalid input")return`${X}: ${Q}`;if(X&&Y)return`${X}: ${Y}`;if(X&&Q)return`invalid value at ${X}`;return Y??Q}function pj4(J){for(let Z of J){let Q=d73(Z);if(Q)return Q}return null}function c73(J){return J.some((Z)=>{if(!Z||typeof Z!=="object")return!1;let Q=Z;return Q.code==="invalid_union"&&(Q.note==="No matching discriminator"||Q.discriminator==="type"||mj4(Q.path)==="type")})}function l73(J,Z){let Q=pj4(Z);if(J&&Q)return`type ${JSON.stringify(J)} failed validation: ${Q}`;if(J)return`type ${JSON.stringify(J)} failed validation`;if(Q)return`message payload failed validation: ${Q}`;return"message payload failed validation"}function dj4(J,Z,Q){let Y=m73(Z),X=(()=>{let F=g73(J);if(F.length===0)return null;return ln0(F,Q?.payloadPreviewMaxChars??1200)})(),K;try{K=JSON.parse(J)}catch{let F=pj4(Y);return{failureType:"invalid_json",summary:F?`malformed JSON: ${F}`:"malformed JSON",messageType:null,typePreview:null,payloadPreview:X,issues:Y}}if(!K||typeof K!=="object"||Array.isArray(K))return{failureType:"invalid_shape",summary:"expected a JSON object payload",messageType:null,typePreview:null,payloadPreview:X,issues:Y};let V=K;if(!Object.hasOwn(V,"type"))return{failureType:"missing_type",summary:'missing string "type"',messageType:null,typePreview:null,payloadPreview:X,issues:Y};let z=V.type,G=p73(z);if(typeof z!=="string")return{failureType:"invalid_type",summary:`expected string "type", got ${G??"unknown value"}`,messageType:null,typePreview:G,payloadPreview:X,issues:Y};if(c73(Y))return{failureType:"unknown_type",summary:`unsupported type ${JSON.stringify(z)} (likely protocol version mismatch)`,messageType:z,typePreview:G,payloadPreview:X,issues:Y};return{failureType:"invalid_shape",summary:l73(z,Y),messageType:z,typePreview:G,payloadPreview:X,issues:Y}}function zi(J,Z){if(J&&typeof J==="object"&&"type"in J){let Y=J;if(Y.type==="delta"||Y.type==="snapshot")return Y}if(Z==="snapshot")return{type:"snapshot",value:J};let Q=typeof J==="string"?J:J!==void 0?JSON.stringify(J):"";return{type:"delta",blocks:Q?[{type:"text",text:Q}]:void 0,state:"generating"}}function cj4(J){let Z=Number.isFinite(J)?J:0,Q=0,Y=Z;function X(V=Z){if(Number.isFinite(V))Z=V;return Q=0,Y=Z,Z}function K(V){if(!Number.isFinite(V)||V<1)return Z;if(V<=Q)return Z;if(Q===0)Y=Z-(V-1);return Z=Math.max(Z,Y+V),Q=V,Z}return{getVersion:()=>Z,reset:X,advanceFromSeq:K}}t$();var lj4="[dtw-parse-error]",nn0="dtw-parse-error",i73=v.object({kind:v.literal(nn0),failureType:v.enum(gj4).nullable().optional(),source:v.string().nullable().optional(),direction:v.string().nullable().optional(),stage:v.string().nullable().optional(),summary:v.string().nullable().optional(),messageType:v.string().nullable().optional(),typePreview:v.string().nullable().optional(),payloadPreview:v.string().nullable().optional(),issues:v.array(v.unknown()).optional()}).passthrough(),n73=v.object({source:v.string(),direction:v.string(),stage:v.string(),summary:v.string().nullable().optional(),messageType:v.string().nullable().optional(),payloadPreview:v.string().nullable().optional(),issues:v.array(v.unknown()).optional()}).passthrough();function in0(J){return{kind:nn0,failureType:J.failureType??null,source:J.source??null,direction:J.direction??null,stage:J.stage??null,summary:J.summary??null,messageType:J.messageType??null,typePreview:J.typePreview??null,payloadPreview:J.payloadPreview??null,issues:J.issues??[]}}function ij4(J){let Z=in0(J);return JSON.stringify(Z)}function nj4(J,Z){let Q=dj4(J,Z);return ij4({failureType:Q.failureType,source:"dtw-transport",direction:"server->client",stage:"decode-server-message",summary:Q.summary,messageType:Q.messageType,typePreview:Q.typePreview,payloadPreview:Q.payloadPreview,issues:Q.issues})}function an0(J){let Z=J.startsWith(lj4)?J.slice(lj4.length):J,Q;try{Q=JSON.parse(Z)}catch{return null}let Y=i73.safeParse(Q);if(Y.success)return in0(Y.data);let X=n73.safeParse(Q);if(X.success)return in0(X.data);return null}O1();class on0 extends Error{constructor(J){super(J);this.name="DTWError"}}class _9 extends on0{cause;constructor(J,Z){super(J);this.cause=Z;this.name="NetworkError"}}O1();var a73=1000,o73=30000,r73=5,s73=30000,t73=200,e73=30000,aj4=["online","focus","pageshow","keydown","pointerdown"],oj4=["visibilitychange"];function sn0(){return globalThis}function sj4(J){if(!J||typeof J!=="object")return null;let Z=J;if(typeof Z.addEventListener!=="function"||typeof Z.removeEventListener!=="function")return null;return Z}function rj4(){return sj4(sn0().window)}function rn0(){let J=sn0().document;if(!sj4(J))return null;return J}function $23(){let J=sn0().navigator;if(!J||typeof J!=="object")return null;return J}function J23(J){if(!J)return"none";let Z=[J.type];if(J.code!==void 0)Z.push(`code=${J.code}`);if(J.reason!==void 0)Z.push(`reason=${J.reason}`);if(J.error!==void 0)Z.push(`error=${J.error}`);return Z.join(" ")}function QY0(J){return!!(J.apiKey&&J.WebSocketClass)}function tn0(J){if(QY0(J))return"one-step";return"two-step"}class en0{ws=null;connectionInfo={state:"disconnected",role:null,clientId:null,threadId:null};reconnectCause=null;reconnectAttempts=0;reconnectTimeoutID=null;reconnectResetTimeoutID=null;pingIntervalID=null;disposed=!1;lastPongAt=Date.now();intentionallyClosedSockets=new WeakSet;reconnectActivityCleanup=null;lifecycleEventID=0;lifecycleEvents=[];connectionSubject=new K4({state:"disconnected",role:null,clientId:null,threadId:null});lifecycleEventSubject=new K4([]);config;currentThreadID=null;currentWsToken=null;constructor(J){this.config={baseURL:J.baseURL,threadId:J.threadId,apiKey:J.apiKey,wsToken:J.wsToken,wsTokenProvider:J.wsTokenProvider,webSocketProvider:J.webSocketProvider,reconnectDelayMs:J.reconnectDelayMs??a73,maxReconnectDelayMs:J.maxReconnectDelayMs??o73,maxReconnectAttempts:J.maxReconnectAttempts??r73,pingIntervalMs:J.pingIntervalMs??s73,WebSocketClass:J.WebSocketClass},this.currentThreadID=J.threadId??null,this.currentWsToken=J.wsToken??null,this.recordLifecycleEvent("transport_initialized",`flow=${tn0(this.config)} threadId=${this.currentThreadID??"none"}`)}getThreadId(){return this.currentThreadID}connectionChanges(){return this.connectionSubject}getConnectionInfo(){return{...this.connectionInfo}}connectionLifecycleChanges(){return this.lifecycleEventSubject}getConnectionLifecycleEvents(){return[...this.lifecycleEvents]}async connect(){return this.connectInternal({fromReconnect:!1})}recordLifecycleEvent(J,Z){let Q={id:++this.lifecycleEventID,at:Date.now(),type:J,...Z?{details:Z}:{}},Y=t73,X=this.lifecycleEvents.slice(-(Y-1));this.lifecycleEvents=[...X,Q],this.lifecycleEventSubject.next([...this.lifecycleEvents])}async connectInternal(J){if(this.disposed)throw new _9("Transport is disposed");if(this.ws)return;this.recordLifecycleEvent("connect_requested",J.fromReconnect?`mode=reconnect attempt=${this.reconnectAttempts}`:"mode=initial"),this.updateConnectionState("connecting");try{let Z=this.config.WebSocketClass??WebSocket,Q;if(this.config.webSocketProvider)Q=await this.config.webSocketProvider();else if(QY0(this.config)){let Y=this.config.baseURL.replace(/^http:/,"ws:").replace(/^https:/,"wss:"),X=this.config.apiKey;if(!X)throw new _9("1-step flow requires apiKey");let K=this.currentThreadID??this.config.threadId;if(!K)K=(await this.fetchWsToken()).threadId;let V=`${Y}/threads`;if(K)V=`${V}?threadId=${encodeURIComponent(K)}`;Q=new Z(V,{headers:{Authorization:`Bearer ${X}`}})}else{let Y=this.config.baseURL.replace(/^http:/,"ws:").replace(/^https:/,"wss:"),{threadId:X,wsToken:K}=await this.ensureWsToken();this.currentThreadID=X,this.currentWsToken=K;let V=`${Y}/threads`;Q=new Z(V,["amp",K])}try{Q.binaryType="arraybuffer"}catch{}await this.waitForOpen(Q),this.ws=Q,this.lastPongAt=Date.now(),this.setupWebSocketHandlers(Q),this.stopWaitingForReconnectActivity(),this.scheduleReconnectAttemptsReset(),this.reconnectCause=null,this.updateConnectionState("connected"),this.recordLifecycleEvent("connect_succeeded",`threadId=${this.currentThreadID??"none"} attempt=${this.reconnectAttempts}`)}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);if(this.recordLifecycleEvent("connect_failed",`mode=${J.fromReconnect?"reconnect":"initial"} error=${Q}`),!J.fromReconnect&&!this.disposed)this.reconnectCause={type:"connect_failed",at:Date.now(),error:Q},this.scheduleReconnect();throw Z}}disconnect(){this.recordLifecycleEvent("disconnect_requested"),this.stopPingInterval(),this.cancelReconnect(),this.reconnectCause=null;let J=this.ws;if(J)this.ws=null,this.intentionallyClosedSockets.add(J),J.close(1000,"Client disconnect");this.updateConnectionState("disconnected")}dispose(){if(this.disposed)return;this.recordLifecycleEvent("disposed"),this.disposed=!0,this.disconnect(),this.connectionSubject.complete(),this.lifecycleEventSubject.complete()}sendRaw(J){if(!this.hasOpenSocket())throw new _9("WebSocket is not connected");this.ws?.send(J)}hasOpenSocket(){return!!this.ws&&this.ws.readyState===WebSocket.OPEN}updateConnectionState(J){if(J==="disconnected"||J==="reconnecting"){let Z={state:J,role:null,clientId:null,threadId:null};if(this.reconnectCause)Z.reconnectCause=this.reconnectCause;this.connectionInfo=Z}else if(this.connectionInfo.state=J,J==="connected")this.connectionInfo.threadId=this.currentThreadID,this.reconnectCause=null,delete this.connectionInfo.reconnectCause;else if(this.reconnectCause)this.connectionInfo.reconnectCause=this.reconnectCause;this.connectionSubject.next({...this.connectionInfo}),this.recordLifecycleEvent("state_changed",`state=${J} cause=${J23(this.reconnectCause)}`)}async handleAuthExpired(){this.recordLifecycleEvent("auth_refresh_started");try{if(this.currentWsToken=null,this.config.wsTokenProvider){let J=await this.config.wsTokenProvider({forceRefresh:!0});this.currentThreadID=J.threadId,this.currentWsToken=J.wsToken}this.recordLifecycleEvent("auth_refresh_succeeded",`threadId=${this.currentThreadID??"none"}`)}catch{this.recordLifecycleEvent("auth_refresh_failed")}}onRawMessage(J){}onMaxReconnectExceeded(J){}async ensureWsToken(){let J=this.reconnectAttempts>0;if(!J&&this.currentWsToken&&this.currentThreadID)return{threadId:this.currentThreadID,wsToken:this.currentWsToken};if(this.config.wsTokenProvider){let Z=await this.config.wsTokenProvider(J?{forceRefresh:!0}:void 0);return this.currentThreadID=Z.threadId,this.currentWsToken=Z.wsToken,Z}if(!J&&this.config.wsToken&&this.config.threadId)return{threadId:this.config.threadId,wsToken:this.config.wsToken};return this.fetchWsToken()}async fetchWsToken(){let Z=`${this.config.baseURL.replace(/^ws:/,"http:").replace(/^wss:/,"https:")}/threads`,Q={"Content-Type":"application/json"};if(this.config.apiKey)Q.Authorization=`Bearer ${this.config.apiKey}`;let Y=this.currentThreadID??this.config.threadId,X={};if(Y)X.threadId=Y;let K=await fetch(Z,{method:"POST",headers:Q,body:JSON.stringify(X)});if(!K.ok){let z=await K.text().catch(()=>"");throw new _9(`Failed to get wsToken: ${K.status} ${z}`)}let V=await K.json();if(!V.threadId||!V.wsToken)throw new _9("Invalid response from /threads: missing threadId or wsToken");return this.currentThreadID=V.threadId,this.currentWsToken=V.wsToken,{threadId:V.threadId,wsToken:V.wsToken}}async waitForOpen(J){if(J.readyState===WebSocket.OPEN)return;return new Promise((Z,Q)=>{let Y=()=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),Z()},X=(V)=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),this.updateConnectionState("disconnected");let z="message"in V?V.message:("error"in V)&&V.error instanceof Error?V.error.message:V.type;Q(new _9(`WebSocket connection failed: ${z}`))},K=(V)=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),this.updateConnectionState("disconnected"),Q(new _9(`WebSocket closed during connect: code=${V.code} reason=${V.reason||"none"}`))};if(J.addEventListener("open",Y),J.addEventListener("error",X),J.addEventListener("close",K),J.readyState===WebSocket.OPEN)return Y();if(J.readyState===WebSocket.CLOSED||J.readyState===WebSocket.CLOSING)return K({code:1006,reason:"Socket already closed before connect"})})}setupWebSocketHandlers(J){J.addEventListener("message",(Z)=>{let Q=Z.data;if(typeof Q==="string"){if(Q==="pong"){this.lastPongAt=Date.now();return}this.onRawMessage(Q)}else if(Q instanceof ArrayBuffer)this.onRawMessage(new TextDecoder().decode(Q))}),J.addEventListener("close",(Z)=>{this.handleClose(J,Z.code,Z.reason)}),J.addEventListener("error",()=>{this.handleError(J)}),this.startPingInterval()}handleClose(J,Z,Q){let Y=this.intentionallyClosedSockets.has(J);if(Y)this.intentionallyClosedSockets.delete(J);if(this.recordLifecycleEvent("socket_closed",`code=${Z} reason=${Q||"none"} intentional=${Y}`),J!==this.ws)return;if(this.ws=null,this.stopPingInterval(),this.cancelReconnectAttemptsReset(),!this.disposed&&!Y){let X=this.reconnectCause,K=X?.type==="ping_timeout"&&Z===4000&&!Q?{...X,at:Date.now(),code:Z}:{type:"close",at:Date.now(),code:Z,...Q?{reason:Q}:{}};if(this.reconnectCause=K,Z===4001||Q.includes("Token expired"))this.handleAuthExpired().catch(()=>{return}).finally(()=>{if(!this.disposed)this.scheduleReconnect()});else this.scheduleReconnect()}else this.reconnectCause=null,this.updateConnectionState("disconnected")}handleError(J){if(J!==this.ws)return;if(this.recordLifecycleEvent("socket_error","error=WebSocket error event"),this.reconnectCause={type:"error",at:Date.now(),error:"WebSocket error event"},this.ws)this.ws.close()}scheduleReconnect(J){if(this.disposed||this.reconnectTimeoutID)return;if(this.reconnectAttempts>=this.config.maxReconnectAttempts){this.stopWaitingForReconnectActivity(),this.recordLifecycleEvent("reconnect_exhausted",`attempts=${this.reconnectAttempts} max=${this.config.maxReconnectAttempts}`),this.updateConnectionState("disconnected"),this.onMaxReconnectExceeded(this.config.maxReconnectAttempts);return}if(!J?.bypassActivityGate&&this.shouldWaitForReconnectActivity()){this.recordLifecycleEvent("reconnect_waiting_for_activity",`offline=${this.isBrowserOffline()} hidden=${this.isDocumentHidden()}`),this.updateConnectionState("reconnecting"),this.waitForReconnectActivity();return}this.stopWaitingForReconnectActivity(),this.updateConnectionState("reconnecting"),this.reconnectAttempts++;let Z=J?.immediate?0:this.getReconnectDelayMs();this.recordLifecycleEvent("reconnect_scheduled",`attempt=${this.reconnectAttempts} delayMs=${Math.round(Z)}`),this.reconnectTimeoutID=setTimeout(()=>{this.reconnectTimeoutID=null,this.connectInternal({fromReconnect:!0}).catch((Q)=>{if(this.reconnectCause={type:"connect_failed",at:Date.now(),error:Q instanceof Error?Q.message:String(Q)},!this.disposed)this.scheduleReconnect()})},Z)}cancelReconnect(){if(this.reconnectTimeoutID)clearTimeout(this.reconnectTimeoutID),this.reconnectTimeoutID=null;this.stopWaitingForReconnectActivity(),this.cancelReconnectAttemptsReset(),this.reconnectAttempts=0}getReconnectDelayMs(){let J=this.config.reconnectDelayMs*2**(this.reconnectAttempts-1),Z=0.8+Math.random()*0.4;return Math.min(J*Z,this.config.maxReconnectDelayMs)}shouldWaitForReconnectActivity(){let J=rj4(),Z=rn0();if(!J&&!Z)return!1;return this.isBrowserOffline()||this.isDocumentHidden()}isBrowserOffline(){let J=$23();if(typeof J?.onLine!=="boolean")return!1;return J.onLine===!1}isDocumentHidden(){let J=rn0();if(!J)return!1;return J.visibilityState==="hidden"}waitForReconnectActivity(){if(this.reconnectActivityCleanup)return;let J=rj4(),Z=rn0();if(!J&&!Z)return;let Q=()=>{this.handleReconnectActivity()};for(let Y of aj4)J?.addEventListener(Y,Q);for(let Y of oj4)Z?.addEventListener(Y,Q);this.reconnectActivityCleanup=()=>{for(let Y of aj4)J?.removeEventListener(Y,Q);for(let Y of oj4)Z?.removeEventListener(Y,Q)}}stopWaitingForReconnectActivity(){this.reconnectActivityCleanup?.(),this.reconnectActivityCleanup=null}handleReconnectActivity(){if(this.disposed||this.ws){this.stopWaitingForReconnectActivity();return}if(this.shouldWaitForReconnectActivity())return;this.stopWaitingForReconnectActivity(),this.recordLifecycleEvent("reconnect_activity_detected"),this.scheduleReconnect({immediate:!0,bypassActivityGate:!0})}scheduleReconnectAttemptsReset(){this.cancelReconnectAttemptsReset(),this.reconnectResetTimeoutID=setTimeout(()=>{this.reconnectResetTimeoutID=null,this.reconnectAttempts=0},e73)}cancelReconnectAttemptsReset(){if(this.reconnectResetTimeoutID)clearTimeout(this.reconnectResetTimeoutID),this.reconnectResetTimeoutID=null}startPingInterval(){this.stopPingInterval();let J=Date.now();this.pingIntervalID=setInterval(()=>{let Z=Date.now(),Q=Z-J;if(J=Z,Q>this.config.pingIntervalMs*3){this.lastPongAt=Z;return}if(this.hasOpenSocket()){let Y=Z-this.lastPongAt,X=this.config.pingIntervalMs*2;if(Y>X){this.recordLifecycleEvent("ping_timeout",`elapsedMs=${Y} thresholdMs=${X}`),this.reconnectCause={type:"ping_timeout",at:Z,code:4000,reason:"Pong timeout",error:`No pong received for ${Y}ms (threshold ${X}ms)`},this.ws?.close(4000,"Pong timeout");return}try{this.ws?.send("ping")}catch{}}},this.config.pingIntervalMs)}stopPingInterval(){if(this.pingIntervalID)clearInterval(this.pingIntervalID),this.pingIntervalID=null}}function Z23(J){let Z=atob(J),Q=new Uint8Array(Z.length);for(let Y=0;Y<Z.length;Y++)Q[Y]=Z.charCodeAt(Y);return Q}class qq extends en0{deltaSubject=new Y4;errorSubject=new Y4;errorEventSubject=new Y4;cancelledSubject=new Y4;agentStateSubject=new Y4;messageAddedSubject=new Y4;editRejectedSubject=new Y4;messageEditedSubject=new Y4;queuedMessagesSubject=new Y4;retrySubject=new Y4;toolLeaseSubject=new Y4;toolLeaseRevokedSubject=new Y4;toolApprovalQueueSubject=new Y4;executorToolApprovalResponseSubject=new Y4;toolProgressSubject=new Y4;executorErrorSubject=new Y4;executorConnectedSubject=new Y4;executorRollbackRequestSubject=new Y4;observersSubject=new Y4;executorStatusSubject=new Y4;environmentUpdateSubject=new Y4;artifactsSubject=new Y4;threadTitleSubject=new Y4;threadStatusSubject=new Y4;threadRelationshipsSubject=new Y4;compactionSubject=new Y4;compactionRecordsSubject=new Y4;pluginMessageSubject=new Y4;fileSystemReadDirectoryRequestSubject=new Y4;fileSystemReadFileRequestSubject=new Y4;pendingReadDirectoryRequests=new Map;pendingReadFileRequests=new Map;fileSystemRequestCounter=0;constructor(J){super(J)}deltas(){return this.deltaSubject}agentStates(){return this.agentStateSubject}messageEvents(){return this.messageAddedSubject}editRejected(){return this.editRejectedSubject}messageEdited(){return this.messageEditedSubject}queuedMessages(){return this.queuedMessagesSubject}retryEvents(){return this.retrySubject}errors(){return this.errorSubject}errorEvents(){return this.errorEventSubject}cancelledEvents(){return this.cancelledSubject}toolLeases(){return this.toolLeaseSubject}toolLeaseRevoked(){return this.toolLeaseRevokedSubject}toolApprovalQueue(){return this.toolApprovalQueueSubject}executorToolApprovalResponses(){return this.executorToolApprovalResponseSubject}toolProgress(){return this.toolProgressSubject}executorErrors(){return this.executorErrorSubject}executorConnected(){return this.executorConnectedSubject}executorRollbackRequests(){return this.executorRollbackRequestSubject}observers(){return this.observersSubject}executorStatuses(){return this.executorStatusSubject}environmentUpdates(){return this.environmentUpdateSubject}artifacts(){return this.artifactsSubject}threadTitles(){return this.threadTitleSubject}threadStatuses(){return this.threadStatusSubject}threadRelationships(){return this.threadRelationshipsSubject}compactionEvents(){return this.compactionSubject}compactionRecords(){return this.compactionRecordsSubject}pluginMessages(){return this.pluginMessageSubject}fileSystemReadDirectoryRequests(){return this.fileSystemReadDirectoryRequestSubject}fileSystemReadFileRequests(){return this.fileSystemReadFileRequestSubject}dispose(){if(this.disposed)return;super.dispose(),this.rejectPendingFileSystemRequests("Transport disposed"),this.deltaSubject.complete(),this.errorSubject.complete(),this.errorEventSubject.complete(),this.cancelledSubject.complete(),this.agentStateSubject.complete(),this.messageAddedSubject.complete(),this.editRejectedSubject.complete(),this.messageEditedSubject.complete(),this.queuedMessagesSubject.complete(),this.retrySubject.complete(),this.toolLeaseSubject.complete(),this.toolLeaseRevokedSubject.complete(),this.toolApprovalQueueSubject.complete(),this.executorToolApprovalResponseSubject.complete(),this.toolProgressSubject.complete(),this.executorErrorSubject.complete(),this.executorConnectedSubject.complete(),this.executorRollbackRequestSubject.complete(),this.observersSubject.complete(),this.executorStatusSubject.complete(),this.environmentUpdateSubject.complete(),this.artifactsSubject.complete(),this.threadTitleSubject.complete(),this.threadStatusSubject.complete(),this.threadRelationshipsSubject.complete(),this.compactionSubject.complete(),this.compactionRecordsSubject.complete(),this.pluginMessageSubject.complete(),this.fileSystemReadDirectoryRequestSubject.complete(),this.fileSystemReadFileRequestSubject.complete()}sendUserMessage(J,Z,Q){let Y=Q?.messageId??Gq();return this.send({type:"client_append_user_msg",content:J,agentMode:Z,messageId:Y,userState:Q?.userState,discoveredGuidanceFiles:Q?.discoveredGuidanceFiles}),Y}removeQueuedMessage(J){this.send({type:"client_remove_queued_msg",queuedMessageId:J})}interruptQueuedMessage(J){this.send({type:"client_interrupt_queued_msg",queuedMessageId:J})}editUserMessage(J,Z,Q,Y){this.send({type:"client_edit_message",messageId:J,editId:Q,content:Z,agentMode:Y})}markMessageRead(J){this.send({type:"client_mark_message_read",messageId:J})}markMessageUnread(J){this.send({type:"client_mark_message_unread",messageId:J})}setThreadTitle(J){this.send({type:"client_set_thread_title",title:J})}upsertNotificationSubscription(J,Z){this.send({type:"client_upsert_notification_subscription",subscription:J,threadURL:Z})}readDirectory(J){return this.requestReadDirectory(J)}readFile(J){return this.requestReadFile(J)}resumeFromVersion(J){this.send({type:"client_resume",version:J})}retryAgentLoop(){this.send({type:"client_retry"})}cancelAgentLoop(){if(!this.hasOpenSocket())return;this.send({type:"client_cancel"})}appendManualBashInvocation(J){this.send({type:"client_append_manual_bash_invocation",args:J.args,run:J.run,hidden:J.hidden})}resolveToolApproval(J,Z,Q){this.send({type:"client_tool_approval_response",toolCallId:J,accepted:Z,input:Q})}requestExecutorSpawn(J,Z){this.send({type:"client_spawn_executor",requestId:J,repositoryURL:Z?.repositoryURL,projectID:Z?.projectID,additionalRepositories:Z?.additionalRepositories})}executePluginCommand(J,Z,Q,Y){this.sendPluginMessage({type:"request",id:J,method:"command.execute",params:{pluginName:Z,commandId:Q,threadID:Y}})}async executorHandshake(J,Z,Q){if(this.disposed)throw new _9("Transport is disposed");if(!this.hasOpenSocket())throw new _9("WebSocket is not connected. Call connect() first.");return new Promise((Y,X)=>{let K=!1,V=null,z=(q)=>{if(K)return;if(K=!0,V)clearTimeout(V),V=null;G.unsubscribe(),F.unsubscribe(),q()},G=this.executorConnectedSubject.subscribe({next:(q)=>{this.connectionInfo.clientId=q.executorId,this.connectionInfo.role="executor",this.updateConnectionState("connected"),z(()=>Y(q))},error:(q)=>{z(()=>X(q))}}),F=this.executorErrorSubject.subscribe({next:(q)=>{z(()=>X(Error(q.message)))}});this.send({type:"executor_connect",clientId:J,capabilities:Z,executorType:Q?.executorType}),V=setTimeout(()=>{z(()=>X(Error("Executor connect timeout")))},1e4)})}ackToolLease(J){this.send({type:"executor_tool_lease_ack",toolCallId:J})}sendToolProgress(J,Z){let Q=zi(Z,"snapshot");this.send({type:"tool_progress",toolCallId:J,progress:Q})}sendExecutorToolResult(J,Z){this.send({type:"executor_tool_result",toolCallId:J,run:Z})}sendExecutorFileSystemReadDirectoryResult(J,Z){this.send({type:"executor_filesystem_read_directory_result",requestId:J,...Z})}sendExecutorFileSystemReadFileResult(J,Z){this.send({type:"executor_filesystem_read_file_result",requestId:J,...Z})}sendExecutorToolApprovalRequest(J){this.send({type:"executor_tool_approval_request",approval:J})}sendPluginMessage(J){this.send({type:"executor_plugin_message",message:J})}sendRevocationAck(J){this.send({type:"executor_revocation_ack",toolCallId:J})}sendExecutorGuidanceSnapshot(J){this.send({type:"executor_guidance_snapshot",...J})}sendExecutorGuidanceDiscovery(J){this.send({type:"executor_guidance_discovery",...J})}sendExecutorSkillSnapshot(J){this.send({type:"executor_skill_snapshot",...J})}sendExecutorSettingsUpdate(J){this.send({type:"executor_settings_update",settings:J})}sendExecutorRollbackAck(J,Z,Q){this.send({type:"executor_rollback_ack",editId:J,ok:Z,error:Q})}registerTools(J){this.send({type:"executor_tools_register",tools:J})}sendExecutorToolsBootstrapComplete(J,Z){this.send({type:"executor_tools_bootstrap_complete",ok:J,error:Z})}sendEnvironmentSnapshot(J){this.send({type:"executor_environment_snapshot",environment:J})}sendEnvironmentUpdate(J){this.send({type:"executor_environment_update",environment:J})}sendExecutorArtifactUpsert(J,Z){this.send({type:"executor_artifact_upsert",artifact:J,toolCallId:Z})}sendExecutorArtifactDelete(J){this.send({type:"executor_artifact_delete",key:J})}unregisterTools(J){this.send({type:"executor_tools_unregister",toolNames:J})}updateConnectionState(J){if(super.updateConnectionState(J),J==="reconnecting"||J==="disconnected")this.rejectPendingFileSystemRequests("Connection closed before filesystem request completed")}requestReadDirectory(J){let Z=this.nextFileSystemRequestID("read-directory");return this.createPendingReadRequest(this.pendingReadDirectoryRequests,Z,()=>{this.send({type:"client_filesystem_read_directory",requestId:Z,uri:J})})}requestReadFile(J){let Z=this.nextFileSystemRequestID("read-file");return this.createPendingReadRequest(this.pendingReadFileRequests,Z,()=>{this.send({type:"client_filesystem_read_file",requestId:Z,uri:J})})}createPendingReadRequest(J,Z,Q){if(!this.hasOpenSocket())return Promise.reject(new _9("WebSocket is not connected"));return new Promise((Y,X)=>{let K=setTimeout(()=>{J.delete(Z),X(new _9(`Filesystem request timed out: ${Z}`))},Cj4);J.set(Z,{resolve:Y,reject:X,timeoutID:K});try{Q()}catch(V){clearTimeout(K),J.delete(Z),X(V instanceof Error?V:Error(String(V)))}})}nextFileSystemRequestID(J){let Z=this.fileSystemRequestCounter++;return`${J}-${Date.now()}-${Z}`}handleReadDirectoryResult(J){let Z=this.pendingReadDirectoryRequests.get(J.requestId);if(!Z)return;if(clearTimeout(Z.timeoutID),this.pendingReadDirectoryRequests.delete(J.requestId),J.ok&&J.entries){Z.resolve(J.entries);return}if(J.ok){Z.reject(Error("Invalid filesystem read_directory response: missing entries"));return}if(!J.error){Z.reject(Error("Invalid filesystem read_directory response: missing error"));return}Z.reject(this.createFileSystemError(J.error))}handleReadFileResult(J){let Z=this.pendingReadFileRequests.get(J.requestId);if(!Z)return;if(clearTimeout(Z.timeoutID),this.pendingReadFileRequests.delete(J.requestId),!J.ok&&J.error){Z.reject(this.createFileSystemError(J.error));return}if(!J.ok){Z.reject(Error("Invalid filesystem read_file response: missing error"));return}if(J.contentBase64===void 0){Z.reject(Error("Invalid filesystem read_file response: missing content"));return}try{Z.resolve(Z23(J.contentBase64))}catch{Z.reject(Error("Invalid base64 payload in filesystem read_file response"))}}createFileSystemError(J){return Error(`Filesystem error (${J.code}): ${J.message}`)}rejectPendingFileSystemRequests(J){for(let[Z,Q]of this.pendingReadDirectoryRequests)clearTimeout(Q.timeoutID),Q.reject(new _9(J)),this.pendingReadDirectoryRequests.delete(Z);for(let[Z,Q]of this.pendingReadFileRequests)clearTimeout(Q.timeoutID),Q.reject(new _9(J)),this.pendingReadFileRequests.delete(Z)}onRawMessage(J){let Z=bj4.safeDecode(J);if(!Z.success){let Y=uj4.safeDecode(J),X=Y.success?Z.error:Y.error;this.errorSubject.next({type:"error",message:nj4(J,X),code:"PARSE_ERROR"});return}let Q=Array.isArray(Z.data)?Z.data:[Z.data];for(let Y of Q)this.handleServerMessage(Y)}handleServerMessage(J){switch(J.type){case"agent_state":this.agentStateSubject.next(J);break;case"error":this.errorSubject.next(J);break;case"error_set":case"error_cleared":this.errorEventSubject.next(J);break;case"cancelled":this.cancelledSubject.next(J);break;case"retry_scheduled":case"retry_started":case"retry_cancelled":this.retrySubject.next(J);break;case"delta":this.deltaSubject.next(J);break;case"message_added":this.messageAddedSubject.next(J);break;case"edit_rejected":this.editRejectedSubject.next(J);break;case"message_edited":this.messageEditedSubject.next(J);break;case"queued_messages":case"queued_message_added":case"queued_message_removed":this.queuedMessagesSubject.next(J);break;case"executor_connected":this.connectionInfo.role="executor",this.connectionInfo.clientId=J.executorId,this.connectionSubject.next({...this.connectionInfo}),this.executorConnectedSubject.next(J);break;case"tool_lease":this.toolLeaseSubject.next(J);break;case"executor_filesystem_read_directory":this.fileSystemReadDirectoryRequestSubject.next(J);break;case"executor_filesystem_read_file":this.fileSystemReadFileRequestSubject.next(J);break;case"executor_rollback_request":this.executorRollbackRequestSubject.next(J);break;case"executor_tool_lease_revoked":this.toolLeaseRevokedSubject.next(J);break;case"tool_approval_queue":this.toolApprovalQueueSubject.next(J);break;case"plugin_message":this.pluginMessageSubject.next(J);break;case"executor_tool_approval_response":this.executorToolApprovalResponseSubject.next(J);break;case"tool_progress":this.toolProgressSubject.next(J);break;case"executor_error":this.executorErrorSubject.next(J);break;case"cf_agent_state":case"cf_agent_mcp_servers":case"cf_agent_identity":break;case"observers":this.observersSubject.next(J);break;case"executor_status":this.executorStatusSubject.next(J);break;case"environment_update":this.environmentUpdateSubject.next(J);break;case"artifacts_snapshot":case"artifact_upserted":case"artifact_deleted":this.artifactsSubject.next(J);break;case"thread_title":this.threadTitleSubject.next(J);break;case"thread_status":this.threadStatusSubject.next(J);break;case"thread_relationships":this.threadRelationshipsSubject.next(J);break;case"client_filesystem_read_directory_result":this.handleReadDirectoryResult(J);break;case"client_filesystem_read_file_result":this.handleReadFileResult(J);break;case"compaction_started":case"compaction_complete":this.compactionSubject.next(J);break;case"compaction_records":this.compactionRecordsSubject.next(J);break}}onMaxReconnectExceeded(J){this.errorSubject.next({type:"error",message:`Failed to reconnect after ${J} attempts`,code:"MAX_RECONNECT_EXCEEDED"})}send(J){try{this.sendRaw(fj4.encode(J))}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw new _9(`Failed to encode DTW client message "${J.type}": ${Q}`,Z)}}}function Q23(J){if(!J||typeof J!=="object")return!1;let Z=J.queuedMessage;if(!Z||typeof Z!=="object")return!1;return typeof Z.messageId==="string"}function Y23(J){if(!J||typeof J!=="object")return!1;return typeof J.id==="string"}function X23(J){if(Q23(J))return J.queuedMessage.messageId;if(Y23(J))return J.id;throw Error("reduceQueuedMessages requires getQueuedMessageId for this message shape")}function $a0(J,Z,Q={}){let Y=Q.getQueuedMessageId??X23;if(Z.type==="queued_messages")return[...Z.messages];if(Z.type==="queued_message_added"){if(Q.dedupeAdded&&J.some((X)=>Y(X)===Y(Z.message)))return[...J];return[...J,Z.message]}if(!J.some((X)=>Y(X)===Z.queuedMessageId))return[...J];return J.filter((X)=>Y(X)!==Z.queuedMessageId)}var K23=15000;function V23(J,Z,Q){let Y=!1,X=null,K=[],V=()=>{if(Y)return;if(Y=!0,X)clearTimeout(X),X=null;for(let G of K)G.unsubscribe()};return{promise:new Promise((G,F)=>{K.push(J.messageEvents().subscribe({next:(q)=>{if(q.message.messageId===Z)V(),G(q)}})),K.push(J.errors().subscribe({next:(q)=>{V(),F(Error(q.message))}})),K.push(J.executorErrors().subscribe({next:(q)=>{V(),F(Error(q.message))}})),K.push(J.connectionChanges().subscribe({next:(q)=>{if(q.state==="disconnected")V(),F(Error("Disconnected before message was acknowledged"))}})),X=setTimeout(()=>{V(),F(Error(`Timed out waiting for message_added after ${Q}ms`))},Q)}),dispose:V}}async function Ja0(J){let Z=J.workerUrl??i7(J.ampURL),Q=new qq({baseURL:Z,apiKey:J.apiKey,threadId:J.threadId,WebSocketClass:WebSocket,maxReconnectAttempts:1,pingIntervalMs:5000}),Y=J.timeoutMs??K23;await Q.connect(),Q.resumeFromVersion(0);let X=Q.sendUserMessage([{type:"text",text:J.message}],J.agentMode),K=V23(Q,X,Y);try{return{messageId:(await K.promise).message.messageId}}finally{K.dispose(),Q.dispose()}}import{watch as z23}from"node:fs";import{mkdir as G23,readdir as F23,readFile as q23}from"node:fs/promises";import{createServer as W23}from"node:http";import Za0 from"node:path";function tj4(J){return J instanceof Error?J.message:String(J)}function Wj(J,Z,Q){J.writeHead(Z,{"Content-Type":"application/json; charset=utf-8"}),J.end(JSON.stringify(Q))}function U23(J,Z){J.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),J.end(Z)}async function ej4(J,Z){let Q=Za0.basename(Z),Y=Q.endsWith(".json")?Za0.join(J,Q):Za0.join(J,`${Q}.json`),X=await q23(Y,"utf-8");return JSON.parse(X)}async function H23(J){let Z=await F23(J,{withFileTypes:!0}).catch(()=>[]),Q=[];for(let Y of Z){if(!Y.isFile()||!Y.name.endsWith(".json"))continue;try{let X=await ej4(J,Y.name);Q.push({sessionID:X.sessionID,createdAt:X.createdAt,runtimeMode:X.runtimeMode,traceName:X.traceName,threadId:X.threadId,protocolEvents:X.protocolEvents.length,providerStates:X.providerStateEvents.length,adapterStates:X.adapterStateEvents.length,commands:X.commandEvents.length})}catch{}}return Q.sort((Y,X)=>X.createdAt-Y.createdAt)}function D23(){return`<!doctype html>
|
|
@@ -6196,11 +6196,11 @@ ${H}`))}},error:(U)=>{if(!W)W=!0,z(Error(`Failed to spawn brew: ${U.message}`))}
|
|
|
6196
6196
|
${H}`;if(X==="pnpm"&&H.includes("Unable to find the global bin directory"))D+=`
|
|
6197
6197
|
|
|
6198
6198
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
6199
|
-
npm install -g @sourcegraph/amp`;z(Error(D))}},error:(U)=>{if(!q)q=!0,z(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}m0();m0();hM();async function uY0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let z=await fetch(X,{signal:K.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),F=G.version??G["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=LP4(J,F),W=q<0,U,H;if(G.time){let D=G.time[J],B=G.time[F],N=Date.now();if(D)U=Math.floor((N-new Date(D).getTime())/3600000);if(B)H=Math.floor((N-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:U,latestVersionAge:H}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:U,latestVersionAge:H,source:"npm"}}catch(z){return P.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var oZ3="https://static.ampcode.com/cli/cli-version.txt";async function bY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${oZ3}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let K=LP4(J,X),V=K<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return P.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var rZ3=604800000;function wP4(J){if(!J)return null;let Z=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Z))return null;let Q=Date.now()-Z;if(Q>rZ3)return{ageMs:Q};return null}function LP4(J,Z){let Q=(V)=>{let[z,G]=V.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let z=Y.parts[V]||0,G=X.parts[V]||0;if(z<G)return-1;if(z>G)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function ma0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?MF(Q):void 0;return{sha:Y,age:X}}catch{return null}}O1();function pa0(J,Z,Q={}){let Y=new Y4,X=Y.pipe(c6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new TG().scoped("update"),V=Q.startDelayMs??0;if(V>0)await JF(V);let z=X.subscribe({next:(G)=>{K.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){K.debug("using fake update status for testing",{status:G}),await JF(500),Y.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){K.debug("checking disabled");return}let q=await fY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await bY0(J):await uY0(J,Oj());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let H=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let D=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(D)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:D}),!0}return!1};if(!F)F=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:F});if(q==="brew"){if(!H())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==xa0()){if(K.debug("non-standard binary path, showing warning"),!H())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!H())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Y.next("update-available");return}try{await Ti(U.latestVersion,q);let D=await Nw(U.latestVersion),B={from:U.currentVersion,to:U.latestVersion,...D};if(D.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(D){Y.next("update-error")}}catch(G){K.debug("check failed",{error:G})}finally{await JF(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}hM();import{stderr as Sz}from"node:process";function OP4(J){let Z=new fN().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Y)=>{await Sa0(Y.force||!1,Y.verbose||!1,"0.0.
|
|
6199
|
+
npm install -g @sourcegraph/amp`;z(Error(D))}},error:(U)=>{if(!q)q=!0,z(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}m0();m0();hM();async function uY0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let z=await fetch(X,{signal:K.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),F=G.version??G["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=LP4(J,F),W=q<0,U,H;if(G.time){let D=G.time[J],B=G.time[F],N=Date.now();if(D)U=Math.floor((N-new Date(D).getTime())/3600000);if(B)H=Math.floor((N-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:U,latestVersionAge:H}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:U,latestVersionAge:H,source:"npm"}}catch(z){return P.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var oZ3="https://static.ampcode.com/cli/cli-version.txt";async function bY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${oZ3}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let K=LP4(J,X),V=K<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return P.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var rZ3=604800000;function wP4(J){if(!J)return null;let Z=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Z))return null;let Q=Date.now()-Z;if(Q>rZ3)return{ageMs:Q};return null}function LP4(J,Z){let Q=(V)=>{let[z,G]=V.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let z=Y.parts[V]||0,G=X.parts[V]||0;if(z<G)return-1;if(z>G)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function ma0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?MF(Q):void 0;return{sha:Y,age:X}}catch{return null}}O1();function pa0(J,Z,Q={}){let Y=new Y4,X=Y.pipe(c6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new TG().scoped("update"),V=Q.startDelayMs??0;if(V>0)await JF(V);let z=X.subscribe({next:(G)=>{K.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){K.debug("using fake update status for testing",{status:G}),await JF(500),Y.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){K.debug("checking disabled");return}let q=await fY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await bY0(J):await uY0(J,Oj());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let H=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let D=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(D)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:D}),!0}return!1};if(!F)F=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:F});if(q==="brew"){if(!H())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==xa0()){if(K.debug("non-standard binary path, showing warning"),!H())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!H())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Y.next("update-available");return}try{await Ti(U.latestVersion,q);let D=await Nw(U.latestVersion),B={from:U.currentVersion,to:U.latestVersion,...D};if(D.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(D){Y.next("update-error")}}catch(G){K.debug("check failed",{error:G})}finally{await JF(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}hM();import{stderr as Sz}from"node:process";function OP4(J){let Z=new fN().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Y)=>{await Sa0(Y.force||!1,Y.verbose||!1,"0.0.1774880298-g3dd925"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new fN("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await sZ3(Y.targetVersion)});J.addCommand(Q)}async function sZ3(J){let Z=process.platform==="win32"&&xY0();if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Sz.write(o0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
6200
6200
|
|
|
6201
6201
|
`));try{if(!J){Sz.write(o0.blue(`Checking for updates...
|
|
6202
|
-
`));let{hasUpdate:X,latestVersion:K}=xY0()?await bY0("0.0.
|
|
6203
|
-
`));let G=await Nw("0.0.
|
|
6202
|
+
`));let{hasUpdate:X,latestVersion:K}=xY0()?await bY0("0.0.1774880298-g3dd925"):await uY0("0.0.1774880298-g3dd925",Oj());if(!X){let V=ma0("0.0.1774880298-g3dd925"),z=V?.age?`released ${V.age} ago`:`built ${MF(new Date("2026-03-30T14:22:23.248Z"))} ago`;Sz.write(o0.green(`✓ Amp is already up to date on version ${"0.0.1774880298-g3dd925"} (${z})
|
|
6203
|
+
`));let G=await Nw("0.0.1774880298-g3dd925");if(G.warning)Sz.write(`
|
|
6204
6204
|
`+o0.yellow(G.warning)+`
|
|
6205
6205
|
`);process.exit(0)}if(!K)Sz.write(o0.yellow("[WARN] could not find latest version")),process.exit(0);J=K}Sz.write(o0.blue(`Updating to version ${J}...
|
|
6206
6206
|
`)),await Ti(J,void 0,(X)=>{Sz.write(o0.dim(`Running: ${X}
|
|
@@ -7372,7 +7372,7 @@ Ctrl-X, Y, Z to unlock`;if(U){let f=F.text.replace(/`([^`]+)`/g,"$1")+`
|
|
|
7372
7372
|
`),K=[];for(let V=0;V<X.length;V++){let F=X[V].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let q of F)if(q.startsWith("\x00")&&q.endsWith("\x01"))K.push(new C(q.slice(1,-1),new g({color:Y.app.keybind,bold:!0})));else K.push(new C(q,new g({color:Q.colorScheme.foreground})));if(V<X.length-1)K.push(new C(`
|
|
7373
7373
|
`))}return new d0({decoration:{color:Q.colorScheme.background,border:c1.all(new g1(Y.app.keybind,1,"rounded"))},child:new n0({padding:C0.symmetric(0,1),child:new e({text:new C(void 0,void 0,K)})})})}}class K01 extends x${chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=Rz0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new Y01({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(J){let Z=J;Z.chartData=this.chartData,Z.highlightIndex=this.highlightIndex,Z.showAxes=this.showAxes,Z.colors=this.colors,Z.markNeedsLayout()}}function Oh4(J,Z,Q,Y,X,K,V){if(K<=0)return null;switch(J){case"horizontal-bar":{let z=Q;return z>=0&&z<K?z:null}case"bar":case"stacked-bar":{let z=V?v9:0,G=Y-z;if(G<=0)return null;let F=Z-z;if(F<0||F>=G)return null;let q=Math.max(1,Math.floor(G/K)),W=Math.floor(F/q);return W>=0&&W<K?W:null}case"line":case"sparkline":case"stacked-area":{let z=V?v9:0,G=Y-z;if(G<=0)return null;let F=Math.max(0,Math.min(G-1,Z-z));if(K===1)return 0;let q=G/(K-1),W=Math.round(F/q);return Math.max(0,Math.min(K-1,W))}default:return null}}function dR3(J,Z,Q,Y,X,K,V,z){if(X<=0||Z<0||Z>=X)return null;let G=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let F=K?v9:0,q=Q-F,W=Y-(K?G:0);if(q<=0||W<=0)return null;let U=Math.max(1,Math.floor(q/X)),H=F+Z*U+Math.floor(U/2),D=z>0?V/z:0,B=Math.round((1-D)*(W-1));return{x:H,y:B}}case"line":case"sparkline":case"stacked-area":{let F=K?v9:0,q=Q-F,W=Y-(K?G:0);if(q<=0||W<=0)return null;let U=X>1?F+Math.round(Z/(X-1)*(q-1)):F+Math.floor(q/2),H=z>0?V/z:0,D=Math.round((1-H)*(W-1));return{x:U,y:D}}default:return null}}function cR3(J){let Z=0;for(let Q of J)for(let Y of Q.points)if(Y.value>Z)Z=Y.value;return Z||1}function lR3(J,Z,Q,Y,X){if(Q.length<=1){let z=Y(J.value),G=J.meta?` (${J.meta})`:"";return J.label.length+2+z.length+G.length}let K=J.label.length,V=0;for(let z of Q){let G=z.points[Z];if(!G)continue;V+=G.value;let F=2+z.name.length+2+Y(G.value).length;K=Math.max(K,F)}if(X){let z=9+Y(V).length;K=Math.max(K,z)}return K}function iR3(J,Z,Q,Y,X,K,V){let z;try{let D=x1.of(J),B=f0.of(J);z={foreground:D.colorScheme.foreground,background:D.colorScheme.background,border:B.app.keybind}}catch{z={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let G=new g({color:z.foreground,bold:!0}),F=new g({color:z.foreground}),q=new g({color:z.foreground,dim:!0}),W=[],U=new g({color:z.foreground,underline:!0}),H=(D,B)=>new C(B,U,void 0,nY0(D),()=>{u3(J,D)});if(Y.length<=1){if(W.push(new C(`${Z.label}: `,G)),Z.link)W.push(H(Z.link,K(Z.value)));else W.push(new C(K(Z.value),F));if(Z.meta)W.push(new C(` (${Z.meta})`,q))}else{let D=V==="stacked-bar"||V==="stacked-area";W.push(new C(`${Z.label}
|
|
7374
7374
|
`,G));let B=0;for(let N=0;N<Y.length;N++){let w=Y[N],L=w.points[Q];if(!L)continue;B+=L.value;let O=w.color??X[N%X.length]??z.foreground;if(W.push(new C("● ",new g({color:O}))),W.push(new C(`${w.name}: `,q)),L.link)W.push(H(L.link,K(L.value)));else W.push(new C(K(L.value),F));if(N<Y.length-1||D)W.push(new C(`
|
|
7375
|
-
`))}if(D)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),F))}return new d0({decoration:{color:z.background,border:c1.all(new g1(z.border,1,"rounded"))},child:new e({text:new C(void 0,void 0,W)})})}sO();m0();_7();QE();N$();y3();_2();Nd();CX();O$();rJ();ZQ();NA();d4();ug();SP();O1();m0();O$();class V01{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Z){this.enabled=J;this.configService=Z;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Z,Q])=>({feature:"cli.command",action:Z,source:{client:"cli",clientVersion:"0.0.1774876048-g0dfb1c"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await H40(Z,this.configService)}catch(Z){P.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class KL extends l0{props;constructor(J){super();this.props=J}createState(){return new Eh4}}class Eh4 extends p0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class Mh4 extends p0{controller=new r7;focusNode=new G6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,z=c1.all(new g1(Q.foreground,1,"solid")),G=new IZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(H)=>{let D=H.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new W1({children:[new d0({decoration:{color:Q.background},child:new e({text:new C(">",new g({color:Q.foreground}))})}),new y1({child:G})]}),q=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new C("Enter",new g({color:Y.keybind}))),W.push(new C(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new C("Esc",new g({color:Y.keybind}))),W.push(new C(" to cancel",new g({color:Q.foreground,dim:!0})));let U=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,W)})});return new d0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new R0({height:1}),F,new f3,U]})})}}class Ma extends l0{props;constructor(J){super();this.props=J}createState(){return new Mh4}}ZQ();import{mkdtemp as oR3,readFile as rR3,rmdir as sR3,unlink as tR3,writeFile as eR3}from"node:fs/promises";import{tmpdir as $I3}from"node:os";import _h4 from"node:path";m0();m0();class Ah4{_listeners=new Set;_disposed=!1;addListener(J){if(this._disposed)throw Error("Cannot add listener to disposed ChangeNotifier");this._listeners.add(J)}removeListener(J){this._listeners.delete(J)}notifyListeners(){if(this._disposed)return;let J=Array.from(this._listeners);for(let Z of J)try{Z()}catch(Q){}}dispose(){this._disposed=!0,this._listeners.clear()}get disposed(){return this._disposed}get hasListeners(){return this._listeners.size>0}}class BR extends Ah4{_value;constructor(J){super();this._value=J}get value(){return this._value}set value(J){let Z=typeof J==="object"||this._value!==J;if(this._value=J,Z)this.notifyListeners()}}function jh4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class z01{builder;maintainState;_overlayState;_needsBuild=!0;constructor(J,Z=!1){this.builder=J;this.maintainState=Z}get mounted(){return this._overlayState!==void 0}remove(){if(this._overlayState)this._overlayState.remove(this)}markNeedsBuild(){if(this._needsBuild=!0,this._overlayState)this._overlayState._markNeedsRebuild()}_setOverlayState(J){this._overlayState=J}_needsRebuild(){return this._needsBuild}_clearNeedsRebuild(){this._needsBuild=!1}}class G01 extends n3{link;showWhenUnlinked;offset;constructor({key:J,link:Z,showWhenUnlinked:Q=!0,offset:Y={x:0,y:0},child:X}){super({key:J,child:X});this.link=Z,this.showWhenUnlinked=Q,this.offset=Y}createElement(){return new Dq(this)}createRenderObject(){return new Rh4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class Rh4 extends u4{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;constructor(J,Z,Q){super();this._link=J,this._showWhenUnlinked=Z,this._followerOffset=Q}get link(){return this._link}set link(J){this._link=J,this._cachedPosition=null,this.markNeedsLayout()}get showWhenUnlinked(){return this._showWhenUnlinked}set showWhenUnlinked(J){if(this._showWhenUnlinked!==J)this._showWhenUnlinked=J,this.markNeedsLayout()}setFollowerOffset(J){if(this._followerOffset.x!==J.x||this._followerOffset.y!==J.y)this._followerOffset={...J},this.markNeedsLayout()}calculatePosition(){let J=this._link.getTargetTransform();if(!J)return null;return{x:J.position.x+this._followerOffset.x,y:J.position.y+this._followerOffset.y}}shouldShow(){return this._link.target!==null||this._showWhenUnlinked}performLayout(){let J=this._lastConstraints;if(Z6(!!J,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Z=this.calculatePosition();if(this._cachedPosition=Z,Z)this.setOffset(Z.x,Z.y);if(this.children.length>0){let Q=this.children[0];Q.layout(J);let Y=Q.size;this.setSize(Y.width,Y.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(J,Z){super.setOffset(J,Z)}paint(J,Z=0,Q=0){super.paint(J,Z,Q)}}m0();var nR3=500;class F01{_state;_textController=null;_lastText="";_triggers=[];_optionsBuilder=null;_onSelected=null;_pendingBuildTimer=null;_disposed=!1;constructor(){let J={trigger:null,options:[],selectedIndex:-1,isActive:!1,generationId:0};this._state=new BR(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Z,optionsBuilder:Q,onSelected:Y}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._lastText=J.text,this._triggers=Z,this._optionsBuilder=Q,this._onSelected=Y||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Z})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Z})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Z=J.options[J.selectedIndex];if(!Z)return;if(this.dismiss(),this._onSelected)this._onSelected(Z)}dismiss(){this._clearPendingBuildTimer(),this._updateState({trigger:null,options:[],selectedIndex:-1,isActive:!1})}dispose(){this._disposed=!0,this._cleanup(),this._state.dispose()}_handleTextChange=()=>{if(!this._textController||!this._optionsBuilder)return;let J=this.currentState.trigger,Z=this._textController.text,Q=Z!==this._lastText;if(this._lastText=Z,!Q&&!this.currentState.isActive)return;let Y=this._textController.cursorPosition,X=null;for(let z of this._triggers){let G=z.detect(Z,Y);if(G&&(!X||G.start>X.start))X=G}if(!this.currentState.isActive&&X&&X.query.length>0){let z=f6(Z),G=Y,F=G;while(F<z.length){let q=z[F];if(q&&/[\s)\]}@]/.test(q))break;F++}if(F>G){let W=[...z.slice(0,G),...z.slice(F)].join("");this._textController.text=W,this._textController.cursorPosition=Y;return}}if(!X){if(this.currentState.isActive)this.dismiss();else this._clearPendingBuildTimer();return}let K=Q&&this._shouldDebounceBuild(J,X),V=this.currentState.generationId+1;if(this._updateState({trigger:X,generationId:V,options:K?[]:this.currentState.options,isActive:!K,selectedIndex:-1}),K){this._scheduleDebouncedBuild(X.query,V);return}this._clearPendingBuildTimer(),this._buildOptions(X.query,V)};async _buildOptions(J,Z){if(!this._optionsBuilder)return;try{let Q=await this._optionsBuilder(J);if(this.currentState.generationId===Z&&!this._disposed)this._updateState({options:Q,selectedIndex:Q.length>0?0:-1,isActive:Q.length>0})}catch(Q){if(P.error("Error building autocomplete options:",Q),this.currentState.generationId===Z&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_scheduleDebouncedBuild(J,Z){this._clearPendingBuildTimer(),this._pendingBuildTimer=setTimeout(()=>{this._pendingBuildTimer=null,this._buildOptions(J,Z)},nR3)}_shouldDebounceBuild(J,Z){if(!J)return!1;if(J.trigger!==Z.trigger||J.start!==Z.start)return!1;return Z.query.length<J.query.length}_clearPendingBuildTimer(){if(this._pendingBuildTimer)clearTimeout(this._pendingBuildTimer),this._pendingBuildTimer=null}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._clearPendingBuildTimer(),this._textController)this._textController.removeListener(this._handleTextChange)}}class Aa{}class ja{}class Ra{}class Pz0{}class Cz0 extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Ih4(this.props)}}class Ih4 extends p0{props;controller;stateListener=null;overlayEntry=null;layerLink=new wa;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new G6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new F01,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=jh4(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.handle)this.props.handle.dismiss=()=>this.controller.dismiss();if(this.props.autofocus??!0)C6.instance.addPostFrameCallback(()=>{this._effectiveFocusNode.requestFocus()})}didUpdateWidget(J){super.didUpdateWidget(J);let Z=J.props,Q=this.widget.props;if(this.props=Q,Z.controller!==Q.controller||Z.triggers!==Q.triggers||Z.optionsBuilder!==Q.optionsBuilder||Z.textFieldProps!==Q.textFieldProps||Z.onSelected!==Q.onSelected)this.controller.initialize({textController:Q.controller,triggers:Q.triggers,optionsBuilder:Q.optionsBuilder,onSelected:Q.onSelected});if(Z.handle!==Q.handle){if(Q.handle)Q.handle.dismiss=()=>this.controller.dismiss()}this.setState(()=>{})}dispose(){this.removeOverlay(),this.stateListener?.dispose(),this.controller.dispose(),this._effectiveFocusNode.dispose(),super.dispose()}invoke=(J)=>{if(!this.controller.currentState.isActive)return"ignored";if(J instanceof Aa)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof ja)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Ra)return this.controller.acceptSelected(),"handled";if(J instanceof Pz0)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Z=J.selectedIndex,Q=J.options.length,Y=this._cachedMaxVisibleOptions||Q;if(Y>=Q){this.scrollOffset=0;return}let X=Z-this.scrollOffset,K=1,V=this.scrollOffset;if(X>=Y-K)V=Math.max(0,Z-(Y-K-1));if(X<K)V=Math.max(0,Z-K);let z=Math.max(0,Q-Y);V=Math.min(V,z),this.scrollOffset=V}build(J){let Z=new IZ({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Q=new m$({shortcuts:new Map([[new D4("ArrowDown"),new Aa],[new D4("ArrowUp"),new ja],[new D4("n",{ctrl:!0}),new Aa],[new D4("p",{ctrl:!0}),new ja],[new D4("Enter"),new Ra],[new D4("Escape"),new Pz0],[new D4("Tab"),new Ra]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new M7({actions:new Map([[Aa,new D6(this.invoke)],[ja,new D6(this.invoke)],[Ra,new D6(this.invoke)],[Pz0,new D6(this.invoke)]]),child:Q});return new Na({link:this.layerLink,child:Y})}updateOverlay(){let J=this.controller.currentState;if(J.isActive&&J.options.length>0)if(!this.overlayEntry)this.createOverlay();else this.overlayEntry.markNeedsBuild();else this.removeOverlay()}createOverlay(){if(this.overlayEntry)return;this.overlayEntry=new z01((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{UR.of(this.context).insert(this.overlayEntry)}catch(J){P.error("Failed to insert autocomplete overlay:",J),this.overlayEntry=null}}removeOverlay(){if(this.overlayEntry)this.overlayEntry.remove(),this.overlayEntry=null}buildOverlayHints(J,Z){if(this.props.overlayHint!==void 0){if(this.props.overlayHint===null)return[];let{prefix:Q,suffix:Y}=this.props.overlayHint,X=[];if(Q)X.push(new C(Q,new g({color:f0.of(J).app.command})),new C(" ",new g({color:Z})));return X.push(new C(Y,new g({color:Z}))),[{child:new e({text:new C(" ",new g({dim:!0}),X)}),position:"top",alignment:"center"}]}return[]}buildOverlayContent(J,Z){let Q=x1.maybeOf(J),Y=Q?.colorScheme.background??M0.default(),X=this.props.overlayBorderColor??Q?.colorScheme.border??M0.default(),K=Z.options.length,V=V4.sizeOf(J).height,z=0;try{let R=this.layerLink.getTargetTransform();if(R)z=R.position.y}catch{}let G=this.props.autoOverlayPosition?z<V/3:!1,F=2,q;if(G){let R=this.props.controller.getCursorVisualRow(),_=z+R+1;q=V-_-F}else q=z-F;K=Math.min(K,Math.max(1,q)),this._cachedMaxVisibleOptions=K,this.updateScrollPosition();let W=this.scrollOffset,U=Math.min(Z.options.length,W+K),H=[],D=0;for(let R=W;R<U;R++){let _=Z.options[R];if(!_)continue;let T=R===Z.selectedIndex,u,m;if(this.props.optionViewBuilder){u=this.props.optionViewBuilder(J,_,T);let f=this.props.displayStringForOption?.(_)??String(_),d="",p=f,h=_;if(h&&typeof h==="object"&&"type"in h)switch(h.type){case"file":d="@",p=h.path||f;break;case"artifact":d="",p=h.label||f;break}m=d+p}else{let f=this.props.displayStringForOption?.(_)??String(_),d=Q?.colorScheme.selection??M0.default(),p=Q?.colorScheme.foreground??M0.default();u=new e({text:new C(f,new g({color:p,backgroundColor:T?d:void 0}))}),m=f}let y=V4.of(J),k=x5(m,y.supportsEmojiWidth);D=Math.max(D,k),H.push(u)}let B=V4.sizeOf(J).width,N=D+4,w=Math.floor(B*0.9),L=Math.max(Math.min(N,w),Math.min(30,w)),M=H.length+2,A;if(G)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new R0({width:L,child:new d0({height:M,decoration:new $6(Y),child:new s8({decoration:{border:c1.all(new g1(X,1,"rounded"))},padding:C0.symmetric(1,0),overlays:this.buildOverlayHints(J,X),child:new x0({crossAxisAlignment:"start",children:H})})})});return new G01({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function Ph4(J){if(J.kind!=="file"&&J.kind!=="folder")throw Error("Invalid completion item: missing path or kind");return{type:"file",path:J.path,kind:J.kind}}function Ch4(J){switch(J.type){case"file":return J.path;case"hint":return`${aR3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function Th4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function aR3(J){switch(J){case"commit":return"@:";case"thread":return"@@"}}class vq{detect(J,Z){if(!J||Z<1)return null;let Q=f6(J);if(Z>Q.length)return null;let Y=this.findWordStart(Q,Z);if(Y>=Q.length||Q[Y]!=="@")return null;let X=Q.slice(Y+1,Z).join("");if(X.includes(" ")||X.includes("\t")||X.includes(`
|
|
7375
|
+
`))}if(D)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),F))}return new d0({decoration:{color:z.background,border:c1.all(new g1(z.border,1,"rounded"))},child:new e({text:new C(void 0,void 0,W)})})}sO();m0();_7();QE();N$();y3();_2();Nd();CX();O$();rJ();ZQ();NA();d4();ug();SP();O1();m0();O$();class V01{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Z){this.enabled=J;this.configService=Z;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Z,Q])=>({feature:"cli.command",action:Z,source:{client:"cli",clientVersion:"0.0.1774880298-g3dd925"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await H40(Z,this.configService)}catch(Z){P.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class KL extends l0{props;constructor(J){super();this.props=J}createState(){return new Eh4}}class Eh4 extends p0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class Mh4 extends p0{controller=new r7;focusNode=new G6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,z=c1.all(new g1(Q.foreground,1,"solid")),G=new IZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(H)=>{let D=H.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new W1({children:[new d0({decoration:{color:Q.background},child:new e({text:new C(">",new g({color:Q.foreground}))})}),new y1({child:G})]}),q=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new C("Enter",new g({color:Y.keybind}))),W.push(new C(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new C("Esc",new g({color:Y.keybind}))),W.push(new C(" to cancel",new g({color:Q.foreground,dim:!0})));let U=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,W)})});return new d0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new R0({height:1}),F,new f3,U]})})}}class Ma extends l0{props;constructor(J){super();this.props=J}createState(){return new Mh4}}ZQ();import{mkdtemp as oR3,readFile as rR3,rmdir as sR3,unlink as tR3,writeFile as eR3}from"node:fs/promises";import{tmpdir as $I3}from"node:os";import _h4 from"node:path";m0();m0();class Ah4{_listeners=new Set;_disposed=!1;addListener(J){if(this._disposed)throw Error("Cannot add listener to disposed ChangeNotifier");this._listeners.add(J)}removeListener(J){this._listeners.delete(J)}notifyListeners(){if(this._disposed)return;let J=Array.from(this._listeners);for(let Z of J)try{Z()}catch(Q){}}dispose(){this._disposed=!0,this._listeners.clear()}get disposed(){return this._disposed}get hasListeners(){return this._listeners.size>0}}class BR extends Ah4{_value;constructor(J){super();this._value=J}get value(){return this._value}set value(J){let Z=typeof J==="object"||this._value!==J;if(this._value=J,Z)this.notifyListeners()}}function jh4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class z01{builder;maintainState;_overlayState;_needsBuild=!0;constructor(J,Z=!1){this.builder=J;this.maintainState=Z}get mounted(){return this._overlayState!==void 0}remove(){if(this._overlayState)this._overlayState.remove(this)}markNeedsBuild(){if(this._needsBuild=!0,this._overlayState)this._overlayState._markNeedsRebuild()}_setOverlayState(J){this._overlayState=J}_needsRebuild(){return this._needsBuild}_clearNeedsRebuild(){this._needsBuild=!1}}class G01 extends n3{link;showWhenUnlinked;offset;constructor({key:J,link:Z,showWhenUnlinked:Q=!0,offset:Y={x:0,y:0},child:X}){super({key:J,child:X});this.link=Z,this.showWhenUnlinked=Q,this.offset=Y}createElement(){return new Dq(this)}createRenderObject(){return new Rh4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class Rh4 extends u4{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;constructor(J,Z,Q){super();this._link=J,this._showWhenUnlinked=Z,this._followerOffset=Q}get link(){return this._link}set link(J){this._link=J,this._cachedPosition=null,this.markNeedsLayout()}get showWhenUnlinked(){return this._showWhenUnlinked}set showWhenUnlinked(J){if(this._showWhenUnlinked!==J)this._showWhenUnlinked=J,this.markNeedsLayout()}setFollowerOffset(J){if(this._followerOffset.x!==J.x||this._followerOffset.y!==J.y)this._followerOffset={...J},this.markNeedsLayout()}calculatePosition(){let J=this._link.getTargetTransform();if(!J)return null;return{x:J.position.x+this._followerOffset.x,y:J.position.y+this._followerOffset.y}}shouldShow(){return this._link.target!==null||this._showWhenUnlinked}performLayout(){let J=this._lastConstraints;if(Z6(!!J,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Z=this.calculatePosition();if(this._cachedPosition=Z,Z)this.setOffset(Z.x,Z.y);if(this.children.length>0){let Q=this.children[0];Q.layout(J);let Y=Q.size;this.setSize(Y.width,Y.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(J,Z){super.setOffset(J,Z)}paint(J,Z=0,Q=0){super.paint(J,Z,Q)}}m0();var nR3=500;class F01{_state;_textController=null;_lastText="";_triggers=[];_optionsBuilder=null;_onSelected=null;_pendingBuildTimer=null;_disposed=!1;constructor(){let J={trigger:null,options:[],selectedIndex:-1,isActive:!1,generationId:0};this._state=new BR(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Z,optionsBuilder:Q,onSelected:Y}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._lastText=J.text,this._triggers=Z,this._optionsBuilder=Q,this._onSelected=Y||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Z})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Z})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Z=J.options[J.selectedIndex];if(!Z)return;if(this.dismiss(),this._onSelected)this._onSelected(Z)}dismiss(){this._clearPendingBuildTimer(),this._updateState({trigger:null,options:[],selectedIndex:-1,isActive:!1})}dispose(){this._disposed=!0,this._cleanup(),this._state.dispose()}_handleTextChange=()=>{if(!this._textController||!this._optionsBuilder)return;let J=this.currentState.trigger,Z=this._textController.text,Q=Z!==this._lastText;if(this._lastText=Z,!Q&&!this.currentState.isActive)return;let Y=this._textController.cursorPosition,X=null;for(let z of this._triggers){let G=z.detect(Z,Y);if(G&&(!X||G.start>X.start))X=G}if(!this.currentState.isActive&&X&&X.query.length>0){let z=f6(Z),G=Y,F=G;while(F<z.length){let q=z[F];if(q&&/[\s)\]}@]/.test(q))break;F++}if(F>G){let W=[...z.slice(0,G),...z.slice(F)].join("");this._textController.text=W,this._textController.cursorPosition=Y;return}}if(!X){if(this.currentState.isActive)this.dismiss();else this._clearPendingBuildTimer();return}let K=Q&&this._shouldDebounceBuild(J,X),V=this.currentState.generationId+1;if(this._updateState({trigger:X,generationId:V,options:K?[]:this.currentState.options,isActive:!K,selectedIndex:-1}),K){this._scheduleDebouncedBuild(X.query,V);return}this._clearPendingBuildTimer(),this._buildOptions(X.query,V)};async _buildOptions(J,Z){if(!this._optionsBuilder)return;try{let Q=await this._optionsBuilder(J);if(this.currentState.generationId===Z&&!this._disposed)this._updateState({options:Q,selectedIndex:Q.length>0?0:-1,isActive:Q.length>0})}catch(Q){if(P.error("Error building autocomplete options:",Q),this.currentState.generationId===Z&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_scheduleDebouncedBuild(J,Z){this._clearPendingBuildTimer(),this._pendingBuildTimer=setTimeout(()=>{this._pendingBuildTimer=null,this._buildOptions(J,Z)},nR3)}_shouldDebounceBuild(J,Z){if(!J)return!1;if(J.trigger!==Z.trigger||J.start!==Z.start)return!1;return Z.query.length<J.query.length}_clearPendingBuildTimer(){if(this._pendingBuildTimer)clearTimeout(this._pendingBuildTimer),this._pendingBuildTimer=null}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._clearPendingBuildTimer(),this._textController)this._textController.removeListener(this._handleTextChange)}}class Aa{}class ja{}class Ra{}class Pz0{}class Cz0 extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Ih4(this.props)}}class Ih4 extends p0{props;controller;stateListener=null;overlayEntry=null;layerLink=new wa;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new G6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new F01,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=jh4(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.handle)this.props.handle.dismiss=()=>this.controller.dismiss();if(this.props.autofocus??!0)C6.instance.addPostFrameCallback(()=>{this._effectiveFocusNode.requestFocus()})}didUpdateWidget(J){super.didUpdateWidget(J);let Z=J.props,Q=this.widget.props;if(this.props=Q,Z.controller!==Q.controller||Z.triggers!==Q.triggers||Z.optionsBuilder!==Q.optionsBuilder||Z.textFieldProps!==Q.textFieldProps||Z.onSelected!==Q.onSelected)this.controller.initialize({textController:Q.controller,triggers:Q.triggers,optionsBuilder:Q.optionsBuilder,onSelected:Q.onSelected});if(Z.handle!==Q.handle){if(Q.handle)Q.handle.dismiss=()=>this.controller.dismiss()}this.setState(()=>{})}dispose(){this.removeOverlay(),this.stateListener?.dispose(),this.controller.dispose(),this._effectiveFocusNode.dispose(),super.dispose()}invoke=(J)=>{if(!this.controller.currentState.isActive)return"ignored";if(J instanceof Aa)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof ja)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Ra)return this.controller.acceptSelected(),"handled";if(J instanceof Pz0)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Z=J.selectedIndex,Q=J.options.length,Y=this._cachedMaxVisibleOptions||Q;if(Y>=Q){this.scrollOffset=0;return}let X=Z-this.scrollOffset,K=1,V=this.scrollOffset;if(X>=Y-K)V=Math.max(0,Z-(Y-K-1));if(X<K)V=Math.max(0,Z-K);let z=Math.max(0,Q-Y);V=Math.min(V,z),this.scrollOffset=V}build(J){let Z=new IZ({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Q=new m$({shortcuts:new Map([[new D4("ArrowDown"),new Aa],[new D4("ArrowUp"),new ja],[new D4("n",{ctrl:!0}),new Aa],[new D4("p",{ctrl:!0}),new ja],[new D4("Enter"),new Ra],[new D4("Escape"),new Pz0],[new D4("Tab"),new Ra]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new M7({actions:new Map([[Aa,new D6(this.invoke)],[ja,new D6(this.invoke)],[Ra,new D6(this.invoke)],[Pz0,new D6(this.invoke)]]),child:Q});return new Na({link:this.layerLink,child:Y})}updateOverlay(){let J=this.controller.currentState;if(J.isActive&&J.options.length>0)if(!this.overlayEntry)this.createOverlay();else this.overlayEntry.markNeedsBuild();else this.removeOverlay()}createOverlay(){if(this.overlayEntry)return;this.overlayEntry=new z01((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{UR.of(this.context).insert(this.overlayEntry)}catch(J){P.error("Failed to insert autocomplete overlay:",J),this.overlayEntry=null}}removeOverlay(){if(this.overlayEntry)this.overlayEntry.remove(),this.overlayEntry=null}buildOverlayHints(J,Z){if(this.props.overlayHint!==void 0){if(this.props.overlayHint===null)return[];let{prefix:Q,suffix:Y}=this.props.overlayHint,X=[];if(Q)X.push(new C(Q,new g({color:f0.of(J).app.command})),new C(" ",new g({color:Z})));return X.push(new C(Y,new g({color:Z}))),[{child:new e({text:new C(" ",new g({dim:!0}),X)}),position:"top",alignment:"center"}]}return[]}buildOverlayContent(J,Z){let Q=x1.maybeOf(J),Y=Q?.colorScheme.background??M0.default(),X=this.props.overlayBorderColor??Q?.colorScheme.border??M0.default(),K=Z.options.length,V=V4.sizeOf(J).height,z=0;try{let R=this.layerLink.getTargetTransform();if(R)z=R.position.y}catch{}let G=this.props.autoOverlayPosition?z<V/3:!1,F=2,q;if(G){let R=this.props.controller.getCursorVisualRow(),_=z+R+1;q=V-_-F}else q=z-F;K=Math.min(K,Math.max(1,q)),this._cachedMaxVisibleOptions=K,this.updateScrollPosition();let W=this.scrollOffset,U=Math.min(Z.options.length,W+K),H=[],D=0;for(let R=W;R<U;R++){let _=Z.options[R];if(!_)continue;let T=R===Z.selectedIndex,u,m;if(this.props.optionViewBuilder){u=this.props.optionViewBuilder(J,_,T);let f=this.props.displayStringForOption?.(_)??String(_),d="",p=f,h=_;if(h&&typeof h==="object"&&"type"in h)switch(h.type){case"file":d="@",p=h.path||f;break;case"artifact":d="",p=h.label||f;break}m=d+p}else{let f=this.props.displayStringForOption?.(_)??String(_),d=Q?.colorScheme.selection??M0.default(),p=Q?.colorScheme.foreground??M0.default();u=new e({text:new C(f,new g({color:p,backgroundColor:T?d:void 0}))}),m=f}let y=V4.of(J),k=x5(m,y.supportsEmojiWidth);D=Math.max(D,k),H.push(u)}let B=V4.sizeOf(J).width,N=D+4,w=Math.floor(B*0.9),L=Math.max(Math.min(N,w),Math.min(30,w)),M=H.length+2,A;if(G)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new R0({width:L,child:new d0({height:M,decoration:new $6(Y),child:new s8({decoration:{border:c1.all(new g1(X,1,"rounded"))},padding:C0.symmetric(1,0),overlays:this.buildOverlayHints(J,X),child:new x0({crossAxisAlignment:"start",children:H})})})});return new G01({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function Ph4(J){if(J.kind!=="file"&&J.kind!=="folder")throw Error("Invalid completion item: missing path or kind");return{type:"file",path:J.path,kind:J.kind}}function Ch4(J){switch(J.type){case"file":return J.path;case"hint":return`${aR3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function Th4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function aR3(J){switch(J){case"commit":return"@:";case"thread":return"@@"}}class vq{detect(J,Z){if(!J||Z<1)return null;let Q=f6(J);if(Z>Q.length)return null;let Y=this.findWordStart(Q,Z);if(Y>=Q.length||Q[Y]!=="@")return null;let X=Q.slice(Y+1,Z).join("");if(X.includes(" ")||X.includes("\t")||X.includes(`
|
|
7376
7376
|
`))return null;return{start:Y,end:Z,query:X,trigger:"@"}}findWordStart(J,Z){let Q=Z;for(let Y=Z-1;Y>=0;Y--){let X=J[Y];if(!X||/[\s([{]/.test(X)){Q=Y+1;break}if(Y===0)Q=0}return Q}}class NR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Sh4(this.props)}}var JI3=":";class Sh4 extends p0{props;_effectiveFocusNode;_textChangeListener=null;_isCommitMode=!1;_imageUploadSpinner=new V3;_imageUploadSpinnerInterval=null;constructor(J){super();this.props=J}buildOptions=async(J)=>{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=new vq().detect(Z,Q);if(X&&this.props.completionBuilder){if(X.query==="@"&&this.props.onDoubleAtTrigger)return this.props.onDoubleAtTrigger(this.props.controller),[];let z=X.query.toLowerCase().startsWith(JI3);if(z!==this._isCommitMode)this._isCommitMode=z,this.setState();return await this.props.completionBuilder.buildOptions(X)}if(this._isCommitMode)this._isCommitMode=!1,this.setState();return[]};defaultOnOptionSelected=(J)=>{switch(J.type){case"hint":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),z=J.kind==="commit"?"@:":"@@",G=K+z+V;this.props.controller.clear(),this.props.controller.insertText(G),this.props.controller.cursorPosition=X+z.length}return}case"file":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),z=K+`@${J.path} `+V;this.props.controller.clear(),this.props.controller.insertText(z),this.props.controller.cursorPosition=X+1+J.path.length+1}break}case"commit":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),z=`git-commit(${J.hash})`,G=K+z+" "+V;this.props.controller.clear(),this.props.controller.insertText(G),this.props.controller.cursorPosition=X+z.length+1}break}}};initState(){super.initState(),this._effectiveFocusNode=this.props.focusNode||new G6({debugLabel:"PromptEditorFocus"}),this._textChangeListener=()=>{this.setState()},this.props.controller.addListener(this._textChangeListener),this.props.controller.onInsertText=(J,Z)=>{if(J.length<=3)return!0;let Q=Eb4(J);if(Q.length===0)return!0;if(this.props.onInsertImage){for(let Y of Q)this.props.onInsertImage(Y);return!1}return!0},this.syncImageUploadSpinner()}didUpdateWidget(J){super.didUpdateWidget(J),this.props=this.widget.props,this.syncImageUploadSpinner()}dispose(){if(this._imageUploadSpinnerInterval)clearInterval(this._imageUploadSpinnerInterval),this._imageUploadSpinnerInterval=null;if(this._textChangeListener)this.props.controller.removeListener(this._textChangeListener),this._textChangeListener=null;if(!this.props.focusNode)this._effectiveFocusNode.dispose();super.dispose()}syncImageUploadSpinner(){if(this.props.showImageUploadSpinner===!0){if(!this._imageUploadSpinnerInterval)this._imageUploadSpinnerInterval=setInterval(()=>{this._imageUploadSpinner.step(),this.setState()},120);return}if(this._imageUploadSpinnerInterval)clearInterval(this._imageUploadSpinnerInterval),this._imageUploadSpinnerInterval=null}_handleOpenInEditor=async(J)=>{try{let Z=await oR3(_h4.join($I3(),"amp-edit-")),Q=_h4.join(Z,"message.amp.md");await eR3(Q,J,"utf-8"),await hK(Q);try{let Y=await rR3(Q,"utf-8");this.props.controller.text=Y}catch(Y){if(Y?.code!=="ENOENT")P.error("Failed to read temporary file",Y)}try{await tR3(Q),await sR3(Z)}catch(Y){P.warn("Failed to clean up temporary file",Y)}}catch(Z){P.error("Error opening editor:",Z)}};_handleBackspaceAtStart=()=>{if(this.props.imageAttachments.length>0&&this.props.popImage)return this.props.popImage(),!0;if((this.props.pendingSkills??[]).length>0&&this.props.popSkill)return this.props.popSkill(),!0;return!1};_handleSubmitted=(J)=>{if(this.props.previousThreadId&&J.trim()===""){this.props.onPreviousThreadHintAccepted?.();return}this.props.onSubmitted?.(J)};build(J){let Z=this.props.theme,Q=this.props.pendingSkills??[],Y=this.props.imageAttachments.length>0,X=Q.length>0?new W1({mainAxisSize:"min",children:[new e({text:new C("Skills: ",new g({color:Z.foreground,dim:!0}))}),...Q.flatMap((G,F)=>{let q=new Q4({onClick:()=>{this.props.onSkillClick?.(F)},cursor:"pointer",child:new e({text:new C(G.name,new g({color:Z.success,underline:!0}))})});if(F<Q.length-1)return[q,new e({text:new C(" ")})];return[q]})]}):null,K=Y?new W1({mainAxisSize:"min",children:[new e({text:new C("Images: ",new g({color:Z.foreground,dim:!0}))}),...this.props.imageAttachments.flatMap((G,F)=>{let q=this.props.onImageClick!==void 0,W=new Q4({onClick:q?()=>{this.props.onImageClick?.(F)}:void 0,cursor:q?"pointer":void 0,child:new e({text:new C(`[Image ${F+1}]`,new g({color:Z.success,underline:!0}))})});if(F<this.props.imageAttachments.length-1)return[W,new e({text:new C(" ")})];return[W]}),...this.props.showImageUploadSpinner?[new e({text:new C(" ")}),new e({text:new C(this._imageUploadSpinner.toBraille(),new g({color:Z.foreground,dim:!0}))})]:[]]}):null,V=new Cz0({controller:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.buildOptions,onSelected:this.props.onOptionSelected??this.defaultOnOptionSelected,displayStringForOption:(G)=>Ch4(G),overlayBorderColor:Z.border,focusNode:this._effectiveFocusNode,autofocus:this.props.autofocus??!0,autoOverlayPosition:this.props.autoOverlayPosition,handle:this.props.autocompleteHandle,textFieldProps:{placeholder:this.props.placeholder,wrap:!0,minLines:this.props.minLines??3,maxLines:null,expands:!0,autofocus:!1,enabled:this.props.enabled??!0,onSubmitted:this._handleSubmitted,onOpenInEditor:this._handleOpenInEditor,submitKey:this.props.submitKey??{character:"Enter"},prompts:this.props.shellPromptRules,style:{backgroundColor:Z.background,border:null,padding:C0.all(0),textColor:this.props.textColor??Z.foreground,cursorColor:Z.cursor,placeholderColor:Z.mutedForeground,selectionBackgroundColor:Z.selection},clipboard:this.props.clipboard,onCopy:this.props.onCopy,copyOnSelectionEnabled:!0,onBackspaceWhenEmpty:this._handleBackspaceAtStart},optionViewBuilder:(G,F,q)=>{let W=q?Z.selection:void 0,U=Z.secondary,H=Z.foreground,D=Z.foreground,B=Z.warning;if(F.type==="commit")return new d0({decoration:new $6(W),child:new W1({children:[new y1({child:new e({text:new C("",void 0,[new C(F.shortHash,new g({color:Z.secondary})),new C(" ",new g({})),new C(F.message,new g({color:H}))]),maxLines:1,overflow:"ellipsis"})}),new e({text:new C(` ${F.relativeDate}`,new g({color:D,dim:!0}))})]})});let N=[];switch(F.type){case"file":N.push(new C("@",new g({color:U}))),N.push(new C(F.path,new g({color:H})));break;case"hint":N.push(new C(F.kind==="commit"?"@:":"@@",new g({color:B}))),N.push(new C(" ",new g({}))),N.push(new C(F.message,new g({color:B})));break}let w=Th4(F);if(w)N.push(new C(" - ",new g({color:D,dim:!0}))),N.push(new C(w,new g({color:D,dim:!0})));return new d0({decoration:new $6(W),child:new e({text:new C("",void 0,N),maxLines:1,overflow:"ellipsis"})})}}),z=[];if(this.props.topWidget)z.push(this.props.topWidget);if(X||K){let G=[];if(X)G.push(X);if(X&&K)G.push(new e({text:new C(" ")}));if(K)G.push(K);let F=new d0({padding:C0.only({bottom:1}),child:new W1({mainAxisSize:"min",children:G})});z.push(F)}if(z.push(new y1({child:V})),this.props.bottomWidget)z.push(this.props.bottomWidget);return new x0({crossAxisAlignment:"start",children:z})}requestFocus(){this._effectiveFocusNode.requestFocus()}}class kh4 extends p0{controller=new r7;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new G6({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(J)=>{if(this.imageAttachments.length>=PV)return!1;let Z=await JL(J);if(typeof Z==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,K=V4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),z=new NR({controller:this.controller,triggers:[new vq],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(H)=>{this.widget.props.onSubmit(H.trim(),this.imageAttachments)},theme:Q,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:t4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),G=new s4({focusNode:this.focusNode,child:z}),F=new d0({constraints:new I1({maxHeight:V}),padding:C0.symmetric(1,0),child:G}),q=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=new d0({padding:C0.symmetric(1,0),child:new e({text:this.isConfirmingClearInput?new C("",void 0,[new C("Esc",new g({color:Y.keybind})),new C(" again to clear input",new g({color:Q.foreground,dim:!0}))]):new C("",void 0,[new C("Press ",new g({color:Q.foreground,dim:!0})),new C("Enter",new g({color:Y.keybind})),new C(" to submit, ",new g({color:Q.foreground,dim:!0})),new C("Esc",new g({color:Y.keybind})),new C(" to clear",new g({color:Q.foreground,dim:!0}))])})}),U=[q,new R0({height:1}),new y1({child:F}),new R0({height:1}),W];return new d0({decoration:{border:c1.all(new g1(Q.foreground,1,"solid")),color:Q.background},padding:C0.all(1),child:new x0({children:U})})}}class q01 extends l0{props;constructor(J){super();this.props=J}createState(){return new kh4}}import{isDeepStrictEqual as W01}from"node:util";var ZI3=/[\\/_ +.#"@[({&]/,QI3=/[\\/_ +.#"@[({&]/g,YI3=/[\s-]/,vh4=/[\s-]/g;function _z0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${K}`;if(V[z]!==void 0)return V[z];let G=Y.charAt(K),F=Q.indexOf(G,X),q=0,W,U,H,D;while(F>=0){if(W=_z0(J,Z,Q,Y,F+1,K+1,V),W>q){if(F===X)W*=1;else if(YI3.test(J.charAt(F-1))){if(W*=0.9,D=J.slice(X,F-1).match(vh4),D&&X>0)W*=0.999**D.length}else if(ZI3.test(J.charAt(F-1))){if(W*=0.8,H=J.slice(X,F-1).match(QI3),H&&X>0)W*=0.999**H.length}else if(W*=0.3,X>0)W*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(K))W*=0.9999}if(W<0.1&&(Q.charAt(F-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(F-1)!==Y.charAt(K))){if(U=_z0(J,Z,Q,Y,F+1,K+2,V),U*0.1>W)W=U*0.1}if(W>q)q=W;F=Q.indexOf(G,F+1)}return V[z]=q,q}function Tz0(J){return J.toLowerCase().replace(vh4," ")}function yh4(J,Z){let Q=_z0(J,Z,Tz0(J),Tz0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let z of Y){let G=_z0(J,z,Tz0(J),Tz0(z),0,0,{});if(G===0)return Q;X+=G,K+=z.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class Hy{}class Dy{}class Sz0{}class kz0{}class xh4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new fh4}}class fh4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function XI3(J,Z){if(J==="")return{matches:!0,score:1};let Q=yh4(Z,J);return{matches:Q>0.15,score:Q}}class $7 extends l0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new uh4}}class uh4 extends p0{textController;focusNode;scrollController=new j5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new r7(this.widget.props.controller?.query??""),this.focusNode=new G6({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>W01(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!W01(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>W01(Q,this.widget.props.controller?.selectedItem));if(Z>=0)this.selectedIndex=Z}this.clampSelectedIndex(),this.ensureSelectedItemVisible(),this.syncSelection()}}dispose(){this.widget.props.onSelectionChange?.(null),this.textController.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof Hy){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof Dy){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof Sz0){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length){let Q=Z[this.selectedIndex];if(Q){if(!(this.widget.props.isItemDisabled?.(Q)??!1))this.widget.props.onAccept(Q,{hasUserInteracted:this.hasUserInteracted})}}return"handled"}if(J instanceof kz0)return this.widget.props.onDismiss?.(),"handled";return"ignored"};syncSelection(){let Z=this.cachedFiltered[this.selectedIndex]??null;if(this.widget.props.controller)this.widget.props.controller.selectedItem=Z;this.widget.props.onSelectionChange?.(Z)}clampSelectedIndex(){let J=this.cachedFiltered.length-1;if(J<0){this.selectedIndex=0;return}this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,J))}recomputeFilteredItems(){let J=this.textController.text,Z=this.widget.props.items,Q=this.widget.props.normalizeQuery?.(J)??J,Y=Z.filter((X)=>!this.widget.props.filterItem||this.widget.props.filterItem(X,J)).map((X)=>({item:X,...XI3(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,K)=>this.widget.props.sortItems(X,K,J):(X,K)=>K.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Z=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Z)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;zy(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=c1.all(new g1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,z=new IZ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),G=new m$({shortcuts:new Map([[new D4("ArrowDown"),new Hy],[new D4("ArrowUp"),new Dy],[new D4("Tab"),new Hy],[new D4("Tab",{shift:!0}),new Dy],[new D4("n",{ctrl:!0}),new Hy],[new D4("p",{ctrl:!0}),new Dy],[new D4("Enter"),new Sz0],[new D4("Escape"),new kz0]]),focusNode:this.focusNode,child:z}),F=new M7({actions:new Map([[Hy,new D6(this.invoke)],[Dy,new D6(this.invoke)],[Sz0,new D6(this.invoke)],[kz0,new D6(this.invoke)]]),child:G}),q=new W1({children:[new d0({decoration:{color:Q.background},child:new e({text:new C(">",new g({color:Q.foreground}))})}),new y1({child:F})]});this.itemContexts=[];let W;if(this.widget.props.isLoading){let N=this.widget.props.loadingText??"Loading...";W=new R0({height:10,child:new X4({child:new e({text:new C(N,new g({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)W=new y1({child:new X4({child:new e({text:new C(this.widget.props.emptyStateText,new g({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,L)=>{let O=L===this.selectedIndex,E=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,O,E,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new d0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C(this.widget.props.getLabel(w),new g({color:j,dim:E}))})})}return new xh4(new Q4({onClick:(A)=>this.handleItemClick(L,A.clickCount),child:M}),(A)=>{this.itemContexts[L]=A})});W=new x0({children:N,crossAxisAlignment:"start"})}let U=new Q4({onScroll:this.handleScroll,opaque:!1,child:new T6({controller:this.scrollController,autofocus:!1,child:W})}),H=[];if(this.widget.props.title){let N=new d0({padding:C0.symmetric(1,0),child:new e({text:new C(this.widget.props.title,new g({color:Z.app.command,bold:!0}))})});H.push(N)}if(!K)H.push(q,new R0({height:1}));if(this.textController.text!==""){let N=Y.length>0?Y[this.selectedIndex]:void 0,w=N&&this.widget.props.buildDisabledReasonWidget?.(N,J);H.push(new y1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new y1({child:U}),new d0({padding:C0.only({top:1}),child:new X4({child:w??new R0({height:1})})})]})}))}else H.push(new y1({child:U}));if(this.widget.props.footer)H.push(this.widget.props.footer);return new d0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:H})})}}function bh4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),K=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(K<7)return`${K}d ago`;return J.toLocaleDateString()}class U01 extends J4{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,K)=>K.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>bh4(X.pubDate).length));return new $7({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,K,V,z)=>{let G=f0.of(z),{colors:F}=G,q=G.app,W=K?q.selectionBackground:void 0,U=K?q.selectionForeground:F.foreground,H=F.mutedForeground,D=(B,N)=>new R0({width:N,child:W1.end([new e({text:new C(B,new g({color:H}))})])});return new d0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new W1({children:[new y1({child:new e({text:new C(X.title,new g({color:U})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),D(bh4(X.pubDate),Q)]})})}})}}hP();class H01 extends l0{createState(){return new hh4}}class hh4 extends p0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new e({text:new C("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function KI3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let z=V.relationships.find((G)=>G.role==="child"&&Z.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(z){Y.set(V.id,z.type);let G=z.threadID,F=Q.get(G)||[];F.push(V),Q.set(G,F)}else X.push(V)}return QV0.flatten(X,(V)=>Q.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function D01(J,Z,Q){return new e({text:new C(`${J}${Z}`,new g({color:Q})),maxLines:1})}function VI3(J,Z,Q,Y){return[D01("+",J,Y.success),f3.horizontal(1),D01("~",Z,Y.warning),f3.horizontal(1),D01("-",Q,Y.destructive)]}function zI3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class vz0 extends l0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new gh4}}class gh4 extends p0{spinner=new V3;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,K=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((L)=>L.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((L)=>L.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],z=new Set(V),G=Z.currentThreadID,F=[...K].sort((L,O)=>{if(G){if(L.id===G)return-1;if(O.id===G)return 1}let E=V.indexOf(L.id),M=V.indexOf(O.id);if(E!==-1&&M!==-1)return E-M;if(E!==-1)return-1;if(M!==-1)return 1;return 0}),q=KI3(F),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),U=f0.of(J),H=new n0({padding:C0.symmetric(0,1),child:new X4({child:new e({text:new C("",new g({color:U.colors.foreground,dim:!0}),[new C("Alt+W/Ctrl+T",new g({color:U.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:U.colors.foreground,dim:!0}))])})})}),D="",B=null,N=(L)=>{if(L!==D)D=L,B=H$(L);return B};return new $7({items:q,getLabel:(L)=>`${L.title} ${L.id}`,filterItem:(L,O)=>{let E=N(O);if(E)return L.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(L)=>N(L)?"":L,onAccept:async(L,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(L.id,O);if(!zI3(E))return;this.setSwitchingThread(!0);try{await E}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(L)=>{if(Z.previewController){if(L)Z.previewController.select(L.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:H,renderItem:(L,O,E,M)=>{let A=f0.of(M),{app:j,colors:R}=A,_=O?j.selectionBackground:void 0,T=O?j.selectionForeground:R.foreground,u=R.mutedForeground,m=(a,W0)=>new R0({width:W0,child:W1.end([new e({text:new C(a,new g({color:u}))})])}),y=Z.threadViewStates[L.id],k=[],f=L.relationshipType==="handoff",d=new on({connectorColor:R.mutedForeground});if(L.depth>0){let a=[],W0=L.ancestorsAreLast.slice(1);for(let L0 of W0)a.push(new C(d.getAncestorPrefix(L0),new g({color:d.connectorColor,dim:d.connectorDim})));let r=L.isLast?d.elbow:d.tee,H0=d.getConnectorText(r);a.push(new C(H0,new g({color:d.connectorColor,dim:d.connectorDim}))),k.push(new e({text:new C("",void 0,a)}))}let p=[],h=G===L.id?new C("(current) ",new g({color:R.success})):z.has(L.id)?new C("(visited) ",new g({color:R.foreground,dim:!0})):null;if(h)p.push(new e({text:h}));if(HN(y))p.push(new H01),p.push(new R0({width:1}));let n=L.title;if(L.relationshipType==="fork"){let a=n.match(/^Forked\((\d+)\): /);if(a)n=n.slice(a[0].length);else while(n.startsWith("Forked: "))n=n.slice(8);p.push(new e({text:new C("[fork] ",new g({color:R.primary}))}))}else if(f)p.push(new e({text:new C("[handoff] ",new g({color:R.accent}))}));if(p.push(new y1({child:new e({text:new C(n,new g({color:T})),overflow:"ellipsis",maxLines:1})})),p.push(new R0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let a=O?{success:u,warning:u,destructive:u}:R;p.push(...VI3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,a)),p.push(new R0({width:2}))}return p.push(m(L.description.timeAgo,W)),new d0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new W1({children:[...k,...p]})})}})}}function mh4(J){return 1-(1-J)**3}function ph4(J,Z,Q){return J+(Z-J)*Q}function Ia(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),K=mh4(Y),V=mh4(X);return{x:ph4(J.startOffset.x,J.targetOffset.x,K),y:ph4(J.startOffset.y,J.targetOffset.y,V)}}var GI3={nodeWidth:3,horizontalSpacing:3};class By{options;constructor(J={}){this.options={...GI3,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let K=0,V=(z,G)=>{let F=Z.get(z.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let q={...z,parentID:Q.get(z.id)};if(F.length===0){Y.push({node:q,position:{x:K,y:G}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let W=[];for(let B of F)W.push(V(B,G+1));let U=Math.min(...W),H=Math.max(...W),D=Math.floor((U+H)/2);return Y.push({node:q,position:{x:D,y:G}}),D};for(let z of X)V(z,0);return Y}buildTree(J){let Z=new Set(J.map((K)=>K.id)),Q=[...J].sort((K,V)=>K.id.localeCompare(V.id)),Y=new Map;for(let K of Q){if(!K.parentID||!Z.has(K.parentID)){Y.set(K.id,void 0);continue}let V=!1,z=K.parentID;while(z){if(z===K.id){V=!0;break}z=Y.get(z)}Y.set(K.id,V?void 0:K.parentID)}let X=new Map;for(let K of J){let V=Y.get(K.id);if(!X.has(V))X.set(V,[]);X.get(V).push(K)}return{childrenMap:X,resolvedParent:Y}}}var FI3={nodeWidth:3,nodeHeight:2};class Ny{options;constructor(J={}){this.options={...FI3,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let K=this.calculateConnectorLine(X.position,Y.position);Z.push({points:K,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,K=Z.x+Q,V=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:V});let z=V+1;if(Y.push({x:X,y:z}),X!==K)Y.push({x:K,y:z});let G=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:G}),Y}}var qI3={nodeWidth:3,nodeHeight:2},WI3={x:0,y:0};class xz0{options;constructor(J={}){this.options={...qI3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=WI3,X,K,V,z){let G=z?f0.of(z):null,F=G?.colors,q=G?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new e({text:new C("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),D=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let _=[],T=0;for(let u of R){if(u.position.x>T)_.push(new R0({width:u.position.x-T}));let m=u.node.id===Q,y=V?.(u.node.data)??!1,k=K?.activeFlashOn??!1,f=u.node.id===K?.copyFlashNodeId;_.push(this.renderNode(m,y,k,f,q,F)),T=u.position.x+this.options.nodeWidth}if(N.push(new W1({crossAxisAlignment:"start",children:_})),j>0){let u=J.filter((k)=>k.position.y===j-1),m=R,y=this.renderConnectors(u,m,Z,D,F,q);N.push(...y)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(U+1)*B,M=[new R0({width:D,height:E}),new t6({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,_=L+A.position.x+this.options.nodeWidth+1,T=O+R*B+1,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new t6({left:_,top:T,child:this.renderInfoBox(j,u,F,q)}))}return new d0({padding:C0.horizontal(2),child:new uz(new z5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",z="└─┘",G=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,F=!1;if(Y)G=X?.threadGraphNodeSelected??K?.primary??G,V="┏━┓",z="┗━┛",F=!0;else if(Z&&Q)G=X?.toolSuccess??K?.primary??G,V="┏━┓",z="┗━┛";return new x0({crossAxisAlignment:"start",children:[new e({text:new C(V,new g({color:G,bold:F}))}),new e({text:new C(z,new g({color:G,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),K=Math.min(Z,Math.max(1,...X.map((U)=>U.length))),V=K+2,z="┌"+"─".repeat(V)+"┐",G="└"+"─".repeat(V)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,W=[new e({text:new C(z,new g({color:F}))})];for(let U of X){let H=" ".repeat(K-U.length);W.push(new e({text:new C("│ ",new g({color:F}),[new C(U+H,new g({color:q??F})),new C(" │",new g({color:F}))])}))}return W.push(new e({text:new C(G,new g({color:F}))})),new x0({crossAxisAlignment:"start",children:W})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),G=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of Z){let H=U.position.x+z;if(H>=0&&H<Y)F[H]="▲"}V.push(new e({text:new C(F.join(""),new g({color:G}))}));let q=Array(Y).fill(" ");for(let U of J){let H=Z.filter((L)=>L.node.parentID===U.node.id);if(H.length===0)continue;let D=U.position.x+z,B=H.map((L)=>L.position.x+z),N=Math.min(...B),w=Math.max(...B);for(let L=N;L<=w;L++)if(L>=0&&L<Y){if(L===D)if(H.length===1&&B[0]===D)q[L]="│";else if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┬";else if(B.includes(L))if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┴";else if(q[L]===" ")q[L]="─"}}V.push(new e({text:new C(q.join(""),new g({color:G}))}));let W=Array(Y).fill(" ");for(let U of J){if(Z.filter((B)=>B.node.parentID===U.node.id).length===0)continue;let D=U.position.x+z;if(D>=0&&D<Y)W[D]="│"}return V.push(new e({text:new C(W.join(""),new g({color:G}))})),V}}var UI3={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},HI3={x:0,y:0};class B01{options;constructor(J={}){this.options={...UI3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=HI3,X,K,V,z){let G=z?f0.of(z):null,F=G?.colors,q=G?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new e({text:new C("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),D=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let _=[],T=0;for(let u of R){if(u.position.x>T)_.push(new R0({width:u.position.x-T}));let m=u.node.id===Q,y=V?.(u.node.data)??!1,k=K?.activeFlashOn??!1;_.push(this.renderNode(m,y,k,q,F)),T=u.position.x+this.options.nodeWidth}if(N.push(new W1({crossAxisAlignment:"start",children:_})),j>0){let u=J.filter((k)=>k.position.y===j-1),m=R,y=this.renderConnectors(u,m,Z,D,F,q);N.push(...y)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(U+1)*B,M=[new R0({width:D,height:E}),new t6({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,_=L+A.position.x+this.options.nodeWidth+1,T=O+R*B,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new t6({left:_,top:T,child:this.renderInfoBox(j,u,F)}))}return new d0({padding:C0.horizontal(2),child:new uz(new z5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let K=J?this.options.selectedIcon:this.options.nodeIcon,V=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)V=Y?.toolSuccess??X?.primary??V,K="■";return new e({text:new C(K,new g({color:V}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,K=[];for(let V of Y)K.push(new e({text:new C(V,new g({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),G=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let q of J){let W=Z.filter((N)=>N.node.parentID===q.node.id);if(W.length===0)continue;let U=q.position.x+z,H=W.map((N)=>N.position.x+z),D=Math.min(...H),B=Math.max(...H);for(let N=D;N<=B;N++)if(N>=0&&N<Y){let w=N===U,L=H.includes(N);if(w&&L)if(W.length===1)F[N]="│";else if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┼";else if(w)if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┬";else if(L)if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┴";else if(F[N]===" ")F[N]="─"}}return V.push(new e({text:new C(F.join(""),new g({color:G}))})),V}}class Pa extends n3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new dh4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class dh4 extends u4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let Y=this.children[0];if(Y)Y.layout(J),this.setSize(Y.size.width,Y.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let Y of this.children)Y.paint(J,Z,Q)}}class wR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new ih4}}var ch4=400,lh4=300,DI3=16;class ih4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new By({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new Ny;renderer=new B01;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((G)=>G.id)),Q=new Set(this.widget.props.threads.map((G)=>G.id));if(Z.size!==Q.size||[...Z].some((G)=>!Q.has(G)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,K=this.widget.props.initialSelectedThreadID;if(X!==K&&K){let F=this.widget.props.threads.find((q)=>q.id===K);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((G)=>G.isActive),z=this.widget.props.threads.some((G)=>G.isActive);if(V!==z){if(this.stopActiveFlashTimer(),z)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:ch4,durationY:lh4};let Z=Math.max(ch4,lh4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Ia(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},DI3)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),K=Math.floor(this.viewportWidth/2)-J-Y,V=Q-Z,z=2,G=Math.floor(this.viewportHeight/2),q=Math.floor(G/2)-V;return{x:K,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((K)=>K.node.parentID===Q.node.id);if(X.length>0){X.sort((V,z)=>V.position.x-z.position.x);let K=Math.floor(X.length/2);Y=X[K]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x<Q.position.x);if(X.length>0)X.sort((K,V)=>V.position.x-K.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x>Q.position.x);if(X.length>0)X.sort((K,V)=>K.position.x-V.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((W)=>W.node.id===this.selectedNodeId):null)??this.positionedNodes.find((W)=>!W.node.parentID);if(q){let W=Math.max(...this.positionedNodes.map((U)=>U.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,W)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),G=new Pa({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new s4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:G})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class ah4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new oh4}}class oh4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var nh4=30,BI3=30;class wy{}class Ly{}class fz0{}class uz0{}class N01 extends l0{props;constructor(J){super();this.props=J}createState(){return new rh4}}class rh4 extends p0{highlightedIndex=0;controller=new r7;focusNode;scrollController=new j5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new G6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;zy(J,{top:Q,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof wy){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof Ly){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof fz0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof uz0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,z=V4.of(J).size.width>=BI3+nh4,G=c1.all(new g1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,q=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("Select a cluster",new g({color:X.command,bold:!0}))})}),W=new IZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),U=new m$({shortcuts:new Map([[new D4("ArrowDown"),new wy],[new D4("ArrowUp"),new Ly],[new D4("Tab"),new wy],[new D4("Tab",{shift:!0}),new Ly],[new D4("n",{ctrl:!0}),new wy],[new D4("p",{ctrl:!0}),new Ly],[new D4("Enter"),new fz0],[new D4("Escape"),new uz0]]),focusNode:this.focusNode,child:W}),H=new M7({actions:new Map([[wy,new D6(this.invoke)],[Ly,new D6(this.invoke)],[fz0,new D6(this.invoke)],[uz0,new D6(this.invoke)]]),child:U}),D=new W1({children:[new d0({decoration:{color:Y.background},child:new e({text:new C(">",new g({color:Y.foreground}))})}),new y1({child:H})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,R=Z?M.threads.some((m)=>m.id===Z):!1,_=j?X.selectionBackground:void 0,T=j?X.selectionForeground:Y.foreground,u=[new C(M.label,new g({color:T})),new C(` (${M.threads.length})`,new g({color:T,dim:!0}))];if(R)u.push(new C(" (current)",new g({color:j?X.selectionForeground:Y.success})));return new ah4(new Q4({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new d0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C("",void 0,u)})})}),(m)=>{this.itemContexts[A]=m})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new y1({child:new Q4({onScroll:this.handleScroll,child:new T6({controller:this.scrollController,autofocus:!1,child:N})})}),L=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],O=F?new d0({padding:C0.all(1),child:new wR({threads:L,autofocus:!1,offsetY:2})}):null,E;if(z){let M=O?new y1({child:O}):new R0({width:nh4});E=new W1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new y1({child:new Q4({onScroll:this.handleScroll,child:new T6({controller:this.scrollController,autofocus:!1,child:N})})})];if(O)M.push(new y1({child:O}));E=new x0({crossAxisAlignment:"stretch",children:M})}return new d0({decoration:{border:G,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[q,D,new R0({height:1}),new y1({child:E})]})})}}m0();IX();hM();CX();O$();d4();N4();SP();var L01=B4(tW(),1);import{execSync as LR}from"node:child_process";import{writeFile as Oy}from"node:fs/promises";import NI3 from"node:os";import yq from"node:path";var sh4="c446b2e9b16cdc06df2ec285894d6421",wI3="5ea19563777f4ade8707fc56f7e7a388",LI3="amp-thread-worker",th4=[{id:"cli-open",label:"cli: open in pager"},{id:"cloudflare-logs",label:"cloudflare: open logs"},{id:"cloudflare-data-studio",label:"cloudflare: open data studio"}];function OI3(J){return!!J&&typeof J==="object"&&"usesDtw"in J}function zL(J){if(!J||!OI3(J.meta))return!1;return J.meta.usesDtw===!0}function O01(J){let Z=new URL(`https://dash.cloudflare.com/${sh4}/workers/durable-objects/view/${wI3}/studio`);return Z.searchParams.set("name",J),Z.searchParams.set("jurisdiction","none"),Z.toString()}function E01(J){let Z=new URL(`https://dash.cloudflare.com/${sh4}/workers/services/view/${LI3}/production/observability/events`);return Z.searchParams.set("filterCombination",'"and"'),Z.searchParams.set("calculations",'[{"operator":"count"}]'),Z.searchParams.set("orderBy",'{"value":"count","limit":10,"order":"desc"}'),Z.searchParams.set("timeframe","24h"),Z.searchParams.set("conditions","{}"),Z.searchParams.set("conditionCombination",'"and"'),Z.searchParams.set("alertTiming",'{"interval":300,"window":900,"timeBeforeFiring":600,"timeBeforeResolved":600}'),Z.searchParams.set("filters",JSON.stringify([{key:"threadId",operation:"eq",value:J,type:"string"}])),Z.toString()}function EI3(J,Z){if(OV(J))return`amp dtw-curl ${Z}`;return`AMP_URL=${JSON.stringify(J)} pnpm -C cli cli -- dtw-curl ${Z}`}function M01(J,Z){let Q=EI3(Z,J);return[{label:"dtw: get full transcript",command:`${Q} get-transcript`},{label:"dtw: send message via curl",command:`${Q} add-message "<your message here>"`},{label:"dtw: dump full sqlite DB to disk",command:`${Q} dump`},{label:"dtw: fetch Cloudflare logs",command:`./scripts/fetch-cloudflare-logs.ts ${J}`}]}function Ca(J,Z,Q){let Y=`select(.pid == ${Z})`,X=Ta(Q);return`${J==="snapshot"?`tail -n 10000 ${X}`:`tail -f ${X}`} | jq -C '${Y}'`}function Ta(J){return J.path??f9(J.uri)}function eh4(J,Z,Q){let Y=Ca("snapshot",J,Z);return Q?`${Y} | ${Q}`:Y}function $g4(J,Z){return M01(J,Z).map(({label:Q,command:Y})=>`# ${Q}
|
|
7377
7377
|
${Y}`).join(`
|
|
7378
7378
|
|
|
@@ -7601,7 +7601,7 @@ ${t.content||""}`:t.content||"",T0=[],e0=t.baseDir.startsWith("file://")?AG0(t.b
|
|
|
7601
7601
|
`),process.exit(1)}process.stdout.write(await YS3(G.result.displayText)+`
|
|
7602
7602
|
`),process.exit(0)})}hM();import{stdout as XS3}from"node:process";function KS3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${MF(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function ld4(J){XS3.write(`${KS3(J)}
|
|
7603
7603
|
`)}function id4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{ld4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{ld4(Z),process.exit(0)})}var Ix3=lH.join(nZ,"logs","headless.log"),r61=lH.join(Qv,"device-id.json"),Hn4=`cli-tui-${An4(16).toString("hex")}`;async function Px3(){for(let J of XE)try{if((await J.listConfigs()).length>0)return J}catch(Z){P.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => B4(oy(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){j2.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
7604
|
-
`)}function Cx3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",z=!1;J.warn(K,{name:V,code:Y})}}function A2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")aJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")aJ("experimental.agentMode",Z.mode)}function Pn4(J,Z){if(J.getOptionValueSourceWithGlobals("sp")==="cli"&&Z.sp)return Z.sp;if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Z.systemPrompt)return Z.systemPrompt;return}async function Tx3(J){try{return await Rn4(J,"utf-8")}catch{return J}}async function s61(J,Z,Q){let Y=Pn4(J,Z);if(!Y)return;let X=o6(Q)?Q.features:[],K=o6(Q)?Q.user.email:void 0;if(!Z51(X,S2.HARNESS_SYSTEM_PROMPT)&&!Cn4(K))throw new T1("You are not allowed to do this.",1);aJ("systemPrompt",await Tx3(Y))}function Cn4(J){return!!(J&&J10(J))}function Z51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function t61(J){return(J.userEmail?dJ(J.userEmail):!1)||Z51(J.features,S2.DTW_TUI)}function Dn4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new T1("This TUI mode is not enabled for your user;",1)}function e61(J,Z){if(typeof J==="boolean")return J;if(!o6(Z))return!1;return t61({userEmail:Z.user.email,features:Z.features})}function $51(J){if(!o6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function _x3(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function UF0(J){let Y=_x3(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new T1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function Bn4(J){if(!Y5.write(J))await Mx3(Y5,"drain")}var Nn4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??yK,description:`Custom settings file path (overrides the default location ${yK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Cn0})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:a7(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:fG.SMART.key,description:`Set the agent mode (${uG().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:uG().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"threadActors",long:"thread-actors",type:"switch",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],wn4=(J)=>("deprecated"in J)&&J.deprecated===!0,Sx3=(J)=>("hidden"in J)&&J.hidden===!0,kx3=(J)=>("default"in J),vx3=(J)=>("default"in J)?J.default:void 0,Tn4=[{name:"toggle-skills-count",entryPoint:jo0}];function yx3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((z)=>Q.includes(z)||z.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new T1(E3.unknownCommand(Q),1,V)}}async function Q51(J){return{...J,getThreadEnvironment:uY,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new hV(J.fileSystem),generateThreadTitle:g80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>xX(J.configService),pluginService:J.pluginService}}function _n4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:uY,filesystem:J.fileSystem,threadService:J.threadService}}var HF0=V1.file(In4.homedir()),J51=process.env.XDG_CONFIG_HOME?V1.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(HF0,".config");function xx3(J){return qq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){Fq4(Z);let Q=AX0(),Y=ho0();if((!Q||Y||CT4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(wH("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(wH("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(AX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function fx3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function R7(J,Z,Q){let Y=Q?.deferAuth??!1;Qf1("0.0.
|
|
7604
|
+
`)}function Cx3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",z=!1;J.warn(K,{name:V,code:Y})}}function A2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")aJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")aJ("experimental.agentMode",Z.mode)}function Pn4(J,Z){if(J.getOptionValueSourceWithGlobals("sp")==="cli"&&Z.sp)return Z.sp;if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Z.systemPrompt)return Z.systemPrompt;return}async function Tx3(J){try{return await Rn4(J,"utf-8")}catch{return J}}async function s61(J,Z,Q){let Y=Pn4(J,Z);if(!Y)return;let X=o6(Q)?Q.features:[],K=o6(Q)?Q.user.email:void 0;if(!Z51(X,S2.HARNESS_SYSTEM_PROMPT)&&!Cn4(K))throw new T1("You are not allowed to do this.",1);aJ("systemPrompt",await Tx3(Y))}function Cn4(J){return!!(J&&J10(J))}function Z51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function t61(J){return(J.userEmail?dJ(J.userEmail):!1)||Z51(J.features,S2.DTW_TUI)}function Dn4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new T1("This TUI mode is not enabled for your user;",1)}function e61(J,Z){if(typeof J==="boolean")return J;if(!o6(Z))return!1;return t61({userEmail:Z.user.email,features:Z.features})}function $51(J){if(!o6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function _x3(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function UF0(J){let Y=_x3(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new T1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function Bn4(J){if(!Y5.write(J))await Mx3(Y5,"drain")}var Nn4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??yK,description:`Custom settings file path (overrides the default location ${yK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Cn0})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:a7(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:fG.SMART.key,description:`Set the agent mode (${uG().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:uG().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"threadActors",long:"thread-actors",type:"switch",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],wn4=(J)=>("deprecated"in J)&&J.deprecated===!0,Sx3=(J)=>("hidden"in J)&&J.hidden===!0,kx3=(J)=>("default"in J),vx3=(J)=>("default"in J)?J.default:void 0,Tn4=[{name:"toggle-skills-count",entryPoint:jo0}];function yx3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((z)=>Q.includes(z)||z.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new T1(E3.unknownCommand(Q),1,V)}}async function Q51(J){return{...J,getThreadEnvironment:uY,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new hV(J.fileSystem),generateThreadTitle:g80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>xX(J.configService),pluginService:J.pluginService}}function _n4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:uY,filesystem:J.fileSystem,threadService:J.threadService}}var HF0=V1.file(In4.homedir()),J51=process.env.XDG_CONFIG_HOME?V1.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(HF0,".config");function xx3(J){return qq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){Fq4(Z);let Q=AX0(),Y=ho0();if((!Q||Y||CT4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(wH("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(wH("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(AX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function fx3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function R7(J,Z,Q){let Y=Q?.deferAuth??!1;Qf1("0.0.1774880298-g3dd925");let X=O10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(V1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:HF0,userConfigDir:J51});PT4(X);let K=await X.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let a=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(a),P.info("API key lookup before login",{found:Boolean(a),ampURL:J.ampURL,deferAuth:Y}),!a)if(Y)P.info("No API key found, continuing startup with deferred auth");else{Y5.write(`No API key found. Starting login flow...
|
|
7605
7605
|
`);let W0=await ux3(J),r=await J.secrets.get("apiKey",J.ampURL);if(P.info("Login flow completed",{success:W0,storedKeyPresent:Boolean(r),ampURL:J.ampURL}),!W0)await VH(),process.exit(1);V=!0}}{let a=await X.getLatest(),W0=a.settings.url,r=a.secrets.isSet?.[W0];P.info("Config secrets state after login",{configURL:W0,apiKeySet:r?.apiKey??!1})}let z=j1(xX(X).pipe(T5((a)=>a!=="pending"))),G=Y?"pending":await z;if(!Y)P.info("Server status resolved",{status:"ready",isAuthenticated:o6(G),isError:bW(G),errorMessage:bW(G)?G.error.message:void 0});let{toolService:F,dispose:q}=Xq4({configService:X}),W=new Map,U=()=>W.clear(),H=new uT0(X,J.settings.getWorkspaceRootPath()),D=zt1({configService:X,filesystem:n8}),B=Qa1({configService:X,trustStore:H,skillMCPServers:D.skillMCPServers,createOAuthProvider:async(a,W0,r)=>{let H0=`${a}:${W0}`,L0=W.get(H0);if(L0)return P.debug("Reusing existing OAuth provider for server",{serverName:a,serverUrl:W0}),L0;P.debug("Creating OAuth provider for server",{serverName:a,serverUrl:W0});let z0=(async()=>{let J0=new HE(J.secrets),G0=await J0.getClientInfo(a,W0),i=r?.scopes??G0?.scopes,o=ZI4();P.info("OAuth headless mode check",{useHeadless:o,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:Y5.isTTY});let t;if(o)t=J.executeMode?JI4():$I4(a);let $0=new NR0({storage:J0,serverName:a,serverUrl:W0,clientId:r?.clientId??G0?.clientId,clientSecret:r?.clientSecret??G0?.clientSecret,authUrl:r?.authUrl??G0?.authUrl,tokenUrl:r?.tokenUrl??G0?.tokenUrl,scopes:i,headlessAuthHandler:t});return P.debug("OAuth provider created",{serverName:a,serverUrl:W0,hasManualClientId:!!(r?.clientId??G0?.clientId),willUseDCR:!(r?.clientId??G0?.clientId),scopes:i,headlessMode:o,executeMode:J.executeMode}),$0})();return W.set(H0,z0),z0}}),N=bg0({configService:X,filesystem:n8,spawn:P$0}),w;if(J.executeMode){let a=await Gz4({toolService:F,providers:[B,N],initialTimeout:15000});w=a.registrations;for(let[W0,r]of a.initErrors)P.warn(`${W0} provider initialization slow or failed:`,r)}else w=hg0({toolService:F,providers:[B,N]});if(Z.jetbrains)$E("JetBrains");else if(Z.ide&&gI4())$E("VS Code");else if(Z.ide&&mI4())$E("Neovim");else if(Z.ide){let a=await Px3();if(a){let W0=_10(a.ideName);if(W0)$E(W0)}}if(J.executeMode)Yf1(!0);let L,O=w$.status.pipe(D1((a)=>Boolean(a.connected&&a.authenticated&&a.ideName&&if1(a.ideName))),b4()).subscribe((a)=>{if(a){if(!L)L=F.registerTool(zz4)}else L?.dispose(),L=void 0}),E;if(!J.executeMode){let a=await J.settings.get("fuzzy.alwaysIncludePaths")??[];E=new WY0(process.cwd(),{alwaysIncludePaths:a},!0)}else E=new class extends WY0{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let M=await Dt1({isDevelopment:!1}),A=new hS0(M,X,{maxThreads:200});P.info("Starting Amp background services");let j=Z.takeMeBack?!1:void 0,R=e61(j,G),_=Boolean(R||Z.headless);if(_)P.info("DTW mode enabled: thread sync service disabled");let T=_?fx3():yt1({threadService:A,configService:X,isExtensionDevelopment:!1}),u;w$.status.subscribe((a)=>{u=a});let m=new iA0({workspaceRoots:[V1.file(process.cwd())],fileSystem:n8,getCurrentFile:()=>{if(!u?.openFile)return;try{return V1.parse(u.openFile)}catch(a){P.warn("Failed to parse current file URI",{uri:u.openFile,error:a});return}},getOpenFiles:()=>{if(!u?.visibleFiles?.length)return[];let a=u.openFile;return u.visibleFiles.filter((W0)=>W0!==a).map((W0)=>{try{return V1.parse(W0)}catch(r){return P.warn("Failed to parse visible file URI",{uri:W0,error:r}),null}}).filter((W0)=>W0!==null)}}),y=new po0,k=process.env.PLUGINS??"off",f=Z.headless?qT4():void 0,d=f??new NX0({configService:X}),p=d instanceof NX0?d:void 0;if(p)p.pluginExecutorKind=R?"local":"unknown";let h=eT0({configService:X,fileSystem:n8,platform:d,internalPlugins:Tn4,pluginFilter:k}),n=sa1({pluginService:h,toolService:F}),c={codebaseContextService:m,configService:X,toolService:F,mcpService:B,skillService:D,toolboxService:N,trustStore:H,threadService:A,threadSyncService:T,threadStorage:M,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,fileSystem:n8,terminal:y,pluginService:h,pluginPlatform:p,headlessPluginPlatform:f,serverStatus:G,serverStatusPromise:z,hasAPIKeyAtStartup:V};return{...c,async asyncDispose(){if(c.mcpService.hasAuthenticatingClients())P.info("Waiting for OAuth authentication to complete before exit..."),await c.mcpService.waitForAuthentication();for(let a of w.values())a.dispose();await c.mcpService.dispose(),U(),await c.threadService.asyncDispose(),c.configService.unsubscribe(),q(),c.fuzzyServer.dispose(),c.threadSyncService.dispose(),c.settingsStorage[Symbol.dispose](),O.unsubscribe(),L?.dispose(),n.dispose(),await c.pluginService.dispose()}}}async function ux3(J){if(!J.executeMode){if(!await HX0("Would you like to log in to Amp? [(y)es, (n)o]: "))return Y5.write(`Login cancelled. Run the command again to retry.
|
|
7606
7606
|
`),!1}return await Sn4(J)}async function Sn4(J){let Z=An4(32).toString("hex"),Q=await qv(J.ampURL,Z),Y=new AbortController;try{await EV(Q,Y.signal)}catch(K){P.error("Error opening browser",{error:K})}let X=await qv(J.ampURL,Z,!1);Y5.write(`If your browser does not open automatically, visit:
|
|
7607
7607
|
|
|
@@ -7609,7 +7609,7 @@ ${o0.blue.bold(X)}
|
|
|
7609
7609
|
|
|
7610
7610
|
`);try{return await cC4(J.ampURL,Z,J.secrets,Y),Y5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return P.error("Login failed",{error:K}),j2.write(`
|
|
7611
7611
|
Login failed: ${K instanceof Error?K.message:String(K)}
|
|
7612
|
-
`),!1}}function Ln4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function bx3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new T1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!b9(Y.threadId))throw new T1("Create response did not include a valid thread ID",1);return Y.threadId}function hx3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function gx3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new T1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!hx3(Q))throw new T1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function mx3(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(J)}async function px3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new T1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function dx3(J){let Z=new fN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Z.exitOverride((B)=>{if(B.code==="commander.help"||B.code==="commander.version"||B.exitCode===0)Uj(),process.exit(0);let N=B.originalError??B;QR4(N)}),id4(Z,{version:"0.0.
|
|
7612
|
+
`),!1}}function Ln4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function bx3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new T1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!b9(Y.threadId))throw new T1("Create response did not include a valid thread ID",1);return Y.threadId}function hx3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function gx3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new T1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!hx3(Q))throw new T1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function mx3(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(J)}async function px3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new T1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function dx3(J){let Z=new fN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Z.exitOverride((B)=>{if(B.code==="commander.help"||B.code==="commander.version"||B.exitCode===0)Uj(),process.exit(0);let N=B.originalError??B;QR4(N)}),id4(Z,{version:"0.0.1774880298-g3dd925",buildTimestamp:"2026-03-30T14:22:23.248Z",buildType:"'release'"}),Z.addHelpText("after",uI4()),Z.configureHelp({formatHelp:bI4}),Z.command("logout").description("Log out by removing stored API key").action(async(B,N)=>{let w=N.optsWithGlobals(),L=await r3(w);await sx3(L)}),Z.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(B,N)=>{let w=N.optsWithGlobals(),L=await r3(w);await rx3(L,await Ma0(w,L.settings))}),Z.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(B,N,w)=>{let L=w.optsWithGlobals(),O=await r3(L);await SR4(B??"get",O.ampURL,O.secrets),process.exit(process.exitCode??0)}),Z.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(B,N)=>{let w=N.optsWithGlobals(),L=await r3(w);await kR4(L.ampURL,L.secrets),process.exit(process.exitCode??0)}),Z.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
|
|
7613
7613
|
Actions:
|
|
7614
7614
|
create Create a new DTW thread and print its ID
|
|
7615
7615
|
add-message <message> Send a user message and wait for message_added
|
|
@@ -7673,8 +7673,8 @@ ${M}
|
|
|
7673
7673
|
|
|
7674
7674
|
This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}async function cx3(J){P.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new rn({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,clientID:J.clientID,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized]).then(()=>{return}),toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:uY,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new hV(J.fileSystem),ampURL:J.ampURL,useThreadActors:J.useThreadActors});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw P.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function lx3(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await Bv()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await Bv()).trimEnd(),stdinInput:null}}function ix3(J,Z,Q){if(J.remote&&!Z)throw new T1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new T1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new T1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new T1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new T1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new T1("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(J.streamJsonInput&&typeof J.execute==="string"&&J.execute.trim()!=="")throw new T1("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new T1("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
|
|
7675
7675
|
Or pipe via stdin: echo "your message" | amp --execute`)}async function DF0(J,Z,Q,Y){let X=process.hrtime.bigint(),K=(z0,J0)=>{let G0=Number(process.hrtime.bigint()-J0)/1e6,i=XO4();P.info("Startup phase",{phase:z0,phaseMs:Math.round(G0),sinceMainMs:i===null?void 0:Math.round(i)})},{userInput:V,stdinInput:z}=await lx3(Z),G=!!Z.streamJson||!!Z.streamJsonThinking;ix3({...Z,streamJson:G},J.executeMode,V),A2(Q,Z);let F=process.hrtime.bigint(),q=Boolean(await J.secrets.get("apiKey",J.ampURL)),W=!J.executeMode&&!Z.headless&&!Z.threadActors&&q;P.info("Interactive auth startup mode",{deferInteractiveAuth:W,hasAPIKeyAtStartup:q,executeMode:J.executeMode,headless:Boolean(Z.headless)});let U=await R7(J,Z,{deferAuth:W});K("runMainThread:createThreadDependencies",F),F=process.hrtime.bigint();let H=await Q51(U);K("runMainThread:createWorkerDeps",F);let{serverStatus:D}=U;if(!W&&bW(D)){let z0=ak(Error(D.error.message));if(z0.message===E3.networkOffline||z0.message===E3.networkTimeout)throw UF0(J.ampURL);throw new T1(E3.invalidAPIKey,1)}let B=o6(D)?D:null,N=B?.user.email,w=Cn4(N),L=t61({userEmail:N,features:B?.features}),O=Z.takeMeBack?!1:void 0,E=B!==null&&e61(O,B);if(!W)await s61(Q,Z,D);let M=$51(D),A=M?.features??[],j=M?.team??null,R=DX0(Z,M);if(R instanceof Error)s3(R.message);if((J.executeMode||G)&&N8(Z.mode)&&!w)throw new T1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(B&&!ZE(Z.mode,N))throw new T1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await HT4(V,z,U.configService),await U.asyncDispose(),process.exit(0);if(Z.headless){if(!N||!dJ(N))throw new T1("Headless DTW mode is only available for Amp employees",1);let z0=await U.secretStorage.get("apiKey",J.ampURL);if(!z0)throw new T1("API key required for headless mode. Please run `amp login` first.",1);let J0=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if(J0&&!b9(J0))throw new T1(`Invalid thread ID: ${J0}`,1);let G0=J0?void 0:await Xf3({dependencies:U,visibility:R??void 0,usesThreadActors:Z.threadActors?!0:void 0}),i=J0??G0?.threadId;if(!i)throw new T1("Failed to resolve headless thread ID",1);let o=await KI4(i);if(o.status==="already-running")await U.asyncDispose(),await VH(),process.exit(0);try{await eR4({ampURL:J.ampURL,apiKey:z0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:i,ownerUserId:G0?.ownerUserId,threadVersion:G0?.threadVersion,agentMode:G0?.agentMode,initialToolDiscovery:Promise.all([U.mcpService.initialized,U.toolboxService.initialized]).then(()=>{return}),configService:U.configService,mcpService:U.mcpService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,pluginService:U.pluginService,pluginPlatform:U.headlessPluginPlatform,useThreadActors:Z.threadActors?!0:void 0})}finally{await o.release(),await U.asyncDispose()}await VH(),process.exit(0)}let _=J.executeMode?void 0:async(z0)=>Lo(z0,"interactive"),T={threadService:U.threadService,workerDeps:H,createThread:async()=>{let z0=W?await U.serverStatusPromise:D,J0=await sQ0(J.settings,process.cwd(),$51(z0),R);if(J0 instanceof Error)s3(J0.message);return Ze0(H,{threadMeta:J0?yz(J0):void 0,agentMode:Z.mode,onFirstAssistantMessage:_})},validateThreadOwnership:async(z0,J0)=>{if(J0?.nonBlockingOwnershipCheck){On4(z0,U.configService).catch((G0)=>{if(G0 instanceof T1){if(J0.onOwnershipError){J0.onOwnershipError(G0,z0);return}zH(G0,z0);return}P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:G0})});return}try{await On4(z0,U.configService)}catch(G0){if(G0 instanceof T1)throw G0;P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:G0})}},switchThreadVisibility:R,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:_,handleError:zH},u=async(z0)=>{try{if(z0==="dtw")return cx3({ampURL:J.ampURL,configService:U.configService,threadService:U.threadService,mcpService:U.mcpService,clientID:Hn4,toolboxService:U.toolboxService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,threadId:Z.threadId,useThreadActors:Z.threadActors?!0:void 0});return Ef4(T,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(J0){if(J0 instanceof T1)throw J0;throw await zH(J0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")j2.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
7676
|
-
`),await VH(),process.exit(1);let m=(async()=>{if(W){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await U.configService.getLatest(),J0=ou(z0),G0=await g6.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(J0)});if(G0.ok)return P.info("User free tier status:",G0),G0.result;return}catch(z0){P.error("Failed to fetch free tier status:",z0);return}})(),k=!J.executeMode?new st0:null,f,d=null;if(k)f=k,d=(async()=>{let z0=W?await U.serverStatusPromise:U.serverStatus;await s61(Q,Z,z0);let J0=process.hrtime.bigint(),G0=e61(O,z0),i=o6(z0)?t61({userEmail:z0.user.email,features:z0.features}):!1;Dn4({dtwEnabled:G0,hasV2TUIAccess:i});let o=await u(G0?"dtw":"worker");if(K("runMainThread:createThreadPool",J0),k.attach(o),V){let t=await j1(o.threadHandles$);if(!t)throw new T1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(z0)=>{let J0=z0 instanceof Error?z0:Error(String(z0));k.setInitError(J0),await zH(z0,Z.threadId)});else F=process.hrtime.bigint(),Dn4({dtwEnabled:E,hasV2TUIAccess:L}),f=await u(E?"dtw":"worker"),K("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let h=await U.configService.getLatest();if(K("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),xx3({configService:U.configService,threadService:U.threadService,config:h,useNotificationsForService:p,threadViewStates$:()=>f.threadHandles$.pipe(H4((z0)=>{if(!z0)return k0.of({});return D5(z0.thread$,z0.threadViewState$).pipe(D1(([J0,G0])=>({[J0.id]:G0})))}))}),K("runMainThread:createCliNotificationService",F),J.executeMode){ZT4(U.mcpService,J.settings);let z0={userInput:V,stdinInput:z,dependencies:U,streamJson:G,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},J0=await HR4({threadPool:f,...z0});if(await Lo(J0,"execute"),Z.archive)await g6.archiveThread({thread:J0,archived:!0},{config:U.configService});await U.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Z.jetbrains||Z.ide){await tf1();let z0=await VE({jetbrainsOnly:Z.jetbrains});if(z0.length===0){if(Z.jetbrains)n=!await U.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let J0=z0[0];if(J0)w$.selectConfig(J0)}else c=!0}F=process.hrtime.bigint();let a=pa0("0.0.
|
|
7677
|
-
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await za1({get:async(z)=>{if(z!==rh)return;try{let G=await Rn4(r61,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==rh)return;await jn4(lH.dirname(r61),{recursive:!0}),await Ax3(r61,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:yG()});Xf1(Y);let X=await LI4({...J,workspaceTrust:{current:!0,changes:su},getHook:process.env.AMP_URL?(z,G)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let z=await $T4(J.mcpConfig);X=JT4(X,z)}let K=lH.dirname(X.getSettingsFilePath());Gq4(Qv,K);let V=await X.get("url","global");if(!V)V=G7;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!OV(V))P.info("Targeting custom Amp server",{ampURL:V});return X=ox1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:LT4(await Ma0(J,X))}}function nx3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function ax3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=lH.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Ix3:Cn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function ox3(){YO4();let J=nx3(process.argv),Z=ax3(process.argv,J),Q=Hj4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)o0.level=0;if(Cx3(P),P.info("Starting Amp CLI.",{version:"0.0.
|
|
7676
|
+
`),await VH(),process.exit(1);let m=(async()=>{if(W){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await U.configService.getLatest(),J0=ou(z0),G0=await g6.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(J0)});if(G0.ok)return P.info("User free tier status:",G0),G0.result;return}catch(z0){P.error("Failed to fetch free tier status:",z0);return}})(),k=!J.executeMode?new st0:null,f,d=null;if(k)f=k,d=(async()=>{let z0=W?await U.serverStatusPromise:U.serverStatus;await s61(Q,Z,z0);let J0=process.hrtime.bigint(),G0=e61(O,z0),i=o6(z0)?t61({userEmail:z0.user.email,features:z0.features}):!1;Dn4({dtwEnabled:G0,hasV2TUIAccess:i});let o=await u(G0?"dtw":"worker");if(K("runMainThread:createThreadPool",J0),k.attach(o),V){let t=await j1(o.threadHandles$);if(!t)throw new T1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(z0)=>{let J0=z0 instanceof Error?z0:Error(String(z0));k.setInitError(J0),await zH(z0,Z.threadId)});else F=process.hrtime.bigint(),Dn4({dtwEnabled:E,hasV2TUIAccess:L}),f=await u(E?"dtw":"worker"),K("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let h=await U.configService.getLatest();if(K("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),xx3({configService:U.configService,threadService:U.threadService,config:h,useNotificationsForService:p,threadViewStates$:()=>f.threadHandles$.pipe(H4((z0)=>{if(!z0)return k0.of({});return D5(z0.thread$,z0.threadViewState$).pipe(D1(([J0,G0])=>({[J0.id]:G0})))}))}),K("runMainThread:createCliNotificationService",F),J.executeMode){ZT4(U.mcpService,J.settings);let z0={userInput:V,stdinInput:z,dependencies:U,streamJson:G,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},J0=await HR4({threadPool:f,...z0});if(await Lo(J0,"execute"),Z.archive)await g6.archiveThread({thread:J0,archived:!0},{config:U.configService});await U.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Z.jetbrains||Z.ide){await tf1();let z0=await VE({jetbrainsOnly:Z.jetbrains});if(z0.length===0){if(Z.jetbrains)n=!await U.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let J0=z0[0];if(J0)w$.selectConfig(J0)}else c=!0}F=process.hrtime.bigint();let a=pa0("0.0.1774880298-g3dd925",U.settingsStorage,{startDelayMs:3000});K("runMainThread:createUpdateService",F),F=process.hrtime.bigint();let W0=new Ao0(U.mcpService,J.settings.getWorkspaceRootPath());if(K("runMainThread:createMcpTrustHandler",F),V&&J.executeMode){let z0=await j1(f.threadHandles$);if(!z0)throw new T1("No active thread is available yet.",1);await z0.sendMessage({content:[{type:"text",text:V}]})}F=process.hrtime.bigint();let r=await LX0();K("runMainThread:loadSessionState",F),P.info("Loaded session state:",r);let H0={...r,launchCount:r.launchCount+1};Ij((z0)=>({...z0,launchCount:z0.launchCount+1}));let L0=Z.threadId&&b9(Z.threadId)?Z.threadId:void 0;try{if(F=process.hrtime.bigint(),await Fu4({codebaseContextService:U.codebaseContextService,history:new Ya0,fuzzyServer:U.fuzzyServer,settingsStorage:U.settingsStorage,threadService:U.threadService,skillService:U.skillService,configService:U.configService,secretStorage:U.secretStorage,internalAPIClient:g6,threadPool:f,createSystemPromptDeps:async()=>_n4(U),ideClient:w$,mcpService:U.mcpService,toolboxService:U.toolboxService,mcpTrustHandler:W0,updateService:a,pluginPlatform:U.pluginPlatform,pluginService:U.pluginService},{initialServerStatus:U.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:U.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:L0,showJetBrainsInstaller:n,showIdePickerHint:c,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Hn4,logFile:{path:Y},sessionState:H0,freeTierStatusPromise:m,workspace:j??null,features:A,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-30T14:22:23.248Z"},(z0)=>new De0({...z0,threadPool:z0.threadPool},(J0)=>new M41({...J0,threadState:J0.threadState}))),K("runMainThread:mountApp-returned",F),d)await d}finally{}await U.asyncDispose(),K("runMainThread:dependencies.asyncDispose",X),process.exit(0)}async function r3(J){if(P.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)j2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
7677
|
+
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await za1({get:async(z)=>{if(z!==rh)return;try{let G=await Rn4(r61,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==rh)return;await jn4(lH.dirname(r61),{recursive:!0}),await Ax3(r61,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:yG()});Xf1(Y);let X=await LI4({...J,workspaceTrust:{current:!0,changes:su},getHook:process.env.AMP_URL?(z,G)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let z=await $T4(J.mcpConfig);X=JT4(X,z)}let K=lH.dirname(X.getSettingsFilePath());Gq4(Qv,K);let V=await X.get("url","global");if(!V)V=G7;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!OV(V))P.info("Targeting custom Amp server",{ampURL:V});return X=ox1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:LT4(await Ma0(J,X))}}function nx3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function ax3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=lH.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Ix3:Cn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function ox3(){YO4();let J=nx3(process.argv),Z=ax3(process.argv,J),Q=Hj4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)o0.level=0;if(Cx3(P),P.info("Starting Amp CLI.",{version:"0.0.1774880298-g3dd925",buildTimestamp:"2026-03-30T14:22:23.248Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new T1(E3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await dx3(Q).parseAsync(process.argv)}Vq4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await ox3().catch(zH)});async function rx3(J,Z){let Q=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Q)await J.settings.set("url",process.env.AMP_URL,"global"),Y5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
7678
7678
|
`);else if(!OV(J.ampURL))Y5.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
7679
7679
|
`);let Y=process.env.AMP_API_KEY;if(Y)Y5.write(`API key found in environment variable, storing...
|
|
7680
7680
|
`),await Z.set("apiKey",Y,J.ampURL),Y5.write(`API key successfully stored.
|