@prisma/dev 0.0.0-dev.202506121448 → 0.0.0-dev.202506132343
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-RCTKDIXK.js +3 -0
- package/dist/index.cjs +6 -6
- package/dist/index.js +4 -4
- package/dist/state.cjs +3 -3
- package/dist/state.d.cts +11 -7
- package/dist/state.d.ts +11 -7
- package/dist/state.js +1 -1
- package/package.json +3 -2
- package/dist/chunk-LBY4H4LD.js +0 -3
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{b as c,f as E,g as $,h as k,i as R,j as M,k as A}from"./chunk-Q3M6SQC2.js";import{writeFile as H}from"fs/promises";import{hc as Y}from"hono/client";import{join as u}from"pathe";import{check as Z,lock as q}from"proper-lockfile";import{process as N}from"std-env";import{integer as L,literal as z,minLength as K,minValue as F,number as J,object as f,optional as m,parseJson as W,pipe as l,safeParse as G,string as b,url as Q}from"valibot";import{process as C}from"std-env";function I(r,e){if(r==null)return!1;try{return C.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}var y=l(b(),Q()),T=f({connectionString:y,prismaORMConnectionString:m(y),terminalCommand:m(b())}),V=f({url:y}),S=l(J(),L(),F(1)),X=f({database:T,http:V,ppg:V,shadowDatabase:T}),ee=f({databasePort:S,exports:m(X),name:l(b(),K(1)),pid:m(l(J(),L(),F(0))),port:S,shadowDatabasePort:S,version:z("1")}),_=Symbol("initialize"),D="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??D,this.persistenceMode=e.persistenceMode,this.pid=e.pid??N.pid,this._port=e.port??51213,this._shadowDatabasePort=e.shadowDatabasePort??51215}static async createExclusively(e){let t=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new p(e):new w(e);return await t[_](),t}static async fromServerDump(e){let{debug:t,name:o=D}=e??{},s=c(o),a=p.getServerDumpPath(s),i=await E(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:h,output:n,success:g}=G(l(b(),W(),ee),i);if(!g)throw t&&console.debug(`[State] Invalid server dump file at "${a}":
|
|
2
|
+
${JSON.stringify(h,null,2)}`),new Error(`Invalid Prisma Dev state for "${o}".`);return new p({databasePort:n.databasePort,debug:t,dryRun:!1,name:o,pid:n.pid,port:n.port,serverDump:n,shadowDatabasePort:n.shadowDatabasePort})}static async scan(e){let{debug:t}=e??{},o=u(c(D),"..");t&&console.debug(`[State] scanning for server states in: ${o}`);let s=await k(o);return t&&console.debug(`[State] found server names: ${JSON.stringify(s)}`),await Promise.all(s.map(a=>te(a,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},w=class extends d{constructor(e){super({...e,persistenceMode:"stateless"})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[_](){}async close(){}async writeServerDump(){}},p=class r extends d{#t;#e;#a;#o;#r;#s=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=c(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[_](){await $(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#s=await q(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 O(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:N.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await H(this.#o,`${JSON.stringify(this.#r,null,2)}
|
|
3
|
+
`,{encoding:"utf-8"})}};async function te(r,e){let{debug:t,onlyMetadata:o}=e||{},s={databasePort:-1,exports:void 0,name:r,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let a=await d.fromServerDump({debug:t,name:r});if(!a)return t&&console.debug(`[State] no server state found for name: ${r}`),{...s,status:"no_such_server"};s.databasePort=a.databasePort,s.exports=a.exports,s.pid=a.pid,s.port=a.port,s.shadowDatabasePort=a.shadowDatabasePort;let{exports:i,pid:h}=a;if(o)return{...s,status:"unknown"};if(!I(h,t))return t&&console.debug(`[State] server state for "${r}" has no running process with PID: ${h}`),{...s,status:"not_running"};let n=c(r);try{if(!await Z(n,{lockfilePath:u(n,".lock")}))return t&&console.debug(`[State] server state for "${r}" is not locked, indicating it is not running.`),{...s,status:"starting_up"}}catch(U){t&&console.error(`[State] server state for "${r}" failed to check lock:`,U)}if(!i)return{...s,status:"starting_up"};let{http:g}=i,P=await Y(g.url).health.$get();if(!P.ok)return t&&console.debug(`[State] server state for "${r}" is not live: ${JSON.stringify(P)}`),{...s,status:"not_running"};let v=await P.json();return v.name!==r?(t&&console.debug(`[State] server state for "${r}" has mismatched health response: ${JSON.stringify(v)}`),{...s,status:"unknown"}):(t&&console.debug(`[State] server state for "${r}" is live: ${JSON.stringify(v)}`),{...s,status:"running"})}catch(a){return t&&console.error(`[State] failed to get server status for "${r}":`,a),{...s,status:"error"}}}var x=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},O=class extends x{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return d.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};export{d as a,x as b,O as c};
|
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";var pt=Object.create;var N=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var gt=Object.getOwnPropertyNames;var ht=Object.getPrototypeOf,ft=Object.prototype.hasOwnProperty;var yt=(t,e)=>{for(var r in e)N(t,r,{get:e[r],enumerable:!0})},me=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of gt(e))!ft.call(t,o)&&o!==r&&N(t,o,{get:()=>e[o],enumerable:!(n=mt(e,o))||n.enumerable});return t};var _=(t,e,r)=>(r=t!=null?pt(ht(t)):{},me(e||!t||!t.__esModule?N(r,"default",{value:t,enumerable:!0}):r,t)),St=t=>me(N({},"__esModule",{value:!0}),t);var Ft={};yt(Ft,{DEFAULT_DATABASE_PORT:()=>Re,DEFAULT_SERVER_PORT:()=>Ae,DEFAULT_SHADOW_DATABASE_PORT:()=>Oe,PortNotAvailableError:()=>E,ServerAlreadyRunningError:()=>L,unstable_startServer:()=>Nt});module.exports=St(Ft);var D=require("hono/http-exception"),l=require("valibot"),ge=/^(postgres|postgresql):\/\//,bt=(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)(ge)),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)(ge))}));function he(t){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([[e],[r]])=>e.localeCompare(r)))),"utf8").toString("base64url")}function vt(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:n,success:o}=(0,l.safeParse)(bt,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]=vt(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:dt,port:ut}=new URL(b),lt=e.get("shadowDBPort");if(S!=="localhost"||Number(M)!==W||dt!=="localhost"||Number(ut)!==lt)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"),$e=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,wt=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)}},Pt=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)}},Dt=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"?wt(t):F.default.platform==="win32"?Pt(t):Dt(t)}var fe=require("pako"),ye=Y("prisma-dev");function Se(t,e){return`${ye.cache}/engine/${t}/${e}`}function I(t){return`${ye.data}/${t}`}async function be(t){try{return await(0,y.access)(t,y.constants.F_OK),!0}catch(e){if(Z(e))return!1;throw e}}async function ve(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(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 Pe(t){try{return await(0,y.readFile)(t,{encoding:"utf-8"})}catch(e){if(Z(e))return null;throw e}}async function De(t){await(0,y.mkdir)(t,{recursive:!0})}async function Ee(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 Re=51214,Ae=51213,Oe=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"},Et=`postgres://${g.username}:${g.password}@localhost`,Ie=new URLSearchParams({sslmode:g.sslMode}),Rt=new URLSearchParams({...Object.fromEntries(Ie.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 xe(t,e,{db:null,port:r,server:null});let{debug:n}=e,s=await(t==="shadow_database"?At:Ce)(e.pgliteDataDirPath,n);n&&s.onNotification((a,c)=>{console.debug(`[${t}][${a}] ${c}`)});let i=new $e.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 xe(t,e,{db:s,port:r,server:i})}function xe(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,Ie),dump:async a=>{t==="shadow_database"||!o||await Ot({db:o,debug:n,destinationPath:a})},port:s,prismaORMConnectionString:Te(s,Rt),terminalCommand:`PGPASSWORD=${g.password} PGSSLMODE=${g.sslMode} psql -h localhost -p ${s} -U ${g.username} -d ${g.database}`}}function Te(t,e){return`${Et}:${t}/${g.database}?${e.toString()}`}async function Ce(t,e){return await ee.PGlite.create({database:g.database,dataDir:t,debug:e?5:void 0,relaxedDurability:!1,username:g.username})}async function At(t,e){return await ee.PGlite.create({database:g.database,dataDir:"memory://",debug:e?5:void 0,relaxedDurability:!1,username:g.username})}async function Ot(t){let{dataDir:e,db:r,debug:n,destinationPath:o}=t,s=r||await Ce(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 Xe=require("http"),Ye=require("util"),Ze=require("@hono/node-server"),et=_(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 tt=require("hono/logger"),se=require("hono/tiny");var Je=require("hono/tiny"),$=require("hono/validator");var f=require("valibot"),xt=(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 ke(t){let{output:e,success:r}=(0,f.safeParse)(xt,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var Be=require("child_process"),je=require("events"),Le=require("fs/promises"),Me=require("path"),Ne=require("timers/promises");var Fe=require("foreground-child/proxy-signals"),Ue=require("std-env");var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Tt,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:$t,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:He}=Ue.process.env,T=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 x.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 x.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=$t||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=(0,Be.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,Fe.proxySignals)(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let i=m=>{let b=m.split(`
|
|
2
|
-
`).find(
|
|
3
|
-
Received data: ${m}`));
|
|
1
|
+
"use strict";var pt=Object.create;var M=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var gt=Object.getOwnPropertyNames;var ht=Object.getPrototypeOf,ft=Object.prototype.hasOwnProperty;var yt=(t,e)=>{for(var r in e)M(t,r,{get:e[r],enumerable:!0})},fe=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of gt(e))!ft.call(t,n)&&n!==r&&M(t,n,{get:()=>e[n],enumerable:!(o=mt(e,n))||o.enumerable});return t};var $=(t,e,r)=>(r=t!=null?pt(ht(t)):{},fe(e||!t||!t.__esModule?M(r,"default",{value:t,enumerable:!0}):r,t)),St=t=>fe(M({},"__esModule",{value:!0}),t);var Ft={};yt(Ft,{DEFAULT_DATABASE_PORT:()=>U,DEFAULT_SERVER_PORT:()=>V,DEFAULT_SHADOW_DATABASE_PORT:()=>G,PortNotAvailableError:()=>P,ServerAlreadyRunningError:()=>L,unstable_startServer:()=>Nt});module.exports=St(Ft);var E=require("hono/http-exception"),l=require("valibot"),ye=/^(postgres|postgresql):\/\//,bt=(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)(ye)),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)(ye))}));function Se(t){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([[e],[r]])=>e.localeCompare(r)))),"utf8").toString("base64url")}function vt(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:o,success:n}=(0,l.safeParse)(bt,e,{abortEarly:!0});return n?[null,o]:[r]}var R=(t,e)=>{let{authorization:r}=t;if(!r)throw new E.HTTPException(401,{message:"Missing API Key"});let[o,n="",s]=r.split(" ");if(o!=="Bearer"||s)throw new E.HTTPException(401,{message:"Invalid API Key"});let[a,i]=vt(n);if(a)throw new E.HTTPException(401,{message:"Invalid API Key",cause:a.join(", ")});let{databaseUrl:u,name:m,shadowDatabaseUrl:v}=i,{name:y}=e.get("serverState");if(!m)throw new E.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 "${y}" server's output for the updated \`DATABASE_URL\` value.`});if(m!==y)throw new E.HTTPException(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${y}", but the API Key is for "${m}"`});let{hostname:S,port:j}=new URL(u),{port:X}=e.get("db"),{hostname:ut,port:dt}=new URL(v),lt=e.get("shadowDBPort");if(S!=="localhost"||Number(j)!==X||ut!=="localhost"||Number(dt)!==lt)throw new E.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:i}};var re=require("@electric-sql/pglite"),_e=require("@electric-sql/pglite-socket"),$e=require("pathe/utils");var F=require("fs"),b=require("fs/promises");var p=$(require("path"),1),Y=$(require("os"),1),N=$(require("process"),1),w=Y.default.homedir(),Z=Y.default.tmpdir(),{env:O}=N.default,wt=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(Z,t)}},Pt=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(Z,t)}},Dt=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(Z,e,t)}};function ee(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"?Pt(t):Dt(t)}var be=require("pako"),ve=ee("prisma-dev");function we(t,e){return`${ve.cache}/engine/${t}/${e}`}function I(t){return`${ve.data}/${t}`}async function Pe(t){try{return await(0,b.access)(t,b.constants.F_OK),!0}catch(e){if(te(e))return!1;throw e}}async function De(t,e){let r=(0,be.inflate)(t);await(0,b.writeFile)(e,r),await(0,b.chmod)(e,"755")}async function Ee(t,e){await t.stream().pipeTo(F.WriteStream.toWeb((0,F.createWriteStream)(e,{encoding:"utf-8"})))}function te(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function Ae(t){try{return await(0,b.readFile)(t,{encoding:"utf-8"})}catch(e){if(te(e))return null;throw e}}async function Re(t){await(0,b.mkdir)(t,{recursive:!0})}async function Oe(t){try{return(await(0,b.readdir)(t,{withFileTypes:!0})).reduce((r,o)=>(o.isDirectory()&&!o.name.startsWith(".")&&r.push(o.name),r),[])}catch(e){if(te(e))return[];throw e}}var U=51214,V=51213,G=51215,P=class extends Error{constructor(r,o){super(`Port number \`${r}\` is not available for service ${o}.`);this.port=r;this.service=o}name="PortNotAvailableError"};var g={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},Et=`postgres://${g.username}:${g.password}@localhost`,Ie=new URLSearchParams({sslmode:g.sslMode}),At=new URLSearchParams({...Object.fromEntries(Ie.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 ne(t,e){let r=t==="database"?e.databasePort:e.shadowDatabasePort;if(e.dryRun)return Te(t,e,{db:null,port:r,server:null});let{debug:o}=e,s=await(t==="shadow_database"?Rt:Ce)(e.pgliteDataDirPath,o);o&&s.onNotification((i,u)=>{console.debug(`[${t}][${i}] ${u}`)});let a=new _e.PGLiteSocketServer({db:s,debug:o,inspect:o,port:r});o&&(a.addEventListener("listening",i=>{let{detail:u}=i;console.debug(`[${t}] server listening on ${JSON.stringify(u)}`)}),a.addEventListener("connection",i=>{let{clientAddress:u,clientPort:m}=i.detail;console.debug(`[${t}] client connected from ${u}:${m}`)}),a.addEventListener("error",i=>{let{detail:u}=i;console.error(`[${t}] server error:`,u)}));try{await a.start()}catch(i){throw i instanceof Error&&"code"in i&&i.code==="EADDRINUSE"?new P(r,t):i}return Te(t,e,{db:s,port:r,server:a})}function Te(t,e,r){let{debug:o}=e,{db:n,port:s,server:a}=r||{};return o&&console.debug(`[${t}] server started on port ${s}`),{...g,close:async()=>{let i=[];try{await a?.stop(),o&&console.debug(`[${t}] server stopped on port ${s}`)}catch(u){console.error(`[${t}] server stop error`,u),i.push(u)}if(t==="database")try{await n?.syncToFs(),o&&console.debug(`[${t}] synced to filesystem`)}catch(u){console.error(`[${t}] sync error`,u),i.push(u)}try{await n?.close(),o&&console.debug(`[${t}] closed`)}catch(u){console.error(`[${t}] close error`,u),i.push(u)}if(i.length>0)throw new AggregateError(i,`Failed to close ${t} properly`)},connectionString:xe(s,Ie),dump:async i=>{t==="shadow_database"||!n||await Ot({db:n,debug:o,destinationPath:i})},port:s,prismaORMConnectionString:xe(s,At),terminalCommand:`PGPASSWORD=${g.password} PGSSLMODE=${g.sslMode} psql -h localhost -p ${s} -U ${g.username} -d ${g.database}`}}function xe(t,e){return`${Et}:${t}/${g.database}?${e.toString()}`}async function Ce(t,e){return await re.PGlite.create({database:g.database,dataDir:t,debug:e?5:void 0,relaxedDurability:!1,username:g.username})}async function Rt(t,e){return await re.PGlite.create({database:g.database,dataDir:"memory://",debug:e?5:void 0,relaxedDurability:!1,username:g.username})}async function Ot(t){let{dataDir:e,db:r,debug:o,destinationPath:n}=t,s=r||await Ce(e,o),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),i=await a({args:["--schema-only","--no-owner"],fileName:n?(0,$e.filename)(n):void 0,pg:await s.clone()});return n?(o&&console.debug(`[DB] Dumping database to ${n}`),await Ee(i,n)):(o&&console.debug("[DB] Dumping database to memory"),await i.text())}var Xe=require("http"),Ye=require("util"),Ze=require("@hono/node-server"),et=$(require("@prisma/get-platform"),1);function q(t){let e,r,o=new Promise((a,i)=>{e=a,r=i}),n=a=>{n=s=null,r(a),t?.onRejected?.(a),t?.onFulfilled?.()},s=a=>{s=n=null,e(a),t?.onResolved?.(a),t?.onFulfilled?.()};return{isFulfilled:()=>s===n,promise:o,reject:a=>n?.(a),resolve:a=>s?.(a)}}var tt=require("hono/logger"),ie=require("hono/tiny");var Je=require("hono/tiny"),_=require("hono/validator");var f=require("valibot"),Tt=(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 ke(t){let{output:e,success:r}=(0,f.safeParse)(Tt,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var Be=require("child_process"),Le=require("events"),je=require("fs/promises"),Me=require("path"),Ne=require("timers/promises");var Fe=require("foreground-child/proxy-signals"),Ue=require("std-env");var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:xt,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:_t,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:He}=Ue.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,o=`${e.schemaHash}:${e.clientVersion}`;try{let n=t.#r.get(o);if(n)return n;let s=new t(e);return t.#r.set(o,s),r&&console.debug("[Query Engine] starting...",e),await s.start(),r&&console.debug("[Query Engine] started!"),s}finally{t.stopAll(o)}}static async stopAll(e){let o=(await Promise.allSettled(Array.from(t.#r.entries()).filter(([n])=>n!==e).map(async([n,s])=>{try{await s.stop()}finally{t.#r.delete(n)}}))).filter(n=>n.status==="rejected").map(n=>n.reason);if(o.length>0)throw new AggregateError(o,"Failed to stop engines")}async commitTransaction(e,r){return await this.#i(e,r,"commit")}async request(e,r){let{url:o}=await this.start(),n=this.#a(r),s=await fetch(o,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...n,"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.#i(e,r,"rollback")}async startTransaction(e,r){let{url:o}=await this.start(),n=this.#a(r),s=await fetch(`${o}/transaction/start`,{body:JSON.stringify(e),headers:{...n,"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:o}=q();this.#t=e;let n=_t||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",n);let s=(0,Be.spawn)(n,["--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,Fe.proxySignals)(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let a=m=>{let v=m.split(`
|
|
2
|
+
`).find(X=>X.includes("Started query engine http server"));if(!v)return;s.stdout.removeListener("data",a);let{fields:y}=JSON.parse(v);if(y==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${m}`));let{ip:S,port:j}=y;if(S==null||j==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}`));o({childProcess:s,url:`http://${S}:${j}`})},i=m=>{this.#t=null,r(new C(String(m))),s.removeListener("exit",u),s.kill()};s.once("error",i);let u=(m,v)=>{this.#t=null,r(new C(`Query Engine exited with code ${m} and signal ${v}`))};return s.once("exit",u),s.stdout.on("data",a),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,Le.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=we(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,je.mkdir)(r,{recursive:!0});let{platform:o}=this.#e.platform,n=o==="windows"?".exe":"",s=(0,Me.join)(r,`query-engine-${o}${n}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(xt==="1"||await Pe(s)===!1)&&await this.#o({commitHash:e,extension:n,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 o=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!o)throw new Error("Couldn't find engines version in package.json");let n=o.split(".").at(-1);if(!n)throw new Error("Couldn't find commit hash in engines version");return n}async#o(e){let{commitHash:r,extension:o,engineBinaryPath:n}=e,{binaryTarget:s}=this.#e.platform,a=`https://binaries.prisma.sh/all_commits/${r}/${s}/query-engine${o}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",a);let i=await fetch(a);if(!i.ok)throw new Error(`Couldn't download engine. URL: ${a}, status code: ${i.status}`);He&&await(0,Ne.setTimeout)(Number(He)),await De(await i.arrayBuffer(),n),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",n)}#a(e){let r={};for(let[o,n]of Object.entries(e))n!=null&&(r[o]=n);return r}async#i(e,r,o){let{url:n}=await this.#t,s=this.#a(r),a=await fetch(`${n}/transaction/${e}/${o}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!a.ok)throw await T.fromResponse(a);try{return await a.json()}catch{return{}}}};function K(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,o,n){super(`${r}: Query Engine response status ${o}, body: ${n}`);this.action=r;this.statusCode=o;this.responseBody=n}name="EngineHttpError";static async fromResponse(r){let o=new URL(r.url),n=await r.text();return new t(o.pathname,r.status,n)}};var oe=require("buffer"),J=new Map;async function se(t){let r=new TextEncoder().encode(t),o=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o)).map(a=>a.toString(16).padStart(2,"0")).join("")}function Ve(t){let e=t.req.param("schemaHash"),r=J.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 Ge(t,e){let r=oe.Buffer.from(t,"base64").toString("utf8"),o=`datasource db {
|
|
4
4
|
provider = "postgresql"
|
|
5
5
|
url = "${e.toString()}"
|
|
6
|
-
}`,
|
|
7
|
-
${JSON.stringify(
|
|
8
|
-
`,{encoding:"utf-8"})}};async function Mt(t,e){let
|
|
6
|
+
}`,n=r.replace($t,o),s=await se(n);return{base64Override:oe.Buffer.from(n,"utf8").toString("base64"),overrideHash:s}}function Q(t){let{req:e}=t;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}var d=require("valibot"),It=(0,d.object)({isolation_level:(0,d.optional)((0,d.string)()),max_wait:(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(0)),timeout:(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(0))});async function qe(t){let{issues:e,output:r,success:o}=(0,d.safeParse)(It,await t.req.json(),{abortEarly:!0});return o?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}var Ct=(0,d.looseObject)({id:(0,d.union)([(0,d.string)(),(0,d.number)()])});function Ke(t,e){let{output:r,success:o}=(0,d.safeParse)(Ct,t);return o?r:e.json({EngineMalfunction:{}},500)}var k=new Je.Hono;k.post("/invalidate",(0,_.validator)("header",R),async t=>{let e=await ke(t);return e instanceof Response?e:t.body(null)});var kt="/:clientVersion/:schemaHash",H=k.basePath(kt);k.route("/",H);var Ht=["/graphql","/itx/:transactionId/graphql"];H.on("POST",[...Ht],(0,_.validator)("header",R),async t=>{let{req:e}=t;try{let r=await ae(t);if(r instanceof Response)return r;let o=await e.text(),n=e.param("transactionId"),s=await r.request(o,{...Q(t),"X-transaction-id":n});return t.text(s)}catch(r){return K(r,t)}});H.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,_.validator)("header",R),async t=>{let{req:e}=t;try{let r=await ae(t);if(r instanceof Response)return r;let n=`${e.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=e.param("transactionId"),a=await r[n](s,Q(t));return t.json(a)}catch(r){return K(r,t)}});H.put("/schema",(0,_.validator)("header",R),async t=>{let{req:e}=t,r=await e.text();if(!r)return t.text("Missing schema",400);let o=e.param("schemaHash"),n=J.get(o);if(n==null){if(o!==await se(r))return t.text("Schema hash mismatch",400);let s=await Ge(r,t.get("db").prismaORMConnectionString);return J.set(o,{base64Original:r,...s}),t.text(o)}return r!==n.base64Original?t.text("Schema mismatch",400):t.text(o)});H.post("/transaction/start",(0,_.validator)("header",R),async t=>{let{req:e}=t,r=await qe(t);if(r instanceof Response)return r;try{let o=await ae(t);if(o instanceof Response)return o;let n=await o.startTransaction(r,Q(t)),s=Ke(n,t);if(s instanceof Response)return s;let{id:a}=s,i=e.param("clientVersion"),u=t.get("port"),m=t.get("protocol"),v=e.param("schemaHash");return t.json({...n,"data-proxy":{endpoint:`${m}://localhost:${u}/${i}/${v}/itx/${a}`}})}catch(o){return K(o,t)}});async function ae(t){let{req:e}=t,r=Ve(t);if(r instanceof Response)return r;let{base64Override:o,overrideHash:n}=r.schemas;return await x.get({base64Schema:o,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.param("clientVersion"),debug:t.get("debug"),platform:t.get("platform"),schemaHash:n})}var Qe=require("hono/tiny"),We=require("http-status-codes"),W=new Qe.Hono;W.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},We.StatusCodes.CREATED)});var Ar=W.get("/health",t=>t.json({name:t.get("serverState").name}));async function rt(t,e){let{port:r}=e;if(e.dryRun)return ze(r,null);let o=await Bt(r,t,e),{promise:n,reject:s,resolve:a}=q(),i=(0,Ze.serve)({createServer:Xe.createServer,fetch:o.fetch,overrideGlobalObjects:!1,port:r},a);return i.on("error",u=>{if(typeof u=="object"&&"code"in u&&u.code==="EADDRINUSE")return s(new P(r,"server"));console.error("[Accelerate]",u)}),await n,ze(r,i)}function ze(t,e){return{async close(){e&&await Promise.allSettled([(0,Ye.promisify)(e.close.bind(e))(),x.stopAll()])},port:t,url:`http://localhost:${t}`}}async function Bt(t,e,r){let{debug:o}=r,n=new ie.Hono,s=await et.default.getPlatformInfo();return o&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),o&&n.use("*",(0,tt.logger)((...a)=>console.log("[Accelerate]",...a))),n.use("*",async(a,i)=>(a.set("db",e),a.set("debug",!!o),a.set("platform",s),a.set("port",t),a.set("protocol","http"),a.set("serverState",r),a.set("shadowDBPort",r.shadowDatabasePort),await i())),n.route("/",ce),n}var ce=new ie.Hono;ce.route("/",k);ce.route("/",W);var it=require("fs/promises"),ct=require("hono/client"),A=require("pathe"),z=require("proper-lockfile"),ge=require("std-env"),c=require("valibot");var nt=require("std-env");function ot(t,e){if(t==null)return!1;try{return nt.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var le=(0,c.pipe)((0,c.string)(),(0,c.url)()),st=(0,c.object)({connectionString:le,prismaORMConnectionString:(0,c.optional)(le),terminalCommand:(0,c.optional)((0,c.string)())}),at=(0,c.object)({url:le}),ue=(0,c.pipe)((0,c.number)(),(0,c.integer)(),(0,c.minValue)(1)),Lt=(0,c.object)({database:st,http:at,ppg:at,shadowDatabase:st}),jt=(0,c.object)({databasePort:ue,exports:(0,c.optional)(Lt),name:(0,c.pipe)((0,c.string)(),(0,c.minLength)(1)),pid:(0,c.optional)((0,c.pipe)((0,c.number)(),(0,c.integer)(),(0,c.minValue)(0))),port:ue,shadowDatabasePort:ue,version:(0,c.literal)("1")}),he=Symbol("initialize"),de="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??de,this.persistenceMode=e.persistenceMode,this.pid=e.pid??ge.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):new pe(e);return await r[he](),r}static async fromServerDump(e){let{debug:r,name:o=de}=e??{},n=I(o),s=B.getServerDumpPath(n),a=await Ae(s);if(a==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(a));let{issues:i,output:u,success:m}=(0,c.safeParse)((0,c.pipe)((0,c.string)(),(0,c.parseJson)(),jt),a);if(!m)throw r&&console.debug(`[State] Invalid server dump file at "${s}":
|
|
7
|
+
${JSON.stringify(i,null,2)}`),new Error(`Invalid Prisma Dev state for "${o}".`);return new B({databasePort:u.databasePort,debug:r,dryRun:!1,name:o,pid:u.pid,port:u.port,serverDump:u,shadowDatabasePort:u.shadowDatabasePort})}static async scan(e){let{debug:r}=e??{},o=(0,A.join)(I(de),"..");r&&console.debug(`[State] scanning for server states in: ${o}`);let n=await Oe(o);return r&&console.debug(`[State] found server names: ${JSON.stringify(n)}`),await Promise.all(n.map(s=>Mt(s,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},pe=class extends D{constructor(e){super({...e,persistenceMode:"stateless"})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[he](){}async close(){}async writeServerDump(){}},B=class t extends D{#r;#e;#t;#s;#n;#o=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=I(this.name),this.#r=(0,A.join)(this.#e,"db_dump.bak"),this.#t=(0,A.join)(this.#e,".pglite"),this.#n=e?.serverDump??null,this.#s=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,A.join)(e,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#n?.exports}get pgliteDataDirPath(){return this.#t}async[he](){await Re(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#o=await(0,z.lock)(this.#e,{lockfilePath:(0,A.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:ge.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 Mt(t,e){let{debug:r,onlyMetadata:o}=e||{},n={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let s=await D.fromServerDump({debug:r,name:t});if(!s)return r&&console.debug(`[State] no server state found for name: ${t}`),{...n,status:"no_such_server"};n.databasePort=s.databasePort,n.exports=s.exports,n.pid=s.pid,n.port=s.port,n.shadowDatabasePort=s.shadowDatabasePort;let{exports:a,pid:i}=s;if(o)return{...n,status:"unknown"};if(!ot(i,r))return r&&console.debug(`[State] server state for "${t}" has no running process with PID: ${i}`),{...n,status:"not_running"};let u=I(t);try{if(!await(0,z.check)(u,{lockfilePath:(0,A.join)(u,".lock")}))return r&&console.debug(`[State] server state for "${t}" is not locked, indicating it is not running.`),{...n,status:"starting_up"}}catch(S){r&&console.error(`[State] server state for "${t}" failed to check lock:`,S)}if(!a)return{...n,status:"starting_up"};let{http:m}=a,v=await(0,ct.hc)(m.url).health.$get();if(!v.ok)return r&&console.debug(`[State] server state for "${t}" is not live: ${JSON.stringify(v)}`),{...n,status:"not_running"};let y=await v.json();return y.name!==t?(r&&console.debug(`[State] server state for "${t}" has mismatched health response: ${JSON.stringify(y)}`),{...n,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(y)}`),{...n,status:"running"})}catch(s){return r&&console.error(`[State] failed to get server status for "${t}":`,s),{...n,status:"error"}}}var me=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},L=class extends me{#r;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#r=e}get server(){return D.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};async function Nt(t){let e=await D.createExclusively(t),[r,o]=await Promise.all([ne("database",e),ne("shadow_database",e)]),n=await rt(r,e),s=`prisma+postgres://localhost:${n.port}/?${new URLSearchParams({api_key:Se({databaseUrl:r.prismaORMConnectionString,name:e.name,shadowDatabaseUrl:o.prismaORMConnectionString})}).toString()}`,a={database:{connectionString:r.connectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand},http:{url:n.url},ppg:{url:s},shadowDatabase:{connectionString:o.prismaORMConnectionString,prismaORMConnectionString:o.prismaORMConnectionString,terminalCommand:o.terminalCommand}};return await e.writeServerDump(a),{...a,close:()=>i(e,[n,r,o]),name:e.name};async function i(u,m){let y=(await Promise.allSettled(m.map(S=>S.close()))).filter(S=>S.status==="rejected").map(S=>new Error(S.reason));try{await u.close()}catch(S){y.push(S)}if(y.length>0)throw new AggregateError(y,"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.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{a as
|
|
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:
|
|
3
|
-
Received data: ${c}`));r({childProcess:s,url:`http://${l}:${
|
|
1
|
+
import{a as _}from"./chunk-GBG44OEG.js";import{a as U,c as de}from"./chunk-RCTKDIXK.js";import{a as L,c as M,d as N,i as le,j as ue,k as me,l as D}from"./chunk-Q3M6SQC2.js";import{HTTPException as h}from"hono/http-exception";import{minLength as ge,object as he,optional as fe,parseJson as ye,pipe as R,regex as q,safeParse as we,string as A,url as K}from"valibot";var V=/^(postgres|postgresql):\/\//,Se=R(A(),ye(),he({databaseUrl:R(A(),K(),q(V)),name:fe(R(A(),ge(1))),shadowDatabaseUrl:R(A(),K(),q(V))}));function F(n){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(n).sort(([[e],[t]])=>e.localeCompare(t)))),"utf8").toString("base64url")}function ve(n){let e=Buffer.from(n,"base64url").toString("utf8"),{issues:t,output:r,success:o}=we(Se,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]=ve(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:P}=new URL(p),{port:x}=e.get("db"),{hostname:ae,port:ce}=new URL(g),pe=e.get("shadowDBPort");if(l!=="localhost"||Number(P)!==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 Xe}from"http";import{promisify as Ye}from"util";import{serve as Ze}from"@hono/node-server";import et from"@prisma/get-platform";function T(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 tt}from"hono/logger";import{Hono as se}from"hono/tiny";import{Hono as Qe}from"hono/tiny";import{validator as v}from"hono/validator";import{array as be,literal as Ee,minLength as Pe,object as Re,pipe as Ae,safeParse as Te,string as Oe,union as He}from"valibot";var Ce=Re({tags:He([Ae(be(Oe()),Pe(1)),Ee("all")])});async function Q(n){let{output:e,success:t}=Te(Ce,await n.req.json(),{abortEarly:!0});return t?e:n.text("Invalid input",400)}import{spawn as Ie}from"child_process";import{once as xe}from"events";import{mkdir as De}from"fs/promises";import{join as _e}from"path";import{setTimeout as ke}from"timers/promises";import{proxySignals as $e}from"foreground-child/proxy-signals";import{process as je}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Be,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:Le,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:z}=je.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}=T();this.#t=e;let o=Le||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=Ie(o,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});$e(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let i=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:P}=u;if(l==null||P==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}:${P}`})},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 xe(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=L(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",t),await De(t,{recursive:!0});let{platform:r}=this.#e.platform,o=r==="windows"?".exe":"",s=_e(t,`query-engine-${r}${o}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(Be==="1"||await M(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 ke(Number(z)),await N(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 k(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 Me=/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(Me,r),s=await k(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 Ne,minValue as Y,number as $,object as Ue,optional as qe,pipe as Z,safeParse as ee,string as te,union as Ke}from"valibot";var Ve=Ue({isolation_level:qe(te()),max_wait:Z($(),X(),Y(0)),timeout:Z($(),X(),Y(0))});async function ne(n){let{issues:e,output:t,success:r}=ee(Ve,await n.req.json(),{abortEarly:!0});return r?t:n.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}var Fe=Ne({id:Ke([te(),$()])});function re(n,e){let{output:t,success:r}=ee(Fe,n);return r?t:e.json({EngineMalfunction:{}},500)}var b=new Qe;b.post("/invalidate",v("header",f),async n=>{let e=await Q(n);return e instanceof Response?e:n.body(null)});var ze="/:clientVersion/:schemaHash",E=b.basePath(ze);b.route("/",E);var Ge=["/graphql","/itx/:transactionId/graphql"];E.on("POST",[...Ge],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)}});E.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)}});E.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 k(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)});E.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 Je}from"hono/tiny";import{StatusCodes as We}from"http-status-codes";var I=new Je;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},We.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 nt(t,n,e),{promise:o,reject:s,resolve:i}=T(),a=Ze({createServer:Xe,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 D(t,"server"));console.error("[Accelerate]",p)}),await o,oe(t,a)}function oe(n,e){return{async close(){e&&await Promise.allSettled([Ye(e.close.bind(e))(),w.stopAll()])},port:n,url:`http://localhost:${n}`}}async function nt(n,e,t){let{debug:r}=t,o=new se,s=await et.getPlatformInfo();return r&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),r&&o.use("*",tt((...i)=>console.log("[Accelerate]",...i))),o.use("*",async(i,a)=>(i.set("db",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("/",B),o}var B=new se;B.route("/",b);B.route("/",I);async function un(n){let e=await U.createExclusively(n),[t,r]=await Promise.all([_("database",e),_("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{le as DEFAULT_DATABASE_PORT,ue as DEFAULT_SERVER_PORT,me as DEFAULT_SHADOW_DATABASE_PORT,D as PortNotAvailableError,de as ServerAlreadyRunningError,un as unstable_startServer};
|
package/dist/state.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
${JSON.stringify(
|
|
3
|
-
`,{encoding:"utf-8"})}};async function
|
|
1
|
+
"use strict";var Z=Object.create;var P=Object.defineProperty;var q=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var Q=Object.getPrototypeOf,ee=Object.prototype.hasOwnProperty;var te=(e,t)=>{for(var s in t)P(e,s,{get:t[s],enumerable:!0})},I=(e,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of z(t))!ee.call(e,o)&&o!==s&&P(e,o,{get:()=>t[o],enumerable:!(i=q(t,o))||i.enumerable});return e};var E=(e,t,s)=>(s=e!=null?Z(Q(e)):{},I(t||!e||!e.__esModule?P(s,"default",{value:e,enumerable:!0}):s,e)),re=e=>I(P({},"__esModule",{value:!0}),e);var me={};te(me,{ServerAlreadyRunningError:()=>y,ServerState:()=>l,ServerStateAlreadyExistsError:()=>S});module.exports=re(me);var X=require("fs/promises"),K=require("hono/client"),p=require("pathe"),w=require("proper-lockfile"),L=require("std-env"),r=require("valibot");var N=require("fs"),c=require("fs/promises");var n=E(require("path"),1),O=E(require("os"),1),v=E(require("process"),1),d=O.default.homedir(),T=O.default.tmpdir(),{env:m}=v.default,se=e=>{let t=n.default.join(d,"Library");return{data:n.default.join(t,"Application Support",e),config:n.default.join(t,"Preferences",e),cache:n.default.join(t,"Caches",e),log:n.default.join(t,"Logs",e),temp:n.default.join(T,e)}},oe=e=>{let t=m.APPDATA||n.default.join(d,"AppData","Roaming"),s=m.LOCALAPPDATA||n.default.join(d,"AppData","Local");return{data:n.default.join(s,e,"Data"),config:n.default.join(t,e,"Config"),cache:n.default.join(s,e,"Cache"),log:n.default.join(s,e,"Log"),temp:n.default.join(T,e)}},ne=e=>{let t=n.default.basename(d);return{data:n.default.join(m.XDG_DATA_HOME||n.default.join(d,".local","share"),e),config:n.default.join(m.XDG_CONFIG_HOME||n.default.join(d,".config"),e),cache:n.default.join(m.XDG_CACHE_HOME||n.default.join(d,".cache"),e),log:n.default.join(m.XDG_STATE_HOME||n.default.join(d,".local","state"),e),temp:n.default.join(T,t,e)}};function $(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),v.default.platform==="darwin"?se(e):v.default.platform==="win32"?oe(e):ne(e)}var ae=require("pako"),ie=$("prisma-dev");function f(e){return`${ie.data}/${e}`}function V(e){return e!=null&&typeof e=="object"&&"code"in e&&e.code==="ENOENT"}async function C(e){try{return await(0,c.readFile)(e,{encoding:"utf-8"})}catch(t){if(V(t))return null;throw t}}async function B(e){await(0,c.mkdir)(e,{recursive:!0})}async function H(e){try{return(await(0,c.readdir)(e,{withFileTypes:!0})).reduce((s,i)=>(i.isDirectory()&&!i.name.startsWith(".")&&s.push(i.name),s),[])}catch(t){if(V(t))return[];throw t}}var J=require("std-env");function U(e,t){if(e==null)return!1;try{return J.process.kill?.(e,0)??!0}catch(s){return t&&console.error(`Error checking if process with PID ${e} exists:`,s),!1}}var k=(0,r.pipe)((0,r.string)(),(0,r.url)()),G=(0,r.object)({connectionString:k,prismaORMConnectionString:(0,r.optional)(k),terminalCommand:(0,r.optional)((0,r.string)())}),W=(0,r.object)({url:k}),R=(0,r.pipe)((0,r.number)(),(0,r.integer)(),(0,r.minValue)(1)),pe=(0,r.object)({database:G,http:W,ppg:W,shadowDatabase:G}),le=(0,r.object)({databasePort:R,exports:(0,r.optional)(pe),name:(0,r.pipe)((0,r.string)(),(0,r.minLength)(1)),pid:(0,r.optional)((0,r.pipe)((0,r.number)(),(0,r.integer)(),(0,r.minValue)(0))),port:R,shadowDatabasePort:R,version:(0,r.literal)("1")}),F=Symbol("initialize"),j="default",l=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(t){this._databasePort=t.databasePort??51214,this.debug=t.debug??!1,this.dryRun=t.dryRun??!1,this.name=t.name??j,this.persistenceMode=t.persistenceMode,this.pid=t.pid??L.process.pid,this._port=t.port??51213,this._shadowDatabasePort=t.shadowDatabasePort??51215}static async createExclusively(t){let s=t?.dryRun!==!0&&t?.persistenceMode!=="stateless"?new g(t):new M(t);return await s[F](),s}static async fromServerDump(t){let{debug:s,name:i=j}=t??{},o=f(i),a=g.getServerDumpPath(o),h=await C(a);if(h==null)return s&&console.debug(`[State] No server dump file found at: ${a}`),null;s&&(console.debug(`[State] server dump file found at "${a}":`),console.debug(h));let{issues:b,output:u,success:x}=(0,r.safeParse)((0,r.pipe)((0,r.string)(),(0,r.parseJson)(),le),h);if(!x)throw s&&console.debug(`[State] Invalid server dump file at "${a}":
|
|
2
|
+
${JSON.stringify(b,null,2)}`),new Error(`Invalid Prisma Dev state for "${i}".`);return new g({databasePort:u.databasePort,debug:s,dryRun:!1,name:i,pid:u.pid,port:u.port,serverDump:u,shadowDatabasePort:u.shadowDatabasePort})}static async scan(t){let{debug:s}=t??{},i=(0,p.join)(f(j),"..");s&&console.debug(`[State] scanning for server states in: ${i}`);let o=await H(i);return s&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(a=>he(a,t)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},M=class extends l{constructor(t){super({...t,persistenceMode:"stateless"})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[F](){}async close(){}async writeServerDump(){}},g=class e extends l{#t;#e;#o;#n;#r;#s=null;constructor(t){super({...t,persistenceMode:"stateful"}),this.#e=f(this.name),this.#t=(0,p.join)(this.#e,"db_dump.bak"),this.#o=(0,p.join)(this.#e,".pglite"),this.#r=t?.serverDump??null,this.#n=e.getServerDumpPath(this.#e)}static getServerDumpPath(t){return(0,p.join)(t,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get pgliteDataDirPath(){return this.#o}async[F](){await B(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#s=await(0,w.lock)(this.#e,{lockfilePath:(0,p.join)(this.#e,".lock")}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`),await this.writeServerDump()}catch(t){throw t instanceof Error&&"code"in t&&t.code==="ELOCKED"?new y(this):t}}async close(){if(this.#s!=null)try{await this.#s(),this.#s=null,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(t){throw console.error(`[State] failed to release lock on: ${this.#e}`),t}}async writeServerDump(t){this.#r={name:this.name,version:"1",pid:L.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:t},await(0,X.writeFile)(this.#n,`${JSON.stringify(this.#r,null,2)}
|
|
3
|
+
`,{encoding:"utf-8"})}};async function he(e,t){let{debug:s,onlyMetadata:i}=t||{},o={databasePort:-1,exports:void 0,name:e,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let a=await l.fromServerDump({debug:s,name:e});if(!a)return s&&console.debug(`[State] no server state found for name: ${e}`),{...o,status:"no_such_server"};o.databasePort=a.databasePort,o.exports=a.exports,o.pid=a.pid,o.port=a.port,o.shadowDatabasePort=a.shadowDatabasePort;let{exports:h,pid:b}=a;if(i)return{...o,status:"unknown"};if(!U(b,s))return s&&console.debug(`[State] server state for "${e}" has no running process with PID: ${b}`),{...o,status:"not_running"};let u=f(e);try{if(!await(0,w.check)(u,{lockfilePath:(0,p.join)(u,".lock")}))return s&&console.debug(`[State] server state for "${e}" is not locked, indicating it is not running.`),{...o,status:"starting_up"}}catch(Y){s&&console.error(`[State] server state for "${e}" failed to check lock:`,Y)}if(!h)return{...o,status:"starting_up"};let{http:x}=h,A=await(0,K.hc)(x.url).health.$get();if(!A.ok)return s&&console.debug(`[State] server state for "${e}" is not live: ${JSON.stringify(A)}`),{...o,status:"not_running"};let _=await A.json();return _.name!==e?(s&&console.debug(`[State] server state for "${e}" has mismatched health response: ${JSON.stringify(_)}`),{...o,status:"unknown"}):(s&&console.debug(`[State] server state for "${e}" is live: ${JSON.stringify(_)}`),{...o,status:"running"})}catch(a){return s&&console.error(`[State] failed to get server status for "${e}":`,a),{...o,status:"error"}}}var S=class extends Error{name="ServerStateAlreadyExistsError";constructor(t){super(`A Prisma Dev server with the name "${t}" is already running.`)}},y=class extends S{#t;name="ServerAlreadyRunningError";constructor(t){super(t.name),this.#t=t}get server(){return l.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};0&&(module.exports={ServerAlreadyRunningError,ServerState,ServerStateAlreadyExistsError});
|
package/dist/state.d.cts
CHANGED
|
@@ -101,20 +101,21 @@ type ResolvedServerOptions = Required<ServerOptions>;
|
|
|
101
101
|
type PersistenceMode = "stateless" | "stateful";
|
|
102
102
|
interface ScanOptions {
|
|
103
103
|
debug?: boolean;
|
|
104
|
+
onlyMetadata?: boolean;
|
|
104
105
|
}
|
|
105
106
|
declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
|
|
106
107
|
declare abstract class ServerState implements ResolvedServerOptions {
|
|
107
|
-
|
|
108
|
+
protected _databasePort: number;
|
|
108
109
|
readonly debug: boolean;
|
|
109
110
|
readonly dryRun: boolean;
|
|
110
111
|
readonly name: string;
|
|
111
112
|
readonly persistenceMode: PersistenceMode;
|
|
112
113
|
readonly pid: number | undefined;
|
|
113
|
-
|
|
114
|
-
|
|
114
|
+
protected _port: number;
|
|
115
|
+
protected _shadowDatabasePort: number;
|
|
115
116
|
protected constructor(options: Omit<ServerOptions, "persistenceMode"> & {
|
|
116
117
|
persistenceMode: PersistenceMode;
|
|
117
|
-
pid
|
|
118
|
+
pid?: number | undefined;
|
|
118
119
|
});
|
|
119
120
|
static createExclusively(options: ServerOptions | undefined): Promise<ServerState>;
|
|
120
121
|
static fromServerDump(options?: Pick<ServerOptions, "debug" | "name">): Promise<StatefulServerState | null>;
|
|
@@ -124,13 +125,16 @@ declare abstract class ServerState implements ResolvedServerOptions {
|
|
|
124
125
|
abstract [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
|
|
125
126
|
abstract close(): Promise<void>;
|
|
126
127
|
abstract writeServerDump(exports?: Exports): Promise<void>;
|
|
128
|
+
get databasePort(): number;
|
|
129
|
+
get port(): number;
|
|
130
|
+
get shadowDatabasePort(): number;
|
|
127
131
|
}
|
|
128
132
|
declare class StatefulServerState extends ServerState {
|
|
129
133
|
#private;
|
|
130
|
-
constructor(options: Omit<ServerOptions, "persistenceMode"> & {
|
|
131
|
-
pid
|
|
134
|
+
constructor(options: (Omit<ServerOptions, "persistenceMode"> & {
|
|
135
|
+
pid?: number | undefined;
|
|
132
136
|
serverDump?: ServerDumpV1;
|
|
133
|
-
});
|
|
137
|
+
}) | undefined);
|
|
134
138
|
static getServerDumpPath(dataDirPath: string): string;
|
|
135
139
|
get databaseDumpPath(): string;
|
|
136
140
|
get exports(): Exports | undefined;
|
package/dist/state.d.ts
CHANGED
|
@@ -101,20 +101,21 @@ type ResolvedServerOptions = Required<ServerOptions>;
|
|
|
101
101
|
type PersistenceMode = "stateless" | "stateful";
|
|
102
102
|
interface ScanOptions {
|
|
103
103
|
debug?: boolean;
|
|
104
|
+
onlyMetadata?: boolean;
|
|
104
105
|
}
|
|
105
106
|
declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
|
|
106
107
|
declare abstract class ServerState implements ResolvedServerOptions {
|
|
107
|
-
|
|
108
|
+
protected _databasePort: number;
|
|
108
109
|
readonly debug: boolean;
|
|
109
110
|
readonly dryRun: boolean;
|
|
110
111
|
readonly name: string;
|
|
111
112
|
readonly persistenceMode: PersistenceMode;
|
|
112
113
|
readonly pid: number | undefined;
|
|
113
|
-
|
|
114
|
-
|
|
114
|
+
protected _port: number;
|
|
115
|
+
protected _shadowDatabasePort: number;
|
|
115
116
|
protected constructor(options: Omit<ServerOptions, "persistenceMode"> & {
|
|
116
117
|
persistenceMode: PersistenceMode;
|
|
117
|
-
pid
|
|
118
|
+
pid?: number | undefined;
|
|
118
119
|
});
|
|
119
120
|
static createExclusively(options: ServerOptions | undefined): Promise<ServerState>;
|
|
120
121
|
static fromServerDump(options?: Pick<ServerOptions, "debug" | "name">): Promise<StatefulServerState | null>;
|
|
@@ -124,13 +125,16 @@ declare abstract class ServerState implements ResolvedServerOptions {
|
|
|
124
125
|
abstract [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
|
|
125
126
|
abstract close(): Promise<void>;
|
|
126
127
|
abstract writeServerDump(exports?: Exports): Promise<void>;
|
|
128
|
+
get databasePort(): number;
|
|
129
|
+
get port(): number;
|
|
130
|
+
get shadowDatabasePort(): number;
|
|
127
131
|
}
|
|
128
132
|
declare class StatefulServerState extends ServerState {
|
|
129
133
|
#private;
|
|
130
|
-
constructor(options: Omit<ServerOptions, "persistenceMode"> & {
|
|
131
|
-
pid
|
|
134
|
+
constructor(options: (Omit<ServerOptions, "persistenceMode"> & {
|
|
135
|
+
pid?: number | undefined;
|
|
132
136
|
serverDump?: ServerDumpV1;
|
|
133
|
-
});
|
|
137
|
+
}) | undefined);
|
|
134
138
|
static getServerDumpPath(dataDirPath: string): string;
|
|
135
139
|
get databaseDumpPath(): string;
|
|
136
140
|
get exports(): Exports | undefined;
|
package/dist/state.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c}from"./chunk-
|
|
1
|
+
import{a,b,c}from"./chunk-RCTKDIXK.js";import"./chunk-Q3M6SQC2.js";export{c as ServerAlreadyRunningError,a as ServerState,b as ServerStateAlreadyExistsError};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma/dev",
|
|
3
|
-
"version": "0.0.0-dev.
|
|
3
|
+
"version": "0.0.0-dev.202506132343",
|
|
4
4
|
"description": "A local Prisma Postgres server for development and testing",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -66,11 +66,11 @@
|
|
|
66
66
|
"@types/node": "22.15.21",
|
|
67
67
|
"@types/pako": "2.0.3",
|
|
68
68
|
"@types/proper-lockfile": "4.1.4",
|
|
69
|
+
"env-paths": "3.0.0",
|
|
69
70
|
"pkg-types": "2.1.0",
|
|
70
71
|
"tsup": "8.5.0",
|
|
71
72
|
"typescript": "5.8.3",
|
|
72
73
|
"vitest": "3.1.4",
|
|
73
|
-
"env-paths": "3.0.0",
|
|
74
74
|
"common-stuff": "^0.0.0"
|
|
75
75
|
},
|
|
76
76
|
"dependencies": {
|
|
@@ -80,6 +80,7 @@
|
|
|
80
80
|
"@hono/node-server": "1.14.2",
|
|
81
81
|
"@prisma/get-platform": "6.8.2",
|
|
82
82
|
"foreground-child": "3.3.1",
|
|
83
|
+
"get-port-please": "3.1.2",
|
|
83
84
|
"hono": "4.7.10",
|
|
84
85
|
"http-status-codes": "2.3.0",
|
|
85
86
|
"pako": "2.1.0",
|
package/dist/chunk-LBY4H4LD.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{b as p,f as E,g as $,h as R,i as _,j as k,k as A}from"./chunk-Q3M6SQC2.js";import{writeFile as B}from"fs/promises";import{hc as C}from"hono/client";import{join as u}from"pathe";import{check as H,lock as Y}from"proper-lockfile";import{process as m}from"std-env";import{integer as V,literal as Z,minLength as q,minValue as N,number as L,object as g,optional as f,parseJson as z,pipe as h,safeParse as K,string as b,url as W}from"valibot";import{process as j}from"std-env";function M(r,e){if(r==null)return!1;try{return j.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}var D=h(b(),W()),I=g({connectionString:D,prismaORMConnectionString:f(D),terminalCommand:f(b())}),T=g({url:D}),S=h(L(),V(),N(1)),G=g({database:I,http:T,ppg:T,shadowDatabase:I}),Q=g({databasePort:S,exports:f(G),name:h(b(),q(1)),pid:f(h(L(),V(),N(0))),port:S,shadowDatabasePort:S,version:Z("1")}),O=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[O](),t}static async fromServerDump(e){let{debug:t,name:s=P}=e??{},n=p(s),a=l.getServerDumpPath(n),i=await E(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}=K(h(b(),z(),Q),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 R(s);return t&&console.debug(`[State] found server names: ${JSON.stringify(n)}`),await Promise.all(n.map(a=>X(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[O](){}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[O](){await $(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#s=await Y(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 x(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 B(this.#o,`${JSON.stringify(this.#r,null,2)}
|
|
3
|
-
`,{encoding:"utf-8"})}};async function X(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(!M(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 H(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(F){e&&console.error(`[State] server state for "${r}" failed to check lock:`,F)}if(!n)return{...t,status:"starting_up"};let{http:v}=n,o=await C(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{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},x=class extends w{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return d.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};export{d as a,w as b,x as c};
|