@prisma/dev 0.6.1 → 0.7.1

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