@zuzjs/pm 0.0.9 → 0.0.11
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/chunk-222DKHA5.js +7 -0
- package/dist/chunk-2CKALMT4.js +3 -0
- package/dist/chunk-EMQYIXKL.cjs +2 -0
- package/dist/chunk-HL4JRTOU.cjs +4 -0
- package/dist/chunk-SBIJ6FLH.js +1 -0
- package/dist/chunk-TVX2LZ37.cjs +8 -0
- package/dist/cli.cjs +3 -3
- package/dist/cli.js +2 -2
- package/dist/daemon.cjs +2 -2
- package/dist/daemon.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +4 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-2PXF47OQ.js +0 -6
- package/dist/chunk-3VIK6Q3M.js +0 -3
- package/dist/chunk-DMPZOTJB.js +0 -1
- package/dist/chunk-I6PNOIS2.cjs +0 -7
- package/dist/chunk-QZATTCNB.cjs +0 -2
- package/dist/chunk-UVQRIGIE.cjs +0 -4
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import C from'path';import {fileURLToPath}from'url';import J from'events';import h from'fs';import D from'net';import w from'os';var v=()=>fileURLToPath(import.meta.url),$=()=>C.dirname(v()),f=$();var L=(s=>(s.Fork="fork",s.Cluster="cluster",s))(L||{}),I=(o=>(o.Stopped="stopped",o.Starting="starting",o.Running="running",o.Stopping="stopping",o.Crashed="crashed",o.Errored="errored",o))(I||{});var R={info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",debug:"\x1B[90m",success:"\x1B[32m"},M="\x1B[0m",N="\x1B[1m";function O(){return new Date().toISOString()}function u(r,e,...s){let t=R[r],n=`${N}${t}[ZPM/${e.toUpperCase()}]${M} ${O()}`;console[r==="success"?"log":r](`${n} \u2192`,...s);}var l={info:(r,...e)=>u("info",r,...e),warn:(r,...e)=>u("warn",r,...e),error:(r,...e)=>u("error",r,...e),debug:(r,...e)=>u("debug",r,...e),success:(r,...e)=>u("success",r,...e)};var b=class extends J{map=new Map;set(e,s){this.map.set(e,s),this.emit("change",e,s);}get(e){return this.map.get(e)}has(e){return this.map.has(e)}delete(e){this.map.delete(e),this.emit("delete",e);}all(){return new Map(this.map)}onchange(e){return this.on("change",e)}offchange(e){return this.off("change",e)}},S=new b;function F(r="zuz-pm"){return w.platform()==="win32"?C.join("\\\\.\\pipe",r):C.join(w.tmpdir(),`${r}.sock`)}function ee(r){let e=F();h.existsSync(e)&&h.unlinkSync(e);let s=D.createServer(t=>{let n="";t.on("data",m=>{n+=m.toString();let o=n.split(`
|
|
2
|
+
`);n=o.pop()??"";for(let g of o)g.trim()&&E(r,t,g);}),t.on("error",m=>{l.error("IPC","Socket error:",m.message);});});return s.listen(e,()=>{if(w.platform()!=="win32")try{h.chmodSync(e,"777");}catch(t){console.error("Failed to set socket permissions:",t);}l.success("IPC",`Listening on ${e}`);}),s.on("error",t=>{l.error("IPC","Server error:",t);}),s}async function E(r,e,s){let t;try{t=JSON.parse(s);}catch{k(e,{ok:false,error:"Invalid JSON"});return}try{let n=null;switch(t.cmd){case "ping":n="pong";break;case "start":await r.start(t.config),n=`Started "${t.name}"`;break;case "stop":await r.stop(t.name),n=`Stopped "${t.name}"`;break;case "restart":await r.restart(t.name),n=`Restarted "${t.name}"`;break;case "delete":await r.delete(t.name),n=`Deleted "${t.name}"`;break;case "stats":n=await r.getStats(t.name);break;case "list":n=r.list();break;case "get-store":{let a=Array.from(S.all()).map(([c,i])=>({name:c,status:i.status,childrenCount:i.children.length,restartCount:i.restartCount,backoffTime:i.backoffTime,isRestarting:i.isRestarting,probeFailures:i.probeFailures}));e.write(JSON.stringify({type:"store-data",data:a})+`
|
|
3
|
+
`);break}case "logs":let m=t.name,o=[];if(m){let a=r.getWorker(m);if(!a){e.write(JSON.stringify({ok:!1,error:`Worker "${m}" not found`})+`
|
|
4
|
+
`);return}o.push(a);}else {let a=r.list();for(let c of a){let i=r.getWorker(c);i&&o.push(i);}}if(o.length===0){e.write(JSON.stringify({ok:!1,error:"No active workers to stream logs from"})+`
|
|
5
|
+
`);return}let g=[];for(let a of o){let c=a.mp();for(let i of c.children){let d=P=>{let x=m?"":`[${a.name}] `;e.write(JSON.stringify({ok:!0,data:`${x}${P.toString()}`})+`
|
|
6
|
+
`);};i.stdout?.on("data",d),i.stderr?.on("data",d),g.push({child:i,onData:d});}}e.on("close",()=>{for(let{child:a,onData:c}of g)a.stdout?.off("data",c),a.stderr?.off("data",c);});break;default:l.error("ZPM",`Unknown command: ${t.cmd}`);}k(e,{ok:!0,data:n});}catch(n){k(e,{ok:false,error:String(n.message??n)});}}function k(r,e){r.writable&&r.write(JSON.stringify(e)+`
|
|
7
|
+
`);}export{f as a,L as b,I as c,l as d,S as e,F as f,ee as g};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {a,d,f as f$1}from'./chunk-222DKHA5.js';import {spawn}from'child_process';import p from'fs';import y from'net';import w from'os';import f from'path';function s(d,n="zuz-pm"){return new Promise((t,e)=>{let r=y.createConnection(f$1(n)),o="";r.on("connect",()=>{r.write(JSON.stringify(d)+`
|
|
2
|
+
`);}),r.on("data",i=>{o+=i.toString();let m=o.split(`
|
|
3
|
+
`);o=m.pop()??"";for(let g of m)if(g.trim())try{let a=JSON.parse(g);r.destroy(),a.ok?t(a.data):e(new Error(a.error));}catch(a){r.destroy(),e(a);}}),r.on("error",i=>e(i)),r.setTimeout(1e4,()=>{r.destroy(),e(new Error("IPC timeout"));});})}var u=class{daemonScript;namespace;constructor(n){this.namespace=n?.namespace??"zuz-pm",this.daemonScript=n?.daemonScript??f.join(a,"daemon.js");}async isDaemonRunning(){try{return d.info("[ZPM]","Daemon is Running :?"),await s({cmd:"ping"},this.namespace),!0}catch{return d.info("[ZPM]","Daemon is not running."),false}}async ensureDaemon(){if(await this.isDaemonRunning())return;d.info("Starting ZPM daemon...");let t=process.env.NODE_ENV!=="production";spawn(process.execPath,[this.daemonScript],{detached:true,stdio:t?"inherit":"ignore"}).unref(),await this.waitForDaemon(8e3);}async killDaemon(){let n=f.join(w.tmpdir(),"zuz-pm.pid");if(!p.existsSync(n))throw new Error("Daemon PID file not found \u2013 is the daemon running?");let t=Number(p.readFileSync(n,"utf8").trim());try{process.kill(t,"SIGTERM"),console.log(`[ZPM] Sent SIGTERM to daemon (PID ${t})`);}catch(e){throw new Error(`Failed to kill daemon: ${e.message}`)}finally{p.unlinkSync(n);}}async getStore(){return s({cmd:"get-store"},this.namespace)}async start(n){return s({cmd:"start",name:n.name,config:n},this.namespace)}async stop(n){return s({cmd:"stop",name:n},this.namespace)}async restart(n){return s({cmd:"restart",name:n},this.namespace)}async delete(n){return s({cmd:"delete",name:n},this.namespace)}async stats(n){return s({cmd:"stats",name:n},this.namespace)}async list(){return s({cmd:"list"},this.namespace)}waitForDaemon(n){let t=Date.now(),e=200;return new Promise((r,o)=>{let i=()=>{this.isDaemonRunning().then(m=>{if(m)return r();if(Date.now()-t>n)return o(new Error("Daemon did not start in time"));setTimeout(i,e);});};setTimeout(i,e);})}},I=new u;export{u as a,I as b};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkTVX2LZ37_cjs=require('./chunk-TVX2LZ37.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'),M=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 M__default=/*#__PURE__*/_interopDefault(M);/* 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,E=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"){chunkTVX2LZ37_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(),chunkTVX2LZ37_cjs.d.info(this.name,"Initializing fresh start...");try{await this.spawnAll(),this.cfg.devMode&&this.watchFiles();}catch(e){this.patch({status:"errored"}),chunkTVX2LZ37_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}),chunkTVX2LZ37_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){chunkTVX2LZ37_cjs.d.error(this.name,`Stop timed out, forcing state reset: ${e.message||"UNKNOWN"}`);}this.patch({children:[],status:"stopped",startTime:null}),this.stopWatcher(),chunkTVX2LZ37_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}),chunkTVX2LZ37_cjs.d.info(this.name,"Stopped.");}async restart(){let t=this.mp();t.isRestarting||(chunkTVX2LZ37_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(){chunkTVX2LZ37_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 M__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)){chunkTVX2LZ37_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){chunkTVX2LZ37_cjs.d.error(this.name,"Failed to spawn any instances."),this.patch({status:"stopped"});return}this.patch({children:r,startTime:Date.now(),status:"running"}),chunkTVX2LZ37_cjs.d.success(this.name,`Started ${r.length} instance(s) [${t}]`);let o=setTimeout(()=>{this.mp().status==="running"&&(this.patch({backoffTime:d,restartCount:0}),chunkTVX2LZ37_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=>{chunkTVX2LZ37_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 chunkTVX2LZ37_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(chunkTVX2LZ37_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){chunkTVX2LZ37_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??E;chunkTVX2LZ37_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}),chunkTVX2LZ37_cjs.d.warn(this.name,`Liveness probe failed (${h}/${r})`),h>=r&&(chunkTVX2LZ37_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")&&(chunkTVX2LZ37_cjs.d.info(this.name,`File ${e}: ${u__default.default.basename(r)} \u2013 restarting`),this.restart());}),this.watcher.on("error",e=>chunkTVX2LZ37_cjs.d.error(this.name,"Watcher error:",e)),this.watcher.on("ready",()=>chunkTVX2LZ37_cjs.d.info(this.name,`Watching ${t}`));}stopWatcher(){this.watcher&&(this.watcher.close(),this.watcher=null);}initStore(){chunkTVX2LZ37_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 chunkTVX2LZ37_cjs.e.get(this.name)}_patch(t){chunkTVX2LZ37_cjs.e.set(this.name,{...this.mp(),...t});}patch(t){let e=this.mp();t.status&&t.status!==e.status&&chunkTVX2LZ37_cjs.d.info(this.name,`[STATE] ${e.status} \u2794 ${t.status}${t.isRestarting?" (Restarting)":""}`),chunkTVX2LZ37_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",()=>chunkTVX2LZ37_cjs.d.debug(this.name,"Connected to log collector")),r.on("error",i=>chunkTVX2LZ37_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)){chunkTVX2LZ37_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),chunkTVX2LZ37_cjs.e.delete(t),chunkTVX2LZ37_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(){chunkTVX2LZ37_cjs.d.info("PM","Stopping all workers..."),await Promise.all([...this.workers.values()].map(t=>t.stop())),chunkTVX2LZ37_cjs.d.info("PM","All workers stopped.");}getWorker(t){let e=this.workers.get(t);return e||(chunkTVX2LZ37_cjs.d.error(t,"Worker Not Found"),null)}require(t){let e=this.workers.get(t);return e||(chunkTVX2LZ37_cjs.d.error(t,"Worker Not Found"),null)}};exports.a=w;exports.b=f;exports.c=P;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
'use strict';var chunkTVX2LZ37_cjs=require('./chunk-TVX2LZ37.cjs'),child_process=require('child_process'),p=require('fs'),h=require('net'),y=require('os'),P=require('path');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var p__default=/*#__PURE__*/_interopDefault(p);var h__default=/*#__PURE__*/_interopDefault(h);var y__default=/*#__PURE__*/_interopDefault(y);var P__default=/*#__PURE__*/_interopDefault(P);/* ZuzJS Process Manager */
|
|
2
|
+
function s(d,n="zuz-pm"){return new Promise((t,e)=>{let r=h__default.default.createConnection(chunkTVX2LZ37_cjs.f(n)),o="";r.on("connect",()=>{r.write(JSON.stringify(d)+`
|
|
3
|
+
`);}),r.on("data",i=>{o+=i.toString();let m=o.split(`
|
|
4
|
+
`);o=m.pop()??"";for(let g of m)if(g.trim())try{let a=JSON.parse(g);r.destroy(),a.ok?t(a.data):e(new Error(a.error));}catch(a){r.destroy(),e(a);}}),r.on("error",i=>e(i)),r.setTimeout(1e4,()=>{r.destroy(),e(new Error("IPC timeout"));});})}var u=class{daemonScript;namespace;constructor(n){this.namespace=n?.namespace??"zuz-pm",this.daemonScript=n?.daemonScript??P__default.default.join(__dirname,"daemon.js");}async isDaemonRunning(){try{return chunkTVX2LZ37_cjs.d.info("[ZPM]","Daemon is Running :?"),await s({cmd:"ping"},this.namespace),!0}catch{return chunkTVX2LZ37_cjs.d.info("[ZPM]","Daemon is not running."),false}}async ensureDaemon(){if(await this.isDaemonRunning())return;chunkTVX2LZ37_cjs.d.info("Starting ZPM daemon...");let t=process.env.NODE_ENV!=="production";child_process.spawn(process.execPath,[this.daemonScript],{detached:true,stdio:t?"inherit":"ignore"}).unref(),await this.waitForDaemon(8e3);}async killDaemon(){let n=P__default.default.join(y__default.default.tmpdir(),"zuz-pm.pid");if(!p__default.default.existsSync(n))throw new Error("Daemon PID file not found \u2013 is the daemon running?");let t=Number(p__default.default.readFileSync(n,"utf8").trim());try{process.kill(t,"SIGTERM"),console.log(`[ZPM] Sent SIGTERM to daemon (PID ${t})`);}catch(e){throw new Error(`Failed to kill daemon: ${e.message}`)}finally{p__default.default.unlinkSync(n);}}async getStore(){return s({cmd:"get-store"},this.namespace)}async start(n){return s({cmd:"start",name:n.name,config:n},this.namespace)}async stop(n){return s({cmd:"stop",name:n},this.namespace)}async restart(n){return s({cmd:"restart",name:n},this.namespace)}async delete(n){return s({cmd:"delete",name:n},this.namespace)}async stats(n){return s({cmd:"stats",name:n},this.namespace)}async list(){return s({cmd:"list"},this.namespace)}waitForDaemon(n){let t=Date.now(),e=200;return new Promise((r,o)=>{let i=()=>{this.isDaemonRunning().then(m=>{if(m)return r();if(Date.now()-t>n)return o(new Error("Daemon did not start in time"));setTimeout(i,e);});};setTimeout(i,e);})}},C=new u;exports.a=u;exports.b=C;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {d as d$1,e}from'./chunk-222DKHA5.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 E 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 E(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)":""}`),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};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
'use strict';var R=require('events'),b=require('fs'),M=require('net'),S=require('os'),w=require('path');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var R__default=/*#__PURE__*/_interopDefault(R);var b__default=/*#__PURE__*/_interopDefault(b);var M__default=/*#__PURE__*/_interopDefault(M);var S__default=/*#__PURE__*/_interopDefault(S);var w__default=/*#__PURE__*/_interopDefault(w);/* ZuzJS Process Manager */
|
|
2
|
+
var x=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,f=x();var y=(s=>(s.Fork="fork",s.Cluster="cluster",s))(y||{}),T=(o=>(o.Stopped="stopped",o.Starting="starting",o.Running="running",o.Stopping="stopping",o.Crashed="crashed",o.Errored="errored",o))(T||{});var v={info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",debug:"\x1B[90m",success:"\x1B[32m"},$="\x1B[0m",I="\x1B[1m";function L(){return new Date().toISOString()}function g(r,e,...s){let t=v[r],n=`${I}${t}[ZPM/${e.toUpperCase()}]${$} ${L()}`;console[r==="success"?"log":r](`${n} \u2192`,...s);}var l={info:(r,...e)=>g("info",r,...e),warn:(r,...e)=>g("warn",r,...e),error:(r,...e)=>g("error",r,...e),debug:(r,...e)=>g("debug",r,...e),success:(r,...e)=>g("success",r,...e)};var p=class extends R__default.default{map=new Map;set(e,s){this.map.set(e,s),this.emit("change",e,s);}get(e){return this.map.get(e)}has(e){return this.map.has(e)}delete(e){this.map.delete(e),this.emit("delete",e);}all(){return new Map(this.map)}onchange(e){return this.on("change",e)}offchange(e){return this.off("change",e)}},k=new p;function N(r="zuz-pm"){return S__default.default.platform()==="win32"?w__default.default.join("\\\\.\\pipe",r):w__default.default.join(S__default.default.tmpdir(),`${r}.sock`)}function G(r){let e=N();b__default.default.existsSync(e)&&b__default.default.unlinkSync(e);let s=M__default.default.createServer(t=>{let n="";t.on("data",c=>{n+=c.toString();let o=n.split(`
|
|
3
|
+
`);n=o.pop()??"";for(let u of o)u.trim()&&O(r,t,u);}),t.on("error",c=>{l.error("IPC","Socket error:",c.message);});});return s.listen(e,()=>{if(S__default.default.platform()!=="win32")try{b__default.default.chmodSync(e,"777");}catch(t){console.error("Failed to set socket permissions:",t);}l.success("IPC",`Listening on ${e}`);}),s.on("error",t=>{l.error("IPC","Server error:",t);}),s}async function O(r,e,s){let t;try{t=JSON.parse(s);}catch{h(e,{ok:false,error:"Invalid JSON"});return}try{let n=null;switch(t.cmd){case "ping":n="pong";break;case "start":await r.start(t.config),n=`Started "${t.name}"`;break;case "stop":await r.stop(t.name),n=`Stopped "${t.name}"`;break;case "restart":await r.restart(t.name),n=`Restarted "${t.name}"`;break;case "delete":await r.delete(t.name),n=`Deleted "${t.name}"`;break;case "stats":n=await r.getStats(t.name);break;case "list":n=r.list();break;case "get-store":{let a=Array.from(k.all()).map(([m,i])=>({name:m,status:i.status,childrenCount:i.children.length,restartCount:i.restartCount,backoffTime:i.backoffTime,isRestarting:i.isRestarting,probeFailures:i.probeFailures}));e.write(JSON.stringify({type:"store-data",data:a})+`
|
|
4
|
+
`);break}case "logs":let c=t.name,o=[];if(c){let a=r.getWorker(c);if(!a){e.write(JSON.stringify({ok:!1,error:`Worker "${c}" not found`})+`
|
|
5
|
+
`);return}o.push(a);}else {let a=r.list();for(let m of a){let i=r.getWorker(m);i&&o.push(i);}}if(o.length===0){e.write(JSON.stringify({ok:!1,error:"No active workers to stream logs from"})+`
|
|
6
|
+
`);return}let u=[];for(let a of o){let m=a.mp();for(let i of m.children){let d=C=>{let P=c?"":`[${a.name}] `;e.write(JSON.stringify({ok:!0,data:`${P}${C.toString()}`})+`
|
|
7
|
+
`);};i.stdout?.on("data",d),i.stderr?.on("data",d),u.push({child:i,onData:d});}}e.on("close",()=>{for(let{child:a,onData:m}of u)a.stdout?.off("data",m),a.stderr?.off("data",m);});break;default:l.error("ZPM",`Unknown command: ${t.cmd}`);}h(e,{ok:!0,data:n});}catch(n){h(e,{ok:false,error:String(n.message??n)});}}function h(r,e){r.writable&&r.write(JSON.stringify(e)+`
|
|
8
|
+
`);}exports.a=f;exports.b=y;exports.c=T;exports.d=l;exports.e=k;exports.f=N;exports.g=G;
|
package/dist/cli.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
'use strict';var
|
|
3
|
-
var
|
|
2
|
+
'use strict';var chunkHL4JRTOU_cjs=require('./chunk-HL4JRTOU.cjs'),chunkTVX2LZ37_cjs=require('./chunk-TVX2LZ37.cjs'),commander=require('commander'),h=require('fs'),y=require('net'),i=require('path'),url=require('url'),c=require('picocolors');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var h__default=/*#__PURE__*/_interopDefault(h);var y__default=/*#__PURE__*/_interopDefault(y);var i__default=/*#__PURE__*/_interopDefault(i);var c__default=/*#__PURE__*/_interopDefault(c);/* ZuzJS Process Manager */
|
|
3
|
+
var r=new commander.Command;r.option("-s, --namespace <name>","Internal daemon namespace","zuz-pm");r.parseOptions(process.argv);var x=r.opts(),b=x.namespace,n=new chunkHL4JRTOU_cjs.a(b),v=i__default.default.dirname(url.fileURLToPath(chunkTVX2LZ37_cjs.a)),S=i__default.default.resolve(v,"../package.json"),$=JSON.parse(h__default.default.readFileSync(S,"utf8"));r.name("zpm").description("Production grade process manager for the @zuzjs ecosystem").version($.version,"-v, --version","output the current version");r.command("start <script>").description("Start a new process").option("-n, --name <name>","Unique name for the process").option("-p, --port <port>","Port the app listens on",parseInt).option("-i, --instances <number>","Number of instances (cluster mode)",parseInt,1).option("-d, --dev","Enable development mode (auto-restart)",false).option("-c, --cluster","Use cluster mode instead of fork",false).option("--ws <url>","WebSocket URL to stream logs (e.g. for ZPanel)","http://127.0.0.1:2082/_/wss/zpm").option("--save-logs","Save logs to a local file",false).option("--args <string>",'Arguments to pass to the script (e.g. "dev -p 3000")').option("--probe-type <type>","Type of probe: http, tcp, or exec").option("--probe-target <target>","URL, host:port, or command").option("--probe-interval <sec>","Seconds between probes",parseInt,30).option("--probe-threshold <count>","Failures before restart",parseInt,3).action(async(o,e)=>{try{await n.ensureDaemon();let t=i__default.default.resolve(process.cwd(),o),s=await n.start({name:e.name??i__default.default.basename(o),scriptPath:t,port:e.port,instances:e.instances,devMode:e.dev,mode:e.cluster?"cluster":"fork",args:e.args?e.args.split(" "):[],probe:e.probeTarget?{type:e.probeType,target:e.probeTarget||(e.probeType==="http"?"http://localhost:3000":"localhost:3000"),intervalSeconds:e.probeInterval,failureThreshold:e.probeThreshold,timeoutSeconds:5}:void 0,logs:{wsUrl:e.ws,saveToFile:e.saveLogs}});console.log(c__default.default.cyan("[ZPM]"),s);}catch(t){console.log(c__default.default.cyan("[ZPM]"),c__default.default.red("[ERROR]"),t.message);}});r.command("logs [name]").description("Stream real-time logs (omit name for all logs)").action(async o=>{try{if(!await n.isDaemonRunning())throw new Error("Daemon is not running.");let t=o?`"${o}"`:"all workers";console.log(c__default.default.cyan("[ZPM]"),`Streaming logs for "${c__default.default.green(t)}" (Ctrl+C to stop)`);let s=y__default.default.createConnection(chunkTVX2LZ37_cjs.f(b));s.write(JSON.stringify({cmd:"logs",name:o})+`
|
|
4
4
|
`),s.on("data",a=>{let u=a.toString().split(`
|
|
5
5
|
`);for(let p of u)if(p.trim())try{let m=JSON.parse(p);m.ok?process.stdout.write(m.data):(console.error(`\x1B[31m${m.error}\x1B[0m`),process.exit(1));}catch{}}),s.on("error",a=>{console.error(`\x1B[31m[IPC Error]\x1B[0m ${a.message}`),process.exit(1);}),process.on("SIGINT",()=>{s.destroy(),console.log(`
|
|
6
|
-
\x1B[90mDisconnected from logs.\x1B[0m`),process.exit();});}catch(e){console.error(`\x1B[31m[Error]\x1B[0m ${e.message}`);}});
|
|
6
|
+
\x1B[90mDisconnected from logs.\x1B[0m`),process.exit();});}catch(e){console.error(`\x1B[31m[Error]\x1B[0m ${e.message}`);}});r.command("list").description("List all managed processes").action(async()=>{let o=await n.list();if(o.length===0){console.log("No workers registered.");return}console.log("\x1B[1mManaged Processes:\x1B[0m"),o.forEach(e=>console.log(` \u2022 ${e}`));});r.command("stats [name]").description("Show telemetry for processes").action(async o=>{let e=await n.stats(o);if(e.length===0){console.log("No stats available.");return}e.forEach(t=>{let s=t.uptime?`${Math.round(t.uptime/1e3)}s`:"0s",a=t.status==="running"?"\x1B[32m":"\x1B[31m";console.log(`${a}[${t.status.toUpperCase()}]\x1B[0m \x1B[1m${t.name.padEnd(15)}\x1B[0m PID: ${String(t.pid??"N/A").padEnd(6)} CPU: ${String(t.cpu??0).padStart(3)}% MEM: ${Math.round((t.memoryRss??0)/1024/1024)}MB Uptime: ${s}`);});});["stop","restart","delete"].forEach(o=>{r.command(`${o} <name>`).description(`${o.charAt(0).toUpperCase()+o.slice(1)} a process`).action(async e=>{try{let t=await n[o](e);console.log(`\x1B[32m[ZPM]\x1B[0m ${t}`);}catch(t){console.error(`\x1B[31m[Error]\x1B[0m ${t.message}`);}});});r.command("kill-daemon").description("Stop the background ZPM daemon").action(async()=>{await n.killDaemon(),console.log("\x1B[33mDaemon killed.\x1B[0m");});r.command("store").description("Show raw internal store state for debugging").action(async()=>{let o=await n.getStore();console.log(o);});r.parse(process.argv);
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {a}from'./chunk-
|
|
2
|
+
import {a}from'./chunk-2CKALMT4.js';import {f as f$1}from'./chunk-222DKHA5.js';import {Command}from'commander';import f from'fs';import h from'net';import i from'path';import {fileURLToPath}from'url';import c from'picocolors';var r=new Command;r.option("-s, --namespace <name>","Internal daemon namespace","zuz-pm");r.parseOptions(process.argv);var w=r.opts(),d=w.namespace,n=new a(d),x=i.dirname(fileURLToPath(import.meta.url)),v=i.resolve(x,"../package.json"),S=JSON.parse(f.readFileSync(v,"utf8"));r.name("zpm").description("Production grade process manager for the @zuzjs ecosystem").version(S.version,"-v, --version","output the current version");r.command("start <script>").description("Start a new process").option("-n, --name <name>","Unique name for the process").option("-p, --port <port>","Port the app listens on",parseInt).option("-i, --instances <number>","Number of instances (cluster mode)",parseInt,1).option("-d, --dev","Enable development mode (auto-restart)",false).option("-c, --cluster","Use cluster mode instead of fork",false).option("--ws <url>","WebSocket URL to stream logs (e.g. for ZPanel)","http://127.0.0.1:2082/_/wss/zpm").option("--save-logs","Save logs to a local file",false).option("--args <string>",'Arguments to pass to the script (e.g. "dev -p 3000")').option("--probe-type <type>","Type of probe: http, tcp, or exec").option("--probe-target <target>","URL, host:port, or command").option("--probe-interval <sec>","Seconds between probes",parseInt,30).option("--probe-threshold <count>","Failures before restart",parseInt,3).action(async(o,e)=>{try{await n.ensureDaemon();let t=i.resolve(process.cwd(),o),s=await n.start({name:e.name??i.basename(o),scriptPath:t,port:e.port,instances:e.instances,devMode:e.dev,mode:e.cluster?"cluster":"fork",args:e.args?e.args.split(" "):[],probe:e.probeTarget?{type:e.probeType,target:e.probeTarget||(e.probeType==="http"?"http://localhost:3000":"localhost:3000"),intervalSeconds:e.probeInterval,failureThreshold:e.probeThreshold,timeoutSeconds:5}:void 0,logs:{wsUrl:e.ws,saveToFile:e.saveLogs}});console.log(c.cyan("[ZPM]"),s);}catch(t){console.log(c.cyan("[ZPM]"),c.red("[ERROR]"),t.message);}});r.command("logs [name]").description("Stream real-time logs (omit name for all logs)").action(async o=>{try{if(!await n.isDaemonRunning())throw new Error("Daemon is not running.");let t=o?`"${o}"`:"all workers";console.log(c.cyan("[ZPM]"),`Streaming logs for "${c.green(t)}" (Ctrl+C to stop)`);let s=h.createConnection(f$1(d));s.write(JSON.stringify({cmd:"logs",name:o})+`
|
|
3
3
|
`),s.on("data",a=>{let b=a.toString().split(`
|
|
4
4
|
`);for(let p of b)if(p.trim())try{let m=JSON.parse(p);m.ok?process.stdout.write(m.data):(console.error(`\x1B[31m${m.error}\x1B[0m`),process.exit(1));}catch{}}),s.on("error",a=>{console.error(`\x1B[31m[IPC Error]\x1B[0m ${a.message}`),process.exit(1);}),process.on("SIGINT",()=>{s.destroy(),console.log(`
|
|
5
|
-
\x1B[90mDisconnected from logs.\x1B[0m`),process.exit();});}catch(e){console.error(`\x1B[31m[Error]\x1B[0m ${e.message}`);}});
|
|
5
|
+
\x1B[90mDisconnected from logs.\x1B[0m`),process.exit();});}catch(e){console.error(`\x1B[31m[Error]\x1B[0m ${e.message}`);}});r.command("list").description("List all managed processes").action(async()=>{let o=await n.list();if(o.length===0){console.log("No workers registered.");return}console.log("\x1B[1mManaged Processes:\x1B[0m"),o.forEach(e=>console.log(` \u2022 ${e}`));});r.command("stats [name]").description("Show telemetry for processes").action(async o=>{let e=await n.stats(o);if(e.length===0){console.log("No stats available.");return}e.forEach(t=>{let s=t.uptime?`${Math.round(t.uptime/1e3)}s`:"0s",a=t.status==="running"?"\x1B[32m":"\x1B[31m";console.log(`${a}[${t.status.toUpperCase()}]\x1B[0m \x1B[1m${t.name.padEnd(15)}\x1B[0m PID: ${String(t.pid??"N/A").padEnd(6)} CPU: ${String(t.cpu??0).padStart(3)}% MEM: ${Math.round((t.memoryRss??0)/1024/1024)}MB Uptime: ${s}`);});});["stop","restart","delete"].forEach(o=>{r.command(`${o} <name>`).description(`${o.charAt(0).toUpperCase()+o.slice(1)} a process`).action(async e=>{try{let t=await n[o](e);console.log(`\x1B[32m[ZPM]\x1B[0m ${t}`);}catch(t){console.error(`\x1B[31m[Error]\x1B[0m ${t.message}`);}});});r.command("kill-daemon").description("Stop the background ZPM daemon").action(async()=>{await n.killDaemon(),console.log("\x1B[33mDaemon killed.\x1B[0m");});r.command("store").description("Show raw internal store state for debugging").action(async()=>{let o=await n.getStore();console.log(o);});r.parse(process.argv);
|
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(){
|
|
1
|
+
'use strict';var chunkEMQYIXKL_cjs=require('./chunk-EMQYIXKL.cjs'),chunkTVX2LZ37_cjs=require('./chunk-TVX2LZ37.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(){chunkTVX2LZ37_cjs.d.success("daemon",`Booting ZPM daemon (PID ${process.pid})`),d();let o=new chunkEMQYIXKL_cjs.c,s=chunkTVX2LZ37_cjs.g(o);async function t(e){chunkTVX2LZ37_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=>chunkTVX2LZ37_cjs.d.error("daemon","Uncaught exception:",e)),process.on("unhandledRejection",e=>chunkTVX2LZ37_cjs.d.error("daemon","Unhandled rejection:",e)),chunkTVX2LZ37_cjs.d.success("daemon","Ready \u2013 waiting for IPC commands.");}S().catch(o=>{chunkTVX2LZ37_cjs.d.error("daemon","Fatal startup error:",o),process.exit(1);});
|
package/dist/daemon.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {c}from'./chunk-SBIJ6FLH.js';import {d as d$1,g}from'./chunk-222DKHA5.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
|
|
1
|
+
'use strict';var chunkHL4JRTOU_cjs=require('./chunk-HL4JRTOU.cjs'),chunkEMQYIXKL_cjs=require('./chunk-EMQYIXKL.cjs'),chunkTVX2LZ37_cjs=require('./chunk-TVX2LZ37.cjs');Object.defineProperty(exports,"ZPMClient",{enumerable:true,get:function(){return chunkHL4JRTOU_cjs.a}});Object.defineProperty(exports,"zpm",{enumerable:true,get:function(){return chunkHL4JRTOU_cjs.b}});Object.defineProperty(exports,"ProcessManager",{enumerable:true,get:function(){return chunkEMQYIXKL_cjs.c}});Object.defineProperty(exports,"Worker",{enumerable:true,get:function(){return chunkEMQYIXKL_cjs.b}});Object.defineProperty(exports,"runProbe",{enumerable:true,get:function(){return chunkEMQYIXKL_cjs.a}});Object.defineProperty(exports,"WorkerMode",{enumerable:true,get:function(){return chunkTVX2LZ37_cjs.b}});Object.defineProperty(exports,"WorkerStatus",{enumerable:true,get:function(){return chunkTVX2LZ37_cjs.c}});Object.defineProperty(exports,"getSocketPath",{enumerable:true,get:function(){return chunkTVX2LZ37_cjs.f}});Object.defineProperty(exports,"logger",{enumerable:true,get:function(){return chunkTVX2LZ37_cjs.d}});Object.defineProperty(exports,"processStore",{enumerable:true,get:function(){return chunkTVX2LZ37_cjs.e}});
|
package/dist/index.d.cts
CHANGED
|
@@ -92,6 +92,8 @@ type IPCCommand = {
|
|
|
92
92
|
} | {
|
|
93
93
|
cmd: "logs";
|
|
94
94
|
name?: string;
|
|
95
|
+
} | {
|
|
96
|
+
cmd: "get-store";
|
|
95
97
|
};
|
|
96
98
|
type IPCResponse = {
|
|
97
99
|
ok: true;
|
|
@@ -142,6 +144,7 @@ declare class Worker {
|
|
|
142
144
|
private stopWatcher;
|
|
143
145
|
private initStore;
|
|
144
146
|
mp(): ManagedProcess;
|
|
147
|
+
private _patch;
|
|
145
148
|
private patch;
|
|
146
149
|
private clearTimers;
|
|
147
150
|
private setupLogging;
|
|
@@ -192,6 +195,7 @@ declare class ZPMClient {
|
|
|
192
195
|
ensureDaemon(): Promise<void>;
|
|
193
196
|
/** Kill the daemon by PID */
|
|
194
197
|
killDaemon(): Promise<void>;
|
|
198
|
+
getStore(): Promise<string>;
|
|
195
199
|
start(config: WorkerConfig): Promise<string>;
|
|
196
200
|
stop(name: string): Promise<string>;
|
|
197
201
|
restart(name: string): Promise<string>;
|
package/dist/index.d.ts
CHANGED
|
@@ -92,6 +92,8 @@ type IPCCommand = {
|
|
|
92
92
|
} | {
|
|
93
93
|
cmd: "logs";
|
|
94
94
|
name?: string;
|
|
95
|
+
} | {
|
|
96
|
+
cmd: "get-store";
|
|
95
97
|
};
|
|
96
98
|
type IPCResponse = {
|
|
97
99
|
ok: true;
|
|
@@ -142,6 +144,7 @@ declare class Worker {
|
|
|
142
144
|
private stopWatcher;
|
|
143
145
|
private initStore;
|
|
144
146
|
mp(): ManagedProcess;
|
|
147
|
+
private _patch;
|
|
145
148
|
private patch;
|
|
146
149
|
private clearTimers;
|
|
147
150
|
private setupLogging;
|
|
@@ -192,6 +195,7 @@ declare class ZPMClient {
|
|
|
192
195
|
ensureDaemon(): Promise<void>;
|
|
193
196
|
/** Kill the daemon by PID */
|
|
194
197
|
killDaemon(): Promise<void>;
|
|
198
|
+
getStore(): Promise<string>;
|
|
195
199
|
start(config: WorkerConfig): Promise<string>;
|
|
196
200
|
stop(name: string): Promise<string>;
|
|
197
201
|
restart(name: string): Promise<string>;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as ZPMClient,b as zpm}from'./chunk-
|
|
1
|
+
export{a as ZPMClient,b as zpm}from'./chunk-2CKALMT4.js';export{c as ProcessManager,b as Worker,a as runProbe}from'./chunk-SBIJ6FLH.js';export{b as WorkerMode,c as WorkerStatus,f as getSocketPath,d as logger,e as processStore}from'./chunk-222DKHA5.js';
|
package/package.json
CHANGED
package/dist/chunk-2PXF47OQ.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import S from'path';import {fileURLToPath}from'url';import p from'fs';import O from'net';import k from'os';var y=()=>fileURLToPath(import.meta.url),v=()=>S.dirname(y()),d=v();var $=(s=>(s.Fork="fork",s.Cluster="cluster",s))($||{}),I=(o=>(o.Stopped="stopped",o.Starting="starting",o.Running="running",o.Stopping="stopping",o.Crashed="crashed",o.Errored="errored",o))(I||{});var T={info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",debug:"\x1B[90m",success:"\x1B[32m"},L="\x1B[0m",N="\x1B[1m";function R(){return new Date().toISOString()}function l(r,e,...s){let n=T[r],t=`${N}${n}[ZPM/${e.toUpperCase()}]${L} ${R()}`;console[r==="success"?"log":r](`${t} \u2192`,...s);}var f={info:(r,...e)=>l("info",r,...e),warn:(r,...e)=>l("warn",r,...e),error:(r,...e)=>l("error",r,...e),debug:(r,...e)=>l("debug",r,...e),success:(r,...e)=>l("success",r,...e)};function J(r="zuz-pm"){return k.platform()==="win32"?S.join("\\\\.\\pipe",r):S.join(k.tmpdir(),`${r}.sock`)}function q(r){let e=J();p.existsSync(e)&&p.unlinkSync(e);let s=O.createServer(n=>{let t="";n.on("data",i=>{t+=i.toString();let o=t.split(`
|
|
2
|
-
`);t=o.pop()??"";for(let u of o)u.trim()&&D(r,n,u);}),n.on("error",i=>{f.error("IPC","Socket error:",i.message);});});return s.listen(e,()=>{if(k.platform()!=="win32")try{p.chmodSync(e,"777");}catch(n){console.error("Failed to set socket permissions:",n);}f.success("IPC",`Listening on ${e}`);}),s.on("error",n=>{f.error("IPC","Server error:",n);}),s}async function D(r,e,s){let n;try{n=JSON.parse(s);}catch{b(e,{ok:false,error:"Invalid JSON"});return}try{let t=null;switch(n.cmd){case "ping":t="pong";break;case "start":await r.start(n.config),t=`Started "${n.name}"`;break;case "stop":await r.stop(n.name),t=`Stopped "${n.name}"`;break;case "restart":await r.restart(n.name),t=`Restarted "${n.name}"`;break;case "delete":await r.delete(n.name),t=`Deleted "${n.name}"`;break;case "stats":t=await r.getStats(n.name);break;case "list":t=r.list();break;case "logs":let i=n.name,o=[];if(i){let a=r.getWorker(i);if(!a){e.write(JSON.stringify({ok:!1,error:`Worker "${i}" not found`})+`
|
|
3
|
-
`);return}o.push(a);}else {let a=r.list();for(let m of a){let c=r.getWorker(m);c&&o.push(c);}}if(o.length===0){e.write(JSON.stringify({ok:!1,error:"No active workers to stream logs from"})+`
|
|
4
|
-
`);return}let u=[];for(let a of o){let m=a.mp();for(let c of m.children){let g=C=>{let h=i?"":`[${a.name}] `;e.write(JSON.stringify({ok:!0,data:`${h}${C.toString()}`})+`
|
|
5
|
-
`);};c.stdout?.on("data",g),c.stderr?.on("data",g),u.push({child:c,onData:g});}}e.on("close",()=>{for(let{child:a,onData:m}of u)a.stdout?.off("data",m),a.stderr?.off("data",m);});break;default:throw new Error(`Unknown command: ${n.cmd}`)}b(e,{ok:!0,data:t});}catch(t){b(e,{ok:false,error:String(t.message??t)});}}function b(r,e){r.writable&&r.write(JSON.stringify(e)+`
|
|
6
|
-
`);}export{d as a,$ as b,I as c,f as d,J as e,q as f};
|
package/dist/chunk-3VIK6Q3M.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import {a,d,e}from'./chunk-2PXF47OQ.js';import {spawn}from'child_process';import p from'fs';import y from'net';import w from'os';import f from'path';function i(d,n="zuz-pm"){return new Promise((t,r)=>{let e$1=y.createConnection(e(n)),o="";e$1.on("connect",()=>{e$1.write(JSON.stringify(d)+`
|
|
2
|
-
`);}),e$1.on("data",s=>{o+=s.toString();let m=o.split(`
|
|
3
|
-
`);o=m.pop()??"";for(let l of m)if(l.trim())try{let a=JSON.parse(l);e$1.destroy(),a.ok?t(a.data):r(new Error(a.error));}catch(a){e$1.destroy(),r(a);}}),e$1.on("error",s=>r(s)),e$1.setTimeout(1e4,()=>{e$1.destroy(),r(new Error("IPC timeout"));});})}var u=class{daemonScript;namespace;constructor(n){this.namespace=n?.namespace??"zuz-pm",this.daemonScript=n?.daemonScript??f.join(a,"daemon.js");}async isDaemonRunning(){try{return d.info("[ZPM]","Daemon is Running :?"),await i({cmd:"ping"},this.namespace),!0}catch{return d.info("[ZPM]","Daemon is not running."),false}}async ensureDaemon(){if(await this.isDaemonRunning())return;d.info("Starting ZPM daemon...");let t=process.env.NODE_ENV!=="production";spawn(process.execPath,[this.daemonScript],{detached:true,stdio:t?"inherit":"ignore"}).unref(),await this.waitForDaemon(8e3);}async killDaemon(){let n=f.join(w.tmpdir(),"zuz-pm.pid");if(!p.existsSync(n))throw new Error("Daemon PID file not found \u2013 is the daemon running?");let t=Number(p.readFileSync(n,"utf8").trim());try{process.kill(t,"SIGTERM"),console.log(`[ZPM] Sent SIGTERM to daemon (PID ${t})`);}catch(r){throw new Error(`Failed to kill daemon: ${r.message}`)}finally{p.unlinkSync(n);}}async start(n){return i({cmd:"start",name:n.name,config:n},this.namespace)}async stop(n){return i({cmd:"stop",name:n},this.namespace)}async restart(n){return i({cmd:"restart",name:n},this.namespace)}async delete(n){return i({cmd:"delete",name:n},this.namespace)}async stats(n){return i({cmd:"stats",name:n},this.namespace)}async list(){return i({cmd:"list"},this.namespace)}waitForDaemon(n){let t=Date.now(),r=200;return new Promise((e,o)=>{let s=()=>{this.isDaemonRunning().then(m=>{if(m)return e();if(Date.now()-t>n)return o(new Error("Daemon did not start in time"));setTimeout(s,r);});};setTimeout(s,r);})}},I=new u;export{u as a,I as b};
|
package/dist/chunk-DMPZOTJB.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import {d as d$1}from'./chunk-2PXF47OQ.js';import S from'events';import {spawn,exec}from'child_process';import C from'http';import W from'https';import F from'net';import I from'chokidar';import _ from'fs';import T from'os';import m from'path';import P from'ws';import A from'pidusage';var d=class extends S{map=new Map;set(t,e){this.map.set(t,e),this.emit("change",t,e);}get(t){return this.map.get(t)}has(t){return this.map.has(t)}delete(t){this.map.delete(t),this.emit("delete",t);}all(){return new Map(this.map)}onchange(t){return this.on("change",t)}offchange(t){return this.off("change",t)}},h=new d;function $(n,t){return new Promise(e=>{let o=(n.startsWith("https")?W:C).get(n,{timeout:t},s=>{e((s.statusCode??500)<500);});o.on("error",()=>e(false)),o.on("timeout",()=>{o.destroy(),e(false);});})}function x(n,t){let[e,r]=n.split(":"),o=Number(r);return new Promise(s=>{let a=F.createConnection({host:e,port:o},()=>{a.destroy(),s(true);});a.setTimeout(t),a.on("timeout",()=>{a.destroy(),s(false);}),a.on("error",()=>s(false));})}function M(n,t){return new Promise(e=>{let r=setTimeout(()=>e(false),t);exec(n,o=>{clearTimeout(r),e(!o);});})}async function k(n){let t=(n.timeoutSeconds??5)*1e3;switch(n.type){case "http":return $(n.target,t);case "tcp":return x(n.target,t);case "exec":return M(n.target,t);default:return false}}var p=5e3,D=16e3,b=1e3,N=5e3;async function K(n){return new Promise(t=>{F.createServer().once("error",()=>t(false)).once("listening",function(){this.close(()=>t(true));}).listen(n);})}async function O(n){if(await K(n))return;let t=T.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 u(n,t){let e=n.process?.pid??n.pid;if(e)return new Promise(r=>{let o=false,s=()=>{o||(o=true,clearTimeout(a),r());};n.once?.("exit",s),n.once?.("exit",s);try{process.kill(e,"SIGTERM");}catch{return s()}let a=setTimeout(()=>{try{process.kill(e,"SIGKILL"),setTimeout(s,100);}catch{s();}},t),c=setInterval(()=>{try{process.kill(e,0);}catch{clearInterval(c),s();}},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",backoffTime:b,restartCount:0,probeFailures:0}),this.clearTimers(),await this.spawnAll(),this.cfg.devMode&&this.watchFiles();}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=>u(e,this.cfg.killTimeout??p))),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)u(e,this.cfg.killTimeout??p);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=>u(e,this.cfg.killTimeout??p))),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)u(e,this.cfg.killTimeout??p);}async getStats(){let t=this.mp(),e=t.children[0]?.pid??null,r=null,o=null,s=null;if(e&&t.status==="running")try{let a=await A(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:s,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 O(this.cfg.port);let t=this.cfg.mode??"fork",e=t==="cluster"?this.cfg.instances??T.cpus().length:1,r=[];for(let s=0;s<e;s++){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:b,restartCount:0}),d$1.success(this.name,"Process is stable."));},N);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:m.dirname(m.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",s=>{d$1.error(this.name,"Spawn error:",s);}),r.on("exit",(s,a)=>{let c=Date.now()-o;this.onChildExit(r,s,a,c);}),r}catch(t){return d$1.error(this.name,"Failed to fork child:",t),null}}onChildExit(t,e,r,o){let s=this.mp(),a=s.children.filter(c=>c!==t);if(this.patch({children:a}),s.status!=="stopping"){if(d$1.warn(this.name,`Process exited (code=${e}, signal=${r}, uptime=${o}ms)`),s.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??D;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,s=setInterval(async()=>{let a=this.mp();if(a.status!=="running")return;if(await k(t)){a.probeFailures>0&&this.patch({probeFailures:0});return}let l=a.probeFailures+1;this.patch({probeFailures:l}),d$1.warn(this.name,`Liveness probe failed (${l}/${r})`),l>=r&&(d$1.error(this.name,"Liveness probe threshold exceeded \u2013 restarting."),this.patch({probeFailures:0}),await this.restart());},e);this.patch({probeTimer:s});}stopProbe(){let{probeTimer:t}=this.mp();t&&(clearInterval(t),this.patch({probeTimer:null,probeFailures:0}));}watchFiles(){this.stopWatcher();let t=m.dirname(this.cfg.scriptPath);this.watcher=I.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}: ${m.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(){h.set(this.name,{config:this.cfg,children:[],status:"stopped",startTime:null,restartCount:0,backoffTime:b,restartTimer:null,stabilityTimer:null,probeTimer:null,probeFailures:0,isRestarting:false});}mp(){return h.get(this.name)}patch(t){h.set(this.name,{...this.mp(),...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 P(e),r.on("open",()=>d$1.debug(this.name,"Connected to log collector")),r.on("error",s=>d$1.error(this.name,"Log Collector WS Error",s.message)));let o=s=>{let a=s.toString();this.cfg.devMode&&process.stdout.write(`[${this.name}] ${a}`),r&&r.readyState===P.OPEN&&r.send(JSON.stringify({app:this.name,timestamp:Date.now(),log:a}));};t.stdout?.on("data",o),t.stderr?.on("data",o);}};var v=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){await this.require(t).stop();}async restart(t){await this.require(t).restart();}async delete(t){await this.require(t).stop(),this.workers.delete(t),h.delete(t),d$1.info("PM",`Deleted worker "${t}"`);}async getStats(t){return t?[await this.require(t).getStats()]: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||null}require(t){let e=this.workers.get(t);if(!e)throw new Error(`Worker "${t}" not found`);return e}};export{h as a,k as b,f as c,v as d};
|
package/dist/chunk-I6PNOIS2.cjs
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
'use strict';var p=require('fs'),R=require('net'),k=require('os'),w=require('path');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var p__default=/*#__PURE__*/_interopDefault(p);var R__default=/*#__PURE__*/_interopDefault(R);var k__default=/*#__PURE__*/_interopDefault(k);var w__default=/*#__PURE__*/_interopDefault(w);/* ZuzJS Process Manager */
|
|
2
|
-
var h=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,d=h();var P=(s=>(s.Fork="fork",s.Cluster="cluster",s))(P||{}),x=(o=>(o.Stopped="stopped",o.Starting="starting",o.Running="running",o.Stopping="stopping",o.Crashed="crashed",o.Errored="errored",o))(x||{});var y={info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",debug:"\x1B[90m",success:"\x1B[32m"},v="\x1B[0m",$="\x1B[1m";function I(){return new Date().toISOString()}function l(e,r,...s){let n=y[e],t=`${$}${n}[ZPM/${r.toUpperCase()}]${v} ${I()}`;console[e==="success"?"log":e](`${t} \u2192`,...s);}var f={info:(e,...r)=>l("info",e,...r),warn:(e,...r)=>l("warn",e,...r),error:(e,...r)=>l("error",e,...r),debug:(e,...r)=>l("debug",e,...r),success:(e,...r)=>l("success",e,...r)};function L(e="zuz-pm"){return k__default.default.platform()==="win32"?w__default.default.join("\\\\.\\pipe",e):w__default.default.join(k__default.default.tmpdir(),`${e}.sock`)}function j(e){let r=L();p__default.default.existsSync(r)&&p__default.default.unlinkSync(r);let s=R__default.default.createServer(n=>{let t="";n.on("data",i=>{t+=i.toString();let o=t.split(`
|
|
3
|
-
`);t=o.pop()??"";for(let u of o)u.trim()&&T(e,n,u);}),n.on("error",i=>{f.error("IPC","Socket error:",i.message);});});return s.listen(r,()=>{if(k__default.default.platform()!=="win32")try{p__default.default.chmodSync(r,"777");}catch(n){console.error("Failed to set socket permissions:",n);}f.success("IPC",`Listening on ${r}`);}),s.on("error",n=>{f.error("IPC","Server error:",n);}),s}async function T(e,r,s){let n;try{n=JSON.parse(s);}catch{b(r,{ok:false,error:"Invalid JSON"});return}try{let t=null;switch(n.cmd){case "ping":t="pong";break;case "start":await e.start(n.config),t=`Started "${n.name}"`;break;case "stop":await e.stop(n.name),t=`Stopped "${n.name}"`;break;case "restart":await e.restart(n.name),t=`Restarted "${n.name}"`;break;case "delete":await e.delete(n.name),t=`Deleted "${n.name}"`;break;case "stats":t=await e.getStats(n.name);break;case "list":t=e.list();break;case "logs":let i=n.name,o=[];if(i){let a=e.getWorker(i);if(!a){r.write(JSON.stringify({ok:!1,error:`Worker "${i}" not found`})+`
|
|
4
|
-
`);return}o.push(a);}else {let a=e.list();for(let m of a){let c=e.getWorker(m);c&&o.push(c);}}if(o.length===0){r.write(JSON.stringify({ok:!1,error:"No active workers to stream logs from"})+`
|
|
5
|
-
`);return}let u=[];for(let a of o){let m=a.mp();for(let c of m.children){let g=S=>{let C=i?"":`[${a.name}] `;r.write(JSON.stringify({ok:!0,data:`${C}${S.toString()}`})+`
|
|
6
|
-
`);};c.stdout?.on("data",g),c.stderr?.on("data",g),u.push({child:c,onData:g});}}r.on("close",()=>{for(let{child:a,onData:m}of u)a.stdout?.off("data",m),a.stderr?.off("data",m);});break;default:throw new Error(`Unknown command: ${n.cmd}`)}b(r,{ok:!0,data:t});}catch(t){b(r,{ok:false,error:String(t.message??t)});}}function b(e,r){e.writable&&e.write(JSON.stringify(r)+`
|
|
7
|
-
`);}exports.a=d;exports.b=P;exports.c=x;exports.d=f;exports.e=L;exports.f=j;
|
package/dist/chunk-QZATTCNB.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkI6PNOIS2_cjs=require('./chunk-I6PNOIS2.cjs'),v=require('events'),child_process=require('child_process'),y=require('http'),C=require('https'),W=require('net'),M=require('chokidar'),L=require('fs'),P=require('os'),m=require('path'),k=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 C__default=/*#__PURE__*/_interopDefault(C);var W__default=/*#__PURE__*/_interopDefault(W);var M__default=/*#__PURE__*/_interopDefault(M);var L__default=/*#__PURE__*/_interopDefault(L);var P__default=/*#__PURE__*/_interopDefault(P);var m__default=/*#__PURE__*/_interopDefault(m);var k__default=/*#__PURE__*/_interopDefault(k);var E__default=/*#__PURE__*/_interopDefault(E);/* ZuzJS Process Manager */
|
|
2
|
-
var d=class extends v__default.default{map=new Map;set(t,e){this.map.set(t,e),this.emit("change",t,e);}get(t){return this.map.get(t)}has(t){return this.map.has(t)}delete(t){this.map.delete(t),this.emit("delete",t);}all(){return new Map(this.map)}onchange(t){return this.on("change",t)}offchange(t){return this.off("change",t)}},h=new d;function F(n,t){return new Promise(e=>{let o=(n.startsWith("https")?C__default.default:y__default.default).get(n,{timeout:t},s=>{e((s.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(s=>{let a=W__default.default.createConnection({host:e,port:o},()=>{a.destroy(),s(true);});a.setTimeout(t),a.on("timeout",()=>{a.destroy(),s(false);}),a.on("error",()=>s(false));})}function x(n,t){return new Promise(e=>{let r=setTimeout(()=>e(false),t);child_process.exec(n,o=>{clearTimeout(r),e(!o);});})}async function b(n){let t=(n.timeoutSeconds??5)*1e3;switch(n.type){case "http":return F(n.target,t);case "tcp":return $(n.target,t);case "exec":return x(n.target,t);default:return false}}var p=5e3,A=16e3,w=1e3,D=5e3;async function N(n){return new Promise(t=>{W__default.default.createServer().once("error",()=>t(false)).once("listening",function(){this.close(()=>t(true));}).listen(n);})}async function K(n){if(await N(n))return;let t=P__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 u(n,t){let e=n.process?.pid??n.pid;if(e)return new Promise(r=>{let o=false,s=()=>{o||(o=true,clearTimeout(a),r());};n.once?.("exit",s),n.once?.("exit",s);try{process.kill(e,"SIGTERM");}catch{return s()}let a=setTimeout(()=>{try{process.kill(e,"SIGKILL"),setTimeout(s,100);}catch{s();}},t),c=setInterval(()=>{try{process.kill(e,0);}catch{clearInterval(c),s();}},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"){chunkI6PNOIS2_cjs.d.warn(this.name,"Already running \u2013 ignoring start()");return}this.patch({status:"starting",backoffTime:w,restartCount:0,probeFailures:0}),this.clearTimers(),await this.spawnAll(),this.cfg.devMode&&this.watchFiles();}async stop(){let t=this.mp();if(t.status!=="stopping"){this.patch({status:"stopping",isRestarting:false}),chunkI6PNOIS2_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=>u(e,this.cfg.killTimeout??p))),new Promise((e,r)=>setTimeout(()=>r(new Error("Termination timeout")),1e4))]);}catch(e){chunkI6PNOIS2_cjs.d.error(this.name,`Stop timed out, forcing state reset: ${e.message||"UNKNOWN"}`);}this.patch({children:[],status:"stopped",startTime:null}),this.stopWatcher(),chunkI6PNOIS2_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)u(e,this.cfg.killTimeout??p);this.stopWatcher(),this.patch({children:[],status:"stopped",startTime:null}),chunkI6PNOIS2_cjs.d.info(this.name,"Stopped.");}async restart(){let t=this.mp();t.isRestarting||(chunkI6PNOIS2_cjs.d.info(this.name,"Restarting..."),this.patch({isRestarting:true,status:"stopping"}),this.clearTimers(),this.stopProbe(),await Promise.all(t.children.map(e=>u(e,this.cfg.killTimeout??p))),this.patch({isRestarting:false,children:[]}));}async _restart(){chunkI6PNOIS2_cjs.d.info(this.name,"Restarting...");let t=this.mp();this.patch({isRestarting:true}),this.clearTimers(),this.stopProbe();for(let e of t.children)u(e,this.cfg.killTimeout??p);}async getStats(){let t=this.mp(),e=t.children[0]?.pid??null,r=null,o=null,s=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:s,mode:this.cfg.mode??"fork",instances:t.children.length}}async spawnAll(){if(!L__default.default.existsSync(this.cfg.scriptPath)){chunkI6PNOIS2_cjs.d.error(this.name,`Script not found: ${this.cfg.scriptPath}. Waiting for build...`),this.patch({status:"errored"});return}this.cfg.port&&await K(this.cfg.port);let t=this.cfg.mode??"fork",e=t==="cluster"?this.cfg.instances??P__default.default.cpus().length:1,r=[];for(let s=0;s<e;s++){let a=this.forkChild();a&&r.push(a);}if(r.length===0){chunkI6PNOIS2_cjs.d.error(this.name,"Failed to spawn any instances."),this.patch({status:"stopped"});return}this.patch({children:r,startTime:Date.now(),status:"running"}),chunkI6PNOIS2_cjs.d.success(this.name,`Started ${r.length} instance(s) [${t}]`);let o=setTimeout(()=>{this.mp().status==="running"&&(this.patch({backoffTime:w,restartCount:0}),chunkI6PNOIS2_cjs.d.success(this.name,"Process is stable."));},D);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:m__default.default.dirname(m__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",s=>{chunkI6PNOIS2_cjs.d.error(this.name,"Spawn error:",s);}),r.on("exit",(s,a)=>{let c=Date.now()-o;this.onChildExit(r,s,a,c);}),r}catch(t){return chunkI6PNOIS2_cjs.d.error(this.name,"Failed to fork child:",t),null}}onChildExit(t,e,r,o){let s=this.mp(),a=s.children.filter(c=>c!==t);if(this.patch({children:a}),s.status!=="stopping"){if(chunkI6PNOIS2_cjs.d.warn(this.name,`Process exited (code=${e}, signal=${r}, uptime=${o}ms)`),s.isRestarting){a.length===0&&(this.patch({isRestarting:false}),this.spawnAll());return}if(e!==0&&e!==null){if(this.patch({status:"crashed"}),o<1500){chunkI6PNOIS2_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??A;chunkI6PNOIS2_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,s=setInterval(async()=>{let a=this.mp();if(a.status!=="running")return;if(await b(t)){a.probeFailures>0&&this.patch({probeFailures:0});return}let l=a.probeFailures+1;this.patch({probeFailures:l}),chunkI6PNOIS2_cjs.d.warn(this.name,`Liveness probe failed (${l}/${r})`),l>=r&&(chunkI6PNOIS2_cjs.d.error(this.name,"Liveness probe threshold exceeded \u2013 restarting."),this.patch({probeFailures:0}),await this.restart());},e);this.patch({probeTimer:s});}stopProbe(){let{probeTimer:t}=this.mp();t&&(clearInterval(t),this.patch({probeTimer:null,probeFailures:0}));}watchFiles(){this.stopWatcher();let t=m__default.default.dirname(this.cfg.scriptPath);this.watcher=M__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")&&(chunkI6PNOIS2_cjs.d.info(this.name,`File ${e}: ${m__default.default.basename(r)} \u2013 restarting`),this.restart());}),this.watcher.on("error",e=>chunkI6PNOIS2_cjs.d.error(this.name,"Watcher error:",e)),this.watcher.on("ready",()=>chunkI6PNOIS2_cjs.d.info(this.name,`Watching ${t}`));}stopWatcher(){this.watcher&&(this.watcher.close(),this.watcher=null);}initStore(){h.set(this.name,{config:this.cfg,children:[],status:"stopped",startTime:null,restartCount:0,backoffTime:w,restartTimer:null,stabilityTimer:null,probeTimer:null,probeFailures:0,isRestarting:false});}mp(){return h.get(this.name)}patch(t){h.set(this.name,{...this.mp(),...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__default.default(e),r.on("open",()=>chunkI6PNOIS2_cjs.d.debug(this.name,"Connected to log collector")),r.on("error",s=>chunkI6PNOIS2_cjs.d.error(this.name,"Log Collector WS Error",s.message)));let o=s=>{let a=s.toString();this.cfg.devMode&&process.stdout.write(`[${this.name}] ${a}`),r&&r.readyState===k__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 T=class{workers=new Map;async start(t){if(this.workers.has(t.name)){chunkI6PNOIS2_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){await this.require(t).stop();}async restart(t){await this.require(t).restart();}async delete(t){await this.require(t).stop(),this.workers.delete(t),h.delete(t),chunkI6PNOIS2_cjs.d.info("PM",`Deleted worker "${t}"`);}async getStats(t){return t?[await this.require(t).getStats()]:await Promise.all([...this.workers.values()].map(r=>r.getStats()))}list(){return [...this.workers.keys()]}async stopAll(){chunkI6PNOIS2_cjs.d.info("PM","Stopping all workers..."),await Promise.all([...this.workers.values()].map(t=>t.stop())),chunkI6PNOIS2_cjs.d.info("PM","All workers stopped.");}getWorker(t){let e=this.workers.get(t);return e||null}require(t){let e=this.workers.get(t);if(!e)throw new Error(`Worker "${t}" not found`);return e}};exports.a=h;exports.b=b;exports.c=f;exports.d=T;
|
package/dist/chunk-UVQRIGIE.cjs
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkI6PNOIS2_cjs=require('./chunk-I6PNOIS2.cjs'),child_process=require('child_process'),p=require('fs'),h=require('net'),y=require('os'),P=require('path');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var p__default=/*#__PURE__*/_interopDefault(p);var h__default=/*#__PURE__*/_interopDefault(h);var y__default=/*#__PURE__*/_interopDefault(y);var P__default=/*#__PURE__*/_interopDefault(P);/* ZuzJS Process Manager */
|
|
2
|
-
function i(d,n="zuz-pm"){return new Promise((t,r)=>{let e=h__default.default.createConnection(chunkI6PNOIS2_cjs.e(n)),o="";e.on("connect",()=>{e.write(JSON.stringify(d)+`
|
|
3
|
-
`);}),e.on("data",s=>{o+=s.toString();let m=o.split(`
|
|
4
|
-
`);o=m.pop()??"";for(let l of m)if(l.trim())try{let a=JSON.parse(l);e.destroy(),a.ok?t(a.data):r(new Error(a.error));}catch(a){e.destroy(),r(a);}}),e.on("error",s=>r(s)),e.setTimeout(1e4,()=>{e.destroy(),r(new Error("IPC timeout"));});})}var u=class{daemonScript;namespace;constructor(n){this.namespace=n?.namespace??"zuz-pm",this.daemonScript=n?.daemonScript??P__default.default.join(__dirname,"daemon.js");}async isDaemonRunning(){try{return chunkI6PNOIS2_cjs.d.info("[ZPM]","Daemon is Running :?"),await i({cmd:"ping"},this.namespace),!0}catch{return chunkI6PNOIS2_cjs.d.info("[ZPM]","Daemon is not running."),false}}async ensureDaemon(){if(await this.isDaemonRunning())return;chunkI6PNOIS2_cjs.d.info("Starting ZPM daemon...");let t=process.env.NODE_ENV!=="production";child_process.spawn(process.execPath,[this.daemonScript],{detached:true,stdio:t?"inherit":"ignore"}).unref(),await this.waitForDaemon(8e3);}async killDaemon(){let n=P__default.default.join(y__default.default.tmpdir(),"zuz-pm.pid");if(!p__default.default.existsSync(n))throw new Error("Daemon PID file not found \u2013 is the daemon running?");let t=Number(p__default.default.readFileSync(n,"utf8").trim());try{process.kill(t,"SIGTERM"),console.log(`[ZPM] Sent SIGTERM to daemon (PID ${t})`);}catch(r){throw new Error(`Failed to kill daemon: ${r.message}`)}finally{p__default.default.unlinkSync(n);}}async start(n){return i({cmd:"start",name:n.name,config:n},this.namespace)}async stop(n){return i({cmd:"stop",name:n},this.namespace)}async restart(n){return i({cmd:"restart",name:n},this.namespace)}async delete(n){return i({cmd:"delete",name:n},this.namespace)}async stats(n){return i({cmd:"stats",name:n},this.namespace)}async list(){return i({cmd:"list"},this.namespace)}waitForDaemon(n){let t=Date.now(),r=200;return new Promise((e,o)=>{let s=()=>{this.isDaemonRunning().then(m=>{if(m)return e();if(Date.now()-t>n)return o(new Error("Daemon did not start in time"));setTimeout(s,r);});};setTimeout(s,r);})}},C=new u;exports.a=u;exports.b=C;
|