nuwax-file-server 1.3.0-beta.24 → 1.3.0-beta.26

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 o from"os";import{fileURLToPath as T}from"url";import I from"dotenv";const L=E.dirname(T(import.meta.url));I.config();function O(){const e=process.env.LOG_BASE_DIR,_=E.join(o.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 p(e){const _=E.join(L,"..",`env.${e}`);if(n.existsSync(_))I.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)}}p(r);const R={NODE_ENV:r,PORT:parseInt(process.env.PORT),DEPLOYMENT_MODE:process.env.DEPLOYMENT_MODE||"docker-compose",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:O(),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",".agents/",".claude/",".opencode/",".codex/"],GIT_ENABLED:process.env.GIT_ENABLED?.toLowerCase()==="true",BASH_PATH:process.env.BASH_PATH||"",ZIP_WORKSPACE_EXCLUDE_DIRS:process.env.ZIP_WORKSPACE_EXCLUDE_DIRS?process.env.ZIP_WORKSPACE_EXCLUDE_DIRS.split(",").map(e=>e.trim()).filter(Boolean):[".git",".tmp",".claude",".agents",".codex",".opencode",".logs","__pycache__","node_modules","dist"]};export default R;
1
+ import E from"path";import n from"fs";import o from"os";import{fileURLToPath as T}from"url";import r from"dotenv";const L=E.dirname(T(import.meta.url));r.config();function p(){const e=process.env.LOG_BASE_DIR,_=E.join(o.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 I=process.env.NODE_ENV||"development";function O(e){const _=E.join(L,"..",`env.${e}`);if(n.existsSync(_))r.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(I);const R={NODE_ENV:I,PORT:parseInt(process.env.PORT),DEPLOYMENT_MODE:process.env.DEPLOYMENT_MODE||"docker-compose",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/"],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"]};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.0-beta.24",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.0-beta.26",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();
@@ -93,11 +93,11 @@ COMPUTER_LOG_DIR=/app/logs/computer_logs
93
93
  GIT_DEFAULT_AUTHOR_NAME=Nuwax File Server
94
94
  GIT_DEFAULT_AUTHOR_EMAIL=git@nuwax.com
95
95
  GIT_AUTO_GITIGNORE=true
96
- GIT_GITIGNORE_ENTRIES=node_modules/|.pnpm-store/|dist/|dist-packages/|build/|.idea/|.vscode/|.DS_Store|.agents/|.claude/|.opencode/|.codex/|.tmp/
96
+ GIT_GITIGNORE_ENTRIES=node_modules/|.pnpm-store/|dist/|dist-packages/|build/|.idea/|.vscode/|.DS_Store|.npmrc|.agents/|.claude/|.opencode/|.codex/|.tmp/|.logs/
97
97
  GIT_ENABLED=true
98
98
 
99
99
  # Windows 专用路径(Linux/macOS 留空)
100
100
  BASH_PATH=
101
101
 
102
- # zip-workspace 打包时排除的目录(逗号分隔)
103
- ZIP_WORKSPACE_EXCLUDE_DIRS=.git,.tmp,.claude,.agents,.codex,.opencode,.logs,__pycache__,node_modules,dist
102
+ # zip-workspace 打包时排除的路径片段(逗号分隔,目录或文件名均可)
103
+ ZIP_WORKSPACE_EXCLUDE=.git,.tmp,.claude,.agents,.codex,.opencode,.logs,.npmrc,__pycache__,node_modules,dist
@@ -93,11 +93,11 @@ COMPUTER_LOG_DIR=/app/logs/computer_logs
93
93
  GIT_DEFAULT_AUTHOR_NAME=Nuwax File Server
94
94
  GIT_DEFAULT_AUTHOR_EMAIL=git@nuwax.com
95
95
  GIT_AUTO_GITIGNORE=true
96
- GIT_GITIGNORE_ENTRIES=node_modules/|.pnpm-store/|dist/|dist-packages/|build/|.idea/|.vscode/|.DS_Store|.agents/|.claude/|.opencode/|.codex/|.tmp/
96
+ GIT_GITIGNORE_ENTRIES=node_modules/|.pnpm-store/|dist/|dist-packages/|build/|.idea/|.vscode/|.DS_Store|.npmrc|.agents/|.claude/|.opencode/|.codex/|.tmp/|.logs/
97
97
  GIT_ENABLED=true
98
98
 
99
99
  # Windows 专用路径(Linux/macOS 留空)
100
100
  BASH_PATH=
101
101
 
102
- # zip-workspace 打包时排除的目录(逗号分隔)
103
- ZIP_WORKSPACE_EXCLUDE_DIRS=.git,.tmp,.claude,.agents,.codex,.opencode,.logs,__pycache__,node_modules,dist
102
+ # zip-workspace 打包时排除的路径片段(逗号分隔,目录或文件名均可)
103
+ ZIP_WORKSPACE_EXCLUDE=.git,.tmp,.claude,.agents,.codex,.opencode,.logs,.npmrc,__pycache__,node_modules,dist
@@ -1,8 +1,8 @@
1
- import A from"path";import i from"fs";import ft from"crypto";import l from"isomorphic-git";import{createPatch as dt}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 k,ResourceError as D}from"../utils/error/errorHandler.js";import{resolveProjectPath as ut}from"../utils/common/projectPathUtils.js";import{isGitRepo as ht,ensureGitRepo as T,ensureGitignore as M,addAll as U,getDefaultAuthor as gt}from"../utils/git/gitUtils.js";function P(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=A.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=ut(a,e||{});if(!i.existsSync(o))throw new D("Project does not exist",{projectId:a});return{targetPath:o,logId:a}}function L(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 ft.createHash("sha1").update(Buffer.concat([t,n])).digest("hex")}function mt(n,t,a,e,s,r,o){const h=dt(n,e?t:"",s?a:"",e?`a/${n}`:"/dev/null",s?`b/${n}`:"/dev/null").split(`
2
- `).slice(4);h.length>0&&h[h.length-1]===""&&h.pop();const g=[];let u=0,d=0;for(const m of h){if(m.startsWith("@@")){const y=m.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(y){const S=y[1],F=y[2]!==void 0?parseInt(y[2],10):1,N=y[3],R=y[4]!==void 0?parseInt(y[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("---")&&d++,g.push(m)}const f=e&&t!==""&&!t.endsWith(`
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
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 y=-1,S=-1,F=-1;for(let R=g.length-1;R>m;R--){const $=g[R];$.startsWith("-")&&!$.startsWith("---")&&y<0?y=R:$.startsWith("+")&&!$.startsWith("++")&&S<0?S=R:$.startsWith(" ")&&F<0&&(F=R)}const N=Math.max(y,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",I=s&&o?C(o).substring(0,7):"0000000",E=[];return E.push(`diff --git a/${n} b/${n}`),e?s?E.push(`index ${O}..${I} 100644`):(E.push("deleted file mode 100644"),E.push(`index ${O}..0000000`)):(E.push("new file mode 100644"),E.push(`index 0000000..${I}`)),E.push(`--- ${e?`a/${n}`:"/dev/null"}`),E.push(`+++ ${s?`b/${n}`:"/dev/null"}`),{diff:[...E,...g].join(`
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(`
5
5
  `)+`
6
- `,insertions:u,deletions:d}}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 q(n={}){const{targetPath:t,logId:a}=P(n);if(ht(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 k("Failed to initialize Git repository",{originalError:e.message})}}async function z(n={}){const{targetPath:t,logId:a}=P(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=[],p=[],h=[];for(const[g,u,d,f]of s)u!==f&&r.push(g),u===0&&f!==0&&c.push(g),(u===1&&f===0||d===0&&f!==0)&&p.push(g),f!==0&&d!==0&&d!==f&&o.push(g),u===0&&f===0&&d!==0&&h.push(g);return{success:!0,logId:a,current:e,staged:[...new Set(r)],modified:[...new Set(o)],created:[...new Set(c)],deleted:[...new Set(p)],untracked:[...new Set(h)],conflicted:[],ahead:0,behind:0,tracking:null}}catch(e){throw w(a,"ERROR","Failed to get Git status",{logId:a,error:e.message}),new k("Failed to get Git status",{originalError:e.message})}}async function K(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}=P(n);await T(r);try{if(Array.isArray(a)&&a.length>0){const u=a.filter(d=>i.existsSync(A.join(r,d)));await Promise.all(u.map(d=>l.add({fs:i,dir:r,filepath:d})))}else await U(r);const p=(await l.statusMatrix({fs:i,dir:r})).some(([,,,u])=>u!==1);if(!p)return{success:!0,message:"Nothing to commit",logId:o,nothingToCommit:!0};const h={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:h});return w(o,"INFO","Git commit successful",{logId:o,commitHash:g,message:t}),{success:!0,message:"Commit successful",logId:o,commit:g,summary:{changes:p?1:0}}}catch(c){throw w(o,"ERROR","Failed to commit",{logId:o,error:c.message}),new k("Failed to commit",{originalError:c.message})}}async function V(n={}){const{files:t}=n,{targetPath:a,logId:e}=P(n);await T(a);try{return Array.isArray(t)&&t.length>0?await Promise.all(t.map(s=>l.add({fs:i,dir:a,filepath:s}))):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 k("Failed to add files",{originalError:s.message})}}async function J(n={}){const{files:t}=n,{targetPath:a,logId:e}=P(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 k("Failed to unstage files",{originalError:s.message})}}async function j(n,t){const a=new Set;for(const s of t){let r=A.dirname(s);for(;r&&r!==".";)a.add(r),r=A.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=A.join(n,s);try{(await i.promises.readdir(r)).length===0&&await i.promises.rmdir(r)}catch{}}}async function Q(n={}){const{files:t}=n,{targetPath:a,logId:e}=P(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=[],p=[];for(const[u,d,f,b]of s)r&&!r.has(u)||(d!==0?(b!==1||f!==1)&&o.push(u):d===0&&b!==0?c.push(u):d===0&&b===0&&f!==0&&p.push(u));const h=await W(a);for(const u of o){const d=await _(a,h,u);if(!d)continue;const f=A.join(a,u);i.mkdirSync(A.dirname(f),{recursive:!0}),i.writeFileSync(f,d.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 d=A.join(a,u);i.existsSync(d)&&await i.promises.unlink(d)}c.length>0&&await j(a,c);for(const u of p){const d=A.join(a,u);i.existsSync(d)&&await i.promises.unlink(d)}p.length>0&&await j(a,p);const g=o.length+c.length+p.length;return w(e,"INFO","Git discard",{logId:e,trackedFiles:o.length,newFiles:c.length,untrackedFiles:p.length}),{success:!0,message:"Files discarded successfully",logId:e,discardedCount:g,trackedFiles:o,newFiles:c,untrackedFiles:p}}catch(s){throw w(e,"ERROR","Failed to discard",{logId:e,error:s.message}),new k("Failed to discard files",{originalError:s.message})}}async function X(n={}){const{maxCount:t=50,branch:a,skip:e=0,filePath:s}=n,{targetPath:r,logId:o}=P(n);await T(r);try{const c=Math.min(Math.max(1,t),500),p=Math.max(0,e),h={fs:i,dir:r,depth:c+p};a&&(h.ref=a),s&&(h.filepath=s);const d=(await l.log(h)).slice(p,p+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:d,total:d.length}}catch(c){throw w(o,"ERROR","Failed to get Git log",{logId:o,error:c.message}),new k("Failed to get Git log",{originalError:c.message})}}async function Y(n={}){const{source:t="worktree",from:a,to:e,paths:s}=n,{targetPath:r,logId:o}=P(n);await T(r);try{const c=Array.isArray(s)&&s.length>0?new Set(s):null;let p="";const h=[];let g=0,u=0;async function d(f,b,O){const I=!!b,E=!!O;if(I&&E&&b.content===O.content)return;let x=!1;if(I&&L(b.buf)&&(x=!0),E&&!x&&L(O.buf)&&(x=!0),x){const F=I?C(b.buf).substring(0,7):"0000000",N=E?C(O.buf).substring(0,7):"0000000",R=[`diff --git a/${f} b/${f}`];I?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 ${I?`a/${f}`:"/dev/null"} and ${E?`b/${f}`:"/dev/null"} differ`),p+=R.join(`
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(`
7
7
  `)+`
8
- `,h.push({file:f,changes:0,insertions:0,deletions:0,binary:!0});return}const{diff:m,insertions:y,deletions:S}=mt(f,I?b.content:"",E?O.content:"",I,E,I?b.buf:null,E?O.buf:null);p+=m,h.push({file:f,changes:y+S,insertions:y,deletions:S,binary:!1}),g+=y,u+=S}if(t==="commit"){let f,b;if(a&&e)f=a,b=e;else if(a){const x=await l.readCommit({fs:i,dir:r,oid:a});x.commit.parent&&x.commit.parent.length>0?(f=x.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,I=new Set(await l.listFiles({fs:i,dir:r,ref:b})),E=new Set([...O,...I]);for(const x of E){if(c&&!c.has(x))continue;const m=O.has(x)?await _(r,f,x):null,y=I.has(x)?await _(r,b,x):null;await d(x,m,y)}}else{const f=await W(r),b=await l.statusMatrix({fs:i,dir:r});for(const[O,I,E,x]of b){if(c&&!c.has(O))continue;if(t==="staged"){if(x===1||I===0&&x===0)continue}else if(I===0&&x===0||I===1&&E===1&&x===1)continue;const m=I!==0?await _(r,f,O):null;let y=null;if(E!==0){const S=A.join(r,O);if(i.existsSync(S))try{const F=i.readFileSync(S);y={content:F.toString("utf8"),buf:F}}catch{}}await d(O,m,y)}}return{success:!0,logId:o,source:t,diff:p,summary:{files:h,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 k("Failed to get Git diff",{originalError:c.message}))}}async function Z(n={}){const{ref:t="HEAD",filePath:a}=n;if(!a)throw new v("filePath is required",{field:"filePath"});const{targetPath:e,logId:s}=P(n);await T(e);try{let r;if(t==="worktree"||t==="staged"||t===""){const o=A.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 k("Failed to get file content",{originalError:r.message}))}}async function tt(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}=P(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 p=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 h=await l.listFiles({fs:i,dir:e,ref:t}),g=new Set(h);for(const d of h)await l.resetIndex({fs:i,dir:e,filepath:d,ref:t});const u=await l.statusMatrix({fs:i,dir:e});for(const[d,,,f]of u)if(!g.has(d)&&f!==0)try{await l.remove({fs:i,dir:e,filepath:d})}catch{}}if(a==="hard"){const h=await l.listFiles({fs:i,dir:e,ref:t}),g=new Set(h);for(const u of h){const d=await _(e,t,u);if(!d)continue;const f=A.join(e,u);i.mkdirSync(A.dirname(f),{recursive:!0}),i.writeFileSync(f,d.buf)}if(p){for(const u of p)if(!g.has(u)){const d=A.join(e,u);i.existsSync(d)&&i.unlinkSync(d)}}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 k("Failed to reset",{originalError:r.message}))}}async function et(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}=P(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 p=await l.statusMatrix({fs:i,dir:r});if(p.some(([m,y,S,F])=>y===0&&F===0?!1:S!==1||F!==1)){const m=p.filter(([,F])=>F!==0),y=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:y})}const g=new Set(await l.listFiles({fs:i,dir:r,ref:c})),u=await W(r),d=new Set(await l.listFiles({fs:i,dir:r,ref:u})),f=[];for(const m of g){const y=await _(r,c,m);if(!y)continue;const S=A.join(r,m);i.mkdirSync(A.dirname(S),{recursive:!0}),i.writeFileSync(S,y.buf),await l.add({fs:i,dir:r,filepath:m})}for(const m of d)if(!g.has(m)){f.push(m);try{await l.remove({fs:i,dir:r,filepath:m})}catch{}const y=A.join(r,m);i.existsSync(y)&&await i.promises.unlink(y)}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 I={name:e||B.GIT_DEFAULT_AUTHOR_NAME,email:s||B.GIT_DEFAULT_AUTHOR_EMAIL},E=a||`Revert to ${c.substring(0,7)}`,x=await l.commit({fs:i,dir:r,message:E,author:I});return w(o,"INFO","Git revert successful",{logId:o,target:c,commitHash:x,previousHead:u,removedFilesCount:f.length}),{success:!0,message:"Revert successful",logId:o,commit:x,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 k("Failed to revert",{originalError:c.message}))}}async function at(n={}){const{target:t}=n;if(!t)throw new v("Checkout target cannot be empty",{field:"target"});const{targetPath:a,logId:e}=P(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=A.join(a,r);i.mkdirSync(A.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 k("Failed to checkout files",{originalError:s.message})}}async function rt(n={}){const{targetPath:t,logId:a}=P(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 k("Failed to list tags",{originalError:e.message})}}async function st(n={}){const{tagName:t,message:a}=n;if(!t)throw new v("Tag name cannot be empty",{field:"tagName"});const{targetPath:e,logId:s}=P(n);await T(e);try{return a?await l.annotatedTag({fs:i,dir:e,ref:t,message:a,tagger:gt()}):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 k("Failed to create tag",{originalError:r.message})}}async function it(n={}){const{tagName:t}=n;if(!t)throw new v("Tag name cannot be empty",{field:"tagName"});const{targetPath:a,logId:e}=P(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 k("Failed to delete tag",{originalError:s.message})}}async function nt(n={}){const{targetPath:t,logId:a}=P(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 k("Failed to list branches",{originalError:e.message})}}async function ot(n={}){const{branchName:t,startPoint:a}=n;if(!t)throw new v("Branch name cannot be empty",{field:"branchName"});const{targetPath:e,logId:s}=P(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 k("Failed to create branch",{originalError:r.message})}}async function ct(n={}){const{branchName:t}=n;if(!t)throw new v("Branch name cannot be empty",{field:"branchName"});const{targetPath:a,logId:e}=P(n);await T(a);try{const s=await l.statusMatrix({fs:i,dir:a});if(s.some(([o,c,p,h])=>c===0&&h===0?!1:p!==1||h!==1)){const o=s.filter(([,h])=>h!==0),c=o.filter(([,,h])=>h!==1).map(([h])=>h),p=o.filter(([,,,h])=>h!==1).map(([h])=>h);throw new G("Working directory is not clean, please commit or stash your changes before switching branches",{staged:p,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 k("Failed to switch branch",{originalError:s.message}))}}async function lt(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}=P(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 k("Failed to delete branch",{originalError:r.message}))}}export{q as init,z as status,K as commit,V as add,J as unstage,Q as discard,X as logHistory,Y as diff,Z as fileContent,tt as reset,et as revert,at as checkout,rt as listTags,st as createTag,it as deleteTag,nt as listBranches,ot as createBranch,ct as switchBranch,lt as deleteBranch};export default{init:q,status:z,commit:K,add:V,unstage:J,discard:Q,logHistory:X,diff:Y,fileContent:Z,reset:tt,revert:et,checkout:at,listTags:rt,createTag:st,deleteTag:it,listBranches:nt,createBranch:ot,switchBranch:ct,deleteBranch:lt};
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};
@@ -1,5 +1,5 @@
1
1
  import i from"fs";import a from"path";import{exec as ae}from"child_process";import ce from"cross-spawn";import le from"archiver";import L from"../../appConfig/index.js";import{extractZip as G}from"../common/zipUtils.js";import{ValidationError as h,SystemError as A,FileError as q}from"../error/errorHandler.js";import{log as o}from"../log/logUtils.js";import{createPnpmNpmrc as pe}from"../common/npmrcUtils.js";import{ensurePrimaryAgentDirs as te,syncAgents as Y}from"../common/AgentWorkspaceUtils.js";function ie(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean);if(typeof e=="string"){const t=e.trim();if(!t)return[];try{const s=JSON.parse(t);if(Array.isArray(s))return s.map(r=>typeof r=="string"?r.trim():"").filter(Boolean)}catch{}return[t]}return[]}async function se(e,t,s){let r;try{r=await fetch(e)}catch(k){throw new q(`Failed to download skill zip from url: ${e}`,{url:e,reason:k.message})}if(!r.ok)throw new q(`Failed to download skill zip from url: ${e}`,{url:e,status:r.status,statusText:r.statusText});const n=r.headers.get("content-type")||"";n&&!n.includes("zip")&&!n.includes("octet-stream")&&o(s,"WARN","Downloaded skill url content-type is not typical zip",{url:e,contentType:n});const c=await r.arrayBuffer(),w=Buffer.from(c);await i.promises.writeFile(t,w)}async function $(e="computer"){const t=L.COMPUTER_WORKSPACE_DIR;if(!t)throw new h("COMPUTER_WORKSPACE_DIR configuration does not exist",{field:"COMPUTER_WORKSPACE_DIR"});return i.existsSync(t)||(await i.promises.mkdir(t,{recursive:!0}),o(e,"INFO","Created user workspace root directory",{workspaceRoot:t})),t}async function V(e,t){const s=a.join(e,t);if(i.existsSync(s)&&(await i.promises.lstat(s)).isDirectory())return s;const r=await i.promises.readdir(e,{withFileTypes:!0});for(const n of r){if(!n.isDirectory())continue;const c=a.join(e,n.name),w=a.join(c,t);if(i.existsSync(w)&&(await i.promises.lstat(w)).isDirectory())return w}return null}async function be(e){return V(e,"skills")}const de=".dynamic_add.lock";function me(e){const t=a.join(e,de);return i.existsSync(t)&&i.statSync(t).isFile()}async function C(e){i.existsSync(e)&&await i.promises.rm(e,{recursive:!0,force:!0})}async function T(e,t){try{await i.promises.rename(e,t)}catch(s){if(s.code==="EXDEV"){async function r(n,c){if((await i.promises.lstat(n)).isDirectory()){await i.promises.mkdir(c,{recursive:!0});const k=await i.promises.readdir(n);for(const l of k)await r(a.join(n,l),a.join(c,l))}else await i.promises.copyFile(n,c)}await r(e,t),await i.promises.rm(e,{recursive:!0,force:!0})}else throw s}}async function fe(e,t,s,r,n,c){const w=t&&t.trim(),k=s&&s.trim(),l=r&&r.trim(),p=Array.isArray(n)&&n.length>0;if(!w&&!k&&!l&&!p)return;const g=a.join(e,".claude");try{if(i.existsSync(g)||await i.promises.mkdir(g,{recursive:!0}),w)try{const u={mcpServers:JSON.parse(t)},x=a.join(e,".mcp.json");await i.promises.writeFile(x,JSON.stringify(u,null,2),"utf-8"),o(c,"INFO","Written .mcp.json to workspace root")}catch(u){o(c,"WARN","Failed to parse/write mcpServersConfig, skipping",{error:u.message})}const m={};if(k)try{m.hooks=JSON.parse(s)}catch(u){o(c,"WARN","Failed to parse hooksConfig, skipping",{error:u.message})}if(l)try{m.permissions=JSON.parse(r)}catch(u){o(c,"WARN","Failed to parse permissionsConfig, skipping",{error:u.message})}if(Object.keys(m).length>0){const u=a.join(g,"settings.json");await i.promises.writeFile(u,JSON.stringify(m,null,2),"utf-8"),o(c,"INFO","Written .claude/settings.json",{keys:Object.keys(m)})}if(p){const u=a.join(g,"hooks");i.existsSync(u)||await i.promises.mkdir(u,{recursive:!0});for(const x of n){if(!x||!x.path||!x.content)continue;const f=a.normalize(x.path);if(f.startsWith("..")||a.isAbsolute(f)){o(c,"WARN","Hook script path contains traversal, skipping",{path:x.path});continue}const S=a.join(g,f),R=a.dirname(S);i.existsSync(R)||await i.promises.mkdir(R,{recursive:!0}),await i.promises.writeFile(S,x.content,"utf-8"),await i.promises.chmod(S,493),o(c,"INFO","Written hook script",{path:x.path})}}}catch(m){o(c,"WARN","Failed to write .claude/settings or .mcp.json or hook scripts, not blocking workspace creation",{error:m.message})}}async function ue(e,t,s,r,n,c,w,k){const l=Date.now(),p=`computer:${e}:${t}`,g=ie(r),m=[],u=[],x=new Set;if(!e)throw new h("userId cannot be empty",{field:"userId"});if(!t)throw new h("cId cannot be empty",{field:"cId"});const f=await $(p),S=a.join(f,String(e),String(t),".tmp"),R=a.join(f,String(e),String(t)),{skillsDir:y,agentsDir:D,agentTypes:O}=await te(R);i.existsSync(R)||await i.promises.mkdir(R,{recursive:!0});const j=a.join(S,`preserved_skills_${Date.now()}_${Math.round(Math.random()*1e6)}`);if(i.existsSync(y)){const P=(await i.promises.readdir(y,{withFileTypes:!0})).filter(z=>z.isDirectory()&&me(a.join(y,z.name)));if(P.length>0){await i.promises.mkdir(j,{recursive:!0});for(const z of P){const N=a.join(y,z.name),E=a.join(j,z.name);await T(N,E)}o(p,"INFO","\u4FDD\u7559\u542B .dynamic_add.lock \u7684 skill",{preserved:P.map(z=>z.name)})}}if(await C(y),await C(D),await i.promises.mkdir(y,{recursive:!0}),await i.promises.mkdir(D,{recursive:!0}),i.existsSync(j)){const d=await i.promises.readdir(j,{withFileTypes:!0});for(const P of d)if(P.isDirectory()){const z=a.join(j,P.name),N=a.join(y,P.name);await T(z,N)}await C(j)}const v=i.existsSync(y),W=i.existsSync(D);o(p,"INFO","Deleted old skills and agents directories completed",{userId:e,cId:t,targetSkillsDir:y,targetAgentsDir:D,agentTypes:O,skillsExists:v,agentsExists:W});const b=a.join(R,".mcp.json");i.existsSync(b)&&await i.promises.unlink(b);const B=a.join(R,".claude","settings.json");if(i.existsSync(B)&&await i.promises.unlink(B),await fe(R,n,w,c,k,p),!s&&g.length===0)return await Y(R),o(p,"INFO","Created workspace (no uploaded file, no skills and agents)",{userId:e,cId:t,workspaceRoot:f,skillsDir:null,agentsDir:null,agentTypes:O,elapsedMs:Date.now()-l}),{message:"Workspace created (no uploaded file, no skills and agents)",workspaceRoot:f};if(s){if(!s.path)throw new h("Uploaded file has no valid path",{field:"file.path"});if(a.extname(s.originalname||s.filename||"").toLowerCase()!==".zip")throw new h("Only zip files are supported",{field:"file",originalName:s.originalname})}o(p,"DEBUG","Start processing workspace resources",{userId:e,cId:t,workspaceRoot:f,hasUploadedZip:!!s,skillUrlsCount:g.length});try{i.existsSync(S)||await i.promises.mkdir(S,{recursive:!0});const d=[];if(s){const N=a.join(S,`skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);u.push(N),await i.promises.mkdir(N,{recursive:!0}),o(p,"DEBUG","Start extracting uploaded zip file",{extractRoot:N}),await G(s.path,N),o(p,"DEBUG","Uploaded zip file extracted successfully",{extractRoot:N});const E=await V(N,"skills"),M=await V(N,"agents");if(E){await i.promises.mkdir(y,{recursive:!0});const _=await i.promises.readdir(E,{withFileTypes:!0});for(const Z of _){if(!Z.isDirectory())continue;const J=a.join(E,Z.name),K=a.join(y,Z.name);i.existsSync(K)&&await C(K),await T(J,K),x.add(Z.name)}d.push("skills"),o(p,"INFO","skills updated to workspace",{userId:e,cId:t,workspaceRoot:f,targetSkillsDir:y,agentTypes:O})}else o(p,"INFO","skills directory not found in uploaded zip, skipping",{userId:e,cId:t,extractRoot:N});M?(await C(D),await T(M,D),d.push("agents"),o(p,"INFO","agents updated to workspace",{userId:e,cId:t,workspaceRoot:f,targetAgentsDir:D,agentTypes:O})):o(p,"INFO","agents directory not found in uploaded zip, skipping",{userId:e,cId:t,extractRoot:N})}for(let N=0;N<g.length;N+=1){const E=g[N],M=a.join(S,`skill_url_${Date.now()}_${N}_${Math.round(Math.random()*1e6)}.zip`);m.push(M);const _=a.join(S,`skill_url_extract_${Date.now()}_${N}_${Math.round(Math.random()*1e6)}`);u.push(_),await i.promises.mkdir(_,{recursive:!0}),o(p,"INFO","Start download skill zip from url",{userId:e,cId:t,skillUrl:E}),await se(E,M,p),o(p,"INFO","Skill zip downloaded, start extracting",{userId:e,cId:t,skillUrl:E,downloadedZipPath:M}),await G(M,_);const J=(await i.promises.readdir(_,{withFileTypes:!0})).filter(F=>F.isDirectory()&&!F.name.startsWith(".")),ee=J.find(F=>F.name==="skills")?(await i.promises.readdir(a.join(_,"skills"),{withFileTypes:!0})).filter(F=>F.isDirectory()&&!F.name.startsWith(".")).map(F=>({name:F.name,sourcePath:a.join(_,"skills",F.name)})):J.map(F=>({name:F.name,sourcePath:a.join(_,F.name)}));if(ee.length===0){o(p,"WARN","No skill directory found after extracting skill url zip",{userId:e,cId:t,skillUrl:E,extractRoot:_});continue}await i.promises.mkdir(y,{recursive:!0});for(const F of ee){const H=a.join(y,F.name);i.existsSync(H)&&await C(H),await T(F.sourcePath,H),x.add(F.name),o(p,"INFO","Skill from url updated to workspace",{userId:e,cId:t,skillUrl:E,skillName:F.name,destSkillPath:H})}d.includes("skills")||d.push("skills")}d.length===0&&o(p,"WARN","No valid skills or agents directories found",{userId:e,cId:t,hasUploadedZip:!!s,skillUrlsCount:g.length});const P=Array.from(x),z=d.length>0?`Workspace created successfully, ${d.join(" and ")} updated`:"Workspace created successfully (skills and agents directories not found)";return o(p,"INFO",z,{userId:e,cId:t,updatedDirs:d,updatedSkills:P,agentTypes:O,elapsedMs:Date.now()-l}),await Y(R),{message:z,workspaceRoot:f,updatedSkills:P}}catch(d){throw o(p,"ERROR","Failed to process workspace resources",{userId:e,cId:t,error:d.message,elapsedMs:Date.now()-l}),d instanceof h||d instanceof q||d instanceof A?d:new A(`Failed to create workspace: ${d.message}`,{userId:e,cId:t})}finally{try{for(const d of u)i.existsSync(d)&&await i.promises.rm(d,{recursive:!0,force:!0})}catch(d){o(p,"WARN","Failed to clean up temporary extracted zip",{error:d.message})}for(const d of m)try{i.existsSync(d)&&await i.promises.unlink(d)}catch(P){o(p,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:d,error:P.message})}try{s&&s.path&&i.existsSync(s.path)&&await i.promises.unlink(s.path)}catch(d){o(p,"WARN","Failed to clean up uploaded zip file",{tempZipPath:s?.path,error:d.message})}}}async function we(e,t,s,r){const n=Date.now(),c=`computer:${e}:${t}`,w=ie(r),k=[],l=[];if(!e)throw new h("userId cannot be empty",{field:"userId"});if(!t)throw new h("cId cannot be empty",{field:"cId"});if(!s&&w.length===0)throw new h("file or skillUrls cannot both be empty",{field:"file|skillUrls"});if(s){if(!s.path)throw new h("Uploaded file has no valid path",{field:"file.path"});if(a.extname(s.originalname||s.filename||"").toLowerCase()!==".zip")throw new h("Only zip files are supported",{field:"file",originalName:s?.originalname})}const p=await $(c),g=a.join(p,String(e),String(t),".tmp"),m=a.join(p,String(e),String(t)),{skillsDir:u,agentTypes:x}=await te(m);try{i.existsSync(m)||await i.promises.mkdir(m,{recursive:!0}),i.existsSync(u)||await i.promises.mkdir(u,{recursive:!0}),i.existsSync(g)||await i.promises.mkdir(g,{recursive:!0});const f=[],S=new Set;if(s){const y=a.join(g,`skill_push_${Date.now()}_${Math.round(Math.random()*1e6)}`);l.push(y),await i.promises.mkdir(y,{recursive:!0}),o(c,"DEBUG","Start extracting skill zip file",{extractRoot:y}),await G(s.path,y),o(c,"DEBUG","Skill zip file extracted successfully",{extractRoot:y});const D=await V(y,"skills");if(!D)o(c,"WARN","skills directory not found in uploaded zip",{userId:e,cId:t,extractRoot:y});else{const j=(await i.promises.readdir(D,{withFileTypes:!0})).filter(v=>v.isDirectory()&&!v.name.startsWith("."));if(j.length===0)o(c,"WARN","skills directory in uploaded zip has no skill subdirectories",{userId:e,cId:t,skillsDir:D});else for(const v of j){const W=a.join(D,v.name),b=a.join(u,v.name);i.existsSync(b)&&await C(b),await T(W,b),S.add(v.name),o(c,"INFO","skill pushed to workspace from uploaded zip",{userId:e,cId:t,skillName:v.name,destSkillPath:b})}}}for(let y=0;y<w.length;y+=1){const D=w[y],O=a.join(g,`skill_push_url_${Date.now()}_${y}_${Math.round(Math.random()*1e6)}.zip`);k.push(O);const j=a.join(g,`skill_push_url_extract_${Date.now()}_${y}_${Math.round(Math.random()*1e6)}`);l.push(j),await i.promises.mkdir(j,{recursive:!0}),o(c,"INFO","Start download skill zip for push from url",{userId:e,cId:t,skillUrl:D}),await se(D,O,c),await G(O,j);const W=(await i.promises.readdir(j,{withFileTypes:!0})).filter(d=>d.isDirectory()&&!d.name.startsWith(".")),B=W.find(d=>d.name==="skills")?(await i.promises.readdir(a.join(j,"skills"),{withFileTypes:!0})).filter(d=>d.isDirectory()&&!d.name.startsWith(".")).map(d=>({name:d.name,sourcePath:a.join(j,"skills",d.name)})):W.map(d=>({name:d.name,sourcePath:a.join(j,d.name)}));if(B.length===0){o(c,"WARN","No skill directory found after extracting push skill url zip",{userId:e,cId:t,skillUrl:D,extractRoot:j});continue}for(const d of B){const P=a.join(u,d.name);i.existsSync(P)&&await C(P),await T(d.sourcePath,P),S.add(d.name),o(c,"INFO","skill pushed to workspace from url zip",{userId:e,cId:t,skillUrl:D,skillName:d.name,destSkillPath:P})}}for(const y of S)f.push(y);const R=f.length>0?`Pushed ${f.length} skills: ${f.join(", ")}`:"No valid skill directories found in file or skillUrls";return o(c,"INFO",R,{userId:e,cId:t,updatedSkills:f,agentTypes:x,elapsedMs:Date.now()-n}),await Y(m),{message:R,workspaceRoot:p,updatedSkills:f}}catch(f){throw o(c,"ERROR","Failed to push skill to workspace",{userId:e,cId:t,error:f.message,elapsedMs:Date.now()-n}),f instanceof h||f instanceof q||f instanceof A?f:new A(`Failed to push skill to workspace: ${f.message}`,{userId:e,cId:t})}finally{try{for(const f of l)i.existsSync(f)&&await i.promises.rm(f,{recursive:!0,force:!0})}catch(f){o(c,"WARN","Failed to clean up temporary extracted zip",{error:f.message})}for(const f of k)try{i.existsSync(f)&&await i.promises.unlink(f)}catch(S){o(c,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:f,error:S.message})}try{s&&s.path&&i.existsSync(s.path)&&await i.promises.unlink(s.path)}catch(f){o(c,"WARN","Failed to clean up uploaded zip file",{tempZipPath:s?.path,error:f.message})}}}async function he(e,t,s,r){const n=Date.now(),c=`computer:${e}:${t}`;if(!e)throw new h("userId cannot be empty",{field:"userId"});if(!t)throw new h("cId cannot be empty",{field:"cId"});if(!s||!s.path)throw new h("file is required",{field:"file"});if(a.extname(s.originalname||s.filename||"").toLowerCase()!==".zip")throw new h("Only zip files are supported",{field:"file",originalName:s.originalname});const k=await $(c),l=a.join(k,String(e),String(t)),p=a.join(l,".tmp"),g=a.join(p,`template_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);try{i.existsSync(l)||await i.promises.mkdir(l,{recursive:!0}),i.existsSync(p)||await i.promises.mkdir(p,{recursive:!0}),await i.promises.mkdir(g,{recursive:!0}),o(c,"DEBUG","Start extracting template zip file",{extractRoot:g}),await G(s.path,g),o(c,"DEBUG","Template zip file extracted successfully",{extractRoot:g});const m=await i.promises.readdir(g,{withFileTypes:!0});for(const u of m){const x=a.join(g,u.name),f=a.join(l,u.name);if(u.isDirectory())await T(x,f);else{const S=a.dirname(f);i.existsSync(S)||await i.promises.mkdir(S,{recursive:!0}),await i.promises.copyFile(x,f)}}if(o(c,"INFO","Template files extracted to workspace",{userId:e,cId:t,targetDir:l,fileCount:m.length}),L.GIT_ENABLED&&(r==="true"||r===!0)){const u=await import("../../service/gitService.js");await u.default.init({workspaceType:"taskAgent",userId:e,cId:t}),await u.default.commit({workspaceType:"taskAgent",userId:e,cId:t,message:"Initial commit"}),o(c,"INFO","Git init and initial commit done",{userId:e,cId:t})}return o(c,"INFO","Init project template completed",{userId:e,cId:t,targetDir:l,elapsedMs:Date.now()-n}),{message:"Project template initialized successfully",workspaceRoot:l}}catch(m){throw o(c,"ERROR","Failed to init project template",{userId:e,cId:t,error:m.message,elapsedMs:Date.now()-n}),m instanceof h||m instanceof q||m instanceof A?m:new A(`Failed to init project template: ${m.message}`,{userId:e,cId:t})}finally{try{i.existsSync(g)&&await i.promises.rm(g,{recursive:!0,force:!0})}catch(m){o(c,"WARN","Failed to clean up temporary extracted zip",{error:m.message})}try{s&&s.path&&i.existsSync(s.path)&&await i.promises.unlink(s.path)}catch(m){o(c,"WARN","Failed to clean up uploaded zip file",{tempZipPath:s?.path,error:m.message})}}}async function ge(e,t,s){if(!e)throw new h("userId cannot be empty",{field:"userId"});if(!t)throw new h("cId cannot be empty",{field:"cId"});if(!s||typeof s!="string"||!s.trim())throw new h("command cannot be empty",{field:"command"});const r=await $("computer"),n=a.join(r,String(e),String(t));if(!i.existsSync(n))throw new h("workspace directory does not exist",{field:"workDir",workDir:n});const c=`computer:${e}:${t}`;o(c,"INFO","Execute command in workspace",{userId:e,cId:t,workDir:n,command:s});const w=10*60*1e3,k={cwd:n,timeout:w,maxBuffer:50*1024*1024};return L.BASH_PATH&&(k.shell=L.BASH_PATH),new Promise((l,p)=>{ae(s,k,(g,m,u)=>{const x=g?g.killed?-1:g.code||1:0,f=g&&g.killed?(u||"")+`
2
- Command timed out after ${w/1e3}s`:u||"";o(c,"INFO","Execute command completed",{userId:e,cId:t,exitCode:x,killed:g?g.killed:!1,stdoutLength:m?m.length:0,stderrLength:f.length}),l({stdout:m||"",stderr:f,exitCode:x})})})}async function ke(e,t,s){const r=`computer:${e}:${t}`;if(!e)throw new h("userId cannot be empty",{field:"userId"});if(!t)throw new h("cId cannot be empty",{field:"cId"});const n=await $(r),c=a.join(n,String(e),String(t));if(!i.existsSync(c))throw new h("workspace directory does not exist",{field:"workDir",workDir:c});const w=L.ZIP_WORKSPACE_EXCLUDE_DIRS||[],k=Array.isArray(s)?s:[],l=new Set([...w,...k]),p=`${e}_${t}.zip`,g=Date.now();o(r,"INFO","Zip workspace request",{userId:e,cId:t,targetDir:c,excludeDirs:[...l]});const m=le("zip",{zlib:{level:9}});return m.directory(c,!1,u=>{const x=u.name||"";if(x.split(/[\/\\]/).filter(Boolean).some(S=>l.has(S)))return!1;try{const S=a.join(c,x);if(i.lstatSync(S).isSymbolicLink())return!1}catch{return!1}return u}),m.on("warning",u=>{u.code==="ENOENT"?o(r,"WARN","Encountered file problem when creating zip",{message:u.message,code:u.code}):o(r,"ERROR","Encountered warning when creating zip",{message:u.message,code:u.code})}),m.on("error",u=>{o(r,"ERROR","Failed to create zip",{message:u.message,elapsedMs:Date.now()-g})}),m.on("end",()=>{o(r,"INFO","Workspace zip created successfully",{targetDir:c,zipFileName:p,elapsedMs:Date.now()-g})}),{archive:m,zipFileName:p}}const Q=new Set([...L.ZIP_WORKSPACE_EXCLUDE_DIRS||[],"dist-packages"]);function X(e){let t;try{t=i.readdirSync(e,{withFileTypes:!0})}catch{return null}const s=a.join(e,"scripts","package-platforms.mjs");if(i.existsSync(s))return e;for(const r of t)if(r.isDirectory()&&!Q.has(r.name)){const n=X(a.join(e,r.name));if(n)return n}return null}function U(e,t,s,r=10*60*1e3){return new Promise(n=>{const c=ce(e,t,{...s,timeout:r});let w="",k="";c.stdout?.on("data",l=>{w+=l.toString()}),c.stderr?.on("data",l=>{k+=l.toString()}),c.on("error",l=>{n({stdout:w,stderr:k+`
2
+ Command timed out after ${w/1e3}s`:u||"";o(c,"INFO","Execute command completed",{userId:e,cId:t,exitCode:x,killed:g?g.killed:!1,stdoutLength:m?m.length:0,stderrLength:f.length}),l({stdout:m||"",stderr:f,exitCode:x})})})}async function ke(e,t,s){const r=`computer:${e}:${t}`;if(!e)throw new h("userId cannot be empty",{field:"userId"});if(!t)throw new h("cId cannot be empty",{field:"cId"});const n=await $(r),c=a.join(n,String(e),String(t));if(!i.existsSync(c))throw new h("workspace directory does not exist",{field:"workDir",workDir:c});const w=L.ZIP_WORKSPACE_EXCLUDE||[],k=Array.isArray(s)?s:[],l=new Set([...w,...k]),p=`${e}_${t}.zip`,g=Date.now();o(r,"INFO","Zip workspace request",{userId:e,cId:t,targetDir:c,excludeDirs:[...l]});const m=le("zip",{zlib:{level:9}});return m.directory(c,!1,u=>{const x=u.name||"";if(x.split(/[\/\\]/).filter(Boolean).some(S=>l.has(S)))return!1;try{const S=a.join(c,x);if(i.lstatSync(S).isSymbolicLink())return!1}catch{return!1}return u}),m.on("warning",u=>{u.code==="ENOENT"?o(r,"WARN","Encountered file problem when creating zip",{message:u.message,code:u.code}):o(r,"ERROR","Encountered warning when creating zip",{message:u.message,code:u.code})}),m.on("error",u=>{o(r,"ERROR","Failed to create zip",{message:u.message,elapsedMs:Date.now()-g})}),m.on("end",()=>{o(r,"INFO","Workspace zip created successfully",{targetDir:c,zipFileName:p,elapsedMs:Date.now()-g})}),{archive:m,zipFileName:p}}const Q=new Set([...L.ZIP_WORKSPACE_EXCLUDE||[],"dist-packages"]);function X(e){let t;try{t=i.readdirSync(e,{withFileTypes:!0})}catch{return null}const s=a.join(e,"scripts","package-platforms.mjs");if(i.existsSync(s))return e;for(const r of t)if(r.isDirectory()&&!Q.has(r.name)){const n=X(a.join(e,r.name));if(n)return n}return null}function U(e,t,s,r=10*60*1e3){return new Promise(n=>{const c=ce(e,t,{...s,timeout:r});let w="",k="";c.stdout?.on("data",l=>{w+=l.toString()}),c.stderr?.on("data",l=>{k+=l.toString()}),c.on("error",l=>{n({stdout:w,stderr:k+`
3
3
  Failed to spawn ${e}: ${l.message}`,exitCode:1})}),c.on("close",(l,p)=>{n(l===null&&p?{stdout:w,stderr:k+`
4
4
  Process killed by signal ${p} (timeout after ${r/1e3}s)`,exitCode:-1}:{stdout:w,stderr:k,exitCode:l??1})})})}function ye(e){if(!e)return null;let t=e;t.endsWith(".tar.gz")?t=t.slice(0,-7):t.endsWith(".tar.bz2")?t=t.slice(0,-8):(t.endsWith(".tgz")||t.endsWith(".zip"))&&(t=t.slice(0,-4));const s=t.split("-");if(s.length<4)return null;let r=-1;for(let n=s.length-1;n>=2;n--)if(/^\d+\.\d+\.\d+$/.test(s[n])){r=n;break}return r<3?null:s.slice(2,r).join("-")}async function xe(e,t,s,r){const n=`computer:${e}:${t}`;if(!e)throw new h("userId cannot be empty",{field:"userId"});if(!t)throw new h("cId cannot be empty",{field:"cId"});if(!s)throw new h("agentId cannot be empty",{field:"agentId"});if(!r)throw new h("version cannot be empty",{field:"version"});const c=await $(n),w=a.join(c,String(e),String(t));if(!i.existsSync(w))throw new h("workspace directory does not exist",{field:"workDir",workDir:w});o(n,"INFO","Build agent package request",{userId:e,cId:t,agentId:s,version:r});const k=X(w);if(!k)throw new h("package-platforms.mjs not found in workspace",{field:"script"});o(n,"INFO","Found package script",{projectDir:k});const l=await re(k,n);if(o(n,"INFO","pnpm install completed",{exitCode:l.exitCode,stderrLength:l.stderr.length}),l.exitCode!==0)throw o(n,"ERROR","pnpm install failed",{stderr:l.stderr}),new A(`pnpm install failed: ${l.stderr}`);const p=a.join(k,"dist-packages"),g=["scripts/package-platforms.mjs",`agent-${s}`,r,p,"--print-artifacts"],m=await U("node",g,{cwd:k,env:I()});if(o(n,"INFO","Build completed",{exitCode:m.exitCode,stdoutLength:m.stdout.length}),m.exitCode!==0)throw o(n,"ERROR","Build failed",{stderr:m.stderr}),new A(`Build failed: ${m.stderr}`);const u=[".tar.gz",".tar.bz2",".zip",".tgz"],x=[],f=m.stdout.split(`
5
5
  `);for(const S of f){const R=S.trim();if(!R)continue;const y=R.toLowerCase();if(!u.some(W=>y.endsWith(W)))continue;const D=a.resolve(k,R);let O=a.relative(w,D);O=O.split(a.sep).join("/");const j=a.basename(R),v=ye(j);x.push({path:O,fileName:j,platform:v||""})}return o(n,"INFO","Build agent package completed",{artifactsCount:x.length,artifacts:x}),{artifacts:x}}async function Se(e,t){const s=`computer:${e}:${t}`;if(!e)throw new h("userId cannot be empty",{field:"userId"});if(!t)throw new h("cId cannot be empty",{field:"cId"});const r=await $(s),n=a.join(r,String(e),String(t));if(!i.existsSync(n))return o(s,"WARN","Workspace not found, skip cleanup",{userId:e,cId:t}),{cleaned:!1};const c=X(n);if(!c)return o(s,"WARN","package-platforms.mjs not found, skip cleanup",{userId:e,cId:t}),{cleaned:!1};const w=a.join(c,"dist-packages");return i.existsSync(w)?(i.rmSync(w,{recursive:!0,force:!0}),o(s,"INFO","Cleaned dist-packages",{distPackagesDir:w}),{cleaned:!0}):(o(s,"INFO","dist-packages not found, nothing to clean",{distPackagesDir:w}),{cleaned:!1})}async function je(e,t){const s=`computer:${e}:${t}`;if(!e)throw new h("userId cannot be empty",{field:"userId"});if(!t)throw new h("cId cannot be empty",{field:"cId"});const r=await $(s),n=a.join(r,String(e),String(t));return i.existsSync(n)?(await i.promises.rm(n,{recursive:!0,force:!0}),o(s,"INFO","Workspace deleted",{userId:e,cId:t,targetDir:n})):o(s,"WARN","Workspace not found, skip delete",{userId:e,cId:t,targetDir:n}),{deleted:!0}}function ne(e){const t=a.join(e,"package.json");if(i.existsSync(t))return e;let s;try{s=i.readdirSync(e,{withFileTypes:!0})}catch{return null}for(const r of s)if(r.isDirectory()&&!Q.has(r.name)&&r.name!=="node_modules"){const n=ne(a.join(e,r.name));if(n)return n}return null}async function Re(e,t){await pe(e,t);const s=a.join(e,".npmrc");let r="";i.existsSync(s)&&(r=await i.promises.readFile(s,"utf8"));const n=[];if(/dangerously-allow-all-builds\s*=/.test(r)||n.push("dangerously-allow-all-builds=true"),/production\s*=/.test(r)||n.push("production=false"),n.length>0){const c=r&&!r.endsWith(`
@@ -1,6 +1,6 @@
1
- import l from"path";import n from"fs";import e from"isomorphic-git";import r from"../../appConfig/index.js";function u(i){return n.existsSync(l.join(i,".git"))}function d(){return{name:r.GIT_DEFAULT_AUTHOR_NAME,email:r.GIT_DEFAULT_AUTHOR_EMAIL}}async function c(i){const t=await e.statusMatrix({fs:n,dir:i});await Promise.all(t.map(([a,s,f])=>{if(f===2)return e.add({fs:n,dir:i,filepath:a}).catch(()=>{});if(s===1&&f===0)return e.remove({fs:n,dir:i,filepath:a}).catch(()=>{})}))}async function A(i){if(u(i))m(i);else{await e.init({fs:n,dir:i,defaultBranch:"main"}),await e.setConfig({fs:n,dir:i,path:"user.name",value:r.GIT_DEFAULT_AUTHOR_NAME}),await e.setConfig({fs:n,dir:i,path:"user.email",value:r.GIT_DEFAULT_AUTHOR_EMAIL}),m(i);const t=l.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(l.join(i,".gitkeep"),""),await e.add({fs:n,dir:i,filepath:".gitkeep"})),await e.commit({fs:n,dir:i,message:"Initial commit",author:d()})}}async function T(i,t){if(u(i))try{Array.isArray(t)&&t.length>0?await Promise.all(t.filter(a=>n.existsSync(l.join(i,a))).map(a=>e.add({fs:n,dir:i,filepath:a}))):await c(i)}catch{}}function m(i){if(!r.GIT_AUTO_GITIGNORE)return;const t=l.join(i,".gitignore"),a=r.GIT_GITIGNORE_ENTRIES||[];let s=[];n.existsSync(t)&&(s=n.readFileSync(t,"utf8").split(/\r?\n/));const f=new Set(s.map(o=>o.trim()).filter(Boolean)),g=a.filter(o=>!f.has(o));if(g.length>0){const o=s.length>0&&s[s.length-1]!==""?`
2
- `+g.join(`
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(`
3
3
  `)+`
4
- `:g.join(`
4
+ `:u.join(`
5
5
  `)+`
6
- `;n.appendFileSync(t,o,"utf8")}}export{u as isGitRepo,A as ensureGitRepo,m as ensureGitignore,T as autoGitAdd,c as addAll,d as getDefaultAuthor};
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};
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.0-beta.24",
4
+ "version": "1.3.0-beta.26",
5
5
  "description": "Cross-platform file service deployment tool with start/stop/restart CLI commands",
6
6
  "type": "module",
7
7
  "main": "index.js",