nuwax-file-server 1.3.0-beta.11 → 1.3.0-beta.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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.11",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.13",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();
@@ -1 +1 @@
1
- import w from"express";import u from"multer";import{asyncHandler as m,ValidationError as s}from"../utils/error/errorHandler.js";import p from"../service/codeService.js";import{log as c}from"../utils/log/logUtils.js";import b from"../appConfig/index.js";import{extractIsolationContext as h}from"../utils/common/projectPathUtils.js";const y=w.Router(),I=u({storage:u.memoryStorage(),limits:{fileSize:b.UPLOAD_SINGLE_FILE_SIZE_BYTES}}),S=[{path:"/specified-files-update",method:"post",handler:m(async(e,a)=>{const{projectId:o,codeVersion:n,files:t}=e.body||{},l=h(e.body||{});c(o,"INFO","Partial files update",{projectId:o,codeVersion:n,filesCount:t?t.length:0}),t&&Array.isArray(t)&&t.forEach(r=>{if(r&&typeof r.contents=="string"&&r.contents)try{r.contents=decodeURIComponent(r.contents)}catch(f){c(o,"WARN","Decode file content failed",{fileName:r.path,error:f.message})}});const i=await p.specifiedFilesUpdate(String(o),String(n),t,e,l);a.status(200).json(i)})},{path:"/all-files-update",method:"post",handler:m(async(e,a)=>{const{projectId:o,codeVersion:n,files:t,basePath:l,pid:i}=e.body||{},r=h(e.body||{});if(c(o,"INFO","Submit files",{projectId:o,codeVersion:n,basePath:l,pid:i}),!o)throw new s("Project ID cannot be empty",{field:"projectId"});if(n==null)throw new s("codeVersion cannot be empty",{field:"codeVersion"});if(!Array.isArray(t))throw new s("files must be an array",{field:"files"});t&&Array.isArray(t)&&t.forEach(d=>{if(d&&typeof d.contents=="string"&&d.contents)try{d.contents=decodeURIComponent(d.contents)}catch(g){c(o,"WARN","Decode file content failed",{fileName:d.name,error:g.message})}});const f=await p.allFilesUpdate(String(o),String(n),t,e,r);a.status(200).json(f)})},{path:"/upload-single-file",method:"post",middleware:I.single("file"),handler:m(async(e,a)=>{const{projectId:o,codeVersion:n,filePath:t}=e.body||{},l=h(e.body||{}),i=e.file;if(c(o,"INFO","\u4E0A\u4F20\u5355\u4E2A\u6587\u4EF6",{projectId:o,codeVersion:n,filePath:t}),!o)throw new s("Project ID cannot be empty",{field:"projectId"});if(n==null)throw new s("codeVersion cannot be empty",{field:"codeVersion"});if(!i)throw new s("File cannot be empty",{field:"file"});if(!t||typeof t!="string")throw new s("File path cannot be empty",{field:"filePath"});c(o,"INFO","Received file information",{originalname:i.originalname,mimetype:i.mimetype,size:i.size,bufferLength:i.buffer?i.buffer.length:0,bufferIsBuffer:Buffer.isBuffer(i.buffer)});const r={buffer:i.buffer,originalname:i.originalname,mimetype:i.mimetype,size:i.size},f=await p.uploadSingleFile(String(o),String(n),r,t,e,l);a.status(200).json(f)})},{path:"/rollback-version",method:"post",handler:m(async(e,a)=>{const{projectId:o,codeVersion:n,rollbackTo:t}=e.body||{},l=h(e.body||{});if(c(o,"INFO","Rollback version",{projectId:o,codeVersion:n,rollbackTo:t}),!o)throw new s("Project ID cannot be empty",{field:"projectId"});if(n==null)throw new s("codeVersion cannot be empty",{field:"codeVersion"});if(t==null)throw new s("rollbackTo cannot be empty",{field:"rollbackTo"});if(b.GIT_ENABLED)return a.status(200).json({success:!1,deprecated:!0,message:"\u6B64\u63A5\u53E3\u5DF2\u5E9F\u5F03\uFF0C\u8BF7\u4F7F\u7528 /api/git/rollback \u8FDB\u884C\u7248\u672C\u56DE\u6EDA"});const i=await p.rollbackVersion(String(o),String(n),String(t),e,l);a.status(200).json(i)})}];S.forEach(e=>{e.middleware?y[e.method](e.path,e.middleware,e.handler):y[e.method](e.path,e.handler)});export default y;
1
+ import I from"express";import b from"multer";import{asyncHandler as p,ValidationError as r}from"../utils/error/errorHandler.js";import h from"../service/codeService.js";import{log as f}from"../utils/log/logUtils.js";import g from"../appConfig/index.js";import{extractIsolationContext as u}from"../utils/common/projectPathUtils.js";const y=I.Router(),w=b({storage:b.memoryStorage(),limits:{fileSize:g.UPLOAD_SINGLE_FILE_SIZE_BYTES}}),j=[{path:"/specified-files-update",method:"post",handler:p(async(e,a)=>{const{projectId:t,codeVersion:i,files:n}=e.body||{},l=u(e.body||{});f(t,"INFO","Partial files update",{projectId:t,codeVersion:i,filesCount:n?n.length:0}),n&&Array.isArray(n)&&n.forEach(s=>{if(s&&typeof s.contents=="string"&&s.contents)try{s.contents=decodeURIComponent(s.contents)}catch(d){f(t,"WARN","Decode file content failed",{fileName:s.path,error:d.message})}});const o=await h.specifiedFilesUpdate(String(t),String(i),n,e,l);a.status(200).json(o)})},{path:"/all-files-update",method:"post",handler:p(async(e,a)=>{const{projectId:t,codeVersion:i,files:n,basePath:l,pid:o}=e.body||{},s=u(e.body||{});if(f(t,"INFO","Submit files",{projectId:t,codeVersion:i,basePath:l,pid:o}),!t)throw new r("Project ID cannot be empty",{field:"projectId"});if(i==null)throw new r("codeVersion cannot be empty",{field:"codeVersion"});if(!Array.isArray(n))throw new r("files must be an array",{field:"files"});n&&Array.isArray(n)&&n.forEach(c=>{if(c&&typeof c.contents=="string"&&c.contents)try{c.contents=decodeURIComponent(c.contents)}catch(m){f(t,"WARN","Decode file content failed",{fileName:c.name,error:m.message})}});const d=await h.allFilesUpdate(String(t),String(i),n,e,s);a.status(200).json(d)})},{path:"/upload-single-file",method:"post",middleware:w.single("file"),handler:p(async(e,a)=>{const{projectId:t,codeVersion:i,filePath:n}=e.body||{},l=u(e.body||{}),o=e.file;if(f(t,"INFO","\u4E0A\u4F20\u5355\u4E2A\u6587\u4EF6",{projectId:t,codeVersion:i,filePath:n}),!t)throw new r("Project ID cannot be empty",{field:"projectId"});if(i==null)throw new r("codeVersion cannot be empty",{field:"codeVersion"});if(!o)throw new r("File cannot be empty",{field:"file"});if(!n||typeof n!="string")throw new r("File path cannot be empty",{field:"filePath"});f(t,"INFO","Received file information",{originalname:o.originalname,mimetype:o.mimetype,size:o.size,bufferLength:o.buffer?o.buffer.length:0,bufferIsBuffer:Buffer.isBuffer(o.buffer)});const s={buffer:o.buffer,originalname:o.originalname,mimetype:o.mimetype,size:o.size},d=await h.uploadSingleFile(String(t),String(i),s,n,e,l);a.status(200).json(d)})},{path:"/upload-batch-files",method:"post",middleware:w.array("files"),handler:p(async(e,a)=>{const{projectId:t,codeVersion:i,filePaths:n}=e.body||{},l=u(e.body||{}),o=e.files;if(f(t,"INFO","\u6279\u91CF\u4E0A\u4F20\u6587\u4EF6",{projectId:t,codeVersion:i,fileCount:o?o.length:0}),!t)throw new r("Project ID cannot be empty",{field:"projectId"});if(i==null)throw new r("codeVersion cannot be empty",{field:"codeVersion"});if(!o||o.length===0)throw new r("Files cannot be empty",{field:"files"});let s=n;if(typeof s=="string"&&(s=[s]),!s||s.length!==o.length)throw new r("filePaths and files count mismatch",{field:"filePaths",filePathsCount:s?s.length:0,filesCount:o.length});const d=o.map(m=>({buffer:m.buffer,originalname:m.originalname,mimetype:m.mimetype,size:m.size})),c=await h.uploadBatchFiles(String(t),String(i),d,s,e,l);a.status(200).json(c)})},{path:"/rollback-version",method:"post",handler:p(async(e,a)=>{const{projectId:t,codeVersion:i,rollbackTo:n}=e.body||{},l=u(e.body||{});if(f(t,"INFO","Rollback version",{projectId:t,codeVersion:i,rollbackTo:n}),!t)throw new r("Project ID cannot be empty",{field:"projectId"});if(i==null)throw new r("codeVersion cannot be empty",{field:"codeVersion"});if(n==null)throw new r("rollbackTo cannot be empty",{field:"rollbackTo"});if(g.GIT_ENABLED)return a.status(200).json({success:!1,deprecated:!0,message:"\u6B64\u63A5\u53E3\u5DF2\u5E9F\u5F03\uFF0C\u8BF7\u4F7F\u7528 /api/git/rollback \u8FDB\u884C\u7248\u672C\u56DE\u6EDA"});const o=await h.rollbackVersion(String(t),String(i),String(n),e,l);a.status(200).json(o)})}];j.forEach(e=>{e.middleware?y[e.method](e.path,e.middleware,e.handler):y[e.method](e.path,e.handler)});export default y;
@@ -1 +1 @@
1
- import N from"express";import S from"multer";import f from"fs";import I from"path";import{ValidationError as z,asyncHandler as p}from"../utils/error/errorHandler.js";import{log as m}from"../utils/log/logUtils.js";import k from"../appConfig/index.js";import{createWorkspace as F,pushSkillsToWorkspace as $,initProjectTemplate as A,executeCommand as b}from"../utils/computer/computerUtils.js";import{getFileList as j,updateFiles as E,uploadFile as O,uploadFiles as P,downloadAllFiles as U}from"../utils/computer/computerFileUtils.js";const g=N.Router(),y=S({storage:S.diskStorage({destination:(e,i,o)=>{try{const t=k.COMPUTER_WORKSPACE_DIR;if(!t)return o(new Error("COMPUTER_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));const s=e.body?.userId||"unknown",a=e.body?.cId||"unknown",n=I.join(t,String(s),String(a),".tmp");f.existsSync(n)||f.mkdirSync(n,{recursive:!0}),o(null,n)}catch(t){o(t)}},filename:(e,i,o)=>{const t=I.extname(i.originalname)||".zip",s=I.basename(i.originalname,t),a=`${Date.now()}_${Math.round(Math.random()*1e6)}`;o(null,`${s}_${a}${t}`)}}),limits:{fileSize:k.UPLOAD_MAX_FILE_SIZE_BYTES}});function R(e,i,o,t){if(e&&e.name==="MulterError"||e&&(e.name==="ValidationError"||e instanceof z))return t(e);t(e)}const x=[{path:"/create-workspace",method:"post",middleware:y.single("file"),handler:p(async(e,i)=>{const{userId:o,cId:t}=e.body||{},s=e.file||null,a=`computer:${o}:${t}`;m(a,"INFO","Create workspace request",{userId:o,cId:t,hasFile:!!s,fileName:s?.originalname,fileSize:s?.size});const n=await F(o,t,s);i.status(200).json({success:!0,...n})})},{path:"/create-workspace-v2",method:"post",middleware:y.single("file"),handler:p(async(e,i)=>{const{userId:o,cId:t,skillUrls:s,mcpServersConfig:a,hooksConfig:n,permissionsConfig:r,hookScripts:l}=e.body||{},d=e.file||null,u=`computer:${o}:${t}`;let c=s;if(typeof s=="string")try{const w=JSON.parse(s);c=Array.isArray(w)?w:[s]}catch{c=[s]}let h=l;if(typeof l=="string")try{h=JSON.parse(l)}catch{h=null}m(u,"INFO","Create workspace v2 request",{userId:o,cId:t,hasFile:!!d,fileName:d?.originalname,fileSize:d?.size,skillUrlsCount:Array.isArray(c)?c.length:0,hasMcpServersConfig:!!a,hasHooksConfig:!!n,hasPermissionsConfig:!!r,hookScriptsCount:Array.isArray(h)?h.length:0});const C=await F(o,t,d,c,a,r,n,h);i.status(200).json({success:!0,...C})})},{path:"/push-skills-to-workspace",method:"post",middleware:y.single("file"),handler:p(async(e,i)=>{const{userId:o,cId:t}=e.body||{},s=e.file||null,a=`computer:${o}:${t}`;m(a,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42",{userId:o,cId:t,hasFile:!!s,fileName:s?.originalname,fileSize:s?.size});const n=await $(o,t,s);i.status(200).json({success:!0,...n})})},{path:"/push-skills-to-workspace-v2",method:"post",middleware:y.single("file"),handler:p(async(e,i)=>{const{userId:o,cId:t,skillUrls:s}=e.body||{},a=e.file||null,n=`computer:${o}:${t}`;let r=s;if(typeof s=="string")try{const d=JSON.parse(s);r=Array.isArray(d)?d:[s]}catch{r=[s]}m(n,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42(v2)",{userId:o,cId:t,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size,skillUrlsCount:Array.isArray(r)?r.length:0});const l=await $(o,t,a,r);i.status(200).json({success:!0,...l})})},{path:"/get-file-list",method:"get",handler:p(async(e,i)=>{const{userId:o,cId:t,proxyPath:s}=e.query,a=await j(o,t,s);i.status(200).json({success:!0,...a})})},{path:"/files-update",method:"post",handler:p(async(e,i)=>{const{userId:o,cId:t,files:s}=e.body||{},a=`computer:${o}:${t}`;m(a,"INFO","Files update",{userId:o,cId:t,filesCount:s?s.length:0}),s&&Array.isArray(s)&&s.forEach(r=>{if(r&&typeof r.contents=="string"&&r.contents)try{r.contents=decodeURIComponent(r.contents)}catch(l){m(a,"WARN","Decode file content failed",{fileName:r.name,error:l.message})}});const n=await E(o,t,s);i.status(200).json(n)})},{path:"/upload-file",method:"post",middleware:y.single("file"),handler:p(async(e,i)=>{const{userId:o,cId:t,filePath:s}=e.body||{},a=e.file,n=`computer:${o}:${t}`;m(n,"INFO","Upload single file",{userId:o,cId:t,filePath:s});const l={buffer:await f.promises.readFile(a.path),originalname:a.originalname,mimetype:a.mimetype,size:a.size};try{const d=await O(o,t,l,s);i.status(200).json(d)}finally{f.existsSync(a.path)&&await f.promises.unlink(a.path)}})},{path:"/upload-files",method:"post",middleware:y.array("files"),handler:p(async(e,i)=>{const{userId:o,cId:t,filePaths:s}=e.body||{},a=e.files||[],n=`computer:${o}:${t}`,r=Array.isArray(s)?s:typeof s=="string"?[s]:s;m(n,"INFO","Batch upload files request",{userId:o,cId:t,filesCount:a.length,filePathsCount:Array.isArray(r)?r.length:0});const l=[],d=[];try{for(const c of a){d.push(c.path);const h=await f.promises.readFile(c.path);l.push({buffer:h,originalname:c.originalname,mimetype:c.mimetype,size:c.size})}const u=await P(o,t,l,r);i.status(200).json(u)}finally{for(const u of d)if(f.existsSync(u))try{await f.promises.unlink(u)}catch(c){m(n,"WARN","Clean temporary file failed",{tempPath:u,error:c.message})}}})},{path:"/init-project-template",method:"post",middleware:y.single("file"),handler:p(async(e,i)=>{const{userId:o,cId:t,enableGit:s}=e.body||{},a=e.file||null,n=`computer:${o}:${t}`;m(n,"INFO","Init project template request",{userId:o,cId:t,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size,enableGit:s});const r=await A(o,t,a,s);i.status(200).json({success:!0,...r})})},{path:"/download-all-files",method:"get",handler:p(async(e,i)=>{const{userId:o,cId:t}=e.query||{},s=`computer:${o}:${t}`;m(s,"INFO","Download all files request",{userId:o,cId:t});const{archive:a,zipFileName:n}=await U(o,t);i.setHeader("Content-Type","application/zip");const r=encodeURIComponent(n);i.setHeader("Content-Disposition",`attachment; filename="${r}"; filename*=UTF-8''${r}`),a.on("error",l=>{i.destroy(l)}),a.pipe(i),a.finalize()})},{path:"/execute-command",method:"post",handler:p(async(e,i)=>{const{userId:o,cId:t,command:s}=e.body||{},a=`computer:${o}:${t}`;m(a,"INFO","Execute command request",{userId:o,cId:t,command:s});const n=await b(o,t,s);i.status(200).json({success:!0,...n})})}];x.forEach(e=>{if(e.middleware)g[e.method](e.path,e.middleware,e.handler);else if(e.customHandler){const i=[];e.handler&&i.push(e.handler),e.decodeMiddleware&&i.push(e.decodeMiddleware),i.push(R),i.push(e.customHandler),g[e.method](e.path,...i)}else g[e.method](e.path,e.handler)});export default g;
1
+ import C from"express";import k from"multer";import u from"fs";import I from"path";import{ValidationError as z,asyncHandler as d}from"../utils/error/errorHandler.js";import{log as m}from"../utils/log/logUtils.js";import F from"../appConfig/index.js";import{createWorkspace as S,pushSkillsToWorkspace as $,initProjectTemplate as A,executeCommand as b,deleteWorkspace as j}from"../utils/computer/computerUtils.js";import{getFileList as O,updateFiles as E,uploadFile as P,uploadFiles as U,downloadAllFiles as R,getLatestLogs as x}from"../utils/computer/computerFileUtils.js";const g=C.Router(),y=k({storage:k.diskStorage({destination:(e,i,o)=>{try{const s=F.COMPUTER_WORKSPACE_DIR;if(!s)return o(new Error("COMPUTER_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));const t=e.body?.userId||"unknown",a=e.body?.cId||"unknown",n=I.join(s,String(t),String(a),".tmp");u.existsSync(n)||u.mkdirSync(n,{recursive:!0}),o(null,n)}catch(s){o(s)}},filename:(e,i,o)=>{const s=I.extname(i.originalname)||".zip",t=I.basename(i.originalname,s),a=`${Date.now()}_${Math.round(Math.random()*1e6)}`;o(null,`${t}_${a}${s}`)}}),limits:{fileSize:F.UPLOAD_MAX_FILE_SIZE_BYTES}});function D(e,i,o,s){if(e&&e.name==="MulterError"||e&&(e.name==="ValidationError"||e instanceof z))return s(e);s(e)}const _=[{path:"/create-workspace",method:"post",middleware:y.single("file"),handler:d(async(e,i)=>{const{userId:o,cId:s}=e.body||{},t=e.file||null,a=`computer:${o}:${s}`;m(a,"INFO","Create workspace request",{userId:o,cId:s,hasFile:!!t,fileName:t?.originalname,fileSize:t?.size});const n=await S(o,s,t);i.status(200).json({success:!0,...n})})},{path:"/create-workspace-v2",method:"post",middleware:y.single("file"),handler:d(async(e,i)=>{const{userId:o,cId:s,skillUrls:t,mcpServersConfig:a,hooksConfig:n,permissionsConfig:r,hookScripts:l}=e.body||{},p=e.file||null,f=`computer:${o}:${s}`;let c=t;if(typeof t=="string")try{const w=JSON.parse(t);c=Array.isArray(w)?w:[t]}catch{c=[t]}let h=l;if(typeof l=="string")try{h=JSON.parse(l)}catch{h=null}m(f,"INFO","Create workspace v2 request",{userId:o,cId:s,hasFile:!!p,fileName:p?.originalname,fileSize:p?.size,skillUrlsCount:Array.isArray(c)?c.length:0,hasMcpServersConfig:!!a,hasHooksConfig:!!n,hasPermissionsConfig:!!r,hookScriptsCount:Array.isArray(h)?h.length:0});const N=await S(o,s,p,c,a,r,n,h);i.status(200).json({success:!0,...N})})},{path:"/push-skills-to-workspace",method:"post",middleware:y.single("file"),handler:d(async(e,i)=>{const{userId:o,cId:s}=e.body||{},t=e.file||null,a=`computer:${o}:${s}`;m(a,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42",{userId:o,cId:s,hasFile:!!t,fileName:t?.originalname,fileSize:t?.size});const n=await $(o,s,t);i.status(200).json({success:!0,...n})})},{path:"/push-skills-to-workspace-v2",method:"post",middleware:y.single("file"),handler:d(async(e,i)=>{const{userId:o,cId:s,skillUrls:t}=e.body||{},a=e.file||null,n=`computer:${o}:${s}`;let r=t;if(typeof t=="string")try{const p=JSON.parse(t);r=Array.isArray(p)?p:[t]}catch{r=[t]}m(n,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42(v2)",{userId:o,cId:s,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size,skillUrlsCount:Array.isArray(r)?r.length:0});const l=await $(o,s,a,r);i.status(200).json({success:!0,...l})})},{path:"/get-file-list",method:"get",handler:d(async(e,i)=>{const{userId:o,cId:s,proxyPath:t}=e.query,a=await O(o,s,t);i.status(200).json({success:!0,...a})})},{path:"/files-update",method:"post",handler:d(async(e,i)=>{const{userId:o,cId:s,files:t}=e.body||{},a=`computer:${o}:${s}`;m(a,"INFO","Files update",{userId:o,cId:s,filesCount:t?t.length:0}),t&&Array.isArray(t)&&t.forEach(r=>{if(r&&typeof r.contents=="string"&&r.contents)try{r.contents=decodeURIComponent(r.contents)}catch(l){m(a,"WARN","Decode file content failed",{fileName:r.name,error:l.message})}});const n=await E(o,s,t);i.status(200).json(n)})},{path:"/upload-file",method:"post",middleware:y.single("file"),handler:d(async(e,i)=>{const{userId:o,cId:s,filePath:t}=e.body||{},a=e.file,n=`computer:${o}:${s}`;m(n,"INFO","Upload single file",{userId:o,cId:s,filePath:t});const l={buffer:await u.promises.readFile(a.path),originalname:a.originalname,mimetype:a.mimetype,size:a.size};try{const p=await P(o,s,l,t);i.status(200).json(p)}finally{u.existsSync(a.path)&&await u.promises.unlink(a.path)}})},{path:"/upload-files",method:"post",middleware:y.array("files"),handler:d(async(e,i)=>{const{userId:o,cId:s,filePaths:t}=e.body||{},a=e.files||[],n=`computer:${o}:${s}`,r=Array.isArray(t)?t:typeof t=="string"?[t]:t;m(n,"INFO","Batch upload files request",{userId:o,cId:s,filesCount:a.length,filePathsCount:Array.isArray(r)?r.length:0});const l=[],p=[];try{for(const c of a){p.push(c.path);const h=await u.promises.readFile(c.path);l.push({buffer:h,originalname:c.originalname,mimetype:c.mimetype,size:c.size})}const f=await U(o,s,l,r);i.status(200).json(f)}finally{for(const f of p)if(u.existsSync(f))try{await u.promises.unlink(f)}catch(c){m(n,"WARN","Clean temporary file failed",{tempPath:f,error:c.message})}}})},{path:"/init-project-template",method:"post",middleware:y.single("file"),handler:d(async(e,i)=>{const{userId:o,cId:s,enableGit:t}=e.body||{},a=e.file||null,n=`computer:${o}:${s}`;m(n,"INFO","Init project template request",{userId:o,cId:s,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size,enableGit:t});const r=await A(o,s,a,t);i.status(200).json({success:!0,...r})})},{path:"/download-all-files",method:"get",handler:d(async(e,i)=>{const{userId:o,cId:s}=e.query||{},t=`computer:${o}:${s}`;m(t,"INFO","Download all files request",{userId:o,cId:s});const{archive:a,zipFileName:n}=await R(o,s);i.setHeader("Content-Type","application/zip");const r=encodeURIComponent(n);i.setHeader("Content-Disposition",`attachment; filename="${r}"; filename*=UTF-8''${r}`),a.on("error",l=>{i.destroy(l)}),a.pipe(i),a.finalize()})},{path:"/execute-command",method:"post",handler:d(async(e,i)=>{const{userId:o,cId:s,command:t}=e.body||{},a=`computer:${o}:${s}`;m(a,"INFO","Execute command request",{userId:o,cId:s,command:t});const n=await b(o,s,t);i.status(200).json({success:!0,...n})})},{path:"/delete-workspace",method:"post",handler:d(async(e,i)=>{const{userId:o,cId:s}=e.body||{},t=`computer:${o}:${s}`;m(t,"INFO","Delete workspace request",{userId:o,cId:s});const a=await j(o,s);i.status(200).json({success:!0,...a})})},{path:"/get-logs",method:"get",handler:d(async(e,i)=>{const{userId:o,cId:s,tailLines:t}=e.query,a=t?parseInt(t,10):200,n=Number.isFinite(a)&&a>0?a:200,r=await x(o,s,n);i.status(200).json({success:!0,...r})})}];_.forEach(e=>{if(e.middleware)g[e.method](e.path,e.middleware,e.handler);else if(e.customHandler){const i=[];e.handler&&i.push(e.handler),e.decodeMiddleware&&i.push(e.decodeMiddleware),i.push(D),i.push(e.customHandler),g[e.method](e.path,...i)}else g[e.method](e.path,e.handler)});export default g;
@@ -1 +1 @@
1
- import l from"express";import{asyncHandler as r,ValidationError as h}from"../utils/error/errorHandler.js";import c from"../service/gitService.js";import{log as d}from"../utils/log/logUtils.js";import{extractIsolationContext as I}from"../utils/common/projectPathUtils.js";const u=l.Router();function p(e){const{workspaceType:o,projectId:t,userId:s,cId:a}=e||{},n=I(e||{});return{workspaceType:o?String(o):void 0,projectId:t?String(t):void 0,userId:s?String(s):void 0,cId:a?String(a):void 0,isolationContext:n}}const y=[{path:"/init",method:"post",handler:r(async(e,o)=>{const t=p(e.body);d(t.projectId||`computer:${t.userId}:${t.cId}`,"INFO","Git init",t);const s=await c.init(t);o.status(200).json(s)})},{path:"/status",method:"get",handler:r(async(e,o)=>{const t=p(e.query);d(t.projectId||`computer:${t.userId}:${t.cId}`,"INFO","Git status",t);const s=await c.status(t);o.status(200).json(s)})},{path:"/commit",method:"post",handler:r(async(e,o)=>{const{message:t,files:s,authorName:a,authorEmail:n}=e.body||{},i={...p(e.body),message:t,files:s,authorName:a,authorEmail:n};if(!t)throw new h("Commit message cannot be empty",{field:"message"});d(i.projectId||`computer:${i.userId}:${i.cId}`,"INFO","Git commit",{...i,filesCount:s?s.length:"all"});const m=await c.commit(i);o.status(200).json(m)})},{path:"/add",method:"post",handler:r(async(e,o)=>{const{files:t}=e.body||{},s={...p(e.body),files:t};d(s.projectId||`computer:${s.userId}:${s.cId}`,"INFO","Git add",{...s,filesCount:t?t.length:"all"});const a=await c.add(s);o.status(200).json(a)})},{path:"/unstage",method:"post",handler:r(async(e,o)=>{const{files:t}=e.body||{},s={...p(e.body),files:t};d(s.projectId||`computer:${s.userId}:${s.cId}`,"INFO","Git unstage",{...s,filesCount:t?t.length:"all"});const a=await c.unstage(s);o.status(200).json(a)})},{path:"/discard",method:"post",handler:r(async(e,o)=>{const{files:t}=e.body||{},s={...p(e.body),files:t};d(s.projectId||`computer:${s.userId}:${s.cId}`,"INFO","Git discard",{...s,filesCount:t?t.length:"all"});const a=await c.discard(s);o.status(200).json(a)})},{path:"/log",method:"get",handler:r(async(e,o)=>{const{maxCount:t,branch:s,skip:a}=e.query||{},n={...p(e.query),maxCount:t?parseInt(t,10):50,skip:a?parseInt(a,10):0,branch:s};d(n.projectId||`computer:${n.userId}:${n.cId}`,"INFO","Git log",n);const i=await c.logHistory(n);o.status(200).json(i)})},{path:"/diff",method:"post",handler:r(async(e,o)=>{const{from:t,to:s,paths:a,source:n}=e.body||{},i={...p(e.body),from:t,to:s,paths:a,source:n};d(i.projectId||`computer:${i.userId}:${i.cId}`,"INFO","Git diff",{from:t,to:s});const m=await c.diff(i);o.status(200).json(m)})},{path:"/file-content",method:"post",handler:r(async(e,o)=>{const{ref:t,filePath:s}=e.body||{},a={...p(e.body),ref:t,filePath:s};d(a.projectId||`computer:${a.userId}:${a.cId}`,"INFO","Git file content",{ref:t,filePath:s});const n=await c.fileContent(a);o.status(200).json(n)})},{path:"/reset",method:"post",handler:r(async(e,o)=>{const{target:t,mode:s}=e.body||{},a={...p(e.body),target:t,mode:s||"mixed"};if(!t)throw new h("Reset target cannot be empty",{field:"target"});d(a.projectId||`computer:${a.userId}:${a.cId}`,"INFO","Git reset",{target:t,mode:s});const n=await c.reset(a);o.status(200).json(n)})},{path:"/checkout",method:"post",handler:r(async(e,o)=>{const{target:t}=e.body||{},s={...p(e.body),target:t};if(!t)throw new h("Checkout target cannot be empty",{field:"target"});d(s.projectId||`computer:${s.userId}:${s.cId}`,"INFO","Git checkout files",{target:t});const a=await c.checkout(s);o.status(200).json(a)})},{path:"/revert",method:"post",handler:r(async(e,o)=>{const{target:t}=e.body||{},s={...p(e.body),target:t};if(!t)throw new h("Revert target cannot be empty",{field:"target"});d(s.projectId||`computer:${s.userId}:${s.cId}`,"INFO","Git revert",{target:t});const a=await c.revert(s);o.status(200).json(a)})},{path:"/tags",method:"get",handler:r(async(e,o)=>{const t=p(e.query);d(t.projectId||`computer:${t.userId}:${t.cId}`,"INFO","Git list tags",t);const s=await c.listTags(t);o.status(200).json(s)})},{path:"/tag-create",method:"post",handler:r(async(e,o)=>{const{tagName:t,message:s}=e.body||{},a={...p(e.body),tagName:t,message:s};if(!t)throw new h("Tag name cannot be empty",{field:"tagName"});d(a.projectId||`computer:${a.userId}:${a.cId}`,"INFO","Git create tag",{tagName:t});const n=await c.createTag(a);o.status(200).json(n)})},{path:"/tag-delete",method:"post",handler:r(async(e,o)=>{const{tagName:t}=e.body||{},s={...p(e.body),tagName:t};if(!t)throw new h("Tag name cannot be empty",{field:"tagName"});d(s.projectId||`computer:${s.userId}:${s.cId}`,"INFO","Git delete tag",{tagName:t});const a=await c.deleteTag(s);o.status(200).json(a)})},{path:"/branches",method:"get",handler:r(async(e,o)=>{const t=p(e.query);d(t.projectId||`computer:${t.userId}:${t.cId}`,"INFO","Git list branches",t);const s=await c.listBranches(t);o.status(200).json(s)})},{path:"/branch-create",method:"post",handler:r(async(e,o)=>{const{branchName:t,startPoint:s}=e.body||{},a={...p(e.body),branchName:t,startPoint:s};if(!t)throw new h("Branch name cannot be empty",{field:"branchName"});d(a.projectId||`computer:${a.userId}:${a.cId}`,"INFO","Git create branch",{branchName:t,startPoint:s});const n=await c.createBranch(a);o.status(200).json(n)})},{path:"/branch-switch",method:"post",handler:r(async(e,o)=>{const{branchName:t}=e.body||{},s={...p(e.body),branchName:t};if(!t)throw new h("Branch name cannot be empty",{field:"branchName"});d(s.projectId||`computer:${s.userId}:${s.cId}`,"INFO","Git switch branch",{branchName:t});const a=await c.switchBranch(s);o.status(200).json(a)})},{path:"/branch-delete",method:"post",handler:r(async(e,o)=>{const{branchName:t,force:s}=e.body||{},a={...p(e.body),branchName:t,force:s===!0};if(!t)throw new h("Branch name cannot be empty",{field:"branchName"});d(a.projectId||`computer:${a.userId}:${a.cId}`,"INFO","Git delete branch",{branchName:t,force:s});const n=await c.deleteBranch(a);o.status(200).json(n)})},{path:"/stash",method:"post",handler:r(async(e,o)=>{const{message:t,files:s}=e.body||{},a={...p(e.body),message:t,files:s};d(a.projectId||`computer:${a.userId}:${a.cId}`,"INFO","Git stash push",a);const n=await c.stashPush(a);o.status(200).json(n)})},{path:"/stash-pop",method:"post",handler:r(async(e,o)=>{const{index:t,files:s}=e.body||{},a={...p(e.body),index:t,files:s};d(a.projectId||`computer:${a.userId}:${a.cId}`,"INFO","Git stash pop",{index:t});const n=await c.stashPop(a);o.status(200).json(n)})},{path:"/stash-list",method:"get",handler:r(async(e,o)=>{const t=p(e.query);d(t.projectId||`computer:${t.userId}:${t.cId}`,"INFO","Git stash list",t);const s=await c.stashList(t);o.status(200).json(s)})}];y.forEach(e=>{e.middleware?u[e.method](e.path,e.middleware,e.handler):u[e.method](e.path,e.handler)});export default u;
1
+ import l from"express";import{asyncHandler as n,ValidationError as h}from"../utils/error/errorHandler.js";import r from"../service/gitService.js";import{log as c}from"../utils/log/logUtils.js";import{extractIsolationContext as I}from"../utils/common/projectPathUtils.js";const u=l.Router();function d(e){const{workspaceType:o,projectId:t,userId:s,cId:a}=e||{},p=I(e||{});return{workspaceType:o?String(o):void 0,projectId:t?String(t):void 0,userId:s?String(s):void 0,cId:a?String(a):void 0,isolationContext:p}}const y=[{path:"/init",method:"post",handler:n(async(e,o)=>{const t=d(e.body);c(t.projectId||`computer:${t.userId}:${t.cId}`,"INFO","Git init",t);const s=await r.init(t);o.status(200).json(s)})},{path:"/status",method:"get",handler:n(async(e,o)=>{const t=d(e.query);c(t.projectId||`computer:${t.userId}:${t.cId}`,"INFO","Git status",t);const s=await r.status(t);o.status(200).json(s)})},{path:"/commit",method:"post",handler:n(async(e,o)=>{const{message:t,files:s,authorName:a,authorEmail:p}=e.body||{},i={...d(e.body),message:t,files:s,authorName:a,authorEmail:p};if(!t)throw new h("Commit message cannot be empty",{field:"message"});c(i.projectId||`computer:${i.userId}:${i.cId}`,"INFO","Git commit",{...i,filesCount:s?s.length:"all"});const m=await r.commit(i);o.status(200).json(m)})},{path:"/add",method:"post",handler:n(async(e,o)=>{const{files:t}=e.body||{},s={...d(e.body),files:t};c(s.projectId||`computer:${s.userId}:${s.cId}`,"INFO","Git add",{...s,filesCount:t?t.length:"all"});const a=await r.add(s);o.status(200).json(a)})},{path:"/unstage",method:"post",handler:n(async(e,o)=>{const{files:t}=e.body||{},s={...d(e.body),files:t};c(s.projectId||`computer:${s.userId}:${s.cId}`,"INFO","Git unstage",{...s,filesCount:t?t.length:"all"});const a=await r.unstage(s);o.status(200).json(a)})},{path:"/discard",method:"post",handler:n(async(e,o)=>{const{files:t}=e.body||{},s={...d(e.body),files:t};c(s.projectId||`computer:${s.userId}:${s.cId}`,"INFO","Git discard",{...s,filesCount:t?t.length:"all"});const a=await r.discard(s);o.status(200).json(a)})},{path:"/log",method:"get",handler:n(async(e,o)=>{const{maxCount:t,branch:s,skip:a,filePath:p}=e.query||{},i={...d(e.query),maxCount:t?parseInt(t,10):50,skip:a?parseInt(a,10):0,branch:s,filePath:p};c(i.projectId||`computer:${i.userId}:${i.cId}`,"INFO","Git log",i);const m=await r.logHistory(i);o.status(200).json(m)})},{path:"/diff",method:"post",handler:n(async(e,o)=>{const{from:t,to:s,paths:a,source:p}=e.body||{},i={...d(e.body),from:t,to:s,paths:a,source:p};c(i.projectId||`computer:${i.userId}:${i.cId}`,"INFO","Git diff",{from:t,to:s});const m=await r.diff(i);o.status(200).json(m)})},{path:"/file-content",method:"post",handler:n(async(e,o)=>{const{ref:t,filePath:s}=e.body||{},a={...d(e.body),ref:t,filePath:s};c(a.projectId||`computer:${a.userId}:${a.cId}`,"INFO","Git file content",{ref:t,filePath:s});const p=await r.fileContent(a);o.status(200).json(p)})},{path:"/reset",method:"post",handler:n(async(e,o)=>{const{target:t,mode:s}=e.body||{},a={...d(e.body),target:t,mode:s||"mixed"};if(!t)throw new h("Reset target cannot be empty",{field:"target"});c(a.projectId||`computer:${a.userId}:${a.cId}`,"INFO","Git reset",{target:t,mode:s});const p=await r.reset(a);o.status(200).json(p)})},{path:"/checkout",method:"post",handler:n(async(e,o)=>{const{target:t}=e.body||{},s={...d(e.body),target:t};if(!t)throw new h("Checkout target cannot be empty",{field:"target"});c(s.projectId||`computer:${s.userId}:${s.cId}`,"INFO","Git checkout files",{target:t});const a=await r.checkout(s);o.status(200).json(a)})},{path:"/revert",method:"post",handler:n(async(e,o)=>{const{target:t}=e.body||{},s={...d(e.body),target:t};if(!t)throw new h("Revert target cannot be empty",{field:"target"});c(s.projectId||`computer:${s.userId}:${s.cId}`,"INFO","Git revert",{target:t});const a=await r.revert(s);o.status(200).json(a)})},{path:"/tags",method:"get",handler:n(async(e,o)=>{const t=d(e.query);c(t.projectId||`computer:${t.userId}:${t.cId}`,"INFO","Git list tags",t);const s=await r.listTags(t);o.status(200).json(s)})},{path:"/tag-create",method:"post",handler:n(async(e,o)=>{const{tagName:t,message:s}=e.body||{},a={...d(e.body),tagName:t,message:s};if(!t)throw new h("Tag name cannot be empty",{field:"tagName"});c(a.projectId||`computer:${a.userId}:${a.cId}`,"INFO","Git create tag",{tagName:t});const p=await r.createTag(a);o.status(200).json(p)})},{path:"/tag-delete",method:"post",handler:n(async(e,o)=>{const{tagName:t}=e.body||{},s={...d(e.body),tagName:t};if(!t)throw new h("Tag name cannot be empty",{field:"tagName"});c(s.projectId||`computer:${s.userId}:${s.cId}`,"INFO","Git delete tag",{tagName:t});const a=await r.deleteTag(s);o.status(200).json(a)})},{path:"/branches",method:"get",handler:n(async(e,o)=>{const t=d(e.query);c(t.projectId||`computer:${t.userId}:${t.cId}`,"INFO","Git list branches",t);const s=await r.listBranches(t);o.status(200).json(s)})},{path:"/branch-create",method:"post",handler:n(async(e,o)=>{const{branchName:t,startPoint:s}=e.body||{},a={...d(e.body),branchName:t,startPoint:s};if(!t)throw new h("Branch name cannot be empty",{field:"branchName"});c(a.projectId||`computer:${a.userId}:${a.cId}`,"INFO","Git create branch",{branchName:t,startPoint:s});const p=await r.createBranch(a);o.status(200).json(p)})},{path:"/branch-switch",method:"post",handler:n(async(e,o)=>{const{branchName:t}=e.body||{},s={...d(e.body),branchName:t};if(!t)throw new h("Branch name cannot be empty",{field:"branchName"});c(s.projectId||`computer:${s.userId}:${s.cId}`,"INFO","Git switch branch",{branchName:t});const a=await r.switchBranch(s);o.status(200).json(a)})},{path:"/branch-delete",method:"post",handler:n(async(e,o)=>{const{branchName:t,force:s}=e.body||{},a={...d(e.body),branchName:t,force:s===!0};if(!t)throw new h("Branch name cannot be empty",{field:"branchName"});c(a.projectId||`computer:${a.userId}:${a.cId}`,"INFO","Git delete branch",{branchName:t,force:s});const p=await r.deleteBranch(a);o.status(200).json(p)})},{path:"/stash",method:"post",handler:n(async(e,o)=>{const{message:t,files:s}=e.body||{},a={...d(e.body),message:t,files:s};c(a.projectId||`computer:${a.userId}:${a.cId}`,"INFO","Git stash push",a);const p=await r.stashPush(a);o.status(200).json(p)})},{path:"/stash-pop",method:"post",handler:n(async(e,o)=>{const{index:t,files:s}=e.body||{},a={...d(e.body),index:t,files:s};c(a.projectId||`computer:${a.userId}:${a.cId}`,"INFO","Git stash pop",{index:t});const p=await r.stashPop(a);o.status(200).json(p)})},{path:"/stash-list",method:"get",handler:n(async(e,o)=>{const t=d(e.query);c(t.projectId||`computer:${t.userId}:${t.cId}`,"INFO","Git stash list",t);const s=await r.stashList(t);o.status(200).json(s)})}];y.forEach(e=>{e.middleware?u[e.method](e.path,e.middleware,e.handler):u[e.method](e.path,e.handler)});export default u;
@@ -1,4 +1,4 @@
1
- import l from"path";import r from"fs";import R from"../appConfig/index.js";import{restartDevServer as A}from"../utils/build/restartDevUtils.js";import{log as i}from"../utils/log/logUtils.js";import{ValidationError as m,SystemError as E,ResourceError as D}from"../utils/error/errorHandler.js";import"../utils/common/sensitiveUtils.js";import{backupProjectToZip as S,restoreProjectFromZip as z,pruneMissingFiles as U}from"../utils/project/backupUtils.js";import"../utils/common/zipUtils.js";import"../utils/buildJudge/restartJudgeUtils.js";import{resolveProjectPath as x}from"../utils/common/projectPathUtils.js";function L(e,P){const n=e.split(/\r?\n/),g=P.split(/\r?\n/),d=n.length,y=g.length,b=Math.min(d,y);let a=0;for(let o=0;o<b;o++)n[o]!==g[o]&&(n[o]=g[o],a++);if(d>y)for(let o=d-1;o>=y;o--)n.splice(o,1),a++;if(y>d)for(let o=d;o<y;o++)n.push(g[o]),a++;const h=e.includes(`\r
1
+ import o from"path";import r from"fs";import R from"../appConfig/index.js";import{restartDevServer as U}from"../utils/build/restartDevUtils.js";import{log as t}from"../utils/log/logUtils.js";import{ValidationError as h,SystemError as x,ResourceError as D}from"../utils/error/errorHandler.js";import"../utils/common/sensitiveUtils.js";import{backupProjectToZip as O,restoreProjectFromZip as z,pruneMissingFiles as L}from"../utils/project/backupUtils.js";import"../utils/common/zipUtils.js";import"../utils/buildJudge/restartJudgeUtils.js";import{resolveProjectPath as S}from"../utils/common/projectPathUtils.js";function V(e,d){const n=e.split(/\r?\n/),g=d.split(/\r?\n/),F=n.length,b=g.length,y=Math.min(F,b);let l=0;for(let a=0;a<y;a++)n[a]!==g[a]&&(n[a]=g[a],l++);if(F>b)for(let a=F-1;a>=b;a--)n.splice(a,1),l++;if(b>F)for(let a=F;a<b;a++)n.push(g[a]),l++;const m=e.includes(`\r
2
2
  `)?`\r
3
3
  `:`
4
- `;return{finalContent:n.join(h),changesCount:a}}function te(e,P){return e===P?{finalContent:e,changesCount:0}:{finalContent:P,changesCount:-1}}async function T(e,P,n,g,d={}){const y=Date.now();if(!e)throw new m("Project ID cannot be empty",{field:"projectId"});if(P==null)throw new m("codeVersion cannot be empty",{field:"codeVersion"});const b=Number(P);if(!Number.isFinite(b))throw new m("codeVersion must be a number",{field:"codeVersion"});if(!Array.isArray(n))throw new m("files must be an array",{field:"files"});for(let s=0;s<n.length;s++){const o=n[s];if(!o||typeof o.operation!="string")throw new m(`files[${s}].operation cannot be empty`,{field:`files[${s}].operation`});if(!o.name||typeof o.name!="string")throw new m(`files[${s}].name cannot be empty`,{field:`files[${s}].name`});const t=o.operation.toLowerCase();if(!["create","delete","rename","modify"].includes(t))throw new m(`files[${s}].operation must be one of create, delete, rename or modify`,{field:`files[${s}].operation`});if(t==="rename"&&!o.renameFrom)throw new m(`files[${s}].renameFrom cannot be empty (rename operation requires)`,{field:`files[${s}].renameFrom`});if(t==="modify"&&typeof o.contents!="string")throw new m(`files[${s}].contents must be a string (modify operation requires)`,{field:`files[${s}].contents`})}const a=x(e,d);if(!r.existsSync(a))throw i(e,"ERROR","Project does not exist",{projectId:e,projectPath:a}),new D("Project does not exist",{projectId:e});let h="";try{const s=l.join(R.UPLOAD_PROJECT_DIR,e);r.existsSync(s)||r.mkdirSync(s,{recursive:!0});const o=`${e}-v${b}.zip`;h=l.join(s,o),i(e,"DEBUG","Start backing up project",{projectId:e,backupZipPath:h}),R.GIT_ENABLED||await S(e,a,h),i(e,"INFO","Project backed up successfully",{projectId:e,zipPath:h});try{i(e,"DEBUG","Start processing file operations",{projectId:e,filesCount:n.length});for(const t of n){const u=t.operation.toLowerCase(),c=t.name,f=l.normalize(c).replace(/^[\/\\]+/,""),w=l.join(a,f),k=l.resolve(w),F=l.resolve(a);if(!k.startsWith(F+l.sep)&&k!==F){i(e,"WARN","Unsafe file path, skipping",{filePath:f,resolvedPath:k});continue}switch(u){case"create":{if(t.isDir===!0)r.existsSync(w)?i(e,"INFO","Directory already exists, skipping creation",{filePath:f}):(await r.promises.mkdir(w,{recursive:!0}),i(e,"INFO","Directory created successfully",{filePath:f}));else{await r.promises.mkdir(l.dirname(w),{recursive:!0});const p=t.contents||"";await r.promises.writeFile(w,p,"utf8"),i(e,"INFO","File created successfully",{filePath:f})}break}case"delete":{r.existsSync(w)?(await r.promises.stat(w)).isDirectory()?(await r.promises.rm(w,{recursive:!0,force:!0}),i(e,"INFO","Directory deleted successfully",{filePath:f})):(await r.promises.unlink(w),i(e,"INFO","File deleted successfully",{filePath:f})):i(e,"WARN","File or directory to delete does not exist",{filePath:f});break}case"rename":{const p=t.renameFrom;if(!p||typeof p!="string"){i(e,"WARN","Rename operation missing renameFrom",{filePath:f});break}const v=l.normalize(p).replace(/^[\/\\]+/,""),O=l.join(a,v),N=l.resolve(O);if(!N.startsWith(F+l.sep)&&N!==F){i(e,"WARN","Unsafe rename source path, skipping",{renameFrom:v,resolvedPath:N});break}r.existsSync(O)?(await r.promises.mkdir(l.dirname(w),{recursive:!0}),await r.promises.rename(O,w),i(e,"INFO","File renamed successfully",{oldPath:v,newPath:f})):i(e,"WARN","File to rename does not exist",{renameFrom:v});break}case"modify":{if(!r.existsSync(w)){i(e,"WARN","File to modify does not exist",{filePath:f});break}const p=await r.promises.readFile(w,"utf8"),v=typeof t.contents=="string"?t.contents:"",{finalContent:O,changesCount:N}=L(p,v);if(N===0){i(e,"INFO","File content unchanged, skipping write",{filePath:f});break}await r.promises.writeFile(w,O,"utf8"),i(e,"INFO","File modified successfully",{filePath:f,changesCount:N});break}default:{i(e,"WARN","Unsupported operation type",{operation:u,filePath:f});break}}}return i(e,"INFO","Specified files updated successfully",{projectId:e,filesCount:n.length,elapsedMs:Date.now()-y}),{success:!0,message:"Specified files updated successfully",projectId:e,filesCount:n.length}}catch(t){throw i(e,"ERROR","Failed to process file operations",{projectId:e,error:t&&t.message,elapsedMs:Date.now()-y}),t}}catch(s){throw s.isOperational?s:new E("Failed to backup project",{projectId:e,originalError:s&&s.message})}}async function C(e,P,n,g,d={}){const y=Date.now();if(!e)throw new m("Project ID cannot be empty",{field:"projectId"});const b=Number(P);if(!Number.isFinite(b))throw new m("codeVersion must be a number",{field:"codeVersion"});if(!Array.isArray(n))throw new m("files must be an array",{field:"files"});const a=x(e,d);if(!r.existsSync(a))throw i(e,"ERROR","Project does not exist",{projectId:e,projectPath:a}),new D("Project does not exist",{projectId:e});let h="";try{const s=l.join(R.UPLOAD_PROJECT_DIR,e);r.existsSync(s)||r.mkdirSync(s,{recursive:!0});const o=`${e}-v${b}.zip`;h=l.join(s,o),i(e,"DEBUG","Start backing up project",{projectId:e,backupZipPath:h}),R.GIT_ENABLED||await S(e,a,h);try{i(e,"DEBUG","Start writing files",{projectId:e,filesCount:n.length});for(const t of n){if(!t||typeof t.name!="string")continue;const u=l.join(a,t.name);if(t.isDir===!0){r.existsSync(u)||(await r.promises.mkdir(u,{recursive:!0}),i(e,"INFO","Directory ensured",{filePath:t.name}));continue}if(t.renameFrom&&typeof t.renameFrom=="string"){const p=l.join(a,t.renameFrom);if(r.existsSync(p)){await r.promises.mkdir(l.dirname(u),{recursive:!0}),await r.promises.rename(p,u),i(e,"INFO","File renamed successfully",{projectId:e,oldPath:t.renameFrom,newPath:t.name});continue}}const c=t.binary===!0,f=t.binary===!1,w=!!t.sizeExceeded,k=typeof t.contents=="string"&&t.contents.length>0;if(c){if(r.existsSync(u)){i(e,"INFO","Binary file already exists, skipping write",{filePath:t.name});continue}if(k)try{await r.promises.mkdir(l.dirname(u),{recursive:!0});const p=Buffer.from(t.contents,"base64");await r.promises.writeFile(u,p),i(e,"INFO","Binary file written successfully",{filePath:t.name})}catch(p){i(e,"ERROR","Failed to write binary file",{filePath:t.name,error:p&&p.message})}else i(e,"WARN","Binary file does not exist and has no content, skipping",{filePath:t.name});continue}f&&(!w||w&&k)&&(await r.promises.mkdir(l.dirname(u),{recursive:!0}),await r.promises.writeFile(u,t.contents||"","utf8"))}}catch(t){throw i(e,"ERROR","Failed to write files",{projectId:e,error:t&&t.message,elapsedMs:Date.now()-y}),t}try{i(e,"DEBUG","Start cleaning missing files",{projectId:e});const t=new Set(n.filter(c=>c&&typeof c.name=="string").map(c=>l.normalize(c.name))),u=n.filter(c=>c&&typeof c.name=="string"&&c.isDir===!0);await U(a,t,R.TRAVERSE_EXCLUDE_DIRS||[]);for(const c of u){const f=l.join(a,c.name);r.existsSync(f)||(await r.promises.mkdir(f,{recursive:!0}),i(e,"INFO","Empty directory recreated",{dirPath:c.name}))}}catch(t){throw i(e,"ERROR","Failed to clean missing files, starting rollback",{projectId:e,error:t&&t.message,elapsedMs:Date.now()-y}),t}return i(e,"INFO","Files submitted successfully",{projectId:e,filesCount:n.length,elapsedMs:Date.now()-y}),{success:!0,message:"Files submitted successfully",projectId:e,restarted:!1}}catch(s){throw s.isOperational?s:new E("Failed to backup old version",{projectId:e,originalError:s&&s.message})}}async function B(e,P,n,g,d,y={}){const b=Date.now();if(!e)throw new m("Project ID cannot be empty",{field:"projectId"});const a=Number(P);if(!Number.isFinite(a))throw new m("codeVersion must be a number",{field:"codeVersion"});if(!n)throw new m("File cannot be empty",{field:"file"});if(!g||typeof g!="string")throw new m("File path cannot be empty",{field:"filePath"});const h=x(e,y);if(!r.existsSync(h))throw i(e,"ERROR","Project does not exist",{projectId:e,projectPath:h}),new D("Project does not exist",{projectId:e});const s=l.normalize(g).replace(/^[\/\\]+/,""),o=l.join(h,s),t=l.resolve(o),u=l.resolve(h);if(!t.startsWith(u))throw new m("File path is not safe, cannot exceed project directory",{field:"filePath",providedPath:g,resolvedPath:t});let c="";try{const f=l.join(R.UPLOAD_PROJECT_DIR,e);r.existsSync(f)||r.mkdirSync(f,{recursive:!0});const w=`${e}-v${a}.zip`;c=l.join(f,w),i(e,"DEBUG","Start backing up project",{projectId:e,backupZipPath:c}),R.GIT_ENABLED||await S(e,h,c),i(e,"INFO",`Project backed up: ${c}`,{projectId:e,zipPath:c});try{if(i(e,"DEBUG","Start writing uploaded file",{projectId:e,filePath:s}),await r.promises.mkdir(l.dirname(o),{recursive:!0}),!n.buffer)throw new m("File content format is incorrect, missing buffer",{field:"file"});if(i(e,"INFO","Prepare to write file",{targetPath:o,bufferLength:n.buffer.length,expectedSize:n.size,bufferIsBuffer:Buffer.isBuffer(n.buffer),sizeMatch:n.buffer.length===n.size}),await r.promises.writeFile(o,n.buffer),i(e,"INFO","File uploaded successfully",{projectId:e,filePath:s,targetPath:t,fileSize:n.buffer?n.buffer.length:0,elapsedMs:Date.now()-b}),!1)try{const F=await A(d,e);return i(e,"INFO","Restart development server successfully",{projectId:e,pid:F.pid,port:F.port}),{success:!0,message:"File uploaded and restarted development server successfully",projectId:e,filePath:s,targetPath:t,fileSize:n.buffer?n.buffer.length:0,pid:F.pid,port:F.port,restarted:!0}}catch(F){i(e,"ERROR","Failed to restart development server",{projectId:e,filePath:s,error:F&&F.message})}else return i(e,"INFO","File modification does not require restarting development server",{projectId:e,filePath:s}),{success:!0,message:"File uploaded successfully, no need to restart development server",projectId:e,restarted:!1}}catch(k){throw i(e,"ERROR","Failed to write file",{projectId:e,filePath:s,error:k&&k.message,elapsedMs:Date.now()-b}),k}}catch(f){throw f.isOperational?f:new E("Failed to backup project",{projectId:e,filePath:s,originalError:f&&f.message})}}async function $(e,P,n,g,d={}){const y=Date.now();if(!e)throw new m("Project ID cannot be empty",{field:"projectId"});const b=Number(P);if(!Number.isFinite(b))throw new m("codeVersion must be a number",{field:"codeVersion"});const a=Number(n);if(!Number.isFinite(a))throw new m("rollbackTo must be a number",{field:"rollbackTo"});if(a<0)throw new m("rollbackTo cannot be less than 0",{field:"rollbackTo"});if(a>=b)throw new m("rollbackTo must be less than current codeVersion",{field:"rollbackTo"});const h=x(e,d);if(!r.existsSync(h))throw i(e,"ERROR","Project does not exist",{projectId:e,projectPath:h}),new D("Project does not exist",{projectId:e});const s=l.join(R.UPLOAD_PROJECT_DIR,e),o=`${e}-v${a}.zip`,t=l.join(s,o);if(!r.existsSync(t))throw i(e,"ERROR","Rollback version backup file does not exist",{projectId:e,rollbackTo:a,zipPath:t}),new D("Rollback version backup file does not exist",{projectId:e,rollbackTo:a});let u="";try{r.existsSync(s)||r.mkdirSync(s,{recursive:!0});const c=`${e}-v${b}.zip`;return u=l.join(s,c),r.existsSync(u)?i(e,"INFO","Current version backup already exists, skipping backup",{projectId:e,zipPath:u}):(await S(e,h,u),i(e,"INFO","Current version backed up",{projectId:e,zipPath:u})),i(e,"DEBUG","Start restoring project from backup",{projectId:e,rollbackToNum:a,rollbackZipPath:t}),await z(e,h,t),i(e,"INFO","Project rolled back successfully",{projectId:e,newVersion:b,toVersion:a,rollbackZipPath:t,elapsedMs:Date.now()-y}),{success:!0,message:"Project rolled back successfully",newVersion:b,rollbackTo:a}}catch(c){if(i(e,"ERROR","Failed to rollback project",{projectId:e,rollbackTo:a,error:c&&c.message,elapsedMs:Date.now()-y}),u&&r.existsSync(u))try{i(e,"INFO","Failed to rollback, trying to restore current version",{projectId:e,backupPath:u}),await z(e,h,u),i(e,"INFO","Current version restored",{projectId:e})}catch(f){i(e,"ERROR","Failed to restore current version",{projectId:e,error:f&&f.message})}throw c.isOperational?c:new E("Failed to rollback project",{projectId:e,rollbackTo:a,originalError:c&&c.message})}}export{T as specifiedFilesUpdate,C as allFilesUpdate,B as uploadSingleFile,$ as rollbackVersion};export default{specifiedFilesUpdate:T,allFilesUpdate:C,uploadSingleFile:B,rollbackVersion:$};
4
+ `;return{finalContent:n.join(m),changesCount:l}}function ie(e,d){return e===d?{finalContent:e,changesCount:0}:{finalContent:d,changesCount:-1}}async function T(e,d,n,g,F={}){const b=Date.now();if(!e)throw new h("Project ID cannot be empty",{field:"projectId"});if(d==null)throw new h("codeVersion cannot be empty",{field:"codeVersion"});const y=Number(d);if(!Number.isFinite(y))throw new h("codeVersion must be a number",{field:"codeVersion"});if(!Array.isArray(n))throw new h("files must be an array",{field:"files"});for(let s=0;s<n.length;s++){const a=n[s];if(!a||typeof a.operation!="string")throw new h(`files[${s}].operation cannot be empty`,{field:`files[${s}].operation`});if(!a.name||typeof a.name!="string")throw new h(`files[${s}].name cannot be empty`,{field:`files[${s}].name`});const i=a.operation.toLowerCase();if(!["create","delete","rename","modify"].includes(i))throw new h(`files[${s}].operation must be one of create, delete, rename or modify`,{field:`files[${s}].operation`});if(i==="rename"&&!a.renameFrom)throw new h(`files[${s}].renameFrom cannot be empty (rename operation requires)`,{field:`files[${s}].renameFrom`});if(i==="modify"&&typeof a.contents!="string")throw new h(`files[${s}].contents must be a string (modify operation requires)`,{field:`files[${s}].contents`})}const l=S(e,F);if(!r.existsSync(l))throw t(e,"ERROR","Project does not exist",{projectId:e,projectPath:l}),new D("Project does not exist",{projectId:e});let m="";try{const s=o.join(R.UPLOAD_PROJECT_DIR,e);r.existsSync(s)||r.mkdirSync(s,{recursive:!0});const a=`${e}-v${y}.zip`;m=o.join(s,a),t(e,"DEBUG","Start backing up project",{projectId:e,backupZipPath:m}),R.GIT_ENABLED||await O(e,l,m),t(e,"INFO","Project backed up successfully",{projectId:e,zipPath:m});try{t(e,"DEBUG","Start processing file operations",{projectId:e,filesCount:n.length});for(const i of n){const c=i.operation.toLowerCase(),f=i.name,u=o.normalize(f).replace(/^[\/\\]+/,""),w=o.join(l,u),k=o.resolve(w),p=o.resolve(l);if(!k.startsWith(p+o.sep)&&k!==p){t(e,"WARN","Unsafe file path, skipping",{filePath:u,resolvedPath:k});continue}switch(c){case"create":{if(i.isDir===!0)r.existsSync(w)?t(e,"INFO","Directory already exists, skipping creation",{filePath:u}):(await r.promises.mkdir(w,{recursive:!0}),t(e,"INFO","Directory created successfully",{filePath:u}));else{await r.promises.mkdir(o.dirname(w),{recursive:!0});const P=i.contents||"";await r.promises.writeFile(w,P,"utf8"),t(e,"INFO","File created successfully",{filePath:u})}break}case"delete":{r.existsSync(w)?(await r.promises.stat(w)).isDirectory()?(await r.promises.rm(w,{recursive:!0,force:!0}),t(e,"INFO","Directory deleted successfully",{filePath:u})):(await r.promises.unlink(w),t(e,"INFO","File deleted successfully",{filePath:u})):t(e,"WARN","File or directory to delete does not exist",{filePath:u});break}case"rename":{const P=i.renameFrom;if(!P||typeof P!="string"){t(e,"WARN","Rename operation missing renameFrom",{filePath:u});break}const v=o.normalize(P).replace(/^[\/\\]+/,""),E=o.join(l,v),N=o.resolve(E);if(!N.startsWith(p+o.sep)&&N!==p){t(e,"WARN","Unsafe rename source path, skipping",{renameFrom:v,resolvedPath:N});break}r.existsSync(E)?(await r.promises.mkdir(o.dirname(w),{recursive:!0}),await r.promises.rename(E,w),t(e,"INFO","File renamed successfully",{oldPath:v,newPath:u})):t(e,"WARN","File to rename does not exist",{renameFrom:v});break}case"modify":{if(!r.existsSync(w)){t(e,"WARN","File to modify does not exist",{filePath:u});break}const P=await r.promises.readFile(w,"utf8"),v=typeof i.contents=="string"?i.contents:"",{finalContent:E,changesCount:N}=V(P,v);if(N===0){t(e,"INFO","File content unchanged, skipping write",{filePath:u});break}await r.promises.writeFile(w,E,"utf8"),t(e,"INFO","File modified successfully",{filePath:u,changesCount:N});break}default:{t(e,"WARN","Unsupported operation type",{operation:c,filePath:u});break}}}return t(e,"INFO","Specified files updated successfully",{projectId:e,filesCount:n.length,elapsedMs:Date.now()-b}),{success:!0,message:"Specified files updated successfully",projectId:e,filesCount:n.length}}catch(i){throw t(e,"ERROR","Failed to process file operations",{projectId:e,error:i&&i.message,elapsedMs:Date.now()-b}),i}}catch(s){throw s.isOperational?s:new x("Failed to backup project",{projectId:e,originalError:s&&s.message})}}async function C(e,d,n,g,F={}){const b=Date.now();if(!e)throw new h("Project ID cannot be empty",{field:"projectId"});const y=Number(d);if(!Number.isFinite(y))throw new h("codeVersion must be a number",{field:"codeVersion"});if(!Array.isArray(n))throw new h("files must be an array",{field:"files"});const l=S(e,F);if(!r.existsSync(l))throw t(e,"ERROR","Project does not exist",{projectId:e,projectPath:l}),new D("Project does not exist",{projectId:e});let m="";try{const s=o.join(R.UPLOAD_PROJECT_DIR,e);r.existsSync(s)||r.mkdirSync(s,{recursive:!0});const a=`${e}-v${y}.zip`;m=o.join(s,a),t(e,"DEBUG","Start backing up project",{projectId:e,backupZipPath:m}),R.GIT_ENABLED||await O(e,l,m);try{t(e,"DEBUG","Start writing files",{projectId:e,filesCount:n.length});for(const i of n){if(!i||typeof i.name!="string")continue;const c=o.join(l,i.name);if(i.isDir===!0){r.existsSync(c)||(await r.promises.mkdir(c,{recursive:!0}),t(e,"INFO","Directory ensured",{filePath:i.name}));continue}if(i.renameFrom&&typeof i.renameFrom=="string"){const P=o.join(l,i.renameFrom);if(r.existsSync(P)){await r.promises.mkdir(o.dirname(c),{recursive:!0}),await r.promises.rename(P,c),t(e,"INFO","File renamed successfully",{projectId:e,oldPath:i.renameFrom,newPath:i.name});continue}}const f=i.binary===!0,u=i.binary===!1,w=!!i.sizeExceeded,k=typeof i.contents=="string"&&i.contents.length>0;if(f){if(r.existsSync(c)){t(e,"INFO","Binary file already exists, skipping write",{filePath:i.name});continue}if(k)try{await r.promises.mkdir(o.dirname(c),{recursive:!0});const P=Buffer.from(i.contents,"base64");await r.promises.writeFile(c,P),t(e,"INFO","Binary file written successfully",{filePath:i.name})}catch(P){t(e,"ERROR","Failed to write binary file",{filePath:i.name,error:P&&P.message})}else t(e,"WARN","Binary file does not exist and has no content, skipping",{filePath:i.name});continue}u&&(!w||w&&k)&&(await r.promises.mkdir(o.dirname(c),{recursive:!0}),await r.promises.writeFile(c,i.contents||"","utf8"))}}catch(i){throw t(e,"ERROR","Failed to write files",{projectId:e,error:i&&i.message,elapsedMs:Date.now()-b}),i}try{t(e,"DEBUG","Start cleaning missing files",{projectId:e});const i=new Set(n.filter(f=>f&&typeof f.name=="string").map(f=>o.normalize(f.name))),c=n.filter(f=>f&&typeof f.name=="string"&&f.isDir===!0);await L(l,i,R.TRAVERSE_EXCLUDE_DIRS||[]);for(const f of c){const u=o.join(l,f.name);r.existsSync(u)||(await r.promises.mkdir(u,{recursive:!0}),t(e,"INFO","Empty directory recreated",{dirPath:f.name}))}}catch(i){throw t(e,"ERROR","Failed to clean missing files, starting rollback",{projectId:e,error:i&&i.message,elapsedMs:Date.now()-b}),i}return t(e,"INFO","Files submitted successfully",{projectId:e,filesCount:n.length,elapsedMs:Date.now()-b}),{success:!0,message:"Files submitted successfully",projectId:e,restarted:!1}}catch(s){throw s.isOperational?s:new x("Failed to backup old version",{projectId:e,originalError:s&&s.message})}}async function B(e,d,n,g,F,b={}){const y=Date.now();if(!e)throw new h("Project ID cannot be empty",{field:"projectId"});const l=Number(d);if(!Number.isFinite(l))throw new h("codeVersion must be a number",{field:"codeVersion"});if(!n)throw new h("File cannot be empty",{field:"file"});if(!g||typeof g!="string")throw new h("File path cannot be empty",{field:"filePath"});const m=S(e,b);if(!r.existsSync(m))throw t(e,"ERROR","Project does not exist",{projectId:e,projectPath:m}),new D("Project does not exist",{projectId:e});const s=o.normalize(g).replace(/^[\/\\]+/,""),a=o.join(m,s),i=o.resolve(a),c=o.resolve(m);if(!i.startsWith(c))throw new h("File path is not safe, cannot exceed project directory",{field:"filePath",providedPath:g,resolvedPath:i});let f="";try{const u=o.join(R.UPLOAD_PROJECT_DIR,e);r.existsSync(u)||r.mkdirSync(u,{recursive:!0});const w=`${e}-v${l}.zip`;f=o.join(u,w),t(e,"DEBUG","Start backing up project",{projectId:e,backupZipPath:f}),R.GIT_ENABLED||await O(e,m,f),t(e,"INFO",`Project backed up: ${f}`,{projectId:e,zipPath:f});try{if(t(e,"DEBUG","Start writing uploaded file",{projectId:e,filePath:s}),await r.promises.mkdir(o.dirname(a),{recursive:!0}),!n.buffer)throw new h("File content format is incorrect, missing buffer",{field:"file"});if(t(e,"INFO","Prepare to write file",{targetPath:a,bufferLength:n.buffer.length,expectedSize:n.size,bufferIsBuffer:Buffer.isBuffer(n.buffer),sizeMatch:n.buffer.length===n.size}),await r.promises.writeFile(a,n.buffer),t(e,"INFO","File uploaded successfully",{projectId:e,filePath:s,targetPath:i,fileSize:n.buffer?n.buffer.length:0,elapsedMs:Date.now()-y}),!1)try{const p=await U(F,e);return t(e,"INFO","Restart development server successfully",{projectId:e,pid:p.pid,port:p.port}),{success:!0,message:"File uploaded and restarted development server successfully",projectId:e,filePath:s,targetPath:i,fileSize:n.buffer?n.buffer.length:0,pid:p.pid,port:p.port,restarted:!0}}catch(p){t(e,"ERROR","Failed to restart development server",{projectId:e,filePath:s,error:p&&p.message})}else return t(e,"INFO","File modification does not require restarting development server",{projectId:e,filePath:s}),{success:!0,message:"File uploaded successfully, no need to restart development server",projectId:e,restarted:!1}}catch(k){throw t(e,"ERROR","Failed to write file",{projectId:e,filePath:s,error:k&&k.message,elapsedMs:Date.now()-y}),k}}catch(u){throw u.isOperational?u:new x("Failed to backup project",{projectId:e,filePath:s,originalError:u&&u.message})}}async function A(e,d,n,g,F={}){const b=Date.now();if(!e)throw new h("Project ID cannot be empty",{field:"projectId"});const y=Number(d);if(!Number.isFinite(y))throw new h("codeVersion must be a number",{field:"codeVersion"});const l=Number(n);if(!Number.isFinite(l))throw new h("rollbackTo must be a number",{field:"rollbackTo"});if(l<0)throw new h("rollbackTo cannot be less than 0",{field:"rollbackTo"});if(l>=y)throw new h("rollbackTo must be less than current codeVersion",{field:"rollbackTo"});const m=S(e,F);if(!r.existsSync(m))throw t(e,"ERROR","Project does not exist",{projectId:e,projectPath:m}),new D("Project does not exist",{projectId:e});const s=o.join(R.UPLOAD_PROJECT_DIR,e),a=`${e}-v${l}.zip`,i=o.join(s,a);if(!r.existsSync(i))throw t(e,"ERROR","Rollback version backup file does not exist",{projectId:e,rollbackTo:l,zipPath:i}),new D("Rollback version backup file does not exist",{projectId:e,rollbackTo:l});let c="";try{r.existsSync(s)||r.mkdirSync(s,{recursive:!0});const f=`${e}-v${y}.zip`;return c=o.join(s,f),r.existsSync(c)?t(e,"INFO","Current version backup already exists, skipping backup",{projectId:e,zipPath:c}):(await O(e,m,c),t(e,"INFO","Current version backed up",{projectId:e,zipPath:c})),t(e,"DEBUG","Start restoring project from backup",{projectId:e,rollbackToNum:l,rollbackZipPath:i}),await z(e,m,i),t(e,"INFO","Project rolled back successfully",{projectId:e,newVersion:y,toVersion:l,rollbackZipPath:i,elapsedMs:Date.now()-b}),{success:!0,message:"Project rolled back successfully",newVersion:y,rollbackTo:l}}catch(f){if(t(e,"ERROR","Failed to rollback project",{projectId:e,rollbackTo:l,error:f&&f.message,elapsedMs:Date.now()-b}),c&&r.existsSync(c))try{t(e,"INFO","Failed to rollback, trying to restore current version",{projectId:e,backupPath:c}),await z(e,m,c),t(e,"INFO","Current version restored",{projectId:e})}catch(u){t(e,"ERROR","Failed to restore current version",{projectId:e,error:u&&u.message})}throw f.isOperational?f:new x("Failed to rollback project",{projectId:e,rollbackTo:l,originalError:f&&f.message})}}async function $(e,d,n,g,F,b={}){const y=Date.now();if(!e)throw new h("Project ID cannot be empty",{field:"projectId"});const l=Number(d);if(!Number.isFinite(l))throw new h("codeVersion must be a number",{field:"codeVersion"});if(!n||n.length===0)throw new h("Files cannot be empty",{field:"files"});if(!g||g.length!==n.length)throw new h("filePaths and files count mismatch",{field:"filePaths"});const m=S(e,b);if(!r.existsSync(m))throw t(e,"ERROR","Project does not exist",{projectId:e,projectPath:m}),new D("Project does not exist",{projectId:e});let s="";try{const a=o.join(R.UPLOAD_PROJECT_DIR,e);r.existsSync(a)||r.mkdirSync(a,{recursive:!0});const i=`${e}-v${l}.zip`;s=o.join(a,i),t(e,"DEBUG","Start backing up project",{projectId:e,backupZipPath:s}),R.GIT_ENABLED||await O(e,m,s),t(e,"INFO",`Project backed up: ${s}`,{projectId:e,zipPath:s});const c=[];for(let f=0;f<n.length;f++){const u=n[f],w=g[f];if(!u||!u.buffer){t(e,"WARN","Skip empty file",{index:f,filePath:w});continue}if(!w||typeof w!="string"){t(e,"WARN","Skip invalid filePath",{index:f,filePath:w});continue}const k=o.normalize(w).replace(/^[\/\\]+/,""),p=o.join(m,k),P=o.resolve(p),v=o.resolve(m);if(!P.startsWith(v)){t(e,"WARN","Skip unsafe file path",{filePath:w,resolvedTargetPath:P});continue}await r.promises.mkdir(o.dirname(p),{recursive:!0}),await r.promises.writeFile(p,u.buffer),c.push({filePath:k,size:u.buffer.length})}return t(e,"INFO","Batch files uploaded successfully",{projectId:e,fileCount:c.length,elapsedMs:Date.now()-y}),{success:!0,message:`${c.length} files uploaded successfully`,projectId:e,fileCount:c.length,files:c,restarted:!1}}catch(a){t(e,"ERROR","Batch upload failed, rolling back",{projectId:e,error:a&&a.message,elapsedMs:Date.now()-y});let i=null;if(s&&r.existsSync(s))try{await z(e,m,s),t(e,"INFO","Rollback completed after batch upload failure")}catch(c){i=c,t(e,"ERROR","Rollback failed",{error:c&&c.message})}throw i||a}}export{T as specifiedFilesUpdate,C as allFilesUpdate,B as uploadSingleFile,$ as uploadBatchFiles,A as rollbackVersion};export default{specifiedFilesUpdate:T,allFilesUpdate:C,uploadSingleFile:B,uploadBatchFiles:$,rollbackVersion:A};
@@ -1,4 +1,4 @@
1
- import I from"path";import F from"fs";import O from"../appConfig/index.js";import{log as c}from"../utils/log/logUtils.js";import{ValidationError as p,BusinessError as E,SystemError as d,ResourceError as G}from"../utils/error/errorHandler.js";import{resolveProjectPath as et}from"../utils/common/projectPathUtils.js";import{getGitInstance as f,isGitRepo as st,ensureGitRepo as w,ensureGitignore as at}from"../utils/git/gitUtils.js";function m(i){const{workspaceType:e,projectId:s,isolationContext:a,userId:t,cId:r}=i||{};if(!e||!["pageApp","taskAgent"].includes(e))throw new p("workspaceType is required and must be pageApp or taskAgent",{field:"workspaceType"});if(e==="taskAgent"){if(!t||!r)throw new p("taskAgent mode requires userId and cId",{field:"userId/cId"});const n=I.join(O.COMPUTER_WORKSPACE_DIR,String(t),String(r));if(!F.existsSync(n))throw new G("Computer workspace does not exist",{userId:t,cId:r});return{targetPath:n,logId:`computer:${t}:${r}`}}if(!s)throw new p("pageApp mode requires projectId",{field:"projectId"});const o=et(s,a||{});if(!F.existsSync(o))throw new G("Project does not exist",{projectId:s});return{targetPath:o,logId:s}}async function C(i={}){const{targetPath:e,logId:s}=m(i);if(st(e))return{success:!0,message:"Git repository already initialized",logId:s,alreadyExists:!0};try{const a=f(e);await a.init(),at(e);const t=O.GIT_DEFAULT_AUTHOR_NAME,r=O.GIT_DEFAULT_AUTHOR_EMAIL;return await a.addConfig("user.name",t,!1,"local"),await a.addConfig("user.email",r,!1,"local"),c(s,"INFO","Git repository initialized",{logId:s,targetPath:e}),{success:!0,message:"Git repository initialized successfully",logId:s,alreadyExists:!1}}catch(a){throw c(s,"ERROR","Failed to initialize Git repository",{logId:s,error:a.message}),new d("Failed to initialize Git repository",{originalError:a.message})}}async function _(i={}){const{targetPath:e,logId:s}=m(i);await w(e);try{const a=f(e),t=await a.status(),r=await a.raw(["status","--porcelain"]),o=[],n=[],l=[],h=[],y=[];if(r)for(const g of r.split(`
2
- `).filter(Boolean)){const u=g[0],b=g[1],R=g.substring(3);u==="M"?o.push(R):u==="A"?(o.push(R),l.push(R)):u==="D"?(o.push(R),h.push(R)):(u==="R"||u==="C")&&o.push(R),b==="M"?n.push(R):b==="D"?(n.push(R),h.push(R)):b==="?"&&y.push(R)}return{success:!0,logId:s,current:t.current,staged:o,modified:n,created:l,deleted:h,untracked:y,conflicted:t.conflicted,ahead:t.ahead,behind:t.behind,tracking:t.tracking}}catch(a){throw c(s,"ERROR","Failed to get Git status",{logId:s,error:a.message}),new d("Failed to get Git status",{originalError:a.message})}}async function S(i={}){const{message:e,files:s,authorName:a,authorEmail:t}=i;if(!e||typeof e!="string")throw new p("Commit message cannot be empty",{field:"message"});const{targetPath:r,logId:o}=m(i);await w(r);try{const n=f(r);if(Array.isArray(s)&&s.length>0){const y=s.filter(g=>F.existsSync(I.join(r,g)));y.length>0&&await n.add(y)}else await n.add("--all");const l=[];if(a||t){const y=a||O.GIT_DEFAULT_AUTHOR_NAME,g=t||O.GIT_DEFAULT_AUTHOR_EMAIL;l.push(`--author=${y} <${g}>`)}const h=await n.commit(e,l);return c(o,"INFO","Git commit successful",{logId:o,commitHash:h.commit,message:e}),{success:!0,message:"Commit successful",logId:o,commit:h.commit,summary:h.summary}}catch(n){if(n.message&&n.message.includes("nothing to commit"))return{success:!0,message:"Nothing to commit",logId:o,nothingToCommit:!0};throw c(o,"ERROR","Failed to commit",{logId:o,error:n.message}),new d("Failed to commit",{originalError:n.message})}}async function B(i={}){const{files:e}=i,{targetPath:s,logId:a}=m(i);await w(s);try{const t=f(s);return Array.isArray(e)&&e.length>0?await t.add(e):await t.add("--all"),c(a,"INFO","Git add successful",{logId:a,filesCount:e?e.length:"all"}),{success:!0,message:"Files staged successfully",logId:a}}catch(t){throw c(a,"ERROR","Failed to add files",{logId:a,error:t.message}),new d("Failed to add files",{originalError:t.message})}}async function $(i={}){const{files:e}=i,{targetPath:s,logId:a}=m(i);await w(s);try{const t=f(s);return Array.isArray(e)&&e.length>0?(await t.raw(["restore","--staged","--",...e]),c(a,"INFO","Git unstage specified files",{logId:a,files:e}),{success:!0,message:"Specified files unstaged successfully",logId:a,files:e}):(await t.raw(["restore","--staged","."]),c(a,"INFO","Git unstage all files",{logId:a}),{success:!0,message:"All files unstaged successfully",logId:a,files:"all"})}catch(t){throw c(a,"ERROR","Failed to unstage",{logId:a,error:t.message}),new d("Failed to unstage files",{originalError:t.message})}}async function rt(i,e){const s=new Set;for(const t of e){let r=I.dirname(t);for(;r&&r!==".";)s.add(r),r=I.dirname(r)}const a=[...s].sort((t,r)=>{const o=t.split(/[/\\]/).length;return r.split(/[/\\]/).length-o});for(const t of a){const r=I.join(i,t);try{(await F.promises.readdir(r)).length===0&&await F.promises.rmdir(r)}catch{}}}async function v(i={}){const{files:e}=i,{targetPath:s,logId:a}=m(i);await w(s);try{const t=f(s),r=await t.status(),o=new Set([...r.created]),n=Array.isArray(e)&&e.length>0?e:null,l=[],h=[];if(n)for(const g of n)o.has(g)?l.push(g):h.push(g);else{for(const u of r.created)l.push(u);const g=new Set([...r.staged,...r.modified,...r.deleted]);for(const u of g)o.has(u)||h.push(u)}if(h.length>0&&await t.raw(["restore","--staged","--worktree","--",...h]),l.length>0){await t.raw(["rm","--cached","-f","--",...l]);for(const g of l){const u=I.join(s,g);F.existsSync(u)&&await F.promises.unlink(u)}await rt(s,l)}const y=h.length+l.length;return c(a,"INFO","Git discard",{logId:a,trackedFiles:h.length,newFiles:l.length}),{success:!0,message:"Files discarded successfully",logId:a,discardedCount:y,trackedFiles:h,newFiles:l}}catch(t){throw c(a,"ERROR","Failed to discard",{logId:a,error:t.message}),new d("Failed to discard files",{originalError:t.message})}}async function D(i={}){const{maxCount:e=50,branch:s,skip:a=0}=i,{targetPath:t,logId:r}=m(i);await w(t);try{const o=f(t),n=Math.min(Math.max(1,e),500),l=Math.max(0,a),h=[];h.push("--reflog"),s&&h.push(s),h.push(`--max-count=${n}`),l>0&&h.push(`--skip=${l}`);const g=(await o.log(h)).all.map(u=>({hash:u.hash,date:u.date,message:u.message,author_name:u.author_name,author_email:u.author_email}));return{success:!0,logId:r,commits:g,total:g.length}}catch(o){throw c(r,"ERROR","Failed to get Git log",{logId:r,error:o.message}),new d("Failed to get Git log",{originalError:o.message})}}async function L(i={}){const{source:e="worktree",from:s,to:a,paths:t}=i,{targetPath:r,logId:o}=m(i);await w(r);try{const n=f(r);let l=[];switch(e){case"staged":l.push("--cached");break;case"commit":if(s&&a)l.push(`${s}..${a}`);else if(s)if((await n.raw(["log","--format=%P","-1",s])).trim())l.push(`${s}^..${s}`);else{const u=Array.isArray(t)&&t.length>0?["--",...t]:[],[b,R]=await Promise.all([n.raw(["diff-tree","-p",s,...u]),n.raw(["diff-tree","--numstat","-r",s,...u])]),N=[];let T=0,x=0;for(const tt of R.split(`
3
- `).filter(Boolean)){const A=tt.split(" ");if(A.length===3){const P=parseInt(A[0],10)||0,k=parseInt(A[1],10)||0;N.push({file:A[2],changes:P+k,insertions:P,deletions:k,binary:!1}),T+=P,x+=k}}return{success:!0,logId:o,source:e,diff:b,summary:{files:N,insertions:T,deletions:x}}}break;case"worktree":default:l.push("HEAD");break}Array.isArray(t)&&t.length>0&&l.push("--",...t);const[h,y]=await Promise.all([n.diff(l),n.diffSummary(l)]);return{success:!0,logId:o,source:e,diff:h,summary:{files:y.files.map(g=>({file:g.file,changes:g.changes,insertions:g.insertions,deletions:g.deletions,binary:g.binary})),insertions:y.insertions,deletions:y.deletions}}}catch(n){throw c(o,"ERROR","Failed to get Git diff",{logId:o,error:n.message}),new d("Failed to get Git diff",{originalError:n.message})}}async function M(i={}){const{ref:e="HEAD",filePath:s}=i;if(!s)throw new p("filePath is required",{field:"filePath"});const{targetPath:a,logId:t}=m(i);await w(a);try{const r=f(a);let o;if(e==="worktree"){const n=I.join(a,s);F.existsSync(n)?o=F.readFileSync(n,"utf-8"):o=""}else if(e==="staged"||e==="")try{o=await r.show([`:${s}`])}catch{o=""}else try{o=await r.show([`${e}:${s}`])}catch{o=""}return{success:!0,logId:t,filePath:s,ref:e,content:o}}catch(r){throw r instanceof G?r:(c(t,"ERROR","Failed to get file content",{logId:t,ref:e,filePath:s,error:r.message}),new d("Failed to get file content",{originalError:r.message}))}}async function H(i={}){const{target:e,mode:s="mixed"}=i;if(!e)throw new p("Reset target cannot be empty",{field:"target"});if(!["soft","mixed","hard"].includes(s))throw new p("Mode must be soft, mixed or hard",{field:"mode"});const{targetPath:a,logId:t}=m(i);await w(a);try{const r=f(a),o=await r.log({maxCount:1}),n=o.latest?o.latest.hash:null;return await r.reset([`--${s}`,e]),c(t,"INFO","Git reset successful",{logId:t,target:e,mode:s,previousHead:n}),{success:!0,message:`Reset (${s}) to ${e} successful`,logId:t,target:e,mode:s,previousHead:n}}catch(r){throw c(t,"ERROR","Failed to reset",{logId:t,target:e,mode:s,error:r.message}),new d("Failed to reset",{originalError:r.message})}}async function j(i={}){const{target:e}=i;if(!e)throw new p("Checkout target cannot be empty",{field:"target"});const{targetPath:s,logId:a}=m(i);await w(s);try{return await f(s).raw(["checkout",e,"--","."]),c(a,"INFO","Git checkout files successful",{logId:a,target:e}),{success:!0,message:`Checkout files from ${e} successful`,logId:a,target:e}}catch(t){throw c(a,"ERROR","Failed to checkout files",{logId:a,target:e,error:t.message}),new d("Failed to checkout files",{originalError:t.message})}}async function U(i={}){const{target:e}=i;if(!e)throw new p("Revert target cannot be empty",{field:"target"});const{targetPath:s,logId:a}=m(i);await w(s);try{const t=f(s),r=await t.status();if(!r.isClean())throw new E("\u5DE5\u4F5C\u533A\u6709\u672A\u63D0\u4EA4\u7684\u4FEE\u6539\uFF0C\u8BF7\u5148 commit \u6216 stash \u540E\u518D revert",{staged:r.staged,modified:r.modified});return await t.revert(e),c(a,"INFO","Git revert successful",{logId:a,target:e}),{success:!0,message:`Revert ${e} successful`,logId:a,target:e}}catch(t){if(t instanceof E)throw t;try{await git.raw(["revert","--abort"])}catch{}throw t.message&&t.message.includes("CONFLICT")?new E("Revert \u4EA7\u751F\u51B2\u7A81\uFF0C\u65E0\u6CD5\u81EA\u52A8\u5408\u5E76\uFF0C\u8BE5 commit \u6682\u4E0D\u652F\u6301 revert",{target:e}):(c(a,"ERROR","Failed to revert",{logId:a,target:e,error:t.message}),new d("Failed to revert",{originalError:t.message}))}}async function z(i={}){const{targetPath:e,logId:s}=m(i);await w(e);try{const t=await f(e).tags();return{success:!0,logId:s,tags:t.all,latest:t.latest}}catch(a){throw c(s,"ERROR","Failed to list tags",{logId:s,error:a.message}),new d("Failed to list tags",{originalError:a.message})}}async function q(i={}){const{tagName:e,message:s}=i;if(!e)throw new p("Tag name cannot be empty",{field:"tagName"});const{targetPath:a,logId:t}=m(i);await w(a);try{const r=f(a);return s?await r.addAnnotatedTag(e,s):await r.addTag(e),c(t,"INFO","Git tag created",{logId:t,tagName:e,annotated:!!s}),{success:!0,message:"Tag created successfully",logId:t,tagName:e}}catch(r){throw c(t,"ERROR","Failed to create tag",{logId:t,tagName:e,error:r.message}),new d("Failed to create tag",{originalError:r.message})}}async function W(i={}){const{tagName:e}=i;if(!e)throw new p("Tag name cannot be empty",{field:"tagName"});const{targetPath:s,logId:a}=m(i);await w(s);try{return await f(s).tag(["-d",e]),c(a,"INFO","Git tag deleted",{logId:a,tagName:e}),{success:!0,message:"Tag deleted successfully",logId:a,tagName:e}}catch(t){throw c(a,"ERROR","Failed to delete tag",{logId:a,tagName:e,error:t.message}),new d("Failed to delete tag",{originalError:t.message})}}async function K(i={}){const{targetPath:e,logId:s}=m(i);await w(e);try{const t=await f(e).branch();return{success:!0,logId:s,branches:t.branches,current:t.current}}catch(a){throw c(s,"ERROR","Failed to list branches",{logId:s,error:a.message}),new d("Failed to list branches",{originalError:a.message})}}async function V(i={}){const{branchName:e,startPoint:s}=i;if(!e)throw new p("Branch name cannot be empty",{field:"branchName"});const{targetPath:a,logId:t}=m(i);await w(a);try{const r=f(a);return s?await r.checkoutBranch(e,s):await r.checkoutLocalBranch(e),c(t,"INFO","Git branch created",{logId:t,branchName:e,startPoint:s}),{success:!0,message:"Branch created and switched to",logId:t,branchName:e}}catch(r){throw c(t,"ERROR","Failed to create branch",{logId:t,branchName:e,error:r.message}),new d("Failed to create branch",{originalError:r.message})}}async function J(i={}){const{branchName:e}=i;if(!e)throw new p("Branch name cannot be empty",{field:"branchName"});const{targetPath:s,logId:a}=m(i);await w(s);try{const t=f(s),r=await t.status();if(!r.isClean())throw new E("Working directory is not clean, please commit or stash your changes before switching branches",{staged:r.staged,modified:r.modified,untracked:r.not_added});return await t.checkout(e),c(a,"INFO","Git branch switched",{logId:a,branchName:e}),{success:!0,message:"Branch switched successfully",logId:a,branchName:e}}catch(t){throw t instanceof E?t:(c(a,"ERROR","Failed to switch branch",{logId:a,branchName:e,error:t.message}),new d("Failed to switch branch",{originalError:t.message}))}}async function Q(i={}){const{branchName:e,force:s=!1}=i;if(!e)throw new p("Branch name cannot be empty",{field:"branchName"});const{targetPath:a,logId:t}=m(i);await w(a);try{const r=f(a);if((await r.status()).current===e)throw new E("Cannot delete the current branch, please switch to another branch first");return s?await r.deleteLocalBranch(e,!0):await r.deleteLocalBranch(e),c(t,"INFO","Git branch deleted",{logId:t,branchName:e,force:s}),{success:!0,message:"Branch deleted successfully",logId:t,branchName:e}}catch(r){throw r instanceof E?r:(c(t,"ERROR","Failed to delete branch",{logId:t,branchName:e,error:r.message}),new d("Failed to delete branch",{originalError:r.message}))}}async function X(i={}){const{message:e,files:s}=i,{targetPath:a,logId:t}=m(i);await w(a);try{const r=f(a),o=["push"];return e&&o.push("-m",e),Array.isArray(s)&&s.length>0&&(await r.add(s),o.push("--",...s)),await r.stash(o),c(t,"INFO","Git stash push",{logId:t,stashMessage:e}),{success:!0,message:"Changes stashed successfully",logId:t}}catch(r){throw c(t,"ERROR","Failed to stash",{logId:t,error:r.message}),new d("Failed to stash changes",{originalError:r.message})}}async function Y(i={}){const{index:e,files:s}=i,{targetPath:a,logId:t}=m(i);await w(a);try{const r=f(a),o=await r.stashList().catch(()=>({all:[],total:0}));if((o.all&&o.all.length||o.total||0)===0)throw new E("No stash entries to restore");const l=e!=null?`stash@{${Number(e)}}`:"stash@{0}";return Array.isArray(s)&&s.length>0?(await r.raw(["checkout",l,"--",...s]),c(t,"INFO","Git stash pop (partial)",{logId:t,index:e,files:s}),{success:!0,message:"Stash restored (partial)",logId:t,index:e,files:s}):(await r.stash(["pop",l]),c(t,"INFO","Git stash pop",{logId:t,index:e}),{success:!0,message:"Stash restored successfully",logId:t})}catch(r){throw r instanceof E?r:(c(t,"ERROR","Failed to pop stash",{logId:t,index:e,error:r.message}),new d("Failed to pop stash",{originalError:r.message}))}}async function Z(i={}){const{targetPath:e,logId:s}=m(i);await w(e);try{const a=f(e),t=await a.stashList(),r=[];for(let o=0;o<t.all.length;o++){const n=t.all[o];let l=[];try{l=(await a.raw(["stash","show",`stash@{${o}}`,"--name-only"])).trim().split(`
4
- `).filter(Boolean)}catch{}r.push({index:o,hash:n.hash,message:n.message,date:n.date,files:l})}return{success:!0,logId:s,stashes:r,total:r.length}}catch(a){throw c(s,"ERROR","Failed to list stashes",{logId:s,error:a.message}),new d("Failed to list stashes",{originalError:a.message})}}export{C as init,_ as status,S as commit,B as add,$ as unstage,v as discard,D as logHistory,L as diff,M as fileContent,H as reset,j as checkout,U as revert,z as listTags,q as createTag,W as deleteTag,K as listBranches,V as createBranch,J as switchBranch,Q as deleteBranch,X as stashPush,Y as stashPop,Z as stashList};export default{init:C,status:_,commit:S,add:B,unstage:$,discard:v,logHistory:D,diff:L,fileContent:M,reset:H,checkout:j,revert:U,listTags:z,createTag:q,deleteTag:W,listBranches:K,createBranch:V,switchBranch:J,deleteBranch:Q,stashPush:X,stashPop:Y,stashList:Z};
1
+ import b from"path";import E from"fs";import O from"../appConfig/index.js";import{log as c}from"../utils/log/logUtils.js";import{ValidationError as R,BusinessError as I,SystemError as m,ResourceError as G}from"../utils/error/errorHandler.js";import{resolveProjectPath as st}from"../utils/common/projectPathUtils.js";import{getGitInstance as w,isGitRepo as at,ensureGitRepo as p,ensureGitignore as rt}from"../utils/git/gitUtils.js";function y(i){const{workspaceType:e,projectId:s,isolationContext:a,userId:t,cId:r}=i||{};if(!e||!["pageApp","taskAgent"].includes(e))throw new R("workspaceType is required and must be pageApp or taskAgent",{field:"workspaceType"});if(e==="taskAgent"){if(!t||!r)throw new R("taskAgent mode requires userId and cId",{field:"userId/cId"});const n=b.join(O.COMPUTER_WORKSPACE_DIR,String(t),String(r));if(!E.existsSync(n))throw new G("Computer workspace does not exist",{userId:t,cId:r});return{targetPath:n,logId:`computer:${t}:${r}`}}if(!s)throw new R("pageApp mode requires projectId",{field:"projectId"});const o=st(s,a||{});if(!E.existsSync(o))throw new G("Project does not exist",{projectId:s});return{targetPath:o,logId:s}}async function C(i={}){const{targetPath:e,logId:s}=y(i);if(at(e))return{success:!0,message:"Git repository already initialized",logId:s,alreadyExists:!0};try{const a=w(e);await a.init(),rt(e);const t=O.GIT_DEFAULT_AUTHOR_NAME,r=O.GIT_DEFAULT_AUTHOR_EMAIL;return await a.addConfig("user.name",t,!1,"local"),await a.addConfig("user.email",r,!1,"local"),c(s,"INFO","Git repository initialized",{logId:s,targetPath:e}),{success:!0,message:"Git repository initialized successfully",logId:s,alreadyExists:!1}}catch(a){throw c(s,"ERROR","Failed to initialize Git repository",{logId:s,error:a.message}),new m("Failed to initialize Git repository",{originalError:a.message})}}async function _(i={}){const{targetPath:e,logId:s}=y(i);await p(e);try{const a=w(e),t=await a.status(),r=await a.raw(["status","--porcelain"]),o=[],n=[],u=[],d=[],l=[];if(r)for(const f of r.split(`
2
+ `).filter(Boolean)){const F=f[0],h=f[1],g=f.substring(3);F==="M"?o.push(g):F==="A"?(o.push(g),u.push(g)):F==="D"?(o.push(g),d.push(g)):(F==="R"||F==="C")&&o.push(g),h==="M"?n.push(g):h==="D"?(n.push(g),d.push(g)):h==="?"&&l.push(g)}return{success:!0,logId:s,current:t.current,staged:o,modified:n,created:u,deleted:d,untracked:l,conflicted:t.conflicted,ahead:t.ahead,behind:t.behind,tracking:t.tracking}}catch(a){throw c(s,"ERROR","Failed to get Git status",{logId:s,error:a.message}),new m("Failed to get Git status",{originalError:a.message})}}async function S(i={}){const{message:e,files:s,authorName:a,authorEmail:t}=i;if(!e||typeof e!="string")throw new R("Commit message cannot be empty",{field:"message"});const{targetPath:r,logId:o}=y(i);await p(r);try{const n=w(r);if(Array.isArray(s)&&s.length>0){const l=s.filter(f=>E.existsSync(b.join(r,f)));l.length>0&&await n.add(l)}else await n.add("--all");const u=[];if(a||t){const l=a||O.GIT_DEFAULT_AUTHOR_NAME,f=t||O.GIT_DEFAULT_AUTHOR_EMAIL;u.push(`--author=${l} <${f}>`)}const d=await n.commit(e,u);return c(o,"INFO","Git commit successful",{logId:o,commitHash:d.commit,message:e}),{success:!0,message:"Commit successful",logId:o,commit:d.commit,summary:d.summary}}catch(n){if(n.message&&n.message.includes("nothing to commit"))return{success:!0,message:"Nothing to commit",logId:o,nothingToCommit:!0};throw c(o,"ERROR","Failed to commit",{logId:o,error:n.message}),new m("Failed to commit",{originalError:n.message})}}async function B(i={}){const{files:e}=i,{targetPath:s,logId:a}=y(i);await p(s);try{const t=w(s);return Array.isArray(e)&&e.length>0?await t.add(e):await t.add("--all"),c(a,"INFO","Git add successful",{logId:a,filesCount:e?e.length:"all"}),{success:!0,message:"Files staged successfully",logId:a}}catch(t){throw c(a,"ERROR","Failed to add files",{logId:a,error:t.message}),new m("Failed to add files",{originalError:t.message})}}async function $(i={}){const{files:e}=i,{targetPath:s,logId:a}=y(i);await p(s);try{const t=w(s);return Array.isArray(e)&&e.length>0?(await t.raw(["restore","--staged","--",...e]),c(a,"INFO","Git unstage specified files",{logId:a,files:e}),{success:!0,message:"Specified files unstaged successfully",logId:a,files:e}):(await t.raw(["restore","--staged","."]),c(a,"INFO","Git unstage all files",{logId:a}),{success:!0,message:"All files unstaged successfully",logId:a,files:"all"})}catch(t){throw c(a,"ERROR","Failed to unstage",{logId:a,error:t.message}),new m("Failed to unstage files",{originalError:t.message})}}async function v(i,e){const s=new Set;for(const t of e){let r=b.dirname(t);for(;r&&r!==".";)s.add(r),r=b.dirname(r)}const a=[...s].sort((t,r)=>{const o=t.split(/[/\\]/).length;return r.split(/[/\\]/).length-o});for(const t of a){const r=b.join(i,t);try{(await E.promises.readdir(r)).length===0&&await E.promises.rmdir(r)}catch{}}}async function D(i={}){const{files:e}=i,{targetPath:s,logId:a}=y(i);await p(s);try{const t=w(s),r=await t.status(),o=new Set([...r.created]),n=new Set([...r.not_added||[]]),u=Array.isArray(e)&&e.length>0?e:null,d=[],l=[],f=[];if(u)for(const h of u)o.has(h)?d.push(h):n.has(h)?l.push(h):f.push(h);else{for(const g of r.created)d.push(g);const h=new Set([...r.staged,...r.modified,...r.deleted]);for(const g of h)o.has(g)||f.push(g)}if(f.length>0)for(const h of f)try{await t.raw(["restore","--staged","--worktree","--",h])}catch{l.push(h)}if(d.length>0){await t.raw(["rm","--cached","-f","--",...d]);for(const h of d){const g=b.join(s,h);E.existsSync(g)&&await E.promises.unlink(g)}await v(s,d)}if(l.length>0){for(const h of l){const g=b.join(s,h);E.existsSync(g)&&await E.promises.unlink(g)}await v(s,l)}const F=f.length+d.length+l.length;return c(a,"INFO","Git discard",{logId:a,trackedFiles:f.length,newFiles:d.length,untrackedFiles:l.length}),{success:!0,message:"Files discarded successfully",logId:a,discardedCount:F,trackedFiles:f,newFiles:d,untrackedFiles:l}}catch(t){throw c(a,"ERROR","Failed to discard",{logId:a,error:t.message}),new m("Failed to discard files",{originalError:t.message})}}async function L(i={}){const{maxCount:e=50,branch:s,skip:a=0,filePath:t}=i,{targetPath:r,logId:o}=y(i);await p(r);try{const n=w(r),u=Math.min(Math.max(1,e),500),d=Math.max(0,a),l=[];t||l.push("--reflog"),s&&l.push(s),l.push(`--max-count=${u}`),d>0&&l.push(`--skip=${d}`),t&&l.push("--",t);const F=(await n.log(l)).all.map(h=>({hash:h.hash,date:h.date,message:h.message,author_name:h.author_name,author_email:h.author_email}));return{success:!0,logId:o,commits:F,total:F.length}}catch(n){throw c(o,"ERROR","Failed to get Git log",{logId:o,error:n.message}),new m("Failed to get Git log",{originalError:n.message})}}async function M(i={}){const{source:e="worktree",from:s,to:a,paths:t}=i,{targetPath:r,logId:o}=y(i);await p(r);try{const n=w(r);let u=[];switch(e){case"staged":u.push("--cached");break;case"commit":if(s&&a)u.push(`${s}..${a}`);else if(s)if((await n.raw(["log","--format=%P","-1",s])).trim())u.push(`${s}^..${s}`);else{const F=Array.isArray(t)&&t.length>0?["--",...t]:[],[h,g]=await Promise.all([n.raw(["diff-tree","-p",s,...F]),n.raw(["diff-tree","--numstat","-r",s,...F])]),N=[];let x=0,T=0;for(const et of g.split(`
3
+ `).filter(Boolean)){const A=et.split(" ");if(A.length===3){const k=parseInt(A[0],10)||0,P=parseInt(A[1],10)||0;N.push({file:A[2],changes:k+P,insertions:k,deletions:P,binary:!1}),x+=k,T+=P}}return{success:!0,logId:o,source:e,diff:h,summary:{files:N,insertions:x,deletions:T}}}break;case"worktree":default:u.push("HEAD");break}Array.isArray(t)&&t.length>0&&u.push("--",...t);const[d,l]=await Promise.all([n.diff(u),n.diffSummary(u)]);return{success:!0,logId:o,source:e,diff:d,summary:{files:l.files.map(f=>({file:f.file,changes:f.changes,insertions:f.insertions,deletions:f.deletions,binary:f.binary})),insertions:l.insertions,deletions:l.deletions}}}catch(n){throw c(o,"ERROR","Failed to get Git diff",{logId:o,error:n.message}),new m("Failed to get Git diff",{originalError:n.message})}}async function j(i={}){const{ref:e="HEAD",filePath:s}=i;if(!s)throw new R("filePath is required",{field:"filePath"});const{targetPath:a,logId:t}=y(i);await p(a);try{const r=w(a);let o;if(e==="worktree"){const n=b.join(a,s);E.existsSync(n)?o=E.readFileSync(n,"utf-8"):o=""}else if(e==="staged"||e==="")try{o=await r.show([`:${s}`])}catch{o=""}else try{o=await r.show([`${e}:${s}`])}catch{o=""}return{success:!0,logId:t,filePath:s,ref:e,content:o}}catch(r){throw r instanceof G?r:(c(t,"ERROR","Failed to get file content",{logId:t,ref:e,filePath:s,error:r.message}),new m("Failed to get file content",{originalError:r.message}))}}async function H(i={}){const{target:e,mode:s="mixed"}=i;if(!e)throw new R("Reset target cannot be empty",{field:"target"});if(!["soft","mixed","hard"].includes(s))throw new R("Mode must be soft, mixed or hard",{field:"mode"});const{targetPath:a,logId:t}=y(i);await p(a);try{const r=w(a),o=await r.log({maxCount:1}),n=o.latest?o.latest.hash:null;return await r.reset([`--${s}`,e]),c(t,"INFO","Git reset successful",{logId:t,target:e,mode:s,previousHead:n}),{success:!0,message:`Reset (${s}) to ${e} successful`,logId:t,target:e,mode:s,previousHead:n}}catch(r){throw c(t,"ERROR","Failed to reset",{logId:t,target:e,mode:s,error:r.message}),new m("Failed to reset",{originalError:r.message})}}async function U(i={}){const{target:e}=i;if(!e)throw new R("Checkout target cannot be empty",{field:"target"});const{targetPath:s,logId:a}=y(i);await p(s);try{return await w(s).raw(["checkout",e,"--","."]),c(a,"INFO","Git checkout files successful",{logId:a,target:e}),{success:!0,message:`Checkout files from ${e} successful`,logId:a,target:e}}catch(t){throw c(a,"ERROR","Failed to checkout files",{logId:a,target:e,error:t.message}),new m("Failed to checkout files",{originalError:t.message})}}async function z(i={}){const{target:e}=i;if(!e)throw new R("Revert target cannot be empty",{field:"target"});const{targetPath:s,logId:a}=y(i);await p(s);try{const t=w(s),r=await t.status();if(!r.isClean())throw new I("\u5DE5\u4F5C\u533A\u6709\u672A\u63D0\u4EA4\u7684\u4FEE\u6539\uFF0C\u8BF7\u5148 commit \u6216 stash \u540E\u518D revert",{staged:r.staged,modified:r.modified});return await t.revert(e),c(a,"INFO","Git revert successful",{logId:a,target:e}),{success:!0,message:`Revert ${e} successful`,logId:a,target:e}}catch(t){if(t instanceof I)throw t;try{await git.raw(["revert","--abort"])}catch{}throw t.message&&t.message.includes("CONFLICT")?new I("Revert \u4EA7\u751F\u51B2\u7A81\uFF0C\u65E0\u6CD5\u81EA\u52A8\u5408\u5E76\uFF0C\u8BE5 commit \u6682\u4E0D\u652F\u6301 revert",{target:e}):(c(a,"ERROR","Failed to revert",{logId:a,target:e,error:t.message}),new m("Failed to revert",{originalError:t.message}))}}async function q(i={}){const{targetPath:e,logId:s}=y(i);await p(e);try{const t=await w(e).tags();return{success:!0,logId:s,tags:t.all,latest:t.latest}}catch(a){throw c(s,"ERROR","Failed to list tags",{logId:s,error:a.message}),new m("Failed to list tags",{originalError:a.message})}}async function W(i={}){const{tagName:e,message:s}=i;if(!e)throw new R("Tag name cannot be empty",{field:"tagName"});const{targetPath:a,logId:t}=y(i);await p(a);try{const r=w(a);return s?await r.addAnnotatedTag(e,s):await r.addTag(e),c(t,"INFO","Git tag created",{logId:t,tagName:e,annotated:!!s}),{success:!0,message:"Tag created successfully",logId:t,tagName:e}}catch(r){throw c(t,"ERROR","Failed to create tag",{logId:t,tagName:e,error:r.message}),new m("Failed to create tag",{originalError:r.message})}}async function K(i={}){const{tagName:e}=i;if(!e)throw new R("Tag name cannot be empty",{field:"tagName"});const{targetPath:s,logId:a}=y(i);await p(s);try{return await w(s).tag(["-d",e]),c(a,"INFO","Git tag deleted",{logId:a,tagName:e}),{success:!0,message:"Tag deleted successfully",logId:a,tagName:e}}catch(t){throw c(a,"ERROR","Failed to delete tag",{logId:a,tagName:e,error:t.message}),new m("Failed to delete tag",{originalError:t.message})}}async function V(i={}){const{targetPath:e,logId:s}=y(i);await p(e);try{const t=await w(e).branch();return{success:!0,logId:s,branches:t.branches,current:t.current}}catch(a){throw c(s,"ERROR","Failed to list branches",{logId:s,error:a.message}),new m("Failed to list branches",{originalError:a.message})}}async function J(i={}){const{branchName:e,startPoint:s}=i;if(!e)throw new R("Branch name cannot be empty",{field:"branchName"});const{targetPath:a,logId:t}=y(i);await p(a);try{const r=w(a);return s?await r.checkoutBranch(e,s):await r.checkoutLocalBranch(e),c(t,"INFO","Git branch created",{logId:t,branchName:e,startPoint:s}),{success:!0,message:"Branch created and switched to",logId:t,branchName:e}}catch(r){throw c(t,"ERROR","Failed to create branch",{logId:t,branchName:e,error:r.message}),new m("Failed to create branch",{originalError:r.message})}}async function Q(i={}){const{branchName:e}=i;if(!e)throw new R("Branch name cannot be empty",{field:"branchName"});const{targetPath:s,logId:a}=y(i);await p(s);try{const t=w(s),r=await t.status();if(!r.isClean())throw new I("Working directory is not clean, please commit or stash your changes before switching branches",{staged:r.staged,modified:r.modified,untracked:r.not_added});return await t.checkout(e),c(a,"INFO","Git branch switched",{logId:a,branchName:e}),{success:!0,message:"Branch switched successfully",logId:a,branchName:e}}catch(t){throw t instanceof I?t:(c(a,"ERROR","Failed to switch branch",{logId:a,branchName:e,error:t.message}),new m("Failed to switch branch",{originalError:t.message}))}}async function X(i={}){const{branchName:e,force:s=!1}=i;if(!e)throw new R("Branch name cannot be empty",{field:"branchName"});const{targetPath:a,logId:t}=y(i);await p(a);try{const r=w(a);if((await r.status()).current===e)throw new I("Cannot delete the current branch, please switch to another branch first");return s?await r.deleteLocalBranch(e,!0):await r.deleteLocalBranch(e),c(t,"INFO","Git branch deleted",{logId:t,branchName:e,force:s}),{success:!0,message:"Branch deleted successfully",logId:t,branchName:e}}catch(r){throw r instanceof I?r:(c(t,"ERROR","Failed to delete branch",{logId:t,branchName:e,error:r.message}),new m("Failed to delete branch",{originalError:r.message}))}}async function Y(i={}){const{message:e,files:s}=i,{targetPath:a,logId:t}=y(i);await p(a);try{const r=w(a),o=["push"];return e&&o.push("-m",e),Array.isArray(s)&&s.length>0&&(await r.add(s),o.push("--",...s)),await r.stash(o),c(t,"INFO","Git stash push",{logId:t,stashMessage:e}),{success:!0,message:"Changes stashed successfully",logId:t}}catch(r){throw c(t,"ERROR","Failed to stash",{logId:t,error:r.message}),new m("Failed to stash changes",{originalError:r.message})}}async function Z(i={}){const{index:e,files:s}=i,{targetPath:a,logId:t}=y(i);await p(a);try{const r=w(a),o=await r.stashList().catch(()=>({all:[],total:0}));if((o.all&&o.all.length||o.total||0)===0)throw new I("No stash entries to restore");const u=e!=null?`stash@{${Number(e)}}`:"stash@{0}";return Array.isArray(s)&&s.length>0?(await r.raw(["checkout",u,"--",...s]),c(t,"INFO","Git stash pop (partial)",{logId:t,index:e,files:s}),{success:!0,message:"Stash restored (partial)",logId:t,index:e,files:s}):(await r.stash(["pop",u]),c(t,"INFO","Git stash pop",{logId:t,index:e}),{success:!0,message:"Stash restored successfully",logId:t})}catch(r){throw r instanceof I?r:(c(t,"ERROR","Failed to pop stash",{logId:t,index:e,error:r.message}),new m("Failed to pop stash",{originalError:r.message}))}}async function tt(i={}){const{targetPath:e,logId:s}=y(i);await p(e);try{const a=w(e),t=await a.stashList(),r=[];for(let o=0;o<t.all.length;o++){const n=t.all[o];let u=[];try{u=(await a.raw(["stash","show",`stash@{${o}}`,"--name-only"])).trim().split(`
4
+ `).filter(Boolean)}catch{}r.push({index:o,hash:n.hash,message:n.message,date:n.date,files:u})}return{success:!0,logId:s,stashes:r,total:r.length}}catch(a){throw c(s,"ERROR","Failed to list stashes",{logId:s,error:a.message}),new m("Failed to list stashes",{originalError:a.message})}}export{C as init,_ as status,S as commit,B as add,$ as unstage,D as discard,L as logHistory,M as diff,j as fileContent,H as reset,U as checkout,z as revert,q as listTags,W as createTag,K as deleteTag,V as listBranches,J as createBranch,Q as switchBranch,X as deleteBranch,Y as stashPush,Z as stashPop,tt as stashList};export default{init:C,status:_,commit:S,add:B,unstage:$,discard:D,logHistory:L,diff:M,fileContent:j,reset:H,checkout:U,revert:z,listTags:q,createTag:W,deleteTag:K,listBranches:V,createBranch:J,switchBranch:Q,deleteBranch:X,stashPush:Y,stashPop:Z,stashList:tt};
@@ -1 +1,2 @@
1
- import m from"fs";import h from"path";import N from"archiver";import I from"../../appConfig/index.js";import{log as r}from"../log/logUtils.js";import{ValidationError as g,SystemError as D}from"../error/errorHandler.js";const A=100*1024*1024,P=I.DOWNLOAD_MAX_FILE_SIZE_BYTES||A;async function O(f,u,a,c){const n=[],w=await m.promises.readdir(f,{withFileTypes:!0});w.sort((t,s)=>t.isDirectory()&&!s.isDirectory()?-1:!t.isDirectory()&&s.isDirectory()?1:t.name.toLowerCase().localeCompare(s.name.toLowerCase()));for(const t of w){const s=h.join(f,t.name);if(!(t.name.startsWith(".")&&t.name!==".gitignore"||(I.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(t.name))&&!(t.isDirectory()&&I.TRAVERSE_EXCLUDE_DIRS.includes(t.name)))if(t.isDirectory()){const e=await O(s,u,a,c);if(e.length===0){const l=u||f,p=h.relative(l,s).replace(/\\/g,"/");n.push({name:p,isDir:!0})}else n.push(...e)}else try{const e=u||f,l=h.relative(e,s).replace(/\\/g,"/"),p=t.isSymbolicLink();let o=null;if(c){const y=l.split("/").map(R=>encodeURIComponent(R)).join("/");o=`${c}/${y}`}const i={name:l,isDir:!1,fileProxyUrl:o,isLink:p};n.push(i)}catch(e){r(a,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${s}`,{error:e.message})}}return n}async function k(f,u,a,c,n=""){const w=await m.promises.readdir(h.join(f,n),{withFileTypes:!0});let t=0;for(const s of w){const d=n?h.join(n,s.name):s.name,e=d.split(h.sep).filter(Boolean);if(e.some(i=>i.startsWith(".")))continue;const l=e[e.length-1];if(u.includes(l)||e.some(i=>a.includes(i)))continue;const p=h.join(f,d);let o;try{o=await m.promises.lstat(p)}catch(i){r(c,"WARN","Error occurred when getting file stats, skipping",{filePath:d.replace(/\\/g,"/"),error:i.message});continue}o.isSymbolicLink()||o.nlink>1||(o.isDirectory()?t+=await k(f,u,a,c,d):o.isFile()&&(t+=o.size))}return t}async function $(f,u,a){const c=Date.now(),n=`computer:${f}:${u}`,w=I.COMPUTER_WORKSPACE_DIR;if(!f)throw new g("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!u)throw new g("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const t=String(f),s=String(u),d=h.join(w,t,s);if(!m.existsSync(d))return r(n,"INFO","Directory does not exist, returning empty list",{targetDir:d,userId:t,cId:s}),{files:[]};r(n,"DEBUG","Start getting user file list",{targetDir:d,userId:t,cId:s});try{const e=await O(d,d,n,a);return r(n,"INFO","User file list obtained successfully",{fileCount:e.length,targetDir:d,userId:t,cId:s,elapsedMs:Date.now()-c}),{files:e}}catch(e){throw r(n,"ERROR","Failed to get user file list",{targetDir:d,userId:t,cId:s,error:e.message,elapsedMs:Date.now()-c}),new D(`Failed to get file list: ${e.message}`,{targetDir:d,originalError:e.message})}}async function _(f,u,a){const c=Date.now(),n=`computer:${f}:${u}`,w=I.COMPUTER_WORKSPACE_DIR;if(!f)throw new g("userId cannot be empty",{field:"userId"});if(!u)throw new g("cId cannot be empty",{field:"cId"});if(!Array.isArray(a))throw new g("files must be an array",{field:"files"});const t=String(f),s=String(u),d=h.join(w,t,s);m.existsSync(d)||m.mkdirSync(d,{recursive:!0});for(let e=0;e<a.length;e++){const l=a[e];if(!l||typeof l.operation!="string")throw new g(`files[${e}].operation cannot be empty`,{field:`files[${e}].operation`});if(!l.name||typeof l.name!="string")throw new g(`files[${e}].name cannot be empty`,{field:`files[${e}].name`});const p=l.operation.toLowerCase();if(!["create","delete","rename","modify"].includes(p))throw new g(`files[${e}].operation must be one of create, delete, rename or modify`,{field:`files[${e}].operation`});if(p==="rename"&&!l.renameFrom)throw new g(`files[${e}].renameFrom cannot be empty (rename operation requires)`,{field:`files[${e}].renameFrom`});if(p==="modify"&&l.isDir!==!0&&typeof l.contents!="string")throw new g(`files[${e}].contents must be a string (modify operation requires)`,{field:`files[${e}].contents`})}r(n,"DEBUG","Start updating user files",{userId:t,cId:s,filesCount:a.length});try{for(const e of a){const l=e.operation.toLowerCase(),p=e.name,o=h.normalize(p).replace(/^[\/\\]+/,""),i=h.join(d,o),y=h.resolve(i),R=h.resolve(d);if(!y.startsWith(R+h.sep)&&y!==R){r(n,"WARN","File path is not secure, skipping",{filePath:o,resolvedPath:y});continue}switch(l){case"create":{if(e.isDir===!0){if(m.existsSync(i)){if((await m.promises.stat(i)).isFile())throw new g("Cannot create directory, file with the same name already exists",{filePath:o});r(n,"INFO","Directory already exists, skipping creation",{filePath:o});break}await m.promises.mkdir(i,{recursive:!0}),r(n,"INFO","Directory created successfully",{filePath:o});break}if(m.existsSync(i)){if((await m.promises.stat(i)).isDirectory())throw new g("Cannot create file, directory with the same name already exists",{filePath:o});r(n,"INFO","File already exists, skipping creation",{filePath:o});break}await m.promises.mkdir(h.dirname(i),{recursive:!0});const F=e.contents||"";await m.promises.writeFile(i,F,"utf8"),r(n,"INFO","File created successfully",{filePath:o});break}case"delete":{m.existsSync(i)?(await m.promises.stat(i)).isDirectory()?(await m.promises.rm(i,{recursive:!0,force:!0}),r(n,"INFO","Directory deleted successfully",{filePath:o})):(await m.promises.unlink(i),r(n,"INFO","File deleted successfully",{filePath:o})):r(n,"WARN","The file or directory to be deleted does not exist",{filePath:o});break}case"rename":{const F=e.renameFrom;if(!F||typeof F!="string"){r(n,"WARN","Rename operation missing renameFrom",{filePath:o});break}const E=h.normalize(F).replace(/^[\/\\]+/,""),S=h.join(d,E),b=h.resolve(S);if(!b.startsWith(R+h.sep)&&b!==R){r(n,"WARN","Source path is not secure, skipping rename",{sourcePath:E,targetPath:o});break}if(m.existsSync(S)){const C=(await m.promises.stat(S)).isDirectory();await m.promises.mkdir(h.dirname(i),{recursive:!0}),await m.promises.rename(S,i),r(n,"INFO",C?"Directory renamed successfully":"File renamed successfully",{sourcePath:E,targetPath:o})}else r(n,"WARN","The file or directory to be renamed does not exist",{sourcePath:E});break}case"modify":{if(!m.existsSync(i)){r(n,"WARN","The file to be modified does not exist",{filePath:o});break}if((await m.promises.stat(i)).isDirectory()){r(n,"INFO","The target is a directory, skipping modification",{filePath:o});break}const E=typeof e.contents=="string"?e.contents:"";if(await m.promises.readFile(i,"utf8")===E){r(n,"INFO","File content has no changes, skipping write",{filePath:o});break}await m.promises.writeFile(i,E,"utf8"),r(n,"INFO","File modified successfully",{filePath:o});break}default:{r(n,"WARN","Unsupported operation type",{operation:l,filePath:o});break}}}return r(n,"INFO","User files updated successfully",{userId:t,cId:s,filesCount:a.length,elapsedMs:Date.now()-c}),{success:!0,message:"User files updated successfully",userId:t,cId:s,filesCount:a.length}}catch(e){throw r(n,"ERROR","User files updated failed",{userId:t,cId:s,error:e.message,elapsedMs:Date.now()-c}),new D(`User files updated failed: ${e.message}`,{userId:t,cId:s,originalError:e.message})}}async function z(f,u,a,c){const n=Date.now(),w=`computer:${f}:${u}`,t=I.COMPUTER_WORKSPACE_DIR;if(!f)throw new g("userId cannot be empty",{field:"userId"});if(!u)throw new g("cId cannot be empty",{field:"cId"});if(!a)throw new g("file cannot be empty",{field:"file"});if(!c||typeof c!="string")throw new g("filePath cannot be empty",{field:"filePath"});const s=String(f),d=String(u),e=h.join(t,s,d);m.existsSync(e)||m.mkdirSync(e,{recursive:!0});const l=h.normalize(c).replace(/^[\/\\]+/,""),p=h.join(e,l),o=h.resolve(p),i=h.resolve(e);if(!o.startsWith(i+h.sep)&&o!==i)throw new g("File path is not secure, cannot exceed user directory",{field:"filePath",providedPath:c,resolvedPath:o});try{if(await m.promises.mkdir(h.dirname(p),{recursive:!0}),a.buffer)await m.promises.writeFile(p,a.buffer);else if(typeof a.contents=="string")await m.promises.writeFile(p,a.contents,"utf8");else throw new g("File content format is incorrect",{field:"file",hasBuffer:!!a.buffer,hasContents:typeof a.contents});return r(w,"INFO","File uploaded successfully",{userId:s,cId:d,filePath:l,targetPath:o,fileSize:a.buffer?a.buffer.length:a.contents?a.contents.length:0,elapsedMs:Date.now()-n}),{success:!0,message:"File uploaded successfully",fileSize:a.buffer?a.buffer.length:a.contents?a.contents.length:0}}catch(y){throw r(w,"ERROR","File upload failed",{userId:s,cId:d,filePath:l,error:y.message,elapsedMs:Date.now()-n}),new D(`File upload failed: ${y.message}`,{userId:s,cId:d,filePath:l,originalError:y.message})}}async function T(f,u,a,c){const n=Date.now(),w=`computer:${f}:${u}`;if(!f)throw new g("userId cannot be empty",{field:"userId"});if(!u)throw new g("cId cannot be empty",{field:"cId"});if(!Array.isArray(a))throw new g("files must be an array",{field:"files"});if(!Array.isArray(c))throw new g("filePaths must be an array",{field:"filePaths"});if(a.length!==c.length)throw new g(`File count (${a.length}) does not match path count (${c.length})`,{field:"filePaths"});r(w,"DEBUG","Start batch uploading files",{userId:f,cId:u,filesCount:a.length});const t=[];try{for(let e=0;e<a.length;e++){const l=a[e],p=c[e];if(!l){r(w,"WARN","Empty file object encountered in batch upload, skipping",{index:e,filePath:p}),t.push({success:!1,filePath:p,error:"Empty file object"});continue}if(!p||typeof p!="string"){r(w,"WARN","Invalid file path in batch upload, skipping",{index:e,originalname:l.originalname}),t.push({success:!1,filePath:p||"",originalname:l.originalname,error:"Invalid file path"});continue}try{const o=await z(f,u,l,p);t.push({success:!0,filePath:p,originalname:l.originalname,...o})}catch(o){r(w,"ERROR","Single file upload failed in batch upload",{filePath:p,originalname:l.originalname,error:o.message}),t.push({success:!1,filePath:p,originalname:l.originalname,error:o.message})}}const s=t.filter(e=>e.success).length,d=t.filter(e=>!e.success).length;return r(w,"INFO","Batch upload files completed",{userId:f,cId:u,totalCount:a.length,successCount:s,failCount:d,elapsedMs:Date.now()-n}),{success:!0,message:"Batch upload completed",totalCount:a.length,successCount:s,failCount:d,results:t}}catch(s){throw r(w,"ERROR","Batch upload files failed",{userId:f,cId:u,error:s.message,elapsedMs:Date.now()-n}),new D(`Batch upload files failed: ${s.message}`,{userId:f,cId:u,originalError:s.message})}}async function v(f,u){const a=Date.now(),c=`computer:${f}:${u}`,n=I.COMPUTER_WORKSPACE_DIR;if(!f)throw new g("userId cannot be empty",{field:"userId"});if(!u)throw new g("cId cannot be empty",{field:"cId"});if(!n)throw new D("COMPUTER_WORKSPACE_DIR is not configured, cannot create zip");const w=String(f),t=String(u),s=h.join(n,w,t);if(!m.existsSync(s)){const i=`${w}_${t}.zip`;r(c,"WARN","Workspace directory does not exist, returning empty zip",{targetDir:s,userId:w,cId:t,zipFileName:i});const y=N("zip",{zlib:{level:9}});return y.append(null,{name:`${w}_${t}/`,type:"directory"}),y.on("warning",R=>{if(R.code==="ENOENT")r(c,"WARN","Encountered file problem when creating empty zip",{message:R.message,code:R.code});else throw r(c,"ERROR","Encountered warning when creating empty zip",{message:R.message,code:R.code}),R}),y.on("error",R=>{r(c,"ERROR","Failed to create empty zip",{message:R.message})}),{archive:y,zipFileName:i}}const d=`${w}_${t}.zip`;r(c,"DEBUG","Start creating workspace directory zip",{targetDir:s,zipFileName:d});const e=N("zip",{zlib:{level:9}}),l=I.CONTENT_TRAVERSE_EXCLUDE_FILES||[],p=I.TRAVERSE_EXCLUDE_DIRS||[],o=await k(s,l,p,c);if(o>P){const i=P/1024/1024,y=(o/1024/1024).toFixed(2);throw r(c,"WARN","Download rejected due to oversized workspace",{targetDir:s,downloadableSize:o,maxSizeBytes:P}),new g(`Download failed: total file size ${y}MB exceeds limit ${i}MB`,{field:"downloadSize",downloadableSize:o,maxSizeBytes:P})}return e.directory(s,`${w}_${t}`,i=>{const y=i.name||"",R=y.split(/[\/\\]/).filter(Boolean);if(R.some(E=>E.startsWith(".")))return!1;const F=R[R.length-1];if(l.includes(F)||R.some(E=>p.includes(E)))return!1;try{const E=h.join(s,y),S=m.lstatSync(E);if(S.isSymbolicLink()||S.nlink>1)return!1}catch(E){return r(c,"WARN","Error occurred when detecting link file, skipping",{filePath:y,error:E.message}),!1}return i}),e.on("warning",i=>{if(i.code==="ENOENT")r(c,"WARN","Encountered file problem when creating zip",{message:i.message,code:i.code});else throw r(c,"ERROR","Encountered warning when creating zip",{message:i.message,code:i.code}),i}),e.on("error",i=>{r(c,"ERROR","Failed to create zip",{message:i.message,elapsedMs:Date.now()-a})}),e.on("end",()=>{r(c,"INFO","Workspace directory zip created successfully",{targetDir:s,zipFileName:d,elapsedMs:Date.now()-a})}),{archive:e,zipFileName:d}}export{$ as getFileList,_ as updateFiles,z as uploadFile,T as uploadFiles,v as downloadAllFiles};
1
+ import m from"fs";import h from"path";import z from"archiver";import I from"../../appConfig/index.js";import{log as s}from"../log/logUtils.js";import{ValidationError as g,SystemError as P}from"../error/errorHandler.js";const _=100*1024*1024,b=I.DOWNLOAD_MAX_FILE_SIZE_BYTES||_;async function N(d,u,a,c){const i=[],w=await m.promises.readdir(d,{withFileTypes:!0});w.sort((n,o)=>n.isDirectory()&&!o.isDirectory()?-1:!n.isDirectory()&&o.isDirectory()?1:n.name.toLowerCase().localeCompare(o.name.toLowerCase()));for(const n of w){const o=h.join(d,n.name);if(!(n.name.startsWith(".")&&n.name!==".gitignore"||(I.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(n.name))&&!(n.isDirectory()&&I.TRAVERSE_EXCLUDE_DIRS.includes(n.name)))if(n.isDirectory()){const e=await N(o,u,a,c);if(e.length===0){const f=u||d,p=h.relative(f,o).replace(/\\/g,"/");i.push({name:p,isDir:!0})}else i.push(...e)}else try{const e=u||d,f=h.relative(e,o).replace(/\\/g,"/"),p=n.isSymbolicLink();let t=null;if(c){const R=f.split("/").map(E=>encodeURIComponent(E)).join("/");t=`${c}/${R}`}const r={name:f,isDir:!1,fileProxyUrl:t,isLink:p};i.push(r)}catch(e){s(a,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${o}`,{error:e.message})}}return i}async function O(d,u,a,c,i=""){const w=await m.promises.readdir(h.join(d,i),{withFileTypes:!0});let n=0;for(const o of w){const l=i?h.join(i,o.name):o.name,e=l.split(h.sep).filter(Boolean);if(e.some(r=>r.startsWith(".")))continue;const f=e[e.length-1];if(u.includes(f)||e.some(r=>a.includes(r)))continue;const p=h.join(d,l);let t;try{t=await m.promises.lstat(p)}catch(r){s(c,"WARN","Error occurred when getting file stats, skipping",{filePath:l.replace(/\\/g,"/"),error:r.message});continue}t.isSymbolicLink()||t.nlink>1||(t.isDirectory()?n+=await O(d,u,a,c,l):t.isFile()&&(n+=t.size))}return n}async function $(d,u,a){const c=Date.now(),i=`computer:${d}:${u}`,w=I.COMPUTER_WORKSPACE_DIR;if(!d)throw new g("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!u)throw new g("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const n=String(d),o=String(u),l=h.join(w,n,o);if(!m.existsSync(l))return s(i,"INFO","Directory does not exist, returning empty list",{targetDir:l,userId:n,cId:o}),{files:[]};s(i,"DEBUG","Start getting user file list",{targetDir:l,userId:n,cId:o});try{const e=await N(l,l,i,a);return s(i,"INFO","User file list obtained successfully",{fileCount:e.length,targetDir:l,userId:n,cId:o,elapsedMs:Date.now()-c}),{files:e}}catch(e){throw s(i,"ERROR","Failed to get user file list",{targetDir:l,userId:n,cId:o,error:e.message,elapsedMs:Date.now()-c}),new P(`Failed to get file list: ${e.message}`,{targetDir:l,originalError:e.message})}}async function A(d,u,a){const c=Date.now(),i=`computer:${d}:${u}`,w=I.COMPUTER_WORKSPACE_DIR;if(!d)throw new g("userId cannot be empty",{field:"userId"});if(!u)throw new g("cId cannot be empty",{field:"cId"});if(!Array.isArray(a))throw new g("files must be an array",{field:"files"});const n=String(d),o=String(u),l=h.join(w,n,o);m.existsSync(l)||m.mkdirSync(l,{recursive:!0});for(let e=0;e<a.length;e++){const f=a[e];if(!f||typeof f.operation!="string")throw new g(`files[${e}].operation cannot be empty`,{field:`files[${e}].operation`});if(!f.name||typeof f.name!="string")throw new g(`files[${e}].name cannot be empty`,{field:`files[${e}].name`});const p=f.operation.toLowerCase();if(!["create","delete","rename","modify"].includes(p))throw new g(`files[${e}].operation must be one of create, delete, rename or modify`,{field:`files[${e}].operation`});if(p==="rename"&&!f.renameFrom)throw new g(`files[${e}].renameFrom cannot be empty (rename operation requires)`,{field:`files[${e}].renameFrom`});if(p==="modify"&&f.isDir!==!0&&typeof f.contents!="string")throw new g(`files[${e}].contents must be a string (modify operation requires)`,{field:`files[${e}].contents`})}s(i,"DEBUG","Start updating user files",{userId:n,cId:o,filesCount:a.length});try{for(const e of a){const f=e.operation.toLowerCase(),p=e.name,t=h.normalize(p).replace(/^[\/\\]+/,""),r=h.join(l,t),R=h.resolve(r),E=h.resolve(l);if(!R.startsWith(E+h.sep)&&R!==E){s(i,"WARN","File path is not secure, skipping",{filePath:t,resolvedPath:R});continue}switch(f){case"create":{if(e.isDir===!0){if(m.existsSync(r)){if((await m.promises.stat(r)).isFile())throw new g("Cannot create directory, file with the same name already exists",{filePath:t});s(i,"INFO","Directory already exists, skipping creation",{filePath:t});break}await m.promises.mkdir(r,{recursive:!0}),s(i,"INFO","Directory created successfully",{filePath:t});break}if(m.existsSync(r)){if((await m.promises.stat(r)).isDirectory())throw new g("Cannot create file, directory with the same name already exists",{filePath:t});s(i,"INFO","File already exists, skipping creation",{filePath:t});break}await m.promises.mkdir(h.dirname(r),{recursive:!0});const S=e.contents||"";await m.promises.writeFile(r,S,"utf8"),s(i,"INFO","File created successfully",{filePath:t});break}case"delete":{m.existsSync(r)?(await m.promises.stat(r)).isDirectory()?(await m.promises.rm(r,{recursive:!0,force:!0}),s(i,"INFO","Directory deleted successfully",{filePath:t})):(await m.promises.unlink(r),s(i,"INFO","File deleted successfully",{filePath:t})):s(i,"WARN","The file or directory to be deleted does not exist",{filePath:t});break}case"rename":{const S=e.renameFrom;if(!S||typeof S!="string"){s(i,"WARN","Rename operation missing renameFrom",{filePath:t});break}const y=h.normalize(S).replace(/^[\/\\]+/,""),D=h.join(l,y),F=h.resolve(D);if(!F.startsWith(E+h.sep)&&F!==E){s(i,"WARN","Source path is not secure, skipping rename",{sourcePath:y,targetPath:t});break}if(m.existsSync(D)){const C=(await m.promises.stat(D)).isDirectory();await m.promises.mkdir(h.dirname(r),{recursive:!0}),await m.promises.rename(D,r),s(i,"INFO",C?"Directory renamed successfully":"File renamed successfully",{sourcePath:y,targetPath:t})}else s(i,"WARN","The file or directory to be renamed does not exist",{sourcePath:y});break}case"modify":{if(!m.existsSync(r)){s(i,"WARN","The file to be modified does not exist",{filePath:t});break}if((await m.promises.stat(r)).isDirectory()){s(i,"INFO","The target is a directory, skipping modification",{filePath:t});break}const y=typeof e.contents=="string"?e.contents:"";if(await m.promises.readFile(r,"utf8")===y){s(i,"INFO","File content has no changes, skipping write",{filePath:t});break}await m.promises.writeFile(r,y,"utf8"),s(i,"INFO","File modified successfully",{filePath:t});break}default:{s(i,"WARN","Unsupported operation type",{operation:f,filePath:t});break}}}return s(i,"INFO","User files updated successfully",{userId:n,cId:o,filesCount:a.length,elapsedMs:Date.now()-c}),{success:!0,message:"User files updated successfully",userId:n,cId:o,filesCount:a.length}}catch(e){throw s(i,"ERROR","User files updated failed",{userId:n,cId:o,error:e.message,elapsedMs:Date.now()-c}),new P(`User files updated failed: ${e.message}`,{userId:n,cId:o,originalError:e.message})}}async function k(d,u,a,c){const i=Date.now(),w=`computer:${d}:${u}`,n=I.COMPUTER_WORKSPACE_DIR;if(!d)throw new g("userId cannot be empty",{field:"userId"});if(!u)throw new g("cId cannot be empty",{field:"cId"});if(!a)throw new g("file cannot be empty",{field:"file"});if(!c||typeof c!="string")throw new g("filePath cannot be empty",{field:"filePath"});const o=String(d),l=String(u),e=h.join(n,o,l);m.existsSync(e)||m.mkdirSync(e,{recursive:!0});const f=h.normalize(c).replace(/^[\/\\]+/,""),p=h.join(e,f),t=h.resolve(p),r=h.resolve(e);if(!t.startsWith(r+h.sep)&&t!==r)throw new g("File path is not secure, cannot exceed user directory",{field:"filePath",providedPath:c,resolvedPath:t});try{if(await m.promises.mkdir(h.dirname(p),{recursive:!0}),a.buffer)await m.promises.writeFile(p,a.buffer);else if(typeof a.contents=="string")await m.promises.writeFile(p,a.contents,"utf8");else throw new g("File content format is incorrect",{field:"file",hasBuffer:!!a.buffer,hasContents:typeof a.contents});return s(w,"INFO","File uploaded successfully",{userId:o,cId:l,filePath:f,targetPath:t,fileSize:a.buffer?a.buffer.length:a.contents?a.contents.length:0,elapsedMs:Date.now()-i}),{success:!0,message:"File uploaded successfully",fileSize:a.buffer?a.buffer.length:a.contents?a.contents.length:0}}catch(R){throw s(w,"ERROR","File upload failed",{userId:o,cId:l,filePath:f,error:R.message,elapsedMs:Date.now()-i}),new P(`File upload failed: ${R.message}`,{userId:o,cId:l,filePath:f,originalError:R.message})}}async function T(d,u,a,c){const i=Date.now(),w=`computer:${d}:${u}`;if(!d)throw new g("userId cannot be empty",{field:"userId"});if(!u)throw new g("cId cannot be empty",{field:"cId"});if(!Array.isArray(a))throw new g("files must be an array",{field:"files"});if(!Array.isArray(c))throw new g("filePaths must be an array",{field:"filePaths"});if(a.length!==c.length)throw new g(`File count (${a.length}) does not match path count (${c.length})`,{field:"filePaths"});s(w,"DEBUG","Start batch uploading files",{userId:d,cId:u,filesCount:a.length});const n=[];try{for(let e=0;e<a.length;e++){const f=a[e],p=c[e];if(!f){s(w,"WARN","Empty file object encountered in batch upload, skipping",{index:e,filePath:p}),n.push({success:!1,filePath:p,error:"Empty file object"});continue}if(!p||typeof p!="string"){s(w,"WARN","Invalid file path in batch upload, skipping",{index:e,originalname:f.originalname}),n.push({success:!1,filePath:p||"",originalname:f.originalname,error:"Invalid file path"});continue}try{const t=await k(d,u,f,p);n.push({success:!0,filePath:p,originalname:f.originalname,...t})}catch(t){s(w,"ERROR","Single file upload failed in batch upload",{filePath:p,originalname:f.originalname,error:t.message}),n.push({success:!1,filePath:p,originalname:f.originalname,error:t.message})}}const o=n.filter(e=>e.success).length,l=n.filter(e=>!e.success).length;return s(w,"INFO","Batch upload files completed",{userId:d,cId:u,totalCount:a.length,successCount:o,failCount:l,elapsedMs:Date.now()-i}),{success:!0,message:"Batch upload completed",totalCount:a.length,successCount:o,failCount:l,results:n}}catch(o){throw s(w,"ERROR","Batch upload files failed",{userId:d,cId:u,error:o.message,elapsedMs:Date.now()-i}),new P(`Batch upload files failed: ${o.message}`,{userId:d,cId:u,originalError:o.message})}}async function x(d,u){const a=Date.now(),c=`computer:${d}:${u}`,i=I.COMPUTER_WORKSPACE_DIR;if(!d)throw new g("userId cannot be empty",{field:"userId"});if(!u)throw new g("cId cannot be empty",{field:"cId"});if(!i)throw new P("COMPUTER_WORKSPACE_DIR is not configured, cannot create zip");const w=String(d),n=String(u),o=h.join(i,w,n);if(!m.existsSync(o)){const r=`${w}_${n}.zip`;s(c,"WARN","Workspace directory does not exist, returning empty zip",{targetDir:o,userId:w,cId:n,zipFileName:r});const R=z("zip",{zlib:{level:9}});return R.append(null,{name:`${w}_${n}/`,type:"directory"}),R.on("warning",E=>{if(E.code==="ENOENT")s(c,"WARN","Encountered file problem when creating empty zip",{message:E.message,code:E.code});else throw s(c,"ERROR","Encountered warning when creating empty zip",{message:E.message,code:E.code}),E}),R.on("error",E=>{s(c,"ERROR","Failed to create empty zip",{message:E.message})}),{archive:R,zipFileName:r}}const l=`${w}_${n}.zip`;s(c,"DEBUG","Start creating workspace directory zip",{targetDir:o,zipFileName:l});const e=z("zip",{zlib:{level:9}}),f=I.CONTENT_TRAVERSE_EXCLUDE_FILES||[],p=I.TRAVERSE_EXCLUDE_DIRS||[],t=await O(o,f,p,c);if(t>b){const r=b/1024/1024,R=(t/1024/1024).toFixed(2);throw s(c,"WARN","Download rejected due to oversized workspace",{targetDir:o,downloadableSize:t,maxSizeBytes:b}),new g(`Download failed: total file size ${R}MB exceeds limit ${r}MB`,{field:"downloadSize",downloadableSize:t,maxSizeBytes:b})}return e.directory(o,`${w}_${n}`,r=>{const R=r.name||"",E=R.split(/[\/\\]/).filter(Boolean);if(E.some(y=>y.startsWith(".")))return!1;const S=E[E.length-1];if(f.includes(S)||E.some(y=>p.includes(y)))return!1;try{const y=h.join(o,R),D=m.lstatSync(y);if(D.isSymbolicLink()||D.nlink>1)return!1}catch(y){return s(c,"WARN","Error occurred when detecting link file, skipping",{filePath:R,error:y.message}),!1}return r}),e.on("warning",r=>{if(r.code==="ENOENT")s(c,"WARN","Encountered file problem when creating zip",{message:r.message,code:r.code});else throw s(c,"ERROR","Encountered warning when creating zip",{message:r.message,code:r.code}),r}),e.on("error",r=>{s(c,"ERROR","Failed to create zip",{message:r.message,elapsedMs:Date.now()-a})}),e.on("end",()=>{s(c,"INFO","Workspace directory zip created successfully",{targetDir:o,zipFileName:l,elapsedMs:Date.now()-a})}),{archive:e,zipFileName:l}}async function W(d,u,a=200){const c=Date.now(),i=`computer:${d}:${u}`;if(!d)throw new g("userId cannot be empty",{field:"userId"});if(!u)throw new g("cId cannot be empty",{field:"cId"});const w=String(d),n=String(u),o=I.COMPUTER_LOG_DIR;if(!o)return s(i,"WARN","COMPUTER_LOG_DIR is not configured"),{fileName:null,fileSize:0,lines:[]};const l=h.join(o,w,n);if(!m.existsSync(l))return s(i,"DEBUG","Log directory does not exist",{logDir:l}),{fileName:null,fileSize:0,lines:[]};const f=(await m.promises.readdir(l)).filter(y=>y.endsWith(".log"));if(f.length===0)return s(i,"DEBUG","No log file found",{logDir:l}),{fileName:null,fileSize:0,lines:[]};const p=[];for(const y of f){const D=h.join(l,y),F=await m.promises.stat(D);p.push({name:y,fullPath:D,mtime:F.mtimeMs,size:F.size})}p.sort((y,D)=>D.mtime-y.mtime);const t=p[0],R=(await m.promises.readFile(t.fullPath,"utf8")).split(`
2
+ `).filter(y=>y.length>0),E=Math.max(1,a),S=R.slice(-E);return s(i,"DEBUG","Get latest logs",{fileName:t.name,fileSize:t.size,totalLines:R.length,returnedLines:S.length,elapsedMs:Date.now()-c}),{fileName:t.name,fileSize:t.size,lines:S}}export{$ as getFileList,A as updateFiles,k as uploadFile,T as uploadFiles,x as downloadAllFiles,W as getLatestLogs};
@@ -1 +1,2 @@
1
- import t from"fs";import a from"path";import{exec as tt}from"child_process";import X from"../../appConfig/index.js";import{extractZip as B}from"../common/zipUtils.js";import{ValidationError as k,SystemError as U,FileError as Z}from"../error/errorHandler.js";import{log as o}from"../log/logUtils.js";import{ensurePrimaryAgentDirs as Y,syncAgents as V}from"../common/AgentWorkspaceUtils.js";function Q(e){if(!e)return[];if(Array.isArray(e))return e.map(i=>typeof i=="string"?i.trim():"").filter(Boolean);if(typeof e=="string"){const i=e.trim();if(!i)return[];try{const s=JSON.parse(i);if(Array.isArray(s))return s.map(w=>typeof w=="string"?w.trim():"").filter(Boolean)}catch{}return[i]}return[]}async function I(e,i,s){let w;try{w=await fetch(e)}catch(N){throw new Z(`Failed to download skill zip from url: ${e}`,{url:e,reason:N.message})}if(!w.ok)throw new Z(`Failed to download skill zip from url: ${e}`,{url:e,status:w.status,statusText:w.statusText});const u=w.headers.get("content-type")||"";u&&!u.includes("zip")&&!u.includes("octet-stream")&&o(s,"WARN","Downloaded skill url content-type is not typical zip",{url:e,contentType:u});const n=await w.arrayBuffer(),x=Buffer.from(n);await t.promises.writeFile(i,x)}async function K(e="computer"){const i=X.COMPUTER_WORKSPACE_DIR;if(!i)throw new k("COMPUTER_WORKSPACE_DIR configuration does not exist",{field:"COMPUTER_WORKSPACE_DIR"});return t.existsSync(i)||(await t.promises.mkdir(i,{recursive:!0}),o(e,"INFO","Created user workspace root directory",{workspaceRoot:i})),i}async function H(e,i){const s=a.join(e,i);if(t.existsSync(s)&&(await t.promises.lstat(s)).isDirectory())return s;const w=await t.promises.readdir(e,{withFileTypes:!0});for(const u of w){if(!u.isDirectory())continue;const n=a.join(e,u.name),x=a.join(n,i);if(t.existsSync(x)&&(await t.promises.lstat(x)).isDirectory())return x}return null}async function ht(e){return H(e,"skills")}const et=".dynamic_add.lock";function it(e){const i=a.join(e,et);return t.existsSync(i)&&t.statSync(i).isFile()}async function T(e){t.existsSync(e)&&await t.promises.rm(e,{recursive:!0,force:!0})}async function W(e,i){try{await t.promises.rename(e,i)}catch(s){if(s.code==="EXDEV"){async function w(u,n){if((await t.promises.lstat(u)).isDirectory()){await t.promises.mkdir(n,{recursive:!0});const N=await t.promises.readdir(u);for(const h of N)await w(a.join(u,h),a.join(n,h))}else await t.promises.copyFile(u,n)}await w(e,i),await t.promises.rm(e,{recursive:!0,force:!0})}else throw s}}async function st(e,i,s,w,u,n){const x=i&&i.trim(),N=s&&s.trim(),h=w&&w.trim(),l=Array.isArray(u)&&u.length>0;if(!x&&!N&&!h&&!l)return;const d=a.join(e,".claude");try{if(t.existsSync(d)||await t.promises.mkdir(d,{recursive:!0}),x)try{const m={mcpServers:JSON.parse(i)},S=a.join(e,".mcp.json");await t.promises.writeFile(S,JSON.stringify(m,null,2),"utf-8"),o(n,"INFO","Written .mcp.json to workspace root")}catch(m){o(n,"WARN","Failed to parse/write mcpServersConfig, skipping",{error:m.message})}const p={};if(N)try{p.hooks=JSON.parse(s)}catch(m){o(n,"WARN","Failed to parse hooksConfig, skipping",{error:m.message})}if(h)try{p.permissions=JSON.parse(w)}catch(m){o(n,"WARN","Failed to parse permissionsConfig, skipping",{error:m.message})}if(Object.keys(p).length>0){const m=a.join(d,"settings.json");await t.promises.writeFile(m,JSON.stringify(p,null,2),"utf-8"),o(n,"INFO","Written .claude/settings.json",{keys:Object.keys(p)})}if(l){const m=a.join(d,"hooks");t.existsSync(m)||await t.promises.mkdir(m,{recursive:!0});for(const S of u){if(!S||!S.path||!S.content)continue;const c=a.normalize(S.path);if(c.startsWith("..")||a.isAbsolute(c)){o(n,"WARN","Hook script path contains traversal, skipping",{path:S.path});continue}const y=a.join(d,c),z=a.dirname(y);t.existsSync(z)||await t.promises.mkdir(z,{recursive:!0}),await t.promises.writeFile(y,S.content,"utf-8"),await t.promises.chmod(y,493),o(n,"INFO","Written hook script",{path:S.path})}}}catch(p){o(n,"WARN","Failed to write .claude/settings or .mcp.json or hook scripts, not blocking workspace creation",{error:p.message})}}async function at(e,i,s,w,u,n,x,N){const h=Date.now(),l=`computer:${e}:${i}`,d=Q(w),p=[],m=[],S=new Set;if(!e)throw new k("userId cannot be empty",{field:"userId"});if(!i)throw new k("cId cannot be empty",{field:"cId"});const c=await K(l),y=a.join(c,String(e),String(i),".tmp"),z=a.join(c,String(e),String(i)),{skillsDir:f,agentsDir:j,agentTypes:A}=await Y(z);t.existsSync(z)||await t.promises.mkdir(z,{recursive:!0});const D=a.join(y,`preserved_skills_${Date.now()}_${Math.round(Math.random()*1e6)}`);if(t.existsSync(f)){const F=(await t.promises.readdir(f,{withFileTypes:!0})).filter(O=>O.isDirectory()&&it(a.join(f,O.name)));if(F.length>0){await t.promises.mkdir(D,{recursive:!0});for(const O of F){const g=a.join(f,O.name),P=a.join(D,O.name);await W(g,P)}o(l,"INFO","\u4FDD\u7559\u542B .dynamic_add.lock \u7684 skill",{preserved:F.map(O=>O.name)})}}if(await T(f),await T(j),await t.promises.mkdir(f,{recursive:!0}),await t.promises.mkdir(j,{recursive:!0}),t.existsSync(D)){const r=await t.promises.readdir(D,{withFileTypes:!0});for(const F of r)if(F.isDirectory()){const O=a.join(D,F.name),g=a.join(f,F.name);await W(O,g)}await T(D)}const _=t.existsSync(f),M=t.existsSync(j);o(l,"INFO","Deleted old skills and agents directories completed",{userId:e,cId:i,targetSkillsDir:f,targetAgentsDir:j,agentTypes:A,skillsExists:_,agentsExists:M});const E=a.join(z,".mcp.json");t.existsSync(E)&&await t.promises.unlink(E);const b=a.join(z,".claude","settings.json");if(t.existsSync(b)&&await t.promises.unlink(b),await st(z,u,x,n,N,l),!s&&d.length===0)return await V(z),o(l,"INFO","Created workspace (no uploaded file, no skills and agents)",{userId:e,cId:i,workspaceRoot:c,skillsDir:null,agentsDir:null,agentTypes:A,elapsedMs:Date.now()-h}),{message:"Workspace created (no uploaded file, no skills and agents)",workspaceRoot:c};if(s){if(!s.path)throw new k("Uploaded file has no valid path",{field:"file.path"});if(a.extname(s.originalname||s.filename||"").toLowerCase()!==".zip")throw new k("Only zip files are supported",{field:"file",originalName:s.originalname})}o(l,"DEBUG","Start processing workspace resources",{userId:e,cId:i,workspaceRoot:c,hasUploadedZip:!!s,skillUrlsCount:d.length});try{t.existsSync(y)||await t.promises.mkdir(y,{recursive:!0});const r=[];if(s){const g=a.join(y,`skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);m.push(g),await t.promises.mkdir(g,{recursive:!0}),o(l,"DEBUG","Start extracting uploaded zip file",{extractRoot:g}),await B(s.path,g),o(l,"DEBUG","Uploaded zip file extracted successfully",{extractRoot:g});const P=await H(g,"skills"),$=await H(g,"agents");if(P){await t.promises.mkdir(f,{recursive:!0});const v=await t.promises.readdir(P,{withFileTypes:!0});for(const C of v){if(!C.isDirectory())continue;const G=a.join(P,C.name),L=a.join(f,C.name);t.existsSync(L)&&await T(L),await W(G,L),S.add(C.name)}r.push("skills"),o(l,"INFO","skills updated to workspace",{userId:e,cId:i,workspaceRoot:c,targetSkillsDir:f,agentTypes:A})}else o(l,"INFO","skills directory not found in uploaded zip, skipping",{userId:e,cId:i,extractRoot:g});$?(await T(j),await W($,j),r.push("agents"),o(l,"INFO","agents updated to workspace",{userId:e,cId:i,workspaceRoot:c,targetAgentsDir:j,agentTypes:A})):o(l,"INFO","agents directory not found in uploaded zip, skipping",{userId:e,cId:i,extractRoot:g})}for(let g=0;g<d.length;g+=1){const P=d[g],$=a.join(y,`skill_url_${Date.now()}_${g}_${Math.round(Math.random()*1e6)}.zip`);p.push($);const v=a.join(y,`skill_url_extract_${Date.now()}_${g}_${Math.round(Math.random()*1e6)}`);m.push(v),await t.promises.mkdir(v,{recursive:!0}),o(l,"INFO","Start download skill zip from url",{userId:e,cId:i,skillUrl:P}),await I(P,$,l),o(l,"INFO","Skill zip downloaded, start extracting",{userId:e,cId:i,skillUrl:P,downloadedZipPath:$}),await B($,v);const G=(await t.promises.readdir(v,{withFileTypes:!0})).filter(R=>R.isDirectory()&&!R.name.startsWith(".")),q=G.find(R=>R.name==="skills")?(await t.promises.readdir(a.join(v,"skills"),{withFileTypes:!0})).filter(R=>R.isDirectory()&&!R.name.startsWith(".")).map(R=>({name:R.name,sourcePath:a.join(v,"skills",R.name)})):G.map(R=>({name:R.name,sourcePath:a.join(v,R.name)}));if(q.length===0){o(l,"WARN","No skill directory found after extracting skill url zip",{userId:e,cId:i,skillUrl:P,extractRoot:v});continue}await t.promises.mkdir(f,{recursive:!0});for(const R of q){const J=a.join(f,R.name);t.existsSync(J)&&await T(J),await W(R.sourcePath,J),S.add(R.name),o(l,"INFO","Skill from url updated to workspace",{userId:e,cId:i,skillUrl:P,skillName:R.name,destSkillPath:J})}r.includes("skills")||r.push("skills")}r.length===0&&o(l,"WARN","No valid skills or agents directories found",{userId:e,cId:i,hasUploadedZip:!!s,skillUrlsCount:d.length});const F=Array.from(S),O=r.length>0?`Workspace created successfully, ${r.join(" and ")} updated`:"Workspace created successfully (skills and agents directories not found)";return o(l,"INFO",O,{userId:e,cId:i,updatedDirs:r,updatedSkills:F,agentTypes:A,elapsedMs:Date.now()-h}),await V(z),{message:O,workspaceRoot:c,updatedSkills:F}}catch(r){throw o(l,"ERROR","Failed to process workspace resources",{userId:e,cId:i,error:r.message,elapsedMs:Date.now()-h}),r instanceof k||r instanceof Z||r instanceof U?r:new U(`Failed to create workspace: ${r.message}`,{userId:e,cId:i})}finally{try{for(const r of m)t.existsSync(r)&&await t.promises.rm(r,{recursive:!0,force:!0})}catch(r){o(l,"WARN","Failed to clean up temporary extracted zip",{error:r.message})}for(const r of p)try{t.existsSync(r)&&await t.promises.unlink(r)}catch(F){o(l,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:r,error:F.message})}try{s&&s.path&&t.existsSync(s.path)&&await t.promises.unlink(s.path)}catch(r){o(l,"WARN","Failed to clean up uploaded zip file",{tempZipPath:s?.path,error:r.message})}}}async function ot(e,i,s,w){const u=Date.now(),n=`computer:${e}:${i}`,x=Q(w),N=[],h=[];if(!e)throw new k("userId cannot be empty",{field:"userId"});if(!i)throw new k("cId cannot be empty",{field:"cId"});if(!s&&x.length===0)throw new k("file or skillUrls cannot both be empty",{field:"file|skillUrls"});if(s){if(!s.path)throw new k("Uploaded file has no valid path",{field:"file.path"});if(a.extname(s.originalname||s.filename||"").toLowerCase()!==".zip")throw new k("Only zip files are supported",{field:"file",originalName:s?.originalname})}const l=await K(n),d=a.join(l,String(e),String(i),".tmp"),p=a.join(l,String(e),String(i)),{skillsDir:m,agentTypes:S}=await Y(p);try{t.existsSync(p)||await t.promises.mkdir(p,{recursive:!0}),t.existsSync(m)||await t.promises.mkdir(m,{recursive:!0}),t.existsSync(d)||await t.promises.mkdir(d,{recursive:!0});const c=[],y=new Set;if(s){const f=a.join(d,`skill_push_${Date.now()}_${Math.round(Math.random()*1e6)}`);h.push(f),await t.promises.mkdir(f,{recursive:!0}),o(n,"DEBUG","Start extracting skill zip file",{extractRoot:f}),await B(s.path,f),o(n,"DEBUG","Skill zip file extracted successfully",{extractRoot:f});const j=await H(f,"skills");if(!j)o(n,"WARN","skills directory not found in uploaded zip",{userId:e,cId:i,extractRoot:f});else{const D=(await t.promises.readdir(j,{withFileTypes:!0})).filter(_=>_.isDirectory()&&!_.name.startsWith("."));if(D.length===0)o(n,"WARN","skills directory in uploaded zip has no skill subdirectories",{userId:e,cId:i,skillsDir:j});else for(const _ of D){const M=a.join(j,_.name),E=a.join(m,_.name);t.existsSync(E)&&await T(E),await W(M,E),y.add(_.name),o(n,"INFO","skill pushed to workspace from uploaded zip",{userId:e,cId:i,skillName:_.name,destSkillPath:E})}}}for(let f=0;f<x.length;f+=1){const j=x[f],A=a.join(d,`skill_push_url_${Date.now()}_${f}_${Math.round(Math.random()*1e6)}.zip`);N.push(A);const D=a.join(d,`skill_push_url_extract_${Date.now()}_${f}_${Math.round(Math.random()*1e6)}`);h.push(D),await t.promises.mkdir(D,{recursive:!0}),o(n,"INFO","Start download skill zip for push from url",{userId:e,cId:i,skillUrl:j}),await I(j,A,n),await B(A,D);const M=(await t.promises.readdir(D,{withFileTypes:!0})).filter(r=>r.isDirectory()&&!r.name.startsWith(".")),b=M.find(r=>r.name==="skills")?(await t.promises.readdir(a.join(D,"skills"),{withFileTypes:!0})).filter(r=>r.isDirectory()&&!r.name.startsWith(".")).map(r=>({name:r.name,sourcePath:a.join(D,"skills",r.name)})):M.map(r=>({name:r.name,sourcePath:a.join(D,r.name)}));if(b.length===0){o(n,"WARN","No skill directory found after extracting push skill url zip",{userId:e,cId:i,skillUrl:j,extractRoot:D});continue}for(const r of b){const F=a.join(m,r.name);t.existsSync(F)&&await T(F),await W(r.sourcePath,F),y.add(r.name),o(n,"INFO","skill pushed to workspace from url zip",{userId:e,cId:i,skillUrl:j,skillName:r.name,destSkillPath:F})}}for(const f of y)c.push(f);const z=c.length>0?`Pushed ${c.length} skills: ${c.join(", ")}`:"No valid skill directories found in file or skillUrls";return o(n,"INFO",z,{userId:e,cId:i,updatedSkills:c,agentTypes:S,elapsedMs:Date.now()-u}),await V(p),{message:z,workspaceRoot:l,updatedSkills:c}}catch(c){throw o(n,"ERROR","Failed to push skill to workspace",{userId:e,cId:i,error:c.message,elapsedMs:Date.now()-u}),c instanceof k||c instanceof Z||c instanceof U?c:new U(`Failed to push skill to workspace: ${c.message}`,{userId:e,cId:i})}finally{try{for(const c of h)t.existsSync(c)&&await t.promises.rm(c,{recursive:!0,force:!0})}catch(c){o(n,"WARN","Failed to clean up temporary extracted zip",{error:c.message})}for(const c of N)try{t.existsSync(c)&&await t.promises.unlink(c)}catch(y){o(n,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:c,error:y.message})}try{s&&s.path&&t.existsSync(s.path)&&await t.promises.unlink(s.path)}catch(c){o(n,"WARN","Failed to clean up uploaded zip file",{tempZipPath:s?.path,error:c.message})}}}async function rt(e,i,s,w){const u=Date.now(),n=`computer:${e}:${i}`;if(!e)throw new k("userId cannot be empty",{field:"userId"});if(!i)throw new k("cId cannot be empty",{field:"cId"});if(!s||!s.path)throw new k("file is required",{field:"file"});if(a.extname(s.originalname||s.filename||"").toLowerCase()!==".zip")throw new k("Only zip files are supported",{field:"file",originalName:s.originalname});const N=await K(n),h=a.join(N,String(e),String(i)),l=a.join(h,".tmp"),d=a.join(l,`template_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);try{t.existsSync(h)||await t.promises.mkdir(h,{recursive:!0}),t.existsSync(l)||await t.promises.mkdir(l,{recursive:!0}),await t.promises.mkdir(d,{recursive:!0}),o(n,"DEBUG","Start extracting template zip file",{extractRoot:d}),await B(s.path,d),o(n,"DEBUG","Template zip file extracted successfully",{extractRoot:d});const p=await t.promises.readdir(d,{withFileTypes:!0});for(const m of p){const S=a.join(d,m.name),c=a.join(h,m.name);if(m.isDirectory())await W(S,c);else{const y=a.dirname(c);t.existsSync(y)||await t.promises.mkdir(y,{recursive:!0}),await t.promises.copyFile(S,c)}}if(o(n,"INFO","Template files extracted to workspace",{userId:e,cId:i,targetDir:h,fileCount:p.length}),X.GIT_ENABLED&&(w==="true"||w===!0)){const m=await import("../../service/gitService.js");await m.default.init({workspaceType:"taskAgent",userId:e,cId:i}),await m.default.commit({workspaceType:"taskAgent",userId:e,cId:i,message:"Initial commit"}),o(n,"INFO","Git init and initial commit done",{userId:e,cId:i})}return o(n,"INFO","Init project template completed",{userId:e,cId:i,targetDir:h,elapsedMs:Date.now()-u}),{message:"Project template initialized successfully",workspaceRoot:h}}catch(p){throw o(n,"ERROR","Failed to init project template",{userId:e,cId:i,error:p.message,elapsedMs:Date.now()-u}),p instanceof k||p instanceof Z||p instanceof U?p:new U(`Failed to init project template: ${p.message}`,{userId:e,cId:i})}finally{try{t.existsSync(d)&&await t.promises.rm(d,{recursive:!0,force:!0})}catch(p){o(n,"WARN","Failed to clean up temporary extracted zip",{error:p.message})}try{s&&s.path&&t.existsSync(s.path)&&await t.promises.unlink(s.path)}catch(p){o(n,"WARN","Failed to clean up uploaded zip file",{tempZipPath:s?.path,error:p.message})}}}async function nt(e,i,s){if(!e)throw new k("userId cannot be empty",{field:"userId"});if(!i)throw new k("cId cannot be empty",{field:"cId"});if(!s||typeof s!="string"||!s.trim())throw new k("command cannot be empty",{field:"command"});const w=await K("computer"),u=a.join(w,String(e),String(i));if(!t.existsSync(u))throw new k("workspace directory does not exist",{field:"workDir",workDir:u});const n=`computer:${e}:${i}`;o(n,"INFO","Execute command in workspace",{userId:e,cId:i,workDir:u,command:s});const x=5*60*1e3;return new Promise((N,h)=>{tt(s,{cwd:u,timeout:x,maxBuffer:50*1024*1024},(l,d,p)=>{const m=l?l.code||1:0;o(n,"INFO","Execute command completed",{userId:e,cId:i,exitCode:m,stdoutLength:d?d.length:0,stderrLength:p?p.length:0}),N({stdout:d||"",stderr:p||"",exitCode:m})})})}export{at as createWorkspace,ot as pushSkillsToWorkspace,rt as initProjectTemplate,nt as executeCommand};
1
+ import t from"fs";import a from"path";import{exec as tt}from"child_process";import X from"../../appConfig/index.js";import{extractZip as B}from"../common/zipUtils.js";import{ValidationError as h,SystemError as U,FileError as Z}from"../error/errorHandler.js";import{log as o}from"../log/logUtils.js";import{ensurePrimaryAgentDirs as Y,syncAgents as V}from"../common/AgentWorkspaceUtils.js";function Q(e){if(!e)return[];if(Array.isArray(e))return e.map(i=>typeof i=="string"?i.trim():"").filter(Boolean);if(typeof e=="string"){const i=e.trim();if(!i)return[];try{const s=JSON.parse(i);if(Array.isArray(s))return s.map(w=>typeof w=="string"?w.trim():"").filter(Boolean)}catch{}return[i]}return[]}async function I(e,i,s){let w;try{w=await fetch(e)}catch(N){throw new Z(`Failed to download skill zip from url: ${e}`,{url:e,reason:N.message})}if(!w.ok)throw new Z(`Failed to download skill zip from url: ${e}`,{url:e,status:w.status,statusText:w.statusText});const p=w.headers.get("content-type")||"";p&&!p.includes("zip")&&!p.includes("octet-stream")&&o(s,"WARN","Downloaded skill url content-type is not typical zip",{url:e,contentType:p});const n=await w.arrayBuffer(),g=Buffer.from(n);await t.promises.writeFile(i,g)}async function G(e="computer"){const i=X.COMPUTER_WORKSPACE_DIR;if(!i)throw new h("COMPUTER_WORKSPACE_DIR configuration does not exist",{field:"COMPUTER_WORKSPACE_DIR"});return t.existsSync(i)||(await t.promises.mkdir(i,{recursive:!0}),o(e,"INFO","Created user workspace root directory",{workspaceRoot:i})),i}async function H(e,i){const s=a.join(e,i);if(t.existsSync(s)&&(await t.promises.lstat(s)).isDirectory())return s;const w=await t.promises.readdir(e,{withFileTypes:!0});for(const p of w){if(!p.isDirectory())continue;const n=a.join(e,p.name),g=a.join(n,i);if(t.existsSync(g)&&(await t.promises.lstat(g)).isDirectory())return g}return null}async function kt(e){return H(e,"skills")}const et=".dynamic_add.lock";function it(e){const i=a.join(e,et);return t.existsSync(i)&&t.statSync(i).isFile()}async function W(e){t.existsSync(e)&&await t.promises.rm(e,{recursive:!0,force:!0})}async function $(e,i){try{await t.promises.rename(e,i)}catch(s){if(s.code==="EXDEV"){async function w(p,n){if((await t.promises.lstat(p)).isDirectory()){await t.promises.mkdir(n,{recursive:!0});const N=await t.promises.readdir(p);for(const k of N)await w(a.join(p,k),a.join(n,k))}else await t.promises.copyFile(p,n)}await w(e,i),await t.promises.rm(e,{recursive:!0,force:!0})}else throw s}}async function st(e,i,s,w,p,n){const g=i&&i.trim(),N=s&&s.trim(),k=w&&w.trim(),c=Array.isArray(p)&&p.length>0;if(!g&&!N&&!k&&!c)return;const f=a.join(e,".claude");try{if(t.existsSync(f)||await t.promises.mkdir(f,{recursive:!0}),g)try{const d={mcpServers:JSON.parse(i)},y=a.join(e,".mcp.json");await t.promises.writeFile(y,JSON.stringify(d,null,2),"utf-8"),o(n,"INFO","Written .mcp.json to workspace root")}catch(d){o(n,"WARN","Failed to parse/write mcpServersConfig, skipping",{error:d.message})}const m={};if(N)try{m.hooks=JSON.parse(s)}catch(d){o(n,"WARN","Failed to parse hooksConfig, skipping",{error:d.message})}if(k)try{m.permissions=JSON.parse(w)}catch(d){o(n,"WARN","Failed to parse permissionsConfig, skipping",{error:d.message})}if(Object.keys(m).length>0){const d=a.join(f,"settings.json");await t.promises.writeFile(d,JSON.stringify(m,null,2),"utf-8"),o(n,"INFO","Written .claude/settings.json",{keys:Object.keys(m)})}if(c){const d=a.join(f,"hooks");t.existsSync(d)||await t.promises.mkdir(d,{recursive:!0});for(const y of p){if(!y||!y.path||!y.content)continue;const l=a.normalize(y.path);if(l.startsWith("..")||a.isAbsolute(l)){o(n,"WARN","Hook script path contains traversal, skipping",{path:y.path});continue}const x=a.join(f,l),O=a.dirname(x);t.existsSync(O)||await t.promises.mkdir(O,{recursive:!0}),await t.promises.writeFile(x,y.content,"utf-8"),await t.promises.chmod(x,493),o(n,"INFO","Written hook script",{path:y.path})}}}catch(m){o(n,"WARN","Failed to write .claude/settings or .mcp.json or hook scripts, not blocking workspace creation",{error:m.message})}}async function at(e,i,s,w,p,n,g,N){const k=Date.now(),c=`computer:${e}:${i}`,f=Q(w),m=[],d=[],y=new Set;if(!e)throw new h("userId cannot be empty",{field:"userId"});if(!i)throw new h("cId cannot be empty",{field:"cId"});const l=await G(c),x=a.join(l,String(e),String(i),".tmp"),O=a.join(l,String(e),String(i)),{skillsDir:u,agentsDir:j,agentTypes:A}=await Y(O);t.existsSync(O)||await t.promises.mkdir(O,{recursive:!0});const D=a.join(x,`preserved_skills_${Date.now()}_${Math.round(Math.random()*1e6)}`);if(t.existsSync(u)){const F=(await t.promises.readdir(u,{withFileTypes:!0})).filter(z=>z.isDirectory()&&it(a.join(u,z.name)));if(F.length>0){await t.promises.mkdir(D,{recursive:!0});for(const z of F){const S=a.join(u,z.name),v=a.join(D,z.name);await $(S,v)}o(c,"INFO","\u4FDD\u7559\u542B .dynamic_add.lock \u7684 skill",{preserved:F.map(z=>z.name)})}}if(await W(u),await W(j),await t.promises.mkdir(u,{recursive:!0}),await t.promises.mkdir(j,{recursive:!0}),t.existsSync(D)){const r=await t.promises.readdir(D,{withFileTypes:!0});for(const F of r)if(F.isDirectory()){const z=a.join(D,F.name),S=a.join(u,F.name);await $(z,S)}await W(D)}const P=t.existsSync(u),M=t.existsSync(j);o(c,"INFO","Deleted old skills and agents directories completed",{userId:e,cId:i,targetSkillsDir:u,targetAgentsDir:j,agentTypes:A,skillsExists:P,agentsExists:M});const E=a.join(O,".mcp.json");t.existsSync(E)&&await t.promises.unlink(E);const b=a.join(O,".claude","settings.json");if(t.existsSync(b)&&await t.promises.unlink(b),await st(O,p,g,n,N,c),!s&&f.length===0)return await V(O),o(c,"INFO","Created workspace (no uploaded file, no skills and agents)",{userId:e,cId:i,workspaceRoot:l,skillsDir:null,agentsDir:null,agentTypes:A,elapsedMs:Date.now()-k}),{message:"Workspace created (no uploaded file, no skills and agents)",workspaceRoot:l};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(c,"DEBUG","Start processing workspace resources",{userId:e,cId:i,workspaceRoot:l,hasUploadedZip:!!s,skillUrlsCount:f.length});try{t.existsSync(x)||await t.promises.mkdir(x,{recursive:!0});const r=[];if(s){const S=a.join(x,`skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);d.push(S),await t.promises.mkdir(S,{recursive:!0}),o(c,"DEBUG","Start extracting uploaded zip file",{extractRoot:S}),await B(s.path,S),o(c,"DEBUG","Uploaded zip file extracted successfully",{extractRoot:S});const v=await H(S,"skills"),T=await H(S,"agents");if(v){await t.promises.mkdir(u,{recursive:!0});const _=await t.promises.readdir(v,{withFileTypes:!0});for(const C of _){if(!C.isDirectory())continue;const L=a.join(v,C.name),J=a.join(u,C.name);t.existsSync(J)&&await W(J),await $(L,J),y.add(C.name)}r.push("skills"),o(c,"INFO","skills updated to workspace",{userId:e,cId:i,workspaceRoot:l,targetSkillsDir:u,agentTypes:A})}else o(c,"INFO","skills directory not found in uploaded zip, skipping",{userId:e,cId:i,extractRoot:S});T?(await W(j),await $(T,j),r.push("agents"),o(c,"INFO","agents updated to workspace",{userId:e,cId:i,workspaceRoot:l,targetAgentsDir:j,agentTypes:A})):o(c,"INFO","agents directory not found in uploaded zip, skipping",{userId:e,cId:i,extractRoot:S})}for(let S=0;S<f.length;S+=1){const v=f[S],T=a.join(x,`skill_url_${Date.now()}_${S}_${Math.round(Math.random()*1e6)}.zip`);m.push(T);const _=a.join(x,`skill_url_extract_${Date.now()}_${S}_${Math.round(Math.random()*1e6)}`);d.push(_),await t.promises.mkdir(_,{recursive:!0}),o(c,"INFO","Start download skill zip from url",{userId:e,cId:i,skillUrl:v}),await I(v,T,c),o(c,"INFO","Skill zip downloaded, start extracting",{userId:e,cId:i,skillUrl:v,downloadedZipPath:T}),await B(T,_);const L=(await t.promises.readdir(_,{withFileTypes:!0})).filter(R=>R.isDirectory()&&!R.name.startsWith(".")),q=L.find(R=>R.name==="skills")?(await t.promises.readdir(a.join(_,"skills"),{withFileTypes:!0})).filter(R=>R.isDirectory()&&!R.name.startsWith(".")).map(R=>({name:R.name,sourcePath:a.join(_,"skills",R.name)})):L.map(R=>({name:R.name,sourcePath:a.join(_,R.name)}));if(q.length===0){o(c,"WARN","No skill directory found after extracting skill url zip",{userId:e,cId:i,skillUrl:v,extractRoot:_});continue}await t.promises.mkdir(u,{recursive:!0});for(const R of q){const K=a.join(u,R.name);t.existsSync(K)&&await W(K),await $(R.sourcePath,K),y.add(R.name),o(c,"INFO","Skill from url updated to workspace",{userId:e,cId:i,skillUrl:v,skillName:R.name,destSkillPath:K})}r.includes("skills")||r.push("skills")}r.length===0&&o(c,"WARN","No valid skills or agents directories found",{userId:e,cId:i,hasUploadedZip:!!s,skillUrlsCount:f.length});const F=Array.from(y),z=r.length>0?`Workspace created successfully, ${r.join(" and ")} updated`:"Workspace created successfully (skills and agents directories not found)";return o(c,"INFO",z,{userId:e,cId:i,updatedDirs:r,updatedSkills:F,agentTypes:A,elapsedMs:Date.now()-k}),await V(O),{message:z,workspaceRoot:l,updatedSkills:F}}catch(r){throw o(c,"ERROR","Failed to process workspace resources",{userId:e,cId:i,error:r.message,elapsedMs:Date.now()-k}),r instanceof h||r instanceof Z||r instanceof U?r:new U(`Failed to create workspace: ${r.message}`,{userId:e,cId:i})}finally{try{for(const r of d)t.existsSync(r)&&await t.promises.rm(r,{recursive:!0,force:!0})}catch(r){o(c,"WARN","Failed to clean up temporary extracted zip",{error:r.message})}for(const r of m)try{t.existsSync(r)&&await t.promises.unlink(r)}catch(F){o(c,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:r,error:F.message})}try{s&&s.path&&t.existsSync(s.path)&&await t.promises.unlink(s.path)}catch(r){o(c,"WARN","Failed to clean up uploaded zip file",{tempZipPath:s?.path,error:r.message})}}}async function ot(e,i,s,w){const p=Date.now(),n=`computer:${e}:${i}`,g=Q(w),N=[],k=[];if(!e)throw new h("userId cannot be empty",{field:"userId"});if(!i)throw new h("cId cannot be empty",{field:"cId"});if(!s&&g.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 c=await G(n),f=a.join(c,String(e),String(i),".tmp"),m=a.join(c,String(e),String(i)),{skillsDir:d,agentTypes:y}=await Y(m);try{t.existsSync(m)||await t.promises.mkdir(m,{recursive:!0}),t.existsSync(d)||await t.promises.mkdir(d,{recursive:!0}),t.existsSync(f)||await t.promises.mkdir(f,{recursive:!0});const l=[],x=new Set;if(s){const u=a.join(f,`skill_push_${Date.now()}_${Math.round(Math.random()*1e6)}`);k.push(u),await t.promises.mkdir(u,{recursive:!0}),o(n,"DEBUG","Start extracting skill zip file",{extractRoot:u}),await B(s.path,u),o(n,"DEBUG","Skill zip file extracted successfully",{extractRoot:u});const j=await H(u,"skills");if(!j)o(n,"WARN","skills directory not found in uploaded zip",{userId:e,cId:i,extractRoot:u});else{const D=(await t.promises.readdir(j,{withFileTypes:!0})).filter(P=>P.isDirectory()&&!P.name.startsWith("."));if(D.length===0)o(n,"WARN","skills directory in uploaded zip has no skill subdirectories",{userId:e,cId:i,skillsDir:j});else for(const P of D){const M=a.join(j,P.name),E=a.join(d,P.name);t.existsSync(E)&&await W(E),await $(M,E),x.add(P.name),o(n,"INFO","skill pushed to workspace from uploaded zip",{userId:e,cId:i,skillName:P.name,destSkillPath:E})}}}for(let u=0;u<g.length;u+=1){const j=g[u],A=a.join(f,`skill_push_url_${Date.now()}_${u}_${Math.round(Math.random()*1e6)}.zip`);N.push(A);const D=a.join(f,`skill_push_url_extract_${Date.now()}_${u}_${Math.round(Math.random()*1e6)}`);k.push(D),await t.promises.mkdir(D,{recursive:!0}),o(n,"INFO","Start download skill zip for push from url",{userId:e,cId:i,skillUrl:j}),await I(j,A,n),await B(A,D);const M=(await t.promises.readdir(D,{withFileTypes:!0})).filter(r=>r.isDirectory()&&!r.name.startsWith(".")),b=M.find(r=>r.name==="skills")?(await t.promises.readdir(a.join(D,"skills"),{withFileTypes:!0})).filter(r=>r.isDirectory()&&!r.name.startsWith(".")).map(r=>({name:r.name,sourcePath:a.join(D,"skills",r.name)})):M.map(r=>({name:r.name,sourcePath:a.join(D,r.name)}));if(b.length===0){o(n,"WARN","No skill directory found after extracting push skill url zip",{userId:e,cId:i,skillUrl:j,extractRoot:D});continue}for(const r of b){const F=a.join(d,r.name);t.existsSync(F)&&await W(F),await $(r.sourcePath,F),x.add(r.name),o(n,"INFO","skill pushed to workspace from url zip",{userId:e,cId:i,skillUrl:j,skillName:r.name,destSkillPath:F})}}for(const u of x)l.push(u);const O=l.length>0?`Pushed ${l.length} skills: ${l.join(", ")}`:"No valid skill directories found in file or skillUrls";return o(n,"INFO",O,{userId:e,cId:i,updatedSkills:l,agentTypes:y,elapsedMs:Date.now()-p}),await V(m),{message:O,workspaceRoot:c,updatedSkills:l}}catch(l){throw o(n,"ERROR","Failed to push skill to workspace",{userId:e,cId:i,error:l.message,elapsedMs:Date.now()-p}),l instanceof h||l instanceof Z||l instanceof U?l:new U(`Failed to push skill to workspace: ${l.message}`,{userId:e,cId:i})}finally{try{for(const l of k)t.existsSync(l)&&await t.promises.rm(l,{recursive:!0,force:!0})}catch(l){o(n,"WARN","Failed to clean up temporary extracted zip",{error:l.message})}for(const l of N)try{t.existsSync(l)&&await t.promises.unlink(l)}catch(x){o(n,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:l,error:x.message})}try{s&&s.path&&t.existsSync(s.path)&&await t.promises.unlink(s.path)}catch(l){o(n,"WARN","Failed to clean up uploaded zip file",{tempZipPath:s?.path,error:l.message})}}}async function rt(e,i,s,w){const p=Date.now(),n=`computer:${e}:${i}`;if(!e)throw new h("userId cannot be empty",{field:"userId"});if(!i)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 N=await G(n),k=a.join(N,String(e),String(i)),c=a.join(k,".tmp"),f=a.join(c,`template_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);try{t.existsSync(k)||await t.promises.mkdir(k,{recursive:!0}),t.existsSync(c)||await t.promises.mkdir(c,{recursive:!0}),await t.promises.mkdir(f,{recursive:!0}),o(n,"DEBUG","Start extracting template zip file",{extractRoot:f}),await B(s.path,f),o(n,"DEBUG","Template zip file extracted successfully",{extractRoot:f});const m=await t.promises.readdir(f,{withFileTypes:!0});for(const d of m){const y=a.join(f,d.name),l=a.join(k,d.name);if(d.isDirectory())await $(y,l);else{const x=a.dirname(l);t.existsSync(x)||await t.promises.mkdir(x,{recursive:!0}),await t.promises.copyFile(y,l)}}if(o(n,"INFO","Template files extracted to workspace",{userId:e,cId:i,targetDir:k,fileCount:m.length}),X.GIT_ENABLED&&(w==="true"||w===!0)){const d=await import("../../service/gitService.js");await d.default.init({workspaceType:"taskAgent",userId:e,cId:i}),await d.default.commit({workspaceType:"taskAgent",userId:e,cId:i,message:"Initial commit"}),o(n,"INFO","Git init and initial commit done",{userId:e,cId:i})}return o(n,"INFO","Init project template completed",{userId:e,cId:i,targetDir:k,elapsedMs:Date.now()-p}),{message:"Project template initialized successfully",workspaceRoot:k}}catch(m){throw o(n,"ERROR","Failed to init project template",{userId:e,cId:i,error:m.message,elapsedMs:Date.now()-p}),m instanceof h||m instanceof Z||m instanceof U?m:new U(`Failed to init project template: ${m.message}`,{userId:e,cId:i})}finally{try{t.existsSync(f)&&await t.promises.rm(f,{recursive:!0,force:!0})}catch(m){o(n,"WARN","Failed to clean up temporary extracted zip",{error:m.message})}try{s&&s.path&&t.existsSync(s.path)&&await t.promises.unlink(s.path)}catch(m){o(n,"WARN","Failed to clean up uploaded zip file",{tempZipPath:s?.path,error:m.message})}}}async function nt(e,i,s){if(!e)throw new h("userId cannot be empty",{field:"userId"});if(!i)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 w=await G("computer"),p=a.join(w,String(e),String(i));if(!t.existsSync(p))throw new h("workspace directory does not exist",{field:"workDir",workDir:p});const n=`computer:${e}:${i}`;o(n,"INFO","Execute command in workspace",{userId:e,cId:i,workDir:p,command:s});const g=10*60*1e3;return new Promise((N,k)=>{tt(s,{cwd:p,timeout:g,maxBuffer:50*1024*1024},(c,f,m)=>{const d=c?c.killed?-1:c.code||1:0,y=c&&c.killed?(m||"")+`
2
+ Command timed out after ${g/1e3}s`:m||"";o(n,"INFO","Execute command completed",{userId:e,cId:i,exitCode:d,killed:c?c.killed:!1,stdoutLength:f?f.length:0,stderrLength:y.length}),N({stdout:f||"",stderr:y,exitCode:d})})})}async function ct(e,i){const s=`computer:${e}:${i}`;if(!e)throw new h("userId cannot be empty",{field:"userId"});if(!i)throw new h("cId cannot be empty",{field:"cId"});const w=await G(s),p=a.join(w,String(e),String(i));return t.existsSync(p)?(await t.promises.rm(p,{recursive:!0,force:!0}),o(s,"INFO","Workspace deleted",{userId:e,cId:i,targetDir:p})):o(s,"WARN","Workspace not found, skip delete",{userId:e,cId:i,targetDir:p}),{deleted:!0}}export{at as createWorkspace,ot as pushSkillsToWorkspace,rt as initProjectTemplate,nt as executeCommand,ct as deleteWorkspace};
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.11",
4
+ "version": "1.3.0-beta.13",
5
5
  "description": "Cross-platform file service deployment tool with start/stop/restart CLI commands",
6
6
  "type": "module",
7
7
  "main": "index.js",