@prisma/dev 0.0.0-dev.202506071014 → 0.0.0-dev.202506071020

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