aicommit2 2.2.23 → 2.2.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -0
- package/dist/cli.mjs +34 -32
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -195,6 +195,13 @@ aicommit2 --all # or -a
|
|
|
195
195
|
- `--generate` or `-g`: Number of messages to generate (default: **1**)
|
|
196
196
|
- **Warning**: This uses more tokens, meaning it costs more.
|
|
197
197
|
- `--exclude` or `-x`: Files to exclude from AI analysis
|
|
198
|
+
- `--include-body` or `-i`: Force include commit body in all generated messages (default: **false**)
|
|
199
|
+
- When enabled, all commit messages will include a detailed body section
|
|
200
|
+
- Useful for providing more context in commit messages
|
|
201
|
+
- `--auto-select` or `-s`: Automatically select the commit message when only one AI model is configured (default: **false**)
|
|
202
|
+
- When enabled and only one AI provider is configured, the generated message is automatically selected
|
|
203
|
+
- Also skips the confirmation prompt for a seamless experience
|
|
204
|
+
- Has no effect when multiple AI providers are configured
|
|
198
205
|
- `--hook-mode`: Run as a Git hook, typically used with prepare-commit-msg hook (default: **false**)
|
|
199
206
|
- This mode is automatically enabled when running through the Git hook system
|
|
200
207
|
- See [Git hook](#git-hook) section for more details
|
package/dist/cli.mjs
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{command as Y,cli as Ho}from"cleye";import{createRequire as Uo}from"module";import{Buffer as qo}from"node:buffer";import te from"node:path";import Xt,{ChildProcess as zo}from"node:child_process";import U from"node:process";import Ko from"child_process";import P from"path";import _ from"fs";import{fileURLToPath as Jt}from"node:url";import Wo,{constants as Qt}from"node:os";import Zt from"assert";import er from"events";import{createWriteStream as Yo,createReadStream as Vo}from"node:fs";import Xo from"buffer";import st from"stream";import tr from"util";import{debuglog as Jo}from"node:util";import Me from"inquirer";import nt from"ora";import w from"chalk";import{of as de,concatMap as k,from as E,map as A,catchError as S,mergeMap as Ie,BehaviorSubject as rr,ReplaySubject as Qo,lastValueFrom as or,filter as sr,toArray as nr,Subject as ir}from"rxjs";import Zo from"@anthropic-ai/sdk";import{fromPromise as M}from"rxjs/internal/observable/innerFrom";import q from"winston";import"winston-daily-rotate-file";import x from"fs/promises";import Re from"os";import{xxh64 as es}from"@pacote/xxhash";import ts from"axios";import{CohereClient as rs}from"cohere-ai";import ar from"openai";import{GoogleGenerativeAI as os,HarmCategory as Oe,HarmBlockThreshold as Le}from"@google/generative-ai";import ss from"groq-sdk";import{Ollama as ns}from"ollama";import{fetch as is,Agent as as}from"undici";import cs from"http";import ls from"https";import ms from"net";import us from"tls";import ps,{fileURLToPath as fs,pathToFileURL as ds}from"url";import cr from"tty";import Te from"readline";import hs from"figlet";import gs from"inquirer-reactive-list-prompt";import{rm as ys}from"node:fs/promises";import ws from"chokidar";import{takeUntil as vs}from"rxjs/operators";var bs="aicommit2",lr="2.2.23",Cs="A Reactive CLI that generates git commit messages with various AI",Ps=["cli","ai","git","commit","git-commit","command-line","commandline","aipick","aicommit","aicommits","aicommit2","openai","huggingface","anthropic","claude","claude3","gemini","gemini-pro","generative-ai","mistral","ollama","llama3","llama3.2","llama3.3","gemma","llm","chatgpt","cohere","groq","codestral","perplexity","deepseek","deepseek-r1","pre-commit"],$s="MIT",Es="tak-bro/aicommit2",xs="Hyungtak Jin(@tak-bro)",As="module",Ss=["dist"],ks={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},Ms={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},Is={"@anthropic-ai/sdk":"^0.39.0","@dqbd/tiktoken":"^1.0.21","@google/generative-ai":"^0.24.1","@inquirer/prompts":"^3.3.2","@pacote/xxhash":"^0.3.2","@types/winston":"^2.4.4",axios:"^1.9.0",chalk:"^5.4.1",chokidar:"^4.0.3",cleye:"^1.3.4","cohere-ai":"^7.17.1","copy-paste":"^1.5.3",figlet:"^1.8.1","formdata-node":"^6.0.3","groq-sdk":"^0.7.0",inquirer:"9.2.8","inquirer-reactive-list-prompt":"^1.0.15",ollama:"^0.5.15",openai:"^5.0.1",ora:"^8.2.0",readline:"^1.3.0",rxjs:"^7.8.2",undici:"^7.10.0",uuid:"^9.0.1",winston:"^3.17.0","winston-daily-rotate-file":"^5.0.0"},Rs={"@pvtnbr/eslint-config":"^0.33.0","@semantic-release/changelog":"^6.0.3","@semantic-release/commit-analyzer":"^12.0.0","@semantic-release/git":"^10.0.1","@semantic-release/github":"^10.3.5","@semantic-release/npm":"^12.0.1","@semantic-release/release-notes-generator":"^13.0.0","@types/figlet":"^1.7.0","@types/ini":"^1.3.34","@types/inquirer":"^9.0.8","@types/node":"^18.19.103","@types/uuid":"^9.0.8","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","clean-pkg-json":"^1.3.0","conventional-changelog-conventionalcommits":"^7.0.2","conventional-commits-parser":"^5.0.0",eslint:"^8.57.1","eslint-config-prettier":"^8.10.0","eslint-plugin-eslint-comments":"^3.2.0","eslint-plugin-import":"^2.31.0","eslint-plugin-jsonc":"^2.20.1","eslint-plugin-no-use-extend-native":"^0.5.0","eslint-plugin-promise":"^6.6.0","eslint-plugin-unicorn":"^49.0.0","eslint-plugin-unused-imports":"^3.2.0",execa:"^7.2.0","fs-fixture":"^1.2.0","https-proxy-agent":"^5.0.1",ini:"^3.0.1","lint-staged":"^13.3.0",manten:"^0.7.0",pkgroll:"^1.11.1",prettier:"^3.5.3","semantic-release":"^23.1.1","simple-git-hooks":"^2.13.0",tsx:"^3.14.0",typescript:"^4.9.5","undici-types":"^7.10.0"},Os={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},Ls={branches:["main"],plugins:[["@semantic-release/commit-analyzer",{preset:"conventionalcommits",releaseRules:[{type:"refactor",release:"patch"},{type:"chore",release:"patch"},{type:"feat",release:"patch"},{scope:"major",release:"major"},{scope:"minor",release:"minor"},{scope:"patch",release:"patch"}]}],"@semantic-release/release-notes-generator",["@semantic-release/changelog",{changelogFile:"CHANGELOG.md"}],"@semantic-release/github",["@semantic-release/git",{assets:["CHANGELOG.md"],message:"chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"}],"@semantic-release/npm"]},Ts={name:bs,version:lr,description:Cs,keywords:Ps,license:$s,repository:Es,author:xs,type:As,files:Ss,bin:ks,scripts:Ms,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:Is,devDependencies:Rs,eslintConfig:Os,release:Ls},Ns=Uo(import.meta.url),L=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function re(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var oe={exports:{}},it,mr;function _s(){if(mr)return it;mr=1,it=r,r.sync=n;var t=_;function e(s,i){var c=i.pathExt!==void 0?i.pathExt:process.env.PATHEXT;if(!c||(c=c.split(";"),c.indexOf("")!==-1))return!0;for(var l=0;l<c.length;l++){var p=c[l].toLowerCase();if(p&&s.substr(-p.length).toLowerCase()===p)return!0}return!1}function o(s,i,c){return!s.isSymbolicLink()&&!s.isFile()?!1:e(i,c)}function r(s,i,c){t.stat(s,function(l,p){c(l,l?!1:o(p,s,i))})}function n(s,i){return o(t.statSync(s),s,i)}return it}var at,ur;function Fs(){if(ur)return at;ur=1,at=e,e.sync=o;var t=_;function e(s,i,c){t.stat(s,function(l,p){c(l,l?!1:r(p,i))})}function o(s,i){return r(t.statSync(s),i)}function r(s,i){return s.isFile()&&n(s,i)}function n(s,i){var c=s.mode,l=s.uid,p=s.gid,m=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),a=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),u=parseInt("100",8),d=parseInt("010",8),h=parseInt("001",8),g=u|d,y=c&h||c&d&&p===a||c&u&&l===m||c&g&&m===0;return y}return at}var Ne;process.platform==="win32"||L.TESTING_WINDOWS?Ne=_s():Ne=Fs();var Ds=ct;ct.sync=Gs;function ct(t,e,o){if(typeof e=="function"&&(o=e,e={}),!o){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(r,n){ct(t,e||{},function(s,i){s?n(s):r(i)})})}Ne(t,e||{},function(r,n){r&&(r.code==="EACCES"||e&&e.ignoreErrors)&&(r=null,n=!1),o(r,n)})}function Gs(t,e){try{return Ne.sync(t,e||{})}catch(o){if(e&&e.ignoreErrors||o.code==="EACCES")return!1;throw o}}const se=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",pr=P,js=se?";":":",fr=Ds,dr=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),hr=(t,e)=>{const o=e.colon||js,r=t.match(/\//)||se&&t.match(/\\/)?[""]:[...se?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(o)],n=se?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=se?n.split(o):[""];return se&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:r,pathExt:s,pathExtExe:n}},gr=(t,e,o)=>{typeof e=="function"&&(o=e,e={}),e||(e={});const{pathEnv:r,pathExt:n,pathExtExe:s}=hr(t,e),i=[],c=p=>new Promise((m,a)=>{if(p===r.length)return e.all&&i.length?m(i):a(dr(t));const u=r[p],d=/^".*"$/.test(u)?u.slice(1,-1):u,h=pr.join(d,t),g=!d&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;m(l(g,p,0))}),l=(p,m,a)=>new Promise((u,d)=>{if(a===n.length)return u(c(m+1));const h=n[a];fr(p+h,{pathExt:s},(g,y)=>{if(!g&&y)if(e.all)i.push(p+h);else return u(p+h);return u(l(p,m,a+1))})});return o?c(0).then(p=>o(null,p),o):c(0)},Bs=(t,e)=>{e=e||{};const{pathEnv:o,pathExt:r,pathExtExe:n}=hr(t,e),s=[];for(let i=0;i<o.length;i++){const c=o[i],l=/^".*"$/.test(c)?c.slice(1,-1):c,p=pr.join(l,t),m=!l&&/^\.[\\\/]/.test(t)?t.slice(0,2)+p:p;for(let a=0;a<r.length;a++){const u=m+r[a];try{if(fr.sync(u,{pathExt:n}))if(e.all)s.push(u);else return u}catch{}}}if(e.all&&s.length)return s;if(e.nothrow)return null;throw dr(t)};var Hs=gr;gr.sync=Bs;var lt={exports:{}};const yr=(t={})=>{const e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(r=>r.toUpperCase()==="PATH")||"Path"};lt.exports=yr,lt.exports.default=yr;var Us=lt.exports;const wr=P,qs=Hs,zs=Us;function vr(t,e){const o=t.options.env||process.env,r=process.cwd(),n=t.options.cwd!=null,s=n&&process.chdir!==void 0&&!process.chdir.disabled;if(s)try{process.chdir(t.options.cwd)}catch{}let i;try{i=qs.sync(t.command,{path:o[zs({env:o})],pathExt:e?wr.delimiter:void 0})}catch{}finally{s&&process.chdir(r)}return i&&(i=wr.resolve(n?t.options.cwd:"",i)),i}function Ks(t){return vr(t)||vr(t,!0)}var Ws=Ks,mt={};const ut=/([()\][%!^"`<>&|;, *?])/g;function Ys(t){return t=t.replace(ut,"^$1"),t}function Vs(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(ut,"^$1"),e&&(t=t.replace(ut,"^$1")),t}mt.command=Ys,mt.argument=Vs;var Xs=/^#!(.*)/;const Js=Xs;var Qs=(t="")=>{const e=t.match(Js);if(!e)return null;const[o,r]=e[0].replace(/#! ?/,"").split(" "),n=o.split("/").pop();return n==="env"?r:r?`${n} ${r}`:n};const pt=_,Zs=Qs;function en(t){const o=Buffer.alloc(150);let r;try{r=pt.openSync(t,"r"),pt.readSync(r,o,0,150,0),pt.closeSync(r)}catch{}return Zs(o.toString())}var tn=en;const rn=P,br=Ws,Cr=mt,on=tn,sn=process.platform==="win32",nn=/\.(?:com|exe)$/i,an=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function cn(t){t.file=br(t);const e=t.file&&on(t.file);return e?(t.args.unshift(t.file),t.command=e,br(t)):t.file}function ln(t){if(!sn)return t;const e=cn(t),o=!nn.test(e);if(t.options.forceShell||o){const r=an.test(e);t.command=rn.normalize(t.command),t.command=Cr.command(t.command),t.args=t.args.map(s=>Cr.argument(s,r));const n=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${n}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function mn(t,e,o){e&&!Array.isArray(e)&&(o=e,e=null),e=e?e.slice(0):[],o=Object.assign({},o);const r={command:t,args:e,options:o,file:void 0,original:{command:t,args:e}};return o.shell?r:ln(r)}var un=mn;const ft=process.platform==="win32";function dt(t,e){return Object.assign(new Error(`${e} ${t.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${t.command}`,path:t.command,spawnargs:t.args})}function pn(t,e){if(!ft)return;const o=t.emit;t.emit=function(r,n){if(r==="exit"){const s=Pr(n,e);if(s)return o.call(t,"error",s)}return o.apply(t,arguments)}}function Pr(t,e){return ft&&t===1&&!e.file?dt(e.original,"spawn"):null}function fn(t,e){return ft&&t===1&&!e.file?dt(e.original,"spawnSync"):null}var dn={hookChildProcess:pn,verifyENOENT:Pr,verifyENOENTSync:fn,notFoundError:dt};const $r=Ko,ht=un,gt=dn;function Er(t,e,o){const r=ht(t,e,o),n=$r.spawn(r.command,r.args,r.options);return gt.hookChildProcess(n,r),n}function hn(t,e,o){const r=ht(t,e,o),n=$r.spawnSync(r.command,r.args,r.options);return n.error=n.error||gt.verifyENOENTSync(n.status,r),n}oe.exports=Er,oe.exports.spawn=Er,oe.exports.sync=hn,oe.exports._parse=ht,oe.exports._enoent=gt;var gn=oe.exports,yn=re(gn);function wn(t){const e=typeof t=="string"?`
|
|
2
|
+
import{command as Y,cli as Ho}from"cleye";import{createRequire as Uo}from"module";import{Buffer as qo}from"node:buffer";import te from"node:path";import Xt,{ChildProcess as zo}from"node:child_process";import z from"node:process";import Ko from"child_process";import $ from"path";import F from"fs";import{fileURLToPath as Jt}from"node:url";import Wo,{constants as Qt}from"node:os";import Zt from"assert";import er from"events";import{createWriteStream as Yo,createReadStream as Vo}from"node:fs";import Xo from"buffer";import st from"stream";import tr from"util";import{debuglog as Jo}from"node:util";import Me from"inquirer";import nt from"ora";import w from"chalk";import{of as de,concatMap as k,from as E,map as S,catchError as A,mergeMap as Ie,BehaviorSubject as rr,ReplaySubject as Qo,lastValueFrom as or,filter as sr,toArray as nr,Subject as ir}from"rxjs";import Zo from"@anthropic-ai/sdk";import{fromPromise as M}from"rxjs/internal/observable/innerFrom";import K from"winston";import"winston-daily-rotate-file";import x from"fs/promises";import Re from"os";import{xxh64 as es}from"@pacote/xxhash";import ts from"axios";import{CohereClient as rs}from"cohere-ai";import ar from"openai";import{GoogleGenerativeAI as os,HarmCategory as Oe,HarmBlockThreshold as Le}from"@google/generative-ai";import ss from"groq-sdk";import{Ollama as ns}from"ollama";import{fetch as is,Agent as as}from"undici";import cs from"http";import ls from"https";import ms from"net";import us from"tls";import ps,{fileURLToPath as fs,pathToFileURL as ds}from"url";import cr from"tty";import Te from"readline";import hs from"figlet";import gs from"inquirer-reactive-list-prompt";import{rm as ys}from"node:fs/promises";import ws from"chokidar";import{takeUntil as vs}from"rxjs/operators";var bs="aicommit2",lr="2.2.24",Cs="A Reactive CLI that generates git commit messages with various AI",Ps=["cli","ai","git","commit","git-commit","command-line","commandline","aipick","aicommit","aicommits","aicommit2","openai","huggingface","anthropic","claude","claude3","gemini","gemini-pro","generative-ai","mistral","ollama","llama3","llama3.2","llama3.3","gemma","llm","chatgpt","cohere","groq","codestral","perplexity","deepseek","deepseek-r1","pre-commit"],$s="MIT",Es="tak-bro/aicommit2",xs="Hyungtak Jin(@tak-bro)",Ss="module",As=["dist"],ks={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},Ms={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},Is={"@anthropic-ai/sdk":"^0.39.0","@dqbd/tiktoken":"^1.0.21","@google/generative-ai":"^0.24.1","@inquirer/prompts":"^3.3.2","@pacote/xxhash":"^0.3.2","@types/winston":"^2.4.4",axios:"^1.9.0",chalk:"^5.4.1",chokidar:"^4.0.3",cleye:"^1.3.4","cohere-ai":"^7.17.1","copy-paste":"^1.5.3",figlet:"^1.8.1","formdata-node":"^6.0.3","groq-sdk":"^0.7.0",inquirer:"9.2.8","inquirer-reactive-list-prompt":"^1.0.15",ollama:"^0.5.15",openai:"^5.0.1",ora:"^8.2.0",readline:"^1.3.0",rxjs:"^7.8.2",undici:"^7.10.0",uuid:"^9.0.1",winston:"^3.17.0","winston-daily-rotate-file":"^5.0.0"},Rs={"@pvtnbr/eslint-config":"^0.33.0","@semantic-release/changelog":"^6.0.3","@semantic-release/commit-analyzer":"^12.0.0","@semantic-release/git":"^10.0.1","@semantic-release/github":"^10.3.5","@semantic-release/npm":"^12.0.1","@semantic-release/release-notes-generator":"^13.0.0","@types/figlet":"^1.7.0","@types/ini":"^1.3.34","@types/inquirer":"^9.0.8","@types/node":"^18.19.103","@types/uuid":"^9.0.8","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","clean-pkg-json":"^1.3.0","conventional-changelog-conventionalcommits":"^7.0.2","conventional-commits-parser":"^5.0.0",eslint:"^8.57.1","eslint-config-prettier":"^8.10.0","eslint-plugin-eslint-comments":"^3.2.0","eslint-plugin-import":"^2.31.0","eslint-plugin-jsonc":"^2.20.1","eslint-plugin-no-use-extend-native":"^0.5.0","eslint-plugin-promise":"^6.6.0","eslint-plugin-unicorn":"^49.0.0","eslint-plugin-unused-imports":"^3.2.0",execa:"^7.2.0","fs-fixture":"^1.2.0","https-proxy-agent":"^5.0.1",ini:"^3.0.1","lint-staged":"^13.3.0",manten:"^0.7.0",pkgroll:"^1.11.1",prettier:"^3.5.3","semantic-release":"^23.1.1","simple-git-hooks":"^2.13.0",tsx:"^3.14.0",typescript:"^4.9.5","undici-types":"^7.10.0"},Os={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},Ls={branches:["main"],plugins:[["@semantic-release/commit-analyzer",{preset:"conventionalcommits",releaseRules:[{type:"refactor",release:"patch"},{type:"chore",release:"patch"},{type:"feat",release:"patch"},{scope:"major",release:"major"},{scope:"minor",release:"minor"},{scope:"patch",release:"patch"}]}],"@semantic-release/release-notes-generator",["@semantic-release/changelog",{changelogFile:"CHANGELOG.md"}],"@semantic-release/github",["@semantic-release/git",{assets:["CHANGELOG.md"],message:"chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"}],"@semantic-release/npm"]},Ts={name:bs,version:lr,description:Cs,keywords:Ps,license:$s,repository:Es,author:xs,type:Ss,files:As,bin:ks,scripts:Ms,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:Is,devDependencies:Rs,eslintConfig:Os,release:Ls},Ns=Uo(import.meta.url),O=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function re(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var oe={exports:{}},it,mr;function _s(){if(mr)return it;mr=1,it=r,r.sync=n;var t=F;function e(s,i){var c=i.pathExt!==void 0?i.pathExt:process.env.PATHEXT;if(!c||(c=c.split(";"),c.indexOf("")!==-1))return!0;for(var l=0;l<c.length;l++){var p=c[l].toLowerCase();if(p&&s.substr(-p.length).toLowerCase()===p)return!0}return!1}function o(s,i,c){return!s.isSymbolicLink()&&!s.isFile()?!1:e(i,c)}function r(s,i,c){t.stat(s,function(l,p){c(l,l?!1:o(p,s,i))})}function n(s,i){return o(t.statSync(s),s,i)}return it}var at,ur;function Fs(){if(ur)return at;ur=1,at=e,e.sync=o;var t=F;function e(s,i,c){t.stat(s,function(l,p){c(l,l?!1:r(p,i))})}function o(s,i){return r(t.statSync(s),i)}function r(s,i){return s.isFile()&&n(s,i)}function n(s,i){var c=s.mode,l=s.uid,p=s.gid,m=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),a=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),u=parseInt("100",8),d=parseInt("010",8),h=parseInt("001",8),g=u|d,y=c&h||c&d&&p===a||c&u&&l===m||c&g&&m===0;return y}return at}var Ne;process.platform==="win32"||O.TESTING_WINDOWS?Ne=_s():Ne=Fs();var Ds=ct;ct.sync=Gs;function ct(t,e,o){if(typeof e=="function"&&(o=e,e={}),!o){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(r,n){ct(t,e||{},function(s,i){s?n(s):r(i)})})}Ne(t,e||{},function(r,n){r&&(r.code==="EACCES"||e&&e.ignoreErrors)&&(r=null,n=!1),o(r,n)})}function Gs(t,e){try{return Ne.sync(t,e||{})}catch(o){if(e&&e.ignoreErrors||o.code==="EACCES")return!1;throw o}}const se=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",pr=$,js=se?";":":",fr=Ds,dr=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),hr=(t,e)=>{const o=e.colon||js,r=t.match(/\//)||se&&t.match(/\\/)?[""]:[...se?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(o)],n=se?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=se?n.split(o):[""];return se&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:r,pathExt:s,pathExtExe:n}},gr=(t,e,o)=>{typeof e=="function"&&(o=e,e={}),e||(e={});const{pathEnv:r,pathExt:n,pathExtExe:s}=hr(t,e),i=[],c=p=>new Promise((m,a)=>{if(p===r.length)return e.all&&i.length?m(i):a(dr(t));const u=r[p],d=/^".*"$/.test(u)?u.slice(1,-1):u,h=pr.join(d,t),g=!d&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;m(l(g,p,0))}),l=(p,m,a)=>new Promise((u,d)=>{if(a===n.length)return u(c(m+1));const h=n[a];fr(p+h,{pathExt:s},(g,y)=>{if(!g&&y)if(e.all)i.push(p+h);else return u(p+h);return u(l(p,m,a+1))})});return o?c(0).then(p=>o(null,p),o):c(0)},Bs=(t,e)=>{e=e||{};const{pathEnv:o,pathExt:r,pathExtExe:n}=hr(t,e),s=[];for(let i=0;i<o.length;i++){const c=o[i],l=/^".*"$/.test(c)?c.slice(1,-1):c,p=pr.join(l,t),m=!l&&/^\.[\\\/]/.test(t)?t.slice(0,2)+p:p;for(let a=0;a<r.length;a++){const u=m+r[a];try{if(fr.sync(u,{pathExt:n}))if(e.all)s.push(u);else return u}catch{}}}if(e.all&&s.length)return s;if(e.nothrow)return null;throw dr(t)};var Hs=gr;gr.sync=Bs;var lt={exports:{}};const yr=(t={})=>{const e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(r=>r.toUpperCase()==="PATH")||"Path"};lt.exports=yr,lt.exports.default=yr;var Us=lt.exports;const wr=$,qs=Hs,zs=Us;function vr(t,e){const o=t.options.env||process.env,r=process.cwd(),n=t.options.cwd!=null,s=n&&process.chdir!==void 0&&!process.chdir.disabled;if(s)try{process.chdir(t.options.cwd)}catch{}let i;try{i=qs.sync(t.command,{path:o[zs({env:o})],pathExt:e?wr.delimiter:void 0})}catch{}finally{s&&process.chdir(r)}return i&&(i=wr.resolve(n?t.options.cwd:"",i)),i}function Ks(t){return vr(t)||vr(t,!0)}var Ws=Ks,mt={};const ut=/([()\][%!^"`<>&|;, *?])/g;function Ys(t){return t=t.replace(ut,"^$1"),t}function Vs(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(ut,"^$1"),e&&(t=t.replace(ut,"^$1")),t}mt.command=Ys,mt.argument=Vs;var Xs=/^#!(.*)/;const Js=Xs;var Qs=(t="")=>{const e=t.match(Js);if(!e)return null;const[o,r]=e[0].replace(/#! ?/,"").split(" "),n=o.split("/").pop();return n==="env"?r:r?`${n} ${r}`:n};const pt=F,Zs=Qs;function en(t){const o=Buffer.alloc(150);let r;try{r=pt.openSync(t,"r"),pt.readSync(r,o,0,150,0),pt.closeSync(r)}catch{}return Zs(o.toString())}var tn=en;const rn=$,br=Ws,Cr=mt,on=tn,sn=process.platform==="win32",nn=/\.(?:com|exe)$/i,an=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function cn(t){t.file=br(t);const e=t.file&&on(t.file);return e?(t.args.unshift(t.file),t.command=e,br(t)):t.file}function ln(t){if(!sn)return t;const e=cn(t),o=!nn.test(e);if(t.options.forceShell||o){const r=an.test(e);t.command=rn.normalize(t.command),t.command=Cr.command(t.command),t.args=t.args.map(s=>Cr.argument(s,r));const n=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${n}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function mn(t,e,o){e&&!Array.isArray(e)&&(o=e,e=null),e=e?e.slice(0):[],o=Object.assign({},o);const r={command:t,args:e,options:o,file:void 0,original:{command:t,args:e}};return o.shell?r:ln(r)}var un=mn;const ft=process.platform==="win32";function dt(t,e){return Object.assign(new Error(`${e} ${t.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${t.command}`,path:t.command,spawnargs:t.args})}function pn(t,e){if(!ft)return;const o=t.emit;t.emit=function(r,n){if(r==="exit"){const s=Pr(n,e);if(s)return o.call(t,"error",s)}return o.apply(t,arguments)}}function Pr(t,e){return ft&&t===1&&!e.file?dt(e.original,"spawn"):null}function fn(t,e){return ft&&t===1&&!e.file?dt(e.original,"spawnSync"):null}var dn={hookChildProcess:pn,verifyENOENT:Pr,verifyENOENTSync:fn,notFoundError:dt};const $r=Ko,ht=un,gt=dn;function Er(t,e,o){const r=ht(t,e,o),n=$r.spawn(r.command,r.args,r.options);return gt.hookChildProcess(n,r),n}function hn(t,e,o){const r=ht(t,e,o),n=$r.spawnSync(r.command,r.args,r.options);return n.error=n.error||gt.verifyENOENTSync(n.status,r),n}oe.exports=Er,oe.exports.spawn=Er,oe.exports.sync=hn,oe.exports._parse=ht,oe.exports._enoent=gt;var gn=oe.exports,yn=re(gn);function wn(t){const e=typeof t=="string"?`
|
|
3
3
|
`:`
|
|
4
|
-
`.charCodeAt(),o=typeof t=="string"?"\r":"\r".charCodeAt();return t[t.length-1]===e&&(t=t.slice(0,-1)),t[t.length-1]===o&&(t=t.slice(0,-1)),t}function xr(t={}){const{env:e=process.env,platform:o=process.platform}=t;return o!=="win32"?"PATH":Object.keys(e).reverse().find(r=>r.toUpperCase()==="PATH")||"Path"}const vn=({cwd:t=
|
|
5
|
-
${e}`,
|
|
6
|
-
${r.message}`:y,
|
|
7
|
-
`);return v?(r.originalMessage=r.message,r.message=
|
|
8
|
-
`)},Fi=1e3*1e3*100,Di=({env:t,extendEnv:e,preferLocal:o,localDir:r,execPath:n})=>{const s=e?{...
|
|
4
|
+
`.charCodeAt(),o=typeof t=="string"?"\r":"\r".charCodeAt();return t[t.length-1]===e&&(t=t.slice(0,-1)),t[t.length-1]===o&&(t=t.slice(0,-1)),t}function xr(t={}){const{env:e=process.env,platform:o=process.platform}=t;return o!=="win32"?"PATH":Object.keys(e).reverse().find(r=>r.toUpperCase()==="PATH")||"Path"}const vn=({cwd:t=z.cwd(),path:e=z.env[xr()],preferLocal:o=!0,execPath:r=z.execPath,addExecPath:n=!0}={})=>{const s=t instanceof URL?Jt(t):t,i=te.resolve(s),c=[];return o&&bn(c,i),n&&Cn(c,r,i),[...c,e].join(te.delimiter)},bn=(t,e)=>{let o;for(;o!==e;)t.push(te.join(e,"node_modules/.bin")),o=e,e=te.resolve(e,"..")},Cn=(t,e,o)=>{const r=e instanceof URL?Jt(e):e;t.push(te.resolve(o,r,".."))},Pn=({env:t=z.env,...e}={})=>{t={...t};const o=xr({env:t});return e.path=t[o],t[o]=vn(e),t},$n=(t,e,o,r)=>{if(o==="length"||o==="prototype"||o==="arguments"||o==="caller")return;const n=Object.getOwnPropertyDescriptor(t,o),s=Object.getOwnPropertyDescriptor(e,o);!En(n,s)&&r||Object.defineProperty(t,o,s)},En=function(t,e){return t===void 0||t.configurable||t.writable===e.writable&&t.enumerable===e.enumerable&&t.configurable===e.configurable&&(t.writable||t.value===e.value)},xn=(t,e)=>{const o=Object.getPrototypeOf(e);o!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,o)},Sn=(t,e)=>`/* Wrapped ${t}*/
|
|
5
|
+
${e}`,An=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),kn=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Mn=(t,e,o)=>{const r=o===""?"":`with ${o.trim()}() `,n=Sn.bind(null,r,e.toString());Object.defineProperty(n,"name",kn),Object.defineProperty(t,"toString",{...An,value:n})};function In(t,e,{ignoreNonConfigurable:o=!1}={}){const{name:r}=t;for(const n of Reflect.ownKeys(e))$n(t,e,n,o);return xn(t,e),Mn(t,e,r),t}const _e=new WeakMap,Sr=(t,e={})=>{if(typeof t!="function")throw new TypeError("Expected a function");let o,r=0;const n=t.displayName||t.name||"<anonymous>",s=function(...i){if(_e.set(s,++r),r===1)o=t.apply(this,i),t=null;else if(e.throw===!0)throw new Error(`Function \`${n}\` can only be called once`);return o};return In(s,t),_e.set(s,r),s};Sr.callCount=t=>{if(!_e.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return _e.get(t)};const Rn=()=>{const t=kr-Ar+1;return Array.from({length:t},On)},On=(t,e)=>({name:`SIGRT${e+1}`,number:Ar+e,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Ar=34,kr=64,Ln=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}],Mr=()=>{const t=Rn();return[...Ln,...t].map(Tn)},Tn=({name:t,number:e,description:o,action:r,forced:n=!1,standard:s})=>{const{signals:{[t]:i}}=Qt,c=i!==void 0;return{name:t,number:c?i:e,description:o,supported:c,action:r,forced:n,standard:s}},Nn=()=>{const t=Mr();return Object.fromEntries(t.map(_n))},_n=({name:t,number:e,description:o,supported:r,action:n,forced:s,standard:i})=>[t,{name:t,number:e,description:o,supported:r,action:n,forced:s,standard:i}],Fn=Nn(),Dn=()=>{const t=Mr(),e=kr+1,o=Array.from({length:e},(r,n)=>Gn(n,t));return Object.assign({},...o)},Gn=(t,e)=>{const o=jn(t,e);if(o===void 0)return{};const{name:r,description:n,supported:s,action:i,forced:c,standard:l}=o;return{[t]:{name:r,number:t,description:n,supported:s,action:i,forced:c,standard:l}}},jn=(t,e)=>{const o=e.find(({name:r})=>Qt.signals[r]===t);return o!==void 0?o:e.find(r=>r.number===t)};Dn();const Bn=({timedOut:t,timeout:e,errorCode:o,signal:r,signalDescription:n,exitCode:s,isCanceled:i})=>t?`timed out after ${e} milliseconds`:i?"was canceled":o!==void 0?`failed with ${o}`:r!==void 0?`was killed with ${r} (${n})`:s!==void 0?`failed with exit code ${s}`:"failed",Ir=({stdout:t,stderr:e,all:o,error:r,signal:n,exitCode:s,command:i,escapedCommand:c,timedOut:l,isCanceled:p,killed:m,parsed:{options:{timeout:a,cwd:u=z.cwd()}}})=>{s=s===null?void 0:s,n=n===null?void 0:n;const d=n===void 0?void 0:Fn[n].description,h=r&&r.code,y=`Command ${Bn({timedOut:l,timeout:a,errorCode:h,signal:n,signalDescription:d,exitCode:s,isCanceled:p})}: ${i}`,v=Object.prototype.toString.call(r)==="[object Error]",P=v?`${y}
|
|
6
|
+
${r.message}`:y,L=[P,e,t].filter(Boolean).join(`
|
|
7
|
+
`);return v?(r.originalMessage=r.message,r.message=L):r=new Error(L),r.shortMessage=P,r.command=i,r.escapedCommand=c,r.exitCode=s,r.signal=n,r.signalDescription=d,r.stdout=t,r.stderr=e,r.cwd=u,o!==void 0&&(r.all=o),"bufferedData"in r&&delete r.bufferedData,r.failed=!0,r.timedOut=!!l,r.isCanceled=p,r.killed=m&&!l,r},Fe=["stdin","stdout","stderr"],Hn=t=>Fe.some(e=>t[e]!==void 0),Un=t=>{if(!t)return;const{stdio:e}=t;if(e===void 0)return Fe.map(r=>t[r]);if(Hn(t))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Fe.map(r=>`\`${r}\``).join(", ")}`);if(typeof e=="string")return e;if(!Array.isArray(e))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof e}\``);const o=Math.max(e.length,Fe.length);return Array.from({length:o},(r,n)=>e[n])};var ne={exports:{}},De={exports:{}};De.exports;var Rr;function qn(){return Rr||(Rr=1,function(t){t.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"],process.platform!=="win32"&&t.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),process.platform==="linux"&&t.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}(De)),De.exports}var I=O.process;const Z=function(t){return t&&typeof t=="object"&&typeof t.removeListener=="function"&&typeof t.emit=="function"&&typeof t.reallyExit=="function"&&typeof t.listeners=="function"&&typeof t.kill=="function"&&typeof t.pid=="number"&&typeof t.on=="function"};if(!Z(I))ne.exports=function(){return function(){}};else{var zn=Zt,he=qn(),Kn=/^win/i.test(I.platform),Ge=er;typeof Ge!="function"&&(Ge=Ge.EventEmitter);var T;I.__signal_exit_emitter__?T=I.__signal_exit_emitter__:(T=I.__signal_exit_emitter__=new Ge,T.count=0,T.emitted={}),T.infinite||(T.setMaxListeners(1/0),T.infinite=!0),ne.exports=function(t,e){if(!Z(O.process))return function(){};zn.equal(typeof t,"function","a callback must be provided for exit handler"),ge===!1&&Or();var o="exit";e&&e.alwaysLast&&(o="afterexit");var r=function(){T.removeListener(o,t),T.listeners("exit").length===0&&T.listeners("afterexit").length===0&&yt()};return T.on(o,t),r};var yt=function(){!ge||!Z(O.process)||(ge=!1,he.forEach(function(e){try{I.removeListener(e,wt[e])}catch{}}),I.emit=vt,I.reallyExit=Lr,T.count-=1)};ne.exports.unload=yt;var ie=function(e,o,r){T.emitted[e]||(T.emitted[e]=!0,T.emit(e,o,r))},wt={};he.forEach(function(t){wt[t]=function(){if(Z(O.process)){var o=I.listeners(t);o.length===T.count&&(yt(),ie("exit",null,t),ie("afterexit",null,t),Kn&&t==="SIGHUP"&&(t="SIGINT"),I.kill(I.pid,t))}}}),ne.exports.signals=function(){return he};var ge=!1,Or=function(){ge||!Z(O.process)||(ge=!0,T.count+=1,he=he.filter(function(e){try{return I.on(e,wt[e]),!0}catch{return!1}}),I.emit=Yn,I.reallyExit=Wn)};ne.exports.load=Or;var Lr=I.reallyExit,Wn=function(e){Z(O.process)&&(I.exitCode=e||0,ie("exit",I.exitCode,null),ie("afterexit",I.exitCode,null),Lr.call(I,I.exitCode))},vt=I.emit,Yn=function(e,o){if(e==="exit"&&Z(O.process)){o!==void 0&&(I.exitCode=o);var r=vt.apply(this,arguments);return ie("exit",I.exitCode,null),ie("afterexit",I.exitCode,null),r}else return vt.apply(this,arguments)}}var Vn=ne.exports,Xn=re(Vn);const Jn=1e3*5,Qn=(t,e="SIGTERM",o={})=>{const r=t(e);return Zn(t,e,o,r),r},Zn=(t,e,o,r)=>{if(!ei(e,o,r))return;const n=ri(o),s=setTimeout(()=>{t("SIGKILL")},n);s.unref&&s.unref()},ei=(t,{forceKillAfterTimeout:e},o)=>ti(t)&&e!==!1&&o,ti=t=>t===Wo.constants.signals.SIGTERM||typeof t=="string"&&t.toUpperCase()==="SIGTERM",ri=({forceKillAfterTimeout:t=!0})=>{if(t===!0)return Jn;if(!Number.isFinite(t)||t<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${t}\` (${typeof t})`);return t},oi=(t,e)=>{t.kill()&&(e.isCanceled=!0)},si=(t,e,o)=>{t.kill(e),o(Object.assign(new Error("Timed out"),{timedOut:!0,signal:e}))},ni=(t,{timeout:e,killSignal:o="SIGTERM"},r)=>{if(e===0||e===void 0)return r;let n;const s=new Promise((c,l)=>{n=setTimeout(()=>{si(t,o,l)},e)}),i=r.finally(()=>{clearTimeout(n)});return Promise.race([s,i])},ii=({timeout:t})=>{if(t!==void 0&&(!Number.isFinite(t)||t<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${t}\` (${typeof t})`)},ai=async(t,{cleanup:e,detached:o},r)=>{if(!e||o)return r;const n=Xn(()=>{t.kill()});return r.finally(()=>{n()})};function Tr(t){return t!==null&&typeof t=="object"&&typeof t.pipe=="function"}function Nr(t){return Tr(t)&&t.writable!==!1&&typeof t._write=="function"&&typeof t._writableState=="object"}const ci=t=>t instanceof zo&&typeof t.then=="function",bt=(t,e,o)=>{if(typeof o=="string")return t[e].pipe(Yo(o)),t;if(Nr(o))return t[e].pipe(o),t;if(!ci(o))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!Nr(o.stdin))throw new TypeError("The target child process's stdin must be available.");return t[e].pipe(o.stdin),o},li=t=>{t.stdout!==null&&(t.pipeStdout=bt.bind(void 0,t,"stdout")),t.stderr!==null&&(t.pipeStderr=bt.bind(void 0,t,"stderr")),t.all!==void 0&&(t.pipeAll=bt.bind(void 0,t,"all"))};var ye={exports:{}};const{PassThrough:mi}=st;var ui=t=>{t={...t};const{array:e}=t;let{encoding:o}=t;const r=o==="buffer";let n=!1;e?n=!(o||r):o=o||"utf8",r&&(o=null);const s=new mi({objectMode:n});o&&s.setEncoding(o);let i=0;const c=[];return s.on("data",l=>{c.push(l),n?i=c.length:i+=l.length}),s.getBufferedValue=()=>e?c:r?Buffer.concat(c,i):c.join(""),s.getBufferedLength=()=>i,s};const{constants:pi}=Xo,fi=st,{promisify:di}=tr,hi=ui,gi=di(fi.pipeline);class _r extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function Ct(t,e){if(!t)throw new Error("Expected a stream");e={maxBuffer:1/0,...e};const{maxBuffer:o}=e,r=hi(e);return await new Promise((n,s)=>{const i=c=>{c&&r.getBufferedLength()<=pi.MAX_LENGTH&&(c.bufferedData=r.getBufferedValue()),s(c)};(async()=>{try{await gi(t,r),n()}catch(c){i(c)}})(),r.on("data",()=>{r.getBufferedLength()>o&&i(new _r)})}),r.getBufferedValue()}ye.exports=Ct,ye.exports.buffer=(t,e)=>Ct(t,{...e,encoding:"buffer"}),ye.exports.array=(t,e)=>Ct(t,{...e,array:!0}),ye.exports.MaxBufferError=_r;var yi=ye.exports,Fr=re(yi);const{PassThrough:wi}=st;var vi=function(){var t=[],e=new wi({objectMode:!0});return e.setMaxListeners(0),e.add=o,e.isEmpty=r,e.on("unpipe",n),Array.prototype.slice.call(arguments).forEach(o),e;function o(s){return Array.isArray(s)?(s.forEach(o),this):(t.push(s),s.once("end",n.bind(null,s)),s.once("error",e.emit.bind(e,"error")),s.pipe(e,{end:!1}),this)}function r(){return t.length==0}function n(s){t=t.filter(function(i){return i!==s}),!t.length&&e.readable&&e.end()}},bi=re(vi);const Ci=t=>{if(t!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},Pi=({input:t,inputFile:e})=>typeof e!="string"?t:(Ci(t),Vo(e)),$i=(t,e)=>{const o=Pi(e);o!==void 0&&(Tr(o)?o.pipe(t.stdin):t.stdin.end(o))},Ei=(t,{all:e})=>{if(!e||!t.stdout&&!t.stderr)return;const o=bi();return t.stdout&&o.add(t.stdout),t.stderr&&o.add(t.stderr),o},Pt=async(t,e)=>{if(!(!t||e===void 0)){t.destroy();try{return await e}catch(o){return o.bufferedData}}},$t=(t,{encoding:e,buffer:o,maxBuffer:r})=>{if(!(!t||!o))return e?Fr(t,{encoding:e,maxBuffer:r}):Fr.buffer(t,{maxBuffer:r})},xi=async({stdout:t,stderr:e,all:o},{encoding:r,buffer:n,maxBuffer:s},i)=>{const c=$t(t,{encoding:r,buffer:n,maxBuffer:s}),l=$t(e,{encoding:r,buffer:n,maxBuffer:s}),p=$t(o,{encoding:r,buffer:n,maxBuffer:s*2});try{return await Promise.all([i,c,l,p])}catch(m){return Promise.all([{error:m,signal:m.signal,timedOut:m.timedOut},Pt(t,c),Pt(e,l),Pt(o,p)])}},Si=(async()=>{})().constructor.prototype,Ai=["then","catch","finally"].map(t=>[t,Reflect.getOwnPropertyDescriptor(Si,t)]),Dr=(t,e)=>{for(const[o,r]of Ai){const n=typeof e=="function"?(...s)=>Reflect.apply(r.value,e(),s):r.value.bind(e);Reflect.defineProperty(t,o,{...r,value:n})}},ki=t=>new Promise((e,o)=>{t.on("exit",(r,n)=>{e({exitCode:r,signal:n})}),t.on("error",r=>{o(r)}),t.stdin&&t.stdin.on("error",r=>{o(r)})}),Gr=(t,e=[])=>Array.isArray(e)?[t,...e]:[t],Mi=/^[\w.-]+$/,Ii=/"/g,Ri=t=>typeof t!="string"||Mi.test(t)?t:`"${t.replace(Ii,'\\"')}"`,Oi=(t,e)=>Gr(t,e).join(" "),Li=(t,e)=>Gr(t,e).map(o=>Ri(o)).join(" "),Ti=Jo("execa").enabled,je=(t,e)=>String(t).padStart(e,"0"),Ni=()=>{const t=new Date;return`${je(t.getHours(),2)}:${je(t.getMinutes(),2)}:${je(t.getSeconds(),2)}.${je(t.getMilliseconds(),3)}`},_i=(t,{verbose:e})=>{e&&z.stderr.write(`[${Ni()}] ${t}
|
|
8
|
+
`)},Fi=1e3*1e3*100,Di=({env:t,extendEnv:e,preferLocal:o,localDir:r,execPath:n})=>{const s=e?{...z.env,...t}:t;return o?Pn({env:s,cwd:r,execPath:n}):s},Gi=(t,e,o={})=>{const r=yn._parse(t,e,o);return t=r.command,e=r.args,o=r.options,o={maxBuffer:Fi,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:o.cwd||z.cwd(),execPath:z.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Ti,...o},o.env=Di(o),o.stdio=Un(o),z.platform==="win32"&&te.basename(t,".exe")==="cmd"&&e.unshift("/q"),{file:t,args:e,options:o,parsed:r}},Et=(t,e,o)=>typeof e!="string"&&!qo.isBuffer(e)?o===void 0?void 0:"":t.stripFinalNewline?wn(e):e;function X(t,e,o){const r=Gi(t,e,o),n=Oi(t,e),s=Li(t,e);_i(s,r.options),ii(r.options);let i;try{i=Xt.spawn(r.file,r.args,r.options)}catch(d){const h=new Xt.ChildProcess,g=Promise.reject(Ir({error:d,stdout:"",stderr:"",all:"",command:n,escapedCommand:s,parsed:r,timedOut:!1,isCanceled:!1,killed:!1}));return Dr(h,g),h}const c=ki(i),l=ni(i,r.options,c),p=ai(i,r.options,l),m={isCanceled:!1};i.kill=Qn.bind(null,i.kill.bind(i)),i.cancel=oi.bind(null,i,m);const u=Sr(async()=>{const[{error:d,exitCode:h,signal:g,timedOut:y},v,P,L]=await xi(i,r.options,p),_=Et(r.options,v),W=Et(r.options,P),fe=Et(r.options,L);if(d||h!==0||g!==null){const V=Ir({error:d,exitCode:h,signal:g,stdout:_,stderr:W,all:fe,command:n,escapedCommand:s,parsed:r,timedOut:y,isCanceled:m.isCanceled||(r.options.signal?r.options.signal.aborted:!1),killed:i.killed});if(!r.options.reject)return V;throw V}return{command:n,escapedCommand:s,exitCode:0,stdout:_,stderr:W,all:fe,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return $i(i,r.options),i.all=Ei(i,r.options),li(i),Dr(i,u),i}class R{static create(e,o){return new e(o)}}const{hasOwnProperty:xt}=Object.prototype,Be=typeof process<"u"&&process.platform==="win32"?`\r
|
|
9
9
|
`:`
|
|
10
|
-
`,
|
|
10
|
+
`,St=(t,e)=>{const o=[];let r="";typeof e=="string"?e={section:e,whitespace:!1}:(e=e||Object.create(null),e.whitespace=e.whitespace===!0);const n=e.whitespace?" = ":"=";for(const s of Object.keys(t)){const i=t[s];if(i&&Array.isArray(i))for(const c of i)r+=ae(s+"[]")+n+ae(c)+Be;else i&&typeof i=="object"?o.push(s):r+=ae(s)+n+ae(i)+Be}e.section&&r.length&&(r="["+ae(e.section)+"]"+Be+r);for(const s of o){const i=jr(s).join("\\."),c=(e.section?e.section+".":"")+i,{whitespace:l}=e,p=St(t[s],{section:c,whitespace:l});r.length&&p.length&&(r+=Be),r+=p}return r},jr=t=>t.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(e=>e.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),Br=t=>{const e=Object.create(null);let o=e,r=null;const n=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,s=t.split(/[\r\n]+/g);for(const c of s){if(!c||c.match(/^\s*[;#]/))continue;const l=c.match(n);if(!l)continue;if(l[1]!==void 0){if(r=He(l[1]),r==="__proto__"){o=Object.create(null);continue}o=e[r]=e[r]||Object.create(null);continue}const p=He(l[2]),m=p.length>2&&p.slice(-2)==="[]",a=m?p.slice(0,-2):p;if(a==="__proto__")continue;const u=l[3]?He(l[4]):!0,d=u==="true"||u==="false"||u==="null"?JSON.parse(u):u;m&&(xt.call(o,a)?Array.isArray(o[a])||(o[a]=[o[a]]):o[a]=[]),Array.isArray(o[a])?o[a].push(d):o[a]=d}const i=[];for(const c of Object.keys(e)){if(!xt.call(e,c)||typeof e[c]!="object"||Array.isArray(e[c]))continue;const l=jr(c);o=e;const p=l.pop(),m=p.replace(/\\\./g,".");for(const a of l)a!=="__proto__"&&((!xt.call(o,a)||typeof o[a]!="object")&&(o[a]=Object.create(null)),o=o[a]);o===e&&m===p||(o[m]=e[c],i.push(c))}for(const c of i)delete e[c];return e},Hr=t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"),ae=t=>typeof t!="string"||t.match(/[=\r\n]/)||t.match(/^\[/)||t.length>1&&Hr(t)||t!==t.trim()?JSON.stringify(t):t.split(";").join("\\;").split("#").join("\\#"),He=(t,e)=>{if(t=(t||"").trim(),Hr(t)){t.charAt(0)==="'"&&(t=t.slice(1,-1));try{t=JSON.parse(t)}catch{}}else{let o=!1,r="";for(let n=0,s=t.length;n<s;n++){const i=t.charAt(n);if(o)"\\;#".indexOf(i)!==-1?r+=i:r+="\\"+i,o=!1;else{if(";#".indexOf(i)!==-1)break;i==="\\"?o=!0:r+=i}}return o&&(r+="\\"),r.trim()}return t};var ji={parse:Br,decode:Br,stringify:St,encode:St,safe:ae,unsafe:He},ce=re(ji);class C extends Error{}const At=" ",ee=t=>{t instanceof Error&&(t instanceof C||(t.stack&&console.error(w.dim(t.stack.split(`
|
|
11
11
|
`).slice(1).join(`
|
|
12
12
|
`))),console.error(`
|
|
13
|
-
${
|
|
14
|
-
${St}Please open a Bug report with the information above:`),console.error(`${St}https://github.com/tak-bro/aicommit2/issues/new/choose`)))},Ur=t=>x.lstat(t).then(()=>!0,()=>!1),qr=async t=>{try{await x.mkdir(t,{recursive:!0})}catch(e){if(e.code!=="EEXIST")throw e}},Ue=t=>t&&`${t[0].toUpperCase()}${t.slice(1)}`,qe=(t,e)=>{const o=Math.ceil(t),r=Math.floor(e);return Math.floor(Math.random()*(r-o+1))+o},Bi=(t,e)=>t.disabled&&!e.disabled?1:!t.disabled&&e.disabled?-1:0,ze=t=>t.reduce((e,o)=>Array.isArray(o)?e.concat(ze(o)):e.concat(o),[]),zr=(t,e=5)=>t.replace(/[\n\r]/g,"").split(" ").slice(0,e).join(" "),Hi=t=>{let e=0;for(let o=0;o<t.length;o++){const r=t.charCodeAt(o);e=(e<<5)-e+r,e=e&e}return Math.abs(e)},Ui=t=>{const e=t%360,o=65+t%15,r=45+t%10;return`hsl(${e}, ${o}%, ${r}%)`},qi=t=>{const[e,o,r]=t.match(/\d+/g).map((a,u)=>u===0?Number(a):Number(a)/100),n=(1-Math.abs(2*r-1))*o,s=n*(1-Math.abs(e/60%2-1)),i=r-n/2;let c,l,p;e<60?[c,l,p]=[n,s,0]:e<120?[c,l,p]=[s,n,0]:e<180?[c,l,p]=[0,n,s]:e<240?[c,l,p]=[0,s,n]:e<300?[c,l,p]=[s,0,n]:[c,l,p]=[n,0,s];const m=a=>{const u=Math.round((a+i)*255).toString(16);return u.length===1?"0"+u:u};return`#${m(c)}${m(l)}${m(p)}`},zi=t=>{const e=Hi(t),o=Ui(e);return{primary:qi(o),secondary:"#FFFFFF"}},Ki=t=>{try{return{ok:!0,data:JSON.parse(t)}}catch(e){return{ok:!1,error:e}}},Ke=t=>{if(!t||typeof t!="string")return"";if(P.isAbsolute(t))return P.resolve(t);if(ve){const e=P.dirname(ve),o=P.join(e,t);return P.resolve(o)}else return""},Wi=["","conventional","gitmoji"],kt="http://localhost:11434",{hasOwnProperty:Yi}=Object.prototype,Mt=(t,e)=>Yi.call(t,e),le=["OPENAI","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK"],Kr=t=>{const e=Re.platform(),o=Re.homedir();let r,n;switch(t){case"config":r=process.env.XDG_CONFIG_HOME;break;case"data":r=process.env.XDG_DATA_HOME;break;case"cache":r=process.env.XDG_CACHE_HOME;break;case"state":r=process.env.XDG_STATE_HOME;break;default:r=void 0}if(e==="darwin")t==="cache"?n=P.join(o,"Library","Caches"):n=P.join(o,"Application Support");else if(e==="win32")n=process.env.LOCALAPPDATA||o;else switch(t){case"config":n=P.join(o,".config");break;case"data":n=P.join(o,".local","share");break;case"cache":n=P.join(o,".cache");break;case"state":n=P.join(o,".local","state");break;default:n=o}return r||n},Vi=P.join(Kr("config"),"aicommit2"),We=P.join(Kr("state"),"aicommit2","logs"),Wr=P.join(Vi,"config.ini"),Yr=P.join(We,"aicommit2-%DATE%.log"),Vr=P.join(We,"exceptions-%DATE%.log"),Xi=t=>{const e=Object.keys(t),o=new Set([...le,...e.filter(r=>/^[A-Z][A-Z0-9_]*$/.test(r))]);return Array.from(o)},b=(t,e,o)=>{if(!e)throw new C(`Invalid config property ${t}: ${o}`)},f={systemPrompt(t){return t||""},systemPromptPath(t){return t||""},codeReviewPromptPath(t){return t||""},timeout(t){if(!t)return 1e4;b("timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("timeout",e>=500,"Must be greater than 500ms"),e},temperature(t){if(!t)return .7;b("temperature",/^(2|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 2");const e=Number(t);return b("temperature",e>0,"Must be greater than 0"),b("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens(t){return t?(b("maxTokens",/^\d+$/.test(t),"Must be an integer"),Number(t)):1024},logging(t){return typeof t=="boolean"?t:t==null?!0:(b("logging",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},logLevel(t){return t?(b("logLevel",/^(?:error|warn|info|http|verbose|debug|silly)$/.test(t),"Must be a valid log level (error, warn, info, http, verbose, debug, silly)"),t):"info"},logFilePath(t){return t||Yr},exceptionLogFilePath(t){return t||Vr},locale(t){return t?(b("locale",t,"Cannot be empty"),b("locale",/^[a-z-]+$/i.test(t),"Must be a valid locale (letters and dashes/underscores). You can consult the list of codes in: https://wikipedia.org/wiki/List_of_ISO_639-1_codes"),t):"en"},generate(t){if(!t)return 1;b("generate",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("generate",e>0,"Must be greater than 0"),b("generate",e<=5,"Must be less or equal to 5"),e},type(t){return t?(b("type",Wi.includes(t),"Invalid commit type"),t):"conventional"},maxLength(t){if(!t)return 50;b("maxLength",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("maxLength",e>=20,"Must be greater than 20 characters"),e},includeBody(t){return typeof t=="boolean"?t:t==null?!1:(b("includeBody",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},exclude:t=>t?(typeof t=="string"?t?.split(","):t).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],topP:t=>{if(!t)return .9;b("topP",/^(1|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 1");const e=Number(t);return b("topP",e>0,"Must be greater than 0"),b("topP",e<=1,"Must be less than or equal to 1"),e},codeReview(t){return typeof t=="boolean"?t:t==null?!1:(b("codeReview",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},disabled(t){return typeof t=="boolean"?t:t==null?!1:(b("disabled",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},watchMode(t){return typeof t=="boolean"?t:t==null?!1:(b("watchMode",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")}},we={OPENAI:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(o=>o.trim()).filter(o=>!!o&&o.length>0):["gpt-4o-mini"],url:t=>t?(b("OPENAI.url",/^https?:\/\//.test(t),"Must be a valid URL"),t):"https://api.openai.com",path:t=>t||"/v1/chat/completions",proxy:t=>t||"",topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},HUGGINGFACE:{cookie:t=>t||"",model:t=>{if(!t)return["CohereForAI/c4ai-command-r-plus"];const e=typeof t=="string"?t?.split(","):t,o=["CohereForAI/c4ai-command-r-plus","meta-llama/Meta-Llama-3-70B-Instruct","HuggingFaceH4/zephyr-orpo-141b-A35b-v0.1","mistralai/Mixtral-8x7B-Instruct-v0.1","NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO","01-ai/Yi-1.5-34B-Chat","mistralai/Mistral-7B-Instruct-v0.2","microsoft/Phi-3-mini-4k-instruct"];for(const r of e)b("HUGGINGFACE.model",o.includes(r.trim()),`Invalid model type of HuggingFace chat: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},GEMINI:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["gemini-2.0-flash"];const e=typeof t=="string"?t?.split(","):t,o=["gemini-2.5-flash","gemini-2.5-flash-preview-04-17","gemini-2.5-flash-preview-05-20","gemini-2.5-flash-lite-preview-06-17","gemini-2.5-pro","gemini-2.5-pro-preview-05-06","gemini-2.0-flash","gemini-2.0-flash-lite","gemini-2.0-flash-preview-image-generation","gemini-1.5-pro","gemini-1.5-flash","gemini-1.5-flash-8b"];for(const r of e)b("GEMINI.model",o.includes(r.trim()),`Invalid model type of Gemini: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},ANTHROPIC:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["claude-3-5-haiku-20241022"];const e=typeof t=="string"?t?.split(","):t,o=["claude-opus-4-20250514","claude-sonnet-4-20250514","claude-3-7-sonnet-20250219","claude-3-5-sonnet-20241022","claude-3-5-haiku-20241022","claude-3-opus-20240229","claude-3-sonnet-20240229","claude-3-haiku-20240307"];for(const r of e)b("ANTHROPIC.model",o.includes(r.trim()),`Invalid model type of Anthropic: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},MISTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["pixtral-12b-2409"];const e=typeof t=="string"?t?.split(","):t,o=["codestral-latest","mistral-large-latest","pixtral-large-latest","ministral-8b-latest","mistral-small-latest","mistral-embed","mistral-moderation-latest"];for(const r of e)b("MISTRAL.model",o.includes(r.trim()),`Invalid model type of Mistral AI: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},CODESTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["codestral-latest"];const e=typeof t=="string"?t?.split(","):t,o=["codestral-latest","codestral-2501"];for(const r of e)b("CODESTRAL.model",o.includes(r.trim()),`Invalid model type of Codestral: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},OLLAMA:{model:t=>t?(typeof t=="string"?t?.split(","):t).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],host:t=>t?(b("OLLAMA.host",/^https?:\/\//.test(t),"Must be a valid URL"),t):kt,timeout:t=>{if(!t)return 1e5;b("OLLAMA.timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("OLLAMA.timeout",e>=500,"Must be greater than 500ms"),e},auth:t=>t||"",key:t=>t||"",envKey:t=>t||"",numCtx:t=>{if(!t)return 2048;b("OLLAMA.numCtx",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("OLLAMA.numCtx",e>=2048,"Must be greater than 2048"),e},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},COHERE:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["command"];const e=typeof t=="string"?t?.split(","):t,o=["command-r7b-12-2024","command-r-plus-08-2024","command-r-plus-04-2024","command-r-plus","command-r-08-2024","command-r-03-2024","command-r","command","command-nightly","command-light","command-light-nightly","c4ai-aya-expanse-8b","c4ai-aya-expanse-32b"];for(const r of e)b("COHERE.model",o.includes(r.trim()),`Invalid model type of Cohere: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},GROQ:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["llama-3.3-70b-versatile"];const e=typeof t=="string"?t?.split(","):t,o=["allam-2-7b","compound-beta","compound-beta-mini","deepseek-r1-distill-llama-70b","distil-whisper-large-v3-en","gemma2-9b-it","llama-3.1-8b-instant","llama-3.3-70b-versatile","llama-guard-3-8b","llama3-70b-8192","llama3-8b-8192","meta-llama/llama-4-maverick-17b-128e-instruct","meta-llama/llama-4-scout-17b-16e-instruct","mistral-saba-24b","playai-tts","playai-tts-arabic","qwen-qwq-32b","whisper-large-v3","whisper-large-v3-turbo"];for(const r of e)b("GROQ.model",o.includes(r.trim()),`Invalid model type of Groq: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},PERPLEXITY:{key:t=>t||"",model:t=>{if(!t)return["sonar"];const e=typeof t=="string"?t?.split(","):t,o=["sonar-pro","sonar","llama-3.1-sonar-small-128k-online","llama-3.1-sonar-large-128k-online","llama-3.1-sonar-huge-128k-online"];for(const r of e)b("PERPLEXITY.model",o.includes(r.trim()),`Invalid model type of Perplexity: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},DEEPSEEK:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["deepseek-chat"];const e=typeof t=="string"?t?.split(","):t,o=["deepseek-reasoner","deepseek-chat"];for(const r of e)b("DEEPSEEK.model",o.includes(r.trim()),`Invalid model type of DeepSeek: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode}};let ve;const Ji=(t=[])=>{const e={};for(const o of t)if(o.startsWith("--")){const[r,n]=o.slice(2).split("="),[s,i]=r.split(".");s&&i&&s in we?(e[s]||(e[s]={}),e[s][i]=n):e[r]=n}return e},Qi=()=>{const t=Re.homedir(),e=process.env.AICOMMIT_CONFIG_PATH,o=Wr,r=P.join(t,".aicommit2");return[e,o,r].filter(n=>!!n)},me=async()=>{const t=Qi();for(const e of t)if(await Ur(e))return e;return Wr},be=async()=>{const t=await me();ve=t;try{const e=await x.readFile(t,"utf8");return ce.parse(e)}catch(e){return e.code==="ENOENT"?(ve=void 0,{}):(console.error(`Error reading config file ${t}:`,e),ve=void 0,{})}},ue=async(t,e=[])=>{const o=await be(),r=Ji(e),n={...t,...r},s={},i=Xi(o),c={};for(const p of i){const a=o[p]?.envKey||`${p}_API_KEY`,u=process.env[a];u&&(c[p]={key:u})}const l=(p,m)=>{const a=n[`${p}.${m}`]??n[p]?.[m],u=c[p]?.[m],d=o[p]?.[m],h=n[m]??o[m];return a!==void 0?a:u!==void 0?u:d!==void 0?d:h};for(const[p,m]of Object.entries(f)){const a=n[p]??o[p];s[p]=m(a)}for(const p of i){s[p]={};const m=we[p]||Ye(p);for(const[a,u]of Object.entries(m)){const d=l(p,a);s[p][a]=u(d)}}return s},Zi=async t=>{const e=await be();for(const[n,s]of t){const[i,c]=n.split(".");if(!c){const m=f[n];if(!m)throw new C(`Invalid config property: ${n}`);e[n]=m(s);continue}if(e[i]||(e[i]={}),le.includes(i)){const m=we[i][c];if(!m)throw new C(`Invalid config property: ${n}`);e[i][c]=m(s);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(i))throw new C(`Invalid service name: ${i}. Service names must be uppercase letters, numbers, and underscores.`);const p=Ye(i);if(!p[c])throw new C(`Invalid config property for custom service: ${n}`);try{e[i][c]=p[c](s)}catch(m){throw m instanceof C?m:new C(`Invalid value for ${n}: ${m.message}`)}}const o=await me(),r=P.dirname(o);await x.mkdir(r,{recursive:!0}),await x.writeFile(o,ce.stringify(e),"utf8")},ea=async t=>{const e=await be();for(const[n,s]of t){const[i,c]=n.split("."),l=e[i];if(c==="model"){l||(e[i]={});const m=e[i][c]||[],a=typeof s=="string"?s.split(",").map(u=>u.trim()).filter(u=>!!u):s;e[i][c]=ze([...m,...a]);continue}if(l&&l.compatible===!0){l||(e[i]={});const m=Ye(i);if(!m[c])throw new C(`Invalid config property: ${n}`);try{e[i][c]=m[c](s)}catch(a){throw a instanceof C?a:new C(`Invalid value for ${n}: ${a.message}`)}continue}if(i in we){l||(e[i]={});const m=we[i][c];if(!m)throw new C(`Invalid config property: ${n}`);e[i][c]=m(s)}else{const m=Ye(i);if(!m[c])throw new C(`Invalid config property: ${n}`);e[i]||(e[i]={}),e[i][c]=m[c](s)}}const o=await me(),r=P.dirname(o);await x.mkdir(r,{recursive:!0}),await x.writeFile(o,ce.stringify(e),"utf8")},ta=async()=>{const t=await be();console.log(ce.stringify(t))},ra=async()=>{console.log(await me())},Ye=t=>({compatible:e=>typeof e=="boolean"?e:e==null?!1:(b("compatible",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),stream:e=>typeof e=="boolean"?e:e==null?!1:(b("stream",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),url:e=>e?(b(`${t}.url`,/^https?:\/\//.test(e),"Must be a valid URL"),e):"",path:e=>e||"",key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(r=>r.trim()).filter(r=>!!r&&r.length>0):[],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode});let Ve;async function oa(t){if(Ve){console.warn("Logger already initialized. Skipping re-initialization.");return}const e=t?.logLevel||"info",o=t?.logFilePath||Yr,r=t?.exceptionLogFilePath||Vr,n=t?.logging??!0;await qr(P.dirname(o)),await qr(P.dirname(r));const s=[];n&&s.push(new q.transports.DailyRotateFile({filename:o,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",level:e,format:q.format.combine(q.format.timestamp(),q.format.printf(({level:i,message:c,timestamp:l})=>`[${l}] ${i}: ${c}`))})),Ve=q.createLogger({level:e,format:q.format.json(),transports:s,exceptionHandlers:n?[new q.transports.DailyRotateFile({filename:r,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",format:q.format.combine(q.format.timestamp(),q.format.json())})]:[],exitOnError:!1})}const Ce=new Proxy({},{get:(t,e,o)=>{if(!Ve)throw new Error("Logger not initialized. Call initializeLogger() first.");return Reflect.get(Ve,e,o)}});class G{constructor(e){this.handleError$=o=>{let r=o.name??"Unknown Error";return Ce.error(`${this.errorPrefix} ${o}`),o.stack&&Ce.error(` ${o.stack}`),o.content&&Ce.error(` Problematic content: ${o.content}`),o.originalError&&Ce.error(` Original error: ${o.originalError}`),o.status?r=`${o.status} ${r}`:o.code&&(r=`${o.code} ${r}`),de({name:`${this.errorPrefix} ${r}`,value:r,isError:!0,disabled:!0})},this.serviceName="AI",this.errorPrefix="ERROR",this.colors={primary:""}}parseMessage(e,o,r){const n=/(\[\s*\{[\s\S]*?\}\s*\]|\{[\s\S]*?\})/,s=e.match(n);if(!s){const a=new Error("AI response did not contain a valid JSON object or array.");throw a.name="InvalidJsonResponse",a.content=e,a}const i=s[0],c=Ki(i);if(!c.ok){const a=new Error("Failed to parse AI response as JSON");throw a.name="JsonParseError",a.content=i,a.originalError=c.error,a}const l=c.data,p=Array.isArray(l)?l:[l];if(!p.length||!p.every(a=>typeof a.subject=="string")){const a=new Error("AI response contained malformed commit message data.");throw a.name="MalformedCommitMessage",a.content=e,a}return p.map(a=>this.extractMessageAsType(a,o)).map(a=>({title:`${a.subject}`,value:`${a.subject}${a.body?`
|
|
13
|
+
${At}${w.dim(`aicommit2 v${lr}`)}`),console.error(`
|
|
14
|
+
${At}Please open a Bug report with the information above:`),console.error(`${At}https://github.com/tak-bro/aicommit2/issues/new/choose`)))},Ur=t=>x.lstat(t).then(()=>!0,()=>!1),qr=async t=>{try{await x.mkdir(t,{recursive:!0})}catch(e){if(e.code!=="EEXIST")throw e}},Ue=t=>t&&`${t[0].toUpperCase()}${t.slice(1)}`,qe=(t,e)=>{const o=Math.ceil(t),r=Math.floor(e);return Math.floor(Math.random()*(r-o+1))+o},Bi=(t,e)=>t.disabled&&!e.disabled?1:!t.disabled&&e.disabled?-1:0,ze=t=>t.reduce((e,o)=>Array.isArray(o)?e.concat(ze(o)):e.concat(o),[]),zr=(t,e=5)=>t.replace(/[\n\r]/g,"").split(" ").slice(0,e).join(" "),Hi=t=>{let e=0;for(let o=0;o<t.length;o++){const r=t.charCodeAt(o);e=(e<<5)-e+r,e=e&e}return Math.abs(e)},Ui=t=>{const e=t%360,o=65+t%15,r=45+t%10;return`hsl(${e}, ${o}%, ${r}%)`},qi=t=>{const[e,o,r]=t.match(/\d+/g).map((a,u)=>u===0?Number(a):Number(a)/100),n=(1-Math.abs(2*r-1))*o,s=n*(1-Math.abs(e/60%2-1)),i=r-n/2;let c,l,p;e<60?[c,l,p]=[n,s,0]:e<120?[c,l,p]=[s,n,0]:e<180?[c,l,p]=[0,n,s]:e<240?[c,l,p]=[0,s,n]:e<300?[c,l,p]=[s,0,n]:[c,l,p]=[n,0,s];const m=a=>{const u=Math.round((a+i)*255).toString(16);return u.length===1?"0"+u:u};return`#${m(c)}${m(l)}${m(p)}`},zi=t=>{const e=Hi(t),o=Ui(e);return{primary:qi(o),secondary:"#FFFFFF"}},Ki=t=>{try{return{ok:!0,data:JSON.parse(t)}}catch(e){return{ok:!1,error:e}}},Ke=t=>{if(!t||typeof t!="string")return"";if($.isAbsolute(t))return $.resolve(t);if(ve){const e=$.dirname(ve),o=$.join(e,t);return $.resolve(o)}else return""},Wi=["","conventional","gitmoji"],kt="http://localhost:11434",{hasOwnProperty:Yi}=Object.prototype,Mt=(t,e)=>Yi.call(t,e),le=["OPENAI","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK"],Kr=t=>{const e=Re.platform(),o=Re.homedir();let r,n;switch(t){case"config":r=process.env.XDG_CONFIG_HOME;break;case"data":r=process.env.XDG_DATA_HOME;break;case"cache":r=process.env.XDG_CACHE_HOME;break;case"state":r=process.env.XDG_STATE_HOME;break;default:r=void 0}if(e==="darwin")t==="cache"?n=$.join(o,"Library","Caches"):n=$.join(o,"Application Support");else if(e==="win32")n=process.env.LOCALAPPDATA||o;else switch(t){case"config":n=$.join(o,".config");break;case"data":n=$.join(o,".local","share");break;case"cache":n=$.join(o,".cache");break;case"state":n=$.join(o,".local","state");break;default:n=o}return r||n},Vi=$.join(Kr("config"),"aicommit2"),We=$.join(Kr("state"),"aicommit2","logs"),Wr=$.join(Vi,"config.ini"),Yr=$.join(We,"aicommit2-%DATE%.log"),Vr=$.join(We,"exceptions-%DATE%.log"),Xi=t=>{const e=Object.keys(t),o=new Set([...le,...e.filter(r=>/^[A-Z][A-Z0-9_]*$/.test(r))]);return Array.from(o)},b=(t,e,o)=>{if(!e)throw new C(`Invalid config property ${t}: ${o}`)},f={systemPrompt(t){return t||""},systemPromptPath(t){return t||""},codeReviewPromptPath(t){return t||""},timeout(t){if(!t)return 1e4;b("timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("timeout",e>=500,"Must be greater than 500ms"),e},temperature(t){if(!t)return .7;b("temperature",/^(2|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 2");const e=Number(t);return b("temperature",e>0,"Must be greater than 0"),b("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens(t){return t?(b("maxTokens",/^\d+$/.test(t),"Must be an integer"),Number(t)):1024},logging(t){return typeof t=="boolean"?t:t==null?!0:(b("logging",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},logLevel(t){return t?(b("logLevel",/^(?:error|warn|info|http|verbose|debug|silly)$/.test(t),"Must be a valid log level (error, warn, info, http, verbose, debug, silly)"),t):"info"},logFilePath(t){return t||Yr},exceptionLogFilePath(t){return t||Vr},locale(t){return t?(b("locale",t,"Cannot be empty"),b("locale",/^[a-z-]+$/i.test(t),"Must be a valid locale (letters and dashes/underscores). You can consult the list of codes in: https://wikipedia.org/wiki/List_of_ISO_639-1_codes"),t):"en"},generate(t){if(!t)return 1;b("generate",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("generate",e>0,"Must be greater than 0"),b("generate",e<=5,"Must be less or equal to 5"),e},type(t){return t?(b("type",Wi.includes(t),"Invalid commit type"),t):"conventional"},maxLength(t){if(!t)return 50;b("maxLength",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("maxLength",e>=20,"Must be greater than 20 characters"),e},includeBody(t){return typeof t=="boolean"?t:t==null?!1:(b("includeBody",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},exclude:t=>t?(typeof t=="string"?t?.split(","):t).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],topP:t=>{if(!t)return .9;b("topP",/^(1|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 1");const e=Number(t);return b("topP",e>0,"Must be greater than 0"),b("topP",e<=1,"Must be less than or equal to 1"),e},codeReview(t){return typeof t=="boolean"?t:t==null?!1:(b("codeReview",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},disabled(t){return typeof t=="boolean"?t:t==null?!1:(b("disabled",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},watchMode(t){return typeof t=="boolean"?t:t==null?!1:(b("watchMode",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")}},we={OPENAI:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(o=>o.trim()).filter(o=>!!o&&o.length>0):["gpt-4o-mini"],url:t=>t?(b("OPENAI.url",/^https?:\/\//.test(t),"Must be a valid URL"),t):"https://api.openai.com",path:t=>t||"/v1/chat/completions",proxy:t=>t||"",topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},HUGGINGFACE:{cookie:t=>t||"",model:t=>{if(!t)return["CohereForAI/c4ai-command-r-plus"];const e=typeof t=="string"?t?.split(","):t,o=["CohereForAI/c4ai-command-r-plus","meta-llama/Meta-Llama-3-70B-Instruct","HuggingFaceH4/zephyr-orpo-141b-A35b-v0.1","mistralai/Mixtral-8x7B-Instruct-v0.1","NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO","01-ai/Yi-1.5-34B-Chat","mistralai/Mistral-7B-Instruct-v0.2","microsoft/Phi-3-mini-4k-instruct"];for(const r of e)b("HUGGINGFACE.model",o.includes(r.trim()),`Invalid model type of HuggingFace chat: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},GEMINI:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["gemini-2.0-flash"];const e=typeof t=="string"?t?.split(","):t,o=["gemini-2.5-flash","gemini-2.5-flash-preview-04-17","gemini-2.5-flash-preview-05-20","gemini-2.5-flash-lite-preview-06-17","gemini-2.5-pro","gemini-2.5-pro-preview-05-06","gemini-2.0-flash","gemini-2.0-flash-lite","gemini-2.0-flash-preview-image-generation","gemini-1.5-pro","gemini-1.5-flash","gemini-1.5-flash-8b"];for(const r of e)b("GEMINI.model",o.includes(r.trim()),`Invalid model type of Gemini: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},ANTHROPIC:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["claude-3-5-haiku-20241022"];const e=typeof t=="string"?t?.split(","):t,o=["claude-opus-4-20250514","claude-sonnet-4-20250514","claude-3-7-sonnet-20250219","claude-3-5-sonnet-20241022","claude-3-5-haiku-20241022","claude-3-opus-20240229","claude-3-sonnet-20240229","claude-3-haiku-20240307"];for(const r of e)b("ANTHROPIC.model",o.includes(r.trim()),`Invalid model type of Anthropic: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},MISTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["pixtral-12b-2409"];const e=typeof t=="string"?t?.split(","):t,o=["codestral-latest","mistral-large-latest","pixtral-large-latest","ministral-8b-latest","mistral-small-latest","mistral-embed","mistral-moderation-latest"];for(const r of e)b("MISTRAL.model",o.includes(r.trim()),`Invalid model type of Mistral AI: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},CODESTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["codestral-latest"];const e=typeof t=="string"?t?.split(","):t,o=["codestral-latest","codestral-2501"];for(const r of e)b("CODESTRAL.model",o.includes(r.trim()),`Invalid model type of Codestral: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},OLLAMA:{model:t=>t?(typeof t=="string"?t?.split(","):t).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],host:t=>t?(b("OLLAMA.host",/^https?:\/\//.test(t),"Must be a valid URL"),t):kt,timeout:t=>{if(!t)return 1e5;b("OLLAMA.timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("OLLAMA.timeout",e>=500,"Must be greater than 500ms"),e},auth:t=>t||"",key:t=>t||"",envKey:t=>t||"",numCtx:t=>{if(!t)return 2048;b("OLLAMA.numCtx",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("OLLAMA.numCtx",e>=2048,"Must be greater than 2048"),e},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},COHERE:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["command"];const e=typeof t=="string"?t?.split(","):t,o=["command-r7b-12-2024","command-r-plus-08-2024","command-r-plus-04-2024","command-r-plus","command-r-08-2024","command-r-03-2024","command-r","command","command-nightly","command-light","command-light-nightly","c4ai-aya-expanse-8b","c4ai-aya-expanse-32b"];for(const r of e)b("COHERE.model",o.includes(r.trim()),`Invalid model type of Cohere: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},GROQ:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["llama-3.3-70b-versatile"];const e=typeof t=="string"?t?.split(","):t,o=["allam-2-7b","compound-beta","compound-beta-mini","deepseek-r1-distill-llama-70b","distil-whisper-large-v3-en","gemma2-9b-it","llama-3.1-8b-instant","llama-3.3-70b-versatile","llama-guard-3-8b","llama3-70b-8192","llama3-8b-8192","meta-llama/llama-4-maverick-17b-128e-instruct","meta-llama/llama-4-scout-17b-16e-instruct","mistral-saba-24b","playai-tts","playai-tts-arabic","qwen-qwq-32b","whisper-large-v3","whisper-large-v3-turbo"];for(const r of e)b("GROQ.model",o.includes(r.trim()),`Invalid model type of Groq: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},PERPLEXITY:{key:t=>t||"",model:t=>{if(!t)return["sonar"];const e=typeof t=="string"?t?.split(","):t,o=["sonar-pro","sonar","llama-3.1-sonar-small-128k-online","llama-3.1-sonar-large-128k-online","llama-3.1-sonar-huge-128k-online"];for(const r of e)b("PERPLEXITY.model",o.includes(r.trim()),`Invalid model type of Perplexity: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},DEEPSEEK:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["deepseek-chat"];const e=typeof t=="string"?t?.split(","):t,o=["deepseek-reasoner","deepseek-chat"];for(const r of e)b("DEEPSEEK.model",o.includes(r.trim()),`Invalid model type of DeepSeek: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode}};let ve;const Ji=(t=[])=>{const e={};for(const o of t)if(o.startsWith("--")){const[r,n]=o.slice(2).split("="),[s,i]=r.split(".");s&&i&&s in we?(e[s]||(e[s]={}),e[s][i]=n):e[r]=n}return e},Qi=()=>{const t=Re.homedir(),e=process.env.AICOMMIT_CONFIG_PATH,o=Wr,r=$.join(t,".aicommit2");return[e,o,r].filter(n=>!!n)},me=async()=>{const t=Qi();for(const e of t)if(await Ur(e))return e;return Wr},be=async()=>{const t=await me();ve=t;try{const e=await x.readFile(t,"utf8");return ce.parse(e)}catch(e){return e.code==="ENOENT"?(ve=void 0,{}):(console.error(`Error reading config file ${t}:`,e),ve=void 0,{})}},ue=async(t,e=[])=>{const o=await be(),r=Ji(e),n={...t,...r},s={},i=Xi(o),c={};for(const p of i){const a=o[p]?.envKey||`${p}_API_KEY`,u=process.env[a];u&&(c[p]={key:u})}const l=(p,m)=>{const a=n[`${p}.${m}`]??n[p]?.[m],u=c[p]?.[m],d=o[p]?.[m],h=n[m]??o[m];return a!==void 0?a:u!==void 0?u:d!==void 0?d:h};for(const[p,m]of Object.entries(f)){const a=n[p]??o[p];s[p]=m(a)}for(const p of i){s[p]={};const m=we[p]||Ye(p);for(const[a,u]of Object.entries(m)){const d=l(p,a);s[p][a]=u(d)}}return s},Zi=async t=>{const e=await be();for(const[n,s]of t){const[i,c]=n.split(".");if(!c){const m=f[n];if(!m)throw new C(`Invalid config property: ${n}`);e[n]=m(s);continue}if(e[i]||(e[i]={}),le.includes(i)){const m=we[i][c];if(!m)throw new C(`Invalid config property: ${n}`);e[i][c]=m(s);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(i))throw new C(`Invalid service name: ${i}. Service names must be uppercase letters, numbers, and underscores.`);const p=Ye(i);if(!p[c])throw new C(`Invalid config property for custom service: ${n}`);try{e[i][c]=p[c](s)}catch(m){throw m instanceof C?m:new C(`Invalid value for ${n}: ${m.message}`)}}const o=await me(),r=$.dirname(o);await x.mkdir(r,{recursive:!0}),await x.writeFile(o,ce.stringify(e),"utf8")},ea=async t=>{const e=await be();for(const[n,s]of t){const[i,c]=n.split("."),l=e[i];if(c==="model"){l||(e[i]={});const m=e[i][c]||[],a=typeof s=="string"?s.split(",").map(u=>u.trim()).filter(u=>!!u):s;e[i][c]=ze([...m,...a]);continue}if(l&&l.compatible===!0){l||(e[i]={});const m=Ye(i);if(!m[c])throw new C(`Invalid config property: ${n}`);try{e[i][c]=m[c](s)}catch(a){throw a instanceof C?a:new C(`Invalid value for ${n}: ${a.message}`)}continue}if(i in we){l||(e[i]={});const m=we[i][c];if(!m)throw new C(`Invalid config property: ${n}`);e[i][c]=m(s)}else{const m=Ye(i);if(!m[c])throw new C(`Invalid config property: ${n}`);e[i]||(e[i]={}),e[i][c]=m[c](s)}}const o=await me(),r=$.dirname(o);await x.mkdir(r,{recursive:!0}),await x.writeFile(o,ce.stringify(e),"utf8")},ta=async()=>{const t=await be();console.log(ce.stringify(t))},ra=async()=>{console.log(await me())},Ye=t=>({compatible:e=>typeof e=="boolean"?e:e==null?!1:(b("compatible",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),stream:e=>typeof e=="boolean"?e:e==null?!1:(b("stream",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),url:e=>e?(b(`${t}.url`,/^https?:\/\//.test(e),"Must be a valid URL"),e):"",path:e=>e||"",key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(r=>r.trim()).filter(r=>!!r&&r.length>0):[],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode});let Ve;async function oa(t){if(Ve){console.warn("Logger already initialized. Skipping re-initialization.");return}const e=t?.logLevel||"info",o=t?.logFilePath||Yr,r=t?.exceptionLogFilePath||Vr,n=t?.logging??!0;await qr($.dirname(o)),await qr($.dirname(r));const s=[];n&&s.push(new K.transports.DailyRotateFile({filename:o,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",level:e,format:K.format.combine(K.format.timestamp(),K.format.printf(({level:i,message:c,timestamp:l})=>`[${l}] ${i}: ${c}`))})),Ve=K.createLogger({level:e,format:K.format.json(),transports:s,exceptionHandlers:n?[new K.transports.DailyRotateFile({filename:r,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",format:K.format.combine(K.format.timestamp(),K.format.json())})]:[],exitOnError:!1})}const Ce=new Proxy({},{get:(t,e,o)=>{if(!Ve)throw new Error("Logger not initialized. Call initializeLogger() first.");return Reflect.get(Ve,e,o)}});class j{constructor(e){this.handleError$=o=>{let r=o.name??"Unknown Error";return Ce.error(`${this.errorPrefix} ${o}`),o.stack&&Ce.error(` ${o.stack}`),o.content&&Ce.error(` Problematic content: ${o.content}`),o.originalError&&Ce.error(` Original error: ${o.originalError}`),o.status?r=`${o.status} ${r}`:o.code&&(r=`${o.code} ${r}`),de({name:`${this.errorPrefix} ${r}`,value:r,isError:!0,disabled:!0})},this.serviceName="AI",this.errorPrefix="ERROR",this.colors={primary:""}}parseMessage(e,o,r){const n=/(\[\s*\{[\s\S]*?\}\s*\]|\{[\s\S]*?\})/,s=e.match(n);if(!s){const a=new Error("AI response did not contain a valid JSON object or array.");throw a.name="InvalidJsonResponse",a.content=e,a}const i=s[0],c=Ki(i);if(!c.ok){const a=new Error("Failed to parse AI response as JSON");throw a.name="JsonParseError",a.content=i,a.originalError=c.error,a}const l=c.data,p=Array.isArray(l)?l:[l];if(!p.length||!p.every(a=>typeof a.subject=="string")){const a=new Error("AI response contained malformed commit message data.");throw a.name="MalformedCommitMessage",a.content=e,a}return p.map(a=>this.extractMessageAsType(a,o)).map(a=>({title:`${a.subject}`,value:`${a.subject}${a.body?`
|
|
15
15
|
|
|
16
16
|
${a.body}`:""}${a.footer?`
|
|
17
17
|
|
|
18
|
-
${a.footer}`:""}`})).slice(0,r)}extractMessageAsType(e,o){switch(o){case"conventional":const r=/(\w+)(?:\(.*?\))?:\s*(.*)/,n=e.subject.match(r),s=n?n[0]:e.subject;return{...e,subject:this.normalizeCommitMessage(s)};case"gitmoji":const i=/:\w*:\s*(.*)/,c=e.subject.match(i);return{...e,subject:c?c[0].toLowerCase():e.subject};default:return e}}normalizeCommitMessage(e){const o=/^(\w+)(\(.*?\))?:\s(.*)$/,r=e.match(o);if(r){const[,n,s,i]=r,c=n.toLowerCase(),l=i.charAt(0).toLowerCase()+i.slice(1);e=`${c}${s||""}: ${l}`}return e}sanitizeResponse(e){if(typeof e=="string")try{return[{title:`${zr(e)}...`,value:e}]}catch{return[]}return e.map(o=>{try{return{title:`${zr(o)}...`,value:o}}catch{return{title:"",value:""}}})}}const sa=new Date,
|
|
18
|
+
${a.footer}`:""}`})).slice(0,r)}extractMessageAsType(e,o){switch(o){case"conventional":const r=/(\w+)(?:\(.*?\))?:\s*(.*)/,n=e.subject.match(r),s=n?n[0]:e.subject;return{...e,subject:this.normalizeCommitMessage(s)};case"gitmoji":const i=/:\w*:\s*(.*)/,c=e.subject.match(i);return{...e,subject:c?c[0].toLowerCase():e.subject};default:return e}}normalizeCommitMessage(e){const o=/^(\w+)(\(.*?\))?:\s(.*)$/,r=e.match(o);if(r){const[,n,s,i]=r,c=n.toLowerCase(),l=i.charAt(0).toLowerCase()+i.slice(1);e=`${c}${s||""}: ${l}`}return e}sanitizeResponse(e){if(typeof e=="string")try{return[{title:`${zr(e)}...`,value:e}]}catch{return[]}return e.map(o=>{try{return{title:`${zr(o)}...`,value:o}}catch{return{title:"",value:""}}})}}const sa=new Date,B=(t,e,o,r,n)=>{const s=`[${t}]`,i=na(sa,e,n),c=`${We}/${i}`,l=`- System Prompt
|
|
19
19
|
${o}`,p=`- Response
|
|
20
20
|
${r}`,m=`[Git Diff]
|
|
21
|
-
${e}`;if(
|
|
21
|
+
${e}`;if(F.existsSync(c)){const a=F.readFileSync(c,"utf-8");Xr(c,`${s}
|
|
22
22
|
${p}
|
|
23
23
|
|
|
24
24
|
${l}
|
|
@@ -28,7 +28,7 @@ ${p}
|
|
|
28
28
|
|
|
29
29
|
${l}
|
|
30
30
|
|
|
31
|
-
${m}`)},na=(t,e,o)=>{const{year:r,month:n,day:s,hours:i,minutes:c,seconds:l}=ia(t),m=es(0).update(e).digest("hex");return o==="review"?`aic2_review_${r}-${n}-${s}_${i}-${c}-${l}_${m}.log`:`aic2_${r}-${n}-${s}_${i}-${c}-${l}_${m}.log`},Xr=(t,e="")=>{
|
|
31
|
+
${m}`)},na=(t,e,o)=>{const{year:r,month:n,day:s,hours:i,minutes:c,seconds:l}=ia(t),m=es(0).update(e).digest("hex");return o==="review"?`aic2_review_${r}-${n}-${s}_${i}-${c}-${l}_${m}.log`:`aic2_${r}-${n}-${s}_${i}-${c}-${l}_${m}.log`},Xr=(t,e="")=>{F.mkdirSync($.dirname(t),{recursive:!0}),F.writeFileSync(t,e,"utf-8")},ia=t=>{const e=t.getFullYear().toString(),o=(t.getMonth()+1).toString().padStart(2,"0"),r=t.getDate().toString().padStart(2,"0"),n=t.getHours().toString().padStart(2,"0"),s=t.getMinutes().toString().padStart(2,"0"),i=t.getSeconds().toString().padStart(2,"0");return{year:e,month:o,day:r,hours:n,minutes:s,seconds:i}},G={locale:"en",maxLength:50,type:"conventional",generate:1,systemPrompt:"",systemPromptPath:"",codeReviewPromptPath:""},aa={"":"<commit message>",conventional:`<type>(<optional scope>): <description>
|
|
32
32
|
|
|
33
33
|
[optional body]
|
|
34
34
|
|
|
@@ -40,7 +40,7 @@ ${m}`)},na=(t,e,o)=>{const{year:r,month:n,day:s,hours:i,minutes:c,seconds:l}=ia(
|
|
|
40
40
|
${Object.entries({":sparkles:":"Introduce new features.",":bug:":"Fix a bug.",":memo:":"Add or update documentation.",":art:":"Improve structure / format of the code.",":zap:":"Improve performance.",":fire:":"Remove code or files.",":ambulance:":"Critical hotfix.",":white_check_mark:":"Add, update, or pass tests.",":lock:":"Fix security or privacy issues.",":rocket:":"Deploy stuff.",":lipstick:":"Add or update the UI and style files.",":tada:":"Begin a project.",":recycle:":"Refactor code.",":wrench:":"Add or update configuration files.",":bulb:":"Add or update comments in source code.",":twisted_rightwards_arrows:":"Merge branches."}).map(([t,e])=>` - ${t}: ${e}`).join(`
|
|
41
41
|
`)}`,conventional:`
|
|
42
42
|
${Object.entries({docs:"Documentation only changes",style:"Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)",refactor:"A code change that neither fixes a bug nor adds a feature",perf:"A code change that improves performance",test:"Adding missing tests or correcting existing tests",build:"Changes that affect the build system or external dependencies",ci:"Changes to CI configuration files, scripts",chore:"Other changes that don't modify src or test files",revert:"Reverts a previous commit",feat:"A new feature",fix:"A bug fix"}).map(([t,e])=>` - ${t}: ${e}`).join(`
|
|
43
|
-
`)}`},Jr=(t,e)=>t.replace(/{(\w+)}/g,(o,r)=>e[r]?.toString()||
|
|
43
|
+
`)}`},Jr=(t,e)=>t.replace(/{(\w+)}/g,(o,r)=>e[r]?.toString()||G[r]?.toString()),Qr=t=>{const{type:e,maxLength:o,generate:r,locale:n}=t;return[`You are a helpful assistant specializing in writing clear and informative Git commit messages using the ${e} style`,`Based on the given code changes or context, generate exactly ${r} ${e} Git commit message${r!==1?"s":""} based on the following guidelines.`,`1. Message Language: ${n}`,`2. Format: follow the ${e} Commits format:`,`${aa[e]}`,`3. Types: use one of the following types:${ca[e]}`,"4. Guidelines for writing commit messages:"," - Be specific about what changes were made",' - Use imperative mood ("add feature" not "added feature")',` - Keep subject line under ${o} characters`," - Do not end the subject line with a period"," - Use the body to explain what and why vs. how","5. Focus on:"," - What problem this commit solves"," - Why this change was necessary"," - Any important technical details","6. Exclude anything unnecessary such as translation or implementation details."].filter(Boolean).join(`
|
|
44
44
|
`)},Xe=(t,e)=>{const o=r=>r==="conventional"?`${Array(e).fill(null).map((n,s)=>`
|
|
45
45
|
{
|
|
46
46
|
"subject": "fix(auth): fix bug in user authentication process",
|
|
@@ -55,11 +55,11 @@ ${Object.entries({docs:"Documentation only changes",style:"Changes that do not a
|
|
|
55
55
|
Lastly, Provide your response as a JSON array containing exactly ${e} object${e!==1?"s":""}, each with the following keys:`,`- "subject": The main commit message using the ${t} style. It should be a concise summary of the changes.`,'- "body": An optional detailed explanation of the changes. If not needed, use an empty string.','- "footer": An optional footer for metadata like BREAKING CHANGES. If not needed, use an empty string.',`The array must always contain ${e} element${e!==1?"s":""}, no more and no less.`,`Example response format:
|
|
56
56
|
[${o(t)}
|
|
57
57
|
]`,`Ensure you generate exactly ${e} commit message${e!==1?"s":""}, even if it requires creating slightly varied versions for similar changes.`,"The response should be valid JSON that can be parsed without errors."].filter(Boolean).join(`
|
|
58
|
-
`)},
|
|
58
|
+
`)},H=t=>{const{systemPrompt:e,systemPromptPath:o,type:r,generate:n}=t;if(e)return`${e}
|
|
59
59
|
${Xe(r,n)}`;if(!o)return`${Qr(t)}
|
|
60
|
-
${Xe(r,n)}`;try{const s=
|
|
60
|
+
${Xe(r,n)}`;try{const s=F.readFileSync(Ke(o),"utf-8");return`${Jr(s,t)}
|
|
61
61
|
${Xe(r,n)}`}catch{return`${Qr(t)}
|
|
62
|
-
${Xe(r,n)}`}},
|
|
62
|
+
${Xe(r,n)}`}},U=t=>{const{codeReviewPromptPath:e,locale:o}=t,r=`I'll give you the output of the "git diff" command as an input. Please review the following code and provide your feedback in Markdown format. Focus on:
|
|
63
63
|
|
|
64
64
|
1. Language: ${o}
|
|
65
65
|
2. Code quality and best practices
|
|
@@ -67,23 +67,23 @@ ${Xe(r,n)}`}},H=t=>{const{codeReviewPromptPath:e,locale:o}=t,r=`I'll give you th
|
|
|
67
67
|
4. Performance improvements
|
|
68
68
|
5. Readability and maintainability
|
|
69
69
|
|
|
70
|
-
Please structure your response with appropriate Markdown headings, code blocks, and bullet points.`;if(!e)return r;try{const n=_.readFileSync(Ke(e),"utf-8");return`${Jr(n,t)}`}catch{return r}},Zr=async t=>{if(t.systemPromptPath)try{_.readFileSync(Ke(t.systemPromptPath),"utf-8")}catch(e){throw new C(`Error reading system prompt file: ${t.systemPromptPath}, ${e}`)}if(t.codeReview&&t.codeReviewPromptPath)try{_.readFileSync(Ke(t.codeReviewPromptPath),"utf-8")}catch(e){throw new C(`Error reading code review prompt file: ${t.codeReviewPromptPath}, ${e}`)}},la=10*60*1e3;class eo extends G{constructor(e){super(e),this.params=e,this.colors={primary:"#AE5630",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Anthropic]"),this.errorPrefix=w.red.bold("[Anthropic]"),this.anthropic=new Zo({apiKey:this.params.config.key,...this.params.config.timeout>la&&{timeout:this.params.config.timeout}})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>E(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>E(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,temperature:c,locale:l,generate:p,type:m,maxLength:a,maxTokens:u,topP:d,model:h}=this.params.config,g={...D,locale:l,maxLength:a,type:m,generate:p,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?H(g):B(g),v={max_tokens:u,temperature:c,system:y,messages:[{role:"user",content:`Here is the diff: ${o}`}],top_p:d,model:h},O=(await this.anthropic.messages.create(v)).content.map(({text:K})=>K).join("");return i&&j("Anthropic",o,y,O,e),e==="review"?this.sanitizeResponse(O):this.parseMessage(O,m,p)}}class Pe{constructor(e={}){if(!e.method)throw new Error("method should be defined!");if(!e.baseURL)throw new Error("baseURL should be defined!");this.config={...e},this.axiosInstance=ts.create(this.config)}setHeaders(e){return this.config.headers=e,this}setParams(e){return this.config.params=e,this}setBody(e){return this.config.data=e,this}addBody(e){return this.config.data={...this.config.data,...e},this}setMethod(e){return this.config.method=e,this}async execute(){try{return await this.axiosInstance.request(this.config)}catch(e){throw e}}}class to extends G{constructor(e){super(e),this.params=e,this.host="https://codestral.mistral.ai",this.apiKey="",this.colors={primary:"#e28c58",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Codestral]"),this.errorPrefix=w.red.bold("[Codestral]"),this.apiKey=this.params.config.key}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>E(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>E(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:p,maxLength:m}=this.params.config,a={...D,locale:c,maxLength:m,type:p,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},u=e==="review"?H(a):B(a);this.checkAvailableModels();const d=await this.createChatCompletions(u,e);return i&&j("Codestral",o,u,d,e),e==="review"?this.sanitizeResponse(d):this.parseMessage(d,p,l)}checkAvailableModels(){if(["codestral-latest","codestral-2501"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of Codestral AI")}async createChatCompletions(e,o){const r=new Pe({method:"POST",baseURL:`${this.host}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody({model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:`Here is the diff: ${this.params.stagedDiff.diff}`}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:qe(10,1e3)});o==="commit"&&r.addBody({response_format:{type:"json_object"}});const s=(await r.execute()).data;if(!s.choices||s.choices.length===0||!s.choices[0].message?.content)throw new Error("No Content on response. Please open a Bug report");return s.choices[0].message.content}}const ma=2*60*1e3;class ro extends G{constructor(e){super(e),this.params=e,this.colors={primary:"#D18EE2",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Cohere]"),this.errorPrefix=w.red.bold("[Cohere]"),this.cohere=new rs({token:this.params.config.key})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>E(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>E(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,temperature:c,locale:l,generate:p,type:m,maxLength:a,maxTokens:u}=this.params.config,d={...D,locale:l,maxLength:a,type:m,generate:p,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},h=e==="review"?H(d):B(d),g=await this.cohere.chat({chatHistory:h?[{role:"SYSTEM",message:h}]:[],message:`Here is the diff: ${o}`,connectors:[{id:"web-search"}],maxTokens:u,temperature:c,model:this.params.config.model,seed:qe(10,1e3),p:this.params.config.topP},{...this.params.config.timeout>ma&&{timeoutInSeconds:Math.floor(this.params.config.timeout/1e3)}});return i&&j("Cohere",o,h,g.text,e),e==="review"?this.sanitizeResponse(g.text):this.parseMessage(g.text,m,p)}}class oo extends G{constructor(e){super(e),this.params=e,this.host="https://api.deepseek.com",this.colors={primary:"#53a3f9",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[DeepSeek]"),this.errorPrefix=w.red.bold("[DeepSeek]"),this.deepSeek=new ar({baseURL:this.host,apiKey:this.params.config.key})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>E(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>E(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:p,maxLength:m}=this.params.config,a={...D,locale:c,maxLength:m,type:p,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},u=e==="review"?H(a):B(a);this.checkAvailableModels();const d=await this.createChatCompletions(u);return i&&j("DeepSeek",o,u,d,e),e==="review"?this.sanitizeResponse(d):this.parseMessage(d,p,l)}checkAvailableModels(){if(["deepseek-reasoner","deepseek-chat"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of DeepSeek")}async createChatCompletions(e){return(await this.deepSeek.chat.completions.create({messages:[{role:"system",content:e},{role:"user",content:`Here is the diff: ${this.params.stagedDiff.diff}`}],model:this.params.config.model,max_tokens:this.params.config.maxTokens,top_p:this.params.config.topP,temperature:this.params.config.temperature},{timeout:this.params.config.timeout})).choices[0].message.content||""}}class so extends G{constructor(e){super(e),this.params=e,this.colors={primary:"#0077FF",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Gemini]"),this.errorPrefix=w.red.bold("[Gemini]"),this.genAI=new os(this.params.config.key)}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>E(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>E(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,logging:s,locale:i,codeReviewPromptPath:c,generate:l,type:p,maxLength:m}=this.params.config,a=this.params.config.maxTokens,u={...D,locale:i,maxLength:m,type:p,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:c},d=e==="review"?H(u):B(u),h={maxOutputTokens:a,temperature:this.params.config.temperature,topP:this.params.config.topP},$=(await this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:d,generationConfig:h,safetySettings:[{category:Oe.HARM_CATEGORY_HATE_SPEECH,threshold:Le.BLOCK_LOW_AND_ABOVE},{category:Oe.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Le.BLOCK_LOW_AND_ABOVE},{category:Oe.HARM_CATEGORY_HARASSMENT,threshold:Le.BLOCK_LOW_AND_ABOVE},{category:Oe.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Le.BLOCK_LOW_AND_ABOVE}]}).generateContent(`Here is the diff: ${o}`)).response.text();return s&&j("Gemini",o,d,$,e),e==="review"?this.sanitizeResponse($):this.parseMessage($,p,l)}}class no extends G{constructor(e){super(e),this.params=e,this.colors={primary:"#f55036",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Groq]"),this.errorPrefix=w.red.bold("[Groq]"),this.groq=new ss({apiKey:this.params.config.key})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>E(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>E(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,temperature:l,generate:p,type:m,maxLength:a}=this.params.config,u=this.params.config.maxTokens,d={...D,locale:c,maxLength:a,type:m,generate:p,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},h=e==="review"?H(d):B(d),y=(await this.groq.chat.completions.create({messages:[{role:"system",content:h},{role:"user",content:`Here is the diff: ${o}`}],model:this.params.config.model,max_tokens:u,top_p:this.params.config.topP,temperature:l},{timeout:this.params.config.timeout})).choices[0].message.content||"";return i&&j("Groq",o,h,y,e),e==="review"?this.sanitizeResponse(y):this.parseMessage(y,m,p)}}class io extends G{constructor(e){super(e),this.params=e,this.headers={accept:"*/*","accept-language":"en-US,en;q=0.9","sec-ch-ua":'"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',"sec-ch-ua-mobile":"?0","sec-ch-ua-platform":'"Windows"',"sec-fetch-dest":"empty","sec-fetch-mode":"cors","sec-fetch-site":"same-origin",origin:"https://huggingface.co","Referrer-Policy":"strict-origin-when-cross-origin"},this.models=[],this.currentModelId=null,this.currentConversation=void 0,this.currentConversionID=void 0,this.cookie="",this.colors={primary:"#FED21F",secondary:"#000"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[HuggingFace]"),this.errorPrefix=w.red.bold("[HuggingFace]"),this.cookie=this.params.config.cookie}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>E(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>E(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){await this.initialize();const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:p,maxLength:m}=this.params.config,a={...D,locale:c,maxLength:m,type:p,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},u=e==="review"?H(a):B(a),d=await this.getNewChat(u),g=await(await this.sendMessage(`Here is the diff: ${o}`,d.id)).completeResponsePromise();return await this.deleteConversation(d.id),i&&j("HuggingFace",o,u,g,e),e==="review"?this.sanitizeResponse(g):this.parseMessage(g,p,l)}async initialize(){const e=await this.getRemoteLlms(),o=e.find(r=>r.name?.toLowerCase()===this.params.config.model.toLowerCase());if(o){this.currentModel=o,this.currentModelId=o.id;return}this.currentModel=e[0],this.currentModelId=e[0].id}async getRemoteLlms(){const e=await fetch("https://huggingface.co/chat/__data.json",{headers:{...this.headers,cookie:this.cookie},body:null,method:"GET"});if(e.status!==200)throw new Error(`Failed to get remote LLMs with status code: ${e.status}`);const r=(await e.json()).nodes[0].data,n=r[r[0].models],s=[],i=c=>c===-1?null:r[c];for(const c of n){const l=r[c];if(r[l.unlisted])continue;const p={id:i(l.id),name:i(l.name),displayName:i(l.displayName),preprompt:i(l.preprompt),promptExamples:[],websiteUrl:i(l.websiteUrl),description:i(l.description),datasetName:i(l.datasetName),datasetUrl:i(l.datasetUrl),modelUrl:i(l.modelUrl),parameters:{}},m=i(l.promptExamples);if(m!==null){const d=m.map(h=>i(h));p.promptExamples=d.map(h=>({title:r[h.title],prompt:r[h.prompt]}))}const a=i(l.parameters),u={};for(const[d,h]of Object.entries(a)){if(h===-1){u[d]=null;continue}if(Array.isArray(r[h])){u[d]=r[h].map(g=>r[g]);continue}u[d]=r[h]}p.parameters=u,s.push(p)}return this.models=s,s}async getNewChat(e){const o={model:this.currentModelId,preprompt:e};let r=0;for(;r<5;){const n=await fetch("https://huggingface.co/chat/conversation",{headers:{...this.headers,"content-type":"application/json",cookie:this.cookie,Referer:"https://huggingface.co/chat/"},body:JSON.stringify(o),method:"POST"}),{conversationId:s}=await n.json();if(s){this.currentConversionID=s;break}else r++}if(!this.currentConversionID)throw new Error("Failed to create new conversion");return await this.getConversationHistory(this.currentConversionID)}async getConversationHistory(e){if(!e)throw new Error("conversationId is required for getConversationHistory");const o=await fetch("https://huggingface.co/chat/conversation/"+e+"/__data.json",{headers:{...this.headers,cookie:this.cookie,Referer:"https://huggingface.co/chat/"},body:null,method:"GET"});if(o.status!=200)throw new Error("Unable get conversation details "+o);{const r=await o.json();return this.metadataParser(r,e)}}metadataParser(e,o){const r={id:"",model:"",systemPrompt:"",title:"",history:[]},n=e.nodes[1].data,s=n[n[0].model],i=n[n[0].preprompt],c=n[n[0].title],l=n[n[0].messages],p=[];for(const m of l){const a=n[m],u=new Date(n[a.createdAt][1]).getTime()/1e3,d=new Date(n[a.updatedAt][1]).getTime()/1e3;p.push({id:n[a.id],role:n[a.from],content:n[a.content],createdAt:u,updatedAt:d})}return r.id=o,r.model=s,r.systemPrompt=i,r.title=c,r.history=p,this.currentConversation=r,r}async sendMessage(e,o){if(e==="")throw new Error("the prompt can not be empty.");if(!o&&!this.currentConversionID?await this.getNewChat():o?(this.currentConversionID=o,await this.getConversationHistory(o)):this.currentConversionID&&await this.getConversationHistory(this.currentConversionID),!this.currentConversation)throw new Error("Failed to create new conversion");const r={inputs:e,id:this.currentConversation.history[this.currentConversation.history.length-1].id,is_retry:!1,is_continue:!1,web_search:!1,tools:[]},n=new FormData;n.append("data",JSON.stringify(r));const s=await fetch("https://huggingface.co/chat/conversation/"+this.currentConversionID,{headers:{...this.headers,cookie:this.cookie,Referer:"https://huggingface.co/chat/conversation/"+this.currentConversionID},body:n,method:"POST"});function i(u){try{const d=u.split(`
|
|
71
|
-
`),h=[];for(const g of d)g.trim()&&h.push(JSON.parse(g));return h}catch{return[{}]}}const c=new TextDecoder;let l="";const p=new TransformStream({async transform(u,d){const h=c.decode(u);try{const g=i(h);for(const y of g)y.type==="finalAnswer"?(l=y?.text||"",d.terminate()):y.type==="stream"&&d.enqueue(y?.token||"")}catch{throw new Error("Error during parsing response")}}}),m=s.body?.pipeThrough(p);async function a(){return new Promise(async(u,d)=>{try{if(!m)d("ModifiedStream undefined");else{const h=m.getReader();for(;;){const{done:g,value:y}=await h.read();if(g){u(l);break}}}}catch(h){d(h)}})}return{id:this.currentConversionID,stream:m,completeResponsePromise:a}}async deleteConversation(e){return(await fetch(`https://huggingface.co/chat/conversation/${e}`,{headers:{...this.headers,cookie:this.cookie,Referer:"https://huggingface.co/chat/"},body:null,method:"DELETE"})).json()}}class ao extends G{constructor(e){super(e),this.params=e,this.host="https://api.mistral.ai",this.apiKey="",this.colors={primary:"#ff7000",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[MistralAI]"),this.errorPrefix=w.red.bold("[MistralAI]"),this.apiKey=this.params.config.key}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>E(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>E(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:p,maxLength:m}=this.params.config,a={...D,locale:c,maxLength:m,type:p,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},u=e==="review"?H(a):B(a);await this.checkAvailableModels();const d=await this.createChatCompletions(u,`Here is the diff: ${o}`);return i&&j("MistralAI",o,u,d,e),e==="review"?this.sanitizeResponse(d):this.parseMessage(d,p,l)}async checkAvailableModels(){if((await this.getAvailableModels()).includes(this.params.config.model))return!0;throw new Error(`Invalid model type of Mistral AI: ${this.params.config.model}`)}async getAvailableModels(){return(await new Pe({method:"GET",baseURL:`${this.host}/v1/models`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).execute()).data.data.filter(o=>o.object==="model").map(o=>o.id)}async createChatCompletions(e,o){const n=(await new Pe({method:"POST",baseURL:`${this.host}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody({model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:o}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:qe(10,1e3)}).execute()).data;if(!n.choices||n.choices.length===0||!n.choices[0].message?.content)throw new Error("No Content on response. Please open a Bug report");return n.choices[0].message.content}}class co extends G{constructor(e){super(e),this.params=e,this.host=kt,this.model="",this.key="",this.auth="",this.setupFetch=(o,r={})=>is(o,{...r,dispatcher:new as({headersTimeout:this.params.config.timeout})}),this.colors={primary:"#FFF",secondary:"#000"},this.model=this.params.keyName,this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${Ue(this.model)}]`),this.errorPrefix=w.red.bold(`[${Ue(this.model)}]`),this.host=this.params.config.host||kt,this.auth=this.params.config.auth||"Bearer",this.key=this.params.config.key||"",this.ollama=new ns({host:this.host,fetch:this.setupFetch,...this.key&&{headers:{Authorization:`${this.auth} ${this.key}`}}})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>E(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>E(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:p,maxLength:m}=this.params.config,a={...D,locale:c,maxLength:m,type:p,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},u=e==="review"?H(a):B(a);await this.checkIsAvailableOllama();const d=await this.createChatCompletions(u,`Here is the diff: ${o}`);return i&&j(`Ollama_${this.model}`,o,u,d,e),e==="review"?this.sanitizeResponse(d):this.parseMessage(d,p,l)}async checkIsAvailableOllama(){const e=new Pe({method:"GET",baseURL:`${this.host}`,timeout:this.params.config.timeout});return this.key&&e.setHeaders({Authorization:`${this.auth} ${this.key}`}),(await e.execute()).data}async createChatCompletions(e,o){const{stream:r,numCtx:n,temperature:s,topP:i,timeout:c,maxTokens:l}=this.params.config,p=r||!1,m=await this.ollama.chat({model:this.model,messages:[{role:"system",content:e},{role:"user",content:o}],stream:p,keep_alive:c,options:{num_ctx:n,temperature:s,top_p:i,seed:qe(10,1e3),num_predict:l??-1}});if(p){let a="";if(m)for await(const u of m)a+=u.message.content;return a}return m.message.content}}class lo extends G{constructor(e){super(e),this.params=e;const o=this.params.keyName||"OPENAI_COMPATIBLE";this.colors=zi(o),this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${Ue(o)}]`),this.errorPrefix=w.red.bold(`[${Ue(o)}]`),this.openAI=new ar({apiKey:this.params.config.key,baseURL:`${this.params.config.url}${this.params.config.path}`})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>E(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>E(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,temperature:l,generate:p,type:m,maxLength:a,timeout:u,stream:d=!1}=this.params.config,h=this.params.config.maxTokens,g={...D,locale:c,maxLength:a,type:m,generate:p,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?H(g):B(g),v=await this.openAI.chat.completions.create({messages:[{role:"system",content:y},{role:"user",content:`Here is the diff: ${o}`}],model:this.params.config.model,stream:d,max_tokens:h,top_p:this.params.config.topP,temperature:l},{timeout:u});let $="";if(d&&v){const O=v;for await(const K of O){const W=K.choices?.[0]?.delta?.content||"",fe=K.choices?.[0]?.delta?.reasoning_content||"",V=`${W}${fe}`;$+=V}}else $=v.choices?.[0]?.message.content||"";return i&&j(this.params.keyName,o,y,$,e),e==="review"?this.sanitizeResponse($):this.parseMessage($,m,p)}}var It={},Rt={exports:{}},$e={exports:{}},Ot,mo;function ua(){if(mo)return Ot;mo=1;var t=1e3,e=t*60,o=e*60,r=o*24,n=r*7,s=r*365.25;Ot=function(m,a){a=a||{};var u=typeof m;if(u==="string"&&m.length>0)return i(m);if(u==="number"&&isFinite(m))return a.long?l(m):c(m);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(m))};function i(m){if(m=String(m),!(m.length>100)){var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(m);if(a){var u=parseFloat(a[1]),d=(a[2]||"ms").toLowerCase();switch(d){case"years":case"year":case"yrs":case"yr":case"y":return u*s;case"weeks":case"week":case"w":return u*n;case"days":case"day":case"d":return u*r;case"hours":case"hour":case"hrs":case"hr":case"h":return u*o;case"minutes":case"minute":case"mins":case"min":case"m":return u*e;case"seconds":case"second":case"secs":case"sec":case"s":return u*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return u;default:return}}}}function c(m){var a=Math.abs(m);return a>=r?Math.round(m/r)+"d":a>=o?Math.round(m/o)+"h":a>=e?Math.round(m/e)+"m":a>=t?Math.round(m/t)+"s":m+"ms"}function l(m){var a=Math.abs(m);return a>=r?p(m,a,r,"day"):a>=o?p(m,a,o,"hour"):a>=e?p(m,a,e,"minute"):a>=t?p(m,a,t,"second"):m+" ms"}function p(m,a,u,d){var h=a>=u*1.5;return Math.round(m/u)+" "+d+(h?"s":"")}return Ot}var Lt,uo;function po(){if(uo)return Lt;uo=1;function t(e){r.debug=r,r.default=r,r.coerce=p,r.disable=c,r.enable=s,r.enabled=l,r.humanize=ua(),r.destroy=m,Object.keys(e).forEach(a=>{r[a]=e[a]}),r.names=[],r.skips=[],r.formatters={};function o(a){let u=0;for(let d=0;d<a.length;d++)u=(u<<5)-u+a.charCodeAt(d),u|=0;return r.colors[Math.abs(u)%r.colors.length]}r.selectColor=o;function r(a){let u,d=null,h,g;function y(...v){if(!y.enabled)return;const $=y,O=Number(new Date),K=O-(u||O);$.diff=K,$.prev=u,$.curr=O,u=O,v[0]=r.coerce(v[0]),typeof v[0]!="string"&&v.unshift("%O");let W=0;v[0]=v[0].replace(/%([a-zA-Z%])/g,(V,jo)=>{if(V==="%%")return"%";W++;const Vt=r.formatters[jo];if(typeof Vt=="function"){const Bo=v[W];V=Vt.call($,Bo),v.splice(W,1),W--}return V}),r.formatArgs.call($,v),($.log||r.log).apply($,v)}return y.namespace=a,y.useColors=r.useColors(),y.color=r.selectColor(a),y.extend=n,y.destroy=r.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==r.namespaces&&(h=r.namespaces,g=r.enabled(a)),g),set:v=>{d=v}}),typeof r.init=="function"&&r.init(y),y}function n(a,u){const d=r(this.namespace+(typeof u>"u"?":":u)+a);return d.log=this.log,d}function s(a){r.save(a),r.namespaces=a,r.names=[],r.skips=[];const u=(typeof a=="string"?a:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const d of u)d[0]==="-"?r.skips.push(d.slice(1)):r.names.push(d)}function i(a,u){let d=0,h=0,g=-1,y=0;for(;d<a.length;)if(h<u.length&&(u[h]===a[d]||u[h]==="*"))u[h]==="*"?(g=h,y=d,h++):(d++,h++);else if(g!==-1)h=g+1,y++,d=y;else return!1;for(;h<u.length&&u[h]==="*";)h++;return h===u.length}function c(){const a=[...r.names,...r.skips.map(u=>"-"+u)].join(",");return r.enable(""),a}function l(a){for(const u of r.skips)if(i(a,u))return!1;for(const u of r.names)if(i(a,u))return!0;return!1}function p(a){return a instanceof Error?a.stack||a.message:a}function m(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}return Lt=t,Lt}$e.exports;var fo;function pa(){return fo||(fo=1,function(t,e){e.formatArgs=r,e.save=n,e.load=s,e.useColors=o,e.storage=i(),e.destroy=(()=>{let l=!1;return()=>{l||(l=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function o(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let l;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(l=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(l[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(l){if(l[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+l[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const p="color: "+this.color;l.splice(1,0,p,"color: inherit");let m=0,a=0;l[0].replace(/%[a-zA-Z%]/g,u=>{u!=="%%"&&(m++,u==="%c"&&(a=m))}),l.splice(a,0,p)}e.log=console.debug||console.log||(()=>{});function n(l){try{l?e.storage.setItem("debug",l):e.storage.removeItem("debug")}catch{}}function s(){let l;try{l=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!l&&typeof process<"u"&&"env"in process&&(l=process.env.DEBUG),l}function i(){try{return localStorage}catch{}}t.exports=po()(e);const{formatters:c}=t.exports;c.j=function(l){try{return JSON.stringify(l)}catch(p){return"[UnexpectedJSONParseError]: "+p.message}}}($e,$e.exports)),$e.exports}var Ee={exports:{}},Tt,ho;function fa(){return ho||(ho=1,Tt=(t,e=process.argv)=>{const o=t.startsWith("-")?"":t.length===1?"-":"--",r=e.indexOf(o+t),n=e.indexOf("--");return r!==-1&&(n===-1||r<n)}),Tt}var Nt,go;function da(){if(go)return Nt;go=1;const t=Re,e=cr,o=fa(),{env:r}=process;let n;o("no-color")||o("no-colors")||o("color=false")||o("color=never")?n=0:(o("color")||o("colors")||o("color=true")||o("color=always"))&&(n=1),"FORCE_COLOR"in r&&(r.FORCE_COLOR==="true"?n=1:r.FORCE_COLOR==="false"?n=0:n=r.FORCE_COLOR.length===0?1:Math.min(parseInt(r.FORCE_COLOR,10),3));function s(l){return l===0?!1:{level:l,hasBasic:!0,has256:l>=2,has16m:l>=3}}function i(l,p){if(n===0)return 0;if(o("color=16m")||o("color=full")||o("color=truecolor"))return 3;if(o("color=256"))return 2;if(l&&!p&&n===void 0)return 0;const m=n||0;if(r.TERM==="dumb")return m;if(process.platform==="win32"){const a=t.release().split(".");return Number(a[0])>=10&&Number(a[2])>=10586?Number(a[2])>=14931?3:2:1}if("CI"in r)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(a=>a in r)||r.CI_NAME==="codeship"?1:m;if("TEAMCITY_VERSION"in r)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(r.TEAMCITY_VERSION)?1:0;if(r.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in r){const a=parseInt((r.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(r.TERM_PROGRAM){case"iTerm.app":return a>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(r.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(r.TERM)||"COLORTERM"in r?1:m}function c(l){const p=i(l,l&&l.isTTY);return s(p)}return Nt={supportsColor:c,stdout:s(i(!0,e.isatty(1))),stderr:s(i(!0,e.isatty(2)))},Nt}Ee.exports;var yo;function ha(){return yo||(yo=1,function(t,e){const o=cr,r=tr;e.init=m,e.log=c,e.formatArgs=s,e.save=l,e.load=p,e.useColors=n,e.destroy=r.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{const u=da();u&&(u.stderr||u).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(u=>/^debug_/i.test(u)).reduce((u,d)=>{const h=d.substring(6).toLowerCase().replace(/_([a-z])/g,(y,v)=>v.toUpperCase());let g=process.env[d];return/^(yes|on|true|enabled)$/i.test(g)?g=!0:/^(no|off|false|disabled)$/i.test(g)?g=!1:g==="null"?g=null:g=Number(g),u[h]=g,u},{});function n(){return"colors"in e.inspectOpts?!!e.inspectOpts.colors:o.isatty(process.stderr.fd)}function s(u){const{namespace:d,useColors:h}=this;if(h){const g=this.color,y="\x1B[3"+(g<8?g:"8;5;"+g),v=` ${y};1m${d} \x1B[0m`;u[0]=v+u[0].split(`
|
|
70
|
+
Please structure your response with appropriate Markdown headings, code blocks, and bullet points.`;if(!e)return r;try{const n=F.readFileSync(Ke(e),"utf-8");return`${Jr(n,t)}`}catch{return r}},Zr=async t=>{if(t.systemPromptPath)try{F.readFileSync(Ke(t.systemPromptPath),"utf-8")}catch(e){throw new C(`Error reading system prompt file: ${t.systemPromptPath}, ${e}`)}if(t.codeReview&&t.codeReviewPromptPath)try{F.readFileSync(Ke(t.codeReviewPromptPath),"utf-8")}catch(e){throw new C(`Error reading code review prompt file: ${t.codeReviewPromptPath}, ${e}`)}},la=10*60*1e3;class eo extends j{constructor(e){super(e),this.params=e,this.colors={primary:"#AE5630",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Anthropic]"),this.errorPrefix=w.red.bold("[Anthropic]"),this.anthropic=new Zo({apiKey:this.params.config.key,...this.params.config.timeout>la&&{timeout:this.params.config.timeout}})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),A(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),A(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,temperature:c,locale:l,generate:p,type:m,maxLength:a,maxTokens:u,topP:d,model:h}=this.params.config,g={...G,locale:l,maxLength:a,type:m,generate:p,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?U(g):H(g),v={max_tokens:u,temperature:c,system:y,messages:[{role:"user",content:`Here is the diff: ${o}`}],top_p:d,model:h},L=(await this.anthropic.messages.create(v)).content.map(({text:_})=>_).join("");return i&&B("Anthropic",o,y,L,e),e==="review"?this.sanitizeResponse(L):this.parseMessage(L,m,p)}}class Pe{constructor(e={}){if(!e.method)throw new Error("method should be defined!");if(!e.baseURL)throw new Error("baseURL should be defined!");this.config={...e},this.axiosInstance=ts.create(this.config)}setHeaders(e){return this.config.headers=e,this}setParams(e){return this.config.params=e,this}setBody(e){return this.config.data=e,this}addBody(e){return this.config.data={...this.config.data,...e},this}setMethod(e){return this.config.method=e,this}async execute(){try{return await this.axiosInstance.request(this.config)}catch(e){throw e}}}class to extends j{constructor(e){super(e),this.params=e,this.host="https://codestral.mistral.ai",this.apiKey="",this.colors={primary:"#e28c58",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Codestral]"),this.errorPrefix=w.red.bold("[Codestral]"),this.apiKey=this.params.config.key}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),A(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),A(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:p,maxLength:m}=this.params.config,a={...G,locale:c,maxLength:m,type:p,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},u=e==="review"?U(a):H(a);this.checkAvailableModels();const d=await this.createChatCompletions(u,e);return i&&B("Codestral",o,u,d,e),e==="review"?this.sanitizeResponse(d):this.parseMessage(d,p,l)}checkAvailableModels(){if(["codestral-latest","codestral-2501"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of Codestral AI")}async createChatCompletions(e,o){const r=new Pe({method:"POST",baseURL:`${this.host}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody({model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:`Here is the diff: ${this.params.stagedDiff.diff}`}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:qe(10,1e3)});o==="commit"&&r.addBody({response_format:{type:"json_object"}});const s=(await r.execute()).data;if(!s.choices||s.choices.length===0||!s.choices[0].message?.content)throw new Error("No Content on response. Please open a Bug report");return s.choices[0].message.content}}const ma=2*60*1e3;class ro extends j{constructor(e){super(e),this.params=e,this.colors={primary:"#D18EE2",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Cohere]"),this.errorPrefix=w.red.bold("[Cohere]"),this.cohere=new rs({token:this.params.config.key})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),A(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),A(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,temperature:c,locale:l,generate:p,type:m,maxLength:a,maxTokens:u}=this.params.config,d={...G,locale:l,maxLength:a,type:m,generate:p,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},h=e==="review"?U(d):H(d),g=await this.cohere.chat({chatHistory:h?[{role:"SYSTEM",message:h}]:[],message:`Here is the diff: ${o}`,connectors:[{id:"web-search"}],maxTokens:u,temperature:c,model:this.params.config.model,seed:qe(10,1e3),p:this.params.config.topP},{...this.params.config.timeout>ma&&{timeoutInSeconds:Math.floor(this.params.config.timeout/1e3)}});return i&&B("Cohere",o,h,g.text,e),e==="review"?this.sanitizeResponse(g.text):this.parseMessage(g.text,m,p)}}class oo extends j{constructor(e){super(e),this.params=e,this.host="https://api.deepseek.com",this.colors={primary:"#53a3f9",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[DeepSeek]"),this.errorPrefix=w.red.bold("[DeepSeek]"),this.deepSeek=new ar({baseURL:this.host,apiKey:this.params.config.key})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),A(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),A(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:p,maxLength:m}=this.params.config,a={...G,locale:c,maxLength:m,type:p,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},u=e==="review"?U(a):H(a);this.checkAvailableModels();const d=await this.createChatCompletions(u);return i&&B("DeepSeek",o,u,d,e),e==="review"?this.sanitizeResponse(d):this.parseMessage(d,p,l)}checkAvailableModels(){if(["deepseek-reasoner","deepseek-chat"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of DeepSeek")}async createChatCompletions(e){return(await this.deepSeek.chat.completions.create({messages:[{role:"system",content:e},{role:"user",content:`Here is the diff: ${this.params.stagedDiff.diff}`}],model:this.params.config.model,max_tokens:this.params.config.maxTokens,top_p:this.params.config.topP,temperature:this.params.config.temperature},{timeout:this.params.config.timeout})).choices[0].message.content||""}}class so extends j{constructor(e){super(e),this.params=e,this.colors={primary:"#0077FF",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Gemini]"),this.errorPrefix=w.red.bold("[Gemini]"),this.genAI=new os(this.params.config.key)}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),A(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),A(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,logging:s,locale:i,codeReviewPromptPath:c,generate:l,type:p,maxLength:m}=this.params.config,a=this.params.config.maxTokens,u={...G,locale:i,maxLength:m,type:p,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:c},d=e==="review"?U(u):H(u),h={maxOutputTokens:a,temperature:this.params.config.temperature,topP:this.params.config.topP},P=(await this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:d,generationConfig:h,safetySettings:[{category:Oe.HARM_CATEGORY_HATE_SPEECH,threshold:Le.BLOCK_LOW_AND_ABOVE},{category:Oe.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Le.BLOCK_LOW_AND_ABOVE},{category:Oe.HARM_CATEGORY_HARASSMENT,threshold:Le.BLOCK_LOW_AND_ABOVE},{category:Oe.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Le.BLOCK_LOW_AND_ABOVE}]}).generateContent(`Here is the diff: ${o}`)).response.text();return s&&B("Gemini",o,d,P,e),e==="review"?this.sanitizeResponse(P):this.parseMessage(P,p,l)}}class no extends j{constructor(e){super(e),this.params=e,this.colors={primary:"#f55036",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Groq]"),this.errorPrefix=w.red.bold("[Groq]"),this.groq=new ss({apiKey:this.params.config.key})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),A(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),A(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,temperature:l,generate:p,type:m,maxLength:a}=this.params.config,u=this.params.config.maxTokens,d={...G,locale:c,maxLength:a,type:m,generate:p,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},h=e==="review"?U(d):H(d),y=(await this.groq.chat.completions.create({messages:[{role:"system",content:h},{role:"user",content:`Here is the diff: ${o}`}],model:this.params.config.model,max_tokens:u,top_p:this.params.config.topP,temperature:l},{timeout:this.params.config.timeout})).choices[0].message.content||"";return i&&B("Groq",o,h,y,e),e==="review"?this.sanitizeResponse(y):this.parseMessage(y,m,p)}}class io extends j{constructor(e){super(e),this.params=e,this.headers={accept:"*/*","accept-language":"en-US,en;q=0.9","sec-ch-ua":'"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',"sec-ch-ua-mobile":"?0","sec-ch-ua-platform":'"Windows"',"sec-fetch-dest":"empty","sec-fetch-mode":"cors","sec-fetch-site":"same-origin",origin:"https://huggingface.co","Referrer-Policy":"strict-origin-when-cross-origin"},this.models=[],this.currentModelId=null,this.currentConversation=void 0,this.currentConversionID=void 0,this.cookie="",this.colors={primary:"#FED21F",secondary:"#000"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[HuggingFace]"),this.errorPrefix=w.red.bold("[HuggingFace]"),this.cookie=this.params.config.cookie}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),A(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),A(this.handleError$))}async generateMessage(e){await this.initialize();const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:p,maxLength:m}=this.params.config,a={...G,locale:c,maxLength:m,type:p,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},u=e==="review"?U(a):H(a),d=await this.getNewChat(u),g=await(await this.sendMessage(`Here is the diff: ${o}`,d.id)).completeResponsePromise();return await this.deleteConversation(d.id),i&&B("HuggingFace",o,u,g,e),e==="review"?this.sanitizeResponse(g):this.parseMessage(g,p,l)}async initialize(){const e=await this.getRemoteLlms(),o=e.find(r=>r.name?.toLowerCase()===this.params.config.model.toLowerCase());if(o){this.currentModel=o,this.currentModelId=o.id;return}this.currentModel=e[0],this.currentModelId=e[0].id}async getRemoteLlms(){const e=await fetch("https://huggingface.co/chat/__data.json",{headers:{...this.headers,cookie:this.cookie},body:null,method:"GET"});if(e.status!==200)throw new Error(`Failed to get remote LLMs with status code: ${e.status}`);const r=(await e.json()).nodes[0].data,n=r[r[0].models],s=[],i=c=>c===-1?null:r[c];for(const c of n){const l=r[c];if(r[l.unlisted])continue;const p={id:i(l.id),name:i(l.name),displayName:i(l.displayName),preprompt:i(l.preprompt),promptExamples:[],websiteUrl:i(l.websiteUrl),description:i(l.description),datasetName:i(l.datasetName),datasetUrl:i(l.datasetUrl),modelUrl:i(l.modelUrl),parameters:{}},m=i(l.promptExamples);if(m!==null){const d=m.map(h=>i(h));p.promptExamples=d.map(h=>({title:r[h.title],prompt:r[h.prompt]}))}const a=i(l.parameters),u={};for(const[d,h]of Object.entries(a)){if(h===-1){u[d]=null;continue}if(Array.isArray(r[h])){u[d]=r[h].map(g=>r[g]);continue}u[d]=r[h]}p.parameters=u,s.push(p)}return this.models=s,s}async getNewChat(e){const o={model:this.currentModelId,preprompt:e};let r=0;for(;r<5;){const n=await fetch("https://huggingface.co/chat/conversation",{headers:{...this.headers,"content-type":"application/json",cookie:this.cookie,Referer:"https://huggingface.co/chat/"},body:JSON.stringify(o),method:"POST"}),{conversationId:s}=await n.json();if(s){this.currentConversionID=s;break}else r++}if(!this.currentConversionID)throw new Error("Failed to create new conversion");return await this.getConversationHistory(this.currentConversionID)}async getConversationHistory(e){if(!e)throw new Error("conversationId is required for getConversationHistory");const o=await fetch("https://huggingface.co/chat/conversation/"+e+"/__data.json",{headers:{...this.headers,cookie:this.cookie,Referer:"https://huggingface.co/chat/"},body:null,method:"GET"});if(o.status!=200)throw new Error("Unable get conversation details "+o);{const r=await o.json();return this.metadataParser(r,e)}}metadataParser(e,o){const r={id:"",model:"",systemPrompt:"",title:"",history:[]},n=e.nodes[1].data,s=n[n[0].model],i=n[n[0].preprompt],c=n[n[0].title],l=n[n[0].messages],p=[];for(const m of l){const a=n[m],u=new Date(n[a.createdAt][1]).getTime()/1e3,d=new Date(n[a.updatedAt][1]).getTime()/1e3;p.push({id:n[a.id],role:n[a.from],content:n[a.content],createdAt:u,updatedAt:d})}return r.id=o,r.model=s,r.systemPrompt=i,r.title=c,r.history=p,this.currentConversation=r,r}async sendMessage(e,o){if(e==="")throw new Error("the prompt can not be empty.");if(!o&&!this.currentConversionID?await this.getNewChat():o?(this.currentConversionID=o,await this.getConversationHistory(o)):this.currentConversionID&&await this.getConversationHistory(this.currentConversionID),!this.currentConversation)throw new Error("Failed to create new conversion");const r={inputs:e,id:this.currentConversation.history[this.currentConversation.history.length-1].id,is_retry:!1,is_continue:!1,web_search:!1,tools:[]},n=new FormData;n.append("data",JSON.stringify(r));const s=await fetch("https://huggingface.co/chat/conversation/"+this.currentConversionID,{headers:{...this.headers,cookie:this.cookie,Referer:"https://huggingface.co/chat/conversation/"+this.currentConversionID},body:n,method:"POST"});function i(u){try{const d=u.split(`
|
|
71
|
+
`),h=[];for(const g of d)g.trim()&&h.push(JSON.parse(g));return h}catch{return[{}]}}const c=new TextDecoder;let l="";const p=new TransformStream({async transform(u,d){const h=c.decode(u);try{const g=i(h);for(const y of g)y.type==="finalAnswer"?(l=y?.text||"",d.terminate()):y.type==="stream"&&d.enqueue(y?.token||"")}catch{throw new Error("Error during parsing response")}}}),m=s.body?.pipeThrough(p);async function a(){return new Promise(async(u,d)=>{try{if(!m)d("ModifiedStream undefined");else{const h=m.getReader();for(;;){const{done:g,value:y}=await h.read();if(g){u(l);break}}}}catch(h){d(h)}})}return{id:this.currentConversionID,stream:m,completeResponsePromise:a}}async deleteConversation(e){return(await fetch(`https://huggingface.co/chat/conversation/${e}`,{headers:{...this.headers,cookie:this.cookie,Referer:"https://huggingface.co/chat/"},body:null,method:"DELETE"})).json()}}class ao extends j{constructor(e){super(e),this.params=e,this.host="https://api.mistral.ai",this.apiKey="",this.colors={primary:"#ff7000",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[MistralAI]"),this.errorPrefix=w.red.bold("[MistralAI]"),this.apiKey=this.params.config.key}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),A(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),A(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:p,maxLength:m}=this.params.config,a={...G,locale:c,maxLength:m,type:p,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},u=e==="review"?U(a):H(a);await this.checkAvailableModels();const d=await this.createChatCompletions(u,`Here is the diff: ${o}`);return i&&B("MistralAI",o,u,d,e),e==="review"?this.sanitizeResponse(d):this.parseMessage(d,p,l)}async checkAvailableModels(){if((await this.getAvailableModels()).includes(this.params.config.model))return!0;throw new Error(`Invalid model type of Mistral AI: ${this.params.config.model}`)}async getAvailableModels(){return(await new Pe({method:"GET",baseURL:`${this.host}/v1/models`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).execute()).data.data.filter(o=>o.object==="model").map(o=>o.id)}async createChatCompletions(e,o){const n=(await new Pe({method:"POST",baseURL:`${this.host}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody({model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:o}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:qe(10,1e3)}).execute()).data;if(!n.choices||n.choices.length===0||!n.choices[0].message?.content)throw new Error("No Content on response. Please open a Bug report");return n.choices[0].message.content}}class co extends j{constructor(e){super(e),this.params=e,this.host=kt,this.model="",this.key="",this.auth="",this.setupFetch=(o,r={})=>is(o,{...r,dispatcher:new as({headersTimeout:this.params.config.timeout})}),this.colors={primary:"#FFF",secondary:"#000"},this.model=this.params.keyName,this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${Ue(this.model)}]`),this.errorPrefix=w.red.bold(`[${Ue(this.model)}]`),this.host=this.params.config.host||kt,this.auth=this.params.config.auth||"Bearer",this.key=this.params.config.key||"",this.ollama=new ns({host:this.host,fetch:this.setupFetch,...this.key&&{headers:{Authorization:`${this.auth} ${this.key}`}}})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),A(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),A(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:p,maxLength:m}=this.params.config,a={...G,locale:c,maxLength:m,type:p,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},u=e==="review"?U(a):H(a);await this.checkIsAvailableOllama();const d=await this.createChatCompletions(u,`Here is the diff: ${o}`);return i&&B(`Ollama_${this.model}`,o,u,d,e),e==="review"?this.sanitizeResponse(d):this.parseMessage(d,p,l)}async checkIsAvailableOllama(){const e=new Pe({method:"GET",baseURL:`${this.host}`,timeout:this.params.config.timeout});return this.key&&e.setHeaders({Authorization:`${this.auth} ${this.key}`}),(await e.execute()).data}async createChatCompletions(e,o){const{stream:r,numCtx:n,temperature:s,topP:i,timeout:c,maxTokens:l}=this.params.config,p=r||!1,m=await this.ollama.chat({model:this.model,messages:[{role:"system",content:e},{role:"user",content:o}],stream:p,keep_alive:c,options:{num_ctx:n,temperature:s,top_p:i,seed:qe(10,1e3),num_predict:l??-1}});if(p){let a="";if(m)for await(const u of m)a+=u.message.content;return a}return m.message.content}}class lo extends j{constructor(e){super(e),this.params=e;const o=this.params.keyName||"OPENAI_COMPATIBLE";this.colors=zi(o),this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${Ue(o)}]`),this.errorPrefix=w.red.bold(`[${Ue(o)}]`),this.openAI=new ar({apiKey:this.params.config.key,baseURL:`${this.params.config.url}${this.params.config.path}`})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),A(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),A(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,temperature:l,generate:p,type:m,maxLength:a,timeout:u,stream:d=!1}=this.params.config,h=this.params.config.maxTokens,g={...G,locale:c,maxLength:a,type:m,generate:p,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?U(g):H(g),v=await this.openAI.chat.completions.create({messages:[{role:"system",content:y},{role:"user",content:`Here is the diff: ${o}`}],model:this.params.config.model,stream:d,max_tokens:h,top_p:this.params.config.topP,temperature:l},{timeout:u});let P="";if(d&&v){const L=v;for await(const _ of L){const W=_.choices?.[0]?.delta?.content||"",fe=_.choices?.[0]?.delta?.reasoning_content||"",V=`${W}${fe}`;P+=V}}else P=v.choices?.[0]?.message.content||"";return i&&B(this.params.keyName,o,y,P,e),e==="review"?this.sanitizeResponse(P):this.parseMessage(P,m,p)}}var It={},Rt={exports:{}},$e={exports:{}},Ot,mo;function ua(){if(mo)return Ot;mo=1;var t=1e3,e=t*60,o=e*60,r=o*24,n=r*7,s=r*365.25;Ot=function(m,a){a=a||{};var u=typeof m;if(u==="string"&&m.length>0)return i(m);if(u==="number"&&isFinite(m))return a.long?l(m):c(m);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(m))};function i(m){if(m=String(m),!(m.length>100)){var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(m);if(a){var u=parseFloat(a[1]),d=(a[2]||"ms").toLowerCase();switch(d){case"years":case"year":case"yrs":case"yr":case"y":return u*s;case"weeks":case"week":case"w":return u*n;case"days":case"day":case"d":return u*r;case"hours":case"hour":case"hrs":case"hr":case"h":return u*o;case"minutes":case"minute":case"mins":case"min":case"m":return u*e;case"seconds":case"second":case"secs":case"sec":case"s":return u*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return u;default:return}}}}function c(m){var a=Math.abs(m);return a>=r?Math.round(m/r)+"d":a>=o?Math.round(m/o)+"h":a>=e?Math.round(m/e)+"m":a>=t?Math.round(m/t)+"s":m+"ms"}function l(m){var a=Math.abs(m);return a>=r?p(m,a,r,"day"):a>=o?p(m,a,o,"hour"):a>=e?p(m,a,e,"minute"):a>=t?p(m,a,t,"second"):m+" ms"}function p(m,a,u,d){var h=a>=u*1.5;return Math.round(m/u)+" "+d+(h?"s":"")}return Ot}var Lt,uo;function po(){if(uo)return Lt;uo=1;function t(e){r.debug=r,r.default=r,r.coerce=p,r.disable=c,r.enable=s,r.enabled=l,r.humanize=ua(),r.destroy=m,Object.keys(e).forEach(a=>{r[a]=e[a]}),r.names=[],r.skips=[],r.formatters={};function o(a){let u=0;for(let d=0;d<a.length;d++)u=(u<<5)-u+a.charCodeAt(d),u|=0;return r.colors[Math.abs(u)%r.colors.length]}r.selectColor=o;function r(a){let u,d=null,h,g;function y(...v){if(!y.enabled)return;const P=y,L=Number(new Date),_=L-(u||L);P.diff=_,P.prev=u,P.curr=L,u=L,v[0]=r.coerce(v[0]),typeof v[0]!="string"&&v.unshift("%O");let W=0;v[0]=v[0].replace(/%([a-zA-Z%])/g,(V,jo)=>{if(V==="%%")return"%";W++;const Vt=r.formatters[jo];if(typeof Vt=="function"){const Bo=v[W];V=Vt.call(P,Bo),v.splice(W,1),W--}return V}),r.formatArgs.call(P,v),(P.log||r.log).apply(P,v)}return y.namespace=a,y.useColors=r.useColors(),y.color=r.selectColor(a),y.extend=n,y.destroy=r.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==r.namespaces&&(h=r.namespaces,g=r.enabled(a)),g),set:v=>{d=v}}),typeof r.init=="function"&&r.init(y),y}function n(a,u){const d=r(this.namespace+(typeof u>"u"?":":u)+a);return d.log=this.log,d}function s(a){r.save(a),r.namespaces=a,r.names=[],r.skips=[];const u=(typeof a=="string"?a:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const d of u)d[0]==="-"?r.skips.push(d.slice(1)):r.names.push(d)}function i(a,u){let d=0,h=0,g=-1,y=0;for(;d<a.length;)if(h<u.length&&(u[h]===a[d]||u[h]==="*"))u[h]==="*"?(g=h,y=d,h++):(d++,h++);else if(g!==-1)h=g+1,y++,d=y;else return!1;for(;h<u.length&&u[h]==="*";)h++;return h===u.length}function c(){const a=[...r.names,...r.skips.map(u=>"-"+u)].join(",");return r.enable(""),a}function l(a){for(const u of r.skips)if(i(a,u))return!1;for(const u of r.names)if(i(a,u))return!0;return!1}function p(a){return a instanceof Error?a.stack||a.message:a}function m(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}return Lt=t,Lt}$e.exports;var fo;function pa(){return fo||(fo=1,function(t,e){e.formatArgs=r,e.save=n,e.load=s,e.useColors=o,e.storage=i(),e.destroy=(()=>{let l=!1;return()=>{l||(l=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function o(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let l;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(l=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(l[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(l){if(l[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+l[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const p="color: "+this.color;l.splice(1,0,p,"color: inherit");let m=0,a=0;l[0].replace(/%[a-zA-Z%]/g,u=>{u!=="%%"&&(m++,u==="%c"&&(a=m))}),l.splice(a,0,p)}e.log=console.debug||console.log||(()=>{});function n(l){try{l?e.storage.setItem("debug",l):e.storage.removeItem("debug")}catch{}}function s(){let l;try{l=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!l&&typeof process<"u"&&"env"in process&&(l=process.env.DEBUG),l}function i(){try{return localStorage}catch{}}t.exports=po()(e);const{formatters:c}=t.exports;c.j=function(l){try{return JSON.stringify(l)}catch(p){return"[UnexpectedJSONParseError]: "+p.message}}}($e,$e.exports)),$e.exports}var Ee={exports:{}},Tt,ho;function fa(){return ho||(ho=1,Tt=(t,e=process.argv)=>{const o=t.startsWith("-")?"":t.length===1?"-":"--",r=e.indexOf(o+t),n=e.indexOf("--");return r!==-1&&(n===-1||r<n)}),Tt}var Nt,go;function da(){if(go)return Nt;go=1;const t=Re,e=cr,o=fa(),{env:r}=process;let n;o("no-color")||o("no-colors")||o("color=false")||o("color=never")?n=0:(o("color")||o("colors")||o("color=true")||o("color=always"))&&(n=1),"FORCE_COLOR"in r&&(r.FORCE_COLOR==="true"?n=1:r.FORCE_COLOR==="false"?n=0:n=r.FORCE_COLOR.length===0?1:Math.min(parseInt(r.FORCE_COLOR,10),3));function s(l){return l===0?!1:{level:l,hasBasic:!0,has256:l>=2,has16m:l>=3}}function i(l,p){if(n===0)return 0;if(o("color=16m")||o("color=full")||o("color=truecolor"))return 3;if(o("color=256"))return 2;if(l&&!p&&n===void 0)return 0;const m=n||0;if(r.TERM==="dumb")return m;if(process.platform==="win32"){const a=t.release().split(".");return Number(a[0])>=10&&Number(a[2])>=10586?Number(a[2])>=14931?3:2:1}if("CI"in r)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(a=>a in r)||r.CI_NAME==="codeship"?1:m;if("TEAMCITY_VERSION"in r)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(r.TEAMCITY_VERSION)?1:0;if(r.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in r){const a=parseInt((r.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(r.TERM_PROGRAM){case"iTerm.app":return a>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(r.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(r.TERM)||"COLORTERM"in r?1:m}function c(l){const p=i(l,l&&l.isTTY);return s(p)}return Nt={supportsColor:c,stdout:s(i(!0,e.isatty(1))),stderr:s(i(!0,e.isatty(2)))},Nt}Ee.exports;var yo;function ha(){return yo||(yo=1,function(t,e){const o=cr,r=tr;e.init=m,e.log=c,e.formatArgs=s,e.save=l,e.load=p,e.useColors=n,e.destroy=r.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{const u=da();u&&(u.stderr||u).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(u=>/^debug_/i.test(u)).reduce((u,d)=>{const h=d.substring(6).toLowerCase().replace(/_([a-z])/g,(y,v)=>v.toUpperCase());let g=process.env[d];return/^(yes|on|true|enabled)$/i.test(g)?g=!0:/^(no|off|false|disabled)$/i.test(g)?g=!1:g==="null"?g=null:g=Number(g),u[h]=g,u},{});function n(){return"colors"in e.inspectOpts?!!e.inspectOpts.colors:o.isatty(process.stderr.fd)}function s(u){const{namespace:d,useColors:h}=this;if(h){const g=this.color,y="\x1B[3"+(g<8?g:"8;5;"+g),v=` ${y};1m${d} \x1B[0m`;u[0]=v+u[0].split(`
|
|
72
72
|
`).join(`
|
|
73
73
|
`+v),u.push(y+"m+"+t.exports.humanize(this.diff)+"\x1B[0m")}else u[0]=i()+d+" "+u[0]}function i(){return e.inspectOpts.hideDate?"":new Date().toISOString()+" "}function c(...u){return process.stderr.write(r.formatWithOptions(e.inspectOpts,...u)+`
|
|
74
74
|
`)}function l(u){u?process.env.DEBUG=u:delete process.env.DEBUG}function p(){return process.env.DEBUG}function m(u){u.inspectOpts={};const d=Object.keys(e.inspectOpts);for(let h=0;h<d.length;h++)u.inspectOpts[d[h]]=e.inspectOpts[d[h]]}t.exports=po()(e);const{formatters:a}=t.exports;a.o=function(u){return this.inspectOpts.colors=this.useColors,r.inspect(u,this.inspectOpts).split(`
|
|
75
|
-
`).map(d=>d.trim()).join(" ")},a.O=function(u){return this.inspectOpts.colors=this.useColors,r.inspect(u,this.inspectOpts)}}(Ee,Ee.exports)),Ee.exports}typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Rt.exports=pa():Rt.exports=ha();var _t=Rt.exports,Ft={};Object.defineProperty(Ft,"__esModule",{value:!0});function ga(t){return function(e,o){return new Promise((r,n)=>{t.call(this,e,o,(s,i)=>{s?n(s):r(i)})})}}Ft.default=ga;var wo=
|
|
76
|
-
`).some(e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1)}function Je(t,e){return new Je.Agent(t,e)}(function(t){class e extends ya.EventEmitter{constructor(r,n){super();let s=n;typeof r=="function"?this.callback=r:r&&(s=r),this.timeout=null,s&&typeof s.timeout=="number"&&(this.timeout=s.timeout),this.maxFreeSockets=1,this.maxSockets=1,this.maxTotalSockets=1/0,this.sockets={},this.freeSockets={},this.requests={},this.options={}}get defaultPort(){return typeof this.explicitDefaultPort=="number"?this.explicitDefaultPort:Dt()?443:80}set defaultPort(r){this.explicitDefaultPort=r}get protocol(){return typeof this.explicitProtocol=="string"?this.explicitProtocol:Dt()?"https:":"http:"}set protocol(r){this.explicitProtocol=r}callback(r,n,s){throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`')}addRequest(r,n){const s=Object.assign({},n);typeof s.secureEndpoint!="boolean"&&(s.secureEndpoint=Dt()),s.host==null&&(s.host="localhost"),s.port==null&&(s.port=s.secureEndpoint?443:80),s.protocol==null&&(s.protocol=s.secureEndpoint?"https:":"http:"),s.host&&s.path&&delete s.path,delete s.agent,delete s.hostname,delete s._defaultAgent,delete s.defaultPort,delete s.createConnection,r._last=!0,r.shouldKeepAlive=!1;let i=!1,c=null;const l=s.timeout||this.timeout,p=d=>{r._hadError||(r.emit("error",d),r._hadError=!0)},m=()=>{c=null,i=!0;const d=new Error(`A "socket" was not created for HTTP request before ${l}ms`);d.code="ETIMEOUT",p(d)},a=d=>{i||(c!==null&&(clearTimeout(c),c=null),p(d))},u=d=>{if(i)return;if(c!=null&&(clearTimeout(c),c=null),ba(d)){xe("Callback returned another Agent instance %o",d.constructor.name),d.addRequest(r,s);return}if(d){d.once("free",()=>{this.freeSocket(d,s)}),r.onSocket(d);return}const h=new Error(`no Duplex stream was returned to agent-base for \`${r.method} ${r.path}\``);p(h)};if(typeof this.callback!="function"){p(new Error("`callback` is not defined"));return}this.promisifiedCallback||(this.callback.length>=3?(xe("Converting legacy callback function to promise"),this.promisifiedCallback=va.default(this.callback)):this.promisifiedCallback=this.callback),typeof l=="number"&&l>0&&(c=setTimeout(m,l)),"port"in s&&typeof s.port!="number"&&(s.port=Number(s.port));try{xe("Resolving socket for %o request: %o",s.protocol,`${r.method} ${r.path}`),Promise.resolve(this.promisifiedCallback(r,s)).then(u,a)}catch(d){Promise.reject(d).catch(a)}}freeSocket(r,n){xe("Freeing socket %o %o",r.constructor.name,n),r.destroy()}destroy(){xe("Destroying agent %o",this.constructor.name)}}t.Agent=e,t.prototype=t.Agent.prototype})(Je||(Je={}));var Ca=Je,Gt={},Pa=
|
|
75
|
+
`).map(d=>d.trim()).join(" ")},a.O=function(u){return this.inspectOpts.colors=this.useColors,r.inspect(u,this.inspectOpts)}}(Ee,Ee.exports)),Ee.exports}typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Rt.exports=pa():Rt.exports=ha();var _t=Rt.exports,Ft={};Object.defineProperty(Ft,"__esModule",{value:!0});function ga(t){return function(e,o){return new Promise((r,n)=>{t.call(this,e,o,(s,i)=>{s?n(s):r(i)})})}}Ft.default=ga;var wo=O&&O.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const ya=er,wa=wo(_t),va=wo(Ft),xe=wa.default("agent-base");function ba(t){return!!t&&typeof t.addRequest=="function"}function Dt(){const{stack:t}=new Error;return typeof t!="string"?!1:t.split(`
|
|
76
|
+
`).some(e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1)}function Je(t,e){return new Je.Agent(t,e)}(function(t){class e extends ya.EventEmitter{constructor(r,n){super();let s=n;typeof r=="function"?this.callback=r:r&&(s=r),this.timeout=null,s&&typeof s.timeout=="number"&&(this.timeout=s.timeout),this.maxFreeSockets=1,this.maxSockets=1,this.maxTotalSockets=1/0,this.sockets={},this.freeSockets={},this.requests={},this.options={}}get defaultPort(){return typeof this.explicitDefaultPort=="number"?this.explicitDefaultPort:Dt()?443:80}set defaultPort(r){this.explicitDefaultPort=r}get protocol(){return typeof this.explicitProtocol=="string"?this.explicitProtocol:Dt()?"https:":"http:"}set protocol(r){this.explicitProtocol=r}callback(r,n,s){throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`')}addRequest(r,n){const s=Object.assign({},n);typeof s.secureEndpoint!="boolean"&&(s.secureEndpoint=Dt()),s.host==null&&(s.host="localhost"),s.port==null&&(s.port=s.secureEndpoint?443:80),s.protocol==null&&(s.protocol=s.secureEndpoint?"https:":"http:"),s.host&&s.path&&delete s.path,delete s.agent,delete s.hostname,delete s._defaultAgent,delete s.defaultPort,delete s.createConnection,r._last=!0,r.shouldKeepAlive=!1;let i=!1,c=null;const l=s.timeout||this.timeout,p=d=>{r._hadError||(r.emit("error",d),r._hadError=!0)},m=()=>{c=null,i=!0;const d=new Error(`A "socket" was not created for HTTP request before ${l}ms`);d.code="ETIMEOUT",p(d)},a=d=>{i||(c!==null&&(clearTimeout(c),c=null),p(d))},u=d=>{if(i)return;if(c!=null&&(clearTimeout(c),c=null),ba(d)){xe("Callback returned another Agent instance %o",d.constructor.name),d.addRequest(r,s);return}if(d){d.once("free",()=>{this.freeSocket(d,s)}),r.onSocket(d);return}const h=new Error(`no Duplex stream was returned to agent-base for \`${r.method} ${r.path}\``);p(h)};if(typeof this.callback!="function"){p(new Error("`callback` is not defined"));return}this.promisifiedCallback||(this.callback.length>=3?(xe("Converting legacy callback function to promise"),this.promisifiedCallback=va.default(this.callback)):this.promisifiedCallback=this.callback),typeof l=="number"&&l>0&&(c=setTimeout(m,l)),"port"in s&&typeof s.port!="number"&&(s.port=Number(s.port));try{xe("Resolving socket for %o request: %o",s.protocol,`${r.method} ${r.path}`),Promise.resolve(this.promisifiedCallback(r,s)).then(u,a)}catch(d){Promise.reject(d).catch(a)}}freeSocket(r,n){xe("Freeing socket %o %o",r.constructor.name,n),r.destroy()}destroy(){xe("Destroying agent %o",this.constructor.name)}}t.Agent=e,t.prototype=t.Agent.prototype})(Je||(Je={}));var Ca=Je,Gt={},Pa=O&&O.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Gt,"__esModule",{value:!0});const $a=Pa(_t),Se=$a.default("https-proxy-agent:parse-proxy-response");function Ea(t){return new Promise((e,o)=>{let r=0;const n=[];function s(){const a=t.read();a?m(a):t.once("readable",s)}function i(){t.removeListener("end",l),t.removeListener("error",p),t.removeListener("close",c),t.removeListener("readable",s)}function c(a){Se("onclose had error %o",a)}function l(){Se("onend")}function p(a){i(),Se("onerror %o",a),o(a)}function m(a){n.push(a),r+=a.length;const u=Buffer.concat(n,r);if(u.indexOf(`\r
|
|
77
77
|
\r
|
|
78
|
-
`)===-1){
|
|
79
|
-
`)),g=+h.split(" ")[1];
|
|
78
|
+
`)===-1){Se("have not received end of HTTP headers yet..."),s();return}const h=u.toString("ascii",0,u.indexOf(`\r
|
|
79
|
+
`)),g=+h.split(" ")[1];Se("got proxy server response: %o",h),e({statusCode:g,buffered:u})}t.on("error",p),t.on("close",c),t.on("end",l),s()})}Gt.default=Ea;var xa=O&&O.__awaiter||function(t,e,o,r){function n(s){return s instanceof o?s:new o(function(i){i(s)})}return new(o||(o=Promise))(function(s,i){function c(m){try{p(r.next(m))}catch(a){i(a)}}function l(m){try{p(r.throw(m))}catch(a){i(a)}}function p(m){m.done?s(m.value):n(m.value).then(c,l)}p((r=r.apply(t,e||[])).next())})},pe=O&&O.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(It,"__esModule",{value:!0});const vo=pe(ms),bo=pe(us),Sa=pe(ps),Aa=pe(Zt),ka=pe(_t),Ma=Ca,Ia=pe(Gt),Ae=ka.default("https-proxy-agent:agent");class Ra extends Ma.Agent{constructor(e){let o;if(typeof e=="string"?o=Sa.default.parse(e):o=e,!o)throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");Ae("creating new HttpsProxyAgent instance: %o",o),super(o);const r=Object.assign({},o);this.secureProxy=o.secureProxy||Ta(r.protocol),r.host=r.hostname||r.host,typeof r.port=="string"&&(r.port=parseInt(r.port,10)),!r.port&&r.host&&(r.port=this.secureProxy?443:80),this.secureProxy&&!("ALPNProtocols"in r)&&(r.ALPNProtocols=["http 1.1"]),r.host&&r.path&&(delete r.path,delete r.pathname),this.proxy=r}callback(e,o){return xa(this,void 0,void 0,function*(){const{proxy:r,secureProxy:n}=this;let s;n?(Ae("Creating `tls.Socket`: %o",r),s=bo.default.connect(r)):(Ae("Creating `net.Socket`: %o",r),s=vo.default.connect(r));const i=Object.assign({},r.headers);let l=`CONNECT ${`${o.host}:${o.port}`} HTTP/1.1\r
|
|
80
80
|
`;r.auth&&(i["Proxy-Authorization"]=`Basic ${Buffer.from(r.auth).toString("base64")}`);let{host:p,port:m,secureEndpoint:a}=o;La(m,a)||(p+=`:${m}`),i.Host=p,i.Connection="close";for(const y of Object.keys(i))l+=`${y}: ${i[y]}\r
|
|
81
81
|
`;const u=Ia.default(s);s.write(`${l}\r
|
|
82
|
-
`);const{statusCode:d,buffered:h}=yield u;if(d===200){if(e.once("socket",Oa),o.secureEndpoint){
|
|
82
|
+
`);const{statusCode:d,buffered:h}=yield u;if(d===200){if(e.once("socket",Oa),o.secureEndpoint){Ae("Upgrading socket connection to TLS");const y=o.servername||o.host;return bo.default.connect(Object.assign(Object.assign({},Na(o,"host","hostname","path","port")),{socket:s,servername:y}))}return s}s.destroy();const g=new vo.default.Socket({writable:!1});return g.readable=!0,e.once("socket",y=>{Ae("replaying proxy buffer for failed request"),Aa.default(y.listenerCount("data")>0),y.push(h),y.push(null)}),g})}}It.default=Ra;function Oa(t){t.resume()}function La(t,e){return!!(!e&&t===80||e&&t===443)}function Ta(t){return typeof t=="string"?/^https:?$/i.test(t):!1}function Na(t,...e){const o={};let r;for(r in t)e.includes(r)||(o[r]=t[r]);return o}var _a=O&&O.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const jt=_a(It);function Bt(t){return new jt.default(t)}(function(t){t.HttpsProxyAgent=jt.default,t.prototype=jt.default.prototype})(Bt||(Bt={}));var Fa=Bt,Da=re(Fa);const Ga=async(t,e,o,r,n,s,i)=>new Promise((c,l)=>{const p=JSON.stringify(r),a=(t.protocol.includes("https")?ls:cs).request({port:i||void 0,hostname:t.hostname,path:e,method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(p),...o},timeout:n,agent:s?Da(s):void 0},u=>{const d=[];u.on("data",h=>d.push(h)),u.on("end",()=>{c({request:a,response:u,data:Buffer.concat(d).toString()})})});a.on("error",l),a.on("timeout",()=>{a.destroy(),l(new C(`Time out error: request took over ${n}ms. Try increasing the \`timeout\` config`))}),a.write(p),a.end()}),ja=async(t,e,o,r,n,s)=>{const i=new URL(t),{response:c,data:l}=await Ga(i,e,{Authorization:`Bearer ${o}`},r,n,s);if(!c.statusCode||c.statusCode<200||c.statusCode>299){let p=`API Error: ${c.statusCode} - ${c.statusMessage}`;throw l&&(p+=`
|
|
83
83
|
|
|
84
84
|
${l}`),c.statusCode===500&&(p+=`
|
|
85
85
|
|
|
86
|
-
Check the API status: ${t}`),new C(p)}return JSON.parse(l)},Co=t=>t.trim(),Ba=async(t,e,o,r,n,s,i,c,l,p,m,a,u,d)=>{try{const h={model:n,messages:[{role:"system",content:m},{role:"user",content:`Here is the diff: ${s}`}],temperature:l,max_tokens:c,stream:!1,n:1,top_p:p,frequency_penalty:0,presence_penalty:0},g=await ja(e,o,r,h,i,d),y=g.choices.filter(v=>v.message?.content).map(v=>Co(v.message.content)).join();return a&&
|
|
86
|
+
Check the API status: ${t}`),new C(p)}return JSON.parse(l)},Co=t=>t.trim(),Ba=async(t,e,o,r,n,s,i,c,l,p,m,a,u,d)=>{try{const h={model:n,messages:[{role:"system",content:m},{role:"user",content:`Here is the diff: ${s}`}],temperature:l,max_tokens:c,stream:!1,n:1,top_p:p,frequency_penalty:0,presence_penalty:0},g=await ja(e,o,r,h,i,d),y=g.choices.filter(v=>v.message?.content).map(v=>Co(v.message.content)).join();return a&&B(t,s,m,y,u),g.choices.filter(v=>v.message?.content).map(v=>Co(v.message.content))}catch(h){const g=h;throw g.code==="ENOTFOUND"?new C(`Error connecting to ${g.hostname} (${g.syscall})`):g}};class Po extends j{constructor(e){super(e),this.params=e,this.colors={primary:"#74AA9C",secondary:"#FFF"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[ChatGPT]"),this.errorPrefix=w.red.bold("[ChatGPT]")}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),A(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),A(this.handleError$))}extractJSONFromError(e){const o=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,r=e.match(o);return r?Object.assign({},...r.map(n=>JSON.parse(n))):{error:{message:"Unknown error"}}}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,temperature:i,logging:c,locale:l,generate:p,type:m,maxLength:a,proxy:u,maxTokens:d,timeout:h}=this.params.config,g={...G,locale:l,maxLength:a,type:m,generate:p,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?U(g):H(g),v=await Ba("ChatGPT",this.params.config.url,this.params.config.path,this.params.config.key,this.params.config.model,o,h,d,i,this.params.config.topP,y,c,e,u);return ze(e==="review"?v.map(P=>this.sanitizeResponse(P)):v.map(P=>this.parseMessage(P,m,p)))}}class $o extends j{constructor(e){super(e),this.params=e,this.host="https://api.perplexity.ai",this.apiKey="",this.colors={primary:"#20808D",secondary:"#FFF"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Perplexity]"),this.errorPrefix=w.red.bold("[Perplexity]"),this.apiKey=this.params.config.key}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),A(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>E(e)),S(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),A(this.handleError$))}extractJSONFromError(e){const o=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,r=e.match(o);return r?Object.assign({},...r.map(n=>JSON.parse(n))):{error:{message:"Unknown error"}}}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:p,maxLength:m}=this.params.config,a={...G,locale:c,maxLength:m,type:p,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},u=e==="review"?U(a):H(a),d=await this.createChatCompletions(u,o);return i&&B("Perplexity",o,u,d,e),this.parseMessage(d,p,l)}async createChatCompletions(e,o){const n=(await new Pe({method:"POST",baseURL:`${this.host}/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody({model:this.params.config.model,messages:[{role:"system",content:`${e}`},{role:"user",content:`Here is the diff: ${o}`}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1}).execute()).data;if(!n.choices||n.choices.length===0||!n.choices[0].message?.content)throw new Error("No Content on response. Please open a Bug report");return n.choices[0].message.content}}class Qe{constructor(e,o){this.config=e,this.stagedDiff=o}createCommitMsgRequests$(e){return E(e).pipe(Ie(o=>{const r=this.config[o],n=Array.isArray(r.model)?r.model:[r.model];return E(n).pipe(Ie(s=>{if(r.compatible)return R.create(lo,{config:{...r,url:r.url||"",path:r.path||"",model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();switch(o){case"OPENAI":return R.create(Po,{config:{...this.config.OPENAI,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"GEMINI":return R.create(so,{config:{...this.config.GEMINI,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"ANTHROPIC":return R.create(eo,{config:{...this.config.ANTHROPIC,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"HUGGINGFACE":return R.create(io,{config:{...this.config.HUGGINGFACE,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"MISTRAL":return R.create(ao,{config:{...this.config.MISTRAL,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"CODESTRAL":return R.create(to,{config:{...this.config.CODESTRAL,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"OLLAMA":return R.create(co,{config:{...this.config.OLLAMA,model:s},keyName:s,stagedDiff:this.stagedDiff}).generateCommitMessage$();case"COHERE":return R.create(ro,{config:{...this.config.COHERE,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"GROQ":return R.create(no,{config:{...this.config.GROQ,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"PERPLEXITY":return R.create($o,{config:{...this.config.PERPLEXITY,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"DEEPSEEK":return R.create(oo,{config:{...this.config.DEEPSEEK,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();default:const i=w.red.bold(`[${o}]`);return de({name:i+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),A(o=>{const r=w.red.bold("[UNKNOWN]");return de({name:r+` ${o.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}createCodeReviewRequests$(e){return E(e).pipe(Ie(o=>{const r=this.config[o],n=Array.isArray(r.model)?r.model:[r.model];return E(n).pipe(Ie(s=>{if(r.compatible)return R.create(lo,{config:{...r,url:r.url||"",path:r.path||"",model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();switch(o){case"OPENAI":return R.create(Po,{config:{...this.config.OPENAI,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"GEMINI":return R.create(so,{config:{...this.config.GEMINI,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"ANTHROPIC":return R.create(eo,{config:{...this.config.ANTHROPIC,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"HUGGINGFACE":return R.create(io,{config:{...this.config.HUGGINGFACE,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"MISTRAL":return R.create(ao,{config:{...this.config.MISTRAL,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"CODESTRAL":return R.create(to,{config:{...this.config.CODESTRAL,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"OLLAMA":return R.create(co,{config:{...this.config.OLLAMA,model:s},keyName:s,stagedDiff:this.stagedDiff}).generateCodeReview$();case"COHERE":return R.create(ro,{config:{...this.config.COHERE,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"GROQ":return R.create(no,{config:{...this.config.GROQ,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"PERPLEXITY":return R.create($o,{config:{...this.config.PERPLEXITY,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"DEEPSEEK":return R.create(oo,{config:{...this.config.DEEPSEEK,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();default:const i=w.red.bold(`[${o}]`);return de({name:i+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),A(o=>{const r=w.red.bold("[UNKNOWN]");return de({name:r+` ${o.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}}const Ht=async()=>{const{stdout:t,failed:e}=await X("git",["rev-parse","--show-toplevel"],{reject:!1});if(e)throw new C("The current directory must be a Git repository!");return t},J=t=>`:(exclude)${t}`,Ze=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb","*.gif","*.png"].map(J),Ut=async(t,e)=>{const o=["diff","--cached","--diff-algorithm=minimal"],{stdout:r}=await X("git",[...o,"--name-only",...Ze,...t?t.map(J):[],...e?e.map(J):[]]);if(!r)return null;const{stdout:n}=await X("git",[...o,...Ze,...t?t.map(J):[]]);return{files:r.split(`
|
|
87
87
|
`),diff:n}},Ha=t=>`Detected ${t.files.length.toLocaleString()} staged file${t.files.length>1?"s":""} (${t.diff.length.toLocaleString()} characters)`,Ua=async(t,e,o)=>{const r=["diff-tree","-r","--no-commit-id","--name-only",t],{stdout:n}=await X("git",[...r,...Ze,...e?e.map(J):[],...o?o.map(J):[]]);if(!n)return null;const{stdout:s}=await X("git",["show",t,"--",...Ze,...e?e.map(J):[],...o?o.map(J):[]]);return{files:n.split(`
|
|
88
88
|
`).filter(Boolean),diff:s}},qa=async()=>{try{const{stdout:t}=await X("git",["config","--get","core.commentChar"]);return t}catch{return"#"}};class Q{constructor(){this.title="aicommit2"}printTitle(){console.log(hs.textSync(this.title,{font:"Small"}))}showLoader(e){if(this.loader){this.loader.text=e;return}this.loader=nt(e).start()}stopLoader(){this.loader?.stop(),this.loader=void 0}displaySpinner(e){return nt(e).start()}stopSpinner(e){e.stop(),e.clear()}printStagedFiles(e){console.log(w.bold.green("\u2714 ")+w.bold(`${Ha(e)}:`)),console.log(`${e.files.map(o=>` ${o}`).join(`
|
|
89
89
|
`)}
|
|
@@ -95,10 +95,12 @@ ${w.bold.green("\u2714")} ${w.bold("Saved commit message")}`)}printCancelledComm
|
|
|
95
95
|
${w.bold.yellow("\u26A0")} ${w.yellow("Commit cancelled")}`)}printError(e){console.log(`
|
|
96
96
|
${w.bold.red("\u2716")} ${w.red(`${e}`)}`)}printWarning(e){console.log(`
|
|
97
97
|
${w.bold.yellow("\u26A0")} ${w.red(`${e}`)}`)}printSetupGitEvent(e){console.log(`
|
|
98
|
-
${w.bold.green("\u2714")} ${w.bold(`Git ${e} hook has been set up`)}`)}moveCursorUp(){const e=Te.createInterface({input:process.stdin,output:process.stdout});Te.moveCursor(process.stdout,0,-1),e.close()}moveCursorDown(){const e=Te.createInterface({input:process.stdin,output:process.stdout});Te.moveCursor(process.stdout,0,2),e.close()}}const za={isLoading:!1,startOption:{text:"AI is analyzing your changes"}},Eo={isLoading:!1,startOption:{text:"AI is performing a code review"}},qt="No commit messages were generated",xo="No code reviews were generated",zt={type:"reactiveListPrompt",name:"aicommit2Prompt",message:"Pick a commit message to use: ",emptyMessage:`\u26A0 ${qt}`,loop:!1,descPageSize:15,showDescription:!0,pickKey:"short",isDescriptionDim:!0,stopMessage:"Changes analyzed"};class Kt{constructor(e){this.choices$=new rr([]),this.destroyed$=new Qo(1),this.stopMessage="Changes analyzed",this.inquirerInstance=null,this.loader$=new rr(e)}initPrompt(e=zt){return this.stopMessage=e.stopMessage,Me.registerPrompt("reactiveListPrompt",gs),this.inquirerInstance=Me.prompt({choices$:this.choices$,loader$:this.loader$,...e}),this.inquirerInstance}startLoader(){this.loader$.next({isLoading:!0})}clearLoader(){this.inquirerInstance&&this.loader$.next({isLoading:!1,clear:!0})}refreshChoices(e){const{value:o,isError:r}=e;!e||!o||this.choices$.next([...this.currentChoices,e].sort(Bi))}checkErrorOnChoices(e=!0){if(this.choices$.getValue().map(r=>r).every(r=>r?.isError||r?.disabled)){this.alertNoGeneratedMessage(),this.logEmptyCommitMessage(),e&&process.exit(1);return}this.stopLoaderOnSuccess()}completeSubject(){this.choices$.complete(),this.loader$.complete(),this.destroyed$.next(!0),this.destroyed$.complete()}closeInquirerInstance(){this.inquirerInstance&&this.inquirerInstance.ui.close()}cancel(){this.inquirerInstance?.ui?.activePrompt&&this.inquirerInstance.ui.activePrompt.abortPrompt()}alertNoGeneratedMessage(){this.loader$.next({isLoading:!1,message:qt,stopOption:{doneFrame:"\u26A0",color:"yellow"}})}stopLoaderOnSuccess(){this.loader$.next({isLoading:!1,message:this.stopMessage})}logEmptyCommitMessage(){console.log(`${w.bold.yellow("\u26A0")} ${w.yellow(`${qt}`)}`)}get currentChoices(){return this.choices$.getValue().map(e=>e)}}const
|
|
98
|
+
${w.bold.green("\u2714")} ${w.bold(`Git ${e} hook has been set up`)}`)}moveCursorUp(){const e=Te.createInterface({input:process.stdin,output:process.stdout});Te.moveCursor(process.stdout,0,-1),e.close()}moveCursorDown(){const e=Te.createInterface({input:process.stdin,output:process.stdout});Te.moveCursor(process.stdout,0,2),e.close()}print(e){console.log(e)}}const za={isLoading:!1,startOption:{text:"AI is analyzing your changes"}},Eo={isLoading:!1,startOption:{text:"AI is performing a code review"}},qt="No commit messages were generated",xo="No code reviews were generated",zt={type:"reactiveListPrompt",name:"aicommit2Prompt",message:"Pick a commit message to use: ",emptyMessage:`\u26A0 ${qt}`,loop:!1,descPageSize:15,showDescription:!0,pickKey:"short",isDescriptionDim:!0,stopMessage:"Changes analyzed"};class Kt{constructor(e){this.choices$=new rr([]),this.destroyed$=new Qo(1),this.stopMessage="Changes analyzed",this.inquirerInstance=null,this.loader$=new rr(e)}initPrompt(e=zt){return this.stopMessage=e.stopMessage,Me.registerPrompt("reactiveListPrompt",gs),this.inquirerInstance=Me.prompt({choices$:this.choices$,loader$:this.loader$,...e}),this.inquirerInstance}startLoader(){this.loader$.next({isLoading:!0})}clearLoader(){this.inquirerInstance&&this.loader$.next({isLoading:!1,clear:!0})}refreshChoices(e){const{value:o,isError:r}=e;!e||!o||this.choices$.next([...this.currentChoices,e].sort(Bi))}checkErrorOnChoices(e=!0){if(this.choices$.getValue().map(r=>r).every(r=>r?.isError||r?.disabled)){this.alertNoGeneratedMessage(),this.logEmptyCommitMessage(),e&&process.exit(1);return}this.stopLoaderOnSuccess()}completeSubject(){this.choices$.complete(),this.loader$.complete(),this.destroyed$.next(!0),this.destroyed$.complete()}closeInquirerInstance(){this.inquirerInstance&&this.inquirerInstance.ui.close()}cancel(){this.inquirerInstance?.ui?.activePrompt&&this.inquirerInstance.ui.activePrompt.abortPrompt()}alertNoGeneratedMessage(){this.loader$.next({isLoading:!1,message:qt,stopOption:{doneFrame:"\u26A0",color:"yellow"}})}stopLoaderOnSuccess(){this.loader$.next({isLoading:!1,message:this.stopMessage})}logEmptyCommitMessage(){console.log(`${w.bold.yellow("\u26A0")} ${w.yellow(`${qt}`)}`)}get currentChoices(){return this.choices$.getValue().map(e=>e)}}const q=new Q;var Ka=async(t,e,o,r,n,s,i,c,l,p,m)=>(async()=>{q.printTitle(),await Ht(),r&&await X("git",["add","--update"]);const a=await ue({locale:t?.toString(),generate:e?.toString(),type:n?.toString(),systemPrompt:c?.toString(),includeBody:l?.toString()},m);(l===!0||a.includeBody===!0)&&Object.keys(a).forEach(_=>{typeof a[_]=="object"&&a[_]!==null&&"includeBody"in a[_]&&(a[_].includeBody=!0)}),await Zr(a);const d=q.displaySpinner("Detecting staged files"),h=await Ut(o,a.exclude);if(d.stop(),!h)throw new C("No staged changes found. Stage your changes manually, or automatically stage all changes with the `--all` flag.");q.printStagedFiles(h);const g=So(a,"commit");if(g.length===0)throw new C("Please set at least one API key via the `aicommit2 config set` command");const y=new Qe(a,h),v=So(a,"review");v.length>0&&await Wa(y,v);const P=await Ya(y,g,p);i&&(Ns("copy-paste").copy(P),q.printCopied(),process.exit()),(s||p&&g.length===1)&&(await Ao(P,m),process.exit());const{confirmationPrompt:L}=await Me.prompt([{type:"confirm",name:"confirmationPrompt",message:"Use selected message?",default:!0}]);L?await Ao(P,m):q.printCancelledCommit(),process.exit()})().catch(a=>{q.printError(a.message),ee(a),process.exit(1)});function So(t,e){return Object.entries(t).map(([o,r])=>[o,r]).filter(([o,r])=>!r.disabled).filter(([o,r])=>le.includes(o)||r.compatible===!0).filter(([o,r])=>{switch(e){case"commit":return o==="OLLAMA"?!!r&&!!r.model&&r.model.length>0:o==="HUGGINGFACE"?!!r&&!!r.cookie:!!r.key&&r.key.length>0;case"review":const n=t.codeReview||r.codeReview;return o==="OLLAMA"?!!r&&!!r.model&&r.model.length>0&&n:o==="HUGGINGFACE"?!!r&&!!r.cookie&&n:!!r.key&&r.key.length>0&&n}}).map(([o])=>o)}async function Wa(t,e){const o=new Kt(Eo),r=o.initPrompt({...zt,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${xo}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20});o.startLoader();const n=t.createCodeReviewRequests$(e).subscribe(l=>o.refreshChoices(l),()=>{},()=>o.checkErrorOnChoices());if(!(await r).codeReviewPrompt?.value)throw new C("An error occurred! No selected code review");n.unsubscribe(),o.completeSubject(),q.moveCursorUp();const{continuePrompt:c}=await Me.prompt([{type:"confirm",name:"continuePrompt",message:"Will you continue without changing the code?",default:!0}]);c||(q.printCancelledCommit(),process.exit())}async function Ya(t,e,o){const r=new Kt(za);if(o&&e.length===1){const l=[];r.startLoader();const p=t.createCommitMsgRequests$(e).subscribe(a=>{l.push(a),r.refreshChoices(a)},()=>{},()=>r.checkErrorOnChoices(!1));await new Promise(a=>{p.add(()=>a())}),r.clearLoader(),r.completeSubject(),q.moveCursorUp();const m=l.find(a=>a.value&&!a.isError&&!a.disabled);if(!m||!m.value)throw new C("No valid commit message was generated");return q.print(`
|
|
99
|
+
${m.name}
|
|
100
|
+
`),m.value}const n=r.initPrompt();r.startLoader();const s=t.createCommitMsgRequests$(e).subscribe(l=>r.refreshChoices(l),()=>{},()=>r.checkErrorOnChoices()),i=await n;s.unsubscribe(),r.completeSubject(),q.moveCursorUp();const c=i.aicommit2Prompt?.value;if(!c)throw new C("An error occurred! No selected message");return c}async function Ao(t,e){const o=nt("Committing with the generated message").start();await X("git",["commit","-m",t,...e]),o.stop(),o.clear(),q.printCommitted()}var Va=Y({name:"config",parameters:["<mode>","[key=value...]"],help:{description:"Manage configuration settings",examples:["aic2 config set <key>=<value> [<key>=<value> ...]","aic2 config get [<key> [<key> ...]]","aic2 config add <key>=<value> [<key>=<value> ...]","aic2 config del <key>","aic2 config list"]},commands:[Y({name:"set",parameters:["<key>=<value>","[<key>=<value> ...]"],help:{description:"Set configuration values. Multiple key-value pairs can be set at once.",examples:["aic2 config set OPENAI.key=<your key>","aic2 config set ANTHROPIC.topP=0.8 ANTHROPIC.generate=2"]}}),Y({name:"get",parameters:["[<key>","[<key> ...]]"],help:{description:"Retrieve configuration values for specified AI provider.",examples:["aic2 config get OPENAI","aic2 config get ANTHROPIC"]}}),Y({name:"add",parameters:["<key>=<value>","[<key>=<value> ...]"],help:{description:"Add new model to existing configuration. Only Ollama.model can be added.",examples:['aic2 config add OLLAMA.model="gemma2"']}}),Y({name:"list",parameters:[],help:{description:"Display all configuration keys and their values.",examples:["aic2 config list"]}}),Y({name:"del",parameters:["<config-name>"],help:{description:"Delete a configuration setting or section.",examples:["aic2 config del <config-name>","aic2 config del OPENAI.key","aic2 config del OPENAI"]}}),Y({name:"path",parameters:[],help:{description:"Display the path of the loaded configuration file.",examples:["aic2 config path"]}})]},t=>{(async()=>{const{mode:e,keyValue:o}=t._,r=t._[1];if(e==="get"){const n=await ue({},[]);if(o.length===0){console.log(n);return}for(const s of o){const i=s.split(".");let c=n,l=!0;for(const p of i)if(Mt(c,p))c=c[p];else{l=!1;break}l?console.log(s,c):console.log(`${s} not found`)}return}if(e==="set"){await Zi(o.map(n=>{const s=n.indexOf("=");if(s===-1)throw new C("Invalid format. Use: key=value");const i=n.slice(0,s),c=n.slice(s+1);return[i,c]}));return}if(e==="add"){await ea(o.map(n=>{const s=n.indexOf("=");if(s===-1)throw new C("Invalid format. Use: key=value");const i=n.slice(0,s),c=n.slice(s+1);return[i,c]}));return}if(e==="list"){await ta();return}if(e==="del"){if(!r)throw new C("Please provide the config name to delete.");const n=await be(),s=r.split(".");if(s.length===2){const[i,c]=s;if(n[i]&&typeof n[i]=="object"&&Mt(n[i],c)){delete n[i][c],Object.keys(n[i]).length===0&&delete n[i];const l=await me();await x.writeFile(l,ce.stringify(n),"utf8"),console.log(`Successfully deleted config: ${r}`);const p=await x.readFile(l,"utf8");console.log("--- Updated Config Content ---"),console.log(p),console.log("----------------------------")}else throw new C(`Config not found: ${r}`)}else if(s.length===1){const i=s[0];if(Mt(n,i)){delete n[i];const c=await me();await x.writeFile(c,ce.stringify(n),"utf8"),console.log(`Successfully deleted config: ${r}`);const l=await x.readFile(c,"utf8");console.log("--- Updated Config Content ---"),console.log(l),console.log("----------------------------")}else throw new C(`Config not found: ${r}`)}else throw new C(`Invalid config name format: ${r}`);return}if(e==="path"){await ra();return}throw new C(`Invalid mode: ${e}`)})().catch(e=>{new Q().printError(e.message),ee(e),process.exit(1)})});const ko="prepare-commit-msg",Mo=`.git/hooks/${ko}`,et=fs(new URL("cli.mjs",import.meta.url)),Xa=process.argv[1].replace(/\\/g,"/").endsWith(`/${Mo}`),Io=process.platform==="win32",Ro=`
|
|
99
101
|
#!/usr/bin/env node
|
|
100
102
|
import(${JSON.stringify(ds(et))})
|
|
101
|
-
`.trim();var Ja=Y({name:"hook",parameters:["<install/uninstall>"],help:{description:"Install or uninstall the Git prepare-commit-msg hook",examples:["aic2 hook install","aic2 hook uninstall"]}},t=>{(async()=>{const e=await Ht(),{installUninstall:o}=t._,r
|
|
103
|
+
`.trim();var Ja=Y({name:"hook",parameters:["<install/uninstall>"],help:{description:"Install or uninstall the Git prepare-commit-msg hook",examples:["aic2 hook install","aic2 hook uninstall"]}},t=>{(async()=>{const e=await Ht(),{installUninstall:o}=t._,r=$.join(e,Mo),n=await Ur(r);if(o==="install"){if(n){if(await x.realpath(r).catch(()=>{})===et){console.warn("The hook is already installed");return}throw new C(`A different ${ko} hook seems to be installed. Please remove it before installing aicommit2.`)}await x.mkdir($.dirname(r),{recursive:!0}),Io?await x.writeFile(r,Ro):(await x.symlink(et,r,"file"),await x.chmod(r,493)),console.log(`${w.green("\u2714")} Hook installed`);return}if(o==="uninstall"){if(!n){console.warn("Hook is not installed");return}if(Io){if(await x.readFile(r,"utf8")!==Ro){console.warn("Hook is not installed");return}}else if(await x.realpath(r)!==et){console.warn("Hook is not installed");return}await x.rm(r),console.log(`${w.green("\u2714")} Hook uninstalled`);return}throw new C(`Invalid mode: ${o}`)})().catch(e=>{console.error(`${w.red("\u2716")} ${e.message}`),ee(e),process.exit(1)})}),Qa=Y({name:"log",parameters:["<removeAll>"],help:{description:"Manage log files generated by the application",examples:["aic2 log removeAll"]}},t=>{(async()=>{const{removeAll:e}=t._;if(e==="removeAll"){await ys(We,{recursive:!0,force:!0}),console.log(`${w.green("\u2714")} All Log files are removed!`);return}throw new C(`Invalid mode: ${e}`)})().catch(e=>{new Q().printError(e.message),ee(e),process.exit(1)})});const Za=process.argv.slice(2).filter(t=>!t.startsWith("--pre-commit")),[tt,Oo]=Za;var ec=()=>(async()=>{if(!tt)throw new C('Commit message file path is missing. This file should be called from the "pre-commit framework"');if(Oo){console.log(`Skipping aicommit2 message generation for ${Oo} commit`);return}const t=await Ut();if(!t)return;const e=new Q;e.printTitle();const o=await ue({});if(o.systemPromptPath)try{await x.readFile($.resolve(o.systemPromptPath),"utf-8")}catch{throw new C(`Error reading system prompt file: ${o.systemPromptPath}`)}const r=Object.entries(o).filter(([d])=>le.includes(d)).map(([d,h])=>[d,h]).filter(([d,h])=>!h.disabled).filter(([d,h])=>d==="OLLAMA"?!!h&&!!h.model&&h.model.length>0:d==="HUGGINGFACE"?!!h&&!!h.cookie:!!h.key&&h.key.length>0).map(([d])=>d);if(r.length===0)throw new C("Please set at least one API key via the `aicommit2 config set` command");const s=new Qe(o,t);let i;try{i=await or(s.createCommitMsgRequests$(r).pipe(sr(d=>!d.isError),S(d=>d.value),nr()))}finally{e.printAnalyzed()}const l=await x.readFile(tt,"utf8")!=="",p=i.length>1;let m="";l&&(m=`# \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
|
|
102
104
|
`,m+=`# ----------------------------------------
|
|
103
105
|
`,m+=`# How to use:
|
|
104
106
|
`,p?(m+=`# 1. Remove the "#" from your chosen message
|
|
@@ -117,7 +119,7 @@ ${i.map(d=>`# ${d}`).join(`
|
|
|
117
119
|
`),m+=`
|
|
118
120
|
${i[0]}
|
|
119
121
|
`);const a=await x.readFile(tt,"utf8"),u=m+`
|
|
120
|
-
`+a;await x.writeFile(tt,u),e.printSavedCommitMessage()})().catch(t=>{new Q().printError(t.message),ee(t),process.exit(1)});const tc=process.argv.slice(2).filter(t=>!t.startsWith("--hook-mode")),[rt,Lo]=tc;var rc=()=>(async()=>{if(!rt)throw new C('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook or with --hook-mode flag');if(Lo){console.log(`Skipping aicommit2 message generation for ${Lo} commit`);return}const t=await Ut();if(!t)return;const e=new Q;e.printTitle();const o=await ue({});if(o.systemPromptPath)try{await x.readFile(
|
|
122
|
+
`+a;await x.writeFile(tt,u),e.printSavedCommitMessage()})().catch(t=>{new Q().printError(t.message),ee(t),process.exit(1)});const tc=process.argv.slice(2).filter(t=>!t.startsWith("--hook-mode")),[rt,Lo]=tc;var rc=()=>(async()=>{if(!rt)throw new C('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook or with --hook-mode flag');if(Lo){console.log(`Skipping aicommit2 message generation for ${Lo} commit`);return}const t=await Ut();if(!t)return;const e=new Q;e.printTitle();const o=await ue({});if(o.systemPromptPath)try{await x.readFile($.resolve(o.systemPromptPath),"utf-8")}catch{throw new C(`Error reading system prompt file: ${o.systemPromptPath}`)}const r=Object.entries(o).filter(([g])=>le.includes(g)).map(([g,y])=>[g,y]).filter(([g,y])=>!y.disabled).filter(([g,y])=>g==="OLLAMA"?!!y&&!!y.model&&y.model.length>0:g==="HUGGINGFACE"?!!y&&!!y.cookie:!!y.key&&y.key.length>0).map(([g])=>g);if(r.length===0)throw new C("Please set at least one API key via the `aicommit2 config set` command");const s=new Qe(o,t),i=e.displaySpinner("The AI is analyzing your changes");let c;try{c=await or(s.createCommitMsgRequests$(r).pipe(sr(g=>!g.isError),S(g=>g.value),nr()))}finally{i.stop(),i.clear(),e.printAnalyzed()}const p=await x.readFile(rt,"utf8")!=="",m=c.length>1,a=await qa();let u="";p&&(u=`${a} \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
|
|
121
123
|
`,u+=`${a} ----------------------------------------
|
|
122
124
|
`,u+=`${a} How to use:
|
|
123
125
|
`,m?(u+=`${a} 1. Remove the "${a}" from your chosen message
|
|
@@ -136,13 +138,13 @@ ${a} \u{1F4DD} Generated commit message:
|
|
|
136
138
|
`),u+=`
|
|
137
139
|
${c[0]}
|
|
138
140
|
`);const d=await x.readFile(rt,"utf8"),h=u+`
|
|
139
|
-
`+d;await x.writeFile(rt,h),e.printSavedCommitMessage()})().catch(t=>{new Q().printError(t.message),ee(t),process.exit(1)});let ot=new ir;const
|
|
141
|
+
`+d;await x.writeFile(rt,h),e.printSavedCommitMessage()})().catch(t=>{new Q().printError(t.message),ee(t),process.exit(1)});let ot=new ir;const D=new Q,To=process.cwd(),oc=$.join(To,".git","hooks","post-commit"),ke=$.join(To,".git","commit-log.txt"),sc=`#!/bin/sh
|
|
140
142
|
commit_hash=$(git rev-parse HEAD)
|
|
141
143
|
commit_message=$(git log -1 --pretty=%B)
|
|
142
144
|
echo "$commit_hash: $commit_message" >> ${ke}
|
|
143
|
-
`;let Wt=null,N=null;const No=async(t,e,o,r,n)=>{
|
|
145
|
+
`;let Wt=null,N=null;const No=async(t,e,o,r,n)=>{D.printTitle(),await Ht();const s=await nc(t,e,r,n);lc(),ac();try{await Do(s)}catch(i){return ic(i),No(t,e,o,r,n)}},nc=async(t,e,o,r)=>{const n=await ue({locale:t?.toString(),generate:e?.toString(),systemPrompt:o?.toString()},r);return await Zr(n),_o(n).length===0&&(D.printError(`Please set at least one API key and watchMode via the config command:
|
|
144
146
|
aicommit2 config set [MODEL].key="YOUR_API_KEY"
|
|
145
|
-
aicommit2 config set [MODEL].watchMode="true"`),process.exit()),n},ic=async t=>{
|
|
147
|
+
aicommit2 config set [MODEL].watchMode="true"`),process.exit()),n},ic=async t=>{D.printError(`An error occurred: ${t.message}`),ee(t),await new Promise(e=>setTimeout(e,3e3)),D.printWarning("Restarting the commit monitoring process...")},ac=()=>{F.writeFileSync(ke,"",{flag:"w"})},_o=t=>Object.entries(t).filter(([e,o])=>le.includes(e)||o.compatible===!0).map(([e,o])=>[e,o]).filter(([e,o])=>!o.disabled).filter(([e,o])=>cc(e,o,t)).map(([e])=>e),cc=(t,e,o)=>{const r=o.watchMode||e.watchMode;return t==="OLLAMA"?!!e&&!!e.model&&e.model.length>0&&r:t==="HUGGINGFACE"?!!e&&!!e.cookie&&r:e.compatible?!!e.url&&!!e.key&&r:!!e.key&&e.key.length>0&&r},lc=()=>{F.writeFileSync(oc,sc,{mode:493}),D.printSetupGitEvent("post-commit")},Fo=()=>{process.stdout.write("\x1Bc")},mc=async(t,e)=>{try{const o=await Ua(e);if(!o){D.printWarning("No changes found in this commit");return}D.stopLoader(),D.printStagedFiles(o);const r=_o(t);if(r.length===0){D.printError(`Please set at least one API key and watchMode via the config command:
|
|
146
148
|
aicommit2 config set [MODEL].key="YOUR_API_KEY"
|
|
147
|
-
aicommit2 config set [MODEL].watchMode="true"`),process.exit();return}await uc(t,o,r)}catch(o){
|
|
148
|
-
`),yc=async(t,e)=>{const[o]=e.split(":");if(!o){
|
|
149
|
+
aicommit2 config set [MODEL].watchMode="true"`),process.exit();return}await uc(t,o,r)}catch(o){D.printError(`Error processing commit ${e}: ${o.message}`)}},uc=async(t,e,o)=>{pc();const r=new Qe(t,e);N=new Kt(Eo);const n=fc();N.startLoader(),Wt=dc(r,o),await n,hc()},pc=()=>{N&&(Wt?.unsubscribe(),N.clearLoader(),N.completeSubject(),N.cancel(),N.closeInquirerInstance()),ot.next(),ot.complete(),ot=new ir},fc=()=>N.initPrompt({...zt,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${xo}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20}),dc=(t,e)=>t.createCodeReviewRequests$(e).pipe(vs(ot)).subscribe(o=>{N?.refreshChoices(o)},()=>{},()=>{N?.checkErrorOnChoices(!1)}),hc=()=>{N&&(Wt?.unsubscribe(),N.clearLoader(),N.completeSubject(),N.cancel(),N.closeInquirerInstance(),N=null),Fo(),D.showLoader("Watching for new Git commits...")},Do=async t=>{const e=ws.watch(ke,{persistent:!0});e.on("change",async()=>{try{const o=await gc();for(const r of o)r&&await yc(t,r)}catch(o){D.printError(`Error reading or processing commit log: ${o.message}`)}finally{wc()}}),e.on("error",vc(t))},gc=async()=>(await F.promises.readFile(ke,"utf8")).trim().split(`
|
|
150
|
+
`),yc=async(t,e)=>{const[o]=e.split(":");if(!o){D.printWarning("Empty commit hash detected, skipping...");return}Fo(),await mc(t,o.trim())},wc=()=>{try{F.truncateSync(ke)}catch(t){D.printError(`Error truncating log file: ${t.message}`)}},vc=t=>e=>{D.printError(`Watcher error: ${e.message}`),setTimeout(()=>Do(t),1e3)},Yt=process.argv.slice(2),{version:Go,description:bc}=Ts;Ho({name:"aicommit2",version:Go,flags:{locale:{type:String,description:"Locale to use for the generated commit messages (default: en)",alias:"l"},generate:{type:Number,description:"Number of messages to generate (Warning: generating multiple costs more) (default: 1)",alias:"g"},exclude:{type:[String],description:"Files to exclude from AI analysis",alias:"x"},all:{type:Boolean,description:"Automatically stage changes in tracked files for the commit",alias:"a",default:!1},type:{type:String,description:"Type of commit message to generate (default: conventional)",alias:"t"},confirm:{type:Boolean,description:"Skip confirmation when committing after message generation (default: false)",alias:"y",default:!1},clipboard:{type:Boolean,description:"Copy the selected message to the clipboard",alias:"c",default:!1},prompt:{type:String,description:"Custom prompt to let users fine-tune provided prompt",alias:"p"},"watch-commit":{type:Boolean,default:!1},"hook-mode":{type:Boolean,description:"Run in git hook mode, allowing chaining with other hooks",default:!1},"pre-commit":{type:Boolean,description:"Run in pre-commit Framework, allowing chaining with other hooks",default:!1},"include-body":{type:Boolean,description:"Force include commit body in all generated messages",alias:"i",default:!1},"auto-select":{type:Boolean,description:"Automatically select the message when only one is generated",alias:"s",default:!1}},commands:[Va,Ja,Qa],help:{description:bc},ignoreArgv:t=>t==="unknown-flag"||t==="argument"},async t=>{const e=await ue({});if(await oa(e),Ce.info(`aicommit2 version: ${Go}`),t.flags["pre-commit"]){ec();return}if(t.flags["hook-mode"]||Xa){rc();return}if(t.flags["watch-commit"]){No(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.prompt,Yt);return}Ka(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.all,t.flags.type,t.flags.confirm,t.flags.clipboard,t.flags.prompt,t.flags["include-body"],t.flags["auto-select"],Yt)},Yt);
|