nuwax-file-server 1.3.4 → 1.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import E from"path";import n from"fs";import I from"os";import{fileURLToPath as T}from"url";import o from"dotenv";const L=E.dirname(T(import.meta.url));o.config();function p(){const e=process.env.LOG_BASE_DIR,_=E.join(I.tmpdir(),"nuwax-file-server","project_logs");if(!e)return _;try{return n.mkdirSync(e,{recursive:!0}),e}catch{try{n.mkdirSync(_,{recursive:!0})}catch{}return _}}const r=process.env.NODE_ENV||"development";function O(e){const _=E.join(L,"..",`env.${e}`);if(n.existsSync(_))o.config({path:_}),console.log(`Environment configuration file env.${e} loaded`);else{const s=`Environment configuration file env.${e} does not exist, please create the corresponding environment configuration file and try again`;throw console.error(s),new Error(s)}}O(r);const R={NODE_ENV:r,PORT:parseInt(process.env.PORT),DEPLOYMENT_MODE:process.env.DEPLOYMENT_MODE||"docker-compose",FAST_RESTART_ENABLED:process.env.FAST_RESTART_ENABLED?.toLowerCase()==="true",INIT_PROJECT_NAME_REACT:process.env.INIT_PROJECT_NAME_REACT||"react-vite-template",INIT_PROJECT_NAME_VUE3:process.env.INIT_PROJECT_NAME_VUE3||"vue3-vite-template",INIT_PROJECT_DIR:process.env.INIT_PROJECT_DIR,PROJECT_SOURCE_DIR:process.env.PROJECT_SOURCE_DIR,DIST_TARGET_DIR:process.env.DIST_TARGET_DIR,UPLOAD_PROJECT_DIR:process.env.UPLOAD_PROJECT_DIR,MAX_BUILD_CONCURRENCY:process.env.MAX_BUILD_CONCURRENCY?parseInt(process.env.MAX_BUILD_CONCURRENCY,10):void 0,MAX_INLINE_FILE_SIZE_BYTES:process.env.MAX_INLINE_FILE_SIZE_BYTES?parseInt(process.env.MAX_INLINE_FILE_SIZE_BYTES,10):void 0,UPLOAD_MAX_FILE_SIZE_BYTES:process.env.UPLOAD_MAX_FILE_SIZE_BYTES?parseInt(process.env.UPLOAD_MAX_FILE_SIZE_BYTES,10):void 0,UPLOAD_ALLOWED_EXTENSIONS:process.env.UPLOAD_ALLOWED_EXTENSIONS?process.env.UPLOAD_ALLOWED_EXTENSIONS.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean):[],UPLOAD_SINGLE_FILE_SIZE_BYTES:process.env.UPLOAD_SINGLE_FILE_SIZE_BYTES?parseInt(process.env.UPLOAD_SINGLE_FILE_SIZE_BYTES,10):void 0,DOWNLOAD_MAX_FILE_SIZE_BYTES:process.env.DOWNLOAD_MAX_FILE_SIZE_BYTES?parseInt(process.env.DOWNLOAD_MAX_FILE_SIZE_BYTES,10):void 0,REQUEST_BODY_LIMIT:process.env.REQUEST_BODY_LIMIT,TRAVERSE_EXCLUDE_DIRS:process.env.TRAVERSE_EXCLUDE_DIRS?process.env.TRAVERSE_EXCLUDE_DIRS.split(",").map(e=>e.trim()).filter(Boolean):[],BACKUP_TRAVERSE_EXCLUDE_FILES:process.env.BACKUP_TRAVERSE_EXCLUDE_FILES?process.env.BACKUP_TRAVERSE_EXCLUDE_FILES.split(",").map(e=>e.trim()).filter(Boolean):[],CONTENT_TRAVERSE_EXCLUDE_FILES:process.env.CONTENT_TRAVERSE_EXCLUDE_FILES?process.env.CONTENT_TRAVERSE_EXCLUDE_FILES.split(",").map(e=>e.trim()).filter(Boolean):[],INLINE_IMAGE_EXTENSIONS:process.env.INLINE_IMAGE_EXTENSIONS?process.env.INLINE_IMAGE_EXTENSIONS.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean):[],TOP_LEVEL_NOISE_PATTERNS:process.env.TOP_LEVEL_NOISE_PATTERNS?process.env.TOP_LEVEL_NOISE_PATTERNS.split(",").map(e=>e.trim()).filter(Boolean):[],LOG_BASE_DIR:p(),LOG_LEVEL:process.env.LOG_LEVEL?process.env.LOG_LEVEL.toLowerCase():void 0,LOG_PREFIX_API:process.env.LOG_PREFIX_API,LOG_PREFIX_BUILD:process.env.LOG_PREFIX_BUILD,LOG_CONSOLE_ENABLED:typeof process.env.LOG_CONSOLE_ENABLED=="string"?process.env.LOG_CONSOLE_ENABLED.toLowerCase()==="true":void 0,LOG_CACHE_ENABLED:typeof process.env.LOG_CACHE_ENABLED=="string"?process.env.LOG_CACHE_ENABLED.toLowerCase()==="true":void 0,LOG_CACHE_DURATION:process.env.LOG_CACHE_DURATION?parseInt(process.env.LOG_CACHE_DURATION,10):void 0,LOG_CACHE_MAX_ENTRIES:process.env.LOG_CACHE_MAX_ENTRIES?parseInt(process.env.LOG_CACHE_MAX_ENTRIES,10):void 0,LOG_CACHE_MAX_FILE_SIZE:process.env.LOG_CACHE_MAX_FILE_SIZE?parseInt(process.env.LOG_CACHE_MAX_FILE_SIZE,10):void 0,DEV_SERVER_PORT_TIMEOUT:process.env.DEV_SERVER_PORT_TIMEOUT?parseInt(process.env.DEV_SERVER_PORT_TIMEOUT,10):void 0,DEV_SERVER_STOP_TIMEOUT:process.env.DEV_SERVER_STOP_TIMEOUT?parseInt(process.env.DEV_SERVER_STOP_TIMEOUT,10):void 0,DEV_SERVER_STOP_CHECK_INTERVAL:process.env.DEV_SERVER_STOP_CHECK_INTERVAL?parseInt(process.env.DEV_SERVER_STOP_CHECK_INTERVAL,10):void 0,DEV_SERVER_STOP_MAX_ATTEMPTS:process.env.DEV_SERVER_STOP_MAX_ATTEMPTS?parseInt(process.env.DEV_SERVER_STOP_MAX_ATTEMPTS,10):void 0,COMPUTER_WORKSPACE_DIR:process.env.COMPUTER_WORKSPACE_DIR,COMPUTER_LOG_DIR:process.env.COMPUTER_LOG_DIR,CLI_SERVICE_NAME:"nuwax-file-server",CLI_PID_DIR:process.env.CLI_PID_DIR||(process.platform==="win32"?E.join(process.env.TEMP||"","nuwax-file-server"):E.join("/tmp","nuwax-file-server")),CLI_PID_FILE:"server.pid",CLI_STOP_TIMEOUT:process.env.CLI_STOP_TIMEOUT?parseInt(process.env.CLI_STOP_TIMEOUT,10):3e4,CLI_CHECK_INTERVAL:process.env.CLI_CHECK_INTERVAL?parseInt(process.env.CLI_CHECK_INTERVAL,10):500,CLI_LOG_DIR:process.env.CLI_LOG_DIR||(process.platform==="win32"?E.join(process.env.TEMP||"","nuwax-file-server","logs"):E.join("/tmp","nuwax-file-server","logs")),CLI_IS_WINDOWS:process.platform==="win32",GIT_DEFAULT_AUTHOR_NAME:process.env.GIT_DEFAULT_AUTHOR_NAME||"Nuwax File Server",GIT_DEFAULT_AUTHOR_EMAIL:process.env.GIT_DEFAULT_AUTHOR_EMAIL||"git@nuwax.local",GIT_AUTO_GITIGNORE:process.env.GIT_AUTO_GITIGNORE?.toLowerCase()!=="false",GIT_GITIGNORE_ENTRIES:process.env.GIT_GITIGNORE_ENTRIES?process.env.GIT_GITIGNORE_ENTRIES.split("|").map(e=>e.trim()).filter(Boolean):["node_modules/",".pnpm-store/","dist/","build/",".idea/",".vscode/",".DS_Store",".npmrc",".agents/",".claude/",".opencode/",".codex/",".tmp/",".logs/","pnpm-lock.yaml","yarn.lock","package-lock.json"],GIT_ENABLED:process.env.GIT_ENABLED?.toLowerCase()==="true",BASH_PATH:process.env.BASH_PATH||"",ZIP_WORKSPACE_EXCLUDE:process.env.ZIP_WORKSPACE_EXCLUDE?process.env.ZIP_WORKSPACE_EXCLUDE.split(",").map(e=>e.trim()).filter(Boolean):[".git",".tmp",".claude",".agents",".codex",".opencode",".logs",".npmrc","__pycache__","node_modules","dist","pnpm-lock.yaml","yarn.lock","package-lock.json"]};export default R;
1
+ import E from"path";import n from"fs";import I from"os";import{fileURLToPath as T}from"url";import o from"dotenv";const L=E.dirname(T(import.meta.url));o.config();function p(){const e=process.env.LOG_BASE_DIR,_=E.join(I.tmpdir(),"nuwax-file-server","project_logs");if(!e)return _;try{return n.mkdirSync(e,{recursive:!0}),e}catch{try{n.mkdirSync(_,{recursive:!0})}catch{}return _}}const r=process.env.NODE_ENV||"development";function O(e){const _=E.join(L,"..",`env.${e}`);if(n.existsSync(_))o.config({path:_}),console.log(`Environment configuration file env.${e} loaded`);else{const s=`Environment configuration file env.${e} does not exist, please create the corresponding environment configuration file and try again`;throw console.error(s),new Error(s)}}O(r);const R={NODE_ENV:r,PORT:parseInt(process.env.PORT),DEPLOYMENT_MODE:process.env.DEPLOYMENT_MODE||"docker-compose",FAST_RESTART_ENABLED:process.env.FAST_RESTART_ENABLED?.toLowerCase()==="true",INIT_PROJECT_NAME_REACT:process.env.INIT_PROJECT_NAME_REACT||"react-vite-template",INIT_PROJECT_NAME_VUE3:process.env.INIT_PROJECT_NAME_VUE3||"vue3-vite-template",INIT_PROJECT_DIR:process.env.INIT_PROJECT_DIR,PROJECT_SOURCE_DIR:process.env.PROJECT_SOURCE_DIR,DIST_TARGET_DIR:process.env.DIST_TARGET_DIR,UPLOAD_PROJECT_DIR:process.env.UPLOAD_PROJECT_DIR,MAX_BUILD_CONCURRENCY:process.env.MAX_BUILD_CONCURRENCY?parseInt(process.env.MAX_BUILD_CONCURRENCY,10):void 0,MAX_INLINE_FILE_SIZE_BYTES:process.env.MAX_INLINE_FILE_SIZE_BYTES?parseInt(process.env.MAX_INLINE_FILE_SIZE_BYTES,10):void 0,UPLOAD_MAX_FILE_SIZE_BYTES:process.env.UPLOAD_MAX_FILE_SIZE_BYTES?parseInt(process.env.UPLOAD_MAX_FILE_SIZE_BYTES,10):void 0,UPLOAD_ALLOWED_EXTENSIONS:process.env.UPLOAD_ALLOWED_EXTENSIONS?process.env.UPLOAD_ALLOWED_EXTENSIONS.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean):[],UPLOAD_SINGLE_FILE_SIZE_BYTES:process.env.UPLOAD_SINGLE_FILE_SIZE_BYTES?parseInt(process.env.UPLOAD_SINGLE_FILE_SIZE_BYTES,10):void 0,DOWNLOAD_MAX_FILE_SIZE_BYTES:process.env.DOWNLOAD_MAX_FILE_SIZE_BYTES?parseInt(process.env.DOWNLOAD_MAX_FILE_SIZE_BYTES,10):void 0,REQUEST_BODY_LIMIT:process.env.REQUEST_BODY_LIMIT,TRAVERSE_EXCLUDE_DIRS:process.env.TRAVERSE_EXCLUDE_DIRS?process.env.TRAVERSE_EXCLUDE_DIRS.split(",").map(e=>e.trim()).filter(Boolean):[],BACKUP_TRAVERSE_EXCLUDE_FILES:process.env.BACKUP_TRAVERSE_EXCLUDE_FILES?process.env.BACKUP_TRAVERSE_EXCLUDE_FILES.split(",").map(e=>e.trim()).filter(Boolean):[],CONTENT_TRAVERSE_EXCLUDE_FILES:process.env.CONTENT_TRAVERSE_EXCLUDE_FILES?process.env.CONTENT_TRAVERSE_EXCLUDE_FILES.split(",").map(e=>e.trim()).filter(Boolean):[],INLINE_IMAGE_EXTENSIONS:process.env.INLINE_IMAGE_EXTENSIONS?process.env.INLINE_IMAGE_EXTENSIONS.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean):[],TOP_LEVEL_NOISE_PATTERNS:process.env.TOP_LEVEL_NOISE_PATTERNS?process.env.TOP_LEVEL_NOISE_PATTERNS.split(",").map(e=>e.trim()).filter(Boolean):[],LOG_BASE_DIR:p(),LOG_LEVEL:process.env.LOG_LEVEL?process.env.LOG_LEVEL.toLowerCase():void 0,LOG_PREFIX_API:process.env.LOG_PREFIX_API,LOG_PREFIX_BUILD:process.env.LOG_PREFIX_BUILD,LOG_CONSOLE_ENABLED:typeof process.env.LOG_CONSOLE_ENABLED=="string"?process.env.LOG_CONSOLE_ENABLED.toLowerCase()==="true":void 0,LOG_CACHE_ENABLED:typeof process.env.LOG_CACHE_ENABLED=="string"?process.env.LOG_CACHE_ENABLED.toLowerCase()==="true":void 0,LOG_CACHE_DURATION:process.env.LOG_CACHE_DURATION?parseInt(process.env.LOG_CACHE_DURATION,10):void 0,LOG_CACHE_MAX_ENTRIES:process.env.LOG_CACHE_MAX_ENTRIES?parseInt(process.env.LOG_CACHE_MAX_ENTRIES,10):void 0,LOG_CACHE_MAX_FILE_SIZE:process.env.LOG_CACHE_MAX_FILE_SIZE?parseInt(process.env.LOG_CACHE_MAX_FILE_SIZE,10):void 0,DEV_SERVER_PORT_TIMEOUT:process.env.DEV_SERVER_PORT_TIMEOUT?parseInt(process.env.DEV_SERVER_PORT_TIMEOUT,10):void 0,DEV_SERVER_STOP_TIMEOUT:process.env.DEV_SERVER_STOP_TIMEOUT?parseInt(process.env.DEV_SERVER_STOP_TIMEOUT,10):void 0,DEV_SERVER_STOP_CHECK_INTERVAL:process.env.DEV_SERVER_STOP_CHECK_INTERVAL?parseInt(process.env.DEV_SERVER_STOP_CHECK_INTERVAL,10):void 0,DEV_SERVER_STOP_MAX_ATTEMPTS:process.env.DEV_SERVER_STOP_MAX_ATTEMPTS?parseInt(process.env.DEV_SERVER_STOP_MAX_ATTEMPTS,10):void 0,COMPUTER_WORKSPACE_DIR:process.env.COMPUTER_WORKSPACE_DIR,COMPUTER_LOG_DIR:process.env.COMPUTER_LOG_DIR,CLI_SERVICE_NAME:"nuwax-file-server",CLI_PID_DIR:process.env.CLI_PID_DIR||(process.platform==="win32"?E.join(process.env.TEMP||"","nuwax-file-server"):E.join("/tmp","nuwax-file-server")),CLI_PID_FILE:"server.pid",CLI_STOP_TIMEOUT:process.env.CLI_STOP_TIMEOUT?parseInt(process.env.CLI_STOP_TIMEOUT,10):3e4,CLI_CHECK_INTERVAL:process.env.CLI_CHECK_INTERVAL?parseInt(process.env.CLI_CHECK_INTERVAL,10):500,CLI_LOG_DIR:process.env.CLI_LOG_DIR||(process.platform==="win32"?E.join(process.env.TEMP||"","nuwax-file-server","logs"):E.join("/tmp","nuwax-file-server","logs")),CLI_IS_WINDOWS:process.platform==="win32",GIT_DEFAULT_AUTHOR_NAME:process.env.GIT_DEFAULT_AUTHOR_NAME||"Nuwax File Server",GIT_DEFAULT_AUTHOR_EMAIL:process.env.GIT_DEFAULT_AUTHOR_EMAIL||"git@nuwax.local",GIT_AUTO_GITIGNORE:process.env.GIT_AUTO_GITIGNORE?.toLowerCase()!=="false",GIT_GITIGNORE_ENTRIES:process.env.GIT_GITIGNORE_ENTRIES?process.env.GIT_GITIGNORE_ENTRIES.split("|").map(e=>e.trim()).filter(Boolean):["node_modules/",".pnpm-store/","dist/","build/",".idea/",".vscode/",".DS_Store",".npmrc",".agents/",".claude/",".opencode/",".codex/",".tmp/",".logs/","pnpm-lock.yaml","yarn.lock","package-lock.json"],GIT_ENABLED:process.env.GIT_ENABLED?.toLowerCase()==="true",GIT_USE_NATIVE:process.env.GIT_USE_NATIVE?.toLowerCase()!=="false",BASH_PATH:process.env.BASH_PATH||"",ZIP_WORKSPACE_EXCLUDE:process.env.ZIP_WORKSPACE_EXCLUDE?process.env.ZIP_WORKSPACE_EXCLUDE.split(",").map(e=>e.trim()).filter(Boolean):[".git",".tmp",".claude",".agents",".codex",".opencode",".logs",".npmrc","__pycache__","node_modules","dist","pnpm-lock.yaml","yarn.lock","package-lock.json"]};export default R;
package/dist/cli.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{Command as ee}from"commander";import{createRequire as te}from"module";import f from"path";import U from"os";import c from"fs-extra";import{spawn as E}from"cross-spawn";import V from"tree-kill";import{fileURLToPath as q}from"url";import{execFileSync as R}from"child_process";import M from"http";import{createRequire as G}from"module";var I=f.dirname(q(import.meta.url)),H=G(import.meta.url),n={name:"nuwax-file-server",pidDir:f.join(U.tmpdir(),"nuwax-file-server"),pidFileName:"server.pid",lockFileName:"start.lock",defaultStopTimeout:3e4,defaultStartTimeout:3e4,staleLockTimeout:12e4,checkInterval:500};function $(){return f.join(n.pidDir,n.pidFileName)}function F(){return f.join(n.pidDir,n.lockFileName)}function J(){let e=[f.join(I,"..","server.js"),f.join(I,"server.js")];for(let t of e)if(c.existsSync(t))return t;return e[0]}function W(){let e=["../../package.json","../package.json"];for(let t of e)try{let o=H(t);if(o?.version)return o.version}catch{}return"unknown"}function x(){try{let e=$();if(!c.existsSync(e))return null;let t=c.readFileSync(e,"utf8"),o=JSON.parse(t);return!o||typeof o.pid!="number"?null:o}catch(e){return e.code!=="ENOENT"&&console.error(`Read PID file failed: ${e.message}`),null}}function B(e){try{let t=$();c.ensureDirSync(n.pidDir),c.writeFileSync(t,JSON.stringify(e,null,2)),console.debug(`PID file written: ${t}`)}catch(t){throw console.error(`Write PID file failed: ${t.message}`),t}}function v(){try{let e=$();c.existsSync(e)&&(c.removeSync(e),console.debug(`PID file deleted: ${e}`))}catch(e){console.error(`Delete PID file failed: ${e.message}`)}}function g(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function K(e){try{return k()?R("powershell",["-NoProfile","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim():R("ps",["-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return""}}function X(e){if(!g(e))return!1;let t=K(e);if(!t)return!1;let o=t.toLowerCase(),s=f.basename(f.join(I,"..","server.js")).toLowerCase(),i=n.name.toLowerCase();return o.includes(s)||o.includes(i)}function z(){c.ensureDirSync(n.pidDir);let e=F(),t=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,o=JSON.stringify({pid:process.pid,token:t,createdAt:new Date().toISOString()},null,2);try{let s=c.openSync(e,"wx");return c.writeSync(s,o),{fd:s,token:t}}catch(s){if(s.code!=="EEXIST")throw s;try{let i=c.readFileSync(e,"utf8"),r=JSON.parse(i),a=Number(r?.pid),u=r?.createdAt?new Date(r.createdAt).getTime():0,l=Date.now()-u,C=Number.isFinite(a)&&a>0&&g(a),p=!u||Number.isNaN(l)||l>n.staleLockTimeout;if(!C||p){c.removeSync(e);let S=c.openSync(e,"wx");return c.writeSync(S,o),console.warn("Detected stale start lock, auto cleaned"),{fd:S,token:t}}}catch{c.removeSync(e);let r=c.openSync(e,"wx");return c.writeSync(r,o),console.warn("Detected invalid start lock, auto cleaned"),{fd:r,token:t}}throw s}}function Q(e){let t=e?.fd,o=e?.token;try{t!=null&&c.closeSync(t)}catch{}try{let s=F();if(c.existsSync(s)){let i=!1;if(!o)i=!0;else try{let r=c.readFileSync(s,"utf8");i=JSON.parse(r)?.token===o}catch{i=!0}i&&c.removeSync(s)}}catch{}}function k(){return process.platform==="win32"}async function Y(e=n.defaultStopTimeout){let t=x();return t?X(t.pid)?(console.log(`Existing service process detected (PID: ${t.pid}), stopping before start...`),await h(t.pid,!1)&&await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped gracefully`}):(console.warn(`Graceful stop timeout or failed for PID ${t.pid}, force stop...`),await h(t.pid,!0)?await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped forcibly`}):{success:!1,message:`Existing process ${t.pid} did not exit after force stop`}:{success:!1,message:`Failed to stop existing process ${t.pid}`})):(console.log(`Found stale PID file (PID: ${t.pid}), clean it...`),v(),{success:!0,message:"Stale PID file cleaned"}):{success:!0,message:"No existing service process"}}async function h(e,t=!1){return new Promise(o=>{if(!g(e)){console.debug(`Process ${e} does not exist, already stopped`),o(!0);return}let s=t?"SIGKILL":"SIGTERM",i=k()?"taskkill":"tree-kill";if(console.debug(`Use ${i} to stop process ${e} (signal: ${s})`),k()){let r=t?["/F","/PID",String(e)]:["/PID",String(e)],a=E("taskkill",r,{stdio:["ignore","pipe","pipe"],windowsHide:!0}),u="";a.stdout.on("data",l=>{u+=l.toString()}),a.stderr.on("data",l=>{u+=l.toString()}),a.on("error",l=>{console.error(`Stop process failed: ${l.message}`),o(!1)}),a.on("close",l=>{l===0?(console.debug(`Process ${e} stopped`),o(!0)):(console.warn(`taskkill exit code: ${l}, output: ${u}`),t?o(!1):h(e,!0).then(o))})}else V(e,s,r=>{r?r.code==="ESRCH"?(console.debug(`Process ${e} does not exist`),o(!0)):(console.error(`Stop process failed: ${r.message}`),o(!1)):(console.debug(`Process ${e} stopped`),o(!0))})})}async function D(e,t=n.defaultStopTimeout){let o=Date.now();for(;g(e);){if(Date.now()-o>t)return console.warn(`Wait for process ${e} to stop timeout (${t}ms)`),!1;await new Promise(i=>setTimeout(i,n.checkInterval))}let s=Date.now()-o;return console.debug(`Process ${e} stopped after ${s}ms`),!0}async function Z(e,t=n.defaultStartTimeout){let o=Number(e);if(!Number.isFinite(o)||o<=0)return!1;let s=Date.now();for(;Date.now()-s<=t;){if(await new Promise(r=>{let a=M.get({host:"127.0.0.1",port:o,path:"/health",timeout:Math.min(2e3,n.checkInterval*4)},u=>{r(u.statusCode>=200&&u.statusCode<300),u.resume()});a.on("timeout",()=>{a.destroy(),r(!1)}),a.on("error",()=>r(!1))}))return!0;await new Promise(r=>setTimeout(r,n.checkInterval))}return!1}async function N(e={}){let{env:t,port:o,config:s}=e,i=null;console.log(`Start service ${n.name}...`);try{i=z()}catch(r){return r.code==="EEXIST"?{success:!1,pid:null,message:"Another start operation is in progress, please retry later"}:{success:!1,pid:null,message:`Acquire start lock failed: ${r.message}`}}try{let r=Number(e.timeout)||n.defaultStopTimeout,a=await Y(r);if(!a.success)return{success:!1,pid:null,message:`Service start blocked: ${a.message}`};let u={...process.env};t&&(u.NODE_ENV=t,console.log(`Environment: ${t}`)),o&&(u.PORT=o,console.log(`Port: ${o}`)),s&&(u.CONFIG_FILE=s,console.log(`Configuration file: ${s}`));let l=J(),p=E("node",[l,...[]],{env:u,stdio:["pipe","pipe","pipe"],detached:!0,cwd:process.cwd()});if(p.stdout.on("data",m=>{process.stdout.write(m)}),p.stderr.on("data",m=>{process.stderr.write(m)}),p.on("error",m=>{console.error(`Start service failed: ${m.message}`)}),await new Promise(m=>setTimeout(m,2e3)),!g(p.pid))return{success:!1,pid:null,message:"Service start failed"};let S={pid:p.pid,startedAt:new Date().toISOString(),env:t||process.env.NODE_ENV||"production",port:o||process.env.PORT||"60000",version:W(),platform:process.platform};B(S);let P=Number(e.startTimeout)||n.defaultStartTimeout;return await Z(S.port,P)?(p.unref(),console.log(`Service started (PID: ${p.pid})`),console.log(`Service address: http://localhost:${S.port}`),{success:!0,pid:p.pid,message:"Service started successfully"}):(console.error(`Service health check timeout (${P}ms), stop failed instance...`),await h(p.pid,!0),v(),{success:!1,pid:null,message:`Service health check timeout (${P}ms)`})}finally{Q(i)}}async function T(e={}){let{force:t=!1,timeout:o=n.defaultStopTimeout}=e;console.log(`Stop service ${n.name}...`);let s=x();if(!s)return{success:!1,message:"Service not found"};if(!g(s.pid))return console.log("Service process has stopped, clean PID file..."),v(),{success:!0,message:"Service has stopped (process has exited)"};if(!await h(s.pid,t))return{success:!1,message:"Stop service failed"};let r=await D(s.pid,o);return v(),r?{success:!0,message:"Service has stopped"}:{success:!1,message:"Service stop timeout"}}async function O(e={}){console.log(`Restart service ${n.name}...`);let t=await T(e);!t.success&&t.message!=="Service not found"&&console.warn(`Stop service failed: ${t.message}`),await new Promise(s=>setTimeout(s,2e3));let o=await N(e);return o.success?{success:!0,pid:o.pid,message:"Service has restarted"}:{success:!1,pid:null,message:`Restart failed: ${o.message}`}}function _(){let e=x();return e?g(e.pid)?{running:!0,pidInfo:e,message:"Service running"}:{running:!1,pidInfo:e,message:"Service process does not exist"}:{running:!1,pidInfo:null,message:"Service not running"}}function L(e){try{let t=new Date(e),o=new Date;if(isNaN(t.getTime()))return"unknown";let s=Math.floor((o-t)/1e3),i=Math.floor(s/3600),r=Math.floor(s%3600/60),a=s%60;return i>0?`${i} hours ${r} minutes ${a} seconds`:r>0?`${r} minutes ${a} seconds`:`${a} seconds`}catch{return"unknown"}}var Pe=te(import.meta.url),A="1.3.4",d=new ee,w={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m"};function j(e){console.error(`${w.red}ERROR: ${e}${w.reset}`)}function b(e){console.log(`${w.green}${e}${w.reset}`)}function oe(e){console.log(`${w.blue}${e}${w.reset}`)}function y(e){return async(...t)=>{try{let o=await e(...t);o&&o.success===!1?(j(o.message||"Command failed"),process.exitCode=1):process.exitCode=0}catch(o){j(o?.message||"Command failed with unexpected error"),process.exitCode=1}}}async function se(e){let t=await N({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(`Service started (PID: ${t.pid})`),t}async function re(e){let t=await T({force:e.force,timeout:Number(e.timeout)});return t.success&&b(t.message||"Service stopped"),t}async function ne(e){let t=await O({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(t.message||"Service restarted"),t}function ie(){let e=_();return oe(`${n.name} service status:`),console.log(""),console.log(` Service name: ${n.name}`),console.log(` Running status: ${e.running?"Running":"Stopped"}`),console.log(` Message: ${e.message}`),console.log(` PID file: ${$()}`),e.pidInfo&&(console.log(` Process ID: ${e.pidInfo.pid}`),console.log(` Environment: ${e.pidInfo.env||"Unknown"}`),console.log(` Port: ${e.pidInfo.port||"Unknown"}`),console.log(` Version: ${e.pidInfo.version||A}`),console.log(` Platform: ${e.pidInfo.platform||process.platform}`),console.log(` Started at: ${e.pidInfo.startedAt||"Unknown"}`),console.log(` Uptime: ${L(e.pidInfo.startedAt)}`)),console.log(""),{success:e.running,message:e.message}}function ce(){d.name("nuwax-file-server").description("Cross-platform file service deployment tool, supporting start/stop/restart/status").version(A,"-v, --version","Display version number").helpOption("-h, --help","Display help information"),d.command("start").allowUnknownOption().description("Start service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(se)),d.command("stop").description("Stop service").option("--force","Force stop").option("--timeout <ms>","\u505C\u6B62\u670D\u52A1\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).action(y(re)),d.command("restart").allowUnknownOption().description("Restart service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(ne)),d.command("status").description("View service status").action(y(ie)),d.command("help").description("Display help information").action(()=>{d.outputHelp()}),d.parse(process.argv),process.argv.slice(2).length||(d.outputHelp(),process.exitCode=0)}ce();
2
+ import{Command as ee}from"commander";import{createRequire as te}from"module";import f from"path";import U from"os";import c from"fs-extra";import{spawn as E}from"cross-spawn";import V from"tree-kill";import{fileURLToPath as q}from"url";import{execFileSync as R}from"child_process";import M from"http";import{createRequire as G}from"module";var I=f.dirname(q(import.meta.url)),H=G(import.meta.url),n={name:"nuwax-file-server",pidDir:f.join(U.tmpdir(),"nuwax-file-server"),pidFileName:"server.pid",lockFileName:"start.lock",defaultStopTimeout:3e4,defaultStartTimeout:3e4,staleLockTimeout:12e4,checkInterval:500};function $(){return f.join(n.pidDir,n.pidFileName)}function F(){return f.join(n.pidDir,n.lockFileName)}function J(){let e=[f.join(I,"..","server.js"),f.join(I,"server.js")];for(let t of e)if(c.existsSync(t))return t;return e[0]}function W(){let e=["../../package.json","../package.json"];for(let t of e)try{let o=H(t);if(o?.version)return o.version}catch{}return"unknown"}function x(){try{let e=$();if(!c.existsSync(e))return null;let t=c.readFileSync(e,"utf8"),o=JSON.parse(t);return!o||typeof o.pid!="number"?null:o}catch(e){return e.code!=="ENOENT"&&console.error(`Read PID file failed: ${e.message}`),null}}function B(e){try{let t=$();c.ensureDirSync(n.pidDir),c.writeFileSync(t,JSON.stringify(e,null,2)),console.debug(`PID file written: ${t}`)}catch(t){throw console.error(`Write PID file failed: ${t.message}`),t}}function v(){try{let e=$();c.existsSync(e)&&(c.removeSync(e),console.debug(`PID file deleted: ${e}`))}catch(e){console.error(`Delete PID file failed: ${e.message}`)}}function g(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function K(e){try{return k()?R("powershell",["-NoProfile","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim():R("ps",["-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return""}}function X(e){if(!g(e))return!1;let t=K(e);if(!t)return!1;let o=t.toLowerCase(),s=f.basename(f.join(I,"..","server.js")).toLowerCase(),i=n.name.toLowerCase();return o.includes(s)||o.includes(i)}function z(){c.ensureDirSync(n.pidDir);let e=F(),t=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,o=JSON.stringify({pid:process.pid,token:t,createdAt:new Date().toISOString()},null,2);try{let s=c.openSync(e,"wx");return c.writeSync(s,o),{fd:s,token:t}}catch(s){if(s.code!=="EEXIST")throw s;try{let i=c.readFileSync(e,"utf8"),r=JSON.parse(i),a=Number(r?.pid),u=r?.createdAt?new Date(r.createdAt).getTime():0,l=Date.now()-u,C=Number.isFinite(a)&&a>0&&g(a),p=!u||Number.isNaN(l)||l>n.staleLockTimeout;if(!C||p){c.removeSync(e);let S=c.openSync(e,"wx");return c.writeSync(S,o),console.warn("Detected stale start lock, auto cleaned"),{fd:S,token:t}}}catch{c.removeSync(e);let r=c.openSync(e,"wx");return c.writeSync(r,o),console.warn("Detected invalid start lock, auto cleaned"),{fd:r,token:t}}throw s}}function Q(e){let t=e?.fd,o=e?.token;try{t!=null&&c.closeSync(t)}catch{}try{let s=F();if(c.existsSync(s)){let i=!1;if(!o)i=!0;else try{let r=c.readFileSync(s,"utf8");i=JSON.parse(r)?.token===o}catch{i=!0}i&&c.removeSync(s)}}catch{}}function k(){return process.platform==="win32"}async function Y(e=n.defaultStopTimeout){let t=x();return t?X(t.pid)?(console.log(`Existing service process detected (PID: ${t.pid}), stopping before start...`),await h(t.pid,!1)&&await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped gracefully`}):(console.warn(`Graceful stop timeout or failed for PID ${t.pid}, force stop...`),await h(t.pid,!0)?await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped forcibly`}):{success:!1,message:`Existing process ${t.pid} did not exit after force stop`}:{success:!1,message:`Failed to stop existing process ${t.pid}`})):(console.log(`Found stale PID file (PID: ${t.pid}), clean it...`),v(),{success:!0,message:"Stale PID file cleaned"}):{success:!0,message:"No existing service process"}}async function h(e,t=!1){return new Promise(o=>{if(!g(e)){console.debug(`Process ${e} does not exist, already stopped`),o(!0);return}let s=t?"SIGKILL":"SIGTERM",i=k()?"taskkill":"tree-kill";if(console.debug(`Use ${i} to stop process ${e} (signal: ${s})`),k()){let r=t?["/F","/PID",String(e)]:["/PID",String(e)],a=E("taskkill",r,{stdio:["ignore","pipe","pipe"],windowsHide:!0}),u="";a.stdout.on("data",l=>{u+=l.toString()}),a.stderr.on("data",l=>{u+=l.toString()}),a.on("error",l=>{console.error(`Stop process failed: ${l.message}`),o(!1)}),a.on("close",l=>{l===0?(console.debug(`Process ${e} stopped`),o(!0)):(console.warn(`taskkill exit code: ${l}, output: ${u}`),t?o(!1):h(e,!0).then(o))})}else V(e,s,r=>{r?r.code==="ESRCH"?(console.debug(`Process ${e} does not exist`),o(!0)):(console.error(`Stop process failed: ${r.message}`),o(!1)):(console.debug(`Process ${e} stopped`),o(!0))})})}async function D(e,t=n.defaultStopTimeout){let o=Date.now();for(;g(e);){if(Date.now()-o>t)return console.warn(`Wait for process ${e} to stop timeout (${t}ms)`),!1;await new Promise(i=>setTimeout(i,n.checkInterval))}let s=Date.now()-o;return console.debug(`Process ${e} stopped after ${s}ms`),!0}async function Z(e,t=n.defaultStartTimeout){let o=Number(e);if(!Number.isFinite(o)||o<=0)return!1;let s=Date.now();for(;Date.now()-s<=t;){if(await new Promise(r=>{let a=M.get({host:"127.0.0.1",port:o,path:"/health",timeout:Math.min(2e3,n.checkInterval*4)},u=>{r(u.statusCode>=200&&u.statusCode<300),u.resume()});a.on("timeout",()=>{a.destroy(),r(!1)}),a.on("error",()=>r(!1))}))return!0;await new Promise(r=>setTimeout(r,n.checkInterval))}return!1}async function N(e={}){let{env:t,port:o,config:s}=e,i=null;console.log(`Start service ${n.name}...`);try{i=z()}catch(r){return r.code==="EEXIST"?{success:!1,pid:null,message:"Another start operation is in progress, please retry later"}:{success:!1,pid:null,message:`Acquire start lock failed: ${r.message}`}}try{let r=Number(e.timeout)||n.defaultStopTimeout,a=await Y(r);if(!a.success)return{success:!1,pid:null,message:`Service start blocked: ${a.message}`};let u={...process.env};t&&(u.NODE_ENV=t,console.log(`Environment: ${t}`)),o&&(u.PORT=o,console.log(`Port: ${o}`)),s&&(u.CONFIG_FILE=s,console.log(`Configuration file: ${s}`));let l=J(),p=E("node",[l,...[]],{env:u,stdio:["pipe","pipe","pipe"],detached:!0,cwd:process.cwd()});if(p.stdout.on("data",m=>{process.stdout.write(m)}),p.stderr.on("data",m=>{process.stderr.write(m)}),p.on("error",m=>{console.error(`Start service failed: ${m.message}`)}),await new Promise(m=>setTimeout(m,2e3)),!g(p.pid))return{success:!1,pid:null,message:"Service start failed"};let S={pid:p.pid,startedAt:new Date().toISOString(),env:t||process.env.NODE_ENV||"production",port:o||process.env.PORT||"60000",version:W(),platform:process.platform};B(S);let P=Number(e.startTimeout)||n.defaultStartTimeout;return await Z(S.port,P)?(p.unref(),console.log(`Service started (PID: ${p.pid})`),console.log(`Service address: http://localhost:${S.port}`),{success:!0,pid:p.pid,message:"Service started successfully"}):(console.error(`Service health check timeout (${P}ms), stop failed instance...`),await h(p.pid,!0),v(),{success:!1,pid:null,message:`Service health check timeout (${P}ms)`})}finally{Q(i)}}async function T(e={}){let{force:t=!1,timeout:o=n.defaultStopTimeout}=e;console.log(`Stop service ${n.name}...`);let s=x();if(!s)return{success:!1,message:"Service not found"};if(!g(s.pid))return console.log("Service process has stopped, clean PID file..."),v(),{success:!0,message:"Service has stopped (process has exited)"};if(!await h(s.pid,t))return{success:!1,message:"Stop service failed"};let r=await D(s.pid,o);return v(),r?{success:!0,message:"Service has stopped"}:{success:!1,message:"Service stop timeout"}}async function O(e={}){console.log(`Restart service ${n.name}...`);let t=await T(e);!t.success&&t.message!=="Service not found"&&console.warn(`Stop service failed: ${t.message}`),await new Promise(s=>setTimeout(s,2e3));let o=await N(e);return o.success?{success:!0,pid:o.pid,message:"Service has restarted"}:{success:!1,pid:null,message:`Restart failed: ${o.message}`}}function _(){let e=x();return e?g(e.pid)?{running:!0,pidInfo:e,message:"Service running"}:{running:!1,pidInfo:e,message:"Service process does not exist"}:{running:!1,pidInfo:null,message:"Service not running"}}function L(e){try{let t=new Date(e),o=new Date;if(isNaN(t.getTime()))return"unknown";let s=Math.floor((o-t)/1e3),i=Math.floor(s/3600),r=Math.floor(s%3600/60),a=s%60;return i>0?`${i} hours ${r} minutes ${a} seconds`:r>0?`${r} minutes ${a} seconds`:`${a} seconds`}catch{return"unknown"}}var Pe=te(import.meta.url),A="1.3.5",d=new ee,w={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m"};function j(e){console.error(`${w.red}ERROR: ${e}${w.reset}`)}function b(e){console.log(`${w.green}${e}${w.reset}`)}function oe(e){console.log(`${w.blue}${e}${w.reset}`)}function y(e){return async(...t)=>{try{let o=await e(...t);o&&o.success===!1?(j(o.message||"Command failed"),process.exitCode=1):process.exitCode=0}catch(o){j(o?.message||"Command failed with unexpected error"),process.exitCode=1}}}async function se(e){let t=await N({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(`Service started (PID: ${t.pid})`),t}async function re(e){let t=await T({force:e.force,timeout:Number(e.timeout)});return t.success&&b(t.message||"Service stopped"),t}async function ne(e){let t=await O({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(t.message||"Service restarted"),t}function ie(){let e=_();return oe(`${n.name} service status:`),console.log(""),console.log(` Service name: ${n.name}`),console.log(` Running status: ${e.running?"Running":"Stopped"}`),console.log(` Message: ${e.message}`),console.log(` PID file: ${$()}`),e.pidInfo&&(console.log(` Process ID: ${e.pidInfo.pid}`),console.log(` Environment: ${e.pidInfo.env||"Unknown"}`),console.log(` Port: ${e.pidInfo.port||"Unknown"}`),console.log(` Version: ${e.pidInfo.version||A}`),console.log(` Platform: ${e.pidInfo.platform||process.platform}`),console.log(` Started at: ${e.pidInfo.startedAt||"Unknown"}`),console.log(` Uptime: ${L(e.pidInfo.startedAt)}`)),console.log(""),{success:e.running,message:e.message}}function ce(){d.name("nuwax-file-server").description("Cross-platform file service deployment tool, supporting start/stop/restart/status").version(A,"-v, --version","Display version number").helpOption("-h, --help","Display help information"),d.command("start").allowUnknownOption().description("Start service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(se)),d.command("stop").description("Stop service").option("--force","Force stop").option("--timeout <ms>","\u505C\u6B62\u670D\u52A1\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).action(y(re)),d.command("restart").allowUnknownOption().description("Restart service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(ne)),d.command("status").description("View service status").action(y(ie)),d.command("help").description("Display help information").action(()=>{d.outputHelp()}),d.parse(process.argv),process.argv.slice(2).length||(d.outputHelp(),process.exitCode=0)}ce();
@@ -95,6 +95,7 @@ GIT_DEFAULT_AUTHOR_EMAIL=git@nuwax.com
95
95
  GIT_AUTO_GITIGNORE=true
96
96
  GIT_GITIGNORE_ENTRIES=node_modules/|.pnpm-store/|dist/|dist-packages/|build/|.idea/|.vscode/|.DS_Store|.npmrc|.agents/|.claude/|.opencode/|.codex/|.tmp/|.logs/|pnpm-lock.yaml|yarn.lock|package-lock.json
97
97
  GIT_ENABLED=true
98
+ GIT_USE_NATIVE=true
98
99
 
99
100
  # Windows 专用路径(Linux/macOS 留空)
100
101
  BASH_PATH=
@@ -95,6 +95,7 @@ GIT_DEFAULT_AUTHOR_EMAIL=git@nuwax.com
95
95
  GIT_AUTO_GITIGNORE=true
96
96
  GIT_GITIGNORE_ENTRIES=node_modules/|.pnpm-store/|dist/|dist-packages/|build/|.idea/|.vscode/|.DS_Store|.npmrc|.agents/|.claude/|.opencode/|.codex/|.tmp/|.logs/|pnpm-lock.yaml|yarn.lock|package-lock.json
97
97
  GIT_ENABLED=true
98
+ GIT_USE_NATIVE=true
98
99
 
99
100
  # Windows 专用路径(Linux/macOS 留空)
100
101
  BASH_PATH=
@@ -1 +1 @@
1
- import b from"express";import k from"multer";import f from"fs";import w from"path";import{ValidationError as F,asyncHandler as d}from"../utils/error/errorHandler.js";import{log as u}from"../utils/log/logUtils.js";import N from"../appConfig/index.js";import{createWorkspace as z,pushSkillsToWorkspace as S,initProjectTemplate as j,installProjectDependencies as C,executeCommand as A,deleteWorkspace as O,zipWorkspace as D,buildAgentPackage as P,cleanupBuildArtifacts as E}from"../utils/computer/computerUtils.js";import{getFileList as T,updateFiles as U,uploadFile as R,uploadFiles as x,downloadAllFiles as q,getLatestLogs as v,importProject as H}from"../utils/computer/computerFileUtils.js";const y=b.Router(),h=k({storage:k.diskStorage({destination:(s,a,t)=>{try{const e=N.COMPUTER_WORKSPACE_DIR;if(!e)return t(new Error("COMPUTER_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));const o=s.body?.userId||"unknown",i=s.body?.cId||"unknown",n=w.join(e,String(o),String(i),".tmp");f.existsSync(n)||f.mkdirSync(n,{recursive:!0}),t(null,n)}catch(e){t(e)}},filename:(s,a,t)=>{const e=w.extname(a.originalname)||".zip",o=w.basename(a.originalname,e),i=`${Date.now()}_${Math.round(Math.random()*1e6)}`;t(null,`${o}_${i}${e}`)}}),limits:{fileSize:N.UPLOAD_MAX_FILE_SIZE_BYTES}});function _(s,a,t,e){if(s&&s.name==="MulterError"||s&&(s.name==="ValidationError"||s instanceof F))return e(s);e(s)}const M=[{path:"/create-workspace",method:"post",middleware:h.single("file"),handler:d(async(s,a)=>{const{userId:t,cId:e}=s.body||{},o=s.file||null,i=`computer:${t}:${e}`;u(i,"INFO","Create workspace request",{userId:t,cId:e,hasFile:!!o,fileName:o?.originalname,fileSize:o?.size});const n=await z(t,e,o);a.status(200).json({success:!0,...n})})},{path:"/create-workspace-v2",method:"post",middleware:h.single("file"),handler:d(async(s,a)=>{const{userId:t,cId:e,skillUrls:o,mcpServersConfig:i,hooksConfig:n,permissionsConfig:r,hookScripts:l}=s.body||{},c=s.file||null,g=`computer:${t}:${e}`;let m=o;if(typeof o=="string")try{const $=JSON.parse(o);m=Array.isArray($)?$:[o]}catch{m=[o]}let p=l;if(typeof l=="string")try{p=JSON.parse(l)}catch{p=null}u(g,"INFO","Create workspace v2 request",{userId:t,cId:e,hasFile:!!c,fileName:c?.originalname,fileSize:c?.size,skillUrlsCount:Array.isArray(m)?m.length:0,hasMcpServersConfig:!!i,hasHooksConfig:!!n,hasPermissionsConfig:!!r,hookScriptsCount:Array.isArray(p)?p.length:0});const I=await z(t,e,c,m,i,r,n,p);a.status(200).json({success:!0,...I})})},{path:"/push-skills-to-workspace",method:"post",middleware:h.single("file"),handler:d(async(s,a)=>{const{userId:t,cId:e}=s.body||{},o=s.file||null,i=`computer:${t}:${e}`;u(i,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42",{userId:t,cId:e,hasFile:!!o,fileName:o?.originalname,fileSize:o?.size});const n=await S(t,e,o);a.status(200).json({success:!0,...n})})},{path:"/push-skills-to-workspace-v2",method:"post",middleware:h.single("file"),handler:d(async(s,a)=>{const{userId:t,cId:e,skillUrls:o}=s.body||{},i=s.file||null,n=`computer:${t}:${e}`;let r=o;if(typeof o=="string")try{const c=JSON.parse(o);r=Array.isArray(c)?c:[o]}catch{r=[o]}u(n,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42(v2)",{userId:t,cId:e,hasFile:!!i,fileName:i?.originalname,fileSize:i?.size,skillUrlsCount:Array.isArray(r)?r.length:0});const l=await S(t,e,i,r);a.status(200).json({success:!0,...l})})},{path:"/get-file-list",method:"get",handler:d(async(s,a)=>{const{userId:t,cId:e,proxyPath:o,customTargetDir:i}=s.query,n=await T(t,e,o,i);a.status(200).json({success:!0,...n})})},{path:"/files-update",method:"post",handler:d(async(s,a)=>{const{userId:t,cId:e,files:o,customTargetDir:i}=s.body||{},n=`computer:${t}:${e}`;u(n,"INFO","Files update",{userId:t,cId:e,filesCount:o?o.length:0}),o&&Array.isArray(o)&&o.forEach(l=>{if(l&&typeof l.contents=="string"&&l.contents)try{l.contents=decodeURIComponent(l.contents)}catch(c){u(n,"WARN","Decode file content failed",{fileName:l.name,error:c.message})}});const r=await U(t,e,o,i);a.status(200).json(r)})},{path:"/upload-file",method:"post",middleware:h.single("file"),handler:d(async(s,a)=>{const{userId:t,cId:e,filePath:o,customTargetDir:i}=s.body||{},n=s.file,r=`computer:${t}:${e}`;u(r,"INFO","Upload single file",{userId:t,cId:e,filePath:o});const c={buffer:await f.promises.readFile(n.path),originalname:n.originalname,mimetype:n.mimetype,size:n.size};try{const g=await R(t,e,c,o,i);a.status(200).json(g)}finally{f.existsSync(n.path)&&await f.promises.unlink(n.path)}})},{path:"/import-project",method:"post",middleware:h.single("file"),handler:d(async(s,a)=>{const{userId:t,cId:e,customTargetDir:o}=s.body||{},i=s.file,n=`computer:${t}:${e}`;if(u(n,"INFO","Import project request",{userId:t,cId:e,fileName:i?.originalname,fileSize:i?.size}),!i)throw new F("file is required",{field:"file"});const r=await H(t,e,i,o);a.status(200).json(r)})},{path:"/upload-files",method:"post",middleware:h.array("files"),handler:d(async(s,a)=>{const{userId:t,cId:e,filePaths:o,customTargetDir:i}=s.body||{},n=s.files||[],r=`computer:${t}:${e}`,l=Array.isArray(o)?o:typeof o=="string"?[o]:o;u(r,"INFO","Batch upload files request",{userId:t,cId:e,filesCount:n.length,filePathsCount:Array.isArray(l)?l.length:0});const c=[],g=[];try{for(const p of n){g.push(p.path);const I=await f.promises.readFile(p.path);c.push({buffer:I,originalname:p.originalname,mimetype:p.mimetype,size:p.size})}const m=await x(t,e,c,l,i);a.status(200).json(m)}finally{for(const m of g)if(f.existsSync(m))try{await f.promises.unlink(m)}catch(p){u(r,"WARN","Clean temporary file failed",{tempPath:m,error:p.message})}}})},{path:"/install-project",method:"post",handler:d(async(s,a)=>{const{userId:t,cId:e,programmingLanguage:o}=s.body||{},i=`computer:${t}:${e}`;u(i,"INFO","Install project request",{userId:t,cId:e,programmingLanguage:o});const n=await C(t,e,o);a.status(200).json({success:!0,...n})})},{path:"/init-project-template",method:"post",middleware:h.single("file"),handler:d(async(s,a)=>{const{userId:t,cId:e,enableGit:o}=s.body||{},i=s.file||null,n=`computer:${t}:${e}`;u(n,"INFO","Init project template request",{userId:t,cId:e,hasFile:!!i,fileName:i?.originalname,fileSize:i?.size,enableGit:o});const r=await j(t,e,i,o);a.status(200).json({success:!0,...r})})},{path:"/download-all-files",method:"get",handler:d(async(s,a)=>{const{userId:t,cId:e,customTargetDir:o}=s.query||{},i=`computer:${t}:${e}`;u(i,"INFO","Download all files request",{userId:t,cId:e});const{archive:n,zipFileName:r}=await q(t,e,o);a.setHeader("Content-Type","application/zip");const l=encodeURIComponent(r);a.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),n.on("error",c=>{a.destroy(c)}),n.pipe(a),n.finalize()})},{path:"/execute-command",method:"post",handler:d(async(s,a)=>{const{userId:t,cId:e,command:o}=s.body||{},i=`computer:${t}:${e}`;u(i,"INFO","Execute command request",{userId:t,cId:e,command:o});const n=await A(t,e,o);a.status(200).json({success:!0,...n})})},{path:"/delete-workspace",method:"post",handler:d(async(s,a)=>{const{userId:t,cId:e}=s.body||{},o=`computer:${t}:${e}`;u(o,"INFO","Delete workspace request",{userId:t,cId:e});const i=await O(t,e);a.status(200).json({success:!0,...i})})},{path:"/get-logs",method:"get",handler:d(async(s,a)=>{const{userId:t,cId:e,tailLines:o}=s.query,i=o?parseInt(o,10):200,n=Number.isFinite(i)&&i>0?i:200,r=await v(t,e,n);a.status(200).json(r)})},{path:"/zip-workspace",method:"post",handler:d(async(s,a)=>{const{userId:t,cId:e,excludeDirs:o}=s.body||{},i=`computer:${t}:${e}`;u(i,"INFO","Zip workspace request",{userId:t,cId:e,hasExcludeDirs:!!o});const{archive:n,zipFileName:r}=await D(t,e,o||null);a.setHeader("Content-Type","application/zip");const l=encodeURIComponent(r);a.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),n.on("error",c=>{a.destroy(c)}),n.pipe(a),n.finalize()})},{path:"/build-agent-package",method:"post",handler:d(async(s,a)=>{const{userId:t,cId:e,agentId:o,version:i}=s.body||{},n=`computer:${t}:${e}`;u(n,"INFO","Build agent package request",{userId:t,cId:e,agentId:o,version:i});const r=await P(t,e,o,i);a.status(200).json({success:!0,...r})})},{path:"/cleanup-build-artifacts",method:"post",handler:d(async(s,a)=>{const{userId:t,cId:e}=s.body||{},o=`computer:${t}:${e}`;u(o,"INFO","Cleanup build artifacts request",{userId:t,cId:e});const i=await E(t,e);a.status(200).json({success:!0,...i})})}];M.forEach(s=>{if(s.middleware)y[s.method](s.path,s.middleware,s.handler);else if(s.customHandler){const a=[];s.handler&&a.push(s.handler),s.decodeMiddleware&&a.push(s.decodeMiddleware),a.push(_),a.push(s.customHandler),y[s.method](s.path,...a)}else y[s.method](s.path,s.handler)});export default y;
1
+ import b from"express";import F from"multer";import f from"fs";import w from"path";import{ValidationError as k,asyncHandler as c}from"../utils/error/errorHandler.js";import{log as d}from"../utils/log/logUtils.js";import N from"../appConfig/index.js";import{createWorkspace as z,pushSkillsToWorkspace as S,initProjectTemplate as j,installProjectDependencies as C,executeCommand as A,deleteWorkspace as O,zipWorkspace as D,buildAgentPackage as P,cleanupBuildArtifacts as T}from"../utils/computer/computerUtils.js";import{getFileList as E,updateFiles as U,uploadFile as R,uploadFiles as x,generateFile as q,downloadAllFiles as v,getLatestLogs as H,importProject as _}from"../utils/computer/computerFileUtils.js";const y=b.Router(),h=F({storage:F.diskStorage({destination:(s,n,t)=>{try{const e=N.COMPUTER_WORKSPACE_DIR;if(!e)return t(new Error("COMPUTER_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));const o=s.body?.userId||"unknown",a=s.body?.cId||"unknown",i=w.join(e,String(o),String(a),".tmp");f.existsSync(i)||f.mkdirSync(i,{recursive:!0}),t(null,i)}catch(e){t(e)}},filename:(s,n,t)=>{const e=w.extname(n.originalname)||".zip",o=w.basename(n.originalname,e),a=`${Date.now()}_${Math.round(Math.random()*1e6)}`;t(null,`${o}_${a}${e}`)}}),limits:{fileSize:N.UPLOAD_MAX_FILE_SIZE_BYTES}});function L(s,n,t,e){if(s&&s.name==="MulterError"||s&&(s.name==="ValidationError"||s instanceof k))return e(s);e(s)}const M=[{path:"/create-workspace",method:"post",middleware:h.single("file"),handler:c(async(s,n)=>{const{userId:t,cId:e}=s.body||{},o=s.file||null,a=`computer:${t}:${e}`;d(a,"INFO","Create workspace request",{userId:t,cId:e,hasFile:!!o,fileName:o?.originalname,fileSize:o?.size});const i=await z(t,e,o);n.status(200).json({success:!0,...i})})},{path:"/create-workspace-v2",method:"post",middleware:h.single("file"),handler:c(async(s,n)=>{const{userId:t,cId:e,skillUrls:o,mcpServersConfig:a,hooksConfig:i,permissionsConfig:r,hookScripts:l}=s.body||{},u=s.file||null,g=`computer:${t}:${e}`;let m=o;if(typeof o=="string")try{const $=JSON.parse(o);m=Array.isArray($)?$:[o]}catch{m=[o]}let p=l;if(typeof l=="string")try{p=JSON.parse(l)}catch{p=null}d(g,"INFO","Create workspace v2 request",{userId:t,cId:e,hasFile:!!u,fileName:u?.originalname,fileSize:u?.size,skillUrlsCount:Array.isArray(m)?m.length:0,hasMcpServersConfig:!!a,hasHooksConfig:!!i,hasPermissionsConfig:!!r,hookScriptsCount:Array.isArray(p)?p.length:0});const I=await z(t,e,u,m,a,r,i,p);n.status(200).json({success:!0,...I})})},{path:"/push-skills-to-workspace",method:"post",middleware:h.single("file"),handler:c(async(s,n)=>{const{userId:t,cId:e}=s.body||{},o=s.file||null,a=`computer:${t}:${e}`;d(a,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42",{userId:t,cId:e,hasFile:!!o,fileName:o?.originalname,fileSize:o?.size});const i=await S(t,e,o);n.status(200).json({success:!0,...i})})},{path:"/push-skills-to-workspace-v2",method:"post",middleware:h.single("file"),handler:c(async(s,n)=>{const{userId:t,cId:e,skillUrls:o}=s.body||{},a=s.file||null,i=`computer:${t}:${e}`;let r=o;if(typeof o=="string")try{const u=JSON.parse(o);r=Array.isArray(u)?u:[o]}catch{r=[o]}d(i,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42(v2)",{userId:t,cId:e,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size,skillUrlsCount:Array.isArray(r)?r.length:0});const l=await S(t,e,a,r);n.status(200).json({success:!0,...l})})},{path:"/get-file-list",method:"get",handler:c(async(s,n)=>{const{userId:t,cId:e,proxyPath:o,customTargetDir:a}=s.query,i=await E(t,e,o,a);n.status(200).json({success:!0,...i})})},{path:"/files-update",method:"post",handler:c(async(s,n)=>{const{userId:t,cId:e,files:o,customTargetDir:a}=s.body||{},i=`computer:${t}:${e}`;d(i,"INFO","Files update",{userId:t,cId:e,filesCount:o?o.length:0}),o&&Array.isArray(o)&&o.forEach(l=>{if(l&&typeof l.contents=="string"&&l.contents)try{l.contents=decodeURIComponent(l.contents)}catch(u){d(i,"WARN","Decode file content failed",{fileName:l.name,error:u.message})}});const r=await U(t,e,o,a);n.status(200).json(r)})},{path:"/upload-file",method:"post",middleware:h.single("file"),handler:c(async(s,n)=>{const{userId:t,cId:e,filePath:o,customTargetDir:a}=s.body||{},i=s.file,r=`computer:${t}:${e}`;d(r,"INFO","Upload single file",{userId:t,cId:e,filePath:o});const u={buffer:await f.promises.readFile(i.path),originalname:i.originalname,mimetype:i.mimetype,size:i.size};try{const g=await R(t,e,u,o,a);n.status(200).json(g)}finally{f.existsSync(i.path)&&await f.promises.unlink(i.path)}})},{path:"/generate-file",method:"post",handler:c(async(s,n)=>{const{userId:t,cId:e,fileName:o,content:a,customTargetDir:i}=s.body||{},r=`computer:${t}:${e}`;d(r,"INFO","Generate file request",{userId:t,cId:e,fileName:o,contentLength:typeof a=="string"?a.length:0});const l=await q(t,e,o,a,i);n.status(200).json(l)})},{path:"/import-project",method:"post",middleware:h.single("file"),handler:c(async(s,n)=>{const{userId:t,cId:e,customTargetDir:o}=s.body||{},a=s.file,i=`computer:${t}:${e}`;if(d(i,"INFO","Import project request",{userId:t,cId:e,fileName:a?.originalname,fileSize:a?.size}),!a)throw new k("file is required",{field:"file"});const r=await _(t,e,a,o);n.status(200).json(r)})},{path:"/upload-files",method:"post",middleware:h.array("files"),handler:c(async(s,n)=>{const{userId:t,cId:e,filePaths:o,customTargetDir:a}=s.body||{},i=s.files||[],r=`computer:${t}:${e}`,l=Array.isArray(o)?o:typeof o=="string"?[o]:o;d(r,"INFO","Batch upload files request",{userId:t,cId:e,filesCount:i.length,filePathsCount:Array.isArray(l)?l.length:0});const u=[],g=[];try{for(const p of i){g.push(p.path);const I=await f.promises.readFile(p.path);u.push({buffer:I,originalname:p.originalname,mimetype:p.mimetype,size:p.size})}const m=await x(t,e,u,l,a);n.status(200).json(m)}finally{for(const m of g)if(f.existsSync(m))try{await f.promises.unlink(m)}catch(p){d(r,"WARN","Clean temporary file failed",{tempPath:m,error:p.message})}}})},{path:"/install-project",method:"post",handler:c(async(s,n)=>{const{userId:t,cId:e,programmingLanguage:o}=s.body||{},a=`computer:${t}:${e}`;d(a,"INFO","Install project request",{userId:t,cId:e,programmingLanguage:o});const i=await C(t,e,o);n.status(200).json({success:!0,...i})})},{path:"/init-project-template",method:"post",middleware:h.single("file"),handler:c(async(s,n)=>{const{userId:t,cId:e,enableGit:o}=s.body||{},a=s.file||null,i=`computer:${t}:${e}`;d(i,"INFO","Init project template request",{userId:t,cId:e,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size,enableGit:o});const r=await j(t,e,a,o);n.status(200).json({success:!0,...r})})},{path:"/download-all-files",method:"get",handler:c(async(s,n)=>{const{userId:t,cId:e,customTargetDir:o}=s.query||{},a=`computer:${t}:${e}`;d(a,"INFO","Download all files request",{userId:t,cId:e});const{archive:i,zipFileName:r}=await v(t,e,o);n.setHeader("Content-Type","application/zip");const l=encodeURIComponent(r);n.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),i.on("error",u=>{n.destroy(u)}),i.pipe(n),i.finalize()})},{path:"/execute-command",method:"post",handler:c(async(s,n)=>{const{userId:t,cId:e,command:o}=s.body||{},a=`computer:${t}:${e}`;d(a,"INFO","Execute command request",{userId:t,cId:e,command:o});const i=await A(t,e,o);n.status(200).json({success:!0,...i})})},{path:"/delete-workspace",method:"post",handler:c(async(s,n)=>{const{userId:t,cId:e}=s.body||{},o=`computer:${t}:${e}`;d(o,"INFO","Delete workspace request",{userId:t,cId:e});const a=await O(t,e);n.status(200).json({success:!0,...a})})},{path:"/get-logs",method:"get",handler:c(async(s,n)=>{const{userId:t,cId:e,tailLines:o}=s.query,a=o?parseInt(o,10):200,i=Number.isFinite(a)&&a>0?a:200,r=await H(t,e,i);n.status(200).json(r)})},{path:"/zip-workspace",method:"post",handler:c(async(s,n)=>{const{userId:t,cId:e,excludeDirs:o}=s.body||{},a=`computer:${t}:${e}`;d(a,"INFO","Zip workspace request",{userId:t,cId:e,hasExcludeDirs:!!o});const{archive:i,zipFileName:r}=await D(t,e,o||null);n.setHeader("Content-Type","application/zip");const l=encodeURIComponent(r);n.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),i.on("error",u=>{n.destroy(u)}),i.pipe(n),i.finalize()})},{path:"/build-agent-package",method:"post",handler:c(async(s,n)=>{const{userId:t,cId:e,agentId:o,version:a}=s.body||{},i=`computer:${t}:${e}`;d(i,"INFO","Build agent package request",{userId:t,cId:e,agentId:o,version:a});const r=await P(t,e,o,a);n.status(200).json({success:!0,...r})})},{path:"/cleanup-build-artifacts",method:"post",handler:c(async(s,n)=>{const{userId:t,cId:e}=s.body||{},o=`computer:${t}:${e}`;d(o,"INFO","Cleanup build artifacts request",{userId:t,cId:e});const a=await T(t,e);n.status(200).json({success:!0,...a})})}];M.forEach(s=>{if(s.middleware)y[s.method](s.path,s.middleware,s.handler);else if(s.customHandler){const n=[];s.handler&&n.push(s.handler),s.decodeMiddleware&&n.push(s.decodeMiddleware),n.push(L),n.push(s.customHandler),y[s.method](s.path,...n)}else y[s.method](s.path,s.handler)});export default y;
@@ -1,8 +1,8 @@
1
- import P from"path";import i from"fs";import dt from"crypto";import l from"isomorphic-git";import{createPatch as ut}from"diff";import B from"../appConfig/index.js";import{log as w}from"../utils/log/logUtils.js";import{ValidationError as v,BusinessError as G,SystemError as A,ResourceError as D}from"../utils/error/errorHandler.js";import{resolveProjectPath as ht}from"../utils/common/projectPathUtils.js";import{isGitRepo as gt,ensureGitRepo as T,ensureGitignore as M,addAll as U,stageFiles as L,getDefaultAuthor as mt}from"../utils/git/gitUtils.js";function k(n){const{workspaceType:t,projectId:a,isolationContext:e,userId:s,cId:r}=n||{};if(!t||!["pageApp","taskAgent"].includes(t))throw new v("workspaceType is required and must be pageApp or taskAgent",{field:"workspaceType"});if(t==="taskAgent"){if(!s||!r)throw new v("taskAgent mode requires userId and cId",{field:"userId/cId"});const c=P.join(B.COMPUTER_WORKSPACE_DIR,String(s),String(r));if(!i.existsSync(c))throw new D("Computer workspace does not exist",{userId:s,cId:r});return{targetPath:c,logId:`computer:${s}:${r}`}}if(!a)throw new v("pageApp mode requires projectId",{field:"projectId"});const o=ht(a,e||{});if(!i.existsSync(o))throw new D("Project does not exist",{projectId:a});return{targetPath:o,logId:a}}function q(n){for(let t=0;t<Math.min(n.length,8e3);t++)if(n[t]===0)return!0;return!1}function C(n){const t=Buffer.from(`blob ${n.length}\0`);return dt.createHash("sha1").update(Buffer.concat([t,n])).digest("hex")}function wt(n,t,a,e,s,r,o){const d=ut(n,e?t:"",s?a:"",e?`a/${n}`:"/dev/null",s?`b/${n}`:"/dev/null").split(`
2
- `).slice(4);d.length>0&&d[d.length-1]===""&&d.pop();const g=[];let u=0,h=0;for(const m of d){if(m.startsWith("@@")){const p=m.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(p){const S=p[1],F=p[2]!==void 0?parseInt(p[2],10):1,N=p[3],R=p[4]!==void 0?parseInt(p[4],10):1,$=F===1?S:`${S},${F}`,H=R===1?N:`${N},${R}`;g.push(`@@ -${$} +${H} @@`);continue}}m.startsWith("+")&&!m.startsWith("+++")?u++:m.startsWith("-")&&!m.startsWith("---")&&h++,g.push(m)}const f=e&&t!==""&&!t.endsWith(`
3
- `),b=s&&a!==""&&!a.endsWith(`
4
- `);if((f||b)&&g.length>0){let m=0;for(let R=0;R<g.length;R++)g[R].startsWith("@@")&&(m=R);let p=-1,S=-1,F=-1;for(let R=g.length-1;R>m;R--){const $=g[R];$.startsWith("-")&&!$.startsWith("---")&&p<0?p=R:$.startsWith("+")&&!$.startsWith("++")&&S<0?S=R:$.startsWith(" ")&&F<0&&(F=R)}const N=Math.max(p,S,F);if(N>=0){const R=g[N];if(R.startsWith(" "))(f||b)&&g.splice(N+1,0,"\");else if(R.startsWith("+")){let $=-1;for(let H=N-1;H>m;H--)if(g[H].startsWith("-")&&!g[H].startsWith("---")){$=H;break}$>=0&&f?(g.splice($+1,0,"\"),b&&g.splice(N+2,0,"\")):b&&g.splice(N+1,0,"\")}else R.startsWith("-")&&f&&g.splice(N+1,0,"\")}}const O=e&&r?C(r).substring(0,7):"0000000",x=s&&o?C(o).substring(0,7):"0000000",E=[];return E.push(`diff --git a/${n} b/${n}`),e?s?E.push(`index ${O}..${x} 100644`):(E.push("deleted file mode 100644"),E.push(`index ${O}..0000000`)):(E.push("new file mode 100644"),E.push(`index 0000000..${x}`)),E.push(`--- ${e?`a/${n}`:"/dev/null"}`),E.push(`+++ ${s?`b/${n}`:"/dev/null"}`),{diff:[...E,...g].join(`
1
+ import P from"path";import i from"fs";import dt from"crypto";import l from"isomorphic-git";import{createPatch as ut}from"diff";import C from"../appConfig/index.js";import{log as g}from"../utils/log/logUtils.js";import{ValidationError as v,BusinessError as H,SystemError as A,ResourceError as D}from"../utils/error/errorHandler.js";import{resolveProjectPath as ht}from"../utils/common/projectPathUtils.js";import{isGitRepo as mt,ensureGitRepo as N,ensureGitignore as _,addAll as gt,commitAllChanges as wt,stageFiles as L,getDefaultAuthor as yt,hasGitHead as W}from"../utils/git/gitUtils.js";function k(o){const{workspaceType:t,projectId:s,isolationContext:e,userId:r,cId:a}=o||{};if(!t||!["pageApp","taskAgent"].includes(t))throw new v("workspaceType is required and must be pageApp or taskAgent",{field:"workspaceType"});if(t==="taskAgent"){if(!r||!a)throw new v("taskAgent mode requires userId and cId",{field:"userId/cId"});const c=P.join(C.COMPUTER_WORKSPACE_DIR,String(r),String(a));if(!i.existsSync(c))throw new D("Computer workspace does not exist",{userId:r,cId:a});return{targetPath:c,logId:`computer:${r}:${a}`}}if(!s)throw new v("pageApp mode requires projectId",{field:"projectId"});const n=ht(s,e||{});if(!i.existsSync(n))throw new D("Project does not exist",{projectId:s});return{targetPath:n,logId:s}}function q(o){for(let t=0;t<Math.min(o.length,8e3);t++)if(o[t]===0)return!0;return!1}function M(o){const t=Buffer.from(`blob ${o.length}\0`);return dt.createHash("sha1").update(Buffer.concat([t,o])).digest("hex")}function pt(o,t,s,e,r,a,n){const u=ut(o,e?t:"",r?s:"",e?`a/${o}`:"/dev/null",r?`b/${o}`:"/dev/null").split(`
2
+ `).slice(4);u.length>0&&u[u.length-1]===""&&u.pop();const d=[];let h=0,m=0;for(const y of u){if(y.startsWith("@@")){const p=y.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(p){const S=p[1],F=p[2]!==void 0?parseInt(p[2],10):1,T=p[3],b=p[4]!==void 0?parseInt(p[4],10):1,$=F===1?S:`${S},${F}`,G=b===1?T:`${T},${b}`;d.push(`@@ -${$} +${G} @@`);continue}}y.startsWith("+")&&!y.startsWith("+++")?h++:y.startsWith("-")&&!y.startsWith("---")&&m++,d.push(y)}const f=e&&t!==""&&!t.endsWith(`
3
+ `),I=r&&s!==""&&!s.endsWith(`
4
+ `);if((f||I)&&d.length>0){let y=0;for(let b=0;b<d.length;b++)d[b].startsWith("@@")&&(y=b);let p=-1,S=-1,F=-1;for(let b=d.length-1;b>y;b--){const $=d[b];$.startsWith("-")&&!$.startsWith("---")&&p<0?p=b:$.startsWith("+")&&!$.startsWith("++")&&S<0?S=b:$.startsWith(" ")&&F<0&&(F=b)}const T=Math.max(p,S,F);if(T>=0){const b=d[T];if(b.startsWith(" "))(f||I)&&d.splice(T+1,0,"\");else if(b.startsWith("+")){let $=-1;for(let G=T-1;G>y;G--)if(d[G].startsWith("-")&&!d[G].startsWith("---")){$=G;break}$>=0&&f?(d.splice($+1,0,"\"),I&&d.splice(T+2,0,"\")):I&&d.splice(T+1,0,"\")}else b.startsWith("-")&&f&&d.splice(T+1,0,"\")}}const O=e&&a?M(a).substring(0,7):"0000000",x=r&&n?M(n).substring(0,7):"0000000",R=[];return R.push(`diff --git a/${o} b/${o}`),e?r?R.push(`index ${O}..${x} 100644`):(R.push("deleted file mode 100644"),R.push(`index ${O}..0000000`)):(R.push("new file mode 100644"),R.push(`index 0000000..${x}`)),R.push(`--- ${e?`a/${o}`:"/dev/null"}`),R.push(`+++ ${r?`b/${o}`:"/dev/null"}`),{diff:[...R,...d].join(`
5
5
  `)+`
6
- `,insertions:u,deletions:h}}async function W(n){return l.resolveRef({fs:i,dir:n,ref:"HEAD"})}async function _(n,t,a){try{const{blob:e}=await l.readBlob({fs:i,dir:n,oid:t,filepath:a}),s=Buffer.from(e);return{content:s.toString("utf8"),buf:s}}catch{return null}}async function z(n={}){const{targetPath:t,logId:a}=k(n);if(gt(t))return{success:!0,message:"Git repository already initialized",logId:a,alreadyExists:!0};try{return await l.init({fs:i,dir:t,defaultBranch:"main"}),M(t),await l.setConfig({fs:i,dir:t,path:"user.name",value:B.GIT_DEFAULT_AUTHOR_NAME}),await l.setConfig({fs:i,dir:t,path:"user.email",value:B.GIT_DEFAULT_AUTHOR_EMAIL}),w(a,"INFO","Git repository initialized",{logId:a,targetPath:t}),{success:!0,message:"Git repository initialized successfully",logId:a,alreadyExists:!1}}catch(e){throw w(a,"ERROR","Failed to initialize Git repository",{logId:a,error:e.message}),new A("Failed to initialize Git repository",{originalError:e.message})}}async function K(n={}){const{targetPath:t,logId:a}=k(n);await T(t);try{const e=await l.currentBranch({fs:i,dir:t,fullname:!1}),s=await l.statusMatrix({fs:i,dir:t}),r=[],o=[],c=[],y=[],d=[];for(const[g,u,h,f]of s)u!==f&&r.push(g),u===0&&f!==0&&c.push(g),(u===1&&f===0||h===0&&f!==0)&&y.push(g),f!==0&&h!==0&&h!==f&&o.push(g),u===0&&f===0&&h!==0&&d.push(g);return{success:!0,logId:a,current:e,staged:[...new Set(r)],modified:[...new Set(o)],created:[...new Set(c)],deleted:[...new Set(y)],untracked:[...new Set(d)],conflicted:[],ahead:0,behind:0,tracking:null}}catch(e){throw w(a,"ERROR","Failed to get Git status",{logId:a,error:e.message}),new A("Failed to get Git status",{originalError:e.message})}}async function V(n={}){const{message:t,files:a,authorName:e,authorEmail:s}=n;if(!t||typeof t!="string")throw new v("Commit message cannot be empty",{field:"message"});const{targetPath:r,logId:o}=k(n);await T(r);try{Array.isArray(a)&&a.length>0?await L(r,a):await U(r);const y=(await l.statusMatrix({fs:i,dir:r})).some(([,,,u])=>u!==1);if(!y)return{success:!0,message:"Nothing to commit",logId:o,nothingToCommit:!0};const d={name:e||B.GIT_DEFAULT_AUTHOR_NAME,email:s||B.GIT_DEFAULT_AUTHOR_EMAIL},g=await l.commit({fs:i,dir:r,message:t,author:d});return w(o,"INFO","Git commit successful",{logId:o,commitHash:g,message:t}),{success:!0,message:"Commit successful",logId:o,commit:g,summary:{changes:y?1:0}}}catch(c){throw w(o,"ERROR","Failed to commit",{logId:o,error:c.message}),new A("Failed to commit",{originalError:c.message})}}async function J(n={}){const{files:t}=n,{targetPath:a,logId:e}=k(n);await T(a);try{return Array.isArray(t)&&t.length>0?await L(a,t):await U(a),w(e,"INFO","Git add successful",{logId:e,filesCount:t?t.length:"all"}),{success:!0,message:"Files staged successfully",logId:e}}catch(s){throw w(e,"ERROR","Failed to add files",{logId:e,error:s.message}),new A("Failed to add files",{originalError:s.message})}}async function Q(n={}){const{files:t}=n,{targetPath:a,logId:e}=k(n);await T(a);try{if(Array.isArray(t)&&t.length>0){for(const o of t)await l.resetIndex({fs:i,dir:a,filepath:o});return w(e,"INFO","Git unstage specified files",{logId:e,files:t}),{success:!0,message:"Specified files unstaged successfully",logId:e,files:t}}const r=(await l.statusMatrix({fs:i,dir:a})).filter(([,,,o])=>o!==1).map(([o])=>o);for(const o of r)await l.resetIndex({fs:i,dir:a,filepath:o});return w(e,"INFO","Git unstage all files",{logId:e}),{success:!0,message:"All files unstaged successfully",logId:e,files:"all"}}catch(s){throw w(e,"ERROR","Failed to unstage",{logId:e,error:s.message}),new A("Failed to unstage files",{originalError:s.message})}}async function j(n,t){const a=new Set;for(const s of t){let r=P.dirname(s);for(;r&&r!==".";)a.add(r),r=P.dirname(r)}const e=[...a].sort((s,r)=>{const o=s.split(/[/\\]/).length;return r.split(/[/\\]/).length-o});for(const s of e){const r=P.join(n,s);try{(await i.promises.readdir(r)).length===0&&await i.promises.rmdir(r)}catch{}}}async function X(n={}){const{files:t}=n,{targetPath:a,logId:e}=k(n);await T(a);try{const s=await l.statusMatrix({fs:i,dir:a}),r=Array.isArray(t)&&t.length>0?new Set(t):null,o=[],c=[],y=[];for(const[u,h,f,b]of s)r&&!r.has(u)||(h!==0?(b!==1||f!==1)&&o.push(u):h===0&&b!==0?c.push(u):h===0&&b===0&&f!==0&&y.push(u));const d=await W(a);for(const u of o){const h=await _(a,d,u);if(!h)continue;const f=P.join(a,u);i.mkdirSync(P.dirname(f),{recursive:!0}),i.writeFileSync(f,h.buf),await l.add({fs:i,dir:a,filepath:u})}for(const u of c){try{await l.remove({fs:i,dir:a,filepath:u})}catch{}const h=P.join(a,u);i.existsSync(h)&&await i.promises.unlink(h)}c.length>0&&await j(a,c);for(const u of y){const h=P.join(a,u);i.existsSync(h)&&await i.promises.unlink(h)}y.length>0&&await j(a,y);const g=o.length+c.length+y.length;return w(e,"INFO","Git discard",{logId:e,trackedFiles:o.length,newFiles:c.length,untrackedFiles:y.length}),{success:!0,message:"Files discarded successfully",logId:e,discardedCount:g,trackedFiles:o,newFiles:c,untrackedFiles:y}}catch(s){throw w(e,"ERROR","Failed to discard",{logId:e,error:s.message}),new A("Failed to discard files",{originalError:s.message})}}async function Y(n={}){const{maxCount:t=50,branch:a,skip:e=0,filePath:s}=n,{targetPath:r,logId:o}=k(n);await T(r);try{const c=Math.min(Math.max(1,t),500),y=Math.max(0,e),d={fs:i,dir:r,depth:c+y};a&&(d.ref=a),s&&(d.filepath=s);const h=(await l.log(d)).slice(y,y+c).map(f=>({hash:f.oid,date:new Date(f.commit.author.timestamp*1e3).toISOString(),message:f.commit.message,author_name:f.commit.author.name,author_email:f.commit.author.email}));return{success:!0,logId:o,commits:h,total:h.length}}catch(c){throw w(o,"ERROR","Failed to get Git log",{logId:o,error:c.message}),new A("Failed to get Git log",{originalError:c.message})}}async function Z(n={}){const{source:t="worktree",from:a,to:e,paths:s}=n,{targetPath:r,logId:o}=k(n);await T(r);try{const c=Array.isArray(s)&&s.length>0?new Set(s):null;let y="";const d=[];let g=0,u=0;async function h(f,b,O){const x=!!b,E=!!O;if(x&&E&&b.content===O.content)return;let I=!1;if(x&&q(b.buf)&&(I=!0),E&&!I&&q(O.buf)&&(I=!0),I){const F=x?C(b.buf).substring(0,7):"0000000",N=E?C(O.buf).substring(0,7):"0000000",R=[`diff --git a/${f} b/${f}`];x?E?R.push(`index ${F}..${N} 100644`):(R.push("deleted file mode 100644"),R.push(`index ${F}..0000000`)):(R.push("new file mode 100644"),R.push(`index 0000000..${N}`)),R.push(`Binary files ${x?`a/${f}`:"/dev/null"} and ${E?`b/${f}`:"/dev/null"} differ`),y+=R.join(`
6
+ `,insertions:h,deletions:m}}async function j(o){return l.resolveRef({fs:i,dir:o,ref:"HEAD"})}async function B(o,t,s){try{const{blob:e}=await l.readBlob({fs:i,dir:o,oid:t,filepath:s}),r=Buffer.from(e);return{content:r.toString("utf8"),buf:r}}catch{return null}}async function z(o={}){const{targetPath:t,logId:s}=k(o);if(mt(t))return{success:!0,message:"Git repository already initialized",logId:s,alreadyExists:!0};try{return await l.init({fs:i,dir:t,defaultBranch:"main"}),_(t),await l.setConfig({fs:i,dir:t,path:"user.name",value:C.GIT_DEFAULT_AUTHOR_NAME}),await l.setConfig({fs:i,dir:t,path:"user.email",value:C.GIT_DEFAULT_AUTHOR_EMAIL}),g(s,"INFO","Git repository initialized",{logId:s,targetPath:t}),{success:!0,message:"Git repository initialized successfully",logId:s,alreadyExists:!1}}catch(e){throw g(s,"ERROR","Failed to initialize Git repository",{logId:s,error:e.message}),new A("Failed to initialize Git repository",{originalError:e.message})}}async function K(o={}){const{targetPath:t,logId:s}=k(o);await N(t);try{const e=await l.currentBranch({fs:i,dir:t,fullname:!1}),r=await l.statusMatrix({fs:i,dir:t}),a=[],n=[],c=[],w=[],u=[];for(const[d,h,m,f]of r)h!==f&&a.push(d),h===0&&f!==0&&c.push(d),(h===1&&f===0||m===0&&f!==0)&&w.push(d),f!==0&&m!==0&&m!==f&&n.push(d),h===0&&f===0&&m!==0&&u.push(d);return{success:!0,logId:s,current:e,staged:[...new Set(a)],modified:[...new Set(n)],created:[...new Set(c)],deleted:[...new Set(w)],untracked:[...new Set(u)],conflicted:[],ahead:0,behind:0,tracking:null}}catch(e){throw g(s,"ERROR","Failed to get Git status",{logId:s,error:e.message}),new A("Failed to get Git status",{originalError:e.message})}}async function V(o={}){const{message:t,files:s,authorName:e,authorEmail:r}=o;if(!t||typeof t!="string")throw new v("Commit message cannot be empty",{field:"message"});const{targetPath:a,logId:n}=k(o);await N(a);try{const c={name:e||C.GIT_DEFAULT_AUTHOR_NAME,email:r||C.GIT_DEFAULT_AUTHOR_EMAIL};if(Array.isArray(s)&&s.length>0){const u={};if(await L(a,s,{cache:u,force:!0}),!(await l.statusMatrix({fs:i,dir:a,cache:u,filepaths:s})).some(([,,,f])=>f!==1))return{success:!0,message:"Nothing to commit",logId:n,nothingToCommit:!0};const m=await l.commit({fs:i,dir:a,message:t,author:c,cache:u});return g(n,"INFO","Git commit successful",{logId:n,commitHash:m,message:t}),{success:!0,message:"Commit successful",logId:n,commit:m,summary:{changes:1}}}const w=await wt(a,{message:t,authorName:c.name,authorEmail:c.email,cache:{}});return w.nothingToCommit?{success:!0,message:"Nothing to commit",logId:n,nothingToCommit:!0}:(g(n,"INFO","Git commit successful",{logId:n,commitHash:w.commitHash,message:t,viaNative:w.viaNative===!0}),{success:!0,message:"Commit successful",logId:n,commit:w.commitHash,summary:{changes:1}})}catch(c){throw g(n,"ERROR","Failed to commit",{logId:n,error:c.message}),new A("Failed to commit",{originalError:c.message})}}async function J(o={}){const{files:t}=o,{targetPath:s,logId:e}=k(o);await N(s);try{const r={};return Array.isArray(t)&&t.length>0?await L(s,t,{cache:r,force:!0}):await gt(s,{cache:r}),g(e,"INFO","Git add successful",{logId:e,filesCount:t?t.length:"all"}),{success:!0,message:"Files staged successfully",logId:e}}catch(r){throw g(e,"ERROR","Failed to add files",{logId:e,error:r.message}),new A("Failed to add files",{originalError:r.message})}}async function Q(o={}){const{files:t}=o,{targetPath:s,logId:e}=k(o);await N(s);try{if(Array.isArray(t)&&t.length>0){for(const n of t)await l.resetIndex({fs:i,dir:s,filepath:n});return g(e,"INFO","Git unstage specified files",{logId:e,files:t}),{success:!0,message:"Specified files unstaged successfully",logId:e,files:t}}const a=(await l.statusMatrix({fs:i,dir:s})).filter(([,,,n])=>n!==1).map(([n])=>n);for(const n of a)await l.resetIndex({fs:i,dir:s,filepath:n});return g(e,"INFO","Git unstage all files",{logId:e}),{success:!0,message:"All files unstaged successfully",logId:e,files:"all"}}catch(r){throw g(e,"ERROR","Failed to unstage",{logId:e,error:r.message}),new A("Failed to unstage files",{originalError:r.message})}}async function U(o,t){const s=new Set;for(const r of t){let a=P.dirname(r);for(;a&&a!==".";)s.add(a),a=P.dirname(a)}const e=[...s].sort((r,a)=>{const n=r.split(/[/\\]/).length;return a.split(/[/\\]/).length-n});for(const r of e){const a=P.join(o,r);try{(await i.promises.readdir(a)).length===0&&await i.promises.rmdir(a)}catch{}}}async function X(o={}){const{files:t}=o,{targetPath:s,logId:e}=k(o);await N(s);try{const r=await l.statusMatrix({fs:i,dir:s}),a=Array.isArray(t)&&t.length>0?new Set(t):null,n=[],c=[],w=[];for(const[d,h,m,f]of r)a&&!a.has(d)||(h!==0?(f!==1||m!==1)&&n.push(d):h===0&&f!==0?c.push(d):h===0&&f===0&&m!==0&&w.push(d));if(n.length>0){const d=await j(s);for(const h of n){const m=await B(s,d,h);if(!m)continue;const f=P.join(s,h);i.mkdirSync(P.dirname(f),{recursive:!0}),i.writeFileSync(f,m.buf),await l.add({fs:i,dir:s,filepath:h})}}for(const d of c){try{await l.remove({fs:i,dir:s,filepath:d})}catch{}const h=P.join(s,d);i.existsSync(h)&&await i.promises.unlink(h)}c.length>0&&await U(s,c);for(const d of w){const h=P.join(s,d);i.existsSync(h)&&await i.promises.unlink(h)}w.length>0&&await U(s,w);const u=n.length+c.length+w.length;return g(e,"INFO","Git discard",{logId:e,trackedFiles:n.length,newFiles:c.length,untrackedFiles:w.length}),{success:!0,message:"Files discarded successfully",logId:e,discardedCount:u,trackedFiles:n,newFiles:c,untrackedFiles:w}}catch(r){throw g(e,"ERROR","Failed to discard",{logId:e,error:r.message}),new A("Failed to discard files",{originalError:r.message})}}async function Y(o={}){const{maxCount:t=50,branch:s,skip:e=0,filePath:r}=o,{targetPath:a,logId:n}=k(o);await N(a);try{const c=Math.min(Math.max(1,t),500),w=Math.max(0,e),u={fs:i,dir:a,depth:c+w};s&&(u.ref=s),r&&(u.filepath=r);const m=(await l.log(u)).slice(w,w+c).map(f=>({hash:f.oid,date:new Date(f.commit.author.timestamp*1e3).toISOString(),message:f.commit.message,author_name:f.commit.author.name,author_email:f.commit.author.email}));return{success:!0,logId:n,commits:m,total:m.length}}catch(c){if(c?.code==="NotFoundError"||/NotFoundError|Could not find|unable to resolve/i.test(String(c?.message||"")))return{success:!0,logId:n,commits:[],total:0};throw g(n,"ERROR","Failed to get Git log",{logId:n,error:c.message}),new A("Failed to get Git log",{originalError:c.message})}}async function Z(o={}){const{source:t="worktree",from:s,to:e,paths:r}=o,{targetPath:a,logId:n}=k(o);await N(a);try{const c=Array.isArray(r)&&r.length>0?new Set(r):null;let w="";const u=[];let d=0,h=0;async function m(f,I,O){const x=!!I,R=!!O;if(x&&R&&I.content===O.content)return;let E=!1;if(x&&q(I.buf)&&(E=!0),R&&!E&&q(O.buf)&&(E=!0),E){const F=x?M(I.buf).substring(0,7):"0000000",T=R?M(O.buf).substring(0,7):"0000000",b=[`diff --git a/${f} b/${f}`];x?R?b.push(`index ${F}..${T} 100644`):(b.push("deleted file mode 100644"),b.push(`index ${F}..0000000`)):(b.push("new file mode 100644"),b.push(`index 0000000..${T}`)),b.push(`Binary files ${x?`a/${f}`:"/dev/null"} and ${R?`b/${f}`:"/dev/null"} differ`),w+=b.join(`
7
7
  `)+`
8
- `,d.push({file:f,changes:0,insertions:0,deletions:0,binary:!0});return}const{diff:m,insertions:p,deletions:S}=wt(f,x?b.content:"",E?O.content:"",x,E,x?b.buf:null,E?O.buf:null);y+=m,d.push({file:f,changes:p+S,insertions:p,deletions:S,binary:!1}),g+=p,u+=S}if(t==="commit"){let f,b;if(a&&e)f=a,b=e;else if(a){const I=await l.readCommit({fs:i,dir:r,oid:a});I.commit.parent&&I.commit.parent.length>0?(f=I.commit.parent[0],b=a):(f=null,b=a)}else throw new v("source=commit requires at least 'from'",{field:"from"});const O=f?new Set(await l.listFiles({fs:i,dir:r,ref:f})):new Set,x=new Set(await l.listFiles({fs:i,dir:r,ref:b})),E=new Set([...O,...x]);for(const I of E){if(c&&!c.has(I))continue;const m=O.has(I)?await _(r,f,I):null,p=x.has(I)?await _(r,b,I):null;await h(I,m,p)}}else{const f=await W(r),b=await l.statusMatrix({fs:i,dir:r});for(const[O,x,E,I]of b){if(c&&!c.has(O))continue;if(t==="staged"){if(I===1||x===0&&I===0)continue}else if(x===0&&I===0||x===1&&E===1&&I===1)continue;const m=x!==0?await _(r,f,O):null;let p=null;if(E!==0){const S=P.join(r,O);if(i.existsSync(S))try{const F=i.readFileSync(S);p={content:F.toString("utf8"),buf:F}}catch{}}await h(O,m,p)}}return{success:!0,logId:o,source:t,diff:y,summary:{files:d,insertions:g,deletions:u}}}catch(c){throw c instanceof v?c:(w(o,"ERROR","Failed to get Git diff",{logId:o,error:c.message}),new A("Failed to get Git diff",{originalError:c.message}))}}async function tt(n={}){const{ref:t="HEAD",filePath:a}=n;if(!a)throw new v("filePath is required",{field:"filePath"});const{targetPath:e,logId:s}=k(n);await T(e);try{let r;if(t==="worktree"||t==="staged"||t===""){const o=P.join(e,a);r=i.existsSync(o)?i.readFileSync(o,"utf8"):""}else try{const o=await l.resolveRef({fs:i,dir:e,ref:t}),{blob:c}=await l.readBlob({fs:i,dir:e,oid:o,filepath:a});r=Buffer.from(c).toString("utf8")}catch{r=""}return{success:!0,logId:s,filePath:a,ref:t,content:r}}catch(r){throw r instanceof D?r:(w(s,"ERROR","Failed to get file content",{logId:s,ref:t,filePath:a,error:r.message}),new A("Failed to get file content",{originalError:r.message}))}}async function et(n={}){const{target:t,mode:a="mixed"}=n;if(!t)throw new v("Reset target cannot be empty",{field:"target"});if(!["soft","mixed","hard"].includes(a))throw new v("Mode must be soft, mixed or hard",{field:"mode"});const{targetPath:e,logId:s}=k(n);await T(e);try{const r=await l.log({fs:i,dir:e,depth:1}),o=r.length>0?r[0].oid:null,c=await l.currentBranch({fs:i,dir:e,fullname:!1});if(!c)throw new G("Cannot reset: detached HEAD");const y=a==="hard"?new Set(await l.listFiles({fs:i,dir:e,ref:"HEAD"})):null;if(await l.writeRef({fs:i,dir:e,ref:`refs/heads/${c}`,value:t,force:!0}),a==="mixed"||a==="hard"){const d=await l.listFiles({fs:i,dir:e,ref:t}),g=new Set(d);for(const h of d)await l.resetIndex({fs:i,dir:e,filepath:h,ref:t});const u=await l.statusMatrix({fs:i,dir:e});for(const[h,,,f]of u)if(!g.has(h)&&f!==0)try{await l.remove({fs:i,dir:e,filepath:h})}catch{}}if(a==="hard"){const d=await l.listFiles({fs:i,dir:e,ref:t}),g=new Set(d);for(const u of d){const h=await _(e,t,u);if(!h)continue;const f=P.join(e,u);i.mkdirSync(P.dirname(f),{recursive:!0}),i.writeFileSync(f,h.buf)}if(y){for(const u of y)if(!g.has(u)){const h=P.join(e,u);i.existsSync(h)&&i.unlinkSync(h)}}M(e),await l.add({fs:i,dir:e,filepath:".gitignore"})}return w(s,"INFO","Git reset successful",{logId:s,target:t,mode:a,previousHead:o}),{success:!0,message:`Reset (${a}) to ${t} successful`,logId:s,target:t,mode:a,previousHead:o}}catch(r){throw r instanceof G?r:(w(s,"ERROR","Failed to reset",{logId:s,target:t,mode:a,error:r.message}),new A("Failed to reset",{originalError:r.message}))}}async function at(n={}){const{target:t,message:a,authorName:e,authorEmail:s}=n;if(!t)throw new v("Revert target cannot be empty",{field:"target"});const{targetPath:r,logId:o}=k(n);await T(r);try{let c;try{c=(await l.readCommit({fs:i,dir:r,oid:t})).oid}catch{throw new v("Revert target commit does not exist",{field:"target",target:t})}const y=await l.statusMatrix({fs:i,dir:r});if(y.some(([m,p,S,F])=>p===0&&F===0?!1:S!==1||F!==1)){const m=y.filter(([,F])=>F!==0),p=m.filter(([,,F])=>F!==1).map(([F])=>F),S=m.filter(([,,,F])=>F!==1).map(([F])=>F);throw new G("Working directory is not clean, please commit or stash your changes before reverting",{staged:S,modified:p})}const g=new Set(await l.listFiles({fs:i,dir:r,ref:c})),u=await W(r),h=new Set(await l.listFiles({fs:i,dir:r,ref:u})),f=[];for(const m of g){const p=await _(r,c,m);if(!p)continue;const S=P.join(r,m);i.mkdirSync(P.dirname(S),{recursive:!0}),i.writeFileSync(S,p.buf),await l.add({fs:i,dir:r,filepath:m})}for(const m of h)if(!g.has(m)){f.push(m);try{await l.remove({fs:i,dir:r,filepath:m})}catch{}const p=P.join(r,m);i.existsSync(p)&&await i.promises.unlink(p)}if(f.length>0&&await j(r,f),M(r),await l.add({fs:i,dir:r,filepath:".gitignore"}),!(await l.statusMatrix({fs:i,dir:r})).some(([,,,m])=>m!==1))return w(o,"INFO","Nothing to revert, current HEAD already matches target",{logId:o,target:c}),{success:!0,message:"Nothing to revert, already at target state",logId:o,nothingToCommit:!0,target:c};const x={name:e||B.GIT_DEFAULT_AUTHOR_NAME,email:s||B.GIT_DEFAULT_AUTHOR_EMAIL},E=a||`Revert to ${c.substring(0,7)}`,I=await l.commit({fs:i,dir:r,message:E,author:x});return w(o,"INFO","Git revert successful",{logId:o,target:c,commitHash:I,previousHead:u,removedFilesCount:f.length}),{success:!0,message:"Revert successful",logId:o,commit:I,target:c,previousHead:u}}catch(c){throw c instanceof v||c instanceof G?c:(w(o,"ERROR","Failed to revert",{logId:o,target:t,error:c.message}),new A("Failed to revert",{originalError:c.message}))}}async function rt(n={}){const{target:t}=n;if(!t)throw new v("Checkout target cannot be empty",{field:"target"});const{targetPath:a,logId:e}=k(n);await T(a);try{const s=await l.listFiles({fs:i,dir:a,ref:t});for(const r of s){const o=await _(a,t,r);if(!o)continue;const c=P.join(a,r);i.mkdirSync(P.dirname(c),{recursive:!0}),i.writeFileSync(c,o.buf),await l.add({fs:i,dir:a,filepath:r})}return M(a),await l.add({fs:i,dir:a,filepath:".gitignore"}),w(e,"INFO","Git checkout files successful",{logId:e,target:t}),{success:!0,message:`Checkout files from ${t} successful`,logId:e,target:t}}catch(s){throw w(e,"ERROR","Failed to checkout files",{logId:e,target:t,error:s.message}),new A("Failed to checkout files",{originalError:s.message})}}async function st(n={}){const{targetPath:t,logId:a}=k(n);await T(t);try{const e=await l.listTags({fs:i,dir:t});return{success:!0,logId:a,tags:e,latest:e.length>0?e[e.length-1]:null}}catch(e){throw w(a,"ERROR","Failed to list tags",{logId:a,error:e.message}),new A("Failed to list tags",{originalError:e.message})}}async function it(n={}){const{tagName:t,message:a}=n;if(!t)throw new v("Tag name cannot be empty",{field:"tagName"});const{targetPath:e,logId:s}=k(n);await T(e);try{return a?await l.annotatedTag({fs:i,dir:e,ref:t,message:a,tagger:mt()}):await l.tag({fs:i,dir:e,ref:t}),w(s,"INFO","Git tag created",{logId:s,tagName:t,annotated:!!a}),{success:!0,message:"Tag created successfully",logId:s,tagName:t}}catch(r){throw w(s,"ERROR","Failed to create tag",{logId:s,tagName:t,error:r.message}),new A("Failed to create tag",{originalError:r.message})}}async function nt(n={}){const{tagName:t}=n;if(!t)throw new v("Tag name cannot be empty",{field:"tagName"});const{targetPath:a,logId:e}=k(n);await T(a);try{return await l.deleteRef({fs:i,dir:a,ref:`refs/tags/${t}`}),w(e,"INFO","Git tag deleted",{logId:e,tagName:t}),{success:!0,message:"Tag deleted successfully",logId:e,tagName:t}}catch(s){throw w(e,"ERROR","Failed to delete tag",{logId:e,tagName:t,error:s.message}),new A("Failed to delete tag",{originalError:s.message})}}async function ot(n={}){const{targetPath:t,logId:a}=k(n);await T(t);try{const e=await l.listBranches({fs:i,dir:t}),s=await l.currentBranch({fs:i,dir:t,fullname:!1}),r={};for(const o of e)r[o]={name:o,current:o===s};return{success:!0,logId:a,branches:r,current:s}}catch(e){throw w(a,"ERROR","Failed to list branches",{logId:a,error:e.message}),new A("Failed to list branches",{originalError:e.message})}}async function ct(n={}){const{branchName:t,startPoint:a}=n;if(!t)throw new v("Branch name cannot be empty",{field:"branchName"});const{targetPath:e,logId:s}=k(n);await T(e);try{const r=a||"HEAD";return await l.branch({fs:i,dir:e,ref:t,object:r,checkout:!0}),w(s,"INFO","Git branch created",{logId:s,branchName:t,startPoint:a}),{success:!0,message:"Branch created and switched to",logId:s,branchName:t}}catch(r){throw w(s,"ERROR","Failed to create branch",{logId:s,branchName:t,error:r.message}),new A("Failed to create branch",{originalError:r.message})}}async function lt(n={}){const{branchName:t}=n;if(!t)throw new v("Branch name cannot be empty",{field:"branchName"});const{targetPath:a,logId:e}=k(n);await T(a);try{const s=await l.statusMatrix({fs:i,dir:a});if(s.some(([o,c,y,d])=>c===0&&d===0?!1:y!==1||d!==1)){const o=s.filter(([,d])=>d!==0),c=o.filter(([,,d])=>d!==1).map(([d])=>d),y=o.filter(([,,,d])=>d!==1).map(([d])=>d);throw new G("Working directory is not clean, please commit or stash your changes before switching branches",{staged:y,modified:c})}return await l.checkout({fs:i,dir:a,ref:t}),w(e,"INFO","Git branch switched",{logId:e,branchName:t}),{success:!0,message:"Branch switched successfully",logId:e,branchName:t}}catch(s){throw s instanceof G?s:(w(e,"ERROR","Failed to switch branch",{logId:e,branchName:t,error:s.message}),new A("Failed to switch branch",{originalError:s.message}))}}async function ft(n={}){const{branchName:t,force:a=!1}=n;if(!t)throw new v("Branch name cannot be empty",{field:"branchName"});const{targetPath:e,logId:s}=k(n);await T(e);try{if(await l.currentBranch({fs:i,dir:e,fullname:!1})===t)throw new G("Cannot delete the current branch, please switch to another branch first");return await l.deleteBranch({fs:i,dir:e,ref:t,force:a}),w(s,"INFO","Git branch deleted",{logId:s,branchName:t,force:a}),{success:!0,message:"Branch deleted successfully",logId:s,branchName:t}}catch(r){throw r instanceof G?r:(w(s,"ERROR","Failed to delete branch",{logId:s,branchName:t,error:r.message}),new A("Failed to delete branch",{originalError:r.message}))}}export{z as init,K as status,V as commit,J as add,Q as unstage,X as discard,Y as logHistory,Z as diff,tt as fileContent,et as reset,at as revert,rt as checkout,st as listTags,it as createTag,nt as deleteTag,ot as listBranches,ct as createBranch,lt as switchBranch,ft as deleteBranch};export default{init:z,status:K,commit:V,add:J,unstage:Q,discard:X,logHistory:Y,diff:Z,fileContent:tt,reset:et,revert:at,checkout:rt,listTags:st,createTag:it,deleteTag:nt,listBranches:ot,createBranch:ct,switchBranch:lt,deleteBranch:ft};
8
+ `,u.push({file:f,changes:0,insertions:0,deletions:0,binary:!0});return}const{diff:y,insertions:p,deletions:S}=pt(f,x?I.content:"",R?O.content:"",x,R,x?I.buf:null,R?O.buf:null);w+=y,u.push({file:f,changes:p+S,insertions:p,deletions:S,binary:!1}),d+=p,h+=S}if(t==="commit"){let f,I;if(s&&e)f=s,I=e;else if(s){const E=await l.readCommit({fs:i,dir:a,oid:s});E.commit.parent&&E.commit.parent.length>0?(f=E.commit.parent[0],I=s):(f=null,I=s)}else throw new v("source=commit requires at least 'from'",{field:"from"});const O=f?new Set(await l.listFiles({fs:i,dir:a,ref:f})):new Set,x=new Set(await l.listFiles({fs:i,dir:a,ref:I})),R=new Set([...O,...x]);for(const E of R){if(c&&!c.has(E))continue;const y=O.has(E)?await B(a,f,E):null,p=x.has(E)?await B(a,I,E):null;await m(E,y,p)}}else{if(!await W(a))return{success:!0,logId:n,source:t,diff:"",summary:{files:[],insertions:0,deletions:0}};const f=await j(a),I=await l.statusMatrix({fs:i,dir:a});for(const[O,x,R,E]of I){if(c&&!c.has(O))continue;if(t==="staged"){if(E===1||x===0&&E===0)continue}else if(x===0&&E===0||x===1&&R===1&&E===1)continue;const y=x!==0?await B(a,f,O):null;let p=null;if(R!==0){const S=P.join(a,O);if(i.existsSync(S))try{const F=i.readFileSync(S);p={content:F.toString("utf8"),buf:F}}catch{}}await m(O,y,p)}}return{success:!0,logId:n,source:t,diff:w,summary:{files:u,insertions:d,deletions:h}}}catch(c){throw c instanceof v?c:(g(n,"ERROR","Failed to get Git diff",{logId:n,error:c.message}),new A("Failed to get Git diff",{originalError:c.message}))}}async function tt(o={}){const{ref:t="HEAD",filePath:s}=o;if(!s)throw new v("filePath is required",{field:"filePath"});const{targetPath:e,logId:r}=k(o);await N(e);try{let a;if(t==="worktree"||t==="staged"||t===""){const n=P.join(e,s);a=i.existsSync(n)?i.readFileSync(n,"utf8"):""}else try{const n=await l.resolveRef({fs:i,dir:e,ref:t}),{blob:c}=await l.readBlob({fs:i,dir:e,oid:n,filepath:s});a=Buffer.from(c).toString("utf8")}catch{a=""}return{success:!0,logId:r,filePath:s,ref:t,content:a}}catch(a){throw a instanceof D?a:(g(r,"ERROR","Failed to get file content",{logId:r,ref:t,filePath:s,error:a.message}),new A("Failed to get file content",{originalError:a.message}))}}async function et(o={}){const{target:t,mode:s="mixed"}=o;if(!t)throw new v("Reset target cannot be empty",{field:"target"});if(!["soft","mixed","hard"].includes(s))throw new v("Mode must be soft, mixed or hard",{field:"mode"});const{targetPath:e,logId:r}=k(o);await N(e);try{if(!await W(e))throw new H("Cannot reset: repository has no commits yet");const a=await l.log({fs:i,dir:e,depth:1}),n=a.length>0?a[0].oid:null,c=await l.currentBranch({fs:i,dir:e,fullname:!1});if(!c)throw new H("Cannot reset: detached HEAD");const w=s==="hard"?new Set(await l.listFiles({fs:i,dir:e,ref:"HEAD"})):null;if(await l.writeRef({fs:i,dir:e,ref:`refs/heads/${c}`,value:t,force:!0}),s==="mixed"||s==="hard"){const u=await l.listFiles({fs:i,dir:e,ref:t}),d=new Set(u);for(const m of u)await l.resetIndex({fs:i,dir:e,filepath:m,ref:t});const h=await l.statusMatrix({fs:i,dir:e});for(const[m,,,f]of h)if(!d.has(m)&&f!==0)try{await l.remove({fs:i,dir:e,filepath:m})}catch{}}if(s==="hard"){const u=await l.listFiles({fs:i,dir:e,ref:t}),d=new Set(u);for(const h of u){const m=await B(e,t,h);if(!m)continue;const f=P.join(e,h);i.mkdirSync(P.dirname(f),{recursive:!0}),i.writeFileSync(f,m.buf)}if(w){for(const h of w)if(!d.has(h)){const m=P.join(e,h);i.existsSync(m)&&i.unlinkSync(m)}}_(e),await l.add({fs:i,dir:e,filepath:".gitignore"})}return g(r,"INFO","Git reset successful",{logId:r,target:t,mode:s,previousHead:n}),{success:!0,message:`Reset (${s}) to ${t} successful`,logId:r,target:t,mode:s,previousHead:n}}catch(a){throw a instanceof H?a:(g(r,"ERROR","Failed to reset",{logId:r,target:t,mode:s,error:a.message}),new A("Failed to reset",{originalError:a.message}))}}async function st(o={}){const{target:t,message:s,authorName:e,authorEmail:r}=o;if(!t)throw new v("Revert target cannot be empty",{field:"target"});const{targetPath:a,logId:n}=k(o);await N(a);try{if(!await W(a))throw new H("Cannot revert: repository has no commits yet");let c;try{c=(await l.readCommit({fs:i,dir:a,oid:t})).oid}catch{throw new v("Revert target commit does not exist",{field:"target",target:t})}const w=await l.statusMatrix({fs:i,dir:a});if(w.some(([y,p,S,F])=>p===0&&F===0?!1:S!==1||F!==1)){const y=w.filter(([,F])=>F!==0),p=y.filter(([,,F])=>F!==1).map(([F])=>F),S=y.filter(([,,,F])=>F!==1).map(([F])=>F);throw new H("Working directory is not clean, please commit or stash your changes before reverting",{staged:S,modified:p})}const d=new Set(await l.listFiles({fs:i,dir:a,ref:c})),h=await j(a),m=new Set(await l.listFiles({fs:i,dir:a,ref:h})),f=[];for(const y of d){const p=await B(a,c,y);if(!p)continue;const S=P.join(a,y);i.mkdirSync(P.dirname(S),{recursive:!0}),i.writeFileSync(S,p.buf),await l.add({fs:i,dir:a,filepath:y})}for(const y of m)if(!d.has(y)){f.push(y);try{await l.remove({fs:i,dir:a,filepath:y})}catch{}const p=P.join(a,y);i.existsSync(p)&&await i.promises.unlink(p)}if(f.length>0&&await U(a,f),_(a),await l.add({fs:i,dir:a,filepath:".gitignore"}),!(await l.statusMatrix({fs:i,dir:a})).some(([,,,y])=>y!==1))return g(n,"INFO","Nothing to revert, current HEAD already matches target",{logId:n,target:c}),{success:!0,message:"Nothing to revert, already at target state",logId:n,nothingToCommit:!0,target:c};const x={name:e||C.GIT_DEFAULT_AUTHOR_NAME,email:r||C.GIT_DEFAULT_AUTHOR_EMAIL},R=s||`Revert to ${c.substring(0,7)}`,E=await l.commit({fs:i,dir:a,message:R,author:x});return g(n,"INFO","Git revert successful",{logId:n,target:c,commitHash:E,previousHead:h,removedFilesCount:f.length}),{success:!0,message:"Revert successful",logId:n,commit:E,target:c,previousHead:h}}catch(c){throw c instanceof v||c instanceof H?c:(g(n,"ERROR","Failed to revert",{logId:n,target:t,error:c.message}),new A("Failed to revert",{originalError:c.message}))}}async function at(o={}){const{target:t}=o;if(!t)throw new v("Checkout target cannot be empty",{field:"target"});const{targetPath:s,logId:e}=k(o);await N(s);try{const r=await l.listFiles({fs:i,dir:s,ref:t});for(const a of r){const n=await B(s,t,a);if(!n)continue;const c=P.join(s,a);i.mkdirSync(P.dirname(c),{recursive:!0}),i.writeFileSync(c,n.buf),await l.add({fs:i,dir:s,filepath:a})}return _(s),await l.add({fs:i,dir:s,filepath:".gitignore"}),g(e,"INFO","Git checkout files successful",{logId:e,target:t}),{success:!0,message:`Checkout files from ${t} successful`,logId:e,target:t}}catch(r){throw g(e,"ERROR","Failed to checkout files",{logId:e,target:t,error:r.message}),new A("Failed to checkout files",{originalError:r.message})}}async function rt(o={}){const{targetPath:t,logId:s}=k(o);await N(t);try{const e=await l.listTags({fs:i,dir:t});return{success:!0,logId:s,tags:e,latest:e.length>0?e[e.length-1]:null}}catch(e){throw g(s,"ERROR","Failed to list tags",{logId:s,error:e.message}),new A("Failed to list tags",{originalError:e.message})}}async function it(o={}){const{tagName:t,message:s}=o;if(!t)throw new v("Tag name cannot be empty",{field:"tagName"});const{targetPath:e,logId:r}=k(o);await N(e);try{return s?await l.annotatedTag({fs:i,dir:e,ref:t,message:s,tagger:yt()}):await l.tag({fs:i,dir:e,ref:t}),g(r,"INFO","Git tag created",{logId:r,tagName:t,annotated:!!s}),{success:!0,message:"Tag created successfully",logId:r,tagName:t}}catch(a){throw g(r,"ERROR","Failed to create tag",{logId:r,tagName:t,error:a.message}),new A("Failed to create tag",{originalError:a.message})}}async function nt(o={}){const{tagName:t}=o;if(!t)throw new v("Tag name cannot be empty",{field:"tagName"});const{targetPath:s,logId:e}=k(o);await N(s);try{return await l.deleteRef({fs:i,dir:s,ref:`refs/tags/${t}`}),g(e,"INFO","Git tag deleted",{logId:e,tagName:t}),{success:!0,message:"Tag deleted successfully",logId:e,tagName:t}}catch(r){throw g(e,"ERROR","Failed to delete tag",{logId:e,tagName:t,error:r.message}),new A("Failed to delete tag",{originalError:r.message})}}async function ot(o={}){const{targetPath:t,logId:s}=k(o);await N(t);try{const e=await l.listBranches({fs:i,dir:t}),r=await l.currentBranch({fs:i,dir:t,fullname:!1}),a={};for(const n of e)a[n]={name:n,current:n===r};return{success:!0,logId:s,branches:a,current:r}}catch(e){throw g(s,"ERROR","Failed to list branches",{logId:s,error:e.message}),new A("Failed to list branches",{originalError:e.message})}}async function ct(o={}){const{branchName:t,startPoint:s}=o;if(!t)throw new v("Branch name cannot be empty",{field:"branchName"});const{targetPath:e,logId:r}=k(o);await N(e);try{const a=s||"HEAD";return await l.branch({fs:i,dir:e,ref:t,object:a,checkout:!0}),g(r,"INFO","Git branch created",{logId:r,branchName:t,startPoint:s}),{success:!0,message:"Branch created and switched to",logId:r,branchName:t}}catch(a){throw g(r,"ERROR","Failed to create branch",{logId:r,branchName:t,error:a.message}),new A("Failed to create branch",{originalError:a.message})}}async function lt(o={}){const{branchName:t}=o;if(!t)throw new v("Branch name cannot be empty",{field:"branchName"});const{targetPath:s,logId:e}=k(o);await N(s);try{const r=await l.statusMatrix({fs:i,dir:s});if(r.some(([n,c,w,u])=>c===0&&u===0?!1:w!==1||u!==1)){const n=r.filter(([,u])=>u!==0),c=n.filter(([,,u])=>u!==1).map(([u])=>u),w=n.filter(([,,,u])=>u!==1).map(([u])=>u);throw new H("Working directory is not clean, please commit or stash your changes before switching branches",{staged:w,modified:c})}return await l.checkout({fs:i,dir:s,ref:t}),g(e,"INFO","Git branch switched",{logId:e,branchName:t}),{success:!0,message:"Branch switched successfully",logId:e,branchName:t}}catch(r){throw r instanceof H?r:(g(e,"ERROR","Failed to switch branch",{logId:e,branchName:t,error:r.message}),new A("Failed to switch branch",{originalError:r.message}))}}async function ft(o={}){const{branchName:t,force:s=!1}=o;if(!t)throw new v("Branch name cannot be empty",{field:"branchName"});const{targetPath:e,logId:r}=k(o);await N(e);try{if(await l.currentBranch({fs:i,dir:e,fullname:!1})===t)throw new H("Cannot delete the current branch, please switch to another branch first");return await l.deleteBranch({fs:i,dir:e,ref:t,force:s}),g(r,"INFO","Git branch deleted",{logId:r,branchName:t,force:s}),{success:!0,message:"Branch deleted successfully",logId:r,branchName:t}}catch(a){throw a instanceof H?a:(g(r,"ERROR","Failed to delete branch",{logId:r,branchName:t,error:a.message}),new A("Failed to delete branch",{originalError:a.message}))}}export{z as init,K as status,V as commit,J as add,Q as unstage,X as discard,Y as logHistory,Z as diff,tt as fileContent,et as reset,st as revert,at as checkout,rt as listTags,it as createTag,nt as deleteTag,ot as listBranches,ct as createBranch,lt as switchBranch,ft as deleteBranch};export default{init:z,status:K,commit:V,add:J,unstage:Q,discard:X,logHistory:Y,diff:Z,fileContent:tt,reset:et,revert:st,checkout:at,listTags:rt,createTag:it,deleteTag:nt,listBranches:ot,createBranch:ct,switchBranch:lt,deleteBranch:ft};
@@ -1,2 +1,2 @@
1
- import i from"fs";import p from"path";import _ from"archiver";import P from"../../appConfig/index.js";import{log as n}from"../log/logUtils.js";import{ValidationError as y,SystemError as N,FileError as j}from"../error/errorHandler.js";import{extractZip as M}from"../common/zipUtils.js";import{moveDirectory as L,movePath as x}from"../common/fileSystemUtils.js";const b=new Set([".git",".agents",".claude",".codex",".opencode",".tmp",".logs"]),U=100*1024*1024,v=P.DOWNLOAD_MAX_FILE_SIZE_BYTES||U;async function C(o,d,r,f,l){const t=[],g=await i.promises.readdir(o,{withFileTypes:!0});g.sort((c,s)=>c.isDirectory()&&!s.isDirectory()?-1:!c.isDirectory()&&s.isDirectory()?1:c.name.toLowerCase().localeCompare(s.name.toLowerCase()));for(const c of g){const s=p.join(o,c.name);if(!(c.name.startsWith(".")&&c.name!==".gitignore"||(P.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(c.name))&&!(c.isDirectory()&&P.TRAVERSE_EXCLUDE_DIRS.includes(c.name)))if(c.isDirectory()){const e=await C(s,d,r,f,l);if(e.length===0){const w=d||o,u=p.relative(w,s).replace(/\\/g,"/");t.push({name:u,isDir:!0})}else t.push(...e)}else try{const e=d||o,w=p.relative(e,s).replace(/\\/g,"/"),u=c.isSymbolicLink();let m=null;if(f){const E=w.split("/").map(R=>encodeURIComponent(R)).join("/");m=`${f}/${E}`,l&&(m+=`?customTargetDir=${encodeURIComponent(l)}`)}const a={name:w,isDir:!1,fileProxyUrl:m,isLink:u};t.push(a)}catch(e){n(r,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${s}`,{error:e.message})}}return t}async function $(o,d,r,f,l=""){const t=await i.promises.readdir(p.join(o,l),{withFileTypes:!0});let g=0;for(const c of t){const s=l?p.join(l,c.name):c.name,h=s.split(p.sep).filter(Boolean);if(h.some(m=>m.startsWith(".")))continue;const e=h[h.length-1];if(d.includes(e)||h.some(m=>r.includes(m)))continue;const w=p.join(o,s);let u;try{u=await i.promises.lstat(w)}catch(m){n(f,"WARN","Error occurred when getting file stats, skipping",{filePath:s.replace(/\\/g,"/"),error:m.message});continue}u.isSymbolicLink()||u.nlink>1||(u.isDirectory()?g+=await $(o,d,r,f,s):u.isFile()&&(g+=u.size))}return g}async function T(o,d,r,f){const l=Date.now(),t=`computer:${o}:${d}`,g=P.COMPUTER_WORKSPACE_DIR;if(!o)throw new y("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!d)throw new y("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const c=String(o),s=String(d),h=f&&f.trim()?f:p.join(g,c,s);if(!i.existsSync(h))return n(t,"INFO","Directory does not exist, returning empty list",{targetDir:h,userId:c,cId:s}),{files:[]};n(t,"DEBUG","Start getting user file list",{targetDir:h,userId:c,cId:s});try{const e=await C(h,h,t,r,f);return n(t,"INFO","User file list obtained successfully",{fileCount:e.length,targetDir:h,userId:c,cId:s,elapsedMs:Date.now()-l}),{files:e}}catch(e){throw n(t,"ERROR","Failed to get user file list",{targetDir:h,userId:c,cId:s,error:e.message,elapsedMs:Date.now()-l}),new N(`Failed to get file list: ${e.message}`,{targetDir:h,originalError:e.message})}}async function B(o,d,r,f){const l=Date.now(),t=`computer:${o}:${d}`,g=P.COMPUTER_WORKSPACE_DIR;if(!o)throw new y("userId cannot be empty",{field:"userId"});if(!d)throw new y("cId cannot be empty",{field:"cId"});if(!Array.isArray(r))throw new y("files must be an array",{field:"files"});const c=String(o),s=String(d),h=f&&f.trim()?f:p.join(g,c,s);i.existsSync(h)||i.mkdirSync(h,{recursive:!0});for(let e=0;e<r.length;e++){const w=r[e];if(!w||typeof w.operation!="string")throw new y(`files[${e}].operation cannot be empty`,{field:`files[${e}].operation`});if(!w.name||typeof w.name!="string")throw new y(`files[${e}].name cannot be empty`,{field:`files[${e}].name`});const u=w.operation.toLowerCase();if(!["create","delete","rename","modify"].includes(u))throw new y(`files[${e}].operation must be one of create, delete, rename or modify`,{field:`files[${e}].operation`});if(u==="rename"&&!w.renameFrom)throw new y(`files[${e}].renameFrom cannot be empty (rename operation requires)`,{field:`files[${e}].renameFrom`});if(u==="modify"&&w.isDir!==!0&&typeof w.contents!="string")throw new y(`files[${e}].contents must be a string (modify operation requires)`,{field:`files[${e}].contents`})}n(t,"DEBUG","Start updating user files",{userId:c,cId:s,filesCount:r.length});try{for(const e of r){const w=e.operation.toLowerCase(),u=e.name,m=p.normalize(u).replace(/^[\/\\]+/,""),a=p.join(h,m),E=p.resolve(a),R=p.resolve(h);if(!E.startsWith(R+p.sep)&&E!==R){n(t,"WARN","File path is not secure, skipping",{filePath:m,resolvedPath:E});continue}switch(w){case"create":{if(e.isDir===!0){if(i.existsSync(a)){if((await i.promises.stat(a)).isFile())throw new y("Cannot create directory, file with the same name already exists",{filePath:m});n(t,"INFO","Directory already exists, skipping creation",{filePath:m});break}await i.promises.mkdir(a,{recursive:!0}),n(t,"INFO","Directory created successfully",{filePath:m});break}if(i.existsSync(a)){if((await i.promises.stat(a)).isDirectory())throw new y("Cannot create file, directory with the same name already exists",{filePath:m});n(t,"INFO","File already exists, skipping creation",{filePath:m});break}await i.promises.mkdir(p.dirname(a),{recursive:!0});const S=e.contents||"";await i.promises.writeFile(a,S,"utf8"),n(t,"INFO","File created successfully",{filePath:m});break}case"delete":{i.existsSync(a)?(await i.promises.stat(a)).isDirectory()?(await i.promises.rm(a,{recursive:!0,force:!0}),n(t,"INFO","Directory deleted successfully",{filePath:m})):(await i.promises.unlink(a),n(t,"INFO","File deleted successfully",{filePath:m})):n(t,"WARN","The file or directory to be deleted does not exist",{filePath:m});break}case"rename":{const S=e.renameFrom;if(!S||typeof S!="string"){n(t,"WARN","Rename operation missing renameFrom",{filePath:m});break}const I=p.normalize(S).replace(/^[\/\\]+/,""),D=p.join(h,I),O=p.resolve(D);if(!O.startsWith(R+p.sep)&&O!==R){n(t,"WARN","Source path is not secure, skipping rename",{sourcePath:I,targetPath:m});break}if(i.existsSync(D)){const k=(await i.promises.stat(D)).isDirectory();await i.promises.mkdir(p.dirname(a),{recursive:!0}),await i.promises.rename(D,a),n(t,"INFO",k?"Directory renamed successfully":"File renamed successfully",{sourcePath:I,targetPath:m})}else n(t,"WARN","The file or directory to be renamed does not exist",{sourcePath:I});break}case"modify":{if(!i.existsSync(a)){n(t,"WARN","The file to be modified does not exist",{filePath:m});break}if((await i.promises.stat(a)).isDirectory()){n(t,"INFO","The target is a directory, skipping modification",{filePath:m});break}const I=typeof e.contents=="string"?e.contents:"";if(await i.promises.readFile(a,"utf8")===I){n(t,"INFO","File content has no changes, skipping write",{filePath:m});break}await i.promises.writeFile(a,I,"utf8"),n(t,"INFO","File modified successfully",{filePath:m});break}default:{n(t,"WARN","Unsupported operation type",{operation:w,filePath:m});break}}}return n(t,"INFO","User files updated successfully",{userId:c,cId:s,filesCount:r.length,elapsedMs:Date.now()-l}),{success:!0,message:"User files updated successfully",userId:c,cId:s,filesCount:r.length}}catch(e){throw n(t,"ERROR","User files updated failed",{userId:c,cId:s,error:e.message,elapsedMs:Date.now()-l}),new N(`User files updated failed: ${e.message}`,{userId:c,cId:s,originalError:e.message})}}async function A(o,d,r,f,l){const t=Date.now(),g=`computer:${o}:${d}`,c=P.COMPUTER_WORKSPACE_DIR;if(!o)throw new y("userId cannot be empty",{field:"userId"});if(!d)throw new y("cId cannot be empty",{field:"cId"});if(!r)throw new y("file cannot be empty",{field:"file"});if(!f||typeof f!="string")throw new y("filePath cannot be empty",{field:"filePath"});const s=String(o),h=String(d),e=l&&l.trim()?l:p.join(c,s,h);i.existsSync(e)||i.mkdirSync(e,{recursive:!0});const w=p.normalize(f).replace(/^[\/\\]+/,""),u=p.join(e,w),m=p.resolve(u),a=p.resolve(e);if(!m.startsWith(a+p.sep)&&m!==a)throw new y("File path is not secure, cannot exceed user directory",{field:"filePath",providedPath:f,resolvedPath:m});try{if(await i.promises.mkdir(p.dirname(u),{recursive:!0}),r.buffer)await i.promises.writeFile(u,r.buffer);else if(typeof r.contents=="string")await i.promises.writeFile(u,r.contents,"utf8");else throw new y("File content format is incorrect",{field:"file",hasBuffer:!!r.buffer,hasContents:typeof r.contents});return n(g,"INFO","File uploaded successfully",{userId:s,cId:h,filePath:w,targetPath:m,fileSize:r.buffer?r.buffer.length:r.contents?r.contents.length:0,elapsedMs:Date.now()-t}),{success:!0,message:"File uploaded successfully",fileSize:r.buffer?r.buffer.length:r.contents?r.contents.length:0}}catch(E){throw n(g,"ERROR","File upload failed",{userId:s,cId:h,filePath:w,error:E.message,elapsedMs:Date.now()-t}),new N(`File upload failed: ${E.message}`,{userId:s,cId:h,filePath:w,originalError:E.message})}}async function G(o,d,r,f,l){const t=Date.now(),g=`computer:${o}:${d}`;if(!o)throw new y("userId cannot be empty",{field:"userId"});if(!d)throw new y("cId cannot be empty",{field:"cId"});if(!Array.isArray(r))throw new y("files must be an array",{field:"files"});if(!Array.isArray(f))throw new y("filePaths must be an array",{field:"filePaths"});if(r.length!==f.length)throw new y(`File count (${r.length}) does not match path count (${f.length})`,{field:"filePaths"});n(g,"DEBUG","Start batch uploading files",{userId:o,cId:d,filesCount:r.length});const c=[];try{for(let e=0;e<r.length;e++){const w=r[e],u=f[e];if(!w){n(g,"WARN","Empty file object encountered in batch upload, skipping",{index:e,filePath:u}),c.push({success:!1,filePath:u,error:"Empty file object"});continue}if(!u||typeof u!="string"){n(g,"WARN","Invalid file path in batch upload, skipping",{index:e,originalname:w.originalname}),c.push({success:!1,filePath:u||"",originalname:w.originalname,error:"Invalid file path"});continue}try{const m=await A(o,d,w,u,l);c.push({success:!0,filePath:u,originalname:w.originalname,...m})}catch(m){n(g,"ERROR","Single file upload failed in batch upload",{filePath:u,originalname:w.originalname,error:m.message}),c.push({success:!1,filePath:u,originalname:w.originalname,error:m.message})}}const s=c.filter(e=>e.success).length,h=c.filter(e=>!e.success).length;return n(g,"INFO","Batch upload files completed",{userId:o,cId:d,totalCount:r.length,successCount:s,failCount:h,elapsedMs:Date.now()-t}),{success:!0,message:"Batch upload completed",totalCount:r.length,successCount:s,failCount:h,results:c}}catch(s){throw n(g,"ERROR","Batch upload files failed",{userId:o,cId:d,error:s.message,elapsedMs:Date.now()-t}),new N(`Batch upload files failed: ${s.message}`,{userId:o,cId:d,originalError:s.message})}}async function K(o,d,r){const f=Date.now(),l=`computer:${o}:${d}`,t=P.COMPUTER_WORKSPACE_DIR;if(!o)throw new y("userId cannot be empty",{field:"userId"});if(!d)throw new y("cId cannot be empty",{field:"cId"});if(!t)throw new N("COMPUTER_WORKSPACE_DIR is not configured, cannot create zip");const g=String(o),c=String(d),s=r&&r.trim()?r:p.join(t,g,c);if(!i.existsSync(s)){const a=`${g}_${c}.zip`;n(l,"WARN","Workspace directory does not exist, returning empty zip",{targetDir:s,userId:g,cId:c,zipFileName:a});const E=_("zip",{zlib:{level:9}});return E.append(null,{name:`${g}_${c}/`,type:"directory"}),E.on("warning",R=>{if(R.code==="ENOENT")n(l,"WARN","Encountered file problem when creating empty zip",{message:R.message,code:R.code});else throw n(l,"ERROR","Encountered warning when creating empty zip",{message:R.message,code:R.code}),R}),E.on("error",R=>{n(l,"ERROR","Failed to create empty zip",{message:R.message})}),{archive:E,zipFileName:a}}const h=`${g}_${c}.zip`;n(l,"DEBUG","Start creating workspace directory zip",{targetDir:s,zipFileName:h});const e=_("zip",{zlib:{level:9}}),w=P.CONTENT_TRAVERSE_EXCLUDE_FILES||[],u=P.TRAVERSE_EXCLUDE_DIRS||[],m=await $(s,w,u,l);if(m>v){const a=v/1024/1024,E=(m/1024/1024).toFixed(2);throw n(l,"WARN","Download rejected due to oversized workspace",{targetDir:s,downloadableSize:m,maxSizeBytes:v}),new y(`Download failed: total file size ${E}MB exceeds limit ${a}MB`,{field:"downloadSize",downloadableSize:m,maxSizeBytes:v})}return e.directory(s,`${g}_${c}`,a=>{const E=a.name||"",R=E.split(/[\/\\]/).filter(Boolean);if(R.some(I=>I.startsWith(".")))return!1;const S=R[R.length-1];if(w.includes(S)||R.some(I=>u.includes(I)))return!1;try{const I=p.join(s,E),D=i.lstatSync(I);if(D.isSymbolicLink()||D.nlink>1)return!1}catch(I){return n(l,"WARN","Error occurred when detecting link file, skipping",{filePath:E,error:I.message}),!1}return a}),e.on("warning",a=>{if(a.code==="ENOENT")n(l,"WARN","Encountered file problem when creating zip",{message:a.message,code:a.code});else throw n(l,"ERROR","Encountered warning when creating zip",{message:a.message,code:a.code}),a}),e.on("error",a=>{n(l,"ERROR","Failed to create zip",{message:a.message,elapsedMs:Date.now()-f})}),e.on("end",()=>{n(l,"INFO","Workspace directory zip created successfully",{targetDir:s,zipFileName:h,elapsedMs:Date.now()-f})}),{archive:e,zipFileName:h}}async function X(o,d,r=200){const f=Date.now(),l=`computer:${o}:${d}`;if(!o)throw new y("userId cannot be empty",{field:"userId"});if(!d)throw new y("cId cannot be empty",{field:"cId"});const t=String(o),g=String(d),c=P.COMPUTER_WORKSPACE_DIR;if(!c)return n(l,"WARN","COMPUTER_WORKSPACE_DIR is not configured"),{success:!0,message:"Log workspace is not configured",logs:[],totalLines:0,startIndex:1,logFileName:null};const s=p.join(c,t,g,".logs");if(!i.existsSync(s))return n(l,"DEBUG","Log directory does not exist",{logDir:s}),{success:!0,message:"Log directory does not exist",logs:[],totalLines:0,startIndex:1,logFileName:null};const e=(await i.promises.readdir(s,{withFileTypes:!0})).filter(F=>F.isFile()).map(F=>F.name);if(e.length===0)return n(l,"DEBUG","No log file found",{logDir:s}),{success:!0,message:"No log file found",logs:[],totalLines:0,startIndex:1,logFileName:null};const w=[];for(const F of e){const k=p.join(s,F),z=await i.promises.stat(k);w.push({name:F,fullPath:k,mtime:z.mtimeMs,size:z.size})}w.sort((F,k)=>k.mtime-F.mtime);const u=w[0],a=(await i.promises.readFile(u.fullPath,"utf8")).split(`
2
- `).filter(F=>F.length>0),E=a.length,R=Math.max(1,r),S=Math.max(0,E-R),I=S+1,O=a.slice(S).map((F,k)=>({line:I+k,content:F}));return n(l,"DEBUG","Get latest logs",{fileName:u.name,fileSize:u.size,totalLines:E,returnedLines:O.length,elapsedMs:Date.now()-f}),{success:!0,message:"Get log successfully",logs:O,totalLines:E,startIndex:I,logFileName:u.name}}async function W(o,d){try{const f=(await i.promises.readdir(o,{withFileTypes:!0})).filter(c=>!c.name.startsWith(".")&&c.name!=="node_modules");if(f.length!==1||!f[0].isDirectory())return;const l=p.join(o,f[0].name),t=p.join(o,`..tmp_${Date.now()}_${Math.round(Math.random()*1e6)}`);try{await i.promises.rename(l,t)}catch(c){if(c.code==="EXDEV")await i.promises.cp(l,t,{recursive:!0}),await i.promises.rm(l,{recursive:!0,force:!0});else throw c}const g=await i.promises.readdir(t);for(const c of g){const s=p.join(t,c),h=p.join(o,c);try{await i.promises.rename(s,h)}catch(e){if(e.code==="EXDEV")(await i.promises.lstat(s)).isDirectory()?await L(s,h):(await i.promises.copyFile(s,h),await i.promises.unlink(s));else throw e}}await i.promises.rm(t,{recursive:!0,force:!0}),n(d,"INFO","Removed single top-level directory from imported zip",{removedDir:f[0].name})}catch(r){n(d,"WARN","Failed to remove top-level directory from imported zip, continuing",{error:r.message})}}async function V(o,d){if(!i.existsSync(o)){await i.promises.mkdir(o,{recursive:!0});return}const r=await i.promises.readdir(o,{withFileTypes:!0});for(const f of r){if(b.has(f.name))continue;const l=p.join(o,f.name);await i.promises.rm(l,{recursive:!0,force:!0}),n(d,"DEBUG","Removed workspace entry during import",{name:f.name})}}async function Z(o,d,r){if(await i.promises.mkdir(d,{recursive:!0}),!i.existsSync(o)){await i.promises.mkdir(o,{recursive:!0});return}const f=await i.promises.readdir(o,{withFileTypes:!0});for(const l of f){if(b.has(l.name))continue;const t=p.join(o,l.name),g=p.join(d,l.name);await x(t,g),n(r,"DEBUG","Backed up workspace entry before import",{name:l.name})}}async function q(o,d,r){if(!i.existsSync(o))return;const f=await i.promises.readdir(o,{withFileTypes:!0});for(const l of f){if(b.has(l.name))continue;const t=p.join(o,l.name),g=p.join(d,l.name);await x(t,g)}n(r,"INFO","Workspace restored from backup after import failure")}async function Y(o,d,r){const f=await i.promises.readdir(o,{withFileTypes:!0}),l=[];try{for(const t of f){if(b.has(t.name)){n(r,"INFO","Skipping preserved entry from imported zip",{name:t.name});continue}const g=p.join(o,t.name),c=p.join(d,t.name);await x(g,c),l.push(t.name)}}catch(t){throw t.mergedEntries=l,t}}async function J(o,d,r,f){const l=Date.now(),t=`computer:${o}:${d}`,g=P.COMPUTER_WORKSPACE_DIR;if(!o)throw new y("userId cannot be empty",{field:"userId"});if(!d)throw new y("cId cannot be empty",{field:"cId"});if(!r||!r.path)throw new y("file is required",{field:"file"});if(!g)throw new N("COMPUTER_WORKSPACE_DIR is not configured");if(p.extname(r.originalname||r.filename||"").toLowerCase()!==".zip")throw new y("Only zip files are supported",{field:"file",originalName:r.originalname});const s=String(o),h=String(d),e=f&&f.trim()?f.trim():p.join(g,s,h),w=p.join(e,".tmp"),u=p.join(w,`import_project_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);let m=null;n(t,"INFO","Start importing project from zip",{userId:s,cId:h,targetDir:e,fileName:r.originalname});try{await i.promises.mkdir(e,{recursive:!0}),await i.promises.mkdir(w,{recursive:!0}),await i.promises.mkdir(u,{recursive:!0}),await M(r.path,u),await W(u,t),m=p.join(w,`import_backup_${Date.now()}_${Math.round(Math.random()*1e6)}`),await Z(e,m,t);try{await Y(u,e,t)}catch(a){throw n(t,"ERROR","Merge imported project failed, restoring workspace",{error:a.message,mergedEntries:a.mergedEntries||[]}),await V(e,t),await q(m,e,t),a}return i.existsSync(m)&&(await i.promises.rm(m,{recursive:!0,force:!0}),m=null),n(t,"INFO","Project imported successfully",{userId:s,cId:h,targetDir:e,elapsedMs:Date.now()-l}),{success:!0,message:"Project imported successfully",userId:s,cId:h,targetDir:e}}catch(a){throw n(t,"ERROR","Failed to import project",{userId:s,cId:h,targetDir:e,error:a.message,elapsedMs:Date.now()-l}),a instanceof y||a instanceof N||a instanceof j?a:new N(`Failed to import project: ${a.message}`,{userId:s,cId:h,originalError:a.message})}finally{if(i.existsSync(u))try{await i.promises.rm(u,{recursive:!0,force:!0})}catch(a){n(t,"WARN","Failed to clean import extract directory",{extractRoot:u,error:a.message})}if(m&&i.existsSync(m))try{await i.promises.rm(m,{recursive:!0,force:!0})}catch(a){n(t,"WARN","Failed to clean import backup directory",{backupDir:m,error:a.message})}if(r?.path&&i.existsSync(r.path))try{await i.promises.unlink(r.path)}catch(a){n(t,"WARN","Failed to clean uploaded zip file",{tempZipPath:r.path,error:a.message})}}}export{T as getFileList,B as updateFiles,A as uploadFile,G as uploadFiles,K as downloadAllFiles,X as getLatestLogs,J as importProject,b as IMPORT_PROJECT_PRESERVED_ENTRIES,W as removeTopLevelDir};
1
+ import i from"fs";import u from"path";import C from"archiver";import P from"../../appConfig/index.js";import{log as a}from"../log/logUtils.js";import{ValidationError as y,SystemError as k,FileError as j}from"../error/errorHandler.js";import{extractZip as L}from"../common/zipUtils.js";import{moveDirectory as M,movePath as z}from"../common/fileSystemUtils.js";const O=new Set([".git",".agents",".claude",".codex",".opencode",".tmp",".logs"]),U=100*1024*1024,x=P.DOWNLOAD_MAX_FILE_SIZE_BYTES||U;async function $(o,d,r,f,l){const t=[],h=await i.promises.readdir(o,{withFileTypes:!0});h.sort((n,s)=>n.isDirectory()&&!s.isDirectory()?-1:!n.isDirectory()&&s.isDirectory()?1:n.name.toLowerCase().localeCompare(s.name.toLowerCase()));for(const n of h){const s=u.join(o,n.name);if(!(n.name.startsWith(".")&&n.name!==".gitignore"||(P.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(n.name))&&!(n.isDirectory()&&P.TRAVERSE_EXCLUDE_DIRS.includes(n.name)))if(n.isDirectory()){const e=await $(s,d,r,f,l);if(e.length===0){const g=d||o,p=u.relative(g,s).replace(/\\/g,"/");t.push({name:p,isDir:!0})}else t.push(...e)}else try{const e=d||o,g=u.relative(e,s).replace(/\\/g,"/"),p=n.isSymbolicLink();let m=null;if(f){const E=g.split("/").map(R=>encodeURIComponent(R)).join("/");m=`${f}/${E}`,l&&(m+=`?customTargetDir=${encodeURIComponent(l)}`)}const c={name:g,isDir:!1,fileProxyUrl:m,isLink:p};t.push(c)}catch(e){a(r,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${s}`,{error:e.message})}}return t}async function A(o,d,r,f,l=""){const t=await i.promises.readdir(u.join(o,l),{withFileTypes:!0});let h=0;for(const n of t){const s=l?u.join(l,n.name):n.name,w=s.split(u.sep).filter(Boolean);if(w.some(m=>m.startsWith(".")))continue;const e=w[w.length-1];if(d.includes(e)||w.some(m=>r.includes(m)))continue;const g=u.join(o,s);let p;try{p=await i.promises.lstat(g)}catch(m){a(f,"WARN","Error occurred when getting file stats, skipping",{filePath:s.replace(/\\/g,"/"),error:m.message});continue}p.isSymbolicLink()||p.nlink>1||(p.isDirectory()?h+=await A(o,d,r,f,s):p.isFile()&&(h+=p.size))}return h}async function T(o,d,r,f){const l=Date.now(),t=`computer:${o}:${d}`,h=P.COMPUTER_WORKSPACE_DIR;if(!o)throw new y("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!d)throw new y("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const n=String(o),s=String(d),w=f&&f.trim()?f:u.join(h,n,s);if(!i.existsSync(w))return a(t,"INFO","Directory does not exist, returning empty list",{targetDir:w,userId:n,cId:s}),{files:[]};a(t,"DEBUG","Start getting user file list",{targetDir:w,userId:n,cId:s});try{const e=await $(w,w,t,r,f);return a(t,"INFO","User file list obtained successfully",{fileCount:e.length,targetDir:w,userId:n,cId:s,elapsedMs:Date.now()-l}),{files:e}}catch(e){throw a(t,"ERROR","Failed to get user file list",{targetDir:w,userId:n,cId:s,error:e.message,elapsedMs:Date.now()-l}),new k(`Failed to get file list: ${e.message}`,{targetDir:w,originalError:e.message})}}async function B(o,d,r,f){const l=Date.now(),t=`computer:${o}:${d}`,h=P.COMPUTER_WORKSPACE_DIR;if(!o)throw new y("userId cannot be empty",{field:"userId"});if(!d)throw new y("cId cannot be empty",{field:"cId"});if(!Array.isArray(r))throw new y("files must be an array",{field:"files"});const n=String(o),s=String(d),w=f&&f.trim()?f:u.join(h,n,s);i.existsSync(w)||i.mkdirSync(w,{recursive:!0});for(let e=0;e<r.length;e++){const g=r[e];if(!g||typeof g.operation!="string")throw new y(`files[${e}].operation cannot be empty`,{field:`files[${e}].operation`});if(!g.name||typeof g.name!="string")throw new y(`files[${e}].name cannot be empty`,{field:`files[${e}].name`});const p=g.operation.toLowerCase();if(!["create","delete","rename","modify"].includes(p))throw new y(`files[${e}].operation must be one of create, delete, rename or modify`,{field:`files[${e}].operation`});if(p==="rename"&&!g.renameFrom)throw new y(`files[${e}].renameFrom cannot be empty (rename operation requires)`,{field:`files[${e}].renameFrom`});if(p==="modify"&&g.isDir!==!0&&typeof g.contents!="string")throw new y(`files[${e}].contents must be a string (modify operation requires)`,{field:`files[${e}].contents`})}a(t,"DEBUG","Start updating user files",{userId:n,cId:s,filesCount:r.length});try{for(const e of r){const g=e.operation.toLowerCase(),p=e.name,m=u.normalize(p).replace(/^[\/\\]+/,""),c=u.join(w,m),E=u.resolve(c),R=u.resolve(w);if(!E.startsWith(R+u.sep)&&E!==R){a(t,"WARN","File path is not secure, skipping",{filePath:m,resolvedPath:E});continue}switch(g){case"create":{if(e.isDir===!0){if(i.existsSync(c)){if((await i.promises.stat(c)).isFile())throw new y("Cannot create directory, file with the same name already exists",{filePath:m});a(t,"INFO","Directory already exists, skipping creation",{filePath:m});break}await i.promises.mkdir(c,{recursive:!0}),a(t,"INFO","Directory created successfully",{filePath:m});break}if(i.existsSync(c)){if((await i.promises.stat(c)).isDirectory())throw new y("Cannot create file, directory with the same name already exists",{filePath:m});a(t,"INFO","File already exists, skipping creation",{filePath:m});break}await i.promises.mkdir(u.dirname(c),{recursive:!0});const S=e.contents||"";await i.promises.writeFile(c,S,"utf8"),a(t,"INFO","File created successfully",{filePath:m});break}case"delete":{i.existsSync(c)?(await i.promises.stat(c)).isDirectory()?(await i.promises.rm(c,{recursive:!0,force:!0}),a(t,"INFO","Directory deleted successfully",{filePath:m})):(await i.promises.unlink(c),a(t,"INFO","File deleted successfully",{filePath:m})):a(t,"WARN","The file or directory to be deleted does not exist",{filePath:m});break}case"rename":{const S=e.renameFrom;if(!S||typeof S!="string"){a(t,"WARN","Rename operation missing renameFrom",{filePath:m});break}const F=u.normalize(S).replace(/^[\/\\]+/,""),D=u.join(w,F),b=u.resolve(D);if(!b.startsWith(R+u.sep)&&b!==R){a(t,"WARN","Source path is not secure, skipping rename",{sourcePath:F,targetPath:m});break}if(i.existsSync(D)){const N=(await i.promises.stat(D)).isDirectory();await i.promises.mkdir(u.dirname(c),{recursive:!0}),await i.promises.rename(D,c),a(t,"INFO",N?"Directory renamed successfully":"File renamed successfully",{sourcePath:F,targetPath:m})}else a(t,"WARN","The file or directory to be renamed does not exist",{sourcePath:F});break}case"modify":{if(!i.existsSync(c)){a(t,"WARN","The file to be modified does not exist",{filePath:m});break}if((await i.promises.stat(c)).isDirectory()){a(t,"INFO","The target is a directory, skipping modification",{filePath:m});break}const F=typeof e.contents=="string"?e.contents:"";if(await i.promises.readFile(c,"utf8")===F){a(t,"INFO","File content has no changes, skipping write",{filePath:m});break}await i.promises.writeFile(c,F,"utf8"),a(t,"INFO","File modified successfully",{filePath:m});break}default:{a(t,"WARN","Unsupported operation type",{operation:g,filePath:m});break}}}return a(t,"INFO","User files updated successfully",{userId:n,cId:s,filesCount:r.length,elapsedMs:Date.now()-l}),{success:!0,message:"User files updated successfully",userId:n,cId:s,filesCount:r.length}}catch(e){throw a(t,"ERROR","User files updated failed",{userId:n,cId:s,error:e.message,elapsedMs:Date.now()-l}),new k(`User files updated failed: ${e.message}`,{userId:n,cId:s,originalError:e.message})}}async function v(o,d,r,f,l){const t=Date.now(),h=`computer:${o}:${d}`,n=P.COMPUTER_WORKSPACE_DIR;if(!o)throw new y("userId cannot be empty",{field:"userId"});if(!d)throw new y("cId cannot be empty",{field:"cId"});if(!r)throw new y("file cannot be empty",{field:"file"});if(!f||typeof f!="string")throw new y("filePath cannot be empty",{field:"filePath"});const s=String(o),w=String(d),e=l&&l.trim()?l:u.join(n,s,w);i.existsSync(e)||i.mkdirSync(e,{recursive:!0});const g=u.normalize(f).replace(/^[\/\\]+/,""),p=u.join(e,g),m=u.resolve(p),c=u.resolve(e);if(!m.startsWith(c+u.sep)&&m!==c)throw new y("File path is not secure, cannot exceed user directory",{field:"filePath",providedPath:f,resolvedPath:m});try{if(await i.promises.mkdir(u.dirname(p),{recursive:!0}),r.buffer)await i.promises.writeFile(p,r.buffer);else if(typeof r.contents=="string")await i.promises.writeFile(p,r.contents,"utf8");else throw new y("File content format is incorrect",{field:"file",hasBuffer:!!r.buffer,hasContents:typeof r.contents});return a(h,"INFO","File uploaded successfully",{userId:s,cId:w,filePath:g,targetPath:m,fileSize:r.buffer?r.buffer.length:r.contents?r.contents.length:0,elapsedMs:Date.now()-t}),{success:!0,message:"File uploaded successfully",fileSize:r.buffer?r.buffer.length:r.contents?r.contents.length:0}}catch(E){throw a(h,"ERROR","File upload failed",{userId:s,cId:w,filePath:g,error:E.message,elapsedMs:Date.now()-t}),new k(`File upload failed: ${E.message}`,{userId:s,cId:w,filePath:g,originalError:E.message})}}async function G(o,d,r,f,l){const t=Date.now(),h=`computer:${o}:${d}`;if(!o)throw new y("userId cannot be empty",{field:"userId"});if(!d)throw new y("cId cannot be empty",{field:"cId"});if(!Array.isArray(r))throw new y("files must be an array",{field:"files"});if(!Array.isArray(f))throw new y("filePaths must be an array",{field:"filePaths"});if(r.length!==f.length)throw new y(`File count (${r.length}) does not match path count (${f.length})`,{field:"filePaths"});a(h,"DEBUG","Start batch uploading files",{userId:o,cId:d,filesCount:r.length});const n=[];try{for(let e=0;e<r.length;e++){const g=r[e],p=f[e];if(!g){a(h,"WARN","Empty file object encountered in batch upload, skipping",{index:e,filePath:p}),n.push({success:!1,filePath:p,error:"Empty file object"});continue}if(!p||typeof p!="string"){a(h,"WARN","Invalid file path in batch upload, skipping",{index:e,originalname:g.originalname}),n.push({success:!1,filePath:p||"",originalname:g.originalname,error:"Invalid file path"});continue}try{const m=await v(o,d,g,p,l);n.push({success:!0,filePath:p,originalname:g.originalname,...m})}catch(m){a(h,"ERROR","Single file upload failed in batch upload",{filePath:p,originalname:g.originalname,error:m.message}),n.push({success:!1,filePath:p,originalname:g.originalname,error:m.message})}}const s=n.filter(e=>e.success).length,w=n.filter(e=>!e.success).length;return a(h,"INFO","Batch upload files completed",{userId:o,cId:d,totalCount:r.length,successCount:s,failCount:w,elapsedMs:Date.now()-t}),{success:!0,message:"Batch upload completed",totalCount:r.length,successCount:s,failCount:w,results:n}}catch(s){throw a(h,"ERROR","Batch upload files failed",{userId:o,cId:d,error:s.message,elapsedMs:Date.now()-t}),new k(`Batch upload files failed: ${s.message}`,{userId:o,cId:d,originalError:s.message})}}async function K(o,d,r){const f=Date.now(),l=`computer:${o}:${d}`,t=P.COMPUTER_WORKSPACE_DIR;if(!o)throw new y("userId cannot be empty",{field:"userId"});if(!d)throw new y("cId cannot be empty",{field:"cId"});if(!t)throw new k("COMPUTER_WORKSPACE_DIR is not configured, cannot create zip");const h=String(o),n=String(d),s=r&&r.trim()?r:u.join(t,h,n);if(!i.existsSync(s)){const c=`${h}_${n}.zip`;a(l,"WARN","Workspace directory does not exist, returning empty zip",{targetDir:s,userId:h,cId:n,zipFileName:c});const E=C("zip",{zlib:{level:9}});return E.append(null,{name:`${h}_${n}/`,type:"directory"}),E.on("warning",R=>{if(R.code==="ENOENT")a(l,"WARN","Encountered file problem when creating empty zip",{message:R.message,code:R.code});else throw a(l,"ERROR","Encountered warning when creating empty zip",{message:R.message,code:R.code}),R}),E.on("error",R=>{a(l,"ERROR","Failed to create empty zip",{message:R.message})}),{archive:E,zipFileName:c}}const w=`${h}_${n}.zip`;a(l,"DEBUG","Start creating workspace directory zip",{targetDir:s,zipFileName:w});const e=C("zip",{zlib:{level:9}}),g=P.CONTENT_TRAVERSE_EXCLUDE_FILES||[],p=P.TRAVERSE_EXCLUDE_DIRS||[],m=await A(s,g,p,l);if(m>x){const c=x/1024/1024,E=(m/1024/1024).toFixed(2);throw a(l,"WARN","Download rejected due to oversized workspace",{targetDir:s,downloadableSize:m,maxSizeBytes:x}),new y(`Download failed: total file size ${E}MB exceeds limit ${c}MB`,{field:"downloadSize",downloadableSize:m,maxSizeBytes:x})}return e.directory(s,`${h}_${n}`,c=>{const E=c.name||"",R=E.split(/[\/\\]/).filter(Boolean);if(R.some(F=>F.startsWith(".")))return!1;const S=R[R.length-1];if(g.includes(S)||R.some(F=>p.includes(F)))return!1;try{const F=u.join(s,E),D=i.lstatSync(F);if(D.isSymbolicLink()||D.nlink>1)return!1}catch(F){return a(l,"WARN","Error occurred when detecting link file, skipping",{filePath:E,error:F.message}),!1}return c}),e.on("warning",c=>{if(c.code==="ENOENT")a(l,"WARN","Encountered file problem when creating zip",{message:c.message,code:c.code});else throw a(l,"ERROR","Encountered warning when creating zip",{message:c.message,code:c.code}),c}),e.on("error",c=>{a(l,"ERROR","Failed to create zip",{message:c.message,elapsedMs:Date.now()-f})}),e.on("end",()=>{a(l,"INFO","Workspace directory zip created successfully",{targetDir:s,zipFileName:w,elapsedMs:Date.now()-f})}),{archive:e,zipFileName:w}}async function X(o,d,r=200){const f=Date.now(),l=`computer:${o}:${d}`;if(!o)throw new y("userId cannot be empty",{field:"userId"});if(!d)throw new y("cId cannot be empty",{field:"cId"});const t=String(o),h=String(d),n=P.COMPUTER_WORKSPACE_DIR;if(!n)return a(l,"WARN","COMPUTER_WORKSPACE_DIR is not configured"),{success:!0,message:"Log workspace is not configured",logs:[],totalLines:0,startIndex:1,logFileName:null};const s=u.join(n,t,h,".logs");if(!i.existsSync(s))return a(l,"DEBUG","Log directory does not exist",{logDir:s}),{success:!0,message:"Log directory does not exist",logs:[],totalLines:0,startIndex:1,logFileName:null};const e=(await i.promises.readdir(s,{withFileTypes:!0})).filter(I=>I.isFile()).map(I=>I.name);if(e.length===0)return a(l,"DEBUG","No log file found",{logDir:s}),{success:!0,message:"No log file found",logs:[],totalLines:0,startIndex:1,logFileName:null};const g=[];for(const I of e){const N=u.join(s,I),_=await i.promises.stat(N);g.push({name:I,fullPath:N,mtime:_.mtimeMs,size:_.size})}g.sort((I,N)=>N.mtime-I.mtime);const p=g[0],c=(await i.promises.readFile(p.fullPath,"utf8")).split(`
2
+ `).filter(I=>I.length>0),E=c.length,R=Math.max(1,r),S=Math.max(0,E-R),F=S+1,b=c.slice(S).map((I,N)=>({line:F+N,content:I}));return a(l,"DEBUG","Get latest logs",{fileName:p.name,fileSize:p.size,totalLines:E,returnedLines:b.length,elapsedMs:Date.now()-f}),{success:!0,message:"Get log successfully",logs:b,totalLines:E,startIndex:F,logFileName:p.name}}async function W(o,d){try{const f=(await i.promises.readdir(o,{withFileTypes:!0})).filter(n=>!n.name.startsWith(".")&&n.name!=="node_modules");if(f.length!==1||!f[0].isDirectory())return;const l=u.join(o,f[0].name),t=u.join(o,`..tmp_${Date.now()}_${Math.round(Math.random()*1e6)}`);try{await i.promises.rename(l,t)}catch(n){if(n.code==="EXDEV")await i.promises.cp(l,t,{recursive:!0}),await i.promises.rm(l,{recursive:!0,force:!0});else throw n}const h=await i.promises.readdir(t);for(const n of h){const s=u.join(t,n),w=u.join(o,n);try{await i.promises.rename(s,w)}catch(e){if(e.code==="EXDEV")(await i.promises.lstat(s)).isDirectory()?await M(s,w):(await i.promises.copyFile(s,w),await i.promises.unlink(s));else throw e}}await i.promises.rm(t,{recursive:!0,force:!0}),a(d,"INFO","Removed single top-level directory from imported zip",{removedDir:f[0].name})}catch(r){a(d,"WARN","Failed to remove top-level directory from imported zip, continuing",{error:r.message})}}async function V(o,d){if(!i.existsSync(o)){await i.promises.mkdir(o,{recursive:!0});return}const r=await i.promises.readdir(o,{withFileTypes:!0});for(const f of r){if(O.has(f.name))continue;const l=u.join(o,f.name);await i.promises.rm(l,{recursive:!0,force:!0}),a(d,"DEBUG","Removed workspace entry during import",{name:f.name})}}async function Z(o,d,r){if(await i.promises.mkdir(d,{recursive:!0}),!i.existsSync(o)){await i.promises.mkdir(o,{recursive:!0});return}const f=await i.promises.readdir(o,{withFileTypes:!0});for(const l of f){if(O.has(l.name))continue;const t=u.join(o,l.name),h=u.join(d,l.name);await z(t,h),a(r,"DEBUG","Backed up workspace entry before import",{name:l.name})}}async function q(o,d,r){if(!i.existsSync(o))return;const f=await i.promises.readdir(o,{withFileTypes:!0});for(const l of f){if(O.has(l.name))continue;const t=u.join(o,l.name),h=u.join(d,l.name);await z(t,h)}a(r,"INFO","Workspace restored from backup after import failure")}async function Y(o,d,r){const f=await i.promises.readdir(o,{withFileTypes:!0}),l=[];try{for(const t of f){if(O.has(t.name)){a(r,"INFO","Skipping preserved entry from imported zip",{name:t.name});continue}const h=u.join(o,t.name),n=u.join(d,t.name);await z(h,n),l.push(t.name)}}catch(t){throw t.mergedEntries=l,t}}async function J(o,d,r,f){const l=Date.now(),t=`computer:${o}:${d}`,h=P.COMPUTER_WORKSPACE_DIR;if(!o)throw new y("userId cannot be empty",{field:"userId"});if(!d)throw new y("cId cannot be empty",{field:"cId"});if(!r||!r.path)throw new y("file is required",{field:"file"});if(!h)throw new k("COMPUTER_WORKSPACE_DIR is not configured");if(u.extname(r.originalname||r.filename||"").toLowerCase()!==".zip")throw new y("Only zip files are supported",{field:"file",originalName:r.originalname});const s=String(o),w=String(d),e=f&&f.trim()?f.trim():u.join(h,s,w),g=u.join(e,".tmp"),p=u.join(g,`import_project_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);let m=null;a(t,"INFO","Start importing project from zip",{userId:s,cId:w,targetDir:e,fileName:r.originalname});try{await i.promises.mkdir(e,{recursive:!0}),await i.promises.mkdir(g,{recursive:!0}),await i.promises.mkdir(p,{recursive:!0}),await L(r.path,p),await W(p,t),m=u.join(g,`import_backup_${Date.now()}_${Math.round(Math.random()*1e6)}`),await Z(e,m,t);try{await Y(p,e,t)}catch(c){throw a(t,"ERROR","Merge imported project failed, restoring workspace",{error:c.message,mergedEntries:c.mergedEntries||[]}),await V(e,t),await q(m,e,t),c}return i.existsSync(m)&&(await i.promises.rm(m,{recursive:!0,force:!0}),m=null),a(t,"INFO","Project imported successfully",{userId:s,cId:w,targetDir:e,elapsedMs:Date.now()-l}),{success:!0,message:"Project imported successfully",userId:s,cId:w,targetDir:e}}catch(c){throw a(t,"ERROR","Failed to import project",{userId:s,cId:w,targetDir:e,error:c.message,elapsedMs:Date.now()-l}),c instanceof y||c instanceof k||c instanceof j?c:new k(`Failed to import project: ${c.message}`,{userId:s,cId:w,originalError:c.message})}finally{if(i.existsSync(p))try{await i.promises.rm(p,{recursive:!0,force:!0})}catch(c){a(t,"WARN","Failed to clean import extract directory",{extractRoot:p,error:c.message})}if(m&&i.existsSync(m))try{await i.promises.rm(m,{recursive:!0,force:!0})}catch(c){a(t,"WARN","Failed to clean import backup directory",{backupDir:m,error:c.message})}if(r?.path&&i.existsSync(r.path))try{await i.promises.unlink(r.path)}catch(c){a(t,"WARN","Failed to clean uploaded zip file",{tempZipPath:r.path,error:c.message})}}}async function H(o,d,r,f,l){const t=`computer:${o}:${d}`;if(!r||typeof r!="string"||!r.trim())throw new y("fileName cannot be empty",{field:"fileName"});if(f!=null&&typeof f!="string")throw new y("content must be a string",{field:"content"});const h=r.trim(),n=f??"";return a(t,"INFO","Generate file from text content",{userId:o,cId:d,fileName:h,contentLength:n.length}),{...await v(o,d,{contents:n,originalname:u.basename(h),size:Buffer.byteLength(n,"utf8")},h,l),message:"File generated successfully",fileName:h}}export{T as getFileList,B as updateFiles,v as uploadFile,G as uploadFiles,H as generateFile,K as downloadAllFiles,X as getLatestLogs,J as importProject,O as IMPORT_PROJECT_PRESERVED_ENTRIES,W as removeTopLevelDir};
@@ -1,6 +1,6 @@
1
- import f from"path";import n from"fs";import e from"isomorphic-git";import o from"../../appConfig/index.js";function g(i){return n.existsSync(f.join(i,".git"))}function m(){return{name:o.GIT_DEFAULT_AUTHOR_NAME,email:o.GIT_DEFAULT_AUTHOR_EMAIL}}async function d(i){const t=await e.statusMatrix({fs:n,dir:i});await Promise.all(t.map(([a,s,l])=>{if(l===2)return e.add({fs:n,dir:i,filepath:a}).catch(()=>{});if(s===1&&l===0)return e.remove({fs:n,dir:i,filepath:a}).catch(()=>{})}))}async function A(i,t){for(const a of t){const s=f.join(i,a);n.existsSync(s)?await e.add({fs:n,dir:i,filepath:a}):await e.remove({fs:n,dir:i,filepath:a}).catch(()=>{})}}async function T(i){if(g(i))c(i);else{await e.init({fs:n,dir:i,defaultBranch:"main"}),await e.setConfig({fs:n,dir:i,path:"user.name",value:o.GIT_DEFAULT_AUTHOR_NAME}),await e.setConfig({fs:n,dir:i,path:"user.email",value:o.GIT_DEFAULT_AUTHOR_EMAIL}),c(i);const t=f.join(i,".gitignore");n.existsSync(t)&&await e.add({fs:n,dir:i,filepath:".gitignore"}),(await e.listFiles({fs:n,dir:i})).length===0&&(n.writeFileSync(f.join(i,".gitkeep"),""),await e.add({fs:n,dir:i,filepath:".gitkeep"})),await e.commit({fs:n,dir:i,message:"Initial commit",author:m()})}}async function _(i,t){if(g(i))try{Array.isArray(t)&&t.length>0?await A(i,t):await d(i)}catch{}}function c(i){if(!o.GIT_AUTO_GITIGNORE)return;const t=f.join(i,".gitignore"),a=o.GIT_GITIGNORE_ENTRIES||[];let s=[];n.existsSync(t)&&(s=n.readFileSync(t,"utf8").split(/\r?\n/));const l=new Set(s.map(r=>r.trim()).filter(Boolean)),u=a.filter(r=>!l.has(r));if(u.length>0){const r=s.length>0&&s[s.length-1]!==""?`
2
- `+u.join(`
1
+ import m from"path";import a from"fs";import r from"isomorphic-git";import u from"../../appConfig/index.js";import{log as G}from"../log/logUtils.js";import{shouldUseNativeGit as d,nativeAddAll as R,nativeAddAllAndCommit as N,isNativeGitUnavailableError as y,markNativeGitMissing as U}from"./nativeGitUtils.js";function g(t){return a.existsSync(m.join(t,".git"))}function S(){return{name:u.GIT_DEFAULT_AUTHOR_NAME,email:u.GIT_DEFAULT_AUTHOR_EMAIL}}async function T(t){try{return await r.resolveRef({fs:a,dir:t,ref:"HEAD"}),!0}catch{return!1}}function _(t,n,e){U();const i=n&&typeof n=="object"&&"message"in n?String(n.message):String(n);G(m.basename(t)||"git","WARN",`Native git unavailable during ${e}, fallback to isomorphic-git`,{error:i})}async function v(t,n={}){const{cache:e}=n,i=[];return await r.walk({fs:a,dir:t,cache:e,trees:[r.WORKDIR()],map:async(s,[o])=>{if(!o)return null;if(s===".")return;const l=await o.type();if(l==="tree")return await r.isIgnored({fs:a,dir:t,filepath:s})?null:void 0;if(l!=="blob"||await r.isIgnored({fs:a,dir:t,filepath:s}))return null;i.push(s)}}),i}async function F(t,n={}){const{cache:e}=n,i=await v(t,{cache:e});return i.length>0&&await r.add({fs:a,dir:t,filepath:i,parallel:!0,cache:e,force:!0}),{hasChanges:i.length>0,toAdd:i,toRemove:[]}}async function h(t,n={}){const{cache:e}=n;if(!await T(t))return F(t,{cache:e});const i=await r.statusMatrix({fs:a,dir:t,cache:e}),s=[],o=[];for(const[c,f,w,p]of i)w===2&&p!==2&&s.push(c),f===1&&w===0&&p!==0&&o.push(c);s.length>0&&await r.add({fs:a,dir:t,filepath:s,parallel:!0,cache:e,force:!0});for(const c of o)await r.remove({fs:a,dir:t,filepath:c,cache:e});return{hasChanges:s.length>0||o.length>0||i.some(([,,,c])=>c!==1),toAdd:s,toRemove:o}}async function I(t,n={}){if(await d())try{return await R(t)}catch(e){if(!y(e))throw e;_(t,e,"addAll")}return h(t,n)}async function C(t,n={}){const{message:e,authorName:i=u.GIT_DEFAULT_AUTHOR_NAME,authorEmail:s=u.GIT_DEFAULT_AUTHOR_EMAIL,cache:o}=n;if(await d())try{return{...await N(t,{message:e,authorName:i,authorEmail:s}),viaNative:!0}}catch(f){if(!y(f))throw f;_(t,f,"commitAllChanges")}const{hasChanges:l}=await h(t,{cache:o});return l?{nothingToCommit:!1,commitHash:await r.commit({fs:a,dir:t,message:e,author:{name:i,email:s},cache:o}),viaNative:!1}:{nothingToCommit:!0,viaNative:!1}}async function E(t,n,e={}){const{cache:i,force:s=!1}=e,o=[],l=[];for(const c of n){const f=m.join(t,c);a.existsSync(f)?o.push(c):l.push(c)}o.length>0&&await r.add({fs:a,dir:t,filepath:o,parallel:!0,cache:i,force:s});for(const c of l)await r.remove({fs:a,dir:t,filepath:c,cache:i})}async function x(t){if(g(t))A(t);else{await r.init({fs:a,dir:t,defaultBranch:"main"}),await r.setConfig({fs:a,dir:t,path:"user.name",value:u.GIT_DEFAULT_AUTHOR_NAME}),await r.setConfig({fs:a,dir:t,path:"user.email",value:u.GIT_DEFAULT_AUTHOR_EMAIL}),A(t);const n=m.join(t,".gitignore"),e=m.join(t,".gitkeep");!a.existsSync(n)&&!a.existsSync(e)&&a.writeFileSync(e,"")}}async function H(t,n){if(g(t))try{Array.isArray(n)&&n.length>0?await E(t,n):await I(t)}catch{}}function A(t){if(!u.GIT_AUTO_GITIGNORE)return;const n=m.join(t,".gitignore"),e=u.GIT_GITIGNORE_ENTRIES||[];let i=[];a.existsSync(n)&&(i=a.readFileSync(n,"utf8").split(/\r?\n/));const s=new Set(i.map(l=>l.trim()).filter(Boolean)),o=e.filter(l=>!s.has(l));if(o.length>0){const l=i.length>0&&i[i.length-1]!==""?`
2
+ `+o.join(`
3
3
  `)+`
4
- `:u.join(`
4
+ `:o.join(`
5
5
  `)+`
6
- `;n.appendFileSync(t,r,"utf8")}}export{g as isGitRepo,T as ensureGitRepo,c as ensureGitignore,_ as autoGitAdd,d as addAll,A as stageFiles,m as getDefaultAuthor};
6
+ `;a.appendFileSync(n,l,"utf8")}}export{g as isGitRepo,x as ensureGitRepo,A as ensureGitignore,H as autoGitAdd,I as addAll,h as addAllWithIsomorphic,C as commitAllChanges,E as stageFiles,S as getDefaultAuthor,T as hasGitHead,v as listWorkdirFilesSkippingIgnored};
@@ -0,0 +1 @@
1
+ import x from"cross-spawn";import U from"../../appConfig/index.js";let E=null,A=0;const p=30*1e3,y=10*60*1e3;function O(){E=null,A=0}function g(){return U.GIT_USE_NATIVE!==!1}function R(e){if(!e||typeof e!="object")return!1;const t=e;if(t.code==="ENOENT"||t.code==="NATIVE_GIT_UNAVAILABLE")return!0;const s=`${t.message||""} ${t.stderr||""}`;return/spawn\s+git(\.exe)?\s+ENOENT|git(\.exe)?:?\s*command not found|git(\.exe)?\s+not found|is not recognized as an internal or external command/i.test(s)}function G(){E=null,A=Date.now()+p}function l(e,t,s={}){const{allowFailure:r=!1,env:m={},timeoutMs:d=y}=s;return new Promise((c,f)=>{const o=x("git",t,{cwd:e,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...m},windowsHide:!0});let a="",u="",h=!1,v=!1,I=null;const w=d>0?setTimeout(()=>{v=!0;try{o.kill("SIGTERM")}catch{}I=setTimeout(()=>{try{o.kill("SIGKILL")}catch{}},2e3)},d):null,C=i=>{h||(h=!0,w&&clearTimeout(w),I&&clearTimeout(I),i())};o.stdout?.on("data",i=>{a+=i.toString()}),o.stderr?.on("data",i=>{u+=i.toString()}),o.on("error",i=>{C(()=>{if(r){c({stdout:a,stderr:u||i.message,exitCode:1});return}f(i)})}),o.on("close",i=>{C(()=>{if(v){const n=new Error(`git ${t.join(" ")} timed out after ${d}ms`);if(n.code="ETIMEDOUT",n.exitCode=-1,n.stdout=a,n.stderr=u,r){c({stdout:a,stderr:u||n.message,exitCode:-1});return}f(n);return}const _=i??1;if(_!==0&&!r){const n=(u||a||"").trim()||`git ${t.join(" ")} failed`,T=new Error(n);T.exitCode=_,T.stdout=a,T.stderr=u,f(T);return}c({stdout:a,stderr:u,exitCode:_})})})})}async function N(){if(!g())return!1;if(E===!0)return!0;if(Date.now()<A)return!1;try{if((await l(process.cwd(),["--version"],{allowFailure:!0,timeoutMs:5e3})).exitCode===0)return E=!0,A=0,!0}catch{}return G(),!1}async function b(){return N()}async function M(e){await l(e,["add","-A"]);const t=await l(e,["diff","--cached","--quiet"],{allowFailure:!0});if(t.exitCode===0)return{hasChanges:!1,toAdd:[],toRemove:[]};if(t.exitCode===1)return{hasChanges:!0,toAdd:[],toRemove:[]};const s=(t.stderr||t.stdout||"").trim()||`git diff --cached --quiet failed (exit ${t.exitCode})`,r=new Error(s);throw r.exitCode=t.exitCode,r.stderr=t.stderr,r.stdout=t.stdout,r}async function L(e,t){const{message:s,authorName:r,authorEmail:m}=t,d={GIT_AUTHOR_NAME:r,GIT_AUTHOR_EMAIL:m,GIT_COMMITTER_NAME:r,GIT_COMMITTER_EMAIL:m},{hasChanges:c}=await M(e);if(!c)return{nothingToCommit:!0};await l(e,["commit","-m",s],{env:d});const{stdout:f}=await l(e,["rev-parse","HEAD"]),o=f.trim();if(!o)throw new Error("Native git commit succeeded but HEAD is empty");return{nothingToCommit:!1,commitHash:o}}export{g as isNativeGitEnabled,N as isNativeGitAvailable,b as shouldUseNativeGit,R as isNativeGitUnavailableError,G as markNativeGitMissing,l as runGit,M as nativeAddAll,L as nativeAddAllAndCommit,O as resetNativeGitAvailabilityCache};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuwax-file-server",
3
3
  "displayName": "nuwax-file-server",
4
- "version": "1.3.4",
4
+ "version": "1.3.5",
5
5
  "description": "Cross-platform file service deployment tool with start/stop/restart CLI commands",
6
6
  "type": "module",
7
7
  "main": "index.js",