@coreframe/dev-supervisor 0.1.2 → 0.1.4

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
@@ -6,7 +6,7 @@ import { CoreframeConfig } from "@coreframe/config";
6
6
  declare const protocolVersion = 1;
7
7
  type DevSupervisorFlutterPlatform = "android" | "ios" | "macos";
8
8
  type DevSupervisorViteResource = "vite:web" | `vite:flutter:${DevSupervisorFlutterPlatform}`;
9
- type DevSupervisorResource = "postgres" | DevSupervisorViteResource;
9
+ type DevSupervisorResource = "postgres" | "sqlite" | DevSupervisorViteResource;
10
10
  type DevSupervisorStream = "stdout" | "stderr";
11
11
  type DevSupervisorProcessSpec = {
12
12
  args: string[];
@@ -77,6 +77,10 @@ type PostgresAcquireParams = {
77
77
  config?: CoreframeConfig;
78
78
  env?: NodeJS.ProcessEnv;
79
79
  };
80
+ type SqliteAcquireParams = {
81
+ config?: CoreframeConfig;
82
+ env?: NodeJS.ProcessEnv;
83
+ };
80
84
  type DevSupervisorPostgresSidecar = {
81
85
  env: NodeJS.ProcessEnv;
82
86
  [Symbol.asyncDispose](): Promise<void>;
@@ -88,6 +92,16 @@ type DevSupervisorPostgresStarter = (options: {
88
92
  failIfRunning: boolean;
89
93
  postgresOutput: Writable;
90
94
  }) => Promise<DevSupervisorPostgresSidecar>;
95
+ type DevSupervisorSqliteSidecar = {
96
+ env: NodeJS.ProcessEnv;
97
+ [Symbol.asyncDispose](): Promise<void>;
98
+ };
99
+ type DevSupervisorSqliteStarter = (options: {
100
+ config?: CoreframeConfig;
101
+ cwd: string;
102
+ env: NodeJS.ProcessEnv;
103
+ tursoOutput: Writable;
104
+ }) => Promise<DevSupervisorSqliteSidecar>;
91
105
  declare function connectDevSupervisor({
92
106
  cwd,
93
107
  env,
@@ -104,10 +118,13 @@ declare function connectExistingDevSupervisor({
104
118
  cwd?: string;
105
119
  env?: NodeJS.ProcessEnv;
106
120
  }): Promise<DevSupervisorClient | undefined>;
121
+ /** Stops one managed Vite resource, or the entire detached supervisor when no resource is supplied. */
107
122
  declare function stopDevSupervisor({
108
- cwd
123
+ cwd,
124
+ resource
109
125
  }?: {
110
126
  cwd?: string;
127
+ resource?: DevSupervisorViteResource;
111
128
  }): Promise<boolean>;
112
129
  declare class DevSupervisorClient {
113
130
  readonly state: SupervisorState;
@@ -129,6 +146,14 @@ declare class DevSupervisorClient {
129
146
  leaseId: string;
130
147
  state: "reused" | "started";
131
148
  }>;
149
+ acquireSqlite({
150
+ config,
151
+ env
152
+ }?: SqliteAcquireParams): Promise<{
153
+ env: NodeJS.ProcessEnv;
154
+ leaseId: string;
155
+ state: "reused" | "started";
156
+ }>;
132
157
  acquireVite(spec: DevSupervisorViteSpec, fresh?: boolean): Promise<{
133
158
  endpoint: {
134
159
  host: string;
@@ -143,6 +168,8 @@ declare class DevSupervisorClient {
143
168
  }>;
144
169
  status(): Promise<unknown>;
145
170
  shutdown(): Promise<void>;
171
+ /** Stops the managed Vite resource without shutting down the supervisor. */
172
+ stopVite(resource: DevSupervisorViteResource): Promise<boolean>;
146
173
  onEvent(listener: (event: DevSupervisorEvent) => void): () => boolean;
147
174
  waitForServiceExit(resource: DevSupervisorResource): Promise<void>;
148
175
  close(): void;
@@ -153,10 +180,12 @@ declare class DevSupervisorClient {
153
180
  }
154
181
  declare function runDevSupervisorProcess({
155
182
  cwd,
156
- startPostgres
183
+ startPostgres,
184
+ startSqlite
157
185
  }?: {
158
186
  cwd?: string;
159
187
  startPostgres?: DevSupervisorPostgresStarter;
188
+ startSqlite?: DevSupervisorSqliteStarter;
160
189
  }): Promise<void>;
161
190
  //#endregion
162
- export { DevSupervisorClient, DevSupervisorEvent, DevSupervisorFlutterPlatform, DevSupervisorPostgresSidecar, DevSupervisorPostgresStarter, DevSupervisorProcessSpec, DevSupervisorResource, DevSupervisorStream, DevSupervisorViteResource, DevSupervisorViteSpec, connectDevSupervisor, connectExistingDevSupervisor, runDevSupervisorProcess, stopDevSupervisor };
191
+ export { DevSupervisorClient, DevSupervisorEvent, DevSupervisorFlutterPlatform, DevSupervisorPostgresSidecar, DevSupervisorPostgresStarter, DevSupervisorProcessSpec, DevSupervisorResource, DevSupervisorSqliteSidecar, DevSupervisorSqliteStarter, DevSupervisorStream, DevSupervisorViteResource, DevSupervisorViteSpec, connectDevSupervisor, connectExistingDevSupervisor, runDevSupervisorProcess, stopDevSupervisor };
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 R(e),a=await F(e);if(!a)return i=await I(e),N({cwd:e,env:t,state:i});try{if(i=await R(e),i&&i.cwd===m.resolve(e)&&Z(i.pid))return await N({cwd:e,env:t,state:i});if(i&&await B(e,i),!n)throw Error(`A development supervisor process entry is required to start the supervisor.`);return await P({cwd:e,env:t,entry:n}),i=await I(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 R(e);if(!(!n||n.cwd!==m.resolve(e)||!Z(n.pid)))try{return await N({cwd:e,env:t,state:n})}catch{await B(e,n);return}}async function E({cwd:e=h.cwd()}={}){let t=await R(e);if(!t||t.cwd!==m.resolve(e)||!Z(t.pid))return await B(e,t),!1;let n=await N({cwd:e,env:h.env,state:t});try{await n.shutdown()}finally{n.close()}return await L(e,t.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:X(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`)}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(re(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}={}){if(!t)throw Error(`A PostgreSQL starter is required to run the development supervisor.`);let n=m.resolve(e,v);await i(n,{recursive:!0,mode:448}),await i(m.join(n,b),{recursive:!0,mode:448});let r=await R(e);if(r&&r.pid!==h.pid&&Z(r.pid))throw Error(`A Coreframe development supervisor is already running for this directory.`);let a=V(e);h.platform!==`win32`&&await l(a).catch(()=>void 0);let o=new k({cwd:m.resolve(e),endpoint:a,root:n,startPostgres:t});await o.listen();let s=()=>{o.shutdown()};h.once(`SIGINT`,s),h.once(`SIGTERM`,s);try{await o.waitForShutdown()}finally{h.off(`SIGINT`,s),h.off(`SIGTERM`,s)}}var k=class{clients=new Set;leases=new Map;resourceOperations=new Map;resources=new Map;logEntries=[];server;root;state;startPostgres;postgres;sequence=0;shutdownPromise;shutdownRequested=!1;idleTimer;leaseTimer;postgresStopTimer;constructor({cwd:e,endpoint:t,root:r,startPostgres:i}){this.root=r,this.startPostgres=i,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 z(this.state,this.root)}waitForShutdown(){return new Promise(e=>{this.shutdownPromise?this.shutdownPromise.then(()=>e()):this.resolveShutdown=e})}async shutdown({stopPostgres:e=!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);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`)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`&&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,H(n.resources));case`acquire`:return this.withResourceOperation(U(n.resource),()=>this.acquire(e,n));case`release`:await this.releaseLease(Y(n.leaseId));return;case`renew`:return this.renewLease(Y(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,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=U(t.resource);if(n===`postgres`)return this.acquirePostgres(e,q(t));let r=W(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&&Y(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=await this.startPostgres({config:t.config,cwd:this.state.cwd,env:X(ne(t.env)),failIfRunning:!1,postgresOutput:e});this.postgres={leases:new Set,sidecar:n},this.publish({event:`service`,resource:`postgres`,state:`running`})}let r=this.createLease(e,`postgres`);return this.postgres.leases.add(r.id),{env:X(this.postgres.sidecar.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{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:X(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=J(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){let t=this.resources.get(e);t&&(this.resources.delete(e),await Promise.all(t.children.map(e=>_(e,`SIGTERM`))),await Promise.all(t.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`}))}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())}cancelPostgresStop(){this.postgresStopTimer&&=(clearTimeout(this.postgresStopTimer),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.idleTimer||(this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.leases.size===0&&this.resources.size===0&&!this.postgres&&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 P({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 F(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 R(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 I(e){let t=Date.now()+1e4;for(;Date.now()<t;){let t=await R(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 L(e,t){let n=Date.now()+1e4;for(;Date.now()<n;){let n=await R(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 R(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 z(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 B(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 V(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 H(e){return Array.isArray(e)?e.map(U):[`postgres`,`vite:web`,`vite:flutter:android`,`vite:flutter:ios`,`vite:flutter:macos`]}function U(e){if(e===`postgres`||G(e))return e;throw Q(`INVALID_REQUEST`,`Unknown supervisor resource: ${String(e)}.`,!1)}function W(e){if(!e||typeof e!=`object`)throw Q(`INVALID_REQUEST`,`A Vite specification is required.`,!1);let t=e;if(!G(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(K))throw Q(`INVALID_REQUEST`,`The Vite specification is invalid.`,!1);return t}function G(e){return e===`vite:web`||typeof e==`string`&&/^vite:flutter:(android|ios|macos)$/u.test(e)}function K(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 q(e){return e&&typeof e==`object`?e:{}}function J(e){return e.split(/(?<=\n)/).filter(e=>ee.test(e.replace(w,``))).join(``)}function Y(e){return typeof e==`string`?e:String(e??``)}function ne(e){let t=q(e);return Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]==`string`))}function X(e){return Object.fromEntries(Object.entries(e).filter(e=>e[1]!==void 0))}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 re(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: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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coreframe/dev-supervisor",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
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.2"
22
+ "@coreframe/config": "^0.1.4"
23
23
  },
24
24
  "devDependencies": {
25
25
  "@types/node": "^26.1.0",