@prisma/dev 0.0.0-dev.202506112317 → 0.0.0-dev.202506121347
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-4M2BYKUR.js → chunk-B3YGM5RH.js} +3 -3
- package/dist/daemon/client.d.cts +3 -1
- package/dist/daemon/client.d.ts +3 -1
- package/dist/db.d.cts +39 -2
- package/dist/db.d.ts +39 -2
- package/dist/index.cjs +6 -6
- package/dist/index.d.cts +24 -2
- package/dist/index.d.ts +24 -2
- package/dist/index.js +4 -4
- package/dist/state.cjs +3 -3
- package/dist/state.d.cts +152 -3
- package/dist/state.d.ts +152 -3
- package/dist/state.js +1 -1
- package/package.json +1 -1
- package/dist/db-B1_DGnTu.d.cts +0 -202
- package/dist/db-B1_DGnTu.d.ts +0 -202
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{b as
|
|
2
|
-
${JSON.stringify(v,null,2)}`),new Error(`Invalid Prisma Dev state for "${s}".`);return new
|
|
3
|
-
`,{encoding:"utf-8"})}};async function Q(r,e){let t={databasePort:-1,exports:void 0,name:r,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let s=await
|
|
1
|
+
import{b as p,f as O,g as E,h as $,i as R,j as _,k}from"./chunk-Q3M6SQC2.js";import{writeFile as j}from"fs/promises";import{hc as B}from"hono/client";import{join as u}from"pathe";import{check as C,lock as H}from"proper-lockfile";import{process as m}from"std-env";import{integer as T,literal as Y,minLength as Z,minValue as V,number as N,object as g,optional as f,parseJson as q,pipe as h,safeParse as z,string as b,url as K}from"valibot";import{process as U}from"std-env";function A(r,e){if(r==null)return!1;try{return U.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}var D=h(b(),K()),M=g({connectionString:D,prismaORMConnectionString:f(D),terminalCommand:f(b())}),I=g({url:D}),S=h(N(),T(),V(1)),W=g({database:M,http:I,ppg:I,shadowDatabase:M}),G=g({databasePort:S,exports:f(W),name:h(b(),Z(1)),pid:f(h(N(),T(),V(0))),port:S,shadowDatabasePort:S,version:Y("1")}),x=Symbol("initialize"),P="default",d=class{databasePort;debug;dryRun;name;persistenceMode;pid;port;shadowDatabasePort;constructor(e){this.databasePort=e.databasePort??51214,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??P,this.persistenceMode=e.persistenceMode,this.pid=e.pid??m.pid,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async createExclusively(e){let t=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new l({...e,pid:m.pid}):new y(e);return await t[x](),t}static async fromServerDump(e){let{debug:t,name:s=P}=e??{},n=p(s),a=l.getServerDumpPath(n),i=await O(a);if(i==null)return t&&console.debug(`[State] No server dump file found at: ${a}`),null;t&&(console.debug(`[State] server dump file found at "${a}":`),console.debug(i));let{issues:v,output:o,success:c}=z(h(b(),q(),G),i);if(!c)throw t&&console.debug(`[State] Invalid server dump file at "${a}":
|
|
2
|
+
${JSON.stringify(v,null,2)}`),new Error(`Invalid Prisma Dev state for "${s}".`);return new l({databasePort:o.databasePort,debug:t,dryRun:!1,name:s,pid:o.pid,port:o.port,serverDump:o,shadowDatabasePort:o.shadowDatabasePort})}static async scan(e){let{debug:t}=e??{},s=u(p(P),"..");t&&console.debug(`[State] scanning for server states in: ${s}`);let n=await $(s);return t&&console.debug(`[State] found server names: ${JSON.stringify(n)}`),await Promise.all(n.map(a=>Q(a,t)))}},y=class extends d{constructor(e){super({...e,persistenceMode:"stateless",pid:m.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[x](){}async close(){}async writeServerDump(){}},l=class r extends d{#t;#e;#a;#o;#r;#s=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=p(this.name),this.#t=u(this.#e,"db_dump.bak"),this.#a=u(this.#e,".pglite"),this.#r=e.serverDump??null,this.#o=r.getServerDumpPath(this.#e)}static getServerDumpPath(e){return u(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get pgliteDataDirPath(){return this.#a}async[x](){await E(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#s=await H(this.#e,{lockfilePath:u(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 w(this):e}}async close(){if(this.#s!=null)try{await this.#s(),this.#s=null,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw console.error(`[State] failed to release lock on: ${this.#e}`),e}}async writeServerDump(e){this.#r={name:this.name,version:"1",pid:m.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await j(this.#o,`${JSON.stringify(this.#r,null,2)}
|
|
3
|
+
`,{encoding:"utf-8"})}};async function Q(r,e){let t={databasePort:-1,exports:void 0,name:r,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let s=await d.fromServerDump({debug:e,name:r});if(!s)return e&&console.debug(`[State] no server state found for name: ${r}`),{...t,status:"no_such_server"};t.databasePort=s.databasePort,t.exports=s.exports,t.pid=s.pid,t.port=s.port,t.shadowDatabasePort=s.shadowDatabasePort;let{exports:n,pid:a}=s;if(!A(a,e))return e&&console.debug(`[State] server state for "${r}" has no running process with PID: ${a}`),{...t,status:"not_running"};let i=p(r);try{if(!await C(i,{lockfilePath:u(i,".lock")}))return e&&console.debug(`[State] server state for "${r}" is not locked, indicating it is not running.`),{...t,status:"starting_up"}}catch(L){e&&console.error(`[State] server state for "${r}" failed to check lock:`,L)}if(!n)return{...t,status:"starting_up"};let{http:v}=n,o=await B(v.url).health.$get();if(!o.ok)return e&&console.debug(`[State] server state for "${r}" is not live: ${JSON.stringify(o)}`),{...t,status:"not_running"};let c=await o.json();return c.name!==r?(e&&console.debug(`[State] server state for "${r}" has mismatched health response: ${JSON.stringify(c)}`),{...t,status:"unknown"}):(e&&console.debug(`[State] server state for "${r}" is live: ${JSON.stringify(c)}`),{...t,status:"running"})}catch(s){return e&&console.error(`[State] failed to get server status for "${r}":`,s),{...t,status:"error"}}}var w=class extends Error{#t;name="ServerAlreadyRunningError";constructor(e){super(`A Prisma Dev with the name "${e.name}" is already running.`),this.#t=e}get server(){return d.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};export{d as a,w as b};
|
package/dist/daemon/client.d.cts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import * as url from 'url';
|
|
2
2
|
import { SockDaemonClient } from 'sock-daemon/client';
|
|
3
|
-
import {
|
|
3
|
+
import { Server } from '../index.cjs';
|
|
4
|
+
import { ServerOptions } from '../state.cjs';
|
|
4
5
|
import { MessageBase } from 'sock-daemon/server';
|
|
6
|
+
import '../db.cjs';
|
|
5
7
|
import '@electric-sql/pglite';
|
|
6
8
|
import 'valibot';
|
|
7
9
|
|
package/dist/daemon/client.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import * as url from 'url';
|
|
2
2
|
import { SockDaemonClient } from 'sock-daemon/client';
|
|
3
|
-
import {
|
|
3
|
+
import { Server } from '../index.js';
|
|
4
|
+
import { ServerOptions } from '../state.js';
|
|
4
5
|
import { MessageBase } from 'sock-daemon/server';
|
|
6
|
+
import '../db.js';
|
|
5
7
|
import '@electric-sql/pglite';
|
|
6
8
|
import 'valibot';
|
|
7
9
|
|
package/dist/db.d.cts
CHANGED
|
@@ -1,3 +1,40 @@
|
|
|
1
|
-
import '@electric-sql/pglite';
|
|
2
|
-
|
|
1
|
+
import { PGlite } from '@electric-sql/pglite';
|
|
2
|
+
import { ServerState } from './state.cjs';
|
|
3
3
|
import 'valibot';
|
|
4
|
+
|
|
5
|
+
interface DBServer {
|
|
6
|
+
close(): Promise<void>;
|
|
7
|
+
readonly connectionLimit: number;
|
|
8
|
+
readonly connectionString: string;
|
|
9
|
+
readonly connectTimeout: number;
|
|
10
|
+
readonly database: string;
|
|
11
|
+
dump(destinationPath: string): Promise<void>;
|
|
12
|
+
readonly maxIdleConnectionLifetime: number;
|
|
13
|
+
readonly password: string;
|
|
14
|
+
readonly poolTimeout: number;
|
|
15
|
+
readonly port: number;
|
|
16
|
+
readonly prismaORMConnectionString: string;
|
|
17
|
+
readonly socketTimeout: number;
|
|
18
|
+
readonly sslMode: string;
|
|
19
|
+
readonly terminalCommand: string;
|
|
20
|
+
readonly username: string;
|
|
21
|
+
}
|
|
22
|
+
interface DBDump {
|
|
23
|
+
dumpPath: string;
|
|
24
|
+
}
|
|
25
|
+
type DBServerPurpose = "database" | "shadow_database";
|
|
26
|
+
declare function startDBServer(purpose: DBServerPurpose, serverState: ServerState): Promise<DBServer>;
|
|
27
|
+
type DumpDBOptions<D extends string> = {
|
|
28
|
+
dataDir: string;
|
|
29
|
+
db?: never;
|
|
30
|
+
debug?: boolean;
|
|
31
|
+
destinationPath?: D;
|
|
32
|
+
} | {
|
|
33
|
+
dataDir?: never;
|
|
34
|
+
db: PGlite;
|
|
35
|
+
debug?: boolean;
|
|
36
|
+
destinationPath?: D;
|
|
37
|
+
};
|
|
38
|
+
declare function dumpDB<D extends string = never>(options: DumpDBOptions<D>): Promise<[D] extends [never] ? string : void>;
|
|
39
|
+
|
|
40
|
+
export { type DBDump, type DBServer, type DBServerPurpose, type DumpDBOptions, dumpDB, startDBServer };
|
package/dist/db.d.ts
CHANGED
|
@@ -1,3 +1,40 @@
|
|
|
1
|
-
import '@electric-sql/pglite';
|
|
2
|
-
|
|
1
|
+
import { PGlite } from '@electric-sql/pglite';
|
|
2
|
+
import { ServerState } from './state.js';
|
|
3
3
|
import 'valibot';
|
|
4
|
+
|
|
5
|
+
interface DBServer {
|
|
6
|
+
close(): Promise<void>;
|
|
7
|
+
readonly connectionLimit: number;
|
|
8
|
+
readonly connectionString: string;
|
|
9
|
+
readonly connectTimeout: number;
|
|
10
|
+
readonly database: string;
|
|
11
|
+
dump(destinationPath: string): Promise<void>;
|
|
12
|
+
readonly maxIdleConnectionLifetime: number;
|
|
13
|
+
readonly password: string;
|
|
14
|
+
readonly poolTimeout: number;
|
|
15
|
+
readonly port: number;
|
|
16
|
+
readonly prismaORMConnectionString: string;
|
|
17
|
+
readonly socketTimeout: number;
|
|
18
|
+
readonly sslMode: string;
|
|
19
|
+
readonly terminalCommand: string;
|
|
20
|
+
readonly username: string;
|
|
21
|
+
}
|
|
22
|
+
interface DBDump {
|
|
23
|
+
dumpPath: string;
|
|
24
|
+
}
|
|
25
|
+
type DBServerPurpose = "database" | "shadow_database";
|
|
26
|
+
declare function startDBServer(purpose: DBServerPurpose, serverState: ServerState): Promise<DBServer>;
|
|
27
|
+
type DumpDBOptions<D extends string> = {
|
|
28
|
+
dataDir: string;
|
|
29
|
+
db?: never;
|
|
30
|
+
debug?: boolean;
|
|
31
|
+
destinationPath?: D;
|
|
32
|
+
} | {
|
|
33
|
+
dataDir?: never;
|
|
34
|
+
db: PGlite;
|
|
35
|
+
debug?: boolean;
|
|
36
|
+
destinationPath?: D;
|
|
37
|
+
};
|
|
38
|
+
declare function dumpDB<D extends string = never>(options: DumpDBOptions<D>): Promise<[D] extends [never] ? string : void>;
|
|
39
|
+
|
|
40
|
+
export { type DBDump, type DBServer, type DBServerPurpose, type DumpDBOptions, dumpDB, startDBServer };
|
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";var lt=Object.create;var M=Object.defineProperty;var pt=Object.getOwnPropertyDescriptor;var mt=Object.getOwnPropertyNames;var gt=Object.getPrototypeOf,ft=Object.prototype.hasOwnProperty;var ht=(t,e)=>{for(var r in e)M(t,r,{get:e[r],enumerable:!0})},pe=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of mt(e))!ft.call(t,o)&&o!==r&&M(t,o,{get:()=>e[o],enumerable:!(n=pt(e,o))||n.enumerable});return t};var _=(t,e,r)=>(r=t!=null?lt(gt(t)):{},pe(e||!t||!t.__esModule?M(r,"default",{value:t,enumerable:!0}):r,t)),yt=t=>pe(M({},"__esModule",{value:!0}),t);var Nt={};ht(Nt,{DEFAULT_DATABASE_PORT:()=>Ee,DEFAULT_SERVER_PORT:()=>Re,DEFAULT_SHADOW_DATABASE_PORT:()=>Ae,PortNotAvailableError:()=>D,unstable_startServer:()=>Mt});module.exports=yt(Nt);var P=require("hono/http-exception"),l=require("valibot"),me=/^(postgres|postgresql):\/\//,St=(0,l.pipe)((0,l.string)(),(0,l.parseJson)(),(0,l.object)({databaseUrl:(0,l.pipe)((0,l.string)(),(0,l.url)(),(0,l.regex)(me)),name:(0,l.optional)((0,l.pipe)((0,l.string)(),(0,l.minLength)(1))),shadowDatabaseUrl:(0,l.pipe)((0,l.string)(),(0,l.url)(),(0,l.regex)(me))}));function ge(t){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([[e],[r]])=>e.localeCompare(r)))),"utf8").toString("base64url")}function bt(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:n,success:o}=(0,l.safeParse)(St,e,{abortEarly:!0});return o?[null,n]:[r]}var A=(t,e)=>{let{authorization:r}=t;if(!r)throw new P.HTTPException(401,{message:"Missing API Key"});let[n,o="",s]=r.split(" ");if(n!=="Bearer"||s)throw new P.HTTPException(401,{message:"Invalid API Key"});let[i,a]=bt(o);if(i)throw new P.HTTPException(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:c,name:m,shadowDatabaseUrl:b}=a,{name:w}=e.get("serverState");if(!m)throw new P.HTTPException(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} requires an API Key from a newer version of \`prisma dev\`. Check the "${w}" server's output for the updated \`DATABASE_URL\` value.`});if(m!==w)throw new P.HTTPException(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${w}", but the API Key is for "${m}"`});let{hostname:S,port:L}=new URL(c),{port:Q}=e.get("db"),{hostname:ct,port:dt}=new URL(b),ut=e.get("shadowDBPort");if(S!=="localhost"||Number(L)!==Q||ct!=="localhost"||Number(dt)!==ut)throw new P.HTTPException(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}};var Z=require("@electric-sql/pglite"),xe=require("@electric-sql/pglite-socket"),$e=require("pathe/utils");var F=require("fs"),y=require("fs/promises");var p=_(require("path"),1),W=_(require("os"),1),N=_(require("process"),1),v=W.default.homedir(),z=W.default.tmpdir(),{env:O}=N.default,wt=t=>{let e=p.default.join(v,"Library");return{data:p.default.join(e,"Application Support",t),config:p.default.join(e,"Preferences",t),cache:p.default.join(e,"Caches",t),log:p.default.join(e,"Logs",t),temp:p.default.join(z,t)}},vt=t=>{let e=O.APPDATA||p.default.join(v,"AppData","Roaming"),r=O.LOCALAPPDATA||p.default.join(v,"AppData","Local");return{data:p.default.join(r,t,"Data"),config:p.default.join(e,t,"Config"),cache:p.default.join(r,t,"Cache"),log:p.default.join(r,t,"Log"),temp:p.default.join(z,t)}},Pt=t=>{let e=p.default.basename(v);return{data:p.default.join(O.XDG_DATA_HOME||p.default.join(v,".local","share"),t),config:p.default.join(O.XDG_CONFIG_HOME||p.default.join(v,".config"),t),cache:p.default.join(O.XDG_CACHE_HOME||p.default.join(v,".cache"),t),log:p.default.join(O.XDG_STATE_HOME||p.default.join(v,".local","state"),t),temp:p.default.join(z,e,t)}};function X(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),N.default.platform==="darwin"?wt(t):N.default.platform==="win32"?vt(t):Pt(t)}var fe=require("pako"),he=X("prisma-dev");function ye(t,e){return`${he.cache}/engine/${t}/${e}`}function I(t){return`${he.data}/${t}`}async function Se(t){try{return await(0,y.access)(t,y.constants.F_OK),!0}catch(e){if(Y(e))return!1;throw e}}async function be(t,e){let r=(0,fe.inflate)(t);await(0,y.writeFile)(e,r),await(0,y.chmod)(e,"755")}async function we(t,e){await t.stream().pipeTo(F.WriteStream.toWeb((0,F.createWriteStream)(e,{encoding:"utf-8"})))}function Y(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function ve(t){try{return await(0,y.readFile)(t,{encoding:"utf-8"})}catch(e){if(Y(e))return null;throw e}}async function Pe(t){await(0,y.mkdir)(t,{recursive:!0})}async function De(t){try{return(await(0,y.readdir)(t,{withFileTypes:!0})).reduce((r,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&r.push(n.name),r),[])}catch(e){if(Y(e))return[];throw e}}var Ee=51214,Re=51213,Ae=51215,D=class extends Error{constructor(r,n){super(`Port number \`${r}\` is not available for service ${n}.`);this.port=r;this.service=n}name="PortNotAvailableError"};var g={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},Dt=`postgres://${g.username}:${g.password}@localhost`,_e=new URLSearchParams({sslmode:g.sslMode}),Et=new URLSearchParams({...Object.fromEntries(_e.entries()),connection_limit:String(g.connectionLimit),connect_timeout:String(g.connectTimeout),max_idle_connection_lifetime:String(g.maxIdleConnectionLifetime),pool_timeout:String(g.poolTimeout),single_use_connections:"true",socket_timeout:String(g.socketTimeout)});async function ee(t,e){let r=t==="database"?e.databasePort:e.shadowDatabasePort;if(e.dryRun)return Oe(t,e,{db:null,port:r,server:null});let{debug:n}=e,s=await(t==="shadow_database"?Rt:Ie)(e.pgliteDataDirPath,n);n&&s.onNotification((a,c)=>{console.debug(`[${t}][${a}] ${c}`)});let i=new xe.PGLiteSocketServer({db:s,debug:n,inspect:n,port:r});n&&(i.addEventListener("listening",a=>{let{detail:c}=a;console.debug(`[${t}] server listening on ${JSON.stringify(c)}`)}),i.addEventListener("connection",a=>{let{clientAddress:c,clientPort:m}=a.detail;console.debug(`[${t}] client connected from ${c}:${m}`)}),i.addEventListener("error",a=>{let{detail:c}=a;console.error(`[${t}] server error:`,c)}));try{await i.start()}catch(a){throw a instanceof Error&&"code"in a&&a.code==="EADDRINUSE"?new D(r,t):a}return Oe(t,e,{db:s,port:r,server:i})}function Oe(t,e,r){let{debug:n}=e,{db:o,port:s,server:i}=r||{};return n&&console.debug(`[${t}] server started on port ${s}`),{...g,close:async()=>{let a=[];try{await i?.stop(),n&&console.debug(`[${t}] server stopped on port ${s}`)}catch(c){console.error(`[${t}] server stop error`,c),a.push(c)}if(t==="database")try{await o?.syncToFs(),n&&console.debug(`[${t}] synced to filesystem`)}catch(c){console.error(`[${t}] sync error`,c),a.push(c)}try{await o?.close(),n&&console.debug(`[${t}] closed`)}catch(c){console.error(`[${t}] close error`,c),a.push(c)}if(a.length>0)throw new AggregateError(a,`Failed to close ${t} properly`)},connectionString:Te(s,_e),dump:async a=>{t==="shadow_database"||!o||await At({db:o,debug:n,destinationPath:a})},port:s,prismaORMConnectionString:Te(s,Et),terminalCommand:`PGPASSWORD=${g.password} PGSSLMODE=${g.sslMode} psql -h localhost -p ${s} -U ${g.username} -d ${g.database}`}}function Te(t,e){return`${Dt}:${t}/${g.database}?${e.toString()}`}async function Ie(t,e){return await Z.PGlite.create({database:g.database,dataDir:t,debug:e?5:void 0,relaxedDurability:!1,username:g.username})}async function Rt(t,e){return await Z.PGlite.create({database:g.database,dataDir:"memory://",debug:e?5:void 0,relaxedDurability:!1,username:g.username})}async function At(t){let{dataDir:e,db:r,debug:n,destinationPath:o}=t,s=r||await Ie(e,n),{pgDump:i}=await import("@electric-sql/pglite-tools/pg_dump"),a=await i({args:["--schema-only","--no-owner"],fileName:o?(0,$e.filename)(o):void 0,pg:await s.clone()});return o?(n&&console.debug(`[DB] Dumping database to ${o}`),await we(a,o)):(n&&console.debug("[DB] Dumping database to memory"),await a.text())}var ze=require("http"),Xe=require("util"),Ye=require("@hono/node-server"),Ze=_(require("@prisma/get-platform"),1);function U(t){let e,r,n=new Promise((i,a)=>{e=i,r=a}),o=i=>{o=s=null,r(i),t?.onRejected?.(i),t?.onFulfilled?.()},s=i=>{s=o=null,e(i),t?.onResolved?.(i),t?.onFulfilled?.()};return{isFulfilled:()=>s===o,promise:n,reject:i=>o?.(i),resolve:i=>s?.(i)}}var et=require("hono/logger"),oe=require("hono/tiny");var Ke=require("hono/tiny"),$=require("hono/validator");var h=require("valibot"),Ot=(0,h.object)({tags:(0,h.union)([(0,h.pipe)((0,h.array)((0,h.string)()),(0,h.minLength)(1)),(0,h.literal)("all")])});async function Ce(t){let{output:e,success:r}=(0,h.safeParse)(Ot,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var He=require("child_process"),Be=require("events"),je=require("fs/promises"),Le=require("path"),Me=require("timers/promises");var Ne=require("foreground-child/proxy-signals"),Fe=require("std-env");var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Tt,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:xt,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:ke}=Fe.process.env,x=class t{static#r=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let{debug:r}=e,n=`${e.schemaHash}:${e.clientVersion}`;try{let o=t.#r.get(n);if(o)return o;let s=new t(e);return t.#r.set(n,s),r&&console.debug("[Query Engine] starting...",e),await s.start(),r&&console.debug("[Query Engine] started!"),s}finally{t.stopAll(n)}}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.#a(e,r,"commit")}async request(e,r){let{url:n}=await this.start(),o=this.#i(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 T.fromResponse(s);return await s.text()}async rollbackTransaction(e,r){return await this.#a(e,r,"rollback")}async startTransaction(e,r){let{url:n}=await this.start(),o=this.#i(r),s=await fetch(`${n}/transaction/start`,{body:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await T.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:r,resolve:n}=U();this.#t=e;let o=xt||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=(0,He.spawn)(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});(0,Ne.proxySignals)(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let i=m=>{let b=m.split(`
|
|
2
|
-
`).find(
|
|
3
|
-
Received data: ${m}`));n({childProcess:s,url:`http://${S}:${
|
|
1
|
+
"use strict";var lt=Object.create;var N=Object.defineProperty;var pt=Object.getOwnPropertyDescriptor;var mt=Object.getOwnPropertyNames;var gt=Object.getPrototypeOf,ht=Object.prototype.hasOwnProperty;var ft=(t,e)=>{for(var r in e)N(t,r,{get:e[r],enumerable:!0})},pe=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of mt(e))!ht.call(t,o)&&o!==r&&N(t,o,{get:()=>e[o],enumerable:!(n=pt(e,o))||n.enumerable});return t};var _=(t,e,r)=>(r=t!=null?lt(gt(t)):{},pe(e||!t||!t.__esModule?N(r,"default",{value:t,enumerable:!0}):r,t)),yt=t=>pe(N({},"__esModule",{value:!0}),t);var Nt={};ft(Nt,{DEFAULT_DATABASE_PORT:()=>Ee,DEFAULT_SERVER_PORT:()=>Re,DEFAULT_SHADOW_DATABASE_PORT:()=>Ae,PortNotAvailableError:()=>E,ServerAlreadyRunningError:()=>L,unstable_startServer:()=>Mt});module.exports=yt(Nt);var D=require("hono/http-exception"),l=require("valibot"),me=/^(postgres|postgresql):\/\//,St=(0,l.pipe)((0,l.string)(),(0,l.parseJson)(),(0,l.object)({databaseUrl:(0,l.pipe)((0,l.string)(),(0,l.url)(),(0,l.regex)(me)),name:(0,l.optional)((0,l.pipe)((0,l.string)(),(0,l.minLength)(1))),shadowDatabaseUrl:(0,l.pipe)((0,l.string)(),(0,l.url)(),(0,l.regex)(me))}));function ge(t){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([[e],[r]])=>e.localeCompare(r)))),"utf8").toString("base64url")}function bt(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:n,success:o}=(0,l.safeParse)(St,e,{abortEarly:!0});return o?[null,n]:[r]}var A=(t,e)=>{let{authorization:r}=t;if(!r)throw new D.HTTPException(401,{message:"Missing API Key"});let[n,o="",s]=r.split(" ");if(n!=="Bearer"||s)throw new D.HTTPException(401,{message:"Invalid API Key"});let[i,a]=bt(o);if(i)throw new D.HTTPException(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:c,name:m,shadowDatabaseUrl:b}=a,{name:v}=e.get("serverState");if(!m)throw new D.HTTPException(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} requires an API Key from a newer version of \`prisma dev\`. Check the "${v}" server's output for the updated \`DATABASE_URL\` value.`});if(m!==v)throw new D.HTTPException(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${v}", but the API Key is for "${m}"`});let{hostname:S,port:M}=new URL(c),{port:W}=e.get("db"),{hostname:ct,port:dt}=new URL(b),ut=e.get("shadowDBPort");if(S!=="localhost"||Number(M)!==W||ct!=="localhost"||Number(dt)!==ut)throw new D.HTTPException(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}};var ee=require("@electric-sql/pglite"),xe=require("@electric-sql/pglite-socket"),$e=require("pathe/utils");var U=require("fs"),y=require("fs/promises");var p=_(require("path"),1),z=_(require("os"),1),F=_(require("process"),1),w=z.default.homedir(),X=z.default.tmpdir(),{env:O}=F.default,vt=t=>{let e=p.default.join(w,"Library");return{data:p.default.join(e,"Application Support",t),config:p.default.join(e,"Preferences",t),cache:p.default.join(e,"Caches",t),log:p.default.join(e,"Logs",t),temp:p.default.join(X,t)}},wt=t=>{let e=O.APPDATA||p.default.join(w,"AppData","Roaming"),r=O.LOCALAPPDATA||p.default.join(w,"AppData","Local");return{data:p.default.join(r,t,"Data"),config:p.default.join(e,t,"Config"),cache:p.default.join(r,t,"Cache"),log:p.default.join(r,t,"Log"),temp:p.default.join(X,t)}},Pt=t=>{let e=p.default.basename(w);return{data:p.default.join(O.XDG_DATA_HOME||p.default.join(w,".local","share"),t),config:p.default.join(O.XDG_CONFIG_HOME||p.default.join(w,".config"),t),cache:p.default.join(O.XDG_CACHE_HOME||p.default.join(w,".cache"),t),log:p.default.join(O.XDG_STATE_HOME||p.default.join(w,".local","state"),t),temp:p.default.join(X,e,t)}};function Y(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),F.default.platform==="darwin"?vt(t):F.default.platform==="win32"?wt(t):Pt(t)}var he=require("pako"),fe=Y("prisma-dev");function ye(t,e){return`${fe.cache}/engine/${t}/${e}`}function I(t){return`${fe.data}/${t}`}async function Se(t){try{return await(0,y.access)(t,y.constants.F_OK),!0}catch(e){if(Z(e))return!1;throw e}}async function be(t,e){let r=(0,he.inflate)(t);await(0,y.writeFile)(e,r),await(0,y.chmod)(e,"755")}async function ve(t,e){await t.stream().pipeTo(U.WriteStream.toWeb((0,U.createWriteStream)(e,{encoding:"utf-8"})))}function Z(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function we(t){try{return await(0,y.readFile)(t,{encoding:"utf-8"})}catch(e){if(Z(e))return null;throw e}}async function Pe(t){await(0,y.mkdir)(t,{recursive:!0})}async function De(t){try{return(await(0,y.readdir)(t,{withFileTypes:!0})).reduce((r,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&r.push(n.name),r),[])}catch(e){if(Z(e))return[];throw e}}var Ee=51214,Re=51213,Ae=51215,E=class extends Error{constructor(r,n){super(`Port number \`${r}\` is not available for service ${n}.`);this.port=r;this.service=n}name="PortNotAvailableError"};var g={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},Dt=`postgres://${g.username}:${g.password}@localhost`,_e=new URLSearchParams({sslmode:g.sslMode}),Et=new URLSearchParams({...Object.fromEntries(_e.entries()),connection_limit:String(g.connectionLimit),connect_timeout:String(g.connectTimeout),max_idle_connection_lifetime:String(g.maxIdleConnectionLifetime),pool_timeout:String(g.poolTimeout),single_use_connections:"true",socket_timeout:String(g.socketTimeout)});async function te(t,e){let r=t==="database"?e.databasePort:e.shadowDatabasePort;if(e.dryRun)return Oe(t,e,{db:null,port:r,server:null});let{debug:n}=e,s=await(t==="shadow_database"?Rt:Ie)(e.pgliteDataDirPath,n);n&&s.onNotification((a,c)=>{console.debug(`[${t}][${a}] ${c}`)});let i=new xe.PGLiteSocketServer({db:s,debug:n,inspect:n,port:r});n&&(i.addEventListener("listening",a=>{let{detail:c}=a;console.debug(`[${t}] server listening on ${JSON.stringify(c)}`)}),i.addEventListener("connection",a=>{let{clientAddress:c,clientPort:m}=a.detail;console.debug(`[${t}] client connected from ${c}:${m}`)}),i.addEventListener("error",a=>{let{detail:c}=a;console.error(`[${t}] server error:`,c)}));try{await i.start()}catch(a){throw a instanceof Error&&"code"in a&&a.code==="EADDRINUSE"?new E(r,t):a}return Oe(t,e,{db:s,port:r,server:i})}function Oe(t,e,r){let{debug:n}=e,{db:o,port:s,server:i}=r||{};return n&&console.debug(`[${t}] server started on port ${s}`),{...g,close:async()=>{let a=[];try{await i?.stop(),n&&console.debug(`[${t}] server stopped on port ${s}`)}catch(c){console.error(`[${t}] server stop error`,c),a.push(c)}if(t==="database")try{await o?.syncToFs(),n&&console.debug(`[${t}] synced to filesystem`)}catch(c){console.error(`[${t}] sync error`,c),a.push(c)}try{await o?.close(),n&&console.debug(`[${t}] closed`)}catch(c){console.error(`[${t}] close error`,c),a.push(c)}if(a.length>0)throw new AggregateError(a,`Failed to close ${t} properly`)},connectionString:Te(s,_e),dump:async a=>{t==="shadow_database"||!o||await At({db:o,debug:n,destinationPath:a})},port:s,prismaORMConnectionString:Te(s,Et),terminalCommand:`PGPASSWORD=${g.password} PGSSLMODE=${g.sslMode} psql -h localhost -p ${s} -U ${g.username} -d ${g.database}`}}function Te(t,e){return`${Dt}:${t}/${g.database}?${e.toString()}`}async function Ie(t,e){return await ee.PGlite.create({database:g.database,dataDir:t,debug:e?5:void 0,relaxedDurability:!1,username:g.username})}async function Rt(t,e){return await ee.PGlite.create({database:g.database,dataDir:"memory://",debug:e?5:void 0,relaxedDurability:!1,username:g.username})}async function At(t){let{dataDir:e,db:r,debug:n,destinationPath:o}=t,s=r||await Ie(e,n),{pgDump:i}=await import("@electric-sql/pglite-tools/pg_dump"),a=await i({args:["--schema-only","--no-owner"],fileName:o?(0,$e.filename)(o):void 0,pg:await s.clone()});return o?(n&&console.debug(`[DB] Dumping database to ${o}`),await ve(a,o)):(n&&console.debug("[DB] Dumping database to memory"),await a.text())}var ze=require("http"),Xe=require("util"),Ye=require("@hono/node-server"),Ze=_(require("@prisma/get-platform"),1);function V(t){let e,r,n=new Promise((i,a)=>{e=i,r=a}),o=i=>{o=s=null,r(i),t?.onRejected?.(i),t?.onFulfilled?.()},s=i=>{s=o=null,e(i),t?.onResolved?.(i),t?.onFulfilled?.()};return{isFulfilled:()=>s===o,promise:n,reject:i=>o?.(i),resolve:i=>s?.(i)}}var et=require("hono/logger"),se=require("hono/tiny");var Ke=require("hono/tiny"),$=require("hono/validator");var f=require("valibot"),Ot=(0,f.object)({tags:(0,f.union)([(0,f.pipe)((0,f.array)((0,f.string)()),(0,f.minLength)(1)),(0,f.literal)("all")])});async function Ce(t){let{output:e,success:r}=(0,f.safeParse)(Ot,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var He=require("child_process"),Be=require("events"),je=require("fs/promises"),Le=require("path"),Me=require("timers/promises");var Ne=require("foreground-child/proxy-signals"),Fe=require("std-env");var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Tt,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:xt,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:ke}=Fe.process.env,x=class t{static#r=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let{debug:r}=e,n=`${e.schemaHash}:${e.clientVersion}`;try{let o=t.#r.get(n);if(o)return o;let s=new t(e);return t.#r.set(n,s),r&&console.debug("[Query Engine] starting...",e),await s.start(),r&&console.debug("[Query Engine] started!"),s}finally{t.stopAll(n)}}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.#a(e,r,"commit")}async request(e,r){let{url:n}=await this.start(),o=this.#i(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 T.fromResponse(s);return await s.text()}async rollbackTransaction(e,r){return await this.#a(e,r,"rollback")}async startTransaction(e,r){let{url:n}=await this.start(),o=this.#i(r),s=await fetch(`${n}/transaction/start`,{body:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await T.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:r,resolve:n}=V();this.#t=e;let o=xt||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=(0,He.spawn)(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});(0,Ne.proxySignals)(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let i=m=>{let b=m.split(`
|
|
2
|
+
`).find(W=>W.includes("Started query engine http server"));if(!b)return;s.stdout.removeListener("data",i);let{fields:v}=JSON.parse(b);if(v==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${m}`));let{ip:S,port:M}=v;if(S==null||M==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.
|
|
3
|
+
Received data: ${m}`));n({childProcess:s,url:`http://${S}:${M}`})},a=m=>{this.#t=null,r(new C(String(m))),s.removeListener("exit",c),s.kill()};s.once("error",a);let c=(m,b)=>{this.#t=null,r(new C(`Query Engine exited with code ${m} and signal ${b}`))};return s.once("exit",c),s.stdout.on("data",i),this.#e.debug&&(s.stderr.on("data",console.error.bind(console,"[Query Engine]")),s.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:e}=await this.#t;e.exitCode==null&&e.signalCode==null&&(this.#t=null,e.kill(),await(0,Be.once)(e,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#n();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let r=ye(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,je.mkdir)(r,{recursive:!0});let{platform:n}=this.#e.platform,o=n==="windows"?".exe":"",s=(0,Le.join)(r,`query-engine-${n}${o}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(Tt==="1"||await Se(s)===!1)&&await this.#o({commitHash:e,extension:o,engineBinaryPath:s}),s}async#n(){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("[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}`);ke&&await(0,Me.setTimeout)(Number(ke)),await be(await a.arrayBuffer(),o),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",o)}#i(e){let r={};for(let[n,o]of Object.entries(e))o!=null&&(r[n]=o);return r}async#a(e,r,n){let{url:o}=await this.#t,s=this.#i(r),i=await fetch(`${o}/transaction/${e}/${n}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await T.fromResponse(i);try{return await i.json()}catch{return{}}}};function G(t,e){return console.error(t),t instanceof C?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof T?e.text(t.responseBody,t.statusCode):e.body(null,500)}var C=class extends Error{name="EngineStartError"},T=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 re=require("buffer"),q=new Map;async function ne(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 Ue(t){let e=t.req.param("schemaHash"),r=q.get(e);return r==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:r}}var $t=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function Ve(t,e){let r=re.Buffer.from(t,"base64").toString("utf8"),n=`datasource db {
|
|
4
4
|
provider = "postgresql"
|
|
5
5
|
url = "${e.toString()}"
|
|
6
|
-
}`,o=r.replace($t,n),s=await
|
|
7
|
-
${JSON.stringify(a,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new B({databasePort:c.databasePort,debug:r,dryRun:!1,name:n,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(e){let{debug:r}=e??{},n=(0,
|
|
8
|
-
`,{encoding:"utf-8"})}};async function Lt(t,e){let r={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let n=await
|
|
6
|
+
}`,o=r.replace($t,n),s=await ne(o);return{base64Override:re.Buffer.from(o,"utf8").toString("base64"),overrideHash:s}}function K(t){let{req:e}=t;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}var u=require("valibot"),_t=(0,u.object)({isolation_level:(0,u.optional)((0,u.string)()),max_wait:(0,u.pipe)((0,u.number)(),(0,u.integer)(),(0,u.minValue)(0)),timeout:(0,u.pipe)((0,u.number)(),(0,u.integer)(),(0,u.minValue)(0))});async function Ge(t){let{issues:e,output:r,success:n}=(0,u.safeParse)(_t,await t.req.json(),{abortEarly:!0});return n?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}var It=(0,u.looseObject)({id:(0,u.union)([(0,u.string)(),(0,u.number)()])});function qe(t,e){let{output:r,success:n}=(0,u.safeParse)(It,t);return n?r:e.json({EngineMalfunction:{}},500)}var k=new Ke.Hono;k.post("/invalidate",(0,$.validator)("header",A),async t=>{let e=await Ce(t);return e instanceof Response?e:t.body(null)});var Ct="/:clientVersion/:schemaHash",H=k.basePath(Ct);k.route("/",H);var kt=["/graphql","/itx/:transactionId/graphql"];H.on("POST",[...kt],(0,$.validator)("header",A),async t=>{let{req:e}=t;try{let r=await oe(t);if(r instanceof Response)return r;let n=await e.text(),o=e.param("transactionId"),s=await r.request(n,{...K(t),"X-transaction-id":o});return t.text(s)}catch(r){return G(r,t)}});H.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,$.validator)("header",A),async t=>{let{req:e}=t;try{let r=await oe(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,K(t));return t.json(i)}catch(r){return G(r,t)}});H.put("/schema",(0,$.validator)("header",A),async t=>{let{req:e}=t,r=await e.text();if(!r)return t.text("Missing schema",400);let n=e.param("schemaHash"),o=q.get(n);if(o==null){if(n!==await ne(r))return t.text("Schema hash mismatch",400);let s=await Ve(r,t.get("db").prismaORMConnectionString);return q.set(n,{base64Original:r,...s}),t.text(n)}return r!==o.base64Original?t.text("Schema mismatch",400):t.text(n)});H.post("/transaction/start",(0,$.validator)("header",A),async t=>{let{req:e}=t,r=await Ge(t);if(r instanceof Response)return r;try{let n=await oe(t);if(n instanceof Response)return n;let o=await n.startTransaction(r,K(t)),s=qe(o,t);if(s instanceof Response)return s;let{id:i}=s,a=e.param("clientVersion"),c=t.get("port"),m=t.get("protocol"),b=e.param("schemaHash");return t.json({...o,"data-proxy":{endpoint:`${m}://localhost:${c}/${a}/${b}/itx/${i}`}})}catch(n){return G(n,t)}});async function oe(t){let{req:e}=t,r=Ue(t);if(r instanceof Response)return r;let{base64Override:n,overrideHash:o}=r.schemas;return await x.get({base64Schema:n,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.param("clientVersion"),debug:t.get("debug"),platform:t.get("platform"),schemaHash:o})}var Je=require("hono/tiny"),Qe=require("http-status-codes"),J=new Je.Hono;J.post("/database/dump",async t=>{let e=t.get("db"),r=t.get("serverState");return await e.dump(r.databaseDumpPath),t.json({dumpPath:r.databaseDumpPath},Qe.StatusCodes.CREATED)});var Er=J.get("/health",t=>t.json({name:t.get("serverState").name}));async function tt(t,e){let{port:r}=e;if(e.dryRun)return We(r,null);let n=await Ht(r,t,e),{promise:o,reject:s,resolve:i}=V(),a=(0,Ye.serve)({createServer:ze.createServer,fetch:n.fetch,overrideGlobalObjects:!1,port:r},i);return a.on("error",c=>{if(typeof c=="object"&&"code"in c&&c.code==="EADDRINUSE")return s(new E(r,"server"));console.error("[Accelerate]",c)}),await o,We(r,a)}function We(t,e){return{async close(){e&&await Promise.allSettled([(0,Xe.promisify)(e.close.bind(e))(),x.stopAll()])},port:t,url:`http://localhost:${t}`}}async function Ht(t,e,r){let{debug:n}=r,o=new se.Hono,s=await Ze.default.getPlatformInfo();return n&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),n&&o.use("*",(0,et.logger)((...i)=>console.log("[Accelerate]",...i))),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),i.set("shadowDBPort",r.shadowDatabasePort),await a())),o.route("/",ie),o}var ie=new se.Hono;ie.route("/",k);ie.route("/",J);var it=require("fs/promises"),at=require("hono/client"),R=require("pathe"),Q=require("proper-lockfile"),j=require("std-env"),d=require("valibot");var rt=require("std-env");function nt(t,e){if(t==null)return!1;try{return rt.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var de=(0,d.pipe)((0,d.string)(),(0,d.url)()),ot=(0,d.object)({connectionString:de,prismaORMConnectionString:(0,d.optional)(de),terminalCommand:(0,d.optional)((0,d.string)())}),st=(0,d.object)({url:de}),ae=(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(1)),Bt=(0,d.object)({database:ot,http:st,ppg:st,shadowDatabase:ot}),jt=(0,d.object)({databasePort:ae,exports:(0,d.optional)(Bt),name:(0,d.pipe)((0,d.string)(),(0,d.minLength)(1)),pid:(0,d.optional)((0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(0))),port:ae,shadowDatabasePort:ae,version:(0,d.literal)("1")}),le=Symbol("initialize"),ce="default",P=class{databasePort;debug;dryRun;name;persistenceMode;pid;port;shadowDatabasePort;constructor(e){this.databasePort=e.databasePort??51214,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??ce,this.persistenceMode=e.persistenceMode,this.pid=e.pid??j.process.pid,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new B({...e,pid:j.process.pid}):new ue(e);return await r[le](),r}static async fromServerDump(e){let{debug:r,name:n=ce}=e??{},o=I(n),s=B.getServerDumpPath(o),i=await we(s);if(i==null)return r&&console.debug(`[State] No server dump file found at: ${s}`),null;r&&(console.debug(`[State] server dump file found at "${s}":`),console.debug(i));let{issues:a,output:c,success:m}=(0,d.safeParse)((0,d.pipe)((0,d.string)(),(0,d.parseJson)(),jt),i);if(!m)throw r&&console.debug(`[State] Invalid server dump file at "${s}":
|
|
7
|
+
${JSON.stringify(a,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new B({databasePort:c.databasePort,debug:r,dryRun:!1,name:n,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(e){let{debug:r}=e??{},n=(0,R.join)(I(ce),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let o=await De(n);return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(s=>Lt(s,r)))}},ue=class extends P{constructor(e){super({...e,persistenceMode:"stateless",pid:j.process.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[le](){}async close(){}async writeServerDump(){}},B=class t extends P{#r;#e;#t;#s;#n;#o=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=I(this.name),this.#r=(0,R.join)(this.#e,"db_dump.bak"),this.#t=(0,R.join)(this.#e,".pglite"),this.#n=e.serverDump??null,this.#s=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,R.join)(e,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#n?.exports}get pgliteDataDirPath(){return this.#t}async[le](){await Pe(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#o=await(0,Q.lock)(this.#e,{lockfilePath:(0,R.join)(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 L(this):e}}async close(){if(this.#o!=null)try{await this.#o(),this.#o=null,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw console.error(`[State] failed to release lock on: ${this.#e}`),e}}async writeServerDump(e){this.#n={name:this.name,version:"1",pid:j.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,it.writeFile)(this.#s,`${JSON.stringify(this.#n,null,2)}
|
|
8
|
+
`,{encoding:"utf-8"})}};async function Lt(t,e){let r={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let n=await P.fromServerDump({debug:e,name:t});if(!n)return e&&console.debug(`[State] no server state found for name: ${t}`),{...r,status:"no_such_server"};r.databasePort=n.databasePort,r.exports=n.exports,r.pid=n.pid,r.port=n.port,r.shadowDatabasePort=n.shadowDatabasePort;let{exports:o,pid:s}=n;if(!nt(s,e))return e&&console.debug(`[State] server state for "${t}" has no running process with PID: ${s}`),{...r,status:"not_running"};let i=I(t);try{if(!await(0,Q.check)(i,{lockfilePath:(0,R.join)(i,".lock")}))return e&&console.debug(`[State] server state for "${t}" is not locked, indicating it is not running.`),{...r,status:"starting_up"}}catch(b){e&&console.error(`[State] server state for "${t}" failed to check lock:`,b)}if(!o)return{...r,status:"starting_up"};let{http:a}=o,c=await(0,at.hc)(a.url).health.$get();if(!c.ok)return e&&console.debug(`[State] server state for "${t}" is not live: ${JSON.stringify(c)}`),{...r,status:"not_running"};let m=await c.json();return m.name!==t?(e&&console.debug(`[State] server state for "${t}" has mismatched health response: ${JSON.stringify(m)}`),{...r,status:"unknown"}):(e&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(m)}`),{...r,status:"running"})}catch(n){return e&&console.error(`[State] failed to get server status for "${t}":`,n),{...r,status:"error"}}}var L=class extends Error{#r;name="ServerAlreadyRunningError";constructor(e){super(`A Prisma Dev with the name "${e.name}" is already running.`),this.#r=e}get server(){return P.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};async function Mt(t){let e=await P.createExclusively(t),[r,n]=await Promise.all([te("database",e),te("shadow_database",e)]),o=await tt(r,e),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:ge({databaseUrl:r.prismaORMConnectionString,name:e.name,shadowDatabaseUrl:n.prismaORMConnectionString})}).toString()}`,i={database:{connectionString:r.connectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand},http:{url:o.url},ppg:{url:s},shadowDatabase:{connectionString:n.prismaORMConnectionString,prismaORMConnectionString:n.prismaORMConnectionString,terminalCommand:n.terminalCommand}};return await e.writeServerDump(i),{...i,close:()=>a(e,[o,r,n]),name:e.name};async function a(c,m){let v=(await Promise.allSettled(m.map(S=>S.close()))).filter(S=>S.status==="rejected").map(S=>new Error(S.reason));try{await c.close()}catch(S){v.push(S)}if(v.length>0)throw new AggregateError(v,"Failed to close some servers")}}0&&(module.exports={DEFAULT_DATABASE_PORT,DEFAULT_SERVER_PORT,DEFAULT_SHADOW_DATABASE_PORT,PortNotAvailableError,ServerAlreadyRunningError,unstable_startServer});
|
package/dist/index.d.cts
CHANGED
|
@@ -1,3 +1,25 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import { Exports, ServerOptions } from './state.cjs';
|
|
2
|
+
export { ServerAlreadyRunningError } from './state.cjs';
|
|
3
|
+
import { DBServerPurpose } from './db.cjs';
|
|
3
4
|
import 'valibot';
|
|
5
|
+
import '@electric-sql/pglite';
|
|
6
|
+
|
|
7
|
+
declare const DEFAULT_DATABASE_PORT = 51214;
|
|
8
|
+
declare const DEFAULT_SERVER_PORT = 51213;
|
|
9
|
+
declare const DEFAULT_SHADOW_DATABASE_PORT = 51215;
|
|
10
|
+
type PortAssignableService = DBServerPurpose | "server";
|
|
11
|
+
declare class PortNotAvailableError extends Error {
|
|
12
|
+
port: number;
|
|
13
|
+
service: PortAssignableService;
|
|
14
|
+
name: string;
|
|
15
|
+
constructor(port: number, service: PortAssignableService);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface Server extends Exports {
|
|
19
|
+
close(): Promise<void>;
|
|
20
|
+
name: string;
|
|
21
|
+
}
|
|
22
|
+
type ReadonlyServer = Omit<Server, "close">;
|
|
23
|
+
declare function unstable_startServer(options?: ServerOptions): Promise<Server>;
|
|
24
|
+
|
|
25
|
+
export { DEFAULT_DATABASE_PORT, DEFAULT_SERVER_PORT, DEFAULT_SHADOW_DATABASE_PORT, type PortAssignableService, PortNotAvailableError, type ReadonlyServer, type Server, unstable_startServer };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,25 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import { Exports, ServerOptions } from './state.js';
|
|
2
|
+
export { ServerAlreadyRunningError } from './state.js';
|
|
3
|
+
import { DBServerPurpose } from './db.js';
|
|
3
4
|
import 'valibot';
|
|
5
|
+
import '@electric-sql/pglite';
|
|
6
|
+
|
|
7
|
+
declare const DEFAULT_DATABASE_PORT = 51214;
|
|
8
|
+
declare const DEFAULT_SERVER_PORT = 51213;
|
|
9
|
+
declare const DEFAULT_SHADOW_DATABASE_PORT = 51215;
|
|
10
|
+
type PortAssignableService = DBServerPurpose | "server";
|
|
11
|
+
declare class PortNotAvailableError extends Error {
|
|
12
|
+
port: number;
|
|
13
|
+
service: PortAssignableService;
|
|
14
|
+
name: string;
|
|
15
|
+
constructor(port: number, service: PortAssignableService);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface Server extends Exports {
|
|
19
|
+
close(): Promise<void>;
|
|
20
|
+
name: string;
|
|
21
|
+
}
|
|
22
|
+
type ReadonlyServer = Omit<Server, "close">;
|
|
23
|
+
declare function unstable_startServer(options?: ServerOptions): Promise<Server>;
|
|
24
|
+
|
|
25
|
+
export { DEFAULT_DATABASE_PORT, DEFAULT_SERVER_PORT, DEFAULT_SHADOW_DATABASE_PORT, type PortAssignableService, PortNotAvailableError, type ReadonlyServer, type Server, unstable_startServer };
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{a as k}from"./chunk-GBG44OEG.js";import{a as q}from"./chunk-
|
|
2
|
-
`).find(x=>x.includes("Started query engine http server"));if(!
|
|
3
|
-
Received data: ${c}`));r({childProcess:s,url:`http://${l}:${E}`})},a=c=>{this.#t=null,t(new S(String(c))),s.removeListener("exit",p),s.kill()};s.once("error",a);let p=(c,
|
|
1
|
+
import{a as k}from"./chunk-GBG44OEG.js";import{a as q,b as le}from"./chunk-B3YGM5RH.js";import{a as B,c as L,d as M,i as et,j as tt,k as nt,l as N}from"./chunk-Q3M6SQC2.js";import{HTTPException as h}from"hono/http-exception";import{minLength as ue,object as me,optional as de,parseJson as ge,pipe as R,regex as K,safeParse as he,string as T,url as U}from"valibot";var V=/^(postgres|postgresql):\/\//,fe=R(T(),ge(),me({databaseUrl:R(T(),U(),K(V)),name:de(R(T(),ue(1))),shadowDatabaseUrl:R(T(),U(),K(V))}));function F(n){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(n).sort(([[e],[t]])=>e.localeCompare(t)))),"utf8").toString("base64url")}function ye(n){let e=Buffer.from(n,"base64url").toString("utf8"),{issues:t,output:r,success:o}=he(fe,e,{abortEarly:!0});return o?[null,r]:[t]}var f=(n,e)=>{let{authorization:t}=n;if(!t)throw new h(401,{message:"Missing API Key"});let[r,o="",s]=t.split(" ");if(r!=="Bearer"||s)throw new h(401,{message:"Invalid API Key"});let[i,a]=ye(o);if(i)throw new h(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:p,name:c,shadowDatabaseUrl:g}=a,{name:u}=e.get("serverState");if(!c)throw new h(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} requires an API Key from a newer version of \`prisma dev\`. Check the "${u}" server's output for the updated \`DATABASE_URL\` value.`});if(c!==u)throw new h(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${u}", but the API Key is for "${c}"`});let{hostname:l,port:E}=new URL(p),{port:x}=e.get("db"),{hostname:ae,port:ce}=new URL(g),pe=e.get("shadowDBPort");if(l!=="localhost"||Number(E)!==x||ae!=="localhost"||Number(ce)!==pe)throw new h(401,{message:"Wrong API Key; Check your Prisma schema's `provider.url` value (probably defined in `.env`'s `DATABASE_URL` environment variable) is aligned with `prisma dev`'s output"});return{decodedAPIKey:a}};import{createServer as Ge}from"http";import{promisify as Je}from"util";import{serve as We}from"@hono/node-server";import Xe from"@prisma/get-platform";function A(n){let e,t,r=new Promise((i,a)=>{e=i,t=a}),o=i=>{o=s=null,t(i),n?.onRejected?.(i),n?.onFulfilled?.()},s=i=>{s=o=null,e(i),n?.onResolved?.(i),n?.onFulfilled?.()};return{isFulfilled:()=>s===o,promise:r,reject:i=>o?.(i),resolve:i=>s?.(i)}}import{logger as Ye}from"hono/logger";import{Hono as se}from"hono/tiny";import{Hono as Ue}from"hono/tiny";import{validator as v}from"hono/validator";import{array as we,literal as Se,minLength as ve,object as be,pipe as Pe,safeParse as Ee,string as Re,union as Te}from"valibot";var Ae=be({tags:Te([Pe(we(Re()),ve(1)),Se("all")])});async function Q(n){let{output:e,success:t}=Ee(Ae,await n.req.json(),{abortEarly:!0});return t?e:n.text("Invalid input",400)}import{spawn as Oe}from"child_process";import{once as He}from"events";import{mkdir as Ce}from"fs/promises";import{join as Ie}from"path";import{setTimeout as xe}from"timers/promises";import{proxySignals as ke}from"foreground-child/proxy-signals";import{process as $e}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:De,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:je,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:z}=$e.env,w=class n{static#n=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let{debug:t}=e,r=`${e.schemaHash}:${e.clientVersion}`;try{let o=n.#n.get(r);if(o)return o;let s=new n(e);return n.#n.set(r,s),t&&console.debug("[Query Engine] starting...",e),await s.start(),t&&console.debug("[Query Engine] started!"),s}finally{n.stopAll(r)}}static async stopAll(e){let r=(await Promise.allSettled(Array.from(n.#n.entries()).filter(([o])=>o!==e).map(async([o,s])=>{try{await s.stop()}finally{n.#n.delete(o)}}))).filter(o=>o.status==="rejected").map(o=>o.reason);if(r.length>0)throw new AggregateError(r,"Failed to stop engines")}async commitTransaction(e,t){return await this.#o(e,t,"commit")}async request(e,t){let{url:r}=await this.start(),o=this.#r(t),s=await fetch(r,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await y.fromResponse(s);return await s.text()}async rollbackTransaction(e,t){return await this.#o(e,t,"rollback")}async startTransaction(e,t){let{url:r}=await this.start(),o=this.#r(t),s=await fetch(`${r}/transaction/start`,{body:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await y.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:t,resolve:r}=A();this.#t=e;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});ke(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let i=c=>{let g=c.split(`
|
|
2
|
+
`).find(x=>x.includes("Started query engine http server"));if(!g)return;s.stdout.removeListener("data",i);let{fields:u}=JSON.parse(g);if(u==null)return t(new Error(`Unexpected data during initialization, "fields" are missing: ${c}`));let{ip:l,port:E}=u;if(l==null||E==null)return t(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
|
|
3
|
+
Received data: ${c}`));r({childProcess:s,url:`http://${l}:${E}`})},a=c=>{this.#t=null,t(new S(String(c))),s.removeListener("exit",p),s.kill()};s.once("error",a);let p=(c,g)=>{this.#t=null,t(new S(`Query Engine exited with code ${c} and signal ${g}`))};return s.once("exit",p),s.stdout.on("data",i),this.#e.debug&&(s.stderr.on("data",console.error.bind(console,"[Query Engine]")),s.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:e}=await this.#t;e.exitCode==null&&e.signalCode==null&&(this.#t=null,e.kill(),await He(e,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#i();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let t=B(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",t),await Ce(t,{recursive:!0});let{platform:r}=this.#e.platform,o=r==="windows"?".exe":"",s=Ie(t,`query-engine-${r}${o}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(De==="1"||await L(s)===!1)&&await this.#a({commitHash:e,extension:o,engineBinaryPath:s}),s}async#i(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let r=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!r)throw new Error("Couldn't find engines version in package.json");let o=r.split(".").at(-1);if(!o)throw new Error("Couldn't find commit hash in engines version");return o}async#a(e){let{commitHash:t,extension:r,engineBinaryPath:o}=e,{binaryTarget:s}=this.#e.platform,i=`https://binaries.prisma.sh/all_commits/${t}/${s}/query-engine${r}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",i);let a=await fetch(i);if(!a.ok)throw new Error(`Couldn't download engine. URL: ${i}, status code: ${a.status}`);z&&await xe(Number(z)),await M(await a.arrayBuffer(),o),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",o)}#r(e){let t={};for(let[r,o]of Object.entries(e))o!=null&&(t[r]=o);return t}async#o(e,t,r){let{url:o}=await this.#t,s=this.#r(t),i=await fetch(`${o}/transaction/${e}/${r}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await y.fromResponse(i);try{return await i.json()}catch{return{}}}};function O(n,e){return console.error(n),n instanceof S?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:n.message}}}},500):n instanceof y?e.text(n.responseBody,n.statusCode):e.body(null,500)}var S=class extends Error{name="EngineStartError"},y=class n extends Error{constructor(t,r,o){super(`${t}: Query Engine response status ${r}, body: ${o}`);this.action=t;this.statusCode=r;this.responseBody=o}name="EngineHttpError";static async fromResponse(t){let r=new URL(t.url),o=await t.text();return new n(r.pathname,t.status,o)}};import{Buffer as G}from"buffer";var H=new Map;async function $(n){let t=new TextEncoder().encode(n),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}function J(n){let e=n.req.param("schemaHash"),t=H.get(e);return t==null?n.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:t}}var _e=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function W(n,e){let t=G.from(n,"base64").toString("utf8"),r=`datasource db {
|
|
4
4
|
provider = "postgresql"
|
|
5
5
|
url = "${e.toString()}"
|
|
6
|
-
}`,o=t.replace(
|
|
6
|
+
}`,o=t.replace(_e,r),s=await $(o);return{base64Override:G.from(o,"utf8").toString("base64"),overrideHash:s}}function C(n){let{req:e}=n;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}import{integer as X,looseObject as Be,minValue as Y,number as D,object as Le,optional as Me,pipe as Z,safeParse as ee,string as te,union as Ne}from"valibot";var qe=Le({isolation_level:Me(te()),max_wait:Z(D(),X(),Y(0)),timeout:Z(D(),X(),Y(0))});async function ne(n){let{issues:e,output:t,success:r}=ee(qe,await n.req.json(),{abortEarly:!0});return r?t:n.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}var Ke=Be({id:Ne([te(),D()])});function re(n,e){let{output:t,success:r}=ee(Ke,n);return r?t:e.json({EngineMalfunction:{}},500)}var b=new Ue;b.post("/invalidate",v("header",f),async n=>{let e=await Q(n);return e instanceof Response?e:n.body(null)});var Ve="/:clientVersion/:schemaHash",P=b.basePath(Ve);b.route("/",P);var Fe=["/graphql","/itx/:transactionId/graphql"];P.on("POST",[...Fe],v("header",f),async n=>{let{req:e}=n;try{let t=await j(n);if(t instanceof Response)return t;let r=await e.text(),o=e.param("transactionId"),s=await t.request(r,{...C(n),"X-transaction-id":o});return n.text(s)}catch(t){return O(t,n)}});P.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],v("header",f),async n=>{let{req:e}=n;try{let t=await j(n);if(t instanceof Response)return t;let o=`${e.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=e.param("transactionId"),i=await t[o](s,C(n));return n.json(i)}catch(t){return O(t,n)}});P.put("/schema",v("header",f),async n=>{let{req:e}=n,t=await e.text();if(!t)return n.text("Missing schema",400);let r=e.param("schemaHash"),o=H.get(r);if(o==null){if(r!==await $(t))return n.text("Schema hash mismatch",400);let s=await W(t,n.get("db").prismaORMConnectionString);return H.set(r,{base64Original:t,...s}),n.text(r)}return t!==o.base64Original?n.text("Schema mismatch",400):n.text(r)});P.post("/transaction/start",v("header",f),async n=>{let{req:e}=n,t=await ne(n);if(t instanceof Response)return t;try{let r=await j(n);if(r instanceof Response)return r;let o=await r.startTransaction(t,C(n)),s=re(o,n);if(s instanceof Response)return s;let{id:i}=s,a=e.param("clientVersion"),p=n.get("port"),c=n.get("protocol"),g=e.param("schemaHash");return n.json({...o,"data-proxy":{endpoint:`${c}://localhost:${p}/${a}/${g}/itx/${i}`}})}catch(r){return O(r,n)}});async function j(n){let{req:e}=n,t=J(n);if(t instanceof Response)return t;let{base64Override:r,overrideHash:o}=t.schemas;return await w.get({base64Schema:r,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.param("clientVersion"),debug:n.get("debug"),platform:n.get("platform"),schemaHash:o})}import{Hono as Qe}from"hono/tiny";import{StatusCodes as ze}from"http-status-codes";var I=new Qe;I.post("/database/dump",async n=>{let e=n.get("db"),t=n.get("serverState");return await e.dump(t.databaseDumpPath),n.json({dumpPath:t.databaseDumpPath},ze.CREATED)});var Vt=I.get("/health",n=>n.json({name:n.get("serverState").name}));async function ie(n,e){let{port:t}=e;if(e.dryRun)return oe(t,null);let r=await Ze(t,n,e),{promise:o,reject:s,resolve:i}=A(),a=We({createServer:Ge,fetch:r.fetch,overrideGlobalObjects:!1,port:t},i);return a.on("error",p=>{if(typeof p=="object"&&"code"in p&&p.code==="EADDRINUSE")return s(new N(t,"server"));console.error("[Accelerate]",p)}),await o,oe(t,a)}function oe(n,e){return{async close(){e&&await Promise.allSettled([Je(e.close.bind(e))(),w.stopAll()])},port:n,url:`http://localhost:${n}`}}async function Ze(n,e,t){let{debug:r}=t,o=new se,s=await Xe.getPlatformInfo();return r&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),r&&o.use("*",Ye((...i)=>console.log("[Accelerate]",...i))),o.use("*",async(i,a)=>(i.set("db",e),i.set("debug",!!r),i.set("platform",s),i.set("port",n),i.set("protocol","http"),i.set("serverState",t),i.set("shadowDBPort",t.shadowDatabasePort),await a())),o.route("/",_),o}var _=new se;_.route("/",b);_.route("/",I);async function un(n){let e=await q.createExclusively(n),[t,r]=await Promise.all([k("database",e),k("shadow_database",e)]),o=await ie(t,e),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:F({databaseUrl:t.prismaORMConnectionString,name:e.name,shadowDatabaseUrl:r.prismaORMConnectionString})}).toString()}`,i={database:{connectionString:t.connectionString,prismaORMConnectionString:t.prismaORMConnectionString,terminalCommand:t.terminalCommand},http:{url:o.url},ppg:{url:s},shadowDatabase:{connectionString:r.prismaORMConnectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand}};return await e.writeServerDump(i),{...i,close:()=>a(e,[o,t,r]),name:e.name};async function a(p,c){let u=(await Promise.allSettled(c.map(l=>l.close()))).filter(l=>l.status==="rejected").map(l=>new Error(l.reason));try{await p.close()}catch(l){u.push(l)}if(u.length>0)throw new AggregateError(u,"Failed to close some servers")}}export{et as DEFAULT_DATABASE_PORT,tt as DEFAULT_SERVER_PORT,nt as DEFAULT_SHADOW_DATABASE_PORT,N as PortNotAvailableError,le as ServerAlreadyRunningError,un as unstable_startServer};
|
package/dist/state.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var X=Object.create;var v=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var Y=Object.getOwnPropertyNames;var Z=Object.getPrototypeOf,q=Object.prototype.hasOwnProperty;var z=(t,e)=>{for(var r in e)v(t,r,{get:e[r],enumerable:!0})},M=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Y(e))!q.call(t,n)&&n!==r&&v(t,n,{get:()=>e[n],enumerable:!(i=K(e,n))||i.enumerable});return t};var A=(t,e,r)=>(r=t!=null?X(Z(t)):{},M(e||!t||!t.__esModule?v(r,"default",{value:t,enumerable:!0}):r,t)),Q=t=>M(v({},"__esModule",{value:!0}),t);var de={};z(de,{
|
|
2
|
-
${JSON.stringify(x,null,2)}`),new Error(`Invalid Prisma Dev state for "${i}".`);return new P({databasePort:u.databasePort,debug:r,dryRun:!1,name:i,pid:u.pid,port:u.port,serverDump:u,shadowDatabasePort:u.shadowDatabasePort})}static async scan(e){let{debug:r}=e??{},i=(0,d.join)(g($),"..");r&&console.debug(`[State] scanning for server states in: ${i}`);let n=await V(i);return r&&console.debug(`[State] found server names: ${JSON.stringify(n)}`),await Promise.all(n.map(c=>pe(c,r)))}},j=class extends
|
|
3
|
-
`,{encoding:"utf-8"})}};async function pe(t,e){let r={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let i=await
|
|
1
|
+
"use strict";var X=Object.create;var v=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var Y=Object.getOwnPropertyNames;var Z=Object.getPrototypeOf,q=Object.prototype.hasOwnProperty;var z=(t,e)=>{for(var r in e)v(t,r,{get:e[r],enumerable:!0})},M=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Y(e))!q.call(t,n)&&n!==r&&v(t,n,{get:()=>e[n],enumerable:!(i=K(e,n))||i.enumerable});return t};var A=(t,e,r)=>(r=t!=null?X(Z(t)):{},M(e||!t||!t.__esModule?v(r,"default",{value:t,enumerable:!0}):r,t)),Q=t=>M(v({},"__esModule",{value:!0}),t);var de={};z(de,{ServerAlreadyRunningError:()=>y,ServerState:()=>l});module.exports=Q(de);var U=require("fs/promises"),G=require("hono/client"),d=require("pathe"),w=require("proper-lockfile"),b=require("std-env"),s=require("valibot");var L=require("fs"),a=require("fs/promises");var o=A(require("path"),1),E=A(require("os"),1),D=A(require("process"),1),p=E.default.homedir(),O=E.default.tmpdir(),{env:m}=D.default,ee=t=>{let e=o.default.join(p,"Library");return{data:o.default.join(e,"Application Support",t),config:o.default.join(e,"Preferences",t),cache:o.default.join(e,"Caches",t),log:o.default.join(e,"Logs",t),temp:o.default.join(O,t)}},te=t=>{let e=m.APPDATA||o.default.join(p,"AppData","Roaming"),r=m.LOCALAPPDATA||o.default.join(p,"AppData","Local");return{data:o.default.join(r,t,"Data"),config:o.default.join(e,t,"Config"),cache:o.default.join(r,t,"Cache"),log:o.default.join(r,t,"Log"),temp:o.default.join(O,t)}},re=t=>{let e=o.default.basename(p);return{data:o.default.join(m.XDG_DATA_HOME||o.default.join(p,".local","share"),t),config:o.default.join(m.XDG_CONFIG_HOME||o.default.join(p,".config"),t),cache:o.default.join(m.XDG_CACHE_HOME||o.default.join(p,".cache"),t),log:o.default.join(m.XDG_STATE_HOME||o.default.join(p,".local","state"),t),temp:o.default.join(O,e,t)}};function _(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),D.default.platform==="darwin"?ee(t):D.default.platform==="win32"?te(t):re(t)}var se=require("pako"),oe=_("prisma-dev");function g(t){return`${oe.data}/${t}`}function F(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function I(t){try{return await(0,a.readFile)(t,{encoding:"utf-8"})}catch(e){if(F(e))return null;throw e}}async function N(t){await(0,a.mkdir)(t,{recursive:!0})}async function V(t){try{return(await(0,a.readdir)(t,{withFileTypes:!0})).reduce((r,i)=>(i.isDirectory()&&!i.name.startsWith(".")&&r.push(i.name),r),[])}catch(e){if(F(e))return[];throw e}}var C=require("std-env");function B(t,e){if(t==null)return!1;try{return C.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var R=(0,s.pipe)((0,s.string)(),(0,s.url)()),H=(0,s.object)({connectionString:R,prismaORMConnectionString:(0,s.optional)(R),terminalCommand:(0,s.optional)((0,s.string)())}),J=(0,s.object)({url:R}),T=(0,s.pipe)((0,s.number)(),(0,s.integer)(),(0,s.minValue)(1)),ce=(0,s.object)({database:H,http:J,ppg:J,shadowDatabase:H}),ue=(0,s.object)({databasePort:T,exports:(0,s.optional)(ce),name:(0,s.pipe)((0,s.string)(),(0,s.minLength)(1)),pid:(0,s.optional)((0,s.pipe)((0,s.number)(),(0,s.integer)(),(0,s.minValue)(0))),port:T,shadowDatabasePort:T,version:(0,s.literal)("1")}),k=Symbol("initialize"),$="default",l=class{databasePort;debug;dryRun;name;persistenceMode;pid;port;shadowDatabasePort;constructor(e){this.databasePort=e.databasePort??51214,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??$,this.persistenceMode=e.persistenceMode,this.pid=e.pid??b.process.pid,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new P({...e,pid:b.process.pid}):new j(e);return await r[k](),r}static async fromServerDump(e){let{debug:r,name:i=$}=e??{},n=g(i),c=P.getServerDumpPath(n),h=await I(c);if(h==null)return r&&console.debug(`[State] No server dump file found at: ${c}`),null;r&&(console.debug(`[State] server dump file found at "${c}":`),console.debug(h));let{issues:x,output:u,success:f}=(0,s.safeParse)((0,s.pipe)((0,s.string)(),(0,s.parseJson)(),ue),h);if(!f)throw r&&console.debug(`[State] Invalid server dump file at "${c}":
|
|
2
|
+
${JSON.stringify(x,null,2)}`),new Error(`Invalid Prisma Dev state for "${i}".`);return new P({databasePort:u.databasePort,debug:r,dryRun:!1,name:i,pid:u.pid,port:u.port,serverDump:u,shadowDatabasePort:u.shadowDatabasePort})}static async scan(e){let{debug:r}=e??{},i=(0,d.join)(g($),"..");r&&console.debug(`[State] scanning for server states in: ${i}`);let n=await V(i);return r&&console.debug(`[State] found server names: ${JSON.stringify(n)}`),await Promise.all(n.map(c=>pe(c,r)))}},j=class extends l{constructor(e){super({...e,persistenceMode:"stateless",pid:b.process.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[k](){}async close(){}async writeServerDump(){}},P=class t extends l{#t;#e;#o;#i;#r;#s=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=g(this.name),this.#t=(0,d.join)(this.#e,"db_dump.bak"),this.#o=(0,d.join)(this.#e,".pglite"),this.#r=e.serverDump??null,this.#i=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,d.join)(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get pgliteDataDirPath(){return this.#o}async[k](){await N(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#s=await(0,w.lock)(this.#e,{lockfilePath:(0,d.join)(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 y(this):e}}async close(){if(this.#s!=null)try{await this.#s(),this.#s=null,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw console.error(`[State] failed to release lock on: ${this.#e}`),e}}async writeServerDump(e){this.#r={name:this.name,version:"1",pid:b.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,U.writeFile)(this.#i,`${JSON.stringify(this.#r,null,2)}
|
|
3
|
+
`,{encoding:"utf-8"})}};async function pe(t,e){let r={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let i=await l.fromServerDump({debug:e,name:t});if(!i)return e&&console.debug(`[State] no server state found for name: ${t}`),{...r,status:"no_such_server"};r.databasePort=i.databasePort,r.exports=i.exports,r.pid=i.pid,r.port=i.port,r.shadowDatabasePort=i.shadowDatabasePort;let{exports:n,pid:c}=i;if(!B(c,e))return e&&console.debug(`[State] server state for "${t}" has no running process with PID: ${c}`),{...r,status:"not_running"};let h=g(t);try{if(!await(0,w.check)(h,{lockfilePath:(0,d.join)(h,".lock")}))return e&&console.debug(`[State] server state for "${t}" is not locked, indicating it is not running.`),{...r,status:"starting_up"}}catch(W){e&&console.error(`[State] server state for "${t}" failed to check lock:`,W)}if(!n)return{...r,status:"starting_up"};let{http:x}=n,u=await(0,G.hc)(x.url).health.$get();if(!u.ok)return e&&console.debug(`[State] server state for "${t}" is not live: ${JSON.stringify(u)}`),{...r,status:"not_running"};let f=await u.json();return f.name!==t?(e&&console.debug(`[State] server state for "${t}" has mismatched health response: ${JSON.stringify(f)}`),{...r,status:"unknown"}):(e&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(f)}`),{...r,status:"running"})}catch(i){return e&&console.error(`[State] failed to get server status for "${t}":`,i),{...r,status:"error"}}}var y=class extends Error{#t;name="ServerAlreadyRunningError";constructor(e){super(`A Prisma Dev with the name "${e.name}" is already running.`),this.#t=e}get server(){return l.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};0&&(module.exports={ServerAlreadyRunningError,ServerState});
|
package/dist/state.d.cts
CHANGED
|
@@ -1,3 +1,152 @@
|
|
|
1
|
-
import 'valibot';
|
|
2
|
-
|
|
3
|
-
|
|
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
|
+
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
|
|
8
|
+
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
|
|
9
|
+
}, undefined>;
|
|
10
|
+
readonly http: valibot.ObjectSchema<{
|
|
11
|
+
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
12
|
+
}, undefined>;
|
|
13
|
+
readonly ppg: valibot.ObjectSchema<{
|
|
14
|
+
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
15
|
+
}, undefined>;
|
|
16
|
+
readonly shadowDatabase: valibot.ObjectSchema<{
|
|
17
|
+
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
18
|
+
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
|
|
19
|
+
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
|
|
20
|
+
}, undefined>;
|
|
21
|
+
}, undefined>;
|
|
22
|
+
type Exports = InferOutput<typeof exportsSchema>;
|
|
23
|
+
declare const serverDumpV1Schema: valibot.ObjectSchema<{
|
|
24
|
+
readonly databasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
|
|
25
|
+
readonly exports: valibot.OptionalSchema<valibot.ObjectSchema<{
|
|
26
|
+
readonly database: valibot.ObjectSchema<{
|
|
27
|
+
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
28
|
+
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
|
|
29
|
+
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
|
|
30
|
+
}, undefined>;
|
|
31
|
+
readonly http: valibot.ObjectSchema<{
|
|
32
|
+
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
33
|
+
}, undefined>;
|
|
34
|
+
readonly ppg: valibot.ObjectSchema<{
|
|
35
|
+
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
36
|
+
}, undefined>;
|
|
37
|
+
readonly shadowDatabase: valibot.ObjectSchema<{
|
|
38
|
+
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
39
|
+
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
|
|
40
|
+
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
|
|
41
|
+
}, undefined>;
|
|
42
|
+
}, undefined>, undefined>;
|
|
43
|
+
readonly name: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
|
|
44
|
+
readonly pid: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 0, undefined>]>, undefined>;
|
|
45
|
+
readonly port: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
|
|
46
|
+
readonly shadowDatabasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
|
|
47
|
+
readonly version: valibot.LiteralSchema<"1", undefined>;
|
|
48
|
+
}, undefined>;
|
|
49
|
+
type ServerDumpV1 = InferOutput<typeof serverDumpV1Schema>;
|
|
50
|
+
interface ServerOptions {
|
|
51
|
+
/**
|
|
52
|
+
* The port the database server will listen on.
|
|
53
|
+
*
|
|
54
|
+
* Defaults to `51214`.
|
|
55
|
+
*
|
|
56
|
+
* An error is thrown if the port is already in use.
|
|
57
|
+
*/
|
|
58
|
+
databasePort?: number;
|
|
59
|
+
/**
|
|
60
|
+
* Whether to enable debug logging.
|
|
61
|
+
*
|
|
62
|
+
* Defaults to `false`.
|
|
63
|
+
*/
|
|
64
|
+
debug?: boolean;
|
|
65
|
+
/**
|
|
66
|
+
* Whether to run the server in dry run mode.
|
|
67
|
+
*
|
|
68
|
+
* Defaults to `false`.
|
|
69
|
+
*/
|
|
70
|
+
dryRun?: boolean;
|
|
71
|
+
/**
|
|
72
|
+
* The name of the server.
|
|
73
|
+
*
|
|
74
|
+
* Defaults to `default`.
|
|
75
|
+
*/
|
|
76
|
+
name?: string;
|
|
77
|
+
/**
|
|
78
|
+
* The persistence mode of the server.
|
|
79
|
+
*
|
|
80
|
+
* Default is `stateless`.
|
|
81
|
+
*/
|
|
82
|
+
persistenceMode?: PersistenceMode;
|
|
83
|
+
/**
|
|
84
|
+
* The port the server will listen on.
|
|
85
|
+
*
|
|
86
|
+
* Defaults to `51213`.
|
|
87
|
+
*
|
|
88
|
+
* An error is thrown if the port is already in use.
|
|
89
|
+
*/
|
|
90
|
+
port?: number;
|
|
91
|
+
/**
|
|
92
|
+
* The port the shadow database server will listen on.
|
|
93
|
+
*
|
|
94
|
+
* Defaults to `51215`.
|
|
95
|
+
*
|
|
96
|
+
* An error is thrown if the port is already in use.
|
|
97
|
+
*/
|
|
98
|
+
shadowDatabasePort?: number;
|
|
99
|
+
}
|
|
100
|
+
type ResolvedServerOptions = Required<ServerOptions>;
|
|
101
|
+
type PersistenceMode = "stateless" | "stateful";
|
|
102
|
+
interface ScanOptions {
|
|
103
|
+
debug?: boolean;
|
|
104
|
+
}
|
|
105
|
+
declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
|
|
106
|
+
declare abstract class ServerState implements ResolvedServerOptions {
|
|
107
|
+
readonly databasePort: number;
|
|
108
|
+
readonly debug: boolean;
|
|
109
|
+
readonly dryRun: boolean;
|
|
110
|
+
readonly name: string;
|
|
111
|
+
readonly persistenceMode: PersistenceMode;
|
|
112
|
+
readonly pid: number | undefined;
|
|
113
|
+
readonly port: number;
|
|
114
|
+
readonly shadowDatabasePort: number;
|
|
115
|
+
protected constructor(options: Omit<ServerOptions, "persistenceMode"> & {
|
|
116
|
+
persistenceMode: PersistenceMode;
|
|
117
|
+
pid: number | undefined;
|
|
118
|
+
});
|
|
119
|
+
static createExclusively(options: ServerOptions | undefined): Promise<ServerState>;
|
|
120
|
+
static fromServerDump(options?: Pick<ServerOptions, "debug" | "name">): Promise<StatefulServerState | null>;
|
|
121
|
+
static scan(options?: ScanOptions): Promise<ServerStatusV1[]>;
|
|
122
|
+
abstract get databaseDumpPath(): string;
|
|
123
|
+
abstract get pgliteDataDirPath(): string;
|
|
124
|
+
abstract [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
|
|
125
|
+
abstract close(): Promise<void>;
|
|
126
|
+
abstract writeServerDump(exports?: Exports): Promise<void>;
|
|
127
|
+
}
|
|
128
|
+
declare class StatefulServerState extends ServerState {
|
|
129
|
+
#private;
|
|
130
|
+
constructor(options: Omit<ServerOptions, "persistenceMode"> & {
|
|
131
|
+
pid: number | undefined;
|
|
132
|
+
serverDump?: ServerDumpV1;
|
|
133
|
+
});
|
|
134
|
+
static getServerDumpPath(dataDirPath: string): string;
|
|
135
|
+
get databaseDumpPath(): string;
|
|
136
|
+
get exports(): Exports | undefined;
|
|
137
|
+
get pgliteDataDirPath(): string;
|
|
138
|
+
[PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
|
|
139
|
+
close(): Promise<void>;
|
|
140
|
+
writeServerDump(exports?: Exports): Promise<void>;
|
|
141
|
+
}
|
|
142
|
+
interface ServerStatusV1 extends ServerDumpV1 {
|
|
143
|
+
status: "running" | "starting_up" | "not_running" | "no_such_server" | "unknown" | "error";
|
|
144
|
+
}
|
|
145
|
+
declare class ServerAlreadyRunningError extends Error {
|
|
146
|
+
#private;
|
|
147
|
+
name: string;
|
|
148
|
+
constructor(server: ServerState);
|
|
149
|
+
get server(): Promise<ServerState | null>;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export { type Exports, type PersistenceMode, type ResolvedServerOptions, type ScanOptions, ServerAlreadyRunningError, type ServerDumpV1, type ServerOptions, ServerState, type ServerStatusV1 };
|
package/dist/state.d.ts
CHANGED
|
@@ -1,3 +1,152 @@
|
|
|
1
|
-
import 'valibot';
|
|
2
|
-
|
|
3
|
-
|
|
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
|
+
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
|
|
8
|
+
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
|
|
9
|
+
}, undefined>;
|
|
10
|
+
readonly http: valibot.ObjectSchema<{
|
|
11
|
+
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
12
|
+
}, undefined>;
|
|
13
|
+
readonly ppg: valibot.ObjectSchema<{
|
|
14
|
+
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
15
|
+
}, undefined>;
|
|
16
|
+
readonly shadowDatabase: valibot.ObjectSchema<{
|
|
17
|
+
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
18
|
+
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
|
|
19
|
+
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
|
|
20
|
+
}, undefined>;
|
|
21
|
+
}, undefined>;
|
|
22
|
+
type Exports = InferOutput<typeof exportsSchema>;
|
|
23
|
+
declare const serverDumpV1Schema: valibot.ObjectSchema<{
|
|
24
|
+
readonly databasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
|
|
25
|
+
readonly exports: valibot.OptionalSchema<valibot.ObjectSchema<{
|
|
26
|
+
readonly database: valibot.ObjectSchema<{
|
|
27
|
+
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
28
|
+
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
|
|
29
|
+
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
|
|
30
|
+
}, undefined>;
|
|
31
|
+
readonly http: valibot.ObjectSchema<{
|
|
32
|
+
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
33
|
+
}, undefined>;
|
|
34
|
+
readonly ppg: valibot.ObjectSchema<{
|
|
35
|
+
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
36
|
+
}, undefined>;
|
|
37
|
+
readonly shadowDatabase: valibot.ObjectSchema<{
|
|
38
|
+
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
39
|
+
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
|
|
40
|
+
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
|
|
41
|
+
}, undefined>;
|
|
42
|
+
}, undefined>, undefined>;
|
|
43
|
+
readonly name: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
|
|
44
|
+
readonly pid: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 0, undefined>]>, undefined>;
|
|
45
|
+
readonly port: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
|
|
46
|
+
readonly shadowDatabasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
|
|
47
|
+
readonly version: valibot.LiteralSchema<"1", undefined>;
|
|
48
|
+
}, undefined>;
|
|
49
|
+
type ServerDumpV1 = InferOutput<typeof serverDumpV1Schema>;
|
|
50
|
+
interface ServerOptions {
|
|
51
|
+
/**
|
|
52
|
+
* The port the database server will listen on.
|
|
53
|
+
*
|
|
54
|
+
* Defaults to `51214`.
|
|
55
|
+
*
|
|
56
|
+
* An error is thrown if the port is already in use.
|
|
57
|
+
*/
|
|
58
|
+
databasePort?: number;
|
|
59
|
+
/**
|
|
60
|
+
* Whether to enable debug logging.
|
|
61
|
+
*
|
|
62
|
+
* Defaults to `false`.
|
|
63
|
+
*/
|
|
64
|
+
debug?: boolean;
|
|
65
|
+
/**
|
|
66
|
+
* Whether to run the server in dry run mode.
|
|
67
|
+
*
|
|
68
|
+
* Defaults to `false`.
|
|
69
|
+
*/
|
|
70
|
+
dryRun?: boolean;
|
|
71
|
+
/**
|
|
72
|
+
* The name of the server.
|
|
73
|
+
*
|
|
74
|
+
* Defaults to `default`.
|
|
75
|
+
*/
|
|
76
|
+
name?: string;
|
|
77
|
+
/**
|
|
78
|
+
* The persistence mode of the server.
|
|
79
|
+
*
|
|
80
|
+
* Default is `stateless`.
|
|
81
|
+
*/
|
|
82
|
+
persistenceMode?: PersistenceMode;
|
|
83
|
+
/**
|
|
84
|
+
* The port the server will listen on.
|
|
85
|
+
*
|
|
86
|
+
* Defaults to `51213`.
|
|
87
|
+
*
|
|
88
|
+
* An error is thrown if the port is already in use.
|
|
89
|
+
*/
|
|
90
|
+
port?: number;
|
|
91
|
+
/**
|
|
92
|
+
* The port the shadow database server will listen on.
|
|
93
|
+
*
|
|
94
|
+
* Defaults to `51215`.
|
|
95
|
+
*
|
|
96
|
+
* An error is thrown if the port is already in use.
|
|
97
|
+
*/
|
|
98
|
+
shadowDatabasePort?: number;
|
|
99
|
+
}
|
|
100
|
+
type ResolvedServerOptions = Required<ServerOptions>;
|
|
101
|
+
type PersistenceMode = "stateless" | "stateful";
|
|
102
|
+
interface ScanOptions {
|
|
103
|
+
debug?: boolean;
|
|
104
|
+
}
|
|
105
|
+
declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
|
|
106
|
+
declare abstract class ServerState implements ResolvedServerOptions {
|
|
107
|
+
readonly databasePort: number;
|
|
108
|
+
readonly debug: boolean;
|
|
109
|
+
readonly dryRun: boolean;
|
|
110
|
+
readonly name: string;
|
|
111
|
+
readonly persistenceMode: PersistenceMode;
|
|
112
|
+
readonly pid: number | undefined;
|
|
113
|
+
readonly port: number;
|
|
114
|
+
readonly shadowDatabasePort: number;
|
|
115
|
+
protected constructor(options: Omit<ServerOptions, "persistenceMode"> & {
|
|
116
|
+
persistenceMode: PersistenceMode;
|
|
117
|
+
pid: number | undefined;
|
|
118
|
+
});
|
|
119
|
+
static createExclusively(options: ServerOptions | undefined): Promise<ServerState>;
|
|
120
|
+
static fromServerDump(options?: Pick<ServerOptions, "debug" | "name">): Promise<StatefulServerState | null>;
|
|
121
|
+
static scan(options?: ScanOptions): Promise<ServerStatusV1[]>;
|
|
122
|
+
abstract get databaseDumpPath(): string;
|
|
123
|
+
abstract get pgliteDataDirPath(): string;
|
|
124
|
+
abstract [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
|
|
125
|
+
abstract close(): Promise<void>;
|
|
126
|
+
abstract writeServerDump(exports?: Exports): Promise<void>;
|
|
127
|
+
}
|
|
128
|
+
declare class StatefulServerState extends ServerState {
|
|
129
|
+
#private;
|
|
130
|
+
constructor(options: Omit<ServerOptions, "persistenceMode"> & {
|
|
131
|
+
pid: number | undefined;
|
|
132
|
+
serverDump?: ServerDumpV1;
|
|
133
|
+
});
|
|
134
|
+
static getServerDumpPath(dataDirPath: string): string;
|
|
135
|
+
get databaseDumpPath(): string;
|
|
136
|
+
get exports(): Exports | undefined;
|
|
137
|
+
get pgliteDataDirPath(): string;
|
|
138
|
+
[PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
|
|
139
|
+
close(): Promise<void>;
|
|
140
|
+
writeServerDump(exports?: Exports): Promise<void>;
|
|
141
|
+
}
|
|
142
|
+
interface ServerStatusV1 extends ServerDumpV1 {
|
|
143
|
+
status: "running" | "starting_up" | "not_running" | "no_such_server" | "unknown" | "error";
|
|
144
|
+
}
|
|
145
|
+
declare class ServerAlreadyRunningError extends Error {
|
|
146
|
+
#private;
|
|
147
|
+
name: string;
|
|
148
|
+
constructor(server: ServerState);
|
|
149
|
+
get server(): Promise<ServerState | null>;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export { type Exports, type PersistenceMode, type ResolvedServerOptions, type ScanOptions, ServerAlreadyRunningError, type ServerDumpV1, type ServerOptions, ServerState, type ServerStatusV1 };
|
package/dist/state.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b}from"./chunk-
|
|
1
|
+
import{a,b}from"./chunk-B3YGM5RH.js";import"./chunk-Q3M6SQC2.js";export{b as ServerAlreadyRunningError,a as ServerState};
|
package/package.json
CHANGED
package/dist/db-B1_DGnTu.d.cts
DELETED
|
@@ -1,202 +0,0 @@
|
|
|
1
|
-
import { PGlite } from '@electric-sql/pglite';
|
|
2
|
-
import * as valibot from 'valibot';
|
|
3
|
-
import { InferOutput } from 'valibot';
|
|
4
|
-
|
|
5
|
-
declare const DEFAULT_DATABASE_PORT = 51214;
|
|
6
|
-
declare const DEFAULT_SERVER_PORT = 51213;
|
|
7
|
-
declare const DEFAULT_SHADOW_DATABASE_PORT = 51215;
|
|
8
|
-
type PortAssignableService = DBServerPurpose | "server";
|
|
9
|
-
declare class PortNotAvailableError extends Error {
|
|
10
|
-
port: number;
|
|
11
|
-
service: PortAssignableService;
|
|
12
|
-
name: string;
|
|
13
|
-
constructor(port: number, service: PortAssignableService);
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
interface Server extends Exports {
|
|
17
|
-
close(): Promise<void>;
|
|
18
|
-
}
|
|
19
|
-
declare function unstable_startServer(options?: ServerOptions): Promise<Server>;
|
|
20
|
-
|
|
21
|
-
declare const exportsSchema: valibot.ObjectSchema<{
|
|
22
|
-
readonly database: valibot.ObjectSchema<{
|
|
23
|
-
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
24
|
-
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
|
|
25
|
-
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
|
|
26
|
-
}, undefined>;
|
|
27
|
-
readonly http: valibot.ObjectSchema<{
|
|
28
|
-
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
29
|
-
}, undefined>;
|
|
30
|
-
readonly ppg: valibot.ObjectSchema<{
|
|
31
|
-
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
32
|
-
}, undefined>;
|
|
33
|
-
readonly shadowDatabase: valibot.ObjectSchema<{
|
|
34
|
-
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
35
|
-
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
|
|
36
|
-
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
|
|
37
|
-
}, undefined>;
|
|
38
|
-
}, undefined>;
|
|
39
|
-
type Exports = InferOutput<typeof exportsSchema>;
|
|
40
|
-
declare const serverDumpV1Schema: valibot.ObjectSchema<{
|
|
41
|
-
readonly databasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
|
|
42
|
-
readonly exports: valibot.OptionalSchema<valibot.ObjectSchema<{
|
|
43
|
-
readonly database: valibot.ObjectSchema<{
|
|
44
|
-
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
45
|
-
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
|
|
46
|
-
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
|
|
47
|
-
}, undefined>;
|
|
48
|
-
readonly http: valibot.ObjectSchema<{
|
|
49
|
-
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
50
|
-
}, undefined>;
|
|
51
|
-
readonly ppg: valibot.ObjectSchema<{
|
|
52
|
-
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
53
|
-
}, undefined>;
|
|
54
|
-
readonly shadowDatabase: valibot.ObjectSchema<{
|
|
55
|
-
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
56
|
-
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
|
|
57
|
-
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
|
|
58
|
-
}, undefined>;
|
|
59
|
-
}, undefined>, undefined>;
|
|
60
|
-
readonly name: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
|
|
61
|
-
readonly pid: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 0, undefined>]>, undefined>;
|
|
62
|
-
readonly port: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
|
|
63
|
-
readonly shadowDatabasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
|
|
64
|
-
readonly version: valibot.LiteralSchema<"1", undefined>;
|
|
65
|
-
}, undefined>;
|
|
66
|
-
type ServerDumpV1 = InferOutput<typeof serverDumpV1Schema>;
|
|
67
|
-
interface ServerOptions {
|
|
68
|
-
/**
|
|
69
|
-
* The port the database server will listen on.
|
|
70
|
-
*
|
|
71
|
-
* Defaults to `51214`.
|
|
72
|
-
*
|
|
73
|
-
* An error is thrown if the port is already in use.
|
|
74
|
-
*/
|
|
75
|
-
databasePort?: number;
|
|
76
|
-
/**
|
|
77
|
-
* Whether to enable debug logging.
|
|
78
|
-
*
|
|
79
|
-
* Defaults to `false`.
|
|
80
|
-
*/
|
|
81
|
-
debug?: boolean;
|
|
82
|
-
/**
|
|
83
|
-
* Whether to run the server in dry run mode.
|
|
84
|
-
*
|
|
85
|
-
* Defaults to `false`.
|
|
86
|
-
*/
|
|
87
|
-
dryRun?: boolean;
|
|
88
|
-
/**
|
|
89
|
-
* The name of the server.
|
|
90
|
-
*
|
|
91
|
-
* Defaults to `default`.
|
|
92
|
-
*/
|
|
93
|
-
name?: string;
|
|
94
|
-
/**
|
|
95
|
-
* The persistence mode of the server.
|
|
96
|
-
*
|
|
97
|
-
* Default is `stateless`.
|
|
98
|
-
*/
|
|
99
|
-
persistenceMode?: PersistenceMode;
|
|
100
|
-
/**
|
|
101
|
-
* The port the server will listen on.
|
|
102
|
-
*
|
|
103
|
-
* Defaults to `51213`.
|
|
104
|
-
*
|
|
105
|
-
* An error is thrown if the port is already in use.
|
|
106
|
-
*/
|
|
107
|
-
port?: number;
|
|
108
|
-
/**
|
|
109
|
-
* The port the shadow database server will listen on.
|
|
110
|
-
*
|
|
111
|
-
* Defaults to `51215`.
|
|
112
|
-
*
|
|
113
|
-
* An error is thrown if the port is already in use.
|
|
114
|
-
*/
|
|
115
|
-
shadowDatabasePort?: number;
|
|
116
|
-
}
|
|
117
|
-
type ResolvedServerOptions = Required<ServerOptions>;
|
|
118
|
-
type PersistenceMode = "stateless" | "stateful";
|
|
119
|
-
interface ScanOptions {
|
|
120
|
-
debug?: boolean;
|
|
121
|
-
}
|
|
122
|
-
declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
|
|
123
|
-
declare abstract class ServerState implements ResolvedServerOptions {
|
|
124
|
-
readonly databasePort: number;
|
|
125
|
-
readonly debug: boolean;
|
|
126
|
-
readonly dryRun: boolean;
|
|
127
|
-
readonly name: string;
|
|
128
|
-
readonly persistenceMode: PersistenceMode;
|
|
129
|
-
readonly pid: number | undefined;
|
|
130
|
-
readonly port: number;
|
|
131
|
-
readonly shadowDatabasePort: number;
|
|
132
|
-
protected constructor(options: Omit<ServerOptions, "persistenceMode"> & {
|
|
133
|
-
persistenceMode: PersistenceMode;
|
|
134
|
-
pid: number | undefined;
|
|
135
|
-
});
|
|
136
|
-
static createExclusively(options: ServerOptions | undefined): Promise<ServerState>;
|
|
137
|
-
static fromServerDump(options?: Pick<ServerOptions, "debug" | "name">): Promise<StatefulServerState | null>;
|
|
138
|
-
static scan(options?: ScanOptions): Promise<ServerStatusV1[]>;
|
|
139
|
-
abstract get databaseDumpPath(): string;
|
|
140
|
-
abstract get pgliteDataDirPath(): string;
|
|
141
|
-
abstract [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
|
|
142
|
-
abstract close(): Promise<void>;
|
|
143
|
-
abstract writeServerDump(exports?: Omit<Server, "close">): Promise<void>;
|
|
144
|
-
}
|
|
145
|
-
declare class StatefulServerState extends ServerState {
|
|
146
|
-
#private;
|
|
147
|
-
constructor(options: Omit<ServerOptions, "persistenceMode"> & {
|
|
148
|
-
pid: number | undefined;
|
|
149
|
-
serverDump?: ServerDumpV1;
|
|
150
|
-
});
|
|
151
|
-
static getServerDumpPath(dataDirPath: string): string;
|
|
152
|
-
get databaseDumpPath(): string;
|
|
153
|
-
get exports(): Exports | undefined;
|
|
154
|
-
get pgliteDataDirPath(): string;
|
|
155
|
-
[PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
|
|
156
|
-
close(): Promise<void>;
|
|
157
|
-
writeServerDump(exports?: Exports): Promise<void>;
|
|
158
|
-
}
|
|
159
|
-
interface ServerStatusV1 extends ServerDumpV1 {
|
|
160
|
-
status: "running" | "starting_up" | "not_running" | "no_such_server" | "unknown" | "error";
|
|
161
|
-
}
|
|
162
|
-
declare class ServerStateAlreadyExistsError extends Error {
|
|
163
|
-
name: string;
|
|
164
|
-
constructor(name: string);
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
interface DBServer {
|
|
168
|
-
close(): Promise<void>;
|
|
169
|
-
readonly connectionLimit: number;
|
|
170
|
-
readonly connectionString: string;
|
|
171
|
-
readonly connectTimeout: number;
|
|
172
|
-
readonly database: string;
|
|
173
|
-
dump(destinationPath: string): Promise<void>;
|
|
174
|
-
readonly maxIdleConnectionLifetime: number;
|
|
175
|
-
readonly password: string;
|
|
176
|
-
readonly poolTimeout: number;
|
|
177
|
-
readonly port: number;
|
|
178
|
-
readonly prismaORMConnectionString: string;
|
|
179
|
-
readonly socketTimeout: number;
|
|
180
|
-
readonly sslMode: string;
|
|
181
|
-
readonly terminalCommand: string;
|
|
182
|
-
readonly username: string;
|
|
183
|
-
}
|
|
184
|
-
interface DBDump {
|
|
185
|
-
dumpPath: string;
|
|
186
|
-
}
|
|
187
|
-
type DBServerPurpose = "database" | "shadow_database";
|
|
188
|
-
declare function startDBServer(purpose: DBServerPurpose, serverState: ServerState): Promise<DBServer>;
|
|
189
|
-
type DumpDBOptions<D extends string> = {
|
|
190
|
-
dataDir: string;
|
|
191
|
-
db?: never;
|
|
192
|
-
debug?: boolean;
|
|
193
|
-
destinationPath?: D;
|
|
194
|
-
} | {
|
|
195
|
-
dataDir?: never;
|
|
196
|
-
db: PGlite;
|
|
197
|
-
debug?: boolean;
|
|
198
|
-
destinationPath?: D;
|
|
199
|
-
};
|
|
200
|
-
declare function dumpDB<D extends string = never>(options: DumpDBOptions<D>): Promise<[D] extends [never] ? string : void>;
|
|
201
|
-
|
|
202
|
-
export { DEFAULT_DATABASE_PORT as D, type Exports as E, type PortAssignableService as P, type ResolvedServerOptions as R, type ServerOptions as S, type Server as a, DEFAULT_SERVER_PORT as b, DEFAULT_SHADOW_DATABASE_PORT as c, PortNotAvailableError as d, type ServerDumpV1 as e, type PersistenceMode as f, type ScanOptions as g, ServerState as h, type ServerStatusV1 as i, ServerStateAlreadyExistsError as j, type DBServer as k, type DBDump as l, type DBServerPurpose as m, type DumpDBOptions as n, dumpDB as o, startDBServer as s, unstable_startServer as u };
|
package/dist/db-B1_DGnTu.d.ts
DELETED
|
@@ -1,202 +0,0 @@
|
|
|
1
|
-
import { PGlite } from '@electric-sql/pglite';
|
|
2
|
-
import * as valibot from 'valibot';
|
|
3
|
-
import { InferOutput } from 'valibot';
|
|
4
|
-
|
|
5
|
-
declare const DEFAULT_DATABASE_PORT = 51214;
|
|
6
|
-
declare const DEFAULT_SERVER_PORT = 51213;
|
|
7
|
-
declare const DEFAULT_SHADOW_DATABASE_PORT = 51215;
|
|
8
|
-
type PortAssignableService = DBServerPurpose | "server";
|
|
9
|
-
declare class PortNotAvailableError extends Error {
|
|
10
|
-
port: number;
|
|
11
|
-
service: PortAssignableService;
|
|
12
|
-
name: string;
|
|
13
|
-
constructor(port: number, service: PortAssignableService);
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
interface Server extends Exports {
|
|
17
|
-
close(): Promise<void>;
|
|
18
|
-
}
|
|
19
|
-
declare function unstable_startServer(options?: ServerOptions): Promise<Server>;
|
|
20
|
-
|
|
21
|
-
declare const exportsSchema: valibot.ObjectSchema<{
|
|
22
|
-
readonly database: valibot.ObjectSchema<{
|
|
23
|
-
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
24
|
-
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
|
|
25
|
-
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
|
|
26
|
-
}, undefined>;
|
|
27
|
-
readonly http: valibot.ObjectSchema<{
|
|
28
|
-
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
29
|
-
}, undefined>;
|
|
30
|
-
readonly ppg: valibot.ObjectSchema<{
|
|
31
|
-
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
32
|
-
}, undefined>;
|
|
33
|
-
readonly shadowDatabase: valibot.ObjectSchema<{
|
|
34
|
-
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
35
|
-
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
|
|
36
|
-
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
|
|
37
|
-
}, undefined>;
|
|
38
|
-
}, undefined>;
|
|
39
|
-
type Exports = InferOutput<typeof exportsSchema>;
|
|
40
|
-
declare const serverDumpV1Schema: valibot.ObjectSchema<{
|
|
41
|
-
readonly databasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
|
|
42
|
-
readonly exports: valibot.OptionalSchema<valibot.ObjectSchema<{
|
|
43
|
-
readonly database: valibot.ObjectSchema<{
|
|
44
|
-
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
45
|
-
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
|
|
46
|
-
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
|
|
47
|
-
}, undefined>;
|
|
48
|
-
readonly http: valibot.ObjectSchema<{
|
|
49
|
-
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
50
|
-
}, undefined>;
|
|
51
|
-
readonly ppg: valibot.ObjectSchema<{
|
|
52
|
-
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
53
|
-
}, undefined>;
|
|
54
|
-
readonly shadowDatabase: valibot.ObjectSchema<{
|
|
55
|
-
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
|
|
56
|
-
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
|
|
57
|
-
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
|
|
58
|
-
}, undefined>;
|
|
59
|
-
}, undefined>, undefined>;
|
|
60
|
-
readonly name: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
|
|
61
|
-
readonly pid: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 0, undefined>]>, undefined>;
|
|
62
|
-
readonly port: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
|
|
63
|
-
readonly shadowDatabasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
|
|
64
|
-
readonly version: valibot.LiteralSchema<"1", undefined>;
|
|
65
|
-
}, undefined>;
|
|
66
|
-
type ServerDumpV1 = InferOutput<typeof serverDumpV1Schema>;
|
|
67
|
-
interface ServerOptions {
|
|
68
|
-
/**
|
|
69
|
-
* The port the database server will listen on.
|
|
70
|
-
*
|
|
71
|
-
* Defaults to `51214`.
|
|
72
|
-
*
|
|
73
|
-
* An error is thrown if the port is already in use.
|
|
74
|
-
*/
|
|
75
|
-
databasePort?: number;
|
|
76
|
-
/**
|
|
77
|
-
* Whether to enable debug logging.
|
|
78
|
-
*
|
|
79
|
-
* Defaults to `false`.
|
|
80
|
-
*/
|
|
81
|
-
debug?: boolean;
|
|
82
|
-
/**
|
|
83
|
-
* Whether to run the server in dry run mode.
|
|
84
|
-
*
|
|
85
|
-
* Defaults to `false`.
|
|
86
|
-
*/
|
|
87
|
-
dryRun?: boolean;
|
|
88
|
-
/**
|
|
89
|
-
* The name of the server.
|
|
90
|
-
*
|
|
91
|
-
* Defaults to `default`.
|
|
92
|
-
*/
|
|
93
|
-
name?: string;
|
|
94
|
-
/**
|
|
95
|
-
* The persistence mode of the server.
|
|
96
|
-
*
|
|
97
|
-
* Default is `stateless`.
|
|
98
|
-
*/
|
|
99
|
-
persistenceMode?: PersistenceMode;
|
|
100
|
-
/**
|
|
101
|
-
* The port the server will listen on.
|
|
102
|
-
*
|
|
103
|
-
* Defaults to `51213`.
|
|
104
|
-
*
|
|
105
|
-
* An error is thrown if the port is already in use.
|
|
106
|
-
*/
|
|
107
|
-
port?: number;
|
|
108
|
-
/**
|
|
109
|
-
* The port the shadow database server will listen on.
|
|
110
|
-
*
|
|
111
|
-
* Defaults to `51215`.
|
|
112
|
-
*
|
|
113
|
-
* An error is thrown if the port is already in use.
|
|
114
|
-
*/
|
|
115
|
-
shadowDatabasePort?: number;
|
|
116
|
-
}
|
|
117
|
-
type ResolvedServerOptions = Required<ServerOptions>;
|
|
118
|
-
type PersistenceMode = "stateless" | "stateful";
|
|
119
|
-
interface ScanOptions {
|
|
120
|
-
debug?: boolean;
|
|
121
|
-
}
|
|
122
|
-
declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
|
|
123
|
-
declare abstract class ServerState implements ResolvedServerOptions {
|
|
124
|
-
readonly databasePort: number;
|
|
125
|
-
readonly debug: boolean;
|
|
126
|
-
readonly dryRun: boolean;
|
|
127
|
-
readonly name: string;
|
|
128
|
-
readonly persistenceMode: PersistenceMode;
|
|
129
|
-
readonly pid: number | undefined;
|
|
130
|
-
readonly port: number;
|
|
131
|
-
readonly shadowDatabasePort: number;
|
|
132
|
-
protected constructor(options: Omit<ServerOptions, "persistenceMode"> & {
|
|
133
|
-
persistenceMode: PersistenceMode;
|
|
134
|
-
pid: number | undefined;
|
|
135
|
-
});
|
|
136
|
-
static createExclusively(options: ServerOptions | undefined): Promise<ServerState>;
|
|
137
|
-
static fromServerDump(options?: Pick<ServerOptions, "debug" | "name">): Promise<StatefulServerState | null>;
|
|
138
|
-
static scan(options?: ScanOptions): Promise<ServerStatusV1[]>;
|
|
139
|
-
abstract get databaseDumpPath(): string;
|
|
140
|
-
abstract get pgliteDataDirPath(): string;
|
|
141
|
-
abstract [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
|
|
142
|
-
abstract close(): Promise<void>;
|
|
143
|
-
abstract writeServerDump(exports?: Omit<Server, "close">): Promise<void>;
|
|
144
|
-
}
|
|
145
|
-
declare class StatefulServerState extends ServerState {
|
|
146
|
-
#private;
|
|
147
|
-
constructor(options: Omit<ServerOptions, "persistenceMode"> & {
|
|
148
|
-
pid: number | undefined;
|
|
149
|
-
serverDump?: ServerDumpV1;
|
|
150
|
-
});
|
|
151
|
-
static getServerDumpPath(dataDirPath: string): string;
|
|
152
|
-
get databaseDumpPath(): string;
|
|
153
|
-
get exports(): Exports | undefined;
|
|
154
|
-
get pgliteDataDirPath(): string;
|
|
155
|
-
[PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
|
|
156
|
-
close(): Promise<void>;
|
|
157
|
-
writeServerDump(exports?: Exports): Promise<void>;
|
|
158
|
-
}
|
|
159
|
-
interface ServerStatusV1 extends ServerDumpV1 {
|
|
160
|
-
status: "running" | "starting_up" | "not_running" | "no_such_server" | "unknown" | "error";
|
|
161
|
-
}
|
|
162
|
-
declare class ServerStateAlreadyExistsError extends Error {
|
|
163
|
-
name: string;
|
|
164
|
-
constructor(name: string);
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
interface DBServer {
|
|
168
|
-
close(): Promise<void>;
|
|
169
|
-
readonly connectionLimit: number;
|
|
170
|
-
readonly connectionString: string;
|
|
171
|
-
readonly connectTimeout: number;
|
|
172
|
-
readonly database: string;
|
|
173
|
-
dump(destinationPath: string): Promise<void>;
|
|
174
|
-
readonly maxIdleConnectionLifetime: number;
|
|
175
|
-
readonly password: string;
|
|
176
|
-
readonly poolTimeout: number;
|
|
177
|
-
readonly port: number;
|
|
178
|
-
readonly prismaORMConnectionString: string;
|
|
179
|
-
readonly socketTimeout: number;
|
|
180
|
-
readonly sslMode: string;
|
|
181
|
-
readonly terminalCommand: string;
|
|
182
|
-
readonly username: string;
|
|
183
|
-
}
|
|
184
|
-
interface DBDump {
|
|
185
|
-
dumpPath: string;
|
|
186
|
-
}
|
|
187
|
-
type DBServerPurpose = "database" | "shadow_database";
|
|
188
|
-
declare function startDBServer(purpose: DBServerPurpose, serverState: ServerState): Promise<DBServer>;
|
|
189
|
-
type DumpDBOptions<D extends string> = {
|
|
190
|
-
dataDir: string;
|
|
191
|
-
db?: never;
|
|
192
|
-
debug?: boolean;
|
|
193
|
-
destinationPath?: D;
|
|
194
|
-
} | {
|
|
195
|
-
dataDir?: never;
|
|
196
|
-
db: PGlite;
|
|
197
|
-
debug?: boolean;
|
|
198
|
-
destinationPath?: D;
|
|
199
|
-
};
|
|
200
|
-
declare function dumpDB<D extends string = never>(options: DumpDBOptions<D>): Promise<[D] extends [never] ? string : void>;
|
|
201
|
-
|
|
202
|
-
export { DEFAULT_DATABASE_PORT as D, type Exports as E, type PortAssignableService as P, type ResolvedServerOptions as R, type ServerOptions as S, type Server as a, DEFAULT_SERVER_PORT as b, DEFAULT_SHADOW_DATABASE_PORT as c, PortNotAvailableError as d, type ServerDumpV1 as e, type PersistenceMode as f, type ScanOptions as g, ServerState as h, type ServerStatusV1 as i, ServerStateAlreadyExistsError as j, type DBServer as k, type DBDump as l, type DBServerPurpose as m, type DumpDBOptions as n, dumpDB as o, startDBServer as s, unstable_startServer as u };
|