@prisma/dev 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,23 +1,4 @@
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
- interface StartServerOptions {
13
- /**
14
- * The port the Accelerate server will listen on.
15
- *
16
- * Defaults to `51213`.
17
- *
18
- * An error is thrown if the port is already in use.
19
- */
20
- acceleratePort?: number;
1
+ interface ServerOptions {
21
2
  /**
22
3
  * The port the database server will listen on.
23
4
  *
@@ -32,6 +13,32 @@ interface StartServerOptions {
32
13
  * Defaults to `false`.
33
14
  */
34
15
  debug?: boolean;
16
+ /**
17
+ * Whether to run the server in dry run mode.
18
+ *
19
+ * Defaults to `false`.
20
+ */
21
+ dryRun?: boolean;
22
+ /**
23
+ * The name of the server.
24
+ *
25
+ * Defaults to `default`.
26
+ */
27
+ name?: string;
28
+ /**
29
+ * The persistence mode of the server.
30
+ *
31
+ * Default is `stateless`.
32
+ */
33
+ persistenceMode?: PersistenceMode;
34
+ /**
35
+ * The port the server will listen on.
36
+ *
37
+ * Defaults to `51213`.
38
+ *
39
+ * An error is thrown if the port is already in use.
40
+ */
41
+ port?: number;
35
42
  /**
36
43
  * The port the shadow database server will listen on.
37
44
  *
@@ -41,6 +48,21 @@ interface StartServerOptions {
41
48
  */
42
49
  shadowDatabasePort?: number;
43
50
  }
51
+ type PersistenceMode = "stateless" | "stateful";
52
+
53
+ type DBServerPurpose = "database" | "shadow_database";
54
+
55
+ declare const DEFAULT_DATABASE_PORT = 51214;
56
+ declare const DEFAULT_SERVER_PORT = 51213;
57
+ declare const DEFAULT_SHADOW_DATABASE_PORT = 51215;
58
+ type PortAssignableService = DBServerPurpose | "server";
59
+ declare class PortNotAvailableError extends Error {
60
+ port: number;
61
+ service: PortAssignableService;
62
+ name: string;
63
+ constructor(port: number, service: PortAssignableService);
64
+ }
65
+
44
66
  interface Server {
45
67
  accelerate: {
46
68
  url: string;
@@ -56,6 +78,6 @@ interface Server {
56
78
  connectionString: string;
57
79
  };
58
80
  }
59
- declare function unstable_startServer(options?: StartServerOptions): Promise<Server>;
81
+ declare function unstable_startServer(options?: ServerOptions): Promise<Server>;
60
82
 
61
- export { DEFAULT_ACCELERATE_PORT, DEFAULT_DATABASE_PORT, DEFAULT_SHADOW_DATABASE_PORT, type PortAssignableService, PortNotAvailableError, type Server, type StartServerOptions, unstable_startServer };
83
+ export { DEFAULT_DATABASE_PORT, DEFAULT_SERVER_PORT, DEFAULT_SHADOW_DATABASE_PORT, type PortAssignableService, PortNotAvailableError, type Server, unstable_startServer };
package/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{createServer as $e}from"http";import{promisify as ke}from"util";import{serve as Be}from"@hono/node-server";import Le from"@prisma/get-platform";import{logger as je}from"hono/logger";import{Hono as ee}from"hono/tiny";import{validator as y}from"hono/validator";import{HTTPException as P}from"hono/http-exception";import{object as ne,optional as re,parseJson as oe,pipe as x,regex as _,safeParse as se,string as O,url as $}from"valibot";var k=/^(postgres|postgresql):\/\//,ae=x(O(),oe(),ne({databaseUrl:x(O(),$(),_(k)),shadowDatabaseUrl:re(x(O(),$(),_(k)))}));function B(t){return Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}function ie(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:n,output:r,success:o}=se(ae,e,{abortEarly:!0});return o?[null,r]:[n]}var u=(t,e)=>{let{authorization:n}=t;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]=ie(o);if(i)throw new P(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:c}=a;if(c!==e.var.db.connectionString)throw new P(401,{message:"Unauthorized"});return{decodedAPIKey:a}};import{array as ce,literal as le,minLength as de,object as ue,pipe as me,safeParse as pe,string as ge,union as fe}from"valibot";var he=ue({tags:fe([me(ce(ge()),de(1)),le("all")])});async function L(t){let{output:e,success:n}=pe(he,await t.req.json(),{abortEarly:!0});return n?e:t.text("Invalid input",400)}import{spawn as Ee}from"child_process";import{once as Ae}from"events";import{mkdir as Te}from"fs/promises";import{join as Re}from"path";import{chmod as ye,stat as we,writeFile as Se}from"fs/promises";import be from"env-paths";import{inflate as Pe}from"pako";var ve=be("prisma-dev").cache;function j(t,e){return`${ve}/${t}/${e}`}async function U(t){try{return await we(t),!0}catch(e){if(e!=null&&typeof e=="object"&&"code"in e&&e.code==="ENOENT")return!1;throw e}}async function q(t,e){let n=Pe(t);await Se(e,n),await ye(e,"755")}function v(){let t,e,n=new Promise((r,o)=>{t=r,e=o});return{fail:e,promise:n,succeed:t}}var f=class t{static#n=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let n=`${e.schemaHash}:${e.clientVersion}`;try{let r=t.#n.get(n);if(r)return r;let o=new t(e);return t.#n.set(n,o),e.debug&&console.debug("starting engine...",e),await o.start(),e.debug&&console.debug("engine started!"),o}finally{t.stopAll(n)}}static async stopAll(e){let r=(await Promise.allSettled(Array.from(t.#n.entries()).filter(([o])=>o!==e).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(e,n){return await this.#o(e,n,"commit")}async request(e,n){let{url:r}=await this.#t,o=this.#r(n),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 m.fromResponse(s);return await s.text()}async rollbackTransaction(e,n){return await this.#o(e,n,"rollback")}async startTransaction(e,n){let{url:r}=await this.#t,o=this.#r(n),s=await fetch(`${r}/transaction/start`,{body:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await m.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return;let e=await this.#s();this.#e.debug&&console.debug("spinning up engine at path...",e);let n=Ee(e,["--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});n.stderr.setEncoding("utf8"),n.stdout.setEncoding("utf8");let{fail:r,promise:o,succeed:s}=v();this.#t=o;let i=a=>{let c=a.split(`
3
- `).find(b=>b.includes("Started query engine http server"));if(!c)return;n.stdout.removeListener("data",i);let{fields:l}=JSON.parse(c);if(l==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${a}`));let{ip:d,port:R}=l;if(d==null||R==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://${d}:${R}`})};n.once("error",a=>{this.#t=null,r(new h(String(a)))}),n.once("exit",(a,c)=>{this.#t=null,r(new h(`Query Engine exited with code ${a} and signal ${c}`))}),n.stdout.on("data",i),n.stderr.on("data",a=>{console.error(a)}),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:e}=await this.#t;e.exitCode==null&&e.signalCode==null&&(e.kill(),await Ae(e,"exit"))}async#s(){this.#e.debug&&console.debug("getting engine commit hash...");let e=await this.#a();this.#e.debug&&console.debug("got engine commit hash",e);let n=j(this.#e.clientVersion,e);this.#e.debug&&console.debug("cache directory path",n),await Te(n,{recursive:!0});let{platform:r}=this.#e.platform,o=r==="windows"?".exe":"",s=Re(n,`query-engine-${r}${o}`);return this.#e.debug&&console.debug("engine binary path",s),(process.env.PRISMA_DEV_FORCE_ENGINE_DOWNLOAD==="1"||await U(s)===!1)&&await this.#i({commitHash:e,extension:o,engineBinaryPath:s}),s}async#a(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let r=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!r)throw new Error("Couldn't find engines version in package.json");let o=r.split(".").at(-1);if(!o)throw new Error("Couldn't find commit hash in engines version");return o}async#i(e){let{commitHash:n,extension:r,engineBinaryPath:o}=e,{binaryTarget:s}=this.#e.platform,i=`https://binaries.prisma.sh/all_commits/${n}/${s}/query-engine${r}.gz`;this.#e.debug&&console.debug("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}`);await q(await a.arrayBuffer(),o),this.#e.debug&&console.debug("engine downloaded and saved at",o)}#r(e){let n={};for(let[r,o]of Object.entries(e))o!=null&&(n[r]=o);return n}async#o(e,n,r){let{url:o}=await this.#t,s=this.#r(n),i=await fetch(`${o}/transaction/${e}/${r}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await m.fromResponse(i);try{return await i.json()}catch{return{}}}};function E(t,e){return console.error(t),t instanceof h?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof m?e.text(t.responseBody,t.statusCode):e.body(null,500)}var h=class extends Error{name="EngineStartError"},m=class t 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 t(r.pathname,n.status,o)}};var F=51213,V=51214,M=51215,p=class extends Error{constructor(n,r){super(`Port number \`${n}\` is not available for service ${r}.`);this.port=n;this.service=r}name="PortNotAvailableError"};import{Buffer as N}from"buffer";var A=new Map;async function H(t){let n=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}function K(t){let e=t.req.param("schemaHash"),n=A.get(e);return n==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:n}}var xe=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function z(t,e){let n=N.from(t,"base64").toString("utf8"),r=`datasource db {
2
+ import{createServer as at}from"http";import{promisify as it}from"util";import{serve as ct}from"@hono/node-server";import dt from"@prisma/get-platform";import{logger as ut}from"hono/logger";import{Hono as fe}from"hono/tiny";import{validator as S}from"hono/validator";import{process as lt}from"std-env";import{HTTPException as E}from"hono/http-exception";import{object as we,optional as Se,parseJson as Pe,pipe as x,regex as U,safeParse as ve,string as I,url as q}from"valibot";var V=/^(postgres|postgresql):\/\//,Ee=x(I(),Pe(),we({databaseUrl:x(I(),q(),U(V)),shadowDatabaseUrl:Se(x(I(),q(),U(V)))}));function K(t){return Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}function De(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:n,success:o}=ve(Ee,e,{abortEarly:!0});return o?[null,n]:[r]}var g=(t,e)=>{let{authorization:r}=t;if(!r)throw new E(401,{message:"Missing API Key"});let[n,o="",s]=r.split(" ");if(n!=="Bearer"||s)throw new E(401,{message:"Invalid API Key"});let[a,i]=De(o);if(a)throw new E(401,{message:"Invalid API Key",cause:a.join(", ")});let{databaseUrl:c}=i;if(c!==e.var.db.connectionString)throw new E(401,{message:"Unauthorized"});return{decodedAPIKey:i}};import{array as Ae,literal as Te,minLength as Re,object as Oe,pipe as xe,safeParse as Ie,string as $e,union as ke}from"valibot";var _e=Oe({tags:ke([xe(Ae($e()),Re(1)),Te("all")])});async function G(t){let{output:e,success:r}=Ie(_e,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}import{spawn as Ke}from"child_process";import{once as Ge}from"events";import{mkdir as ze}from"fs/promises";import{join as Je}from"path";import{setTimeout as We}from"timers/promises";import{proxySignals as Qe}from"foreground-child/proxy-signals";import{process as Ye}from"std-env";import{createWriteStream as He,WriteStream as Be}from"fs";import{access as Le,chmod as Ce,constants as Me,readFile as Fe,stat as je,unlink as Ne,writeFile as Ue}from"fs/promises";import qe from"env-paths";import{inflate as Ve}from"pako";var z=qe("prisma-dev");function J(t,e){return`${z.cache}/engine/${t}/${e}`}function W(t){return`${z.data}/${t}`}async function D(t){try{return await Le(t,Me.F_OK),!0}catch(e){if(k(e))return!1;throw e}}async function Q(t,e){let r=Ve(t);await Ue(e,r),await Ce(e,"755")}async function Y(t,e){await t.stream().pipeTo(Be.toWeb(He(e,{encoding:"utf-8"})))}async function X(t){try{return await Ne(t),!0}catch{return!1}}async function $(t){try{return(await je(t)).mtimeMs}catch(e){if(k(e))return-1/0;throw e}}function k(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function Z(t){try{return await Fe(t,{encoding:"utf-8"})}catch(e){if(k(e))return null;throw e}}function A(){let t,e,r=new Promise((s,a)=>{t=s,e=a}),n=s=>{n=o=null,e(s)},o=s=>{o=n=null,t(s)};return{fail:s=>n?.(s),promise:r,succeed:s=>o?.(s)}}var{PRISMA_DEV_FORCE_ENGINE_DOWNLOAD:Xe,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:ee}=Ye.env,y=class t{static#r=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let r=`${e.schemaHash}:${e.clientVersion}`;try{let n=t.#r.get(r);if(n)return n;let o=new t(e);return t.#r.set(r,o),e.debug&&console.debug("starting engine...",e),await o.start(),e.debug&&console.debug("engine started!"),o}finally{t.stopAll(r)}}static async stopAll(e){let n=(await Promise.allSettled(Array.from(t.#r.entries()).filter(([o])=>o!==e).map(async([o,s])=>{try{await s.stop()}finally{t.#r.delete(o)}}))).filter(o=>o.status==="rejected").map(o=>o.reason);if(n.length>0)throw new AggregateError(n,"Failed to stop engines")}async commitTransaction(e,r){return await this.#i(e,r,"commit")}async request(e,r){let{url:n}=await this.#t,o=this.#n(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 f.fromResponse(s);return await s.text()}async rollbackTransaction(e,r){return await this.#i(e,r,"rollback")}async startTransaction(e,r){let{url:n}=await this.#t,o=this.#n(r),s=await fetch(`${n}/transaction/start`,{body:JSON.stringify(e),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;let{fail:e,promise:r,succeed:n}=A();this.#t=r;let o=await this.#s();this.#e.debug&&console.debug("spinning up engine at path...",o);let s=Ke(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});Qe(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let a=u=>{let m=u.split(`
3
+ `).find(ye=>ye.includes("Started query engine http server"));if(!m)return;s.stdout.removeListener("data",a);let{fields:p}=JSON.parse(m);if(p==null)return e(new Error(`Unexpected data during initialization, "fields" are missing: ${u}`));let{ip:l,port:N}=p;if(l==null||N==null)return e(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: ${u}`));n({childProcess:s,url:`http://${l}:${N}`})},i=u=>{this.#t=null,e(new w(String(u))),s.removeListener("exit",c),s.kill()};s.once("error",i);let c=(u,m)=>{this.#t=null,e(new w(`Query Engine exited with code ${u} and signal ${m}`))};s.once("exit",c),s.stdout.on("data",a),s.stderr.on("data",console.error),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:e}=await this.#t;e.exitCode==null&&e.signalCode==null&&(e.kill(),await Ge(e,"exit"))}async#s(){this.#e.debug&&console.debug("getting engine commit hash...");let e=await this.#o();this.#e.debug&&console.debug("got engine commit hash",e);let r=J(this.#e.clientVersion,e);this.#e.debug&&console.debug("cache directory path",r),await ze(r,{recursive:!0});let{platform:n}=this.#e.platform,o=n==="windows"?".exe":"",s=Je(r,`query-engine-${n}${o}`);return this.#e.debug&&console.debug("engine binary path",s),(Xe==="1"||await D(s)===!1)&&await this.#a({commitHash:e,extension:o,engineBinaryPath:s}),s}async#o(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let n=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!n)throw new Error("Couldn't find engines version in package.json");let o=n.split(".").at(-1);if(!o)throw new Error("Couldn't find commit hash in engines version");return o}async#a(e){let{commitHash:r,extension:n,engineBinaryPath:o}=e,{binaryTarget:s}=this.#e.platform,a=`https://binaries.prisma.sh/all_commits/${r}/${s}/query-engine${n}.gz`;this.#e.debug&&console.debug("downloading engine from url",a);let i=await fetch(a);if(!i.ok)throw new Error(`Couldn't download engine. URL: ${a}, status code: ${i.status}`);ee&&await We(Number(ee)),await Q(await i.arrayBuffer(),o),this.#e.debug&&console.debug("engine downloaded and saved at",o)}#n(e){let r={};for(let[n,o]of Object.entries(e))o!=null&&(r[n]=o);return r}async#i(e,r,n){let{url:o}=await this.#t,s=this.#n(r),a=await fetch(`${o}/transaction/${e}/${n}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!a.ok)throw await f.fromResponse(a);try{return await a.json()}catch{return{}}}};function T(t,e){return console.error(t),t instanceof w?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof f?e.text(t.responseBody,t.statusCode):e.body(null,500)}var w=class extends Error{name="EngineStartError"},f=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=51214,re=51213,ne=51215,h=class extends Error{constructor(r,n){super(`Port number \`${r}\` is not available for service ${n}.`);this.port=r;this.service=n}name="PortNotAvailableError"};import{Buffer as oe}from"buffer";var R=new Map;async function _(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(a=>a.toString(16).padStart(2,"0")).join("")}function se(t){let e=t.req.param("schemaHash"),r=R.get(e);return r==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:r}}var Ze=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function ae(t,e){let r=oe.from(t,"base64").toString("utf8"),n=`datasource db {
5
5
  provider = "postgresql"
6
6
  url = "${e}"
7
- }`,o=n.replace(xe,r),s=await H(o);return{base64Override:N.from(o,"utf8").toString("base64"),overrideHash:s}}function T(t){let{req:e}=t;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}import{integer as G,looseObject as Oe,minValue as J,number as I,object as He,optional as Ie,pipe as Q,safeParse as X,string as W,union as Ce}from"valibot";var De=He({isolation_level:Ie(W()),max_wait:Q(I(),G(),J(0)),timeout:Q(I(),G(),J(0))});async function Y(t){let{issues:e,output:n,success:r}=X(De,await t.req.json(),{abortEarly:!0});return r?n:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}var _e=Oe({id:Ce([W(),I()])});function Z(t,e){let{output:n,success:r}=X(_e,t);return r?n:e.json({EngineMalfunction:{}},500)}async function te(t,e,n){let r=await Ue(t,e,n),{fail:o,promise:s,succeed:i}=v(),a=Be({createServer:$e,fetch:r.fetch,port:t},()=>{i()});return a.on("error",c=>{if(typeof c=="object"&&"code"in c&&c.code==="EADDRINUSE")return o(new p(t,"accelerate"));console.error(c)}),await s,{async close(){await Promise.allSettled([ke(a.close.bind(a))(),f.stopAll()])},port:t,url:`http://localhost:${t}`}}async function Ue(t,e,n){let r=new ee,o=await Le.getPlatformInfo();return n&&console.debug("platform info: %s",JSON.stringify(o)),n&&r.use("*",je()),r.use("*",async(s,i)=>(s.set("db",e),s.set("debug",!!n),s.set("platform",o),s.set("port",t),s.set("protocol","http"),await i())),r.route("/",w),r}var w=new ee;w.get("/health",t=>t.text("ok"));w.post("/invalidate",y("header",u),async t=>{let e=await L(t);return e instanceof Response?e:t.body(null)});var qe="/:clientVersion/:schemaHash",S=w.basePath(qe);w.route("/",S);var Fe=["/graphql","/itx/:transactionId/graphql"];S.on("POST",[...Fe],y("header",u),async t=>{let{req:e}=t;try{let n=await C(t);if(n instanceof Response)return n;let r=await e.text(),o=e.param("transactionId"),s=await n.request(r,{...T(t),"X-transaction-id":o});return t.text(s)}catch(n){return E(n,t)}});S.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],y("header",u),async t=>{let{req:e}=t;try{let n=await C(t);if(n instanceof Response)return n;let o=`${e.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=e.param("transactionId"),i=await n[o](s,T(t));return t.json(i)}catch(n){return E(n,t)}});S.put("/schema",y("header",u),async t=>{let{req:e}=t,n=await e.text();if(!n)return t.text("Missing schema",400);let r=e.param("schemaHash"),o=A.get(r);if(o==null){if(r!==await H(n))return t.text("Schema hash mismatch",400);let s=await z(n,t.get("db").connectionString);return A.set(r,{base64Original:n,...s}),t.text(r)}return n!==o.base64Original?t.text("Schema mismatch",400):t.text(r)});S.post("/transaction/start",y("header",u),async t=>{let{req:e}=t,n=await Y(t);if(n instanceof Response)return n;try{let r=await C(t);if(r instanceof Response)return r;let o=await r.startTransaction(n,T(t)),s=Z(o,t);if(s instanceof Response)return s;let{id:i}=s,a=e.param("clientVersion"),c=t.get("port"),l=t.get("protocol"),d=e.param("schemaHash");return t.json({...o,"data-proxy":{endpoint:`${l}://localhost:${c}/${a}/${d}/itx/${i}`}})}catch(r){return E(r,t)}});async function C(t){let{req:e}=t,n=K(t);if(n instanceof Response)return n;let{base64Override:r,overrideHash:o}=n.schemas;return await f.get({base64Schema:r,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.param("clientVersion"),debug:t.get("debug"),platform:t.get("platform"),schemaHash:o})}import{PGlite as Ve}from"@electric-sql/pglite";import{PGLiteSocketServer as Me}from"@electric-sql/pglite-socket";async function D(t,e,n){let r={connectionLimit:1,connectTimeout:0,database:"postgres",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,port:t,socketTimeout:0,sslMode:"disable",username:"postgres"},o=await Ve.create({database:r.database,dataDir:"memory://",debug:n?5:void 0,defaultDataTransferContainer:"file",username:r.username});await o.waitReady;let s=new Me({db:o,inspect:n,port:t});try{await s.start()}catch(a){throw a instanceof Error&&"code"in a&&a.code==="EADDRINUSE"?new p(t,e):a}n&&console.debug(`${e} server started on port %i`,t);let i=`postgres://${r.username}:${r.password}@localhost:${t}/${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 s.stop()}finally{await o.close()}},connectionString:i}}async function jt(t){let{acceleratePort:e=51213,databasePort:n=51214,debug:r=!1,shadowDatabasePort:o=51215}=t||{},[s,i]=await Promise.all([D(n,"database",r),D(o,"shadow_database",r)]),a=await te(e,s,r),c=`prisma+postgres://localhost:${a.port}/?${new URLSearchParams({api_key:B({databaseUrl:s.connectionString,shadowDatabaseUrl:i.connectionString})}).toString()}`;return{accelerate:{url:a.url},close:()=>l([a,s,i]),database:{connectionString:s.connectionString},ppg:{url:c},shadowDatabase:{connectionString:i.connectionString}};async function l(d){let b=(await Promise.allSettled(d.map(g=>g.close()))).filter(g=>g.status==="rejected").map(g=>new Error(g.reason));if(b.length>0)throw new AggregateError(b,"Failed to close some servers")}}export{F as DEFAULT_ACCELERATE_PORT,V as DEFAULT_DATABASE_PORT,M as DEFAULT_SHADOW_DATABASE_PORT,p as PortNotAvailableError,jt as unstable_startServer};
7
+ }`,o=r.replace(Ze,n),s=await _(o);return{base64Override:oe.from(o,"utf8").toString("base64"),overrideHash:s}}function O(t){let{req:e}=t;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}import{integer as ie,looseObject as et,minValue as ce,number as H,object as tt,optional as rt,pipe as de,safeParse as ue,string as le,union as nt}from"valibot";var ot=tt({isolation_level:rt(le()),max_wait:de(H(),ie(),ce(0)),timeout:de(H(),ie(),ce(0))});async function me(t){let{issues:e,output:r,success:n}=ue(ot,await t.req.json(),{abortEarly:!0});return n?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}var st=et({id:nt([le(),H()])});function pe(t,e){let{output:r,success:n}=ue(st,t);return n?r:e.json({EngineMalfunction:{}},500)}async function he(t,e){let{port:r}=e;if(e.dryRun)return ge(r,null);let n=await mt(r,t,e),{fail:o,promise:s,succeed:a}=A(),i=ct({createServer:at,fetch:n.fetch,port:r},()=>{a()});return i.on("error",c=>{if(typeof c=="object"&&"code"in c&&c.code==="EADDRINUSE")return o(new h(r,"server"));console.error(c)}),await s,ge(r,i)}function ge(t,e){return{async close(){e&&await Promise.allSettled([it(e.close.bind(e))(),y.stopAll()])},port:t,url:`http://localhost:${t}`}}async function mt(t,e,r){let{debug:n}=r,o=new fe,s=await dt.getPlatformInfo();return n&&console.debug("platform info: %s",JSON.stringify(s)),n&&o.use("*",ut()),o.use("*",async(a,i)=>(a.set("db",e),a.set("debug",!!n),a.set("platform",s),a.set("port",t),a.set("protocol","http"),a.set("serverState",r),await i())),o.route("/",P),o}var P=new fe;P.get("/health",t=>t.json({name:t.get("serverState").name}));P.post("/invalidate",S("header",g),async t=>{let e=await G(t);return e instanceof Response?e:t.body(null)});var pt="/:clientVersion/:schemaHash",v=P.basePath(pt);P.route("/",v);var gt=["/graphql","/itx/:transactionId/graphql"];v.on("POST",[...gt],S("header",g),async t=>{let{req:e}=t;try{let r=await B(t);if(r instanceof Response)return r;let n=await e.text(),o=e.param("transactionId"),s=await r.request(n,{...O(t),"X-transaction-id":o});return t.text(s)}catch(r){return T(r,t)}});v.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],S("header",g),async t=>{let{req:e}=t;try{let r=await B(t);if(r instanceof Response)return r;let o=`${e.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=e.param("transactionId"),a=await r[o](s,O(t));return t.json(a)}catch(r){return T(r,t)}});v.put("/schema",S("header",g),async t=>{let{req:e}=t,r=await e.text();if(!r)return t.text("Missing schema",400);let n=e.param("schemaHash"),o=R.get(n);if(o==null){if(n!==await _(r))return t.text("Schema hash mismatch",400);let s=await ae(r,t.get("db").connectionString);return R.set(n,{base64Original:r,...s}),t.text(n)}return r!==o.base64Original?t.text("Schema mismatch",400):t.text(n)});v.post("/transaction/start",S("header",g),async t=>{let{req:e}=t,r=await me(t);if(r instanceof Response)return r;try{let n=await B(t);if(n instanceof Response)return n;let o=await n.startTransaction(r,O(t)),s=pe(o,t);if(s instanceof Response)return s;let{id:a}=s,i=e.param("clientVersion"),c=t.get("port"),u=t.get("protocol"),m=e.param("schemaHash");return t.json({...o,"data-proxy":{endpoint:`${u}://localhost:${c}/${i}/${m}/itx/${a}`}})}catch(n){return T(n,t)}});async function B(t){let{req:e}=t,r=se(t);if(r instanceof Response)return r;let{base64Override:n,overrideHash:o}=r.schemas;return await y.get({base64Schema:n,clientVersion:lt.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.param("clientVersion"),debug:t.get("debug"),platform:t.get("platform"),schemaHash:o})}import{PGlite as ft}from"@electric-sql/pglite";import{PGLiteSocketServer as ht}from"@electric-sql/pglite-socket";import{pgDump as bt}from"@electric-sql/pglite-tools/pg_dump";var d={connectionLimit:1,connectTimeout:0,database:"postgres",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},yt=`postgres://${d.username}:${d.password}@localhost`,wt=new URLSearchParams({connection_limit:String(d.connectionLimit),connect_timeout:String(d.connectTimeout),max_idle_connection_lifetime:String(d.maxIdleConnectionLifetime),pool_timeout:String(d.poolTimeout),socket_timeout:String(d.socketTimeout),sslmode:d.sslMode});async function L(t,e){let r=t==="database"?e.databasePort:e.shadowDatabasePort;if(e.dryRun)return be(t,e,{db:null,port:r,server:null});let{debug:n}=e,o=await ft.create({database:d.database,dataDir:"memory://",debug:n?5:void 0,defaultDataTransferContainer:"file",username:d.username});await o.waitReady,t==="database"&&await St(o,e);let s=new ht({db:o,inspect:n,port:r});try{await s.start()}catch(a){throw a instanceof Error&&"code"in a&&a.code==="EADDRINUSE"?new h(r,t):a}return be(t,e,{db:o,port:r,server:s})}function be(t,e,r){let{debug:n}=e,{db:o,port:s,server:a}=r||{};return n&&console.debug(`${t} server started on port ${s}`),{...d,close:async()=>{let i=[];try{await a?.stop(),n&&console.debug(`${t} server stopped on port ${s}`)}catch(c){console.error("server stop error",c),i.push(c)}if(t==="database")try{await Pt(o,e),n&&console.debug(`${t} state saved`)}catch(c){console.error("dump error",c),i.push(c)}try{await o?.close(),n&&console.debug(`${t} closed`)}catch(c){console.error("db close error",c),i.push(c)}if(i.length>0)throw new AggregateError(i,`Failed to close ${t} properly`)},connectionString:vt(s),port:s}}async function St(t,e){let r=await e.readDatabaseDump();r&&(await t.exec(`${r}; set search_path to public;`),e.debug&&console.debug("successfully loaded database state from a dump file"))}async function Pt(t,e){await e.writeDatabaseDump(()=>bt({args:[],pg:t}))}function vt(t){return`${yt}:${t}/${d.database}?${wt.toString()}`}import{copyFile as Et,mkdir as Dt,writeFile as At}from"fs/promises";import{join as C}from"pathe";import{lock as Tt}from"proper-lockfile";import{readLastLines as Rt}from"read-last-lines-ts";import{process as Ot}from"std-env";var j=Symbol("initialize"),b=class{databasePort;debug;dryRun;name;persistenceMode;port;shadowDatabasePort;constructor(e){this.databasePort=e.databasePort??51214,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??"default",this.persistenceMode=e.persistenceMode,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async get(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new F(e):new M(e);return await r[j](),r}},M=class extends b{constructor(e){super({...e,persistenceMode:"stateless"})}async[j](){}async close(){}readDatabaseDump(){return Promise.resolve(null)}async writeDatabaseDump(){}async writeServerDump(){}},F=class extends b{#r;#e;#t;#s;#o=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#r=W(this.name),this.#e=C(this.#r,"ppg.sql"),this.#t=`${this.#e}.bak`,this.#s=C(this.#r,"server.json")}async[j](){await Dt(this.#r,{recursive:!0}),this.debug&&console.debug(`using data directory: ${this.#r}`);try{this.#o=await Tt(this.#r,{lockfilePath:C(this.#r,".lock")}),this.debug&&console.debug(`obtained lock on: ${this.#r}`),await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new Error(`A server with the name "${this.name}" is already running. `):e}}async close(){this.#o!=null&&(await this.#o(),this.debug&&console.debug(`released lock on: ${this.#r}`))}async readDatabaseDump(){let[e,r]=await Promise.all([$(this.#e),$(this.#t)]),n=Number.isFinite(e)?this.#e:null,o=Number.isFinite(r)?this.#t:null,s=(e>=r?[n,o]:[o,n]).filter(Boolean);for(let a of s){if(!await this.#a(a)){this.debug&&console.debug(`database dump not completed at: ${a}`);continue}let i=await Z(a);if(!i){this.debug&&console.debug(`database dump no longer available at: ${a}`);continue}if(!this.#n(i)){this.debug&&console.debug(`database dump no longer completed at: ${a}`);continue}return this.debug&&console.debug(`using database dump from: ${a}`),i}return this.debug&&console.debug("no completed database dumps found"),null}async writeDatabaseDump(e){let r=!1;await this.#a(this.#e)&&(await Et(this.#e,this.#t),r=!0,this.debug&&console.debug(`backed up dump to: ${this.#t}`));let n=await e();if(await Y(n,this.#e),this.debug&&console.debug(`dumped database to: ${this.#e}`),!r)return;let o=await X(this.#t);this.debug&&o&&console.debug(`deleted backup dump: ${this.#t}`)}async writeServerDump(e){await At(this.#s,`${JSON.stringify({name:this.name,version:"1",pid:Ot.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},null,2)}
8
+ `,{encoding:"utf-8"})}async#a(e){if(!await D(e))return!1;let r=Rt(e,5).toString("utf-8");return this.debug&&console.debug(`last lines of checked dump: ${r}`),this.#n(r)}#n(e){return e.includes("-- PostgreSQL database dump complete")}};async function Cr(t){let e=await b.get(t),[r,n]=await Promise.all([L("database",e),L("shadow_database",e)]),o=await he(r,e),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:K({databaseUrl:r.connectionString,shadowDatabaseUrl:n.connectionString})}).toString()}`,a={accelerate:{url:o.url},database:{connectionString:r.connectionString},ppg:{url:s},shadowDatabase:{connectionString:n.connectionString}};return await e.writeServerDump(a),{...a,close:()=>i(e,[o,r,n])};async function i(c,u){let p=(await Promise.allSettled(u.map(l=>l.close()))).filter(l=>l.status==="rejected").map(l=>new Error(l.reason));try{await c.close()}catch(l){p.push(l)}if(p.length>0)throw new AggregateError(p,"Failed to close some servers")}}export{te as DEFAULT_DATABASE_PORT,re as DEFAULT_SERVER_PORT,ne as DEFAULT_SHADOW_DATABASE_PORT,h as PortNotAvailableError,Cr as unstable_startServer};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/dev",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "A local Prisma Postgres server for development and testing",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -27,22 +27,29 @@
27
27
  ],
28
28
  "license": "ISC",
29
29
  "devDependencies": {
30
- "@arethetypeswrong/cli": "0.17.4",
31
- "@types/node": "22.3.0",
30
+ "@arethetypeswrong/cli": "0.18.1",
31
+ "@types/node": "22.15.21",
32
32
  "@types/pako": "2.0.3",
33
+ "@types/proper-lockfile": "4.1.4",
33
34
  "pkg-types": "2.1.0",
34
- "tsup": "8.0.2",
35
+ "tsup": "8.5.0",
35
36
  "typescript": "5.8.3",
36
- "vitest": "3.1.3"
37
+ "vitest": "3.1.4"
37
38
  },
38
39
  "dependencies": {
39
- "@electric-sql/pglite": "0.3.1",
40
- "@electric-sql/pglite-socket": "0.0.4",
41
- "@hono/node-server": "1.14.1",
42
- "@prisma/get-platform": "6.7.0",
40
+ "@electric-sql/pglite": "0.3.2",
41
+ "@electric-sql/pglite-socket": "0.0.6",
42
+ "@electric-sql/pglite-tools": "0.2.7",
43
+ "@hono/node-server": "1.14.2",
44
+ "@prisma/get-platform": "6.8.2",
43
45
  "env-paths": "3.0.0",
44
- "hono": "4.7.8",
46
+ "foreground-child": "3.3.1",
47
+ "hono": "4.7.10",
45
48
  "pako": "2.1.0",
49
+ "pathe": "2.0.3",
50
+ "proper-lockfile": "4.1.2",
51
+ "read-last-lines-ts": "1.2.1",
52
+ "std-env": "3.9.0",
46
53
  "valibot": "1.1.0"
47
54
  },
48
55
  "scripts": {