@coreframe/dev-supervisor 0.1.6 → 0.1.8

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/index.d.ts CHANGED
@@ -4,7 +4,7 @@ import { CoreframeConfig } from "@coreframe/config";
4
4
 
5
5
  //#region src/index.d.ts
6
6
  declare const protocolVersion = 1;
7
- type DevSupervisorFlutterPlatform = "android" | "ios" | "macos";
7
+ type DevSupervisorFlutterPlatform = "android" | "ios" | "linux" | "macos" | "windows";
8
8
  type DevSupervisorViteResource = "vite:web" | `vite:flutter:${DevSupervisorFlutterPlatform}`;
9
9
  type DevSupervisorResource = "postgres" | "sqlite" | DevSupervisorViteResource;
10
10
  type DevSupervisorStream = "stdout" | "stderr";
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{spawn as e}from"node:child_process";import{createHash as t,randomUUID as n}from"node:crypto";import{appendFile as r,mkdir as i,readFile as a,rename as o,rm as s,stat as c,unlink as l,writeFile as u}from"node:fs/promises";import{createConnection as d,createServer as f}from"node:net";import{tmpdir as p}from"node:os";import m from"node:path";import h from"node:process";import{Writable as g}from"node:stream";import _ from"@alloc/tree-kill";const v=`.coreframe/dev-supervisor`,y=`supervisor.json`,b=`logs`,x=1*1024*1024,S=4*1024*1024,C=45e3,w=RegExp(`\x1B\\[[0-?]*[ -/]*[@-~]`,`g`),ee=/^[\t ]*➜[\t ]+\S+:[\t ]+.+(?:\r?\n|$)/mu;async function te({cwd:e=h.cwd(),env:t=h.env,supervisorEntry:n}={}){let r=await T({cwd:e,env:t});if(r)return r;let i=await F(e),a=await re(e);if(!a)return i=await P(e),N({cwd:e,env:t,state:i});try{if(i=await F(e),i&&i.cwd===m.resolve(e)&&Z(i.pid))return await N({cwd:e,env:t,state:i});if(i&&await L(e,i),!n)throw Error(`A development supervisor process entry is required to start the supervisor.`);return await ne({cwd:e,env:t,entry:n}),i=await P(e),N({cwd:e,env:t,state:i})}finally{await a()}}async function T({cwd:e=h.cwd(),env:t=h.env}={}){let n=await F(e);if(!(!n||n.cwd!==m.resolve(e)||!Z(n.pid)))try{return await N({cwd:e,env:t,state:n})}catch{await L(e,n);return}}async function E({cwd:e=h.cwd(),resource:t}={}){let n=await F(e);if(!n||n.cwd!==m.resolve(e)||!Z(n.pid))return await L(e,n),!1;let r=await N({cwd:e,env:h.env,state:n});try{if(t)return await r.stopVite(t);await r.shutdown()}finally{r.close()}return await ie(e,n.supervisorId),!0}var D=class e{state;socket;pending=new Map;listeners=new Set;closeListeners=new Set;leases=new Set;decoder=new j;closed=!1;renewalTimer;constructor(e){this.state=e.state,this.socket=e.socket,this.socket.on(`data`,e=>{for(let t of this.decoder.push(e))this.handleFrame(t)}),this.socket.on(`close`,()=>this.handleClose(Error(`Development supervisor disconnected.`))),this.socket.on(`error`,e=>this.handleClose(e)),this.renewalTimer=setInterval(()=>void this.renewLeases(),C/3),this.renewalTimer.unref()}static async create(t){let n=new e(t);return await n.request(`hello`,{protocol:1,token:t.state.token}),n}async acquirePostgres({config:e,env:t}={}){let n=await this.request(`acquire`,{resource:`postgres`,config:e,env:Y(t??h.env)});return this.leases.add(n.leaseId),n}async acquireSqlite({config:e,env:t}={}){let n=await this.request(`acquire`,{resource:`sqlite`,config:e,env:Y(t??h.env)});return this.leases.add(n.leaseId),n}async acquireVite(e,t=!1){let n=await this.request(`acquire`,{resource:e.resource,spec:e,fresh:t});return this.leases.add(n.leaseId),n}async release(e){this.leases.delete(e),await this.request(`release`,{leaseId:e})}async subscribe(e){return this.request(`subscribe`,{resources:e})}async status(){return this.request(`status`)}async shutdown(){await this.request(`shutdown`)}async stopVite(e){return this.request(`stop`,{resource:e})}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}waitForServiceExit(e){return this.closed?Promise.resolve():new Promise(t=>{let n=()=>{r(),this.closeListeners.delete(n),t()},r=this.onEvent(t=>{!(`resource`in t)||t.resource!==e||t.event!==`service`||(t.state===`failed`||t.state===`stopped`)&&n()});this.closeListeners.add(n)})}close(){this.closed||(this.socket.end(),this.handleClose(Error(`Development supervisor client closed.`)))}request(e,t){if(this.closed)return Promise.reject(Error(`Development supervisor client is closed.`));let r=n();return new Promise((n,i)=>{this.pending.set(r,{resolve:n,reject:i}),this.socket.write(M({id:r,method:e,params:t,type:`request`}))})}async renewLeases(){for(let e of this.leases)await this.request(`renew`,{leaseId:e}).catch(()=>{this.leases.delete(e)})}handleFrame(e){if(e.type===`event`){for(let t of this.listeners)t(e.event);return}if(e.type!==`response`)return;let t=this.pending.get(e.id);t&&(this.pending.delete(e.id),e.ok?t.resolve(e.result):t.reject(ae(e.error)))}handleClose(e){if(!this.closed){this.closed=!0,clearInterval(this.renewalTimer);for(let t of this.pending.values())t.reject(e);this.pending.clear();for(let e of this.closeListeners)e();this.closeListeners.clear()}}};async function O({cwd:e=h.cwd(),startPostgres:t,startSqlite:n}={}){if(!t)throw Error(`A PostgreSQL starter is required to run the development supervisor.`);let r=m.resolve(e,v);await i(r,{recursive:!0,mode:448}),await i(m.join(r,b),{recursive:!0,mode:448});let a=await F(e);if(a&&a.pid!==h.pid&&Z(a.pid))throw Error(`A Coreframe development supervisor is already running for this directory.`);let o=R(e);h.platform!==`win32`&&await l(o).catch(()=>void 0);let s=new k({cwd:m.resolve(e),endpoint:o,root:r,startPostgres:t,startSqlite:n});await s.listen();let c=()=>{s.shutdown()};h.once(`SIGINT`,c),h.once(`SIGTERM`,c);try{await s.waitForShutdown()}finally{h.off(`SIGINT`,c),h.off(`SIGTERM`,c)}}var k=class{clients=new Set;leases=new Map;resourceOperations=new Map;resources=new Map;logEntries=[];server;root;state;startPostgres;startSqlite;postgres;sqlite;sequence=0;shutdownPromise;shutdownRequested=!1;idleTimer;leaseTimer;postgresStopTimer;sqliteStopTimer;constructor({cwd:e,endpoint:t,root:r,startPostgres:i,startSqlite:a}){this.root=r,this.startPostgres=i,this.startSqlite=a,this.state={cwd:e,endpoint:t,pid:h.pid,protocol:1,supervisorId:n(),token:n()},this.server=f(e=>this.accept(e)),this.leaseTimer=setInterval(()=>this.expireLeases(),5e3),this.leaseTimer.unref()}async listen(){await new Promise((e,t)=>{this.server.once(`error`,t),this.server.listen(this.state.endpoint,()=>{this.server.off(`error`,t),e()})}),await I(this.state,this.root)}waitForShutdown(){return new Promise(e=>{this.shutdownPromise?this.shutdownPromise.then(()=>e()):this.resolveShutdown=e})}async shutdown({stopPostgres:e=!0,stopSqlite:t=!0}={}){return this.shutdownPromise||=(async()=>{this.shutdownRequested=!0,this.idleTimer&&clearTimeout(this.idleTimer),clearInterval(this.leaseTimer),await Promise.all(this.resourceOperations.values()),this.leases.clear();for(let e of this.resources.keys())await this.stopVite(e);e?await this.stopPostgres():(this.cancelPostgresStop(),this.postgres=void 0),t?await this.stopSqlite():(this.cancelSqliteStop(),this.sqlite=void 0);for(let e of this.clients)e.close();await new Promise(e=>this.server.close(()=>e())),await l(this.state.endpoint).catch(()=>void 0),await l(m.join(this.root,y)).catch(()=>void 0),this.resolveShutdown?.()})(),this.shutdownPromise}resolveShutdown;accept(e){let t=new A(this,e);this.clients.add(t),e.once(`close`,()=>{this.clients.delete(t);for(let e of this.leases.values())e.connection===t&&this.releaseLease(e.id);this.maybeScheduleIdleShutdown()})}async handleRequest(e,t){try{let n=await this.dispatch(e,t.method,t.params??{});e.respond(t.id,{ok:!0,result:n})}catch(n){e.respond(t.id,{ok:!1,error:$(n)})}}publish(e){let t={...e,sequence:++this.sequence,timestamp:new Date().toISOString()};if(t.event===`log`&&t.resource!==`postgres`&&t.resource!==`sqlite`)for(this.logEntries.push(t);this.logEntries.length>2e3;)this.logEntries.shift();for(let e of this.clients)e.publish(t);return t}async addSubscription(e,t){e.subscribe(t);let r=this.logEntries.filter(e=>(e.resource===`postgres`||e.resource===`sqlite`)&&t.includes(e.resource));for(let t of r)e.publish(t);return e.publish({event:`replay-complete`,sequence:this.sequence,timestamp:new Date().toISOString()}),{subscriptionId:n()}}async dispatch(e,t,n){if(this.shutdownRequested&&t!==`shutdown`)throw Q(`SUPERVISOR_STOPPING`,`Development supervisor is stopping.`,!0);switch(t){case`hello`:return this.hello(e,n);case`status`:return this.status();case`subscribe`:return this.addSubscription(e,z(n.resources));case`acquire`:return this.withResourceOperation(B(n.resource),()=>this.acquire(e,n));case`release`:await this.releaseLease(q(n.leaseId));return;case`stop`:{let e=V(n.resource);return this.withResourceOperation(e,async()=>{let t=await this.stopVite(e,!0);return this.maybeScheduleIdleShutdown(),t})}case`renew`:return this.renewLease(q(n.leaseId));case`shutdown`:this.shutdownRequested=!0,setImmediate(()=>void this.shutdown({stopPostgres:!1}));return;default:throw Q(`INVALID_REQUEST`,`Unknown supervisor method: ${t}.`,!1)}}async withResourceOperation(e,t){let n=this.resourceOperations.get(e),r,i=new Promise(e=>{r=e});this.resourceOperations.set(e,i),n&&await n;try{return await t()}finally{r(),this.resourceOperations.get(e)===i&&this.resourceOperations.delete(e)}}hello(e,t){if(t.protocol!==1||t.token!==this.state.token)throw e.close(),Q(`AUTH_FAILED`,`Invalid supervisor protocol or token.`,!1);return e.authenticated=!0,{cwd:this.state.cwd,protocol:1,supervisorId:this.state.supervisorId}}status(){return{postgres:this.postgres?{leases:this.postgres.leases.size,state:`running`}:void 0,sqlite:this.sqlite?{leases:this.sqlite.leases.size,state:`running`}:void 0,resources:[...this.resources.entries()].map(([e,t])=>({endpoint:t.spec.endpoint,leases:t.leases.size,resource:e,state:`running`}))}}async acquire(e,t){let n=B(t.resource);if(n===`postgres`)return this.acquirePostgres(e,G(t));if(n===`sqlite`)return this.acquireSqlite(e,G(t));let r=H(t.spec);if(r.resource!==n)throw Q(`INVALID_REQUEST`,`The Vite resource does not match its specification.`,!1);let i=this.resources.get(n);if(i&&q(t.fresh)!==`true`){if(i.spec.configFingerprint!==r.configFingerprint||r.endpoint.port!==void 0&&i.spec.endpoint.port!==r.endpoint.port)throw Q(`CONFIG_MISMATCH`,`A ${n} Vite server already exists with different settings.`,!1,{existing:{configFingerprint:i.spec.configFingerprint,endpoint:i.spec.endpoint},requested:{configFingerprint:r.configFingerprint,endpoint:r.endpoint}});let t=this.createLease(e,n);i.leases.add(t.id);for(let t of i.startupLinks)e.publish(t);return{endpoint:i.spec.endpoint,leaseId:t.id,state:`reused`}}if(i){if(i.leases.size>0)throw Q(`RESOURCE_BUSY`,`Cannot replace active ${n} development.`,!0);await this.stopVite(n)}if(r.endpoint.port===void 0)throw Q(`INVALID_REQUEST`,`A ${n} Vite server requires a port when it is started.`,!1);let a={...r,endpoint:{...r.endpoint,port:r.endpoint.port}},o={children:[],leases:new Set,startupLinks:[],spec:a};this.resources.set(n,o),this.publish({event:`service`,resource:n,state:`starting`,endpoint:a.endpoint});try{for(let e of r.processes){let t=this.spawnProcess(n,e);o.children.push(t)}let t=this.createLease(e,n);return o.leases.add(t.id),this.publish({event:`service`,resource:n,state:`running`,endpoint:a.endpoint,pid:o.children[0]?.pid??void 0}),{endpoint:a.endpoint,leaseId:t.id,state:`started`}}catch(e){throw await this.stopVite(n),e}}async acquirePostgres(e,t){let n=this.postgres===void 0;if(this.postgres)this.cancelPostgresStop();else{let e=await this.createLogStream(`postgres`),n=J(t.env),r=await this.startPostgres({config:t.config,cwd:this.state.cwd,env:Y(n),failIfRunning:!1,postgresOutput:e});this.postgres={env:X(n,r.env),leases:new Set,sidecar:r},this.publish({event:`service`,resource:`postgres`,state:`running`})}let r=this.createLease(e,`postgres`);return this.postgres.leases.add(r.id),{env:Y(this.postgres.env),leaseId:r.id,state:n?`started`:`reused`}}async acquireSqlite(e,t){if(!this.startSqlite)throw Error(`A SQLite starter is required to run the development supervisor.`);let n=this.sqlite===void 0;if(this.sqlite)this.cancelSqliteStop();else{let e=await this.createLogStream(`sqlite`),n=J(t.env),r=await this.startSqlite({config:t.config,cwd:this.state.cwd,env:Y(n),tursoOutput:e});this.sqlite={env:X(n,r.env),leases:new Set,sidecar:r},this.publish({event:`service`,resource:`sqlite`,state:`running`})}let r=this.createLease(e,`sqlite`);return this.sqlite.leases.add(r.id),{env:Y(this.sqlite.env),leaseId:r.id,state:n?`started`:`reused`}}createLease(e,t){let r={connection:e,expiresAt:Date.now()+C,id:n(),resource:t};return this.leases.set(r.id,r),r}renewLease(e){let t=this.leases.get(e);if(!t)throw Q(`LEASE_EXPIRED`,`The supervisor lease is no longer active.`,!0);return t.expiresAt=Date.now()+C,{expiresAt:t.expiresAt}}expireLeases(){for(let e of this.leases.values())e.expiresAt<=Date.now()&&this.releaseLease(e.id)}async releaseLease(e){let t=this.leases.get(e);if(t){if(this.leases.delete(e),t.resource===`postgres`)this.postgres?.leases.delete(e),this.postgres?.leases.size===0&&this.schedulePostgresStop();else if(t.resource===`sqlite`)this.sqlite?.leases.delete(e),this.sqlite?.leases.size===0&&this.scheduleSqliteStop();else{let n=this.resources.get(t.resource);n?.leases.delete(e),n?.leases.size===0&&await this.stopVite(t.resource)}this.maybeScheduleIdleShutdown()}}spawnProcess(t,n){let r=e(n.command,n.args,{cwd:n.cwd,env:Y(n.env),stdio:[`ignore`,`pipe`,`pipe`]}),i=(e,n)=>{let r=this.publish({event:`log`,resource:t,stream:e,data:String(n)});if(r.event!==`log`)return;let i=K(r.data);i&&this.resources.get(t)?.startupLinks.push({...r,data:i})};return r.stdout.on(`data`,e=>i(`stdout`,e)),r.stderr.on(`data`,e=>i(`stderr`,e)),r.on(`error`,e=>{this.publish({event:`service`,resource:t,state:`failed`,error:e.message})}),r.on(`exit`,(e,n)=>{this.resources.has(t)&&(this.publish({event:`service`,resource:t,state:e===0||n?`stopped`:`failed`,error:e&&!n?`Process exited with code ${e}.`:void 0}),this.stopVite(t))}),r}async stopVite(e,t=!1){let n=this.resources.get(e);if(!n)return!1;if(this.resources.delete(e),t){for(let e of n.leases)this.leases.delete(e);n.leases.clear()}return await Promise.all(n.children.map(e=>_(e,`SIGTERM`))),await Promise.all(n.children.map(e=>new Promise(t=>{if(e.exitCode!==null){t();return}e.once(`exit`,()=>t()),setTimeout(()=>{_(e,`SIGKILL`).then(t,t)},5e3).unref()}))),this.publish({event:`service`,resource:e,state:`stopped`}),!0}async stopPostgres(){if(this.cancelPostgresStop(),!this.postgres)return;let e=this.postgres;this.postgres=void 0,await e.sidecar[Symbol.asyncDispose](),this.publish({event:`service`,resource:`postgres`,state:`stopped`})}schedulePostgresStop(){this.postgresStopTimer||(this.postgresStopTimer=setTimeout(()=>{this.postgresStopTimer=void 0,this.withResourceOperation(`postgres`,async()=>{this.postgres?.leases.size===0&&await this.stopPostgres()}).then(()=>this.maybeScheduleIdleShutdown(),()=>this.maybeScheduleIdleShutdown())},3e5),this.postgresStopTimer.unref())}async stopSqlite(){if(this.cancelSqliteStop(),!this.sqlite)return;let e=this.sqlite;this.sqlite=void 0,await e.sidecar[Symbol.asyncDispose](),this.publish({event:`service`,resource:`sqlite`,state:`stopped`})}scheduleSqliteStop(){this.sqliteStopTimer||(this.sqliteStopTimer=setTimeout(()=>{this.sqliteStopTimer=void 0,this.withResourceOperation(`sqlite`,async()=>{this.sqlite?.leases.size===0&&await this.stopSqlite()}).then(()=>this.maybeScheduleIdleShutdown(),()=>this.maybeScheduleIdleShutdown())},3e5),this.sqliteStopTimer.unref())}cancelPostgresStop(){this.postgresStopTimer&&=(clearTimeout(this.postgresStopTimer),void 0)}cancelSqliteStop(){this.sqliteStopTimer&&=(clearTimeout(this.sqliteStopTimer),void 0)}async createLogStream(e){let t=m.join(this.root,b,`${e.replaceAll(`:`,`-`)}.log`);await i(m.dirname(t),{recursive:!0,mode:448}),await u(t,``);let n=0;return new g({write:(i,a,o)=>{let s=String(i),c=Buffer.from(s),l=c.subarray(Math.max(0,c.length-x)),d=n+l.length>x;(d?u(t,l):r(t,l)).then(()=>{n=d?l.length:n+l.length,o()},o),this.publish({event:`log`,resource:e,stream:`stdout`,data:s})}})}maybeScheduleIdleShutdown(){this.leases.size>0||this.resources.size>0||this.postgres||this.sqlite||this.idleTimer||(this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.leases.size===0&&this.resources.size===0&&!this.postgres&&!this.sqlite&&this.shutdown()},3e4),this.idleTimer.unref())}},A=class{authenticated=!1;decoder=new j;subscriptions=new Set;eventQueue=[];queuedEventBytes=0;writingEvent=!1;droppedEventRange;server;socket;constructor(e,t){this.server=e,this.socket=t,t.on(`error`,()=>this.close()),t.on(`data`,t=>{try{for(let n of this.decoder.push(t))n.type===`request`&&(!this.authenticated&&n.method!==`hello`?this.respond(n.id,{ok:!1,error:$(Q(`AUTH_FAILED`,`Send hello first.`,!1))}):e.handleRequest(this,n))}catch{this.close()}})}respond(e,t){this.socket.write(M({...t,id:e,type:`response`}))}publish(e){let t=[...this.subscriptions];t.length!==0&&(e.event!==`replay-complete`&&e.event!==`gap`&&(e.resource===void 0||!t.some(t=>t.has(e.resource)))||this.enqueueEvent(e))}subscribe(e){this.subscriptions.add(new Set(e))}close(){this.eventQueue.length=0,this.queuedEventBytes=0,this.socket.destroy()}enqueueEvent(e){let t=M({event:e,type:`event`});if(t.length>S){this.noteDropped(e);return}for(;;){let n=this.droppedEventRange?{event:{event:`gap`,from:this.droppedEventRange.from,reason:`buffer-overflow`,to:this.droppedEventRange.to,sequence:e.sequence,timestamp:new Date().toISOString()},frame:Buffer.alloc(0)}:void 0;n&&(n.frame=M({event:n.event,type:`event`}));let r=t.length+(n?.frame.length??0),i=!1;for(;this.queuedEventBytes+r>S;){let e=this.eventQueue.shift();if(!e)break;i=!0,this.queuedEventBytes-=e.frame.length,this.noteDropped(e.event)}if(!i){if(this.queuedEventBytes+r<=S){n&&(this.eventQueue.push(n),this.queuedEventBytes+=n.frame.length,this.droppedEventRange=void 0),this.eventQueue.push({event:e,frame:t}),this.queuedEventBytes+=t.length,this.pumpEvents();return}if(this.eventQueue.length===0){this.noteDropped(e);return}}}}noteDropped(e){let t=e.sequence;if(!this.droppedEventRange){this.droppedEventRange={from:t,to:t};return}this.droppedEventRange.from=Math.min(this.droppedEventRange.from,t),this.droppedEventRange.to=Math.max(this.droppedEventRange.to,t)}pumpEvents(){if(this.writingEvent||this.eventQueue.length===0||this.socket.destroyed)return;let e=this.eventQueue.shift();this.queuedEventBytes-=e.frame.length,this.writingEvent=!0,this.socket.write(e.frame,()=>{this.writingEvent=!1,this.pumpEvents()})}},j=class{buffer=Buffer.alloc(0);push(e){this.buffer=Buffer.concat([this.buffer,Buffer.from(e)]);let t=[];for(;this.buffer.length>=4;){let e=this.buffer.readUInt32BE(0);if(e>16777216)throw Error(`Development supervisor protocol frame is too large.`);if(this.buffer.length<e+4)break;let n=this.buffer.subarray(4,e+4).toString(`utf8`);this.buffer=this.buffer.subarray(e+4),t.push(JSON.parse(n))}return t}};function M(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.allocUnsafe(t.length+4);return n.writeUInt32BE(t.length,0),t.copy(n,4),n}async function N(e){let t=await new Promise((t,n)=>{let r=d(e.state.endpoint);r.once(`connect`,()=>t(r)),r.once(`error`,n)});return D.create({...e,socket:t})}async function ne({cwd:t,env:n,entry:r}){e(h.execPath,[r,`--cwd`,t],{cwd:t,detached:!0,env:{...n,COREFRAME_DEV_SUPERVISOR:`1`},stdio:`ignore`}).unref()}async function re(e){let t=m.join(e,v),n=m.join(t,`start.lock`),r=Date.now()+1e4;for(await i(t,{recursive:!0,mode:448});Date.now()<r;)try{return await u(n,`${h.pid}\n`,{flag:`wx`,mode:384}),async()=>{await l(n).catch(()=>void 0)}}catch(t){if(!(t instanceof Error&&t.code===`EEXIST`))throw t;let r=await F(e);if(r&&Z(r.pid))return;try{let e=await c(n);if(Date.now()-e.mtimeMs>1e4){await l(n).catch(()=>void 0);continue}}catch{continue}await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor startup is already in progress.`)}async function P(e){let t=Date.now()+1e4;for(;Date.now()<t;){let t=await F(e);if(t&&Z(t.pid))return t;await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor did not start within 10 seconds.`)}async function ie(e,t){let n=Date.now()+1e4;for(;Date.now()<n;){let n=await F(e);if(!n||n.supervisorId!==t)return;await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor did not stop within 10 seconds.`)}async function F(e){try{let t=JSON.parse(await a(m.join(e,v,y),`utf8`));return t.protocol!==1||typeof t.cwd!=`string`||typeof t.endpoint!=`string`||typeof t.pid!=`number`||!Number.isSafeInteger(t.pid)||t.pid<=0||typeof t.supervisorId!=`string`||typeof t.token!=`string`?void 0:t}catch{return}}async function I(e,t){let r=m.join(t,y),a=`${r}.${n()}.tmp`;await i(m.dirname(r),{recursive:!0,mode:448});try{await u(a,`${JSON.stringify(e)}\n`,{flag:`wx`,mode:384}),await o(a,r)}finally{await l(a).catch(()=>void 0)}}async function L(e,t){t&&t.cwd!==m.resolve(e)||(await s(m.join(e,v,y),{force:!0}),t&&h.platform!==`win32`&&await l(t.endpoint).catch(()=>void 0))}function R(e){if(h.platform===`win32`)return`\\\\.\\pipe\\coreframe-dev-${t(`sha256`).update(m.resolve(e)).digest(`hex`).slice(0,24)}`;let n=t(`sha256`).update(m.resolve(e)).digest(`hex`).slice(0,24);return m.join(p(),`coreframe-dev-${n}-supervisor.sock`)}function z(e){return Array.isArray(e)?e.map(B):[`postgres`,`sqlite`,`vite:web`,`vite:flutter:android`,`vite:flutter:ios`,`vite:flutter:macos`]}function B(e){if(e===`postgres`||e===`sqlite`||U(e))return e;throw Q(`INVALID_REQUEST`,`Unknown supervisor resource: ${String(e)}.`,!1)}function V(e){if(U(e))return e;throw Q(`INVALID_REQUEST`,`Unknown Vite resource: ${String(e)}.`,!1)}function H(e){if(!e||typeof e!=`object`)throw Q(`INVALID_REQUEST`,`A Vite specification is required.`,!1);let t=e;if(!U(t.resource)||typeof t.configFingerprint!=`string`||!t.endpoint||typeof t.endpoint.host!=`string`||t.endpoint.port!==void 0&&(!Number.isSafeInteger(t.endpoint.port)||t.endpoint.port<=0||t.endpoint.port>65535)||!Array.isArray(t.processes)||!t.processes.every(W))throw Q(`INVALID_REQUEST`,`The Vite specification is invalid.`,!1);return t}function U(e){return e===`vite:web`||typeof e==`string`&&/^vite:flutter:(android|ios|macos)$/u.test(e)}function W(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.command==`string`&&typeof t.cwd==`string`&&Array.isArray(t.args)&&t.args.every(e=>typeof e==`string`)&&!!t.env&&typeof t.env==`object`&&Object.values(t.env).every(e=>e===void 0||typeof e==`string`)}function G(e){return e&&typeof e==`object`?e:{}}function K(e){return e.split(/(?<=\n)/).filter(e=>ee.test(e.replace(w,``))).join(``)}function q(e){return typeof e==`string`?e:String(e??``)}function J(e){let t=G(e);return Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]==`string`))}function Y(e){return Object.fromEntries(Object.entries(e).filter(e=>e[1]!==void 0))}function X(e,t){return Object.fromEntries(Object.entries(t).filter(t=>{let[n,r]=t;return r!==void 0&&e[n]!==r}))}function Z(e){try{return h.kill(e,0),!0}catch(e){return e instanceof Error&&e.code===`EPERM`}}function Q(e,t,n,r){return Object.assign(Error(t),{code:e,details:r,retryable:n})}function $(e){if(e&&typeof e==`object`){let t=e;return{code:t.code??`SUPERVISOR_ERROR`,details:t.details,message:t.message??String(e),retryable:t.retryable??!1}}return{code:`SUPERVISOR_ERROR`,message:String(e),retryable:!1}}function ae(e){let t=Error(e?.message??`Development supervisor request failed.`);return t.code=e?.code,t.details=e?.details,t.retryable=e?.retryable,t}export{D as DevSupervisorClient,te as connectDevSupervisor,T as connectExistingDevSupervisor,O as runDevSupervisorProcess,E as stopDevSupervisor};
1
+ import{spawn as e}from"node:child_process";import{createHash as t,randomUUID as n}from"node:crypto";import{appendFile as r,mkdir as i,readFile as a,rename as o,rm as s,stat as c,unlink as l,writeFile as u}from"node:fs/promises";import{createConnection as d,createServer as f}from"node:net";import{tmpdir as p}from"node:os";import m from"node:path";import h from"node:process";import{Writable as g}from"node:stream";import _ from"@alloc/tree-kill";const v=`.coreframe/dev-supervisor`,y=`supervisor.json`,b=`logs`,x=1*1024*1024,S=4*1024*1024,C=45e3,w=RegExp(`\x1B\\[[0-?]*[ -/]*[@-~]`,`g`),ee=/^[\t ]*➜[\t ]+\S+:[\t ]+.+(?:\r?\n|$)/mu;async function te({cwd:e=h.cwd(),env:t=h.env,supervisorEntry:n}={}){let r=await T({cwd:e,env:t});if(r)return r;let i=await F(e),a=await re(e);if(!a)return i=await P(e),N({cwd:e,env:t,state:i});try{if(i=await F(e),i&&i.cwd===m.resolve(e)&&Z(i.pid))return await N({cwd:e,env:t,state:i});if(i&&await L(e,i),!n)throw Error(`A development supervisor process entry is required to start the supervisor.`);return await ne({cwd:e,env:t,entry:n}),i=await P(e),N({cwd:e,env:t,state:i})}finally{await a()}}async function T({cwd:e=h.cwd(),env:t=h.env}={}){let n=await F(e);if(!(!n||n.cwd!==m.resolve(e)||!Z(n.pid)))try{return await N({cwd:e,env:t,state:n})}catch{await L(e,n);return}}async function E({cwd:e=h.cwd(),resource:t}={}){let n=await F(e);if(!n||n.cwd!==m.resolve(e)||!Z(n.pid))return await L(e,n),!1;let r=await N({cwd:e,env:h.env,state:n});try{if(t)return await r.stopVite(t);await r.shutdown()}finally{r.close()}return await ie(e,n.supervisorId),!0}var D=class e{state;socket;pending=new Map;listeners=new Set;closeListeners=new Set;leases=new Set;decoder=new j;closed=!1;renewalTimer;constructor(e){this.state=e.state,this.socket=e.socket,this.socket.on(`data`,e=>{for(let t of this.decoder.push(e))this.handleFrame(t)}),this.socket.on(`close`,()=>this.handleClose(Error(`Development supervisor disconnected.`))),this.socket.on(`error`,e=>this.handleClose(e)),this.renewalTimer=setInterval(()=>void this.renewLeases(),C/3),this.renewalTimer.unref()}static async create(t){let n=new e(t);return await n.request(`hello`,{protocol:1,token:t.state.token}),n}async acquirePostgres({config:e,env:t}={}){let n=await this.request(`acquire`,{resource:`postgres`,config:e,env:Y(t??h.env)});return this.leases.add(n.leaseId),n}async acquireSqlite({config:e,env:t}={}){let n=await this.request(`acquire`,{resource:`sqlite`,config:e,env:Y(t??h.env)});return this.leases.add(n.leaseId),n}async acquireVite(e,t=!1){let n=await this.request(`acquire`,{resource:e.resource,spec:e,fresh:t});return this.leases.add(n.leaseId),n}async release(e){this.leases.delete(e),await this.request(`release`,{leaseId:e})}async subscribe(e){return this.request(`subscribe`,{resources:e})}async status(){return this.request(`status`)}async shutdown(){await this.request(`shutdown`)}async stopVite(e){return this.request(`stop`,{resource:e})}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}waitForServiceExit(e){return this.closed?Promise.resolve():new Promise(t=>{let n=()=>{r(),this.closeListeners.delete(n),t()},r=this.onEvent(t=>{!(`resource`in t)||t.resource!==e||t.event!==`service`||(t.state===`failed`||t.state===`stopped`)&&n()});this.closeListeners.add(n)})}close(){this.closed||(this.socket.end(),this.handleClose(Error(`Development supervisor client closed.`)))}request(e,t){if(this.closed)return Promise.reject(Error(`Development supervisor client is closed.`));let r=n();return new Promise((n,i)=>{this.pending.set(r,{resolve:n,reject:i}),this.socket.write(M({id:r,method:e,params:t,type:`request`}))})}async renewLeases(){for(let e of this.leases)await this.request(`renew`,{leaseId:e}).catch(()=>{this.leases.delete(e)})}handleFrame(e){if(e.type===`event`){for(let t of this.listeners)t(e.event);return}if(e.type!==`response`)return;let t=this.pending.get(e.id);t&&(this.pending.delete(e.id),e.ok?t.resolve(e.result):t.reject(ae(e.error)))}handleClose(e){if(!this.closed){this.closed=!0,clearInterval(this.renewalTimer);for(let t of this.pending.values())t.reject(e);this.pending.clear();for(let e of this.closeListeners)e();this.closeListeners.clear()}}};async function O({cwd:e=h.cwd(),startPostgres:t,startSqlite:n}={}){if(!t)throw Error(`A PostgreSQL starter is required to run the development supervisor.`);let r=m.resolve(e,v);await i(r,{recursive:!0,mode:448}),await i(m.join(r,b),{recursive:!0,mode:448});let a=await F(e);if(a&&a.pid!==h.pid&&Z(a.pid))throw Error(`A Coreframe development supervisor is already running for this directory.`);let o=R(e);h.platform!==`win32`&&await l(o).catch(()=>void 0);let s=new k({cwd:m.resolve(e),endpoint:o,root:r,startPostgres:t,startSqlite:n});await s.listen();let c=()=>{s.shutdown()};h.once(`SIGINT`,c),h.once(`SIGTERM`,c);try{await s.waitForShutdown()}finally{h.off(`SIGINT`,c),h.off(`SIGTERM`,c)}}var k=class{clients=new Set;leases=new Map;resourceOperations=new Map;resources=new Map;logEntries=[];server;root;state;startPostgres;startSqlite;postgres;sqlite;sequence=0;shutdownPromise;shutdownRequested=!1;idleTimer;leaseTimer;postgresStopTimer;sqliteStopTimer;constructor({cwd:e,endpoint:t,root:r,startPostgres:i,startSqlite:a}){this.root=r,this.startPostgres=i,this.startSqlite=a,this.state={cwd:e,endpoint:t,pid:h.pid,protocol:1,supervisorId:n(),token:n()},this.server=f(e=>this.accept(e)),this.leaseTimer=setInterval(()=>this.expireLeases(),5e3),this.leaseTimer.unref()}async listen(){await new Promise((e,t)=>{this.server.once(`error`,t),this.server.listen(this.state.endpoint,()=>{this.server.off(`error`,t),e()})}),await I(this.state,this.root)}waitForShutdown(){return new Promise(e=>{this.shutdownPromise?this.shutdownPromise.then(()=>e()):this.resolveShutdown=e})}async shutdown({stopPostgres:e=!0,stopSqlite:t=!0}={}){return this.shutdownPromise||=(async()=>{this.shutdownRequested=!0,this.idleTimer&&clearTimeout(this.idleTimer),clearInterval(this.leaseTimer),await Promise.all(this.resourceOperations.values()),this.leases.clear();for(let e of this.resources.keys())await this.stopVite(e);e?await this.stopPostgres():(this.cancelPostgresStop(),this.postgres=void 0),t?await this.stopSqlite():(this.cancelSqliteStop(),this.sqlite=void 0);for(let e of this.clients)e.close();await new Promise(e=>this.server.close(()=>e())),await l(this.state.endpoint).catch(()=>void 0),await l(m.join(this.root,y)).catch(()=>void 0),this.resolveShutdown?.()})(),this.shutdownPromise}resolveShutdown;accept(e){let t=new A(this,e);this.clients.add(t),e.once(`close`,()=>{this.clients.delete(t);for(let e of this.leases.values())e.connection===t&&this.releaseLease(e.id);this.maybeScheduleIdleShutdown()})}async handleRequest(e,t){try{let n=await this.dispatch(e,t.method,t.params??{});e.respond(t.id,{ok:!0,result:n})}catch(n){e.respond(t.id,{ok:!1,error:$(n)})}}publish(e){let t={...e,sequence:++this.sequence,timestamp:new Date().toISOString()};if(t.event===`log`&&t.resource!==`postgres`&&t.resource!==`sqlite`)for(this.logEntries.push(t);this.logEntries.length>2e3;)this.logEntries.shift();for(let e of this.clients)e.publish(t);return t}async addSubscription(e,t){e.subscribe(t);let r=this.logEntries.filter(e=>(e.resource===`postgres`||e.resource===`sqlite`)&&t.includes(e.resource));for(let t of r)e.publish(t);return e.publish({event:`replay-complete`,sequence:this.sequence,timestamp:new Date().toISOString()}),{subscriptionId:n()}}async dispatch(e,t,n){if(this.shutdownRequested&&t!==`shutdown`)throw Q(`SUPERVISOR_STOPPING`,`Development supervisor is stopping.`,!0);switch(t){case`hello`:return this.hello(e,n);case`status`:return this.status();case`subscribe`:return this.addSubscription(e,z(n.resources));case`acquire`:return this.withResourceOperation(B(n.resource),()=>this.acquire(e,n));case`release`:await this.releaseLease(q(n.leaseId));return;case`stop`:{let e=V(n.resource);return this.withResourceOperation(e,async()=>{let t=await this.stopVite(e,!0);return this.maybeScheduleIdleShutdown(),t})}case`renew`:return this.renewLease(q(n.leaseId));case`shutdown`:this.shutdownRequested=!0,setImmediate(()=>void this.shutdown({stopPostgres:!1}));return;default:throw Q(`INVALID_REQUEST`,`Unknown supervisor method: ${t}.`,!1)}}async withResourceOperation(e,t){let n=this.resourceOperations.get(e),r,i=new Promise(e=>{r=e});this.resourceOperations.set(e,i),n&&await n;try{return await t()}finally{r(),this.resourceOperations.get(e)===i&&this.resourceOperations.delete(e)}}hello(e,t){if(t.protocol!==1||t.token!==this.state.token)throw e.close(),Q(`AUTH_FAILED`,`Invalid supervisor protocol or token.`,!1);return e.authenticated=!0,{cwd:this.state.cwd,protocol:1,supervisorId:this.state.supervisorId}}status(){return{postgres:this.postgres?{leases:this.postgres.leases.size,state:`running`}:void 0,sqlite:this.sqlite?{leases:this.sqlite.leases.size,state:`running`}:void 0,resources:[...this.resources.entries()].map(([e,t])=>({endpoint:t.spec.endpoint,leases:t.leases.size,resource:e,state:`running`}))}}async acquire(e,t){let n=B(t.resource);if(n===`postgres`)return this.acquirePostgres(e,G(t));if(n===`sqlite`)return this.acquireSqlite(e,G(t));let r=H(t.spec);if(r.resource!==n)throw Q(`INVALID_REQUEST`,`The Vite resource does not match its specification.`,!1);let i=this.resources.get(n);if(i&&q(t.fresh)!==`true`){if(i.spec.configFingerprint!==r.configFingerprint||r.endpoint.port!==void 0&&i.spec.endpoint.port!==r.endpoint.port)throw Q(`CONFIG_MISMATCH`,`A ${n} Vite server already exists with different settings.`,!1,{existing:{configFingerprint:i.spec.configFingerprint,endpoint:i.spec.endpoint},requested:{configFingerprint:r.configFingerprint,endpoint:r.endpoint}});let t=this.createLease(e,n);i.leases.add(t.id);for(let t of i.startupLinks)e.publish(t);return{endpoint:i.spec.endpoint,leaseId:t.id,state:`reused`}}if(i){if(i.leases.size>0)throw Q(`RESOURCE_BUSY`,`Cannot replace active ${n} development.`,!0);await this.stopVite(n)}if(r.endpoint.port===void 0)throw Q(`INVALID_REQUEST`,`A ${n} Vite server requires a port when it is started.`,!1);let a={...r,endpoint:{...r.endpoint,port:r.endpoint.port}},o={children:[],leases:new Set,startupLinks:[],spec:a};this.resources.set(n,o),this.publish({event:`service`,resource:n,state:`starting`,endpoint:a.endpoint});try{for(let e of r.processes){let t=this.spawnProcess(n,e);o.children.push(t)}let t=this.createLease(e,n);return o.leases.add(t.id),this.publish({event:`service`,resource:n,state:`running`,endpoint:a.endpoint,pid:o.children[0]?.pid??void 0}),{endpoint:a.endpoint,leaseId:t.id,state:`started`}}catch(e){throw await this.stopVite(n),e}}async acquirePostgres(e,t){let n=this.postgres===void 0;if(this.postgres)this.cancelPostgresStop();else{let e=await this.createLogStream(`postgres`),n=J(t.env),r=await this.startPostgres({config:t.config,cwd:this.state.cwd,env:Y(n),failIfRunning:!1,postgresOutput:e});this.postgres={env:X(n,r.env),leases:new Set,sidecar:r},this.publish({event:`service`,resource:`postgres`,state:`running`})}let r=this.createLease(e,`postgres`);return this.postgres.leases.add(r.id),{env:Y(this.postgres.env),leaseId:r.id,state:n?`started`:`reused`}}async acquireSqlite(e,t){if(!this.startSqlite)throw Error(`A SQLite starter is required to run the development supervisor.`);let n=this.sqlite===void 0;if(this.sqlite)this.cancelSqliteStop();else{let e=await this.createLogStream(`sqlite`),n=J(t.env),r=await this.startSqlite({config:t.config,cwd:this.state.cwd,env:Y(n),tursoOutput:e});this.sqlite={env:X(n,r.env),leases:new Set,sidecar:r},this.publish({event:`service`,resource:`sqlite`,state:`running`})}let r=this.createLease(e,`sqlite`);return this.sqlite.leases.add(r.id),{env:Y(this.sqlite.env),leaseId:r.id,state:n?`started`:`reused`}}createLease(e,t){let r={connection:e,expiresAt:Date.now()+C,id:n(),resource:t};return this.leases.set(r.id,r),r}renewLease(e){let t=this.leases.get(e);if(!t)throw Q(`LEASE_EXPIRED`,`The supervisor lease is no longer active.`,!0);return t.expiresAt=Date.now()+C,{expiresAt:t.expiresAt}}expireLeases(){for(let e of this.leases.values())e.expiresAt<=Date.now()&&this.releaseLease(e.id)}async releaseLease(e){let t=this.leases.get(e);if(t){if(this.leases.delete(e),t.resource===`postgres`)this.postgres?.leases.delete(e),this.postgres?.leases.size===0&&this.schedulePostgresStop();else if(t.resource===`sqlite`)this.sqlite?.leases.delete(e),this.sqlite?.leases.size===0&&this.scheduleSqliteStop();else{let n=this.resources.get(t.resource);n?.leases.delete(e),n?.leases.size===0&&await this.stopVite(t.resource)}this.maybeScheduleIdleShutdown()}}spawnProcess(t,n){let r=e(n.command,n.args,{cwd:n.cwd,env:Y(n.env),stdio:[`ignore`,`pipe`,`pipe`]}),i=(e,n)=>{let r=this.publish({event:`log`,resource:t,stream:e,data:String(n)});if(r.event!==`log`)return;let i=K(r.data);i&&this.resources.get(t)?.startupLinks.push({...r,data:i})};return r.stdout.on(`data`,e=>i(`stdout`,e)),r.stderr.on(`data`,e=>i(`stderr`,e)),r.on(`error`,e=>{this.publish({event:`service`,resource:t,state:`failed`,error:e.message})}),r.on(`exit`,(e,n)=>{this.resources.has(t)&&(this.publish({event:`service`,resource:t,state:e===0||n?`stopped`:`failed`,error:e&&!n?`Process exited with code ${e}.`:void 0}),this.stopVite(t))}),r}async stopVite(e,t=!1){let n=this.resources.get(e);if(!n)return!1;if(this.resources.delete(e),t){for(let e of n.leases)this.leases.delete(e);n.leases.clear()}return await Promise.all(n.children.map(e=>_(e,`SIGTERM`))),await Promise.all(n.children.map(e=>new Promise(t=>{if(e.exitCode!==null){t();return}e.once(`exit`,()=>t()),setTimeout(()=>{_(e,`SIGKILL`).then(t,t)},5e3).unref()}))),this.publish({event:`service`,resource:e,state:`stopped`}),!0}async stopPostgres(){if(this.cancelPostgresStop(),!this.postgres)return;let e=this.postgres;this.postgres=void 0,await e.sidecar[Symbol.asyncDispose](),this.publish({event:`service`,resource:`postgres`,state:`stopped`})}schedulePostgresStop(){this.postgresStopTimer||(this.postgresStopTimer=setTimeout(()=>{this.postgresStopTimer=void 0,this.withResourceOperation(`postgres`,async()=>{this.postgres?.leases.size===0&&await this.stopPostgres()}).then(()=>this.maybeScheduleIdleShutdown(),()=>this.maybeScheduleIdleShutdown())},3e5),this.postgresStopTimer.unref())}async stopSqlite(){if(this.cancelSqliteStop(),!this.sqlite)return;let e=this.sqlite;this.sqlite=void 0,await e.sidecar[Symbol.asyncDispose](),this.publish({event:`service`,resource:`sqlite`,state:`stopped`})}scheduleSqliteStop(){this.sqliteStopTimer||(this.sqliteStopTimer=setTimeout(()=>{this.sqliteStopTimer=void 0,this.withResourceOperation(`sqlite`,async()=>{this.sqlite?.leases.size===0&&await this.stopSqlite()}).then(()=>this.maybeScheduleIdleShutdown(),()=>this.maybeScheduleIdleShutdown())},3e5),this.sqliteStopTimer.unref())}cancelPostgresStop(){this.postgresStopTimer&&=(clearTimeout(this.postgresStopTimer),void 0)}cancelSqliteStop(){this.sqliteStopTimer&&=(clearTimeout(this.sqliteStopTimer),void 0)}async createLogStream(e){let t=m.join(this.root,b,`${e.replaceAll(`:`,`-`)}.log`);await i(m.dirname(t),{recursive:!0,mode:448}),await u(t,``);let n=0;return new g({write:(i,a,o)=>{let s=String(i),c=Buffer.from(s),l=c.subarray(Math.max(0,c.length-x)),d=n+l.length>x;(d?u(t,l):r(t,l)).then(()=>{n=d?l.length:n+l.length,o()},o),this.publish({event:`log`,resource:e,stream:`stdout`,data:s})}})}maybeScheduleIdleShutdown(){this.leases.size>0||this.resources.size>0||this.postgres||this.sqlite||this.idleTimer||(this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.leases.size===0&&this.resources.size===0&&!this.postgres&&!this.sqlite&&this.shutdown()},3e4),this.idleTimer.unref())}},A=class{authenticated=!1;decoder=new j;subscriptions=new Set;eventQueue=[];queuedEventBytes=0;writingEvent=!1;droppedEventRange;server;socket;constructor(e,t){this.server=e,this.socket=t,t.on(`error`,()=>this.close()),t.on(`data`,t=>{try{for(let n of this.decoder.push(t))n.type===`request`&&(!this.authenticated&&n.method!==`hello`?this.respond(n.id,{ok:!1,error:$(Q(`AUTH_FAILED`,`Send hello first.`,!1))}):e.handleRequest(this,n))}catch{this.close()}})}respond(e,t){this.socket.write(M({...t,id:e,type:`response`}))}publish(e){let t=[...this.subscriptions];t.length!==0&&(e.event!==`replay-complete`&&e.event!==`gap`&&(e.resource===void 0||!t.some(t=>t.has(e.resource)))||this.enqueueEvent(e))}subscribe(e){this.subscriptions.add(new Set(e))}close(){this.eventQueue.length=0,this.queuedEventBytes=0,this.socket.destroy()}enqueueEvent(e){let t=M({event:e,type:`event`});if(t.length>S){this.noteDropped(e);return}for(;;){let n=this.droppedEventRange?{event:{event:`gap`,from:this.droppedEventRange.from,reason:`buffer-overflow`,to:this.droppedEventRange.to,sequence:e.sequence,timestamp:new Date().toISOString()},frame:Buffer.alloc(0)}:void 0;n&&(n.frame=M({event:n.event,type:`event`}));let r=t.length+(n?.frame.length??0),i=!1;for(;this.queuedEventBytes+r>S;){let e=this.eventQueue.shift();if(!e)break;i=!0,this.queuedEventBytes-=e.frame.length,this.noteDropped(e.event)}if(!i){if(this.queuedEventBytes+r<=S){n&&(this.eventQueue.push(n),this.queuedEventBytes+=n.frame.length,this.droppedEventRange=void 0),this.eventQueue.push({event:e,frame:t}),this.queuedEventBytes+=t.length,this.pumpEvents();return}if(this.eventQueue.length===0){this.noteDropped(e);return}}}}noteDropped(e){let t=e.sequence;if(!this.droppedEventRange){this.droppedEventRange={from:t,to:t};return}this.droppedEventRange.from=Math.min(this.droppedEventRange.from,t),this.droppedEventRange.to=Math.max(this.droppedEventRange.to,t)}pumpEvents(){if(this.writingEvent||this.eventQueue.length===0||this.socket.destroyed)return;let e=this.eventQueue.shift();this.queuedEventBytes-=e.frame.length,this.writingEvent=!0,this.socket.write(e.frame,()=>{this.writingEvent=!1,this.pumpEvents()})}},j=class{buffer=Buffer.alloc(0);push(e){this.buffer=Buffer.concat([this.buffer,Buffer.from(e)]);let t=[];for(;this.buffer.length>=4;){let e=this.buffer.readUInt32BE(0);if(e>16777216)throw Error(`Development supervisor protocol frame is too large.`);if(this.buffer.length<e+4)break;let n=this.buffer.subarray(4,e+4).toString(`utf8`);this.buffer=this.buffer.subarray(e+4),t.push(JSON.parse(n))}return t}};function M(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.allocUnsafe(t.length+4);return n.writeUInt32BE(t.length,0),t.copy(n,4),n}async function N(e){let t=await new Promise((t,n)=>{let r=d(e.state.endpoint);r.once(`connect`,()=>t(r)),r.once(`error`,n)});return D.create({...e,socket:t})}async function ne({cwd:t,env:n,entry:r}){e(h.execPath,[r,`--cwd`,t],{cwd:t,detached:!0,env:{...n,COREFRAME_DEV_SUPERVISOR:`1`},stdio:`ignore`}).unref()}async function re(e){let t=m.join(e,v),n=m.join(t,`start.lock`),r=Date.now()+1e4;for(await i(t,{recursive:!0,mode:448});Date.now()<r;)try{return await u(n,`${h.pid}\n`,{flag:`wx`,mode:384}),async()=>{await l(n).catch(()=>void 0)}}catch(t){if(!(t instanceof Error&&t.code===`EEXIST`))throw t;let r=await F(e);if(r&&Z(r.pid))return;try{let e=await c(n);if(Date.now()-e.mtimeMs>1e4){await l(n).catch(()=>void 0);continue}}catch{continue}await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor startup is already in progress.`)}async function P(e){let t=Date.now()+1e4;for(;Date.now()<t;){let t=await F(e);if(t&&Z(t.pid))return t;await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor did not start within 10 seconds.`)}async function ie(e,t){let n=Date.now()+1e4;for(;Date.now()<n;){let n=await F(e);if(!n||n.supervisorId!==t)return;await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor did not stop within 10 seconds.`)}async function F(e){try{let t=JSON.parse(await a(m.join(e,v,y),`utf8`));return t.protocol!==1||typeof t.cwd!=`string`||typeof t.endpoint!=`string`||typeof t.pid!=`number`||!Number.isSafeInteger(t.pid)||t.pid<=0||typeof t.supervisorId!=`string`||typeof t.token!=`string`?void 0:t}catch{return}}async function I(e,t){let r=m.join(t,y),a=`${r}.${n()}.tmp`;await i(m.dirname(r),{recursive:!0,mode:448});try{await u(a,`${JSON.stringify(e)}\n`,{flag:`wx`,mode:384}),await o(a,r)}finally{await l(a).catch(()=>void 0)}}async function L(e,t){t&&t.cwd!==m.resolve(e)||(await s(m.join(e,v,y),{force:!0}),t&&h.platform!==`win32`&&await l(t.endpoint).catch(()=>void 0))}function R(e){if(h.platform===`win32`)return`\\\\.\\pipe\\coreframe-dev-${t(`sha256`).update(m.resolve(e)).digest(`hex`).slice(0,24)}`;let n=t(`sha256`).update(m.resolve(e)).digest(`hex`).slice(0,24);return m.join(p(),`coreframe-dev-${n}-supervisor.sock`)}function z(e){return Array.isArray(e)?e.map(B):[`postgres`,`sqlite`,`vite:web`,`vite:flutter:android`,`vite:flutter:ios`,`vite:flutter:linux`,`vite:flutter:macos`,`vite:flutter:windows`]}function B(e){if(e===`postgres`||e===`sqlite`||U(e))return e;throw Q(`INVALID_REQUEST`,`Unknown supervisor resource: ${String(e)}.`,!1)}function V(e){if(U(e))return e;throw Q(`INVALID_REQUEST`,`Unknown Vite resource: ${String(e)}.`,!1)}function H(e){if(!e||typeof e!=`object`)throw Q(`INVALID_REQUEST`,`A Vite specification is required.`,!1);let t=e;if(!U(t.resource)||typeof t.configFingerprint!=`string`||!t.endpoint||typeof t.endpoint.host!=`string`||t.endpoint.port!==void 0&&(!Number.isSafeInteger(t.endpoint.port)||t.endpoint.port<=0||t.endpoint.port>65535)||!Array.isArray(t.processes)||!t.processes.every(W))throw Q(`INVALID_REQUEST`,`The Vite specification is invalid.`,!1);return t}function U(e){return e===`vite:web`||typeof e==`string`&&/^vite:flutter:(android|ios|linux|macos|windows)$/u.test(e)}function W(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.command==`string`&&typeof t.cwd==`string`&&Array.isArray(t.args)&&t.args.every(e=>typeof e==`string`)&&!!t.env&&typeof t.env==`object`&&Object.values(t.env).every(e=>e===void 0||typeof e==`string`)}function G(e){return e&&typeof e==`object`?e:{}}function K(e){return e.split(/(?<=\n)/).filter(e=>ee.test(e.replace(w,``))).join(``)}function q(e){return typeof e==`string`?e:String(e??``)}function J(e){let t=G(e);return Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]==`string`))}function Y(e){return Object.fromEntries(Object.entries(e).filter(e=>e[1]!==void 0))}function X(e,t){return Object.fromEntries(Object.entries(t).filter(t=>{let[n,r]=t;return r!==void 0&&e[n]!==r}))}function Z(e){try{return h.kill(e,0),!0}catch(e){return e instanceof Error&&e.code===`EPERM`}}function Q(e,t,n,r){return Object.assign(Error(t),{code:e,details:r,retryable:n})}function $(e){if(e&&typeof e==`object`){let t=e;return{code:t.code??`SUPERVISOR_ERROR`,details:t.details,message:t.message??String(e),retryable:t.retryable??!1}}return{code:`SUPERVISOR_ERROR`,message:String(e),retryable:!1}}function ae(e){let t=Error(e?.message??`Development supervisor request failed.`);return t.code=e?.code,t.details=e?.details,t.retryable=e?.retryable,t}export{D as DevSupervisorClient,te as connectDevSupervisor,T as connectExistingDevSupervisor,O as runDevSupervisorProcess,E as stopDevSupervisor};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coreframe/dev-supervisor",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "description": "Process supervision utilities for Coreframe development workflows",
5
5
  "repository": {
6
6
  "type": "git",
@@ -19,7 +19,7 @@
19
19
  },
20
20
  "dependencies": {
21
21
  "@alloc/tree-kill": "1.4.0",
22
- "@coreframe/config": "^0.1.6"
22
+ "@coreframe/config": "^0.1.8"
23
23
  },
24
24
  "devDependencies": {
25
25
  "@types/node": "^26.1.0",