@prisma/dev 0.0.0-dev.202505121240 → 0.0.0-dev.202505121252

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.
package/dist/index.d.ts CHANGED
@@ -1,19 +1,8 @@
1
- declare const DEFAULT_ACCELERATE_PORT = 51213;
2
- declare const DEFAULT_DATABASE_PORT = 51214;
3
- declare const DEFAULT_SHADOW_DATABASE_PORT = 51215;
4
- type PortAssignableService = "accelerate" | "database" | "shadow_database";
5
- declare class PortNotAvailableError extends Error {
6
- port: number;
7
- service: PortAssignableService;
8
- name: string;
9
- constructor(port: number, service: PortAssignableService);
10
- }
11
-
12
1
  interface StartServerOptions {
13
2
  /**
14
3
  * The port the Accelerate server will listen on.
15
4
  *
16
- * Defaults to `51213`.
5
+ * Defaults to `5433`.
17
6
  *
18
7
  * An error is thrown if the port is already in use.
19
8
  */
@@ -21,7 +10,7 @@ interface StartServerOptions {
21
10
  /**
22
11
  * The port the database server will listen on.
23
12
  *
24
- * Defaults to `51214`.
13
+ * Defaults to `5432`.
25
14
  *
26
15
  * An error is thrown if the port is already in use.
27
16
  */
@@ -32,14 +21,6 @@ interface StartServerOptions {
32
21
  * Defaults to `false`.
33
22
  */
34
23
  debug?: boolean;
35
- /**
36
- * The port the shadow database server will listen on.
37
- *
38
- * Defaults to `51215`.
39
- *
40
- * An error is thrown if the port is already in use.
41
- */
42
- shadowDatabasePort?: number;
43
24
  }
44
25
  interface Server {
45
26
  accelerate: {
@@ -52,10 +33,7 @@ interface Server {
52
33
  ppg: {
53
34
  url: string;
54
35
  };
55
- shadowDatabase: {
56
- connectionString: string;
57
- };
58
36
  }
59
37
  declare function unstable_startServer(options?: StartServerOptions): Promise<Server>;
60
38
 
61
- export { DEFAULT_ACCELERATE_PORT, DEFAULT_DATABASE_PORT, DEFAULT_SHADOW_DATABASE_PORT, type PortAssignableService, PortNotAvailableError, type Server, type StartServerOptions, unstable_startServer };
39
+ export { type Server, type StartServerOptions, unstable_startServer };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{createSecureServer as qe}from"http2";import{promisify as Fe}from"util";import{serve as Ke}from"@hono/node-server";import Me from"@prisma/get-platform";import{Hono as re}from"hono/tiny";import{validator as w}from"hono/validator";import{HTTPException as v}from"hono/http-exception";import{object as se,parse as ie,pipe as ae,regex as ce,string as me,url as le}from"valibot";var pe=/^(postgres|postgresql):\/\//,ue=se({databaseUrl:ae(me(),le(),ce(pe))});function B(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function de(e){try{let t=Buffer.from(e,"base64url").toString("utf8");return ie(ue,JSON.parse(t))}catch{return null}}var p=(e,t)=>{let{authorization:n}=e;if(!n)throw new v(401,{message:"Missing API Key"});let[r,o="",s]=n.split(" ");if(r!=="Bearer"||s)throw new v(401,{message:"Invalid API Key"});let i=de(o);if(i==null)throw new v(401,{message:"Invalid API Key"});let{databaseUrl:a}=i;if(a!==t.var.db.connectionString)throw new v(401,{message:"Unauthorized"});return{decodedAPIKey:i}};import{array as fe,literal as ge,minLength as he,object as ye,pipe as we,safeParse as Se,string as Pe,union as ve}from"valibot";var be=ye({tags:ve([we(fe(Pe()),he(1)),ge("all")])});async function L(e){let{output:t,success:n}=Se(be,await e.req.json());return n?t:e.text("Invalid input",400)}import{mkdir as He,readFile as q,writeFile as F}from"fs/promises";import{join as I}from"path";import{certificateFor as Ce}from"@expo/devcert";import{chmod as Ee,stat as Te,writeFile as Ae}from"fs/promises";import Re from"env-paths";import{inflate as xe}from"pako";var H=Re("prisma-dev").cache;function j(e,t){return`${H}/${e}/${t}`}async function h(e){try{return await Te(e),!0}catch(t){if(t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT")return!1;throw t}}async function U(e,t){let n=xe(e);await Ae(t,n),await Ee(t,"755")}var k=I(H,"certs"),C=I(k,"tls.cert"),O=I(k,"tls.key");async function K(){if(await He(k,{recursive:!0}),await h(C)&&await h(O))return{cert:await q(C),key:await q(O)};let e=await Ce("localhost");return await Promise.all([F(C,e.cert),F(O,e.key)]),{cert:e.cert,key:e.key}}import{spawn as Oe}from"child_process";import{once as Ie}from"events";import{mkdir as ke}from"fs/promises";import{join as _e}from"path";function u(){let e,t,n=new Promise((r,o)=>{e=r,t=o});return{fail:t,promise:n,succeed:e}}var b=class e{static#n=new Map;#t;#e;constructor(t){this.#t=t,this.#e=null}static async get(t){let n=`${t.schemaHash}:${t.clientVersion}`;try{let r=e.#n.get(n);if(r)return r;let o=new e(t);return e.#n.set(n,o),await o.start(),o}finally{e.stopAll(n)}}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.#e,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 d.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.#e,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 d.fromResponse(s);return await s.json()}async start(){if(this.#e!=null)return;let t=await this.#s(),n=Oe(t,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#t.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});n.stderr.setEncoding("utf8"),n.stdout.setEncoding("utf8");let{fail:r,promise:o,succeed:s}=u();this.#e=o;let i=a=>{let c=a.split(`
3
- `).find(P=>P.includes("Started query engine http server"));if(!c)return;n.stdout.removeListener("data",i);let{fields:m}=JSON.parse(c);if(m==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${a}`));let{ip:l,port:x}=m;if(l==null||x==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.
4
- Received data: ${a}`));s({childProcess:n,url:`http://${l}:${x}`})};n.once("error",a=>{this.#e=null,r(new y(String(a)))}),n.once("exit",(a,c)=>{this.#e=null,r(new y(`Query Engine exited with code ${a} and signal ${c}`))}),n.stdout.on("data",i),n.stderr.on("data",a=>{console.error(a)}),await this.#e}async stop(){if(this.#e==null)return;let{childProcess:t}=await this.#e;t.exitCode==null&&t.signalCode==null&&(t.kill(),await Ie(t,"exit"))}async#s(){let t=await this.#i(),n=j(this.#t.clientVersion,t);await ke(n,{recursive:!0});let{platform:r}=this.#t.platform,o=r==="windows"?".exe":"",s=_e(n,`query-engine-${r}${o}`);return await h(s)||await this.#a({commitHash:t,extension:o,engineBinaryPath:s}),s}async#i(){let t=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#t.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,{platform:s}=this.#t.platform,i=`https://binaries.prisma.sh/all_commits/${n}/${s}/query-engine${r}.gz`,a=await fetch(i);if(!a.ok)throw new Error(`Couldn't download engine. URL: ${i}, status code: ${a.status}`);await U(await a.arrayBuffer(),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.#e,s=this.#r(n),i=await fetch(`${o}/transaction/${t}/${r}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await d.fromResponse(i);try{return await i.json()}catch{return{}}}};function E(e,t){return console.error(e),e instanceof y?t.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:e.message}}}},500):e instanceof d?t.text(e.responseBody,e.statusCode):t.body(null,500)}var y=class extends Error{name="EngineStartError"},d=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)}};var M=51213,V=51214,N=51215,f=class extends Error{constructor(n,r){super(`Port ${n} is already in use.`);this.port=n;this.service=r}name="PortNotAvailableError"};import{Buffer as z}from"buffer";var T=new Map;async function J(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 G(e){let t=e.req.param("schemaHash"),n=T.get(t);return n==null?e.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:t,schemas:n}}var De=/datasource\s+db\s+[\w\s\d{="[\])(]+}/;function Q(e,t){let n=z.from(e,"base64").toString("utf8"),r=`datasource db {
2
+ import{createSecureServer as _e}from"http2";import{promisify as De}from"util";import{serve as je}from"@hono/node-server";import Le from"@prisma/get-platform";import{Hono as X}from"hono/tiny";import{validator as y}from"hono/validator";import{HTTPException as S}from"hono/http-exception";import{object as ee,parse as te,pipe as ne,regex as re,string as oe,url as se}from"valibot";var ie=/^(postgres|postgresql):\/\//,ae=ee({databaseUrl:ne(oe(),se(),re(ie))});function O(t){return Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}function ce(t){try{let n=Buffer.from(t,"base64url").toString("utf8");return te(ae,JSON.parse(n))}catch{return null}}var u=(t,n)=>{let{authorization:e}=t;if(!e)throw new S(401,{message:"Missing API Key"});let[r,o="",s]=e.split(" ");if(r!=="Bearer"||s)throw new S(401,{message:"Invalid API Key"});let i=ce(o);if(i==null)throw new S(401,{message:"Invalid API Key"});let{databaseUrl:a}=i;if(a!==n.var.db.connectionString)throw new S(401,{message:"Unauthorized"});return{decodedAPIKey:i}};import{array as me,literal as le,minLength as pe,object as ue,pipe as de,safeParse as fe,string as ge,union as he}from"valibot";var ye=ue({tags:he([de(me(ge()),pe(1)),le("all")])});async function $(t){let{output:n,success:e}=fe(ye,await t.req.json());return e?n:t.text("Invalid input",400)}import{mkdir as Ee,readFile as D,writeFile as j}from"fs/promises";import{join as A}from"path";import{certificateFor as Te}from"@expo/devcert";import{chmod as we,stat as Se,writeFile as ve}from"fs/promises";import Pe from"env-paths";import{inflate as be}from"pako";var R=Pe("prisma-dev").cache;function B(t,n){return`${R}/${t}/${n}`}async function g(t){try{return await Se(t),!0}catch(n){if(n!=null&&typeof n=="object"&&"code"in n&&n.code==="ENOENT")return!1;throw n}}async function _(t,n){let e=be(t);await ve(n,e),await we(n,"755")}var C=A(R,"certs"),H=A(C,"tls.cert"),x=A(C,"tls.key");async function L(){if(await Ee(C,{recursive:!0}),await g(H)&&await g(x))return{cert:await D(H),key:await D(x)};let t=await Te("localhost");return await Promise.all([j(H,t.cert),j(x,t.key)]),{cert:t.cert,key:t.key}}import{spawn as Re}from"child_process";import{once as He}from"events";import{mkdir as xe}from"fs/promises";import{join as Ae}from"path";function d(){let t,n,e=new Promise((r,o)=>{t=r,n=o});return{fail:n,promise:e,succeed:t}}var v=class t{static#n=new Map;#t;#e;constructor(n){this.#t=n,this.#e=null}static async get(n){let e=`${n.schemaHash}:${n.clientVersion}`;try{let r=t.#n.get(e);if(r)return r;let o=new t(n);return t.#n.set(e,o),await o.start(),o}finally{t.stopAll(e)}}static async stopAll(n){let r=(await Promise.allSettled(Array.from(t.#n.entries()).filter(([o])=>o!==n).map(async([o,s])=>{try{await s.stop()}finally{t.#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(n,e){return await this.#o(n,e,"commit")}async request(n,e){let{url:r}=await this.#e,o=this.#r(e),s=await fetch(r,{body:typeof n=="string"?n:JSON.stringify(n),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await f.fromResponse(s);return await s.text()}async rollbackTransaction(n,e){return await this.#o(n,e,"rollback")}async startTransaction(n,e){let{url:r}=await this.#e,o=this.#r(e),s=await fetch(`${r}/transaction/start`,{body:JSON.stringify(n),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await f.fromResponse(s);return await s.json()}async start(){if(this.#e!=null)return;let n=await this.#s(),e=Re(n,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#t.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});e.stderr.setEncoding("utf8"),e.stdout.setEncoding("utf8");let{fail:r,promise:o,succeed:s}=d();this.#e=o;let i=a=>{let c=a.split(`
3
+ `).find(Z=>Z.includes("Started query engine http server"));if(!c)return;e.stdout.removeListener("data",i);let{fields:m}=JSON.parse(c);if(m==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${a}`));let{ip:p,port:l}=m;if(p==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.
4
+ Received data: ${a}`));s({childProcess:e,url:`http://${p}:${l}`})};e.once("error",a=>{this.#e=null,r(new h(String(a)))}),e.once("exit",(a,c)=>{this.#e=null,r(new h(`Query Engine exited with code ${a} and signal ${c}`))}),e.stdout.on("data",i),e.stderr.on("data",a=>{console.error(a)}),await this.#e}async stop(){if(this.#e==null)return;let{childProcess:n}=await this.#e;n.exitCode==null&&n.signalCode==null&&(n.kill(),await He(n,"exit"))}async#s(){let n=await this.#i(),e=B(this.#t.clientVersion,n);await xe(e,{recursive:!0});let{platform:r}=this.#t.platform,o=r==="windows"?".exe":"",s=Ae(e,`query-engine-${r}${o}`);return await g(s)||await this.#a({commitHash:n,extension:o,engineBinaryPath:s}),s}async#i(){let n=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#t.clientVersion}`);if(!n.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${n.status}`);let r=(await n.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(n){let{commitHash:e,extension:r,engineBinaryPath:o}=n,{platform:s}=this.#t.platform,i=`https://binaries.prisma.sh/all_commits/${e}/${s}/query-engine${r}.gz`,a=await fetch(i);if(!a.ok)throw new Error(`Couldn't download engine. URL: ${i}, status code: ${a.status}`);await _(await a.arrayBuffer(),o)}#r(n){let e={};for(let[r,o]of Object.entries(n))o!=null&&(e[r]=o);return e}async#o(n,e,r){let{url:o}=await this.#e,s=this.#r(e),i=await fetch(`${o}/transaction/${n}/${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 P(t,n){return console.error(t),t instanceof h?n.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof f?n.text(t.responseBody,t.statusCode):n.body(null,500)}var h=class extends Error{name="EngineStartError"},f=class t extends Error{constructor(e,r,o){super(`${e}: Query Engine response status ${r}, body: ${o}`);this.action=e;this.statusCode=r;this.responseBody=o}name="EngineHttpError";static async fromResponse(e){let r=new URL(e.url),o=await e.text();return new t(r.pathname,e.status,o)}};import{Buffer as q}from"buffer";var b=new Map;async function K(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}function U(t){let n=t.req.param("schemaHash"),e=b.get(n);return e==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:n,schemas:e}}var Ce=/datasource\s+db\s+[\w\s\d{="[\])(]+}/;function M(t,n){let e=q.from(t,"base64").toString("utf8"),r=`datasource db {
5
5
  provider = "postgresql"
6
- url = "${t}"
7
- }`,o=n.replace(De,r);return z.from(o,"utf8").toString("base64")}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 $e,minValue as W,number as _,object as Be,pipe as Y,safeParse as Z,string as ee,union as Le}from"valibot";var je=Be({isolation_level:ee(),max_wait:Y(_(),X(),W(0)),timeout:Y(_(),X(),W(0))});async function te(e){let{output:t,success:n}=Z(je,await e.req.json());return n?t:e.json({EngineNotStarted:{reason:"InvalidRequest"}},400)}var Ue=$e({id:Le([ee(),_()])});function ne(e,t){let{output:n,success:r}=Z(Ue,e);return r?n:t.json({EngineMalfunction:{}},500)}async function oe(e,t,n){let r=await Ve(e,t,n),o=await K(),{fail:s,promise:i,succeed:a}=u(),c=Ke({createServer:qe,fetch:r.fetch,port:e,serverOptions:{...o,allowHTTP1:!0}},()=>{a()});return c.on("error",m=>{if(typeof m=="object"&&"code"in m&&m.code==="EADDRINUSE")return s(new f(e,"accelerate"));console.error(m)}),await i,{async close(){await Fe(c.close.bind(c))()},port:e,url:`http://localhost:${e}`}}async function Ve(e,t,n){let r=new re,o=await Me.getPlatformInfo();return n&&console.debug("platform info: %s",JSON.stringify(o)),r.use("*",async(s,i)=>(s.set("db",t),s.set("debug",!!n),s.set("platform",o),s.set("port",e),s.set("protocol","https"),await i())),r.route("/",R),r}var R=new re;R.post("/invalidate",w("header",p),async e=>{let t=await L(e);return t instanceof Response?t:e.body(null)});var Ne="/:clientVersion/:schemaHash",S=R.basePath(Ne);R.route("/",S);var ze=["/graphql","/itx/:transactionId/graphql"];S.on("POST",[...ze],w("header",p),async e=>{let{req:t}=e;try{let n=await D(e);if(console.log("got engine!"),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 E(n,e)}});S.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],w("header",p),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 E(n,e)}});S.put("/schema",w("header",p),async e=>{let{req:t}=e,n=await t.text();if(!n)return e.text("Missing schema",400);let r=t.param("schemaHash"),o=T.get(r);return o==null?r!==await J(n)?e.text("Schema hash mismatch",400):(T.set(r,{original:n,override:Q(n,e.get("db").connectionString)}),e.text(r)):n!==o.original?e.text("Schema mismatch",400):e.text(r)});S.post("/transaction/start",w("header",p),async e=>{let{req:t}=e,n=await te(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=ne(o,e);if(s instanceof Response)return s;let{id:i}=s,a=t.param("clientVersion"),c=e.get("port"),m=e.get("protocol"),l=t.param("schemaHash");return e.json({...o,"data-proxy":{endpoint:`${m}://localhost:${c}/${a}/${l}/itx/${i}`}})}catch(r){return E(r,e)}});async function D(e){let{req:t}=e,n=G(e);return n instanceof Response?n:await b.get({base64Schema:n.schemas.override,clientVersion:t.param("clientVersion"),platform:e.get("platform"),schemaHash:n.schemaHash})}import{promisify as Je}from"util";import{PGlite as Ge}from"@electric-sql/pglite";import{createServer as Qe,LogLevel as Xe}from"pglite-server";async function $(e,t,n){let r={connectionLimit:1,connectTimeout:0,database:"postgres",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,port:e,socketTimeout:0,sslMode:"disable",username:"postgres"},o=await Ge.create({database:r.database,dataDir:"memory://",debug:n?5:void 0,defaultDataTransferContainer:"file",username:r.username});await o.waitReady;let s=Qe(o,{keepAlive:!0,logLevel:n?Xe.Debug:void 0}),{fail:i,promise:a,succeed:c}=u();s.on("error",l=>{if("code"in l&&l.code==="EADDRINUSE")return i(new f(e,t));console.error(l)}),s.listen(e,()=>c()),await a;let m=`postgres://${r.username}:${r.password}@localhost:${e}/${r.database}?${new URLSearchParams({connection_limit:String(r.connectionLimit),connect_timeout:String(r.connectTimeout),max_idle_connection_lifetime:String(r.maxIdleConnectionLifetime),pool_timeout:String(r.poolTimeout),socket_timeout:String(r.socketTimeout),sslmode:r.sslMode}).toString()}`;return{...r,async close(){try{await Je(s.close.bind(s))()}finally{await o.close()}},connectionString:m}}async function Yt(e){let{acceleratePort:t=51213,databasePort:n=51214,debug:r=!1,shadowDatabasePort:o=51215}=e||{},[s,i]=await Promise.all([$(n,"database",r),$(o,"shadow_database",r)]),a=await oe(t,s,r),c=`prisma+postgres://localhost:${a.port}/?${new URLSearchParams({api_key:B({databaseUrl:s.connectionString})}).toString()}`;return{accelerate:{url:a.url},close:()=>m([a,s,i]),database:{connectionString:s.connectionString},ppg:{url:c},shadowDatabase:{connectionString:i.connectionString}};async function m(l){let P=(await Promise.allSettled(l.map(g=>g.close()))).filter(g=>g.status==="rejected").map(g=>new Error(g.reason));if(P.length>0)throw new AggregateError(P,"Failed to close some servers")}}export{M as DEFAULT_ACCELERATE_PORT,V as DEFAULT_DATABASE_PORT,N as DEFAULT_SHADOW_DATABASE_PORT,f as PortNotAvailableError,Yt as unstable_startServer};
6
+ url = "${n}"
7
+ }`,o=e.replace(Ce,r);return q.from(o,"utf8").toString("base64")}function E(t){let{req:n}=t;return{traceparent:n.header("traceparent"),"X-capture-telemetry":n.header("X-capture-telemetry")}}import{integer as V,looseObject as Ie,minValue as F,number as I,object as ke,pipe as N,safeParse as z,string as J,union as Oe}from"valibot";var $e=ke({isolation_level:J(),max_wait:N(I(),V(),F(0)),timeout:N(I(),V(),F(0))});async function G(t){let{output:n,success:e}=z($e,await t.req.json());return e?n:t.json({EngineNotStarted:{reason:"InvalidRequest"}},400)}var Be=Ie({id:Oe([J(),I()])});function Q(t,n){let{output:e,success:r}=z(Be,t);return r?e:n.json({EngineMalfunction:{}},500)}async function Y(t,n,e){let r=await qe(t,n,e),o=await L(),{fail:s,promise:i,succeed:a}=d(),c=je({createServer:_e,fetch:r.fetch,port:t,serverOptions:{...o,allowHTTP1:!0}},()=>{a()});return c.on("error",m=>{if(typeof m=="object"&&"code"in m&&m.code==="EADDRINUSE")return s({portNotAvailable:t});console.error(m)}),await i,{async close(){await De(c.close.bind(c))()},port:t,url:`http://localhost:${t}`}}async function qe(t,n,e){let r=new X,o=await Le.getPlatformInfo();return e&&console.debug("platform info: %s",JSON.stringify(o)),r.use("*",async(s,i)=>(s.set("db",n),s.set("debug",!!e),s.set("platform",o),s.set("port",t),s.set("protocol","https"),await i())),r.route("/",T),r}var T=new X;T.post("/invalidate",y("header",u),async t=>{let n=await $(t);return n instanceof Response?n:t.body(null)});var Ke="/:clientVersion/:schemaHash",w=T.basePath(Ke);T.route("/",w);var Ue=["/graphql","/itx/:transactionId/graphql"];w.on("POST",[...Ue],y("header",u),async t=>{let{req:n}=t;try{let e=await k(t);if(console.log("got engine!"),e instanceof Response)return e;let r=await n.text(),o=n.param("transactionId"),s=await e.request(r,{...E(t),"X-transaction-id":o});return t.text(s)}catch(e){return P(e,t)}});w.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],y("header",u),async t=>{let{req:n}=t;try{let e=await k(t);if(e instanceof Response)return e;let o=`${n.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=n.param("transactionId"),i=await e[o](s,E(t));return t.json(i)}catch(e){return P(e,t)}});w.put("/schema",y("header",u),async t=>{let{req:n}=t,e=await n.text();if(!e)return t.text("Missing schema",400);let r=n.param("schemaHash"),o=b.get(r);return o==null?r!==await K(e)?t.text("Schema hash mismatch",400):(b.set(r,{original:e,override:M(e,t.get("db").connectionString)}),t.text(r)):e!==o.original?t.text("Schema mismatch",400):t.text(r)});w.post("/transaction/start",y("header",u),async t=>{let{req:n}=t,e=await G(t);if(e instanceof Response)return e;try{let r=await k(t);if(r instanceof Response)return r;let o=await r.startTransaction(e,E(t)),s=Q(o,t);if(s instanceof Response)return s;let{id:i}=s,a=n.param("clientVersion"),c=t.get("port"),m=t.get("protocol"),p=n.param("schemaHash");return t.json({...o,"data-proxy":{endpoint:`${m}://localhost:${c}/${a}/${p}/itx/${i}`}})}catch(r){return P(r,t)}});async function k(t){let{req:n}=t,e=U(t);return e instanceof Response?e:await v.get({base64Schema:e.schemas.override,clientVersion:n.param("clientVersion"),platform:t.get("platform"),schemaHash:e.schemaHash})}import{promisify as Me}from"util";import{PGlite as Ve}from"@electric-sql/pglite";import{createServer as Fe,LogLevel as Ne}from"pglite-server";async function W(t,n){let e={connectionLimit:1,connectTimeout:0,database:"postgres",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,port:t,socketTimeout:0,sslMode:"disable",username:"postgres"},r=await Ve.create({database:e.database,dataDir:"memory://",debug:n?5:void 0,defaultDataTransferContainer:"file",username:e.username});await r.waitReady;let o=Fe(r,{keepAlive:!0,logLevel:n?Ne.Debug:void 0}),{fail:s,promise:i,succeed:a}=d();o.on("error",m=>{if("code"in m&&m.code==="EADDRINUSE")return s(new Error(`Port ${t} is already in use. Provide a different \`dbport\` number and try again.`));console.error(m)}),o.listen(t,()=>a()),await i;let c=`postgres://${e.username}:${e.password}@localhost:${t}/${e.database}?${new URLSearchParams({connection_limit:String(e.connectionLimit),connect_timeout:String(e.connectTimeout),max_idle_connection_lifetime:String(e.maxIdleConnectionLifetime),pool_timeout:String(e.poolTimeout),socket_timeout:String(e.socketTimeout),sslmode:e.sslMode}).toString()}`;return{...e,async close(){try{await Me(o.close.bind(o))()}finally{await r.close()}},connectionString:c}}async function Vt(t){let{acceleratePort:n=5433,databasePort:e=5432,debug:r}=t||{},o=await W(e,r),s=await Y(n,o,r),i=`prisma+postgres://localhost:${s.port}/?${new URLSearchParams({api_key:O({databaseUrl:o.connectionString})}).toString()}`;return{accelerate:{url:s.url},close:()=>a([s,o]),database:{connectionString:o.connectionString},ppg:{url:i}};async function a(c){let p=(await Promise.allSettled(c.map(l=>l.close()))).filter(l=>l.status==="rejected").map(l=>new Error(l.reason));if(p.length>0)throw new AggregateError(p,"Failed to close some servers")}}export{Vt as unstable_startServer};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/dev",
3
- "version": "0.0.0-dev.202505121240",
3
+ "version": "0.0.0-dev.202505121252",
4
4
  "description": "A local Prisma Postgres server for development and testing",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",