@prisma/dev 0.2.0 → 0.3.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/chunk-EVE556Q6.js +2 -0
- package/dist/daemon/client.d.ts +24 -0
- package/dist/daemon/client.js +2 -0
- package/dist/daemon/daemon.d.ts +2 -0
- package/dist/daemon/daemon.js +2 -0
- package/dist/index-CW1pktRs.d.ts +83 -0
- package/dist/index.d.ts +1 -83
- package/dist/index.js +6 -6
- package/package.json +9 -2
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import * as url from 'url';
|
|
2
|
+
import { SockDaemonClient } from 'sock-daemon/client';
|
|
3
|
+
import { S as ServerOptions, a as Server } from '../index-CW1pktRs.js';
|
|
4
|
+
import { MessageBase } from 'sock-daemon/server';
|
|
5
|
+
|
|
6
|
+
type Kind = "START_SERVER" | "STOP_SERVER";
|
|
7
|
+
type RequestMessage = MessageBase & {
|
|
8
|
+
kind: Kind;
|
|
9
|
+
args?: unknown;
|
|
10
|
+
};
|
|
11
|
+
type ResponseMessage = MessageBase & {
|
|
12
|
+
kind: Kind;
|
|
13
|
+
result?: unknown;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
declare class MyServiceClient extends SockDaemonClient<RequestMessage, ResponseMessage> {
|
|
17
|
+
static get serviceName(): string;
|
|
18
|
+
static get daemonScript(): url.URL;
|
|
19
|
+
isResponse(msg: unknown): msg is ResponseMessage;
|
|
20
|
+
stopServer(): Promise<void>;
|
|
21
|
+
startServer(options: ServerOptions): Promise<Server>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export { MyServiceClient };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
|
|
2
|
+
import{a as s}from"../chunk-EVE556Q6.js";import{SockDaemonClient as a}from"sock-daemon/client";var r=class extends a{static get serviceName(){return s}static get daemonScript(){return new URL("./daemon.js",import.meta.url)}isResponse(e){return super.isMessage(e)}async stopServer(){await super.request({kind:"STOP_SERVER"})}async startServer(e){let{result:t}=await super.request({kind:"START_SERVER",args:e});return t}};export{r as MyServiceClient};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
|
|
2
|
+
import{a as r}from"../chunk-EVE556Q6.js";import{SockDaemonServer as o}from"sock-daemon/server";var s=class extends o{isRequest(e){return super.isMessage(e)}static get serviceName(){return r}handle(e){return console.error("got request",e),Promise.resolve({id:e.id,kind:e.kind,result:null})}};var t=new s({});t.listen();
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
interface ServerOptions {
|
|
2
|
+
/**
|
|
3
|
+
* The port the database server will listen on.
|
|
4
|
+
*
|
|
5
|
+
* Defaults to `51214`.
|
|
6
|
+
*
|
|
7
|
+
* An error is thrown if the port is already in use.
|
|
8
|
+
*/
|
|
9
|
+
databasePort?: number;
|
|
10
|
+
/**
|
|
11
|
+
* Whether to enable debug logging.
|
|
12
|
+
*
|
|
13
|
+
* Defaults to `false`.
|
|
14
|
+
*/
|
|
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;
|
|
42
|
+
/**
|
|
43
|
+
* The port the shadow database server will listen on.
|
|
44
|
+
*
|
|
45
|
+
* Defaults to `51215`.
|
|
46
|
+
*
|
|
47
|
+
* An error is thrown if the port is already in use.
|
|
48
|
+
*/
|
|
49
|
+
shadowDatabasePort?: number;
|
|
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
|
+
|
|
66
|
+
interface Server {
|
|
67
|
+
accelerate: {
|
|
68
|
+
url: string;
|
|
69
|
+
};
|
|
70
|
+
close(): Promise<void>;
|
|
71
|
+
database: {
|
|
72
|
+
connectionString: string;
|
|
73
|
+
};
|
|
74
|
+
ppg: {
|
|
75
|
+
url: string;
|
|
76
|
+
};
|
|
77
|
+
shadowDatabase: {
|
|
78
|
+
connectionString: string;
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
declare function unstable_startServer(options?: ServerOptions): Promise<Server>;
|
|
82
|
+
|
|
83
|
+
export { DEFAULT_DATABASE_PORT as D, type PortAssignableService as P, type ServerOptions as S, type Server as a, DEFAULT_SERVER_PORT as b, DEFAULT_SHADOW_DATABASE_PORT as c, PortNotAvailableError as d, unstable_startServer as u };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,83 +1 @@
|
|
|
1
|
-
|
|
2
|
-
/**
|
|
3
|
-
* The port the database server will listen on.
|
|
4
|
-
*
|
|
5
|
-
* Defaults to `51214`.
|
|
6
|
-
*
|
|
7
|
-
* An error is thrown if the port is already in use.
|
|
8
|
-
*/
|
|
9
|
-
databasePort?: number;
|
|
10
|
-
/**
|
|
11
|
-
* Whether to enable debug logging.
|
|
12
|
-
*
|
|
13
|
-
* Defaults to `false`.
|
|
14
|
-
*/
|
|
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;
|
|
42
|
-
/**
|
|
43
|
-
* The port the shadow database server will listen on.
|
|
44
|
-
*
|
|
45
|
-
* Defaults to `51215`.
|
|
46
|
-
*
|
|
47
|
-
* An error is thrown if the port is already in use.
|
|
48
|
-
*/
|
|
49
|
-
shadowDatabasePort?: number;
|
|
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
|
-
|
|
66
|
-
interface Server {
|
|
67
|
-
accelerate: {
|
|
68
|
-
url: string;
|
|
69
|
-
};
|
|
70
|
-
close(): Promise<void>;
|
|
71
|
-
database: {
|
|
72
|
-
connectionString: string;
|
|
73
|
-
};
|
|
74
|
-
ppg: {
|
|
75
|
-
url: string;
|
|
76
|
-
};
|
|
77
|
-
shadowDatabase: {
|
|
78
|
-
connectionString: string;
|
|
79
|
-
};
|
|
80
|
-
}
|
|
81
|
-
declare function unstable_startServer(options?: ServerOptions): Promise<Server>;
|
|
82
|
-
|
|
83
|
-
export { DEFAULT_DATABASE_PORT, DEFAULT_SERVER_PORT, DEFAULT_SHADOW_DATABASE_PORT, type PortAssignableService, PortNotAvailableError, type Server, unstable_startServer };
|
|
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 './index-CW1pktRs.js';
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{createServer as
|
|
3
|
-
`).find(ye=>ye.includes("Started query engine http server"));if(!m)return;s.stdout.removeListener("data",
|
|
4
|
-
Received data: ${
|
|
1
|
+
import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
|
|
2
|
+
import{createServer as it}from"http";import{promisify as at}from"util";import{serve as ct}from"@hono/node-server";import dt from"@prisma/get-platform";function E(){let t,e,r=new Promise((s,i)=>{t=s,e=i}),n=s=>{n=o=null,e(s)},o=s=>{o=n=null,t(s)};return{promise:r,reject:s=>n?.(s),resolve:s=>o?.(s)}}import{logger as lt}from"hono/logger";import{Hono as he}from"hono/tiny";import{validator as S}from"hono/validator";import{process as ut}from"std-env";import{HTTPException as D}from"hono/http-exception";import{object as we,optional as Se,parseJson as Pe,pipe as I,regex as U,safeParse as ve,string as k,url as q}from"valibot";var V=/^(postgres|postgresql):\/\//,Ee=I(k(),Pe(),we({databaseUrl:I(k(),q(),U(V)),shadowDatabaseUrl:Se(I(k(),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 D(401,{message:"Missing API Key"});let[n,o="",s]=r.split(" ");if(n!=="Bearer"||s)throw new D(401,{message:"Invalid API Key"});let[i,a]=De(o);if(i)throw new D(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:c}=a;if(c!==e.var.db.connectionString)throw new D(401,{message:"Unauthorized"});return{decodedAPIKey:a}};import{array as Ae,literal as Te,minLength as Re,object as Oe,pipe as xe,safeParse as Ie,string as ke,union as $e}from"valibot";var _e=Oe({tags:$e([xe(Ae(ke()),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 A(t){try{return await Le(t,Me.F_OK),!0}catch(e){if(_(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(_(e))return-1/0;throw e}}function _(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(_(e))return null;throw e}}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.#s(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 h.fromResponse(s);return await s.text()}async rollbackTransaction(e,r){return await this.#s(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 h.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return;let{promise:e,reject:r,resolve:n}=E();this.#t=e;let o=await this.#i();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 i=l=>{let m=l.split(`
|
|
3
|
+
`).find(ye=>ye.includes("Started query engine http server"));if(!m)return;s.stdout.removeListener("data",i);let{fields:p}=JSON.parse(m);if(p==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${l}`));let{ip:u,port:N}=p;if(u==null||N==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: ${l}`));n({childProcess:s,url:`http://${u}:${N}`})},a=l=>{this.#t=null,r(new w(String(l))),s.removeListener("exit",c),s.kill()};s.once("error",a);let c=(l,m)=>{this.#t=null,r(new w(`Query Engine exited with code ${l} and signal ${m}`))};s.once("exit",c),s.stdout.on("data",i),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#i(){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 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 A(s)===!1)&&await this.#o({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 n=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!n)throw new Error("Couldn't find engines version in package.json");let o=n.split(".").at(-1);if(!o)throw new Error("Couldn't find commit hash in engines version");return o}async#o(e){let{commitHash:r,extension:n,engineBinaryPath:o}=e,{binaryTarget:s}=this.#e.platform,i=`https://binaries.prisma.sh/all_commits/${r}/${s}/query-engine${n}.gz`;this.#e.debug&&console.debug("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}`);ee&&await We(Number(ee)),await Q(await a.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#s(e,r,n){let{url:o}=await this.#t,s=this.#n(r),i=await fetch(`${o}/transaction/${e}/${n}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await h.fromResponse(i);try{return await i.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 h?e.text(t.responseBody,t.statusCode):e.body(null,500)}var w=class extends Error{name="EngineStartError"},h=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,f=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 H(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}function 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 ie(t,e){let r=oe.from(t,"base64").toString("utf8"),n=`datasource db {
|
|
5
5
|
provider = "postgresql"
|
|
6
6
|
url = "${e}"
|
|
7
|
-
}`,o=r.replace(Ze,n),s=await
|
|
8
|
-
`,{encoding:"utf-8"})}async#
|
|
7
|
+
}`,o=r.replace(Ze,n),s=await H(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 ae,looseObject as et,minValue as ce,number as B,object as tt,optional as rt,pipe as de,safeParse as le,string as ue,union as nt}from"valibot";var ot=tt({isolation_level:rt(ue()),max_wait:de(B(),ae(),ce(0)),timeout:de(B(),ae(),ce(0))});async function me(t){let{issues:e,output:r,success:n}=le(ot,await t.req.json(),{abortEarly:!0});return n?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}var st=et({id:nt([ue(),B()])});function pe(t,e){let{output:r,success:n}=le(st,t);return n?r:e.json({EngineMalfunction:{}},500)}async function fe(t,e){let{port:r}=e;if(e.dryRun)return ge(r,null);let n=await mt(r,t,e),{promise:o,reject:s,resolve:i}=E(),a=ct({createServer:it,fetch:n.fetch,port:r},i);return a.on("error",c=>{if(typeof c=="object"&&"code"in c&&c.code==="EADDRINUSE")return s(new f(r,"server"));console.error(c)}),await o,ge(r,a)}function ge(t,e){return{async close(){e&&await Promise.allSettled([at(e.close.bind(e))(),y.stopAll()])},port:t,url:`http://localhost:${t}`}}async function mt(t,e,r){let{debug:n}=r,o=new he,s=await dt.getPlatformInfo();return n&&console.debug("platform info: %s",JSON.stringify(s)),n&&o.use("*",lt()),o.use("*",async(i,a)=>(i.set("db",e),i.set("debug",!!n),i.set("platform",s),i.set("port",t),i.set("protocol","http"),i.set("serverState",r),await a())),o.route("/",P),o}var P=new he;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 L(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 L(t);if(r instanceof Response)return r;let o=`${e.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=e.param("transactionId"),i=await r[o](s,O(t));return t.json(i)}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 H(r))return t.text("Schema hash mismatch",400);let s=await ie(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 L(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:i}=s,a=e.param("clientVersion"),c=t.get("port"),l=t.get("protocol"),m=e.param("schemaHash");return t.json({...o,"data-proxy":{endpoint:`${l}://localhost:${c}/${a}/${m}/itx/${i}`}})}catch(n){return T(n,t)}});async function L(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:ut.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.param("clientVersion"),debug:t.get("debug"),platform:t.get("platform"),schemaHash:o})}import{PGlite as ht}from"@electric-sql/pglite";import{PGLiteSocketServer as ft}from"@electric-sql/pglite-socket";var d={connectionLimit:1,connectTimeout:0,database:"postgres",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},bt=`postgres://${d.username}:${d.password}@localhost`,yt=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 C(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 ht.create({database:d.database,dataDir:t==="database"?e.pgliteDataDirPath:"memory://",debug:n?5:void 0,defaultDataTransferContainer:"file",username:d.username});await o.waitReady;let s=new ft({db:o,inspect:n,port:r});try{await s.start()}catch(i){throw i instanceof Error&&"code"in i&&i.code==="EADDRINUSE"?new f(r,t):i}return be(t,e,{db:o,port:r,server:s})}function be(t,e,r){let{debug:n}=e,{db:o,port:s,server:i}=r||{};return n&&console.debug(`${t} server started on port ${s}`),{...d,close:async()=>{let a=[];try{await i?.stop(),n&&console.debug(`${t} server stopped on port ${s}`)}catch(c){console.error("server stop error",c),a.push(c)}try{await o?.close(),n&&console.debug(`${t} closed`)}catch(c){console.error("db close error",c),a.push(c)}if(a.length>0)throw new AggregateError(a,`Failed to close ${t} properly`)},connectionString:wt(s),port:s}}function wt(t){return`${bt}:${t}/${d.database}?${yt.toString()}`}import{copyFile as St,mkdir as Pt,writeFile as vt}from"fs/promises";import{join as x}from"pathe";import{lock as Et}from"proper-lockfile";import{readLastLines as Dt}from"read-last-lines-ts";import{process as At}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"})}get pgliteDataDirPath(){return"memory://"}async[j](){}async close(){}readDatabaseDump(){return Promise.resolve(null)}async writeDatabaseDump(){}async writeServerDump(){}},F=class extends b{#r;#e;#t;#i;#a;#o=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#r=W(this.name),this.#e=x(this.#r,"ppg.sql"),this.#t=`${this.#e}.bak`,this.#i=x(this.#r,".pglite"),this.#a=x(this.#r,"server.json")}get pgliteDataDirPath(){return this.#i}async[j](){await Pt(this.#r,{recursive:!0}),this.debug&&console.debug(`using data directory: ${this.#r}`);try{this.#o=await Et(this.#r,{lockfilePath:x(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 i of s){if(!await this.#n(i)){this.debug&&console.debug(`database dump not completed at: ${i}`);continue}let a=await Z(i);if(!a){this.debug&&console.debug(`database dump no longer available at: ${i}`);continue}if(!this.#s(a)){this.debug&&console.debug(`database dump no longer completed at: ${i}`);continue}return this.debug&&console.debug(`using database dump from: ${i}`),a}return this.debug&&console.debug("no completed database dumps found"),null}async writeDatabaseDump(e){let r=!1;await this.#n(this.#e)&&(await St(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 vt(this.#a,`${JSON.stringify({name:this.name,version:"1",pid:At.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},null,2)}
|
|
8
|
+
`,{encoding:"utf-8"})}async#n(e){if(!await A(e))return!1;let r=Dt(e,5).toString("utf-8");return this.debug&&console.debug(`last lines of checked dump: ${r}`),this.#s(r)}#s(e){return e.includes("-- PostgreSQL database dump complete")}};async function _r(t){let e=await b.get(t),[r,n]=await Promise.all([C("database",e),C("shadow_database",e)]),o=await fe(r,e),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:K({databaseUrl:r.connectionString,shadowDatabaseUrl:n.connectionString})}).toString()}`,i={accelerate:{url:o.url},database:{connectionString:r.connectionString},ppg:{url:s},shadowDatabase:{connectionString:n.connectionString}};return await e.writeServerDump(i),{...i,close:()=>a(e,[o,r,n])};async function a(c,l){let p=(await Promise.allSettled(l.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{te as DEFAULT_DATABASE_PORT,re as DEFAULT_SERVER_PORT,ne as DEFAULT_SHADOW_DATABASE_PORT,f as PortNotAvailableError,_r as unstable_startServer};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma/dev",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "A local Prisma Postgres server for development and testing",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -14,6 +14,11 @@
|
|
|
14
14
|
"types": "./dist/index.d.ts",
|
|
15
15
|
"import": "./dist/index.js",
|
|
16
16
|
"default": "./dist/index.js"
|
|
17
|
+
},
|
|
18
|
+
"./daemon": {
|
|
19
|
+
"types": "./dist/daemon/client.d.ts",
|
|
20
|
+
"import": "./dist/daemon/client.js",
|
|
21
|
+
"default": "./dist/daemon/client.js"
|
|
17
22
|
}
|
|
18
23
|
},
|
|
19
24
|
"keywords": [
|
|
@@ -34,7 +39,8 @@
|
|
|
34
39
|
"pkg-types": "2.1.0",
|
|
35
40
|
"tsup": "8.5.0",
|
|
36
41
|
"typescript": "5.8.3",
|
|
37
|
-
"vitest": "3.1.4"
|
|
42
|
+
"vitest": "3.1.4",
|
|
43
|
+
"common-stuff": "^0.0.0"
|
|
38
44
|
},
|
|
39
45
|
"dependencies": {
|
|
40
46
|
"@electric-sql/pglite": "0.3.2",
|
|
@@ -49,6 +55,7 @@
|
|
|
49
55
|
"pathe": "2.0.3",
|
|
50
56
|
"proper-lockfile": "4.1.2",
|
|
51
57
|
"read-last-lines-ts": "1.2.1",
|
|
58
|
+
"sock-daemon": "1.4.2",
|
|
52
59
|
"std-env": "3.9.0",
|
|
53
60
|
"valibot": "1.1.0"
|
|
54
61
|
},
|