#!/usr/bin/env node "use strict";var $=Object.create;var h=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var L=Object.getPrototypeOf,N=Object.prototype.hasOwnProperty;var P=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of M(t))!N.call(e,s)&&s!==r&&h(e,s,{get:()=>t[s],enumerable:!(i=I(t,s))||i.enumerable});return e};var G=(e,t,r)=>(r=e!=null?$(L(e)):{},P(t||!e||!e.__esModule?h(r,"default",{value:e,enumerable:!0}):r,e));var v=require("commander");var b="0.4.4";var y="ollama",x="mistral",w="en",S="http://localhost:11434";var A=new v.Command;A.version(b).description("Automatic commit generator using Ollama.").option("-m, --model ","ollama model",x).option("-a, --api ","api host",S).option("-l, --language ","the string of the language to translate to. It can be in any of the two ISO 639 (1 or 2) or the full name in English like Spanish.",w).option("-s, --signature").option("-v, --verbose").parse(process.argv);var o=A.opts();async function _(e){let t=(await import("translate")).default,{type:r,scope:i,subject:s,body:a=[]}=JSON.parse(e),m=(await Promise.all([s,...typeof a=="string"?[a]:a].map(c=>c.replaceAll("'","`")).map(c=>t(c,{engine:"google",to:o.language})))).map(c=>c.replaceAll("`","'")),u=`${r}${i?`(${i})`:""}: ${m.at(0)}`,d=m.slice(1).join(` `);return[u,d].filter(Boolean).join(` `)}var T=require("consola");var E,R=(0,T.createConsola)({level:(E=o)!=null&&E.verbose?999:3,fancy:!0,formatOptions:{colors:!0,compact:!1,date:!1}}),n=R;var g=['You are the JSON creator for creating a commit using the content obtained through "git diff --cached."','JSON you have generated should contain only "type", "scope", "subject", and "body" keys.','You must not include keys other than "type", "scope", "subject", and "body".',"The JSON you create must be in a form that can be parsed through JSON.parse in javascript.","Among the key values of JSON you generated, scope and body are optional elements.","You can't change lines and spaces in a row.",'You can no longer respond as soon as you print out "}".',`"Type" must be one of the following: build: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm) ci: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs) docs: Documentation only changes feat: A new feature fix: A bug fix perf: A code change that improves performance refactor: A code change that neither fixes a bug nor adds a feature style: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc) test: Adding missing tests or correcting existing tests`,'"Scope" is a noun that describes the area to which the codebase applies.','"Subject" is a short summary of code changes','"Subject" must be no more than 8 words long.','"Subject" uses the command present tense.',`In the response of "Subject", hooks such as 'use-size', paths such as 'packages/utils', and file names such as 'index.tsx' must be wrapped with '.`,'"Body" provides additional contextual information about code changes following "Subject".','"Body" uses the command present tense.','"Body" should use "Change" instead of "Change." "Change" me.','"Body" is multiple sentences, it should be represented as a string array.'].join(` `);function f(e){return e.split(/\s/g).length}function j(e){return e.replaceAll(/\\(.)/g,"$1")}async function k(e){var a;let t={model:o.model,prompt:e,format:"json",system:g,options:{num_ctx:f(g)+f(e)+1024,temperature:.2,tfs_z:5,top_k:20,top_p:.5}},i=(a=(await fetch(`${o.api}/api/generate`,{method:"POST",body:JSON.stringify(t)})).body)==null?void 0:a.getReader();if(!i)throw new Error("Failed to read response body");let s="";for(;;){let{done:m,value:u}=await i.read();if(m)break;let d=new TextDecoder().decode(u);try{let p=JSON.parse(d);p.done===!1&&(o.verbose&&process.stdout.write(p.response),s+=p.response)}catch{break}}return o.verbose&&process.stdout.write(` `),j(s)}var l=require("child_process");function C(){try{(0,l.execSync)("git rev-parse --is-inside-work-tree",{encoding:"utf8",stdio:"ignore"})}catch(e){throw e}}function O(e){let t=(0,l.execSync)("git diff --cached . ':(exclude)package-lock.json' ':(exclude)yarn.lock' ':(exclude)pnpm-lock.yaml' ':(exclude)bun.lockb'").toString();return t||(n.warn("No staged changes found. Make sure there are changes and run `git add .` or use the `--auto-add-all`, `-a` option."),process.exit(1)),t.length>e&&(n.warn(`The diff is too large (${t.length} > ${e} chars) to write a commit message. Please consider splitting your changes into multiple commits.`),process.exit(1)),t}var D=e=>{(0,l.execSync)("git commit -F -",{input:e})};async function U(){n.info(`AI PROVIDER: ${y}`),n.info(`AI MODEL: ${o.model}`),n.info(`API HOST: ${o.api}`),n.info(`LANGUAGE: ${o.language}`),C();let e=O(+o.maxDiffLength);n.start(`The currently prepared commit diff is ${Intl.NumberFormat("en-US").format(e.length)} characters long.`),n.start(`Generating commit message... `);let t=Date.now(),r=await k(e),s=(Date.now()-t)/1e3,a=await _(r);o.signature&&(a+=` made by ollama-commit`),n.success("\u2705 Commit message generation successful!"),n.success(`\u{1F680} Generating commit message took ${s} seconds. `),process.stdout.write(`${a} `),await n.prompt("Do you want to continue?",{type:"confirm",initial:!0})||(n.info(`Commit aborted by user \u{1F645}\u200D\u2642\uFE0F `),process.exit(1)),D(a),process.exit()}U().catch(e=>{n.error(e),process.exit(1)});