@buddysh/buddy 0.11.11 → 0.11.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/bin/cli.ts +5 -8
  3. package/dist/bin/cli.js +74 -74
  4. package/dist/{chunk-raj75r4h.js → chunk-01d81hn0.js} +1 -1
  5. package/dist/{chunk-z05djfac.js → chunk-028354j6.js} +7 -7
  6. package/dist/chunk-0w6jmcsh.js +2 -0
  7. package/dist/{chunk-3c114myc.js → chunk-1tdkpeva.js} +1 -1
  8. package/dist/{chunk-2e4e6zjs.js → chunk-1znpbjrv.js} +1 -1
  9. package/dist/{chunk-0g4ybxwj.js → chunk-2b07w74s.js} +1 -1
  10. package/dist/{chunk-42xvqxdw.js → chunk-2z85fqdp.js} +2 -2
  11. package/dist/{chunk-b9szrnxw.js → chunk-34vracy4.js} +1 -1
  12. package/dist/chunk-3578axtf.js +2 -0
  13. package/dist/{chunk-2jjrxgs1.js → chunk-37zd94a7.js} +2 -2
  14. package/dist/{chunk-pq115qkn.js → chunk-3a5gcj3y.js} +1 -1
  15. package/dist/{chunk-1xe0960b.js → chunk-3a63hke8.js} +1 -1
  16. package/dist/{chunk-dsnd6ndd.js → chunk-3nn2j810.js} +1 -1
  17. package/dist/chunk-3r0jb90q.js +2 -0
  18. package/dist/{chunk-ycbk7tg9.js → chunk-4fh7w98z.js} +1 -1
  19. package/dist/{chunk-sxfk3naz.js → chunk-4kyxrwxn.js} +1 -1
  20. package/dist/{chunk-vtr2vbk0.js → chunk-4qv88x27.js} +1 -1
  21. package/dist/chunk-4x1mv7qj.js +2 -0
  22. package/dist/{chunk-d9m42wym.js → chunk-54hdfa8r.js} +1 -1
  23. package/dist/{chunk-va3k91tf.js → chunk-5sh69bkj.js} +1 -1
  24. package/dist/{chunk-g0x10e1d.js → chunk-66nntsnf.js} +1 -1
  25. package/dist/chunk-6hyrj0b5.js +2 -0
  26. package/dist/{chunk-mt53v4sx.js → chunk-6np84pfr.js} +1 -1
  27. package/dist/{chunk-hc651afv.js → chunk-6prz7chv.js} +1 -1
  28. package/dist/{chunk-bsh3kp53.js → chunk-6qw89f68.js} +1 -1
  29. package/dist/{chunk-mpb1g0xk.js → chunk-7b156stw.js} +1 -1
  30. package/dist/{chunk-2z9pkk1y.js → chunk-7t8s2mcf.js} +1 -1
  31. package/dist/{chunk-25sjd6zk.js → chunk-83srz04v.js} +4 -4
  32. package/dist/chunk-86xv8x00.js +2 -0
  33. package/dist/chunk-87k997bm.js +2 -0
  34. package/dist/chunk-8jvmqdvc.js +2 -0
  35. package/dist/{chunk-gpjde0j6.js → chunk-92gh2n65.js} +1 -1
  36. package/dist/{chunk-54er1whp.js → chunk-94tnmc7j.js} +2 -2
  37. package/dist/{chunk-csqh2ca4.js → chunk-9n1kth4b.js} +1 -1
  38. package/dist/{chunk-z4btj7s0.js → chunk-a6hv92fx.js} +1 -1
  39. package/dist/{chunk-rr8apsh5.js → chunk-awjm9n45.js} +1 -1
  40. package/dist/{chunk-2hb8dan0.js → chunk-bgw39afd.js} +1 -1
  41. package/dist/{chunk-wt83nzn3.js → chunk-bstgsak0.js} +1 -1
  42. package/dist/{chunk-33h1me7n.js → chunk-c4cj24qm.js} +2 -2
  43. package/dist/chunk-c8xfj0m5.js +2 -0
  44. package/dist/{chunk-08daxhzx.js → chunk-c9266b5x.js} +1 -1
  45. package/dist/{chunk-4kr6evh6.js → chunk-ce26jarj.js} +1 -1
  46. package/dist/chunk-cj5fkyxv.js +2 -0
  47. package/dist/{chunk-7c1284fb.js → chunk-cx89kty3.js} +1 -1
  48. package/dist/chunk-d3m5kcpp.js +2 -0
  49. package/dist/{chunk-vs68hsbp.js → chunk-dg2q6egm.js} +1 -1
  50. package/dist/{chunk-8swwcx7w.js → chunk-dkhherd0.js} +1 -1
  51. package/dist/{chunk-qdr900z7.js → chunk-dq681xgx.js} +1 -1
  52. package/dist/{chunk-ktn47bq8.js → chunk-drmk6r1m.js} +1 -1
  53. package/dist/{chunk-5jvde2as.js → chunk-ebnc6980.js} +1 -1
  54. package/dist/{chunk-gweqk008.js → chunk-edm12hnb.js} +1 -1
  55. package/dist/{chunk-naz864cb.js → chunk-eh71jv8w.js} +1 -1
  56. package/dist/{chunk-40pvn33p.js → chunk-ekf183jk.js} +1 -1
  57. package/dist/{chunk-jhz202wk.js → chunk-fgec04jx.js} +1 -1
  58. package/dist/chunk-fzfgvt8s.js +2 -0
  59. package/dist/{chunk-dd895pm0.js → chunk-gcwg4b2w.js} +1 -1
  60. package/dist/{chunk-w55x2g9n.js → chunk-gjhxc6ma.js} +1 -1
  61. package/dist/{chunk-q7y8dvbz.js → chunk-hc2pdv4j.js} +1 -1
  62. package/dist/chunk-j21m6rf6.js +2 -0
  63. package/dist/{chunk-0m1z85m9.js → chunk-j6bejzk9.js} +1 -1
  64. package/dist/{chunk-vpw7adwd.js → chunk-j6geg3qt.js} +1 -1
  65. package/dist/{chunk-ry5zh9cx.js → chunk-j7qktvpg.js} +1 -1
  66. package/dist/chunk-jjwxbcfz.js +2 -0
  67. package/dist/{chunk-nkztawjh.js → chunk-jkn2sdm0.js} +1 -1
  68. package/dist/{chunk-apdrg3r7.js → chunk-jn3t9v6d.js} +1 -1
  69. package/dist/{chunk-b3s185kp.js → chunk-k907b533.js} +1 -1
  70. package/dist/{chunk-zk8zdv23.js → chunk-kjhqe26r.js} +1 -1
  71. package/dist/chunk-kkh3q0s2.js +2 -0
  72. package/dist/chunk-ksngk47a.js +2 -0
  73. package/dist/{chunk-y3w8h4sy.js → chunk-m00hfvnp.js} +1 -1
  74. package/dist/{chunk-65by8f14.js → chunk-m8brd9b5.js} +1 -1
  75. package/dist/{chunk-wjfw6rx8.js → chunk-ma01xp3y.js} +1 -1
  76. package/dist/{chunk-5pheqk23.js → chunk-mg67hhgj.js} +1 -1
  77. package/dist/{chunk-62j8q7sg.js → chunk-n5mz7csc.js} +1 -1
  78. package/dist/chunk-nd780ymh.js +2 -0
  79. package/dist/chunk-ngzrrqy2.js +2 -0
  80. package/dist/{chunk-afstgmb4.js → chunk-nn5rzwty.js} +1 -1
  81. package/dist/{chunk-esm5jjgf.js → chunk-p16pnhj3.js} +1 -1
  82. package/dist/{chunk-k3r7v3dp.js → chunk-p2h2z6d3.js} +2 -2
  83. package/dist/{chunk-yqfwvk9z.js → chunk-pg32mf9k.js} +1 -1
  84. package/dist/{chunk-5vekh5w1.js → chunk-q7709hwk.js} +1 -1
  85. package/dist/{chunk-vmt1bed1.js → chunk-q99xd3m5.js} +1 -1
  86. package/dist/{chunk-a3zgenkh.js → chunk-qcvtp2mt.js} +1 -1
  87. package/dist/{chunk-7b4jsg36.js → chunk-qjzpzd7j.js} +1 -1
  88. package/dist/{chunk-0rbxek2f.js → chunk-rwz433q2.js} +2 -2
  89. package/dist/{chunk-gzkwszsg.js → chunk-s5czyzje.js} +3 -3
  90. package/dist/{chunk-pegk4jhq.js → chunk-s609kp6h.js} +1 -1
  91. package/dist/{chunk-kbvj6qxc.js → chunk-s82adeq9.js} +1 -1
  92. package/dist/{chunk-59993g25.js → chunk-sn0qr6q7.js} +1 -1
  93. package/dist/{chunk-nbyxgt9c.js → chunk-t5hq4ke1.js} +1 -1
  94. package/dist/{chunk-77qe887p.js → chunk-t879n4ab.js} +1 -1
  95. package/dist/chunk-tmzd2p2n.js +2 -0
  96. package/dist/chunk-tqsrr90t.js +2 -0
  97. package/dist/{chunk-be7g40yf.js → chunk-v808b36p.js} +1 -1
  98. package/dist/chunk-v9avf6sc.js +2 -0
  99. package/dist/chunk-w2vsf1q0.js +2 -0
  100. package/dist/{chunk-89jytkd6.js → chunk-wf1jcxtr.js} +1 -1
  101. package/dist/chunk-wjmrh1nv.js +2 -0
  102. package/dist/{chunk-jsf2322c.js → chunk-x9qhsyp6.js} +2 -2
  103. package/dist/chunk-x9vpk4kk.js +7 -0
  104. package/dist/{chunk-h8wskvjv.js → chunk-xhn5331s.js} +1 -1
  105. package/dist/{chunk-b6a5txek.js → chunk-y1d6e0ye.js} +1 -1
  106. package/dist/{chunk-kq0n3x2e.js → chunk-ym9475ry.js} +1 -1
  107. package/dist/chunk-yrr9hqvw.js +2 -0
  108. package/dist/chunk-zcsahxe6.js +2 -0
  109. package/dist/chunk-zpgm9yzy.js +2 -0
  110. package/dist/{chunk-ddky3026.js → chunk-zrec546r.js} +1 -1
  111. package/dist/{chunk-x1w6q9tk.js → chunk-zwtx6vn3.js} +1 -1
  112. package/dist/chunk-zy49dwqk.js +44 -0
  113. package/dist/src/index.js +1 -1
  114. package/dist/src/pr/pr-manifest.d.ts +10 -0
  115. package/dist/src/setup.js +1 -1
  116. package/package.json +1 -1
  117. package/dist/chunk-0m6b7bac.js +0 -2
  118. package/dist/chunk-0sm25gee.js +0 -2
  119. package/dist/chunk-18xha279.js +0 -2
  120. package/dist/chunk-1tx3t9ke.js +0 -2
  121. package/dist/chunk-1w1h2tsf.js +0 -2
  122. package/dist/chunk-2h90wcxe.js +0 -2
  123. package/dist/chunk-64kt1w23.js +0 -2
  124. package/dist/chunk-6gdenphk.js +0 -2
  125. package/dist/chunk-6pcnvdj9.js +0 -2
  126. package/dist/chunk-7m1ab6p8.js +0 -2
  127. package/dist/chunk-83yea9pk.js +0 -2
  128. package/dist/chunk-9exbsfz5.js +0 -2
  129. package/dist/chunk-b59zbkfx.js +0 -2
  130. package/dist/chunk-ffbbc38r.js +0 -2
  131. package/dist/chunk-hmymd6m2.js +0 -2
  132. package/dist/chunk-knpdntnh.js +0 -7
  133. package/dist/chunk-m1zv8db4.js +0 -2
  134. package/dist/chunk-m63hkte2.js +0 -2
  135. package/dist/chunk-njrezpsw.js +0 -2
  136. package/dist/chunk-qxf3f6ks.js +0 -2
  137. package/dist/chunk-rphwf28s.js +0 -2
  138. package/dist/chunk-sd5xqd44.js +0 -2
  139. package/dist/chunk-tbt8btwf.js +0 -2
  140. package/dist/chunk-tjvvb919.js +0 -2
  141. package/dist/chunk-vpsvtb9v.js +0 -2
  142. package/dist/chunk-xdrvb89m.js +0 -44
  143. package/dist/chunk-xxwevpnr.js +0 -2
  144. package/dist/chunk-yf01hyxn.js +0 -2
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Jh as O}from"./chunk-b9szrnxw.js";import{Ph as q}from"./chunk-x1w6q9tk.js";import{el as p}from"./chunk-kbvj6qxc.js";var T=/(?:^|[-_.])(?:rc|alpha|beta|pre|dev|nightly|canary|snapshot|edge|next)\d*(?:$|[-_.])/i;function B(j){let z=/^v?(\d+(?:\.\d+)*)(.*)$/.exec(j.trim());if(!z)return null;let[,G,Q]=z,J=T.test(Q),Y=Q.replace(T,(Z)=>{return Z.endsWith("-")||Z.endsWith("_")||Z.endsWith(".")?"-":""}).replace(/^[-_.]/,"").toLowerCase();return{raw:j,version:G.split(".").map(Number),suffix:Y,prerelease:J}}function x(j,z){for(let G=0;G<Math.max(j.length,z.length);G++){let Q=(j[G]??0)-(z[G]??0);if(Q!==0)return Q}return j.length-z.length}function k(j,z){let G=(Q)=>/^[a-z]+/.exec(Q)?.[0]??Q;return G(j)===G(z)}function b(j,z,G={}){let Q=B(j);if(!Q)return null;let J=z.map(B).filter((Y)=>Y!==null).filter((Y)=>G.includePrerelease?!0:!Y.prerelease).filter((Y)=>k(Y.suffix,Q.suffix)).filter((Y)=>Y.version.length===Q.version.length).filter((Y)=>x(Y.version,Q.version)>0);if(J.length===0)return null;return J.sort((Y,Z)=>x(Z.version,Y.version)),J[0].raw}function l(j,z){let G=B(j),Q=B(z);if(!G||!Q)return"patch";if((Q.version[0]??0)!==(G.version[0]??0))return"major";if((Q.version[1]??0)!==(G.version[1]??0))return"minor";return"patch"}import P from"process";var v="registry-1.docker.io";function U(j){let z=j.trim(),G,Q=z.indexOf("@");if(Q!==-1)G=z.slice(Q+1),z=z.slice(0,Q);let J=z.indexOf("/"),Y=J===-1?"":z.slice(0,J),Z=Y==="localhost"||Y.includes(".")||Y.includes(":"),X=Z?Y:"docker.io",$=Z?z.slice(J+1):z,K="latest",S=$.lastIndexOf("/"),W=$.indexOf(":",S+1);if(W!==-1)K=$.slice(W+1),$=$.slice(0,W);let M=X==="docker.io"&&!$.includes("/")?`library/${$}`:$;return{registry:X,repository:M,tag:K,...G?{digest:G}:{}}}function i(j){let z=j.registry==="docker.io"?j.repository.replace(/^library\//,""):`${j.registry}/${j.repository}`;return j.digest?`${z}:${j.tag}@${j.digest}`:`${z}:${j.tag}`}function C(j){return j==="docker.io"?v:j}function y(j,z,G=P.env){let Q=z?.[j];if(Q?.tokenEnv){let J=G[Q.tokenEnv]?.trim();if(J)return{token:J}}if(Q?.username&&Q.passwordEnv){let J=G[Q.passwordEnv]?.trim();if(J)return{username:Q.username,password:J}}if(j==="ghcr.io"){let J=G.GITHUB_TOKEN?.trim()||G.BUDDY_TOKEN?.trim();if(J)return{username:"buddy",password:J}}if(j==="docker.io"){let J=G.DOCKERHUB_TOKEN?.trim()||G.DOCKER_TOKEN?.trim();if(J)return{username:G.DOCKERHUB_USERNAME?.trim()||"buddy",password:J}}return null}function R(j){if(!j?.toLowerCase().startsWith("bearer "))return null;let z={};for(let G of j.slice(7).matchAll(/(\w+)="([^"]*)"/g))z[G[1]]=G[2];return z.realm?{realm:z.realm,...z.service?{service:z.service}:{},...z.scope?{scope:z.scope}:{}}:null}function u(j,z){let G=new URL(j.realm);if(j.service)G.searchParams.set("service",j.service);return G.searchParams.set("scope",j.scope??`repository:${z}:pull`),G.toString()}class H{options;logger;tokens=new Map;constructor(j={}){this.options=j;this.logger=j.logger??q()}async listTags(j){let z=C(j.registry),G=this.options.maxPages??10,Q=[],J=`https://${z}/v2/${j.repository}/tags/list?n=100`;for(let Y=0;Y<G&&J;Y++){let Z=await this.authorizedFetch(J,j);if(!Z?.ok){if(Y===0)this.logger.debug(`Could not list tags for ${j.repository} on ${j.registry}: ${Z?.status??"no response"}`);break}let X=await Z.json().catch(()=>null);if(Array.isArray(X?.tags))Q.push(...X.tags);J=h(Z.headers.get("link"),z)}return Q}async resolveDigest(j){let G=`https://${C(j.registry)}/v2/${j.repository}/manifests/${j.tag}`,Q=await this.authorizedFetch(G,j,{method:"HEAD",headers:{Accept:["application/vnd.oci.image.index.v1+json","application/vnd.oci.image.manifest.v1+json","application/vnd.docker.distribution.manifest.list.v2+json","application/vnd.docker.distribution.manifest.v2+json"].join(", ")}});return Q?.ok?Q.headers.get("docker-content-digest"):null}async authorizedFetch(j,z,G={}){let Q={"User-Agent":"buddy",...G.headers},J=this.tokens.get(I(z));if(J)Q.Authorization=`Bearer ${J}`;let Y=()=>O(j,{...G,headers:Q}).catch(()=>null),Z=await Y();if(Z?.status!==401||J!==void 0)return Z;let X=R(Z.headers.get("www-authenticate"));if(!X)return Z;let $=await this.fetchToken(X,z);if(!$)return Z;return this.tokens.set(I(z),$),Q.Authorization=`Bearer ${$}`,Z=await Y(),Z}async fetchToken(j,z){let G=y(z.registry,this.options.registries,this.options.env);if(G&&"token"in G)return G.token;let Q={"User-Agent":"buddy"};if(G){let Z=Buffer.from(`${G.username}:${G.password}`).toString("base64");Q.Authorization=`Basic ${Z}`}let J=await O(u(j,z.repository),{headers:Q}).catch(()=>null);if(!J?.ok)return this.logger.debug(`Token exchange failed for ${z.registry}/${z.repository}: ${J?.status??"no response"}`),null;let Y=await J.json().catch(()=>null);return Y?.token??Y?.access_token??null}}function I(j){return`${j.registry}/${j.repository}`}function h(j,z){if(!j)return null;let G=/<([^>]+)>\s*;\s*rel="?next"?/i.exec(j);if(!G)return null;let Q=G[1];return Q.startsWith("http")?Q:`https://${z}${Q}`}var m=[".md",".txt",".log",".bak",".orig",".example",".sample",".tmpl",".template"];function F(j){let z=(j.split("/").pop()||"").toLowerCase();if(!z)return!1;if(m.some((G)=>z.endsWith(G)))return!1;if(z==="containerfile"||z.startsWith("containerfile."))return!0;if(z==="dockerfile"||z.startsWith("dockerfile."))return!0;return z.endsWith(".dockerfile")||z.endsWith(".containerfile")}async function jj(j,z){try{if(!F(j))return null;let G=[],Q=z.split(`
2
+ import{Kh as O}from"./chunk-34vracy4.js";import{Qh as q}from"./chunk-zwtx6vn3.js";import{fl as p}from"./chunk-s82adeq9.js";var T=/(?:^|[-_.])(?:rc|alpha|beta|pre|dev|nightly|canary|snapshot|edge|next)\d*(?:$|[-_.])/i;function B(j){let z=/^v?(\d+(?:\.\d+)*)(.*)$/.exec(j.trim());if(!z)return null;let[,G,Q]=z,J=T.test(Q),Y=Q.replace(T,(Z)=>{return Z.endsWith("-")||Z.endsWith("_")||Z.endsWith(".")?"-":""}).replace(/^[-_.]/,"").toLowerCase();return{raw:j,version:G.split(".").map(Number),suffix:Y,prerelease:J}}function x(j,z){for(let G=0;G<Math.max(j.length,z.length);G++){let Q=(j[G]??0)-(z[G]??0);if(Q!==0)return Q}return j.length-z.length}function k(j,z){let G=(Q)=>/^[a-z]+/.exec(Q)?.[0]??Q;return G(j)===G(z)}function b(j,z,G={}){let Q=B(j);if(!Q)return null;let J=z.map(B).filter((Y)=>Y!==null).filter((Y)=>G.includePrerelease?!0:!Y.prerelease).filter((Y)=>k(Y.suffix,Q.suffix)).filter((Y)=>Y.version.length===Q.version.length).filter((Y)=>x(Y.version,Q.version)>0);if(J.length===0)return null;return J.sort((Y,Z)=>x(Z.version,Y.version)),J[0].raw}function l(j,z){let G=B(j),Q=B(z);if(!G||!Q)return"patch";if((Q.version[0]??0)!==(G.version[0]??0))return"major";if((Q.version[1]??0)!==(G.version[1]??0))return"minor";return"patch"}import P from"process";var v="registry-1.docker.io";function U(j){let z=j.trim(),G,Q=z.indexOf("@");if(Q!==-1)G=z.slice(Q+1),z=z.slice(0,Q);let J=z.indexOf("/"),Y=J===-1?"":z.slice(0,J),Z=Y==="localhost"||Y.includes(".")||Y.includes(":"),X=Z?Y:"docker.io",$=Z?z.slice(J+1):z,K="latest",S=$.lastIndexOf("/"),W=$.indexOf(":",S+1);if(W!==-1)K=$.slice(W+1),$=$.slice(0,W);let M=X==="docker.io"&&!$.includes("/")?`library/${$}`:$;return{registry:X,repository:M,tag:K,...G?{digest:G}:{}}}function i(j){let z=j.registry==="docker.io"?j.repository.replace(/^library\//,""):`${j.registry}/${j.repository}`;return j.digest?`${z}:${j.tag}@${j.digest}`:`${z}:${j.tag}`}function C(j){return j==="docker.io"?v:j}function y(j,z,G=P.env){let Q=z?.[j];if(Q?.tokenEnv){let J=G[Q.tokenEnv]?.trim();if(J)return{token:J}}if(Q?.username&&Q.passwordEnv){let J=G[Q.passwordEnv]?.trim();if(J)return{username:Q.username,password:J}}if(j==="ghcr.io"){let J=G.GITHUB_TOKEN?.trim()||G.BUDDY_TOKEN?.trim();if(J)return{username:"buddy",password:J}}if(j==="docker.io"){let J=G.DOCKERHUB_TOKEN?.trim()||G.DOCKER_TOKEN?.trim();if(J)return{username:G.DOCKERHUB_USERNAME?.trim()||"buddy",password:J}}return null}function R(j){if(!j?.toLowerCase().startsWith("bearer "))return null;let z={};for(let G of j.slice(7).matchAll(/(\w+)="([^"]*)"/g))z[G[1]]=G[2];return z.realm?{realm:z.realm,...z.service?{service:z.service}:{},...z.scope?{scope:z.scope}:{}}:null}function u(j,z){let G=new URL(j.realm);if(j.service)G.searchParams.set("service",j.service);return G.searchParams.set("scope",j.scope??`repository:${z}:pull`),G.toString()}class H{options;logger;tokens=new Map;constructor(j={}){this.options=j;this.logger=j.logger??q()}async listTags(j){let z=C(j.registry),G=this.options.maxPages??10,Q=[],J=`https://${z}/v2/${j.repository}/tags/list?n=100`;for(let Y=0;Y<G&&J;Y++){let Z=await this.authorizedFetch(J,j);if(!Z?.ok){if(Y===0)this.logger.debug(`Could not list tags for ${j.repository} on ${j.registry}: ${Z?.status??"no response"}`);break}let X=await Z.json().catch(()=>null);if(Array.isArray(X?.tags))Q.push(...X.tags);J=h(Z.headers.get("link"),z)}return Q}async resolveDigest(j){let G=`https://${C(j.registry)}/v2/${j.repository}/manifests/${j.tag}`,Q=await this.authorizedFetch(G,j,{method:"HEAD",headers:{Accept:["application/vnd.oci.image.index.v1+json","application/vnd.oci.image.manifest.v1+json","application/vnd.docker.distribution.manifest.list.v2+json","application/vnd.docker.distribution.manifest.v2+json"].join(", ")}});return Q?.ok?Q.headers.get("docker-content-digest"):null}async authorizedFetch(j,z,G={}){let Q={"User-Agent":"buddy",...G.headers},J=this.tokens.get(I(z));if(J)Q.Authorization=`Bearer ${J}`;let Y=()=>O(j,{...G,headers:Q}).catch(()=>null),Z=await Y();if(Z?.status!==401||J!==void 0)return Z;let X=R(Z.headers.get("www-authenticate"));if(!X)return Z;let $=await this.fetchToken(X,z);if(!$)return Z;return this.tokens.set(I(z),$),Q.Authorization=`Bearer ${$}`,Z=await Y(),Z}async fetchToken(j,z){let G=y(z.registry,this.options.registries,this.options.env);if(G&&"token"in G)return G.token;let Q={"User-Agent":"buddy"};if(G){let Z=Buffer.from(`${G.username}:${G.password}`).toString("base64");Q.Authorization=`Basic ${Z}`}let J=await O(u(j,z.repository),{headers:Q}).catch(()=>null);if(!J?.ok)return this.logger.debug(`Token exchange failed for ${z.registry}/${z.repository}: ${J?.status??"no response"}`),null;let Y=await J.json().catch(()=>null);return Y?.token??Y?.access_token??null}}function I(j){return`${j.registry}/${j.repository}`}function h(j,z){if(!j)return null;let G=/<([^>]+)>\s*;\s*rel="?next"?/i.exec(j);if(!G)return null;let Q=G[1];return Q.startsWith("http")?Q:`https://${z}${Q}`}var m=[".md",".txt",".log",".bak",".orig",".example",".sample",".tmpl",".template"];function F(j){let z=(j.split("/").pop()||"").toLowerCase();if(!z)return!1;if(m.some((G)=>z.endsWith(G)))return!1;if(z==="containerfile"||z.startsWith("containerfile."))return!0;if(z==="dockerfile"||z.startsWith("dockerfile."))return!0;return z.endsWith(".dockerfile")||z.endsWith(".containerfile")}async function jj(j,z){try{if(!F(j))return null;let G=[],Q=z.split(`
3
3
  `);for(let J=0;J<Q.length;J++){let Y=Q[J].trim();if(!Y||Y.startsWith("#"))continue;let Z=Y.match(/^FROM\s+(\S+)(?:\s+as\s+\w+)?$/i);if(Z){let X=Z[1];if(X==="scratch"||X.startsWith("$"))continue;let $=c(X);if($)G.push({name:$.name,currentVersion:$.version,type:"docker-image",file:j})}}return{path:j,type:"Dockerfile",content:z,dependencies:G}}catch(G){return q().warn(`Failed to parse Dockerfile ${j}:`,G),null}}function c(j){try{let z,G,Q=j.indexOf("@"),J=Q===-1?void 0:j.slice(Q+1);if(Q!==-1)j=j.slice(0,Q);if(J&&!j.includes(":"))return null;if(j.includes(":")){let Y=j.lastIndexOf(":"),Z=j.substring(0,Y),X=j.substring(Y+1);if(/^\d+\//.test(X))z=j,G="latest";else z=Z,G=X}else z=j,G="latest";if(G.includes("$")||G.startsWith("sha256:"))return null;return{name:z,version:G,...J?{digest:J}:{}}}catch(z){return q().warn(`Failed to parse image reference ${j}:`,z),null}}async function zj(j,z,G={}){try{let Q=j.replace(/\s*\(.*\)$/,""),J=U(z?`${Q}:${z}`:Q),Z=await new H({...G.registries?{registries:G.registries}:{},logger:q()}).listTags(J);if(Z.length===0)return null;return b(J.tag,Z,{includePrerelease:G.includePrerelease??!1})}catch(Q){return q().warn(`Failed to fetch latest version for Docker image ${j}:`,Q),null}}async function d(j,z,G){let Q=U(`${j.replace(/\s*\(.*\)$/,"")}:${z}`);return new H({...G?{registries:G}:{},logger:q()}).resolveDigest(Q)}async function f(j,z,G,Q){try{if(!F(j))return q().info(`\u26A0\uFE0F updateDockerfile: ${j} is not a Dockerfile, returning original content`),z;let J=z;for(let Y of G){if(Y.dependencyType!=="docker-image")continue;let Z=Y.name.replace(/\s*\(.*\)$/,""),X=Z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),$=new RegExp(`(FROM\\s+${X})(:)([^\\s@]+)(@sha256:[a-f0-9]+)?([ \\t].*)?$`,"gim"),K=(W)=>{let M=["latest","main","master","develop","dev","stable"],w=W.toLowerCase().trim();return M.includes(w)},S=J.matchAll($);for(let W of S){let M=W[0],w=W[1],L=W[2],_=W[3],V=W[4]||"",D=W[5]||"";if(K(_)){q().info(`\u26A0\uFE0F Skipping update for ${Z} - version "${_}" should be respected`);continue}let A=V;if(V){let E=await d(Z,Y.newVersion,Q);if(!E){q().warn(`\u26A0\uFE0F Leaving ${Z} pinned at ${_}: could not resolve the digest for ${Y.newVersion}`);continue}A=`@${E}`}let N=`${w}${L}${Y.newVersion}${A}${D}`;J=J.replace(M,N),q().info(`\uD83D\uDCDD Updated ${Z}: ${_} \u2192 ${Y.newVersion}${A?" (digest re-resolved)":""}`)}}return J}catch(J){return q().warn(`Failed to update Dockerfile ${j}:`,J),z}}async function Gj(j,z){let G=[],Q=new Map;for(let J of j)if(J.dependencyType==="docker-image"&&F(J.file)){if(!Q.has(J.file))Q.set(J.file,[]);Q.get(J.file).push(J)}for(let[J,Y]of Q)try{let Z=await import("fs");if(Z.existsSync(J)){let X=Z.readFileSync(J,"utf-8"),$=await f(J,X,Y,z);if($!==X)G.push({path:J,content:$,type:"update"}),q().info(`\u2705 Generated update for ${J} with ${Y.length} image changes`);else q().info(`\u2139\uFE0F No changes needed for ${J} - versions already up to date`)}else q().warn(`\u26A0\uFE0F Dockerfile ${J} does not exist`)}catch(Z){q().warn(`Failed to generate updates for Dockerfile ${J}:`,Z)}return G}
4
4
  export{B as Fe,x as Ge,k as He,b as Ie,l as Je,U as Ke,i as Le,C as Me,y as Ne,R as Oe,H as Pe,F as Qe,jj as Re,zj as Se,d as Te,f as Ue,Gj as Ve};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ph as z}from"./chunk-x1w6q9tk.js";function Y(q,F,M=""){if(typeof F!=="object"||F===null)return[];let C=F,Q=M||"(root)",N=[];if(typeof C.type==="string"){let K=D(q);if(!(C.type==="integer"?Number.isInteger(q):K===C.type||C.type==="number"&&K==="integer"))return N.push({path:Q,message:`expected ${C.type}, got ${K}`}),N}if(Array.isArray(C.enum)&&!C.enum.includes(q))N.push({path:Q,message:`expected one of ${C.enum.map((K)=>JSON.stringify(K)).join(", ")}`});if(Array.isArray(C.required)&&typeof q==="object"&&q!==null){for(let K of C.required)if(!(String(K)in q))N.push({path:M?`${M}.${K}`:String(K),message:"is required but missing"})}if(typeof C.properties==="object"&&C.properties!==null&&typeof q==="object"&&q!==null)for(let[K,V]of Object.entries(C.properties)){let X=q[K];if(X!==void 0)N.push(...Y(X,V,M?`${M}.${K}`:K))}if(C.items!==void 0&&Array.isArray(q))q.forEach((K,V)=>{N.push(...Y(K,C.items,`${M}[${V}]`))});return N}function D(q){if(q===null)return"null";if(Array.isArray(q))return"array";if(Number.isInteger(q))return"integer";return typeof q}async function B(q){let F=q.logger??z(),M=q.maxRetries??2,C=q.system??"You are running as a pipeline step. Answer the request directly and completely. There is no interactive user to ask follow-up questions of.",Q="";for(let N=1;N<=M+1;N++){let K=N===1?q.prompt:`${q.prompt}
2
+ import{Qh as z}from"./chunk-zwtx6vn3.js";function Y(q,F,M=""){if(typeof F!=="object"||F===null)return[];let C=F,Q=M||"(root)",N=[];if(typeof C.type==="string"){let K=D(q);if(!(C.type==="integer"?Number.isInteger(q):K===C.type||C.type==="number"&&K==="integer"))return N.push({path:Q,message:`expected ${C.type}, got ${K}`}),N}if(Array.isArray(C.enum)&&!C.enum.includes(q))N.push({path:Q,message:`expected one of ${C.enum.map((K)=>JSON.stringify(K)).join(", ")}`});if(Array.isArray(C.required)&&typeof q==="object"&&q!==null){for(let K of C.required)if(!(String(K)in q))N.push({path:M?`${M}.${K}`:String(K),message:"is required but missing"})}if(typeof C.properties==="object"&&C.properties!==null&&typeof q==="object"&&q!==null)for(let[K,V]of Object.entries(C.properties)){let X=q[K];if(X!==void 0)N.push(...Y(X,V,M?`${M}.${K}`:K))}if(C.items!==void 0&&Array.isArray(q))q.forEach((K,V)=>{N.push(...Y(K,C.items,`${M}[${V}]`))});return N}function D(q){if(q===null)return"null";if(Array.isArray(q))return"array";if(Number.isInteger(q))return"integer";return typeof q}async function B(q){let F=q.logger??z(),M=q.maxRetries??2,C=q.system??"You are running as a pipeline step. Answer the request directly and completely. There is no interactive user to ask follow-up questions of.",Q="";for(let N=1;N<=M+1;N++){let K=N===1?q.prompt:`${q.prompt}
3
3
 
4
4
  Your previous answer did not satisfy the required schema:
5
5
  ${Q}
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Nc as a,Oc as b,Pc as c,Qc as d,Rc as e,Sc as f,Tc as g}from"./chunk-9n1kth4b.js";import"./chunk-zy49dwqk.js";import"./chunk-x9vpk4kk.js";import"./chunk-94tnmc7j.js";import"./chunk-drmk6r1m.js";import"./chunk-7t8s2mcf.js";import"./chunk-34vracy4.js";import"./chunk-zwtx6vn3.js";import"./chunk-028354j6.js";import"./chunk-s82adeq9.js";export{b as regenerateLockFile,d as nestedLockProjects,f as missingLockFiles,e as lockFileFor,g as hasLockFile,a as getAllLockFilePaths,c as detectRequiredPackageManagers};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{A as V0,B as z0,C as EQ,a as N,b as X,c as R,r as dQ,s as $0,t as HQ,x as F,y as U,z as AQ}from"./chunk-2jjrxgs1.js";import"./chunk-kbvj6qxc.js";import*as O from"fs/promises";import*as XQ from"fs";import*as T from"path";import*as FQ from"child_process";import*as M0 from"crypto";import*as A0 from"readline";function S(V){if(V.inputSchema.type!=="object")throw Error(`JSON schema for tool "${V.name}" must be an object, but got ${V.inputSchema.type}`);return{type:"custom",name:V.name,input_schema:V.inputSchema,description:V.description,run:V.run,parse:(Q)=>Q,...V.close?{close:V.close}:{}}}import*as b from"fs/promises";import*as C from"path";import{randomUUID as L0}from"crypto";var e=493,T0=420;function YQ(V,Q){let $=C.relative(V,Q);return $===""||!$.startsWith(".."+C.sep)&&$!==".."&&!C.isAbsolute($)}async function OQ(V,Q){for(let $ of V)if(YQ(await r(C.resolve($)),Q))return $;return}var y0=40;function QQ(V){let Q=V?.code;return typeof Q==="string"?Q:void 0}async function r(V){let Q=[],$=V,z=0;for(;;){let K;try{K=await b.realpath($)}catch(Z){let q;try{q=(await b.lstat($)).isSymbolicLink()}catch(Y){let W=QQ(Y);if(W!=="ENOENT"&&W!=="ENOTDIR")throw Y;let J=C.dirname($);if(J===$)throw Y;Q.push(C.basename($)),$=J;continue}if(!q)throw Z;if(++z>y0)throw Object.assign(Error("too many levels of symbolic links"),{code:"ELOOP"});$=C.resolve(C.dirname($),await b.readlink($));continue}return Q.length?C.join(K,...Q.reverse()):K}}async function fQ(V,Q,$){let z=$?.allowedRoots??[],K=await r(C.resolve(V)),Z;try{Z=await r(C.resolve(K,Q))}catch(Y){throw new U(n(Y,`path ${JSON.stringify(Q)}`))}if(YQ(K,Z)||await OQ(z,Z)!==void 0)return Z;let q=z.length?"the session's working directory and its other permitted directories":"the session's working directory";throw new U(`path ${JSON.stringify(Q)} is outside ${q}`)}async function RQ(V,Q){let $=C.dirname(V),z=C.join($,`.tmp-${process.pid}-${L0()}`),K;try{K=await b.open(z,"wx",T0),await K.writeFile(Q,"utf-8"),await K.sync(),await K.close(),K=void 0,await b.rename(z,V)}catch(Z){if(K)await K.close().catch(()=>{});throw await b.unlink(z).catch(()=>{}),Z}}function n(V,Q){let $=QQ(V);switch($){case"ENOENT":return`${Q}: no such file or directory`;case"EACCES":case"EPERM":return`${Q}: permission denied`;case"ENOTDIR":return`${Q}: not a directory`;case"EISDIR":return`${Q}: is a directory`;case"ELOOP":return`${Q}: too many levels of symbolic links`;case"ENAMETOOLONG":return`${Q}: file name too long`;case"ENOSPC":return`${Q}: no space left on device`;case"EMFILE":case"ENFILE":return`${Q}: too many open files`;default:return`${Q}: ${$!==void 0?`i/o error (${$})`:"i/o error"}`}}import*as G from"fs/promises";import*as uQ from"fs";import*as w from"path";import{execFile as b0}from"child_process";import{promisify as x0}from"util";import{Readable as v0}from"stream";import{pipeline as P0}from"stream/promises";var E0=x0(b0);async function F0(V){let{client:Q,sessionId:$}=V;if(!Q)return async()=>{};let z=HQ(Q),K=V.session;if(!K){if($===void 0)return async()=>{};z.warn("AgentToolContext.sessionId is deprecated and costs an extra session fetch; fetch the session once and set `session` instead",{component:"agent-tool-context"}),K=await Q.beta.sessions.retrieve($)}let Z=w.resolve(V.workdir,"skills"),q=[];for(let Y of K.agent.skills)try{let W=await Q.beta.skills.versions.retrieve(Y.version,{skill_id:Y.skill_id}),J=w.basename(W.name.trim());if(J===""||J==="."||J==="..")J=Y.skill_id;let H=w.resolve(Z,J);if(H!==Z&&!H.startsWith(Z+w.sep)){z.warn("skill name escapes the skills dir; skipping",{component:"agent-tool-context",name:W.name});continue}let M=await Q.beta.skills.versions.download(W.id,{skill_id:Y.skill_id});await G.rm(H,{recursive:!0,force:!0}),await G.mkdir(H,{recursive:!0,mode:e}),q.push(H),await mQ(M,H),z.info("downloaded skill",{component:"agent-tool-context",skill_id:Y.skill_id,version:W.id,dest:H})}catch(W){z.warn("failed to download skill",{component:"agent-tool-context",skill_id:Y.skill_id,error:String(W)})}return async()=>{for(let Y of q)await G.rm(Y,{recursive:!0,force:!0}).catch((W)=>{z.warn("failed to clean up skill",{component:"agent-tool-context",dest:Y,error:String(W)})})}}function f0(V){for(let Q of V){let $=Q.trim();if(!$)continue;if(w.isAbsolute($)||$.split(/[\\/]/).includes(".."))throw new R(`refusing to extract unsafe archive member: ${$}`)}}var LQ="skill archive listing is inconsistent; refusing to extract",g0={unzip:new Set(["-","d","?"]),tar:new Set(["-","d","C"])};function gQ(V){let Q=V.split(`
2
+ import{A as V0,B as z0,C as EQ,a as N,b as X,c as R,r as dQ,s as $0,t as HQ,x as F,y as U,z as AQ}from"./chunk-37zd94a7.js";import"./chunk-s82adeq9.js";import*as O from"fs/promises";import*as XQ from"fs";import*as T from"path";import*as FQ from"child_process";import*as M0 from"crypto";import*as A0 from"readline";function S(V){if(V.inputSchema.type!=="object")throw Error(`JSON schema for tool "${V.name}" must be an object, but got ${V.inputSchema.type}`);return{type:"custom",name:V.name,input_schema:V.inputSchema,description:V.description,run:V.run,parse:(Q)=>Q,...V.close?{close:V.close}:{}}}import*as b from"fs/promises";import*as C from"path";import{randomUUID as L0}from"crypto";var e=493,T0=420;function YQ(V,Q){let $=C.relative(V,Q);return $===""||!$.startsWith(".."+C.sep)&&$!==".."&&!C.isAbsolute($)}async function OQ(V,Q){for(let $ of V)if(YQ(await r(C.resolve($)),Q))return $;return}var y0=40;function QQ(V){let Q=V?.code;return typeof Q==="string"?Q:void 0}async function r(V){let Q=[],$=V,z=0;for(;;){let K;try{K=await b.realpath($)}catch(Z){let q;try{q=(await b.lstat($)).isSymbolicLink()}catch(Y){let W=QQ(Y);if(W!=="ENOENT"&&W!=="ENOTDIR")throw Y;let J=C.dirname($);if(J===$)throw Y;Q.push(C.basename($)),$=J;continue}if(!q)throw Z;if(++z>y0)throw Object.assign(Error("too many levels of symbolic links"),{code:"ELOOP"});$=C.resolve(C.dirname($),await b.readlink($));continue}return Q.length?C.join(K,...Q.reverse()):K}}async function fQ(V,Q,$){let z=$?.allowedRoots??[],K=await r(C.resolve(V)),Z;try{Z=await r(C.resolve(K,Q))}catch(Y){throw new U(n(Y,`path ${JSON.stringify(Q)}`))}if(YQ(K,Z)||await OQ(z,Z)!==void 0)return Z;let q=z.length?"the session's working directory and its other permitted directories":"the session's working directory";throw new U(`path ${JSON.stringify(Q)} is outside ${q}`)}async function RQ(V,Q){let $=C.dirname(V),z=C.join($,`.tmp-${process.pid}-${L0()}`),K;try{K=await b.open(z,"wx",T0),await K.writeFile(Q,"utf-8"),await K.sync(),await K.close(),K=void 0,await b.rename(z,V)}catch(Z){if(K)await K.close().catch(()=>{});throw await b.unlink(z).catch(()=>{}),Z}}function n(V,Q){let $=QQ(V);switch($){case"ENOENT":return`${Q}: no such file or directory`;case"EACCES":case"EPERM":return`${Q}: permission denied`;case"ENOTDIR":return`${Q}: not a directory`;case"EISDIR":return`${Q}: is a directory`;case"ELOOP":return`${Q}: too many levels of symbolic links`;case"ENAMETOOLONG":return`${Q}: file name too long`;case"ENOSPC":return`${Q}: no space left on device`;case"EMFILE":case"ENFILE":return`${Q}: too many open files`;default:return`${Q}: ${$!==void 0?`i/o error (${$})`:"i/o error"}`}}import*as G from"fs/promises";import*as uQ from"fs";import*as w from"path";import{execFile as b0}from"child_process";import{promisify as x0}from"util";import{Readable as v0}from"stream";import{pipeline as P0}from"stream/promises";var E0=x0(b0);async function F0(V){let{client:Q,sessionId:$}=V;if(!Q)return async()=>{};let z=HQ(Q),K=V.session;if(!K){if($===void 0)return async()=>{};z.warn("AgentToolContext.sessionId is deprecated and costs an extra session fetch; fetch the session once and set `session` instead",{component:"agent-tool-context"}),K=await Q.beta.sessions.retrieve($)}let Z=w.resolve(V.workdir,"skills"),q=[];for(let Y of K.agent.skills)try{let W=await Q.beta.skills.versions.retrieve(Y.version,{skill_id:Y.skill_id}),J=w.basename(W.name.trim());if(J===""||J==="."||J==="..")J=Y.skill_id;let H=w.resolve(Z,J);if(H!==Z&&!H.startsWith(Z+w.sep)){z.warn("skill name escapes the skills dir; skipping",{component:"agent-tool-context",name:W.name});continue}let M=await Q.beta.skills.versions.download(W.id,{skill_id:Y.skill_id});await G.rm(H,{recursive:!0,force:!0}),await G.mkdir(H,{recursive:!0,mode:e}),q.push(H),await mQ(M,H),z.info("downloaded skill",{component:"agent-tool-context",skill_id:Y.skill_id,version:W.id,dest:H})}catch(W){z.warn("failed to download skill",{component:"agent-tool-context",skill_id:Y.skill_id,error:String(W)})}return async()=>{for(let Y of q)await G.rm(Y,{recursive:!0,force:!0}).catch((W)=>{z.warn("failed to clean up skill",{component:"agent-tool-context",dest:Y,error:String(W)})})}}function f0(V){for(let Q of V){let $=Q.trim();if(!$)continue;if(w.isAbsolute($)||$.split(/[\\/]/).includes(".."))throw new R(`refusing to extract unsafe archive member: ${$}`)}}var LQ="skill archive listing is inconsistent; refusing to extract",g0={unzip:new Set(["-","d","?"]),tar:new Set(["-","d","C"])};function gQ(V){let Q=V.split(`
3
3
  `);if(Q[Q.length-1]==="")Q.pop();return Q}function u0(V,Q){return/^[\x20-\x7E]+$/.test(Q)&&!/[\\^#]/.test(Q)&&!(V==="unzip"&&Q.startsWith("-"))}function S0(V,Q,$){let z=gQ(Q),K=gQ($);if(z.length!==K.length)throw new R(LQ);let Z=[],q=[];return z.forEach((Y,W)=>{if(g0[V].has(K[W].charAt(0))){Z.push(Y);return}if(!u0(V,Y))throw new R(`refusing to extract archive: cannot safely exclude member ${JSON.stringify(Y)}`);q.push(Y)}),{plain:Z,special:q}}async function SQ(V){for(let Q of await G.readdir(V,{withFileTypes:!0}))if(Q.isDirectory())await SQ(w.join(V,Q.name));else if(!Q.isFile())throw new R(LQ)}async function jQ(V,Q){try{let{stdout:$}=await E0(V,Q);return $}catch($){if(QQ($)==="ENOENT")throw new R(`skill extraction requires the \`${V}\` command, but it was not found on PATH`);throw $}}function m0(V){let Q,$=!1;for(let z of V){let K=z.trim().split("/").filter((q)=>q!==""&&q!==".");if(K.length===0)continue;let Z=K[0];if(Q===void 0)Q=Z;else if(Z!==Q)return"";if(K.length>1)$=!0}return Q!==void 0&&$?Q:""}async function mQ(V,Q){let $=w.join(Q,`.skill-archive-${process.pid}-${Date.now()}`);if(!V.body)throw new R("skill download response had no body");await P0(v0.fromWeb(V.body),uQ.createWriteStream($));let z=w.join(w.dirname(Q),`.skill-stage-${process.pid}-${Date.now()}`),K=w.join(w.dirname(Q),`.skill-exclude-${process.pid}-${Date.now()}`);try{let Z=await _0($,4),q=Z.length>=4&&Z[0]===80&&Z[1]===75&&Z[2]===3&&Z[3]===4,Y=q?"unzip":"tar",W=await jQ(Y,q?["-Z1",$]:["-tf",$]),J=await jQ(Y,q?["-Z","--h","--t",$]:["-tvf",$]),{plain:H,special:M}=S0(Y,W,J);f0([...H,...M]);let j=m0(H);if(await G.mkdir(z,{recursive:!0,mode:e}),H.length>0)await jQ(Y,await p0(Y,$,z,M,K));await SQ(z);let v=j?w.join(z,j):z,P=await G.readdir(v).catch((E)=>{throw QQ(E)==="ENOENT"?new R(LQ):E});for(let E of P)await G.rename(w.join(v,E),w.join(Q,E))}finally{await G.rm($,{force:!0}),await G.rm(K,{force:!0}),await G.rm(z,{recursive:!0,force:!0})}}async function p0(V,Q,$,z,K){let Z=z.map((q)=>q.replace(/[*?[\\]/g,"\\$&"));if(V==="unzip")return["-oq",Q,"-d",$,...Z.length>0?["-x",...Z]:[]];if(Z.length===0)return["-xf",Q,"-C",$];return await G.writeFile(K,Z.join(`
4
4
  `)+`
5
5
  `,{flag:"wx",mode:384}),["-xf",Q,"-C",$,"-X",K]}async function _0(V,Q){let $=await G.open(V,"r");try{let z=Buffer.alloc(Q),{bytesRead:K}=await $.read(z,0,Q,0);return z.subarray(0,K)}finally{await $.close()}}import*as q0 from"path";import{createHash as V1}from"crypto";import*as A from"fs/promises";import*as k from"path";import{constants as i}from"fs";import{createHash as h0,randomBytes as d0}from"crypto";var cQ=448,c0=384,n0=448,TQ=i.O_NOFOLLOW??0,i0=i.O_NONBLOCK??0;class D extends Error{constructor(V,Q){super(`path ${JSON.stringify(Q)} ${V}`);this.name="FileStoreError",this.reason=V,this.relPath=Q}}D.ESCAPES_ROOT="escapes the store root";D.IS_A_SYMLINK="is a symlink";D.NOT_A_FILE="is not a regular file";D.NOT_A_DIRECTORY="is not a directory";D.NOT_UTF8="is not valid utf-8";D.MOVE_DESTINATION_EXISTS="already exists";function yQ(V){return V.startsWith("/")&&!V.split("/").includes("..")}class l{constructor(V,Q,$=!1){this.hashes=new Map,this.rootPath=V,this.removedOnDispose=Q,this.decoder=$?new TextDecoder("utf-8",{fatal:!0}):void 0}static async open(V,Q){if(!l0())throw Error("FileStore requires O_NOFOLLOW support on this platform");let $=!1;try{await A.lstat(V)}catch(z){if(z.code!=="ENOENT")throw z;$=!0}return new l(k.resolve(V),$,Q?.utf8??!1)}async createRoot(){await a0(this.rootPath)}root(){return{path:this.rootPath,removedOnDispose:this.removedOnDispose}}async dispose(){if(!this.removedOnDispose)return;await A.rm(this.rootPath,{recursive:!0,force:!0})}async put(V,Q,$){let z=V.replace(/\\/g,"/");if(z.endsWith("/")||z.endsWith("/.")||z===""||z===".")throw new D(D.NOT_A_FILE,V);let K=this.resolveUnderRoot(V),Z=typeof Q==="string"?dQ(Q):Q;this.requireUtf8(V,Z),await pQ(this.rootPath,k.dirname(K)),await o0(K,Z,$?.executable??!1)}async get(V){let Q=this.resolveUnderRoot(V),$;try{$=await nQ(V,Q)}catch(K){if(K.code==="ENOENT")return null;throw K}let z;try{let K=await $.readFile();z=new Uint8Array(K.buffer,K.byteOffset,K.byteLength)}finally{await $.close()}return this.requireUtf8(V,z),z}async ls(V="/"){let Q=this.resolveUnderRoot(V);return new Set((await _Q(this.rootPath,V,Q)).map(([$])=>$))}async findSymlinks(V="/"){let Q=this.resolveUnderRoot(V);return t0(this.rootPath,V,Q)}async hashtree(V="/"){let Q=this.resolveUnderRoot(V),$=JQ.nowNs(),z=Object.create(null);for(let[K,Z]of await _Q(this.rootPath,V,Q)){let q=await this.hashViaCache(K,Z,$);if(q!==null)z[K]=q}return z}async hashFile(V){let Q=this.resolveUnderRoot(V),$;try{$=await A.lstat(Q,{bigint:!0})}catch(K){if(K.code==="ENOENT")return null;throw K}if($.isSymbolicLink())throw new D(D.IS_A_SYMLINK,V);if(!$.isFile())throw new D(D.NOT_A_FILE,V);let z=k.relative(this.rootPath,Q).split(k.sep).join("/");return this.hashViaCache(z,Q,JQ.nowNs())}async move(V,Q){let $=this.resolveUnderRoot(V),z=this.resolveUnderRoot(Q);if($===this.rootPath||z===this.rootPath)return;if(await A.stat(z).then(()=>!0,()=>!1))throw new D(D.MOVE_DESTINATION_EXISTS,Q);await pQ(this.rootPath,k.dirname(z)),await A.rename($,z)}async remove(V){let Q=this.resolveUnderRoot(V);if(Q===this.rootPath)return;let $;try{$=await A.lstat(Q,{bigint:!0})}catch(z){if(z.code==="ENOENT")return;throw z}if($.isDirectory())await A.rm(Q,{recursive:!0,force:!0});else try{await A.unlink(Q)}catch(z){if(z.code!=="ENOENT")throw z}}resolveUnderRoot(V){let Q=V.replace(/\\/g,"/").replace(/^\/+/,""),$=Q.split("/").filter((z)=>z!==""&&z!==".");if(k.posix.isAbsolute(Q)||$.includes(".."))throw new D(D.ESCAPES_ROOT,V);return $.length===0?this.rootPath:k.join(this.rootPath,...$)}requireUtf8(V,Q){if(!this.decoder)return;try{this.decoder.decode(Q)}catch{throw new D(D.NOT_UTF8,V)}}async hashViaCache(V,Q,$){let z;try{z=await A.lstat(Q,{bigint:!0})}catch(q){if(q.code==="ENOENT")return null;throw q}if(!z.isFile())return null;let K=this.hashes.get(V),Z;if(K!==void 0&&e0(K,z))Z=K.sha;else try{Z=await JQ.hashFile(Q)}catch(q){let Y=q.code;if(Y==="ENOENT"||q instanceof D)return null;if(Y==="ELOOP"||Y==="EMLINK")return null;throw q}if(Q1(z,$))this.hashes.set(V,{mtimeNs:z.mtimeNs,ctimeNs:z.ctimeNs,size:z.size,sha:Z});return Z}}l.isPathLegal=yQ;function l0(){return TQ!==0}async function a0(V){let Q=[],$=V;for(;;){try{await A.stat($);break}catch(K){let Z=K.code;if(Z!=="ENOENT"&&Z!=="ENOTDIR"&&Z!=="ELOOP")throw K}Q.push($);let z=k.dirname($);if(z===$)break;$=z}for(let z of Q.reverse())try{await A.mkdir(z,{mode:cQ})}catch(K){if(K.code!=="EEXIST")throw K}}async function pQ(V,Q){let $=k.relative(V,Q);if($==="")return;let z=V;for(let K of $.split(k.sep)){z=k.join(z,K);try{await A.mkdir(z,{mode:cQ})}catch(Z){if(Z.code!=="EEXIST")throw Z}}}async function o0(V,Q,$){let z=$?n0:c0,K=k.join(k.dirname(V),`.fs-${d0(8).toString("hex")}.tmp`),Z;try{Z=await A.open(K,i.O_WRONLY|i.O_CREAT|i.O_EXCL|TQ,z),await Z.writeFile(Q),await Z.close(),Z=void 0,await A.rename(K,V)}catch(q){if(Z)await Z.close().catch(()=>{});throw await A.unlink(K).catch(()=>{}),q}}async function nQ(V,Q){let $;try{$=await A.open(Q,i.O_RDONLY|TQ|i0)}catch(z){let K=z.code;if(K==="ELOOP"||K==="EMLINK")throw new D(D.IS_A_SYMLINK,V);throw z}try{if(!(await $.stat()).isFile())throw new D(D.NOT_A_FILE,V)}catch(z){throw await $.close().catch(()=>{}),z}return $}async function s0(V){let Q=h0("sha256"),$=await nQ(k.basename(V),V),z=new Uint8Array(1048576);try{for(;;){let{bytesRead:K}=await $.read(z,0,z.length);if(K===0)break;Q.update(z.subarray(0,K))}}finally{await $.close()}return Q.digest("hex")}async function _Q(V,Q,$){if(!await r0(Q,$))return[];let z=[];return await iQ($,(K,Z)=>{if(Z.isFile())z.push([k.relative(V,K).split(k.sep).join("/"),K])}),z.sort(),z}async function t0(V,Q,$){let z=(q)=>k.relative(V,q).split(k.sep).join("/"),K;try{K=await A.lstat($,{bigint:!0})}catch(q){let Y=q.code;if(Y==="ENOENT"||Y==="ENOTDIR")return new Set;throw q}if(K.isSymbolicLink())return new Set([z($)]);if(!K.isDirectory())throw new D(D.NOT_A_DIRECTORY,Q);let Z=new Set;return await iQ($,(q,Y)=>{if(Y.isSymbolicLink())Z.add(z(q))}),Z}async function r0(V,Q){let $;try{$=await A.lstat(Q,{bigint:!0})}catch(z){let K=z.code;if(K==="ENOENT"||K==="ENOTDIR")return!1;throw z}if(!$.isDirectory())throw new D(D.NOT_A_DIRECTORY,V);return!0}async function iQ(V,Q){let $=[V];while($.length){let z=$.pop(),K;try{K=await A.readdir(z,{withFileTypes:!0})}catch(Z){if(Z.code==="ENOENT")continue;throw Z}for(let Z of K){let q=k.join(z,Z.name);if(Q(q,Z),Z.isDirectory()&&!Z.isSymbolicLink())$.push(q)}}}function e0(V,Q){return Q.mtimeNs===V.mtimeNs&&Q.ctimeNs===V.ctimeNs&&Q.size===V.size}function Q1(V,Q){return(V.mtimeNs>V.ctimeNs?V.mtimeNs:V.ctimeNs)<Q-JQ.timestampTrustMarginNs}var $1=2000000000n,JQ={hashFile:s0,timestampTrustMarginNs:$1,nowNs:()=>BigInt(Date.now())*1000000n},lQ=l,hQ=Symbol.asyncDispose;if(hQ)Object.defineProperty(l.prototype,hQ,{value:l.prototype.dispose,configurable:!0,writable:!0});var I,g,BQ,$Q,MQ,B,a,DQ,f,K0,NQ,Z0,X0,bQ,vQ,aQ,oQ,xQ,sQ,tQ,WQ,UQ,rQ,eQ,z1=30000,o=".anthropic-memory-store",Y0=1;function Q0(V){return V1("sha256").update(`version ${Y0}
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Vf as F,Xf as O,Yf as U}from"./chunk-z18bksyr.js";import{$f as w}from"./chunk-cj4d5ad7.js";import{Ph as S}from"./chunk-x1w6q9tk.js";import{readdir as g,stat as _}from"fs/promises";import{join as x,relative as E,resolve as C}from"path";var D=1e5;function M(G,q){let J=w(G),Q=C(q),K=C(Q,J),$=E(Q,K);if($.startsWith("..")||C(Q,$)!==K)throw Error(`Refusing to access a path outside the workspace: ${G}`);return K}var h={name:"read_file",tier:"read",description:"Read a UTF-8 text file from the repository. Paths are relative to the repository root.",parameters:{type:"object",properties:{path:{type:"string",description:"Repository-relative path, e.g. src/index.ts"}},required:["path"]},async run(G,q){let J=String(G.path??""),Q=M(J,q.workspace),K=Bun.file(Q);if(!await K.exists())return{content:`File not found: ${J}`,isError:!0};let $=await K.text();if($.length>D)return{content:`${$.slice(0,D)}
2
+ import{Vf as F,Xf as O,Yf as U}from"./chunk-z18bksyr.js";import{$f as w}from"./chunk-cj4d5ad7.js";import{Qh as S}from"./chunk-zwtx6vn3.js";import{readdir as g,stat as _}from"fs/promises";import{join as x,relative as E,resolve as C}from"path";var D=1e5;function M(G,q){let J=w(G),Q=C(q),K=C(Q,J),$=E(Q,K);if($.startsWith("..")||C(Q,$)!==K)throw Error(`Refusing to access a path outside the workspace: ${G}`);return K}var h={name:"read_file",tier:"read",description:"Read a UTF-8 text file from the repository. Paths are relative to the repository root.",parameters:{type:"object",properties:{path:{type:"string",description:"Repository-relative path, e.g. src/index.ts"}},required:["path"]},async run(G,q){let J=String(G.path??""),Q=M(J,q.workspace),K=Bun.file(Q);if(!await K.exists())return{content:`File not found: ${J}`,isError:!0};let $=await K.text();if($.length>D)return{content:`${$.slice(0,D)}
3
3
 
4
4
  [truncated at ${D} characters]`};return{content:$}}},T={name:"write_file",tier:"write",description:"Write a UTF-8 text file in the repository, creating or replacing it.",parameters:{type:"object",properties:{path:{type:"string",description:"Repository-relative path"},content:{type:"string",description:"Full file content to write"}},required:["path","content"]},async run(G,q){let J=String(G.path??""),Q=M(J,q.workspace);return await Bun.write(Q,String(G.content??"")),q.log(`wrote ${J}`),{content:`Wrote ${J}`}}},m={name:"list_dir",tier:"read",description:"List the entries of a directory in the repository.",parameters:{type:"object",properties:{path:{type:"string",description:"Repository-relative directory, defaults to the root"}}},async run(G,q){let J=G.path?String(G.path):".",Q=J==="."?C(q.workspace):M(J,q.workspace);try{let K=await g(Q);return{content:(await Promise.all(K.map(async(z)=>{return(await _(x(Q,z)).catch(()=>null))?.isDirectory()?`${z}/`:z}))).sort().join(`
5
5
  `)||"(empty)"}}catch(K){return{content:`Could not list ${J}: ${K}`,isError:!0}}}},L=[h,T,m];import u from"process";var d=120000,v=30000,c=["PATH","HOME","LANG","LC_ALL","TZ","TMPDIR","SHELL","USER","PWD","NODE_ENV","CI","BUN_INSTALL","XDG_CACHE_HOME"],p=/_(?:TOKEN|KEY|SECRET|PASSWORD|CREDENTIAL|CREDENTIALS)$|^(?:GITHUB_TOKEN|ANTHROPIC_API_KEY|OPENAI_API_KEY|NPM_TOKEN)$/i;function l(G=u.env,q=[]){let J=new Set([...c,...q]),Q={};for(let[K,$]of Object.entries(G)){if($===void 0)continue;if(!J.has(K))continue;if(p.test(K))continue;Q[K]=$}return Q}var y={name:"run_command",tier:"shell",description:"Run a shell command in the repository. The environment is stripped of credentials, so commands cannot authenticate to external services.",parameters:{type:"object",properties:{command:{type:"string",description:"Command to run, e.g. bun test"},timeoutMs:{type:"number",description:"Optional timeout in milliseconds"}},required:["command"]},async run(G,q){let J=String(G.command??"").trim();if(!J)return{content:"No command supplied",isError:!0};let Q=Number(G.timeoutMs)>0?Number(G.timeoutMs):d;q.log(`running: ${J}`);try{let K=Bun.spawn(["sh","-c",J],{cwd:q.workspace,env:l(),stdout:"pipe",stderr:"pipe"}),$=setTimeout(()=>K.kill(),Q),[z,V,I]=await Promise.all([new Response(K.stdout).text(),new Response(K.stderr).text(),K.exited]);clearTimeout($);let H=[z,V].filter(Boolean).join(`
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Qb as p,Rb as q,Sb as r,Tb as s,Ub as t,Vb as u,Wb as v,Xb as w,Yb as x}from"./chunk-59993g25.js";import{$b as i,Zb as g,_b as h,ac as j,bc as k,cc as l,dc as m,ec as n,fc as o}from"./chunk-va3k91tf.js";import"./chunk-24xvskkf.js";import{Uf as a,Vf as b,Wf as c,Xf as d,Yf as e,Zf as f}from"./chunk-z18bksyr.js";import"./chunk-b9szrnxw.js";import"./chunk-x1w6q9tk.js";import"./chunk-kbvj6qxc.js";export{s as serializeLearnings,v as selectLearnings,j as resolveModelAlias,n as resolveAiProvider,w as renderLearnings,d as redactError,c as redactDeep,b as redact,r as parseLearnings,x as loadLearnings,m as createOpenAiProvider,t as createLearning,l as createGoogleProvider,k as createAnthropicProvider,o as createAiClient,u as addLearning,a as REDACTED,i as PROVIDER_PRIORITY,h as PROVIDER_KEY_ENV,g as MODEL_ALIASES,q as DEFAULT_PROMPT_LIMIT,p as DEFAULT_LEARNINGS_FILE,f as AiProviderError,e as AiBudgetExceededError};
2
+ import{Qb as p,Rb as q,Sb as r,Tb as s,Ub as t,Vb as u,Wb as v,Xb as w,Yb as x}from"./chunk-sn0qr6q7.js";import{$b as i,Zb as g,_b as h,ac as j,bc as k,cc as l,dc as m,ec as n,fc as o}from"./chunk-5sh69bkj.js";import"./chunk-24xvskkf.js";import{Uf as a,Vf as b,Wf as c,Xf as d,Yf as e,Zf as f}from"./chunk-z18bksyr.js";import"./chunk-34vracy4.js";import"./chunk-zwtx6vn3.js";import"./chunk-s82adeq9.js";export{s as serializeLearnings,v as selectLearnings,j as resolveModelAlias,n as resolveAiProvider,w as renderLearnings,d as redactError,c as redactDeep,b as redact,r as parseLearnings,x as loadLearnings,m as createOpenAiProvider,t as createLearning,l as createGoogleProvider,k as createAnthropicProvider,o as createAiClient,u as addLearning,a as REDACTED,i as PROVIDER_PRIORITY,h as PROVIDER_KEY_ENV,g as MODEL_ALIASES,q as DEFAULT_PROMPT_LIMIT,p as DEFAULT_LEARNINGS_FILE,f as AiProviderError,e as AiBudgetExceededError};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Ea as a,Fa as b,Ga as c,Ha as d,Ia as e,Ja as f,Ka as g}from"./chunk-s5czyzje.js";import"./chunk-qjzpzd7j.js";import"./chunk-ebnc6980.js";import"./chunk-y1d6e0ye.js";import"./chunk-1pecmenc.js";import"./chunk-4kyxrwxn.js";import"./chunk-z18bksyr.js";import"./chunk-cj4d5ad7.js";import"./chunk-34vracy4.js";import"./chunk-zwtx6vn3.js";import"./chunk-s82adeq9.js";export{g as runFixCi,e as latestFailurePerWorkflow,d as failsOnBaseBranch,b as extractErrorLines,c as describeFailure,a as classifyFailure,f as attemptFix};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{_c as oX}from"./chunk-raj75r4h.js";import{dd as sX}from"./chunk-25sjd6zk.js";import{Ph as iX}from"./chunk-x1w6q9tk.js";import{el as n}from"./chunk-kbvj6qxc.js";import{resolve as b8}from"path";import y8 from"process";import{existsSync as aX,statSync as eX}from"fs";import{resolve as wQ}from"path";import SZ from"process";import{existsSync as TZ,mkdirSync as m8,readdirSync as u8,readFileSync as OZ,writeFileSync as g8}from"fs";import{homedir as ZQ}from"os";import{dirname as n8,resolve as l}from"path";import QX from"process";import{existsSync as QY,statSync as XY}from"fs";import{existsSync as SX,mkdirSync as NZ,readdirSync as CZ,writeFileSync as xZ}from"fs";import{homedir as $Q}from"os";import{dirname as YY,resolve as y}from"path";import YQ from"process";import{join as kZ,relative as PZ,resolve as ZY}from"path";import mQ from"process";import{existsSync as gY,mkdirSync as Y9,readdirSync as Z9,writeFileSync as $9}from"fs";import{homedir as HX}from"os";import{dirname as J9,resolve as b}from"path";import KQ from"process";import{join as bZ,relative as yZ,resolve as $Y}from"path";import uQ from"process";import{existsSync as cY,mkdirSync as W9,readdirSync as z9,writeFileSync as B9}from"fs";import{dirname as w9,resolve as gQ}from"path";import VX from"process";import{Buffer as e}from"buffer";import{createCipheriv as vZ,createDecipheriv as hZ,randomBytes as UX}from"crypto";import{closeSync as JX,createReadStream as HY,createWriteStream as dZ,existsSync as GX,fsyncSync as UY,openSync as JY,writeFileSync as fZ}from"fs";import{access as pZ,constants as GY,mkdir as mZ,readdir as MQ,rename as _Y,stat as HQ,unlink as DQ,writeFile as _X}from"fs/promises";import{join as UQ}from"path";import x from"process";import{pipeline as uZ}from"stream/promises";import{createGzip as qY}from"zlib";import JQ from"process";import o from"process";import{Buffer as i}from"buffer";import{createCipheriv as gZ,createDecipheriv as cZ,randomBytes as qX}from"crypto";import{closeSync as AX,createReadStream as AY,createWriteStream as lZ,existsSync as SQ,fsyncSync as WY,openSync as zY,writeFileSync as nZ}from"fs";import{access as iZ,constants as BY,mkdir as sZ,readdir as VQ,rename as RY,stat as GQ,unlink as EQ,writeFile as WX}from"fs/promises";import{isAbsolute as oZ,join as _Q,resolve as rZ}from"path";import w from"process";import{pipeline as tZ}from"stream/promises";import{createGzip as wY}from"zlib";import qQ from"process";import r from"process";import TQ from"process";import{existsSync as OQ}from"fs";import{resolve as zX}from"path";import{existsSync as aZ}from"fs";import{existsSync as eZ,readdirSync as Q0}from"fs";import{extname as BX,resolve as LY}from"path";import X0 from"process";import{join as Y0,relative as Z0,resolve as KY}from"path";import cQ from"process";import{Buffer as s}from"buffer";import{createCipheriv as $0,createDecipheriv as H0,randomBytes as RX}from"crypto";import{closeSync as wX,createReadStream as jY,createWriteStream as U0,existsSync as NQ,fsyncSync as IY,openSync as FY,writeFileSync as J0}from"fs";import{access as G0,constants as MY,mkdir as _0,readdir as CQ,rename as DY,stat as AQ,unlink as xQ,writeFile as LX}from"fs/promises";import{isAbsolute as q0,join as WQ,resolve as A0}from"path";import L from"process";import{pipeline as W0}from"stream/promises";import{createGzip as SY}from"zlib";import zQ from"process";import t from"process";import PQ from"process";import{existsSync as bQ}from"fs";import{resolve as dY}from"path";import{existsSync as x8}from"fs";class fY{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!aX(Q))return!0;return eX(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=aX(Y)?eX(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class pY{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}var pQ=new fY,vX=new pY;var mY=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function uY(Q={}){let{name:X="",alias:Y}=Q,Z=["config",".config"];if(X)Z.push(X,`.${X}.config`,`${X}.config`,`.${X}`);let $=Y===void 0?[]:Array.isArray(Y)?Y:[Y];for(let H of $){if(!H)continue;if(Z.push(H,`.${H}.config`,`${H}.config`,`.${H}`),X)Z.push(`${X}.${H}.config`,`.${X}.${H}.config`)}return Array.from(new Set(Z.filter(Boolean)))}function VZ(Q){return uY(Q).flatMap((Y)=>mY.map((Z)=>wQ(Q.directory,`${Y}${Z}`)))}function EZ(Q={}){let X=wQ(Q.cwd||SZ.cwd());return Array.from(new Set([X,wQ(X,"config"),wQ(X,".config"),Q.configDir?wQ(X,Q.configDir):void 0].filter((Y)=>Boolean(Y))))}var z0=Object.defineProperty,B0=(Q)=>Q;function R0(Q,X){this[Q]=B0.bind(null,X)}var w0=(Q,X)=>{for(var Y in X)z0(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:R0.bind(X,Y)})},L0=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X),lY={};w0(lY,{withErrorRecovery:()=>sY,tryLoadConfig:()=>p0,loadConfigWithResult:()=>d0,loadConfig:()=>eY,isRetryableError:()=>k0,isConfigNotFoundError:()=>x0,isBunfigError:()=>oY,globalPerformanceMonitor:()=>FQ,globalCache:()=>BQ,getEnvOrDefault:()=>P0,generateConfigTypes:()=>m0,defaultGeneratedDir:()=>JZ,defaultConfigDir:()=>UZ,deepMergeWithArrayStrategy:()=>mX,deepMerge:()=>rY,createLibraryConfig:()=>u0,config:()=>f0,bunfigPlugin:()=>g0,applyEnvVarsToConfig:()=>LQ,TypeGenerationError:()=>kX,SchemaValidationError:()=>IQ,PluginError:()=>bX,PerformanceMonitor:()=>dX,FileSystemError:()=>xX,ErrorFactory:()=>QQ,EnvVarError:()=>rQ,EnvProcessor:()=>XX,ConfigValidator:()=>uX,ConfigValidationError:()=>NX,ConfigNotFoundError:()=>oQ,ConfigMergeError:()=>CX,ConfigLoader:()=>gX,ConfigLoadError:()=>jQ,ConfigFileLoader:()=>YX,ConfigCache:()=>hX,CacheUtils:()=>XZ,BunfigError:()=>h,BrowserConfigError:()=>PX,ArrayMergeStrategies:()=>$Z});class hX{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!QY(Q))return!0;return XY(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=QY(Y)?XY(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class dX{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}function K0(Q,X={}){let Z=Object.keys(X).sort().map(($)=>`${$}:${X[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function j0(Q,X){try{return JSON.stringify(Q)===JSON.stringify(X)}catch{return Q===X}}function I0(Q){return Q.getStats().size*2}function fX(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&D(X[0])&&"id"in X[0]&&X[0].id===3&&D(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(D(X)&&D(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(D(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&D(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&D(X[0])&&D(Q[0])){let Z=[...X];for(let $ of Q)if(D($)&&"name"in $){if(!Z.find((U)=>D(U)&&("name"in U)&&U.name===$.name))Z.push($)}else if(D($)&&"path"in $){if(!Z.find((U)=>D(U)&&("path"in U)&&U.path===$.path))Z.push($)}else if(!Z.some((H)=>lQ(H,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!D(X)||!D(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(D($)&&D(Y[Z]))Y[Z]=fX(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&D($[0])&&D(Y[Z][0])){let H=[...$];for(let U of Y[Z])if(D(U)&&"name"in U){if(!H.find((J)=>D(J)&&("name"in J)&&J.name===U.name))H.push(U)}else if(D(U)&&"path"in U){if(!H.find((J)=>D(J)&&("path"in J)&&J.path===U.path))H.push(U)}else if(!H.some((G)=>lQ(G,U)))H.push(U);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let U of Y[Z])if(!H.includes(U))H.push(U);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function lQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!lQ(Q[Y],X[Y]))return!1;return!0}if(D(Q)&&D(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!lQ(Q[$],X[$]))return!1}return!0}return!1}function D(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function F0(Q,X){if(!cY(Q))return null;try{let Y=await import(Q),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return fX(X,Z)}catch{return null}}catch{return null}}async function M0({name:Q="",cwd:X,defaultConfig:Y}){let Z=X||VX.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],H=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let U of H)for(let G of $){let J=gQ(Z,`${U}${G}`),_=await F0(J,Y);if(_!==null)return _}try{let U=gQ(Z,"package.json");if(cY(U)){let J=(await import(U))[Q];if(J&&typeof J==="object"&&!Array.isArray(J))try{return fX(Y,J)}catch{}}}catch{}return Y}function D0(Q,X={}){let Y=uQ.cwd();while(Y.includes("storage"))Y=$Y(Y,"..");let Z=$Y(Y,Q||"");if(X?.relative)return yZ(uQ.cwd(),Z);return Z}async function S0(){try{let Q=await M0({name:"clarity",defaultConfig:vQ,cwd:uQ.cwd(),endpoint:"",headers:{}});return{...vQ,...Q}}catch{return vQ}}function S(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function V0(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof o<"u"){let Q=o.type;if(Q==="renderer"||Q==="worker")return!1;return!!(o.versions&&(o.versions.node||o.versions.bun))}return!1}class nY{async format(Q){let X=await V0(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:JQ.pid,hostname:X(),environment:JQ.env.NODE_ENV||"development",platform:JQ.platform,version:JQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:JQ.env.NODE_ENV||JQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class nQ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,X={}){this.name=Q,this.config={...TX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new nY,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...hQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...hQ};return{...hQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:TX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,G=1000;while(H<U)try{try{try{await pZ(this.config.logDirectory,GY.F_OK|GY.W_OK)}catch(_){if(_ instanceof Error&&"code"in _)if(_.code==="ENOENT")await mZ(this.config.logDirectory,{recursive:!0,mode:493});else if(_.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw _;else throw _}}catch(_){throw console.error("Debug: [writeToFile] Failed to create log directory:",_),_}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:e.from(Q);try{if(!GX(this.currentLogFile))await _X(this.currentLogFile,"",{mode:420});if($=JY(this.currentLogFile,"a",420),fZ($,J,{flag:"a"}),UY($),$!==void 0)JX($),$=void 0;if((await HQ(this.currentLogFile)).size===0){if(await _X(this.currentLogFile,J,{flag:"w",mode:420}),(await HQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(_){let q=_;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(H<U-1){let A=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${U}:`,A);let z=G*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{JX($)}catch(_){console.error("Debug: [writeToFile] Error closing file descriptor:",_)}}}catch(J){if(H===U-1){let q=J,A=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}H++;let _=G*2**(H-1);await new Promise((q)=>setTimeout(q,_))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return UQ(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return UQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return UQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(S())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,G],[,J])=>J.createdAt.getTime()-G.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[G]of $.slice(U))this.encryptionKeys.delete(G),this.keys.delete(G)}generateKeyId(){return UX(16).toString("hex")}generateKey(){return UX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=UX(16),Z=vZ("aes-256-gcm",X,Y),$=e.concat([Z.update(Q,"utf8"),Z.final()]),H=Z.getAuthTag();return{encrypted:e.concat([Y,$,H]),iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=qY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(e.from(e.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(S())return;let Q=await HQ(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await MQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,_)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(_.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,G=`${Y}.${U}`;if(await HQ(Y).catch(()=>null))try{if(await _Y(Y,G),X.compress)try{let J=`${G}.gz`;await this.compressLogFile(G,J),await DQ(G)}catch(J){console.error("Error compressing rotated file:",J)}if(H.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await _X(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await HQ(Y).catch(()=>null))await _Y(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await MQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,G)=>G.localeCompare(U));for(let U of H.slice(X.maxFiles))await DQ(UQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=HY(Q),Z=dZ(X),$=qY();await uZ(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:Q,message:X,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),GX(this.currentLogFile))try{let Q=JY(this.currentLogFile,"r+");UY(Q),JX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await MQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await DQ(UQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?M.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:U=!0}=Q,G=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(U)W.push(X);if(H==="warning")W.push("WARN");else if(H==="error")W.push("ERROR");else if(Y)W.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let J=x.stdout.columns||120,_="";if(H==="warning"||H==="error")_=`${Y} ${$}`;else if(H==="info"||H==="success")_=`${Y} ${Z} ${$}`;else _=`${Y} ${Z} ${M.cyan($)}`;if(!U)return _.trim();let q=G(_).trim().length,A=G(X).length,z=Math.max(1,J-2-q-A);return`${_.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let G=Number.parseInt(U,10);return G<X[0].length?String(X[0][G]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let G=X[Z++];switch(U){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return H}});if(Z<X.length)$+=` ${X.slice(Z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return $}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),H=this.formatFileTimestamp(Z),U,G;if(X instanceof Error)U=X.message,G=X.stack;else U=this.formatMessage(X,Y);if(this.fancy&&!S()){let _=YZ[Q],q=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.gray(U),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.green(U),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A),G){let z=G.split(`
2
+ import{_c as oX}from"./chunk-01d81hn0.js";import{dd as sX}from"./chunk-83srz04v.js";import{Qh as iX}from"./chunk-zwtx6vn3.js";import{fl as n}from"./chunk-s82adeq9.js";import{resolve as b8}from"path";import y8 from"process";import{existsSync as aX,statSync as eX}from"fs";import{resolve as wQ}from"path";import SZ from"process";import{existsSync as TZ,mkdirSync as m8,readdirSync as u8,readFileSync as OZ,writeFileSync as g8}from"fs";import{homedir as ZQ}from"os";import{dirname as n8,resolve as l}from"path";import QX from"process";import{existsSync as QY,statSync as XY}from"fs";import{existsSync as SX,mkdirSync as NZ,readdirSync as CZ,writeFileSync as xZ}from"fs";import{homedir as $Q}from"os";import{dirname as YY,resolve as y}from"path";import YQ from"process";import{join as kZ,relative as PZ,resolve as ZY}from"path";import mQ from"process";import{existsSync as gY,mkdirSync as Y9,readdirSync as Z9,writeFileSync as $9}from"fs";import{homedir as HX}from"os";import{dirname as J9,resolve as b}from"path";import KQ from"process";import{join as bZ,relative as yZ,resolve as $Y}from"path";import uQ from"process";import{existsSync as cY,mkdirSync as W9,readdirSync as z9,writeFileSync as B9}from"fs";import{dirname as w9,resolve as gQ}from"path";import VX from"process";import{Buffer as e}from"buffer";import{createCipheriv as vZ,createDecipheriv as hZ,randomBytes as UX}from"crypto";import{closeSync as JX,createReadStream as HY,createWriteStream as dZ,existsSync as GX,fsyncSync as UY,openSync as JY,writeFileSync as fZ}from"fs";import{access as pZ,constants as GY,mkdir as mZ,readdir as MQ,rename as _Y,stat as HQ,unlink as DQ,writeFile as _X}from"fs/promises";import{join as UQ}from"path";import x from"process";import{pipeline as uZ}from"stream/promises";import{createGzip as qY}from"zlib";import JQ from"process";import o from"process";import{Buffer as i}from"buffer";import{createCipheriv as gZ,createDecipheriv as cZ,randomBytes as qX}from"crypto";import{closeSync as AX,createReadStream as AY,createWriteStream as lZ,existsSync as SQ,fsyncSync as WY,openSync as zY,writeFileSync as nZ}from"fs";import{access as iZ,constants as BY,mkdir as sZ,readdir as VQ,rename as RY,stat as GQ,unlink as EQ,writeFile as WX}from"fs/promises";import{isAbsolute as oZ,join as _Q,resolve as rZ}from"path";import w from"process";import{pipeline as tZ}from"stream/promises";import{createGzip as wY}from"zlib";import qQ from"process";import r from"process";import TQ from"process";import{existsSync as OQ}from"fs";import{resolve as zX}from"path";import{existsSync as aZ}from"fs";import{existsSync as eZ,readdirSync as Q0}from"fs";import{extname as BX,resolve as LY}from"path";import X0 from"process";import{join as Y0,relative as Z0,resolve as KY}from"path";import cQ from"process";import{Buffer as s}from"buffer";import{createCipheriv as $0,createDecipheriv as H0,randomBytes as RX}from"crypto";import{closeSync as wX,createReadStream as jY,createWriteStream as U0,existsSync as NQ,fsyncSync as IY,openSync as FY,writeFileSync as J0}from"fs";import{access as G0,constants as MY,mkdir as _0,readdir as CQ,rename as DY,stat as AQ,unlink as xQ,writeFile as LX}from"fs/promises";import{isAbsolute as q0,join as WQ,resolve as A0}from"path";import L from"process";import{pipeline as W0}from"stream/promises";import{createGzip as SY}from"zlib";import zQ from"process";import t from"process";import PQ from"process";import{existsSync as bQ}from"fs";import{resolve as dY}from"path";import{existsSync as x8}from"fs";class fY{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!aX(Q))return!0;return eX(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=aX(Y)?eX(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class pY{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}var pQ=new fY,vX=new pY;var mY=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function uY(Q={}){let{name:X="",alias:Y}=Q,Z=["config",".config"];if(X)Z.push(X,`.${X}.config`,`${X}.config`,`.${X}`);let $=Y===void 0?[]:Array.isArray(Y)?Y:[Y];for(let H of $){if(!H)continue;if(Z.push(H,`.${H}.config`,`${H}.config`,`.${H}`),X)Z.push(`${X}.${H}.config`,`.${X}.${H}.config`)}return Array.from(new Set(Z.filter(Boolean)))}function VZ(Q){return uY(Q).flatMap((Y)=>mY.map((Z)=>wQ(Q.directory,`${Y}${Z}`)))}function EZ(Q={}){let X=wQ(Q.cwd||SZ.cwd());return Array.from(new Set([X,wQ(X,"config"),wQ(X,".config"),Q.configDir?wQ(X,Q.configDir):void 0].filter((Y)=>Boolean(Y))))}var z0=Object.defineProperty,B0=(Q)=>Q;function R0(Q,X){this[Q]=B0.bind(null,X)}var w0=(Q,X)=>{for(var Y in X)z0(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:R0.bind(X,Y)})},L0=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X),lY={};w0(lY,{withErrorRecovery:()=>sY,tryLoadConfig:()=>p0,loadConfigWithResult:()=>d0,loadConfig:()=>eY,isRetryableError:()=>k0,isConfigNotFoundError:()=>x0,isBunfigError:()=>oY,globalPerformanceMonitor:()=>FQ,globalCache:()=>BQ,getEnvOrDefault:()=>P0,generateConfigTypes:()=>m0,defaultGeneratedDir:()=>JZ,defaultConfigDir:()=>UZ,deepMergeWithArrayStrategy:()=>mX,deepMerge:()=>rY,createLibraryConfig:()=>u0,config:()=>f0,bunfigPlugin:()=>g0,applyEnvVarsToConfig:()=>LQ,TypeGenerationError:()=>kX,SchemaValidationError:()=>IQ,PluginError:()=>bX,PerformanceMonitor:()=>dX,FileSystemError:()=>xX,ErrorFactory:()=>QQ,EnvVarError:()=>rQ,EnvProcessor:()=>XX,ConfigValidator:()=>uX,ConfigValidationError:()=>NX,ConfigNotFoundError:()=>oQ,ConfigMergeError:()=>CX,ConfigLoader:()=>gX,ConfigLoadError:()=>jQ,ConfigFileLoader:()=>YX,ConfigCache:()=>hX,CacheUtils:()=>XZ,BunfigError:()=>h,BrowserConfigError:()=>PX,ArrayMergeStrategies:()=>$Z});class hX{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!QY(Q))return!0;return XY(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=QY(Y)?XY(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class dX{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}function K0(Q,X={}){let Z=Object.keys(X).sort().map(($)=>`${$}:${X[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function j0(Q,X){try{return JSON.stringify(Q)===JSON.stringify(X)}catch{return Q===X}}function I0(Q){return Q.getStats().size*2}function fX(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&D(X[0])&&"id"in X[0]&&X[0].id===3&&D(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(D(X)&&D(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(D(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&D(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&D(X[0])&&D(Q[0])){let Z=[...X];for(let $ of Q)if(D($)&&"name"in $){if(!Z.find((U)=>D(U)&&("name"in U)&&U.name===$.name))Z.push($)}else if(D($)&&"path"in $){if(!Z.find((U)=>D(U)&&("path"in U)&&U.path===$.path))Z.push($)}else if(!Z.some((H)=>lQ(H,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!D(X)||!D(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(D($)&&D(Y[Z]))Y[Z]=fX(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&D($[0])&&D(Y[Z][0])){let H=[...$];for(let U of Y[Z])if(D(U)&&"name"in U){if(!H.find((J)=>D(J)&&("name"in J)&&J.name===U.name))H.push(U)}else if(D(U)&&"path"in U){if(!H.find((J)=>D(J)&&("path"in J)&&J.path===U.path))H.push(U)}else if(!H.some((G)=>lQ(G,U)))H.push(U);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let U of Y[Z])if(!H.includes(U))H.push(U);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function lQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!lQ(Q[Y],X[Y]))return!1;return!0}if(D(Q)&&D(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!lQ(Q[$],X[$]))return!1}return!0}return!1}function D(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function F0(Q,X){if(!cY(Q))return null;try{let Y=await import(Q),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return fX(X,Z)}catch{return null}}catch{return null}}async function M0({name:Q="",cwd:X,defaultConfig:Y}){let Z=X||VX.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],H=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let U of H)for(let G of $){let J=gQ(Z,`${U}${G}`),_=await F0(J,Y);if(_!==null)return _}try{let U=gQ(Z,"package.json");if(cY(U)){let J=(await import(U))[Q];if(J&&typeof J==="object"&&!Array.isArray(J))try{return fX(Y,J)}catch{}}}catch{}return Y}function D0(Q,X={}){let Y=uQ.cwd();while(Y.includes("storage"))Y=$Y(Y,"..");let Z=$Y(Y,Q||"");if(X?.relative)return yZ(uQ.cwd(),Z);return Z}async function S0(){try{let Q=await M0({name:"clarity",defaultConfig:vQ,cwd:uQ.cwd(),endpoint:"",headers:{}});return{...vQ,...Q}}catch{return vQ}}function S(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function V0(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof o<"u"){let Q=o.type;if(Q==="renderer"||Q==="worker")return!1;return!!(o.versions&&(o.versions.node||o.versions.bun))}return!1}class nY{async format(Q){let X=await V0(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:JQ.pid,hostname:X(),environment:JQ.env.NODE_ENV||"development",platform:JQ.platform,version:JQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:JQ.env.NODE_ENV||JQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class nQ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,X={}){this.name=Q,this.config={...TX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new nY,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...hQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...hQ};return{...hQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:TX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,G=1000;while(H<U)try{try{try{await pZ(this.config.logDirectory,GY.F_OK|GY.W_OK)}catch(_){if(_ instanceof Error&&"code"in _)if(_.code==="ENOENT")await mZ(this.config.logDirectory,{recursive:!0,mode:493});else if(_.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw _;else throw _}}catch(_){throw console.error("Debug: [writeToFile] Failed to create log directory:",_),_}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:e.from(Q);try{if(!GX(this.currentLogFile))await _X(this.currentLogFile,"",{mode:420});if($=JY(this.currentLogFile,"a",420),fZ($,J,{flag:"a"}),UY($),$!==void 0)JX($),$=void 0;if((await HQ(this.currentLogFile)).size===0){if(await _X(this.currentLogFile,J,{flag:"w",mode:420}),(await HQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(_){let q=_;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(H<U-1){let A=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${U}:`,A);let z=G*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{JX($)}catch(_){console.error("Debug: [writeToFile] Error closing file descriptor:",_)}}}catch(J){if(H===U-1){let q=J,A=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}H++;let _=G*2**(H-1);await new Promise((q)=>setTimeout(q,_))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return UQ(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return UQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return UQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(S())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,G],[,J])=>J.createdAt.getTime()-G.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[G]of $.slice(U))this.encryptionKeys.delete(G),this.keys.delete(G)}generateKeyId(){return UX(16).toString("hex")}generateKey(){return UX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=UX(16),Z=vZ("aes-256-gcm",X,Y),$=e.concat([Z.update(Q,"utf8"),Z.final()]),H=Z.getAuthTag();return{encrypted:e.concat([Y,$,H]),iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=qY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(e.from(e.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(S())return;let Q=await HQ(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await MQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,_)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(_.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,G=`${Y}.${U}`;if(await HQ(Y).catch(()=>null))try{if(await _Y(Y,G),X.compress)try{let J=`${G}.gz`;await this.compressLogFile(G,J),await DQ(G)}catch(J){console.error("Error compressing rotated file:",J)}if(H.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await _X(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await HQ(Y).catch(()=>null))await _Y(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await MQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,G)=>G.localeCompare(U));for(let U of H.slice(X.maxFiles))await DQ(UQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=HY(Q),Z=dZ(X),$=qY();await uZ(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:Q,message:X,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),GX(this.currentLogFile))try{let Q=JY(this.currentLogFile,"r+");UY(Q),JX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await MQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await DQ(UQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?M.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:U=!0}=Q,G=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(U)W.push(X);if(H==="warning")W.push("WARN");else if(H==="error")W.push("ERROR");else if(Y)W.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let J=x.stdout.columns||120,_="";if(H==="warning"||H==="error")_=`${Y} ${$}`;else if(H==="info"||H==="success")_=`${Y} ${Z} ${$}`;else _=`${Y} ${Z} ${M.cyan($)}`;if(!U)return _.trim();let q=G(_).trim().length,A=G(X).length,z=Math.max(1,J-2-q-A);return`${_.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let G=Number.parseInt(U,10);return G<X[0].length?String(X[0][G]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let G=X[Z++];switch(U){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return H}});if(Z<X.length)$+=` ${X.slice(Z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return $}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),H=this.formatFileTimestamp(Z),U,G;if(X instanceof Error)U=X.message,G=X.stack;else U=this.formatMessage(X,Y);if(this.fancy&&!S()){let _=YZ[Q],q=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.gray(U),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.green(U),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A),G){let z=G.split(`
3
3
  `);for(let W of z)if(W.trim()&&!W.includes(U))console.error(this.formatConsoleMessage({timestamp:$,message:M.gray(` ${W}`),level:Q,showTimestamp:!1}))}break}}else if(!S()){if(console.error(`${H} ${this.environment}.${Q.toUpperCase()}: ${U}`),G)console.error(G)}if(!this.shouldLog(Q))return;let J=`${H} ${this.environment}.${Q.toUpperCase()}: ${U}
4
4
  `;if(G)J+=`${G}
5
5
  `;J=J.replace(this.ANSI_PATTERN,""),await this.writeToFile(J)}time(Q){let X=performance.now();if(this.fancy&&!S()){let Y=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:M.blue("\u25D0"),tag:Y,message:`${M.cyan(Q)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-X),H=`${Q} completed in ${$}ms`,U=new Date,G=this.formatConsoleTimestamp(U),_=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${H}`;if(Y)_+=` ${JSON.stringify(Y)}`;if(_+=`
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Vf as K,Xf as T,Yf as S,Zf as F}from"./chunk-z18bksyr.js";import{Jh as N}from"./chunk-b9szrnxw.js";import{Ph as C}from"./chunk-x1w6q9tk.js";import{el as _}from"./chunk-kbvj6qxc.js";var x={claude:"claude-opus-5","claude-opus":"claude-opus-5",opus:"claude-opus-5","claude-sonnet":"claude-sonnet-5",sonnet:"claude-sonnet-5","claude-haiku":"claude-haiku-4-5",haiku:"claude-haiku-4-5","claude-fable":"claude-fable-5",fable:"claude-fable-5"},L={anthropic:"claude-opus-5"},w={anthropic:["ANTHROPIC_API_KEY"],openai:["OPENAI_API_KEY"],google:["GOOGLE_API_KEY","GEMINI_API_KEY"],openrouter:["OPENROUTER_API_KEY"],"openai-compatible":["OPENAI_COMPATIBLE_API_KEY","OPENAI_API_KEY"]},D=["anthropic","openai","google","openrouter"];function M(j){return x[j.toLowerCase().trim()]??j}var b=16000;function k(j){let Z;async function $(){if(Z)return Z;let H;try{H=(await import("./chunk-ddky3026.js")).default}catch{throw new F(`The Anthropic provider needs @anthropic-ai/sdk, which is an optional peer dependency.
2
+ import{Vf as K,Xf as T,Yf as S,Zf as F}from"./chunk-z18bksyr.js";import{Kh as N}from"./chunk-34vracy4.js";import{Qh as C}from"./chunk-zwtx6vn3.js";import{fl as _}from"./chunk-s82adeq9.js";var x={claude:"claude-opus-5","claude-opus":"claude-opus-5",opus:"claude-opus-5","claude-sonnet":"claude-sonnet-5",sonnet:"claude-sonnet-5","claude-haiku":"claude-haiku-4-5",haiku:"claude-haiku-4-5","claude-fable":"claude-fable-5",fable:"claude-fable-5"},L={anthropic:"claude-opus-5"},w={anthropic:["ANTHROPIC_API_KEY"],openai:["OPENAI_API_KEY"],google:["GOOGLE_API_KEY","GEMINI_API_KEY"],openrouter:["OPENROUTER_API_KEY"],"openai-compatible":["OPENAI_COMPATIBLE_API_KEY","OPENAI_API_KEY"]},D=["anthropic","openai","google","openrouter"];function M(j){return x[j.toLowerCase().trim()]??j}var b=16000;function k(j){let Z;async function $(){if(Z)return Z;let H;try{H=(await import("./chunk-zrec546r.js")).default}catch{throw new F(`The Anthropic provider needs @anthropic-ai/sdk, which is an optional peer dependency.
3
3
  Install it with: bun add @anthropic-ai/sdk`,"anthropic")}return Z=new H({apiKey:j.apiKey,...j.baseUrl?{baseURL:j.baseUrl}:{}}),Z}return{name:"anthropic",async complete(H,G){let W={};if(H.effort)W.effort=H.effort;if(H.jsonSchema)W.format={type:"json_schema",schema:H.jsonSchema};let z=await(await $()).messages.create({model:G,max_tokens:H.maxTokens??b,...H.system?{system:H.system}:{},messages:H.messages.map((Q)=>({role:Q.role,content:Q.content})),...H.tools?.length?{tools:H.tools.map((Q)=>({name:Q.name,description:Q.description,input_schema:Q.parameters}))}:{},...Object.keys(W).length>0?{output_config:W}:{}}),X="",J=[];for(let Q of z.content)if(Q.type==="text")X+=Q.text;else if(Q.type==="tool_use")J.push({id:Q.id,name:Q.name,input:Q.input});return{text:X,toolCalls:J,json:y(X,H.jsonSchema!==void 0),stopReason:P(z.stop_reason),usage:{inputTokens:z.usage.input_tokens,outputTokens:z.usage.output_tokens,...z.usage.cache_read_input_tokens!=null?{cachedInputTokens:z.usage.cache_read_input_tokens}:{}},model:z.model}}}}function P(j){switch(j){case"end_turn":case"stop_sequence":return"end";case"tool_use":return"tool_use";case"max_tokens":return"max_tokens";case"refusal":return"refusal";default:return"other"}}function y(j,Z){if(!Z)return;try{return JSON.parse(j)}catch{throw new F("Model returned malformed JSON for a schema-constrained request","anthropic")}}var f=16000,A="https://generativelanguage.googleapis.com/v1beta";function U(j){let Z=(j.baseUrl??A).replace(/\/+$/,"");return{name:"google",async complete($,H){let G={contents:$.messages.map((Y)=>({role:Y.role==="assistant"?"model":"user",parts:[{text:Y.content}]})),generationConfig:{maxOutputTokens:$.maxTokens??f,...$.jsonSchema?{responseMimeType:"application/json",responseSchema:$.jsonSchema}:{}}};if($.system)G.systemInstruction={parts:[{text:$.system}]};if($.tools?.length)G.tools=[{functionDeclarations:$.tools.map((Y)=>({name:Y.name,description:Y.description,parameters:Y.parameters}))}];let W=await N(`${Z}/models/${encodeURIComponent(H)}:generateContent`,{method:"POST",headers:{"x-goog-api-key":j.apiKey,"Content-Type":"application/json"},body:JSON.stringify(G)});if(!W.ok){let Y=await W.text().catch(()=>"");throw new F(`google request failed: ${W.status} ${W.statusText} ${K(Y.slice(0,500))}`.trim(),"google",W.status)}let z=await W.json(),X=z.candidates?.[0],J="",Q=[];for(let[Y,V]of(X?.content?.parts??[]).entries()){if(V.text)J+=V.text;if(V.functionCall?.name)Q.push({id:`${V.functionCall.name}-${Y}`,name:V.functionCall.name,input:V.functionCall.args??{}})}return{text:J,toolCalls:Q,json:$.jsonSchema?h(J):void 0,stopReason:E(X?.finishReason,Q.length>0),usage:{inputTokens:z.usageMetadata?.promptTokenCount??0,outputTokens:z.usageMetadata?.candidatesTokenCount??0,...z.usageMetadata?.cachedContentTokenCount!=null?{cachedInputTokens:z.usageMetadata.cachedContentTokenCount}:{}},model:z.modelVersion??H}}}}function E(j,Z){if(Z)return"tool_use";switch(j){case"STOP":return"end";case"MAX_TOKENS":return"max_tokens";case"SAFETY":case"PROHIBITED_CONTENT":case"BLOCKLIST":return"refusal";default:return"other"}}function h(j){try{return JSON.parse(j)}catch{throw new F("Model returned malformed JSON for a schema-constrained request","google")}}var g=16000,v="https://api.openai.com/v1",m="https://openrouter.ai/api/v1";function O(j){let Z=j.provider??"openai",$=(j.baseUrl??q(Z)).replace(/\/+$/,"");return{name:Z,async complete(H,G){let W=[];if(H.system)W.push({role:"system",content:H.system});for(let B of H.messages)W.push({role:B.role,content:B.content});let z={model:G,messages:W,max_completion_tokens:H.maxTokens??g};if(H.tools?.length)z.tools=H.tools.map((B)=>({type:"function",function:{name:B.name,description:B.description,parameters:B.parameters}}));if(H.jsonSchema)z.response_format={type:"json_schema",json_schema:{name:"response",schema:H.jsonSchema,strict:!0}};if(H.effort)z.reasoning_effort=H.effort;let X={Authorization:`Bearer ${j.apiKey}`,"Content-Type":"application/json"};if(Z==="openrouter")X["HTTP-Referer"]="https://github.com/stacksjs/buddy",X["X-Title"]="buddy";let J=await N(`${$}/chat/completions`,{method:"POST",headers:X,body:JSON.stringify(z)});if(!J.ok){let B=await J.text().catch(()=>"");throw new F(`${Z} request failed: ${J.status} ${J.statusText} ${K(B.slice(0,500))}`.trim(),Z,J.status)}let Q=await J.json(),Y=Q.choices?.[0],V=Y?.message?.content??"",I=(Y?.message?.tool_calls??[]).map((B)=>({id:B.id,name:B.function?.name??"",input:p(B.function?.arguments,Z)}));return{text:V,toolCalls:I,json:H.jsonSchema?d(V,Z):void 0,stopReason:c(Y?.finish_reason,I.length>0),usage:{inputTokens:Q.usage?.prompt_tokens??0,outputTokens:Q.usage?.completion_tokens??0,...Q.usage?.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:Q.usage.prompt_tokens_details.cached_tokens}:{}},model:Q.model??G}}}}function q(j){return j==="openrouter"?m:v}function c(j,Z){if(Z||j==="tool_calls")return"tool_use";switch(j){case"stop":return"end";case"length":return"max_tokens";case"content_filter":return"refusal";default:return"other"}}function p(j,Z){if(!j)return{};try{return JSON.parse(j)}catch{throw new F("Model returned malformed JSON tool arguments",Z)}}function d(j,Z){try{return JSON.parse(j)}catch{throw new F("Model returned malformed JSON for a schema-constrained request",Z)}}import R from"process";function u(j,Z=R.env){let $=j.ai;if($?.enabled===!1)return null;let H=$?.provider?[$.provider]:D;for(let G of H){let W=i(G,$?.apiKeyEnv,Z);if(!W)continue;let{key:z,source:X}=W,J=a(G,$?.model);if(!J)continue;return{provider:G,model:J,apiKey:z,apiKeyEnv:X,...$?.baseUrl?{baseUrl:$.baseUrl}:{}}}return null}function Vj(j,Z=C()){let $=u(j);if(!$)return Z.debug("AI disabled: no provider configured with an available API key"),null;let H=n($),G=j.ai?.maxTokensPerRun,W=j.ai?.effort,z=0;return{provider:$.provider,model:$.model,get tokensUsed(){return z},async complete(X){if(G!==void 0&&z>=G)throw new S(z,G);let J=X.model?M(X.model):$.model;try{let Q=await H.complete({...X,effort:X.effort??W},J);return z+=Q.usage.outputTokens,Z.debug(`AI ${$.provider}/${Q.model}: ${Q.usage.inputTokens} in, ${Q.usage.outputTokens} out (${Q.stopReason})`),Q}catch(Q){if(Q instanceof S)throw Q;let Y=T(Q);throw Z.warn(`\u26A0\uFE0F AI request failed (${$.provider}): ${Y}`),Q instanceof F?Q:new F(Y,$.provider)}}}}function n(j){switch(j.provider){case"anthropic":return k({apiKey:j.apiKey,baseUrl:j.baseUrl});case"google":return U({apiKey:j.apiKey,baseUrl:j.baseUrl});case"openai":case"openrouter":case"openai-compatible":return O({apiKey:j.apiKey,baseUrl:j.baseUrl,provider:j.provider})}}function i(j,Z,$){let H=Z?[Z,...w[j]]:w[j];for(let G of H){let W=$[G];if(W&&W.trim().length>0)return{key:W.trim(),source:G}}return}function a(j,Z){let $=R.env.BUDDY_MODEL||Z;if($)return M($);return L[j]}
4
4
  export{x as Zb,w as _b,D as $b,M as ac,k as bc,U as cc,O as dc,u as ec,Vj as fc};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{We as c}from"./chunk-gpjde0j6.js";import{bg as l,kg as A}from"./chunk-xdrvb89m.js";import{sg as y}from"./chunk-knpdntnh.js";import{yh as k}from"./chunk-2z9pkk1y.js";import{Ph as i}from"./chunk-x1w6q9tk.js";import u from"process";var d=/\{([a-z_]+)\}/gi,b={title:"title",message:"message",group:"group",count:"count",strategy:"strategy",update_type:"updateType",updateType:"updateType",packages:"packages",updates_table:"updatesTable",release_notes:"releaseNotes",footer:"footer",package_count:"packageCount"};function h(W,$){return W.replace(d,(Y,R)=>{let K=b[R]??b[R.toLowerCase()];if(!K)return Y;let H=$[K];return H===void 0?Y:String(H)})}function f(W,$={},Y){return{...$,group:W.name,count:W.updates.length,packageCount:W.updates.length,updateType:W.updateType,packages:W.updates.map((R)=>R.name).join(", "),...Y?{strategy:Y}:{}}}class p{config;releaseNotesFetcher=new c;verbose=!1;logger;constructor(W,$){this.config=W;this.verbose=W?.verbose||u.env.BUDDY_VERBOSE==="true",this.logger=$??i()}get releaseNotesSettings(){let W=this.config?.releaseNotes;return{enabled:W?.enabled??!0,maxReleases:W?.maxReleases??3,maxBodyLength:W?.maxBodyLength??1000,includeCompareLinks:W?.includeCompareLinks??!0}}repositoryFileUrl(W){let $=k(this.config),{owner:Y,name:R,baseBranch:K}=this.config?.repository??{};return`${$}/${Y}/${R}/blob/${K||"main"}/${W}`}log(W,$){if(this.verbose){let Y=new Date().toISOString();if(this.logger.info(`[${Y}] PR-GEN: ${W}`),$)this.logger.info(JSON.stringify($,null,2))}}async generatePullRequests(W){let $=[];for(let Y of W){let R=this.generateTitle(Y),K=await this.generateBody(Y),H={number:0,title:R,body:K,head:`buddy/update-${Y.name.toLowerCase().replace(/\s+/g,"-")}`,base:"main",state:"open",url:"",createdAt:new Date,updatedAt:new Date,author:"github-actions[bot]",reviewers:[],assignees:[],labels:this.generateLabels(Y),draft:!1};$.push(H)}return $}generateLabels(W){let $=["dependencies"];if(W.updateType==="major")$.push("major");else if(W.updateType==="minor")$.push("minor");else if(W.updateType==="patch")$.push("patch");let Y=W.updates.filter((D)=>D.file==="package.json"||D.file.endsWith("/package.json")||D.file.endsWith("\\package.json")).length,R=W.updates.filter((D)=>D.file.endsWith("composer.json")||D.file.endsWith("composer.lock")).length,K=W.updates.filter((D)=>D.file.endsWith("build.zig.zon")).length,H=W.updates.filter((D)=>(D.file.includes(".yaml")||D.file.includes(".yml"))&&!D.file.includes(".github/workflows/")).length,Z=W.updates.filter((D)=>D.file.includes(".github/workflows/")).length;if(Y>0)$.push("npm");if(R>0)$.push("composer");if(K>0)$.push("zig");if(H>0)$.push("system");if(Z>0)$.push("github-actions");if(W.updates.length===1){let D=W.updates[0];$.push(D.name)}if(W.updates.length>=5)$.push("bulk-update");return $}generateTitle(W){let $=this.config?.pullRequest?.titleFormat;if($)return h($,f(W,{title:this.defaultTitle(W)},this.config?.packages?.strategy));return this.defaultTitle(W)}defaultTitle(W){if(W.updates.length===1){let R=W.updates[0];return`chore(deps): update dependency ${R.name} to v${R.newVersion}`}let $=W.updates.filter((R)=>R.updateType==="major").length,Y=W.updates.filter((R)=>R.updateType==="minor").length;if($>0)return`chore(deps): update ${W.updates.length} dependencies (major)`;else if(Y>0)return`chore(deps): update ${W.updates.length} dependencies (minor)`;else return`chore(deps): update ${W.updates.length} dependencies (patch)`}async generateBody(W){if(this.log("\uD83D\uDE80 Starting PR body generation",{groupName:W.name,totalUpdates:W.updates.length,updates:W.updates.map((Q)=>({name:Q.name,file:Q.file,dependencyType:Q.dependencyType,currentVersion:Q.currentVersion,newVersion:Q.newVersion,updateType:Q.updateType}))}),W.updates.length===0)this.log("\u26A0\uFE0F WARNING: No updates in group - this will result in sparse PR body",{groupName:W.name,groupTitle:W.title});let $=W.updates.filter((Q)=>Q.file==="package.json"||Q.file.endsWith("/package.json")||Q.file.endsWith("\\package.json")).length,Y=W.updates.filter((Q)=>(Q.file.includes(".yaml")||Q.file.includes(".yml"))&&!Q.file.includes(".github/workflows/")).length,R=W.updates.filter((Q)=>Q.file.includes(".github/workflows/")).length,K=W.updates.filter((Q)=>Q.file.endsWith("composer.json")||Q.file.endsWith("composer.lock")).length,H=W.updates.filter((Q)=>Q.file.endsWith("build.zig.zon")).length;if(this.log("\uD83D\uDCCA Package type counts",{packageJsonCount:$,dependencyFileCount:Y,githubActionsCount:R,composerCount:K,total:W.updates.length}),W.updates.length>0)this.log("\uD83D\uDD0D File path analysis",{files:W.updates.map((Q)=>({name:Q.name,file:Q.file,isExactMatch:Q.file==="package.json",endsWithSlash:Q.file.endsWith("/package.json"),endsWithBackslash:Q.file.endsWith("\\package.json"),matchesAny:Q.file==="package.json"||Q.file.endsWith("/package.json")||Q.file.endsWith("\\package.json")}))});let Z=`This PR contains the following updates:
2
+ import{We as c}from"./chunk-92gh2n65.js";import{bg as l,kg as A}from"./chunk-zy49dwqk.js";import{sg as y}from"./chunk-x9vpk4kk.js";import{zh as k}from"./chunk-7t8s2mcf.js";import{Qh as i}from"./chunk-zwtx6vn3.js";import u from"process";var d=/\{([a-z_]+)\}/gi,b={title:"title",message:"message",group:"group",count:"count",strategy:"strategy",update_type:"updateType",updateType:"updateType",packages:"packages",updates_table:"updatesTable",release_notes:"releaseNotes",footer:"footer",package_count:"packageCount"};function h(W,$){return W.replace(d,(Y,R)=>{let K=b[R]??b[R.toLowerCase()];if(!K)return Y;let H=$[K];return H===void 0?Y:String(H)})}function f(W,$={},Y){return{...$,group:W.name,count:W.updates.length,packageCount:W.updates.length,updateType:W.updateType,packages:W.updates.map((R)=>R.name).join(", "),...Y?{strategy:Y}:{}}}class p{config;releaseNotesFetcher=new c;verbose=!1;logger;constructor(W,$){this.config=W;this.verbose=W?.verbose||u.env.BUDDY_VERBOSE==="true",this.logger=$??i()}get releaseNotesSettings(){let W=this.config?.releaseNotes;return{enabled:W?.enabled??!0,maxReleases:W?.maxReleases??3,maxBodyLength:W?.maxBodyLength??1000,includeCompareLinks:W?.includeCompareLinks??!0}}repositoryFileUrl(W){let $=k(this.config),{owner:Y,name:R,baseBranch:K}=this.config?.repository??{};return`${$}/${Y}/${R}/blob/${K||"main"}/${W}`}log(W,$){if(this.verbose){let Y=new Date().toISOString();if(this.logger.info(`[${Y}] PR-GEN: ${W}`),$)this.logger.info(JSON.stringify($,null,2))}}async generatePullRequests(W){let $=[];for(let Y of W){let R=this.generateTitle(Y),K=await this.generateBody(Y),H={number:0,title:R,body:K,head:`buddy/update-${Y.name.toLowerCase().replace(/\s+/g,"-")}`,base:"main",state:"open",url:"",createdAt:new Date,updatedAt:new Date,author:"github-actions[bot]",reviewers:[],assignees:[],labels:this.generateLabels(Y),draft:!1};$.push(H)}return $}generateLabels(W){let $=["dependencies"];if(W.updateType==="major")$.push("major");else if(W.updateType==="minor")$.push("minor");else if(W.updateType==="patch")$.push("patch");let Y=W.updates.filter((D)=>D.file==="package.json"||D.file.endsWith("/package.json")||D.file.endsWith("\\package.json")).length,R=W.updates.filter((D)=>D.file.endsWith("composer.json")||D.file.endsWith("composer.lock")).length,K=W.updates.filter((D)=>D.file.endsWith("build.zig.zon")).length,H=W.updates.filter((D)=>(D.file.includes(".yaml")||D.file.includes(".yml"))&&!D.file.includes(".github/workflows/")).length,Z=W.updates.filter((D)=>D.file.includes(".github/workflows/")).length;if(Y>0)$.push("npm");if(R>0)$.push("composer");if(K>0)$.push("zig");if(H>0)$.push("system");if(Z>0)$.push("github-actions");if(W.updates.length===1){let D=W.updates[0];$.push(D.name)}if(W.updates.length>=5)$.push("bulk-update");return $}generateTitle(W){let $=this.config?.pullRequest?.titleFormat;if($)return h($,f(W,{title:this.defaultTitle(W)},this.config?.packages?.strategy));return this.defaultTitle(W)}defaultTitle(W){if(W.updates.length===1){let R=W.updates[0];return`chore(deps): update dependency ${R.name} to v${R.newVersion}`}let $=W.updates.filter((R)=>R.updateType==="major").length,Y=W.updates.filter((R)=>R.updateType==="minor").length;if($>0)return`chore(deps): update ${W.updates.length} dependencies (major)`;else if(Y>0)return`chore(deps): update ${W.updates.length} dependencies (minor)`;else return`chore(deps): update ${W.updates.length} dependencies (patch)`}async generateBody(W){if(this.log("\uD83D\uDE80 Starting PR body generation",{groupName:W.name,totalUpdates:W.updates.length,updates:W.updates.map((Q)=>({name:Q.name,file:Q.file,dependencyType:Q.dependencyType,currentVersion:Q.currentVersion,newVersion:Q.newVersion,updateType:Q.updateType}))}),W.updates.length===0)this.log("\u26A0\uFE0F WARNING: No updates in group - this will result in sparse PR body",{groupName:W.name,groupTitle:W.title});let $=W.updates.filter((Q)=>Q.file==="package.json"||Q.file.endsWith("/package.json")||Q.file.endsWith("\\package.json")).length,Y=W.updates.filter((Q)=>(Q.file.includes(".yaml")||Q.file.includes(".yml"))&&!Q.file.includes(".github/workflows/")).length,R=W.updates.filter((Q)=>Q.file.includes(".github/workflows/")).length,K=W.updates.filter((Q)=>Q.file.endsWith("composer.json")||Q.file.endsWith("composer.lock")).length,H=W.updates.filter((Q)=>Q.file.endsWith("build.zig.zon")).length;if(this.log("\uD83D\uDCCA Package type counts",{packageJsonCount:$,dependencyFileCount:Y,githubActionsCount:R,composerCount:K,total:W.updates.length}),W.updates.length>0)this.log("\uD83D\uDD0D File path analysis",{files:W.updates.map((Q)=>({name:Q.name,file:Q.file,isExactMatch:Q.file==="package.json",endsWithSlash:Q.file.endsWith("/package.json"),endsWithBackslash:Q.file.endsWith("\\package.json"),matchesAny:Q.file==="package.json"||Q.file.endsWith("/package.json")||Q.file.endsWith("\\package.json")}))});let Z=`This PR contains the following updates:
3
3
 
4
4
  `;Z+=l(W.updates);let D=W.updates.length>1;if(D){if(Z+=`## Package Updates Summary
5
5
 
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{kd as a}from"./chunk-x9qhsyp6.js";import"./chunk-bnp0r4eh.js";import"./chunk-0f1xye20.js";import"./chunk-zy49dwqk.js";import"./chunk-x9vpk4kk.js";import"./chunk-94tnmc7j.js";import"./chunk-drmk6r1m.js";import"./chunk-7t8s2mcf.js";import"./chunk-34vracy4.js";import"./chunk-zwtx6vn3.js";import"./chunk-028354j6.js";import"./chunk-s82adeq9.js";export{a as RegistryClient};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Eh as Z}from"./chunk-vpw7adwd.js";import{Ph as K}from"./chunk-x1w6q9tk.js";var R=".buddy/reports.jsonl",U=52;function X(M){if(!M?.trim())return[];let E=[];for(let j of M.split(`
2
+ import{Fh as Z}from"./chunk-j6geg3qt.js";import{Qh as K}from"./chunk-zwtx6vn3.js";var R=".buddy/reports.jsonl",U=52;function X(M){if(!M?.trim())return[];let E=[];for(let j of M.split(`
3
3
  `)){if(!j.trim())continue;try{let N=JSON.parse(j);if(N?.period&&N.generatedAt&&N.health&&N.activity)E.push(N)}catch{continue}}return E}function x(M,E){return`${[...M,E].slice(-U).map((N)=>JSON.stringify(N)).join(`
4
4
  `)}
5
5
  `}function W(M,E){for(let j=M.length-1;j>=0;j--)if(M[j].period===E)return M[j];return null}async function _(M,E,j=K()){try{return X(await M.getFileContent(R,E))}catch(N){return j.debug(`No report history at ${R}: ${N}`),[]}}var k=["7d","30d","90d"],O={"7d":7,"30d":30,"90d":90};function A(M){let E=new Date(M.now.getTime()-O[M.period]*24*60*60*1000),j=M.pullRequests.filter((q)=>M.branchPrefix?q.head.startsWith(M.branchPrefix):Z(q.head)),N=j.filter((q)=>q.createdAt>=E),C=j.filter((q)=>q.mergedAt!==void 0&&q.mergedAt>=E),z=j.filter((q)=>q.state==="closed"&&q.mergedAt===void 0&&q.updatedAt>=E),F=C.map((q)=>(q.mergedAt.getTime()-q.createdAt.getTime())/3600000).sort((q,Q)=>q-Q),H=Object.values(M.dependenciesByEcosystem).reduce((q,Q)=>q+Q,0),J=M.updates.length;return{period:M.period,generatedAt:M.now.toISOString(),health:{byEcosystem:{...M.dependenciesByEcosystem},total:H,outdated:J,outdatedPercent:H>0?Math.round(J/H*100):0,majorBehind:M.updates.filter((q)=>q.updateType==="major").length,vulnerable:M.updates.filter((q)=>(q.securityAdvisories?.length??0)>0).length,deprecated:M.deprecated??0,drifted:M.drifted??0},activity:{opened:N.length,merged:C.length,closed:z.length,open:j.filter((q)=>q.state==="open").length,medianHoursToMerge:L(F),mergeRate:N.length>0?Math.round(C.length/N.length*100):0}}}function L(M){if(M.length===0)return null;let E=Math.floor(M.length/2),j=M.length%2===0?(M[E-1]+M[E])/2:M[E];return Math.round(j*10)/10}function S(M,E){if(!E)return{};let j=new Set(["merged","mergeRate"]),N=[["outdated",M.health.outdated,E.health.outdated],["majorBehind",M.health.majorBehind,E.health.majorBehind],["vulnerable",M.health.vulnerable,E.health.vulnerable],["deprecated",M.health.deprecated,E.health.deprecated],["opened",M.activity.opened,E.activity.opened],["merged",M.activity.merged,E.activity.merged],["mergeRate",M.activity.mergeRate,E.activity.mergeRate]],C={};for(let[z,F,H]of N){let J=F-H;C[z]={current:F,previous:H,change:J,improved:j.has(z)?J>=0:J<=0}}return C}var $="<!-- buddy:report -->";function G(M){if(!M||M.change===0)return"\u2014";let E=M.change>0?"\u25B2":"\u25BC",j=M.change>0?"+":"";return`${E} ${j}${M.change}${M.improved?"":" \u26A0\uFE0F"}`}function T(M,E={}){let j=O[M.period],N=[$,"",`## Dependency report \u2014 last ${j} days`,"",`Generated ${M.generatedAt.slice(0,10)}.`,"","### Dependency health","","| Metric | Value | Change |","| --- | --- | --- |",`| Total dependencies | ${M.health.total} | |`,`| Outdated | ${M.health.outdated} (${M.health.outdatedPercent}%) | ${G(E.outdated)} |`,`| A major behind | ${M.health.majorBehind} | ${G(E.majorBehind)} |`,`| With known advisories | ${M.health.vulnerable} | ${G(E.vulnerable)} |`,`| Deprecated | ${M.health.deprecated} | ${G(E.deprecated)} |`];if(M.health.drifted>0)N.push(`| Held back by a dependant | ${M.health.drifted} | |`);N.push("","### By ecosystem","");let C=Object.entries(M.health.byEcosystem).filter(([,z])=>z>0).sort(([,z],[,F])=>F-z);if(C.length===0)N.push("No dependencies detected.");else{N.push("| Ecosystem | Dependencies |","| --- | --- |");for(let[z,F]of C)N.push(`| ${z} | ${F} |`)}if(N.push("","### Bot activity","","| Metric | Value | Change |","| --- | --- | --- |",`| Pull requests opened | ${M.activity.opened} | ${G(E.opened)} |`,`| Merged | ${M.activity.merged} | ${G(E.merged)} |`,`| Closed without merging | ${M.activity.closed} | |`,`| Currently open | ${M.activity.open} | |`),M.activity.medianHoursToMerge!==null)N.push(`| Median time to merge | ${w(M.activity.medianHoursToMerge)} | |`);if(N.push(`| Merged vs opened | ${M.activity.mergeRate}% | ${G(E.mergeRate)} |`),N.push("",`_"Merged vs opened" compares both counts within the same ${j}-day window, so`,"recently opened pull requests depress it by definition._"),Object.keys(E).length===0)N.push("","_No previous report to compare against; this is the baseline._");return N.join(`
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Ph as X}from"./chunk-x1w6q9tk.js";import"./chunk-kbvj6qxc.js";import{readFileSync as _}from"fs";function L(q){let z=q.split("/").pop()||"";return z==="composer.json"||z==="composer.lock"}async function R(q,z){try{let j=JSON.parse(z),A=[];if(j.require)J(j.require,"require",q,A);if(j["require-dev"])J(j["require-dev"],"require-dev",q,A);return{path:q,type:"composer.json",content:z,dependencies:A}}catch(j){return X().warn(`Failed to parse composer.json file ${q}:`,j),null}}async function S(q,z){try{let j=JSON.parse(z),A=[];if(j.packages){for(let b of j.packages)if(b.name&&b.version)A.push({name:b.name,currentVersion:b.version,type:"require",file:q})}if(j["packages-dev"]){for(let b of j["packages-dev"])if(b.name&&b.version)A.push({name:b.name,currentVersion:b.version,type:"require-dev",file:q})}return{path:q,type:"composer.lock",content:z,dependencies:A}}catch(j){return X().warn(`Failed to parse composer.lock file ${q}:`,j),null}}async function v(q,z){let j=q.split("/").pop()||"";if(j==="composer.json")return R(q,z);if(j==="composer.lock")return S(q,z);return null}function J(q,z,j,A){for(let[b,Z]of Object.entries(q)){if(b==="php"||b.startsWith("ext-"))continue;if(b.includes("/"))A.push({name:b,currentVersion:Z,type:z,file:j})}}async function U(q){let z=[],j=q.filter((b)=>b.file.endsWith("composer.json"));if(j.length===0)return z;let A=new Map;for(let b of j){if(!A.has(b.file))A.set(b.file,[]);A.get(b.file).push({name:b.name,newVersion:b.newVersion})}for(let[b,Z]of A)try{let K=_(b,"utf-8"),T=JSON.parse(K);for(let E of Z){let Y=!1;if(T.require&&T.require[E.name]){let H=T.require[E.name],O;if(H.includes(",")){let G=H.match(/\d+\.\d+(?:\.\d+)?/),Q=G?G[0]:null;O=H.replace(/\d+\.\d+(?:\.\d+)?/g,(W)=>{return Q!==null&&W===Q?E.newVersion:W})}else{let G=H.match(/^(\D*)/);O=`${G?G[1]:""}${E.newVersion}`}let $=new RegExp(`("${E.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}"\\s*:\\s*")([^"]+)(")`,"g");K=K.replace($,`$1${O}$3`),Y=!0}if(!Y&&T["require-dev"]&&T["require-dev"][E.name]){let H=T["require-dev"][E.name],O;if(H.includes(",")){let G=H.match(/\d+\.\d+(?:\.\d+)?/),Q=G?G[0]:null;O=H.replace(/\d+\.\d+(?:\.\d+)?/g,(W)=>{return Q!==null&&W===Q?E.newVersion:W})}else{let G=H.match(/^(\D*)/);O=`${G?G[1]:""}${E.newVersion}`}let $=new RegExp(`("${E.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}"\\s*:\\s*")([^"]+)(")`,"g");K=K.replace($,`$1${O}$3`),Y=!0}if(!Y)X().warn(`Package ${E.name} not found in ${b}`)}z.push({path:b,content:K,type:"update"})}catch(K){X().error(`Failed to update ${b}:`,K)}return z}export{S as parseComposerLock,R as parseComposerJson,v as parseComposerFile,L as isComposerFile,U as generateComposerUpdates};
2
+ import{Qh as X}from"./chunk-zwtx6vn3.js";import"./chunk-s82adeq9.js";import{readFileSync as _}from"fs";function L(q){let z=q.split("/").pop()||"";return z==="composer.json"||z==="composer.lock"}async function R(q,z){try{let j=JSON.parse(z),A=[];if(j.require)J(j.require,"require",q,A);if(j["require-dev"])J(j["require-dev"],"require-dev",q,A);return{path:q,type:"composer.json",content:z,dependencies:A}}catch(j){return X().warn(`Failed to parse composer.json file ${q}:`,j),null}}async function S(q,z){try{let j=JSON.parse(z),A=[];if(j.packages){for(let b of j.packages)if(b.name&&b.version)A.push({name:b.name,currentVersion:b.version,type:"require",file:q})}if(j["packages-dev"]){for(let b of j["packages-dev"])if(b.name&&b.version)A.push({name:b.name,currentVersion:b.version,type:"require-dev",file:q})}return{path:q,type:"composer.lock",content:z,dependencies:A}}catch(j){return X().warn(`Failed to parse composer.lock file ${q}:`,j),null}}async function v(q,z){let j=q.split("/").pop()||"";if(j==="composer.json")return R(q,z);if(j==="composer.lock")return S(q,z);return null}function J(q,z,j,A){for(let[b,Z]of Object.entries(q)){if(b==="php"||b.startsWith("ext-"))continue;if(b.includes("/"))A.push({name:b,currentVersion:Z,type:z,file:j})}}async function U(q){let z=[],j=q.filter((b)=>b.file.endsWith("composer.json"));if(j.length===0)return z;let A=new Map;for(let b of j){if(!A.has(b.file))A.set(b.file,[]);A.get(b.file).push({name:b.name,newVersion:b.newVersion})}for(let[b,Z]of A)try{let K=_(b,"utf-8"),T=JSON.parse(K);for(let E of Z){let Y=!1;if(T.require&&T.require[E.name]){let H=T.require[E.name],O;if(H.includes(",")){let G=H.match(/\d+\.\d+(?:\.\d+)?/),Q=G?G[0]:null;O=H.replace(/\d+\.\d+(?:\.\d+)?/g,(W)=>{return Q!==null&&W===Q?E.newVersion:W})}else{let G=H.match(/^(\D*)/);O=`${G?G[1]:""}${E.newVersion}`}let $=new RegExp(`("${E.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}"\\s*:\\s*")([^"]+)(")`,"g");K=K.replace($,`$1${O}$3`),Y=!0}if(!Y&&T["require-dev"]&&T["require-dev"][E.name]){let H=T["require-dev"][E.name],O;if(H.includes(",")){let G=H.match(/\d+\.\d+(?:\.\d+)?/),Q=G?G[0]:null;O=H.replace(/\d+\.\d+(?:\.\d+)?/g,(W)=>{return Q!==null&&W===Q?E.newVersion:W})}else{let G=H.match(/^(\D*)/);O=`${G?G[1]:""}${E.newVersion}`}let $=new RegExp(`("${E.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}"\\s*:\\s*")([^"]+)(")`,"g");K=K.replace($,`$1${O}$3`),Y=!0}if(!Y)X().warn(`Package ${E.name} not found in ${b}`)}z.push({path:b,content:K,type:"update"})}catch(K){X().error(`Failed to update ${b}:`,K)}return z}export{S as parseComposerLock,R as parseComposerJson,v as parseComposerFile,L as isComposerFile,U as generateComposerUpdates};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{$e as e,Xe as a,Ye as b,Ze as c,_e as d,af as f,bf as g,cf as h}from"./chunk-j46f90n8.js";import"./chunk-kbvj6qxc.js";export{e as resolveEngineVersion,d as pinBlocksUpdate,b as extractEngines,g as engineUpdateType,c as collectResolutionPins,f as bumpEngineConstraint,h as applyEngineUpdates,a as KNOWN_ENGINES};
2
+ import{$e as e,Xe as a,Ye as b,Ze as c,_e as d,af as f,bf as g,cf as h}from"./chunk-j46f90n8.js";import"./chunk-s82adeq9.js";export{e as resolveEngineVersion,d as pinBlocksUpdate,b as extractEngines,g as engineUpdateType,c as collectResolutionPins,f as bumpEngineConstraint,h as applyEngineUpdates,a as KNOWN_ENGINES};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Eb as _,Fb as y}from"./chunk-q2tjkhez.js";import{Mb as g,Nb as r,Ob as e,Pb as jj}from"./chunk-5yfaptmp.js";import{Wb as n,Xb as o,Yb as t}from"./chunk-59993g25.js";import{fc as s}from"./chunk-va3k91tf.js";import{fe as i}from"./chunk-0g4ybxwj.js";import{se as S}from"./chunk-b6a5txek.js";import{Sf as b,Tf as m}from"./chunk-24xvskkf.js";import{Ph as Y}from"./chunk-x1w6q9tk.js";var C=["critical","major","minor","nit"],w={type:"object",properties:{summary:{type:"string",description:"One paragraph on what this change does"},effort:{type:"integer",description:"Reviewer effort, 1 (trivial) to 5 (demanding)"},walkthrough:{type:"array",items:{type:"object",properties:{path:{type:"string"},description:{type:"string"}},required:["path","description"],additionalProperties:!1}},findings:{type:"array",items:{type:"object",properties:{path:{type:"string",description:"Repository-relative path"},line:{type:"integer",description:"Line number on the new side of the diff"},severity:{type:"string",enum:C},category:{type:"string",description:"Short slug, e.g. correctness or security"},message:{type:"string",description:"What is wrong and why it matters"},suggestion:{type:"string",description:"Replacement code, only when the fix is mechanical"}},required:["path","line","severity","category","message"],additionalProperties:!1}}},required:["summary","effort","walkthrough","findings"],additionalProperties:!1};function I(J){let j=J.message.toLowerCase().replace(/\s+/g," ").trim().slice(0,120);return`${J.path}:${J.category}:${j}`}function N(J,j){let Q=[],Z=[];for(let $ of J)if(j.get($.path)?.has($.line))Q.push($);else Z.push($);return Q.sort(($,X)=>C.indexOf($.severity)-C.indexOf(X.severity)),{valid:Q,dropped:Z}}function v(J,j){let Q=[],Z=new Set;for(let $ of J){let X=I($);if(j.has(X)||Z.has(X))continue;Z.add(X),Q.push($)}return Q}var Jj=[/(?:^|\/)(?:bun\.lockb?|package-lock\.json|yarn\.lock|pnpm-lock\.yaml|composer\.lock|pantry\.lock)$/,/(?:^|\/)(?:dist|build|out|coverage|node_modules|vendor)\//,/\.min\.(?:js|css)$/,/(?:^|\/)(?:.*\.snap)$/],Qj=`You are reviewing a pull request diff.
2
+ import{Eb as _,Fb as y}from"./chunk-q2tjkhez.js";import{Mb as g,Nb as r,Ob as e,Pb as jj}from"./chunk-5yfaptmp.js";import{Wb as n,Xb as o,Yb as t}from"./chunk-sn0qr6q7.js";import{fc as s}from"./chunk-5sh69bkj.js";import{fe as i}from"./chunk-2b07w74s.js";import{se as S}from"./chunk-y1d6e0ye.js";import{Sf as b,Tf as m}from"./chunk-24xvskkf.js";import{Qh as Y}from"./chunk-zwtx6vn3.js";var C=["critical","major","minor","nit"],w={type:"object",properties:{summary:{type:"string",description:"One paragraph on what this change does"},effort:{type:"integer",description:"Reviewer effort, 1 (trivial) to 5 (demanding)"},walkthrough:{type:"array",items:{type:"object",properties:{path:{type:"string"},description:{type:"string"}},required:["path","description"],additionalProperties:!1}},findings:{type:"array",items:{type:"object",properties:{path:{type:"string",description:"Repository-relative path"},line:{type:"integer",description:"Line number on the new side of the diff"},severity:{type:"string",enum:C},category:{type:"string",description:"Short slug, e.g. correctness or security"},message:{type:"string",description:"What is wrong and why it matters"},suggestion:{type:"string",description:"Replacement code, only when the fix is mechanical"}},required:["path","line","severity","category","message"],additionalProperties:!1}}},required:["summary","effort","walkthrough","findings"],additionalProperties:!1};function I(J){let j=J.message.toLowerCase().replace(/\s+/g," ").trim().slice(0,120);return`${J.path}:${J.category}:${j}`}function N(J,j){let Q=[],Z=[];for(let $ of J)if(j.get($.path)?.has($.line))Q.push($);else Z.push($);return Q.sort(($,X)=>C.indexOf($.severity)-C.indexOf(X.severity)),{valid:Q,dropped:Z}}function v(J,j){let Q=[],Z=new Set;for(let $ of J){let X=I($);if(j.has(X)||Z.has(X))continue;Z.add(X),Q.push($)}return Q}var Jj=[/(?:^|\/)(?:bun\.lockb?|package-lock\.json|yarn\.lock|pnpm-lock\.yaml|composer\.lock|pantry\.lock)$/,/(?:^|\/)(?:dist|build|out|coverage|node_modules|vendor)\//,/\.min\.(?:js|css)$/,/(?:^|\/)(?:.*\.snap)$/],Qj=`You are reviewing a pull request diff.
3
3
 
4
4
  Report only defects you can point at in the diff. A review that invents
5
5
  findings to look thorough is worse than one that reports nothing, so say
@@ -1,4 +1,4 @@
1
1
  // @bun
2
2
  import z from"fs";import F from"os";import Y from"path";import K from"process";var G="https://api.github.com",P="https://github.com",S="https://registry.npmjs.org",A="https://packagist.org";function $(j){return j.trim().replace(/\/+$/,"")}function b(...j){for(let q of j)if(q&&q.trim())return q;return}function y(j){return $(b(j?.repository?.apiUrl,K.env.GITHUB_API_URL,G))}function L(j){return $(b(j?.repository?.serverUrl,K.env.GITHUB_SERVER_URL,P))}function C(){return K.env.HOME||K.env.USERPROFILE||F.homedir()}var H=new Map;function D(j){let q=H.get(j);if(q)return q;let J={scoped:new Map},Q=[Y.join(C(),".npmrc"),Y.join(j,".npmrc")];for(let X of Q){let M;try{M=z.readFileSync(X,"utf-8")}catch{continue}for(let O of M.split(`
3
3
  `)){let W=O.trim();if(!W||W.startsWith("#")||W.startsWith(";"))continue;let x=W.indexOf("=");if(x===-1)continue;let Z=W.slice(0,x).trim(),V=I(W.slice(x+1).trim());if(!V)continue;if(Z==="registry")J.default=V;else if(Z.endsWith(":registry")&&Z.startsWith("@"))J.scoped.set(Z.slice(0,-9),V)}}return H.set(j,J),J}function I(j){return j.replace(/\$\{([^}]+)\}/g,(q,J)=>K.env[J]??"")}function w(){H.clear()}function N(j,q,J=K.cwd()){let Q=j?.startsWith("@")?j.split("/")[0]:void 0,X=D(J);return $(b(Q?q?.registries?.npmScopes?.[Q]:void 0,q?.registries?.npm,K.env.NPM_CONFIG_REGISTRY,Q?X.scoped.get(Q):void 0,X.default,S))}function U(j){return $(b(j?.registries?.composer,K.env.COMPOSER_REGISTRY_URL,A))}
4
- export{y as xh,L as yh,w as zh,N as Ah,U as Bh};
4
+ export{y as yh,L as zh,w as Ah,N as Bh,U as Ch};