@prisma/dev 0.0.0-dev.202506040041 → 0.0.0-dev.202506040107

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,2 @@
1
+ import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
+ import{e as l,j as m}from"./chunk-HWX5WUGO.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};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
+ import{createWriteStream as a,WriteStream as c}from"fs";import{access as u,chmod as p,constants as l,readFile as m,writeFile as f}from"fs/promises";import g from"env-paths";import{inflate as x}from"pako";var o=g("prisma-dev");function T(r,e){return`${o.cache}/engine/${r}/${e}`}function D(r){return`${o.data}/${r}`}async function F(r){try{return await u(r,l.F_OK),!0}catch(e){if(n(e))return!1;throw e}}async function b(r,e){let t=x(r);await f(e,t),await p(e,"755")}async function v(r,e){await r.stream().pipeTo(c.toWeb(a(e,{encoding:"utf-8"})))}function n(r){return r!=null&&typeof r=="object"&&"code"in r&&r.code==="ENOENT"}async function y(r){try{return await m(r,{encoding:"utf-8"})}catch(e){if(n(e))return null;throw e}}var _=51214,h=51213,w=51215,i=class extends Error{constructor(t,s){super(`Port number \`${t}\` is not available for service ${s}.`);this.port=t;this.service=s}name="PortNotAvailableError"};export{T as a,D as b,F as c,b as d,v as e,y as f,_ as g,h,w as i,i as j};
@@ -0,0 +1,4 @@
1
+ import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
+ import{b as m,f as D,g as f,h as y,i as S}from"./chunk-HWX5WUGO.js";import{mkdir as k,writeFile as L}from"fs/promises";import{join as n}from"pathe";import{lock as V}from"proper-lockfile";import{process as d}from"std-env";import{integer as M,literal as F,minLength as N,minValue as x,number as R,object as p,optional as w,parseJson as U,pipe as a,safeParse as B,string as g,url as j}from"valibot";var I=a(g(),j()),O=p({connectionString:I}),E=p({url:I}),h=a(R(),M(),x(1)),J=p({database:O,http:E,ppg:E,shadowDatabase:O}),C=p({databasePort:h,exports:w(J),name:a(g(),N(1)),pid:w(a(R(),M(),x(0))),port:h,shadowDatabasePort:h,version:F("1")}),v=Symbol("initialize"),A="default",u=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??A,this.persistenceMode=e.persistenceMode,this.pid=e.pid??d.pid,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async createExclusively(e){let t=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new s({...e,pid:d.pid}):new b(e);return await t[v](),t}static async fromServerDump(e){let{debug:t,name:c=A}=e??{},T=m(c),o=s.getServerDumpPath(T),l=await D(o);if(l==null)return t&&console.debug(`[State] No server dump file found at: ${o}`),null;t&&(console.debug(`[State] server dump file found at "${o}":`),console.debug(l));let{issues:_,output:r,success:$}=B(a(g(),U(),C),l);if(!$)throw t&&console.debug(`[State] Invalid server dump file at "${o}":
3
+ ${JSON.stringify(_,null,2)}`),new Error(`Invalid Prisma Dev state for "${c}".`);return new s({databasePort:r.databasePort,debug:t,dryRun:!1,name:c,pid:r.pid,port:r.port,serverDump:r,shadowDatabasePort:r.shadowDatabasePort})}},b=class extends u{constructor(e){super({...e,persistenceMode:"stateless",pid:d.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[v](){}async close(){}async writeServerDump(){}},s=class i extends u{#s;#e;#a;#i;#r;#t=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=m(this.name),this.#s=n(this.#e,"db_dump.bak"),this.#a=n(this.#e,".pglite"),this.#r=e.serverDump??null,this.#i=i.getServerDumpPath(this.#e)}static getServerDumpPath(e){return n(e,"server.json")}get databaseDumpPath(){return this.#s}get pgliteDataDirPath(){return this.#a}async[v](){await k(this.#e,{recursive:!0}),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#t=await V(this.#e,{lockfilePath:n(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 P(this.name):e}}async close(){if(this.#t!=null)try{await this.#t(),this.#t=null,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw console.error(`[State] failed to release lock on: ${this.#e}`),e}}async writeServerDump(e){this.#r={name:this.name,version:"1",pid:d.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await L(this.#i,`${JSON.stringify(this.#r,null,2)}
4
+ `,{encoding:"utf-8"})}},P=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A server with the name "${e}" is already running.`)}};export{u as a,P as b};
@@ -1,7 +1,8 @@
1
1
  import * as url from 'url';
2
2
  import { SockDaemonClient } from 'sock-daemon/client';
3
- import { S as ServerOptions, a as Server } from '../index-BY1kJS25.js';
3
+ import { S as ServerOptions, a as Server } from '../db-mXLGDv93.js';
4
4
  import { MessageBase } from 'sock-daemon/server';
5
+ import '@electric-sql/pglite';
5
6
  import 'valibot';
6
7
 
7
8
  type Kind = "START_SERVER" | "STOP_SERVER";
@@ -1,6 +1,23 @@
1
+ import { PGlite } from '@electric-sql/pglite';
1
2
  import * as valibot from 'valibot';
2
3
  import { InferOutput } from 'valibot';
3
4
 
5
+ declare const DEFAULT_DATABASE_PORT = 51214;
6
+ declare const DEFAULT_SERVER_PORT = 51213;
7
+ declare const DEFAULT_SHADOW_DATABASE_PORT = 51215;
8
+ type PortAssignableService = DBServerPurpose | "server";
9
+ declare class PortNotAvailableError extends Error {
10
+ port: number;
11
+ service: PortAssignableService;
12
+ name: string;
13
+ constructor(port: number, service: PortAssignableService);
14
+ }
15
+
16
+ interface Server extends Exports {
17
+ close(): Promise<void>;
18
+ }
19
+ declare function unstable_startServer(options?: ServerOptions): Promise<Server>;
20
+
4
21
  declare const exportsSchema: valibot.ObjectSchema<{
5
22
  readonly database: valibot.ObjectSchema<{
6
23
  readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
@@ -105,7 +122,7 @@ declare abstract class ServerState implements ResolvedServerOptions {
105
122
  persistenceMode: PersistenceMode;
106
123
  pid: number | undefined;
107
124
  });
108
- static create(options: ServerOptions | undefined): Promise<ServerState>;
125
+ static createExclusively(options: ServerOptions | undefined): Promise<ServerState>;
109
126
  static fromServerDump(options?: Pick<ServerOptions, "debug" | "name">): Promise<ServerState | null>;
110
127
  abstract get databaseDumpPath(): string;
111
128
  abstract get pgliteDataDirPath(): string;
@@ -118,22 +135,37 @@ declare class ServerStateAlreadyExistsError extends Error {
118
135
  constructor(name: string);
119
136
  }
120
137
 
121
- type DBServerPurpose = "database" | "shadow_database";
122
-
123
- declare const DEFAULT_DATABASE_PORT = 51214;
124
- declare const DEFAULT_SERVER_PORT = 51213;
125
- declare const DEFAULT_SHADOW_DATABASE_PORT = 51215;
126
- type PortAssignableService = DBServerPurpose | "server";
127
- declare class PortNotAvailableError extends Error {
128
- port: number;
129
- service: PortAssignableService;
130
- name: string;
131
- constructor(port: number, service: PortAssignableService);
132
- }
133
-
134
- interface Server extends Exports {
138
+ interface DBServer {
135
139
  close(): Promise<void>;
140
+ readonly connectionLimit: number;
141
+ readonly connectionString: string;
142
+ readonly connectTimeout: number;
143
+ readonly database: string;
144
+ dump(destinationPath: string): Promise<void>;
145
+ readonly maxIdleConnectionLifetime: number;
146
+ readonly password: string;
147
+ readonly poolTimeout: number;
148
+ readonly port: number;
149
+ readonly socketTimeout: number;
150
+ readonly sslMode: string;
151
+ readonly username: string;
136
152
  }
137
- declare function unstable_startServer(options?: ServerOptions): Promise<Server>;
153
+ interface DBDump {
154
+ dumpPath: string;
155
+ }
156
+ type DBServerPurpose = "database" | "shadow_database";
157
+ declare function startDBServer(purpose: DBServerPurpose, serverState: ServerState): Promise<DBServer>;
158
+ type DumpDBOptions<D extends string> = {
159
+ dataDir: string;
160
+ db?: never;
161
+ debug?: boolean;
162
+ destinationPath?: D;
163
+ } | {
164
+ dataDir?: never;
165
+ db: PGlite;
166
+ debug?: boolean;
167
+ destinationPath?: D;
168
+ };
169
+ declare function dumpDB<D extends string = never>(options: DumpDBOptions<D>): Promise<[D] extends [never] ? string : void>;
138
170
 
139
- export { DEFAULT_DATABASE_PORT as D, type Exports as E, type PersistenceMode as P, type ResolvedServerOptions as R, type ServerOptions as S, type Server as a, type ServerDumpV1 as b, ServerState as c, ServerStateAlreadyExistsError as d, DEFAULT_SERVER_PORT as e, DEFAULT_SHADOW_DATABASE_PORT as f, type PortAssignableService as g, PortNotAvailableError as h, unstable_startServer as u };
171
+ export { DEFAULT_DATABASE_PORT as D, type Exports as E, type PortAssignableService as P, type ResolvedServerOptions as R, type ServerOptions as S, type Server as a, DEFAULT_SERVER_PORT as b, DEFAULT_SHADOW_DATABASE_PORT as c, PortNotAvailableError as d, type ServerDumpV1 as e, type PersistenceMode as f, ServerState as g, ServerStateAlreadyExistsError as h, type DBServer as i, type DBDump as j, type DBServerPurpose as k, type DumpDBOptions as l, dumpDB as m, startDBServer as s, unstable_startServer as u };
package/dist/db.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import '@electric-sql/pglite';
2
+ export { j as DBDump, i as DBServer, k as DBServerPurpose, l as DumpDBOptions, m as dumpDB, s as startDBServer } from './db-mXLGDv93.js';
3
+ import 'valibot';
package/dist/db.js ADDED
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
+ import{a,b}from"./chunk-2XOXBODY.js";import"./chunk-HWX5WUGO.js";export{b as dumpDB,a as startDBServer};
package/dist/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
- export { D as DEFAULT_DATABASE_PORT, e as DEFAULT_SERVER_PORT, f as DEFAULT_SHADOW_DATABASE_PORT, g as PortAssignableService, h as PortNotAvailableError, a as Server, u as unstable_startServer } from './index-BY1kJS25.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-mXLGDv93.js';
2
+ import '@electric-sql/pglite';
2
3
  import 'valibot';
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{a as B,b as L,c as j,d as N,e as rt,f as ot,g as st,h as v,i as U}from"./chunk-A33H6MPG.js";import{HTTPException as P}from"hono/http-exception";import{object as ce,optional as le,parseJson as de,pipe as H,regex as q,safeParse as ue,string as I,url as M}from"valibot";var V=/^(postgres|postgresql):\/\//,me=H(I(),de(),ce({databaseUrl:H(I(),M(),q(V)),shadowDatabaseUrl:le(H(I(),M(),q(V)))}));function K(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function pe(e){let t=Buffer.from(e,"base64url").toString("utf8"),{issues:n,output:r,success:o}=ue(me,t,{abortEarly:!0});return o?[null,r]:[n]}var g=(e,t)=>{let{authorization:n}=e;if(!n)throw new P(401,{message:"Missing API Key"});let[r,o="",s]=n.split(" ");if(r!=="Bearer"||s)throw new P(401,{message:"Invalid API Key"});let[i,a]=pe(o);if(i)throw new P(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:c}=a;if(c!==t.var.db.connectionString)throw new P(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{PGlite as ge}from"@electric-sql/pglite";import{PGLiteSocketServer as fe}from"@electric-sql/pglite-socket";import{pgDump as he}from"@electric-sql/pglite-tools/pg_dump";import{filename as ye}from"pathe/utils";var l={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},we=`postgres://${l.username}:${l.password}@localhost`,Se=new URLSearchParams({connection_limit:String(l.connectionLimit),connect_timeout:String(l.connectTimeout),max_idle_connection_lifetime:String(l.maxIdleConnectionLifetime),pool_timeout:String(l.poolTimeout),socket_timeout:String(l.socketTimeout),sslmode:l.sslMode});async function O(e,t){let n=e==="database"?t.databasePort:t.shadowDatabasePort;if(t.dryRun)return Q(e,t,{db:null,port:n,server:null});let{debug:r}=t,o=await ge.create({database:l.database,dataDir:e==="database"?t.pgliteDataDirPath:"memory://",debug:r?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:l.username});r&&o.onNotification((i,a)=>{console.debug(`[${e}][${i}] ${a}`)});let s=new fe({db:o,debug:r,inspect:r,port:n});r&&(s.addEventListener("listening",i=>{let{detail:a}=i;console.debug(`[${e}] server listening on ${JSON.stringify(a)}`)}),s.addEventListener("connection",i=>{let{clientAddress:a,clientPort:c}=i.detail;console.debug(`[${e}] client connected from ${a}:${c}`)}),s.addEventListener("error",i=>{let{detail:a}=i;console.error(`[${e}] server error:`,a)}));try{await s.start()}catch(i){throw i instanceof Error&&"code"in i&&i.code==="EADDRINUSE"?new v(n,e):i}return Q(e,t,{db:o,port:n,server:s})}function Q(e,t,n){let{debug:r}=t,{db:o,port:s,server:i}=n||{};return r&&console.debug(`[${e}] server started on port ${s}`),{...l,close:async()=>{let a=[];try{await i?.stop(),r&&console.debug(`[${e}] server stopped on port ${s}`)}catch(c){console.error(`[${e}] server stop error`,c),a.push(c)}if(e==="database")try{await o?.syncToFs(),r&&console.debug(`[${e}] synced to filesystem`)}catch(c){console.error(`[${e}] sync error`,c),a.push(c)}try{await o?.close(),r&&console.debug(`[${e}] closed`)}catch(c){console.error(`[${e}] close error`,c),a.push(c)}if(a.length>0)throw new AggregateError(a,`Failed to close ${e} properly`)},connectionString:be(s),dump:async()=>{if(!o||e==="shadow_database")return{dumpPath:""};let{databaseDumpPath:a}=t,c=await he({args:["--format=custom","--quote-all-identifiers","--schema-only","--verbose"],fileName:ye(a),pg:o});return await N(c,a),{dumpPath:a}},port:s}}function be(e){return`${we}:${e}/${l.database}?${Se.toString()}`}import{createServer as Xe}from"http";import{promisify as We}from"util";import{serve as Ze}from"@hono/node-server";import et from"@prisma/get-platform";function E(){let e,t,n=new Promise((s,i)=>{e=s,t=i}),r=s=>{r=o=null,t(s)},o=s=>{o=r=null,e(s)};return{promise:n,reject:s=>r?.(s),resolve:s=>o?.(s)}}import{logger as tt}from"hono/logger";import{Hono as se}from"hono/tiny";import{Hono as Fe}from"hono/tiny";import{validator as w}from"hono/validator";import{array as ve,literal as Pe,minLength as Ee,object as Te,pipe as Re,safeParse as Ae,string as xe,union as He}from"valibot";var Ie=Te({tags:He([Re(ve(xe()),Ee(1)),Pe("all")])});async function F(e){let{output:t,success:n}=Ae(Ie,await e.req.json(),{abortEarly:!0});return n?t:e.text("Invalid input",400)}import{spawn as Oe}from"child_process";import{once as $e}from"events";import{mkdir as Ce}from"fs/promises";import{join as De}from"path";import{setTimeout as ke}from"timers/promises";import{proxySignals as _e}from"foreground-child/proxy-signals";import{process as Be}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Le,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:je,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:G}=Be.env,h=class e{static#n=new Map;#e;#t;constructor(t){this.#e=t,this.#t=null}static async get(t){let{debug:n}=t,r=`${t.schemaHash}:${t.clientVersion}`;try{let o=e.#n.get(r);if(o)return o;let s=new e(t);return e.#n.set(r,s),n&&console.debug("[Query Engine] starting...",t),await s.start(),n&&console.debug("[Query Engine] started!"),s}finally{e.stopAll(r)}}static async stopAll(t){let r=(await Promise.allSettled(Array.from(e.#n.entries()).filter(([o])=>o!==t).map(async([o,s])=>{try{await s.stop()}finally{e.#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(t,n){return await this.#o(t,n,"commit")}async request(t,n){let{url:r}=await this.start(),o=this.#r(n),s=await fetch(r,{body:typeof t=="string"?t:JSON.stringify(t),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await f.fromResponse(s);return await s.text()}async rollbackTransaction(t,n){return await this.#o(t,n,"rollback")}async startTransaction(t,n){let{url:r}=await this.start(),o=this.#r(n),s=await fetch(`${r}/transaction/start`,{body:JSON.stringify(t),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await f.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:t,reject:n,resolve:r}=E();this.#t=t;let o=je||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=Oe(o,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});_e(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let i=d=>{let m=d.split(`
3
- `).find(ae=>ae.includes("Started query engine http server"));if(!m)return;s.stdout.removeListener("data",i);let{fields:p}=JSON.parse(m);if(p==null)return n(new Error(`Unexpected data during initialization, "fields" are missing: ${d}`));let{ip:u,port:_}=p;if(u==null||_==null)return n(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
4
- Received data: ${d}`));r({childProcess:s,url:`http://${u}:${_}`})},a=d=>{this.#t=null,n(new y(String(d))),s.removeListener("exit",c),s.kill()};s.once("error",a);let c=(d,m)=>{this.#t=null,n(new y(`Query Engine exited with code ${d} and signal ${m}`))};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:t}=await this.#t;t.exitCode==null&&t.signalCode==null&&(this.#t=null,t.kill(),await $e(t,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let t=await this.#i();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",t);let n=B(this.#e.clientVersion,t);this.#e.debug&&console.debug("[Query Engine] cache directory path",n),await Ce(n,{recursive:!0});let{platform:r}=this.#e.platform,o=r==="windows"?".exe":"",s=De(n,`query-engine-${r}${o}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(Le==="1"||await L(s)===!1)&&await this.#a({commitHash:t,extension:o,engineBinaryPath:s}),s}async#i(){let t=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!t.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${t.status}`);let r=(await t.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(t){let{commitHash:n,extension:r,engineBinaryPath:o}=t,{binaryTarget:s}=this.#e.platform,i=`https://binaries.prisma.sh/all_commits/${n}/${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}`);G&&await ke(Number(G)),await j(await a.arrayBuffer(),o),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",o)}#r(t){let n={};for(let[r,o]of Object.entries(t))o!=null&&(n[r]=o);return n}async#o(t,n,r){let{url:o}=await this.#t,s=this.#r(n),i=await fetch(`${o}/transaction/${t}/${r}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await f.fromResponse(i);try{return await i.json()}catch{return{}}}};function T(e,t){return console.error(e),e instanceof y?t.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:e.message}}}},500):e instanceof f?t.text(e.responseBody,e.statusCode):t.body(null,500)}var y=class extends Error{name="EngineStartError"},f=class e extends Error{constructor(n,r,o){super(`${n}: Query Engine response status ${r}, body: ${o}`);this.action=n;this.statusCode=r;this.responseBody=o}name="EngineHttpError";static async fromResponse(n){let r=new URL(n.url),o=await n.text();return new e(r.pathname,n.status,o)}};import{Buffer as J}from"buffer";var R=new Map;async function $(e){let n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}function z(e){let t=e.req.param("schemaHash"),n=R.get(t);return n==null?e.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:t,schemas:n}}var Ne=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function Y(e,t){let n=J.from(e,"base64").toString("utf8"),r=`datasource db {
2
+ import{a as A}from"./chunk-2XOXBODY.js";import{a as L}from"./chunk-T2ZEK4IZ.js";import{a as $,c as j,d as D,g as ze,h as Ge,i as Je,j as B}from"./chunk-HWX5WUGO.js";import{HTTPException as v}from"hono/http-exception";import{object as se,optional as ie,parseJson as ae,pipe as H,regex as q,safeParse as ce,string as I,url as N}from"valibot";var V=/^(postgres|postgresql):\/\//,pe=H(I(),ae(),se({databaseUrl:H(I(),N(),q(V)),shadowDatabaseUrl:ie(H(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 fe,safeParse as he,string as ye,union as we}from"valibot";var Se=ge({tags:we([fe(le(ye()),de(1)),me("all")])});async function K(n){let{output:e,success:t}=he(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 Ae}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:He,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:Ie,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:M}=Ae.env,f=class n{static#n=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let{debug:t}=e,r=`${e.schemaHash}:${e.clientVersion}`;try{let o=n.#n.get(r);if(o)return o;let s=new n(e);return n.#n.set(r,s),t&&console.debug("[Query Engine] starting...",e),await s.start(),t&&console.debug("[Query Engine] started!"),s}finally{n.stopAll(r)}}static async stopAll(e){let r=(await Promise.allSettled(Array.from(n.#n.entries()).filter(([o])=>o!==e).map(async([o,s])=>{try{await s.stop()}finally{n.#n.delete(o)}}))).filter(o=>o.status==="rejected").map(o=>o.reason);if(r.length>0)throw new AggregateError(r,"Failed to stop engines")}async commitTransaction(e,t){return await this.#o(e,t,"commit")}async request(e,t){let{url:r}=await this.start(),o=this.#r(t),s=await fetch(r,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await 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(`
3
+ `).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.
4
+ Received data: ${p}`));r({childProcess:s,url:`http://${u}:${_}`})},a=p=>{this.#t=null,t(new h(String(p))),s.removeListener("exit",c),s.kill()};s.once("error",a);let c=(p,l)=>{this.#t=null,t(new h(`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),(He==="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 h?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:n.message}}}},500):n instanceof g?e.text(n.responseBody,n.statusCode):e.body(null,500)}var h=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 {
5
5
  provider = "postgresql"
6
- url = "${t.toString()}"
7
- }`,o=n.replace(Ne,r),s=await $(o);return{base64Override:J.from(o,"utf8").toString("base64"),overrideHash:s}}function A(e){let{req:t}=e;return{traceparent:t.header("traceparent"),"X-capture-telemetry":t.header("X-capture-telemetry")}}import{integer as X,looseObject as Ue,minValue as W,number as C,object as qe,optional as Me,pipe as Z,safeParse as ee,string as te,union as Ve}from"valibot";var Ke=qe({isolation_level:Me(te()),max_wait:Z(C(),X(),W(0)),timeout:Z(C(),X(),W(0))});async function ne(e){let{issues:t,output:n,success:r}=ee(Ke,await e.req.json(),{abortEarly:!0});return r?n:e.json({EngineNotStarted:{reason:"InvalidRequest",issues:t}},400)}var Qe=Ue({id:Ve([te(),C()])});function re(e,t){let{output:n,success:r}=ee(Qe,e);return r?n:t.json({EngineMalfunction:{}},500)}var S=new Fe;S.post("/invalidate",w("header",g),async e=>{let t=await F(e);return t instanceof Response?t:e.body(null)});var Ge="/:clientVersion/:schemaHash",b=S.basePath(Ge);S.route("/",b);var Je=["/graphql","/itx/:transactionId/graphql"];b.on("POST",[...Je],w("header",g),async e=>{let{req:t}=e;try{let n=await D(e);if(n instanceof Response)return n;let r=await t.text(),o=t.param("transactionId"),s=await n.request(r,{...A(e),"X-transaction-id":o});return e.text(s)}catch(n){return T(n,e)}});b.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],w("header",g),async e=>{let{req:t}=e;try{let n=await D(e);if(n instanceof Response)return n;let o=`${t.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=t.param("transactionId"),i=await n[o](s,A(e));return e.json(i)}catch(n){return T(n,e)}});b.put("/schema",w("header",g),async e=>{let{req:t}=e,n=await t.text();if(!n)return e.text("Missing schema",400);let r=t.param("schemaHash"),o=R.get(r);if(o==null){if(r!==await $(n))return e.text("Schema hash mismatch",400);let s=new URL(e.get("db").connectionString);s.searchParams.set("single_use_connections","true");let i=await Y(n,s);return R.set(r,{base64Original:n,...i}),e.text(r)}return n!==o.base64Original?e.text("Schema mismatch",400):e.text(r)});b.post("/transaction/start",w("header",g),async e=>{let{req:t}=e,n=await ne(e);if(n instanceof Response)return n;try{let r=await D(e);if(r instanceof Response)return r;let o=await r.startTransaction(n,A(e)),s=re(o,e);if(s instanceof Response)return s;let{id:i}=s,a=t.param("clientVersion"),c=e.get("port"),d=e.get("protocol"),m=t.param("schemaHash");return e.json({...o,"data-proxy":{endpoint:`${d}://localhost:${c}/${a}/${m}/itx/${i}`}})}catch(r){return T(r,e)}});async function D(e){let{req:t}=e,n=z(e);if(n instanceof Response)return n;let{base64Override:r,overrideHash:o}=n.schemas;return await h.get({base64Schema:r,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||t.param("clientVersion"),debug:e.get("debug"),platform:e.get("platform"),schemaHash:o})}import{Hono as ze}from"hono/tiny";import{StatusCodes as Ye}from"http-status-codes";var x=new ze;x.post("/database/dump",async e=>{let n=await e.get("db").dump();return e.json(n,Ye.CREATED)});x.get("/health",e=>e.json({name:e.get("serverState").name}));async function ie(e,t){let{port:n}=t;if(t.dryRun)return oe(n,null);let r=await nt(n,e,t),{promise:o,reject:s,resolve:i}=E(),a=Ze({createServer:Xe,fetch:r.fetch,overrideGlobalObjects:!1,port:n},i);return a.on("error",c=>{if(typeof c=="object"&&"code"in c&&c.code==="EADDRINUSE")return s(new v(n,"server"));console.error("[Accelerate]",c)}),await o,oe(n,a)}function oe(e,t){return{async close(){t&&await Promise.allSettled([We(t.close.bind(t))(),h.stopAll()])},port:e,url:`http://localhost:${e}`}}async function nt(e,t,n){let{debug:r}=n,o=new se,s=await et.getPlatformInfo();return r&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),r&&o.use("*",tt((...i)=>console.log("[Accelerate]",...i))),o.use("*",async(i,a)=>(i.set("db",t),i.set("debug",!!r),i.set("platform",s),i.set("port",e),i.set("protocol","http"),i.set("serverState",n),await a())),o.route("/",k),o}var k=new se;k.route("/",S);k.route("/",x);async function dn(e){let t=await U.create(e),[n,r]=await Promise.all([O("database",t),O("shadow_database",t)]),o=await ie(n,t),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:K({databaseUrl:n.connectionString,shadowDatabaseUrl:r.connectionString})}).toString()}`,i={database:{connectionString:n.connectionString},http:{url:o.url},ppg:{url:s},shadowDatabase:{connectionString:r.connectionString}};return await t.writeServerDump(i),{...i,close:()=>a(t,[o,n,r])};async function a(c,d){let p=(await Promise.allSettled(d.map(u=>u.close()))).filter(u=>u.status==="rejected").map(u=>new Error(u.reason));try{await c.close()}catch(u){p.push(u)}if(p.length>0)throw new AggregateError(p,"Failed to close some servers")}}export{rt as DEFAULT_DATABASE_PORT,ot as DEFAULT_SERVER_PORT,st as DEFAULT_SHADOW_DATABASE_PORT,v as PortNotAvailableError,dn as unstable_startServer};
6
+ url = "${e.toString()}"
7
+ }`,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 f.get({base64Schema:r,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.param("clientVersion"),debug:n.get("debug"),platform:n.get("platform"),schemaHash:o})}import{Hono as 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)});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))(),f.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 Ft(n){let e=await L.createExclusively(n),[t,r]=await Promise.all([A("database",e),A("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,Ft as unstable_startServer};
package/dist/state.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  import 'valibot';
2
- export { E as Exports, P as PersistenceMode, R as ResolvedServerOptions, b as ServerDumpV1, S as ServerOptions, c as ServerState, d as ServerStateAlreadyExistsError } from './index-BY1kJS25.js';
2
+ export { E as Exports, f as PersistenceMode, R as ResolvedServerOptions, e as ServerDumpV1, S as ServerOptions, g as ServerState, h as ServerStateAlreadyExistsError } from './db-mXLGDv93.js';
3
+ import '@electric-sql/pglite';
package/dist/state.js CHANGED
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{i as a,j as b}from"./chunk-A33H6MPG.js";export{a as ServerState,b as ServerStateAlreadyExistsError};
2
+ import{a,b}from"./chunk-T2ZEK4IZ.js";import"./chunk-HWX5WUGO.js";export{a as ServerState,b as ServerStateAlreadyExistsError};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/dev",
3
- "version": "0.0.0-dev.202506040041",
3
+ "version": "0.0.0-dev.202506040107",
4
4
  "description": "A local Prisma Postgres server for development and testing",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -20,6 +20,11 @@
20
20
  "import": "./dist/daemon/client.js",
21
21
  "default": "./dist/daemon/client.js"
22
22
  },
23
+ "./internal/db": {
24
+ "types": "./dist/db.d.ts",
25
+ "import": "./dist/db.js",
26
+ "default": "./dist/db.js"
27
+ },
23
28
  "./internal/state": {
24
29
  "types": "./dist/state.d.ts",
25
30
  "import": "./dist/state.js",
@@ -1,4 +0,0 @@
1
- import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{mkdir as K,writeFile as Y}from"fs/promises";import{join as d}from"pathe";import{lock as Z}from"proper-lockfile";import{process as u}from"std-env";import{integer as _,literal as q,minLength as z,minValue as F,number as M,object as p,optional as E,parseJson as G,pipe as i,safeParse as Q,string as g,url as X}from"valibot";import{createWriteStream as B,WriteStream as N}from"fs";import{access as V,chmod as U,constants as W,readFile as j,writeFile as H}from"fs/promises";import J from"env-paths";import{inflate as C}from"pako";var v=J("prisma-dev");function ie(t,e){return`${v.cache}/engine/${t}/${e}`}function l(t){return`${v.data}/${t}`}async function ne(t){try{return await V(t,W.F_OK),!0}catch(e){if(D(e))return!1;throw e}}async function de(t,e){let r=C(t);await H(e,r),await U(e,"755")}async function ue(t,e){await t.stream().pipeTo(N.toWeb(B(e,{encoding:"utf-8"})))}function D(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function S(t){try{return await j(t,{encoding:"utf-8"})}catch(e){if(D(e))return null;throw e}}var w=51214,A=51213,x=51215,y=class extends Error{constructor(r,s){super(`Port number \`${r}\` is not available for service ${s}.`);this.port=r;this.service=s}name="PortNotAvailableError"};var $=i(g(),X()),O=p({connectionString:$}),T=p({url:$}),h=i(M(),_(),F(1)),ee=p({database:O,http:T,ppg:T,shadowDatabase:O}),te=p({databasePort:h,exports:E(ee),name:i(g(),z(1)),pid:E(i(M(),_(),F(0))),port:h,shadowDatabasePort:h,version:q("1")}),f=Symbol("initialize"),R="default",c=class{databasePort;debug;dryRun;name;persistenceMode;pid;port;shadowDatabasePort;constructor(e){this.databasePort=e.databasePort??51214,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??R,this.persistenceMode=e.persistenceMode,this.pid=e.pid??u.pid,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async create(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new o({...e,pid:u.pid}):new b(e);return await r[f](),r}static async fromServerDump(e){let{debug:r,name:s=R}=e??{},I=l(s),n=o.getServerDumpPath(I),m=await S(n);if(m==null)return r&&console.debug(`[State] No server dump file found at: ${n}`),null;r&&(console.debug(`[State] server dump file found at "${n}":`),console.debug(m));let{issues:L,output:a,success:k}=Q(i(g(),G(),te),m);if(!k)throw r&&console.debug(`[State] Invalid server dump file at "${n}":
3
- ${JSON.stringify(L,null,2)}`),new Error(`Invalid Prisma Dev state for "${s}".`);return new o({databasePort:a.databasePort,debug:r,dryRun:!1,name:s,pid:a.pid,port:a.port,serverDump:a,shadowDatabasePort:a.shadowDatabasePort})}},b=class extends c{constructor(e){super({...e,persistenceMode:"stateless",pid:u.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[f](){}async close(){}async writeServerDump(){}},o=class t extends c{#s;#e;#a;#o;#r;#t=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=l(this.name),this.#s=d(this.#e,"db_dump.bak"),this.#a=d(this.#e,".pglite"),this.#r=e.serverDump??null,this.#o=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return d(e,"server.json")}get databaseDumpPath(){return this.#s}get pgliteDataDirPath(){return this.#a}async[f](){await K(this.#e,{recursive:!0}),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#t=await Z(this.#e,{lockfilePath:d(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 P(this.name):e}}async close(){if(this.#t!=null)try{await this.#t(),this.#t=null,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw console.error(`[State] failed to release lock on: ${this.#e}`),e}}async writeServerDump(e){this.#r={name:this.name,version:"1",pid:u.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await Y(this.#o,`${JSON.stringify(this.#r,null,2)}
4
- `,{encoding:"utf-8"})}},P=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A server with the name "${e}" is already running.`)}};export{ie as a,ne as b,de as c,ue as d,w as e,A as f,x as g,y as h,c as i,P as j};