sync-dev-server
Version:
Starts a server before your tests and stops on completion. Inspired by jest-puppeteer's subpackage jest-dev-server. Setup and teardown operations are fully synchronous.
25 lines (20 loc) • 2.71 kB
JavaScript
import{sync as e}from"command-exists";import{execSync as t,spawn as n}from"child_process";import{Transform as r}from"stream";import i from"dns-lookup-sync";import a from"kill-sync";import o from"node-netstat";import s from"slync";const c=e=>{try{if(process.platform===`darwin`||process.platform===`linux`){let n=t(`lsof -ti:${e}`).toString().split(`
`).filter(Boolean);return n.length?Number(n[0]):null}else if(process.platform===`win32`){let n=t(`for /f "tokens=5" %a in ('netstat -ano ^| findstr :${e}') do @echo %a`).toString().split(`
`).filter(Boolean);return n.length?Number(n[0]):null}return null}catch{return null}},l=(e,t)=>{let n,r=t===`localhost`?i(t).address:t,a={port:e,...r?{address:r}:{}};return o({sync:!0,filter:{local:a},limit:1},e=>{n=e}),n},u=(e,t)=>{let n=e.isServerReadyFn??(()=>l(e.port,e.host));for(let r=0;r<e.timeout;r+=200){if(!!n()===t)return!0;s(200)}return!1},d=(e,t)=>{if(e===void 0)throw Error(`The given server child process has undefined pid!`);try{a(e,t,!0)}catch(n){console.error(`\
WARNING - failed to kill server with pid ${e} using signal ${t??`SIGTERM`}.
ERROR STACK:
${n.stack}
`)}},f=(e,t)=>{if(d(t,e.signal),!u(e,!1))throw Error(`
>>> Failed to kill server.
>>> Options:
${JSON.stringify(e,null,2)}
`)},p=(e,t,n)=>{if(n){if(e.usedPortAction===`error`)throw Error(`Port ${e.port} is already taken.`);if(e.usedPortAction===`kill`){let n=t?.pid??c(e.port);if(!n)throw Error(`Failed to kill existing server - missing pid`);f(e,n)}}},m=(e,t,i)=>{let a=n(e,t,{env:Object.assign(process.env,i.env)});if(!u(i,!0))throw d(a.pid,i.signal),Error(`
Failed to start server after ${i.timeout} milliseconds.
Please double check that you've specified the correct options, as
the default options may not meet your needs (e.g. opts.port):
${JSON.stringify(i,null,2)}
`);let o=new r({transform(e,t,n){this.push(`[sync-dev-server] ${e.toString()}`),n()}});return i.debug?a.stdout.pipe(o).pipe(process.stdout):a.stdout.on(`data`,()=>{}),a},h={port:5e3,host:``,timeout:1e4,signal:`SIGTERM`,debug:!0,usedPortAction:`error`,env:{},isServerReadyFn:null},g=(e,t=`SIGTERM`)=>{e!==null&&d(e.pid,t)};function _(t,n){let r={...h,...n},i=e(`netstat`);!i&&!r.isServerReadyFn&&console.warn(`WARNING: "netstat" command not found in Path.
Please install net-tools: https://net-tools.sourceforge.io/, or otherwise provide
opts.isServerReadyFn
`);let a=t.split(` `),o=a.shift();if(!o)throw Error(`Command is empty: ${t}`);let s=i?l(r.port,r.host):void 0,c=r.isServerReadyFn?.()??s!==void 0;return c&&r.usedPortAction===`ignore`?null:(p(r,s,c),m(o,a,r))}var v={startServer:_,stopServer:g};export{v as default,_ as startServer,g as stopServer};
//# sourceMappingURL=index.mjs.map