@zuzjs/pm 0.0.13 → 0.0.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
'use strict';var chunkX4TWGCVL_cjs=require('./chunk-X4TWGCVL.cjs'),child_process=require('child_process'),v=require('http'),y=require('https'),S=require('net'),F=require('chokidar'),I=require('fs'),k=require('os'),u=require('path'),b=require('ws'),E=require('pidusage');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var v__default=/*#__PURE__*/_interopDefault(v);var y__default=/*#__PURE__*/_interopDefault(y);var S__default=/*#__PURE__*/_interopDefault(S);var F__default=/*#__PURE__*/_interopDefault(F);var I__default=/*#__PURE__*/_interopDefault(I);var k__default=/*#__PURE__*/_interopDefault(k);var u__default=/*#__PURE__*/_interopDefault(u);var b__default=/*#__PURE__*/_interopDefault(b);var E__default=/*#__PURE__*/_interopDefault(E);/* ZuzJS Process Manager */
|
|
2
|
-
function W(n,t){return new Promise(e=>{let o=(n.startsWith("https")?y__default.default:v__default.default).get(n,{timeout:t},i=>{e((i.statusCode??500)<500);});o.on("error",()=>e(false)),o.on("timeout",()=>{o.destroy(),e(false);});})}function C(n,t){let[e,r]=n.split(":"),o=Number(r);return new Promise(i=>{let a=S__default.default.createConnection({host:e,port:o},()=>{a.destroy(),i(true);});a.setTimeout(t),a.on("timeout",()=>{a.destroy(),i(false);}),a.on("error",()=>i(false));})}function $(n,t){return new Promise(e=>{let r=setTimeout(()=>e(false),t);child_process.exec(n,o=>{clearTimeout(r),e(!o);});})}async function w(n){let t=(n.timeoutSeconds??5)*1e3;switch(n.type){case "http":return W(n.target,t);case "tcp":return C(n.target,t);case "exec":return $(n.target,t);default:return false}}var m=5e3,M=16e3,d=1e3,L=5e3;async function A(n){return new Promise(t=>{S__default.default.createServer().once("error",()=>t(false)).once("listening",function(){this.close(()=>t(true));}).listen(n);})}async function N(n){if(await A(n))return;let t=k__default.default.platform()==="darwin"?`lsof -ti :${n} | xargs kill -9 2>/dev/null || true`:`fuser -k -9 ${n}/tcp 2>/dev/null; true`;await new Promise(e=>child_process.exec(t,()=>e())),await new Promise(e=>setTimeout(e,800));}async function p(n,t){let e=n.process?.pid??n.pid;if(e)return new Promise(r=>{let o=false,i=()=>{o||(o=true,clearTimeout(a),r());};n.once?.("exit",i),n.once?.("exit",i);try{process.kill(e,"SIGTERM");}catch{return i()}let a=setTimeout(()=>{try{process.kill(e,"SIGKILL"),setTimeout(i,100);}catch{i();}},t),l=setInterval(()=>{try{process.kill(e,0);}catch{clearInterval(l),i();}},500);})}var f=class{cfg;name;watcher=null;constructor(t){this.cfg={mode:"fork",instances:1,...t},this.name=t.name,this.initStore();}async start(){let t=this.mp();if(t.status==="running"||t.status==="starting"){chunkX4TWGCVL_cjs.d.warn(this.name,"Already running \u2013 ignoring start()");return}this.patch({status:"starting",isRestarting:false,children:[],restartCount:0,backoffTime:d,probeFailures:0,startTime:null}),this.clearTimers(),this.stopProbe(),chunkX4TWGCVL_cjs.d.info(this.name,"Initializing fresh start...");try{await this.spawnAll(),this.cfg.devMode&&this.watchFiles();}catch(e){this.patch({status:"errored"}),chunkX4TWGCVL_cjs.d.error(this.name,`Start failed: ${e.message}`);}}async stop(){let t=this.mp();if(t.status!=="stopping"){this.patch({status:"stopping",isRestarting:false}),chunkX4TWGCVL_cjs.d.info(this.name,`Stopping ${t.children.length} instances...`),this.clearTimers(),this.stopProbe(),this.stopWatcher();try{await Promise.race([Promise.all(t.children.map(e=>p(e,this.cfg.killTimeout??m))),new Promise((e,r)=>setTimeout(()=>r(new Error("Termination timeout")),1e4))]);}catch(e){chunkX4TWGCVL_cjs.d.error(this.name,`Stop timed out, forcing state reset: ${e.message||"UNKNOWN"}`);}this.patch({children:[],status:"stopped",startTime:null}),this.stopWatcher(),chunkX4TWGCVL_cjs.d.success(this.name,"Stopped.");}}async _stop(){let t=this.mp();this.patch({status:"stopping",isRestarting:false}),this.clearTimers(),this.stopProbe();for(let e of t.children)p(e,this.cfg.killTimeout??m);this.stopWatcher(),this.patch({children:[],status:"stopped",startTime:null}),chunkX4TWGCVL_cjs.d.info(this.name,"Stopped.");}async restart(){let t=this.mp();t.isRestarting||(chunkX4TWGCVL_cjs.d.info(this.name,"Restarting..."),this.patch({isRestarting:true,status:"stopping"}),this.clearTimers(),this.stopProbe(),await Promise.all(t.children.map(e=>p(e,this.cfg.killTimeout??m))),this.patch({isRestarting:false,children:[]}));}async _restart(){chunkX4TWGCVL_cjs.d.info(this.name,"Restarting...");let t=this.mp();this.patch({isRestarting:true}),this.clearTimers(),this.stopProbe();for(let e of t.children)p(e,this.cfg.killTimeout??m);}async getStats(){let t=this.mp(),e=t.children[0]?.pid??null,r=null,o=null,i=null;if(e&&t.status==="running")try{let a=await E__default.default(e);r=a.cpu,o=a.memory;}catch{}return {name:this.name,status:t.status,pid:e,uptime:t.startTime?Date.now()-t.startTime:null,restartCount:t.restartCount,cpu:r,memoryRss:o,memoryHeap:i,mode:this.cfg.mode??"fork",instances:t.children.length}}async spawnAll(){if(!I__default.default.existsSync(this.cfg.scriptPath)){chunkX4TWGCVL_cjs.d.error(this.name,`Script not found: ${this.cfg.scriptPath}. Waiting for build...`),this.patch({status:"errored"});return}this.cfg.port&&await N(this.cfg.port);let t=this.cfg.mode??"fork",e=t==="cluster"?this.cfg.instances??k__default.default.cpus().length:1,r=[];for(let i=0;i<e;i++){let a=this.forkChild();a&&r.push(a);}if(r.length===0){chunkX4TWGCVL_cjs.d.error(this.name,"Failed to spawn any instances."),this.patch({status:"stopped"});return}this.patch({children:r,startTime:Date.now(),status:"running"}),chunkX4TWGCVL_cjs.d.success(this.name,`Started ${r.length} instance(s) [${t}]`);let o=setTimeout(()=>{this.mp().status==="running"&&(this.patch({backoffTime:d,restartCount:0}),chunkX4TWGCVL_cjs.d.success(this.name,"Process is stable."));},L);this.patch({stabilityTimer:o}),this.cfg.probe&&this.startProbe();}forkChild(){try{let t=this.cfg.scriptPath.endsWith(".js")?"node":this.cfg.scriptPath,e=this.cfg.scriptPath.endsWith(".js")?[this.cfg.scriptPath,...this.cfg.args??[]]:[...this.cfg.args??[]],r=child_process.spawn(t,e,{cwd:u__default.default.dirname(u__default.default.resolve(this.cfg.scriptPath,"..")),stdio:["ignore","pipe","pipe"],env:{...process.env,...this.cfg.env??{},NODE_ENV:this.cfg.devMode?"development":"production"},detached:!1,shell:!1});this.setupLogging(r);let o=Date.now();return r.on("error",i=>{chunkX4TWGCVL_cjs.d.error(this.name,"Spawn error:",i);}),r.on("exit",(i,a)=>{let l=Date.now()-o;this.onChildExit(r,i,a,l);}),r}catch(t){return chunkX4TWGCVL_cjs.d.error(this.name,"Failed to fork child:",t),null}}onChildExit(t,e,r,o){let i=this.mp(),a=i.children.filter(l=>l!==t);if(this.patch({children:a}),i.status!=="stopping"){if(chunkX4TWGCVL_cjs.d.warn(this.name,`Process exited (code=${e}, signal=${r}, uptime=${o}ms)`),i.isRestarting){a.length===0&&(this.patch({isRestarting:false}),this.spawnAll());return}if(e!==0&&e!==null){if(this.patch({status:"crashed"}),o<1500){chunkX4TWGCVL_cjs.d.error(this.name,`Immediate crash (${o}ms) \u2013 likely a syntax/build error. Waiting for next file change.`);return}this.scheduleRestart();}}}scheduleRestart(){let t=this.mp(),e=t.backoffTime,r=this.cfg.maxBackoff??M;chunkX4TWGCVL_cjs.d.warn(this.name,`Scheduling restart in ${e}ms (attempt #${t.restartCount+1})`);let o=setTimeout(async()=>{this.patch({restartCount:t.restartCount+1,backoffTime:Math.min(e*2,r)}),await this.spawnAll();},e);this.patch({restartTimer:o});}startProbe(){let t=this.cfg.probe,e=(t.intervalSeconds??10)*1e3,r=t.failureThreshold??3,i=setInterval(async()=>{let a=this.mp();if(a.status!=="running")return;if(await w(t)){a.probeFailures>0&&this.patch({probeFailures:0});return}let h=a.probeFailures+1;this.patch({probeFailures:h}),chunkX4TWGCVL_cjs.d.warn(this.name,`Liveness probe failed (${h}/${r})`),h>=r&&(chunkX4TWGCVL_cjs.d.error(this.name,"Liveness probe threshold exceeded \u2013 restarting."),this.patch({probeFailures:0}),await this.restart());},e);this.patch({probeTimer:i});}stopProbe(){let{probeTimer:t}=this.mp();t&&(clearInterval(t),this.patch({probeTimer:null,probeFailures:0}));}watchFiles(){this.stopWatcher();let t=u__default.default.dirname(this.cfg.scriptPath);this.watcher=F__default.default.watch(t,{ignored:[/node_modules/,/\.pid$/],persistent:true,ignoreInitial:true,awaitWriteFinish:{stabilityThreshold:1500,pollInterval:500}}),this.watcher.on("all",(e,r)=>{(e==="change"||e==="add")&&(chunkX4TWGCVL_cjs.d.info(this.name,`File ${e}: ${u__default.default.basename(r)} \u2013 restarting`),this.restart());}),this.watcher.on("error",e=>chunkX4TWGCVL_cjs.d.error(this.name,"Watcher error:",e)),this.watcher.on("ready",()=>chunkX4TWGCVL_cjs.d.info(this.name,`Watching ${t}`));}stopWatcher(){this.watcher&&(this.watcher.close(),this.watcher=null);}initStore(){chunkX4TWGCVL_cjs.e.set(this.name,{config:this.cfg,children:[],status:"stopped",startTime:null,restartCount:0,backoffTime:d,restartTimer:null,stabilityTimer:null,probeTimer:null,probeFailures:0,isRestarting:false});}mp(){return chunkX4TWGCVL_cjs.e.get(this.name)}_patch(t){chunkX4TWGCVL_cjs.e.set(this.name,{...this.mp(),...t});}patch(t){let e=this.mp();t.status&&t.status!==e.status&&chunkX4TWGCVL_cjs.d.info(this.name,`[STATE] ${e.status} \u2794 ${t.status}${t.isRestarting?" (Restarting)":""}`),t.lastError&&chunkX4TWGCVL_cjs.d.error(this.name,`[REASON] ${t.lastError}`),chunkX4TWGCVL_cjs.e.set(this.name,{...e,...t});}clearTimers(){let{restartTimer:t,stabilityTimer:e}=this.mp();t&&clearTimeout(t),e&&clearTimeout(e),this.patch({restartTimer:null,stabilityTimer:null});}setupLogging(t){let e=this.cfg.logs?.wsUrl,r=null;e&&(r=new b__default.default(e),r.on("open",()=>chunkX4TWGCVL_cjs.d.debug(this.name,"Connected to log collector")),r.on("error",i=>chunkX4TWGCVL_cjs.d.error(this.name,"Log Collector WS Error",i.message)));let o=i=>{let a=i.toString();this.cfg.devMode&&process.stdout.write(`[${this.name}] ${a}`),r&&r.readyState===b__default.default.OPEN&&r.send(JSON.stringify({app:this.name,timestamp:Date.now(),log:a}));};t.stdout?.on("data",o),t.stderr?.on("data",o);}};var P=class{workers=new Map;async start(t){if(this.workers.has(t.name)){chunkX4TWGCVL_cjs.d.warn("PM",`Worker "${t.name}" already registered \u2013 use restart()`);return}let e=new f(t);this.workers.set(t.name,e),await e.start();}async stop(t){let e=this.require(t);e&&await e.stop();}async restart(t){let e=this.require(t);e&&await e.restart();}async delete(t){let e=this.require(t);e&&(await e.stop(),this.workers.delete(t),chunkX4TWGCVL_cjs.e.delete(t),chunkX4TWGCVL_cjs.d.info("PM",`Deleted worker "${t}"`));}async getStats(t){if(t){let r=this.require(t);return r?[await r.getStats()]:[]}return await Promise.all([...this.workers.values()].map(r=>r.getStats()))}list(){return [...this.workers.keys()]}async stopAll(){chunkX4TWGCVL_cjs.d.info("PM","Stopping all workers..."),await Promise.all([...this.workers.values()].map(t=>t.stop())),chunkX4TWGCVL_cjs.d.info("PM","All workers stopped.");}getWorker(t){let e=this.workers.get(t);return e||(chunkX4TWGCVL_cjs.d.error(t,"Worker Not Found"),null)}require(t){let e=this.workers.get(t);return e||(chunkX4TWGCVL_cjs.d.error(t,"Worker Not Found"),null)}};exports.a=w;exports.b=f;exports.c=P;
|
|
2
|
+
function W(n,t){return new Promise(e=>{let o=(n.startsWith("https")?y__default.default:v__default.default).get(n,{timeout:t},i=>{e((i.statusCode??500)<500);});o.on("error",()=>e(false)),o.on("timeout",()=>{o.destroy(),e(false);});})}function C(n,t){let[e,r]=n.split(":"),o=Number(r);return new Promise(i=>{let a=S__default.default.createConnection({host:e,port:o},()=>{a.destroy(),i(true);});a.setTimeout(t),a.on("timeout",()=>{a.destroy(),i(false);}),a.on("error",()=>i(false));})}function $(n,t){return new Promise(e=>{let r=setTimeout(()=>e(false),t);child_process.exec(n,o=>{clearTimeout(r),e(!o);});})}async function w(n){let t=(n.timeoutSeconds??5)*1e3;switch(n.type){case "http":return W(n.target,t);case "tcp":return C(n.target,t);case "exec":return $(n.target,t);default:return false}}var m=5e3,M=16e3,d=1e3,A=5e3;async function L(n){return new Promise(t=>{S__default.default.createServer().once("error",()=>t(false)).once("listening",function(){this.close(()=>t(true));}).listen(n);})}async function N(n){if(await L(n))return;let t=k__default.default.platform()==="darwin"?`lsof -ti :${n} | xargs kill -9 2>/dev/null || true`:`fuser -k -9 ${n}/tcp 2>/dev/null; true`;await new Promise(e=>child_process.exec(t,()=>e())),await new Promise(e=>setTimeout(e,800));}async function p(n,t){let e=n.process?.pid??n.pid;if(e)return new Promise(r=>{let o=false,i=()=>{o||(o=true,clearTimeout(a),r());};n.once?.("exit",i),n.once?.("exit",i);try{process.kill(e,"SIGTERM");}catch{return i()}let a=setTimeout(()=>{try{process.kill(e,"SIGKILL"),setTimeout(i,100);}catch{i();}},t),l=setInterval(()=>{try{process.kill(e,0);}catch{clearInterval(l),i();}},500);})}var f=class{cfg;name;watcher=null;constructor(t){this.cfg={mode:"fork",instances:1,...t},this.name=t.name,this.initStore();}async start(){let t=this.mp();if(t.status==="running"||t.status==="starting"){chunkX4TWGCVL_cjs.d.warn(this.name,"Already running \u2013 ignoring start()");return}this.patch({status:"starting",isRestarting:false,children:[],restartCount:0,backoffTime:d,probeFailures:0,startTime:null}),this.clearTimers(),this.stopProbe(),chunkX4TWGCVL_cjs.d.info(this.name,"Initializing fresh start...");try{await this.spawnAll(),this.cfg.devMode&&this.watchFiles();}catch(e){this.patch({status:"errored"}),chunkX4TWGCVL_cjs.d.error(this.name,`Start failed: ${e.message}`);}}async stop(){let t=this.mp();if(t.status==="stopping"){chunkX4TWGCVL_cjs.d.info(this.name,"Already stopping...");return}this.patch({status:"stopping",isRestarting:false}),chunkX4TWGCVL_cjs.d.info(this.name,`Stopping ${t.children.length} instances...`),this.clearTimers(),this.stopProbe(),this.stopWatcher();try{await Promise.race([Promise.all(t.children.map(e=>p(e,this.cfg.killTimeout??m))),new Promise((e,r)=>setTimeout(()=>r(new Error("Termination timeout")),1e4))]);}catch(e){chunkX4TWGCVL_cjs.d.error(this.name,`Stop timed out, forcing state reset: ${e.message||"UNKNOWN"}`);}this.patch({children:[],status:"stopped",startTime:null}),this.stopWatcher(),chunkX4TWGCVL_cjs.d.success(this.name,"Stopped.");}async _stop(){let t=this.mp();this.patch({status:"stopping",isRestarting:false}),this.clearTimers(),this.stopProbe();for(let e of t.children)p(e,this.cfg.killTimeout??m);this.stopWatcher(),this.patch({children:[],status:"stopped",startTime:null}),chunkX4TWGCVL_cjs.d.info(this.name,"Stopped.");}async restart(){let t=this.mp();t.isRestarting||(chunkX4TWGCVL_cjs.d.info(this.name,"Restarting..."),this.patch({isRestarting:true,status:"stopping"}),this.clearTimers(),this.stopProbe(),await Promise.all(t.children.map(e=>p(e,this.cfg.killTimeout??m))),this.patch({isRestarting:false,children:[]}));}async _restart(){chunkX4TWGCVL_cjs.d.info(this.name,"Restarting...");let t=this.mp();this.patch({isRestarting:true}),this.clearTimers(),this.stopProbe();for(let e of t.children)p(e,this.cfg.killTimeout??m);}async getStats(){let t=this.mp(),e=t.children[0]?.pid??null,r=null,o=null,i=null;if(e&&t.status==="running")try{let a=await E__default.default(e);r=a.cpu,o=a.memory;}catch{}return {name:this.name,status:t.status,pid:e,uptime:t.startTime?Date.now()-t.startTime:null,restartCount:t.restartCount,cpu:r,memoryRss:o,memoryHeap:i,mode:this.cfg.mode??"fork",instances:t.children.length}}async spawnAll(){if(!I__default.default.existsSync(this.cfg.scriptPath)){chunkX4TWGCVL_cjs.d.error(this.name,`Script not found: ${this.cfg.scriptPath}. Waiting for build...`),this.patch({status:"errored"});return}this.cfg.port&&await N(this.cfg.port);let t=this.cfg.mode??"fork",e=t==="cluster"?this.cfg.instances??k__default.default.cpus().length:1,r=[];for(let i=0;i<e;i++){let a=this.forkChild();a&&r.push(a);}if(r.length===0){chunkX4TWGCVL_cjs.d.error(this.name,"Failed to spawn any instances."),this.patch({status:"stopped"});return}this.patch({children:r,startTime:Date.now(),status:"running"}),chunkX4TWGCVL_cjs.d.success(this.name,`Started ${r.length} instance(s) [${t}]`);let o=setTimeout(()=>{this.mp().status==="running"&&(this.patch({backoffTime:d,restartCount:0}),chunkX4TWGCVL_cjs.d.success(this.name,"Process is stable."));},A);this.patch({stabilityTimer:o}),this.cfg.probe&&this.startProbe();}forkChild(){try{let t=this.cfg.scriptPath.endsWith(".js")?"node":this.cfg.scriptPath,e=this.cfg.scriptPath.endsWith(".js")?[this.cfg.scriptPath,...this.cfg.args??[]]:[...this.cfg.args??[]],r=child_process.spawn(t,e,{cwd:u__default.default.dirname(u__default.default.resolve(this.cfg.scriptPath,"..")),stdio:["ignore","pipe","pipe"],env:{...process.env,...this.cfg.env??{},NODE_ENV:this.cfg.devMode?"development":"production"},detached:!1,shell:!1});this.setupLogging(r);let o=Date.now();return r.on("error",i=>{chunkX4TWGCVL_cjs.d.error(this.name,"Spawn error:",i);}),r.on("exit",(i,a)=>{let l=Date.now()-o;this.onChildExit(r,i,a,l);}),r}catch(t){return chunkX4TWGCVL_cjs.d.error(this.name,"Failed to fork child:",t),null}}onChildExit(t,e,r,o){let i=this.mp(),a=i.children.filter(l=>l!==t);if(this.patch({children:a}),i.status!=="stopping"){if(chunkX4TWGCVL_cjs.d.warn(this.name,`Process exited (code=${e}, signal=${r}, uptime=${o}ms)`),i.isRestarting){a.length===0&&(this.patch({isRestarting:false}),this.spawnAll());return}e!==0&&e!==null&&(this.patch({status:"crashed"}),o<1500&&chunkX4TWGCVL_cjs.d.error(this.name,`Immediate crash (${o}ms) \u2013 likely a syntax/build error. Waiting for next file change.`),this.scheduleRestart());}}scheduleRestart(){let t=this.mp(),e=t.backoffTime,r=this.cfg.maxBackoff??M;chunkX4TWGCVL_cjs.d.warn(this.name,`Scheduling restart in ${e}ms (attempt #${t.restartCount+1})`);let o=setTimeout(async()=>{this.patch({restartCount:t.restartCount+1,backoffTime:Math.min(e*2,r)}),await this.spawnAll();},e);this.patch({restartTimer:o});}startProbe(){let t=this.cfg.probe,e=(t.intervalSeconds??10)*1e3,r=t.failureThreshold??3,i=setInterval(async()=>{let a=this.mp();if(a.status!=="running")return;if(await w(t)){a.probeFailures>0&&this.patch({probeFailures:0});return}let h=a.probeFailures+1;this.patch({probeFailures:h}),chunkX4TWGCVL_cjs.d.warn(this.name,`Liveness probe failed (${h}/${r})`),h>=r&&(chunkX4TWGCVL_cjs.d.error(this.name,"Liveness probe threshold exceeded \u2013 restarting."),this.patch({probeFailures:0}),await this.restart());},e);this.patch({probeTimer:i});}stopProbe(){let{probeTimer:t}=this.mp();t&&(clearInterval(t),this.patch({probeTimer:null,probeFailures:0}));}watchFiles(){this.stopWatcher();let t=u__default.default.dirname(this.cfg.scriptPath);this.watcher=F__default.default.watch(t,{ignored:[/node_modules/,/\.pid$/],persistent:true,ignoreInitial:true,awaitWriteFinish:{stabilityThreshold:1500,pollInterval:500}}),this.watcher.on("all",(e,r)=>{(e==="change"||e==="add")&&(chunkX4TWGCVL_cjs.d.info(this.name,`File ${e}: ${u__default.default.basename(r)} \u2013 restarting`),this.restart());}),this.watcher.on("error",e=>chunkX4TWGCVL_cjs.d.error(this.name,"Watcher error:",e)),this.watcher.on("ready",()=>chunkX4TWGCVL_cjs.d.info(this.name,`Watching ${t}`));}stopWatcher(){this.watcher&&(this.watcher.close(),this.watcher=null);}initStore(){chunkX4TWGCVL_cjs.e.set(this.name,{config:this.cfg,children:[],status:"stopped",startTime:null,restartCount:0,backoffTime:d,restartTimer:null,stabilityTimer:null,probeTimer:null,probeFailures:0,isRestarting:false});}mp(){return chunkX4TWGCVL_cjs.e.get(this.name)}_patch(t){chunkX4TWGCVL_cjs.e.set(this.name,{...this.mp(),...t});}patch(t){let e=this.mp();t.status&&t.status!==e.status&&chunkX4TWGCVL_cjs.d.info(this.name,`[STATE] ${e.status} \u2794 ${t.status}${t.isRestarting?" (Restarting)":""}`),t.lastError&&chunkX4TWGCVL_cjs.d.error(this.name,`[REASON] ${t.lastError}`),chunkX4TWGCVL_cjs.e.set(this.name,{...e,...t});}clearTimers(){let{restartTimer:t,stabilityTimer:e}=this.mp();t&&clearTimeout(t),e&&clearTimeout(e),this.patch({restartTimer:null,stabilityTimer:null});}setupLogging(t){let e=this.cfg.logs?.wsUrl,r=null;e&&(r=new b__default.default(e),r.on("open",()=>chunkX4TWGCVL_cjs.d.debug(this.name,"Connected to log collector")),r.on("error",i=>chunkX4TWGCVL_cjs.d.error(this.name,"Log Collector WS Error",i.message)));let o=i=>{let a=i.toString();this.cfg.devMode&&process.stdout.write(`[${this.name}] ${a}`),r&&r.readyState===b__default.default.OPEN&&r.send(JSON.stringify({app:this.name,timestamp:Date.now(),log:a}));};t.stdout?.on("data",o),t.stderr?.on("data",o);}};var P=class{workers=new Map;async start(t){if(this.workers.has(t.name)){chunkX4TWGCVL_cjs.d.warn("PM",`Worker "${t.name}" already registered \u2013 use restart()`);return}let e=new f(t);this.workers.set(t.name,e),await e.start();}async stop(t){let e=this.require(t);e&&await e.stop();}async restart(t){let e=this.require(t);e&&await e.restart();}async delete(t){let e=this.require(t);e&&(await e.stop(),this.workers.delete(t),chunkX4TWGCVL_cjs.e.delete(t),chunkX4TWGCVL_cjs.d.info("PM",`Deleted worker "${t}"`));}async getStats(t){if(t){let r=this.require(t);return r?[await r.getStats()]:[]}return await Promise.all([...this.workers.values()].map(r=>r.getStats()))}list(){return [...this.workers.keys()]}async stopAll(){chunkX4TWGCVL_cjs.d.info("PM","Stopping all workers..."),await Promise.all([...this.workers.values()].map(t=>t.stop())),chunkX4TWGCVL_cjs.d.info("PM","All workers stopped.");}getWorker(t){let e=this.workers.get(t);return e||(chunkX4TWGCVL_cjs.d.error(t,"Worker Not Found"),null)}require(t){let e=this.workers.get(t);return e||(chunkX4TWGCVL_cjs.d.error(t,"Worker Not Found"),null)}};exports.a=w;exports.b=f;exports.c=P;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {d as d$1,e}from'./chunk-USJACDTS.js';import {spawn,exec}from'child_process';import y from'http';import S from'https';import W from'net';import R from'chokidar';import _ from'fs';import P from'os';import u from'path';import k from'ws';import M from'pidusage';function C(n,t){return new Promise(e=>{let o=(n.startsWith("https")?S:y).get(n,{timeout:t},i=>{e((i.statusCode??500)<500);});o.on("error",()=>e(false)),o.on("timeout",()=>{o.destroy(),e(false);});})}function $(n,t){let[e,r]=n.split(":"),o=Number(r);return new Promise(i=>{let a=W.createConnection({host:e,port:o},()=>{a.destroy(),i(true);});a.setTimeout(t),a.on("timeout",()=>{a.destroy(),i(false);}),a.on("error",()=>i(false));})}function F(n,t){return new Promise(e=>{let r=setTimeout(()=>e(false),t);exec(n,o=>{clearTimeout(r),e(!o);});})}async function b(n){let t=(n.timeoutSeconds??5)*1e3;switch(n.type){case "http":return C(n.target,t);case "tcp":return $(n.target,t);case "exec":return F(n.target,t);default:return false}}var m=5e3,A=16e3,d=1e3,L=5e3;async function N(n){return new Promise(t=>{W.createServer().once("error",()=>t(false)).once("listening",function(){this.close(()=>t(true));}).listen(n);})}async function D(n){if(await N(n))return;let t=P.platform()==="darwin"?`lsof -ti :${n} | xargs kill -9 2>/dev/null || true`:`fuser -k -9 ${n}/tcp 2>/dev/null; true`;await new Promise(e=>exec(t,()=>e())),await new Promise(e=>setTimeout(e,800));}async function p(n,t){let e=n.process?.pid??n.pid;if(e)return new Promise(r=>{let o=false,i=()=>{o||(o=true,clearTimeout(a),r());};n.once?.("exit",i),n.once?.("exit",i);try{process.kill(e,"SIGTERM");}catch{return i()}let a=setTimeout(()=>{try{process.kill(e,"SIGKILL"),setTimeout(i,100);}catch{i();}},t),l=setInterval(()=>{try{process.kill(e,0);}catch{clearInterval(l),i();}},500);})}var f=class{cfg;name;watcher=null;constructor(t){this.cfg={mode:"fork",instances:1,...t},this.name=t.name,this.initStore();}async start(){let t=this.mp();if(t.status==="running"||t.status==="starting"){d$1.warn(this.name,"Already running \u2013 ignoring start()");return}this.patch({status:"starting",isRestarting:false,children:[],restartCount:0,backoffTime:d,probeFailures:0,startTime:null}),this.clearTimers(),this.stopProbe(),d$1.info(this.name,"Initializing fresh start...");try{await this.spawnAll(),this.cfg.devMode&&this.watchFiles();}catch(e){this.patch({status:"errored"}),d$1.error(this.name,`Start failed: ${e.message}`);}}async stop(){let t=this.mp();if(t.status==="stopping"){d$1.info(this.name,"Already stopping...");return}this.patch({status:"stopping",isRestarting:false}),d$1.info(this.name,`Stopping ${t.children.length} instances...`),this.clearTimers(),this.stopProbe(),this.stopWatcher();try{await Promise.race([Promise.all(t.children.map(e=>p(e,this.cfg.killTimeout??m))),new Promise((e,r)=>setTimeout(()=>r(new Error("Termination timeout")),1e4))]);}catch(e){d$1.error(this.name,`Stop timed out, forcing state reset: ${e.message||"UNKNOWN"}`);}this.patch({children:[],status:"stopped",startTime:null}),this.stopWatcher(),d$1.success(this.name,"Stopped.");}async _stop(){let t=this.mp();this.patch({status:"stopping",isRestarting:false}),this.clearTimers(),this.stopProbe();for(let e of t.children)p(e,this.cfg.killTimeout??m);this.stopWatcher(),this.patch({children:[],status:"stopped",startTime:null}),d$1.info(this.name,"Stopped.");}async restart(){let t=this.mp();t.isRestarting||(d$1.info(this.name,"Restarting..."),this.patch({isRestarting:true,status:"stopping"}),this.clearTimers(),this.stopProbe(),await Promise.all(t.children.map(e=>p(e,this.cfg.killTimeout??m))),this.patch({isRestarting:false,children:[]}));}async _restart(){d$1.info(this.name,"Restarting...");let t=this.mp();this.patch({isRestarting:true}),this.clearTimers(),this.stopProbe();for(let e of t.children)p(e,this.cfg.killTimeout??m);}async getStats(){let t=this.mp(),e=t.children[0]?.pid??null,r=null,o=null,i=null;if(e&&t.status==="running")try{let a=await M(e);r=a.cpu,o=a.memory;}catch{}return {name:this.name,status:t.status,pid:e,uptime:t.startTime?Date.now()-t.startTime:null,restartCount:t.restartCount,cpu:r,memoryRss:o,memoryHeap:i,mode:this.cfg.mode??"fork",instances:t.children.length}}async spawnAll(){if(!_.existsSync(this.cfg.scriptPath)){d$1.error(this.name,`Script not found: ${this.cfg.scriptPath}. Waiting for build...`),this.patch({status:"errored"});return}this.cfg.port&&await D(this.cfg.port);let t=this.cfg.mode??"fork",e=t==="cluster"?this.cfg.instances??P.cpus().length:1,r=[];for(let i=0;i<e;i++){let a=this.forkChild();a&&r.push(a);}if(r.length===0){d$1.error(this.name,"Failed to spawn any instances."),this.patch({status:"stopped"});return}this.patch({children:r,startTime:Date.now(),status:"running"}),d$1.success(this.name,`Started ${r.length} instance(s) [${t}]`);let o=setTimeout(()=>{this.mp().status==="running"&&(this.patch({backoffTime:d,restartCount:0}),d$1.success(this.name,"Process is stable."));},L);this.patch({stabilityTimer:o}),this.cfg.probe&&this.startProbe();}forkChild(){try{let t=this.cfg.scriptPath.endsWith(".js")?"node":this.cfg.scriptPath,e=this.cfg.scriptPath.endsWith(".js")?[this.cfg.scriptPath,...this.cfg.args??[]]:[...this.cfg.args??[]],r=spawn(t,e,{cwd:u.dirname(u.resolve(this.cfg.scriptPath,"..")),stdio:["ignore","pipe","pipe"],env:{...process.env,...this.cfg.env??{},NODE_ENV:this.cfg.devMode?"development":"production"},detached:!1,shell:!1});this.setupLogging(r);let o=Date.now();return r.on("error",i=>{d$1.error(this.name,"Spawn error:",i);}),r.on("exit",(i,a)=>{let l=Date.now()-o;this.onChildExit(r,i,a,l);}),r}catch(t){return d$1.error(this.name,"Failed to fork child:",t),null}}onChildExit(t,e,r,o){let i=this.mp(),a=i.children.filter(l=>l!==t);if(this.patch({children:a}),i.status!=="stopping"){if(d$1.warn(this.name,`Process exited (code=${e}, signal=${r}, uptime=${o}ms)`),i.isRestarting){a.length===0&&(this.patch({isRestarting:false}),this.spawnAll());return}e!==0&&e!==null&&(this.patch({status:"crashed"}),o<1500&&d$1.error(this.name,`Immediate crash (${o}ms) \u2013 likely a syntax/build error. Waiting for next file change.`),this.scheduleRestart());}}scheduleRestart(){let t=this.mp(),e=t.backoffTime,r=this.cfg.maxBackoff??A;d$1.warn(this.name,`Scheduling restart in ${e}ms (attempt #${t.restartCount+1})`);let o=setTimeout(async()=>{this.patch({restartCount:t.restartCount+1,backoffTime:Math.min(e*2,r)}),await this.spawnAll();},e);this.patch({restartTimer:o});}startProbe(){let t=this.cfg.probe,e=(t.intervalSeconds??10)*1e3,r=t.failureThreshold??3,i=setInterval(async()=>{let a=this.mp();if(a.status!=="running")return;if(await b(t)){a.probeFailures>0&&this.patch({probeFailures:0});return}let h=a.probeFailures+1;this.patch({probeFailures:h}),d$1.warn(this.name,`Liveness probe failed (${h}/${r})`),h>=r&&(d$1.error(this.name,"Liveness probe threshold exceeded \u2013 restarting."),this.patch({probeFailures:0}),await this.restart());},e);this.patch({probeTimer:i});}stopProbe(){let{probeTimer:t}=this.mp();t&&(clearInterval(t),this.patch({probeTimer:null,probeFailures:0}));}watchFiles(){this.stopWatcher();let t=u.dirname(this.cfg.scriptPath);this.watcher=R.watch(t,{ignored:[/node_modules/,/\.pid$/],persistent:true,ignoreInitial:true,awaitWriteFinish:{stabilityThreshold:1500,pollInterval:500}}),this.watcher.on("all",(e,r)=>{(e==="change"||e==="add")&&(d$1.info(this.name,`File ${e}: ${u.basename(r)} \u2013 restarting`),this.restart());}),this.watcher.on("error",e=>d$1.error(this.name,"Watcher error:",e)),this.watcher.on("ready",()=>d$1.info(this.name,`Watching ${t}`));}stopWatcher(){this.watcher&&(this.watcher.close(),this.watcher=null);}initStore(){e.set(this.name,{config:this.cfg,children:[],status:"stopped",startTime:null,restartCount:0,backoffTime:d,restartTimer:null,stabilityTimer:null,probeTimer:null,probeFailures:0,isRestarting:false});}mp(){return e.get(this.name)}_patch(t){e.set(this.name,{...this.mp(),...t});}patch(t){let e$1=this.mp();t.status&&t.status!==e$1.status&&d$1.info(this.name,`[STATE] ${e$1.status} \u2794 ${t.status}${t.isRestarting?" (Restarting)":""}`),t.lastError&&d$1.error(this.name,`[REASON] ${t.lastError}`),e.set(this.name,{...e$1,...t});}clearTimers(){let{restartTimer:t,stabilityTimer:e}=this.mp();t&&clearTimeout(t),e&&clearTimeout(e),this.patch({restartTimer:null,stabilityTimer:null});}setupLogging(t){let e=this.cfg.logs?.wsUrl,r=null;e&&(r=new k(e),r.on("open",()=>d$1.debug(this.name,"Connected to log collector")),r.on("error",i=>d$1.error(this.name,"Log Collector WS Error",i.message)));let o=i=>{let a=i.toString();this.cfg.devMode&&process.stdout.write(`[${this.name}] ${a}`),r&&r.readyState===k.OPEN&&r.send(JSON.stringify({app:this.name,timestamp:Date.now(),log:a}));};t.stdout?.on("data",o),t.stderr?.on("data",o);}};var T=class{workers=new Map;async start(t){if(this.workers.has(t.name)){d$1.warn("PM",`Worker "${t.name}" already registered \u2013 use restart()`);return}let e=new f(t);this.workers.set(t.name,e),await e.start();}async stop(t){let e=this.require(t);e&&await e.stop();}async restart(t){let e=this.require(t);e&&await e.restart();}async delete(t){let e$1=this.require(t);e$1&&(await e$1.stop(),this.workers.delete(t),e.delete(t),d$1.info("PM",`Deleted worker "${t}"`));}async getStats(t){if(t){let r=this.require(t);return r?[await r.getStats()]:[]}return await Promise.all([...this.workers.values()].map(r=>r.getStats()))}list(){return [...this.workers.keys()]}async stopAll(){d$1.info("PM","Stopping all workers..."),await Promise.all([...this.workers.values()].map(t=>t.stop())),d$1.info("PM","All workers stopped.");}getWorker(t){let e=this.workers.get(t);return e||(d$1.error(t,"Worker Not Found"),null)}require(t){let e=this.workers.get(t);return e||(d$1.error(t,"Worker Not Found"),null)}};export{b as a,f as b,T as c};
|
package/dist/daemon.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
2
|
-
var i=p__default.default.join(m__default.default.tmpdir(),"zuz-pm.pid");function d(){r__default.default.writeFileSync(i,String(process.pid));}function u(){r__default.default.existsSync(i)&&r__default.default.unlinkSync(i);}var f=p__default.default.join(m__default.default.tmpdir(),"zuz-pm.snapshot.json");function l(o){try{let s=o.list();r__default.default.writeFileSync(f,JSON.stringify(s,null,2));}catch{}}async function S(){chunkX4TWGCVL_cjs.d.success("daemon",`Booting ZPM daemon (PID ${process.pid})`),d();let o=new
|
|
1
|
+
'use strict';var chunkKXRLI3RB_cjs=require('./chunk-KXRLI3RB.cjs'),chunkX4TWGCVL_cjs=require('./chunk-X4TWGCVL.cjs'),r=require('fs'),m=require('os'),p=require('path');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var r__default=/*#__PURE__*/_interopDefault(r);var m__default=/*#__PURE__*/_interopDefault(m);var p__default=/*#__PURE__*/_interopDefault(p);/* ZuzJS Process Manager */
|
|
2
|
+
var i=p__default.default.join(m__default.default.tmpdir(),"zuz-pm.pid");function d(){r__default.default.writeFileSync(i,String(process.pid));}function u(){r__default.default.existsSync(i)&&r__default.default.unlinkSync(i);}var f=p__default.default.join(m__default.default.tmpdir(),"zuz-pm.snapshot.json");function l(o){try{let s=o.list();r__default.default.writeFileSync(f,JSON.stringify(s,null,2));}catch{}}async function S(){chunkX4TWGCVL_cjs.d.success("daemon",`Booting ZPM daemon (PID ${process.pid})`),d();let o=new chunkKXRLI3RB_cjs.c,s=chunkX4TWGCVL_cjs.g(o);async function t(e){chunkX4TWGCVL_cjs.d.info("daemon",`Received ${e} \u2013 shutting down\u2026`),l(o),s.close(),await o.stopAll(),u(),process.exit(0);}process.on("SIGINT",()=>t("SIGINT")),process.on("SIGTERM",()=>t("SIGTERM")),process.on("uncaughtException",e=>chunkX4TWGCVL_cjs.d.error("daemon","Uncaught exception:",e)),process.on("unhandledRejection",e=>chunkX4TWGCVL_cjs.d.error("daemon","Unhandled rejection:",e)),chunkX4TWGCVL_cjs.d.success("daemon","Ready \u2013 waiting for IPC commands.");}S().catch(o=>{chunkX4TWGCVL_cjs.d.error("daemon","Fatal startup error:",o),process.exit(1);});
|
package/dist/daemon.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {c}from'./chunk-
|
|
1
|
+
import {c}from'./chunk-XWDXM76F.js';import {d as d$1,g}from'./chunk-USJACDTS.js';import r from'fs';import m from'os';import p from'path';var i=p.join(m.tmpdir(),"zuz-pm.pid");function d(){r.writeFileSync(i,String(process.pid));}function u(){r.existsSync(i)&&r.unlinkSync(i);}var f=p.join(m.tmpdir(),"zuz-pm.snapshot.json");function l(o){try{let s=o.list();r.writeFileSync(f,JSON.stringify(s,null,2));}catch{}}async function S(){d$1.success("daemon",`Booting ZPM daemon (PID ${process.pid})`),d();let o=new c,s=g(o);async function t(e){d$1.info("daemon",`Received ${e} \u2013 shutting down\u2026`),l(o),s.close(),await o.stopAll(),u(),process.exit(0);}process.on("SIGINT",()=>t("SIGINT")),process.on("SIGTERM",()=>t("SIGTERM")),process.on("uncaughtException",e=>d$1.error("daemon","Uncaught exception:",e)),process.on("unhandledRejection",e=>d$1.error("daemon","Unhandled rejection:",e)),d$1.success("daemon","Ready \u2013 waiting for IPC commands.");}S().catch(o=>{d$1.error("daemon","Fatal startup error:",o),process.exit(1);});
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var chunkFXHHFO4C_cjs=require('./chunk-FXHHFO4C.cjs'),
|
|
1
|
+
'use strict';var chunkFXHHFO4C_cjs=require('./chunk-FXHHFO4C.cjs'),chunkKXRLI3RB_cjs=require('./chunk-KXRLI3RB.cjs'),chunkX4TWGCVL_cjs=require('./chunk-X4TWGCVL.cjs');Object.defineProperty(exports,"ZPMClient",{enumerable:true,get:function(){return chunkFXHHFO4C_cjs.a}});Object.defineProperty(exports,"zpm",{enumerable:true,get:function(){return chunkFXHHFO4C_cjs.b}});Object.defineProperty(exports,"ProcessManager",{enumerable:true,get:function(){return chunkKXRLI3RB_cjs.c}});Object.defineProperty(exports,"Worker",{enumerable:true,get:function(){return chunkKXRLI3RB_cjs.b}});Object.defineProperty(exports,"runProbe",{enumerable:true,get:function(){return chunkKXRLI3RB_cjs.a}});Object.defineProperty(exports,"WorkerMode",{enumerable:true,get:function(){return chunkX4TWGCVL_cjs.b}});Object.defineProperty(exports,"WorkerStatus",{enumerable:true,get:function(){return chunkX4TWGCVL_cjs.c}});Object.defineProperty(exports,"getSocketPath",{enumerable:true,get:function(){return chunkX4TWGCVL_cjs.f}});Object.defineProperty(exports,"logger",{enumerable:true,get:function(){return chunkX4TWGCVL_cjs.d}});Object.defineProperty(exports,"processStore",{enumerable:true,get:function(){return chunkX4TWGCVL_cjs.e}});
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as ZPMClient,b as zpm}from'./chunk-C2XMYYVX.js';export{c as ProcessManager,b as Worker,a as runProbe}from'./chunk-
|
|
1
|
+
export{a as ZPMClient,b as zpm}from'./chunk-C2XMYYVX.js';export{c as ProcessManager,b as Worker,a as runProbe}from'./chunk-XWDXM76F.js';export{b as WorkerMode,c as WorkerStatus,f as getSocketPath,d as logger,e as processStore}from'./chunk-USJACDTS.js';
|
package/package.json
CHANGED
package/dist/chunk-BVPMXWDI.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import {d as d$1,e}from'./chunk-USJACDTS.js';import {spawn,exec}from'child_process';import y from'http';import S from'https';import W from'net';import R from'chokidar';import _ from'fs';import P from'os';import u from'path';import k from'ws';import M from'pidusage';function C(n,t){return new Promise(e=>{let o=(n.startsWith("https")?S:y).get(n,{timeout:t},i=>{e((i.statusCode??500)<500);});o.on("error",()=>e(false)),o.on("timeout",()=>{o.destroy(),e(false);});})}function $(n,t){let[e,r]=n.split(":"),o=Number(r);return new Promise(i=>{let a=W.createConnection({host:e,port:o},()=>{a.destroy(),i(true);});a.setTimeout(t),a.on("timeout",()=>{a.destroy(),i(false);}),a.on("error",()=>i(false));})}function F(n,t){return new Promise(e=>{let r=setTimeout(()=>e(false),t);exec(n,o=>{clearTimeout(r),e(!o);});})}async function b(n){let t=(n.timeoutSeconds??5)*1e3;switch(n.type){case "http":return C(n.target,t);case "tcp":return $(n.target,t);case "exec":return F(n.target,t);default:return false}}var m=5e3,L=16e3,d=1e3,A=5e3;async function N(n){return new Promise(t=>{W.createServer().once("error",()=>t(false)).once("listening",function(){this.close(()=>t(true));}).listen(n);})}async function D(n){if(await N(n))return;let t=P.platform()==="darwin"?`lsof -ti :${n} | xargs kill -9 2>/dev/null || true`:`fuser -k -9 ${n}/tcp 2>/dev/null; true`;await new Promise(e=>exec(t,()=>e())),await new Promise(e=>setTimeout(e,800));}async function p(n,t){let e=n.process?.pid??n.pid;if(e)return new Promise(r=>{let o=false,i=()=>{o||(o=true,clearTimeout(a),r());};n.once?.("exit",i),n.once?.("exit",i);try{process.kill(e,"SIGTERM");}catch{return i()}let a=setTimeout(()=>{try{process.kill(e,"SIGKILL"),setTimeout(i,100);}catch{i();}},t),l=setInterval(()=>{try{process.kill(e,0);}catch{clearInterval(l),i();}},500);})}var f=class{cfg;name;watcher=null;constructor(t){this.cfg={mode:"fork",instances:1,...t},this.name=t.name,this.initStore();}async start(){let t=this.mp();if(t.status==="running"||t.status==="starting"){d$1.warn(this.name,"Already running \u2013 ignoring start()");return}this.patch({status:"starting",isRestarting:false,children:[],restartCount:0,backoffTime:d,probeFailures:0,startTime:null}),this.clearTimers(),this.stopProbe(),d$1.info(this.name,"Initializing fresh start...");try{await this.spawnAll(),this.cfg.devMode&&this.watchFiles();}catch(e){this.patch({status:"errored"}),d$1.error(this.name,`Start failed: ${e.message}`);}}async stop(){let t=this.mp();if(t.status!=="stopping"){this.patch({status:"stopping",isRestarting:false}),d$1.info(this.name,`Stopping ${t.children.length} instances...`),this.clearTimers(),this.stopProbe(),this.stopWatcher();try{await Promise.race([Promise.all(t.children.map(e=>p(e,this.cfg.killTimeout??m))),new Promise((e,r)=>setTimeout(()=>r(new Error("Termination timeout")),1e4))]);}catch(e){d$1.error(this.name,`Stop timed out, forcing state reset: ${e.message||"UNKNOWN"}`);}this.patch({children:[],status:"stopped",startTime:null}),this.stopWatcher(),d$1.success(this.name,"Stopped.");}}async _stop(){let t=this.mp();this.patch({status:"stopping",isRestarting:false}),this.clearTimers(),this.stopProbe();for(let e of t.children)p(e,this.cfg.killTimeout??m);this.stopWatcher(),this.patch({children:[],status:"stopped",startTime:null}),d$1.info(this.name,"Stopped.");}async restart(){let t=this.mp();t.isRestarting||(d$1.info(this.name,"Restarting..."),this.patch({isRestarting:true,status:"stopping"}),this.clearTimers(),this.stopProbe(),await Promise.all(t.children.map(e=>p(e,this.cfg.killTimeout??m))),this.patch({isRestarting:false,children:[]}));}async _restart(){d$1.info(this.name,"Restarting...");let t=this.mp();this.patch({isRestarting:true}),this.clearTimers(),this.stopProbe();for(let e of t.children)p(e,this.cfg.killTimeout??m);}async getStats(){let t=this.mp(),e=t.children[0]?.pid??null,r=null,o=null,i=null;if(e&&t.status==="running")try{let a=await M(e);r=a.cpu,o=a.memory;}catch{}return {name:this.name,status:t.status,pid:e,uptime:t.startTime?Date.now()-t.startTime:null,restartCount:t.restartCount,cpu:r,memoryRss:o,memoryHeap:i,mode:this.cfg.mode??"fork",instances:t.children.length}}async spawnAll(){if(!_.existsSync(this.cfg.scriptPath)){d$1.error(this.name,`Script not found: ${this.cfg.scriptPath}. Waiting for build...`),this.patch({status:"errored"});return}this.cfg.port&&await D(this.cfg.port);let t=this.cfg.mode??"fork",e=t==="cluster"?this.cfg.instances??P.cpus().length:1,r=[];for(let i=0;i<e;i++){let a=this.forkChild();a&&r.push(a);}if(r.length===0){d$1.error(this.name,"Failed to spawn any instances."),this.patch({status:"stopped"});return}this.patch({children:r,startTime:Date.now(),status:"running"}),d$1.success(this.name,`Started ${r.length} instance(s) [${t}]`);let o=setTimeout(()=>{this.mp().status==="running"&&(this.patch({backoffTime:d,restartCount:0}),d$1.success(this.name,"Process is stable."));},A);this.patch({stabilityTimer:o}),this.cfg.probe&&this.startProbe();}forkChild(){try{let t=this.cfg.scriptPath.endsWith(".js")?"node":this.cfg.scriptPath,e=this.cfg.scriptPath.endsWith(".js")?[this.cfg.scriptPath,...this.cfg.args??[]]:[...this.cfg.args??[]],r=spawn(t,e,{cwd:u.dirname(u.resolve(this.cfg.scriptPath,"..")),stdio:["ignore","pipe","pipe"],env:{...process.env,...this.cfg.env??{},NODE_ENV:this.cfg.devMode?"development":"production"},detached:!1,shell:!1});this.setupLogging(r);let o=Date.now();return r.on("error",i=>{d$1.error(this.name,"Spawn error:",i);}),r.on("exit",(i,a)=>{let l=Date.now()-o;this.onChildExit(r,i,a,l);}),r}catch(t){return d$1.error(this.name,"Failed to fork child:",t),null}}onChildExit(t,e,r,o){let i=this.mp(),a=i.children.filter(l=>l!==t);if(this.patch({children:a}),i.status!=="stopping"){if(d$1.warn(this.name,`Process exited (code=${e}, signal=${r}, uptime=${o}ms)`),i.isRestarting){a.length===0&&(this.patch({isRestarting:false}),this.spawnAll());return}if(e!==0&&e!==null){if(this.patch({status:"crashed"}),o<1500){d$1.error(this.name,`Immediate crash (${o}ms) \u2013 likely a syntax/build error. Waiting for next file change.`);return}this.scheduleRestart();}}}scheduleRestart(){let t=this.mp(),e=t.backoffTime,r=this.cfg.maxBackoff??L;d$1.warn(this.name,`Scheduling restart in ${e}ms (attempt #${t.restartCount+1})`);let o=setTimeout(async()=>{this.patch({restartCount:t.restartCount+1,backoffTime:Math.min(e*2,r)}),await this.spawnAll();},e);this.patch({restartTimer:o});}startProbe(){let t=this.cfg.probe,e=(t.intervalSeconds??10)*1e3,r=t.failureThreshold??3,i=setInterval(async()=>{let a=this.mp();if(a.status!=="running")return;if(await b(t)){a.probeFailures>0&&this.patch({probeFailures:0});return}let h=a.probeFailures+1;this.patch({probeFailures:h}),d$1.warn(this.name,`Liveness probe failed (${h}/${r})`),h>=r&&(d$1.error(this.name,"Liveness probe threshold exceeded \u2013 restarting."),this.patch({probeFailures:0}),await this.restart());},e);this.patch({probeTimer:i});}stopProbe(){let{probeTimer:t}=this.mp();t&&(clearInterval(t),this.patch({probeTimer:null,probeFailures:0}));}watchFiles(){this.stopWatcher();let t=u.dirname(this.cfg.scriptPath);this.watcher=R.watch(t,{ignored:[/node_modules/,/\.pid$/],persistent:true,ignoreInitial:true,awaitWriteFinish:{stabilityThreshold:1500,pollInterval:500}}),this.watcher.on("all",(e,r)=>{(e==="change"||e==="add")&&(d$1.info(this.name,`File ${e}: ${u.basename(r)} \u2013 restarting`),this.restart());}),this.watcher.on("error",e=>d$1.error(this.name,"Watcher error:",e)),this.watcher.on("ready",()=>d$1.info(this.name,`Watching ${t}`));}stopWatcher(){this.watcher&&(this.watcher.close(),this.watcher=null);}initStore(){e.set(this.name,{config:this.cfg,children:[],status:"stopped",startTime:null,restartCount:0,backoffTime:d,restartTimer:null,stabilityTimer:null,probeTimer:null,probeFailures:0,isRestarting:false});}mp(){return e.get(this.name)}_patch(t){e.set(this.name,{...this.mp(),...t});}patch(t){let e$1=this.mp();t.status&&t.status!==e$1.status&&d$1.info(this.name,`[STATE] ${e$1.status} \u2794 ${t.status}${t.isRestarting?" (Restarting)":""}`),t.lastError&&d$1.error(this.name,`[REASON] ${t.lastError}`),e.set(this.name,{...e$1,...t});}clearTimers(){let{restartTimer:t,stabilityTimer:e}=this.mp();t&&clearTimeout(t),e&&clearTimeout(e),this.patch({restartTimer:null,stabilityTimer:null});}setupLogging(t){let e=this.cfg.logs?.wsUrl,r=null;e&&(r=new k(e),r.on("open",()=>d$1.debug(this.name,"Connected to log collector")),r.on("error",i=>d$1.error(this.name,"Log Collector WS Error",i.message)));let o=i=>{let a=i.toString();this.cfg.devMode&&process.stdout.write(`[${this.name}] ${a}`),r&&r.readyState===k.OPEN&&r.send(JSON.stringify({app:this.name,timestamp:Date.now(),log:a}));};t.stdout?.on("data",o),t.stderr?.on("data",o);}};var T=class{workers=new Map;async start(t){if(this.workers.has(t.name)){d$1.warn("PM",`Worker "${t.name}" already registered \u2013 use restart()`);return}let e=new f(t);this.workers.set(t.name,e),await e.start();}async stop(t){let e=this.require(t);e&&await e.stop();}async restart(t){let e=this.require(t);e&&await e.restart();}async delete(t){let e$1=this.require(t);e$1&&(await e$1.stop(),this.workers.delete(t),e.delete(t),d$1.info("PM",`Deleted worker "${t}"`));}async getStats(t){if(t){let r=this.require(t);return r?[await r.getStats()]:[]}return await Promise.all([...this.workers.values()].map(r=>r.getStats()))}list(){return [...this.workers.keys()]}async stopAll(){d$1.info("PM","Stopping all workers..."),await Promise.all([...this.workers.values()].map(t=>t.stop())),d$1.info("PM","All workers stopped.");}getWorker(t){let e=this.workers.get(t);return e||(d$1.error(t,"Worker Not Found"),null)}require(t){let e=this.workers.get(t);return e||(d$1.error(t,"Worker Not Found"),null)}};export{b as a,f as b,T as c};
|