@prisma/dev 0.7.0 → 0.8.0

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.
@@ -0,0 +1 @@
1
+ import{e as l,l as m}from"./chunk-Q3M6SQC2.js";import{PGlite as b}from"@electric-sql/pglite";import{PGLiteSocketServer as P}from"@electric-sql/pglite-socket";import{filename as w}from"pathe/utils";var n={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},y=`postgres://${n.username}:${n.password}@localhost`,f=new URLSearchParams({sslmode:n.sslMode}),p=new URLSearchParams({...Object.fromEntries(f.entries()),connection_limit:String(n.connectionLimit),connect_timeout:String(n.connectTimeout),max_idle_connection_lifetime:String(n.maxIdleConnectionLifetime),pool_timeout:String(n.poolTimeout),single_use_connections:"true",socket_timeout:String(n.socketTimeout)});async function L(e,o){let c=e==="database"?o.databasePort:o.shadowDatabasePort;if(o.dryRun)return u(e,o,{db:null,port:c,server:null});let{debug:a}=o,i=await(e==="shadow_database"?v:D)(o.pgliteDataDirPath,a);a&&i.onNotification((t,r)=>{console.debug(`[${e}][${t}] ${r}`)});let d=new P({db:i,debug:a,inspect:a,port:c});a&&(d.addEventListener("listening",t=>{let{detail:r}=t;console.debug(`[${e}] server listening on ${JSON.stringify(r)}`)}),d.addEventListener("connection",t=>{let{clientAddress:r,clientPort:S}=t.detail;console.debug(`[${e}] client connected from ${r}:${S}`)}),d.addEventListener("error",t=>{let{detail:r}=t;console.error(`[${e}] server error:`,r)}));try{await d.start()}catch(t){throw t instanceof Error&&"code"in t&&t.code==="EADDRINUSE"?new m(c,e):t}return u(e,o,{db:i,port:c,server:d})}function u(e,o,c){let{debug:a}=o,{db:s,port:i,server:d}=c||{};return a&&console.debug(`[${e}] server started on port ${i}`),{...n,close:async()=>{let t=[];try{await d?.stop(),a&&console.debug(`[${e}] server stopped on port ${i}`)}catch(r){console.error(`[${e}] server stop error`,r),t.push(r)}if(e==="database")try{await s?.syncToFs(),a&&console.debug(`[${e}] synced to filesystem`)}catch(r){console.error(`[${e}] sync error`,r),t.push(r)}try{await s?.close(),a&&console.debug(`[${e}] closed`)}catch(r){console.error(`[${e}] close error`,r),t.push(r)}if(t.length>0)throw new AggregateError(t,`Failed to close ${e} properly`)},connectionString:g(i,f),dump:async t=>{e==="shadow_database"||!s||await $({db:s,debug:a,destinationPath:t})},port:i,prismaORMConnectionString:g(i,p),terminalCommand:`PGPASSWORD=${n.password} PGSSLMODE=${n.sslMode} psql -h localhost -p ${i} -U ${n.username} -d ${n.database}`}}function g(e,o){return`${y}:${e}/${n.database}?${o.toString()}`}async function D(e,o){return await b.create({database:n.database,dataDir:e,debug:o?5:void 0,relaxedDurability:!1,username:n.username})}async function v(e,o){return await b.create({database:n.database,dataDir:"memory://",debug:o?5:void 0,relaxedDurability:!1,username:n.username})}async function $(e){let{dataDir:o,db:c,debug:a,destinationPath:s}=e,i=c||await D(o,a),{pgDump:d}=await import("@electric-sql/pglite-tools/pg_dump"),t=await d({args:["--schema-only","--no-owner"],fileName:s?w(s):void 0,pg:await i.clone()});return s?(a&&console.debug(`[DB] Dumping database to ${s}`),await l(t,s)):(a&&console.debug("[DB] Dumping database to memory"),await t.text())}export{L as a,$ as b};
@@ -0,0 +1,3 @@
1
+ import{b as p,f as E,g as $,h as R,i as _,j as k,k as A}from"./chunk-Q3M6SQC2.js";import{writeFile as B}from"fs/promises";import{hc as C}from"hono/client";import{join as u}from"pathe";import{check as H,lock as Y}from"proper-lockfile";import{process as m}from"std-env";import{integer as V,literal as Z,minLength as q,minValue as N,number as L,object as g,optional as f,parseJson as z,pipe as h,safeParse as K,string as b,url as W}from"valibot";import{process as j}from"std-env";function M(r,e){if(r==null)return!1;try{return j.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}var D=h(b(),W()),I=g({connectionString:D,prismaORMConnectionString:f(D),terminalCommand:f(b())}),T=g({url:D}),S=h(L(),V(),N(1)),G=g({database:I,http:T,ppg:T,shadowDatabase:I}),Q=g({databasePort:S,exports:f(G),name:h(b(),q(1)),pid:f(h(L(),V(),N(0))),port:S,shadowDatabasePort:S,version:Z("1")}),O=Symbol("initialize"),P="default",d=class{databasePort;debug;dryRun;name;persistenceMode;pid;port;shadowDatabasePort;constructor(e){this.databasePort=e.databasePort??51214,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??P,this.persistenceMode=e.persistenceMode,this.pid=e.pid??m.pid,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async createExclusively(e){let t=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new l({...e,pid:m.pid}):new y(e);return await t[O](),t}static async fromServerDump(e){let{debug:t,name:s=P}=e??{},n=p(s),a=l.getServerDumpPath(n),i=await E(a);if(i==null)return t&&console.debug(`[State] No server dump file found at: ${a}`),null;t&&(console.debug(`[State] server dump file found at "${a}":`),console.debug(i));let{issues:v,output:o,success:c}=K(h(b(),z(),Q),i);if(!c)throw t&&console.debug(`[State] Invalid server dump file at "${a}":
2
+ ${JSON.stringify(v,null,2)}`),new Error(`Invalid Prisma Dev state for "${s}".`);return new l({databasePort:o.databasePort,debug:t,dryRun:!1,name:s,pid:o.pid,port:o.port,serverDump:o,shadowDatabasePort:o.shadowDatabasePort})}static async scan(e){let{debug:t}=e??{},s=u(p(P),"..");t&&console.debug(`[State] scanning for server states in: ${s}`);let n=await R(s);return t&&console.debug(`[State] found server names: ${JSON.stringify(n)}`),await Promise.all(n.map(a=>X(a,t)))}},y=class extends d{constructor(e){super({...e,persistenceMode:"stateless",pid:m.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[O](){}async close(){}async writeServerDump(){}},l=class r extends d{#t;#e;#a;#o;#r;#s=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=p(this.name),this.#t=u(this.#e,"db_dump.bak"),this.#a=u(this.#e,".pglite"),this.#r=e.serverDump??null,this.#o=r.getServerDumpPath(this.#e)}static getServerDumpPath(e){return u(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get pgliteDataDirPath(){return this.#a}async[O](){await $(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#s=await Y(this.#e,{lockfilePath:u(this.#e,".lock")}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`),await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new x(this):e}}async close(){if(this.#s!=null)try{await this.#s(),this.#s=null,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw console.error(`[State] failed to release lock on: ${this.#e}`),e}}async writeServerDump(e){this.#r={name:this.name,version:"1",pid:m.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await B(this.#o,`${JSON.stringify(this.#r,null,2)}
3
+ `,{encoding:"utf-8"})}};async function X(r,e){let t={databasePort:-1,exports:void 0,name:r,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let s=await d.fromServerDump({debug:e,name:r});if(!s)return e&&console.debug(`[State] no server state found for name: ${r}`),{...t,status:"no_such_server"};t.databasePort=s.databasePort,t.exports=s.exports,t.pid=s.pid,t.port=s.port,t.shadowDatabasePort=s.shadowDatabasePort;let{exports:n,pid:a}=s;if(!M(a,e))return e&&console.debug(`[State] server state for "${r}" has no running process with PID: ${a}`),{...t,status:"not_running"};let i=p(r);try{if(!await H(i,{lockfilePath:u(i,".lock")}))return e&&console.debug(`[State] server state for "${r}" is not locked, indicating it is not running.`),{...t,status:"starting_up"}}catch(F){e&&console.error(`[State] server state for "${r}" failed to check lock:`,F)}if(!n)return{...t,status:"starting_up"};let{http:v}=n,o=await C(v.url).health.$get();if(!o.ok)return e&&console.debug(`[State] server state for "${r}" is not live: ${JSON.stringify(o)}`),{...t,status:"not_running"};let c=await o.json();return c.name!==r?(e&&console.debug(`[State] server state for "${r}" has mismatched health response: ${JSON.stringify(c)}`),{...t,status:"unknown"}):(e&&console.debug(`[State] server state for "${r}" is live: ${JSON.stringify(c)}`),{...t,status:"running"})}catch(s){return e&&console.error(`[State] failed to get server status for "${r}":`,s),{...t,status:"error"}}}var w=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},x=class extends w{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return d.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};export{d as a,w as b,x as c};
@@ -1,7 +1,9 @@
1
1
  import * as url from 'url';
2
2
  import { SockDaemonClient } from 'sock-daemon/client';
3
- import { S as ServerOptions, a as Server } from '../db-B1_DGnTu.cjs';
3
+ import { Server } from '../index.cjs';
4
+ import { ServerOptions } from '../state.cjs';
4
5
  import { MessageBase } from 'sock-daemon/server';
6
+ import '../db.cjs';
5
7
  import '@electric-sql/pglite';
6
8
  import 'valibot';
7
9
 
@@ -1,7 +1,9 @@
1
1
  import * as url from 'url';
2
2
  import { SockDaemonClient } from 'sock-daemon/client';
3
- import { S as ServerOptions, a as Server } from '../db-B1_DGnTu.js';
3
+ import { Server } from '../index.js';
4
+ import { ServerOptions } from '../state.js';
4
5
  import { MessageBase } from 'sock-daemon/server';
6
+ import '../db.js';
5
7
  import '@electric-sql/pglite';
6
8
  import 'valibot';
7
9
 
package/dist/db.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var j=Object.create;var p=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var N=Object.getOwnPropertyNames;var F=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty;var k=(e,t)=>{for(var n in t)p(e,n,{get:t[n],enumerable:!0})},A=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of N(t))!G.call(e,s)&&s!==n&&p(e,s,{get:()=>t[s],enumerable:!(i=C(t,s))||i.enumerable});return e};var f=(e,t,n)=>(n=e!=null?j(F(e)):{},A(t||!e||!e.__esModule?p(n,"default",{value:e,enumerable:!0}):n,e)),M=e=>A(p({},"__esModule",{value:!0}),e);var q={};k(q,{dumpDB:()=>L,startDBServer:()=>Q});module.exports=M(q);var v=require("@electric-sql/pglite"),$=require("@electric-sql/pglite-socket"),x=require("pathe/utils");var D=require("fs"),m=require("fs/promises");var r=f(require("path"),1),S=f(require("os"),1),b=f(require("process"),1),u=S.default.homedir(),w=S.default.tmpdir(),{env:g}=b.default,I=e=>{let t=r.default.join(u,"Library");return{data:r.default.join(t,"Application Support",e),config:r.default.join(t,"Preferences",e),cache:r.default.join(t,"Caches",e),log:r.default.join(t,"Logs",e),temp:r.default.join(w,e)}},U=e=>{let t=g.APPDATA||r.default.join(u,"AppData","Roaming"),n=g.LOCALAPPDATA||r.default.join(u,"AppData","Local");return{data:r.default.join(n,e,"Data"),config:r.default.join(t,e,"Config"),cache:r.default.join(n,e,"Cache"),log:r.default.join(n,e,"Log"),temp:r.default.join(w,e)}},H=e=>{let t=r.default.basename(u);return{data:r.default.join(g.XDG_DATA_HOME||r.default.join(u,".local","share"),e),config:r.default.join(g.XDG_CONFIG_HOME||r.default.join(u,".config"),e),cache:r.default.join(g.XDG_CACHE_HOME||r.default.join(u,".cache"),e),log:r.default.join(g.XDG_STATE_HOME||r.default.join(u,".local","state"),e),temp:r.default.join(w,t,e)}};function h(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),b.default.platform==="darwin"?I(e):b.default.platform==="win32"?U(e):H(e)}var W=require("pako"),ee=h("prisma-dev");async function _(e,t){await e.stream().pipeTo(D.WriteStream.toWeb((0,D.createWriteStream)(t,{encoding:"utf-8"})))}var P=class extends Error{constructor(n,i){super(`Port number \`${n}\` is not available for service ${i}.`);this.port=n;this.service=i}name="PortNotAvailableError"};var a={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},X=`postgres://${a.username}:${a.password}@localhost`,O=new URLSearchParams({sslmode:a.sslMode}),J=new URLSearchParams({...Object.fromEntries(O.entries()),connection_limit:String(a.connectionLimit),connect_timeout:String(a.connectTimeout),max_idle_connection_lifetime:String(a.maxIdleConnectionLifetime),pool_timeout:String(a.poolTimeout),single_use_connections:"true",socket_timeout:String(a.socketTimeout)});async function Q(e,t){let n=e==="database"?t.databasePort:t.shadowDatabasePort;if(t.dryRun)return E(e,t,{db:null,port:n,server:null});let{debug:i}=t,d=await(e==="shadow_database"?Y:B)(t.pgliteDataDirPath,i);i&&d.onNotification((o,c)=>{console.debug(`[${e}][${o}] ${c}`)});let l=new $.PGLiteSocketServer({db:d,debug:i,inspect:i,port:n});i&&(l.addEventListener("listening",o=>{let{detail:c}=o;console.debug(`[${e}] server listening on ${JSON.stringify(c)}`)}),l.addEventListener("connection",o=>{let{clientAddress:c,clientPort:R}=o.detail;console.debug(`[${e}] client connected from ${c}:${R}`)}),l.addEventListener("error",o=>{let{detail:c}=o;console.error(`[${e}] server error:`,c)}));try{await l.start()}catch(o){throw o instanceof Error&&"code"in o&&o.code==="EADDRINUSE"?new P(n,e):o}return E(e,t,{db:d,port:n,server:l})}function E(e,t,n){let{debug:i}=t,{db:s,port:d,server:l}=n||{};return i&&console.debug(`[${e}] server started on port ${d}`),{...a,close:async()=>{let o=[];try{await l?.stop(),i&&console.debug(`[${e}] server stopped on port ${d}`)}catch(c){console.error(`[${e}] server stop error`,c),o.push(c)}if(e==="database")try{await s?.syncToFs(),i&&console.debug(`[${e}] synced to filesystem`)}catch(c){console.error(`[${e}] sync error`,c),o.push(c)}try{await s?.close(),i&&console.debug(`[${e}] closed`)}catch(c){console.error(`[${e}] close error`,c),o.push(c)}if(o.length>0)throw new AggregateError(o,`Failed to close ${e} properly`)},connectionString:T(d,O),dump:async o=>{e==="shadow_database"||!s||await L({db:s,debug:i,destinationPath:o})},port:d,prismaORMConnectionString:T(d,J),terminalCommand:`PGPASSWORD=${a.password} PGSSLMODE=${a.sslMode} psql -h localhost -p ${d} -U ${a.username} -d ${a.database}`}}function T(e,t){return`${X}:${e}/${a.database}?${t.toString()}`}async function B(e,t){return await v.PGlite.create({database:a.database,dataDir:e,debug:t?5:void 0,relaxedDurability:!1,username:a.username})}async function Y(e,t){return await v.PGlite.create({database:a.database,dataDir:"memory://",debug:t?5:void 0,relaxedDurability:!1,username:a.username})}async function L(e){let{dataDir:t,db:n,debug:i,destinationPath:s}=e,d=n||await B(t,i),{pgDump:l}=await import("@electric-sql/pglite-tools/pg_dump"),o=await l({args:["--schema-only"],fileName:s?(0,x.filename)(s):void 0,pg:await d.clone()});return s?(i&&console.debug(`[DB] Dumping database to ${s}`),await _(o,s)):(i&&console.debug("[DB] Dumping database to memory"),await o.text())}0&&(module.exports={dumpDB,startDBServer});
1
+ "use strict";var j=Object.create;var p=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var N=Object.getOwnPropertyNames;var F=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty;var k=(e,t)=>{for(var n in t)p(e,n,{get:t[n],enumerable:!0})},A=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of N(t))!G.call(e,s)&&s!==n&&p(e,s,{get:()=>t[s],enumerable:!(i=C(t,s))||i.enumerable});return e};var f=(e,t,n)=>(n=e!=null?j(F(e)):{},A(t||!e||!e.__esModule?p(n,"default",{value:e,enumerable:!0}):n,e)),M=e=>A(p({},"__esModule",{value:!0}),e);var q={};k(q,{dumpDB:()=>L,startDBServer:()=>Q});module.exports=M(q);var v=require("@electric-sql/pglite"),$=require("@electric-sql/pglite-socket"),x=require("pathe/utils");var D=require("fs"),m=require("fs/promises");var r=f(require("path"),1),w=f(require("os"),1),b=f(require("process"),1),u=w.default.homedir(),S=w.default.tmpdir(),{env:g}=b.default,I=e=>{let t=r.default.join(u,"Library");return{data:r.default.join(t,"Application Support",e),config:r.default.join(t,"Preferences",e),cache:r.default.join(t,"Caches",e),log:r.default.join(t,"Logs",e),temp:r.default.join(S,e)}},U=e=>{let t=g.APPDATA||r.default.join(u,"AppData","Roaming"),n=g.LOCALAPPDATA||r.default.join(u,"AppData","Local");return{data:r.default.join(n,e,"Data"),config:r.default.join(t,e,"Config"),cache:r.default.join(n,e,"Cache"),log:r.default.join(n,e,"Log"),temp:r.default.join(S,e)}},H=e=>{let t=r.default.basename(u);return{data:r.default.join(g.XDG_DATA_HOME||r.default.join(u,".local","share"),e),config:r.default.join(g.XDG_CONFIG_HOME||r.default.join(u,".config"),e),cache:r.default.join(g.XDG_CACHE_HOME||r.default.join(u,".cache"),e),log:r.default.join(g.XDG_STATE_HOME||r.default.join(u,".local","state"),e),temp:r.default.join(S,t,e)}};function h(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),b.default.platform==="darwin"?I(e):b.default.platform==="win32"?U(e):H(e)}var W=require("pako"),ee=h("prisma-dev");async function _(e,t){await e.stream().pipeTo(D.WriteStream.toWeb((0,D.createWriteStream)(t,{encoding:"utf-8"})))}var P=class extends Error{constructor(n,i){super(`Port number \`${n}\` is not available for service ${i}.`);this.port=n;this.service=i}name="PortNotAvailableError"};var a={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},X=`postgres://${a.username}:${a.password}@localhost`,O=new URLSearchParams({sslmode:a.sslMode}),J=new URLSearchParams({...Object.fromEntries(O.entries()),connection_limit:String(a.connectionLimit),connect_timeout:String(a.connectTimeout),max_idle_connection_lifetime:String(a.maxIdleConnectionLifetime),pool_timeout:String(a.poolTimeout),single_use_connections:"true",socket_timeout:String(a.socketTimeout)});async function Q(e,t){let n=e==="database"?t.databasePort:t.shadowDatabasePort;if(t.dryRun)return E(e,t,{db:null,port:n,server:null});let{debug:i}=t,d=await(e==="shadow_database"?Y:B)(t.pgliteDataDirPath,i);i&&d.onNotification((o,c)=>{console.debug(`[${e}][${o}] ${c}`)});let l=new $.PGLiteSocketServer({db:d,debug:i,inspect:i,port:n});i&&(l.addEventListener("listening",o=>{let{detail:c}=o;console.debug(`[${e}] server listening on ${JSON.stringify(c)}`)}),l.addEventListener("connection",o=>{let{clientAddress:c,clientPort:R}=o.detail;console.debug(`[${e}] client connected from ${c}:${R}`)}),l.addEventListener("error",o=>{let{detail:c}=o;console.error(`[${e}] server error:`,c)}));try{await l.start()}catch(o){throw o instanceof Error&&"code"in o&&o.code==="EADDRINUSE"?new P(n,e):o}return E(e,t,{db:d,port:n,server:l})}function E(e,t,n){let{debug:i}=t,{db:s,port:d,server:l}=n||{};return i&&console.debug(`[${e}] server started on port ${d}`),{...a,close:async()=>{let o=[];try{await l?.stop(),i&&console.debug(`[${e}] server stopped on port ${d}`)}catch(c){console.error(`[${e}] server stop error`,c),o.push(c)}if(e==="database")try{await s?.syncToFs(),i&&console.debug(`[${e}] synced to filesystem`)}catch(c){console.error(`[${e}] sync error`,c),o.push(c)}try{await s?.close(),i&&console.debug(`[${e}] closed`)}catch(c){console.error(`[${e}] close error`,c),o.push(c)}if(o.length>0)throw new AggregateError(o,`Failed to close ${e} properly`)},connectionString:T(d,O),dump:async o=>{e==="shadow_database"||!s||await L({db:s,debug:i,destinationPath:o})},port:d,prismaORMConnectionString:T(d,J),terminalCommand:`PGPASSWORD=${a.password} PGSSLMODE=${a.sslMode} psql -h localhost -p ${d} -U ${a.username} -d ${a.database}`}}function T(e,t){return`${X}:${e}/${a.database}?${t.toString()}`}async function B(e,t){return await v.PGlite.create({database:a.database,dataDir:e,debug:t?5:void 0,relaxedDurability:!1,username:a.username})}async function Y(e,t){return await v.PGlite.create({database:a.database,dataDir:"memory://",debug:t?5:void 0,relaxedDurability:!1,username:a.username})}async function L(e){let{dataDir:t,db:n,debug:i,destinationPath:s}=e,d=n||await B(t,i),{pgDump:l}=await import("@electric-sql/pglite-tools/pg_dump"),o=await l({args:["--schema-only","--no-owner"],fileName:s?(0,x.filename)(s):void 0,pg:await d.clone()});return s?(i&&console.debug(`[DB] Dumping database to ${s}`),await _(o,s)):(i&&console.debug("[DB] Dumping database to memory"),await o.text())}0&&(module.exports={dumpDB,startDBServer});
package/dist/db.d.cts CHANGED
@@ -1,3 +1,40 @@
1
- import '@electric-sql/pglite';
2
- export { l as DBDump, k as DBServer, m as DBServerPurpose, n as DumpDBOptions, o as dumpDB, s as startDBServer } from './db-B1_DGnTu.cjs';
1
+ import { PGlite } from '@electric-sql/pglite';
2
+ import { ServerState } from './state.cjs';
3
3
  import 'valibot';
4
+
5
+ interface DBServer {
6
+ close(): Promise<void>;
7
+ readonly connectionLimit: number;
8
+ readonly connectionString: string;
9
+ readonly connectTimeout: number;
10
+ readonly database: string;
11
+ dump(destinationPath: string): Promise<void>;
12
+ readonly maxIdleConnectionLifetime: number;
13
+ readonly password: string;
14
+ readonly poolTimeout: number;
15
+ readonly port: number;
16
+ readonly prismaORMConnectionString: string;
17
+ readonly socketTimeout: number;
18
+ readonly sslMode: string;
19
+ readonly terminalCommand: string;
20
+ readonly username: string;
21
+ }
22
+ interface DBDump {
23
+ dumpPath: string;
24
+ }
25
+ type DBServerPurpose = "database" | "shadow_database";
26
+ declare function startDBServer(purpose: DBServerPurpose, serverState: ServerState): Promise<DBServer>;
27
+ type DumpDBOptions<D extends string> = {
28
+ dataDir: string;
29
+ db?: never;
30
+ debug?: boolean;
31
+ destinationPath?: D;
32
+ } | {
33
+ dataDir?: never;
34
+ db: PGlite;
35
+ debug?: boolean;
36
+ destinationPath?: D;
37
+ };
38
+ declare function dumpDB<D extends string = never>(options: DumpDBOptions<D>): Promise<[D] extends [never] ? string : void>;
39
+
40
+ export { type DBDump, type DBServer, type DBServerPurpose, type DumpDBOptions, dumpDB, startDBServer };
package/dist/db.d.ts CHANGED
@@ -1,3 +1,40 @@
1
- import '@electric-sql/pglite';
2
- export { l as DBDump, k as DBServer, m as DBServerPurpose, n as DumpDBOptions, o as dumpDB, s as startDBServer } from './db-B1_DGnTu.js';
1
+ import { PGlite } from '@electric-sql/pglite';
2
+ import { ServerState } from './state.js';
3
3
  import 'valibot';
4
+
5
+ interface DBServer {
6
+ close(): Promise<void>;
7
+ readonly connectionLimit: number;
8
+ readonly connectionString: string;
9
+ readonly connectTimeout: number;
10
+ readonly database: string;
11
+ dump(destinationPath: string): Promise<void>;
12
+ readonly maxIdleConnectionLifetime: number;
13
+ readonly password: string;
14
+ readonly poolTimeout: number;
15
+ readonly port: number;
16
+ readonly prismaORMConnectionString: string;
17
+ readonly socketTimeout: number;
18
+ readonly sslMode: string;
19
+ readonly terminalCommand: string;
20
+ readonly username: string;
21
+ }
22
+ interface DBDump {
23
+ dumpPath: string;
24
+ }
25
+ type DBServerPurpose = "database" | "shadow_database";
26
+ declare function startDBServer(purpose: DBServerPurpose, serverState: ServerState): Promise<DBServer>;
27
+ type DumpDBOptions<D extends string> = {
28
+ dataDir: string;
29
+ db?: never;
30
+ debug?: boolean;
31
+ destinationPath?: D;
32
+ } | {
33
+ dataDir?: never;
34
+ db: PGlite;
35
+ debug?: boolean;
36
+ destinationPath?: D;
37
+ };
38
+ declare function dumpDB<D extends string = never>(options: DumpDBOptions<D>): Promise<[D] extends [never] ? string : void>;
39
+
40
+ export { type DBDump, type DBServer, type DBServerPurpose, type DumpDBOptions, dumpDB, startDBServer };
package/dist/db.js CHANGED
@@ -1 +1 @@
1
- import{a,b}from"./chunk-U4KQZNBE.js";import"./chunk-Q3M6SQC2.js";export{b as dumpDB,a as startDBServer};
1
+ import{a,b}from"./chunk-GBG44OEG.js";import"./chunk-Q3M6SQC2.js";export{b as dumpDB,a as startDBServer};
package/dist/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
- "use strict";var lt=Object.create;var M=Object.defineProperty;var pt=Object.getOwnPropertyDescriptor;var mt=Object.getOwnPropertyNames;var gt=Object.getPrototypeOf,ft=Object.prototype.hasOwnProperty;var ht=(t,e)=>{for(var r in e)M(t,r,{get:e[r],enumerable:!0})},pe=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of mt(e))!ft.call(t,o)&&o!==r&&M(t,o,{get:()=>e[o],enumerable:!(n=pt(e,o))||n.enumerable});return t};var _=(t,e,r)=>(r=t!=null?lt(gt(t)):{},pe(e||!t||!t.__esModule?M(r,"default",{value:t,enumerable:!0}):r,t)),yt=t=>pe(M({},"__esModule",{value:!0}),t);var Nt={};ht(Nt,{DEFAULT_DATABASE_PORT:()=>Ee,DEFAULT_SERVER_PORT:()=>Ae,DEFAULT_SHADOW_DATABASE_PORT:()=>Re,PortNotAvailableError:()=>D,unstable_startServer:()=>Mt});module.exports=yt(Nt);var v=require("hono/http-exception"),l=require("valibot"),me=/^(postgres|postgresql):\/\//,St=(0,l.pipe)((0,l.string)(),(0,l.parseJson)(),(0,l.object)({databaseUrl:(0,l.pipe)((0,l.string)(),(0,l.url)(),(0,l.regex)(me)),name:(0,l.optional)((0,l.pipe)((0,l.string)(),(0,l.minLength)(1))),shadowDatabaseUrl:(0,l.pipe)((0,l.string)(),(0,l.url)(),(0,l.regex)(me))}));function ge(t){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([[e],[r]])=>e.localeCompare(r)))),"utf8").toString("base64url")}function bt(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:n,success:o}=(0,l.safeParse)(St,e,{abortEarly:!0});return o?[null,n]:[r]}var R=(t,e)=>{let{authorization:r}=t;if(!r)throw new v.HTTPException(401,{message:"Missing API Key"});let[n,o="",s]=r.split(" ");if(n!=="Bearer"||s)throw new v.HTTPException(401,{message:"Invalid API Key"});let[i,a]=bt(o);if(i)throw new v.HTTPException(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:c,name:m,shadowDatabaseUrl:b}=a,{name:w}=e.get("serverState");if(!m)throw new v.HTTPException(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} requires an API Key from a newer version of \`prisma dev\`. Check the "${w}" server's output for the updated \`DATABASE_URL\` value.`});if(m!==w)throw new v.HTTPException(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${w}", but the API Key is for "${m}"`});let{hostname:S,port:j}=new URL(c),{port:Q}=e.get("db"),{hostname:ct,port:ut}=new URL(b),dt=e.get("shadowDBPort");if(S!=="localhost"||Number(j)!==Q||ct!=="localhost"||Number(ut)!==dt)throw new v.HTTPException(401,{message:"Wrong API Key; Check your Prisma schema's `provider.url` value (probably defined in `.env`'s `DATABASE_URL` environment variable) is aligned with `prisma dev`'s output"});return{decodedAPIKey:a}};var Z=require("@electric-sql/pglite"),xe=require("@electric-sql/pglite-socket"),$e=require("pathe/utils");var F=require("fs"),y=require("fs/promises");var p=_(require("path"),1),W=_(require("os"),1),N=_(require("process"),1),P=W.default.homedir(),z=W.default.tmpdir(),{env:O}=N.default,wt=t=>{let e=p.default.join(P,"Library");return{data:p.default.join(e,"Application Support",t),config:p.default.join(e,"Preferences",t),cache:p.default.join(e,"Caches",t),log:p.default.join(e,"Logs",t),temp:p.default.join(z,t)}},Pt=t=>{let e=O.APPDATA||p.default.join(P,"AppData","Roaming"),r=O.LOCALAPPDATA||p.default.join(P,"AppData","Local");return{data:p.default.join(r,t,"Data"),config:p.default.join(e,t,"Config"),cache:p.default.join(r,t,"Cache"),log:p.default.join(r,t,"Log"),temp:p.default.join(z,t)}},vt=t=>{let e=p.default.basename(P);return{data:p.default.join(O.XDG_DATA_HOME||p.default.join(P,".local","share"),t),config:p.default.join(O.XDG_CONFIG_HOME||p.default.join(P,".config"),t),cache:p.default.join(O.XDG_CACHE_HOME||p.default.join(P,".cache"),t),log:p.default.join(O.XDG_STATE_HOME||p.default.join(P,".local","state"),t),temp:p.default.join(z,e,t)}};function X(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),N.default.platform==="darwin"?wt(t):N.default.platform==="win32"?Pt(t):vt(t)}var fe=require("pako"),he=X("prisma-dev");function ye(t,e){return`${he.cache}/engine/${t}/${e}`}function I(t){return`${he.data}/${t}`}async function Se(t){try{return await(0,y.access)(t,y.constants.F_OK),!0}catch(e){if(Y(e))return!1;throw e}}async function be(t,e){let r=(0,fe.inflate)(t);await(0,y.writeFile)(e,r),await(0,y.chmod)(e,"755")}async function we(t,e){await t.stream().pipeTo(F.WriteStream.toWeb((0,F.createWriteStream)(e,{encoding:"utf-8"})))}function Y(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function Pe(t){try{return await(0,y.readFile)(t,{encoding:"utf-8"})}catch(e){if(Y(e))return null;throw e}}async function ve(t){await(0,y.mkdir)(t,{recursive:!0})}async function De(t){try{return(await(0,y.readdir)(t,{withFileTypes:!0})).reduce((r,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&r.push(n.name),r),[])}catch(e){if(Y(e))return[];throw e}}var Ee=51214,Ae=51213,Re=51215,D=class extends Error{constructor(r,n){super(`Port number \`${r}\` is not available for service ${n}.`);this.port=r;this.service=n}name="PortNotAvailableError"};var g={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},Dt=`postgres://${g.username}:${g.password}@localhost`,_e=new URLSearchParams({sslmode:g.sslMode}),Et=new URLSearchParams({...Object.fromEntries(_e.entries()),connection_limit:String(g.connectionLimit),connect_timeout:String(g.connectTimeout),max_idle_connection_lifetime:String(g.maxIdleConnectionLifetime),pool_timeout:String(g.poolTimeout),single_use_connections:"true",socket_timeout:String(g.socketTimeout)});async function ee(t,e){let r=t==="database"?e.databasePort:e.shadowDatabasePort;if(e.dryRun)return Oe(t,e,{db:null,port:r,server:null});let{debug:n}=e,s=await(t==="shadow_database"?At:Ie)(e.pgliteDataDirPath,n);n&&s.onNotification((a,c)=>{console.debug(`[${t}][${a}] ${c}`)});let i=new xe.PGLiteSocketServer({db:s,debug:n,inspect:n,port:r});n&&(i.addEventListener("listening",a=>{let{detail:c}=a;console.debug(`[${t}] server listening on ${JSON.stringify(c)}`)}),i.addEventListener("connection",a=>{let{clientAddress:c,clientPort:m}=a.detail;console.debug(`[${t}] client connected from ${c}:${m}`)}),i.addEventListener("error",a=>{let{detail:c}=a;console.error(`[${t}] server error:`,c)}));try{await i.start()}catch(a){throw a instanceof Error&&"code"in a&&a.code==="EADDRINUSE"?new D(r,t):a}return Oe(t,e,{db:s,port:r,server:i})}function Oe(t,e,r){let{debug:n}=e,{db:o,port:s,server:i}=r||{};return n&&console.debug(`[${t}] server started on port ${s}`),{...g,close:async()=>{let a=[];try{await i?.stop(),n&&console.debug(`[${t}] server stopped on port ${s}`)}catch(c){console.error(`[${t}] server stop error`,c),a.push(c)}if(t==="database")try{await o?.syncToFs(),n&&console.debug(`[${t}] synced to filesystem`)}catch(c){console.error(`[${t}] sync error`,c),a.push(c)}try{await o?.close(),n&&console.debug(`[${t}] closed`)}catch(c){console.error(`[${t}] close error`,c),a.push(c)}if(a.length>0)throw new AggregateError(a,`Failed to close ${t} properly`)},connectionString:Te(s,_e),dump:async a=>{t==="shadow_database"||!o||await Rt({db:o,debug:n,destinationPath:a})},port:s,prismaORMConnectionString:Te(s,Et),terminalCommand:`PGPASSWORD=${g.password} PGSSLMODE=${g.sslMode} psql -h localhost -p ${s} -U ${g.username} -d ${g.database}`}}function Te(t,e){return`${Dt}:${t}/${g.database}?${e.toString()}`}async function Ie(t,e){return await Z.PGlite.create({database:g.database,dataDir:t,debug:e?5:void 0,relaxedDurability:!1,username:g.username})}async function At(t,e){return await Z.PGlite.create({database:g.database,dataDir:"memory://",debug:e?5:void 0,relaxedDurability:!1,username:g.username})}async function Rt(t){let{dataDir:e,db:r,debug:n,destinationPath:o}=t,s=r||await Ie(e,n),{pgDump:i}=await import("@electric-sql/pglite-tools/pg_dump"),a=await i({args:["--schema-only"],fileName:o?(0,$e.filename)(o):void 0,pg:await s.clone()});return o?(n&&console.debug(`[DB] Dumping database to ${o}`),await we(a,o)):(n&&console.debug("[DB] Dumping database to memory"),await a.text())}var ze=require("http"),Xe=require("util"),Ye=require("@hono/node-server"),Ze=_(require("@prisma/get-platform"),1);function U(){let t,e,r=new Promise((s,i)=>{t=s,e=i}),n=s=>{n=o=null,e(s)},o=s=>{o=n=null,t(s)};return{promise:r,reject:s=>n?.(s),resolve:s=>o?.(s)}}var et=require("hono/logger"),oe=require("hono/tiny");var Ke=require("hono/tiny"),$=require("hono/validator");var h=require("valibot"),Ot=(0,h.object)({tags:(0,h.union)([(0,h.pipe)((0,h.array)((0,h.string)()),(0,h.minLength)(1)),(0,h.literal)("all")])});async function Ce(t){let{output:e,success:r}=(0,h.safeParse)(Ot,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var He=require("child_process"),Be=require("events"),Le=require("fs/promises"),je=require("path"),Me=require("timers/promises");var Ne=require("foreground-child/proxy-signals"),Fe=require("std-env");var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Tt,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:xt,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:ke}=Fe.process.env,x=class t{static#r=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let{debug:r}=e,n=`${e.schemaHash}:${e.clientVersion}`;try{let o=t.#r.get(n);if(o)return o;let s=new t(e);return t.#r.set(n,s),r&&console.debug("[Query Engine] starting...",e),await s.start(),r&&console.debug("[Query Engine] started!"),s}finally{t.stopAll(n)}}static async stopAll(e){let n=(await Promise.allSettled(Array.from(t.#r.entries()).filter(([o])=>o!==e).map(async([o,s])=>{try{await s.stop()}finally{t.#r.delete(o)}}))).filter(o=>o.status==="rejected").map(o=>o.reason);if(n.length>0)throw new AggregateError(n,"Failed to stop engines")}async commitTransaction(e,r){return await this.#a(e,r,"commit")}async request(e,r){let{url:n}=await this.start(),o=this.#i(r),s=await fetch(n,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await T.fromResponse(s);return await s.text()}async rollbackTransaction(e,r){return await this.#a(e,r,"rollback")}async startTransaction(e,r){let{url:n}=await this.start(),o=this.#i(r),s=await fetch(`${n}/transaction/start`,{body:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await T.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:r,resolve:n}=U();this.#t=e;let o=xt||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=(0,He.spawn)(o,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});(0,Ne.proxySignals)(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let i=m=>{let b=m.split(`
2
- `).find(Q=>Q.includes("Started query engine http server"));if(!b)return;s.stdout.removeListener("data",i);let{fields:w}=JSON.parse(b);if(w==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${m}`));let{ip:S,port:j}=w;if(S==null||j==null)return r(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
3
- Received data: ${m}`));n({childProcess:s,url:`http://${S}:${j}`})},a=m=>{this.#t=null,r(new C(String(m))),s.removeListener("exit",c),s.kill()};s.once("error",a);let c=(m,b)=>{this.#t=null,r(new C(`Query Engine exited with code ${m} and signal ${b}`))};return s.once("exit",c),s.stdout.on("data",i),this.#e.debug&&(s.stderr.on("data",console.error.bind(console,"[Query Engine]")),s.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:e}=await this.#t;e.exitCode==null&&e.signalCode==null&&(this.#t=null,e.kill(),await(0,Be.once)(e,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#n();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let r=ye(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,Le.mkdir)(r,{recursive:!0});let{platform:n}=this.#e.platform,o=n==="windows"?".exe":"",s=(0,je.join)(r,`query-engine-${n}${o}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(Tt==="1"||await Se(s)===!1)&&await this.#o({commitHash:e,extension:o,engineBinaryPath:s}),s}async#n(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let n=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!n)throw new Error("Couldn't find engines version in package.json");let o=n.split(".").at(-1);if(!o)throw new Error("Couldn't find commit hash in engines version");return o}async#o(e){let{commitHash:r,extension:n,engineBinaryPath:o}=e,{binaryTarget:s}=this.#e.platform,i=`https://binaries.prisma.sh/all_commits/${r}/${s}/query-engine${n}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",i);let a=await fetch(i);if(!a.ok)throw new Error(`Couldn't download engine. URL: ${i}, status code: ${a.status}`);ke&&await(0,Me.setTimeout)(Number(ke)),await be(await a.arrayBuffer(),o),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",o)}#i(e){let r={};for(let[n,o]of Object.entries(e))o!=null&&(r[n]=o);return r}async#a(e,r,n){let{url:o}=await this.#t,s=this.#i(r),i=await fetch(`${o}/transaction/${e}/${n}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await T.fromResponse(i);try{return await i.json()}catch{return{}}}};function V(t,e){return console.error(t),t instanceof C?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof T?e.text(t.responseBody,t.statusCode):e.body(null,500)}var C=class extends Error{name="EngineStartError"},T=class t extends Error{constructor(r,n,o){super(`${r}: Query Engine response status ${n}, body: ${o}`);this.action=r;this.statusCode=n;this.responseBody=o}name="EngineHttpError";static async fromResponse(r){let n=new URL(r.url),o=await r.text();return new t(n.pathname,r.status,o)}};var te=require("buffer"),G=new Map;async function re(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}function Ue(t){let e=t.req.param("schemaHash"),r=G.get(e);return r==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:r}}var $t=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function Ve(t,e){let r=te.Buffer.from(t,"base64").toString("utf8"),n=`datasource db {
1
+ "use strict";var pt=Object.create;var N=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var gt=Object.getOwnPropertyNames;var ht=Object.getPrototypeOf,ft=Object.prototype.hasOwnProperty;var yt=(t,e)=>{for(var r in e)N(t,r,{get:e[r],enumerable:!0})},me=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of gt(e))!ft.call(t,o)&&o!==r&&N(t,o,{get:()=>e[o],enumerable:!(n=mt(e,o))||n.enumerable});return t};var _=(t,e,r)=>(r=t!=null?pt(ht(t)):{},me(e||!t||!t.__esModule?N(r,"default",{value:t,enumerable:!0}):r,t)),St=t=>me(N({},"__esModule",{value:!0}),t);var Ft={};yt(Ft,{DEFAULT_DATABASE_PORT:()=>Re,DEFAULT_SERVER_PORT:()=>Ae,DEFAULT_SHADOW_DATABASE_PORT:()=>Oe,PortNotAvailableError:()=>E,ServerAlreadyRunningError:()=>L,unstable_startServer:()=>Nt});module.exports=St(Ft);var D=require("hono/http-exception"),l=require("valibot"),ge=/^(postgres|postgresql):\/\//,bt=(0,l.pipe)((0,l.string)(),(0,l.parseJson)(),(0,l.object)({databaseUrl:(0,l.pipe)((0,l.string)(),(0,l.url)(),(0,l.regex)(ge)),name:(0,l.optional)((0,l.pipe)((0,l.string)(),(0,l.minLength)(1))),shadowDatabaseUrl:(0,l.pipe)((0,l.string)(),(0,l.url)(),(0,l.regex)(ge))}));function he(t){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([[e],[r]])=>e.localeCompare(r)))),"utf8").toString("base64url")}function vt(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:n,success:o}=(0,l.safeParse)(bt,e,{abortEarly:!0});return o?[null,n]:[r]}var A=(t,e)=>{let{authorization:r}=t;if(!r)throw new D.HTTPException(401,{message:"Missing API Key"});let[n,o="",s]=r.split(" ");if(n!=="Bearer"||s)throw new D.HTTPException(401,{message:"Invalid API Key"});let[i,a]=vt(o);if(i)throw new D.HTTPException(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:c,name:m,shadowDatabaseUrl:b}=a,{name:v}=e.get("serverState");if(!m)throw new D.HTTPException(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} requires an API Key from a newer version of \`prisma dev\`. Check the "${v}" server's output for the updated \`DATABASE_URL\` value.`});if(m!==v)throw new D.HTTPException(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${v}", but the API Key is for "${m}"`});let{hostname:S,port:M}=new URL(c),{port:W}=e.get("db"),{hostname:dt,port:ut}=new URL(b),lt=e.get("shadowDBPort");if(S!=="localhost"||Number(M)!==W||dt!=="localhost"||Number(ut)!==lt)throw new D.HTTPException(401,{message:"Wrong API Key; Check your Prisma schema's `provider.url` value (probably defined in `.env`'s `DATABASE_URL` environment variable) is aligned with `prisma dev`'s output"});return{decodedAPIKey:a}};var ee=require("@electric-sql/pglite"),$e=require("@electric-sql/pglite-socket"),_e=require("pathe/utils");var U=require("fs"),y=require("fs/promises");var p=_(require("path"),1),z=_(require("os"),1),F=_(require("process"),1),w=z.default.homedir(),X=z.default.tmpdir(),{env:O}=F.default,wt=t=>{let e=p.default.join(w,"Library");return{data:p.default.join(e,"Application Support",t),config:p.default.join(e,"Preferences",t),cache:p.default.join(e,"Caches",t),log:p.default.join(e,"Logs",t),temp:p.default.join(X,t)}},Pt=t=>{let e=O.APPDATA||p.default.join(w,"AppData","Roaming"),r=O.LOCALAPPDATA||p.default.join(w,"AppData","Local");return{data:p.default.join(r,t,"Data"),config:p.default.join(e,t,"Config"),cache:p.default.join(r,t,"Cache"),log:p.default.join(r,t,"Log"),temp:p.default.join(X,t)}},Dt=t=>{let e=p.default.basename(w);return{data:p.default.join(O.XDG_DATA_HOME||p.default.join(w,".local","share"),t),config:p.default.join(O.XDG_CONFIG_HOME||p.default.join(w,".config"),t),cache:p.default.join(O.XDG_CACHE_HOME||p.default.join(w,".cache"),t),log:p.default.join(O.XDG_STATE_HOME||p.default.join(w,".local","state"),t),temp:p.default.join(X,e,t)}};function Y(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),F.default.platform==="darwin"?wt(t):F.default.platform==="win32"?Pt(t):Dt(t)}var fe=require("pako"),ye=Y("prisma-dev");function Se(t,e){return`${ye.cache}/engine/${t}/${e}`}function I(t){return`${ye.data}/${t}`}async function be(t){try{return await(0,y.access)(t,y.constants.F_OK),!0}catch(e){if(Z(e))return!1;throw e}}async function ve(t,e){let r=(0,fe.inflate)(t);await(0,y.writeFile)(e,r),await(0,y.chmod)(e,"755")}async function we(t,e){await t.stream().pipeTo(U.WriteStream.toWeb((0,U.createWriteStream)(e,{encoding:"utf-8"})))}function Z(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function Pe(t){try{return await(0,y.readFile)(t,{encoding:"utf-8"})}catch(e){if(Z(e))return null;throw e}}async function De(t){await(0,y.mkdir)(t,{recursive:!0})}async function Ee(t){try{return(await(0,y.readdir)(t,{withFileTypes:!0})).reduce((r,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&r.push(n.name),r),[])}catch(e){if(Z(e))return[];throw e}}var Re=51214,Ae=51213,Oe=51215,E=class extends Error{constructor(r,n){super(`Port number \`${r}\` is not available for service ${n}.`);this.port=r;this.service=n}name="PortNotAvailableError"};var g={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},Et=`postgres://${g.username}:${g.password}@localhost`,Ie=new URLSearchParams({sslmode:g.sslMode}),Rt=new URLSearchParams({...Object.fromEntries(Ie.entries()),connection_limit:String(g.connectionLimit),connect_timeout:String(g.connectTimeout),max_idle_connection_lifetime:String(g.maxIdleConnectionLifetime),pool_timeout:String(g.poolTimeout),single_use_connections:"true",socket_timeout:String(g.socketTimeout)});async function te(t,e){let r=t==="database"?e.databasePort:e.shadowDatabasePort;if(e.dryRun)return xe(t,e,{db:null,port:r,server:null});let{debug:n}=e,s=await(t==="shadow_database"?At:Ce)(e.pgliteDataDirPath,n);n&&s.onNotification((a,c)=>{console.debug(`[${t}][${a}] ${c}`)});let i=new $e.PGLiteSocketServer({db:s,debug:n,inspect:n,port:r});n&&(i.addEventListener("listening",a=>{let{detail:c}=a;console.debug(`[${t}] server listening on ${JSON.stringify(c)}`)}),i.addEventListener("connection",a=>{let{clientAddress:c,clientPort:m}=a.detail;console.debug(`[${t}] client connected from ${c}:${m}`)}),i.addEventListener("error",a=>{let{detail:c}=a;console.error(`[${t}] server error:`,c)}));try{await i.start()}catch(a){throw a instanceof Error&&"code"in a&&a.code==="EADDRINUSE"?new E(r,t):a}return xe(t,e,{db:s,port:r,server:i})}function xe(t,e,r){let{debug:n}=e,{db:o,port:s,server:i}=r||{};return n&&console.debug(`[${t}] server started on port ${s}`),{...g,close:async()=>{let a=[];try{await i?.stop(),n&&console.debug(`[${t}] server stopped on port ${s}`)}catch(c){console.error(`[${t}] server stop error`,c),a.push(c)}if(t==="database")try{await o?.syncToFs(),n&&console.debug(`[${t}] synced to filesystem`)}catch(c){console.error(`[${t}] sync error`,c),a.push(c)}try{await o?.close(),n&&console.debug(`[${t}] closed`)}catch(c){console.error(`[${t}] close error`,c),a.push(c)}if(a.length>0)throw new AggregateError(a,`Failed to close ${t} properly`)},connectionString:Te(s,Ie),dump:async a=>{t==="shadow_database"||!o||await Ot({db:o,debug:n,destinationPath:a})},port:s,prismaORMConnectionString:Te(s,Rt),terminalCommand:`PGPASSWORD=${g.password} PGSSLMODE=${g.sslMode} psql -h localhost -p ${s} -U ${g.username} -d ${g.database}`}}function Te(t,e){return`${Et}:${t}/${g.database}?${e.toString()}`}async function Ce(t,e){return await ee.PGlite.create({database:g.database,dataDir:t,debug:e?5:void 0,relaxedDurability:!1,username:g.username})}async function At(t,e){return await ee.PGlite.create({database:g.database,dataDir:"memory://",debug:e?5:void 0,relaxedDurability:!1,username:g.username})}async function Ot(t){let{dataDir:e,db:r,debug:n,destinationPath:o}=t,s=r||await Ce(e,n),{pgDump:i}=await import("@electric-sql/pglite-tools/pg_dump"),a=await i({args:["--schema-only","--no-owner"],fileName:o?(0,_e.filename)(o):void 0,pg:await s.clone()});return o?(n&&console.debug(`[DB] Dumping database to ${o}`),await we(a,o)):(n&&console.debug("[DB] Dumping database to memory"),await a.text())}var Xe=require("http"),Ye=require("util"),Ze=require("@hono/node-server"),et=_(require("@prisma/get-platform"),1);function V(t){let e,r,n=new Promise((i,a)=>{e=i,r=a}),o=i=>{o=s=null,r(i),t?.onRejected?.(i),t?.onFulfilled?.()},s=i=>{s=o=null,e(i),t?.onResolved?.(i),t?.onFulfilled?.()};return{isFulfilled:()=>s===o,promise:n,reject:i=>o?.(i),resolve:i=>s?.(i)}}var tt=require("hono/logger"),se=require("hono/tiny");var Je=require("hono/tiny"),$=require("hono/validator");var f=require("valibot"),xt=(0,f.object)({tags:(0,f.union)([(0,f.pipe)((0,f.array)((0,f.string)()),(0,f.minLength)(1)),(0,f.literal)("all")])});async function ke(t){let{output:e,success:r}=(0,f.safeParse)(xt,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var Be=require("child_process"),je=require("events"),Le=require("fs/promises"),Me=require("path"),Ne=require("timers/promises");var Fe=require("foreground-child/proxy-signals"),Ue=require("std-env");var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Tt,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:$t,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:He}=Ue.process.env,T=class t{static#r=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let{debug:r}=e,n=`${e.schemaHash}:${e.clientVersion}`;try{let o=t.#r.get(n);if(o)return o;let s=new t(e);return t.#r.set(n,s),r&&console.debug("[Query Engine] starting...",e),await s.start(),r&&console.debug("[Query Engine] started!"),s}finally{t.stopAll(n)}}static async stopAll(e){let n=(await Promise.allSettled(Array.from(t.#r.entries()).filter(([o])=>o!==e).map(async([o,s])=>{try{await s.stop()}finally{t.#r.delete(o)}}))).filter(o=>o.status==="rejected").map(o=>o.reason);if(n.length>0)throw new AggregateError(n,"Failed to stop engines")}async commitTransaction(e,r){return await this.#a(e,r,"commit")}async request(e,r){let{url:n}=await this.start(),o=this.#i(r),s=await fetch(n,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await x.fromResponse(s);return await s.text()}async rollbackTransaction(e,r){return await this.#a(e,r,"rollback")}async startTransaction(e,r){let{url:n}=await this.start(),o=this.#i(r),s=await fetch(`${n}/transaction/start`,{body:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await x.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:r,resolve:n}=V();this.#t=e;let o=$t||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=(0,Be.spawn)(o,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});(0,Fe.proxySignals)(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let i=m=>{let b=m.split(`
2
+ `).find(W=>W.includes("Started query engine http server"));if(!b)return;s.stdout.removeListener("data",i);let{fields:v}=JSON.parse(b);if(v==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${m}`));let{ip:S,port:M}=v;if(S==null||M==null)return r(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
3
+ Received data: ${m}`));n({childProcess:s,url:`http://${S}:${M}`})},a=m=>{this.#t=null,r(new C(String(m))),s.removeListener("exit",c),s.kill()};s.once("error",a);let c=(m,b)=>{this.#t=null,r(new C(`Query Engine exited with code ${m} and signal ${b}`))};return s.once("exit",c),s.stdout.on("data",i),this.#e.debug&&(s.stderr.on("data",console.error.bind(console,"[Query Engine]")),s.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:e}=await this.#t;e.exitCode==null&&e.signalCode==null&&(this.#t=null,e.kill(),await(0,je.once)(e,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#n();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let r=Se(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,Le.mkdir)(r,{recursive:!0});let{platform:n}=this.#e.platform,o=n==="windows"?".exe":"",s=(0,Me.join)(r,`query-engine-${n}${o}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(Tt==="1"||await be(s)===!1)&&await this.#o({commitHash:e,extension:o,engineBinaryPath:s}),s}async#n(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let n=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!n)throw new Error("Couldn't find engines version in package.json");let o=n.split(".").at(-1);if(!o)throw new Error("Couldn't find commit hash in engines version");return o}async#o(e){let{commitHash:r,extension:n,engineBinaryPath:o}=e,{binaryTarget:s}=this.#e.platform,i=`https://binaries.prisma.sh/all_commits/${r}/${s}/query-engine${n}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",i);let a=await fetch(i);if(!a.ok)throw new Error(`Couldn't download engine. URL: ${i}, status code: ${a.status}`);He&&await(0,Ne.setTimeout)(Number(He)),await ve(await a.arrayBuffer(),o),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",o)}#i(e){let r={};for(let[n,o]of Object.entries(e))o!=null&&(r[n]=o);return r}async#a(e,r,n){let{url:o}=await this.#t,s=this.#i(r),i=await fetch(`${o}/transaction/${e}/${n}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await x.fromResponse(i);try{return await i.json()}catch{return{}}}};function G(t,e){return console.error(t),t instanceof C?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof x?e.text(t.responseBody,t.statusCode):e.body(null,500)}var C=class extends Error{name="EngineStartError"},x=class t extends Error{constructor(r,n,o){super(`${r}: Query Engine response status ${n}, body: ${o}`);this.action=r;this.statusCode=n;this.responseBody=o}name="EngineHttpError";static async fromResponse(r){let n=new URL(r.url),o=await r.text();return new t(n.pathname,r.status,o)}};var re=require("buffer"),q=new Map;async function ne(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}function Ve(t){let e=t.req.param("schemaHash"),r=q.get(e);return r==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:r}}var _t=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function Ge(t,e){let r=re.Buffer.from(t,"base64").toString("utf8"),n=`datasource db {
4
4
  provider = "postgresql"
5
5
  url = "${e.toString()}"
6
- }`,o=r.replace($t,n),s=await re(o);return{base64Override:te.Buffer.from(o,"utf8").toString("base64"),overrideHash:s}}function q(t){let{req:e}=t;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}var d=require("valibot"),_t=(0,d.object)({isolation_level:(0,d.optional)((0,d.string)()),max_wait:(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(0)),timeout:(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(0))});async function Ge(t){let{issues:e,output:r,success:n}=(0,d.safeParse)(_t,await t.req.json(),{abortEarly:!0});return n?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}var It=(0,d.looseObject)({id:(0,d.union)([(0,d.string)(),(0,d.number)()])});function qe(t,e){let{output:r,success:n}=(0,d.safeParse)(It,t);return n?r:e.json({EngineMalfunction:{}},500)}var k=new Ke.Hono;k.post("/invalidate",(0,$.validator)("header",R),async t=>{let e=await Ce(t);return e instanceof Response?e:t.body(null)});var Ct="/:clientVersion/:schemaHash",H=k.basePath(Ct);k.route("/",H);var kt=["/graphql","/itx/:transactionId/graphql"];H.on("POST",[...kt],(0,$.validator)("header",R),async t=>{let{req:e}=t;try{let r=await ne(t);if(r instanceof Response)return r;let n=await e.text(),o=e.param("transactionId"),s=await r.request(n,{...q(t),"X-transaction-id":o});return t.text(s)}catch(r){return V(r,t)}});H.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,$.validator)("header",R),async t=>{let{req:e}=t;try{let r=await ne(t);if(r instanceof Response)return r;let o=`${e.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=e.param("transactionId"),i=await r[o](s,q(t));return t.json(i)}catch(r){return V(r,t)}});H.put("/schema",(0,$.validator)("header",R),async t=>{let{req:e}=t,r=await e.text();if(!r)return t.text("Missing schema",400);let n=e.param("schemaHash"),o=G.get(n);if(o==null){if(n!==await re(r))return t.text("Schema hash mismatch",400);let s=await Ve(r,t.get("db").prismaORMConnectionString);return G.set(n,{base64Original:r,...s}),t.text(n)}return r!==o.base64Original?t.text("Schema mismatch",400):t.text(n)});H.post("/transaction/start",(0,$.validator)("header",R),async t=>{let{req:e}=t,r=await Ge(t);if(r instanceof Response)return r;try{let n=await ne(t);if(n instanceof Response)return n;let o=await n.startTransaction(r,q(t)),s=qe(o,t);if(s instanceof Response)return s;let{id:i}=s,a=e.param("clientVersion"),c=t.get("port"),m=t.get("protocol"),b=e.param("schemaHash");return t.json({...o,"data-proxy":{endpoint:`${m}://localhost:${c}/${a}/${b}/itx/${i}`}})}catch(n){return V(n,t)}});async function ne(t){let{req:e}=t,r=Ue(t);if(r instanceof Response)return r;let{base64Override:n,overrideHash:o}=r.schemas;return await x.get({base64Schema:n,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.param("clientVersion"),debug:t.get("debug"),platform:t.get("platform"),schemaHash:o})}var Je=require("hono/tiny"),Qe=require("http-status-codes"),K=new Je.Hono;K.post("/database/dump",async t=>{let e=t.get("db"),r=t.get("serverState");return await e.dump(r.databaseDumpPath),t.json({dumpPath:r.databaseDumpPath},Qe.StatusCodes.CREATED)});var Er=K.get("/health",t=>t.json({name:t.get("serverState").name}));async function tt(t,e){let{port:r}=e;if(e.dryRun)return We(r,null);let n=await Ht(r,t,e),{promise:o,reject:s,resolve:i}=U(),a=(0,Ye.serve)({createServer:ze.createServer,fetch:n.fetch,overrideGlobalObjects:!1,port:r},i);return a.on("error",c=>{if(typeof c=="object"&&"code"in c&&c.code==="EADDRINUSE")return s(new D(r,"server"));console.error("[Accelerate]",c)}),await o,We(r,a)}function We(t,e){return{async close(){e&&await Promise.allSettled([(0,Xe.promisify)(e.close.bind(e))(),x.stopAll()])},port:t,url:`http://localhost:${t}`}}async function Ht(t,e,r){let{debug:n}=r,o=new oe.Hono,s=await Ze.default.getPlatformInfo();return n&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),n&&o.use("*",(0,et.logger)((...i)=>console.log("[Accelerate]",...i))),o.use("*",async(i,a)=>(i.set("db",e),i.set("debug",!!n),i.set("platform",s),i.set("port",t),i.set("protocol","http"),i.set("serverState",r),i.set("shadowDBPort",r.shadowDatabasePort),await a())),o.route("/",se),o}var se=new oe.Hono;se.route("/",k);se.route("/",K);var it=require("fs/promises"),at=require("hono/client"),E=require("pathe"),J=require("proper-lockfile"),L=require("std-env"),u=require("valibot");var rt=require("std-env");function nt(t,e){if(t==null)return!1;try{return rt.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var ce=(0,u.pipe)((0,u.string)(),(0,u.url)()),ot=(0,u.object)({connectionString:ce,prismaORMConnectionString:(0,u.optional)(ce),terminalCommand:(0,u.optional)((0,u.string)())}),st=(0,u.object)({url:ce}),ie=(0,u.pipe)((0,u.number)(),(0,u.integer)(),(0,u.minValue)(1)),Bt=(0,u.object)({database:ot,http:st,ppg:st,shadowDatabase:ot}),Lt=(0,u.object)({databasePort:ie,exports:(0,u.optional)(Bt),name:(0,u.pipe)((0,u.string)(),(0,u.minLength)(1)),pid:(0,u.optional)((0,u.pipe)((0,u.number)(),(0,u.integer)(),(0,u.minValue)(0))),port:ie,shadowDatabasePort:ie,version:(0,u.literal)("1")}),le=Symbol("initialize"),ae="default",A=class{databasePort;debug;dryRun;name;persistenceMode;pid;port;shadowDatabasePort;constructor(e){this.databasePort=e.databasePort??51214,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??ae,this.persistenceMode=e.persistenceMode,this.pid=e.pid??L.process.pid,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new B({...e,pid:L.process.pid}):new ue(e);return await r[le](),r}static async fromServerDump(e){let{debug:r,name:n=ae}=e??{},o=I(n),s=B.getServerDumpPath(o),i=await Pe(s);if(i==null)return r&&console.debug(`[State] No server dump file found at: ${s}`),null;r&&(console.debug(`[State] server dump file found at "${s}":`),console.debug(i));let{issues:a,output:c,success:m}=(0,u.safeParse)((0,u.pipe)((0,u.string)(),(0,u.parseJson)(),Lt),i);if(!m)throw r&&console.debug(`[State] Invalid server dump file at "${s}":
7
- ${JSON.stringify(a,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new B({databasePort:c.databasePort,debug:r,dryRun:!1,name:n,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(e){let{debug:r}=e??{},n=(0,E.join)(I(ae),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let o=await De(n);return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(s=>jt(s,r)))}},ue=class extends A{constructor(e){super({...e,persistenceMode:"stateless",pid:L.process.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[le](){}async close(){}async writeServerDump(){}},B=class t extends A{#r;#e;#t;#s;#n;#o=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=I(this.name),this.#r=(0,E.join)(this.#e,"db_dump.bak"),this.#t=(0,E.join)(this.#e,".pglite"),this.#n=e.serverDump??null,this.#s=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,E.join)(e,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#n?.exports}get pgliteDataDirPath(){return this.#t}async[le](){await ve(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#o=await(0,J.lock)(this.#e,{lockfilePath:(0,E.join)(this.#e,".lock")}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`),await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new de(this.name):e}}async close(){if(this.#o!=null)try{await this.#o(),this.#o=null,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw console.error(`[State] failed to release lock on: ${this.#e}`),e}}async writeServerDump(e){this.#n={name:this.name,version:"1",pid:L.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,it.writeFile)(this.#s,`${JSON.stringify(this.#n,null,2)}
8
- `,{encoding:"utf-8"})}};async function jt(t,e){let r={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let n=await A.fromServerDump({debug:e,name:t});if(!n)return e&&console.debug(`[State] no server state found for name: ${t}`),{...r,status:"no_such_server"};r.databasePort=n.databasePort,r.exports=n.exports,r.pid=n.pid,r.port=n.port,r.shadowDatabasePort=n.shadowDatabasePort;let{exports:o,pid:s}=n;if(!nt(s,e))return e&&console.debug(`[State] server state for "${t}" has no running process with PID: ${s}`),{...r,status:"not_running"};let i=I(t);try{if(!await(0,J.check)(i,{lockfilePath:(0,E.join)(i,".lock")}))return e&&console.debug(`[State] server state for "${t}" is not locked, indicating it is not running.`),{...r,status:"starting_up"}}catch(b){e&&console.error(`[State] server state for "${t}" failed to check lock:`,b)}if(!o)return{...r,status:"starting_up"};let{http:a}=o,c=await(0,at.hc)(a.url).health.$get();if(!c.ok)return e&&console.debug(`[State] server state for "${t}" is not live: ${JSON.stringify(c)}`),{...r,status:"not_running"};let m=await c.json();return m.name!==t?(e&&console.debug(`[State] server state for "${t}" has mismatched health response: ${JSON.stringify(m)}`),{...r,status:"unknown"}):(e&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(m)}`),{...r,status:"running"})}catch(n){return e&&console.error(`[State] failed to get server status for "${t}":`,n),{...r,status:"error"}}}var de=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A server with the name "${e}" is already running.`)}};async function Mt(t){let e=await A.createExclusively(t),[r,n]=await Promise.all([ee("database",e),ee("shadow_database",e)]),o=await tt(r,e),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:ge({databaseUrl:r.prismaORMConnectionString,name:e.name,shadowDatabaseUrl:n.prismaORMConnectionString})}).toString()}`,i={database:{connectionString:r.connectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand},http:{url:o.url},ppg:{url:s},shadowDatabase:{connectionString:n.prismaORMConnectionString,prismaORMConnectionString:n.prismaORMConnectionString,terminalCommand:n.terminalCommand}};return await e.writeServerDump(i),{...i,close:()=>a(e,[o,r,n])};async function a(c,m){let w=(await Promise.allSettled(m.map(S=>S.close()))).filter(S=>S.status==="rejected").map(S=>new Error(S.reason));try{await c.close()}catch(S){w.push(S)}if(w.length>0)throw new AggregateError(w,"Failed to close some servers")}}0&&(module.exports={DEFAULT_DATABASE_PORT,DEFAULT_SERVER_PORT,DEFAULT_SHADOW_DATABASE_PORT,PortNotAvailableError,unstable_startServer});
6
+ }`,o=r.replace(_t,n),s=await ne(o);return{base64Override:re.Buffer.from(o,"utf8").toString("base64"),overrideHash:s}}function K(t){let{req:e}=t;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}var u=require("valibot"),It=(0,u.object)({isolation_level:(0,u.optional)((0,u.string)()),max_wait:(0,u.pipe)((0,u.number)(),(0,u.integer)(),(0,u.minValue)(0)),timeout:(0,u.pipe)((0,u.number)(),(0,u.integer)(),(0,u.minValue)(0))});async function qe(t){let{issues:e,output:r,success:n}=(0,u.safeParse)(It,await t.req.json(),{abortEarly:!0});return n?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}var Ct=(0,u.looseObject)({id:(0,u.union)([(0,u.string)(),(0,u.number)()])});function Ke(t,e){let{output:r,success:n}=(0,u.safeParse)(Ct,t);return n?r:e.json({EngineMalfunction:{}},500)}var k=new Je.Hono;k.post("/invalidate",(0,$.validator)("header",A),async t=>{let e=await ke(t);return e instanceof Response?e:t.body(null)});var kt="/:clientVersion/:schemaHash",H=k.basePath(kt);k.route("/",H);var Ht=["/graphql","/itx/:transactionId/graphql"];H.on("POST",[...Ht],(0,$.validator)("header",A),async t=>{let{req:e}=t;try{let r=await oe(t);if(r instanceof Response)return r;let n=await e.text(),o=e.param("transactionId"),s=await r.request(n,{...K(t),"X-transaction-id":o});return t.text(s)}catch(r){return G(r,t)}});H.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,$.validator)("header",A),async t=>{let{req:e}=t;try{let r=await oe(t);if(r instanceof Response)return r;let o=`${e.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=e.param("transactionId"),i=await r[o](s,K(t));return t.json(i)}catch(r){return G(r,t)}});H.put("/schema",(0,$.validator)("header",A),async t=>{let{req:e}=t,r=await e.text();if(!r)return t.text("Missing schema",400);let n=e.param("schemaHash"),o=q.get(n);if(o==null){if(n!==await ne(r))return t.text("Schema hash mismatch",400);let s=await Ge(r,t.get("db").prismaORMConnectionString);return q.set(n,{base64Original:r,...s}),t.text(n)}return r!==o.base64Original?t.text("Schema mismatch",400):t.text(n)});H.post("/transaction/start",(0,$.validator)("header",A),async t=>{let{req:e}=t,r=await qe(t);if(r instanceof Response)return r;try{let n=await oe(t);if(n instanceof Response)return n;let o=await n.startTransaction(r,K(t)),s=Ke(o,t);if(s instanceof Response)return s;let{id:i}=s,a=e.param("clientVersion"),c=t.get("port"),m=t.get("protocol"),b=e.param("schemaHash");return t.json({...o,"data-proxy":{endpoint:`${m}://localhost:${c}/${a}/${b}/itx/${i}`}})}catch(n){return G(n,t)}});async function oe(t){let{req:e}=t,r=Ve(t);if(r instanceof Response)return r;let{base64Override:n,overrideHash:o}=r.schemas;return await T.get({base64Schema:n,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.param("clientVersion"),debug:t.get("debug"),platform:t.get("platform"),schemaHash:o})}var Qe=require("hono/tiny"),We=require("http-status-codes"),J=new Qe.Hono;J.post("/database/dump",async t=>{let e=t.get("db"),r=t.get("serverState");return await e.dump(r.databaseDumpPath),t.json({dumpPath:r.databaseDumpPath},We.StatusCodes.CREATED)});var Rr=J.get("/health",t=>t.json({name:t.get("serverState").name}));async function rt(t,e){let{port:r}=e;if(e.dryRun)return ze(r,null);let n=await Bt(r,t,e),{promise:o,reject:s,resolve:i}=V(),a=(0,Ze.serve)({createServer:Xe.createServer,fetch:n.fetch,overrideGlobalObjects:!1,port:r},i);return a.on("error",c=>{if(typeof c=="object"&&"code"in c&&c.code==="EADDRINUSE")return s(new E(r,"server"));console.error("[Accelerate]",c)}),await o,ze(r,a)}function ze(t,e){return{async close(){e&&await Promise.allSettled([(0,Ye.promisify)(e.close.bind(e))(),T.stopAll()])},port:t,url:`http://localhost:${t}`}}async function Bt(t,e,r){let{debug:n}=r,o=new se.Hono,s=await et.default.getPlatformInfo();return n&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),n&&o.use("*",(0,tt.logger)((...i)=>console.log("[Accelerate]",...i))),o.use("*",async(i,a)=>(i.set("db",e),i.set("debug",!!n),i.set("platform",s),i.set("port",t),i.set("protocol","http"),i.set("serverState",r),i.set("shadowDBPort",r.shadowDatabasePort),await a())),o.route("/",ie),o}var ie=new se.Hono;ie.route("/",k);ie.route("/",J);var at=require("fs/promises"),ct=require("hono/client"),R=require("pathe"),Q=require("proper-lockfile"),j=require("std-env"),d=require("valibot");var nt=require("std-env");function ot(t,e){if(t==null)return!1;try{return nt.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var de=(0,d.pipe)((0,d.string)(),(0,d.url)()),st=(0,d.object)({connectionString:de,prismaORMConnectionString:(0,d.optional)(de),terminalCommand:(0,d.optional)((0,d.string)())}),it=(0,d.object)({url:de}),ae=(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(1)),jt=(0,d.object)({database:st,http:it,ppg:it,shadowDatabase:st}),Lt=(0,d.object)({databasePort:ae,exports:(0,d.optional)(jt),name:(0,d.pipe)((0,d.string)(),(0,d.minLength)(1)),pid:(0,d.optional)((0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(0))),port:ae,shadowDatabasePort:ae,version:(0,d.literal)("1")}),pe=Symbol("initialize"),ce="default",P=class{databasePort;debug;dryRun;name;persistenceMode;pid;port;shadowDatabasePort;constructor(e){this.databasePort=e.databasePort??51214,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??ce,this.persistenceMode=e.persistenceMode,this.pid=e.pid??j.process.pid,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new B({...e,pid:j.process.pid}):new ue(e);return await r[pe](),r}static async fromServerDump(e){let{debug:r,name:n=ce}=e??{},o=I(n),s=B.getServerDumpPath(o),i=await Pe(s);if(i==null)return r&&console.debug(`[State] No server dump file found at: ${s}`),null;r&&(console.debug(`[State] server dump file found at "${s}":`),console.debug(i));let{issues:a,output:c,success:m}=(0,d.safeParse)((0,d.pipe)((0,d.string)(),(0,d.parseJson)(),Lt),i);if(!m)throw r&&console.debug(`[State] Invalid server dump file at "${s}":
7
+ ${JSON.stringify(a,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new B({databasePort:c.databasePort,debug:r,dryRun:!1,name:n,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(e){let{debug:r}=e??{},n=(0,R.join)(I(ce),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let o=await Ee(n);return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(s=>Mt(s,r)))}},ue=class extends P{constructor(e){super({...e,persistenceMode:"stateless",pid:j.process.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[pe](){}async close(){}async writeServerDump(){}},B=class t extends P{#r;#e;#t;#s;#n;#o=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=I(this.name),this.#r=(0,R.join)(this.#e,"db_dump.bak"),this.#t=(0,R.join)(this.#e,".pglite"),this.#n=e.serverDump??null,this.#s=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,R.join)(e,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#n?.exports}get pgliteDataDirPath(){return this.#t}async[pe](){await De(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#o=await(0,Q.lock)(this.#e,{lockfilePath:(0,R.join)(this.#e,".lock")}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`),await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new L(this):e}}async close(){if(this.#o!=null)try{await this.#o(),this.#o=null,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw console.error(`[State] failed to release lock on: ${this.#e}`),e}}async writeServerDump(e){this.#n={name:this.name,version:"1",pid:j.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,at.writeFile)(this.#s,`${JSON.stringify(this.#n,null,2)}
8
+ `,{encoding:"utf-8"})}};async function Mt(t,e){let r={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let n=await P.fromServerDump({debug:e,name:t});if(!n)return e&&console.debug(`[State] no server state found for name: ${t}`),{...r,status:"no_such_server"};r.databasePort=n.databasePort,r.exports=n.exports,r.pid=n.pid,r.port=n.port,r.shadowDatabasePort=n.shadowDatabasePort;let{exports:o,pid:s}=n;if(!ot(s,e))return e&&console.debug(`[State] server state for "${t}" has no running process with PID: ${s}`),{...r,status:"not_running"};let i=I(t);try{if(!await(0,Q.check)(i,{lockfilePath:(0,R.join)(i,".lock")}))return e&&console.debug(`[State] server state for "${t}" is not locked, indicating it is not running.`),{...r,status:"starting_up"}}catch(b){e&&console.error(`[State] server state for "${t}" failed to check lock:`,b)}if(!o)return{...r,status:"starting_up"};let{http:a}=o,c=await(0,ct.hc)(a.url).health.$get();if(!c.ok)return e&&console.debug(`[State] server state for "${t}" is not live: ${JSON.stringify(c)}`),{...r,status:"not_running"};let m=await c.json();return m.name!==t?(e&&console.debug(`[State] server state for "${t}" has mismatched health response: ${JSON.stringify(m)}`),{...r,status:"unknown"}):(e&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(m)}`),{...r,status:"running"})}catch(n){return e&&console.error(`[State] failed to get server status for "${t}":`,n),{...r,status:"error"}}}var le=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},L=class extends le{#r;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#r=e}get server(){return P.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};async function Nt(t){let e=await P.createExclusively(t),[r,n]=await Promise.all([te("database",e),te("shadow_database",e)]),o=await rt(r,e),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:he({databaseUrl:r.prismaORMConnectionString,name:e.name,shadowDatabaseUrl:n.prismaORMConnectionString})}).toString()}`,i={database:{connectionString:r.connectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand},http:{url:o.url},ppg:{url:s},shadowDatabase:{connectionString:n.prismaORMConnectionString,prismaORMConnectionString:n.prismaORMConnectionString,terminalCommand:n.terminalCommand}};return await e.writeServerDump(i),{...i,close:()=>a(e,[o,r,n]),name:e.name};async function a(c,m){let v=(await Promise.allSettled(m.map(S=>S.close()))).filter(S=>S.status==="rejected").map(S=>new Error(S.reason));try{await c.close()}catch(S){v.push(S)}if(v.length>0)throw new AggregateError(v,"Failed to close some servers")}}0&&(module.exports={DEFAULT_DATABASE_PORT,DEFAULT_SERVER_PORT,DEFAULT_SHADOW_DATABASE_PORT,PortNotAvailableError,ServerAlreadyRunningError,unstable_startServer});
package/dist/index.d.cts CHANGED
@@ -1,3 +1,25 @@
1
- export { D as DEFAULT_DATABASE_PORT, b as DEFAULT_SERVER_PORT, c as DEFAULT_SHADOW_DATABASE_PORT, P as PortAssignableService, d as PortNotAvailableError, a as Server, u as unstable_startServer } from './db-B1_DGnTu.cjs';
2
- import '@electric-sql/pglite';
1
+ import { Exports, ServerOptions } from './state.cjs';
2
+ export { ServerAlreadyRunningError } from './state.cjs';
3
+ import { DBServerPurpose } from './db.cjs';
3
4
  import 'valibot';
5
+ import '@electric-sql/pglite';
6
+
7
+ declare const DEFAULT_DATABASE_PORT = 51214;
8
+ declare const DEFAULT_SERVER_PORT = 51213;
9
+ declare const DEFAULT_SHADOW_DATABASE_PORT = 51215;
10
+ type PortAssignableService = DBServerPurpose | "server";
11
+ declare class PortNotAvailableError extends Error {
12
+ port: number;
13
+ service: PortAssignableService;
14
+ name: string;
15
+ constructor(port: number, service: PortAssignableService);
16
+ }
17
+
18
+ interface Server extends Exports {
19
+ close(): Promise<void>;
20
+ name: string;
21
+ }
22
+ type ReadonlyServer = Omit<Server, "close">;
23
+ declare function unstable_startServer(options?: ServerOptions): Promise<Server>;
24
+
25
+ export { DEFAULT_DATABASE_PORT, DEFAULT_SERVER_PORT, DEFAULT_SHADOW_DATABASE_PORT, type PortAssignableService, PortNotAvailableError, type ReadonlyServer, type Server, ServerOptions, unstable_startServer };
package/dist/index.d.ts CHANGED
@@ -1,3 +1,25 @@
1
- export { D as DEFAULT_DATABASE_PORT, b as DEFAULT_SERVER_PORT, c as DEFAULT_SHADOW_DATABASE_PORT, P as PortAssignableService, d as PortNotAvailableError, a as Server, u as unstable_startServer } from './db-B1_DGnTu.js';
2
- import '@electric-sql/pglite';
1
+ import { Exports, ServerOptions } from './state.js';
2
+ export { ServerAlreadyRunningError } from './state.js';
3
+ import { DBServerPurpose } from './db.js';
3
4
  import 'valibot';
5
+ import '@electric-sql/pglite';
6
+
7
+ declare const DEFAULT_DATABASE_PORT = 51214;
8
+ declare const DEFAULT_SERVER_PORT = 51213;
9
+ declare const DEFAULT_SHADOW_DATABASE_PORT = 51215;
10
+ type PortAssignableService = DBServerPurpose | "server";
11
+ declare class PortNotAvailableError extends Error {
12
+ port: number;
13
+ service: PortAssignableService;
14
+ name: string;
15
+ constructor(port: number, service: PortAssignableService);
16
+ }
17
+
18
+ interface Server extends Exports {
19
+ close(): Promise<void>;
20
+ name: string;
21
+ }
22
+ type ReadonlyServer = Omit<Server, "close">;
23
+ declare function unstable_startServer(options?: ServerOptions): Promise<Server>;
24
+
25
+ export { DEFAULT_DATABASE_PORT, DEFAULT_SERVER_PORT, DEFAULT_SHADOW_DATABASE_PORT, type PortAssignableService, PortNotAvailableError, type ReadonlyServer, type Server, ServerOptions, unstable_startServer };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import{a as k}from"./chunk-U4KQZNBE.js";import{a as q}from"./chunk-4M2BYKUR.js";import{a as B,c as L,d as M,i as Ze,j as et,k as tt,l as N}from"./chunk-Q3M6SQC2.js";import{HTTPException as h}from"hono/http-exception";import{minLength as ue,object as me,optional as le,parseJson as de,pipe as R,regex as K,safeParse as ge,string as T,url as U}from"valibot";var V=/^(postgres|postgresql):\/\//,he=R(T(),de(),me({databaseUrl:R(T(),U(),K(V)),name:le(R(T(),ue(1))),shadowDatabaseUrl:R(T(),U(),K(V))}));function Q(n){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(n).sort(([[e],[t]])=>e.localeCompare(t)))),"utf8").toString("base64url")}function fe(n){let e=Buffer.from(n,"base64url").toString("utf8"),{issues:t,output:r,success:o}=ge(he,e,{abortEarly:!0});return o?[null,r]:[t]}var f=(n,e)=>{let{authorization:t}=n;if(!t)throw new h(401,{message:"Missing API Key"});let[r,o="",s]=t.split(" ");if(r!=="Bearer"||s)throw new h(401,{message:"Invalid API Key"});let[a,i]=fe(o);if(a)throw new h(401,{message:"Invalid API Key",cause:a.join(", ")});let{databaseUrl:p,name:c,shadowDatabaseUrl:g}=i,{name:m}=e.get("serverState");if(!c)throw new h(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} requires an API Key from a newer version of \`prisma dev\`. Check the "${m}" server's output for the updated \`DATABASE_URL\` value.`});if(c!==m)throw new h(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${m}", but the API Key is for "${c}"`});let{hostname:u,port:E}=new URL(p),{port:x}=e.get("db"),{hostname:ie,port:ce}=new URL(g),pe=e.get("shadowDBPort");if(u!=="localhost"||Number(E)!==x||ie!=="localhost"||Number(ce)!==pe)throw new h(401,{message:"Wrong API Key; Check your Prisma schema's `provider.url` value (probably defined in `.env`'s `DATABASE_URL` environment variable) is aligned with `prisma dev`'s output"});return{decodedAPIKey:i}};import{createServer as ze}from"http";import{promisify as Ge}from"util";import{serve as Je}from"@hono/node-server";import We from"@prisma/get-platform";function A(){let n,e,t=new Promise((s,a)=>{n=s,e=a}),r=s=>{r=o=null,e(s)},o=s=>{o=r=null,n(s)};return{promise:t,reject:s=>r?.(s),resolve:s=>o?.(s)}}import{logger as Xe}from"hono/logger";import{Hono as se}from"hono/tiny";import{Hono as Ke}from"hono/tiny";import{validator as v}from"hono/validator";import{array as ye,literal as we,minLength as Se,object as ve,pipe as be,safeParse as Pe,string as Ee,union as Re}from"valibot";var Te=ve({tags:Re([be(ye(Ee()),Se(1)),we("all")])});async function F(n){let{output:e,success:t}=Pe(Te,await n.req.json(),{abortEarly:!0});return t?e:n.text("Invalid input",400)}import{spawn as Ae}from"child_process";import{once as Oe}from"events";import{mkdir as He}from"fs/promises";import{join as Ce}from"path";import{setTimeout as Ie}from"timers/promises";import{proxySignals as xe}from"foreground-child/proxy-signals";import{process as ke}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:$e,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:De,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:z}=ke.env,w=class n{static#n=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let{debug:t}=e,r=`${e.schemaHash}:${e.clientVersion}`;try{let o=n.#n.get(r);if(o)return o;let s=new n(e);return n.#n.set(r,s),t&&console.debug("[Query Engine] starting...",e),await s.start(),t&&console.debug("[Query Engine] started!"),s}finally{n.stopAll(r)}}static async stopAll(e){let r=(await Promise.allSettled(Array.from(n.#n.entries()).filter(([o])=>o!==e).map(async([o,s])=>{try{await s.stop()}finally{n.#n.delete(o)}}))).filter(o=>o.status==="rejected").map(o=>o.reason);if(r.length>0)throw new AggregateError(r,"Failed to stop engines")}async commitTransaction(e,t){return await this.#o(e,t,"commit")}async request(e,t){let{url:r}=await this.start(),o=this.#r(t),s=await fetch(r,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await y.fromResponse(s);return await s.text()}async rollbackTransaction(e,t){return await this.#o(e,t,"rollback")}async startTransaction(e,t){let{url:r}=await this.start(),o=this.#r(t),s=await fetch(`${r}/transaction/start`,{body:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await y.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:t,resolve:r}=A();this.#t=e;let o=De||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=Ae(o,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});xe(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let a=c=>{let g=c.split(`
2
- `).find(x=>x.includes("Started query engine http server"));if(!g)return;s.stdout.removeListener("data",a);let{fields:m}=JSON.parse(g);if(m==null)return t(new Error(`Unexpected data during initialization, "fields" are missing: ${c}`));let{ip:u,port:E}=m;if(u==null||E==null)return t(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
3
- Received data: ${c}`));r({childProcess:s,url:`http://${u}:${E}`})},i=c=>{this.#t=null,t(new S(String(c))),s.removeListener("exit",p),s.kill()};s.once("error",i);let p=(c,g)=>{this.#t=null,t(new S(`Query Engine exited with code ${c} and signal ${g}`))};return s.once("exit",p),s.stdout.on("data",a),this.#e.debug&&(s.stderr.on("data",console.error.bind(console,"[Query Engine]")),s.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:e}=await this.#t;e.exitCode==null&&e.signalCode==null&&(this.#t=null,e.kill(),await Oe(e,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#a();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let t=B(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",t),await He(t,{recursive:!0});let{platform:r}=this.#e.platform,o=r==="windows"?".exe":"",s=Ce(t,`query-engine-${r}${o}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),($e==="1"||await L(s)===!1)&&await this.#i({commitHash:e,extension:o,engineBinaryPath:s}),s}async#a(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let r=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!r)throw new Error("Couldn't find engines version in package.json");let o=r.split(".").at(-1);if(!o)throw new Error("Couldn't find commit hash in engines version");return o}async#i(e){let{commitHash:t,extension:r,engineBinaryPath:o}=e,{binaryTarget:s}=this.#e.platform,a=`https://binaries.prisma.sh/all_commits/${t}/${s}/query-engine${r}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",a);let i=await fetch(a);if(!i.ok)throw new Error(`Couldn't download engine. URL: ${a}, status code: ${i.status}`);z&&await Ie(Number(z)),await M(await i.arrayBuffer(),o),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",o)}#r(e){let t={};for(let[r,o]of Object.entries(e))o!=null&&(t[r]=o);return t}async#o(e,t,r){let{url:o}=await this.#t,s=this.#r(t),a=await fetch(`${o}/transaction/${e}/${r}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!a.ok)throw await y.fromResponse(a);try{return await a.json()}catch{return{}}}};function O(n,e){return console.error(n),n instanceof S?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:n.message}}}},500):n instanceof y?e.text(n.responseBody,n.statusCode):e.body(null,500)}var S=class extends Error{name="EngineStartError"},y=class n extends Error{constructor(t,r,o){super(`${t}: Query Engine response status ${r}, body: ${o}`);this.action=t;this.statusCode=r;this.responseBody=o}name="EngineHttpError";static async fromResponse(t){let r=new URL(t.url),o=await t.text();return new n(r.pathname,t.status,o)}};import{Buffer as G}from"buffer";var H=new Map;async function $(n){let t=new TextEncoder().encode(n),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(a=>a.toString(16).padStart(2,"0")).join("")}function J(n){let e=n.req.param("schemaHash"),t=H.get(e);return t==null?n.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:t}}var _e=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function W(n,e){let t=G.from(n,"base64").toString("utf8"),r=`datasource db {
1
+ import{a as k}from"./chunk-GBG44OEG.js";import{a as q,c as le}from"./chunk-LBY4H4LD.js";import{a as B,c as L,d as M,i as et,j as tt,k as nt,l as N}from"./chunk-Q3M6SQC2.js";import{HTTPException as h}from"hono/http-exception";import{minLength as ue,object as me,optional as de,parseJson as ge,pipe as R,regex as K,safeParse as he,string as T,url as U}from"valibot";var V=/^(postgres|postgresql):\/\//,fe=R(T(),ge(),me({databaseUrl:R(T(),U(),K(V)),name:de(R(T(),ue(1))),shadowDatabaseUrl:R(T(),U(),K(V))}));function F(n){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(n).sort(([[e],[t]])=>e.localeCompare(t)))),"utf8").toString("base64url")}function ye(n){let e=Buffer.from(n,"base64url").toString("utf8"),{issues:t,output:r,success:o}=he(fe,e,{abortEarly:!0});return o?[null,r]:[t]}var f=(n,e)=>{let{authorization:t}=n;if(!t)throw new h(401,{message:"Missing API Key"});let[r,o="",s]=t.split(" ");if(r!=="Bearer"||s)throw new h(401,{message:"Invalid API Key"});let[i,a]=ye(o);if(i)throw new h(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:p,name:c,shadowDatabaseUrl:g}=a,{name:u}=e.get("serverState");if(!c)throw new h(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} requires an API Key from a newer version of \`prisma dev\`. Check the "${u}" server's output for the updated \`DATABASE_URL\` value.`});if(c!==u)throw new h(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${u}", but the API Key is for "${c}"`});let{hostname:l,port:E}=new URL(p),{port:x}=e.get("db"),{hostname:ae,port:ce}=new URL(g),pe=e.get("shadowDBPort");if(l!=="localhost"||Number(E)!==x||ae!=="localhost"||Number(ce)!==pe)throw new h(401,{message:"Wrong API Key; Check your Prisma schema's `provider.url` value (probably defined in `.env`'s `DATABASE_URL` environment variable) is aligned with `prisma dev`'s output"});return{decodedAPIKey:a}};import{createServer as Ge}from"http";import{promisify as Je}from"util";import{serve as We}from"@hono/node-server";import Xe from"@prisma/get-platform";function A(n){let e,t,r=new Promise((i,a)=>{e=i,t=a}),o=i=>{o=s=null,t(i),n?.onRejected?.(i),n?.onFulfilled?.()},s=i=>{s=o=null,e(i),n?.onResolved?.(i),n?.onFulfilled?.()};return{isFulfilled:()=>s===o,promise:r,reject:i=>o?.(i),resolve:i=>s?.(i)}}import{logger as Ye}from"hono/logger";import{Hono as se}from"hono/tiny";import{Hono as Ue}from"hono/tiny";import{validator as v}from"hono/validator";import{array as we,literal as Se,minLength as ve,object as be,pipe as Pe,safeParse as Ee,string as Re,union as Te}from"valibot";var Ae=be({tags:Te([Pe(we(Re()),ve(1)),Se("all")])});async function Q(n){let{output:e,success:t}=Ee(Ae,await n.req.json(),{abortEarly:!0});return t?e:n.text("Invalid input",400)}import{spawn as Oe}from"child_process";import{once as He}from"events";import{mkdir as Ce}from"fs/promises";import{join as Ie}from"path";import{setTimeout as xe}from"timers/promises";import{proxySignals as ke}from"foreground-child/proxy-signals";import{process as $e}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:De,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:je,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:z}=$e.env,w=class n{static#n=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let{debug:t}=e,r=`${e.schemaHash}:${e.clientVersion}`;try{let o=n.#n.get(r);if(o)return o;let s=new n(e);return n.#n.set(r,s),t&&console.debug("[Query Engine] starting...",e),await s.start(),t&&console.debug("[Query Engine] started!"),s}finally{n.stopAll(r)}}static async stopAll(e){let r=(await Promise.allSettled(Array.from(n.#n.entries()).filter(([o])=>o!==e).map(async([o,s])=>{try{await s.stop()}finally{n.#n.delete(o)}}))).filter(o=>o.status==="rejected").map(o=>o.reason);if(r.length>0)throw new AggregateError(r,"Failed to stop engines")}async commitTransaction(e,t){return await this.#o(e,t,"commit")}async request(e,t){let{url:r}=await this.start(),o=this.#r(t),s=await fetch(r,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await y.fromResponse(s);return await s.text()}async rollbackTransaction(e,t){return await this.#o(e,t,"rollback")}async startTransaction(e,t){let{url:r}=await this.start(),o=this.#r(t),s=await fetch(`${r}/transaction/start`,{body:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await y.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:t,resolve:r}=A();this.#t=e;let o=je||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=Oe(o,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});ke(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let i=c=>{let g=c.split(`
2
+ `).find(x=>x.includes("Started query engine http server"));if(!g)return;s.stdout.removeListener("data",i);let{fields:u}=JSON.parse(g);if(u==null)return t(new Error(`Unexpected data during initialization, "fields" are missing: ${c}`));let{ip:l,port:E}=u;if(l==null||E==null)return t(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
3
+ Received data: ${c}`));r({childProcess:s,url:`http://${l}:${E}`})},a=c=>{this.#t=null,t(new S(String(c))),s.removeListener("exit",p),s.kill()};s.once("error",a);let p=(c,g)=>{this.#t=null,t(new S(`Query Engine exited with code ${c} and signal ${g}`))};return s.once("exit",p),s.stdout.on("data",i),this.#e.debug&&(s.stderr.on("data",console.error.bind(console,"[Query Engine]")),s.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:e}=await this.#t;e.exitCode==null&&e.signalCode==null&&(this.#t=null,e.kill(),await He(e,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#i();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let t=B(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",t),await Ce(t,{recursive:!0});let{platform:r}=this.#e.platform,o=r==="windows"?".exe":"",s=Ie(t,`query-engine-${r}${o}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(De==="1"||await L(s)===!1)&&await this.#a({commitHash:e,extension:o,engineBinaryPath:s}),s}async#i(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let r=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!r)throw new Error("Couldn't find engines version in package.json");let o=r.split(".").at(-1);if(!o)throw new Error("Couldn't find commit hash in engines version");return o}async#a(e){let{commitHash:t,extension:r,engineBinaryPath:o}=e,{binaryTarget:s}=this.#e.platform,i=`https://binaries.prisma.sh/all_commits/${t}/${s}/query-engine${r}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",i);let a=await fetch(i);if(!a.ok)throw new Error(`Couldn't download engine. URL: ${i}, status code: ${a.status}`);z&&await xe(Number(z)),await M(await a.arrayBuffer(),o),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",o)}#r(e){let t={};for(let[r,o]of Object.entries(e))o!=null&&(t[r]=o);return t}async#o(e,t,r){let{url:o}=await this.#t,s=this.#r(t),i=await fetch(`${o}/transaction/${e}/${r}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await y.fromResponse(i);try{return await i.json()}catch{return{}}}};function O(n,e){return console.error(n),n instanceof S?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:n.message}}}},500):n instanceof y?e.text(n.responseBody,n.statusCode):e.body(null,500)}var S=class extends Error{name="EngineStartError"},y=class n extends Error{constructor(t,r,o){super(`${t}: Query Engine response status ${r}, body: ${o}`);this.action=t;this.statusCode=r;this.responseBody=o}name="EngineHttpError";static async fromResponse(t){let r=new URL(t.url),o=await t.text();return new n(r.pathname,t.status,o)}};import{Buffer as G}from"buffer";var H=new Map;async function $(n){let t=new TextEncoder().encode(n),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}function J(n){let e=n.req.param("schemaHash"),t=H.get(e);return t==null?n.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:t}}var _e=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function W(n,e){let t=G.from(n,"base64").toString("utf8"),r=`datasource db {
4
4
  provider = "postgresql"
5
5
  url = "${e.toString()}"
6
- }`,o=t.replace(_e,r),s=await $(o);return{base64Override:G.from(o,"utf8").toString("base64"),overrideHash:s}}function C(n){let{req:e}=n;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}import{integer as X,looseObject as je,minValue as Y,number as D,object as Be,optional as Le,pipe as Z,safeParse as ee,string as te,union as Me}from"valibot";var Ne=Be({isolation_level:Le(te()),max_wait:Z(D(),X(),Y(0)),timeout:Z(D(),X(),Y(0))});async function ne(n){let{issues:e,output:t,success:r}=ee(Ne,await n.req.json(),{abortEarly:!0});return r?t:n.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}var qe=je({id:Me([te(),D()])});function re(n,e){let{output:t,success:r}=ee(qe,n);return r?t:e.json({EngineMalfunction:{}},500)}var b=new Ke;b.post("/invalidate",v("header",f),async n=>{let e=await F(n);return e instanceof Response?e:n.body(null)});var Ue="/:clientVersion/:schemaHash",P=b.basePath(Ue);b.route("/",P);var Ve=["/graphql","/itx/:transactionId/graphql"];P.on("POST",[...Ve],v("header",f),async n=>{let{req:e}=n;try{let t=await _(n);if(t instanceof Response)return t;let r=await e.text(),o=e.param("transactionId"),s=await t.request(r,{...C(n),"X-transaction-id":o});return n.text(s)}catch(t){return O(t,n)}});P.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],v("header",f),async n=>{let{req:e}=n;try{let t=await _(n);if(t instanceof Response)return t;let o=`${e.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=e.param("transactionId"),a=await t[o](s,C(n));return n.json(a)}catch(t){return O(t,n)}});P.put("/schema",v("header",f),async n=>{let{req:e}=n,t=await e.text();if(!t)return n.text("Missing schema",400);let r=e.param("schemaHash"),o=H.get(r);if(o==null){if(r!==await $(t))return n.text("Schema hash mismatch",400);let s=await W(t,n.get("db").prismaORMConnectionString);return H.set(r,{base64Original:t,...s}),n.text(r)}return t!==o.base64Original?n.text("Schema mismatch",400):n.text(r)});P.post("/transaction/start",v("header",f),async n=>{let{req:e}=n,t=await ne(n);if(t instanceof Response)return t;try{let r=await _(n);if(r instanceof Response)return r;let o=await r.startTransaction(t,C(n)),s=re(o,n);if(s instanceof Response)return s;let{id:a}=s,i=e.param("clientVersion"),p=n.get("port"),c=n.get("protocol"),g=e.param("schemaHash");return n.json({...o,"data-proxy":{endpoint:`${c}://localhost:${p}/${i}/${g}/itx/${a}`}})}catch(r){return O(r,n)}});async function _(n){let{req:e}=n,t=J(n);if(t instanceof Response)return t;let{base64Override:r,overrideHash:o}=t.schemas;return await w.get({base64Schema:r,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.param("clientVersion"),debug:n.get("debug"),platform:n.get("platform"),schemaHash:o})}import{Hono as Qe}from"hono/tiny";import{StatusCodes as Fe}from"http-status-codes";var I=new Qe;I.post("/database/dump",async n=>{let e=n.get("db"),t=n.get("serverState");return await e.dump(t.databaseDumpPath),n.json({dumpPath:t.databaseDumpPath},Fe.CREATED)});var Ut=I.get("/health",n=>n.json({name:n.get("serverState").name}));async function ae(n,e){let{port:t}=e;if(e.dryRun)return oe(t,null);let r=await Ye(t,n,e),{promise:o,reject:s,resolve:a}=A(),i=Je({createServer:ze,fetch:r.fetch,overrideGlobalObjects:!1,port:t},a);return i.on("error",p=>{if(typeof p=="object"&&"code"in p&&p.code==="EADDRINUSE")return s(new N(t,"server"));console.error("[Accelerate]",p)}),await o,oe(t,i)}function oe(n,e){return{async close(){e&&await Promise.allSettled([Ge(e.close.bind(e))(),w.stopAll()])},port:n,url:`http://localhost:${n}`}}async function Ye(n,e,t){let{debug:r}=t,o=new se,s=await We.getPlatformInfo();return r&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),r&&o.use("*",Xe((...a)=>console.log("[Accelerate]",...a))),o.use("*",async(a,i)=>(a.set("db",e),a.set("debug",!!r),a.set("platform",s),a.set("port",n),a.set("protocol","http"),a.set("serverState",t),a.set("shadowDBPort",t.shadowDatabasePort),await i())),o.route("/",j),o}var j=new se;j.route("/",b);j.route("/",I);async function un(n){let e=await q.createExclusively(n),[t,r]=await Promise.all([k("database",e),k("shadow_database",e)]),o=await ae(t,e),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:Q({databaseUrl:t.prismaORMConnectionString,name:e.name,shadowDatabaseUrl:r.prismaORMConnectionString})}).toString()}`,a={database:{connectionString:t.connectionString,prismaORMConnectionString:t.prismaORMConnectionString,terminalCommand:t.terminalCommand},http:{url:o.url},ppg:{url:s},shadowDatabase:{connectionString:r.prismaORMConnectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand}};return await e.writeServerDump(a),{...a,close:()=>i(e,[o,t,r])};async function i(p,c){let m=(await Promise.allSettled(c.map(u=>u.close()))).filter(u=>u.status==="rejected").map(u=>new Error(u.reason));try{await p.close()}catch(u){m.push(u)}if(m.length>0)throw new AggregateError(m,"Failed to close some servers")}}export{Ze as DEFAULT_DATABASE_PORT,et as DEFAULT_SERVER_PORT,tt as DEFAULT_SHADOW_DATABASE_PORT,N as PortNotAvailableError,un as unstable_startServer};
6
+ }`,o=t.replace(_e,r),s=await $(o);return{base64Override:G.from(o,"utf8").toString("base64"),overrideHash:s}}function C(n){let{req:e}=n;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}import{integer as X,looseObject as Be,minValue as Y,number as D,object as Le,optional as Me,pipe as Z,safeParse as ee,string as te,union as Ne}from"valibot";var qe=Le({isolation_level:Me(te()),max_wait:Z(D(),X(),Y(0)),timeout:Z(D(),X(),Y(0))});async function ne(n){let{issues:e,output:t,success:r}=ee(qe,await n.req.json(),{abortEarly:!0});return r?t:n.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}var Ke=Be({id:Ne([te(),D()])});function re(n,e){let{output:t,success:r}=ee(Ke,n);return r?t:e.json({EngineMalfunction:{}},500)}var b=new Ue;b.post("/invalidate",v("header",f),async n=>{let e=await Q(n);return e instanceof Response?e:n.body(null)});var Ve="/:clientVersion/:schemaHash",P=b.basePath(Ve);b.route("/",P);var Fe=["/graphql","/itx/:transactionId/graphql"];P.on("POST",[...Fe],v("header",f),async n=>{let{req:e}=n;try{let t=await j(n);if(t instanceof Response)return t;let r=await e.text(),o=e.param("transactionId"),s=await t.request(r,{...C(n),"X-transaction-id":o});return n.text(s)}catch(t){return O(t,n)}});P.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],v("header",f),async n=>{let{req:e}=n;try{let t=await j(n);if(t instanceof Response)return t;let o=`${e.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=e.param("transactionId"),i=await t[o](s,C(n));return n.json(i)}catch(t){return O(t,n)}});P.put("/schema",v("header",f),async n=>{let{req:e}=n,t=await e.text();if(!t)return n.text("Missing schema",400);let r=e.param("schemaHash"),o=H.get(r);if(o==null){if(r!==await $(t))return n.text("Schema hash mismatch",400);let s=await W(t,n.get("db").prismaORMConnectionString);return H.set(r,{base64Original:t,...s}),n.text(r)}return t!==o.base64Original?n.text("Schema mismatch",400):n.text(r)});P.post("/transaction/start",v("header",f),async n=>{let{req:e}=n,t=await ne(n);if(t instanceof Response)return t;try{let r=await j(n);if(r instanceof Response)return r;let o=await r.startTransaction(t,C(n)),s=re(o,n);if(s instanceof Response)return s;let{id:i}=s,a=e.param("clientVersion"),p=n.get("port"),c=n.get("protocol"),g=e.param("schemaHash");return n.json({...o,"data-proxy":{endpoint:`${c}://localhost:${p}/${a}/${g}/itx/${i}`}})}catch(r){return O(r,n)}});async function j(n){let{req:e}=n,t=J(n);if(t instanceof Response)return t;let{base64Override:r,overrideHash:o}=t.schemas;return await w.get({base64Schema:r,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.param("clientVersion"),debug:n.get("debug"),platform:n.get("platform"),schemaHash:o})}import{Hono as Qe}from"hono/tiny";import{StatusCodes as ze}from"http-status-codes";var I=new Qe;I.post("/database/dump",async n=>{let e=n.get("db"),t=n.get("serverState");return await e.dump(t.databaseDumpPath),n.json({dumpPath:t.databaseDumpPath},ze.CREATED)});var Vt=I.get("/health",n=>n.json({name:n.get("serverState").name}));async function ie(n,e){let{port:t}=e;if(e.dryRun)return oe(t,null);let r=await Ze(t,n,e),{promise:o,reject:s,resolve:i}=A(),a=We({createServer:Ge,fetch:r.fetch,overrideGlobalObjects:!1,port:t},i);return a.on("error",p=>{if(typeof p=="object"&&"code"in p&&p.code==="EADDRINUSE")return s(new N(t,"server"));console.error("[Accelerate]",p)}),await o,oe(t,a)}function oe(n,e){return{async close(){e&&await Promise.allSettled([Je(e.close.bind(e))(),w.stopAll()])},port:n,url:`http://localhost:${n}`}}async function Ze(n,e,t){let{debug:r}=t,o=new se,s=await Xe.getPlatformInfo();return r&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),r&&o.use("*",Ye((...i)=>console.log("[Accelerate]",...i))),o.use("*",async(i,a)=>(i.set("db",e),i.set("debug",!!r),i.set("platform",s),i.set("port",n),i.set("protocol","http"),i.set("serverState",t),i.set("shadowDBPort",t.shadowDatabasePort),await a())),o.route("/",_),o}var _=new se;_.route("/",b);_.route("/",I);async function un(n){let e=await q.createExclusively(n),[t,r]=await Promise.all([k("database",e),k("shadow_database",e)]),o=await ie(t,e),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:F({databaseUrl:t.prismaORMConnectionString,name:e.name,shadowDatabaseUrl:r.prismaORMConnectionString})}).toString()}`,i={database:{connectionString:t.connectionString,prismaORMConnectionString:t.prismaORMConnectionString,terminalCommand:t.terminalCommand},http:{url:o.url},ppg:{url:s},shadowDatabase:{connectionString:r.prismaORMConnectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand}};return await e.writeServerDump(i),{...i,close:()=>a(e,[o,t,r]),name:e.name};async function a(p,c){let u=(await Promise.allSettled(c.map(l=>l.close()))).filter(l=>l.status==="rejected").map(l=>new Error(l.reason));try{await p.close()}catch(l){u.push(l)}if(u.length>0)throw new AggregateError(u,"Failed to close some servers")}}export{et as DEFAULT_DATABASE_PORT,tt as DEFAULT_SERVER_PORT,nt as DEFAULT_SHADOW_DATABASE_PORT,N as PortNotAvailableError,le as ServerAlreadyRunningError,un as unstable_startServer};
package/dist/state.cjs CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var X=Object.create;var v=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var Y=Object.getOwnPropertyNames;var Z=Object.getPrototypeOf,q=Object.prototype.hasOwnProperty;var z=(t,e)=>{for(var r in e)v(t,r,{get:e[r],enumerable:!0})},M=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Y(e))!q.call(t,n)&&n!==r&&v(t,n,{get:()=>e[n],enumerable:!(i=K(e,n))||i.enumerable});return t};var A=(t,e,r)=>(r=t!=null?X(Z(t)):{},M(e||!t||!t.__esModule?v(r,"default",{value:t,enumerable:!0}):r,t)),Q=t=>M(v({},"__esModule",{value:!0}),t);var de={};z(de,{ServerState:()=>h,ServerStateAlreadyExistsError:()=>y});module.exports=Q(de);var U=require("fs/promises"),G=require("hono/client"),d=require("pathe"),w=require("proper-lockfile"),b=require("std-env"),s=require("valibot");var L=require("fs"),a=require("fs/promises");var o=A(require("path"),1),E=A(require("os"),1),D=A(require("process"),1),p=E.default.homedir(),O=E.default.tmpdir(),{env:f}=D.default,ee=t=>{let e=o.default.join(p,"Library");return{data:o.default.join(e,"Application Support",t),config:o.default.join(e,"Preferences",t),cache:o.default.join(e,"Caches",t),log:o.default.join(e,"Logs",t),temp:o.default.join(O,t)}},te=t=>{let e=f.APPDATA||o.default.join(p,"AppData","Roaming"),r=f.LOCALAPPDATA||o.default.join(p,"AppData","Local");return{data:o.default.join(r,t,"Data"),config:o.default.join(e,t,"Config"),cache:o.default.join(r,t,"Cache"),log:o.default.join(r,t,"Log"),temp:o.default.join(O,t)}},re=t=>{let e=o.default.basename(p);return{data:o.default.join(f.XDG_DATA_HOME||o.default.join(p,".local","share"),t),config:o.default.join(f.XDG_CONFIG_HOME||o.default.join(p,".config"),t),cache:o.default.join(f.XDG_CACHE_HOME||o.default.join(p,".cache"),t),log:o.default.join(f.XDG_STATE_HOME||o.default.join(p,".local","state"),t),temp:o.default.join(O,e,t)}};function _(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),D.default.platform==="darwin"?ee(t):D.default.platform==="win32"?te(t):re(t)}var se=require("pako"),oe=_("prisma-dev");function g(t){return`${oe.data}/${t}`}function F(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function I(t){try{return await(0,a.readFile)(t,{encoding:"utf-8"})}catch(e){if(F(e))return null;throw e}}async function N(t){await(0,a.mkdir)(t,{recursive:!0})}async function V(t){try{return(await(0,a.readdir)(t,{withFileTypes:!0})).reduce((r,i)=>(i.isDirectory()&&!i.name.startsWith(".")&&r.push(i.name),r),[])}catch(e){if(F(e))return[];throw e}}var C=require("std-env");function B(t,e){if(t==null)return!1;try{return C.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var R=(0,s.pipe)((0,s.string)(),(0,s.url)()),H=(0,s.object)({connectionString:R,prismaORMConnectionString:(0,s.optional)(R),terminalCommand:(0,s.optional)((0,s.string)())}),J=(0,s.object)({url:R}),T=(0,s.pipe)((0,s.number)(),(0,s.integer)(),(0,s.minValue)(1)),ce=(0,s.object)({database:H,http:J,ppg:J,shadowDatabase:H}),ue=(0,s.object)({databasePort:T,exports:(0,s.optional)(ce),name:(0,s.pipe)((0,s.string)(),(0,s.minLength)(1)),pid:(0,s.optional)((0,s.pipe)((0,s.number)(),(0,s.integer)(),(0,s.minValue)(0))),port:T,shadowDatabasePort:T,version:(0,s.literal)("1")}),k=Symbol("initialize"),$="default",h=class{databasePort;debug;dryRun;name;persistenceMode;pid;port;shadowDatabasePort;constructor(e){this.databasePort=e.databasePort??51214,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??$,this.persistenceMode=e.persistenceMode,this.pid=e.pid??b.process.pid,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new P({...e,pid:b.process.pid}):new j(e);return await r[k](),r}static async fromServerDump(e){let{debug:r,name:i=$}=e??{},n=g(i),c=P.getServerDumpPath(n),l=await I(c);if(l==null)return r&&console.debug(`[State] No server dump file found at: ${c}`),null;r&&(console.debug(`[State] server dump file found at "${c}":`),console.debug(l));let{issues:x,output:u,success:m}=(0,s.safeParse)((0,s.pipe)((0,s.string)(),(0,s.parseJson)(),ue),l);if(!m)throw r&&console.debug(`[State] Invalid server dump file at "${c}":
2
- ${JSON.stringify(x,null,2)}`),new Error(`Invalid Prisma Dev state for "${i}".`);return new P({databasePort:u.databasePort,debug:r,dryRun:!1,name:i,pid:u.pid,port:u.port,serverDump:u,shadowDatabasePort:u.shadowDatabasePort})}static async scan(e){let{debug:r}=e??{},i=(0,d.join)(g($),"..");r&&console.debug(`[State] scanning for server states in: ${i}`);let n=await V(i);return r&&console.debug(`[State] found server names: ${JSON.stringify(n)}`),await Promise.all(n.map(c=>pe(c,r)))}},j=class extends h{constructor(e){super({...e,persistenceMode:"stateless",pid:b.process.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[k](){}async close(){}async writeServerDump(){}},P=class t extends h{#s;#e;#o;#i;#t;#r=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=g(this.name),this.#s=(0,d.join)(this.#e,"db_dump.bak"),this.#o=(0,d.join)(this.#e,".pglite"),this.#t=e.serverDump??null,this.#i=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,d.join)(e,"server.json")}get databaseDumpPath(){return this.#s}get exports(){return this.#t?.exports}get pgliteDataDirPath(){return this.#o}async[k](){await N(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#r=await(0,w.lock)(this.#e,{lockfilePath:(0,d.join)(this.#e,".lock")}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`),await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new y(this.name):e}}async close(){if(this.#r!=null)try{await this.#r(),this.#r=null,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw console.error(`[State] failed to release lock on: ${this.#e}`),e}}async writeServerDump(e){this.#t={name:this.name,version:"1",pid:b.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,U.writeFile)(this.#i,`${JSON.stringify(this.#t,null,2)}
3
- `,{encoding:"utf-8"})}};async function pe(t,e){let r={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let i=await h.fromServerDump({debug:e,name:t});if(!i)return e&&console.debug(`[State] no server state found for name: ${t}`),{...r,status:"no_such_server"};r.databasePort=i.databasePort,r.exports=i.exports,r.pid=i.pid,r.port=i.port,r.shadowDatabasePort=i.shadowDatabasePort;let{exports:n,pid:c}=i;if(!B(c,e))return e&&console.debug(`[State] server state for "${t}" has no running process with PID: ${c}`),{...r,status:"not_running"};let l=g(t);try{if(!await(0,w.check)(l,{lockfilePath:(0,d.join)(l,".lock")}))return e&&console.debug(`[State] server state for "${t}" is not locked, indicating it is not running.`),{...r,status:"starting_up"}}catch(W){e&&console.error(`[State] server state for "${t}" failed to check lock:`,W)}if(!n)return{...r,status:"starting_up"};let{http:x}=n,u=await(0,G.hc)(x.url).health.$get();if(!u.ok)return e&&console.debug(`[State] server state for "${t}" is not live: ${JSON.stringify(u)}`),{...r,status:"not_running"};let m=await u.json();return m.name!==t?(e&&console.debug(`[State] server state for "${t}" has mismatched health response: ${JSON.stringify(m)}`),{...r,status:"unknown"}):(e&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(m)}`),{...r,status:"running"})}catch(i){return e&&console.error(`[State] failed to get server status for "${t}":`,i),{...r,status:"error"}}}var y=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A server with the name "${e}" is already running.`)}};0&&(module.exports={ServerState,ServerStateAlreadyExistsError});
1
+ "use strict";var K=Object.create;var b=Object.defineProperty;var Y=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var q=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty;var Q=(t,e)=>{for(var r in e)b(t,r,{get:e[r],enumerable:!0})},L=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Z(e))!z.call(t,n)&&n!==r&&b(t,n,{get:()=>e[n],enumerable:!(i=Y(e,n))||i.enumerable});return t};var E=(t,e,r)=>(r=t!=null?K(q(t)):{},L(e||!t||!t.__esModule?b(r,"default",{value:t,enumerable:!0}):r,t)),ee=t=>L(b({},"__esModule",{value:!0}),t);var le={};Q(le,{ServerAlreadyRunningError:()=>w,ServerState:()=>l,ServerStateAlreadyExistsError:()=>y});module.exports=ee(le);var G=require("fs/promises"),W=require("hono/client"),d=require("pathe"),x=require("proper-lockfile"),v=require("std-env"),s=require("valibot");var F=require("fs"),a=require("fs/promises");var o=E(require("path"),1),O=E(require("os"),1),D=E(require("process"),1),p=O.default.homedir(),_=O.default.tmpdir(),{env:h}=D.default,te=t=>{let e=o.default.join(p,"Library");return{data:o.default.join(e,"Application Support",t),config:o.default.join(e,"Preferences",t),cache:o.default.join(e,"Caches",t),log:o.default.join(e,"Logs",t),temp:o.default.join(_,t)}},re=t=>{let e=h.APPDATA||o.default.join(p,"AppData","Roaming"),r=h.LOCALAPPDATA||o.default.join(p,"AppData","Local");return{data:o.default.join(r,t,"Data"),config:o.default.join(e,t,"Config"),cache:o.default.join(r,t,"Cache"),log:o.default.join(r,t,"Log"),temp:o.default.join(_,t)}},se=t=>{let e=o.default.basename(p);return{data:o.default.join(h.XDG_DATA_HOME||o.default.join(p,".local","share"),t),config:o.default.join(h.XDG_CONFIG_HOME||o.default.join(p,".config"),t),cache:o.default.join(h.XDG_CACHE_HOME||o.default.join(p,".cache"),t),log:o.default.join(h.XDG_STATE_HOME||o.default.join(p,".local","state"),t),temp:o.default.join(_,e,t)}};function T(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),D.default.platform==="darwin"?te(t):D.default.platform==="win32"?re(t):se(t)}var oe=require("pako"),ie=T("prisma-dev");function g(t){return`${ie.data}/${t}`}function I(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function N(t){try{return await(0,a.readFile)(t,{encoding:"utf-8"})}catch(e){if(I(e))return null;throw e}}async function V(t){await(0,a.mkdir)(t,{recursive:!0})}async function C(t){try{return(await(0,a.readdir)(t,{withFileTypes:!0})).reduce((r,i)=>(i.isDirectory()&&!i.name.startsWith(".")&&r.push(i.name),r),[])}catch(e){if(I(e))return[];throw e}}var B=require("std-env");function H(t,e){if(t==null)return!1;try{return B.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var j=(0,s.pipe)((0,s.string)(),(0,s.url)()),J=(0,s.object)({connectionString:j,prismaORMConnectionString:(0,s.optional)(j),terminalCommand:(0,s.optional)((0,s.string)())}),U=(0,s.object)({url:j}),$=(0,s.pipe)((0,s.number)(),(0,s.integer)(),(0,s.minValue)(1)),ue=(0,s.object)({database:J,http:U,ppg:U,shadowDatabase:J}),pe=(0,s.object)({databasePort:$,exports:(0,s.optional)(ue),name:(0,s.pipe)((0,s.string)(),(0,s.minLength)(1)),pid:(0,s.optional)((0,s.pipe)((0,s.number)(),(0,s.integer)(),(0,s.minValue)(0))),port:$,shadowDatabasePort:$,version:(0,s.literal)("1")}),M=Symbol("initialize"),R="default",l=class{databasePort;debug;dryRun;name;persistenceMode;pid;port;shadowDatabasePort;constructor(e){this.databasePort=e.databasePort??51214,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??R,this.persistenceMode=e.persistenceMode,this.pid=e.pid??v.process.pid,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new P({...e,pid:v.process.pid}):new k(e);return await r[M](),r}static async fromServerDump(e){let{debug:r,name:i=R}=e??{},n=g(i),c=P.getServerDumpPath(n),m=await N(c);if(m==null)return r&&console.debug(`[State] No server dump file found at: ${c}`),null;r&&(console.debug(`[State] server dump file found at "${c}":`),console.debug(m));let{issues:A,output:u,success:f}=(0,s.safeParse)((0,s.pipe)((0,s.string)(),(0,s.parseJson)(),pe),m);if(!f)throw r&&console.debug(`[State] Invalid server dump file at "${c}":
2
+ ${JSON.stringify(A,null,2)}`),new Error(`Invalid Prisma Dev state for "${i}".`);return new P({databasePort:u.databasePort,debug:r,dryRun:!1,name:i,pid:u.pid,port:u.port,serverDump:u,shadowDatabasePort:u.shadowDatabasePort})}static async scan(e){let{debug:r}=e??{},i=(0,d.join)(g(R),"..");r&&console.debug(`[State] scanning for server states in: ${i}`);let n=await C(i);return r&&console.debug(`[State] found server names: ${JSON.stringify(n)}`),await Promise.all(n.map(c=>de(c,r)))}},k=class extends l{constructor(e){super({...e,persistenceMode:"stateless",pid:v.process.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[M](){}async close(){}async writeServerDump(){}},P=class t extends l{#t;#e;#o;#i;#r;#s=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=g(this.name),this.#t=(0,d.join)(this.#e,"db_dump.bak"),this.#o=(0,d.join)(this.#e,".pglite"),this.#r=e.serverDump??null,this.#i=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,d.join)(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get pgliteDataDirPath(){return this.#o}async[M](){await V(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#s=await(0,x.lock)(this.#e,{lockfilePath:(0,d.join)(this.#e,".lock")}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`),await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new w(this):e}}async close(){if(this.#s!=null)try{await this.#s(),this.#s=null,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw console.error(`[State] failed to release lock on: ${this.#e}`),e}}async writeServerDump(e){this.#r={name:this.name,version:"1",pid:v.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,G.writeFile)(this.#i,`${JSON.stringify(this.#r,null,2)}
3
+ `,{encoding:"utf-8"})}};async function de(t,e){let r={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let i=await l.fromServerDump({debug:e,name:t});if(!i)return e&&console.debug(`[State] no server state found for name: ${t}`),{...r,status:"no_such_server"};r.databasePort=i.databasePort,r.exports=i.exports,r.pid=i.pid,r.port=i.port,r.shadowDatabasePort=i.shadowDatabasePort;let{exports:n,pid:c}=i;if(!H(c,e))return e&&console.debug(`[State] server state for "${t}" has no running process with PID: ${c}`),{...r,status:"not_running"};let m=g(t);try{if(!await(0,x.check)(m,{lockfilePath:(0,d.join)(m,".lock")}))return e&&console.debug(`[State] server state for "${t}" is not locked, indicating it is not running.`),{...r,status:"starting_up"}}catch(X){e&&console.error(`[State] server state for "${t}" failed to check lock:`,X)}if(!n)return{...r,status:"starting_up"};let{http:A}=n,u=await(0,W.hc)(A.url).health.$get();if(!u.ok)return e&&console.debug(`[State] server state for "${t}" is not live: ${JSON.stringify(u)}`),{...r,status:"not_running"};let f=await u.json();return f.name!==t?(e&&console.debug(`[State] server state for "${t}" has mismatched health response: ${JSON.stringify(f)}`),{...r,status:"unknown"}):(e&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(f)}`),{...r,status:"running"})}catch(i){return e&&console.error(`[State] failed to get server status for "${t}":`,i),{...r,status:"error"}}}var y=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},w=class extends y{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return l.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};0&&(module.exports={ServerAlreadyRunningError,ServerState,ServerStateAlreadyExistsError});