nuwax-file-server 1.3.2 → 1.3.3

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.2",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.3",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 z from"express";import k from"multer";import f from"fs";import w from"path";import{ValidationError as C,asyncHandler as d}from"../utils/error/errorHandler.js";import{log as u}from"../utils/log/logUtils.js";import F from"../appConfig/index.js";import{createWorkspace as N,pushSkillsToWorkspace as S,initProjectTemplate as b,installProjectDependencies as A,executeCommand as j,deleteWorkspace as O,zipWorkspace as D,buildAgentPackage as E,cleanupBuildArtifacts as P}from"../utils/computer/computerUtils.js";import{getFileList as U,updateFiles as T,uploadFile as R,uploadFiles as x,downloadAllFiles as v,getLatestLogs as H}from"../utils/computer/computerFileUtils.js";const g=z.Router(),h=k({storage:k.diskStorage({destination:(t,a,s)=>{try{const e=F.COMPUTER_WORKSPACE_DIR;if(!e)return s(new Error("COMPUTER_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));const o=t.body?.userId||"unknown",n=t.body?.cId||"unknown",i=w.join(e,String(o),String(n),".tmp");f.existsSync(i)||f.mkdirSync(i,{recursive:!0}),s(null,i)}catch(e){s(e)}},filename:(t,a,s)=>{const e=w.extname(a.originalname)||".zip",o=w.basename(a.originalname,e),n=`${Date.now()}_${Math.round(Math.random()*1e6)}`;s(null,`${o}_${n}${e}`)}}),limits:{fileSize:F.UPLOAD_MAX_FILE_SIZE_BYTES}});function _(t,a,s,e){if(t&&t.name==="MulterError"||t&&(t.name==="ValidationError"||t instanceof C))return e(t);e(t)}const q=[{path:"/create-workspace",method:"post",middleware:h.single("file"),handler:d(async(t,a)=>{const{userId:s,cId:e}=t.body||{},o=t.file||null,n=`computer:${s}:${e}`;u(n,"INFO","Create workspace request",{userId:s,cId:e,hasFile:!!o,fileName:o?.originalname,fileSize:o?.size});const i=await N(s,e,o);a.status(200).json({success:!0,...i})})},{path:"/create-workspace-v2",method:"post",middleware:h.single("file"),handler:d(async(t,a)=>{const{userId:s,cId:e,skillUrls:o,mcpServersConfig:n,hooksConfig:i,permissionsConfig:r,hookScripts:l}=t.body||{},c=t.file||null,y=`computer:${s}:${e}`;let m=o;if(typeof o=="string")try{const $=JSON.parse(o);m=Array.isArray($)?$:[o]}catch{m=[o]}let p=l;if(typeof l=="string")try{p=JSON.parse(l)}catch{p=null}u(y,"INFO","Create workspace v2 request",{userId:s,cId:e,hasFile:!!c,fileName:c?.originalname,fileSize:c?.size,skillUrlsCount:Array.isArray(m)?m.length:0,hasMcpServersConfig:!!n,hasHooksConfig:!!i,hasPermissionsConfig:!!r,hookScriptsCount:Array.isArray(p)?p.length:0});const I=await N(s,e,c,m,n,r,i,p);a.status(200).json({success:!0,...I})})},{path:"/push-skills-to-workspace",method:"post",middleware:h.single("file"),handler:d(async(t,a)=>{const{userId:s,cId:e}=t.body||{},o=t.file||null,n=`computer:${s}:${e}`;u(n,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42",{userId:s,cId:e,hasFile:!!o,fileName:o?.originalname,fileSize:o?.size});const i=await S(s,e,o);a.status(200).json({success:!0,...i})})},{path:"/push-skills-to-workspace-v2",method:"post",middleware:h.single("file"),handler:d(async(t,a)=>{const{userId:s,cId:e,skillUrls:o}=t.body||{},n=t.file||null,i=`computer:${s}:${e}`;let r=o;if(typeof o=="string")try{const c=JSON.parse(o);r=Array.isArray(c)?c:[o]}catch{r=[o]}u(i,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42(v2)",{userId:s,cId:e,hasFile:!!n,fileName:n?.originalname,fileSize:n?.size,skillUrlsCount:Array.isArray(r)?r.length:0});const l=await S(s,e,n,r);a.status(200).json({success:!0,...l})})},{path:"/get-file-list",method:"get",handler:d(async(t,a)=>{const{userId:s,cId:e,proxyPath:o,customTargetDir:n}=t.query,i=await U(s,e,o,n);a.status(200).json({success:!0,...i})})},{path:"/files-update",method:"post",handler:d(async(t,a)=>{const{userId:s,cId:e,files:o,customTargetDir:n}=t.body||{},i=`computer:${s}:${e}`;u(i,"INFO","Files update",{userId:s,cId:e,filesCount:o?o.length:0}),o&&Array.isArray(o)&&o.forEach(l=>{if(l&&typeof l.contents=="string"&&l.contents)try{l.contents=decodeURIComponent(l.contents)}catch(c){u(i,"WARN","Decode file content failed",{fileName:l.name,error:c.message})}});const r=await T(s,e,o,n);a.status(200).json(r)})},{path:"/upload-file",method:"post",middleware:h.single("file"),handler:d(async(t,a)=>{const{userId:s,cId:e,filePath:o,customTargetDir:n}=t.body||{},i=t.file,r=`computer:${s}:${e}`;u(r,"INFO","Upload single file",{userId:s,cId:e,filePath:o});const c={buffer:await f.promises.readFile(i.path),originalname:i.originalname,mimetype:i.mimetype,size:i.size};try{const y=await R(s,e,c,o,n);a.status(200).json(y)}finally{f.existsSync(i.path)&&await f.promises.unlink(i.path)}})},{path:"/upload-files",method:"post",middleware:h.array("files"),handler:d(async(t,a)=>{const{userId:s,cId:e,filePaths:o,customTargetDir:n}=t.body||{},i=t.files||[],r=`computer:${s}:${e}`,l=Array.isArray(o)?o:typeof o=="string"?[o]:o;u(r,"INFO","Batch upload files request",{userId:s,cId:e,filesCount:i.length,filePathsCount:Array.isArray(l)?l.length:0});const c=[],y=[];try{for(const p of i){y.push(p.path);const I=await f.promises.readFile(p.path);c.push({buffer:I,originalname:p.originalname,mimetype:p.mimetype,size:p.size})}const m=await x(s,e,c,l,n);a.status(200).json(m)}finally{for(const m of y)if(f.existsSync(m))try{await f.promises.unlink(m)}catch(p){u(r,"WARN","Clean temporary file failed",{tempPath:m,error:p.message})}}})},{path:"/install-project",method:"post",handler:d(async(t,a)=>{const{userId:s,cId:e,programmingLanguage:o}=t.body||{},n=`computer:${s}:${e}`;u(n,"INFO","Install project request",{userId:s,cId:e,programmingLanguage:o});const i=await A(s,e,o);a.status(200).json({success:!0,...i})})},{path:"/init-project-template",method:"post",middleware:h.single("file"),handler:d(async(t,a)=>{const{userId:s,cId:e,enableGit:o}=t.body||{},n=t.file||null,i=`computer:${s}:${e}`;u(i,"INFO","Init project template request",{userId:s,cId:e,hasFile:!!n,fileName:n?.originalname,fileSize:n?.size,enableGit:o});const r=await b(s,e,n,o);a.status(200).json({success:!0,...r})})},{path:"/download-all-files",method:"get",handler:d(async(t,a)=>{const{userId:s,cId:e,customTargetDir:o}=t.query||{},n=`computer:${s}:${e}`;u(n,"INFO","Download all files request",{userId:s,cId:e});const{archive:i,zipFileName:r}=await v(s,e,o);a.setHeader("Content-Type","application/zip");const l=encodeURIComponent(r);a.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),i.on("error",c=>{a.destroy(c)}),i.pipe(a),i.finalize()})},{path:"/execute-command",method:"post",handler:d(async(t,a)=>{const{userId:s,cId:e,command:o}=t.body||{},n=`computer:${s}:${e}`;u(n,"INFO","Execute command request",{userId:s,cId:e,command:o});const i=await j(s,e,o);a.status(200).json({success:!0,...i})})},{path:"/delete-workspace",method:"post",handler:d(async(t,a)=>{const{userId:s,cId:e}=t.body||{},o=`computer:${s}:${e}`;u(o,"INFO","Delete workspace request",{userId:s,cId:e});const n=await O(s,e);a.status(200).json({success:!0,...n})})},{path:"/get-logs",method:"get",handler:d(async(t,a)=>{const{userId:s,cId:e,tailLines:o}=t.query,n=o?parseInt(o,10):200,i=Number.isFinite(n)&&n>0?n:200,r=await H(s,e,i);a.status(200).json(r)})},{path:"/zip-workspace",method:"post",handler:d(async(t,a)=>{const{userId:s,cId:e,excludeDirs:o}=t.body||{},n=`computer:${s}:${e}`;u(n,"INFO","Zip workspace request",{userId:s,cId:e,hasExcludeDirs:!!o});const{archive:i,zipFileName:r}=await D(s,e,o||null);a.setHeader("Content-Type","application/zip");const l=encodeURIComponent(r);a.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),i.on("error",c=>{a.destroy(c)}),i.pipe(a),i.finalize()})},{path:"/build-agent-package",method:"post",handler:d(async(t,a)=>{const{userId:s,cId:e,agentId:o,version:n}=t.body||{},i=`computer:${s}:${e}`;u(i,"INFO","Build agent package request",{userId:s,cId:e,agentId:o,version:n});const r=await E(s,e,o,n);a.status(200).json({success:!0,...r})})},{path:"/cleanup-build-artifacts",method:"post",handler:d(async(t,a)=>{const{userId:s,cId:e}=t.body||{},o=`computer:${s}:${e}`;u(o,"INFO","Cleanup build artifacts request",{userId:s,cId:e});const n=await P(s,e);a.status(200).json({success:!0,...n})})}];q.forEach(t=>{if(t.middleware)g[t.method](t.path,t.middleware,t.handler);else if(t.customHandler){const a=[];t.handler&&a.push(t.handler),t.decodeMiddleware&&a.push(t.decodeMiddleware),a.push(_),a.push(t.customHandler),g[t.method](t.path,...a)}else g[t.method](t.path,t.handler)});export default g;
1
+ import b from"express";import k from"multer";import f from"fs";import w from"path";import{ValidationError as F,asyncHandler as d}from"../utils/error/errorHandler.js";import{log as u}from"../utils/log/logUtils.js";import N from"../appConfig/index.js";import{createWorkspace as z,pushSkillsToWorkspace as S,initProjectTemplate as j,installProjectDependencies as C,executeCommand as A,deleteWorkspace as O,zipWorkspace as D,buildAgentPackage as P,cleanupBuildArtifacts as E}from"../utils/computer/computerUtils.js";import{getFileList as T,updateFiles as U,uploadFile as R,uploadFiles as x,downloadAllFiles as q,getLatestLogs as v,importProject as H}from"../utils/computer/computerFileUtils.js";const y=b.Router(),h=k({storage:k.diskStorage({destination:(s,a,t)=>{try{const e=N.COMPUTER_WORKSPACE_DIR;if(!e)return t(new Error("COMPUTER_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));const o=s.body?.userId||"unknown",i=s.body?.cId||"unknown",n=w.join(e,String(o),String(i),".tmp");f.existsSync(n)||f.mkdirSync(n,{recursive:!0}),t(null,n)}catch(e){t(e)}},filename:(s,a,t)=>{const e=w.extname(a.originalname)||".zip",o=w.basename(a.originalname,e),i=`${Date.now()}_${Math.round(Math.random()*1e6)}`;t(null,`${o}_${i}${e}`)}}),limits:{fileSize:N.UPLOAD_MAX_FILE_SIZE_BYTES}});function _(s,a,t,e){if(s&&s.name==="MulterError"||s&&(s.name==="ValidationError"||s instanceof F))return e(s);e(s)}const M=[{path:"/create-workspace",method:"post",middleware:h.single("file"),handler:d(async(s,a)=>{const{userId:t,cId:e}=s.body||{},o=s.file||null,i=`computer:${t}:${e}`;u(i,"INFO","Create workspace request",{userId:t,cId:e,hasFile:!!o,fileName:o?.originalname,fileSize:o?.size});const n=await z(t,e,o);a.status(200).json({success:!0,...n})})},{path:"/create-workspace-v2",method:"post",middleware:h.single("file"),handler:d(async(s,a)=>{const{userId:t,cId:e,skillUrls:o,mcpServersConfig:i,hooksConfig:n,permissionsConfig:r,hookScripts:l}=s.body||{},c=s.file||null,g=`computer:${t}:${e}`;let m=o;if(typeof o=="string")try{const $=JSON.parse(o);m=Array.isArray($)?$:[o]}catch{m=[o]}let p=l;if(typeof l=="string")try{p=JSON.parse(l)}catch{p=null}u(g,"INFO","Create workspace v2 request",{userId:t,cId:e,hasFile:!!c,fileName:c?.originalname,fileSize:c?.size,skillUrlsCount:Array.isArray(m)?m.length:0,hasMcpServersConfig:!!i,hasHooksConfig:!!n,hasPermissionsConfig:!!r,hookScriptsCount:Array.isArray(p)?p.length:0});const I=await z(t,e,c,m,i,r,n,p);a.status(200).json({success:!0,...I})})},{path:"/push-skills-to-workspace",method:"post",middleware:h.single("file"),handler:d(async(s,a)=>{const{userId:t,cId:e}=s.body||{},o=s.file||null,i=`computer:${t}:${e}`;u(i,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42",{userId:t,cId:e,hasFile:!!o,fileName:o?.originalname,fileSize:o?.size});const n=await S(t,e,o);a.status(200).json({success:!0,...n})})},{path:"/push-skills-to-workspace-v2",method:"post",middleware:h.single("file"),handler:d(async(s,a)=>{const{userId:t,cId:e,skillUrls:o}=s.body||{},i=s.file||null,n=`computer:${t}:${e}`;let r=o;if(typeof o=="string")try{const c=JSON.parse(o);r=Array.isArray(c)?c:[o]}catch{r=[o]}u(n,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42(v2)",{userId:t,cId:e,hasFile:!!i,fileName:i?.originalname,fileSize:i?.size,skillUrlsCount:Array.isArray(r)?r.length:0});const l=await S(t,e,i,r);a.status(200).json({success:!0,...l})})},{path:"/get-file-list",method:"get",handler:d(async(s,a)=>{const{userId:t,cId:e,proxyPath:o,customTargetDir:i}=s.query,n=await T(t,e,o,i);a.status(200).json({success:!0,...n})})},{path:"/files-update",method:"post",handler:d(async(s,a)=>{const{userId:t,cId:e,files:o,customTargetDir:i}=s.body||{},n=`computer:${t}:${e}`;u(n,"INFO","Files update",{userId:t,cId:e,filesCount:o?o.length:0}),o&&Array.isArray(o)&&o.forEach(l=>{if(l&&typeof l.contents=="string"&&l.contents)try{l.contents=decodeURIComponent(l.contents)}catch(c){u(n,"WARN","Decode file content failed",{fileName:l.name,error:c.message})}});const r=await U(t,e,o,i);a.status(200).json(r)})},{path:"/upload-file",method:"post",middleware:h.single("file"),handler:d(async(s,a)=>{const{userId:t,cId:e,filePath:o,customTargetDir:i}=s.body||{},n=s.file,r=`computer:${t}:${e}`;u(r,"INFO","Upload single file",{userId:t,cId:e,filePath:o});const c={buffer:await f.promises.readFile(n.path),originalname:n.originalname,mimetype:n.mimetype,size:n.size};try{const g=await R(t,e,c,o,i);a.status(200).json(g)}finally{f.existsSync(n.path)&&await f.promises.unlink(n.path)}})},{path:"/import-project",method:"post",middleware:h.single("file"),handler:d(async(s,a)=>{const{userId:t,cId:e,customTargetDir:o}=s.body||{},i=s.file,n=`computer:${t}:${e}`;if(u(n,"INFO","Import project request",{userId:t,cId:e,fileName:i?.originalname,fileSize:i?.size}),!i)throw new F("file is required",{field:"file"});const r=await H(t,e,i,o);a.status(200).json(r)})},{path:"/upload-files",method:"post",middleware:h.array("files"),handler:d(async(s,a)=>{const{userId:t,cId:e,filePaths:o,customTargetDir:i}=s.body||{},n=s.files||[],r=`computer:${t}:${e}`,l=Array.isArray(o)?o:typeof o=="string"?[o]:o;u(r,"INFO","Batch upload files request",{userId:t,cId:e,filesCount:n.length,filePathsCount:Array.isArray(l)?l.length:0});const c=[],g=[];try{for(const p of n){g.push(p.path);const I=await f.promises.readFile(p.path);c.push({buffer:I,originalname:p.originalname,mimetype:p.mimetype,size:p.size})}const m=await x(t,e,c,l,i);a.status(200).json(m)}finally{for(const m of g)if(f.existsSync(m))try{await f.promises.unlink(m)}catch(p){u(r,"WARN","Clean temporary file failed",{tempPath:m,error:p.message})}}})},{path:"/install-project",method:"post",handler:d(async(s,a)=>{const{userId:t,cId:e,programmingLanguage:o}=s.body||{},i=`computer:${t}:${e}`;u(i,"INFO","Install project request",{userId:t,cId:e,programmingLanguage:o});const n=await C(t,e,o);a.status(200).json({success:!0,...n})})},{path:"/init-project-template",method:"post",middleware:h.single("file"),handler:d(async(s,a)=>{const{userId:t,cId:e,enableGit:o}=s.body||{},i=s.file||null,n=`computer:${t}:${e}`;u(n,"INFO","Init project template request",{userId:t,cId:e,hasFile:!!i,fileName:i?.originalname,fileSize:i?.size,enableGit:o});const r=await j(t,e,i,o);a.status(200).json({success:!0,...r})})},{path:"/download-all-files",method:"get",handler:d(async(s,a)=>{const{userId:t,cId:e,customTargetDir:o}=s.query||{},i=`computer:${t}:${e}`;u(i,"INFO","Download all files request",{userId:t,cId:e});const{archive:n,zipFileName:r}=await q(t,e,o);a.setHeader("Content-Type","application/zip");const l=encodeURIComponent(r);a.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),n.on("error",c=>{a.destroy(c)}),n.pipe(a),n.finalize()})},{path:"/execute-command",method:"post",handler:d(async(s,a)=>{const{userId:t,cId:e,command:o}=s.body||{},i=`computer:${t}:${e}`;u(i,"INFO","Execute command request",{userId:t,cId:e,command:o});const n=await A(t,e,o);a.status(200).json({success:!0,...n})})},{path:"/delete-workspace",method:"post",handler:d(async(s,a)=>{const{userId:t,cId:e}=s.body||{},o=`computer:${t}:${e}`;u(o,"INFO","Delete workspace request",{userId:t,cId:e});const i=await O(t,e);a.status(200).json({success:!0,...i})})},{path:"/get-logs",method:"get",handler:d(async(s,a)=>{const{userId:t,cId:e,tailLines:o}=s.query,i=o?parseInt(o,10):200,n=Number.isFinite(i)&&i>0?i:200,r=await v(t,e,n);a.status(200).json(r)})},{path:"/zip-workspace",method:"post",handler:d(async(s,a)=>{const{userId:t,cId:e,excludeDirs:o}=s.body||{},i=`computer:${t}:${e}`;u(i,"INFO","Zip workspace request",{userId:t,cId:e,hasExcludeDirs:!!o});const{archive:n,zipFileName:r}=await D(t,e,o||null);a.setHeader("Content-Type","application/zip");const l=encodeURIComponent(r);a.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),n.on("error",c=>{a.destroy(c)}),n.pipe(a),n.finalize()})},{path:"/build-agent-package",method:"post",handler:d(async(s,a)=>{const{userId:t,cId:e,agentId:o,version:i}=s.body||{},n=`computer:${t}:${e}`;u(n,"INFO","Build agent package request",{userId:t,cId:e,agentId:o,version:i});const r=await P(t,e,o,i);a.status(200).json({success:!0,...r})})},{path:"/cleanup-build-artifacts",method:"post",handler:d(async(s,a)=>{const{userId:t,cId:e}=s.body||{},o=`computer:${t}:${e}`;u(o,"INFO","Cleanup build artifacts request",{userId:t,cId:e});const i=await E(t,e);a.status(200).json({success:!0,...i})})}];M.forEach(s=>{if(s.middleware)y[s.method](s.path,s.middleware,s.handler);else if(s.customHandler){const a=[];s.handler&&a.push(s.handler),s.decodeMiddleware&&a.push(s.decodeMiddleware),a.push(_),a.push(s.customHandler),y[s.method](s.path,...a)}else y[s.method](s.path,s.handler)});export default y;
@@ -0,0 +1 @@
1
+ import e from"fs";import n from"path";import{FileError as m}from"../error/errorHandler.js";function u(r,i){const t=String(i||"").replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[a-zA-Z]:/.test(t))throw new m(`Unsafe zip entry path: ${i}`,{entryName:i});const s=t.replace(/^\/+/,"").split("/").filter(Boolean);if(s.some(c=>c===".."))throw new m(`Unsafe zip entry path: ${i}`,{entryName:i});const o=n.resolve(r,...s),p=n.resolve(r);if(o!==p&&!o.startsWith(p+n.sep))throw new m(`Unsafe zip entry path: ${i}`,{entryName:i,targetPath:o,basePath:p});return o}async function w(r,i){try{await e.promises.rename(r,i)}catch(t){if(t.code==="EXDEV"){async function a(s,o){if((await e.promises.lstat(s)).isDirectory()){await e.promises.mkdir(o,{recursive:!0});const c=await e.promises.readdir(s);for(const f of c)await a(n.join(s,f),n.join(o,f))}else await e.promises.copyFile(s,o)}await a(r,i),await e.promises.rm(r,{recursive:!0,force:!0})}else throw t}}async function l(r,i){if(!e.existsSync(r))return;if(e.existsSync(i)&&await e.promises.rm(i,{recursive:!0,force:!0}),(await e.promises.lstat(r)).isDirectory()){await w(r,i);return}await e.promises.mkdir(n.dirname(i),{recursive:!0});try{await e.promises.rename(r,i)}catch(a){if(a.code==="EXDEV")await e.promises.copyFile(r,i),await e.promises.unlink(r);else throw a}}export{u as assertSafeZipEntryPath,w as moveDirectory,l as movePath};
@@ -1 +1 @@
1
- import l from"fs";import E from"path";import h from"yauzl";import{FileError as g}from"../error/errorHandler.js";function k(c,i){return new Promise((d,r)=>{h.open(c,{lazyEntries:!0},(m,e)=>{if(m)return r(new g(`\u65E0\u6CD5\u6253\u5F00\u538B\u7F29\u5305: ${m.message}`,{zipPath:c,originalError:m.message}));e.readEntry(),e.on("entry",n=>{if(/\/$/.test(n.fileName)){const t=E.join(i,n.fileName);try{l.mkdirSync(t,{recursive:!0})}catch(s){console.warn("[extractZip] mkdir for directory entry failed, skip this dir",{dirPath:t,code:s.code,message:s.message}),e.readEntry();return}e.readEntry()}else e.openReadStream(n,(t,s)=>{if(t)return r(new g(`Failed to read zip entry: ${t.message}`,{entry:n.fileName,originalError:t.message}));const a=E.join(i,n.fileName),u=E.dirname(a);try{l.mkdirSync(u,{recursive:!0})}catch(o){console.warn("[extractZip] mkdir for file entry failed, skip this file",{dirPath:u,filePath:a,code:o.code,message:o.message}),e.readEntry();return}try{if(l.existsSync(a)&&l.statSync(a).isDirectory()){e.readEntry();return}}catch(o){return r(new g(`Failed to check file status: ${o.message}`,{filePath:a,originalError:o.message}))}const f=l.createWriteStream(a);s.pipe(f),f.on("close",()=>{e.readEntry()}),f.on("error",o=>{r(new g(`Failed to write file: ${o.message}`,{filePath:a,originalError:o.message}))})})}),e.on("end",()=>{d()}),e.on("error",n=>{r(new g(`Error occurred during unzip: ${n.message}`,{zipPath:c,originalError:n.message}))})})})}const y=new Map,w=50;function S(c){return new Promise(i=>{try{const d=l.statSync(c),r=`${c}:${d.mtimeMs}:${d.size}`;if(y.has(r))return i(y.get(r));h.open(c,{lazyEntries:!0},(m,e)=>{if(m)return i(null);const n=new Map;e.readEntry(),e.on("entry",t=>{const s=t.fileName.replace(/\\/g,"/");/\/$/.test(t.fileName)||n.set(s,t),e.readEntry()}),e.on("end",()=>{e.close(),y.size>=w&&Array.from(y.keys()).slice(0,Math.floor(w/2)).forEach(s=>y.delete(s)),y.set(r,n),i(n)}),e.on("error",()=>{e.close(),i(null)})})}catch{i(null)}})}function $(c,i,d){return new Promise(async r=>{try{const m=await S(c);if(!m)return r(!1);const e=i.replace(/^[\/\\]+/,"").replace(/\\/g,"/");if(!m.has(e))return r(!1);h.open(c,{lazyEntries:!1},(n,t)=>{if(n)return r(!1);let s=null;for(const a of t.entries)if(a.fileName.replace(/\\/g,"/")===e&&!/\/$/.test(a.fileName)){s=a;break}if(!s)return t.close(),r(!1);t.openReadStream(s,(a,u)=>{if(a||!u)return t.close(),r(!1);const f=E.dirname(d);try{l.mkdirSync(f,{recursive:!0})}catch{return t.close(),r(!1)}const o=l.createWriteStream(d);u.pipe(o),o.on("close",()=>{t.close(),r(!0)}),o.on("error",()=>{t.close(),r(!1)})})})}catch{r(!1)}})}export{k as extractZip,$ as extractSingleFileFromZip};
1
+ import u from"fs";import w from"path";import h from"yauzl";import{FileError as E}from"../error/errorHandler.js";import{assertSafeZipEntryPath as S}from"./fileSystemUtils.js";function $(o,c){return new Promise((d,e)=>{h.open(o,{lazyEntries:!0},(i,r)=>{if(i)return e(new E(`\u65E0\u6CD5\u6253\u5F00\u538B\u7F29\u5305: ${i.message}`,{zipPath:o,originalError:i.message}));r.readEntry(),r.on("entry",a=>{let t;try{t=S(c,a.fileName)}catch(n){return r.close(),e(n)}if(/\/$/.test(a.fileName)){try{u.mkdirSync(t,{recursive:!0})}catch(n){console.warn("[extractZip] mkdir for directory entry failed, skip this dir",{dirPath:t,code:n.code,message:n.message}),r.readEntry();return}r.readEntry()}else r.openReadStream(a,(n,y)=>{if(n)return e(new E(`Failed to read zip entry: ${n.message}`,{entry:a.fileName,originalError:n.message}));const s=t,g=w.dirname(s);try{u.mkdirSync(g,{recursive:!0})}catch(m){console.warn("[extractZip] mkdir for file entry failed, skip this file",{dirPath:g,filePath:s,code:m.code,message:m.message}),r.readEntry();return}try{if(u.existsSync(s)&&u.statSync(s).isDirectory()){r.readEntry();return}}catch(m){return e(new E(`Failed to check file status: ${m.message}`,{filePath:s,originalError:m.message}))}const l=u.createWriteStream(s);y.pipe(l),l.on("close",()=>{r.readEntry()}),l.on("error",m=>{e(new E(`Failed to write file: ${m.message}`,{filePath:s,originalError:m.message}))})})}),r.on("end",()=>{d()}),r.on("error",a=>{e(new E(`Error occurred during unzip: ${a.message}`,{zipPath:o,originalError:a.message}))})})})}const f=new Map,k=50;function x(o){return new Promise(c=>{try{const d=u.statSync(o),e=`${o}:${d.mtimeMs}:${d.size}`;if(f.has(e))return c(f.get(e));h.open(o,{lazyEntries:!0},(i,r)=>{if(i)return c(null);const a=new Map;r.readEntry(),r.on("entry",t=>{const n=t.fileName.replace(/\\/g,"/");/\/$/.test(t.fileName)||a.set(n,t),r.readEntry()}),r.on("end",()=>{r.close(),f.size>=k&&Array.from(f.keys()).slice(0,Math.floor(k/2)).forEach(n=>f.delete(n)),f.set(e,a),c(a)}),r.on("error",()=>{r.close(),c(null)})})}catch{c(null)}})}function p(o,c,d){return new Promise(async e=>{try{const i=await x(o);if(!i)return e(!1);const r=c.replace(/^[\/\\]+/,"").replace(/\\/g,"/");if(!i.has(r))return e(!1);h.open(o,{lazyEntries:!1},(a,t)=>{if(a)return e(!1);let n=null;for(const y of t.entries)if(y.fileName.replace(/\\/g,"/")===r&&!/\/$/.test(y.fileName)){n=y;break}if(!n)return t.close(),e(!1);t.openReadStream(n,(y,s)=>{if(y||!s)return t.close(),e(!1);const g=w.dirname(d);try{u.mkdirSync(g,{recursive:!0})}catch{return t.close(),e(!1)}const l=u.createWriteStream(d);s.pipe(l),l.on("close",()=>{t.close(),e(!0)}),l.on("error",()=>{t.close(),e(!1)})})})}catch{e(!1)}})}export{$ as extractZip,p as extractSingleFileFromZip};
@@ -1,2 +1,2 @@
1
- import m from"fs";import h from"path";import C from"archiver";import P from"../../appConfig/index.js";import{log as s}from"../log/logUtils.js";import{ValidationError as y,SystemError as z}from"../error/errorHandler.js";const _=100*1024*1024,O=P.DOWNLOAD_MAX_FILE_SIZE_BYTES||_;async function x(d,u,n,g,f){const r=[],w=await m.promises.readdir(d,{withFileTypes:!0});w.sort((i,t)=>i.isDirectory()&&!t.isDirectory()?-1:!i.isDirectory()&&t.isDirectory()?1:i.name.toLowerCase().localeCompare(t.name.toLowerCase()));for(const i of w){const t=h.join(d,i.name);if(!(i.name.startsWith(".")&&i.name!==".gitignore"||(P.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(i.name))&&!(i.isDirectory()&&P.TRAVERSE_EXCLUDE_DIRS.includes(i.name)))if(i.isDirectory()){const e=await x(t,u,n,g,f);if(e.length===0){const c=u||d,l=h.relative(c,t).replace(/\\/g,"/");r.push({name:l,isDir:!0})}else r.push(...e)}else try{const e=u||d,c=h.relative(e,t).replace(/\\/g,"/"),l=i.isSymbolicLink();let o=null;if(g){const R=c.split("/").map(E=>encodeURIComponent(E)).join("/");o=`${g}/${R}`,f&&(o+=`?customTargetDir=${encodeURIComponent(f)}`)}const a={name:c,isDir:!1,fileProxyUrl:o,isLink:l};r.push(a)}catch(e){s(n,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${t}`,{error:e.message})}}return r}async function A(d,u,n,g,f=""){const r=await m.promises.readdir(h.join(d,f),{withFileTypes:!0});let w=0;for(const i of r){const t=f?h.join(f,i.name):i.name,p=t.split(h.sep).filter(Boolean);if(p.some(o=>o.startsWith(".")))continue;const e=p[p.length-1];if(u.includes(e)||p.some(o=>n.includes(o)))continue;const c=h.join(d,t);let l;try{l=await m.promises.lstat(c)}catch(o){s(g,"WARN","Error occurred when getting file stats, skipping",{filePath:t.replace(/\\/g,"/"),error:o.message});continue}l.isSymbolicLink()||l.nlink>1||(l.isDirectory()?w+=await A(d,u,n,g,t):l.isFile()&&(w+=l.size))}return w}async function L(d,u,n,g){const f=Date.now(),r=`computer:${d}:${u}`,w=P.COMPUTER_WORKSPACE_DIR;if(!d)throw new y("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!u)throw new y("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const i=String(d),t=String(u),p=g&&g.trim()?g:h.join(w,i,t);if(!m.existsSync(p))return s(r,"INFO","Directory does not exist, returning empty list",{targetDir:p,userId:i,cId:t}),{files:[]};s(r,"DEBUG","Start getting user file list",{targetDir:p,userId:i,cId:t});try{const e=await x(p,p,r,n,g);return s(r,"INFO","User file list obtained successfully",{fileCount:e.length,targetDir:p,userId:i,cId:t,elapsedMs:Date.now()-f}),{files:e}}catch(e){throw s(r,"ERROR","Failed to get user file list",{targetDir:p,userId:i,cId:t,error:e.message,elapsedMs:Date.now()-f}),new z(`Failed to get file list: ${e.message}`,{targetDir:p,originalError:e.message})}}async function W(d,u,n,g){const f=Date.now(),r=`computer:${d}:${u}`,w=P.COMPUTER_WORKSPACE_DIR;if(!d)throw new y("userId cannot be empty",{field:"userId"});if(!u)throw new y("cId cannot be empty",{field:"cId"});if(!Array.isArray(n))throw new y("files must be an array",{field:"files"});const i=String(d),t=String(u),p=g&&g.trim()?g:h.join(w,i,t);m.existsSync(p)||m.mkdirSync(p,{recursive:!0});for(let e=0;e<n.length;e++){const c=n[e];if(!c||typeof c.operation!="string")throw new y(`files[${e}].operation cannot be empty`,{field:`files[${e}].operation`});if(!c.name||typeof c.name!="string")throw new y(`files[${e}].name cannot be empty`,{field:`files[${e}].name`});const l=c.operation.toLowerCase();if(!["create","delete","rename","modify"].includes(l))throw new y(`files[${e}].operation must be one of create, delete, rename or modify`,{field:`files[${e}].operation`});if(l==="rename"&&!c.renameFrom)throw new y(`files[${e}].renameFrom cannot be empty (rename operation requires)`,{field:`files[${e}].renameFrom`});if(l==="modify"&&c.isDir!==!0&&typeof c.contents!="string")throw new y(`files[${e}].contents must be a string (modify operation requires)`,{field:`files[${e}].contents`})}s(r,"DEBUG","Start updating user files",{userId:i,cId:t,filesCount:n.length});try{for(const e of n){const c=e.operation.toLowerCase(),l=e.name,o=h.normalize(l).replace(/^[\/\\]+/,""),a=h.join(p,o),R=h.resolve(a),E=h.resolve(p);if(!R.startsWith(E+h.sep)&&R!==E){s(r,"WARN","File path is not secure, skipping",{filePath:o,resolvedPath:R});continue}switch(c){case"create":{if(e.isDir===!0){if(m.existsSync(a)){if((await m.promises.stat(a)).isFile())throw new y("Cannot create directory, file with the same name already exists",{filePath:o});s(r,"INFO","Directory already exists, skipping creation",{filePath:o});break}await m.promises.mkdir(a,{recursive:!0}),s(r,"INFO","Directory created successfully",{filePath:o});break}if(m.existsSync(a)){if((await m.promises.stat(a)).isDirectory())throw new y("Cannot create file, directory with the same name already exists",{filePath:o});s(r,"INFO","File already exists, skipping creation",{filePath:o});break}await m.promises.mkdir(h.dirname(a),{recursive:!0});const S=e.contents||"";await m.promises.writeFile(a,S,"utf8"),s(r,"INFO","File created successfully",{filePath:o});break}case"delete":{m.existsSync(a)?(await m.promises.stat(a)).isDirectory()?(await m.promises.rm(a,{recursive:!0,force:!0}),s(r,"INFO","Directory deleted successfully",{filePath:o})):(await m.promises.unlink(a),s(r,"INFO","File deleted successfully",{filePath:o})):s(r,"WARN","The file or directory to be deleted does not exist",{filePath:o});break}case"rename":{const S=e.renameFrom;if(!S||typeof S!="string"){s(r,"WARN","Rename operation missing renameFrom",{filePath:o});break}const I=h.normalize(S).replace(/^[\/\\]+/,""),D=h.join(p,I),N=h.resolve(D);if(!N.startsWith(E+h.sep)&&N!==E){s(r,"WARN","Source path is not secure, skipping rename",{sourcePath:I,targetPath:o});break}if(m.existsSync(D)){const b=(await m.promises.stat(D)).isDirectory();await m.promises.mkdir(h.dirname(a),{recursive:!0}),await m.promises.rename(D,a),s(r,"INFO",b?"Directory renamed successfully":"File renamed successfully",{sourcePath:I,targetPath:o})}else s(r,"WARN","The file or directory to be renamed does not exist",{sourcePath:I});break}case"modify":{if(!m.existsSync(a)){s(r,"WARN","The file to be modified does not exist",{filePath:o});break}if((await m.promises.stat(a)).isDirectory()){s(r,"INFO","The target is a directory, skipping modification",{filePath:o});break}const I=typeof e.contents=="string"?e.contents:"";if(await m.promises.readFile(a,"utf8")===I){s(r,"INFO","File content has no changes, skipping write",{filePath:o});break}await m.promises.writeFile(a,I,"utf8"),s(r,"INFO","File modified successfully",{filePath:o});break}default:{s(r,"WARN","Unsupported operation type",{operation:c,filePath:o});break}}}return s(r,"INFO","User files updated successfully",{userId:i,cId:t,filesCount:n.length,elapsedMs:Date.now()-f}),{success:!0,message:"User files updated successfully",userId:i,cId:t,filesCount:n.length}}catch(e){throw s(r,"ERROR","User files updated failed",{userId:i,cId:t,error:e.message,elapsedMs:Date.now()-f}),new z(`User files updated failed: ${e.message}`,{userId:i,cId:t,originalError:e.message})}}async function $(d,u,n,g,f){const r=Date.now(),w=`computer:${d}:${u}`,i=P.COMPUTER_WORKSPACE_DIR;if(!d)throw new y("userId cannot be empty",{field:"userId"});if(!u)throw new y("cId cannot be empty",{field:"cId"});if(!n)throw new y("file cannot be empty",{field:"file"});if(!g||typeof g!="string")throw new y("filePath cannot be empty",{field:"filePath"});const t=String(d),p=String(u),e=f&&f.trim()?f:h.join(i,t,p);m.existsSync(e)||m.mkdirSync(e,{recursive:!0});const c=h.normalize(g).replace(/^[\/\\]+/,""),l=h.join(e,c),o=h.resolve(l),a=h.resolve(e);if(!o.startsWith(a+h.sep)&&o!==a)throw new y("File path is not secure, cannot exceed user directory",{field:"filePath",providedPath:g,resolvedPath:o});try{if(await m.promises.mkdir(h.dirname(l),{recursive:!0}),n.buffer)await m.promises.writeFile(l,n.buffer);else if(typeof n.contents=="string")await m.promises.writeFile(l,n.contents,"utf8");else throw new y("File content format is incorrect",{field:"file",hasBuffer:!!n.buffer,hasContents:typeof n.contents});return s(w,"INFO","File uploaded successfully",{userId:t,cId:p,filePath:c,targetPath:o,fileSize:n.buffer?n.buffer.length:n.contents?n.contents.length:0,elapsedMs:Date.now()-r}),{success:!0,message:"File uploaded successfully",fileSize:n.buffer?n.buffer.length:n.contents?n.contents.length:0}}catch(R){throw s(w,"ERROR","File upload failed",{userId:t,cId:p,filePath:c,error:R.message,elapsedMs:Date.now()-r}),new z(`File upload failed: ${R.message}`,{userId:t,cId:p,filePath:c,originalError:R.message})}}async function v(d,u,n,g,f){const r=Date.now(),w=`computer:${d}:${u}`;if(!d)throw new y("userId cannot be empty",{field:"userId"});if(!u)throw new y("cId cannot be empty",{field:"cId"});if(!Array.isArray(n))throw new y("files must be an array",{field:"files"});if(!Array.isArray(g))throw new y("filePaths must be an array",{field:"filePaths"});if(n.length!==g.length)throw new y(`File count (${n.length}) does not match path count (${g.length})`,{field:"filePaths"});s(w,"DEBUG","Start batch uploading files",{userId:d,cId:u,filesCount:n.length});const i=[];try{for(let e=0;e<n.length;e++){const c=n[e],l=g[e];if(!c){s(w,"WARN","Empty file object encountered in batch upload, skipping",{index:e,filePath:l}),i.push({success:!1,filePath:l,error:"Empty file object"});continue}if(!l||typeof l!="string"){s(w,"WARN","Invalid file path in batch upload, skipping",{index:e,originalname:c.originalname}),i.push({success:!1,filePath:l||"",originalname:c.originalname,error:"Invalid file path"});continue}try{const o=await $(d,u,c,l,f);i.push({success:!0,filePath:l,originalname:c.originalname,...o})}catch(o){s(w,"ERROR","Single file upload failed in batch upload",{filePath:l,originalname:c.originalname,error:o.message}),i.push({success:!1,filePath:l,originalname:c.originalname,error:o.message})}}const t=i.filter(e=>e.success).length,p=i.filter(e=>!e.success).length;return s(w,"INFO","Batch upload files completed",{userId:d,cId:u,totalCount:n.length,successCount:t,failCount:p,elapsedMs:Date.now()-r}),{success:!0,message:"Batch upload completed",totalCount:n.length,successCount:t,failCount:p,results:i}}catch(t){throw s(w,"ERROR","Batch upload files failed",{userId:d,cId:u,error:t.message,elapsedMs:Date.now()-r}),new z(`Batch upload files failed: ${t.message}`,{userId:d,cId:u,originalError:t.message})}}async function U(d,u,n){const g=Date.now(),f=`computer:${d}:${u}`,r=P.COMPUTER_WORKSPACE_DIR;if(!d)throw new y("userId cannot be empty",{field:"userId"});if(!u)throw new y("cId cannot be empty",{field:"cId"});if(!r)throw new z("COMPUTER_WORKSPACE_DIR is not configured, cannot create zip");const w=String(d),i=String(u),t=n&&n.trim()?n:h.join(r,w,i);if(!m.existsSync(t)){const a=`${w}_${i}.zip`;s(f,"WARN","Workspace directory does not exist, returning empty zip",{targetDir:t,userId:w,cId:i,zipFileName:a});const R=C("zip",{zlib:{level:9}});return R.append(null,{name:`${w}_${i}/`,type:"directory"}),R.on("warning",E=>{if(E.code==="ENOENT")s(f,"WARN","Encountered file problem when creating empty zip",{message:E.message,code:E.code});else throw s(f,"ERROR","Encountered warning when creating empty zip",{message:E.message,code:E.code}),E}),R.on("error",E=>{s(f,"ERROR","Failed to create empty zip",{message:E.message})}),{archive:R,zipFileName:a}}const p=`${w}_${i}.zip`;s(f,"DEBUG","Start creating workspace directory zip",{targetDir:t,zipFileName:p});const e=C("zip",{zlib:{level:9}}),c=P.CONTENT_TRAVERSE_EXCLUDE_FILES||[],l=P.TRAVERSE_EXCLUDE_DIRS||[],o=await A(t,c,l,f);if(o>O){const a=O/1024/1024,R=(o/1024/1024).toFixed(2);throw s(f,"WARN","Download rejected due to oversized workspace",{targetDir:t,downloadableSize:o,maxSizeBytes:O}),new y(`Download failed: total file size ${R}MB exceeds limit ${a}MB`,{field:"downloadSize",downloadableSize:o,maxSizeBytes:O})}return e.directory(t,`${w}_${i}`,a=>{const R=a.name||"",E=R.split(/[\/\\]/).filter(Boolean);if(E.some(I=>I.startsWith(".")))return!1;const S=E[E.length-1];if(c.includes(S)||E.some(I=>l.includes(I)))return!1;try{const I=h.join(t,R),D=m.lstatSync(I);if(D.isSymbolicLink()||D.nlink>1)return!1}catch(I){return s(f,"WARN","Error occurred when detecting link file, skipping",{filePath:R,error:I.message}),!1}return a}),e.on("warning",a=>{if(a.code==="ENOENT")s(f,"WARN","Encountered file problem when creating zip",{message:a.message,code:a.code});else throw s(f,"ERROR","Encountered warning when creating zip",{message:a.message,code:a.code}),a}),e.on("error",a=>{s(f,"ERROR","Failed to create zip",{message:a.message,elapsedMs:Date.now()-g})}),e.on("end",()=>{s(f,"INFO","Workspace directory zip created successfully",{targetDir:t,zipFileName:p,elapsedMs:Date.now()-g})}),{archive:e,zipFileName:p}}async function M(d,u,n=200){const g=Date.now(),f=`computer:${d}:${u}`;if(!d)throw new y("userId cannot be empty",{field:"userId"});if(!u)throw new y("cId cannot be empty",{field:"cId"});const r=String(d),w=String(u),i=P.COMPUTER_WORKSPACE_DIR;if(!i)return s(f,"WARN","COMPUTER_WORKSPACE_DIR is not configured"),{success:!0,message:"Log workspace is not configured",logs:[],totalLines:0,startIndex:1,logFileName:null};const t=h.join(i,r,w,".logs");if(!m.existsSync(t))return s(f,"DEBUG","Log directory does not exist",{logDir:t}),{success:!0,message:"Log directory does not exist",logs:[],totalLines:0,startIndex:1,logFileName:null};const e=(await m.promises.readdir(t,{withFileTypes:!0})).filter(F=>F.isFile()).map(F=>F.name);if(e.length===0)return s(f,"DEBUG","No log file found",{logDir:t}),{success:!0,message:"No log file found",logs:[],totalLines:0,startIndex:1,logFileName:null};const c=[];for(const F of e){const b=h.join(t,F),k=await m.promises.stat(b);c.push({name:F,fullPath:b,mtime:k.mtimeMs,size:k.size})}c.sort((F,b)=>b.mtime-F.mtime);const l=c[0],a=(await m.promises.readFile(l.fullPath,"utf8")).split(`
2
- `).filter(F=>F.length>0),R=a.length,E=Math.max(1,n),S=Math.max(0,R-E),I=S+1,N=a.slice(S).map((F,b)=>({line:I+b,content:F}));return s(f,"DEBUG","Get latest logs",{fileName:l.name,fileSize:l.size,totalLines:R,returnedLines:N.length,elapsedMs:Date.now()-g}),{success:!0,message:"Get log successfully",logs:N,totalLines:R,startIndex:I,logFileName:l.name}}export{L as getFileList,W as updateFiles,$ as uploadFile,v as uploadFiles,U as downloadAllFiles,M as getLatestLogs};
1
+ import i from"fs";import p from"path";import _ from"archiver";import P from"../../appConfig/index.js";import{log as n}from"../log/logUtils.js";import{ValidationError as y,SystemError as N,FileError as j}from"../error/errorHandler.js";import{extractZip as M}from"../common/zipUtils.js";import{moveDirectory as L,movePath as x}from"../common/fileSystemUtils.js";const b=new Set([".git",".agents",".claude",".codex",".opencode",".tmp",".logs"]),U=100*1024*1024,v=P.DOWNLOAD_MAX_FILE_SIZE_BYTES||U;async function C(o,d,r,f,l){const t=[],g=await i.promises.readdir(o,{withFileTypes:!0});g.sort((c,s)=>c.isDirectory()&&!s.isDirectory()?-1:!c.isDirectory()&&s.isDirectory()?1:c.name.toLowerCase().localeCompare(s.name.toLowerCase()));for(const c of g){const s=p.join(o,c.name);if(!(c.name.startsWith(".")&&c.name!==".gitignore"||(P.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(c.name))&&!(c.isDirectory()&&P.TRAVERSE_EXCLUDE_DIRS.includes(c.name)))if(c.isDirectory()){const e=await C(s,d,r,f,l);if(e.length===0){const w=d||o,u=p.relative(w,s).replace(/\\/g,"/");t.push({name:u,isDir:!0})}else t.push(...e)}else try{const e=d||o,w=p.relative(e,s).replace(/\\/g,"/"),u=c.isSymbolicLink();let m=null;if(f){const E=w.split("/").map(R=>encodeURIComponent(R)).join("/");m=`${f}/${E}`,l&&(m+=`?customTargetDir=${encodeURIComponent(l)}`)}const a={name:w,isDir:!1,fileProxyUrl:m,isLink:u};t.push(a)}catch(e){n(r,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${s}`,{error:e.message})}}return t}async function $(o,d,r,f,l=""){const t=await i.promises.readdir(p.join(o,l),{withFileTypes:!0});let g=0;for(const c of t){const s=l?p.join(l,c.name):c.name,h=s.split(p.sep).filter(Boolean);if(h.some(m=>m.startsWith(".")))continue;const e=h[h.length-1];if(d.includes(e)||h.some(m=>r.includes(m)))continue;const w=p.join(o,s);let u;try{u=await i.promises.lstat(w)}catch(m){n(f,"WARN","Error occurred when getting file stats, skipping",{filePath:s.replace(/\\/g,"/"),error:m.message});continue}u.isSymbolicLink()||u.nlink>1||(u.isDirectory()?g+=await $(o,d,r,f,s):u.isFile()&&(g+=u.size))}return g}async function T(o,d,r,f){const l=Date.now(),t=`computer:${o}:${d}`,g=P.COMPUTER_WORKSPACE_DIR;if(!o)throw new y("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!d)throw new y("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const c=String(o),s=String(d),h=f&&f.trim()?f:p.join(g,c,s);if(!i.existsSync(h))return n(t,"INFO","Directory does not exist, returning empty list",{targetDir:h,userId:c,cId:s}),{files:[]};n(t,"DEBUG","Start getting user file list",{targetDir:h,userId:c,cId:s});try{const e=await C(h,h,t,r,f);return n(t,"INFO","User file list obtained successfully",{fileCount:e.length,targetDir:h,userId:c,cId:s,elapsedMs:Date.now()-l}),{files:e}}catch(e){throw n(t,"ERROR","Failed to get user file list",{targetDir:h,userId:c,cId:s,error:e.message,elapsedMs:Date.now()-l}),new N(`Failed to get file list: ${e.message}`,{targetDir:h,originalError:e.message})}}async function B(o,d,r,f){const l=Date.now(),t=`computer:${o}:${d}`,g=P.COMPUTER_WORKSPACE_DIR;if(!o)throw new y("userId cannot be empty",{field:"userId"});if(!d)throw new y("cId cannot be empty",{field:"cId"});if(!Array.isArray(r))throw new y("files must be an array",{field:"files"});const c=String(o),s=String(d),h=f&&f.trim()?f:p.join(g,c,s);i.existsSync(h)||i.mkdirSync(h,{recursive:!0});for(let e=0;e<r.length;e++){const w=r[e];if(!w||typeof w.operation!="string")throw new y(`files[${e}].operation cannot be empty`,{field:`files[${e}].operation`});if(!w.name||typeof w.name!="string")throw new y(`files[${e}].name cannot be empty`,{field:`files[${e}].name`});const u=w.operation.toLowerCase();if(!["create","delete","rename","modify"].includes(u))throw new y(`files[${e}].operation must be one of create, delete, rename or modify`,{field:`files[${e}].operation`});if(u==="rename"&&!w.renameFrom)throw new y(`files[${e}].renameFrom cannot be empty (rename operation requires)`,{field:`files[${e}].renameFrom`});if(u==="modify"&&w.isDir!==!0&&typeof w.contents!="string")throw new y(`files[${e}].contents must be a string (modify operation requires)`,{field:`files[${e}].contents`})}n(t,"DEBUG","Start updating user files",{userId:c,cId:s,filesCount:r.length});try{for(const e of r){const w=e.operation.toLowerCase(),u=e.name,m=p.normalize(u).replace(/^[\/\\]+/,""),a=p.join(h,m),E=p.resolve(a),R=p.resolve(h);if(!E.startsWith(R+p.sep)&&E!==R){n(t,"WARN","File path is not secure, skipping",{filePath:m,resolvedPath:E});continue}switch(w){case"create":{if(e.isDir===!0){if(i.existsSync(a)){if((await i.promises.stat(a)).isFile())throw new y("Cannot create directory, file with the same name already exists",{filePath:m});n(t,"INFO","Directory already exists, skipping creation",{filePath:m});break}await i.promises.mkdir(a,{recursive:!0}),n(t,"INFO","Directory created successfully",{filePath:m});break}if(i.existsSync(a)){if((await i.promises.stat(a)).isDirectory())throw new y("Cannot create file, directory with the same name already exists",{filePath:m});n(t,"INFO","File already exists, skipping creation",{filePath:m});break}await i.promises.mkdir(p.dirname(a),{recursive:!0});const S=e.contents||"";await i.promises.writeFile(a,S,"utf8"),n(t,"INFO","File created successfully",{filePath:m});break}case"delete":{i.existsSync(a)?(await i.promises.stat(a)).isDirectory()?(await i.promises.rm(a,{recursive:!0,force:!0}),n(t,"INFO","Directory deleted successfully",{filePath:m})):(await i.promises.unlink(a),n(t,"INFO","File deleted successfully",{filePath:m})):n(t,"WARN","The file or directory to be deleted does not exist",{filePath:m});break}case"rename":{const S=e.renameFrom;if(!S||typeof S!="string"){n(t,"WARN","Rename operation missing renameFrom",{filePath:m});break}const I=p.normalize(S).replace(/^[\/\\]+/,""),D=p.join(h,I),O=p.resolve(D);if(!O.startsWith(R+p.sep)&&O!==R){n(t,"WARN","Source path is not secure, skipping rename",{sourcePath:I,targetPath:m});break}if(i.existsSync(D)){const k=(await i.promises.stat(D)).isDirectory();await i.promises.mkdir(p.dirname(a),{recursive:!0}),await i.promises.rename(D,a),n(t,"INFO",k?"Directory renamed successfully":"File renamed successfully",{sourcePath:I,targetPath:m})}else n(t,"WARN","The file or directory to be renamed does not exist",{sourcePath:I});break}case"modify":{if(!i.existsSync(a)){n(t,"WARN","The file to be modified does not exist",{filePath:m});break}if((await i.promises.stat(a)).isDirectory()){n(t,"INFO","The target is a directory, skipping modification",{filePath:m});break}const I=typeof e.contents=="string"?e.contents:"";if(await i.promises.readFile(a,"utf8")===I){n(t,"INFO","File content has no changes, skipping write",{filePath:m});break}await i.promises.writeFile(a,I,"utf8"),n(t,"INFO","File modified successfully",{filePath:m});break}default:{n(t,"WARN","Unsupported operation type",{operation:w,filePath:m});break}}}return n(t,"INFO","User files updated successfully",{userId:c,cId:s,filesCount:r.length,elapsedMs:Date.now()-l}),{success:!0,message:"User files updated successfully",userId:c,cId:s,filesCount:r.length}}catch(e){throw n(t,"ERROR","User files updated failed",{userId:c,cId:s,error:e.message,elapsedMs:Date.now()-l}),new N(`User files updated failed: ${e.message}`,{userId:c,cId:s,originalError:e.message})}}async function A(o,d,r,f,l){const t=Date.now(),g=`computer:${o}:${d}`,c=P.COMPUTER_WORKSPACE_DIR;if(!o)throw new y("userId cannot be empty",{field:"userId"});if(!d)throw new y("cId cannot be empty",{field:"cId"});if(!r)throw new y("file cannot be empty",{field:"file"});if(!f||typeof f!="string")throw new y("filePath cannot be empty",{field:"filePath"});const s=String(o),h=String(d),e=l&&l.trim()?l:p.join(c,s,h);i.existsSync(e)||i.mkdirSync(e,{recursive:!0});const w=p.normalize(f).replace(/^[\/\\]+/,""),u=p.join(e,w),m=p.resolve(u),a=p.resolve(e);if(!m.startsWith(a+p.sep)&&m!==a)throw new y("File path is not secure, cannot exceed user directory",{field:"filePath",providedPath:f,resolvedPath:m});try{if(await i.promises.mkdir(p.dirname(u),{recursive:!0}),r.buffer)await i.promises.writeFile(u,r.buffer);else if(typeof r.contents=="string")await i.promises.writeFile(u,r.contents,"utf8");else throw new y("File content format is incorrect",{field:"file",hasBuffer:!!r.buffer,hasContents:typeof r.contents});return n(g,"INFO","File uploaded successfully",{userId:s,cId:h,filePath:w,targetPath:m,fileSize:r.buffer?r.buffer.length:r.contents?r.contents.length:0,elapsedMs:Date.now()-t}),{success:!0,message:"File uploaded successfully",fileSize:r.buffer?r.buffer.length:r.contents?r.contents.length:0}}catch(E){throw n(g,"ERROR","File upload failed",{userId:s,cId:h,filePath:w,error:E.message,elapsedMs:Date.now()-t}),new N(`File upload failed: ${E.message}`,{userId:s,cId:h,filePath:w,originalError:E.message})}}async function G(o,d,r,f,l){const t=Date.now(),g=`computer:${o}:${d}`;if(!o)throw new y("userId cannot be empty",{field:"userId"});if(!d)throw new y("cId cannot be empty",{field:"cId"});if(!Array.isArray(r))throw new y("files must be an array",{field:"files"});if(!Array.isArray(f))throw new y("filePaths must be an array",{field:"filePaths"});if(r.length!==f.length)throw new y(`File count (${r.length}) does not match path count (${f.length})`,{field:"filePaths"});n(g,"DEBUG","Start batch uploading files",{userId:o,cId:d,filesCount:r.length});const c=[];try{for(let e=0;e<r.length;e++){const w=r[e],u=f[e];if(!w){n(g,"WARN","Empty file object encountered in batch upload, skipping",{index:e,filePath:u}),c.push({success:!1,filePath:u,error:"Empty file object"});continue}if(!u||typeof u!="string"){n(g,"WARN","Invalid file path in batch upload, skipping",{index:e,originalname:w.originalname}),c.push({success:!1,filePath:u||"",originalname:w.originalname,error:"Invalid file path"});continue}try{const m=await A(o,d,w,u,l);c.push({success:!0,filePath:u,originalname:w.originalname,...m})}catch(m){n(g,"ERROR","Single file upload failed in batch upload",{filePath:u,originalname:w.originalname,error:m.message}),c.push({success:!1,filePath:u,originalname:w.originalname,error:m.message})}}const s=c.filter(e=>e.success).length,h=c.filter(e=>!e.success).length;return n(g,"INFO","Batch upload files completed",{userId:o,cId:d,totalCount:r.length,successCount:s,failCount:h,elapsedMs:Date.now()-t}),{success:!0,message:"Batch upload completed",totalCount:r.length,successCount:s,failCount:h,results:c}}catch(s){throw n(g,"ERROR","Batch upload files failed",{userId:o,cId:d,error:s.message,elapsedMs:Date.now()-t}),new N(`Batch upload files failed: ${s.message}`,{userId:o,cId:d,originalError:s.message})}}async function K(o,d,r){const f=Date.now(),l=`computer:${o}:${d}`,t=P.COMPUTER_WORKSPACE_DIR;if(!o)throw new y("userId cannot be empty",{field:"userId"});if(!d)throw new y("cId cannot be empty",{field:"cId"});if(!t)throw new N("COMPUTER_WORKSPACE_DIR is not configured, cannot create zip");const g=String(o),c=String(d),s=r&&r.trim()?r:p.join(t,g,c);if(!i.existsSync(s)){const a=`${g}_${c}.zip`;n(l,"WARN","Workspace directory does not exist, returning empty zip",{targetDir:s,userId:g,cId:c,zipFileName:a});const E=_("zip",{zlib:{level:9}});return E.append(null,{name:`${g}_${c}/`,type:"directory"}),E.on("warning",R=>{if(R.code==="ENOENT")n(l,"WARN","Encountered file problem when creating empty zip",{message:R.message,code:R.code});else throw n(l,"ERROR","Encountered warning when creating empty zip",{message:R.message,code:R.code}),R}),E.on("error",R=>{n(l,"ERROR","Failed to create empty zip",{message:R.message})}),{archive:E,zipFileName:a}}const h=`${g}_${c}.zip`;n(l,"DEBUG","Start creating workspace directory zip",{targetDir:s,zipFileName:h});const e=_("zip",{zlib:{level:9}}),w=P.CONTENT_TRAVERSE_EXCLUDE_FILES||[],u=P.TRAVERSE_EXCLUDE_DIRS||[],m=await $(s,w,u,l);if(m>v){const a=v/1024/1024,E=(m/1024/1024).toFixed(2);throw n(l,"WARN","Download rejected due to oversized workspace",{targetDir:s,downloadableSize:m,maxSizeBytes:v}),new y(`Download failed: total file size ${E}MB exceeds limit ${a}MB`,{field:"downloadSize",downloadableSize:m,maxSizeBytes:v})}return e.directory(s,`${g}_${c}`,a=>{const E=a.name||"",R=E.split(/[\/\\]/).filter(Boolean);if(R.some(I=>I.startsWith(".")))return!1;const S=R[R.length-1];if(w.includes(S)||R.some(I=>u.includes(I)))return!1;try{const I=p.join(s,E),D=i.lstatSync(I);if(D.isSymbolicLink()||D.nlink>1)return!1}catch(I){return n(l,"WARN","Error occurred when detecting link file, skipping",{filePath:E,error:I.message}),!1}return a}),e.on("warning",a=>{if(a.code==="ENOENT")n(l,"WARN","Encountered file problem when creating zip",{message:a.message,code:a.code});else throw n(l,"ERROR","Encountered warning when creating zip",{message:a.message,code:a.code}),a}),e.on("error",a=>{n(l,"ERROR","Failed to create zip",{message:a.message,elapsedMs:Date.now()-f})}),e.on("end",()=>{n(l,"INFO","Workspace directory zip created successfully",{targetDir:s,zipFileName:h,elapsedMs:Date.now()-f})}),{archive:e,zipFileName:h}}async function X(o,d,r=200){const f=Date.now(),l=`computer:${o}:${d}`;if(!o)throw new y("userId cannot be empty",{field:"userId"});if(!d)throw new y("cId cannot be empty",{field:"cId"});const t=String(o),g=String(d),c=P.COMPUTER_WORKSPACE_DIR;if(!c)return n(l,"WARN","COMPUTER_WORKSPACE_DIR is not configured"),{success:!0,message:"Log workspace is not configured",logs:[],totalLines:0,startIndex:1,logFileName:null};const s=p.join(c,t,g,".logs");if(!i.existsSync(s))return n(l,"DEBUG","Log directory does not exist",{logDir:s}),{success:!0,message:"Log directory does not exist",logs:[],totalLines:0,startIndex:1,logFileName:null};const e=(await i.promises.readdir(s,{withFileTypes:!0})).filter(F=>F.isFile()).map(F=>F.name);if(e.length===0)return n(l,"DEBUG","No log file found",{logDir:s}),{success:!0,message:"No log file found",logs:[],totalLines:0,startIndex:1,logFileName:null};const w=[];for(const F of e){const k=p.join(s,F),z=await i.promises.stat(k);w.push({name:F,fullPath:k,mtime:z.mtimeMs,size:z.size})}w.sort((F,k)=>k.mtime-F.mtime);const u=w[0],a=(await i.promises.readFile(u.fullPath,"utf8")).split(`
2
+ `).filter(F=>F.length>0),E=a.length,R=Math.max(1,r),S=Math.max(0,E-R),I=S+1,O=a.slice(S).map((F,k)=>({line:I+k,content:F}));return n(l,"DEBUG","Get latest logs",{fileName:u.name,fileSize:u.size,totalLines:E,returnedLines:O.length,elapsedMs:Date.now()-f}),{success:!0,message:"Get log successfully",logs:O,totalLines:E,startIndex:I,logFileName:u.name}}async function W(o,d){try{const f=(await i.promises.readdir(o,{withFileTypes:!0})).filter(c=>!c.name.startsWith(".")&&c.name!=="node_modules");if(f.length!==1||!f[0].isDirectory())return;const l=p.join(o,f[0].name),t=p.join(o,`..tmp_${Date.now()}_${Math.round(Math.random()*1e6)}`);try{await i.promises.rename(l,t)}catch(c){if(c.code==="EXDEV")await i.promises.cp(l,t,{recursive:!0}),await i.promises.rm(l,{recursive:!0,force:!0});else throw c}const g=await i.promises.readdir(t);for(const c of g){const s=p.join(t,c),h=p.join(o,c);try{await i.promises.rename(s,h)}catch(e){if(e.code==="EXDEV")(await i.promises.lstat(s)).isDirectory()?await L(s,h):(await i.promises.copyFile(s,h),await i.promises.unlink(s));else throw e}}await i.promises.rm(t,{recursive:!0,force:!0}),n(d,"INFO","Removed single top-level directory from imported zip",{removedDir:f[0].name})}catch(r){n(d,"WARN","Failed to remove top-level directory from imported zip, continuing",{error:r.message})}}async function V(o,d){if(!i.existsSync(o)){await i.promises.mkdir(o,{recursive:!0});return}const r=await i.promises.readdir(o,{withFileTypes:!0});for(const f of r){if(b.has(f.name))continue;const l=p.join(o,f.name);await i.promises.rm(l,{recursive:!0,force:!0}),n(d,"DEBUG","Removed workspace entry during import",{name:f.name})}}async function Z(o,d,r){if(await i.promises.mkdir(d,{recursive:!0}),!i.existsSync(o)){await i.promises.mkdir(o,{recursive:!0});return}const f=await i.promises.readdir(o,{withFileTypes:!0});for(const l of f){if(b.has(l.name))continue;const t=p.join(o,l.name),g=p.join(d,l.name);await x(t,g),n(r,"DEBUG","Backed up workspace entry before import",{name:l.name})}}async function q(o,d,r){if(!i.existsSync(o))return;const f=await i.promises.readdir(o,{withFileTypes:!0});for(const l of f){if(b.has(l.name))continue;const t=p.join(o,l.name),g=p.join(d,l.name);await x(t,g)}n(r,"INFO","Workspace restored from backup after import failure")}async function Y(o,d,r){const f=await i.promises.readdir(o,{withFileTypes:!0}),l=[];try{for(const t of f){if(b.has(t.name)){n(r,"INFO","Skipping preserved entry from imported zip",{name:t.name});continue}const g=p.join(o,t.name),c=p.join(d,t.name);await x(g,c),l.push(t.name)}}catch(t){throw t.mergedEntries=l,t}}async function J(o,d,r,f){const l=Date.now(),t=`computer:${o}:${d}`,g=P.COMPUTER_WORKSPACE_DIR;if(!o)throw new y("userId cannot be empty",{field:"userId"});if(!d)throw new y("cId cannot be empty",{field:"cId"});if(!r||!r.path)throw new y("file is required",{field:"file"});if(!g)throw new N("COMPUTER_WORKSPACE_DIR is not configured");if(p.extname(r.originalname||r.filename||"").toLowerCase()!==".zip")throw new y("Only zip files are supported",{field:"file",originalName:r.originalname});const s=String(o),h=String(d),e=f&&f.trim()?f.trim():p.join(g,s,h),w=p.join(e,".tmp"),u=p.join(w,`import_project_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);let m=null;n(t,"INFO","Start importing project from zip",{userId:s,cId:h,targetDir:e,fileName:r.originalname});try{await i.promises.mkdir(e,{recursive:!0}),await i.promises.mkdir(w,{recursive:!0}),await i.promises.mkdir(u,{recursive:!0}),await M(r.path,u),await W(u,t),m=p.join(w,`import_backup_${Date.now()}_${Math.round(Math.random()*1e6)}`),await Z(e,m,t);try{await Y(u,e,t)}catch(a){throw n(t,"ERROR","Merge imported project failed, restoring workspace",{error:a.message,mergedEntries:a.mergedEntries||[]}),await V(e,t),await q(m,e,t),a}return i.existsSync(m)&&(await i.promises.rm(m,{recursive:!0,force:!0}),m=null),n(t,"INFO","Project imported successfully",{userId:s,cId:h,targetDir:e,elapsedMs:Date.now()-l}),{success:!0,message:"Project imported successfully",userId:s,cId:h,targetDir:e}}catch(a){throw n(t,"ERROR","Failed to import project",{userId:s,cId:h,targetDir:e,error:a.message,elapsedMs:Date.now()-l}),a instanceof y||a instanceof N||a instanceof j?a:new N(`Failed to import project: ${a.message}`,{userId:s,cId:h,originalError:a.message})}finally{if(i.existsSync(u))try{await i.promises.rm(u,{recursive:!0,force:!0})}catch(a){n(t,"WARN","Failed to clean import extract directory",{extractRoot:u,error:a.message})}if(m&&i.existsSync(m))try{await i.promises.rm(m,{recursive:!0,force:!0})}catch(a){n(t,"WARN","Failed to clean import backup directory",{backupDir:m,error:a.message})}if(r?.path&&i.existsSync(r.path))try{await i.promises.unlink(r.path)}catch(a){n(t,"WARN","Failed to clean uploaded zip file",{tempZipPath:r.path,error:a.message})}}}export{T as getFileList,B as updateFiles,A as uploadFile,G as uploadFiles,K as downloadAllFiles,X as getLatestLogs,J as importProject,b as IMPORT_PROJECT_PRESERVED_ENTRIES,W as removeTopLevelDir};
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.2",
4
+ "version": "1.3.3",
5
5
  "description": "Cross-platform file service deployment tool with start/stop/restart CLI commands",
6
6
  "type": "module",
7
7
  "main": "index.js",