@prisma/dev 0.0.0-dev.202506031934 → 0.0.0-dev.202506031938
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-PVN7L773.js +3 -0
- package/dist/daemon/client.d.ts +2 -1
- package/dist/index-CMQuwyab.d.ts +133 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +5 -6
- package/dist/state.d.ts +2 -0
- package/dist/state.js +2 -0
- package/package.json +6 -1
- package/dist/index-BtR4iL6u.d.ts +0 -83
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
|
|
2
|
+
import{mkdir as B,writeFile as V}from"fs/promises";import{join as s}from"pathe";import{lock as N}from"proper-lockfile";import{process as U}from"std-env";import{integer as w,literal as W,minLength as j,minValue as x,number as A,object as n,optional as v,pipe as a,safeParse as H,string as E,url as C}from"valibot";import{createWriteStream as T,WriteStream as _}from"fs";import{access as R,chmod as F,constants as M,readFile as I,writeFile as L}from"fs/promises";import $ from"env-paths";import{inflate as k}from"pako";var m=$("prisma-dev");function G(t,e){return`${m.cache}/engine/${t}/${e}`}function l(t){return`${m.data}/${t}`}async function Q(t){try{return await R(t,M.F_OK),!0}catch(e){if(h(e))return!1;throw e}}async function X(t,e){let r=k(t);await L(e,r),await F(e,"755")}async function ee(t,e){await t.stream().pipeTo(_.toWeb(T(e,{encoding:"utf-8"})))}function h(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function P(t){try{return await I(t,{encoding:"utf-8"})}catch(e){if(h(e))return null;throw e}}var g=51214,f=51213,D=51215,b=class extends Error{constructor(r,c){super(`Port number \`${r}\` is not available for service ${c}.`);this.port=r;this.service=c}name="PortNotAvailableError"};var O=a(E(),C()),y=n({connectionString:O}),S=n({url:O}),u=a(A(),w(),x(1)),J=n({database:y,http:S,ppg:S,shadowDatabase:y}),K=n({databasePort:u,exports:v(J),name:a(E(),j(1)),pid:v(a(A(),w(),x(0))),port:u,shadowDatabasePort:u,version:W("1")}),p=Symbol("initialize"),i=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 readServerDump(e){return await new o({name:e}).readServerDump()}static async get(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new o(e):new d(e);return await r[p](),r}},d=class extends i{constructor(e){super({...e,persistenceMode:"stateless"})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[p](){}async close(){}async writeServerDump(){}},o=class extends i{#s;#e;#a;#t;#r=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=l(this.name),this.#s=s(this.#e,"db_dump.bak"),this.#a=s(this.#e,".pglite"),this.#t=s(this.#e,"server.json")}get databaseDumpPath(){return this.#s}get pgliteDataDirPath(){return this.#a}async[p](){await B(this.#e,{recursive:!0}),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#r=await N(this.#e,{lockfilePath:s(this.#e,".lock")}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`),await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new Error(`A server with the name "${this.name}" is already running. `):e}}async close(){this.#r!=null&&(await this.#r(),this.debug&&console.debug(`[State] released lock on: ${this.#e}`))}async readServerDump(){let e=await P(this.#t);if(e==null)return null;let{output:r,success:c}=H(K,JSON.parse(e));if(!c)throw new Error(`Invalid Prisma Dev state for "${this.name}".`);return r}async writeServerDump(e){await V(this.#t,`${JSON.stringify({name:this.name,version:"1",pid:U.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},null,2)}
|
|
3
|
+
`,{encoding:"utf-8"})}};export{G as a,Q as b,X as c,ee as d,g as e,f,D as g,b as h,i};
|
package/dist/daemon/client.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import * as url from 'url';
|
|
2
2
|
import { SockDaemonClient } from 'sock-daemon/client';
|
|
3
|
-
import { S as ServerOptions, a as Server } from '../index-
|
|
3
|
+
import { S as ServerOptions, a as Server } from '../index-CMQuwyab.js';
|
|
4
4
|
import { MessageBase } from 'sock-daemon/server';
|
|
5
|
+
import 'valibot';
|
|
5
6
|
|
|
6
7
|
type Kind = "START_SERVER" | "STOP_SERVER";
|
|
7
8
|
type RequestMessage = MessageBase & {
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import * as valibot from 'valibot';
|
|
2
|
+
import { InferOutput } from 'valibot';
|
|
3
|
+
|
|
4
|
+
declare const exportsSchema: valibot.ObjectSchema<{
|
|
5
|
+
readonly database: valibot.ObjectSchema<{
|
|
6
|
+
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
7
|
+
}, undefined>;
|
|
8
|
+
readonly http: valibot.ObjectSchema<{
|
|
9
|
+
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
10
|
+
}, undefined>;
|
|
11
|
+
readonly ppg: valibot.ObjectSchema<{
|
|
12
|
+
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
13
|
+
}, undefined>;
|
|
14
|
+
readonly shadowDatabase: valibot.ObjectSchema<{
|
|
15
|
+
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
16
|
+
}, undefined>;
|
|
17
|
+
}, undefined>;
|
|
18
|
+
type Exports = InferOutput<typeof exportsSchema>;
|
|
19
|
+
declare const serverDumpV1Schema: valibot.ObjectSchema<{
|
|
20
|
+
readonly databasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
|
|
21
|
+
readonly exports: valibot.OptionalSchema<valibot.ObjectSchema<{
|
|
22
|
+
readonly database: valibot.ObjectSchema<{
|
|
23
|
+
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
24
|
+
}, undefined>;
|
|
25
|
+
readonly http: valibot.ObjectSchema<{
|
|
26
|
+
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
27
|
+
}, undefined>;
|
|
28
|
+
readonly ppg: valibot.ObjectSchema<{
|
|
29
|
+
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
30
|
+
}, undefined>;
|
|
31
|
+
readonly shadowDatabase: valibot.ObjectSchema<{
|
|
32
|
+
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
33
|
+
}, undefined>;
|
|
34
|
+
}, undefined>, undefined>;
|
|
35
|
+
readonly name: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
|
|
36
|
+
readonly pid: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 0, undefined>]>, undefined>;
|
|
37
|
+
readonly port: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
|
|
38
|
+
readonly shadowDatabasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
|
|
39
|
+
readonly version: valibot.LiteralSchema<"1", undefined>;
|
|
40
|
+
}, undefined>;
|
|
41
|
+
type ServerDumpV1 = InferOutput<typeof serverDumpV1Schema>;
|
|
42
|
+
interface ServerOptions {
|
|
43
|
+
/**
|
|
44
|
+
* The port the database server will listen on.
|
|
45
|
+
*
|
|
46
|
+
* Defaults to `51214`.
|
|
47
|
+
*
|
|
48
|
+
* An error is thrown if the port is already in use.
|
|
49
|
+
*/
|
|
50
|
+
databasePort?: number;
|
|
51
|
+
/**
|
|
52
|
+
* Whether to enable debug logging.
|
|
53
|
+
*
|
|
54
|
+
* Defaults to `false`.
|
|
55
|
+
*/
|
|
56
|
+
debug?: boolean;
|
|
57
|
+
/**
|
|
58
|
+
* Whether to run the server in dry run mode.
|
|
59
|
+
*
|
|
60
|
+
* Defaults to `false`.
|
|
61
|
+
*/
|
|
62
|
+
dryRun?: boolean;
|
|
63
|
+
/**
|
|
64
|
+
* The name of the server.
|
|
65
|
+
*
|
|
66
|
+
* Defaults to `default`.
|
|
67
|
+
*/
|
|
68
|
+
name?: string;
|
|
69
|
+
/**
|
|
70
|
+
* The persistence mode of the server.
|
|
71
|
+
*
|
|
72
|
+
* Default is `stateless`.
|
|
73
|
+
*/
|
|
74
|
+
persistenceMode?: PersistenceMode;
|
|
75
|
+
/**
|
|
76
|
+
* The port the server will listen on.
|
|
77
|
+
*
|
|
78
|
+
* Defaults to `51213`.
|
|
79
|
+
*
|
|
80
|
+
* An error is thrown if the port is already in use.
|
|
81
|
+
*/
|
|
82
|
+
port?: number;
|
|
83
|
+
/**
|
|
84
|
+
* The port the shadow database server will listen on.
|
|
85
|
+
*
|
|
86
|
+
* Defaults to `51215`.
|
|
87
|
+
*
|
|
88
|
+
* An error is thrown if the port is already in use.
|
|
89
|
+
*/
|
|
90
|
+
shadowDatabasePort?: number;
|
|
91
|
+
}
|
|
92
|
+
type ResolvedServerOptions = Required<ServerOptions>;
|
|
93
|
+
type PersistenceMode = "stateless" | "stateful";
|
|
94
|
+
declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
|
|
95
|
+
declare abstract class ServerState implements ResolvedServerOptions {
|
|
96
|
+
readonly databasePort: number;
|
|
97
|
+
readonly debug: boolean;
|
|
98
|
+
readonly dryRun: boolean;
|
|
99
|
+
readonly name: string;
|
|
100
|
+
readonly persistenceMode: PersistenceMode;
|
|
101
|
+
readonly port: number;
|
|
102
|
+
readonly shadowDatabasePort: number;
|
|
103
|
+
protected constructor(options: Omit<ServerOptions, "persistenceMode"> & {
|
|
104
|
+
persistenceMode: PersistenceMode;
|
|
105
|
+
});
|
|
106
|
+
static readServerDump(name: string): Promise<ServerDumpV1 | null>;
|
|
107
|
+
static get(options: ServerOptions | undefined): Promise<ServerState>;
|
|
108
|
+
abstract get databaseDumpPath(): string;
|
|
109
|
+
abstract get pgliteDataDirPath(): string;
|
|
110
|
+
abstract [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
|
|
111
|
+
abstract close(): Promise<void>;
|
|
112
|
+
abstract writeServerDump(exports?: Omit<Server, "close">): Promise<void>;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
type DBServerPurpose = "database" | "shadow_database";
|
|
116
|
+
|
|
117
|
+
declare const DEFAULT_DATABASE_PORT = 51214;
|
|
118
|
+
declare const DEFAULT_SERVER_PORT = 51213;
|
|
119
|
+
declare const DEFAULT_SHADOW_DATABASE_PORT = 51215;
|
|
120
|
+
type PortAssignableService = DBServerPurpose | "server";
|
|
121
|
+
declare class PortNotAvailableError extends Error {
|
|
122
|
+
port: number;
|
|
123
|
+
service: PortAssignableService;
|
|
124
|
+
name: string;
|
|
125
|
+
constructor(port: number, service: PortAssignableService);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
interface Server extends Exports {
|
|
129
|
+
close(): Promise<void>;
|
|
130
|
+
}
|
|
131
|
+
declare function unstable_startServer(options?: ServerOptions): Promise<Server>;
|
|
132
|
+
|
|
133
|
+
export { DEFAULT_DATABASE_PORT as D, type Exports as E, type PersistenceMode as P, type ResolvedServerOptions as R, type ServerOptions as S, type Server as a, type ServerDumpV1 as b, ServerState as c, DEFAULT_SERVER_PORT as d, DEFAULT_SHADOW_DATABASE_PORT as e, type PortAssignableService as f, PortNotAvailableError as g, unstable_startServer as u };
|
package/dist/index.d.ts
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
export { D as DEFAULT_DATABASE_PORT,
|
|
1
|
+
export { D as DEFAULT_DATABASE_PORT, d as DEFAULT_SERVER_PORT, e as DEFAULT_SHADOW_DATABASE_PORT, f as PortAssignableService, g as PortNotAvailableError, a as Server, u as unstable_startServer } from './index-CMQuwyab.js';
|
|
2
|
+
import 'valibot';
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{HTTPException as
|
|
3
|
-
`).find(
|
|
4
|
-
Received data: ${
|
|
2
|
+
import{a as B,b as L,c as j,d as N,e as rt,f as ot,g as st,h as v,i as U}from"./chunk-PVN7L773.js";import{HTTPException as P}from"hono/http-exception";import{object as ce,optional as le,parseJson as de,pipe as H,regex as q,safeParse as ue,string as I,url as M}from"valibot";var V=/^(postgres|postgresql):\/\//,me=H(I(),de(),ce({databaseUrl:H(I(),M(),q(V)),shadowDatabaseUrl:le(H(I(),M(),q(V)))}));function K(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function pe(e){let t=Buffer.from(e,"base64url").toString("utf8"),{issues:n,output:r,success:o}=ue(me,t,{abortEarly:!0});return o?[null,r]:[n]}var g=(e,t)=>{let{authorization:n}=e;if(!n)throw new P(401,{message:"Missing API Key"});let[r,o="",s]=n.split(" ");if(r!=="Bearer"||s)throw new P(401,{message:"Invalid API Key"});let[i,a]=pe(o);if(i)throw new P(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:c}=a;if(c!==t.var.db.connectionString)throw new P(401,{message:"Wrong API Key; Check your Prisma schema's `provider.url` value (probably defined in `.env`'s `DATABASE_URL` environment variable) is aligned with `prisma dev`'s output"});return{decodedAPIKey:a}};import{PGlite as ge}from"@electric-sql/pglite";import{PGLiteSocketServer as fe}from"@electric-sql/pglite-socket";import{pgDump as he}from"@electric-sql/pglite-tools/pg_dump";import{filename as ye}from"pathe/utils";var l={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},we=`postgres://${l.username}:${l.password}@localhost`,Se=new URLSearchParams({connection_limit:String(l.connectionLimit),connect_timeout:String(l.connectTimeout),max_idle_connection_lifetime:String(l.maxIdleConnectionLifetime),pool_timeout:String(l.poolTimeout),socket_timeout:String(l.socketTimeout),sslmode:l.sslMode});async function O(e,t){let n=e==="database"?t.databasePort:t.shadowDatabasePort;if(t.dryRun)return Q(e,t,{db:null,port:n,server:null});let{debug:r}=t,o=await ge.create({database:l.database,dataDir:e==="database"?t.pgliteDataDirPath:"memory://",debug:r?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:l.username});r&&o.onNotification((i,a)=>{console.debug(`[${e}][${i}] ${a}`)});let s=new fe({db:o,debug:r,inspect:r,port:n});r&&(s.addEventListener("listening",i=>{let{detail:a}=i;console.debug(`[${e}] server listening on ${JSON.stringify(a)}`)}),s.addEventListener("connection",i=>{let{clientAddress:a,clientPort:c}=i.detail;console.debug(`[${e}] client connected from ${a}:${c}`)}),s.addEventListener("error",i=>{let{detail:a}=i;console.error(`[${e}] server error:`,a)}));try{await s.start()}catch(i){throw i instanceof Error&&"code"in i&&i.code==="EADDRINUSE"?new v(n,e):i}return Q(e,t,{db:o,port:n,server:s})}function Q(e,t,n){let{debug:r}=t,{db:o,port:s,server:i}=n||{};return r&&console.debug(`[${e}] server started on port ${s}`),{...l,close:async()=>{let a=[];try{await i?.stop(),r&&console.debug(`[${e}] server stopped on port ${s}`)}catch(c){console.error(`[${e}] server stop error`,c),a.push(c)}if(e==="database")try{await o?.syncToFs(),r&&console.debug(`[${e}] synced to filesystem`)}catch(c){console.error(`[${e}] sync error`,c),a.push(c)}try{await o?.close(),r&&console.debug(`[${e}] closed`)}catch(c){console.error(`[${e}] close error`,c),a.push(c)}if(a.length>0)throw new AggregateError(a,`Failed to close ${e} properly`)},connectionString:be(s),dump:async()=>{if(!o||e==="shadow_database")return{dumpPath:""};let{databaseDumpPath:a}=t,c=await he({args:["--format=custom","--quote-all-identifiers","--schema-only","--verbose"],fileName:ye(a),pg:o});return await N(c,a),{dumpPath:a}},port:s}}function be(e){return`${we}:${e}/${l.database}?${Se.toString()}`}import{createServer as Xe}from"http";import{promisify as We}from"util";import{serve as Ze}from"@hono/node-server";import et from"@prisma/get-platform";function E(){let e,t,n=new Promise((s,i)=>{e=s,t=i}),r=s=>{r=o=null,t(s)},o=s=>{o=r=null,e(s)};return{promise:n,reject:s=>r?.(s),resolve:s=>o?.(s)}}import{logger as tt}from"hono/logger";import{Hono as se}from"hono/tiny";import{Hono as Fe}from"hono/tiny";import{validator as w}from"hono/validator";import{array as ve,literal as Pe,minLength as Ee,object as Te,pipe as Re,safeParse as Ae,string as xe,union as He}from"valibot";var Ie=Te({tags:He([Re(ve(xe()),Ee(1)),Pe("all")])});async function F(e){let{output:t,success:n}=Ae(Ie,await e.req.json(),{abortEarly:!0});return n?t:e.text("Invalid input",400)}import{spawn as Oe}from"child_process";import{once as $e}from"events";import{mkdir as Ce}from"fs/promises";import{join as De}from"path";import{setTimeout as ke}from"timers/promises";import{proxySignals as _e}from"foreground-child/proxy-signals";import{process as Be}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Le,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:je,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:G}=Be.env,h=class e{static#n=new Map;#e;#t;constructor(t){this.#e=t,this.#t=null}static async get(t){let{debug:n}=t,r=`${t.schemaHash}:${t.clientVersion}`;try{let o=e.#n.get(r);if(o)return o;let s=new e(t);return e.#n.set(r,s),n&&console.debug("[Query Engine] starting...",t),await s.start(),n&&console.debug("[Query Engine] started!"),s}finally{e.stopAll(r)}}static async stopAll(t){let r=(await Promise.allSettled(Array.from(e.#n.entries()).filter(([o])=>o!==t).map(async([o,s])=>{try{await s.stop()}finally{e.#n.delete(o)}}))).filter(o=>o.status==="rejected").map(o=>o.reason);if(r.length>0)throw new AggregateError(r,"Failed to stop engines")}async commitTransaction(t,n){return await this.#o(t,n,"commit")}async request(t,n){let{url:r}=await this.start(),o=this.#r(n),s=await fetch(r,{body:typeof t=="string"?t:JSON.stringify(t),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await f.fromResponse(s);return await s.text()}async rollbackTransaction(t,n){return await this.#o(t,n,"rollback")}async startTransaction(t,n){let{url:r}=await this.start(),o=this.#r(n),s=await fetch(`${r}/transaction/start`,{body:JSON.stringify(t),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await f.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:t,reject:n,resolve:r}=E();this.#t=t;let o=je||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=Oe(o,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});_e(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let i=d=>{let m=d.split(`
|
|
3
|
+
`).find(ae=>ae.includes("Started query engine http server"));if(!m)return;s.stdout.removeListener("data",i);let{fields:p}=JSON.parse(m);if(p==null)return n(new Error(`Unexpected data during initialization, "fields" are missing: ${d}`));let{ip:u,port:_}=p;if(u==null||_==null)return n(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
|
|
4
|
+
Received data: ${d}`));r({childProcess:s,url:`http://${u}:${_}`})},a=d=>{this.#t=null,n(new y(String(d))),s.removeListener("exit",c),s.kill()};s.once("error",a);let c=(d,m)=>{this.#t=null,n(new y(`Query Engine exited with code ${d} and signal ${m}`))};return s.once("exit",c),s.stdout.on("data",i),this.#e.debug&&(s.stderr.on("data",console.error.bind(console,"[Query Engine]")),s.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:t}=await this.#t;t.exitCode==null&&t.signalCode==null&&(this.#t=null,t.kill(),await $e(t,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let t=await this.#i();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",t);let n=B(this.#e.clientVersion,t);this.#e.debug&&console.debug("[Query Engine] cache directory path",n),await Ce(n,{recursive:!0});let{platform:r}=this.#e.platform,o=r==="windows"?".exe":"",s=De(n,`query-engine-${r}${o}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(Le==="1"||await L(s)===!1)&&await this.#a({commitHash:t,extension:o,engineBinaryPath:s}),s}async#i(){let t=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!t.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${t.status}`);let r=(await t.json()).devDependencies?.["@prisma/engines-version"];if(!r)throw new Error("Couldn't find engines version in package.json");let o=r.split(".").at(-1);if(!o)throw new Error("Couldn't find commit hash in engines version");return o}async#a(t){let{commitHash:n,extension:r,engineBinaryPath:o}=t,{binaryTarget:s}=this.#e.platform,i=`https://binaries.prisma.sh/all_commits/${n}/${s}/query-engine${r}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",i);let a=await fetch(i);if(!a.ok)throw new Error(`Couldn't download engine. URL: ${i}, status code: ${a.status}`);G&&await ke(Number(G)),await j(await a.arrayBuffer(),o),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",o)}#r(t){let n={};for(let[r,o]of Object.entries(t))o!=null&&(n[r]=o);return n}async#o(t,n,r){let{url:o}=await this.#t,s=this.#r(n),i=await fetch(`${o}/transaction/${t}/${r}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await f.fromResponse(i);try{return await i.json()}catch{return{}}}};function T(e,t){return console.error(e),e instanceof y?t.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:e.message}}}},500):e instanceof f?t.text(e.responseBody,e.statusCode):t.body(null,500)}var y=class extends Error{name="EngineStartError"},f=class e extends Error{constructor(n,r,o){super(`${n}: Query Engine response status ${r}, body: ${o}`);this.action=n;this.statusCode=r;this.responseBody=o}name="EngineHttpError";static async fromResponse(n){let r=new URL(n.url),o=await n.text();return new e(r.pathname,n.status,o)}};import{Buffer as J}from"buffer";var R=new Map;async function $(e){let n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}function z(e){let t=e.req.param("schemaHash"),n=R.get(t);return n==null?e.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:t,schemas:n}}var Ne=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function Y(e,t){let n=J.from(e,"base64").toString("utf8"),r=`datasource db {
|
|
5
5
|
provider = "postgresql"
|
|
6
|
-
url = "${
|
|
7
|
-
}`,o=
|
|
8
|
-
`,{encoding:"utf-8"})}};async function Ur(t){let e=await b.get(t),[r,n]=await Promise.all([$("database",e),$("shadow_database",e)]),o=await he(r,e),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:q({databaseUrl:r.connectionString,shadowDatabaseUrl:n.connectionString})}).toString()}`,i={database:{connectionString:r.connectionString},http:{url:o.url},ppg:{url:s},shadowDatabase:{connectionString:n.connectionString}};return await e.writeServerDump(i),{...i,close:()=>a(e,[o,r,n])};async function a(c,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{Y as DEFAULT_DATABASE_PORT,X as DEFAULT_SERVER_PORT,Z as DEFAULT_SHADOW_DATABASE_PORT,h as PortNotAvailableError,Ur as unstable_startServer};
|
|
6
|
+
url = "${t.toString()}"
|
|
7
|
+
}`,o=n.replace(Ne,r),s=await $(o);return{base64Override:J.from(o,"utf8").toString("base64"),overrideHash:s}}function A(e){let{req:t}=e;return{traceparent:t.header("traceparent"),"X-capture-telemetry":t.header("X-capture-telemetry")}}import{integer as X,looseObject as Ue,minValue as W,number as C,object as qe,optional as Me,pipe as Z,safeParse as ee,string as te,union as Ve}from"valibot";var Ke=qe({isolation_level:Me(te()),max_wait:Z(C(),X(),W(0)),timeout:Z(C(),X(),W(0))});async function ne(e){let{issues:t,output:n,success:r}=ee(Ke,await e.req.json(),{abortEarly:!0});return r?n:e.json({EngineNotStarted:{reason:"InvalidRequest",issues:t}},400)}var Qe=Ue({id:Ve([te(),C()])});function re(e,t){let{output:n,success:r}=ee(Qe,e);return r?n:t.json({EngineMalfunction:{}},500)}var S=new Fe;S.post("/invalidate",w("header",g),async e=>{let t=await F(e);return t instanceof Response?t:e.body(null)});var Ge="/:clientVersion/:schemaHash",b=S.basePath(Ge);S.route("/",b);var Je=["/graphql","/itx/:transactionId/graphql"];b.on("POST",[...Je],w("header",g),async e=>{let{req:t}=e;try{let n=await D(e);if(n instanceof Response)return n;let r=await t.text(),o=t.param("transactionId"),s=await n.request(r,{...A(e),"X-transaction-id":o});return e.text(s)}catch(n){return T(n,e)}});b.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],w("header",g),async e=>{let{req:t}=e;try{let n=await D(e);if(n instanceof Response)return n;let o=`${t.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=t.param("transactionId"),i=await n[o](s,A(e));return e.json(i)}catch(n){return T(n,e)}});b.put("/schema",w("header",g),async e=>{let{req:t}=e,n=await t.text();if(!n)return e.text("Missing schema",400);let r=t.param("schemaHash"),o=R.get(r);if(o==null){if(r!==await $(n))return e.text("Schema hash mismatch",400);let s=new URL(e.get("db").connectionString);s.searchParams.set("single_use_connections","true");let i=await Y(n,s);return R.set(r,{base64Original:n,...i}),e.text(r)}return n!==o.base64Original?e.text("Schema mismatch",400):e.text(r)});b.post("/transaction/start",w("header",g),async e=>{let{req:t}=e,n=await ne(e);if(n instanceof Response)return n;try{let r=await D(e);if(r instanceof Response)return r;let o=await r.startTransaction(n,A(e)),s=re(o,e);if(s instanceof Response)return s;let{id:i}=s,a=t.param("clientVersion"),c=e.get("port"),d=e.get("protocol"),m=t.param("schemaHash");return e.json({...o,"data-proxy":{endpoint:`${d}://localhost:${c}/${a}/${m}/itx/${i}`}})}catch(r){return T(r,e)}});async function D(e){let{req:t}=e,n=z(e);if(n instanceof Response)return n;let{base64Override:r,overrideHash:o}=n.schemas;return await h.get({base64Schema:r,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||t.param("clientVersion"),debug:e.get("debug"),platform:e.get("platform"),schemaHash:o})}import{Hono as ze}from"hono/tiny";import{StatusCodes as Ye}from"http-status-codes";var x=new ze;x.post("/database/dump",async e=>{let n=await e.get("db").dump();return e.json(n,Ye.CREATED)});x.get("/health",e=>e.json({name:e.get("serverState").name}));async function ie(e,t){let{port:n}=t;if(t.dryRun)return oe(n,null);let r=await nt(n,e,t),{promise:o,reject:s,resolve:i}=E(),a=Ze({createServer:Xe,fetch:r.fetch,port:n},i);return a.on("error",c=>{if(typeof c=="object"&&"code"in c&&c.code==="EADDRINUSE")return s(new v(n,"server"));console.error("[Accelerate]",c)}),await o,oe(n,a)}function oe(e,t){return{async close(){t&&await Promise.allSettled([We(t.close.bind(t))(),h.stopAll()])},port:e,url:`http://localhost:${e}`}}async function nt(e,t,n){let{debug:r}=n,o=new se,s=await et.getPlatformInfo();return r&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),r&&o.use("*",tt((...i)=>console.log("[Accelerate]",...i))),o.use("*",async(i,a)=>(i.set("db",t),i.set("debug",!!r),i.set("platform",s),i.set("port",e),i.set("protocol","http"),i.set("serverState",n),await a())),o.route("/",k),o}var k=new se;k.route("/",S);k.route("/",x);async function dn(e){let t=await U.get(e),[n,r]=await Promise.all([O("database",t),O("shadow_database",t)]),o=await ie(n,t),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:K({databaseUrl:n.connectionString,shadowDatabaseUrl:r.connectionString})}).toString()}`,i={database:{connectionString:n.connectionString},http:{url:o.url},ppg:{url:s},shadowDatabase:{connectionString:r.connectionString}};return await t.writeServerDump(i),{...i,close:()=>a(t,[o,n,r])};async function a(c,d){let p=(await Promise.allSettled(d.map(u=>u.close()))).filter(u=>u.status==="rejected").map(u=>new Error(u.reason));try{await c.close()}catch(u){p.push(u)}if(p.length>0)throw new AggregateError(p,"Failed to close some servers")}}export{rt as DEFAULT_DATABASE_PORT,ot as DEFAULT_SERVER_PORT,st as DEFAULT_SHADOW_DATABASE_PORT,v as PortNotAvailableError,dn as unstable_startServer};
|
package/dist/state.d.ts
ADDED
package/dist/state.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma/dev",
|
|
3
|
-
"version": "0.0.0-dev.
|
|
3
|
+
"version": "0.0.0-dev.202506031938",
|
|
4
4
|
"description": "A local Prisma Postgres server for development and testing",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -19,6 +19,11 @@
|
|
|
19
19
|
"types": "./dist/daemon/client.d.ts",
|
|
20
20
|
"import": "./dist/daemon/client.js",
|
|
21
21
|
"default": "./dist/daemon/client.js"
|
|
22
|
+
},
|
|
23
|
+
"./internal/state": {
|
|
24
|
+
"types": "./dist/state.d.ts",
|
|
25
|
+
"import": "./dist/state.js",
|
|
26
|
+
"default": "./dist/state.js"
|
|
22
27
|
}
|
|
23
28
|
},
|
|
24
29
|
"keywords": [
|
package/dist/index-BtR4iL6u.d.ts
DELETED
|
@@ -1,83 +0,0 @@
|
|
|
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
|
-
close(): Promise<void>;
|
|
68
|
-
database: {
|
|
69
|
-
connectionString: string;
|
|
70
|
-
};
|
|
71
|
-
http: {
|
|
72
|
-
url: 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 };
|