@negoziator/ai-commit 2.81.0 → 2.83.0

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.
@@ -1,4 +1,4 @@
1
- var y=Object.defineProperty;var u=(f,t)=>y(f,"name",{value:t,configurable:!0});import l from"https";import{d as w}from"./index-Bi9U2ify.mjs";import{L as A,g as C}from"./prompt-BGI0PV0L.mjs";import{K as a}from"./cli-COuffhrp.mjs";import"net";import"tls";import"assert";import"tty";import"util";import"os";import"http";import"url";import"node:url";import"node:child_process";import"node:string_decoder";import"node:util";import"node:process";import"node:tty";import"node:path";import"child_process";import"path";import"fs";import"node:timers/promises";import"node:os";import"node:events";import"node:v8";import"node:fs";import"node:stream";import"node:buffer";import"node:stream/promises";import"node:readline";import"fs/promises";const h=class h extends A{get name(){return"anthropic"}validateConfig(){const{apiKey:t}=this.config;if(!t)throw new a("Please set your Anthropic API key via `aicommit config set ANTHROPIC_KEY=<your token>`\nGet your API key from: https://console.anthropic.com/");if(!t.startsWith("sk-ant-"))throw new a('Invalid Anthropic API key: Must start with "sk-ant-"')}async generateCommitMessage(t){try{const i=C(this.config.locale,this.config.maxLength,this.config.type,t.projectConfig),o=[{role:"user",content:t.diff}],e=[];for(let s=0;s<t.completions;s++){const r=(await this.createMessage(i,o)).content[0]?.text;r&&e.push(this.sanitizeMessage(r))}return{messages:this.deduplicateMessages(e)}}catch(i){const o=i;throw o.code==="ENOTFOUND"?new a(`Error connecting to ${o.hostname} (${o.syscall}). Are you connected to the internet?`):o}}async createMessage(t,i){const o={model:this.config.model,max_tokens:this.config.maxCompletionTokens,temperature:this.config.temperature,system:t,messages:i},{response:e,data:n}=await this.httpsPost("api.anthropic.com","/v1/messages",{"x-api-key":this.config.apiKey,"anthropic-version":"2023-06-01"},o);if(!e.statusCode||e.statusCode<200||e.statusCode>299){let s=`Anthropic API Error: ${e.statusCode} - ${e.statusMessage}`;throw n&&(s+=`
1
+ var y=Object.defineProperty;var u=(f,t)=>y(f,"name",{value:t,configurable:!0});import l from"https";import{d as w}from"./index-Bi9U2ify.mjs";import{L as A,g as C}from"./prompt-BGI0PV0L.mjs";import{K as a}from"./cli-BMzt-Oel.mjs";import"net";import"tls";import"assert";import"tty";import"util";import"os";import"http";import"url";import"node:url";import"node:child_process";import"node:string_decoder";import"node:util";import"node:process";import"node:tty";import"node:path";import"child_process";import"path";import"fs";import"node:timers/promises";import"node:os";import"node:events";import"node:v8";import"node:fs";import"node:stream";import"node:buffer";import"node:stream/promises";import"node:readline";import"fs/promises";const h=class h extends A{get name(){return"anthropic"}validateConfig(){const{apiKey:t}=this.config;if(!t)throw new a("Please set your Anthropic API key via `aicommit config set ANTHROPIC_KEY=<your token>`\nGet your API key from: https://console.anthropic.com/");if(!t.startsWith("sk-ant-"))throw new a('Invalid Anthropic API key: Must start with "sk-ant-"')}async generateCommitMessage(t){try{const i=C(this.config.locale,this.config.maxLength,this.config.type,t.projectConfig),o=[{role:"user",content:t.diff}],e=[];for(let s=0;s<t.completions;s++){const r=(await this.createMessage(i,o)).content[0]?.text;r&&e.push(this.sanitizeMessage(r))}return{messages:this.deduplicateMessages(e)}}catch(i){const o=i;throw o.code==="ENOTFOUND"?new a(`Error connecting to ${o.hostname} (${o.syscall}). Are you connected to the internet?`):o}}async createMessage(t,i){const o={model:this.config.model,max_tokens:this.config.maxCompletionTokens,temperature:this.config.temperature,system:t,messages:i},{response:e,data:n}=await this.httpsPost("api.anthropic.com","/v1/messages",{"x-api-key":this.config.apiKey,"anthropic-version":"2023-06-01"},o);if(!e.statusCode||e.statusCode<200||e.statusCode>299){let s=`Anthropic API Error: ${e.statusCode} - ${e.statusMessage}`;throw n&&(s+=`
2
2
 
3
3
  ${n}`),e.statusCode===500&&(s+=`
4
4
 
@@ -1,3 +1,3 @@
1
- var l=Object.defineProperty;var f=(u,t)=>l(u,"name",{value:t,configurable:!0});import y from"https";import{d as w}from"./index-Bi9U2ify.mjs";import{L as C,g as A}from"./prompt-BGI0PV0L.mjs";import{K as a}from"./cli-COuffhrp.mjs";import"net";import"tls";import"assert";import"tty";import"util";import"os";import"http";import"url";import"node:url";import"node:child_process";import"node:string_decoder";import"node:util";import"node:process";import"node:tty";import"node:path";import"child_process";import"path";import"fs";import"node:timers/promises";import"node:os";import"node:events";import"node:v8";import"node:fs";import"node:stream";import"node:buffer";import"node:stream/promises";import"node:readline";import"fs/promises";const g=class g extends C{get name(){return"azure-openai"}validateConfig(){const{apiKey:t,endpoint:i}=this.config;if(!t)throw new a("Please set your Azure OpenAI API key via `aicommit config set AZURE_OPENAI_KEY=<your token>`");if(!i)throw new a("Please set your Azure OpenAI endpoint via `aicommit config set AZURE_ENDPOINT=<your endpoint>`")}async generateCommitMessage(t){try{const i=await this.createChatCompletion({model:this.config.model,messages:[{role:"system",content:A(this.config.locale,this.config.maxLength,this.config.type,t.projectConfig)},{role:"user",content:t.diff}],temperature:this.config.temperature,top_p:1,frequency_penalty:0,presence_penalty:0,max_tokens:this.config.maxCompletionTokens,n:t.completions});return{messages:this.deduplicateMessages(i.choices.filter(r=>r.message?.content).map(r=>this.sanitizeMessage(r.message.content)))}}catch(i){const e=i;throw e.code==="ENOTFOUND"?new a(`Error connecting to ${e.hostname} (${e.syscall}). Are you connected to the internet?`):e}}async createChatCompletion(t){const e=new URL(this.config.endpoint).hostname,m=`/openai/deployments/${this.config.deploymentName||this.config.model}/chat/completions?api-version=2024-02-01`,{response:n,data:s}=await this.httpsPost(e,m,{"api-key":this.config.apiKey},t);if(!n.statusCode||n.statusCode<200||n.statusCode>299){let o=`Azure OpenAI API Error: ${n.statusCode} - ${n.statusMessage}`;throw s&&(o+=`
1
+ var l=Object.defineProperty;var f=(u,t)=>l(u,"name",{value:t,configurable:!0});import y from"https";import{d as w}from"./index-Bi9U2ify.mjs";import{L as C,g as A}from"./prompt-BGI0PV0L.mjs";import{K as a}from"./cli-BMzt-Oel.mjs";import"net";import"tls";import"assert";import"tty";import"util";import"os";import"http";import"url";import"node:url";import"node:child_process";import"node:string_decoder";import"node:util";import"node:process";import"node:tty";import"node:path";import"child_process";import"path";import"fs";import"node:timers/promises";import"node:os";import"node:events";import"node:v8";import"node:fs";import"node:stream";import"node:buffer";import"node:stream/promises";import"node:readline";import"fs/promises";const g=class g extends C{get name(){return"azure-openai"}validateConfig(){const{apiKey:t,endpoint:i}=this.config;if(!t)throw new a("Please set your Azure OpenAI API key via `aicommit config set AZURE_OPENAI_KEY=<your token>`");if(!i)throw new a("Please set your Azure OpenAI endpoint via `aicommit config set AZURE_ENDPOINT=<your endpoint>`")}async generateCommitMessage(t){try{const i=await this.createChatCompletion({model:this.config.model,messages:[{role:"system",content:A(this.config.locale,this.config.maxLength,this.config.type,t.projectConfig)},{role:"user",content:t.diff}],temperature:this.config.temperature,top_p:1,frequency_penalty:0,presence_penalty:0,max_tokens:this.config.maxCompletionTokens,n:t.completions});return{messages:this.deduplicateMessages(i.choices.filter(r=>r.message?.content).map(r=>this.sanitizeMessage(r.message.content)))}}catch(i){const e=i;throw e.code==="ENOTFOUND"?new a(`Error connecting to ${e.hostname} (${e.syscall}). Are you connected to the internet?`):e}}async createChatCompletion(t){const e=new URL(this.config.endpoint).hostname,m=`/openai/deployments/${this.config.deploymentName||this.config.model}/chat/completions?api-version=2024-02-01`,{response:n,data:s}=await this.httpsPost(e,m,{"api-key":this.config.apiKey},t);if(!n.statusCode||n.statusCode<200||n.statusCode>299){let o=`Azure OpenAI API Error: ${n.statusCode} - ${n.statusMessage}`;throw s&&(o+=`
2
2
 
3
3
  ${s}`),new a(o)}return JSON.parse(s)}async httpsPost(t,i,e,r){return new Promise((m,n)=>{const s=JSON.stringify(r),o=y.request({hostname:t,path:i,method:"POST",headers:{...e,"Content-Type":"application/json","Content-Length":Buffer.byteLength(s)},timeout:this.config.timeout,agent:this.config.proxy?new w.HttpsProxyAgent(this.config.proxy):void 0},p=>{const h=[];p.on("data",d=>h.push(d)),p.on("end",()=>{m({request:o,response:p,data:Buffer.concat(h).toString()})})});o.on("error",n),o.on("timeout",()=>{o.destroy(),n(new a(`Time out error: request took over ${this.config.timeout}ms. Try increasing the \`timeout\` config`))}),o.write(s),o.end()})}sanitizeMessage(t){return t.trim().replace(/[\n\r]/g,"").replace(/(\w)\.$/,"$1")}deduplicateMessages(t){return Array.from(new Set(t))}};f(g,"AzureOpenAIProvider");let c=g;export{c as default};
@@ -19,7 +19,7 @@ var Ac=Object.defineProperty;var o=(e,t)=>Ac(e,"name",{value:t,configurable:!0})
19
19
  `:"")+(n?this.indentText({text:this.render(n),spaces:r}):"")}
20
20
  `}table({tableData:t,tableOptions:n,tableBreakpoints:r}){return Ol(t.map(i=>i.map(s=>this.render(s))),r?xl(r):n)}flagParameter(t){return t===Boolean?"":t===String?"<string>":t===Number?"<number>":Array.isArray(t)?this.flagParameter(t[0]):"<value>"}flagOperator(t){return" "}flagName(t){const{flag:n,flagFormatted:r,aliasesEnabled:i,aliasFormatted:s}=t;let a="";if(s?a+=`${s}, `:i&&(a+=" "),a+=r,"placeholder"in n&&typeof n.placeholder=="string")a+=`${this.flagOperator(t)}${n.placeholder}`;else{const u=this.flagParameter("type"in n?n.type:n);u&&(a+=`${this.flagOperator(t)}${u}`)}return a}flagDefault(t){return JSON.stringify(t)}flagDescription({flag:t}){let n="description"in t?t.description??"":"";if("default"in t){let{default:r}=t;typeof r=="function"&&(r=r()),r&&(n+=` (default: ${this.flagDefault(r)})`)}return n}render(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(n=>this.render(n)).join(`
21
21
  `);if("type"in t&&this[t.type]){const n=this[t.type];if(typeof n=="function")return n.call(this,t.data)}throw new Error(`Invalid node type: ${JSON.stringify(t)}`)}},o(Ve,"_ne"),Ve);B(Ei,"Renderers");let zl=Ei;const bi=B(e=>e.length>0&&!e.includes(" "),"isValidScriptName"),{stringify:Q}=JSON,Vl=/[|\\{}()[\]^$+*?.]/;function wn(e){const t=[];let n,r;for(const i of e){if(r)throw new Error(`Invalid parameter: Spread parameter ${Q(r)} must be last`);const s=i[0],a=i.at(-1);let u;if(s==="<"&&a===">"&&(u=!0,n))throw new Error(`Invalid parameter: Required parameter ${Q(i)} cannot come after optional parameter ${Q(n)}`);if(s==="["&&a==="]"&&(u=!1,n=i),u===void 0)throw new Error(`Invalid parameter: ${Q(i)}. Must be wrapped in <> (required parameter) or [] (optional parameter)`);let c=i.slice(1,-1);const d=c.slice(-3)==="...";d&&(r=i,c=c.slice(0,-3));const l=c.match(Vl);if(l)throw new Error(`Invalid parameter: ${Q(i)}. Invalid character found ${Q(l[0])}`);t.push({name:c,required:u,spread:d})}return t}o(wn,"P"),B(wn,"parseParameters");function yn(e,t,n,r){for(let i=0;i<t.length;i+=1){const{name:s,required:a,spread:u}=t[i],c=kl(s);if(c in e)throw new Error(`Invalid parameter: ${Q(s)} is used more than once.`);const d=u?n.slice(i):n[i];if(u&&(i=t.length),a&&(!d||u&&d.length===0))return console.error(`Error: Missing required parameter ${Q(s)}
22
- `),r(),process.exit(1);e[c]=d}}o(yn,"S"),B(yn,"mapParametersToArguments");function Ci(e){return e!==!1}o(Ci,"se"),B(Ci,"helpEnabled");const Hl=B(e=>{const t=[];for(const[n,r]of Object.entries(e))if(t.push(n),r&&typeof r=="object"&&"alias"in r){const{alias:i}=r;typeof i=="string"&&i?t.push(i):Array.isArray(i)&&t.push(...i.filter(Boolean))}return t},"getKnownFlagNames"),Kl=B((e,t)=>{if(e.length<3||t.length===0)return;const n=Nl(e,t);return li(e,n)<=2?n:void 0},"findClosestFlag"),ql=B((e,t)=>{const n=Object.keys(e);if(n.length!==0){for(const r of n){const i=Kl(r,t),s=i?` (Did you mean --${i}?)`:"";console.error(`Error: Unknown flag: --${r}.${s}`)}process.exit(1)}},"handleUnknownFlags");function En(e,t,n,r){const i={...t.flags},s=t.version&&!("version"in i);s&&(i.version={type:Boolean,description:"Show version"});const{help:a}=t,u=Ci(a);u&&!("help"in i)&&(i.help={type:Boolean,alias:"h",description:"Show help"});const c=ll(i,r,{ignore:t.ignoreArgv,booleanNegation:t.booleanFlagNegation??t.parent?.booleanFlagNegation}),d=B(()=>{console.log(t.version)},"showVersion");if(s&&c.flags.version===!0)return d(),process.exit(0);const l=new zl,f=u&&a?.render?a.render:m=>l.render(m),h=B(m=>{const g=Wl({...t,...m?{help:m}:{},flags:i});console.log(f(g,l))},"showHelp");if(u&&c.flags.help===!0)return h(),process.exit(0);if((t.strictFlags??t.parent?.strictFlags)&&ql(c.unknownFlags,Hl(i)),t.parameters){let{parameters:m}=t,g=c._;const F=m.indexOf("--"),w=m.slice(F+1),E=Object.create(null);let y=[];F>-1&&w.length>0&&(m=m.slice(0,F),y=c._["--"],g=g.slice(0,-y.length||void 0)),yn(E,wn(m),g,h),F>-1&&w.length>0&&yn(E,wn(w),y,h),Object.assign(c._,E)}const D={...c,showVersion:d,showHelp:h},p={command:e,...D};if(typeof n=="function"){const m=n(D);if(m&&"then"in m)return Object.assign(Promise.resolve(m),p)}return p}o(En,"I"),B(En,"cliBase");function Si(e,t){const n=new Map;for(const r of t){const i=[r.options.name],{alias:s}=r.options;s&&(Array.isArray(s)?i.push(...s):i.push(s));for(const a of i){if(n.has(a))throw new Error(`Duplicate command name found: ${Q(a)}`);n.set(a,r)}}return n.get(e)}o(Si,"ce"),B(Si,"getCommand");function vi(e,t,n=process.argv.slice(2)){if(!e)throw new Error("Options is required");if("name"in e&&(!e.name||e.name!==e.name.trim()))throw new Error(`Invalid script name: ${Q(e.name)}`);const r=n[0];if(e.commands&&r&&bi(r)){const i=Si(r,e.commands);if(i)return En(i.options.name,{...i.options,parent:e},i.callback,n.slice(1))}return En(void 0,e,t,n)}o(vi,"fe"),B(vi,"cli");function bn(e,t){if(!e)throw new Error("Command options are required");const{name:n}=e;if(n===void 0)throw new Error("Command name is required");if(!bi(n))throw new Error(`Invalid command name ${JSON.stringify(n)}. Command names must be one word.`);return{options:e,callback:t}}o(bn,"de"),B(bn,"command");var Yl="2.81.0",Zl="Writes your git commit messages for you with AI",Cn={version:Yl,description:Zl};function Y(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}o(Y,"isPlainObject");const Sn=o((e,t)=>{const n=$i(Jl(e));if(typeof n!="string")throw new TypeError(`${t} must be a string or a file URL: ${n}.`);return n},"safeNormalizeFileUrl"),Jl=o(e=>Ai(e)?e.toString():e,"normalizeDenoExecPath"),Ai=o(e=>typeof e!="string"&&e&&Object.getPrototypeOf(e)===String.prototype,"isDenoExecPath"),$i=o(e=>e instanceof URL?Co(e):e,"normalizeFileUrl"),Bi=o((e,t=[],n={})=>{const r=Sn(e,"First argument"),[i,s]=Y(t)?[[],t]:[t,n];if(!Array.isArray(i))throw new TypeError(`Second argument must be either an array of arguments or an options object: ${i}`);if(i.some(c=>typeof c=="object"&&c!==null))throw new TypeError(`Second argument must be an array of strings: ${i}`);const a=i.map(String),u=a.find(c=>c.includes("\0"));if(u!==void 0)throw new TypeError(`Arguments cannot contain null bytes ("\\0"): ${u}`);if(!Y(s))throw new TypeError(`Last argument must be an options object: ${s}`);return[r,a,s]},"normalizeParameters"),{toString:Ti}=Object.prototype,Xl=o(e=>Ti.call(e)==="[object ArrayBuffer]","isArrayBuffer"),J=o(e=>Ti.call(e)==="[object Uint8Array]","isUint8Array"),qe=o(e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength),"bufferToUint8Array"),Ql=new TextEncoder,Ii=o(e=>Ql.encode(e),"stringToUint8Array"),ed=new TextDecoder,Oi=o(e=>ed.decode(e),"uint8ArrayToString"),td=o((e,t)=>nd(e,t).join(""),"joinToString"),nd=o((e,t)=>{if(t==="utf8"&&e.every(s=>typeof s=="string"))return e;const n=new vo(t),r=e.map(s=>typeof s=="string"?Ii(s):s).map(s=>n.write(s)),i=n.end();return i===""?r:[...r,i]},"uint8ArraysToStrings"),vn=o(e=>e.length===1&&J(e[0])?e[0]:Ri(rd(e)),"joinToUint8Array"),rd=o(e=>e.map(t=>typeof t=="string"?Ii(t):t),"stringsToUint8Arrays"),Ri=o(e=>{const t=new Uint8Array(od(e));let n=0;for(const r of e)t.set(r,n),n+=r.length;return t},"concatUint8Arrays"),od=o(e=>{let t=0;for(const n of e)t+=n.length;return t},"getJoinLength"),id=o(e=>Array.isArray(e)&&Array.isArray(e.raw),"isTemplateString"),sd=o((e,t)=>{let n=[];for(const[s,a]of e.entries())n=ad({templates:e,expressions:t,tokens:n,index:s,template:a});if(n.length===0)throw new TypeError("Template script must not be empty");const[r,...i]=n;return[r,i,{}]},"parseTemplates"),ad=o(({templates:e,expressions:t,tokens:n,index:r,template:i})=>{if(i===void 0)throw new TypeError(`Invalid backslash sequence: ${e.raw[r]}`);const{nextTokens:s,leadingWhitespaces:a,trailingWhitespaces:u}=ud(i,e.raw[r]),c=xi(n,s,a);if(r===t.length)return c;const d=t[r],l=Array.isArray(d)?d.map(f=>Mi(f)):[Mi(d)];return xi(c,l,u)},"parseTemplate"),ud=o((e,t)=>{if(t.length===0)return{nextTokens:[],leadingWhitespaces:!1,trailingWhitespaces:!1};const n=[];let r=0;const i=_i.has(t[0]);for(let a=0,u=0;a<e.length;a+=1,u+=1){const c=t[u];if(_i.has(c))r!==a&&n.push(e.slice(r,a)),r=a+1;else if(c==="\\"){const d=t[u+1];d===`
22
+ `),r(),process.exit(1);e[c]=d}}o(yn,"S"),B(yn,"mapParametersToArguments");function Ci(e){return e!==!1}o(Ci,"se"),B(Ci,"helpEnabled");const Hl=B(e=>{const t=[];for(const[n,r]of Object.entries(e))if(t.push(n),r&&typeof r=="object"&&"alias"in r){const{alias:i}=r;typeof i=="string"&&i?t.push(i):Array.isArray(i)&&t.push(...i.filter(Boolean))}return t},"getKnownFlagNames"),Kl=B((e,t)=>{if(e.length<3||t.length===0)return;const n=Nl(e,t);return li(e,n)<=2?n:void 0},"findClosestFlag"),ql=B((e,t)=>{const n=Object.keys(e);if(n.length!==0){for(const r of n){const i=Kl(r,t),s=i?` (Did you mean --${i}?)`:"";console.error(`Error: Unknown flag: --${r}.${s}`)}process.exit(1)}},"handleUnknownFlags");function En(e,t,n,r){const i={...t.flags},s=t.version&&!("version"in i);s&&(i.version={type:Boolean,description:"Show version"});const{help:a}=t,u=Ci(a);u&&!("help"in i)&&(i.help={type:Boolean,alias:"h",description:"Show help"});const c=ll(i,r,{ignore:t.ignoreArgv,booleanNegation:t.booleanFlagNegation??t.parent?.booleanFlagNegation}),d=B(()=>{console.log(t.version)},"showVersion");if(s&&c.flags.version===!0)return d(),process.exit(0);const l=new zl,f=u&&a?.render?a.render:m=>l.render(m),h=B(m=>{const g=Wl({...t,...m?{help:m}:{},flags:i});console.log(f(g,l))},"showHelp");if(u&&c.flags.help===!0)return h(),process.exit(0);if((t.strictFlags??t.parent?.strictFlags)&&ql(c.unknownFlags,Hl(i)),t.parameters){let{parameters:m}=t,g=c._;const F=m.indexOf("--"),w=m.slice(F+1),E=Object.create(null);let y=[];F>-1&&w.length>0&&(m=m.slice(0,F),y=c._["--"],g=g.slice(0,-y.length||void 0)),yn(E,wn(m),g,h),F>-1&&w.length>0&&yn(E,wn(w),y,h),Object.assign(c._,E)}const D={...c,showVersion:d,showHelp:h},p={command:e,...D};if(typeof n=="function"){const m=n(D);if(m&&"then"in m)return Object.assign(Promise.resolve(m),p)}return p}o(En,"I"),B(En,"cliBase");function Si(e,t){const n=new Map;for(const r of t){const i=[r.options.name],{alias:s}=r.options;s&&(Array.isArray(s)?i.push(...s):i.push(s));for(const a of i){if(n.has(a))throw new Error(`Duplicate command name found: ${Q(a)}`);n.set(a,r)}}return n.get(e)}o(Si,"ce"),B(Si,"getCommand");function vi(e,t,n=process.argv.slice(2)){if(!e)throw new Error("Options is required");if("name"in e&&(!e.name||e.name!==e.name.trim()))throw new Error(`Invalid script name: ${Q(e.name)}`);const r=n[0];if(e.commands&&r&&bi(r)){const i=Si(r,e.commands);if(i)return En(i.options.name,{...i.options,parent:e},i.callback,n.slice(1))}return En(void 0,e,t,n)}o(vi,"fe"),B(vi,"cli");function bn(e,t){if(!e)throw new Error("Command options are required");const{name:n}=e;if(n===void 0)throw new Error("Command name is required");if(!bi(n))throw new Error(`Invalid command name ${JSON.stringify(n)}. Command names must be one word.`);return{options:e,callback:t}}o(bn,"de"),B(bn,"command");var Yl="2.83.0",Zl="Writes your git commit messages for you with AI",Cn={version:Yl,description:Zl};function Y(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}o(Y,"isPlainObject");const Sn=o((e,t)=>{const n=$i(Jl(e));if(typeof n!="string")throw new TypeError(`${t} must be a string or a file URL: ${n}.`);return n},"safeNormalizeFileUrl"),Jl=o(e=>Ai(e)?e.toString():e,"normalizeDenoExecPath"),Ai=o(e=>typeof e!="string"&&e&&Object.getPrototypeOf(e)===String.prototype,"isDenoExecPath"),$i=o(e=>e instanceof URL?Co(e):e,"normalizeFileUrl"),Bi=o((e,t=[],n={})=>{const r=Sn(e,"First argument"),[i,s]=Y(t)?[[],t]:[t,n];if(!Array.isArray(i))throw new TypeError(`Second argument must be either an array of arguments or an options object: ${i}`);if(i.some(c=>typeof c=="object"&&c!==null))throw new TypeError(`Second argument must be an array of strings: ${i}`);const a=i.map(String),u=a.find(c=>c.includes("\0"));if(u!==void 0)throw new TypeError(`Arguments cannot contain null bytes ("\\0"): ${u}`);if(!Y(s))throw new TypeError(`Last argument must be an options object: ${s}`);return[r,a,s]},"normalizeParameters"),{toString:Ti}=Object.prototype,Xl=o(e=>Ti.call(e)==="[object ArrayBuffer]","isArrayBuffer"),J=o(e=>Ti.call(e)==="[object Uint8Array]","isUint8Array"),qe=o(e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength),"bufferToUint8Array"),Ql=new TextEncoder,Ii=o(e=>Ql.encode(e),"stringToUint8Array"),ed=new TextDecoder,Oi=o(e=>ed.decode(e),"uint8ArrayToString"),td=o((e,t)=>nd(e,t).join(""),"joinToString"),nd=o((e,t)=>{if(t==="utf8"&&e.every(s=>typeof s=="string"))return e;const n=new vo(t),r=e.map(s=>typeof s=="string"?Ii(s):s).map(s=>n.write(s)),i=n.end();return i===""?r:[...r,i]},"uint8ArraysToStrings"),vn=o(e=>e.length===1&&J(e[0])?e[0]:Ri(rd(e)),"joinToUint8Array"),rd=o(e=>e.map(t=>typeof t=="string"?Ii(t):t),"stringsToUint8Arrays"),Ri=o(e=>{const t=new Uint8Array(od(e));let n=0;for(const r of e)t.set(r,n),n+=r.length;return t},"concatUint8Arrays"),od=o(e=>{let t=0;for(const n of e)t+=n.length;return t},"getJoinLength"),id=o(e=>Array.isArray(e)&&Array.isArray(e.raw),"isTemplateString"),sd=o((e,t)=>{let n=[];for(const[s,a]of e.entries())n=ad({templates:e,expressions:t,tokens:n,index:s,template:a});if(n.length===0)throw new TypeError("Template script must not be empty");const[r,...i]=n;return[r,i,{}]},"parseTemplates"),ad=o(({templates:e,expressions:t,tokens:n,index:r,template:i})=>{if(i===void 0)throw new TypeError(`Invalid backslash sequence: ${e.raw[r]}`);const{nextTokens:s,leadingWhitespaces:a,trailingWhitespaces:u}=ud(i,e.raw[r]),c=xi(n,s,a);if(r===t.length)return c;const d=t[r],l=Array.isArray(d)?d.map(f=>Mi(f)):[Mi(d)];return xi(c,l,u)},"parseTemplate"),ud=o((e,t)=>{if(t.length===0)return{nextTokens:[],leadingWhitespaces:!1,trailingWhitespaces:!1};const n=[];let r=0;const i=_i.has(t[0]);for(let a=0,u=0;a<e.length;a+=1,u+=1){const c=t[u];if(_i.has(c))r!==a&&n.push(e.slice(r,a)),r=a+1;else if(c==="\\"){const d=t[u+1];d===`
23
23
  `?(a-=1,u+=1):d==="u"&&t[u+2]==="{"?u=t.indexOf("}",u+3):u+=cd[d]??1}}const s=r===e.length;return s||n.push(e.slice(r)),{nextTokens:n,leadingWhitespaces:i,trailingWhitespaces:s}},"splitByWhitespaces"),_i=new Set([" "," ","\r",`
24
24
  `]),cd={x:3,u:5},xi=o((e,t,n)=>n||e.length===0||t.length===0?[...e,...t]:[...e.slice(0,-1),`${e.at(-1)}${t[0]}`,...t.slice(1)],"concatTokens"),Mi=o(e=>{const t=typeof e;if(t==="string")return e;if(t==="number")return String(e);if(Y(e)&&("stdout"in e||"isMaxBuffer"in e))return ld(e);throw e instanceof So||Object.prototype.toString.call(e)==="[object Promise]"?new TypeError("Unexpected subprocess in template expression. Please use ${await subprocess} instead of ${subprocess}."):new TypeError(`Unexpected "${t}" in template expression`)},"parseExpression"),ld=o(({stdout:e})=>{if(typeof e=="string")return e;if(J(e))return Oi(e);throw e===void 0?new TypeError(`Missing result.stdout in template expression. This is probably due to the previous subprocess' "stdout" option.`):new TypeError(`Unexpected "${typeof e}" stdout in template expression`)},"getSubprocessResult"),Fe=o(e=>An.includes(e),"isStandardStream"),An=[O.stdin,O.stdout,O.stderr],ee=["stdin","stdout","stderr"],Pi=o(e=>ee[e]??`stdio[${e}]`,"getStreamName"),dd=o(e=>{const t={...e};for(const n of Ui)t[n]=Li(e,n);return t},"normalizeFdSpecificOptions"),Li=o((e,t)=>{const n=Array.from({length:fd(e)+1}),r=hd(e[t],n,t);return Fd(r,t)},"normalizeFdSpecificOption"),fd=o(({stdio:e})=>Array.isArray(e)?Math.max(e.length,ee.length):ee.length,"getStdioLength"),hd=o((e,t,n)=>Y(e)?Dd(e,t,n):t.fill(e),"normalizeFdSpecificValue"),Dd=o((e,t,n)=>{for(const r of Object.keys(e).sort(pd))for(const i of md(r,n,t))t[i]=e[r];return t},"normalizeOptionObject"),pd=o((e,t)=>Ni(e)<Ni(t)?1:-1,"compareFdName"),Ni=o(e=>e==="stdout"||e==="stderr"?0:e==="all"?2:1,"getFdNameOrder"),md=o((e,t,n)=>{if(e==="ipc")return[n.length-1];const r=ki(e);if(r===void 0||r===0)throw new TypeError(`"${t}.${e}" is invalid.
25
25
  It must be "${t}.stdout", "${t}.stderr", "${t}.all", "${t}.ipc", or "${t}.fd3", "${t}.fd4" (and so on).`);if(r>=n.length)throw new TypeError(`"${t}.${e}" is invalid: that file descriptor does not exist.
@@ -74,57 +74,58 @@ Instead, \`yield\` should either be called with a value, or not be called at all
74
74
  `).length-1;this.output.write(U.cursor.move(-999,t*-1))}render(){const t=ze(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(U.cursor.hide);else{const n=oF(this._prevFrame,t),r=nc(this.output);if(this.restoreCursor(),n){const i=Math.max(0,n.numLinesAfter-r),s=Math.max(0,n.numLinesBefore-r);let a=n.lines.find(u=>u>=i);if(a===void 0){this._prevFrame=t;return}if(n.lines.length===1){this.output.write(U.cursor.move(0,a-s)),this.output.write(U.erase.lines(1));const u=t.split(`
75
75
  `);this.output.write(u[a]),this._prevFrame=t,this.output.write(U.cursor.move(0,u.length-a-1));return}else if(n.lines.length>1){if(i<s)a=i;else{const c=a-s;c>0&&this.output.write(U.cursor.move(0,c))}this.output.write(U.erase.down());const u=t.split(`
76
76
  `).slice(a);this.output.write(u.join(`
77
- `)),this._prevFrame=t;return}}this.output.write(U.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}};o(wo,"V");let Qt=wo;const yo=class yo extends Qt{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",n=>{this.output.write(U.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};o(yo,"r");let Yr=yo;const Eo=class Eo extends Qt{constructor(t){super(t,!1),j(this,"options"),j(this,"cursor",0),this.options=t.options;const n=this.options.findIndex(({value:i})=>i===t.initialValue),r=n===-1?0:n;this.cursor=this.options[r].disabled?Zt(r,1,this.options):r,this.changeValue(),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=Zt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Zt(this.cursor,1,this.options);break}this.changeValue()})}get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}};o(Eo,"a2");let Zr=Eo;function uF(){return O.platform!=="win32"?O.env.TERM!=="linux":!!O.env.CI||!!O.env.WT_SESSION||!!O.env.TERMINUS_SUBLIME||O.env.ConEmuTask==="{cmd::Cmder}"||O.env.TERM_PROGRAM==="Terminus-Sublime"||O.env.TERM_PROGRAM==="vscode"||O.env.TERM==="xterm-256color"||O.env.TERM==="alacritty"||O.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}o(uF,"isUnicodeSupported");const Jr=uF(),cF=o(()=>process.env.CI==="true","isCI"),ue=o((e,t)=>Jr?e:t,"unicodeOr"),lF=ue("\u25C6","*"),rc=ue("\u25A0","x"),oc=ue("\u25B2","x"),ic=ue("\u25C7","o"),dF=ue("\u250C","T"),k=ue("\u2502","|"),Xr=ue("\u2514","\u2014"),Qr=ue("\u25CF",">"),en=ue("\u25CB"," "),sc=o(e=>{switch(e){case"initial":case"active":return C("cyan",lF);case"cancel":return C("red",rc);case"error":return C("yellow",oc);case"submit":return C("green",ic)}},"symbol"),fF=o(e=>{switch(e){case"initial":case"active":return C("cyan",k);case"cancel":return C("red",k);case"error":return C("yellow",k);case"submit":return C("green",k)}},"symbolBar"),ac=o((e,t,n,r,i,s=!1)=>{let a=t,u=0;if(s)for(let c=r-1;c>=n&&(a-=e[c].length,u++,!(a<=i));c--);else for(let c=n;c<r&&(a-=e[c].length,u++,!(a<=i));c++);return{lineCount:a,removals:u}},"E$1"),hF=o(({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:a=4})=>{const u=qr(r)-s,c=nc(r),d=C("dim","..."),l=Math.max(c-a,0),f=Math.max(Math.min(i,l),5);let h=0;e>=f-3&&(h=Math.max(Math.min(e-f+3,t.length-f),0));let D=f<t.length&&h>0,p=f<t.length&&h+f<t.length;const m=Math.min(h+f,t.length),g=[];let F=0;D&&F++,p&&F++;const w=h+(D?1:0),E=m-(p?1:0);for(let b=w;b<E;b++){const S=ze(n(t[b],b===e),u,{hard:!0,trim:!1}).split(`
78
- `);g.push(S),F+=S.length}if(F>l){let b=0,S=0,$=F;const T=e-w;let I=l;const G=o(()=>ac(g,$,0,T,I),"T"),L=o(()=>ac(g,$,T+1,g.length,I,!0),"L");D?({lineCount:$,removals:b}=G(),$>I&&(p||(I-=1),{lineCount:$,removals:S}=L())):(p||(I-=1),{lineCount:$,removals:S}=L(),$>I&&(I-=1,{lineCount:$,removals:b}=G())),b>0&&(D=!0,g.splice(0,b)),S>0&&(p=!0,g.splice(g.length-S,S))}const y=[];D&&y.push(d);for(const b of g)for(const S of b)y.push(S);return p&&y.push(d),y},"limitOptions"),DF=o(e=>{const t=e.active??"Yes",n=e.inactive??"No";return new Yr({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){const r=e.withGuide??ae.withGuide,i=`${sc(this.state)} `,s=r?`${C("gray",k)} `:"",a=Xt(e.output,e.message,s,i),u=`${r?`${C("gray",k)}
77
+ `)),this._prevFrame=t;return}}this.output.write(U.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}};o(wo,"V");let Qt=wo;const yo=class yo extends Qt{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",n=>{this.output.write(U.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};o(yo,"r");let Yr=yo;const Eo=class Eo extends Qt{constructor(t){super(t,!1),j(this,"options"),j(this,"cursor",0),this.options=t.options;const n=this.options.findIndex(({value:i})=>i===t.initialValue),r=n===-1?0:n;this.cursor=this.options[r].disabled?Zt(r,1,this.options):r,this.changeValue(),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=Zt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Zt(this.cursor,1,this.options);break}this.changeValue()})}get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}};o(Eo,"a2");let Zr=Eo;function uF(){return O.platform!=="win32"?O.env.TERM!=="linux":!!O.env.CI||!!O.env.WT_SESSION||!!O.env.TERMINUS_SUBLIME||O.env.ConEmuTask==="{cmd::Cmder}"||O.env.TERM_PROGRAM==="Terminus-Sublime"||O.env.TERM_PROGRAM==="vscode"||O.env.TERM==="xterm-256color"||O.env.TERM==="alacritty"||O.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}o(uF,"isUnicodeSupported");const Jr=uF(),cF=o(()=>process.env.CI==="true","isCI"),ue=o((e,t)=>Jr?e:t,"unicodeOr"),lF=ue("\u25C6","*"),rc=ue("\u25A0","x"),oc=ue("\u25B2","x"),ic=ue("\u25C7","o"),dF=ue("\u250C","T"),k=ue("\u2502","|"),Xr=ue("\u2514","\u2014"),Qr=ue("\u25CF",">"),en=ue("\u25CB"," "),sc=o(e=>{switch(e){case"initial":case"active":return C("cyan",lF);case"cancel":return C("red",rc);case"error":return C("yellow",oc);case"submit":return C("green",ic)}},"symbol"),fF=o(e=>{switch(e){case"initial":case"active":return C("cyan",k);case"cancel":return C("red",k);case"error":return C("yellow",k);case"submit":return C("green",k)}},"symbolBar");function hF(e,t){const n=[`${t?`${C("cyan",k)} `:""}${e.join(" \u2022 ")}`];return t&&n.push(C("cyan",Xr)),n}o(hF,"formatInstructionFooter");const ac=o((e,t,n,r,i,s=!1)=>{let a=t,u=0;if(s)for(let c=r-1;c>=n&&(a-=e[c].length,u++,!(a<=i));c--);else for(let c=n;c<r&&(a-=e[c].length,u++,!(a<=i));c++);return{lineCount:a,removals:u}},"E$1"),DF=o(({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:a=4})=>{const u=qr(r)-s,c=nc(r),d=C("dim","..."),l=Math.max(c-a,0),f=Math.max(Math.min(i,l),5);let h=0;e>=f-3&&(h=Math.max(Math.min(e-f+3,t.length-f),0));let D=f<t.length&&h>0,p=f<t.length&&h+f<t.length;const m=Math.min(h+f,t.length),g=[];let F=0;D&&F++,p&&F++;const w=h+(D?1:0),E=m-(p?1:0);for(let b=w;b<E;b++){const S=ze(n(t[b],b===e),u,{hard:!0,trim:!1}).split(`
78
+ `);g.push(S),F+=S.length}if(F>l){let b=0,S=0,$=F;const T=e-w;let I=l;const G=o(()=>ac(g,$,0,T,I),"T"),L=o(()=>ac(g,$,T+1,g.length,I,!0),"L");D?({lineCount:$,removals:b}=G(),$>I&&(p||(I-=1),{lineCount:$,removals:S}=L())):(p||(I-=1),{lineCount:$,removals:S}=L(),$>I&&(I-=1,{lineCount:$,removals:b}=G())),b>0&&(D=!0,g.splice(0,b)),S>0&&(p=!0,g.splice(g.length-S,S))}const y=[];D&&y.push(d);for(const b of g)for(const S of b)y.push(S);return p&&y.push(d),y},"limitOptions"),pF=o(e=>{const t=e.active??"Yes",n=e.inactive??"No";return new Yr({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){const r=e.withGuide??ae.withGuide,i=`${sc(this.state)} `,s=r?`${C("gray",k)} `:"",a=Xt(e.output,e.message,s,i),u=`${r?`${C("gray",k)}
79
79
  `:""}${a}
80
80
  `,c=this.value?t:n;switch(this.state){case"submit":{const d=r?`${C("gray",k)} `:"";return`${u}${d}${C("dim",c)}`}case"cancel":{const d=r?`${C("gray",k)} `:"";return`${u}${d}${C(["strikethrough","dim"],c)}${r?`
81
81
  ${C("gray",k)}`:""}`}default:{const d=r?`${C("cyan",k)} `:"",l=r?C("cyan",Xr):"";return`${u}${d}${this.value?`${C("green",Qr)} ${t}`:`${C("dim",en)} ${C("dim",t)}`}${e.vertical?r?`
82
82
  ${C("cyan",k)} `:`
83
83
  `:` ${C("dim","/")} `}${this.value?`${C("dim",en)} ${C("dim",n)}`:`${C("green",Qr)} ${n}`}
84
84
  ${l}
85
- `}}}}).prompt()},"confirm"),uc=o((e="",t)=>{const n=process.stdout,r=`${C("gray",dF)} `;n.write(`${r}${e}
85
+ `}}}}).prompt()},"confirm");`${C("dim","\u2191/\u2193")}`,`${C("dim","Space:")}`,`${C("dim","Enter:")}`;const uc=o((e="",t)=>{const n=process.stdout,r=`${C("gray",dF)} `;n.write(`${r}${e}
86
86
  `)},"intro"),Oe=o((e="",t)=>{const n=process.stdout,r=`${C("gray",k)}
87
87
  ${C("gray",Xr)} `;n.write(`${r}${e}
88
88
 
89
- `)},"outro"),pF=o(e=>C("magenta",e),"W"),eo=o(({indicator:e="dots",onCancel:t,output:n=process.stdout,cancelMessage:r,errorMessage:i,frames:s=Jr?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:a=Jr?80:120,signal:u,...c}={})=>{const d=cF();let l,f,h=!1,D=!1,p="",m,g=performance.now();const F=qr(n),w=c?.styleFrame??pF,E=o(P=>{const q=P>1?i??ae.messages.error:r??ae.messages.cancel;D=P===1,h&&(Ke(q,P),D&&typeof t=="function"&&t())},"g"),y=o(()=>E(2),"f"),b=o(()=>E(1),"i2"),S=o(()=>{process.on("uncaughtExceptionMonitor",y),process.on("unhandledRejection",y),process.on("SIGINT",b),process.on("SIGTERM",b),process.on("exit",E),u&&u.addEventListener("abort",b)},"A2"),$=o(()=>{process.removeListener("uncaughtExceptionMonitor",y),process.removeListener("unhandledRejection",y),process.removeListener("SIGINT",b),process.removeListener("SIGTERM",b),process.removeListener("exit",E),u&&u.removeEventListener("abort",b)},"H"),T=o(()=>{if(m===void 0)return;d&&n.write(`
89
+ `)},"outro"),mF=o(e=>C("magenta",e),"W"),eo=o(({indicator:e="dots",onCancel:t,output:n=process.stdout,cancelMessage:r,errorMessage:i,frames:s=Jr?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:a=Jr?80:120,signal:u,...c}={})=>{const d=cF();let l,f,h=!1,D=!1,p="",m,g=performance.now();const F=qr(n),w=c?.styleFrame??mF,E=o(P=>{const q=P>1?i??ae.messages.error:r??ae.messages.cancel;D=P===1,h&&(Ke(q,P),D&&typeof t=="function"&&t())},"g"),y=o(()=>E(2),"f"),b=o(()=>E(1),"i2"),S=o(()=>{process.on("uncaughtExceptionMonitor",y),process.on("unhandledRejection",y),process.on("SIGINT",b),process.on("SIGTERM",b),process.on("exit",E),u&&u.addEventListener("abort",b)},"A2"),$=o(()=>{process.removeListener("uncaughtExceptionMonitor",y),process.removeListener("unhandledRejection",y),process.removeListener("SIGINT",b),process.removeListener("SIGTERM",b),process.removeListener("exit",E),u&&u.removeEventListener("abort",b)},"H"),T=o(()=>{if(m===void 0)return;d&&n.write(`
90
90
  `);const P=ze(m,F,{hard:!0,trim:!1}).split(`
91
91
  `);P.length>1&&n.write(U.cursor.up(P.length-1)),n.write(U.cursor.to(0)),n.write(U.erase.down())},"y"),I=o(P=>P.replace(/\.+$/,""),"C2"),G=o(P=>{const q=(performance.now()-P)/1e3,re=Math.floor(q/60),oe=Math.floor(q%60);return re>0?`[${re}m ${oe}s]`:`[${oe}s]`},"_"),L=c.withGuide??ae.withGuide,ht=o((P="")=>{h=!0,l=sF({output:n}),p=I(P),g=performance.now(),L&&n.write(`${C("gray",k)}
92
92
  `);let q=0,re=0;S(),f=setInterval(()=>{if(d&&p===m)return;T(),m=p;const oe=w(s[q]);let Dt;if(d)Dt=`${oe} ${p}...`;else if(e==="timer")Dt=`${oe} ${p} ${G(g)}`;else{const vc=".".repeat(Math.floor(re)).slice(0,3);Dt=`${oe} ${p}${vc}`}const Sc=ze(Dt,F,{hard:!0,trim:!1});n.write(Sc),q=q+1<s.length?q+1:0,re=re<4?re+.125:0},a)},"P2"),Ke=o((P="",q=0,re=!1)=>{if(!h)return;h=!1,clearInterval(f),T();const oe=q===0?C("green",ic):q===1?C("red",rc):C("red",oc);p=P??p,re||(e==="timer"?n.write(`${oe} ${p} ${G(g)}
93
93
  `):n.write(`${oe} ${p}
94
- `)),$(),l()},"a");return{start:ht,stop:o((P="")=>Ke(P,0),"stop"),message:o((P="")=>{p=I(P??p)},"message"),cancel:o((P="")=>Ke(P,1),"cancel"),error:o((P="")=>Ke(P,2),"error"),clear:o(()=>Ke("",0,!0),"clear"),get isCancelled(){return D}}},"spinner"),tn=o((e,t)=>e.includes(`
94
+ `)),$(),l()},"a");return{start:ht,stop:o((P="")=>Ke(P,0),"stop"),message:o((P="")=>{p=I(P??p)},"message"),cancel:o((P="")=>Ke(P,1),"cancel"),error:o((P="")=>Ke(P,2),"error"),clear:o(()=>Ke("",0,!0),"clear"),get isCancelled(){return D}}},"spinner"),gF=[`${C("dim","\u2191/\u2193")} to navigate`,`${C("dim","Enter:")} confirm`],tn=o((e,t)=>e.includes(`
95
95
  `)?e.split(`
96
96
  `).map(n=>t(n)).join(`
97
- `):t(e),"c"),mF=o(e=>{const t=o((n,r)=>{const i=n.label??String(n.value);switch(r){case"disabled":return`${C("gray",en)} ${tn(i,s=>C("gray",s))}${n.hint?` ${C("dim",`(${n.hint??"disabled"})`)}`:""}`;case"selected":return`${tn(i,s=>C("dim",s))}`;case"active":return`${C("green",Qr)} ${i}${n.hint?` ${C("dim",`(${n.hint})`)}`:""}`;case"cancelled":return`${tn(i,s=>C(["strikethrough","dim"],s))}`;default:return`${C("dim",en)} ${tn(i,s=>C("dim",s))}`}},"a");return new Zr({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){const n=e.withGuide??ae.withGuide,r=`${sc(this.state)} `,i=`${fF(this.state)} `,s=Xt(e.output,e.message,i,r),a=`${n?`${C("gray",k)}
97
+ `):t(e),"c"),FF=o(e=>{const t=o((n,r)=>{const i=n.label??String(n.value);switch(r){case"disabled":return`${C("gray",en)} ${tn(i,s=>C("gray",s))}${n.hint?` ${C("dim",`(${n.hint??"disabled"})`)}`:""}`;case"selected":return`${tn(i,s=>C("dim",s))}`;case"active":return`${C("green",Qr)} ${i}${n.hint?` ${C("dim",`(${n.hint})`)}`:""}`;case"cancelled":return`${tn(i,s=>C(["strikethrough","dim"],s))}`;default:return`${C("dim",en)} ${tn(i,s=>C("dim",s))}`}},"a");return new Zr({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){const n=e.withGuide??ae.withGuide,r=`${sc(this.state)} `,i=`${fF(this.state)} `,s=Xt(e.output,e.message,i,r),a=`${n?`${C("gray",k)}
98
98
  `:""}${s}
99
99
  `;switch(this.state){case"submit":{const u=n?`${C("gray",k)} `:"",c=Xt(e.output,t(this.options[this.cursor],"selected"),u);return`${a}${c}`}case"cancel":{const u=n?`${C("gray",k)} `:"",c=Xt(e.output,t(this.options[this.cursor],"cancelled"),u);return`${a}${c}${n?`
100
- ${C("gray",k)}`:""}`}default:{const u=n?`${C("cyan",k)} `:"",c=n?C("cyan",Xr):"",d=a.split(`
101
- `).length,l=n?2:1;return`${a}${u}${hF({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:u.length,rowPadding:d+l,style:o((f,h)=>t(f,f.disabled?"disabled":h?"active":"inactive"),"style")}).join(`
100
+ ${C("gray",k)}`:""}`}default:{const u=n?`${C("cyan",k)} `:"",c=a.split(`
101
+ `).length,d=hF(gF,n),l=d.join(`
102
+ `),f=d.length+1;return`${a}${u}${DF({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:u.length,rowPadding:c+f,style:o((h,D)=>t(h,h.disabled?"disabled":D?"active":"inactive"),"style")}).join(`
102
103
  ${u}`)}
103
- ${c}
104
+ ${l}
104
105
  `}}}}).prompt()},"select");`${C("gray",k)}`;const bo=class bo extends Error{};o(bo,"KnownError");let R=bo;const to=" ",nn=o(e=>{e instanceof Error&&!(e instanceof R)&&(e.stack&&console.error(jr(e.stack.split(`
105
106
  `).slice(1).join(`
106
107
  `))),console.error(`
107
108
  ${to}${jr(`aicommit v${Cn.version}`)}`),console.error(`
108
109
  ${to}Please open a Bug report with the information above:`),console.error(`${to}https://github.com/NegoZiatoR/ai-commit/issues/new/choose`))},"handleCliError"),no=o(async()=>{const{stdout:e,failed:t}=await We("git",["rev-parse","--show-toplevel"],{reject:!1});if(t)throw new R("The current directory must be a Git repository!");return e},"assertGitRepo"),ro=o(e=>`:(exclude)${e}`,"excludeFromDiff"),cc=["package-lock.json","*.lock"].map(ro),lc=o(async e=>{const t=["diff","--cached","--diff-algorithm=minimal"],{stdout:n}=await We("git",[...t,"--name-only",...cc,...e?e.map(ro):[]]);if(!n)return;const{stdout:r}=await We("git",[...t,...cc,...e?e.map(ro):[]]);return{files:n.split(`
109
- `),diff:r}},"getStagedDiff"),gF=o(e=>`Detected ${e.length.toLocaleString()} staged file${e.length>1?"s":""}`,"getDetectedMessage");var oo,dc;function FF(){if(dc)return oo;dc=1;const{hasOwnProperty:e}=Object.prototype,t=o((u,c={})=>{typeof c=="string"&&(c={section:c}),c.align=c.align===!0,c.newline=c.newline===!0,c.sort=c.sort===!0,c.whitespace=c.whitespace===!0||c.align===!0,c.platform=c.platform||typeof process<"u"&&process.platform,c.bracketedArray=c.bracketedArray!==!1;const d=c.platform==="win32"?`\r
110
+ `),diff:r}},"getStagedDiff"),wF=o(e=>`Detected ${e.length.toLocaleString()} staged file${e.length>1?"s":""}`,"getDetectedMessage");var oo,dc;function yF(){if(dc)return oo;dc=1;const{hasOwnProperty:e}=Object.prototype,t=o((u,c={})=>{typeof c=="string"&&(c={section:c}),c.align=c.align===!0,c.newline=c.newline===!0,c.sort=c.sort===!0,c.whitespace=c.whitespace===!0||c.align===!0,c.platform=c.platform||typeof process<"u"&&process.platform,c.bracketedArray=c.bracketedArray!==!1;const d=c.platform==="win32"?`\r
110
111
  `:`
111
- `,l=c.whitespace?" = ":"=",f=[],h=c.sort?Object.keys(u).sort():Object.keys(u);let D=0;c.align&&(D=s(h.filter(g=>u[g]===null||Array.isArray(u[g])||typeof u[g]!="object").map(g=>Array.isArray(u[g])?`${g}[]`:g).concat([""]).reduce((g,F)=>s(g).length>=s(F).length?g:F)).length);let p="";const m=c.bracketedArray?"[]":"";for(const g of h){const F=u[g];if(F&&Array.isArray(F))for(const w of F)p+=s(`${g}${m}`).padEnd(D," ")+l+s(w)+d;else F&&typeof F=="object"?f.push(g):p+=s(g).padEnd(D," ")+l+s(F)+d}c.section&&p.length&&(p="["+s(c.section)+"]"+(c.newline?d+d:d)+p);for(const g of f){const F=n(g,".").join("\\."),w=(c.section?c.section+".":"")+F,E=t(u[g],{...c,section:w});p.length&&E.length&&(p+=d),p+=E}return p},"encode");function n(u,c){var d=0,l=0,f=0,h=[];do if(f=u.indexOf(c,d),f!==-1){if(d=f+c.length,f>0&&u[f-1]==="\\")continue;h.push(u.slice(l,f)),l=f+c.length}while(f!==-1);return h.push(u.slice(l)),h}o(n,"splitSections");const r=o((u,c={})=>{c.bracketedArray=c.bracketedArray!==!1;const d=Object.create(null);let l=d,f=null;const h=/^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i,D=u.split(/[\r\n]+/g),p={};for(const g of D){if(!g||g.match(/^\s*[;#]/)||g.match(/^\s*$/))continue;const F=g.match(h);if(!F)continue;if(F[1]!==void 0){if(f=a(F[1]),f==="__proto__"){l=Object.create(null);continue}l=d[f]=d[f]||Object.create(null);continue}const w=a(F[2]);let E;c.bracketedArray?E=w.length>2&&w.slice(-2)==="[]":(p[w]=(p?.[w]||0)+1,E=p[w]>1);const y=E&&w.endsWith("[]")?w.slice(0,-2):w;if(y==="__proto__")continue;const b=F[3]?a(F[4]):!0,S=b==="true"||b==="false"||b==="null"?JSON.parse(b):b;E&&(e.call(l,y)?Array.isArray(l[y])||(l[y]=[l[y]]):l[y]=[]),Array.isArray(l[y])?l[y].push(S):l[y]=S}const m=[];for(const g of Object.keys(d)){if(!e.call(d,g)||typeof d[g]!="object"||Array.isArray(d[g]))continue;const F=n(g,".");l=d;const w=F.pop(),E=w.replace(/\\\./g,".");for(const y of F)y!=="__proto__"&&((!e.call(l,y)||typeof l[y]!="object")&&(l[y]=Object.create(null)),l=l[y]);l===d&&E===w||(l[E]=d[g],m.push(g))}for(const g of m)delete d[g];return d},"decode"),i=o(u=>u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"),"isQuoted"),s=o(u=>typeof u!="string"||u.match(/[=\r\n]/)||u.match(/^\[/)||u.length>1&&i(u)||u!==u.trim()?JSON.stringify(u):u.split(";").join("\\;").split("#").join("\\#"),"safe"),a=o(u=>{if(u=(u||"").trim(),i(u)){u.charAt(0)==="'"&&(u=u.slice(1,-1));try{u=JSON.parse(u)}catch{}}else{let c=!1,d="";for(let l=0,f=u.length;l<f;l++){const h=u.charAt(l);if(c)"\\;#".indexOf(h)!==-1?d+=h:d+="\\"+h,c=!1;else{if(";#".indexOf(h)!==-1)break;h==="\\"?c=!0:d+=h}}return c&&(d+="\\"),d.trim()}return u},"unsafe");return oo={parse:r,decode:r,stringify:t,encode:t,safe:s,unsafe:a},oo}o(FF,"requireIni");var wF=FF(),fc=Yi(wF);const rn=o(e=>W.lstat(e).then(()=>!0,()=>!1),"fileExists"),io=o(async e=>{try{let t;try{t=e||await no()}catch(a){if(a instanceof R&&a.message.includes("Git repository"))return;throw a}const n=ce.join(t,".ai-commit.json");if(!await rn(n))return;const i=await W.readFile(n,"utf8");return JSON.parse(i)}catch(t){if(t instanceof R)throw t;return}},"getProjectConfig");function yF(e){const t={},n=e.split(`
112
- `);for(const r of n){const i=r.trim();if(!i||i.startsWith("#"))continue;const s=i.match(/^([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);if(!s)continue;const[,a,u]=s;let c=u.trim();(c.startsWith('"')&&c.endsWith('"')||c.startsWith("'")&&c.endsWith("'"))&&(c=c.slice(1,-1)),t[a]=c}return t}o(yF,"parseEnvContent");async function hc(e){const{filename:t=".env",directory:n=process.cwd(),override:r=!1}=e||{},i=ce.join(n,t);if(!await rn(i))return{};try{const a=await W.readFile(i,"utf8"),u=yF(a);for(const[c,d]of Object.entries(u))(r||process.env[c]===void 0)&&(process.env[c]=d);return u}catch{return{}}}o(hc,"loadEnvFile");async function EF(){process.env.NODE_ENV==="test"?await hc({filename:".env.local"}):await hc({filename:".env"})}o(EF,"loadEnvironment");const Dc=["openai","anthropic","azure-openai","ollama","custom"],bF=["","conventional"],{hasOwnProperty:CF}=Object.prototype,pc=o((e,t)=>CF.call(e,t),"hasOwn"),_=o((e,t,n)=>{if(!t)throw new R(`Invalid config property ${e}: ${n}`)},"parseAssert"),on={provider(e){return e?(_("provider",Dc.includes(e),`Must be one of: ${Dc.join(", ")}`),e):"openai"},OPENAI_KEY(e){if(e)return _("OPENAI_KEY",e.startsWith("sk-"),'Must start with "sk-"'),e},ANTHROPIC_KEY(e){if(e)return _("ANTHROPIC_KEY",e.startsWith("sk-ant-"),'Must start with "sk-ant-"'),e},AZURE_OPENAI_KEY(e){return e},AZURE_ENDPOINT(e){if(e)return _("AZURE_ENDPOINT",/^https?:\/\//.test(e),"Must be a valid URL"),e},OLLAMA_ENDPOINT(e){return e?(_("OLLAMA_ENDPOINT",/^https?:\/\//.test(e),"Must be a valid URL"),e):"http://localhost:11434"},CUSTOM_ENDPOINT(e){if(e)return _("CUSTOM_ENDPOINT",/^https?:\/\//.test(e),"Must be a valid URL"),e},CUSTOM_KEY(e){return e},locale(e){return e?(_("locale",e,"Cannot be empty"),_("locale",/^[a-z-]+$/i.test(e),"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"),e):"en"},generate(e){if(!e)return 1;_("generate",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return _("generate",t>0,"Must be greater than 0"),_("generate",t<=5,"Must be less or equal to 5"),t},type(e){return e?(_("type",bF.includes(e),"Invalid commit type"),e):""},proxy(e){if(!(!e||e.length===0))return _("proxy",/^https?:\/\//.test(e),"Must be a valid URL"),e},model(e){return!e||e.length===0?"gpt-4o-mini":e},timeout(e){if(!e)return 1e4;_("timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return _("timeout",t>=500,"Must be greater than 500ms"),t},temperature(e){if(!e)return .2;_("temperature",/^(2|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 2");const t=Number(e);return _("temperature",t>0,"Must be greater than 0"),_("temperature",t<=2,"Must be less than or equal to 2"),t},"max-length"(e){if(!e)return 50;_("max-length",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return _("max-length",t>=20,"Must be greater than 20 characters"),t},"max-completion-tokens"(e){if(!e)return 1e4;_("max-completion-tokens",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return _("max-completion-tokens",t>0,"Must be greater than 0"),t},"auto-confirm"(e){return e?typeof e=="boolean"?e:(_("auto-confirm",/^(?:true|false)$/.test(e),"Must be a boolean"),e==="true"):!1},"prepend-reference"(e){return e?typeof e=="boolean"?e:(_("prepend-reference",/^(?:true|false)$/.test(e),"Must be a boolean"),e==="true"):!1},signoff(e){return e?typeof e=="boolean"?e:(_("signoff",/^(?:true|false)$/.test(e),"Must be a boolean"),e==="true"):!1}},so=ce.join(Kc.homedir(),".aicommit"),mc=o(async()=>{if(!await rn(so))return Object.create(null);const t=await W.readFile(so,"utf8");return fc.parse(t)},"readConfigFile"),SF=o(e=>{const t=e.provider;switch(t){case"openai":if(!e.OPENAI_KEY)throw new R("Please set your OpenAI API key via `aicommit config set OPENAI_KEY=<your token>`");break;case"anthropic":if(!e.ANTHROPIC_KEY)throw new R("Please set your Anthropic API key via `aicommit config set ANTHROPIC_KEY=<your token>`\nGet your API key from: https://console.anthropic.com/");break;case"azure-openai":if(!e.AZURE_OPENAI_KEY)throw new R("Please set your Azure OpenAI API key via `aicommit config set AZURE_OPENAI_KEY=<your token>`");if(!e.AZURE_ENDPOINT)throw new R("Please set your Azure OpenAI endpoint via `aicommit config set AZURE_ENDPOINT=<your endpoint>`");break;case"ollama":break;case"custom":if(!e.CUSTOM_ENDPOINT)throw new R("Please set your custom endpoint via `aicommit config set CUSTOM_ENDPOINT=<your endpoint>`");break;default:throw new R(`Unknown provider: ${t}`)}},"validateProviderConfig"),ao=o(async(e,t)=>{await EF();const n=await mc(),r=await io(),i={};for(const a of Object.keys(on)){const u=on[a];let c=r?.[a]??e?.[a]??process.env[a]??n[a];if(typeof c=="boolean"&&(c=c.toString()),t)try{i[a]=u(c)}catch{}else i[a]=u(c)}const s=i;return t||SF(s),s},"getConfig"),vF=o(async e=>{const t=await mc();for(const[n,r]of e){if(!pc(on,n))throw new R(`Invalid config property: ${n}`);const i=on[n](r);t[n]=i}await W.writeFile(so,fc.stringify(t),"utf8")},"setConfigs"),gc={openai:o(()=>import("./openai-BsbE56tI.mjs"),"openai"),anthropic:o(()=>import("./anthropic-DD9wAiLK.mjs"),"anthropic"),"azure-openai":o(()=>import("./azure-openai-DYjwU8hD.mjs"),"azure-openai"),ollama:o(()=>import("./ollama-7WRtzG8h.mjs"),"ollama"),custom:o(()=>import("./custom-BqrMrbwo.mjs"),"custom")};async function Fc(e,t){const n=gc[e];if(!n)throw new R(`Unknown provider type: ${e}. Supported providers: ${Object.keys(gc).join(", ")}`);try{const i=(await n()).default;return new i(t)}catch(r){throw r instanceof R?r:r.code==="ERR_MODULE_NOT_FOUND"?new R(`Provider "${e}" is not yet implemented. Currently supported: openai`):new R(`Failed to initialize provider "${e}": ${r.message}`)}}o(Fc,"createProvider");var AF=o(async(e,t,n,r,i)=>(async()=>{uc(Gu(Wu(" aicommit "))),await no();const s=eo();n&&await We("git",["add","--update"]),s.start("Detecting staged files");const a=await lc(t);if(!a)throw s.stop("Detecting staged files"),new R("No staged changes found. Stage your changes manually, or automatically stage all changes with the `--all` flag.");s.stop(`${gF(a.files)}:
112
+ `,l=c.whitespace?" = ":"=",f=[],h=c.sort?Object.keys(u).sort():Object.keys(u);let D=0;c.align&&(D=s(h.filter(g=>u[g]===null||Array.isArray(u[g])||typeof u[g]!="object").map(g=>Array.isArray(u[g])?`${g}[]`:g).concat([""]).reduce((g,F)=>s(g).length>=s(F).length?g:F)).length);let p="";const m=c.bracketedArray?"[]":"";for(const g of h){const F=u[g];if(F&&Array.isArray(F))for(const w of F)p+=s(`${g}${m}`).padEnd(D," ")+l+s(w)+d;else F&&typeof F=="object"?f.push(g):p+=s(g).padEnd(D," ")+l+s(F)+d}c.section&&p.length&&(p="["+s(c.section)+"]"+(c.newline?d+d:d)+p);for(const g of f){const F=n(g,".").join("\\."),w=(c.section?c.section+".":"")+F,E=t(u[g],{...c,section:w});p.length&&E.length&&(p+=d),p+=E}return p},"encode");function n(u,c){var d=0,l=0,f=0,h=[];do if(f=u.indexOf(c,d),f!==-1){if(d=f+c.length,f>0&&u[f-1]==="\\")continue;h.push(u.slice(l,f)),l=f+c.length}while(f!==-1);return h.push(u.slice(l)),h}o(n,"splitSections");const r=o((u,c={})=>{c.bracketedArray=c.bracketedArray!==!1;const d=Object.create(null);let l=d,f=null;const h=/^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i,D=u.split(/[\r\n]+/g),p={};for(const g of D){if(!g||g.match(/^\s*[;#]/)||g.match(/^\s*$/))continue;const F=g.match(h);if(!F)continue;if(F[1]!==void 0){if(f=a(F[1]),f==="__proto__"){l=Object.create(null);continue}l=d[f]=d[f]||Object.create(null);continue}const w=a(F[2]);let E;c.bracketedArray?E=w.length>2&&w.slice(-2)==="[]":(p[w]=(p?.[w]||0)+1,E=p[w]>1);const y=E&&w.endsWith("[]")?w.slice(0,-2):w;if(y==="__proto__")continue;const b=F[3]?a(F[4]):!0,S=b==="true"||b==="false"||b==="null"?JSON.parse(b):b;E&&(e.call(l,y)?Array.isArray(l[y])||(l[y]=[l[y]]):l[y]=[]),Array.isArray(l[y])?l[y].push(S):l[y]=S}const m=[];for(const g of Object.keys(d)){if(!e.call(d,g)||typeof d[g]!="object"||Array.isArray(d[g]))continue;const F=n(g,".");l=d;const w=F.pop(),E=w.replace(/\\\./g,".");for(const y of F)y!=="__proto__"&&((!e.call(l,y)||typeof l[y]!="object")&&(l[y]=Object.create(null)),l=l[y]);l===d&&E===w||(l[E]=d[g],m.push(g))}for(const g of m)delete d[g];return d},"decode"),i=o(u=>u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"),"isQuoted"),s=o(u=>typeof u!="string"||u.match(/[=\r\n]/)||u.match(/^\[/)||u.length>1&&i(u)||u!==u.trim()?JSON.stringify(u):u.split(";").join("\\;").split("#").join("\\#"),"safe"),a=o(u=>{if(u=(u||"").trim(),i(u)){u.charAt(0)==="'"&&(u=u.slice(1,-1));try{u=JSON.parse(u)}catch{}}else{let c=!1,d="";for(let l=0,f=u.length;l<f;l++){const h=u.charAt(l);if(c)"\\;#".indexOf(h)!==-1?d+=h:d+="\\"+h,c=!1;else{if(";#".indexOf(h)!==-1)break;h==="\\"?c=!0:d+=h}}return c&&(d+="\\"),d.trim()}return u},"unsafe");return oo={parse:r,decode:r,stringify:t,encode:t,safe:s,unsafe:a},oo}o(yF,"requireIni");var EF=yF(),fc=Yi(EF);const rn=o(e=>W.lstat(e).then(()=>!0,()=>!1),"fileExists"),io=o(async e=>{try{let t;try{t=e||await no()}catch(a){if(a instanceof R&&a.message.includes("Git repository"))return;throw a}const n=ce.join(t,".ai-commit.json");if(!await rn(n))return;const i=await W.readFile(n,"utf8");return JSON.parse(i)}catch(t){if(t instanceof R)throw t;return}},"getProjectConfig");function bF(e){const t={},n=e.split(`
113
+ `);for(const r of n){const i=r.trim();if(!i||i.startsWith("#"))continue;const s=i.match(/^([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);if(!s)continue;const[,a,u]=s;let c=u.trim();(c.startsWith('"')&&c.endsWith('"')||c.startsWith("'")&&c.endsWith("'"))&&(c=c.slice(1,-1)),t[a]=c}return t}o(bF,"parseEnvContent");async function hc(e){const{filename:t=".env",directory:n=process.cwd(),override:r=!1}=e||{},i=ce.join(n,t);if(!await rn(i))return{};try{const a=await W.readFile(i,"utf8"),u=bF(a);for(const[c,d]of Object.entries(u))(r||process.env[c]===void 0)&&(process.env[c]=d);return u}catch{return{}}}o(hc,"loadEnvFile");async function CF(){process.env.NODE_ENV==="test"?await hc({filename:".env.local"}):await hc({filename:".env"})}o(CF,"loadEnvironment");const Dc=["openai","anthropic","azure-openai","ollama","custom"],SF=["","conventional"],{hasOwnProperty:vF}=Object.prototype,pc=o((e,t)=>vF.call(e,t),"hasOwn"),_=o((e,t,n)=>{if(!t)throw new R(`Invalid config property ${e}: ${n}`)},"parseAssert"),on={provider(e){return e?(_("provider",Dc.includes(e),`Must be one of: ${Dc.join(", ")}`),e):"openai"},OPENAI_KEY(e){if(e)return _("OPENAI_KEY",e.startsWith("sk-"),'Must start with "sk-"'),e},ANTHROPIC_KEY(e){if(e)return _("ANTHROPIC_KEY",e.startsWith("sk-ant-"),'Must start with "sk-ant-"'),e},AZURE_OPENAI_KEY(e){return e},AZURE_ENDPOINT(e){if(e)return _("AZURE_ENDPOINT",/^https?:\/\//.test(e),"Must be a valid URL"),e},OLLAMA_ENDPOINT(e){return e?(_("OLLAMA_ENDPOINT",/^https?:\/\//.test(e),"Must be a valid URL"),e):"http://localhost:11434"},CUSTOM_ENDPOINT(e){if(e)return _("CUSTOM_ENDPOINT",/^https?:\/\//.test(e),"Must be a valid URL"),e},CUSTOM_KEY(e){return e},locale(e){return e?(_("locale",e,"Cannot be empty"),_("locale",/^[a-z-]+$/i.test(e),"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"),e):"en"},generate(e){if(!e)return 1;_("generate",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return _("generate",t>0,"Must be greater than 0"),_("generate",t<=5,"Must be less or equal to 5"),t},type(e){return e?(_("type",SF.includes(e),"Invalid commit type"),e):""},proxy(e){if(!(!e||e.length===0))return _("proxy",/^https?:\/\//.test(e),"Must be a valid URL"),e},model(e){return!e||e.length===0?"gpt-4o-mini":e},timeout(e){if(!e)return 1e4;_("timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return _("timeout",t>=500,"Must be greater than 500ms"),t},temperature(e){if(!e)return .2;_("temperature",/^(2|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 2");const t=Number(e);return _("temperature",t>0,"Must be greater than 0"),_("temperature",t<=2,"Must be less than or equal to 2"),t},"max-length"(e){if(!e)return 50;_("max-length",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return _("max-length",t>=20,"Must be greater than 20 characters"),t},"max-completion-tokens"(e){if(!e)return 1e4;_("max-completion-tokens",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return _("max-completion-tokens",t>0,"Must be greater than 0"),t},"auto-confirm"(e){return e?typeof e=="boolean"?e:(_("auto-confirm",/^(?:true|false)$/.test(e),"Must be a boolean"),e==="true"):!1},"prepend-reference"(e){return e?typeof e=="boolean"?e:(_("prepend-reference",/^(?:true|false)$/.test(e),"Must be a boolean"),e==="true"):!1},signoff(e){return e?typeof e=="boolean"?e:(_("signoff",/^(?:true|false)$/.test(e),"Must be a boolean"),e==="true"):!1}},so=ce.join(Kc.homedir(),".aicommit"),mc=o(async()=>{if(!await rn(so))return Object.create(null);const t=await W.readFile(so,"utf8");return fc.parse(t)},"readConfigFile"),AF=o(e=>{const t=e.provider;switch(t){case"openai":if(!e.OPENAI_KEY)throw new R("Please set your OpenAI API key via `aicommit config set OPENAI_KEY=<your token>`");break;case"anthropic":if(!e.ANTHROPIC_KEY)throw new R("Please set your Anthropic API key via `aicommit config set ANTHROPIC_KEY=<your token>`\nGet your API key from: https://console.anthropic.com/");break;case"azure-openai":if(!e.AZURE_OPENAI_KEY)throw new R("Please set your Azure OpenAI API key via `aicommit config set AZURE_OPENAI_KEY=<your token>`");if(!e.AZURE_ENDPOINT)throw new R("Please set your Azure OpenAI endpoint via `aicommit config set AZURE_ENDPOINT=<your endpoint>`");break;case"ollama":break;case"custom":if(!e.CUSTOM_ENDPOINT)throw new R("Please set your custom endpoint via `aicommit config set CUSTOM_ENDPOINT=<your endpoint>`");break;default:throw new R(`Unknown provider: ${t}`)}},"validateProviderConfig"),ao=o(async(e,t)=>{await CF();const n=await mc(),r=await io(),i={};for(const a of Object.keys(on)){const u=on[a];let c=r?.[a]??e?.[a]??process.env[a]??n[a];if(typeof c=="boolean"&&(c=c.toString()),t)try{i[a]=u(c)}catch{}else i[a]=u(c)}const s=i;return t||AF(s),s},"getConfig"),$F=o(async e=>{const t=await mc();for(const[n,r]of e){if(!pc(on,n))throw new R(`Invalid config property: ${n}`);const i=on[n](r);t[n]=i}await W.writeFile(so,fc.stringify(t),"utf8")},"setConfigs"),gc={openai:o(()=>import("./openai-Dj7-_Crv.mjs"),"openai"),anthropic:o(()=>import("./anthropic-BLj6gUuf.mjs"),"anthropic"),"azure-openai":o(()=>import("./azure-openai-D_BUw_Ew.mjs"),"azure-openai"),ollama:o(()=>import("./ollama-u7lcyhdH.mjs"),"ollama"),custom:o(()=>import("./custom-BQcoNa20.mjs"),"custom")};async function Fc(e,t){const n=gc[e];if(!n)throw new R(`Unknown provider type: ${e}. Supported providers: ${Object.keys(gc).join(", ")}`);try{const i=(await n()).default;return new i(t)}catch(r){throw r instanceof R?r:r.code==="ERR_MODULE_NOT_FOUND"?new R(`Provider "${e}" is not yet implemented. Currently supported: openai`):new R(`Failed to initialize provider "${e}": ${r.message}`)}}o(Fc,"createProvider");var BF=o(async(e,t,n,r,i)=>(async()=>{uc(Gu(Wu(" aicommit "))),await no();const s=eo();n&&await We("git",["add","--update"]),s.start("Detecting staged files");const a=await lc(t);if(!a)throw s.stop("Detecting staged files"),new R("No staged changes found. Stage your changes manually, or automatically stage all changes with the `--all` flag.");s.stop(`${wF(a.files)}:
113
114
  ${a.files.map(D=>` ${D}`).join(`
114
115
  `)}`);const{env:u}=process,c=await ao({OPENAI_KEY:u.OPENAI_KEY||u.OPENAI_API_KEY,proxy:u.https_proxy||u.HTTPS_PROXY||u.http_proxy||u.HTTP_PROXY,generate:e?.toString(),type:r?.toString()}),d=eo();d.start("The AI is analyzing your changes");let l;try{const D={model:c.model,locale:c.locale,maxLength:c["max-length"],type:c.type,timeout:c.timeout,temperature:c.temperature,maxCompletionTokens:c["max-completion-tokens"],proxy:c.proxy};let p;switch(c.provider){case"openai":p={...D,apiKey:c.OPENAI_KEY};break;case"anthropic":p={...D,apiKey:c.ANTHROPIC_KEY};break;case"azure-openai":p={...D,apiKey:c.AZURE_OPENAI_KEY,endpoint:c.AZURE_ENDPOINT};break;case"ollama":p={...D,endpoint:c.OLLAMA_ENDPOINT};break;case"custom":p={...D,endpoint:c.CUSTOM_ENDPOINT,apiKey:c.CUSTOM_KEY};break;default:p={...D,apiKey:c.OPENAI_KEY}}const m=await Fc(c.provider,p),g=await io();l=(await m.generateCommitMessage({diff:a.diff,completions:c.generate,projectConfig:g})).messages}finally{d.stop("Changes analyzed")}if(l.length===0)throw new R("No commit messages were generated. Try again.");let f;if(l.length===1){[f]=l;let D;if(c["auto-confirm"]?(D=!0,Oe(`${ft("\u2714")} Auto confirmed commit message.
115
116
 
116
117
  ${f}
117
- `)):D=await DF({message:`Use this commit message?
118
+ `)):D=await pF({message:`Use this commit message?
118
119
 
119
120
  ${f}
120
- `}),!D||tc(D)){Oe("Commit cancelled");return}}else{const D=await mF({message:`Pick a commit message to use: ${jr("(Ctrl+c to exit)")}`,options:l.map(p=>({label:p,value:p}))});if(tc(D)){Oe("Commit cancelled");return}f=D}if(c["prepend-reference"]){const{stdout:D}=await We("git",["branch","--show-current"]),p=D.match(/([a-zA-Z])+-([0-9]+)/)?.[0];p?.length&&(f=`${p?.toUpperCase()}: ${f}`)}const h=["commit","-m",f,...i];c.signoff&&h.push("--signoff"),await We("git",h),Oe(`${ft("\u2714")} Successfully committed!`)})().catch(s=>{Oe(`${qt("\u2716")} ${s.message}`),nn(s),process.exit(1)}),"aicommit");const[uo,$F]=process.argv.slice(2);var BF=o(()=>(async()=>{if(!uo)throw new R('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook');if($F)return;const e=await lc();if(!e)return;uc(Gu(Wu(" aicommit ")));const{env:t}=process,n=await ao({proxy:t.https_proxy||t.HTTPS_PROXY||t.http_proxy||t.HTTP_PROXY}),r=eo();r.start("The AI is analyzing your changes");let i;try{const d={model:n.model,locale:n.locale,maxLength:n["max-length"],type:n.type,timeout:n.timeout,temperature:n.temperature,maxCompletionTokens:n["max-completion-tokens"],proxy:n.proxy};let l;switch(n.provider){case"openai":l={...d,apiKey:n.OPENAI_KEY};break;case"anthropic":l={...d,apiKey:n.ANTHROPIC_KEY};break;case"azure-openai":l={...d,apiKey:n.AZURE_OPENAI_KEY,endpoint:n.AZURE_ENDPOINT};break;case"ollama":l={...d,endpoint:n.OLLAMA_ENDPOINT};break;case"custom":l={...d,endpoint:n.CUSTOM_ENDPOINT,apiKey:n.CUSTOM_KEY};break;default:l={...d,apiKey:n.OPENAI_KEY}}const f=await Fc(n.provider,l),h=await io();i=(await f.generateCommitMessage({diff:e.diff,completions:n.generate,projectConfig:h})).messages}finally{r.stop("Changes analyzed")}const a=await W.readFile(uo,"utf8")!=="",u=i.length>1;let c="";a&&(c=`# \u{1F916} AI generated commit${u?"s":""}
121
+ `}),!D||tc(D)){Oe("Commit cancelled");return}}else{const D=await FF({message:`Pick a commit message to use: ${jr("(Ctrl+c to exit)")}`,options:l.map(p=>({label:p,value:p}))});if(tc(D)){Oe("Commit cancelled");return}f=D}if(c["prepend-reference"]){const{stdout:D}=await We("git",["branch","--show-current"]),p=D.match(/([a-zA-Z])+-([0-9]+)/)?.[0];p?.length&&(f=`${p?.toUpperCase()}: ${f}`)}const h=["commit","-m",f,...i];c.signoff&&h.push("--signoff"),await We("git",h),Oe(`${ft("\u2714")} Successfully committed!`)})().catch(s=>{Oe(`${qt("\u2716")} ${s.message}`),nn(s),process.exit(1)}),"aicommit");const[uo,TF]=process.argv.slice(2);var IF=o(()=>(async()=>{if(!uo)throw new R('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook');if(TF)return;const e=await lc();if(!e)return;uc(Gu(Wu(" aicommit ")));const{env:t}=process,n=await ao({proxy:t.https_proxy||t.HTTPS_PROXY||t.http_proxy||t.HTTP_PROXY}),r=eo();r.start("The AI is analyzing your changes");let i;try{const d={model:n.model,locale:n.locale,maxLength:n["max-length"],type:n.type,timeout:n.timeout,temperature:n.temperature,maxCompletionTokens:n["max-completion-tokens"],proxy:n.proxy};let l;switch(n.provider){case"openai":l={...d,apiKey:n.OPENAI_KEY};break;case"anthropic":l={...d,apiKey:n.ANTHROPIC_KEY};break;case"azure-openai":l={...d,apiKey:n.AZURE_OPENAI_KEY,endpoint:n.AZURE_ENDPOINT};break;case"ollama":l={...d,endpoint:n.OLLAMA_ENDPOINT};break;case"custom":l={...d,endpoint:n.CUSTOM_ENDPOINT,apiKey:n.CUSTOM_KEY};break;default:l={...d,apiKey:n.OPENAI_KEY}}const f=await Fc(n.provider,l),h=await io();i=(await f.generateCommitMessage({diff:e.diff,completions:n.generate,projectConfig:h})).messages}finally{r.stop("Changes analyzed")}const a=await W.readFile(uo,"utf8")!=="",u=i.length>1;let c="";a&&(c=`# \u{1F916} AI generated commit${u?"s":""}
121
122
  `),u?(a&&(c+=`# Select one of the following messages by uncommeting:
122
123
  `),c+=`
123
124
  ${i.map(d=>`# ${d}`).join(`
124
125
  `)}`):(a&&(c+=`# Edit the message below and commit:
125
126
  `),c+=`
126
127
  ${i[0]}
127
- `),await W.appendFile(uo,c),Oe(`${ft("\u2714")} Saved commit message!`)})().catch(e=>{Oe(`${qt("\u2716")} ${e.message}`),nn(e),process.exit(1)}),"prepareCommitMessageHook"),TF=bn({name:"config",parameters:["<mode>","<key=value...>"]},e=>{(async()=>{const{mode:t,keyValue:n}=e._;if(t==="get"){const r=await ao({},!0);for(const i of n)pc(r,i)&&console.log(`${i}=${r[i]}`);return}if(t==="set"){await vF(n.map(r=>r.split("=")));return}throw new R(`Invalid mode: ${t}`)})().catch(t=>{console.error(`${qt("\u2716")} ${t.message}`),nn(t),process.exit(1)})});const wc="prepare-commit-msg",yc=`.git/hooks/${wc}`,sn=qc(new URL("cli.mjs",import.meta.url)),IF=process.argv[1].replace(/\\/g,"/").endsWith(`/${yc}`),Ec=process.platform==="win32",bc=`
128
+ `),await W.appendFile(uo,c),Oe(`${ft("\u2714")} Saved commit message!`)})().catch(e=>{Oe(`${qt("\u2716")} ${e.message}`),nn(e),process.exit(1)}),"prepareCommitMessageHook"),OF=bn({name:"config",parameters:["<mode>","<key=value...>"]},e=>{(async()=>{const{mode:t,keyValue:n}=e._;if(t==="get"){const r=await ao({},!0);for(const i of n)pc(r,i)&&console.log(`${i}=${r[i]}`);return}if(t==="set"){await $F(n.map(r=>r.split("=")));return}throw new R(`Invalid mode: ${t}`)})().catch(t=>{console.error(`${qt("\u2716")} ${t.message}`),nn(t),process.exit(1)})});const wc="prepare-commit-msg",yc=`.git/hooks/${wc}`,sn=qc(new URL("cli.mjs",import.meta.url)),RF=process.argv[1].replace(/\\/g,"/").endsWith(`/${yc}`),Ec=process.platform==="win32",bc=`
128
129
  #!/usr/bin/env node
129
130
  import(${JSON.stringify(Yc(sn))})
130
- `.trim();var OF=bn({name:"hook",parameters:["<install/uninstall>"]},e=>{(async()=>{const t=await no(),{installUninstall:n}=e._,r=ce.join(t,yc),i=await rn(r);if(n==="install"){if(i){if(await W.realpath(r).catch(()=>{})===sn){console.warn("The hook is already installed");return}throw new R(`A different ${wc} hook seems to be installed. Please remove it before installing aicommit.`)}await W.mkdir(ce.dirname(r),{recursive:!0}),Ec?await W.writeFile(r,bc):(await W.symlink(sn,r,"file"),await W.chmod(r,493)),console.log(`${ft("\u2714")} Hook installed`);return}if(n==="uninstall"){if(!i){console.warn("Hook is not installed");return}if(Ec){if(await W.readFile(r,"utf8")!==bc){console.warn("Hook is not installed");return}}else if(await W.realpath(r)!==sn){console.warn("Hook is not installed");return}await W.rm(r),console.log(`${ft("\u2714")} Hook uninstalled`);return}throw new R(`Invalid mode: ${n}`)})().catch(t=>{console.error(`${qt("\u2716")} ${t.message}`),nn(t),process.exit(1)})});const Cc=process.argv.slice(2);vi({name:"aicommit",version:Cn.version,flags:{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",alias:"t"}},commands:[TF,OF],help:{description:Cn.description},ignoreArgv:o(e=>e==="unknown-flag"||e==="argument","ignoreArgv")},e=>{IF?BF():AF(e.flags.generate,e.flags.exclude,e.flags.all,e.flags.type,Cc)},Cc);export{R as K};
131
+ `.trim();var _F=bn({name:"hook",parameters:["<install/uninstall>"]},e=>{(async()=>{const t=await no(),{installUninstall:n}=e._,r=ce.join(t,yc),i=await rn(r);if(n==="install"){if(i){if(await W.realpath(r).catch(()=>{})===sn){console.warn("The hook is already installed");return}throw new R(`A different ${wc} hook seems to be installed. Please remove it before installing aicommit.`)}await W.mkdir(ce.dirname(r),{recursive:!0}),Ec?await W.writeFile(r,bc):(await W.symlink(sn,r,"file"),await W.chmod(r,493)),console.log(`${ft("\u2714")} Hook installed`);return}if(n==="uninstall"){if(!i){console.warn("Hook is not installed");return}if(Ec){if(await W.readFile(r,"utf8")!==bc){console.warn("Hook is not installed");return}}else if(await W.realpath(r)!==sn){console.warn("Hook is not installed");return}await W.rm(r),console.log(`${ft("\u2714")} Hook uninstalled`);return}throw new R(`Invalid mode: ${n}`)})().catch(t=>{console.error(`${qt("\u2716")} ${t.message}`),nn(t),process.exit(1)})});const Cc=process.argv.slice(2);vi({name:"aicommit",version:Cn.version,flags:{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",alias:"t"}},commands:[OF,_F],help:{description:Cn.description},ignoreArgv:o(e=>e==="unknown-flag"||e==="argument","ignoreArgv")},e=>{RF?IF():BF(e.flags.generate,e.flags.exclude,e.flags.all,e.flags.type,Cc)},Cc);export{R as K};
package/dist/cli.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import"./cli-COuffhrp.mjs";import"tty";import"node:url";import"node:child_process";import"node:string_decoder";import"node:util";import"node:process";import"node:tty";import"node:path";import"child_process";import"path";import"fs";import"node:timers/promises";import"node:os";import"node:events";import"node:v8";import"node:fs";import"node:stream";import"node:buffer";import"node:stream/promises";import"node:readline";import"fs/promises";import"os";import"url";
2
+ import"./cli-BMzt-Oel.mjs";import"tty";import"node:url";import"node:child_process";import"node:string_decoder";import"node:util";import"node:process";import"node:tty";import"node:path";import"child_process";import"path";import"fs";import"node:timers/promises";import"node:os";import"node:events";import"node:v8";import"node:fs";import"node:stream";import"node:buffer";import"node:stream/promises";import"node:readline";import"fs/promises";import"os";import"url";
@@ -1,3 +1,3 @@
1
- var M=Object.defineProperty;var d=(l,t)=>M(l,"name",{value:t,configurable:!0});import T from"http";import N from"https";import{L as O,g as P}from"./prompt-BGI0PV0L.mjs";import{K as m}from"./cli-COuffhrp.mjs";import"tty";import"node:url";import"node:child_process";import"node:string_decoder";import"node:util";import"node:process";import"node:tty";import"node:path";import"child_process";import"path";import"fs";import"node:timers/promises";import"node:os";import"node:events";import"node:v8";import"node:fs";import"node:stream";import"node:buffer";import"node:stream/promises";import"node:readline";import"fs/promises";import"os";import"url";const g=class g extends O{get name(){return"custom"}validateConfig(){const{endpoint:t}=this.config;if(!t)throw new m("Please set your custom endpoint via `aicommit config set CUSTOM_ENDPOINT=<your endpoint>`")}async generateCommitMessage(t){try{const o=[{role:"system",content:P(this.config.locale,this.config.maxLength,this.config.type,t.projectConfig)},{role:"user",content:t.diff}],s=[];for(let i=0;i<t.completions;i++){const e=await this.createChatCompletion(o);let n;e.choices&&e.choices[0]?.message?.content?n=e.choices[0].message.content:e.message?.content?n=e.message.content:e.content?n=e.content:typeof e=="string"&&(n=e),n&&s.push(this.sanitizeMessage(n))}return{messages:this.deduplicateMessages(s)}}catch(r){const o=r;throw o.code==="ECONNREFUSED"?new m(`Cannot connect to custom endpoint at ${this.config.endpoint}. Make sure your endpoint is running and accessible.`):o.code==="ENOTFOUND"?new m(`Error connecting to ${o.hostname} (${o.syscall}). Check your CUSTOM_ENDPOINT configuration.`):o}}async createChatCompletion(t){const r={model:this.config.model,messages:t,temperature:this.config.temperature,max_tokens:this.config.maxCompletionTokens},o={...this.config.headers||{}};this.config.apiKey&&(o.Authorization=`Bearer ${this.config.apiKey}`);const{response:s,data:a}=await this.httpPost(this.config.endpoint,"",o,r);if(!s.statusCode||s.statusCode<200||s.statusCode>299){let i=`Custom API Error: ${s.statusCode} - ${s.statusMessage}`;throw a&&(i+=`
1
+ var M=Object.defineProperty;var d=(l,t)=>M(l,"name",{value:t,configurable:!0});import T from"http";import N from"https";import{L as O,g as P}from"./prompt-BGI0PV0L.mjs";import{K as m}from"./cli-BMzt-Oel.mjs";import"tty";import"node:url";import"node:child_process";import"node:string_decoder";import"node:util";import"node:process";import"node:tty";import"node:path";import"child_process";import"path";import"fs";import"node:timers/promises";import"node:os";import"node:events";import"node:v8";import"node:fs";import"node:stream";import"node:buffer";import"node:stream/promises";import"node:readline";import"fs/promises";import"os";import"url";const g=class g extends O{get name(){return"custom"}validateConfig(){const{endpoint:t}=this.config;if(!t)throw new m("Please set your custom endpoint via `aicommit config set CUSTOM_ENDPOINT=<your endpoint>`")}async generateCommitMessage(t){try{const o=[{role:"system",content:P(this.config.locale,this.config.maxLength,this.config.type,t.projectConfig)},{role:"user",content:t.diff}],s=[];for(let i=0;i<t.completions;i++){const e=await this.createChatCompletion(o);let n;e.choices&&e.choices[0]?.message?.content?n=e.choices[0].message.content:e.message?.content?n=e.message.content:e.content?n=e.content:typeof e=="string"&&(n=e),n&&s.push(this.sanitizeMessage(n))}return{messages:this.deduplicateMessages(s)}}catch(r){const o=r;throw o.code==="ECONNREFUSED"?new m(`Cannot connect to custom endpoint at ${this.config.endpoint}. Make sure your endpoint is running and accessible.`):o.code==="ENOTFOUND"?new m(`Error connecting to ${o.hostname} (${o.syscall}). Check your CUSTOM_ENDPOINT configuration.`):o}}async createChatCompletion(t){const r={model:this.config.model,messages:t,temperature:this.config.temperature,max_tokens:this.config.maxCompletionTokens},o={...this.config.headers||{}};this.config.apiKey&&(o.Authorization=`Bearer ${this.config.apiKey}`);const{response:s,data:a}=await this.httpPost(this.config.endpoint,"",o,r);if(!s.statusCode||s.statusCode<200||s.statusCode>299){let i=`Custom API Error: ${s.statusCode} - ${s.statusMessage}`;throw a&&(i+=`
2
2
 
3
3
  ${a}`),new m(i)}return JSON.parse(a)}async httpPost(t,r,o,s){return new Promise((a,i)=>{const e=new URL(t),n=e.protocol==="https:",y=n?N:T,C=e.pathname+(r||""),f=JSON.stringify(s),c=y.request({hostname:e.hostname,port:e.port||(n?443:80),path:C,method:"POST",headers:{...o,"Content-Type":"application/json","Content-Length":Buffer.byteLength(f)},timeout:this.config.timeout},p=>{const u=[];p.on("data",w=>u.push(w)),p.on("end",()=>{a({request:c,response:p,data:Buffer.concat(u).toString()})})});c.on("error",i),c.on("timeout",()=>{c.destroy(),i(new m(`Time out error: request took over ${this.config.timeout}ms. Try increasing the \`timeout\` config.`))}),c.write(f),c.end()})}sanitizeMessage(t){return t.trim().replace(/[\n\r]/g,"").replace(/(\w)\.$/,"$1")}deduplicateMessages(t){return Array.from(new Set(t))}};d(g,"CustomProvider");let h=g;export{h as default};
@@ -1,4 +1,4 @@
1
- var C=Object.defineProperty;var f=(d,t)=>C(d,"name",{value:t,configurable:!0});import M from"http";import O from"https";import{L as $,g as L}from"./prompt-BGI0PV0L.mjs";import{K as m}from"./cli-COuffhrp.mjs";import"tty";import"node:url";import"node:child_process";import"node:string_decoder";import"node:util";import"node:process";import"node:tty";import"node:path";import"child_process";import"path";import"fs";import"node:timers/promises";import"node:os";import"node:events";import"node:v8";import"node:fs";import"node:stream";import"node:buffer";import"node:stream/promises";import"node:readline";import"fs/promises";import"os";import"url";const g=class g extends ${get name(){return"ollama"}validateConfig(){const{endpoint:t}=this.config;if(!t)throw new m("Ollama endpoint is not configured. Using default: http://localhost:11434")}async generateCommitMessage(t){try{const e=[{role:"system",content:L(this.config.locale,this.config.maxLength,this.config.type,t.projectConfig)},{role:"user",content:t.diff}],o=[];for(let s=0;s<t.completions;s++){const a=(await this.createChatCompletion(e)).message.content;a&&o.push(this.sanitizeMessage(a))}return{messages:this.deduplicateMessages(o)}}catch(r){const e=r;throw e.code==="ECONNREFUSED"?new m(`Cannot connect to Ollama at ${this.config.endpoint}. Make sure Ollama is running. Install from: https://ollama.com`):e.code==="ENOTFOUND"?new m(`Error connecting to ${e.hostname} (${e.syscall}). Check your OLLAMA_ENDPOINT configuration.`):e}}async createChatCompletion(t){const r={model:this.config.model,messages:t,stream:!1,options:{temperature:this.config.temperature,num_predict:this.config.maxCompletionTokens}},{response:e,data:o}=await this.httpPost(this.config.endpoint,"/api/chat",{},r);if(!e.statusCode||e.statusCode<200||e.statusCode>299){let n=`Ollama API Error: ${e.statusCode} - ${e.statusMessage}`;if(o)try{const s=JSON.parse(o);s.error&&(n+=`
1
+ var C=Object.defineProperty;var f=(d,t)=>C(d,"name",{value:t,configurable:!0});import M from"http";import O from"https";import{L as $,g as L}from"./prompt-BGI0PV0L.mjs";import{K as m}from"./cli-BMzt-Oel.mjs";import"tty";import"node:url";import"node:child_process";import"node:string_decoder";import"node:util";import"node:process";import"node:tty";import"node:path";import"child_process";import"path";import"fs";import"node:timers/promises";import"node:os";import"node:events";import"node:v8";import"node:fs";import"node:stream";import"node:buffer";import"node:stream/promises";import"node:readline";import"fs/promises";import"os";import"url";const g=class g extends ${get name(){return"ollama"}validateConfig(){const{endpoint:t}=this.config;if(!t)throw new m("Ollama endpoint is not configured. Using default: http://localhost:11434")}async generateCommitMessage(t){try{const e=[{role:"system",content:L(this.config.locale,this.config.maxLength,this.config.type,t.projectConfig)},{role:"user",content:t.diff}],o=[];for(let s=0;s<t.completions;s++){const a=(await this.createChatCompletion(e)).message.content;a&&o.push(this.sanitizeMessage(a))}return{messages:this.deduplicateMessages(o)}}catch(r){const e=r;throw e.code==="ECONNREFUSED"?new m(`Cannot connect to Ollama at ${this.config.endpoint}. Make sure Ollama is running. Install from: https://ollama.com`):e.code==="ENOTFOUND"?new m(`Error connecting to ${e.hostname} (${e.syscall}). Check your OLLAMA_ENDPOINT configuration.`):e}}async createChatCompletion(t){const r={model:this.config.model,messages:t,stream:!1,options:{temperature:this.config.temperature,num_predict:this.config.maxCompletionTokens}},{response:e,data:o}=await this.httpPost(this.config.endpoint,"/api/chat",{},r);if(!e.statusCode||e.statusCode<200||e.statusCode>299){let n=`Ollama API Error: ${e.statusCode} - ${e.statusMessage}`;if(o)try{const s=JSON.parse(o);s.error&&(n+=`
2
2
 
3
3
  ${s.error}`)}catch{n+=`
4
4
 
@@ -1,4 +1,4 @@
1
- var d=Object.defineProperty;var g=(u,t)=>d(u,"name",{value:t,configurable:!0});import y from"https";import{d as w}from"./index-Bi9U2ify.mjs";import{L as C,g as A}from"./prompt-BGI0PV0L.mjs";import{K as i}from"./cli-COuffhrp.mjs";import"net";import"tls";import"assert";import"tty";import"util";import"os";import"http";import"url";import"node:url";import"node:child_process";import"node:string_decoder";import"node:util";import"node:process";import"node:tty";import"node:path";import"child_process";import"path";import"fs";import"node:timers/promises";import"node:os";import"node:events";import"node:v8";import"node:fs";import"node:stream";import"node:buffer";import"node:stream/promises";import"node:readline";import"fs/promises";const m=class m extends C{get name(){return"openai"}validateConfig(){const{apiKey:t}=this.config;if(!t)throw new i("Please set your OpenAI API key via `aicommit config set OPENAI_KEY=<your token>`");if(!t.startsWith("sk-"))throw new i('Invalid OpenAI API key: Must start with "sk-"')}async generateCommitMessage(t){try{const e=await this.createChatCompletion({model:this.config.model,messages:[{role:"system",content:A(this.config.locale,this.config.maxLength,this.config.type,t.projectConfig)},{role:"user",content:t.diff}],temperature:this.config.temperature,top_p:1,frequency_penalty:0,presence_penalty:0,max_completion_tokens:this.config.maxCompletionTokens,stream:!1,n:t.completions});return{messages:this.deduplicateMessages(e.choices.filter(s=>s.message?.content).map(s=>this.sanitizeMessage(s.message.content)))}}catch(e){const o=e;throw o.code==="ENOTFOUND"?new i(`Error connecting to ${o.hostname} (${o.syscall}). Are you connected to the internet?`):o}}async createChatCompletion(t){const{response:e,data:o}=await this.httpsPost("api.openai.com","/v1/chat/completions",{Authorization:`Bearer ${this.config.apiKey}`},t);if(!e.statusCode||e.statusCode<200||e.statusCode>299){let s=`OpenAI API Error: ${e.statusCode} - ${e.statusMessage}`;throw o&&(s+=`
1
+ var d=Object.defineProperty;var g=(u,t)=>d(u,"name",{value:t,configurable:!0});import y from"https";import{d as w}from"./index-Bi9U2ify.mjs";import{L as C,g as A}from"./prompt-BGI0PV0L.mjs";import{K as i}from"./cli-BMzt-Oel.mjs";import"net";import"tls";import"assert";import"tty";import"util";import"os";import"http";import"url";import"node:url";import"node:child_process";import"node:string_decoder";import"node:util";import"node:process";import"node:tty";import"node:path";import"child_process";import"path";import"fs";import"node:timers/promises";import"node:os";import"node:events";import"node:v8";import"node:fs";import"node:stream";import"node:buffer";import"node:stream/promises";import"node:readline";import"fs/promises";const m=class m extends C{get name(){return"openai"}validateConfig(){const{apiKey:t}=this.config;if(!t)throw new i("Please set your OpenAI API key via `aicommit config set OPENAI_KEY=<your token>`");if(!t.startsWith("sk-"))throw new i('Invalid OpenAI API key: Must start with "sk-"')}async generateCommitMessage(t){try{const e=await this.createChatCompletion({model:this.config.model,messages:[{role:"system",content:A(this.config.locale,this.config.maxLength,this.config.type,t.projectConfig)},{role:"user",content:t.diff}],temperature:this.config.temperature,top_p:1,frequency_penalty:0,presence_penalty:0,max_completion_tokens:this.config.maxCompletionTokens,stream:!1,n:t.completions});return{messages:this.deduplicateMessages(e.choices.filter(s=>s.message?.content).map(s=>this.sanitizeMessage(s.message.content)))}}catch(e){const o=e;throw o.code==="ENOTFOUND"?new i(`Error connecting to ${o.hostname} (${o.syscall}). Are you connected to the internet?`):o}}async createChatCompletion(t){const{response:e,data:o}=await this.httpsPost("api.openai.com","/v1/chat/completions",{Authorization:`Bearer ${this.config.apiKey}`},t);if(!e.statusCode||e.statusCode<200||e.statusCode>299){let s=`OpenAI API Error: ${e.statusCode} - ${e.statusMessage}`;throw o&&(s+=`
2
2
 
3
3
  ${o}`),e.statusCode===500&&(s+=`
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@negoziator/ai-commit",
3
- "version": "2.81.0",
3
+ "version": "2.83.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },