@meirblachman/azure-pipelines-visualizer 0.1.3 → 0.1.5

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/index.min.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{existsSync as Tt,readFileSync as Pt}from"node:fs";import{extname as Na,join as Fr}from"node:path";import{fileURLToPath as La}from"node:url";import{createServer as _t}from"http";import{Http2ServerRequest as $r,constants as Ft}from"http2";import{Http2ServerRequest as Ze}from"http2";import{Readable as Lr}from"stream";import qt from"crypto";var L=class extends Error{constructor(e,r){super(e,r),this.name="RequestError"}},jt=e=>e instanceof L?e:new L(e.message,{cause:e}),Nt=global.Request,fe=class extends Nt{constructor(e,r){typeof e=="object"&&K in e&&(e=e[K]()),typeof r?.body?.getReader<"u"&&(r.duplex??="half"),super(e,r)}},Lt=e=>{let r=[],n=e.rawHeaders;for(let t=0;t<n.length;t+=2){let{[t]:i,[t+1]:o}=n;i.charCodeAt(0)!==58&&r.push([i,o])}return new Headers(r)},Mr=Symbol("wrapBodyStream"),Dt=(e,r,n,t,i)=>{let o={method:e,headers:n,signal:i.signal};if(e==="TRACE"){o.method="GET";let s=new fe(r,o);return Object.defineProperty(s,"method",{get(){return"TRACE"}}),s}if(!(e==="GET"||e==="HEAD"))if("rawBody"in t&&t.rawBody instanceof Buffer)o.body=new ReadableStream({start(s){s.enqueue(t.rawBody),s.close()}});else if(t[Mr]){let s;o.body=new ReadableStream({async pull(a){try{s||=Lr.toWeb(t).getReader();let{done:l,value:c}=await s.read();l?a.close():a.enqueue(c)}catch(l){a.error(l)}}})}else o.body=Lr.toWeb(t);return new fe(r,o)},K=Symbol("getRequestCache"),Hr=Symbol("requestCache"),ke=Symbol("incomingKey"),Se=Symbol("urlKey"),$t=Symbol("headersKey"),G=Symbol("abortControllerKey"),Mt=Symbol("getAbortController"),pe={get method(){return this[ke].method||"GET"},get url(){return this[Se]},get headers(){return this[$t]||=Lt(this[ke])},[Mt](){return this[K](),this[G]},[K](){return this[G]||=new AbortController,this[Hr]||=Dt(this.method,this[Se],this.headers,this[ke],this[G])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty(pe,e,{get(){return this[K]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(pe,e,{value:function(){return this[K]()[e]()}})});Object.defineProperty(pe,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,r,n){let t={method:this.method,url:this.url,headers:this.headers,nativeRequest:this[Hr]};return`Request (lightweight) ${n(t,{...r,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(pe,fe.prototype);var Ht=(e,r)=>{let n=Object.create(pe);n[ke]=e;let t=e.url||"";if(t[0]!=="/"&&(t.startsWith("http://")||t.startsWith("https://"))){if(e instanceof Ze)throw new L("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(t);n[Se]=a.href}catch(a){throw new L("Invalid absolute URL",{cause:a})}return n}let i=(e instanceof Ze?e.authority:e.headers.host)||r;if(!i)throw new L("Missing host header");let o;if(e instanceof Ze){if(o=e.scheme,!(o==="http"||o==="https"))throw new L("Unsupported scheme")}else o=e.socket&&e.socket.encrypted?"https":"http";let s=new URL(`${o}://${i}${t}`);if(s.hostname.length!==i.length&&s.hostname!==i.replace(/:\d+$/,""))throw new L("Invalid host header");return n[Se]=s.href,n},Qe=Symbol("responseCache"),W=Symbol("getResponseCache"),D=Symbol("cache"),rr=global.Response,Y=class zr{#r;#e;[W](){return delete this[D],this[Qe]||=new rr(this.#r,this.#e)}constructor(r,n){let t;if(this.#r=r,n instanceof zr){let i=n[Qe];if(i){this.#e=i,this[W]();return}else this.#e=n.#e,t=new Headers(n.#e.headers)}else this.#e=n;(typeof r=="string"||typeof r?.getReader<"u"||r instanceof Blob||r instanceof Uint8Array)&&(this[D]=[n?.status||200,r,t||n?.headers])}get headers(){let r=this[D];return r?(r[2]instanceof Headers||(r[2]=new Headers(r[2]||{"content-type":"text/plain; charset=UTF-8"})),r[2]):this[W]().headers}get status(){return this[D]?.[0]??this[W]().status}get ok(){let r=this.status;return r>=200&&r<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(Y.prototype,e,{get(){return this[W]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(Y.prototype,e,{value:function(){return this[W]()[e]()}})});Object.defineProperty(Y.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,r,n){let t={status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[Qe]};return`Response (lightweight) ${n(t,{...r,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(Y,rr);Object.setPrototypeOf(Y.prototype,rr.prototype);async function zt(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function Br(e,r,n){let t=a=>{e.cancel(a).catch(()=>{})};return r.on("close",t),r.on("error",t),(n??e.read()).then(s,i),e.closed.finally(()=>{r.off("close",t),r.off("error",t)});function i(a){a&&r.destroy(a)}function o(){e.read().then(s,i)}function s({done:a,value:l}){try{if(a)r.end();else if(!r.write(l))r.once("drain",o);else return e.read().then(s,i)}catch(c){i(c)}}}function Bt(e,r){if(e.locked)throw new TypeError("ReadableStream is locked.");return r.destroyed?void 0:Br(e.getReader(),r)}var Xe=e=>{let r={};e instanceof Headers||(e=new Headers(e??void 0));let n=[];for(let[t,i]of e)t==="set-cookie"?n.push(i):r[t]=i;return n.length>0&&(r["set-cookie"]=n),r["content-type"]??="text/plain; charset=UTF-8",r},Ut="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=qt);var nr=Symbol("outgoingEnded"),Dr=Symbol("incomingDraining"),Wt=500,Gt=64*1024*1024,Je=e=>{let r=e;if(e.destroyed||r[Dr])return;if(r[Dr]=!0,e instanceof $r){try{e.stream?.close?.(Ft.NGHTTP2_NO_ERROR)}catch{}return}let n=0,t=()=>{clearTimeout(o),e.off("data",s),e.off("end",t),e.off("error",t)},i=()=>{t();let a=e.socket;a&&!a.destroyed&&a.destroySoon()},o=setTimeout(i,Wt);o.unref?.();let s=a=>{n+=a.length,n>Gt&&i()};e.on("data",s),e.on("end",t),e.on("error",t),e.resume()},Kt=()=>new Response(null,{status:400}),Ur=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),er=(e,r)=>{let n=e instanceof Error?e:new Error("unknown error",{cause:e});n.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(e),r.headersSent||r.writeHead(500,{"Content-Type":"text/plain"}),r.end(`Error: ${n.message}`),r.destroy(n))},qr=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},Wr=async(e,r)=>{let[n,t,i]=e[D],o=!1;if(!i)i={"content-type":"text/plain; charset=UTF-8"};else if(i instanceof Headers)o=i.has("content-length"),i=Xe(i);else if(Array.isArray(i)){let s=new Headers(i);o=s.has("content-length"),i=Xe(s)}else for(let s in i)if(s.length===14&&s.toLowerCase()==="content-length"){o=!0;break}o||(typeof t=="string"?i["Content-Length"]=Buffer.byteLength(t):t instanceof Uint8Array?i["Content-Length"]=t.byteLength:t instanceof Blob&&(i["Content-Length"]=t.size)),r.writeHead(n,i),typeof t=="string"||t instanceof Uint8Array?r.end(t):t instanceof Blob?r.end(new Uint8Array(await t.arrayBuffer())):(qr(r),await Bt(t,r)?.catch(s=>er(s,r))),r[nr]?.()},Yt=e=>typeof e.then=="function",Vt=async(e,r,n={})=>{if(Yt(e))if(n.errorHandler)try{e=await e}catch(i){let o=await n.errorHandler(i);if(!o)return;e=o}else e=await e.catch(Ur);if(D in e)return Wr(e,r);let t=Xe(e.headers);if(e.body){let i=e.body.getReader(),o=[],s=!1,a;if(t["transfer-encoding"]!=="chunked"){let l=2;for(let c=0;c<l;c++){a||=i.read();let f=await zt(a).catch(u=>{console.error(u),s=!0});if(!f){if(c===1){await new Promise(u=>setTimeout(u)),l=3;continue}break}if(a=void 0,f.value&&o.push(f.value),f.done){s=!0;break}}s&&!("content-length"in t)&&(t["content-length"]=o.reduce((c,f)=>c+f.length,0))}r.writeHead(e.status,t),o.forEach(l=>{r.write(l)}),s?r.end():(o.length===0&&qr(r),await Br(i,r,a))}else t[Ut]||(r.writeHead(e.status,t),r.end());r[nr]?.()},Zt=(e,r={})=>{let n=r.autoCleanupIncoming??!0;return r.overrideGlobalObjects!==!1&&global.Request!==fe&&(Object.defineProperty(global,"Request",{value:fe}),Object.defineProperty(global,"Response",{value:Y})),async(t,i)=>{let o,s;try{s=Ht(t,r.hostname);let a=!n||t.method==="GET"||t.method==="HEAD";if(a||(t[Mr]=!0,t.on("end",()=>{a=!0}),t instanceof $r&&(i[nr]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{Je(t)})})}),i.on("finish",()=>{a||Je(t)})),i.on("close",()=>{s[G]&&(t.errored?s[G].abort(t.errored.toString()):i.writableFinished||s[G].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{Je(t)})})}),o=e(s,{incoming:t,outgoing:i}),D in o)return Wr(o,i)}catch(a){if(o)return er(a,i);if(r.errorHandler){if(o=await r.errorHandler(s?a:jt(a)),!o)return}else s?o=Ur(a):o=Kt()}try{return await Vt(o,i,r)}catch(a){return er(a,i)}}},Jt=e=>{let r=e.fetch,n=Zt(r,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||_t)(e.serverOptions||{},n)},Gr=(e,r)=>{let n=Jt(e);return n.listen(e?.port??3e3,e.hostname,()=>{let t=n.address();r&&r(t)}),n};var tr=(e,r,n)=>(t,i)=>{let o=-1;return s(0);async function s(a){if(a<=o)throw new Error("next() called multiple times");o=a;let l,c=!1,f;if(e[a]?(f=e[a][0][0],t.req.routeIndex=a):f=a===e.length&&i||void 0,f)try{l=await f(t,()=>s(a+1))}catch(u){if(u instanceof Error&&r)t.error=u,l=await r(u,t),c=!0;else throw u}else t.finalized===!1&&n&&(l=await n(t));return l&&(t.finalized===!1||c)&&(t.res=l),t}};var Kr=Symbol();var Yr=async(e,r=Object.create(null))=>{let{all:n=!1,dot:t=!1}=r,o=(e instanceof Te?e.raw.headers:e.headers).get("Content-Type");return o?.startsWith("multipart/form-data")||o?.startsWith("application/x-www-form-urlencoded")?Qt(e,{all:n,dot:t}):{}};async function Qt(e,r){let n=await e.formData();return n?Xt(n,r):{}}function Xt(e,r){let n=Object.create(null);return e.forEach((t,i)=>{r.all||i.endsWith("[]")?ei(n,i,t):n[i]=t}),r.dot&&Object.entries(n).forEach(([t,i])=>{t.includes(".")&&(ri(n,t,i),delete n[t])}),n}var ei=(e,r,n)=>{e[r]!==void 0?Array.isArray(e[r])?e[r].push(n):e[r]=[e[r],n]:r.endsWith("[]")?e[r]=[n]:e[r]=n},ri=(e,r,n)=>{if(/(?:^|\.)__proto__\./.test(r))return;let t=e,i=r.split(".");i.forEach((o,s)=>{s===i.length-1?t[o]=n:((!t[o]||typeof t[o]!="object"||Array.isArray(t[o])||t[o]instanceof File)&&(t[o]=Object.create(null)),t=t[o])})};var or=e=>{let r=e.split("/");return r[0]===""&&r.shift(),r},Vr=e=>{let{groups:r,path:n}=ni(e),t=or(n);return ti(t,r)},ni=e=>{let r=[];return e=e.replace(/\{[^}]+\}/g,(n,t)=>{let i=`@${t}`;return r.push([i,n]),i}),{groups:r,path:e}},ti=(e,r)=>{for(let n=r.length-1;n>=0;n--){let[t]=r[n];for(let i=e.length-1;i>=0;i--)if(e[i].includes(t)){e[i]=e[i].replace(t,r[n][1]);break}}return e},Pe={},Zr=(e,r)=>{if(e==="*")return"*";let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let t=`${e}#${r}`;return Pe[t]||(n[2]?Pe[t]=r&&r[0]!==":"&&r[0]!=="*"?[t,n[1],new RegExp(`^${n[2]}(?=/${r})`)]:[e,n[1],new RegExp(`^${n[2]}$`)]:Pe[t]=[e,n[1],!0]),Pe[t]}return null},Oe=(e,r)=>{try{return r(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return r(n)}catch{return n}})}},ii=e=>Oe(e,decodeURI),sr=e=>{let r=e.url,n=r.indexOf("/",r.indexOf(":")+4),t=n;for(;t<r.length;t++){let i=r.charCodeAt(t);if(i===37){let o=r.indexOf("?",t),s=r.indexOf("#",t),a=o===-1?s===-1?void 0:s:s===-1?o:Math.min(o,s),l=r.slice(n,a);return ii(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(i===63||i===35)break}return r.slice(n,t)};var Jr=e=>{let r=sr(e);return r.length>1&&r.at(-1)==="/"?r.slice(0,-1):r},$=(e,r,...n)=>(n.length&&(r=$(r,...n)),`${e?.[0]==="/"?"":"/"}${e}${r==="/"?"":`${e?.at(-1)==="/"?"":"/"}${r?.[0]==="/"?r.slice(1):r}`}`),Ie=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let r=e.split("/"),n=[],t="";return r.forEach(i=>{if(i!==""&&!/\:/.test(i))t+="/"+i;else if(/\:/.test(i))if(/\?/.test(i)){n.length===0&&t===""?n.push("/"):n.push(t);let o=i.replace("?","");t+="/"+o,n.push(t)}else t+="/"+i}),n.filter((i,o,s)=>s.indexOf(i)===o)},ir=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?Oe(e,ar):e):e,Qr=(e,r,n)=>{let t;if(!n&&r&&!/[%+]/.test(r)){let s=e.indexOf("?",8);if(s===-1)return;for(e.startsWith(r,s+1)||(s=e.indexOf(`&${r}`,s+1));s!==-1;){let a=e.charCodeAt(s+r.length+1);if(a===61){let l=s+r.length+2,c=e.indexOf("&",l);return ir(e.slice(l,c===-1?void 0:c))}else if(a==38||isNaN(a))return"";s=e.indexOf(`&${r}`,s+1)}if(t=/[%+]/.test(e),!t)return}let i={};t??=/[%+]/.test(e);let o=e.indexOf("?",8);for(;o!==-1;){let s=e.indexOf("&",o+1),a=e.indexOf("=",o);a>s&&s!==-1&&(a=-1);let l=e.slice(o+1,a===-1?s===-1?void 0:s:a);if(t&&(l=ir(l)),o=s,l==="")continue;let c;a===-1?c="":(c=e.slice(a+1,s===-1?void 0:s),t&&(c=ir(c))),n?(i[l]&&Array.isArray(i[l])||(i[l]=[]),i[l].push(c)):i[l]??=c}return r?i[r]:i},Xr=Qr,en=(e,r)=>Qr(e,r,!0),ar=decodeURIComponent;var rn=e=>Oe(e,ar),Te=class{raw;#r;#e;routeIndex=0;path;bodyCache={};constructor(e,r="/",n=[[]]){this.raw=e,this.path=r,this.#e=n,this.#r={}}param(e){return e?this.#n(e):this.#o()}#n(e){let r=this.#e[0][this.routeIndex][1][e],n=this.#i(r);return n&&/\%/.test(n)?rn(n):n}#o(){let e={},r=Object.keys(this.#e[0][this.routeIndex][1]);for(let n of r){let t=this.#i(this.#e[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?rn(t):t)}return e}#i(e){return this.#e[1]?this.#e[1][e]:e}query(e){return Xr(this.url,e)}queries(e){return en(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let r={};return this.raw.headers.forEach((n,t)=>{r[t]=n}),r}async parseBody(e){return Yr(this,e)}#t=e=>{let{bodyCache:r,raw:n}=this,t=r[e];if(t)return t;let i=Object.keys(r)[0];return i?r[i].then(o=>(i==="json"&&(o=JSON.stringify(o)),new Response(o)[e]())):r[e]=n[e]()};json(){return this.#t("text").then(e=>JSON.parse(e))}text(){return this.#t("text")}arrayBuffer(){return this.#t("arrayBuffer")}blob(){return this.#t("blob")}formData(){return this.#t("formData")}addValidatedData(e,r){this.#r[e]=r}valid(e){return this.#r[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Kr](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};var nn={Stringify:1,BeforeStream:2,Stream:3},oi=(e,r)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=r,n};var lr=async(e,r,n,t,i)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let o=e.callbacks;if(!o?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let s=Promise.all(o.map(a=>a({phase:r,buffer:i,context:t}))).then(a=>Promise.all(a.filter(Boolean).map(l=>lr(l,r,!1,t,i))).then(()=>i[0]));return n?oi(await s,o):s};var si="text/plain; charset=UTF-8",cr=(e,r)=>({"Content-Type":e,...r}),de=(e,r)=>new Response(e,r),tn=class{#r;#e;env={};#n;finalized=!1;error;#o;#i;#t;#u;#l;#c;#a;#f;#p;constructor(e,r){this.#r=e,r&&(this.#i=r.executionCtx,this.env=r.env,this.#c=r.notFoundHandler,this.#p=r.path,this.#f=r.matchResult)}get req(){return this.#e??=new Te(this.#r,this.#p,this.#f),this.#e}get event(){if(this.#i&&"respondWith"in this.#i)return this.#i;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#i)return this.#i;throw Error("This context has no ExecutionContext")}get res(){return this.#t||=de(null,{headers:this.#a??=new Headers})}set res(e){if(this.#t&&e){e=de(e.body,e);for(let[r,n]of this.#t.headers.entries())if(r!=="content-type")if(r==="set-cookie"){let t=this.#t.headers.getSetCookie();e.headers.delete("set-cookie");for(let i of t)e.headers.append("set-cookie",i)}else e.headers.set(r,n)}this.#t=e,this.finalized=!0}render=(...e)=>(this.#l??=r=>this.html(r),this.#l(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#l=e};header=(e,r,n)=>{this.finalized&&(this.#t=de(this.#t.body,this.#t));let t=this.#t?this.#t.headers:this.#a??=new Headers;r===void 0?t.delete(e):n?.append?t.append(e,r):t.set(e,r)};status=e=>{this.#o=e};set=(e,r)=>{this.#n??=new Map,this.#n.set(e,r)};get=e=>this.#n?this.#n.get(e):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#s(e,r,n){let t=this.#t?new Headers(this.#t.headers):this.#a??new Headers;if(typeof r=="object"&&"headers"in r){let o=r.headers instanceof Headers?r.headers:new Headers(r.headers);for(let[s,a]of o)s.toLowerCase()==="set-cookie"?t.append(s,a):t.set(s,a)}if(n)for(let[o,s]of Object.entries(n))if(typeof s=="string")t.set(o,s);else{t.delete(o);for(let a of s)t.append(o,a)}let i=typeof r=="number"?r:r?.status??this.#o;return de(e,{status:i,headers:t})}newResponse=(...e)=>this.#s(...e);body=(e,r,n)=>this.#s(e,r,n);text=(e,r,n)=>!this.#a&&!this.#o&&!r&&!n&&!this.finalized?new Response(e):this.#s(e,r,cr(si,n));json=(e,r,n)=>this.#s(JSON.stringify(e),r,cr("application/json",n));html=(e,r,n)=>{let t=i=>this.#s(i,r,cr("text/html; charset=UTF-8",n));return typeof e=="object"?lr(e,nn.Stringify,!1,{}).then(t):t(e)};redirect=(e,r)=>{let n=String(e);return this.header("Location",/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,r??302)};notFound=()=>(this.#c??=()=>de(),this.#c(this))};var A="ALL",on="all",sn=["get","post","put","delete","options","patch"],_e="Can not add a route since the matcher is already built.",Fe=class extends Error{};var an="__COMPOSED_HANDLER";var ai=e=>e.text("404 Not Found",404),ln=(e,r)=>{if("getResponse"in e){let n=e.getResponse();return r.newResponse(n.body,n)}return console.error(e),r.text("Internal Server Error",500)},cn=class un{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#r="/";routes=[];constructor(r={}){[...sn,on].forEach(o=>{this[o]=(s,...a)=>(typeof s=="string"?this.#r=s:this.#o(o,this.#r,s),a.forEach(l=>{this.#o(o,this.#r,l)}),this)}),this.on=(o,s,...a)=>{for(let l of[s].flat()){this.#r=l;for(let c of[o].flat())a.map(f=>{this.#o(c.toUpperCase(),this.#r,f)})}return this},this.use=(o,...s)=>(typeof o=="string"?this.#r=o:(this.#r="*",s.unshift(o)),s.forEach(a=>{this.#o(A,this.#r,a)}),this);let{strict:t,...i}=r;Object.assign(this,i),this.getPath=t??!0?r.getPath??sr:Jr}#e(){let r=new un({router:this.router,getPath:this.getPath});return r.errorHandler=this.errorHandler,r.#n=this.#n,r.routes=this.routes,r}#n=ai;errorHandler=ln;route(r,n){let t=this.basePath(r);return n.routes.map(i=>{let o;n.errorHandler===ln?o=i.handler:(o=async(s,a)=>(await tr([],n.errorHandler)(s,()=>i.handler(s,a))).res,o[an]=i.handler),t.#o(i.method,i.path,o)}),this}basePath(r){let n=this.#e();return n._basePath=$(this._basePath,r),n}onError=r=>(this.errorHandler=r,this);notFound=r=>(this.#n=r,this);mount(r,n,t){let i,o;t&&(typeof t=="function"?o=t:(o=t.optionHandler,t.replaceRequest===!1?i=l=>l:i=t.replaceRequest));let s=o?l=>{let c=o(l);return Array.isArray(c)?c:[c]}:l=>{let c;try{c=l.executionCtx}catch{}return[l.env,c]};i||=(()=>{let l=$(this._basePath,r),c=l==="/"?0:l.length;return f=>{let u=new URL(f.url);return u.pathname=u.pathname.slice(c)||"/",new Request(u,f)}})();let a=async(l,c)=>{let f=await n(i(l.req.raw),...s(l));if(f)return f;await c()};return this.#o(A,$(r,"*"),a),this}#o(r,n,t){r=r.toUpperCase(),n=$(this._basePath,n);let i={basePath:this._basePath,path:n,method:r,handler:t};this.router.add(r,n,[t,i]),this.routes.push(i)}#i(r,n){if(r instanceof Error)return this.errorHandler(r,n);throw r}#t(r,n,t,i){if(i==="HEAD")return(async()=>new Response(null,await this.#t(r,n,t,"GET")))();let o=this.getPath(r,{env:t}),s=this.router.match(i,o),a=new tn(r,{path:o,matchResult:s,env:t,executionCtx:n,notFoundHandler:this.#n});if(s[0].length===1){let c;try{c=s[0][0][0][0](a,async()=>{a.res=await this.#n(a)})}catch(f){return this.#i(f,a)}return c instanceof Promise?c.then(f=>f||(a.finalized?a.res:this.#n(a))).catch(f=>this.#i(f,a)):c??this.#n(a)}let l=tr(s[0],this.errorHandler,this.#n);return(async()=>{try{let c=await l(a);if(!c.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return c.res}catch(c){return this.#i(c,a)}})()}fetch=(r,...n)=>this.#t(r,n[1],n[0],r.method);request=(r,n,t,i)=>r instanceof Request?this.fetch(n?new Request(r,n):r,t,i):(r=r.toString(),this.fetch(new Request(/^https?:\/\//.test(r)?r:`http://localhost${$("/",r)}`,n),t,i));fire=()=>{addEventListener("fetch",r=>{r.respondWith(this.#t(r.request,r,void 0,r.request.method))})}};var je=[];function ur(e,r){let n=this.buildAllMatchers(),t=((i,o)=>{let s=n[i]||n[A],a=s[2][o];if(a)return a;let l=o.match(s[0]);if(!l)return[[],je];let c=l.indexOf("",1);return[s[1][c],l]});return this.match=t,t(e,r)}var Ne="[^/]+",he=".*",me="(?:|/.*)",M=Symbol(),li=new Set(".\\+*[^]$()");function ci(e,r){return e.length===1?r.length===1?e<r?-1:1:-1:r.length===1||e===he||e===me?1:r===he||r===me?-1:e===Ne?1:r===Ne?-1:e.length===r.length?e<r?-1:1:r.length-e.length}var fn=class fr{#r;#e;#n=Object.create(null);insert(r,n,t,i,o){if(r.length===0){if(this.#r!==void 0)throw M;if(o)return;this.#r=n;return}let[s,...a]=r,l=s==="*"?a.length===0?["","",he]:["","",Ne]:s==="/*"?["","",me]:s.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(l){let f=l[1],u=l[2]||Ne;if(f&&l[2]&&(u===".*"||(u=u.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(u))))throw M;if(c=this.#n[u],!c){if(Object.keys(this.#n).some(p=>p!==he&&p!==me))throw M;if(o)return;c=this.#n[u]=new fr,f!==""&&(c.#e=i.varIndex++)}!o&&f!==""&&t.push([f,c.#e])}else if(c=this.#n[s],!c){if(Object.keys(this.#n).some(f=>f.length>1&&f!==he&&f!==me))throw M;if(o)return;c=this.#n[s]=new fr}c.insert(a,n,t,i,o)}buildRegExpStr(){let n=Object.keys(this.#n).sort(ci).map(t=>{let i=this.#n[t];return(typeof i.#e=="number"?`(${t})@${i.#e}`:li.has(t)?`\\${t}`:t)+i.buildRegExpStr()});return typeof this.#r=="number"&&n.unshift(`#${this.#r}`),n.length===0?"":n.length===1?n[0]:"(?:"+n.join("|")+")"}};var pn=class{#r={varIndex:0};#e=new fn;insert(e,r,n){let t=[],i=[];for(let s=0;;){let a=!1;if(e=e.replace(/\{[^}]+\}/g,l=>{let c=`@\\${s}`;return i[s]=[c,l],s++,a=!0,c}),!a)break}let o=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let s=i.length-1;s>=0;s--){let[a]=i[s];for(let l=o.length-1;l>=0;l--)if(o[l].indexOf(a)!==-1){o[l]=o[l].replace(a,i[s][1]);break}}return this.#e.insert(o,r,t,this.#r,n),t}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let r=0,n=[],t=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(i,o,s)=>o!==void 0?(n[++r]=Number(o),"$()"):(s!==void 0&&(t[Number(s)]=++r),"")),[new RegExp(`^${e}`),n,t]}};var ui=[/^$/,[],Object.create(null)],dn=Object.create(null);function hn(e){return dn[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(r,n)=>n?`\\${n}`:"(?:|/.*)")}$`)}function fi(){dn=Object.create(null)}function pi(e){let r=new pn,n=[];if(e.length===0)return ui;let t=e.map(c=>[!/\*|\/:/.test(c[0]),...c]).sort(([c,f],[u,p])=>c?1:u?-1:f.length-p.length),i=Object.create(null);for(let c=0,f=-1,u=t.length;c<u;c++){let[p,d,m]=t[c];p?i[d]=[m.map(([x])=>[x,Object.create(null)]),je]:f++;let y;try{y=r.insert(d,f,p)}catch(x){throw x===M?new Fe(d):x}p||(n[f]=m.map(([x,v])=>{let g=Object.create(null);for(v-=1;v>=0;v--){let[le,Ye]=y[v];g[le]=Ye}return[x,g]}))}let[o,s,a]=r.buildRegExp();for(let c=0,f=n.length;c<f;c++)for(let u=0,p=n[c].length;u<p;u++){let d=n[c][u]?.[1];if(!d)continue;let m=Object.keys(d);for(let y=0,x=m.length;y<x;y++)d[m[y]]=a[d[m[y]]]}let l=[];for(let c in s)l[c]=n[s[c]];return[o,l,i]}function V(e,r){if(e){for(let n of Object.keys(e).sort((t,i)=>i.length-t.length))if(hn(n).test(r))return[...e[n]]}}var Le=class{name="RegExpRouter";#r;#e;constructor(){this.#r={[A]:Object.create(null)},this.#e={[A]:Object.create(null)}}add(e,r,n){let t=this.#r,i=this.#e;if(!t||!i)throw new Error(_e);t[e]||[t,i].forEach(a=>{a[e]=Object.create(null),Object.keys(a[A]).forEach(l=>{a[e][l]=[...a[A][l]]})}),r==="/*"&&(r="*");let o=(r.match(/\/:/g)||[]).length;if(/\*$/.test(r)){let a=hn(r);e===A?Object.keys(t).forEach(l=>{t[l][r]||=V(t[l],r)||V(t[A],r)||[]}):t[e][r]||=V(t[e],r)||V(t[A],r)||[],Object.keys(t).forEach(l=>{(e===A||e===l)&&Object.keys(t[l]).forEach(c=>{a.test(c)&&t[l][c].push([n,o])})}),Object.keys(i).forEach(l=>{(e===A||e===l)&&Object.keys(i[l]).forEach(c=>a.test(c)&&i[l][c].push([n,o]))});return}let s=Ie(r)||[r];for(let a=0,l=s.length;a<l;a++){let c=s[a];Object.keys(i).forEach(f=>{(e===A||e===f)&&(i[f][c]||=[...V(t[f],c)||V(t[A],c)||[]],i[f][c].push([n,o-l+a+1]))})}}match=ur;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#r)).forEach(r=>{e[r]||=this.#n(r)}),this.#r=this.#e=void 0,fi(),e}#n(e){let r=[],n=e===A;return[this.#r,this.#e].forEach(t=>{let i=t[e]?Object.keys(t[e]).map(o=>[o,t[e][o]]):[];i.length!==0?(n||=!0,r.push(...i)):e!==A&&r.push(...Object.keys(t[A]).map(o=>[o,t[A][o]]))}),n?pi(r):null}};var pr=class{name="SmartRouter";#r=[];#e=[];constructor(e){this.#r=e.routers}add(e,r,n){if(!this.#e)throw new Error(_e);this.#e.push([e,r,n])}match(e,r){if(!this.#e)throw new Error("Fatal error");let n=this.#r,t=this.#e,i=n.length,o=0,s;for(;o<i;o++){let a=n[o];try{for(let l=0,c=t.length;l<c;l++)a.add(...t[l]);s=a.match(e,r)}catch(l){if(l instanceof Fe)continue;throw l}this.match=a.match.bind(a),this.#r=[a],this.#e=void 0;break}if(o===i)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,s}get activeRouter(){if(this.#e||this.#r.length!==1)throw new Error("No active router has been determined yet.");return this.#r[0]}};var ge=Object.create(null),di=e=>{for(let r in e)return!0;return!1},mn=class gn{#r;#e;#n;#o=0;#i=ge;constructor(r,n,t){if(this.#e=t||Object.create(null),this.#r=[],r&&n){let i=Object.create(null);i[r]={handler:n,possibleKeys:[],score:0},this.#r=[i]}this.#n=[]}insert(r,n,t){this.#o=++this.#o;let i=this,o=Vr(n),s=[];for(let a=0,l=o.length;a<l;a++){let c=o[a],f=o[a+1],u=Zr(c,f),p=Array.isArray(u)?u[0]:c;if(p in i.#e){i=i.#e[p],u&&s.push(u[1]);continue}i.#e[p]=new gn,u&&(i.#n.push(u),s.push(u[1])),i=i.#e[p]}return i.#r.push({[r]:{handler:t,possibleKeys:s.filter((a,l,c)=>c.indexOf(a)===l),score:this.#o}}),i}#t(r,n,t,i,o){for(let s=0,a=n.#r.length;s<a;s++){let l=n.#r[s],c=l[t]||l[A],f={};if(c!==void 0&&(c.params=Object.create(null),r.push(c),i!==ge||o&&o!==ge))for(let u=0,p=c.possibleKeys.length;u<p;u++){let d=c.possibleKeys[u],m=f[c.score];c.params[d]=o?.[d]&&!m?o[d]:i[d]??o?.[d],f[c.score]=!0}}}search(r,n){let t=[];this.#i=ge;let o=[this],s=or(n),a=[],l=s.length,c=null;for(let f=0;f<l;f++){let u=s[f],p=f===l-1,d=[];for(let y=0,x=o.length;y<x;y++){let v=o[y],g=v.#e[u];g&&(g.#i=v.#i,p?(g.#e["*"]&&this.#t(t,g.#e["*"],r,v.#i),this.#t(t,g,r,v.#i)):d.push(g));for(let le=0,Ye=v.#n.length;le<Ye;le++){let jr=v.#n[le],_=v.#i===ge?{}:{...v.#i};if(jr==="*"){let q=v.#e["*"];q&&(this.#t(t,q,r,v.#i),q.#i=_,d.push(q));continue}let[It,Nr,ce]=jr;if(!u&&!(ce instanceof RegExp))continue;let P=v.#e[It];if(ce instanceof RegExp){if(c===null){c=new Array(l);let Ee=n[0]==="/"?1:0;for(let ue=0;ue<l;ue++)c[ue]=Ee,Ee+=s[ue].length+1}let q=n.substring(c[f]),Ve=ce.exec(q);if(Ve){if(_[Nr]=Ve[0],this.#t(t,P,r,v.#i,_),di(P.#e)){P.#i=_;let Ee=Ve[0].match(/\//)?.length??0;(a[Ee]||=[]).push(P)}continue}}(ce===!0||ce.test(u))&&(_[Nr]=u,p?(this.#t(t,P,r,_,v.#i),P.#e["*"]&&this.#t(t,P.#e["*"],r,_,v.#i)):(P.#i=_,d.push(P)))}}let m=a.shift();o=m?d.concat(m):d}return t.length>1&&t.sort((f,u)=>f.score-u.score),[t.map(({handler:f,params:u})=>[f,u])]}};var dr=class{name="TrieRouter";#r;constructor(){this.#r=new mn}add(e,r,n){let t=Ie(r);if(t){for(let i=0,o=t.length;i<o;i++)this.#r.insert(e,t[i],n);return}this.#r.insert(e,r,n)}match(e,r){return this.#r.search(e,r)}};var O=class extends cn{constructor(e={}){super(e),this.router=e.router??new pr({routers:[new Le,new dr]})}};var yn=e=>{let n={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...e},t=(o=>typeof o=="string"?o==="*"?n.credentials?s=>s||null:()=>o:s=>o===s?s:null:typeof o=="function"?o:s=>o.includes(s)?s:null)(n.origin),i=(o=>typeof o=="function"?o:Array.isArray(o)?()=>o:()=>[])(n.allowMethods);return async function(s,a){function l(f,u){s.res.headers.set(f,u)}let c=await t(s.req.header("origin")||"",s);if(c&&l("Access-Control-Allow-Origin",c),n.credentials&&l("Access-Control-Allow-Credentials","true"),n.exposeHeaders?.length&&l("Access-Control-Expose-Headers",n.exposeHeaders.join(",")),s.req.method==="OPTIONS"){(n.origin!=="*"||n.credentials)&&l("Vary","Origin"),n.maxAge!=null&&l("Access-Control-Max-Age",n.maxAge.toString());let f=await i(s.req.header("origin")||"",s);f.length&&l("Access-Control-Allow-Methods",f.join(","));let u=n.allowHeaders;if(!u?.length){let p=s.req.header("Access-Control-Request-Headers");p&&(u=p.split(/\s*,\s*/))}return u?.length&&(l("Access-Control-Allow-Headers",u.join(",")),s.res.headers.append("Vary","Access-Control-Request-Headers")),s.res.headers.delete("Content-Length"),s.res.headers.delete("Content-Type"),new Response(null,{headers:s.res.headers,status:204,statusText:"No Content"})}await a(),(n.origin!=="*"||n.credentials)&&s.header("Vary","Origin",{append:!0})}};function hi(){let{process:e,Deno:r}=globalThis;return!(typeof r?.noColor=="boolean"?r.noColor:e!==void 0?"NO_COLOR"in e?.env:!1)}async function xn(){let{navigator:e}=globalThis,r="cloudflare:workers";return!(e!==void 0&&e.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import(r)).env??{})}catch{return!1}})():!hi())}var mi=e=>{let[r,n]=[",","."];return e.map(i=>i.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+r)).join(n)},gi=e=>{let r=Date.now()-e;return mi([r<1e3?r+"ms":Math.round(r/1e3)+"s"])},yi=async e=>{if(await xn())switch(e/100|0){case 5:return`\x1B[31m${e}\x1B[0m`;case 4:return`\x1B[33m${e}\x1B[0m`;case 3:return`\x1B[36m${e}\x1B[0m`;case 2:return`\x1B[32m${e}\x1B[0m`}return`${e}`};async function vn(e,r,n,t,i=0,o){let s=r==="<--"?`${r} ${n} ${t}`:`${r} ${n} ${t} ${await yi(i)} ${o}`;e(s)}var An=(e=console.log)=>async function(n,t){let{method:i,url:o}=n.req,s=o.slice(o.indexOf("/",8));await vn(e,"<--",i,s);let a=Date.now();await t(),await vn(e,"-->",i,s,n.res.status,gi(a))};import{existsSync as xi,readFileSync as vi}from"node:fs";import{dirname as Ai,resolve as bn}from"node:path";import{fileURLToPath as bi}from"node:url";var wn="apv.config.json",H=null;function F(){if(H)return H;let r=[process.env.APV_CONFIG,bn(process.cwd(),wn),bn(Ai(bi(import.meta.url)),"..","..","..",wn)].filter(Boolean);for(let n of r)if(xi(n))try{let t=vi(n,"utf-8"),i=JSON.parse(t);return H={cacheDir:i.cacheDir,localRepos:i.localRepos??{},customTaskDocs:i.customTaskDocs??{}},console.log(`Loaded config from ${n}`),wi(H),H}catch(t){console.warn(`Failed to parse ${n}:`,t)}return H={localRepos:{},customTaskDocs:{}},H}function Rn(e,r,n){let t=F(),i=`${e}/${r}/${n}`;if(t.localRepos[i])return t.localRepos[i];let o=i.toLowerCase();for(let[s,a]of Object.entries(t.localRepos))if(s.toLowerCase()===o)return a}function wi(e){let r=Object.entries(e.localRepos);if(r.length===0){console.log(" No local repo mappings configured");return}console.log(` ${r.length} local repo mapping(s):`);for(let[n,t]of r)console.log(` ${n} \u2192 ${t}`)}function De(e){let r=e.startsWith("/"),n=e.split("/").filter(o=>o!==""&&o!=="."),t=[];for(let o of n)o===".."?t.length>0&&t[t.length-1]!==".."?t.pop():r||t.push(o):t.push(o);let i=t.join("/");return r?`/${i}`:i}function Mn(e){return typeof e>"u"||e===null}function Ci(e){return typeof e=="object"&&e!==null}function Ei(e){return Array.isArray(e)?e:Mn(e)?[]:[e]}function ki(e,r){var n,t,i,o;if(r)for(o=Object.keys(r),n=0,t=o.length;n<t;n+=1)i=o[n],e[i]=r[i];return e}function Si(e,r){var n="",t;for(t=0;t<r;t+=1)n+=e;return n}function Ti(e){return e===0&&Number.NEGATIVE_INFINITY===1/e}var Pi=Mn,Oi=Ci,Ii=Ei,_i=Si,Fi=Ti,ji=ki,w={isNothing:Pi,isObject:Oi,toArray:Ii,repeat:_i,isNegativeZero:Fi,extend:ji};function Hn(e,r){var n="",t=e.reason||"(unknown reason)";return e.mark?(e.mark.name&&(n+='in "'+e.mark.name+'" '),n+="("+(e.mark.line+1)+":"+(e.mark.column+1)+")",!r&&e.mark.snippet&&(n+=`
2
+ import{existsSync as Tt,readFileSync as Pt}from"node:fs";import{extname as Fa,join as Fr}from"node:path";import{fileURLToPath as ja}from"node:url";import{createServer as _t}from"http";import{Http2ServerRequest as $r,constants as Ft}from"http2";import{Http2ServerRequest as Ze}from"http2";import{Readable as Lr}from"stream";import qt from"crypto";var L=class extends Error{constructor(e,r){super(e,r),this.name="RequestError"}},jt=e=>e instanceof L?e:new L(e.message,{cause:e}),Nt=global.Request,fe=class extends Nt{constructor(e,r){typeof e=="object"&&K in e&&(e=e[K]()),typeof r?.body?.getReader<"u"&&(r.duplex??="half"),super(e,r)}},Lt=e=>{let r=[],n=e.rawHeaders;for(let t=0;t<n.length;t+=2){let{[t]:i,[t+1]:o}=n;i.charCodeAt(0)!==58&&r.push([i,o])}return new Headers(r)},Mr=Symbol("wrapBodyStream"),Dt=(e,r,n,t,i)=>{let o={method:e,headers:n,signal:i.signal};if(e==="TRACE"){o.method="GET";let s=new fe(r,o);return Object.defineProperty(s,"method",{get(){return"TRACE"}}),s}if(!(e==="GET"||e==="HEAD"))if("rawBody"in t&&t.rawBody instanceof Buffer)o.body=new ReadableStream({start(s){s.enqueue(t.rawBody),s.close()}});else if(t[Mr]){let s;o.body=new ReadableStream({async pull(a){try{s||=Lr.toWeb(t).getReader();let{done:l,value:c}=await s.read();l?a.close():a.enqueue(c)}catch(l){a.error(l)}}})}else o.body=Lr.toWeb(t);return new fe(r,o)},K=Symbol("getRequestCache"),Hr=Symbol("requestCache"),ke=Symbol("incomingKey"),Se=Symbol("urlKey"),$t=Symbol("headersKey"),G=Symbol("abortControllerKey"),Mt=Symbol("getAbortController"),pe={get method(){return this[ke].method||"GET"},get url(){return this[Se]},get headers(){return this[$t]||=Lt(this[ke])},[Mt](){return this[K](),this[G]},[K](){return this[G]||=new AbortController,this[Hr]||=Dt(this.method,this[Se],this.headers,this[ke],this[G])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty(pe,e,{get(){return this[K]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(pe,e,{value:function(){return this[K]()[e]()}})});Object.defineProperty(pe,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,r,n){let t={method:this.method,url:this.url,headers:this.headers,nativeRequest:this[Hr]};return`Request (lightweight) ${n(t,{...r,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(pe,fe.prototype);var Ht=(e,r)=>{let n=Object.create(pe);n[ke]=e;let t=e.url||"";if(t[0]!=="/"&&(t.startsWith("http://")||t.startsWith("https://"))){if(e instanceof Ze)throw new L("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(t);n[Se]=a.href}catch(a){throw new L("Invalid absolute URL",{cause:a})}return n}let i=(e instanceof Ze?e.authority:e.headers.host)||r;if(!i)throw new L("Missing host header");let o;if(e instanceof Ze){if(o=e.scheme,!(o==="http"||o==="https"))throw new L("Unsupported scheme")}else o=e.socket&&e.socket.encrypted?"https":"http";let s=new URL(`${o}://${i}${t}`);if(s.hostname.length!==i.length&&s.hostname!==i.replace(/:\d+$/,""))throw new L("Invalid host header");return n[Se]=s.href,n},Qe=Symbol("responseCache"),W=Symbol("getResponseCache"),D=Symbol("cache"),rr=global.Response,Y=class zr{#r;#e;[W](){return delete this[D],this[Qe]||=new rr(this.#r,this.#e)}constructor(r,n){let t;if(this.#r=r,n instanceof zr){let i=n[Qe];if(i){this.#e=i,this[W]();return}else this.#e=n.#e,t=new Headers(n.#e.headers)}else this.#e=n;(typeof r=="string"||typeof r?.getReader<"u"||r instanceof Blob||r instanceof Uint8Array)&&(this[D]=[n?.status||200,r,t||n?.headers])}get headers(){let r=this[D];return r?(r[2]instanceof Headers||(r[2]=new Headers(r[2]||{"content-type":"text/plain; charset=UTF-8"})),r[2]):this[W]().headers}get status(){return this[D]?.[0]??this[W]().status}get ok(){let r=this.status;return r>=200&&r<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(Y.prototype,e,{get(){return this[W]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(Y.prototype,e,{value:function(){return this[W]()[e]()}})});Object.defineProperty(Y.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,r,n){let t={status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[Qe]};return`Response (lightweight) ${n(t,{...r,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(Y,rr);Object.setPrototypeOf(Y.prototype,rr.prototype);async function zt(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function Br(e,r,n){let t=a=>{e.cancel(a).catch(()=>{})};return r.on("close",t),r.on("error",t),(n??e.read()).then(s,i),e.closed.finally(()=>{r.off("close",t),r.off("error",t)});function i(a){a&&r.destroy(a)}function o(){e.read().then(s,i)}function s({done:a,value:l}){try{if(a)r.end();else if(!r.write(l))r.once("drain",o);else return e.read().then(s,i)}catch(c){i(c)}}}function Bt(e,r){if(e.locked)throw new TypeError("ReadableStream is locked.");return r.destroyed?void 0:Br(e.getReader(),r)}var Xe=e=>{let r={};e instanceof Headers||(e=new Headers(e??void 0));let n=[];for(let[t,i]of e)t==="set-cookie"?n.push(i):r[t]=i;return n.length>0&&(r["set-cookie"]=n),r["content-type"]??="text/plain; charset=UTF-8",r},Ut="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=qt);var nr=Symbol("outgoingEnded"),Dr=Symbol("incomingDraining"),Wt=500,Gt=64*1024*1024,Je=e=>{let r=e;if(e.destroyed||r[Dr])return;if(r[Dr]=!0,e instanceof $r){try{e.stream?.close?.(Ft.NGHTTP2_NO_ERROR)}catch{}return}let n=0,t=()=>{clearTimeout(o),e.off("data",s),e.off("end",t),e.off("error",t)},i=()=>{t();let a=e.socket;a&&!a.destroyed&&a.destroySoon()},o=setTimeout(i,Wt);o.unref?.();let s=a=>{n+=a.length,n>Gt&&i()};e.on("data",s),e.on("end",t),e.on("error",t),e.resume()},Kt=()=>new Response(null,{status:400}),Ur=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),er=(e,r)=>{let n=e instanceof Error?e:new Error("unknown error",{cause:e});n.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(e),r.headersSent||r.writeHead(500,{"Content-Type":"text/plain"}),r.end(`Error: ${n.message}`),r.destroy(n))},qr=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},Wr=async(e,r)=>{let[n,t,i]=e[D],o=!1;if(!i)i={"content-type":"text/plain; charset=UTF-8"};else if(i instanceof Headers)o=i.has("content-length"),i=Xe(i);else if(Array.isArray(i)){let s=new Headers(i);o=s.has("content-length"),i=Xe(s)}else for(let s in i)if(s.length===14&&s.toLowerCase()==="content-length"){o=!0;break}o||(typeof t=="string"?i["Content-Length"]=Buffer.byteLength(t):t instanceof Uint8Array?i["Content-Length"]=t.byteLength:t instanceof Blob&&(i["Content-Length"]=t.size)),r.writeHead(n,i),typeof t=="string"||t instanceof Uint8Array?r.end(t):t instanceof Blob?r.end(new Uint8Array(await t.arrayBuffer())):(qr(r),await Bt(t,r)?.catch(s=>er(s,r))),r[nr]?.()},Yt=e=>typeof e.then=="function",Vt=async(e,r,n={})=>{if(Yt(e))if(n.errorHandler)try{e=await e}catch(i){let o=await n.errorHandler(i);if(!o)return;e=o}else e=await e.catch(Ur);if(D in e)return Wr(e,r);let t=Xe(e.headers);if(e.body){let i=e.body.getReader(),o=[],s=!1,a;if(t["transfer-encoding"]!=="chunked"){let l=2;for(let c=0;c<l;c++){a||=i.read();let f=await zt(a).catch(u=>{console.error(u),s=!0});if(!f){if(c===1){await new Promise(u=>setTimeout(u)),l=3;continue}break}if(a=void 0,f.value&&o.push(f.value),f.done){s=!0;break}}s&&!("content-length"in t)&&(t["content-length"]=o.reduce((c,f)=>c+f.length,0))}r.writeHead(e.status,t),o.forEach(l=>{r.write(l)}),s?r.end():(o.length===0&&qr(r),await Br(i,r,a))}else t[Ut]||(r.writeHead(e.status,t),r.end());r[nr]?.()},Zt=(e,r={})=>{let n=r.autoCleanupIncoming??!0;return r.overrideGlobalObjects!==!1&&global.Request!==fe&&(Object.defineProperty(global,"Request",{value:fe}),Object.defineProperty(global,"Response",{value:Y})),async(t,i)=>{let o,s;try{s=Ht(t,r.hostname);let a=!n||t.method==="GET"||t.method==="HEAD";if(a||(t[Mr]=!0,t.on("end",()=>{a=!0}),t instanceof $r&&(i[nr]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{Je(t)})})}),i.on("finish",()=>{a||Je(t)})),i.on("close",()=>{s[G]&&(t.errored?s[G].abort(t.errored.toString()):i.writableFinished||s[G].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{Je(t)})})}),o=e(s,{incoming:t,outgoing:i}),D in o)return Wr(o,i)}catch(a){if(o)return er(a,i);if(r.errorHandler){if(o=await r.errorHandler(s?a:jt(a)),!o)return}else s?o=Ur(a):o=Kt()}try{return await Vt(o,i,r)}catch(a){return er(a,i)}}},Jt=e=>{let r=e.fetch,n=Zt(r,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||_t)(e.serverOptions||{},n)},Gr=(e,r)=>{let n=Jt(e);return n.listen(e?.port??3e3,e.hostname,()=>{let t=n.address();r&&r(t)}),n};var tr=(e,r,n)=>(t,i)=>{let o=-1;return s(0);async function s(a){if(a<=o)throw new Error("next() called multiple times");o=a;let l,c=!1,f;if(e[a]?(f=e[a][0][0],t.req.routeIndex=a):f=a===e.length&&i||void 0,f)try{l=await f(t,()=>s(a+1))}catch(u){if(u instanceof Error&&r)t.error=u,l=await r(u,t),c=!0;else throw u}else t.finalized===!1&&n&&(l=await n(t));return l&&(t.finalized===!1||c)&&(t.res=l),t}};var Kr=Symbol();var Yr=async(e,r=Object.create(null))=>{let{all:n=!1,dot:t=!1}=r,o=(e instanceof Te?e.raw.headers:e.headers).get("Content-Type");return o?.startsWith("multipart/form-data")||o?.startsWith("application/x-www-form-urlencoded")?Qt(e,{all:n,dot:t}):{}};async function Qt(e,r){let n=await e.formData();return n?Xt(n,r):{}}function Xt(e,r){let n=Object.create(null);return e.forEach((t,i)=>{r.all||i.endsWith("[]")?ei(n,i,t):n[i]=t}),r.dot&&Object.entries(n).forEach(([t,i])=>{t.includes(".")&&(ri(n,t,i),delete n[t])}),n}var ei=(e,r,n)=>{e[r]!==void 0?Array.isArray(e[r])?e[r].push(n):e[r]=[e[r],n]:r.endsWith("[]")?e[r]=[n]:e[r]=n},ri=(e,r,n)=>{if(/(?:^|\.)__proto__\./.test(r))return;let t=e,i=r.split(".");i.forEach((o,s)=>{s===i.length-1?t[o]=n:((!t[o]||typeof t[o]!="object"||Array.isArray(t[o])||t[o]instanceof File)&&(t[o]=Object.create(null)),t=t[o])})};var or=e=>{let r=e.split("/");return r[0]===""&&r.shift(),r},Vr=e=>{let{groups:r,path:n}=ni(e),t=or(n);return ti(t,r)},ni=e=>{let r=[];return e=e.replace(/\{[^}]+\}/g,(n,t)=>{let i=`@${t}`;return r.push([i,n]),i}),{groups:r,path:e}},ti=(e,r)=>{for(let n=r.length-1;n>=0;n--){let[t]=r[n];for(let i=e.length-1;i>=0;i--)if(e[i].includes(t)){e[i]=e[i].replace(t,r[n][1]);break}}return e},Pe={},Zr=(e,r)=>{if(e==="*")return"*";let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let t=`${e}#${r}`;return Pe[t]||(n[2]?Pe[t]=r&&r[0]!==":"&&r[0]!=="*"?[t,n[1],new RegExp(`^${n[2]}(?=/${r})`)]:[e,n[1],new RegExp(`^${n[2]}$`)]:Pe[t]=[e,n[1],!0]),Pe[t]}return null},Oe=(e,r)=>{try{return r(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return r(n)}catch{return n}})}},ii=e=>Oe(e,decodeURI),sr=e=>{let r=e.url,n=r.indexOf("/",r.indexOf(":")+4),t=n;for(;t<r.length;t++){let i=r.charCodeAt(t);if(i===37){let o=r.indexOf("?",t),s=r.indexOf("#",t),a=o===-1?s===-1?void 0:s:s===-1?o:Math.min(o,s),l=r.slice(n,a);return ii(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(i===63||i===35)break}return r.slice(n,t)};var Jr=e=>{let r=sr(e);return r.length>1&&r.at(-1)==="/"?r.slice(0,-1):r},$=(e,r,...n)=>(n.length&&(r=$(r,...n)),`${e?.[0]==="/"?"":"/"}${e}${r==="/"?"":`${e?.at(-1)==="/"?"":"/"}${r?.[0]==="/"?r.slice(1):r}`}`),Ie=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let r=e.split("/"),n=[],t="";return r.forEach(i=>{if(i!==""&&!/\:/.test(i))t+="/"+i;else if(/\:/.test(i))if(/\?/.test(i)){n.length===0&&t===""?n.push("/"):n.push(t);let o=i.replace("?","");t+="/"+o,n.push(t)}else t+="/"+i}),n.filter((i,o,s)=>s.indexOf(i)===o)},ir=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?Oe(e,ar):e):e,Qr=(e,r,n)=>{let t;if(!n&&r&&!/[%+]/.test(r)){let s=e.indexOf("?",8);if(s===-1)return;for(e.startsWith(r,s+1)||(s=e.indexOf(`&${r}`,s+1));s!==-1;){let a=e.charCodeAt(s+r.length+1);if(a===61){let l=s+r.length+2,c=e.indexOf("&",l);return ir(e.slice(l,c===-1?void 0:c))}else if(a==38||isNaN(a))return"";s=e.indexOf(`&${r}`,s+1)}if(t=/[%+]/.test(e),!t)return}let i={};t??=/[%+]/.test(e);let o=e.indexOf("?",8);for(;o!==-1;){let s=e.indexOf("&",o+1),a=e.indexOf("=",o);a>s&&s!==-1&&(a=-1);let l=e.slice(o+1,a===-1?s===-1?void 0:s:a);if(t&&(l=ir(l)),o=s,l==="")continue;let c;a===-1?c="":(c=e.slice(a+1,s===-1?void 0:s),t&&(c=ir(c))),n?(i[l]&&Array.isArray(i[l])||(i[l]=[]),i[l].push(c)):i[l]??=c}return r?i[r]:i},Xr=Qr,en=(e,r)=>Qr(e,r,!0),ar=decodeURIComponent;var rn=e=>Oe(e,ar),Te=class{raw;#r;#e;routeIndex=0;path;bodyCache={};constructor(e,r="/",n=[[]]){this.raw=e,this.path=r,this.#e=n,this.#r={}}param(e){return e?this.#n(e):this.#o()}#n(e){let r=this.#e[0][this.routeIndex][1][e],n=this.#i(r);return n&&/\%/.test(n)?rn(n):n}#o(){let e={},r=Object.keys(this.#e[0][this.routeIndex][1]);for(let n of r){let t=this.#i(this.#e[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?rn(t):t)}return e}#i(e){return this.#e[1]?this.#e[1][e]:e}query(e){return Xr(this.url,e)}queries(e){return en(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let r={};return this.raw.headers.forEach((n,t)=>{r[t]=n}),r}async parseBody(e){return Yr(this,e)}#t=e=>{let{bodyCache:r,raw:n}=this,t=r[e];if(t)return t;let i=Object.keys(r)[0];return i?r[i].then(o=>(i==="json"&&(o=JSON.stringify(o)),new Response(o)[e]())):r[e]=n[e]()};json(){return this.#t("text").then(e=>JSON.parse(e))}text(){return this.#t("text")}arrayBuffer(){return this.#t("arrayBuffer")}blob(){return this.#t("blob")}formData(){return this.#t("formData")}addValidatedData(e,r){this.#r[e]=r}valid(e){return this.#r[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Kr](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};var nn={Stringify:1,BeforeStream:2,Stream:3},oi=(e,r)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=r,n};var lr=async(e,r,n,t,i)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let o=e.callbacks;if(!o?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let s=Promise.all(o.map(a=>a({phase:r,buffer:i,context:t}))).then(a=>Promise.all(a.filter(Boolean).map(l=>lr(l,r,!1,t,i))).then(()=>i[0]));return n?oi(await s,o):s};var si="text/plain; charset=UTF-8",cr=(e,r)=>({"Content-Type":e,...r}),de=(e,r)=>new Response(e,r),tn=class{#r;#e;env={};#n;finalized=!1;error;#o;#i;#t;#u;#l;#c;#a;#f;#p;constructor(e,r){this.#r=e,r&&(this.#i=r.executionCtx,this.env=r.env,this.#c=r.notFoundHandler,this.#p=r.path,this.#f=r.matchResult)}get req(){return this.#e??=new Te(this.#r,this.#p,this.#f),this.#e}get event(){if(this.#i&&"respondWith"in this.#i)return this.#i;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#i)return this.#i;throw Error("This context has no ExecutionContext")}get res(){return this.#t||=de(null,{headers:this.#a??=new Headers})}set res(e){if(this.#t&&e){e=de(e.body,e);for(let[r,n]of this.#t.headers.entries())if(r!=="content-type")if(r==="set-cookie"){let t=this.#t.headers.getSetCookie();e.headers.delete("set-cookie");for(let i of t)e.headers.append("set-cookie",i)}else e.headers.set(r,n)}this.#t=e,this.finalized=!0}render=(...e)=>(this.#l??=r=>this.html(r),this.#l(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#l=e};header=(e,r,n)=>{this.finalized&&(this.#t=de(this.#t.body,this.#t));let t=this.#t?this.#t.headers:this.#a??=new Headers;r===void 0?t.delete(e):n?.append?t.append(e,r):t.set(e,r)};status=e=>{this.#o=e};set=(e,r)=>{this.#n??=new Map,this.#n.set(e,r)};get=e=>this.#n?this.#n.get(e):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#s(e,r,n){let t=this.#t?new Headers(this.#t.headers):this.#a??new Headers;if(typeof r=="object"&&"headers"in r){let o=r.headers instanceof Headers?r.headers:new Headers(r.headers);for(let[s,a]of o)s.toLowerCase()==="set-cookie"?t.append(s,a):t.set(s,a)}if(n)for(let[o,s]of Object.entries(n))if(typeof s=="string")t.set(o,s);else{t.delete(o);for(let a of s)t.append(o,a)}let i=typeof r=="number"?r:r?.status??this.#o;return de(e,{status:i,headers:t})}newResponse=(...e)=>this.#s(...e);body=(e,r,n)=>this.#s(e,r,n);text=(e,r,n)=>!this.#a&&!this.#o&&!r&&!n&&!this.finalized?new Response(e):this.#s(e,r,cr(si,n));json=(e,r,n)=>this.#s(JSON.stringify(e),r,cr("application/json",n));html=(e,r,n)=>{let t=i=>this.#s(i,r,cr("text/html; charset=UTF-8",n));return typeof e=="object"?lr(e,nn.Stringify,!1,{}).then(t):t(e)};redirect=(e,r)=>{let n=String(e);return this.header("Location",/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,r??302)};notFound=()=>(this.#c??=()=>de(),this.#c(this))};var A="ALL",on="all",sn=["get","post","put","delete","options","patch"],_e="Can not add a route since the matcher is already built.",Fe=class extends Error{};var an="__COMPOSED_HANDLER";var ai=e=>e.text("404 Not Found",404),ln=(e,r)=>{if("getResponse"in e){let n=e.getResponse();return r.newResponse(n.body,n)}return console.error(e),r.text("Internal Server Error",500)},cn=class un{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#r="/";routes=[];constructor(r={}){[...sn,on].forEach(o=>{this[o]=(s,...a)=>(typeof s=="string"?this.#r=s:this.#o(o,this.#r,s),a.forEach(l=>{this.#o(o,this.#r,l)}),this)}),this.on=(o,s,...a)=>{for(let l of[s].flat()){this.#r=l;for(let c of[o].flat())a.map(f=>{this.#o(c.toUpperCase(),this.#r,f)})}return this},this.use=(o,...s)=>(typeof o=="string"?this.#r=o:(this.#r="*",s.unshift(o)),s.forEach(a=>{this.#o(A,this.#r,a)}),this);let{strict:t,...i}=r;Object.assign(this,i),this.getPath=t??!0?r.getPath??sr:Jr}#e(){let r=new un({router:this.router,getPath:this.getPath});return r.errorHandler=this.errorHandler,r.#n=this.#n,r.routes=this.routes,r}#n=ai;errorHandler=ln;route(r,n){let t=this.basePath(r);return n.routes.map(i=>{let o;n.errorHandler===ln?o=i.handler:(o=async(s,a)=>(await tr([],n.errorHandler)(s,()=>i.handler(s,a))).res,o[an]=i.handler),t.#o(i.method,i.path,o)}),this}basePath(r){let n=this.#e();return n._basePath=$(this._basePath,r),n}onError=r=>(this.errorHandler=r,this);notFound=r=>(this.#n=r,this);mount(r,n,t){let i,o;t&&(typeof t=="function"?o=t:(o=t.optionHandler,t.replaceRequest===!1?i=l=>l:i=t.replaceRequest));let s=o?l=>{let c=o(l);return Array.isArray(c)?c:[c]}:l=>{let c;try{c=l.executionCtx}catch{}return[l.env,c]};i||=(()=>{let l=$(this._basePath,r),c=l==="/"?0:l.length;return f=>{let u=new URL(f.url);return u.pathname=u.pathname.slice(c)||"/",new Request(u,f)}})();let a=async(l,c)=>{let f=await n(i(l.req.raw),...s(l));if(f)return f;await c()};return this.#o(A,$(r,"*"),a),this}#o(r,n,t){r=r.toUpperCase(),n=$(this._basePath,n);let i={basePath:this._basePath,path:n,method:r,handler:t};this.router.add(r,n,[t,i]),this.routes.push(i)}#i(r,n){if(r instanceof Error)return this.errorHandler(r,n);throw r}#t(r,n,t,i){if(i==="HEAD")return(async()=>new Response(null,await this.#t(r,n,t,"GET")))();let o=this.getPath(r,{env:t}),s=this.router.match(i,o),a=new tn(r,{path:o,matchResult:s,env:t,executionCtx:n,notFoundHandler:this.#n});if(s[0].length===1){let c;try{c=s[0][0][0][0](a,async()=>{a.res=await this.#n(a)})}catch(f){return this.#i(f,a)}return c instanceof Promise?c.then(f=>f||(a.finalized?a.res:this.#n(a))).catch(f=>this.#i(f,a)):c??this.#n(a)}let l=tr(s[0],this.errorHandler,this.#n);return(async()=>{try{let c=await l(a);if(!c.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return c.res}catch(c){return this.#i(c,a)}})()}fetch=(r,...n)=>this.#t(r,n[1],n[0],r.method);request=(r,n,t,i)=>r instanceof Request?this.fetch(n?new Request(r,n):r,t,i):(r=r.toString(),this.fetch(new Request(/^https?:\/\//.test(r)?r:`http://localhost${$("/",r)}`,n),t,i));fire=()=>{addEventListener("fetch",r=>{r.respondWith(this.#t(r.request,r,void 0,r.request.method))})}};var je=[];function ur(e,r){let n=this.buildAllMatchers(),t=((i,o)=>{let s=n[i]||n[A],a=s[2][o];if(a)return a;let l=o.match(s[0]);if(!l)return[[],je];let c=l.indexOf("",1);return[s[1][c],l]});return this.match=t,t(e,r)}var Ne="[^/]+",he=".*",me="(?:|/.*)",M=Symbol(),li=new Set(".\\+*[^]$()");function ci(e,r){return e.length===1?r.length===1?e<r?-1:1:-1:r.length===1||e===he||e===me?1:r===he||r===me?-1:e===Ne?1:r===Ne?-1:e.length===r.length?e<r?-1:1:r.length-e.length}var fn=class fr{#r;#e;#n=Object.create(null);insert(r,n,t,i,o){if(r.length===0){if(this.#r!==void 0)throw M;if(o)return;this.#r=n;return}let[s,...a]=r,l=s==="*"?a.length===0?["","",he]:["","",Ne]:s==="/*"?["","",me]:s.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(l){let f=l[1],u=l[2]||Ne;if(f&&l[2]&&(u===".*"||(u=u.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(u))))throw M;if(c=this.#n[u],!c){if(Object.keys(this.#n).some(p=>p!==he&&p!==me))throw M;if(o)return;c=this.#n[u]=new fr,f!==""&&(c.#e=i.varIndex++)}!o&&f!==""&&t.push([f,c.#e])}else if(c=this.#n[s],!c){if(Object.keys(this.#n).some(f=>f.length>1&&f!==he&&f!==me))throw M;if(o)return;c=this.#n[s]=new fr}c.insert(a,n,t,i,o)}buildRegExpStr(){let n=Object.keys(this.#n).sort(ci).map(t=>{let i=this.#n[t];return(typeof i.#e=="number"?`(${t})@${i.#e}`:li.has(t)?`\\${t}`:t)+i.buildRegExpStr()});return typeof this.#r=="number"&&n.unshift(`#${this.#r}`),n.length===0?"":n.length===1?n[0]:"(?:"+n.join("|")+")"}};var pn=class{#r={varIndex:0};#e=new fn;insert(e,r,n){let t=[],i=[];for(let s=0;;){let a=!1;if(e=e.replace(/\{[^}]+\}/g,l=>{let c=`@\\${s}`;return i[s]=[c,l],s++,a=!0,c}),!a)break}let o=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let s=i.length-1;s>=0;s--){let[a]=i[s];for(let l=o.length-1;l>=0;l--)if(o[l].indexOf(a)!==-1){o[l]=o[l].replace(a,i[s][1]);break}}return this.#e.insert(o,r,t,this.#r,n),t}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let r=0,n=[],t=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(i,o,s)=>o!==void 0?(n[++r]=Number(o),"$()"):(s!==void 0&&(t[Number(s)]=++r),"")),[new RegExp(`^${e}`),n,t]}};var ui=[/^$/,[],Object.create(null)],dn=Object.create(null);function hn(e){return dn[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(r,n)=>n?`\\${n}`:"(?:|/.*)")}$`)}function fi(){dn=Object.create(null)}function pi(e){let r=new pn,n=[];if(e.length===0)return ui;let t=e.map(c=>[!/\*|\/:/.test(c[0]),...c]).sort(([c,f],[u,p])=>c?1:u?-1:f.length-p.length),i=Object.create(null);for(let c=0,f=-1,u=t.length;c<u;c++){let[p,d,m]=t[c];p?i[d]=[m.map(([x])=>[x,Object.create(null)]),je]:f++;let y;try{y=r.insert(d,f,p)}catch(x){throw x===M?new Fe(d):x}p||(n[f]=m.map(([x,v])=>{let g=Object.create(null);for(v-=1;v>=0;v--){let[le,Ye]=y[v];g[le]=Ye}return[x,g]}))}let[o,s,a]=r.buildRegExp();for(let c=0,f=n.length;c<f;c++)for(let u=0,p=n[c].length;u<p;u++){let d=n[c][u]?.[1];if(!d)continue;let m=Object.keys(d);for(let y=0,x=m.length;y<x;y++)d[m[y]]=a[d[m[y]]]}let l=[];for(let c in s)l[c]=n[s[c]];return[o,l,i]}function V(e,r){if(e){for(let n of Object.keys(e).sort((t,i)=>i.length-t.length))if(hn(n).test(r))return[...e[n]]}}var Le=class{name="RegExpRouter";#r;#e;constructor(){this.#r={[A]:Object.create(null)},this.#e={[A]:Object.create(null)}}add(e,r,n){let t=this.#r,i=this.#e;if(!t||!i)throw new Error(_e);t[e]||[t,i].forEach(a=>{a[e]=Object.create(null),Object.keys(a[A]).forEach(l=>{a[e][l]=[...a[A][l]]})}),r==="/*"&&(r="*");let o=(r.match(/\/:/g)||[]).length;if(/\*$/.test(r)){let a=hn(r);e===A?Object.keys(t).forEach(l=>{t[l][r]||=V(t[l],r)||V(t[A],r)||[]}):t[e][r]||=V(t[e],r)||V(t[A],r)||[],Object.keys(t).forEach(l=>{(e===A||e===l)&&Object.keys(t[l]).forEach(c=>{a.test(c)&&t[l][c].push([n,o])})}),Object.keys(i).forEach(l=>{(e===A||e===l)&&Object.keys(i[l]).forEach(c=>a.test(c)&&i[l][c].push([n,o]))});return}let s=Ie(r)||[r];for(let a=0,l=s.length;a<l;a++){let c=s[a];Object.keys(i).forEach(f=>{(e===A||e===f)&&(i[f][c]||=[...V(t[f],c)||V(t[A],c)||[]],i[f][c].push([n,o-l+a+1]))})}}match=ur;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#r)).forEach(r=>{e[r]||=this.#n(r)}),this.#r=this.#e=void 0,fi(),e}#n(e){let r=[],n=e===A;return[this.#r,this.#e].forEach(t=>{let i=t[e]?Object.keys(t[e]).map(o=>[o,t[e][o]]):[];i.length!==0?(n||=!0,r.push(...i)):e!==A&&r.push(...Object.keys(t[A]).map(o=>[o,t[A][o]]))}),n?pi(r):null}};var pr=class{name="SmartRouter";#r=[];#e=[];constructor(e){this.#r=e.routers}add(e,r,n){if(!this.#e)throw new Error(_e);this.#e.push([e,r,n])}match(e,r){if(!this.#e)throw new Error("Fatal error");let n=this.#r,t=this.#e,i=n.length,o=0,s;for(;o<i;o++){let a=n[o];try{for(let l=0,c=t.length;l<c;l++)a.add(...t[l]);s=a.match(e,r)}catch(l){if(l instanceof Fe)continue;throw l}this.match=a.match.bind(a),this.#r=[a],this.#e=void 0;break}if(o===i)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,s}get activeRouter(){if(this.#e||this.#r.length!==1)throw new Error("No active router has been determined yet.");return this.#r[0]}};var ge=Object.create(null),di=e=>{for(let r in e)return!0;return!1},mn=class gn{#r;#e;#n;#o=0;#i=ge;constructor(r,n,t){if(this.#e=t||Object.create(null),this.#r=[],r&&n){let i=Object.create(null);i[r]={handler:n,possibleKeys:[],score:0},this.#r=[i]}this.#n=[]}insert(r,n,t){this.#o=++this.#o;let i=this,o=Vr(n),s=[];for(let a=0,l=o.length;a<l;a++){let c=o[a],f=o[a+1],u=Zr(c,f),p=Array.isArray(u)?u[0]:c;if(p in i.#e){i=i.#e[p],u&&s.push(u[1]);continue}i.#e[p]=new gn,u&&(i.#n.push(u),s.push(u[1])),i=i.#e[p]}return i.#r.push({[r]:{handler:t,possibleKeys:s.filter((a,l,c)=>c.indexOf(a)===l),score:this.#o}}),i}#t(r,n,t,i,o){for(let s=0,a=n.#r.length;s<a;s++){let l=n.#r[s],c=l[t]||l[A],f={};if(c!==void 0&&(c.params=Object.create(null),r.push(c),i!==ge||o&&o!==ge))for(let u=0,p=c.possibleKeys.length;u<p;u++){let d=c.possibleKeys[u],m=f[c.score];c.params[d]=o?.[d]&&!m?o[d]:i[d]??o?.[d],f[c.score]=!0}}}search(r,n){let t=[];this.#i=ge;let o=[this],s=or(n),a=[],l=s.length,c=null;for(let f=0;f<l;f++){let u=s[f],p=f===l-1,d=[];for(let y=0,x=o.length;y<x;y++){let v=o[y],g=v.#e[u];g&&(g.#i=v.#i,p?(g.#e["*"]&&this.#t(t,g.#e["*"],r,v.#i),this.#t(t,g,r,v.#i)):d.push(g));for(let le=0,Ye=v.#n.length;le<Ye;le++){let jr=v.#n[le],_=v.#i===ge?{}:{...v.#i};if(jr==="*"){let q=v.#e["*"];q&&(this.#t(t,q,r,v.#i),q.#i=_,d.push(q));continue}let[It,Nr,ce]=jr;if(!u&&!(ce instanceof RegExp))continue;let P=v.#e[It];if(ce instanceof RegExp){if(c===null){c=new Array(l);let Ee=n[0]==="/"?1:0;for(let ue=0;ue<l;ue++)c[ue]=Ee,Ee+=s[ue].length+1}let q=n.substring(c[f]),Ve=ce.exec(q);if(Ve){if(_[Nr]=Ve[0],this.#t(t,P,r,v.#i,_),di(P.#e)){P.#i=_;let Ee=Ve[0].match(/\//)?.length??0;(a[Ee]||=[]).push(P)}continue}}(ce===!0||ce.test(u))&&(_[Nr]=u,p?(this.#t(t,P,r,_,v.#i),P.#e["*"]&&this.#t(t,P.#e["*"],r,_,v.#i)):(P.#i=_,d.push(P)))}}let m=a.shift();o=m?d.concat(m):d}return t.length>1&&t.sort((f,u)=>f.score-u.score),[t.map(({handler:f,params:u})=>[f,u])]}};var dr=class{name="TrieRouter";#r;constructor(){this.#r=new mn}add(e,r,n){let t=Ie(r);if(t){for(let i=0,o=t.length;i<o;i++)this.#r.insert(e,t[i],n);return}this.#r.insert(e,r,n)}match(e,r){return this.#r.search(e,r)}};var O=class extends cn{constructor(e={}){super(e),this.router=e.router??new pr({routers:[new Le,new dr]})}};var yn=e=>{let n={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...e},t=(o=>typeof o=="string"?o==="*"?n.credentials?s=>s||null:()=>o:s=>o===s?s:null:typeof o=="function"?o:s=>o.includes(s)?s:null)(n.origin),i=(o=>typeof o=="function"?o:Array.isArray(o)?()=>o:()=>[])(n.allowMethods);return async function(s,a){function l(f,u){s.res.headers.set(f,u)}let c=await t(s.req.header("origin")||"",s);if(c&&l("Access-Control-Allow-Origin",c),n.credentials&&l("Access-Control-Allow-Credentials","true"),n.exposeHeaders?.length&&l("Access-Control-Expose-Headers",n.exposeHeaders.join(",")),s.req.method==="OPTIONS"){(n.origin!=="*"||n.credentials)&&l("Vary","Origin"),n.maxAge!=null&&l("Access-Control-Max-Age",n.maxAge.toString());let f=await i(s.req.header("origin")||"",s);f.length&&l("Access-Control-Allow-Methods",f.join(","));let u=n.allowHeaders;if(!u?.length){let p=s.req.header("Access-Control-Request-Headers");p&&(u=p.split(/\s*,\s*/))}return u?.length&&(l("Access-Control-Allow-Headers",u.join(",")),s.res.headers.append("Vary","Access-Control-Request-Headers")),s.res.headers.delete("Content-Length"),s.res.headers.delete("Content-Type"),new Response(null,{headers:s.res.headers,status:204,statusText:"No Content"})}await a(),(n.origin!=="*"||n.credentials)&&s.header("Vary","Origin",{append:!0})}};function hi(){let{process:e,Deno:r}=globalThis;return!(typeof r?.noColor=="boolean"?r.noColor:e!==void 0?"NO_COLOR"in e?.env:!1)}async function xn(){let{navigator:e}=globalThis,r="cloudflare:workers";return!(e!==void 0&&e.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import(r)).env??{})}catch{return!1}})():!hi())}var mi=e=>{let[r,n]=[",","."];return e.map(i=>i.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+r)).join(n)},gi=e=>{let r=Date.now()-e;return mi([r<1e3?r+"ms":Math.round(r/1e3)+"s"])},yi=async e=>{if(await xn())switch(e/100|0){case 5:return`\x1B[31m${e}\x1B[0m`;case 4:return`\x1B[33m${e}\x1B[0m`;case 3:return`\x1B[36m${e}\x1B[0m`;case 2:return`\x1B[32m${e}\x1B[0m`}return`${e}`};async function vn(e,r,n,t,i=0,o){let s=r==="<--"?`${r} ${n} ${t}`:`${r} ${n} ${t} ${await yi(i)} ${o}`;e(s)}var An=(e=console.log)=>async function(n,t){let{method:i,url:o}=n.req,s=o.slice(o.indexOf("/",8));await vn(e,"<--",i,s);let a=Date.now();await t(),await vn(e,"-->",i,s,n.res.status,gi(a))};import{existsSync as xi,readFileSync as vi}from"node:fs";import{dirname as Ai,resolve as bn}from"node:path";import{fileURLToPath as bi}from"node:url";var wn="apv.config.json",H=null;function F(){if(H)return H;let r=[process.env.APV_CONFIG,bn(process.cwd(),wn),bn(Ai(bi(import.meta.url)),"..","..","..",wn)].filter(Boolean);for(let n of r)if(xi(n))try{let t=vi(n,"utf-8"),i=JSON.parse(t);return H={cacheDir:i.cacheDir,localRepos:i.localRepos??{},customTaskDocs:i.customTaskDocs??{}},console.log(`Loaded config from ${n}`),wi(H),H}catch(t){console.warn(`Failed to parse ${n}:`,t)}return H={localRepos:{},customTaskDocs:{}},H}function Rn(e,r,n){let t=F(),i=`${e}/${r}/${n}`;if(t.localRepos[i])return t.localRepos[i];let o=i.toLowerCase();for(let[s,a]of Object.entries(t.localRepos))if(s.toLowerCase()===o)return a}function wi(e){let r=Object.entries(e.localRepos);if(r.length===0){console.log(" No local repo mappings configured");return}console.log(` ${r.length} local repo mapping(s):`);for(let[n,t]of r)console.log(` ${n} \u2192 ${t}`)}function De(e){let r=e.startsWith("/"),n=e.split("/").filter(o=>o!==""&&o!=="."),t=[];for(let o of n)o===".."?t.length>0&&t[t.length-1]!==".."?t.pop():r||t.push(o):t.push(o);let i=t.join("/");return r?`/${i}`:i}function Mn(e){return typeof e>"u"||e===null}function Ci(e){return typeof e=="object"&&e!==null}function Ei(e){return Array.isArray(e)?e:Mn(e)?[]:[e]}function ki(e,r){var n,t,i,o;if(r)for(o=Object.keys(r),n=0,t=o.length;n<t;n+=1)i=o[n],e[i]=r[i];return e}function Si(e,r){var n="",t;for(t=0;t<r;t+=1)n+=e;return n}function Ti(e){return e===0&&Number.NEGATIVE_INFINITY===1/e}var Pi=Mn,Oi=Ci,Ii=Ei,_i=Si,Fi=Ti,ji=ki,w={isNothing:Pi,isObject:Oi,toArray:Ii,repeat:_i,isNegativeZero:Fi,extend:ji};function Hn(e,r){var n="",t=e.reason||"(unknown reason)";return e.mark?(e.mark.name&&(n+='in "'+e.mark.name+'" '),n+="("+(e.mark.line+1)+":"+(e.mark.column+1)+")",!r&&e.mark.snippet&&(n+=`
3
3
 
4
4
  `+e.mark.snippet),t+" "+n):t}function xe(e,r){Error.call(this),this.name="YAMLException",this.reason=e,this.mark=r,this.message=Hn(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}xe.prototype=Object.create(Error.prototype);xe.prototype.constructor=xe;xe.prototype.toString=function(r){return this.name+": "+Hn(this,r)};var E=xe;function hr(e,r,n,t,i){var o="",s="",a=Math.floor(i/2)-1;return t-r>a&&(o=" ... ",r=t-a+o.length),n-t>a&&(s=" ...",n=t+a-s.length),{str:o+e.slice(r,n).replace(/\t/g,"\u2192")+s,pos:t-r+o.length}}function mr(e,r){return w.repeat(" ",r-e.length)+e}function Ni(e,r){if(r=Object.create(r||null),!e.buffer)return null;r.maxLength||(r.maxLength=79),typeof r.indent!="number"&&(r.indent=1),typeof r.linesBefore!="number"&&(r.linesBefore=3),typeof r.linesAfter!="number"&&(r.linesAfter=2);for(var n=/\r?\n|\r|\0/g,t=[0],i=[],o,s=-1;o=n.exec(e.buffer);)i.push(o.index),t.push(o.index+o[0].length),e.position<=o.index&&s<0&&(s=t.length-2);s<0&&(s=t.length-1);var a="",l,c,f=Math.min(e.line+r.linesAfter,i.length).toString().length,u=r.maxLength-(r.indent+f+3);for(l=1;l<=r.linesBefore&&!(s-l<0);l++)c=hr(e.buffer,t[s-l],i[s-l],e.position-(t[s]-t[s-l]),u),a=w.repeat(" ",r.indent)+mr((e.line-l+1).toString(),f)+" | "+c.str+`
5
5
  `+a;for(c=hr(e.buffer,t[s],i[s],e.position,u),a+=w.repeat(" ",r.indent)+mr((e.line+1).toString(),f)+" | "+c.str+`
@@ -30,7 +30,7 @@ import{existsSync as Tt,readFileSync as Pt}from"node:fs";import{extname as Na,jo
30
30
  `+e.slice(i,o),i=o+1),s=a;return l+=`
31
31
  `,e.length-i>r&&s>i?l+=e.slice(i,s)+`
32
32
  `+e.slice(s+1):l+=e.slice(i),l.slice(1)}function Ms(e){for(var r="",n=0,t,i=0;i<e.length;n>=65536?i+=2:i++)n=ye(e,i),t=C[n],!t&&be(n)?(r+=e[i],n>=65536&&(r+=e[i+1])):r+=t||Os(n);return r}function Hs(e,r,n){var t="",i=e.tag,o,s,a;for(o=0,s=n.length;o<s;o+=1)a=n[o],e.replacer&&(a=e.replacer.call(n,String(o),a)),(I(e,r,a,!1,!1)||typeof a>"u"&&I(e,r,null,!1,!1))&&(t!==""&&(t+=","+(e.condenseFlow?"":" ")),t+=e.dump);e.tag=i,e.dump="["+t+"]"}function Dn(e,r,n,t){var i="",o=e.tag,s,a,l;for(s=0,a=n.length;s<a;s+=1)l=n[s],e.replacer&&(l=e.replacer.call(n,String(s),l)),(I(e,r+1,l,!0,!0,!1,!0)||typeof l>"u"&&I(e,r+1,null,!0,!0,!1,!0))&&((!t||i!=="")&&(i+=vr(e,r)),e.dump&&ve===e.dump.charCodeAt(0)?i+="-":i+="- ",i+=e.dump);e.tag=o,e.dump=i||"[]"}function zs(e,r,n){var t="",i=e.tag,o=Object.keys(n),s,a,l,c,f;for(s=0,a=o.length;s<a;s+=1)f="",t!==""&&(f+=", "),e.condenseFlow&&(f+='"'),l=o[s],c=n[l],e.replacer&&(c=e.replacer.call(n,l,c)),I(e,r,l,!1,!1)&&(e.dump.length>1024&&(f+="? "),f+=e.dump+(e.condenseFlow?'"':"")+":"+(e.condenseFlow?"":" "),I(e,r,c,!1,!1)&&(f+=e.dump,t+=f));e.tag=i,e.dump="{"+t+"}"}function Bs(e,r,n,t){var i="",o=e.tag,s=Object.keys(n),a,l,c,f,u,p;if(e.sortKeys===!0)s.sort();else if(typeof e.sortKeys=="function")s.sort(e.sortKeys);else if(e.sortKeys)throw new E("sortKeys must be a boolean or a function");for(a=0,l=s.length;a<l;a+=1)p="",(!t||i!=="")&&(p+=vr(e,r)),c=s[a],f=n[c],e.replacer&&(f=e.replacer.call(n,c,f)),I(e,r+1,c,!0,!0,!0)&&(u=e.tag!==null&&e.tag!=="?"||e.dump&&e.dump.length>1024,u&&(e.dump&&ve===e.dump.charCodeAt(0)?p+="?":p+="? "),p+=e.dump,u&&(p+=vr(e,r)),I(e,r+1,f,!0,u)&&(e.dump&&ve===e.dump.charCodeAt(0)?p+=":":p+=": ",p+=e.dump,i+=p));e.tag=o,e.dump=i||"{}"}function $n(e,r,n){var t,i,o,s,a,l;for(i=n?e.explicitTypes:e.implicitTypes,o=0,s=i.length;o<s;o+=1)if(a=i[o],(a.instanceOf||a.predicate)&&(!a.instanceOf||typeof r=="object"&&r instanceof a.instanceOf)&&(!a.predicate||a.predicate(r))){if(n?a.multi&&a.representName?e.tag=a.representName(r):e.tag=a.tag:e.tag="?",a.represent){if(l=e.styleMap[a.tag]||a.defaultStyle,et.call(a.represent)==="[object Function]")t=a.represent(r,l);else if(rt.call(a.represent,l))t=a.represent[l](r,l);else throw new E("!<"+a.tag+'> tag resolver accepts not "'+l+'" style');e.dump=t}return!0}return!1}function I(e,r,n,t,i,o,s){e.tag=null,e.dump=n,$n(e,n,!1)||$n(e,n,!0);var a=et.call(e.dump),l=t,c;t&&(t=e.flowLevel<0||e.flowLevel>r);var f=a==="[object Object]"||a==="[object Array]",u,p;if(f&&(u=e.duplicates.indexOf(n),p=u!==-1),(e.tag!==null&&e.tag!=="?"||p||e.indent!==2&&r>0)&&(i=!1),p&&e.usedDuplicates[u])e.dump="*ref_"+u;else{if(f&&p&&!e.usedDuplicates[u]&&(e.usedDuplicates[u]=!0),a==="[object Object]")t&&Object.keys(e.dump).length!==0?(Bs(e,r,e.dump,i),p&&(e.dump="&ref_"+u+e.dump)):(zs(e,r,e.dump),p&&(e.dump="&ref_"+u+" "+e.dump));else if(a==="[object Array]")t&&e.dump.length!==0?(e.noArrayIndent&&!s&&r>0?Dn(e,r-1,e.dump,i):Dn(e,r,e.dump,i),p&&(e.dump="&ref_"+u+e.dump)):(Hs(e,r,e.dump),p&&(e.dump="&ref_"+u+" "+e.dump));else if(a==="[object String]")e.tag!=="?"&&Ds(e,e.dump,r,o,l);else{if(a==="[object Undefined]")return!1;if(e.skipInvalid)return!1;throw new E("unacceptable kind of an object to dump "+a)}e.tag!==null&&e.tag!=="?"&&(c=encodeURI(e.tag[0]==="!"?e.tag.slice(1):e.tag).replace(/!/g,"%21"),e.tag[0]==="!"?c="!"+c:c.slice(0,18)==="tag:yaml.org,2002:"?c="!!"+c.slice(18):c="!<"+c+">",e.dump=c+" "+e.dump)}return!0}function Us(e,r){var n=[],t=[],i,o;for(br(e,n,t),i=0,o=t.length;i<o;i+=1)r.duplicates.push(n[t[i]]);r.usedDuplicates=new Array(o)}function br(e,r,n){var t,i,o;if(e!==null&&typeof e=="object")if(i=r.indexOf(e),i!==-1)n.indexOf(i)===-1&&n.push(i);else if(r.push(e),Array.isArray(e))for(i=0,o=e.length;i<o;i+=1)br(e[i],r,n);else for(t=Object.keys(e),i=0,o=t.length;i<o;i+=1)br(e[t[i]],r,n)}function qs(e,r){r=r||{};var n=new _s(r);n.noRefs||Us(e,n);var t=e;return n.replacer&&(t=n.replacer.call({"":t},"",t)),I(n,0,t,!0,!0)?n.dump+`
33
- `:""}var Ws=qs,Gs={dump:Ws};function kr(e,r){return function(){throw new Error("Function yaml."+e+" is removed in js-yaml 4. Use yaml."+r+" instead, which is now safe by default.")}}var _c=Xn.load,Fc=Xn.loadAll,jc=Gs.dump;var Nc=kr("safeLoad","load"),Lc=kr("safeLoadAll","loadAll"),Dc=kr("safeDump","dump");import{DefaultAzureCredential as Qs}from"@azure/identity";var Xs="499b84ac-1321-427f-aa17-267ca6975798/.default",Sr=null;function ea(){return Sr||(Sr=new Qs),Sr}async function ee(){return(await ea().getToken(Xs)).token}var we=class{store=new Map;ttlMs;maxSize;constructor(r,n=1e3){this.ttlMs=r*1e3,this.maxSize=n}get(r){let n=this.store.get(r);if(n){if(Date.now()>n.expiresAt){this.store.delete(r);return}return n.value}}set(r,n){if(this.store.size>=this.maxSize&&!this.store.has(r)){let t=this.store.keys().next().value;t!==void 0&&this.store.delete(t)}this.store.set(r,{value:n,expiresAt:Date.now()+this.ttlMs})}async getOrFetch(r,n){let t=this.get(r);if(t!==void 0)return t;let i=await n();return this.set(r,i),i}get size(){return this.store.size}clear(){this.store.clear()}};var re="7.1",ra=new we(600),na=new we(120),ta=/^[0-9a-f]{7,40}$/i;async function ne(e){let r=await ee(),n=await fetch(e,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});if(!n.ok){let t=await n.text();throw new Error(`Azure DevOps API error (${n.status}): ${t}`)}return n}function te(e,r){return`https://dev.azure.com/${encodeURIComponent(e)}/${encodeURIComponent(r)}/_apis`}function ie(e){return e.startsWith("refs/")||ta.test(e)?e:`refs/heads/${e}`}function oe(e){let r=ie(e);return r.startsWith("refs/heads/")?{version:r.slice(11),versionType:"branch"}:r.startsWith("refs/tags/")?{version:r.slice(10),versionType:"tag"}:{version:r,versionType:"commit"}}async function qe(e,r,n,t){let i=ie(t),o=oe(i);if(o.versionType==="commit")return o.version;let s=`${e}/${r}/${n}/${i}`.toLowerCase();return na.getOrFetch(s,async()=>{let a=i.replace(/^refs\//,""),l=`${te(e,r)}/git/repositories/${encodeURIComponent(n)}/refs?filter=${encodeURIComponent(a)}&api-version=${re}`,u=(await(await ne(l)).json()).value?.find(p=>p.name===i);if(!u?.objectId)throw new Error(`Git ref not found: ${i}`);return u.objectId})}async function pt(e,r){let n=`${te(e,r)}/pipelines?api-version=${re}`;return(await(await ne(n)).json()).value}async function Tr(e,r,n){let t=`${te(e,r)}/build/definitions/${n}?api-version=${re}`,o=await(await ne(t)).json();return{id:o.id,name:o.name,path:o.process?.yamlFilename??o.path,repository:{id:o.repository?.id,name:o.repository?.name,type:o.repository?.type,defaultBranch:o.repository?.defaultBranch}}}async function dt(e,r){let n=`${te(e,r)}/git/repositories?api-version=${re}`;return(await(await ne(n)).json()).value}async function We(e,r,n){let t=`${e}/${r}/${n}`.toLowerCase();return ra.getOrFetch(t,async()=>{let i=`${te(e,r)}/git/repositories/${encodeURIComponent(n)}?api-version=${re}`;return(await ne(i)).json()})}async function ht(e,r,n,t,i){let o=t.startsWith("/")?t:`/${t}`,s=De(o),a=`${te(e,r)}/git/repositories/${encodeURIComponent(n)}/items?scopePath=${encodeURIComponent(s)}&api-version=${re}&$format=text`;if(i){let c=oe(i);a+=`&versionDescriptor.version=${encodeURIComponent(c.version)}&versionDescriptor.versionType=${c.versionType}`}return(await ne(a)).text()}import{existsSync as ia}from"node:fs";import{readFile as oa}from"node:fs/promises";import{join as sa,normalize as mt}from"node:path";async function gt(e,r){let n=r.replace(/\\/g,"/").replace(/^\/+/,""),t=mt(sa(e,n)),i=mt(e);if(!t.startsWith(i))throw new Error(`Path traversal attempt: ${r}`);if(!ia(t))throw new Error(`File not found locally: ${t}`);return oa(t,"utf-8")}import{createHash as aa}from"node:crypto";import{existsSync as yt}from"node:fs";import{mkdir as la,readFile as xt,writeFile as vt}from"node:fs/promises";import{dirname as ca,resolve as se}from"node:path";import{fileURLToPath as ua}from"node:url";function fa(e){if(e)return se(e);let r=F().cacheDir;return r?se(r):se(ca(ua(import.meta.url)),"..","..","..",".cache","ado-file-cache")}function pa(e){return aa("sha256").update(JSON.stringify(e)).digest("hex")}function da(e,r){let n=se(e,r.slice(0,2),r.slice(2,4),r);return{dir:n,metadataPath:se(n,"metadata.json"),contentPath:se(n,"content.txt")}}async function ha(e){if(!yt(e.metadataPath)||!yt(e.contentPath))return null;let[r,n]=await Promise.all([xt(e.metadataPath,"utf-8"),xt(e.contentPath,"utf-8")]);return{metadata:JSON.parse(r),content:n}}async function ma(e,r,n){await la(e.dir,{recursive:!0}),await Promise.all([vt(e.metadataPath,JSON.stringify(r,null,2),"utf-8"),vt(e.contentPath,n,"utf-8")])}async function Re(e){let r=De(e.path.startsWith("/")?e.path:`/${e.path}`),n=ie(e.ref),t=oe(n).versionType,i=fa(e.cacheRoot),o=e.resolveCommitShaFn??qe,s=e.fetchFileContentFn??ht,a=await o(e.org,e.project,e.repoId,n),l={org:e.org,project:e.project,repoId:e.repoId,repoName:e.repoName,path:r,requestedRef:e.ref,normalizedRef:n,refType:t,commitSha:a},c=pa(l),f=da(i,c),u=await ha(f);if(u)return{content:u.content,path:r,repoId:e.repoId,repoName:e.repoName,requestedRef:u.metadata.requestedRef,normalizedRef:u.metadata.normalizedRef,refType:u.metadata.refType,commitSha:u.metadata.commitSha,cache:"hit"};let p=await s(e.org,e.project,e.repoId,r,a),d={...l,fetchedAt:new Date().toISOString()};return await ma(f,d,p),{content:p,path:r,repoId:e.repoId,repoName:e.repoName,requestedRef:e.ref,normalizedRef:n,refType:t,commitSha:a,cache:"miss"}}import{existsSync as Ke}from"node:fs";import{mkdir as ga,readdir as ya,readFile as bt,writeFile as Pr}from"node:fs/promises";import{dirname as xa,join as U,normalize as At,resolve as Ge}from"node:path";import{fileURLToPath as va}from"node:url";var Aa="7.1";async function ba(e,r,n,t){let i=await ee(),o=oe(t),s=`https://dev.azure.com/${encodeURIComponent(e)}/${encodeURIComponent(r)}/_apis/git/repositories/${encodeURIComponent(n)}/items?scopePath=/&download=true&$format=zip&versionDescriptor.version=${encodeURIComponent(o.version)}&versionDescriptor.versionType=${o.versionType}&api-version=${Aa}`,a=await fetch(s,{headers:{Authorization:`Bearer ${i}`}});if(!a.ok){let l=await a.text();throw new Error(`Failed to download repo ZIP (${a.status}): ${l}`)}return Buffer.from(await a.arrayBuffer())}function wa(e){if(e)return Ge(e);let r=F().cacheDir;return r?Ge(r,"..","ado-zip-cache"):Ge(xa(va(import.meta.url)),"..","..","..",".cache","ado-zip-cache")}function wt(e,r,n,t,i){return Ge(e,r.toLowerCase(),n.toLowerCase(),t.toLowerCase(),i.toLowerCase())}function Ra(e,r,n,t,i){let o=wt(e,r,n,t,i);return Ke(U(o,".zip-cache-complete"))}async function Ca(e,r){await ga(r,{recursive:!0});let n=U(r,"__repo.zip");if(await Pr(n,e),await Bun.spawn(["tar","-xf",n,"-C",r],{stdout:"pipe",stderr:"pipe"}).exited!==0)if(process.platform==="win32"){let s=Bun.spawn(["powershell","-NoProfile","-Command",`Expand-Archive -Path '${n}' -DestinationPath '${r}' -Force`],{stdout:"pipe",stderr:"pipe"});if(await s.exited!==0){let l=await new Response(s.stderr).text();throw new Error(`Failed to extract ZIP: ${l}`)}}else{let s=Bun.spawn(["unzip","-o",n,"-d",r],{stdout:"pipe",stderr:"pipe"});if(await s.exited!==0){let l=await new Response(s.stderr).text();throw new Error(`Failed to extract ZIP: ${l}`)}}await Pr(U(r,".zip-cache-complete"),"","utf-8")}async function Rt(e){let r=await ya(e,{withFileTypes:!0}),n=r.filter(i=>i.isDirectory()&&i.name!=="__MACOSX"&&!i.name.startsWith(".")),t=r.filter(i=>i.isFile()&&i.name!=="__repo.zip"&&i.name!==".zip-cache-complete");return n.length===1&&t.length===0?U(e,n[0].name):e}async function Ea(e){let r=U(e,".zip-cache-root");if(Ke(r)){let n=(await bt(r,"utf-8")).trim();if(n&&Ke(n))return n}return Rt(e)}async function Or(e){let r=wa(e.cacheRoot),n=ie(e.ref),t=e.resolveCommitShaFn??qe,i=e.downloadZipFn??ba,o=await t(e.org,e.project,e.repoId,n),s=wt(r,e.org,e.project,e.repoId,o);if(Ra(r,e.org,e.project,e.repoId,o))return{repoDir:await Ea(s),commitSha:o,cache:"hit"};let a=await i(e.org,e.project,e.repoId,n);await(e.extractZipFn??Ca)(a,s);let c=await Rt(s);return await Pr(U(s,".zip-cache-root"),c,"utf-8"),{repoDir:c,commitSha:o,cache:"miss"}}async function Ir(e){let{repoDir:r,commitSha:n,cache:t}=await Or(e),i=e.path.replace(/\\/g,"/").replace(/^\/+/,""),o=At(U(r,i)),s=At(r);if(!o.startsWith(s))throw new Error(`Path traversal attempt: ${e.path}`);if(!Ke(o))throw new Error(`File not found in cached repo: ${i}`);return{content:await bt(o,"utf-8"),cache:t,commitSha:n}}var ae=new O;ae.get("/:org/:project/repos",async e=>{let{org:r,project:n}=e.req.param(),t=await dt(r,n);return e.json(t)});ae.get("/:org/:project/repos/:repoId/file",async e=>{let{org:r,project:n,repoId:t}=e.req.param(),i=e.req.query("path"),o=e.req.query("branch");if(!i)return e.json({error:"path query parameter is required"},400);let s=await We(r,n,t),a=o||s.defaultBranch;try{let c=await Ir({org:r,project:n,repoId:s.id,path:i,ref:a});return e.json({content:c.content,path:i,repoId:s.id,repoName:s.name,branch:a,commitSha:c.commitSha,cache:`zip-${c.cache}`})}catch{}let l=await Re({org:r,project:n,repoId:s.id,repoName:s.name,path:i,ref:a});return e.json({content:l.content,path:l.path,repoId:l.repoId,repoName:l.repoName,branch:l.requestedRef,commitSha:l.commitSha,cache:l.cache})});ae.get("/:org/:project/file-by-repo-name",async e=>{let{org:r,project:n}=e.req.param(),t=e.req.query("repo"),i=e.req.query("path"),o=e.req.query("branch");if(!t||!i)return e.json({error:"repo and path query parameters are required"},400);let s=Rn(r,n,t);if(s)try{let f=await gt(s,i);return e.json({content:f,path:i,repoId:t,repoName:t,branch:o||"local",commitSha:"local",cache:"local"})}catch{}let a=await We(r,n,t);if(!a)return e.json({error:`Repository not found: ${t}`},404);let l=o||a.defaultBranch;try{let f=await Ir({org:r,project:n,repoId:a.id,path:i,ref:l});return e.json({content:f.content,path:i,repoId:a.id,repoName:a.name,branch:l,commitSha:f.commitSha,cache:`zip-${f.cache}`})}catch{}let c=await Re({org:r,project:n,repoId:a.id,repoName:a.name,path:i,ref:l});return e.json({content:c.content,path:c.path,repoId:c.repoId,repoName:c.repoName,branch:c.requestedRef,commitSha:c.commitSha,cache:c.cache})});ae.post("/:org/:project/repos/:repoId/cache",async e=>{let{org:r,project:n,repoId:t}=e.req.param(),i=e.req.query("branch"),o=await We(r,n,t),s=i||o.defaultBranch,a=await Or({org:r,project:n,repoId:o.id,ref:s});return e.json({repoId:o.id,repoName:o.name,branch:s,commitSha:a.commitSha,cache:a.cache})});var Ce=new O;Ce.get("/:org/:project/pipelines",async e=>{let{org:r,project:n}=e.req.param(),t=await pt(r,n);return e.json(t)});Ce.get("/:org/:project/pipelines/:id",async e=>{let{org:r,project:n,id:t}=e.req.param(),i=await Tr(r,n,Number(t));return e.json(i)});Ce.get("/:org/:project/pipelines/:id/yaml",async e=>{let{org:r,project:n,id:t}=e.req.param(),i=await Tr(r,n,Number(t)),o=await Re({org:r,project:n,repoId:i.repository.id,repoName:i.repository.name,path:i.path,ref:i.repository.defaultBranch});return e.json({definition:i,yaml:o.content,branch:o.requestedRef,commitSha:o.commitSha,cache:o.cache})});import{existsSync as Et,mkdirSync as ka,readFileSync as Sa,statSync as Ta,writeFileSync as Pa}from"node:fs";import{dirname as kt,resolve as Ct}from"node:path";import{fileURLToPath as Oa}from"node:url";var _r=new O,Ia=1440*60*1e3;function St(e){let r=Ct(kt(Oa(import.meta.url)),"..","..","..","..");return Ct(r,".cache",`task-schema-${e.toLowerCase()}.json`)}function _a(e){let r=St(e);if(!Et(r))return null;try{let n=Ta(r);return Date.now()-n.mtimeMs>Ia?null:JSON.parse(Sa(r,"utf-8"))}catch{return null}}function Fa(e,r){let n=St(e),t=kt(n);Et(t)||ka(t,{recursive:!0}),Pa(n,JSON.stringify(r,null,2))}function ja(e){let r=e.definitions;if(!r)return[];let i=r.task?.properties?.task?.anyOf;if(!i)return[];let o=[];for(let s of i){let a=s.enum;if(!a?.length)continue;let l=a[0],c=typeof s.description=="string"?s.description:"",f=l.lastIndexOf("@"),u,p;f>0?(u=l.slice(0,f),p=parseInt(l.slice(f+1),10),Number.isNaN(p)&&(p=0)):(u=l,p=0),o.push({name:u,description:c,version:p,inputs:[]})}return o}_r.get("/:org/schema/tasks",async e=>{let{org:r}=e.req.param(),n=_a(r);if(n)return e.json({tasks:n,cached:!0});let t=await ee(),i=`https://dev.azure.com/${encodeURIComponent(r)}/_apis/distributedtask/yamlschema?api-version=7.1`,o=await fetch(i,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!o.ok){let l=await o.text();return e.json({error:`Failed to fetch schema: ${o.status} ${l}`},o.status)}let s=await o.json(),a=ja(s);return Fa(r,a),console.log(`Cached ${a.length} task definitions for org "${r}"`),e.json({tasks:a,cached:!1})});var Da=La(new URL(".",import.meta.url)),Ot=Fr(Da,"web"),$a={".html":"text/html; charset=utf-8",".js":"application/javascript",".css":"text/css",".ttf":"font/ttf",".woff":"font/woff",".woff2":"font/woff2",".svg":"image/svg+xml",".png":"image/png",".json":"application/json"};function Ma(e){let r=Na(e);return $a[r]??"application/octet-stream"}F();var S=new O;S.use("/*",An());S.use("/*",yn({origin:"*"}));S.get("/health",e=>e.json({status:"ok"}));S.get("/api/config/task-docs",e=>{let r=F();return e.json({customTaskDocs:r.customTaskDocs??{}})});S.route("/api",Ce);S.route("/api",ae);S.route("/api",_r);S.all("/api/*",e=>e.json({error:`Not found: ${e.req.path}`},404));S.onError((e,r)=>{if(console.error("Server error:",e.message),e.message.includes("DefaultAzureCredential")||e.message.includes("authentication"))return r.json({error:"Authentication failed. Ensure you are logged in via `az login`.",details:e.message},401);let n=e.message.match(/API error \((\d+)\)/);if(n){let t=Number(n[1]);return r.json({error:e.message},t)}return r.json({error:e.message},500)});S.get("/assets/*",e=>{let r=e.req.path,n=Fr(Ot,r);if(!Tt(n))return e.notFound();let t=Pt(n);return e.body(t,200,{"Content-Type":Ma(r),"Cache-Control":"public, immutable, max-age=31536000"})});S.get("*",e=>{let r=Fr(Ot,"index.html");if(!Tt(r))return e.notFound();let n=Pt(r,"utf-8");return e.html(n)});var Ha=Number(process.env.PORT)||3001;Gr({fetch:S.fetch,port:Ha},e=>{console.log(`APV server listening on http://localhost:${e.port}`)});export{S as app};
33
+ `:""}var Ws=qs,Gs={dump:Ws};function kr(e,r){return function(){throw new Error("Function yaml."+e+" is removed in js-yaml 4. Use yaml."+r+" instead, which is now safe by default.")}}var Oc=Xn.load,Ic=Xn.loadAll,_c=Gs.dump;var Fc=kr("safeLoad","load"),jc=kr("safeLoadAll","loadAll"),Nc=kr("safeDump","dump");import{DefaultAzureCredential as Qs}from"@azure/identity";var Xs="499b84ac-1321-427f-aa17-267ca6975798/.default",Sr=null;function ea(){return Sr||(Sr=new Qs),Sr}async function ee(){return(await ea().getToken(Xs)).token}var we=class{store=new Map;ttlMs;maxSize;constructor(r,n=1e3){this.ttlMs=r*1e3,this.maxSize=n}get(r){let n=this.store.get(r);if(n){if(Date.now()>n.expiresAt){this.store.delete(r);return}return n.value}}set(r,n){if(this.store.size>=this.maxSize&&!this.store.has(r)){let t=this.store.keys().next().value;t!==void 0&&this.store.delete(t)}this.store.set(r,{value:n,expiresAt:Date.now()+this.ttlMs})}async getOrFetch(r,n){let t=this.get(r);if(t!==void 0)return t;let i=await n();return this.set(r,i),i}get size(){return this.store.size}clear(){this.store.clear()}};var re="7.1",ra=new we(600),na=new we(120),ta=/^[0-9a-f]{7,40}$/i;async function ne(e){let r=await ee(),n=await fetch(e,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});if(!n.ok){let t=await n.text();throw new Error(`Azure DevOps API error (${n.status}): ${t}`)}return n}function te(e,r){return`https://dev.azure.com/${encodeURIComponent(e)}/${encodeURIComponent(r)}/_apis`}function ie(e){return e.startsWith("refs/")||ta.test(e)?e:`refs/heads/${e}`}function oe(e){let r=ie(e);return r.startsWith("refs/heads/")?{version:r.slice(11),versionType:"branch"}:r.startsWith("refs/tags/")?{version:r.slice(10),versionType:"tag"}:{version:r,versionType:"commit"}}async function qe(e,r,n,t){let i=ie(t),o=oe(i);if(o.versionType==="commit")return o.version;let s=`${e}/${r}/${n}/${i}`.toLowerCase();return na.getOrFetch(s,async()=>{let a=i.replace(/^refs\//,""),l=`${te(e,r)}/git/repositories/${encodeURIComponent(n)}/refs?filter=${encodeURIComponent(a)}&api-version=${re}`,u=(await(await ne(l)).json()).value?.find(p=>p.name===i);if(!u?.objectId)throw new Error(`Git ref not found: ${i}`);return u.objectId})}async function pt(e,r){let n=`${te(e,r)}/pipelines?api-version=${re}`;return(await(await ne(n)).json()).value}async function Tr(e,r,n){let t=`${te(e,r)}/build/definitions/${n}?api-version=${re}`,o=await(await ne(t)).json();return{id:o.id,name:o.name,path:o.process?.yamlFilename??o.path,repository:{id:o.repository?.id,name:o.repository?.name,type:o.repository?.type,defaultBranch:o.repository?.defaultBranch}}}async function dt(e,r){let n=`${te(e,r)}/git/repositories?api-version=${re}`;return(await(await ne(n)).json()).value}async function We(e,r,n){let t=`${e}/${r}/${n}`.toLowerCase();return ra.getOrFetch(t,async()=>{let i=`${te(e,r)}/git/repositories/${encodeURIComponent(n)}?api-version=${re}`;return(await ne(i)).json()})}async function ht(e,r,n,t,i){let o=t.startsWith("/")?t:`/${t}`,s=De(o),a=`${te(e,r)}/git/repositories/${encodeURIComponent(n)}/items?scopePath=${encodeURIComponent(s)}&api-version=${re}&$format=text`;if(i){let c=oe(i);a+=`&versionDescriptor.version=${encodeURIComponent(c.version)}&versionDescriptor.versionType=${c.versionType}`}return(await ne(a)).text()}import{existsSync as ia}from"node:fs";import{readFile as oa}from"node:fs/promises";import{join as sa,normalize as mt}from"node:path";async function gt(e,r){let n=r.replace(/\\/g,"/").replace(/^\/+/,""),t=mt(sa(e,n)),i=mt(e);if(!t.startsWith(i))throw new Error(`Path traversal attempt: ${r}`);if(!ia(t))throw new Error(`File not found locally: ${t}`);return oa(t,"utf-8")}import{createHash as aa}from"node:crypto";import{existsSync as yt}from"node:fs";import{mkdir as la,readFile as xt,writeFile as vt}from"node:fs/promises";import{homedir as ca}from"node:os";import{resolve as se}from"node:path";function ua(e){if(e)return se(e);let r=F().cacheDir;return r?se(r):se(ca(),".apv","cache","ado-file-cache")}function fa(e){return aa("sha256").update(JSON.stringify(e)).digest("hex")}function pa(e,r){let n=se(e,r.slice(0,2),r.slice(2,4),r);return{dir:n,metadataPath:se(n,"metadata.json"),contentPath:se(n,"content.txt")}}async function da(e){if(!yt(e.metadataPath)||!yt(e.contentPath))return null;let[r,n]=await Promise.all([xt(e.metadataPath,"utf-8"),xt(e.contentPath,"utf-8")]);return{metadata:JSON.parse(r),content:n}}async function ha(e,r,n){await la(e.dir,{recursive:!0}),await Promise.all([vt(e.metadataPath,JSON.stringify(r,null,2),"utf-8"),vt(e.contentPath,n,"utf-8")])}async function Re(e){let r=De(e.path.startsWith("/")?e.path:`/${e.path}`),n=ie(e.ref),t=oe(n).versionType,i=ua(e.cacheRoot),o=e.resolveCommitShaFn??qe,s=e.fetchFileContentFn??ht,a=await o(e.org,e.project,e.repoId,n),l={org:e.org,project:e.project,repoId:e.repoId,repoName:e.repoName,path:r,requestedRef:e.ref,normalizedRef:n,refType:t,commitSha:a},c=fa(l),f=pa(i,c),u=await da(f);if(u)return{content:u.content,path:r,repoId:e.repoId,repoName:e.repoName,requestedRef:u.metadata.requestedRef,normalizedRef:u.metadata.normalizedRef,refType:u.metadata.refType,commitSha:u.metadata.commitSha,cache:"hit"};let p=await s(e.org,e.project,e.repoId,r,a),d={...l,fetchedAt:new Date().toISOString()};return await ha(f,d,p),{content:p,path:r,repoId:e.repoId,repoName:e.repoName,requestedRef:e.ref,normalizedRef:n,refType:t,commitSha:a,cache:"miss"}}import{existsSync as Ke}from"node:fs";import{mkdir as ma,readdir as ga,readFile as bt,writeFile as Pr}from"node:fs/promises";import{homedir as ya}from"node:os";import{join as U,normalize as At,resolve as Ge}from"node:path";var xa="7.1";async function va(e,r,n,t){let i=await ee(),o=oe(t),s=`https://dev.azure.com/${encodeURIComponent(e)}/${encodeURIComponent(r)}/_apis/git/repositories/${encodeURIComponent(n)}/items?scopePath=/&download=true&$format=zip&versionDescriptor.version=${encodeURIComponent(o.version)}&versionDescriptor.versionType=${o.versionType}&api-version=${xa}`,a=await fetch(s,{headers:{Authorization:`Bearer ${i}`}});if(!a.ok){let l=await a.text();throw new Error(`Failed to download repo ZIP (${a.status}): ${l}`)}return Buffer.from(await a.arrayBuffer())}function Aa(e){if(e)return Ge(e);let r=F().cacheDir;return r?Ge(r,"ado-zip-cache"):Ge(ya(),".apv","cache","ado-zip-cache")}function wt(e,r,n,t,i){return Ge(e,r.toLowerCase(),n.toLowerCase(),t.toLowerCase(),i.toLowerCase())}function ba(e,r,n,t,i){let o=wt(e,r,n,t,i);return Ke(U(o,".zip-cache-complete"))}async function wa(e,r){await ma(r,{recursive:!0});let n=U(r,"__repo.zip");if(await Pr(n,e),await Bun.spawn(["tar","-xf",n,"-C",r],{stdout:"pipe",stderr:"pipe"}).exited!==0)if(process.platform==="win32"){let s=Bun.spawn(["powershell","-NoProfile","-Command",`Expand-Archive -Path '${n}' -DestinationPath '${r}' -Force`],{stdout:"pipe",stderr:"pipe"});if(await s.exited!==0){let l=await new Response(s.stderr).text();throw new Error(`Failed to extract ZIP: ${l}`)}}else{let s=Bun.spawn(["unzip","-o",n,"-d",r],{stdout:"pipe",stderr:"pipe"});if(await s.exited!==0){let l=await new Response(s.stderr).text();throw new Error(`Failed to extract ZIP: ${l}`)}}await Pr(U(r,".zip-cache-complete"),"","utf-8")}async function Rt(e){let r=await ga(e,{withFileTypes:!0}),n=r.filter(i=>i.isDirectory()&&i.name!=="__MACOSX"&&!i.name.startsWith(".")),t=r.filter(i=>i.isFile()&&i.name!=="__repo.zip"&&i.name!==".zip-cache-complete");return n.length===1&&t.length===0?U(e,n[0].name):e}async function Ra(e){let r=U(e,".zip-cache-root");if(Ke(r)){let n=(await bt(r,"utf-8")).trim();if(n&&Ke(n))return n}return Rt(e)}async function Or(e){let r=Aa(e.cacheRoot),n=ie(e.ref),t=e.resolveCommitShaFn??qe,i=e.downloadZipFn??va,o=await t(e.org,e.project,e.repoId,n),s=wt(r,e.org,e.project,e.repoId,o);if(ba(r,e.org,e.project,e.repoId,o))return{repoDir:await Ra(s),commitSha:o,cache:"hit"};let a=await i(e.org,e.project,e.repoId,n);await(e.extractZipFn??wa)(a,s);let c=await Rt(s);return await Pr(U(s,".zip-cache-root"),c,"utf-8"),{repoDir:c,commitSha:o,cache:"miss"}}async function Ir(e){let{repoDir:r,commitSha:n,cache:t}=await Or(e),i=e.path.replace(/\\/g,"/").replace(/^\/+/,""),o=At(U(r,i)),s=At(r);if(!o.startsWith(s))throw new Error(`Path traversal attempt: ${e.path}`);if(!Ke(o))throw new Error(`File not found in cached repo: ${i}`);return{content:await bt(o,"utf-8"),cache:t,commitSha:n}}var ae=new O;ae.get("/:org/:project/repos",async e=>{let{org:r,project:n}=e.req.param(),t=await dt(r,n);return e.json(t)});ae.get("/:org/:project/repos/:repoId/file",async e=>{let{org:r,project:n,repoId:t}=e.req.param(),i=e.req.query("path"),o=e.req.query("branch");if(!i)return e.json({error:"path query parameter is required"},400);let s=await We(r,n,t),a=o||s.defaultBranch;try{let c=await Ir({org:r,project:n,repoId:s.id,path:i,ref:a});return e.json({content:c.content,path:i,repoId:s.id,repoName:s.name,branch:a,commitSha:c.commitSha,cache:`zip-${c.cache}`})}catch{}let l=await Re({org:r,project:n,repoId:s.id,repoName:s.name,path:i,ref:a});return e.json({content:l.content,path:l.path,repoId:l.repoId,repoName:l.repoName,branch:l.requestedRef,commitSha:l.commitSha,cache:l.cache})});ae.get("/:org/:project/file-by-repo-name",async e=>{let{org:r,project:n}=e.req.param(),t=e.req.query("repo"),i=e.req.query("path"),o=e.req.query("branch");if(!t||!i)return e.json({error:"repo and path query parameters are required"},400);let s=Rn(r,n,t);if(s)try{let f=await gt(s,i);return e.json({content:f,path:i,repoId:t,repoName:t,branch:o||"local",commitSha:"local",cache:"local"})}catch{}let a=await We(r,n,t);if(!a)return e.json({error:`Repository not found: ${t}`},404);let l=o||a.defaultBranch;try{let f=await Ir({org:r,project:n,repoId:a.id,path:i,ref:l});return e.json({content:f.content,path:i,repoId:a.id,repoName:a.name,branch:l,commitSha:f.commitSha,cache:`zip-${f.cache}`})}catch{}let c=await Re({org:r,project:n,repoId:a.id,repoName:a.name,path:i,ref:l});return e.json({content:c.content,path:c.path,repoId:c.repoId,repoName:c.repoName,branch:c.requestedRef,commitSha:c.commitSha,cache:c.cache})});ae.post("/:org/:project/repos/:repoId/cache",async e=>{let{org:r,project:n,repoId:t}=e.req.param(),i=e.req.query("branch"),o=await We(r,n,t),s=i||o.defaultBranch,a=await Or({org:r,project:n,repoId:o.id,ref:s});return e.json({repoId:o.id,repoName:o.name,branch:s,commitSha:a.commitSha,cache:a.cache})});var Ce=new O;Ce.get("/:org/:project/pipelines",async e=>{let{org:r,project:n}=e.req.param(),t=await pt(r,n);return e.json(t)});Ce.get("/:org/:project/pipelines/:id",async e=>{let{org:r,project:n,id:t}=e.req.param(),i=await Tr(r,n,Number(t));return e.json(i)});Ce.get("/:org/:project/pipelines/:id/yaml",async e=>{let{org:r,project:n,id:t}=e.req.param(),i=await Tr(r,n,Number(t)),o=await Re({org:r,project:n,repoId:i.repository.id,repoName:i.repository.name,path:i.path,ref:i.repository.defaultBranch});return e.json({definition:i,yaml:o.content,branch:o.requestedRef,commitSha:o.commitSha,cache:o.cache})});import{existsSync as Et,mkdirSync as Ca,readFileSync as Ea,statSync as ka,writeFileSync as Sa}from"node:fs";import{dirname as kt,resolve as Ct}from"node:path";import{fileURLToPath as Ta}from"node:url";var _r=new O,Pa=1440*60*1e3;function St(e){let r=Ct(kt(Ta(import.meta.url)),"..","..","..","..");return Ct(r,".cache",`task-schema-${e.toLowerCase()}.json`)}function Oa(e){let r=St(e);if(!Et(r))return null;try{let n=ka(r);return Date.now()-n.mtimeMs>Pa?null:JSON.parse(Ea(r,"utf-8"))}catch{return null}}function Ia(e,r){let n=St(e),t=kt(n);Et(t)||Ca(t,{recursive:!0}),Sa(n,JSON.stringify(r,null,2))}function _a(e){let r=e.definitions;if(!r)return[];let i=r.task?.properties?.task?.anyOf;if(!i)return[];let o=[];for(let s of i){let a=s.enum;if(!a?.length)continue;let l=a[0],c=typeof s.description=="string"?s.description:"",f=l.lastIndexOf("@"),u,p;f>0?(u=l.slice(0,f),p=parseInt(l.slice(f+1),10),Number.isNaN(p)&&(p=0)):(u=l,p=0),o.push({name:u,description:c,version:p,inputs:[]})}return o}_r.get("/:org/schema/tasks",async e=>{let{org:r}=e.req.param(),n=Oa(r);if(n)return e.json({tasks:n,cached:!0});let t=await ee(),i=`https://dev.azure.com/${encodeURIComponent(r)}/_apis/distributedtask/yamlschema?api-version=7.1`,o=await fetch(i,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!o.ok){let l=await o.text();return e.json({error:`Failed to fetch schema: ${o.status} ${l}`},o.status)}let s=await o.json(),a=_a(s);return Ia(r,a),console.log(`Cached ${a.length} task definitions for org "${r}"`),e.json({tasks:a,cached:!1})});var Na=ja(new URL(".",import.meta.url)),Ot=Fr(Na,"web"),La={".html":"text/html; charset=utf-8",".js":"application/javascript",".css":"text/css",".ttf":"font/ttf",".woff":"font/woff",".woff2":"font/woff2",".svg":"image/svg+xml",".png":"image/png",".json":"application/json"};function Da(e){let r=Fa(e);return La[r]??"application/octet-stream"}F();var S=new O;S.use("/*",An());S.use("/*",yn({origin:"*"}));S.get("/health",e=>e.json({status:"ok"}));S.get("/api/config/task-docs",e=>{let r=F();return e.json({customTaskDocs:r.customTaskDocs??{}})});S.route("/api",Ce);S.route("/api",ae);S.route("/api",_r);S.all("/api/*",e=>e.json({error:`Not found: ${e.req.path}`},404));S.onError((e,r)=>{if(console.error("Server error:",e.message),e.message.includes("DefaultAzureCredential")||e.message.includes("authentication"))return r.json({error:"Authentication failed. Ensure you are logged in via `az login`.",details:e.message},401);let n=e.message.match(/API error \((\d+)\)/);if(n){let t=Number(n[1]);return r.json({error:e.message},t)}return r.json({error:e.message},500)});S.get("/assets/*",e=>{let r=e.req.path,n=Fr(Ot,r);if(!Tt(n))return e.notFound();let t=Pt(n);return e.body(t,200,{"Content-Type":Da(r),"Cache-Control":"public, immutable, max-age=31536000"})});S.get("*",e=>{let r=Fr(Ot,"index.html");if(!Tt(r))return e.notFound();let n=Pt(r,"utf-8");return e.html(n)});var $a=Number(process.env.PORT)||3001;Gr({fetch:S.fetch,port:$a},e=>{console.log(`APV server listening on http://localhost:${e.port}`)});export{S as app};
34
34
  /*! Bundled license information:
35
35
 
36
36
  js-yaml/dist/js-yaml.mjs: