@prisma/dev 0.8.0 → 0.9.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,n as m}from"./chunk-H6HHF4W5.js";import{PGlite as b}from"@electric-sql/pglite";import{PGLiteSocketServer as P}from"@electric-sql/pglite-socket";import{filename as p}from"pathe/utils";var n={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},w=`postgres://${n.username}:${n.password}@localhost`,f=new URLSearchParams({sslmode:n.sslMode}),y=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):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,y),terminalCommand:`PGPASSWORD=${n.password} PGSSLMODE=${n.sslMode} psql -h localhost -p ${i} -U ${n.username} -d ${n.database}`}}function g(e,o){return`${w}:${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?p(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 c,f as $,g as k,h as R,i as M,j as A,k as I,l as m,m as T}from"./chunk-H6HHF4W5.js";import{writeFile as Y}from"fs/promises";import{hc as Z}from"hono/client";import{join as d}from"pathe";import{check as z,lock as K}from"proper-lockfile";import{process as F}from"std-env";import{integer as J,literal as W,minLength as G,minValue as U,number as j,object as f,optional as b,parseJson as Q,pipe as l,safeParse as X,string as g,url as ee}from"valibot";import{process as q}from"std-env";function V(r,e){if(r==null)return!1;try{return q.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}var w=l(g(),ee()),N=f({connectionString:w,prismaORMConnectionString:b(w),terminalCommand:b(g())}),L=f({url:w}),D=l(j(),J(),U(1)),te=f({database:N,http:L,ppg:L,shadowDatabase:N}),re=f({databasePort:D,exports:b(te),name:l(g(),G(1)),pid:b(l(j(),J(),U(0))),port:D,shadowDatabasePort:D,version:W("1")}),E=Symbol("initialize"),y="default",i=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??m,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??y,this.persistenceMode=e.persistenceMode,this.pid=e.pid??F.pid,this._port=e.port??m,this._shadowDatabasePort=e.shadowDatabasePort??m}static async createExclusively(e){let t=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new p(e):new x(e);return await t[E](),t}static async fromServerDump(e){let{debug:t,name:o=y}=e??{},s=c(o),a=p.getServerDumpPath(s),u=await $(a);if(u==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(u));let{issues:h,output:n,success:P}=X(l(g(),Q(),re),u);if(!P)throw t&&console.debug(`[State] Invalid server dump file at "${a}":
2
+ ${JSON.stringify(h,null,2)}`),new Error(`Invalid Prisma Dev state for "${o}".`);return new p({databasePort:n.databasePort,debug:t,dryRun:!1,name:o,pid:n.pid,port:n.port,serverDump:n,shadowDatabasePort:n.shadowDatabasePort})}static async scan(e){let{debug:t}=e??{},o=d(c(y),"..");t&&console.debug(`[State] scanning for server states in: ${o}`);let s=await R(o);return t&&console.debug(`[State] found server names: ${JSON.stringify(s)}`),await Promise.all(s.map(a=>se(a,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},x=class extends i{constructor(e){super({...e,databasePort:e?.databasePort??M,persistenceMode:"stateless",port:e?.port??A,shadowDatabasePort:e?.shadowDatabasePort??I})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[E](){}async close(){}async writeServerDump(){}},p=class r extends i{#t;#e;#a;#o;#r;#s=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=c(this.name),this.#t=d(this.#e,"db_dump.bak"),this.#a=d(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#o=r.getServerDumpPath(this.#e)}static getServerDumpPath(e){return d(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get pgliteDataDirPath(){return this.#a}async[E](){await k(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#s=await K(this.#e,{lockfilePath:d(this.#e,".lock")}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await i.scan({debug:this.debug,onlyMetadata:!0}),t=await T({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=t.databasePort,this._port=t.port,this._shadowDatabasePort=t.shadowDatabasePort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new O(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:F.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await Y(this.#o,`${JSON.stringify(this.#r,null,2)}
3
+ `,{encoding:"utf-8"})}};async function se(r,e){let{debug:t,onlyMetadata:o}=e||{},s={databasePort:-1,exports:void 0,name:r,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let a=await i.fromServerDump({debug:t,name:r});if(!a)return t&&console.debug(`[State] no server state found for name: ${r}`),{...s,status:"no_such_server"};s.databasePort=a.databasePort,s.exports=a.exports,s.pid=a.pid,s.port=a.port,s.shadowDatabasePort=a.shadowDatabasePort;let{exports:u,pid:h}=a;if(o)return{...s,status:"unknown"};if(!V(h,t))return t&&console.debug(`[State] server state for "${r}" has no running process with PID: ${h}`),{...s,status:"not_running"};let n=c(r);try{if(!await z(n,{lockfilePath:d(n,".lock")}))return t&&console.debug(`[State] server state for "${r}" is not locked, indicating it is not running.`),{...s,status:"starting_up"}}catch(B){t&&console.error(`[State] server state for "${r}" failed to check lock:`,B)}if(!u)return{...s,status:"starting_up"};let{http:P}=u,v=await Z(P.url).health.$get();if(!v.ok)return t&&console.debug(`[State] server state for "${r}" is not live: ${JSON.stringify(v)}`),{...s,status:"not_running"};let S=await v.json();return S.name!==r?(t&&console.debug(`[State] server state for "${r}" has mismatched health response: ${JSON.stringify(S)}`),{...s,status:"unknown"}):(t&&console.debug(`[State] server state for "${r}" is live: ${JSON.stringify(S)}`),{...s,status:"running"})}catch(a){return t&&console.error(`[State] failed to get server status for "${r}":`,a),{...s,status:"error"}}}var _=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},O=class extends _{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return i.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};export{i as a,_ as b,O as c};
@@ -0,0 +1 @@
1
+ import{createWriteStream as q,WriteStream as F}from"fs";import{access as N,chmod as K,constants as C,mkdir as G,readdir as M,readFile as H,writeFile as V}from"fs/promises";import s from"path";import A from"os";import h from"process";var d=A.homedir(),g=A.tmpdir(),{env:l}=h,U=e=>{let r=s.join(d,"Library");return{data:s.join(r,"Application Support",e),config:s.join(r,"Preferences",e),cache:s.join(r,"Caches",e),log:s.join(r,"Logs",e),temp:s.join(g,e)}},L=e=>{let r=l.APPDATA||s.join(d,"AppData","Roaming"),t=l.LOCALAPPDATA||s.join(d,"AppData","Local");return{data:s.join(t,e,"Data"),config:s.join(r,e,"Config"),cache:s.join(t,e,"Cache"),log:s.join(t,e,"Log"),temp:s.join(g,e)}},R=e=>{let r=s.basename(d);return{data:s.join(l.XDG_DATA_HOME||s.join(d,".local","share"),e),config:s.join(l.XDG_CONFIG_HOME||s.join(d,".config"),e),cache:s.join(l.XDG_CACHE_HOME||s.join(d,".cache"),e),log:s.join(l.XDG_STATE_HOME||s.join(d,".local","state"),e),temp:s.join(g,r,e)}};function v(e,{suffix:r="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return r&&(e+=`-${r}`),h.platform==="darwin"?U(e):h.platform==="win32"?L(e):R(e)}import{inflate as W}from"pako";var j=v("prisma-dev");function ue(e,r){return`${j.cache}/engine/${e}/${r}`}function pe(e){return`${j.data}/${e}`}async function de(e){try{return await N(e,C.F_OK),!0}catch(r){if(w(r))return!1;throw r}}async function fe(e,r){let t=W(e);await V(r,t),await K(r,"755")}async function le(e,r){await e.stream().pipeTo(F.toWeb(q(r,{encoding:"utf-8"})))}function w(e){return e!=null&&typeof e=="object"&&"code"in e&&e.code==="ENOENT"}async function Pe(e){try{return await H(e,{encoding:"utf-8"})}catch(r){if(w(r))return null;throw r}}async function ye(e){await G(e,{recursive:!0})}async function be(e){try{return(await M(e,{withFileTypes:!0})).reduce((t,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&t.push(n.name),t),[])}catch(r){if(w(r))return[];throw r}}import{checkPort as B,getPort as D,isUnsafePort as X}from"get-port-please";import{difference as I,range as J}from"remeda";var $=51214,E=51213,k=51215,P=65535,y=-1/0;async function we(e){let{debug:r,name:t,requestedPorts:n,servers:u}=e,{portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a}=Y(t,u);r&&(console.debug(`ports used by other servers: ${Object.keys(o).join(", ")}`),console.debug(`ports used by "${t}" server last time: ${JSON.stringify(a)}`));let c={databasePort:y,port:y,shadowDatabasePort:y},i=["port","databasePort","shadowDatabasePort"];for(let p of i){let f=await z({debug:r,portKey:p,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a,requestedPorts:n})??await Q({debug:r,pickedPorts:c,portKey:p,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a});r&&console.debug(`Got port for "${p}": ${f}`),c[p]=f}return r&&console.debug(`Picked ports: ${JSON.stringify(c)}`),c}async function z(e){let{debug:r,portKey:t,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:u,requestedPorts:o}=e,{[t]:a,...c}=o;if(_(a))return await Z({debug:r,otherRequestedPorts:c,portKey:t,portsUsedByOtherServers:n,requestedPort:a}),a;let i=u?.[t]??y;if(!_(i))return r&&console.debug(`No port specified for "${t}". Trying to pick a new port.`),null;let p=i in n;return p||Object.values(c).includes(i)?(r&&console.debug(`Port ${i} that was used last time for this server, ${p?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await B(i)===!1?(r&&console.debug(`Port ${i}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(r&&console.debug(`Using port ${i} for "${t}" as it was used last time and is available.`),i)}async function Q(e){let{debug:r,pickedPorts:t,portKey:n,portsUsedByOtherServers:u,portsUsedByThisServerLastTime:o}=e,a=Math.max($,E,k)+1,c=[...Object.values(t),...Object.keys(u).map(Number),...Object.values(o||{})],i=Math.min(Math.max(a,...c)+100,P),p=I(J(a,i),c),f={port:E,databasePort:$,shadowDatabasePort:k}[n];try{return await D({port:f in u||Object.values(t).includes(f)||Object.values(o||{}).includes(f)?void 0:f,ports:p})}catch(m){if(m instanceof Error&&m.name==="GetPortError"&&i+1<=P)return r&&console.debug(`Expanding port lookup to range [${i+1}, ${P}].`),await D({portRange:[i+1,P]});throw m}}function _(e){return e>=0}function Y(e,r){let t={},n;for(let u of r){let{databasePort:o,port:a,shadowDatabasePort:c}=u;if(u.name===e){n={databasePort:o,port:a,shadowDatabasePort:c};continue}t[o]=!0,t[a]=!0,t[c]=!0}return{portsUsedByOtherServers:t,portsUsedByThisServerLastTime:n}}async function Z(e){let{debug:r,otherRequestedPorts:t,portKey:n,portsUsedByOtherServers:u,requestedPort:o}=e;if(o in u)throw r&&console.error(`Port ${o} was requested for "${n}", but is already used by another server.`),new S(o);if(Object.values(t).includes(o))throw r&&console.error(`Port ${o} was requested for "${n}", but also for another key.`),new O(o);if(X(o))throw r&&console.error(`Port ${o} was requested for "${n}", but is unsafe.`),new b(o);if(await B(o)===!1)throw r&&console.error(`Port ${o} was requested for "${n}", but is not available.`),new b(o)}var b=class extends Error{constructor(t){super(`Port \`${t}\` is not available.`);this.port=t}name="PortNotAvailableError"},O=class extends Error{constructor(t){super(`Port number \`${t}\` was requested twice. Please choose a different port for each service.`);this.port=t}name="PortRequestedTwiceError"},S=class extends Error{constructor(t){super(`Port number \`${t}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=t}name="PortBelongsToAnotherServerError"};export{ue as a,pe as b,de as c,fe as d,le as e,Pe as f,ye as g,be as h,$ as i,E as j,k,y as l,we as m,b as n};
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),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});
1
+ "use strict";var U=Object.create;var f=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var G=Object.getPrototypeOf,M=Object.prototype.hasOwnProperty;var F=(e,t)=>{for(var o in t)f(e,o,{get:t[o],enumerable:!0})},O=(e,t,o,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of C(t))!M.call(e,a)&&a!==o&&f(e,a,{get:()=>t[a],enumerable:!(s=N(t,a))||s.enumerable});return e};var P=(e,t,o)=>(o=e!=null?U(G(e)):{},O(t||!e||!e.__esModule?f(o,"default",{value:e,enumerable:!0}):o,e)),q=e=>O(f({},"__esModule",{value:!0}),e);var Y={};F(Y,{dumpDB:()=>L,startDBServer:()=>J});module.exports=q(Y);var $=require("@electric-sql/pglite"),E=require("@electric-sql/pglite-socket"),B=require("pathe/utils");var g=require("fs"),m=require("fs/promises");var r=P(require("path"),1),w=P(require("os"),1),b=P(require("process"),1),l=w.default.homedir(),v=w.default.tmpdir(),{env:p}=b.default,I=e=>{let t=r.default.join(l,"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(v,e)}},K=e=>{let t=p.APPDATA||r.default.join(l,"AppData","Roaming"),o=p.LOCALAPPDATA||r.default.join(l,"AppData","Local");return{data:r.default.join(o,e,"Data"),config:r.default.join(t,e,"Config"),cache:r.default.join(o,e,"Cache"),log:r.default.join(o,e,"Log"),temp:r.default.join(v,e)}},H=e=>{let t=r.default.basename(l);return{data:r.default.join(p.XDG_DATA_HOME||r.default.join(l,".local","share"),e),config:r.default.join(p.XDG_CONFIG_HOME||r.default.join(l,".config"),e),cache:r.default.join(p.XDG_CACHE_HOME||r.default.join(l,".cache"),e),log:r.default.join(p.XDG_STATE_HOME||r.default.join(l,".local","state"),e),temp:r.default.join(v,t,e)}};function S(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"?K(e):H(e)}var W=require("pako"),re=S("prisma-dev");async function T(e,t){await e.stream().pipeTo(g.WriteStream.toWeb((0,g.createWriteStream)(t,{encoding:"utf-8"})))}var D=require("get-port-please"),x=require("remeda");var y=class extends Error{constructor(o){super(`Port \`${o}\` is not available.`);this.port=o}name="PortNotAvailableError"};var i={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},V=`postgres://${i.username}:${i.password}@localhost`,k=new URLSearchParams({sslmode:i.sslMode}),X=new URLSearchParams({...Object.fromEntries(k.entries()),connection_limit:String(i.connectionLimit),connect_timeout:String(i.connectTimeout),max_idle_connection_lifetime:String(i.maxIdleConnectionLifetime),pool_timeout:String(i.poolTimeout),single_use_connections:"true",socket_timeout:String(i.socketTimeout)});async function J(e,t){let o=e==="database"?t.databasePort:t.shadowDatabasePort;if(t.dryRun)return _(e,t,{db:null,port:o,server:null});let{debug:s}=t,d=await(e==="shadow_database"?Q:R)(t.pgliteDataDirPath,s);s&&d.onNotification((n,c)=>{console.debug(`[${e}][${n}] ${c}`)});let u=new E.PGLiteSocketServer({db:d,debug:s,inspect:s,port:o});s&&(u.addEventListener("listening",n=>{let{detail:c}=n;console.debug(`[${e}] server listening on ${JSON.stringify(c)}`)}),u.addEventListener("connection",n=>{let{clientAddress:c,clientPort:j}=n.detail;console.debug(`[${e}] client connected from ${c}:${j}`)}),u.addEventListener("error",n=>{let{detail:c}=n;console.error(`[${e}] server error:`,c)}));try{await u.start()}catch(n){throw n instanceof Error&&"code"in n&&n.code==="EADDRINUSE"?new y(o):n}return _(e,t,{db:d,port:o,server:u})}function _(e,t,o){let{debug:s}=t,{db:a,port:d,server:u}=o||{};return s&&console.debug(`[${e}] server started on port ${d}`),{...i,close:async()=>{let n=[];try{await u?.stop(),s&&console.debug(`[${e}] server stopped on port ${d}`)}catch(c){console.error(`[${e}] server stop error`,c),n.push(c)}if(e==="database")try{await a?.syncToFs(),s&&console.debug(`[${e}] synced to filesystem`)}catch(c){console.error(`[${e}] sync error`,c),n.push(c)}try{await a?.close(),s&&console.debug(`[${e}] closed`)}catch(c){console.error(`[${e}] close error`,c),n.push(c)}if(n.length>0)throw new AggregateError(n,`Failed to close ${e} properly`)},connectionString:A(d,k),dump:async n=>{e==="shadow_database"||!a||await L({db:a,debug:s,destinationPath:n})},port:d,prismaORMConnectionString:A(d,X),terminalCommand:`PGPASSWORD=${i.password} PGSSLMODE=${i.sslMode} psql -h localhost -p ${d} -U ${i.username} -d ${i.database}`}}function A(e,t){return`${V}:${e}/${i.database}?${t.toString()}`}async function R(e,t){return await $.PGlite.create({database:i.database,dataDir:e,debug:t?5:void 0,relaxedDurability:!1,username:i.username})}async function Q(e,t){return await $.PGlite.create({database:i.database,dataDir:"memory://",debug:t?5:void 0,relaxedDurability:!1,username:i.username})}async function L(e){let{dataDir:t,db:o,debug:s,destinationPath:a}=e,d=o||await R(t,s),{pgDump:u}=await import("@electric-sql/pglite-tools/pg_dump"),n=await u({args:["--schema-only","--no-owner"],fileName:a?(0,B.filename)(a):void 0,pg:await d.clone()});return a?(s&&console.debug(`[DB] Dumping database to ${a}`),await T(n,a)):(s&&console.debug("[DB] Dumping database to memory"),await n.text())}0&&(module.exports={dumpDB,startDBServer});
package/dist/db.js CHANGED
@@ -1 +1 @@
1
- import{a,b}from"./chunk-GBG44OEG.js";import"./chunk-Q3M6SQC2.js";export{b as dumpDB,a as startDBServer};
1
+ import{a,b}from"./chunk-3QVAUUGC.js";import"./chunk-H6HHF4W5.js";export{b as dumpDB,a as startDBServer};
package/dist/index.cjs CHANGED
@@ -1,8 +1,8 @@
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 {
1
+ "use strict";var St=Object.create;var V=Object.defineProperty;var vt=Object.getOwnPropertyDescriptor;var wt=Object.getOwnPropertyNames;var Dt=Object.getPrototypeOf,Et=Object.prototype.hasOwnProperty;var Ot=(t,e)=>{for(var r in e)V(t,r,{get:e[r],enumerable:!0})},we=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of wt(e))!Et.call(t,o)&&o!==r&&V(t,o,{get:()=>e[o],enumerable:!(n=vt(e,o))||n.enumerable});return t};var H=(t,e,r)=>(r=t!=null?St(Dt(t)):{},we(e||!t||!t.__esModule?V(r,"default",{value:t,enumerable:!0}):r,t)),Rt=t=>we(V({},"__esModule",{value:!0}),t);var Zt={};Ot(Zt,{DEFAULT_DATABASE_PORT:()=>$,DEFAULT_SERVER_PORT:()=>_,DEFAULT_SHADOW_DATABASE_PORT:()=>k,PortNotAvailableError:()=>v,ServerAlreadyRunningError:()=>F,unstable_startServer:()=>Yt});module.exports=Rt(Zt);var R=require("hono/http-exception"),p=require("valibot"),De=/^(postgres|postgresql):\/\//,Tt=(0,p.pipe)((0,p.string)(),(0,p.parseJson)(),(0,p.object)({databaseUrl:(0,p.pipe)((0,p.string)(),(0,p.url)(),(0,p.regex)(De)),name:(0,p.optional)((0,p.pipe)((0,p.string)(),(0,p.minLength)(1))),shadowDatabaseUrl:(0,p.pipe)((0,p.string)(),(0,p.url)(),(0,p.regex)(De))}));function Ee(t){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([[e],[r]])=>e.localeCompare(r)))),"utf8").toString("base64url")}function At(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:n,success:o}=(0,p.safeParse)(Tt,e,{abortEarly:!0});return o?[null,n]:[r]}var A=(t,e)=>{let{authorization:r}=t;if(!r)throw new R.HTTPException(401,{message:"Missing API Key"});let[n,o="",s]=r.split(" ");if(n!=="Bearer"||s)throw new R.HTTPException(401,{message:"Invalid API Key"});let[a,i]=At(o);if(a)throw new R.HTTPException(401,{message:"Invalid API Key",cause:a.join(", ")});let{databaseUrl:c,name:u,shadowDatabaseUrl:f}=i,{name:h}=e.get("serverState");if(!u)throw new R.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 "${h}" server's output for the updated \`DATABASE_URL\` value.`});if(u!==h)throw new R.HTTPException(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${h}", but the API Key is for "${u}"`});let{hostname:P,port:q}=new URL(c),{port:te}=e.get("db"),{hostname:bt,port:yt}=new URL(f),Pt=e.get("shadowDBPort");if(P!=="localhost"||Number(q)!==te||bt!=="localhost"||Number(yt)!==Pt)throw new R.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:i}};var ce=require("@electric-sql/pglite"),je=require("@electric-sql/pglite-socket"),Me=require("pathe/utils");var G=require("fs"),S=require("fs/promises");var m=H(require("path"),1),re=H(require("os"),1),K=H(require("process"),1),D=re.default.homedir(),oe=re.default.tmpdir(),{env:x}=K.default,xt=t=>{let e=m.default.join(D,"Library");return{data:m.default.join(e,"Application Support",t),config:m.default.join(e,"Preferences",t),cache:m.default.join(e,"Caches",t),log:m.default.join(e,"Logs",t),temp:m.default.join(oe,t)}},$t=t=>{let e=x.APPDATA||m.default.join(D,"AppData","Roaming"),r=x.LOCALAPPDATA||m.default.join(D,"AppData","Local");return{data:m.default.join(r,t,"Data"),config:m.default.join(e,t,"Config"),cache:m.default.join(r,t,"Cache"),log:m.default.join(r,t,"Log"),temp:m.default.join(oe,t)}},_t=t=>{let e=m.default.basename(D);return{data:m.default.join(x.XDG_DATA_HOME||m.default.join(D,".local","share"),t),config:m.default.join(x.XDG_CONFIG_HOME||m.default.join(D,".config"),t),cache:m.default.join(x.XDG_CACHE_HOME||m.default.join(D,".cache"),t),log:m.default.join(x.XDG_STATE_HOME||m.default.join(D,".local","state"),t),temp:m.default.join(oe,e,t)}};function ne(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),K.default.platform==="darwin"?xt(t):K.default.platform==="win32"?$t(t):_t(t)}var Oe=require("pako"),Re=ne("prisma-dev");function Te(t,e){return`${Re.cache}/engine/${t}/${e}`}function L(t){return`${Re.data}/${t}`}async function Ae(t){try{return await(0,S.access)(t,S.constants.F_OK),!0}catch(e){if(se(e))return!1;throw e}}async function xe(t,e){let r=(0,Oe.inflate)(t);await(0,S.writeFile)(e,r),await(0,S.chmod)(e,"755")}async function $e(t,e){await t.stream().pipeTo(G.WriteStream.toWeb((0,G.createWriteStream)(e,{encoding:"utf-8"})))}function se(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function _e(t){try{return await(0,S.readFile)(t,{encoding:"utf-8"})}catch(e){if(se(e))return null;throw e}}async function ke(t){await(0,S.mkdir)(t,{recursive:!0})}async function Ie(t){try{return(await(0,S.readdir)(t,{withFileTypes:!0})).reduce((r,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&r.push(n.name),r),[])}catch(e){if(se(e))return[];throw e}}var O=require("get-port-please"),Q=require("remeda"),$=51214,_=51213,k=51215,J=65535,E=-1/0;async function Be(t){let{debug:e,name:r,requestedPorts:n,servers:o}=t,{portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a}=Ct(r,o);e&&(console.debug(`ports used by other servers: ${Object.keys(s).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(a)}`));let i={databasePort:E,port:E,shadowDatabasePort:E},c=["port","databasePort","shadowDatabasePort"];for(let u of c){let f=await kt({debug:e,portKey:u,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a,requestedPorts:n})??await It({debug:e,pickedPorts:i,portKey:u,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a});e&&console.debug(`Got port for "${u}": ${f}`),i[u]=f}return e&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function kt(t){let{debug:e,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:o,requestedPorts:s}=t,{[r]:a,...i}=s;if(Ce(a))return await Bt({debug:e,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:n,requestedPort:a}),a;let c=o?.[r]??E;if(!Ce(c))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let u=c in n;return u||Object.values(i).includes(c)?(e&&console.debug(`Port ${c} that was used last time for this server, ${u?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,O.checkPort)(c)===!1?(e&&console.debug(`Port ${c}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(e&&console.debug(`Using port ${c} for "${r}" as it was used last time and is available.`),c)}async function It(t){let{debug:e,pickedPorts:r,portKey:n,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:s}=t,a=Math.max($,_,k)+1,i=[...Object.values(r),...Object.keys(o).map(Number),...Object.values(s||{})],c=Math.min(Math.max(a,...i)+100,J),u=(0,Q.difference)((0,Q.range)(a,c),i),f={port:_,databasePort:$,shadowDatabasePort:k}[n];try{return await(0,O.getPort)({port:f in o||Object.values(r).includes(f)||Object.values(s||{}).includes(f)?void 0:f,ports:u})}catch(h){if(h instanceof Error&&h.name==="GetPortError"&&c+1<=J)return e&&console.debug(`Expanding port lookup to range [${c+1}, ${J}].`),await(0,O.getPort)({portRange:[c+1,J]});throw h}}function Ce(t){return t>=0}function Ct(t,e){let r={},n;for(let o of e){let{databasePort:s,port:a,shadowDatabasePort:i}=o;if(o.name===t){n={databasePort:s,port:a,shadowDatabasePort:i};continue}r[s]=!0,r[a]=!0,r[i]=!0}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}async function Bt(t){let{debug:e,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:o,requestedPort:s}=t;if(s in o)throw e&&console.error(`Port ${s} was requested for "${n}", but is already used by another server.`),new ie(s);if(Object.values(r).includes(s))throw e&&console.error(`Port ${s} was requested for "${n}", but also for another key.`),new ae(s);if((0,O.isUnsafePort)(s))throw e&&console.error(`Port ${s} was requested for "${n}", but is unsafe.`),new v(s);if(await(0,O.checkPort)(s)===!1)throw e&&console.error(`Port ${s} was requested for "${n}", but is not available.`),new v(s)}var v=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},ae=class extends Error{constructor(r){super(`Port number \`${r}\` was requested twice. Please choose a different port for each service.`);this.port=r}name="PortRequestedTwiceError"},ie=class extends Error{constructor(r){super(`Port number \`${r}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=r}name="PortBelongsToAnotherServerError"};var g={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},Ht=`postgres://${g.username}:${g.password}@localhost`,Ne=new URLSearchParams({sslmode:g.sslMode}),Lt=new URLSearchParams({...Object.fromEntries(Ne.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 de(t,e){let r=t==="database"?e.databasePort:e.shadowDatabasePort;if(e.dryRun)return He(t,e,{db:null,port:r,server:null});let{debug:n}=e,s=await(t==="shadow_database"?jt:Ue)(e.pgliteDataDirPath,n);n&&s.onNotification((i,c)=>{console.debug(`[${t}][${i}] ${c}`)});let a=new je.PGLiteSocketServer({db:s,debug:n,inspect:n,port:r});n&&(a.addEventListener("listening",i=>{let{detail:c}=i;console.debug(`[${t}] server listening on ${JSON.stringify(c)}`)}),a.addEventListener("connection",i=>{let{clientAddress:c,clientPort:u}=i.detail;console.debug(`[${t}] client connected from ${c}:${u}`)}),a.addEventListener("error",i=>{let{detail:c}=i;console.error(`[${t}] server error:`,c)}));try{await a.start()}catch(i){throw i instanceof Error&&"code"in i&&i.code==="EADDRINUSE"?new v(r):i}return He(t,e,{db:s,port:r,server:a})}function He(t,e,r){let{debug:n}=e,{db:o,port:s,server:a}=r||{};return n&&console.debug(`[${t}] server started on port ${s}`),{...g,close:async()=>{let i=[];try{await a?.stop(),n&&console.debug(`[${t}] server stopped on port ${s}`)}catch(c){console.error(`[${t}] server stop error`,c),i.push(c)}if(t==="database")try{await o?.syncToFs(),n&&console.debug(`[${t}] synced to filesystem`)}catch(c){console.error(`[${t}] sync error`,c),i.push(c)}try{await o?.close(),n&&console.debug(`[${t}] closed`)}catch(c){console.error(`[${t}] close error`,c),i.push(c)}if(i.length>0)throw new AggregateError(i,`Failed to close ${t} properly`)},connectionString:Le(s,Ne),dump:async i=>{t==="shadow_database"||!o||await Mt({db:o,debug:n,destinationPath:i})},port:s,prismaORMConnectionString:Le(s,Lt),terminalCommand:`PGPASSWORD=${g.password} PGSSLMODE=${g.sslMode} psql -h localhost -p ${s} -U ${g.username} -d ${g.database}`}}function Le(t,e){return`${Ht}:${t}/${g.database}?${e.toString()}`}async function Ue(t,e){return await ce.PGlite.create({database:g.database,dataDir:t,debug:e?5:void 0,relaxedDurability:!1,username:g.username})}async function jt(t,e){return await ce.PGlite.create({database:g.database,dataDir:"memory://",debug:e?5:void 0,relaxedDurability:!1,username:g.username})}async function Mt(t){let{dataDir:e,db:r,debug:n,destinationPath:o}=t,s=r||await Ue(e,n),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),i=await a({args:["--schema-only","--no-owner"],fileName:o?(0,Me.filename)(o):void 0,pg:await s.clone()});return o?(n&&console.debug(`[DB] Dumping database to ${o}`),await $e(i,o)):(n&&console.debug("[DB] Dumping database to memory"),await i.text())}var st=require("http"),at=require("util"),it=require("@hono/node-server"),ct=H(require("@prisma/get-platform"),1);function W(t){let e,r,n=new Promise((a,i)=>{e=a,r=i}),o=a=>{o=s=null,r(a),t?.onRejected?.(a),t?.onFulfilled?.()},s=a=>{s=o=null,e(a),t?.onResolved?.(a),t?.onFulfilled?.()};return{isFulfilled:()=>s===o,promise:n,reject:a=>o?.(a),resolve:a=>s?.(a)}}var dt=require("hono/logger"),me=require("hono/tiny");var tt=require("hono/tiny"),B=require("hono/validator");var y=require("valibot"),Nt=(0,y.object)({tags:(0,y.union)([(0,y.pipe)((0,y.array)((0,y.string)()),(0,y.minLength)(1)),(0,y.literal)("all")])});async function Fe(t){let{output:e,success:r}=(0,y.safeParse)(Nt,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var Ve=require("child_process"),Ke=require("events"),Ge=require("fs/promises"),Je=require("path"),Qe=require("timers/promises");var We=require("foreground-child/proxy-signals"),ze=require("std-env");var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Ut,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:Ft,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:qe}=ze.process.env,C=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.#i(e,r,"commit")}async request(e,r){let{url:n}=await this.start(),o=this.#a(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 I.fromResponse(s);return await s.text()}async rollbackTransaction(e,r){return await this.#i(e,r,"rollback")}async startTransaction(e,r){let{url:n}=await this.start(),o=this.#a(r),s=await fetch(`${n}/transaction/start`,{body:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await I.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:r,resolve:n}=W();this.#t=e;let o=Ft||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=(0,Ve.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,We.proxySignals)(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let a=u=>{let f=u.split(`
2
+ `).find(te=>te.includes("Started query engine http server"));if(!f)return;s.stdout.removeListener("data",a);let{fields:h}=JSON.parse(f);if(h==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${u}`));let{ip:P,port:q}=h;if(P==null||q==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: ${u}`));n({childProcess:s,url:`http://${P}:${q}`})},i=u=>{this.#t=null,r(new j(String(u))),s.removeListener("exit",c),s.kill()};s.once("error",i);let c=(u,f)=>{this.#t=null,r(new j(`Query Engine exited with code ${u} and signal ${f}`))};return s.once("exit",c),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(0,Ke.once)(e,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#o();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let r=Te(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,Ge.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),(Ut==="1"||await Ae(s)===!1)&&await this.#n({commitHash:e,extension:o,engineBinaryPath:s}),s}async#o(){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#n(e){let{commitHash:r,extension:n,engineBinaryPath:o}=e,{binaryTarget:s}=this.#e.platform,a=`https://binaries.prisma.sh/all_commits/${r}/${s}/query-engine${n}.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}`);qe&&await(0,Qe.setTimeout)(Number(qe)),await xe(await i.arrayBuffer(),o),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",o)}#a(e){let r={};for(let[n,o]of Object.entries(e))o!=null&&(r[n]=o);return r}async#i(e,r,n){let{url:o}=await this.#t,s=this.#a(r),a=await fetch(`${o}/transaction/${e}/${n}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!a.ok)throw await I.fromResponse(a);try{return await a.json()}catch{return{}}}};function z(t,e){return console.error(t),t instanceof j?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof I?e.text(t.responseBody,t.statusCode):e.body(null,500)}var j=class extends Error{name="EngineStartError"},I=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 ue=require("buffer"),X=new Map;async function le(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(a=>a.toString(16).padStart(2,"0")).join("")}function Xe(t){let e=t.req.param("schemaHash"),r=X.get(e);return r==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:r}}var qt=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function Ye(t,e){let r=ue.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 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});
6
+ }`,o=r.replace(qt,n),s=await le(o);return{base64Override:ue.Buffer.from(o,"utf8").toString("base64"),overrideHash:s}}function Y(t){let{req:e}=t;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}var l=require("valibot"),Vt=(0,l.object)({isolation_level:(0,l.optional)((0,l.string)()),max_wait:(0,l.pipe)((0,l.number)(),(0,l.integer)(),(0,l.minValue)(0)),timeout:(0,l.pipe)((0,l.number)(),(0,l.integer)(),(0,l.minValue)(0))});async function Ze(t){let{issues:e,output:r,success:n}=(0,l.safeParse)(Vt,await t.req.json(),{abortEarly:!0});return n?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}var Kt=(0,l.looseObject)({id:(0,l.union)([(0,l.string)(),(0,l.number)()])});function et(t,e){let{output:r,success:n}=(0,l.safeParse)(Kt,t);return n?r:e.json({EngineMalfunction:{}},500)}var M=new tt.Hono;M.post("/invalidate",(0,B.validator)("header",A),async t=>{let e=await Fe(t);return e instanceof Response?e:t.body(null)});var Gt="/:clientVersion/:schemaHash",N=M.basePath(Gt);M.route("/",N);var Jt=["/graphql","/itx/:transactionId/graphql"];N.on("POST",[...Jt],(0,B.validator)("header",A),async t=>{let{req:e}=t;try{let r=await pe(t);if(r instanceof Response)return r;let n=await e.text(),o=e.param("transactionId"),s=await r.request(n,{...Y(t),"X-transaction-id":o});return t.text(s)}catch(r){return z(r,t)}});N.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,B.validator)("header",A),async t=>{let{req:e}=t;try{let r=await pe(t);if(r instanceof Response)return r;let o=`${e.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=e.param("transactionId"),a=await r[o](s,Y(t));return t.json(a)}catch(r){return z(r,t)}});N.put("/schema",(0,B.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=X.get(n);if(o==null){if(n!==await le(r))return t.text("Schema hash mismatch",400);let s=await Ye(r,t.get("db").prismaORMConnectionString);return X.set(n,{base64Original:r,...s}),t.text(n)}return r!==o.base64Original?t.text("Schema mismatch",400):t.text(n)});N.post("/transaction/start",(0,B.validator)("header",A),async t=>{let{req:e}=t,r=await Ze(t);if(r instanceof Response)return r;try{let n=await pe(t);if(n instanceof Response)return n;let o=await n.startTransaction(r,Y(t)),s=et(o,t);if(s instanceof Response)return s;let{id:a}=s,i=e.param("clientVersion"),c=t.get("port"),u=t.get("protocol"),f=e.param("schemaHash");return t.json({...o,"data-proxy":{endpoint:`${u}://localhost:${c}/${i}/${f}/itx/${a}`}})}catch(n){return z(n,t)}});async function pe(t){let{req:e}=t,r=Xe(t);if(r instanceof Response)return r;let{base64Override:n,overrideHash:o}=r.schemas;return await C.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 rt=require("hono/tiny"),ot=require("http-status-codes"),Z=new rt.Hono;Z.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},ot.StatusCodes.CREATED)});var Lr=Z.get("/health",t=>t.json({name:t.get("serverState").name}));async function ut(t,e){let{port:r}=e;if(e.dryRun)return nt(r,null);let n=await Qt(r,t,e),{promise:o,reject:s,resolve:a}=W(),i=(0,it.serve)({createServer:st.createServer,fetch:n.fetch,overrideGlobalObjects:!1,port:r},a);return i.on("error",c=>{if(typeof c=="object"&&"code"in c&&c.code==="EADDRINUSE")return s(new v(r));console.error("[Accelerate]",c)}),await o,nt(r,i)}function nt(t,e){return{async close(){e&&await Promise.allSettled([(0,at.promisify)(e.close.bind(e))(),C.stopAll()])},port:t,url:`http://localhost:${t}`}}async function Qt(t,e,r){let{debug:n}=r,o=new me.Hono,s=await ct.default.getPlatformInfo();return n&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),n&&o.use("*",(0,dt.logger)((...a)=>console.log("[Accelerate]",...a))),o.use("*",async(a,i)=>(a.set("db",e),a.set("debug",!!n),a.set("platform",s),a.set("port",t),a.set("protocol","http"),a.set("serverState",r),a.set("shadowDBPort",r.shadowDatabasePort),await i())),o.route("/",fe),o}var fe=new me.Hono;fe.route("/",M);fe.route("/",Z);var ht=require("fs/promises"),gt=require("hono/client"),T=require("pathe"),ee=require("proper-lockfile"),Se=require("std-env"),d=require("valibot");var lt=require("std-env");function pt(t,e){if(t==null)return!1;try{return lt.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var be=(0,d.pipe)((0,d.string)(),(0,d.url)()),mt=(0,d.object)({connectionString:be,prismaORMConnectionString:(0,d.optional)(be),terminalCommand:(0,d.optional)((0,d.string)())}),ft=(0,d.object)({url:be}),he=(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(1)),Wt=(0,d.object)({database:mt,http:ft,ppg:ft,shadowDatabase:mt}),zt=(0,d.object)({databasePort:he,exports:(0,d.optional)(Wt),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:he,shadowDatabasePort:he,version:(0,d.literal)("1")}),ve=Symbol("initialize"),ge="default",w=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??E,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??ge,this.persistenceMode=e.persistenceMode,this.pid=e.pid??Se.process.pid,this._port=e.port??E,this._shadowDatabasePort=e.shadowDatabasePort??E}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new U(e):new ye(e);return await r[ve](),r}static async fromServerDump(e){let{debug:r,name:n=ge}=e??{},o=L(n),s=U.getServerDumpPath(o),a=await _e(s);if(a==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(a));let{issues:i,output:c,success:u}=(0,d.safeParse)((0,d.pipe)((0,d.string)(),(0,d.parseJson)(),zt),a);if(!u)throw r&&console.debug(`[State] Invalid server dump file at "${s}":
7
+ ${JSON.stringify(i,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new U({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,T.join)(L(ge),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let o=await Ie(n);return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(s=>Xt(s,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},ye=class extends w{constructor(e){super({...e,databasePort:e?.databasePort??$,persistenceMode:"stateless",port:e?.port??_,shadowDatabasePort:e?.shadowDatabasePort??k})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[ve](){}async close(){}async writeServerDump(){}},U=class t extends w{#r;#e;#t;#s;#o;#n=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=L(this.name),this.#r=(0,T.join)(this.#e,"db_dump.bak"),this.#t=(0,T.join)(this.#e,".pglite"),this.#o=e?.serverDump??null,this.#s=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,T.join)(e,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#o?.exports}get pgliteDataDirPath(){return this.#t}async[ve](){await ke(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#n=await(0,ee.lock)(this.#e,{lockfilePath:(0,T.join)(this.#e,".lock")}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await w.scan({debug:this.debug,onlyMetadata:!0}),r=await Be({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new F(this):e}}async close(){if(this.#n!=null)try{await this.#n(),this.#n=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.#o={name:this.name,version:"1",pid:Se.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,ht.writeFile)(this.#s,`${JSON.stringify(this.#o,null,2)}
8
+ `,{encoding:"utf-8"})}};async function Xt(t,e){let{debug:r,onlyMetadata:n}=e||{},o={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let s=await w.fromServerDump({debug:r,name:t});if(!s)return r&&console.debug(`[State] no server state found for name: ${t}`),{...o,status:"no_such_server"};o.databasePort=s.databasePort,o.exports=s.exports,o.pid=s.pid,o.port=s.port,o.shadowDatabasePort=s.shadowDatabasePort;let{exports:a,pid:i}=s;if(n)return{...o,status:"unknown"};if(!pt(i,r))return r&&console.debug(`[State] server state for "${t}" has no running process with PID: ${i}`),{...o,status:"not_running"};let c=L(t);try{if(!await(0,ee.check)(c,{lockfilePath:(0,T.join)(c,".lock")}))return r&&console.debug(`[State] server state for "${t}" is not locked, indicating it is not running.`),{...o,status:"starting_up"}}catch(P){r&&console.error(`[State] server state for "${t}" failed to check lock:`,P)}if(!a)return{...o,status:"starting_up"};let{http:u}=a,f=await(0,gt.hc)(u.url).health.$get();if(!f.ok)return r&&console.debug(`[State] server state for "${t}" is not live: ${JSON.stringify(f)}`),{...o,status:"not_running"};let h=await f.json();return h.name!==t?(r&&console.debug(`[State] server state for "${t}" has mismatched health response: ${JSON.stringify(h)}`),{...o,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(h)}`),{...o,status:"running"})}catch(s){return r&&console.error(`[State] failed to get server status for "${t}":`,s),{...o,status:"error"}}}var Pe=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},F=class extends Pe{#r;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#r=e}get server(){return w.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};async function Yt(t){let e=await w.createExclusively(t),[r,n]=await Promise.all([de("database",e),de("shadow_database",e)]),o=await ut(r,e),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:Ee({databaseUrl:r.prismaORMConnectionString,name:e.name,shadowDatabaseUrl:n.prismaORMConnectionString})}).toString()}`,a={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(a),{...a,close:()=>i(e,[o,r,n]),name:e.name};async function i(c,u){let h=(await Promise.allSettled(u.map(P=>P.close()))).filter(P=>P.status==="rejected").map(P=>new Error(P.reason));try{await c.close()}catch(P){h.push(P)}if(h.length>0)throw new AggregateError(h,"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
@@ -9,10 +9,9 @@ declare const DEFAULT_SERVER_PORT = 51213;
9
9
  declare const DEFAULT_SHADOW_DATABASE_PORT = 51215;
10
10
  type PortAssignableService = DBServerPurpose | "server";
11
11
  declare class PortNotAvailableError extends Error {
12
- port: number;
13
- service: PortAssignableService;
12
+ readonly port: number;
14
13
  name: string;
15
- constructor(port: number, service: PortAssignableService);
14
+ constructor(port: number);
16
15
  }
17
16
 
18
17
  interface Server extends Exports {
package/dist/index.d.ts CHANGED
@@ -9,10 +9,9 @@ declare const DEFAULT_SERVER_PORT = 51213;
9
9
  declare const DEFAULT_SHADOW_DATABASE_PORT = 51215;
10
10
  type PortAssignableService = DBServerPurpose | "server";
11
11
  declare class PortNotAvailableError extends Error {
12
- port: number;
13
- service: PortAssignableService;
12
+ readonly port: number;
14
13
  name: string;
15
- constructor(port: number, service: PortAssignableService);
14
+ constructor(port: number);
16
15
  }
17
16
 
18
17
  interface Server extends Exports {
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
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 {
1
+ import{a as _}from"./chunk-3QVAUUGC.js";import{a as U,c as de}from"./chunk-BS26VSZW.js";import{a as L,c as M,d as N,i as le,j as ue,k as me,n as D}from"./chunk-H6HHF4W5.js";import{HTTPException as h}from"hono/http-exception";import{minLength as ge,object as he,optional as fe,parseJson as ye,pipe as R,regex as q,safeParse as we,string as A,url as K}from"valibot";var V=/^(postgres|postgresql):\/\//,Se=R(A(),ye(),he({databaseUrl:R(A(),K(),q(V)),name:fe(R(A(),ge(1))),shadowDatabaseUrl:R(A(),K(),q(V))}));function F(n){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(n).sort(([[e],[t]])=>e.localeCompare(t)))),"utf8").toString("base64url")}function ve(n){let e=Buffer.from(n,"base64url").toString("utf8"),{issues:t,output:r,success:o}=we(Se,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]=ve(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:P}=new URL(p),{port:x}=e.get("db"),{hostname:ae,port:ce}=new URL(g),pe=e.get("shadowDBPort");if(l!=="localhost"||Number(P)!==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 Xe}from"http";import{promisify as Ye}from"util";import{serve as Ze}from"@hono/node-server";import et from"@prisma/get-platform";function T(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 tt}from"hono/logger";import{Hono as se}from"hono/tiny";import{Hono as Qe}from"hono/tiny";import{validator as v}from"hono/validator";import{array as be,literal as Ee,minLength as Pe,object as Re,pipe as Ae,safeParse as Te,string as Oe,union as He}from"valibot";var Ce=Re({tags:He([Ae(be(Oe()),Pe(1)),Ee("all")])});async function Q(n){let{output:e,success:t}=Te(Ce,await n.req.json(),{abortEarly:!0});return t?e:n.text("Invalid input",400)}import{spawn as Ie}from"child_process";import{once as xe}from"events";import{mkdir as De}from"fs/promises";import{join as _e}from"path";import{setTimeout as ke}from"timers/promises";import{proxySignals as $e}from"foreground-child/proxy-signals";import{process as je}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Be,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:Le,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:z}=je.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}=T();this.#t=e;let o=Le||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=Ie(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});$e(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:P}=u;if(l==null||P==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}:${P}`})},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 xe(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=L(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",t),await De(t,{recursive:!0});let{platform:r}=this.#e.platform,o=r==="windows"?".exe":"",s=_e(t,`query-engine-${r}${o}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(Be==="1"||await M(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 ke(Number(z)),await N(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 k(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 Me=/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 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};
6
+ }`,o=t.replace(Me,r),s=await k(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 Ne,minValue as Y,number as $,object as Ue,optional as qe,pipe as Z,safeParse as ee,string as te,union as Ke}from"valibot";var Ve=Ue({isolation_level:qe(te()),max_wait:Z($(),X(),Y(0)),timeout:Z($(),X(),Y(0))});async function ne(n){let{issues:e,output:t,success:r}=ee(Ve,await n.req.json(),{abortEarly:!0});return r?t:n.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}var Fe=Ne({id:Ke([te(),$()])});function re(n,e){let{output:t,success:r}=ee(Fe,n);return r?t:e.json({EngineMalfunction:{}},500)}var b=new Qe;b.post("/invalidate",v("header",f),async n=>{let e=await Q(n);return e instanceof Response?e:n.body(null)});var ze="/:clientVersion/:schemaHash",E=b.basePath(ze);b.route("/",E);var Ge=["/graphql","/itx/:transactionId/graphql"];E.on("POST",[...Ge],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)}});E.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)}});E.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 k(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)});E.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 Je}from"hono/tiny";import{StatusCodes as We}from"http-status-codes";var I=new Je;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},We.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 nt(t,n,e),{promise:o,reject:s,resolve:i}=T(),a=Ze({createServer:Xe,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 D(t));console.error("[Accelerate]",p)}),await o,oe(t,a)}function oe(n,e){return{async close(){e&&await Promise.allSettled([Ye(e.close.bind(e))(),w.stopAll()])},port:n,url:`http://localhost:${n}`}}async function nt(n,e,t){let{debug:r}=t,o=new se,s=await et.getPlatformInfo();return r&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),r&&o.use("*",tt((...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("/",B),o}var B=new se;B.route("/",b);B.route("/",I);async function un(n){let e=await U.createExclusively(n),[t,r]=await Promise.all([_("database",e),_("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{le as DEFAULT_DATABASE_PORT,ue as DEFAULT_SERVER_PORT,me as DEFAULT_SHADOW_DATABASE_PORT,D as PortNotAvailableError,de as ServerAlreadyRunningError,un as unstable_startServer};
package/dist/state.cjs CHANGED
@@ -1,3 +1,3 @@
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});
1
+ "use strict";var ue=Object.create;var D=Object.defineProperty;var ce=Object.getOwnPropertyDescriptor;var de=Object.getOwnPropertyNames;var pe=Object.getPrototypeOf,le=Object.prototype.hasOwnProperty;var fe=(t,e)=>{for(var r in e)D(t,r,{get:e[r],enumerable:!0})},G=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of de(e))!le.call(t,a)&&a!==r&&D(t,a,{get:()=>e[a],enumerable:!(n=ce(e,a))||n.enumerable});return t};var L=(t,e,r)=>(r=t!=null?ue(pe(t)):{},G(e||!t||!t.__esModule?D(r,"default",{value:t,enumerable:!0}):r,t)),he=t=>G(D({},"__esModule",{value:!0}),t);var Te={};fe(Te,{ServerAlreadyRunningError:()=>j,ServerState:()=>b,ServerStateAlreadyExistsError:()=>R});module.exports=he(Te);var ae=require("fs/promises"),ne=require("hono/client"),y=require("pathe"),M=require("proper-lockfile"),J=require("std-env"),o=require("valibot");var W=require("fs"),f=require("fs/promises");var u=L(require("path"),1),U=L(require("os"),1),O=L(require("process"),1),h=U.default.homedir(),B=U.default.tmpdir(),{env:v}=O.default,me=t=>{let e=u.default.join(h,"Library");return{data:u.default.join(e,"Application Support",t),config:u.default.join(e,"Preferences",t),cache:u.default.join(e,"Caches",t),log:u.default.join(e,"Logs",t),temp:u.default.join(B,t)}},Pe=t=>{let e=v.APPDATA||u.default.join(h,"AppData","Roaming"),r=v.LOCALAPPDATA||u.default.join(h,"AppData","Local");return{data:u.default.join(r,t,"Data"),config:u.default.join(e,t,"Config"),cache:u.default.join(r,t,"Cache"),log:u.default.join(r,t,"Log"),temp:u.default.join(B,t)}},be=t=>{let e=u.default.basename(h);return{data:u.default.join(v.XDG_DATA_HOME||u.default.join(h,".local","share"),t),config:u.default.join(v.XDG_CONFIG_HOME||u.default.join(h,".config"),t),cache:u.default.join(v.XDG_CACHE_HOME||u.default.join(h,".cache"),t),log:u.default.join(v.XDG_STATE_HOME||u.default.join(h,".local","state"),t),temp:u.default.join(B,e,t)}};function N(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),O.default.platform==="darwin"?me(t):O.default.platform==="win32"?Pe(t):be(t)}var ge=require("pako"),ye=N("prisma-dev");function S(t){return`${ye.data}/${t}`}function X(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function Y(t){try{return await(0,f.readFile)(t,{encoding:"utf-8"})}catch(e){if(X(e))return null;throw e}}async function Z(t){await(0,f.mkdir)(t,{recursive:!0})}async function z(t){try{return(await(0,f.readdir)(t,{withFileTypes:!0})).reduce((r,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&r.push(n.name),r),[])}catch(e){if(X(e))return[];throw e}}var Q=require("std-env");function ee(t,e){if(t==null)return!1;try{return Q.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var P=require("get-port-please"),k=require("remeda"),T=51214,$=51213,A=51215,_=65535,m=-1/0;async function re(t){let{debug:e,name:r,requestedPorts:n,servers:a}=t,{portsUsedByOtherServers:s,portsUsedByThisServerLastTime:c}=we(r,a);e&&(console.debug(`ports used by other servers: ${Object.keys(s).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(c)}`));let d={databasePort:m,port:m,shadowDatabasePort:m},i=["port","databasePort","shadowDatabasePort"];for(let p of i){let l=await ve({debug:e,portKey:p,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:c,requestedPorts:n})??await Se({debug:e,pickedPorts:d,portKey:p,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:c});e&&console.debug(`Got port for "${p}": ${l}`),d[p]=l}return e&&console.debug(`Picked ports: ${JSON.stringify(d)}`),d}async function ve(t){let{debug:e,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:a,requestedPorts:s}=t,{[r]:c,...d}=s;if(te(c))return await De({debug:e,otherRequestedPorts:d,portKey:r,portsUsedByOtherServers:n,requestedPort:c}),c;let i=a?.[r]??m;if(!te(i))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let p=i in n;return p||Object.values(d).includes(i)?(e&&console.debug(`Port ${i} that was used last time for this server, ${p?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,P.checkPort)(i)===!1?(e&&console.debug(`Port ${i}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(e&&console.debug(`Using port ${i} for "${r}" as it was used last time and is available.`),i)}async function Se(t){let{debug:e,pickedPorts:r,portKey:n,portsUsedByOtherServers:a,portsUsedByThisServerLastTime:s}=t,c=Math.max(T,$,A)+1,d=[...Object.values(r),...Object.keys(a).map(Number),...Object.values(s||{})],i=Math.min(Math.max(c,...d)+100,_),p=(0,k.difference)((0,k.range)(c,i),d),l={port:$,databasePort:T,shadowDatabasePort:A}[n];try{return await(0,P.getPort)({port:l in a||Object.values(r).includes(l)||Object.values(s||{}).includes(l)?void 0:l,ports:p})}catch(g){if(g instanceof Error&&g.name==="GetPortError"&&i+1<=_)return e&&console.debug(`Expanding port lookup to range [${i+1}, ${_}].`),await(0,P.getPort)({portRange:[i+1,_]});throw g}}function te(t){return t>=0}function we(t,e){let r={},n;for(let a of e){let{databasePort:s,port:c,shadowDatabasePort:d}=a;if(a.name===t){n={databasePort:s,port:c,shadowDatabasePort:d};continue}r[s]=!0,r[c]=!0,r[d]=!0}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}async function De(t){let{debug:e,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:a,requestedPort:s}=t;if(s in a)throw e&&console.error(`Port ${s} was requested for "${n}", but is already used by another server.`),new I(s);if(Object.values(r).includes(s))throw e&&console.error(`Port ${s} was requested for "${n}", but also for another key.`),new F(s);if((0,P.isUnsafePort)(s))throw e&&console.error(`Port ${s} was requested for "${n}", but is unsafe.`),new E(s);if(await(0,P.checkPort)(s)===!1)throw e&&console.error(`Port ${s} was requested for "${n}", but is not available.`),new E(s)}var E=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},F=class extends Error{constructor(r){super(`Port number \`${r}\` was requested twice. Please choose a different port for each service.`);this.port=r}name="PortRequestedTwiceError"},I=class extends Error{constructor(r){super(`Port number \`${r}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=r}name="PortBelongsToAnotherServerError"};var C=(0,o.pipe)((0,o.string)(),(0,o.url)()),se=(0,o.object)({connectionString:C,prismaORMConnectionString:(0,o.optional)(C),terminalCommand:(0,o.optional)((0,o.string)())}),oe=(0,o.object)({url:C}),q=(0,o.pipe)((0,o.number)(),(0,o.integer)(),(0,o.minValue)(1)),Oe=(0,o.object)({database:se,http:oe,ppg:oe,shadowDatabase:se}),xe=(0,o.object)({databasePort:q,exports:(0,o.optional)(Oe),name:(0,o.pipe)((0,o.string)(),(0,o.minLength)(1)),pid:(0,o.optional)((0,o.pipe)((0,o.number)(),(0,o.integer)(),(0,o.minValue)(0))),port:q,shadowDatabasePort:q,version:(0,o.literal)("1")}),K=Symbol("initialize"),V="default",b=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??m,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??V,this.persistenceMode=e.persistenceMode,this.pid=e.pid??J.process.pid,this._port=e.port??m,this._shadowDatabasePort=e.shadowDatabasePort??m}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new w(e):new H(e);return await r[K](),r}static async fromServerDump(e){let{debug:r,name:n=V}=e??{},a=S(n),s=w.getServerDumpPath(a),c=await Y(s);if(c==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(c));let{issues:d,output:i,success:p}=(0,o.safeParse)((0,o.pipe)((0,o.string)(),(0,o.parseJson)(),xe),c);if(!p)throw r&&console.debug(`[State] Invalid server dump file at "${s}":
2
+ ${JSON.stringify(d,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new w({databasePort:i.databasePort,debug:r,dryRun:!1,name:n,pid:i.pid,port:i.port,serverDump:i,shadowDatabasePort:i.shadowDatabasePort})}static async scan(e){let{debug:r}=e??{},n=(0,y.join)(S(V),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let a=await z(n);return r&&console.debug(`[State] found server names: ${JSON.stringify(a)}`),await Promise.all(a.map(s=>_e(s,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},H=class extends b{constructor(e){super({...e,databasePort:e?.databasePort??T,persistenceMode:"stateless",port:e?.port??$,shadowDatabasePort:e?.shadowDatabasePort??A})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[K](){}async close(){}async writeServerDump(){}},w=class t extends b{#t;#e;#o;#a;#r;#s=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=S(this.name),this.#t=(0,y.join)(this.#e,"db_dump.bak"),this.#o=(0,y.join)(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#a=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,y.join)(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get pgliteDataDirPath(){return this.#o}async[K](){await Z(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#s=await(0,M.lock)(this.#e,{lockfilePath:(0,y.join)(this.#e,".lock")}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await b.scan({debug:this.debug,onlyMetadata:!0}),r=await re({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new j(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:J.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,ae.writeFile)(this.#a,`${JSON.stringify(this.#r,null,2)}
3
+ `,{encoding:"utf-8"})}};async function _e(t,e){let{debug:r,onlyMetadata:n}=e||{},a={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let s=await b.fromServerDump({debug:r,name:t});if(!s)return r&&console.debug(`[State] no server state found for name: ${t}`),{...a,status:"no_such_server"};a.databasePort=s.databasePort,a.exports=s.exports,a.pid=s.pid,a.port=s.port,a.shadowDatabasePort=s.shadowDatabasePort;let{exports:c,pid:d}=s;if(n)return{...a,status:"unknown"};if(!ee(d,r))return r&&console.debug(`[State] server state for "${t}" has no running process with PID: ${d}`),{...a,status:"not_running"};let i=S(t);try{if(!await(0,M.check)(i,{lockfilePath:(0,y.join)(i,".lock")}))return r&&console.debug(`[State] server state for "${t}" is not locked, indicating it is not running.`),{...a,status:"starting_up"}}catch(ie){r&&console.error(`[State] server state for "${t}" failed to check lock:`,ie)}if(!c)return{...a,status:"starting_up"};let{http:p}=c,l=await(0,ne.hc)(p.url).health.$get();if(!l.ok)return r&&console.debug(`[State] server state for "${t}" is not live: ${JSON.stringify(l)}`),{...a,status:"not_running"};let g=await l.json();return g.name!==t?(r&&console.debug(`[State] server state for "${t}" has mismatched health response: ${JSON.stringify(g)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(g)}`),{...a,status:"running"})}catch(s){return r&&console.error(`[State] failed to get server status for "${t}":`,s),{...a,status:"error"}}}var R=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},j=class extends R{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return b.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};0&&(module.exports={ServerAlreadyRunningError,ServerState,ServerStateAlreadyExistsError});
package/dist/state.d.cts CHANGED
@@ -101,20 +101,21 @@ type ResolvedServerOptions = Required<ServerOptions>;
101
101
  type PersistenceMode = "stateless" | "stateful";
102
102
  interface ScanOptions {
103
103
  debug?: boolean;
104
+ onlyMetadata?: boolean;
104
105
  }
105
106
  declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
106
107
  declare abstract class ServerState implements ResolvedServerOptions {
107
- readonly databasePort: number;
108
+ protected _databasePort: number;
108
109
  readonly debug: boolean;
109
110
  readonly dryRun: boolean;
110
111
  readonly name: string;
111
112
  readonly persistenceMode: PersistenceMode;
112
113
  readonly pid: number | undefined;
113
- readonly port: number;
114
- readonly shadowDatabasePort: number;
114
+ protected _port: number;
115
+ protected _shadowDatabasePort: number;
115
116
  protected constructor(options: Omit<ServerOptions, "persistenceMode"> & {
116
117
  persistenceMode: PersistenceMode;
117
- pid: number | undefined;
118
+ pid?: number | undefined;
118
119
  });
119
120
  static createExclusively(options: ServerOptions | undefined): Promise<ServerState>;
120
121
  static fromServerDump(options?: Pick<ServerOptions, "debug" | "name">): Promise<StatefulServerState | null>;
@@ -124,13 +125,16 @@ declare abstract class ServerState implements ResolvedServerOptions {
124
125
  abstract [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
125
126
  abstract close(): Promise<void>;
126
127
  abstract writeServerDump(exports?: Exports): Promise<void>;
128
+ get databasePort(): number;
129
+ get port(): number;
130
+ get shadowDatabasePort(): number;
127
131
  }
128
132
  declare class StatefulServerState extends ServerState {
129
133
  #private;
130
- constructor(options: Omit<ServerOptions, "persistenceMode"> & {
131
- pid: number | undefined;
134
+ constructor(options: (Omit<ServerOptions, "persistenceMode"> & {
135
+ pid?: number | undefined;
132
136
  serverDump?: ServerDumpV1;
133
- });
137
+ }) | undefined);
134
138
  static getServerDumpPath(dataDirPath: string): string;
135
139
  get databaseDumpPath(): string;
136
140
  get exports(): Exports | undefined;
package/dist/state.d.ts CHANGED
@@ -101,20 +101,21 @@ type ResolvedServerOptions = Required<ServerOptions>;
101
101
  type PersistenceMode = "stateless" | "stateful";
102
102
  interface ScanOptions {
103
103
  debug?: boolean;
104
+ onlyMetadata?: boolean;
104
105
  }
105
106
  declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
106
107
  declare abstract class ServerState implements ResolvedServerOptions {
107
- readonly databasePort: number;
108
+ protected _databasePort: number;
108
109
  readonly debug: boolean;
109
110
  readonly dryRun: boolean;
110
111
  readonly name: string;
111
112
  readonly persistenceMode: PersistenceMode;
112
113
  readonly pid: number | undefined;
113
- readonly port: number;
114
- readonly shadowDatabasePort: number;
114
+ protected _port: number;
115
+ protected _shadowDatabasePort: number;
115
116
  protected constructor(options: Omit<ServerOptions, "persistenceMode"> & {
116
117
  persistenceMode: PersistenceMode;
117
- pid: number | undefined;
118
+ pid?: number | undefined;
118
119
  });
119
120
  static createExclusively(options: ServerOptions | undefined): Promise<ServerState>;
120
121
  static fromServerDump(options?: Pick<ServerOptions, "debug" | "name">): Promise<StatefulServerState | null>;
@@ -124,13 +125,16 @@ declare abstract class ServerState implements ResolvedServerOptions {
124
125
  abstract [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
125
126
  abstract close(): Promise<void>;
126
127
  abstract writeServerDump(exports?: Exports): Promise<void>;
128
+ get databasePort(): number;
129
+ get port(): number;
130
+ get shadowDatabasePort(): number;
127
131
  }
128
132
  declare class StatefulServerState extends ServerState {
129
133
  #private;
130
- constructor(options: Omit<ServerOptions, "persistenceMode"> & {
131
- pid: number | undefined;
134
+ constructor(options: (Omit<ServerOptions, "persistenceMode"> & {
135
+ pid?: number | undefined;
132
136
  serverDump?: ServerDumpV1;
133
- });
137
+ }) | undefined);
134
138
  static getServerDumpPath(dataDirPath: string): string;
135
139
  get databaseDumpPath(): string;
136
140
  get exports(): Exports | undefined;
package/dist/state.js CHANGED
@@ -1 +1 @@
1
- import{a,b,c}from"./chunk-LBY4H4LD.js";import"./chunk-Q3M6SQC2.js";export{c as ServerAlreadyRunningError,a as ServerState,b as ServerStateAlreadyExistsError};
1
+ import{a,b,c}from"./chunk-BS26VSZW.js";import"./chunk-H6HHF4W5.js";export{c as ServerAlreadyRunningError,a as ServerState,b as ServerStateAlreadyExistsError};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/dev",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "A local Prisma Postgres server for development and testing",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -66,11 +66,11 @@
66
66
  "@types/node": "22.15.21",
67
67
  "@types/pako": "2.0.3",
68
68
  "@types/proper-lockfile": "4.1.4",
69
+ "env-paths": "3.0.0",
69
70
  "pkg-types": "2.1.0",
70
71
  "tsup": "8.5.0",
71
72
  "typescript": "5.8.3",
72
73
  "vitest": "3.1.4",
73
- "env-paths": "3.0.0",
74
74
  "common-stuff": "^0.0.0"
75
75
  },
76
76
  "dependencies": {
@@ -80,12 +80,14 @@
80
80
  "@hono/node-server": "1.14.2",
81
81
  "@prisma/get-platform": "6.8.2",
82
82
  "foreground-child": "3.3.1",
83
+ "get-port-please": "3.1.2",
83
84
  "hono": "4.7.10",
84
85
  "http-status-codes": "2.3.0",
85
86
  "pako": "2.1.0",
86
87
  "pathe": "2.0.3",
87
88
  "proper-lockfile": "4.1.2",
88
89
  "read-last-lines-ts": "1.2.1",
90
+ "remeda": "2.21.3",
89
91
  "sock-daemon": "1.4.2",
90
92
  "std-env": "3.9.0",
91
93
  "valibot": "1.1.0"
@@ -1 +0,0 @@
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};
@@ -1,3 +0,0 @@
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 +0,0 @@
1
- import{createWriteStream as j,WriteStream as P}from"fs";import{access as y,chmod as E,constants as x,mkdir as T,readdir as w,readFile as _,writeFile as v}from"fs/promises";import o from"path";import g from"os";import c from"process";var i=g.homedir(),a=g.tmpdir(),{env:n}=c,m=r=>{let t=o.join(i,"Library");return{data:o.join(t,"Application Support",r),config:o.join(t,"Preferences",r),cache:o.join(t,"Caches",r),log:o.join(t,"Logs",r),temp:o.join(a,r)}},h=r=>{let t=n.APPDATA||o.join(i,"AppData","Roaming"),e=n.LOCALAPPDATA||o.join(i,"AppData","Local");return{data:o.join(e,r,"Data"),config:o.join(t,r,"Config"),cache:o.join(e,r,"Cache"),log:o.join(e,r,"Log"),temp:o.join(a,r)}},D=r=>{let t=o.basename(i);return{data:o.join(n.XDG_DATA_HOME||o.join(i,".local","share"),r),config:o.join(n.XDG_CONFIG_HOME||o.join(i,".config"),r),cache:o.join(n.XDG_CACHE_HOME||o.join(i,".cache"),r),log:o.join(n.XDG_STATE_HOME||o.join(i,".local","state"),r),temp:o.join(a,t,r)}};function p(r,{suffix:t="nodejs"}={}){if(typeof r!="string")throw new TypeError(`Expected a string, got ${typeof r}`);return t&&(r+=`-${t}`),c.platform==="darwin"?m(r):c.platform==="win32"?h(r):D(r)}import{inflate as O}from"pako";var d=p("prisma-dev");function G(r,t){return`${d.cache}/engine/${r}/${t}`}function N(r){return`${d.data}/${r}`}async function W(r){try{return await y(r,x.F_OK),!0}catch(t){if(u(t))return!1;throw t}}async function k(r,t){let e=O(r);await v(t,e),await E(t,"755")}async function M(r,t){await r.stream().pipeTo(P.toWeb(j(t,{encoding:"utf-8"})))}function u(r){return r!=null&&typeof r=="object"&&"code"in r&&r.code==="ENOENT"}async function X(r){try{return await _(r,{encoding:"utf-8"})}catch(t){if(u(t))return null;throw t}}async function U(r){await T(r,{recursive:!0})}async function I(r){try{return(await w(r,{withFileTypes:!0})).reduce((e,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&e.push(s.name),e),[])}catch(t){if(u(t))return[];throw t}}var V=51214,q=51213,z=51215,A=class extends Error{constructor(e,s){super(`Port number \`${e}\` is not available for service ${s}.`);this.port=e;this.service=s}name="PortNotAvailableError"};export{G as a,N as b,W as c,k as d,M as e,X as f,U as g,I as h,V as i,q as j,z as k,A as l};