@prisma/dev 0.0.0-dev.202510282348 → 0.0.0-dev.202510290238

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.
@@ -0,0 +1 @@
1
+ import{a as f}from"./chunk-RBVZVBDC.js";import{a as w}from"./chunk-FZ7JBZR6.js";import{f as d}from"./chunk-LMPFMHCB.js";import{a as u,c as v,d as g}from"./chunk-7EOUKLQR.js";import{createServer as A}from"http";import{promisify as R}from"util";import T from"@prisma/get-platform";async function P(a,e){let{port:r}=e;if(e.dryRun)return y(r,null);let t=await E(r,a,e),{promise:s,reject:S,resolve:c}=v(),{serve:i}=await import("@hono/node-server"),m=i({createServer:A,fetch:t.fetch,overrideGlobalObjects:!1,port:r},c);return m.on("error",o=>{if(typeof o=="object"&&"code"in o&&o.code==="EADDRINUSE")return S(new d(r));console.error("[Accelerate]",o)}),await s,y(r,m)}function y(a,e){return{async close(){e&&await Promise.allSettled([R(e.close.bind(e))(),g.stopAll()])},port:a,url:`http://localhost:${a}`}}async function E(a,e,r){let{debug:t}=r,[{Hono:s},{accelerateRoute:S},{utilityRoute:c}]=await Promise.all([import("hono/tiny"),import("./accelerate-MVW5ZKXM.js"),import("./utility-YJ4TFSMW.js")]),i=new s,m=await T.getPlatformInfo();if(t&&console.debug("[Accelerate] platform info: %s",JSON.stringify(m)),t){let{logger:n}=await import("hono/logger");i.use("*",n((...p)=>console.log("[Accelerate]",...p)))}i.use("*",async(n,p)=>(n.set("db",e),n.set("debug",!!t),n.set("platform",m),n.set("port",a),n.set("protocol","http"),n.set("serverState",r),n.set("shadowDBPort",r.shadowDatabasePort),await p()));let o=new s;return o.route("/",S),o.route("/",c),i.route("/",o),i}async function G(a){let e=await w.createExclusively(a),[r,t]=await Promise.all([f("database",e),f("shadow_database",e)]),s=await P(r,e),S=`prisma+postgres://localhost:${s.port}/?${new URLSearchParams({api_key:u({databaseUrl:r.prismaORMConnectionString,name:e.name,shadowDatabaseUrl:t.prismaORMConnectionString})}).toString()}`,c={database:{connectionString:r.connectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand},http:{url:s.url},ppg:{url:S},shadowDatabase:{connectionString:t.prismaORMConnectionString,prismaORMConnectionString:t.prismaORMConnectionString,terminalCommand:t.terminalCommand}};return await e.writeServerDump(c),{...c,close:()=>i(e,[s,r,t]),name:e.name};async function i(m,o){let p=(await Promise.allSettled(o.map(l=>l.close()))).filter(l=>l.status==="rejected").map(l=>new Error(l.reason));try{await m.close()}catch(l){p.push(l)}if(p.length>0)throw new AggregateError(p,"Failed to close some servers")}}export{G as a};
package/dist/daemon.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var Gt=Object.create;var ie=Object.defineProperty;var Kt=Object.getOwnPropertyDescriptor;var Qt=Object.getOwnPropertyNames;var Jt=Object.getPrototypeOf,Wt=Object.prototype.hasOwnProperty;var y=(t,e)=>()=>(t&&(e=t(t=0)),e);var ce=(t,e)=>{for(var r in e)ie(t,r,{get:e[r],enumerable:!0})},zt=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Qt(e))!Wt.call(t,n)&&n!==r&&ie(t,n,{get:()=>e[n],enumerable:!(o=Kt(e,n))||o.enumerable});return t};var w=(t,e,r)=>(r=t!=null?Gt(Jt(t)):{},zt(e||!t||!t.__esModule?ie(r,"default",{value:t,enumerable:!0}):r,t));var l=y(()=>{"use strict"});function Ie(t){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([[e],[r]])=>e.localeCompare(r)))),"utf8").toString("base64url")}function Yt(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:o,success:n}=(0,f.safeParse)(Xt,e,{abortEarly:!0});return n?[null,o]:[r]}var f,ke,Xt,k,ue=y(()=>{"use strict";l();f=require("valibot"),ke=/^(postgres|postgresql):\/\//,Xt=(0,f.pipe)((0,f.string)(),(0,f.parseJson)(),(0,f.object)({databaseUrl:(0,f.pipe)((0,f.string)(),(0,f.url)(),(0,f.regex)(ke)),name:(0,f.optional)((0,f.pipe)((0,f.string)(),(0,f.minLength)(1))),shadowDatabaseUrl:(0,f.pipe)((0,f.string)(),(0,f.url)(),(0,f.regex)(ke))}));k=async(t,e)=>{let{authorization:r}=t,{HTTPException:o}=await import("hono/http-exception");if(!r)throw new o(401,{message:"Missing API Key"});let[n,s="",a]=r.split(" ");if(n!=="Bearer"||a)throw new o(401,{message:"Invalid API Key"});let[i,c]=Yt(s);if(i)throw new o(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:u,name:p,shadowDatabaseUrl:g}=c,{name:S}=e.get("serverState");if(!p)throw new o(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 "${S}" server's output for the updated \`DATABASE_URL\` value.`});if(p!==S)throw new o(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${S}", but the API Key is for "${p}"`});let{hostname:x,port:R}=new URL(u),{port:q}=e.get("db"),{hostname:qt,port:Ft}=new URL(g),Vt=e.get("shadowDBPort");if(x!=="localhost"||Number(R)!==q||qt!=="localhost"||Number(Ft)!==Vt)throw new o(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:c}}});function pe(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),X.default.platform==="darwin"?Zt(t):X.default.platform==="win32"?er(t):tr(t)}var h,de,X,O,le,L,Zt,er,tr,Ce=y(()=>{"use strict";l();h=w(require("path"),1),de=w(require("os"),1),X=w(require("process"),1),O=de.default.homedir(),le=de.default.tmpdir(),{env:L}=X.default,Zt=t=>{let e=h.default.join(O,"Library");return{data:h.default.join(e,"Application Support",t),config:h.default.join(e,"Preferences",t),cache:h.default.join(e,"Caches",t),log:h.default.join(e,"Logs",t),temp:h.default.join(le,t)}},er=t=>{let e=L.APPDATA||h.default.join(O,"AppData","Roaming"),r=L.LOCALAPPDATA||h.default.join(O,"AppData","Local");return{data:h.default.join(r,t,"Data"),config:h.default.join(e,t,"Config"),cache:h.default.join(r,t,"Cache"),log:h.default.join(r,t,"Log"),temp:h.default.join(le,t)}},tr=t=>{let e=h.default.basename(O);return{data:h.default.join(L.XDG_DATA_HOME||h.default.join(O,".local","share"),t),config:h.default.join(L.XDG_CONFIG_HOME||h.default.join(O,".config"),t),cache:h.default.join(L.XDG_CACHE_HOME||h.default.join(O,".cache"),t),log:h.default.join(L.XDG_STATE_HOME||h.default.join(O,".local","state"),t),temp:h.default.join(le,e,t)}}});function je(t,e){return`${Me.cache}/engine/${t}/${e}`}function F(t){return`${Me.data}/${t}`}async function Ue(t){try{return await(0,D.access)(t,D.constants.F_OK),!0}catch(e){if(me(e))return!1;throw e}}async function Ne(t,e){let r=await rr(t);await(0,D.writeFile)(e,r),await(0,D.chmod)(e,"755")}async function qe(t,e){await t.stream().pipeTo(Y.WriteStream.toWeb((0,Y.createWriteStream)(e,{encoding:"utf-8"})))}function me(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function Fe(t){try{return await(0,D.readFile)(t,{encoding:"utf-8"})}catch(e){if(me(e))return null;throw e}}async function Ve(t){await(0,D.mkdir)(t,{recursive:!0})}async function Ge(t,e){try{return(await(0,D.readdir)(t,{withFileTypes:!0})).reduce((o,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&(!e||(0,He.default)(e,n.name))&&o.push(n.name),o),[])}catch(r){if(me(r))return[];throw r}}var Y,D,Le,Be,He,Me,rr,Z=y(()=>{"use strict";l();Y=require("fs"),D=require("fs/promises"),Le=require("util"),Be=require("zlib");Ce();He=w(require("zeptomatch"),1),Me=pe("prisma-dev"),rr=(0,Le.promisify)(Be.unzip)});async function Qe(t){let{debug:e,name:r,requestedPorts:o,servers:n}=t,{portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a}=sr(r,n);e&&(console.debug(`ports used by other servers: ${Object.keys(s).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(a)}`));let i={databasePort:A,port:A,shadowDatabasePort:A},c=["port","databasePort","shadowDatabasePort"];for(let u of c){let p=await or({debug:e,portKey:u,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a,requestedPorts:o})??await nr({debug:e,pickedPorts:i,portKey:u,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a});e&&console.debug(`Got port for "${u}": ${p}`),i[u]=p}return e&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function or(t){let{debug:e,portKey:r,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:n,requestedPorts:s}=t,{[r]:a,...i}=s;if(Ke(a))return await ar({debug:e,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:o,requestedPort:a}),a;let c=n?.[r]??A;if(!Ke(c))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let u=c in o;return u||Object.values(i).includes(c)?(e&&console.debug(`Port ${c} that was used last time for this server, ${u?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,_.checkPort)(c)===!1?(e&&console.debug(`Port ${c}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(e&&console.debug(`Using port ${c} for "${r}" as it was used last time and is available.`),c)}async function nr(t){let{debug:e,pickedPorts:r,portKey:o,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s}=t,a=Math.max(B,H,M)+1,i=[...Object.values(r),...Object.keys(n).map(Number),...Object.values(s||{})],c=Math.min(Math.max(a,...i)+100,ee),u=(0,te.difference)((0,te.range)(a,c),i),p={port:H,databasePort:B,shadowDatabasePort:M}[o];try{return await(0,_.getPort)({port:p in n||Object.values(r).includes(p)||Object.values(s||{}).includes(p)?void 0:p,ports:u})}catch(g){if(g instanceof Error&&g.name==="GetPortError"&&c+1<=ee)return e&&console.debug(`Expanding port lookup to range [${c+1}, ${ee}].`),await(0,_.getPort)({portRange:[c+1,ee]});throw g}}function Ke(t){return t>=0}function sr(t,e){let r={},o;for(let n of e){let{databasePort:s,port:a,shadowDatabasePort:i}=n;if(n.name===t){o={databasePort:s,port:a,shadowDatabasePort:i};continue}r[s]=!0,r[a]=!0,r[i]=!0}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:o}}async function ar(t){let{debug:e,otherRequestedPorts:r,portKey:o,portsUsedByOtherServers:n,requestedPort:s}=t;if(s in n)throw e&&console.error(`Port ${s} was requested for "${o}", but is already used by another server.`),new he(s);if(Object.values(r).includes(s))throw e&&console.error(`Port ${s} was requested for "${o}", but also for another key.`),new fe(s);if((0,_.isUnsafePort)(s))throw e&&console.error(`Port ${s} was requested for "${o}", but is unsafe.`),new E(s);if(await(0,_.checkPort)(s)===!1)throw e&&console.error(`Port ${s} was requested for "${o}", but is not available.`),new E(s)}var _,te,B,H,M,ee,A,E,fe,he,V=y(()=>{"use strict";l();_=require("get-port-please"),te=require("remeda"),B=51214,H=51213,M=51215,ee=65535,A=-1/0;E=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},fe=class extends Error{constructor(r){super(`Port number \`${r}\` was requested twice. Please choose a different port for each service.`);this.port=r}name="PortRequestedTwiceError"},he=class extends Error{constructor(r){super(`Port number \`${r}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=r}name="PortBelongsToAnotherServerError"}});async function ge(t,e){let r=t==="database"?e.databasePort:e.shadowDatabasePort;if(e.dryRun)return Je(t,e,{db:null,port:r,server:null});let{debug:o}=e,s=await(t==="shadow_database"?ur:Ye)(e.pgliteDataDirPath,o);o&&s.onNotification((c,u)=>{console.debug(`[${t}][${c}] ${u}`)});let{PGLiteSocketServer:a}=await import("@electric-sql/pglite-socket"),i=new a({db:s,debug:o,inspect:o,port:r});o&&(i.addEventListener("listening",c=>{let{detail:u}=c;console.debug(`[${t}] server listening on ${JSON.stringify(u)}`)}),i.addEventListener("connection",c=>{let{clientAddress:u,clientPort:p}=c.detail;console.debug(`[${t}] client connected from ${u}:${p}`)}),i.addEventListener("error",c=>{let{detail:u}=c;console.error(`[${t}] server error:`,u)}));try{await i.start()}catch(c){throw c instanceof Error&&"code"in c&&c.code==="EADDRINUSE"?new E(r):c}return Je(t,e,{db:s,port:r,server:i})}function Je(t,e,r){let{debug:o}=e,{db:n,port:s,server:a}=r||{};return o&&console.debug(`[${t}] server started on port ${s}`),{...b,close:async()=>{let i=[];try{await a?.stop(),o&&console.debug(`[${t}] server stopped on port ${s}`)}catch(c){console.error(`[${t}] server stop error`,c),i.push(c)}if(t==="database")try{await n?.syncToFs(),o&&console.debug(`[${t}] synced to filesystem`)}catch(c){console.error(`[${t}] sync error`,c),i.push(c)}try{await n?.close(),o&&console.debug(`[${t}] closed`)}catch(c){console.error(`[${t}] close error`,c),i.push(c)}if(i.length>0)throw new AggregateError(i,`Failed to close ${t} properly`)},connectionString:We(s,Xe),dump:async i=>{t==="shadow_database"||!n||await dr({db:n,debug:o,destinationPath:i})},port:s,prismaORMConnectionString:We(s,cr),terminalCommand:`PGPASSWORD=${b.password} PGSSLMODE=${b.sslMode} psql -h localhost -p ${s} -U ${b.username} -d ${b.database}`}}function We(t,e){return`${ir}:${t}/${b.database}?${e.toString()}`}async function Ye(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:b.database,dataDir:t,debug:e?5:void 0,relaxedDurability:!1,username:b.username})}async function ur(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:b.database,dataDir:"memory://",debug:e?5:void 0,relaxedDurability:!1,username:b.username})}async function dr(t){let{dataDir:e,db:r,debug:o,destinationPath:n}=t,s=r||await Ye(e,o),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),i=await a({args:["--schema-only","--no-owner"],fileName:n?(0,ze.filename)(n):void 0,pg:await s.clone()});return n?(o&&console.debug(`[DB] Dumping database to ${n}`),await qe(i,n)):(o&&console.debug("[DB] Dumping database to memory"),await i.text())}var ze,b,ir,Xe,cr,Ze=y(()=>{"use strict";l();ze=require("pathe/utils");Z();V();b={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},ir=`postgres://${b.username}:${b.password}@localhost`,Xe=new URLSearchParams({sslmode:b.sslMode}),cr=new URLSearchParams({...Object.fromEntries(Xe.entries()),connection_limit:String(b.connectionLimit),connect_timeout:String(b.connectTimeout),max_idle_connection_lifetime:String(b.maxIdleConnectionLifetime),pool_timeout:String(b.poolTimeout),single_use_connections:"true",socket_timeout:String(b.socketTimeout)})});function re(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 ye=y(()=>{"use strict";l()});function oe(t,e){return console.error(t),t instanceof G?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof j?e.text(t.responseBody,t.statusCode):e.body(null,500)}var tt,rt,ot,nt,st,at,lr,pr,et,U,G,j,Pe=y(()=>{"use strict";l();tt=require("child_process"),rt=require("events"),ot=require("fs/promises"),nt=require("path"),st=require("timers/promises");ye();at=require("std-env");Z();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:lr,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:pr,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:et}=at.process.env),U=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.#o(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 j.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.#o(r),s=await fetch(`${o}/transaction/start`,{body:JSON.stringify(e),headers:{...n,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await j.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:r,resolve:o}=re();this.#t=e;let n=pr||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",n);let{proxySignals:s}=await import("foreground-child/proxy-signals"),a=(0,tt.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});s(a),a.stderr.setEncoding("utf8"),a.stdout.setEncoding("utf8");let i=p=>{let g=p.split(`
2
- `).find(q=>q.includes("Started query engine http server"));if(!g)return;a.stdout.removeListener("data",i);let{fields:S}=JSON.parse(g);if(S==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${p}`));let{ip:x,port:R}=S;if(x==null||R==null)return r(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
3
- Received data: ${p}`));o({childProcess:a,url:`http://${x}:${R}`})},c=p=>{this.#t=null,r(new G(String(p))),a.removeListener("exit",u),a.kill()};a.once("error",c);let u=(p,g)=>{this.#t=null,r(new G(`Query Engine exited with code ${p} and signal ${g}`))};return a.once("exit",u),a.stdout.on("data",i),this.#e.debug&&(a.stderr.on("data",console.error.bind(console,"[Query Engine]")),a.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,rt.once)(e,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#a();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let r=je(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,ot.mkdir)(r,{recursive:!0});let{binaryTarget:o}=this.#e.platform,n=o==="windows"?".exe":"",s=(0,nt.join)(r,`query-engine-${o}${n}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(lr==="1"||await Ue(s)===!1)&&await this.#n({commitHash:e,extension:n,engineBinaryPath:s}),s}async#a(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let 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#n(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}`);et&&await(0,st.setTimeout)(Number(et)),await Ne(await i.arrayBuffer(),n),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",n)}#o(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.#o(r),a=await fetch(`${n}/transaction/${e}/${o}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!a.ok)throw await j.fromResponse(a);try{return await a.json()}catch{return{}}}};G=class extends Error{name="EngineStartError"},j=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)}}});async function it(t){let{output:e,success:r}=(0,v.safeParse)(mr,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var v,mr,ct=y(()=>{"use strict";l();v=require("valibot"),mr=(0,v.object)({tags:(0,v.union)([(0,v.pipe)((0,v.array)((0,v.string)()),(0,v.minLength)(1)),(0,v.literal)("all")])})});async function ut(t){return be===void 0&&(be=await $.Server.create({databaseUrl:t.get("db").connectionString,maxResponseSize:(0,$.parseSize)("128 MiB"),queryTimeout:(0,$.parseDuration)("PT5M"),maxTransactionTimeout:(0,$.parseDuration)("PT5M"),maxTransactionWaitTime:(0,$.parseDuration)("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:t.get("debug")?"debug":"off"}})),be}var $,ne,be,dt=y(()=>{"use strict";l();$=require("@prisma/query-plan-executor"),ne=require("@prisma/query-plan-executor")});async function ve(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 pt(t){let e=t.req.param("schemaHash"),r=se.get(e);return r==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:r}}async function mt(t,e,r){let o=Se.Buffer.from(t,"base64").toString("utf8"),n=(0,lt.produceSchema)(o,a=>{a.datasource('"postgresql"',e.toString())});r&&console.log("[Accelerate] schema with override:",n);let s=await ve(n);return{base64Override:Se.Buffer.from(n,"utf8").toString("base64"),overrideHash:s}}var Se,lt,se,ft=y(()=>{"use strict";l();Se=require("buffer"),lt=require("@mrleebo/prisma-ast"),se=new Map});function ae(t){let{req:e}=t;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}var ht=y(()=>{"use strict";l()});async function gt(t){let{issues:e,output:r,success:o}=(0,m.safeParse)(fr,await t.req.json(),{abortEarly:!0});return o?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}function yt(t,e){let{output:r,success:o}=(0,m.safeParse)(hr,t);return o?r:e.json({EngineMalfunction:{}},500)}var m,fr,hr,Pt=y(()=>{"use strict";l();m=require("valibot"),fr=(0,m.object)({isolation_level:(0,m.optional)((0,m.string)()),max_wait:(0,m.pipe)((0,m.number)(),(0,m.integer)(),(0,m.minValue)(0)),timeout:(0,m.pipe)((0,m.number)(),(0,m.integer)(),(0,m.minValue)(0))});hr=(0,m.looseObject)({id:(0,m.union)([(0,m.string)(),(0,m.number)()])})});var vt={};ce(vt,{accelerateRoute:()=>K});async function we(t){let{req:e}=t,r=pt(t);if(r instanceof Response)return r;let{base64Override:o,overrideHash:n}=r.schemas;return await U.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 bt,St,I,K,gr,Q,yr,Pr,wt=y(()=>{"use strict";l();bt=require("hono/http-exception"),St=require("hono/tiny"),I=require("hono/validator");ue();ct();Pe();dt();ft();ht();Pt();K=new St.Hono;K.post("/invalidate",(0,I.validator)("header",k),async t=>{let e=await it(t);return e instanceof Response?e:t.body(null)});gr="/:clientVersion/:schemaHash",Q=K.basePath(gr);K.route("/",Q);yr=["/graphql","/itx/:transactionId/graphql"];Q.on("POST",[...yr],(0,I.validator)("header",k),async t=>{let{req:e}=t;try{let r=await we(t);if(r instanceof Response)return r;let o=await e.text(),n=e.param("transactionId"),s=await r.request(o,{...ae(t),"X-transaction-id":n});return t.text(s)}catch(r){return oe(r,t)}});Q.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,I.validator)("header",k),async t=>{let{req:e}=t;try{let r=await we(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,ae(t));return t.json(a)}catch(r){return oe(r,t)}});Q.put("/schema",(0,I.validator)("header",k),async t=>{let{req:e}=t,r=await e.text();if(!r)return t.text("Missing schema",400);let o=e.param("schemaHash"),n=se.get(o);if(n==null){if(o!==await ve(r))return t.text("Schema hash mismatch",400);let s=await mt(r,t.get("db").prismaORMConnectionString,t.get("debug"));return se.set(o,{base64Original:r,...s}),t.text(o)}return r!==n.base64Original?t.text("Schema mismatch",400):t.text(o)});Q.post("/transaction/start",(0,I.validator)("header",k),async t=>{let{req:e}=t,r=await gt(t);if(r instanceof Response)return r;try{let o=await we(t);if(o instanceof Response)return o;let n=await o.startTransaction(r,ae(t)),s=yt(n,t);if(s instanceof Response)return s;let{id:a}=s,i=e.param("clientVersion"),c=t.get("port"),u=t.get("protocol"),p=e.param("schemaHash");return t.json({...n,"data-proxy":{endpoint:`${u}://localhost:${c}/${i}/${p}/itx/${a}`}})}catch(o){return oe(o,t)}});Pr=[["/connection-info","GET"],["/query","POST"],["/transaction/start","POST"],["/transaction/:transactionId/commit","POST"],["/transaction/:transactionId/query","POST"],["/transaction/:transactionId/rollback","POST"]];for(let[t,e]of Pr)K.on(e,t,(0,I.validator)("header",k),async r=>{let o=r.req.header("prisma-engine-hash");if(o!=="0.0.0"&&o!==ne.version)throw new bt.HTTPException(400,{message:`Using an HTTP connection string is not supported with Prisma Client version ${o} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${ne.version}.`});return await(await ut(r)).fetch(r.req.raw)})});var Tt={};ce(Tt,{utilityRoute:()=>De});var Dt,Et,De,mo,xt=y(()=>{"use strict";l();Dt=require("hono/tiny"),Et=require("http-status-codes"),De=new Dt.Hono;De.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},Et.StatusCodes.CREATED)});mo=De.get("/health",t=>t.json({name:t.get("serverState").name}))});async function $t(t,e){let{port:r}=e;if(e.dryRun)return Rt(r,null);let o=await br(r,t,e),{promise:n,reject:s,resolve:a}=re(),{serve:i}=await import("@hono/node-server"),c=i({createServer:Ot.createServer,fetch:o.fetch,overrideGlobalObjects:!1,port:r},a);return c.on("error",u=>{if(typeof u=="object"&&"code"in u&&u.code==="EADDRINUSE")return s(new E(r));console.error("[Accelerate]",u)}),await n,Rt(r,c)}function Rt(t,e){return{async close(){e&&await Promise.allSettled([(0,At.promisify)(e.close.bind(e))(),U.stopAll()])},port:t,url:`http://localhost:${t}`}}async function br(t,e,r){let{debug:o}=r,[{Hono:n},{accelerateRoute:s},{utilityRoute:a}]=await Promise.all([import("hono/tiny"),Promise.resolve().then(()=>(wt(),vt)),Promise.resolve().then(()=>(xt(),Tt))]),i=new n,c=await _t.default.getPlatformInfo();if(o&&console.debug("[Accelerate] platform info: %s",JSON.stringify(c)),o){let{logger:p}=await import("hono/logger");i.use("*",p((...g)=>console.log("[Accelerate]",...g)))}i.use("*",async(p,g)=>(p.set("db",e),p.set("debug",!!o),p.set("platform",c),p.set("port",t),p.set("protocol","http"),p.set("serverState",r),p.set("shadowDBPort",r.shadowDatabasePort),await g()));let u=new n;return u.route("/",s),u.route("/",a),i.route("/",u),i}var Ot,At,_t,kt=y(()=>{"use strict";l();Ot=require("http"),At=require("util"),_t=w(require("@prisma/get-platform"),1);ye();Pe();V()});function Ct(t,e){if(t==null)return!1;try{return It.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var Sr,It,Lt=y(()=>{"use strict";l();Sr=require("timers/promises"),It=require("std-env")});async function Dr(t,e){let{debug:r,onlyMetadata:o}=e||{},n=typeof t=="string"?t:t.name,s=typeof t!="string"?t:void 0,a={databasePort:s?.databasePort??-1,exports:s?.exports,name:n,pid:s?.pid,port:s?.port??-1,shadowDatabasePort:s?.shadowDatabasePort??-1,version:"1"};try{let i=s||await T.fromServerDump({debug:r,name:n});if(!i)return r&&console.debug(`[State] no server state found for name: ${n}`),{...a,status:"no_such_server"};a.databasePort=i.databasePort,a.exports=i.exports,a.pid=i.pid,a.port=i.port,a.shadowDatabasePort=i.shadowDatabasePort;let{exports:c,pid:u}=i;if(o)return{...a,status:"unknown"};if(!Ct(u,r))return r&&console.debug(`[State] server state for "${n}" has no running process with PID: ${u}`),{...a,status:"not_running"};let p=F(n);try{if(!await(0,N.check)(p,{lockfilePath:(0,C.join)(p,".lock")}))return r&&console.debug(`[State] server state for "${n}" is not locked, indicating it is not running.`),{...a,status:"starting_up"}}catch(q){r&&console.error(`[State] server state for "${n}" failed to check lock:`,q)}if(!c)return{...a,status:"starting_up"};let{http:g}=c,{hc:S}=await import("hono/client"),x=await S(g.url).health.$get();if(!x.ok)return r&&console.debug(`[State] server state for "${n}" is not live: ${JSON.stringify(x)}`),{...a,status:"not_running"};let R=await x.json();return R.name!==t?(r&&console.debug(`[State] server state for "${n}" has mismatched health response: ${JSON.stringify(R)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(R)}`),{...a,status:"running"})}catch(i){return r&&console.error(`[State] failed to get server status for "${n}":`,i),{...a,status:"error"}}}var Mt,C,N,Ae,d,xe,Bt,Ht,Ee,vr,wr,_e,Te,T,Re,J,Oe,W,$e=y(()=>{"use strict";l();Mt=require("fs/promises"),C=require("pathe"),N=require("proper-lockfile"),Ae=require("std-env"),d=require("valibot");Z();Lt();V();xe=(0,d.pipe)((0,d.string)(),(0,d.url)()),Bt=(0,d.object)({connectionString:xe,prismaORMConnectionString:(0,d.optional)(xe),terminalCommand:(0,d.optional)((0,d.string)())}),Ht=(0,d.object)({url:xe}),Ee=(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(1)),vr=(0,d.object)({database:Bt,http:Ht,ppg:Ht,shadowDatabase:Bt}),wr=(0,d.object)({databasePort:Ee,exports:(0,d.optional)(vr),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:Ee,shadowDatabasePort:Ee,version:(0,d.literal)("1")}),_e=Symbol("initialize"),Te="default",T=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??A,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??Te,this.persistenceMode=e.persistenceMode,this.pid=e.pid??Ae.process.pid,this._port=e.port??A,this._shadowDatabasePort=e.shadowDatabasePort??A}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new J(e):new Re(e);return await r[_e](),r}static async fromServerDump(e){let{debug:r,name:o=Te}=e??{},n=F(o),s=J.getServerDumpPath(n),a=await Fe(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:c,success:u}=(0,d.safeParse)((0,d.pipe)((0,d.string)(),(0,d.parseJson)(),wr),a);if(!u)throw r&&console.debug(`[State] Invalid server dump file at "${s}":
4
- ${JSON.stringify(i,null,2)}`),new Error(`Invalid Prisma Dev state for "${o}".`);return new J({databasePort:c.databasePort,debug:r,dryRun:!1,name:o,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(e){let{debug:r,globs:o}=e??{},n=(0,C.join)(F(Te),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let s=await Ge(n,o);return r&&console.debug(`[State] found server names: ${JSON.stringify(s)}`),await Promise.all(s.map(a=>Dr(a,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},Re=class extends T{constructor(e){super({...e,databasePort:e?.databasePort??B,persistenceMode:"stateless",port:e?.port??H,shadowDatabasePort:e?.shadowDatabasePort??M})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[_e](){}async close(){}async writeServerDump(){}},J=class t extends T{#r;#e;#t;#s;#a;#n;#o;constructor(e){super({...e,persistenceMode:"stateful"}),this.#n=!1,this.#e=F(this.name),this.#r=(0,C.join)(this.#e,"db_dump.bak"),this.#t=(0,C.join)(this.#e,".lock"),this.#s=(0,C.join)(this.#e,".pglite"),this.#o=e?.serverDump??null,this.#a=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,C.join)(e,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#o?.exports}get pgliteDataDirPath(){return this.#s}async[_e](){await Ve(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,N.lock)(this.#e,{lockfilePath:this.#t}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await T.scan({debug:this.debug,onlyMetadata:!0}),r=await Qe({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new W(this):e}}async close(){if(!this.#n)try{await(0,N.unlock)(this.#e,{lockfilePath:this.#t}),this.#n=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,e),e}}async writeServerDump(e){this.#o={name:this.name,version:"1",pid:Ae.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,Mt.writeFile)(this.#a,`${JSON.stringify(this.#o,null,2)}
5
- `,{encoding:"utf-8"})}};Oe=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},W=class extends Oe{#r;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#r=e}get server(){return T.fromServerDump({debug:this.#r.debug,name:this.#r.name})}}});var jt={};ce(jt,{DEFAULT_DATABASE_PORT:()=>B,DEFAULT_SERVER_PORT:()=>H,DEFAULT_SHADOW_DATABASE_PORT:()=>M,PortNotAvailableError:()=>E,ServerAlreadyRunningError:()=>W,unstable_startServer:()=>Er});async function Er(t){let e=await T.createExclusively(t),[r,o]=await Promise.all([ge("database",e),ge("shadow_database",e)]),n=await $t(r,e),s=`prisma+postgres://localhost:${n.port}/?${new URLSearchParams({api_key:Ie({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(c,u){let g=(await Promise.allSettled(u.map(S=>S.close()))).filter(S=>S.status==="rejected").map(S=>new Error(S.reason));try{await c.close()}catch(S){g.push(S)}if(g.length>0)throw new AggregateError(g,"Failed to close some servers")}}var Ut=y(()=>{"use strict";l();ue();Ze();kt();$e();V();$e()});l();var Nt=require("timers/promises"),z;process.once("SIGTERM",()=>{process.removeAllListeners("SIGINT"),process.exitCode=143,z?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{process.removeAllListeners("SIGTERM"),process.exitCode=130,z?.close().finally(()=>process.exit())});async function Tr(){let[,,t]=process.argv;if(!t)return process.send?.({type:"error",error:'Missing "name" argument, server cannot be started'},void 0,{keepOpen:!1}),process.exit(1);try{let{unstable_startServer:e}=await Promise.resolve().then(()=>(Ut(),jt));z=await e({debug:!0,persistenceMode:"stateful",name:t}),z.close=void 0,process.send?.({type:"started",server:z},void 0,{keepOpen:!1})}catch(e){let r=e instanceof Error?e.message:String(e);process.send?.({type:"error",error:r},void 0,{keepOpen:!1}),await(0,Nt.setTimeout)(1e3),process.exit(1)}}Tr();
1
+ "use strict";var Ut=Object.create;var J=Object.defineProperty;var Nt=Object.getOwnPropertyDescriptor;var qt=Object.getOwnPropertyNames;var Ft=Object.getPrototypeOf,Vt=Object.prototype.hasOwnProperty;var D=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ae=(t,e)=>{for(var r in e)J(t,r,{get:e[r],enumerable:!0})},_e=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of qt(e))!Vt.call(t,n)&&n!==r&&J(t,n,{get:()=>e[n],enumerable:!(o=Nt(e,n))||o.enumerable});return t};var v=(t,e,r)=>(r=t!=null?Ut(Ft(t)):{},_e(e||!t||!t.__esModule?J(r,"default",{value:t,enumerable:!0}):r,t)),Gt=t=>_e(J({},"__esModule",{value:!0}),t);var l=D(()=>{"use strict"});function ke(t){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([[e],[r]])=>e.localeCompare(r)))),"utf8").toString("base64url")}function Qt(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:o,success:n}=(0,f.safeParse)(Kt,e,{abortEarly:!0});return n?[null,o]:[r]}var f,$e,Kt,k,ie=D(()=>{"use strict";l();f=require("valibot"),$e=/^(postgres|postgresql):\/\//,Kt=(0,f.pipe)((0,f.string)(),(0,f.parseJson)(),(0,f.object)({databaseUrl:(0,f.pipe)((0,f.string)(),(0,f.url)(),(0,f.regex)($e)),name:(0,f.optional)((0,f.pipe)((0,f.string)(),(0,f.minLength)(1))),shadowDatabaseUrl:(0,f.pipe)((0,f.string)(),(0,f.url)(),(0,f.regex)($e))}));k=async(t,e)=>{let{authorization:r}=t,{HTTPException:o}=await import("hono/http-exception");if(!r)throw new o(401,{message:"Missing API Key"});let[n,s="",a]=r.split(" ");if(n!=="Bearer"||a)throw new o(401,{message:"Invalid API Key"});let[i,c]=Qt(s);if(i)throw new o(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:u,name:p,shadowDatabaseUrl:h}=c,{name:b}=e.get("serverState");if(!p)throw new o(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 "${b}" server's output for the updated \`DATABASE_URL\` value.`});if(p!==b)throw new o(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${b}", but the API Key is for "${p}"`});let{hostname:x,port:R}=new URL(u),{port:j}=e.get("db"),{hostname:Bt,port:Ht}=new URL(h),jt=e.get("shadowDBPort");if(x!=="localhost"||Number(R)!==j||Bt!=="localhost"||Number(Ht)!==jt)throw new o(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:c}}});function de(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),W.default.platform==="darwin"?Jt(t):W.default.platform==="win32"?Wt(t):zt(t)}var g,ce,W,O,ue,M,Jt,Wt,zt,Ie=D(()=>{"use strict";l();g=v(require("path"),1),ce=v(require("os"),1),W=v(require("process"),1),O=ce.default.homedir(),ue=ce.default.tmpdir(),{env:M}=W.default,Jt=t=>{let e=g.default.join(O,"Library");return{data:g.default.join(e,"Application Support",t),config:g.default.join(e,"Preferences",t),cache:g.default.join(e,"Caches",t),log:g.default.join(e,"Logs",t),temp:g.default.join(ue,t)}},Wt=t=>{let e=M.APPDATA||g.default.join(O,"AppData","Roaming"),r=M.LOCALAPPDATA||g.default.join(O,"AppData","Local");return{data:g.default.join(r,t,"Data"),config:g.default.join(e,t,"Config"),cache:g.default.join(r,t,"Cache"),log:g.default.join(r,t,"Log"),temp:g.default.join(ue,t)}},zt=t=>{let e=g.default.basename(O);return{data:g.default.join(M.XDG_DATA_HOME||g.default.join(O,".local","share"),t),config:g.default.join(M.XDG_CONFIG_HOME||g.default.join(O,".config"),t),cache:g.default.join(M.XDG_CACHE_HOME||g.default.join(O,".cache"),t),log:g.default.join(M.XDG_STATE_HOME||g.default.join(O,".local","state"),t),temp:g.default.join(ue,e,t)}}});function He(t,e){return`${Be.cache}/engine/${t}/${e}`}function U(t){return`${Be.data}/${t}`}async function je(t){try{return await(0,w.access)(t,w.constants.F_OK),!0}catch(e){if(le(e))return!1;throw e}}async function Ue(t,e){let r=await Xt(t);await(0,w.writeFile)(e,r),await(0,w.chmod)(e,"755")}async function Ne(t,e){await t.stream().pipeTo(z.WriteStream.toWeb((0,z.createWriteStream)(e,{encoding:"utf-8"})))}function le(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function qe(t){try{return await(0,w.readFile)(t,{encoding:"utf-8"})}catch(e){if(le(e))return null;throw e}}async function Fe(t){await(0,w.mkdir)(t,{recursive:!0})}async function Ve(t,e){try{return(await(0,w.readdir)(t,{withFileTypes:!0})).reduce((o,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&(!e||(0,Le.default)(e,n.name))&&o.push(n.name),o),[])}catch(r){if(le(r))return[];throw r}}var z,w,Ce,Me,Le,Be,Xt,X=D(()=>{"use strict";l();z=require("fs"),w=require("fs/promises"),Ce=require("util"),Me=require("zlib");Ie();Le=v(require("zeptomatch"),1),Be=de("prisma-dev"),Xt=(0,Ce.promisify)(Me.unzip)});function ee(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 ge=D(()=>{"use strict";l()});function te(t,e){return console.error(t),t instanceof V?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof L?e.text(t.responseBody,t.statusCode):e.body(null,500)}var Ze,et,tt,rt,ot,nt,ar,ir,Ye,B,V,L,he=D(()=>{"use strict";l();Ze=require("child_process"),et=require("events"),tt=require("fs/promises"),rt=require("path"),ot=require("timers/promises");ge();nt=require("std-env");X();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:ar,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:ir,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:Ye}=nt.process.env),B=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.#o(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 L.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.#o(r),s=await fetch(`${o}/transaction/start`,{body:JSON.stringify(e),headers:{...n,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await L.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:r,resolve:o}=ee();this.#t=e;let n=ir||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",n);let{proxySignals:s}=await import("foreground-child/proxy-signals"),a=(0,Ze.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});s(a),a.stderr.setEncoding("utf8"),a.stdout.setEncoding("utf8");let i=p=>{let h=p.split(`
2
+ `).find(j=>j.includes("Started query engine http server"));if(!h)return;a.stdout.removeListener("data",i);let{fields:b}=JSON.parse(h);if(b==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${p}`));let{ip:x,port:R}=b;if(x==null||R==null)return r(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
3
+ Received data: ${p}`));o({childProcess:a,url:`http://${x}:${R}`})},c=p=>{this.#t=null,r(new V(String(p))),a.removeListener("exit",u),a.kill()};a.once("error",c);let u=(p,h)=>{this.#t=null,r(new V(`Query Engine exited with code ${p} and signal ${h}`))};return a.once("exit",u),a.stdout.on("data",i),this.#e.debug&&(a.stderr.on("data",console.error.bind(console,"[Query Engine]")),a.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,et.once)(e,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#a();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let r=He(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,tt.mkdir)(r,{recursive:!0});let{binaryTarget:o}=this.#e.platform,n=o==="windows"?".exe":"",s=(0,rt.join)(r,`query-engine-${o}${n}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(ar==="1"||await je(s)===!1)&&await this.#n({commitHash:e,extension:n,engineBinaryPath:s}),s}async#a(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let 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#n(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}`);Ye&&await(0,ot.setTimeout)(Number(Ye)),await Ue(await i.arrayBuffer(),n),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",n)}#o(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.#o(r),a=await fetch(`${n}/transaction/${e}/${o}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!a.ok)throw await L.fromResponse(a);try{return await a.json()}catch{return{}}}};V=class extends Error{name="EngineStartError"},L=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)}}});async function st(t){let{output:e,success:r}=(0,S.safeParse)(cr,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var S,cr,at=D(()=>{"use strict";l();S=require("valibot"),cr=(0,S.object)({tags:(0,S.union)([(0,S.pipe)((0,S.array)((0,S.string)()),(0,S.minLength)(1)),(0,S.literal)("all")])})});async function it(t){return ye===void 0&&(ye=await $.Server.create({databaseUrl:t.get("db").connectionString,maxResponseSize:(0,$.parseSize)("128 MiB"),queryTimeout:(0,$.parseDuration)("PT5M"),maxTransactionTimeout:(0,$.parseDuration)("PT5M"),maxTransactionWaitTime:(0,$.parseDuration)("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:t.get("debug")?"debug":"off"}})),ye}var $,re,ye,ct=D(()=>{"use strict";l();$=require("@prisma/query-plan-executor"),re=require("@prisma/query-plan-executor")});async function be(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 dt(t){let e=t.req.param("schemaHash"),r=oe.get(e);return r==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:r}}async function lt(t,e,r){let o=Pe.Buffer.from(t,"base64").toString("utf8"),n=(0,ut.produceSchema)(o,a=>{a.datasource('"postgresql"',e.toString())});r&&console.log("[Accelerate] schema with override:",n);let s=await be(n);return{base64Override:Pe.Buffer.from(n,"utf8").toString("base64"),overrideHash:s}}var Pe,ut,oe,pt=D(()=>{"use strict";l();Pe=require("buffer"),ut=require("@mrleebo/prisma-ast"),oe=new Map});function ne(t){let{req:e}=t;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}var mt=D(()=>{"use strict";l()});async function ft(t){let{issues:e,output:r,success:o}=(0,m.safeParse)(ur,await t.req.json(),{abortEarly:!0});return o?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}function gt(t,e){let{output:r,success:o}=(0,m.safeParse)(dr,t);return o?r:e.json({EngineMalfunction:{}},500)}var m,ur,dr,ht=D(()=>{"use strict";l();m=require("valibot"),ur=(0,m.object)({isolation_level:(0,m.optional)((0,m.string)()),max_wait:(0,m.pipe)((0,m.number)(),(0,m.integer)(),(0,m.minValue)(0)),timeout:(0,m.pipe)((0,m.number)(),(0,m.integer)(),(0,m.minValue)(0))});dr=(0,m.looseObject)({id:(0,m.union)([(0,m.string)(),(0,m.number)()])})});var bt={};Ae(bt,{accelerateRoute:()=>G});async function Se(t){let{req:e}=t,r=dt(t);if(r instanceof Response)return r;let{base64Override:o,overrideHash:n}=r.schemas;return await B.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 yt,Pt,I,G,lr,K,pr,mr,St=D(()=>{"use strict";l();yt=require("hono/http-exception"),Pt=require("hono/tiny"),I=require("hono/validator");ie();at();he();ct();pt();mt();ht();G=new Pt.Hono;G.post("/invalidate",(0,I.validator)("header",k),async t=>{let e=await st(t);return e instanceof Response?e:t.body(null)});lr="/:clientVersion/:schemaHash",K=G.basePath(lr);G.route("/",K);pr=["/graphql","/itx/:transactionId/graphql"];K.on("POST",[...pr],(0,I.validator)("header",k),async t=>{let{req:e}=t;try{let r=await Se(t);if(r instanceof Response)return r;let o=await e.text(),n=e.param("transactionId"),s=await r.request(o,{...ne(t),"X-transaction-id":n});return t.text(s)}catch(r){return te(r,t)}});K.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,I.validator)("header",k),async t=>{let{req:e}=t;try{let r=await Se(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,ne(t));return t.json(a)}catch(r){return te(r,t)}});K.put("/schema",(0,I.validator)("header",k),async t=>{let{req:e}=t,r=await e.text();if(!r)return t.text("Missing schema",400);let o=e.param("schemaHash"),n=oe.get(o);if(n==null){if(o!==await be(r))return t.text("Schema hash mismatch",400);let s=await lt(r,t.get("db").prismaORMConnectionString,t.get("debug"));return oe.set(o,{base64Original:r,...s}),t.text(o)}return r!==n.base64Original?t.text("Schema mismatch",400):t.text(o)});K.post("/transaction/start",(0,I.validator)("header",k),async t=>{let{req:e}=t,r=await ft(t);if(r instanceof Response)return r;try{let o=await Se(t);if(o instanceof Response)return o;let n=await o.startTransaction(r,ne(t)),s=gt(n,t);if(s instanceof Response)return s;let{id:a}=s,i=e.param("clientVersion"),c=t.get("port"),u=t.get("protocol"),p=e.param("schemaHash");return t.json({...n,"data-proxy":{endpoint:`${u}://localhost:${c}/${i}/${p}/itx/${a}`}})}catch(o){return te(o,t)}});mr=[["/connection-info","GET"],["/query","POST"],["/transaction/start","POST"],["/transaction/:transactionId/commit","POST"],["/transaction/:transactionId/query","POST"],["/transaction/:transactionId/rollback","POST"]];for(let[t,e]of mr)G.on(e,t,(0,I.validator)("header",k),async r=>{let o=r.req.header("prisma-engine-hash");if(o!=="0.0.0"&&o!==re.version)throw new yt.HTTPException(400,{message:`Using an HTTP connection string is not supported with Prisma Client version ${o} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${re.version}.`});return await(await it(r)).fetch(r.req.raw)})});var Dt={};Ae(Dt,{utilityRoute:()=>ve});var vt,wt,ve,io,Et=D(()=>{"use strict";l();vt=require("hono/tiny"),wt=require("http-status-codes"),ve=new vt.Hono;ve.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},wt.StatusCodes.CREATED)});io=ve.get("/health",t=>t.json({name:t.get("serverState").name}))});var Sr={};module.exports=Gt(Sr);l();var Lt=require("timers/promises");l();ie();l();var We=require("pathe/utils");X();l();var _=require("get-port-please"),Z=require("remeda"),N=51214,q=51213,F=51215,Y=65535,A=-1/0;async function Ke(t){let{debug:e,name:r,requestedPorts:o,servers:n}=t,{portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a}=er(r,n);e&&(console.debug(`ports used by other servers: ${Object.keys(s).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(a)}`));let i={databasePort:A,port:A,shadowDatabasePort:A},c=["port","databasePort","shadowDatabasePort"];for(let u of c){let p=await Yt({debug:e,portKey:u,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a,requestedPorts:o})??await Zt({debug:e,pickedPorts:i,portKey:u,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a});e&&console.debug(`Got port for "${u}": ${p}`),i[u]=p}return e&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function Yt(t){let{debug:e,portKey:r,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:n,requestedPorts:s}=t,{[r]:a,...i}=s;if(Ge(a))return await tr({debug:e,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:o,requestedPort:a}),a;let c=n?.[r]??A;if(!Ge(c))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let u=c in o;return u||Object.values(i).includes(c)?(e&&console.debug(`Port ${c} that was used last time for this server, ${u?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,_.checkPort)(c)===!1?(e&&console.debug(`Port ${c}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(e&&console.debug(`Using port ${c} for "${r}" as it was used last time and is available.`),c)}async function Zt(t){let{debug:e,pickedPorts:r,portKey:o,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s}=t,a=Math.max(N,q,F)+1,i=[...Object.values(r),...Object.keys(n).map(Number),...Object.values(s||{})],c=Math.min(Math.max(a,...i)+100,Y),u=(0,Z.difference)((0,Z.range)(a,c),i),p={port:q,databasePort:N,shadowDatabasePort:F}[o];try{return await(0,_.getPort)({port:p in n||Object.values(r).includes(p)||Object.values(s||{}).includes(p)?void 0:p,ports:u})}catch(h){if(h instanceof Error&&h.name==="GetPortError"&&c+1<=Y)return e&&console.debug(`Expanding port lookup to range [${c+1}, ${Y}].`),await(0,_.getPort)({portRange:[c+1,Y]});throw h}}function Ge(t){return t>=0}function er(t,e){let r={},o;for(let n of e){let{databasePort:s,port:a,shadowDatabasePort:i}=n;if(n.name===t){o={databasePort:s,port:a,shadowDatabasePort:i};continue}r[s]=!0,r[a]=!0,r[i]=!0}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:o}}async function tr(t){let{debug:e,otherRequestedPorts:r,portKey:o,portsUsedByOtherServers:n,requestedPort:s}=t;if(s in n)throw e&&console.error(`Port ${s} was requested for "${o}", but is already used by another server.`),new me(s);if(Object.values(r).includes(s))throw e&&console.error(`Port ${s} was requested for "${o}", but also for another key.`),new pe(s);if((0,_.isUnsafePort)(s))throw e&&console.error(`Port ${s} was requested for "${o}", but is unsafe.`),new E(s);if(await(0,_.checkPort)(s)===!1)throw e&&console.error(`Port ${s} was requested for "${o}", but is not available.`),new E(s)}var E=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},pe=class extends Error{constructor(r){super(`Port number \`${r}\` was requested twice. Please choose a different port for each service.`);this.port=r}name="PortRequestedTwiceError"},me=class extends Error{constructor(r){super(`Port number \`${r}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=r}name="PortBelongsToAnotherServerError"};var P={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},rr=`postgres://${P.username}:${P.password}@localhost`,ze=new URLSearchParams({sslmode:P.sslMode}),or=new URLSearchParams({...Object.fromEntries(ze.entries()),connection_limit:String(P.connectionLimit),connect_timeout:String(P.connectTimeout),max_idle_connection_lifetime:String(P.maxIdleConnectionLifetime),pool_timeout:String(P.poolTimeout),single_use_connections:"true",socket_timeout:String(P.socketTimeout)});async function fe(t,e){let r=t==="database"?e.databasePort:e.shadowDatabasePort;if(e.dryRun)return Qe(t,e,{db:null,port:r,server:null});let{debug:o}=e,s=await(t==="shadow_database"?nr:Xe)(e.pgliteDataDirPath,o);o&&s.onNotification((c,u)=>{console.debug(`[${t}][${c}] ${u}`)});let{PGLiteSocketServer:a}=await import("@electric-sql/pglite-socket"),i=new a({db:s,debug:o,inspect:o,port:r});o&&(i.addEventListener("listening",c=>{let{detail:u}=c;console.debug(`[${t}] server listening on ${JSON.stringify(u)}`)}),i.addEventListener("connection",c=>{let{clientAddress:u,clientPort:p}=c.detail;console.debug(`[${t}] client connected from ${u}:${p}`)}),i.addEventListener("error",c=>{let{detail:u}=c;console.error(`[${t}] server error:`,u)}));try{await i.start()}catch(c){throw c instanceof Error&&"code"in c&&c.code==="EADDRINUSE"?new E(r):c}return Qe(t,e,{db:s,port:r,server:i})}function Qe(t,e,r){let{debug:o}=e,{db:n,port:s,server:a}=r||{};return o&&console.debug(`[${t}] server started on port ${s}`),{...P,close:async()=>{let i=[];try{await a?.stop(),o&&console.debug(`[${t}] server stopped on port ${s}`)}catch(c){console.error(`[${t}] server stop error`,c),i.push(c)}if(t==="database")try{await n?.syncToFs(),o&&console.debug(`[${t}] synced to filesystem`)}catch(c){console.error(`[${t}] sync error`,c),i.push(c)}try{await n?.close(),o&&console.debug(`[${t}] closed`)}catch(c){console.error(`[${t}] close error`,c),i.push(c)}if(i.length>0)throw new AggregateError(i,`Failed to close ${t} properly`)},connectionString:Je(s,ze),dump:async i=>{t==="shadow_database"||!n||await sr({db:n,debug:o,destinationPath:i})},port:s,prismaORMConnectionString:Je(s,or),terminalCommand:`PGPASSWORD=${P.password} PGSSLMODE=${P.sslMode} psql -h localhost -p ${s} -U ${P.username} -d ${P.database}`}}function Je(t,e){return`${rr}:${t}/${P.database}?${e.toString()}`}async function Xe(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:P.database,dataDir:t,debug:e?5:void 0,relaxedDurability:!1,username:P.username})}async function nr(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:P.database,dataDir:"memory://",debug:e?5:void 0,relaxedDurability:!1,username:P.username})}async function sr(t){let{dataDir:e,db:r,debug:o,destinationPath:n}=t,s=r||await Xe(e,o),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),i=await a({args:["--schema-only","--no-owner"],fileName:n?(0,We.filename)(n):void 0,pg:await s.clone()});return n?(o&&console.debug(`[DB] Dumping database to ${n}`),await Ne(i,n)):(o&&console.debug("[DB] Dumping database to memory"),await i.text())}l();var xt=require("http"),Rt=require("util"),Ot=v(require("@prisma/get-platform"),1);ge();he();async function At(t,e){let{port:r}=e;if(e.dryRun)return Tt(r,null);let o=await fr(r,t,e),{promise:n,reject:s,resolve:a}=ee(),{serve:i}=await import("@hono/node-server"),c=i({createServer:xt.createServer,fetch:o.fetch,overrideGlobalObjects:!1,port:r},a);return c.on("error",u=>{if(typeof u=="object"&&"code"in u&&u.code==="EADDRINUSE")return s(new E(r));console.error("[Accelerate]",u)}),await n,Tt(r,c)}function Tt(t,e){return{async close(){e&&await Promise.allSettled([(0,Rt.promisify)(e.close.bind(e))(),B.stopAll()])},port:t,url:`http://localhost:${t}`}}async function fr(t,e,r){let{debug:o}=r,[{Hono:n},{accelerateRoute:s},{utilityRoute:a}]=await Promise.all([import("hono/tiny"),Promise.resolve().then(()=>(St(),bt)),Promise.resolve().then(()=>(Et(),Dt))]),i=new n,c=await Ot.default.getPlatformInfo();if(o&&console.debug("[Accelerate] platform info: %s",JSON.stringify(c)),o){let{logger:p}=await import("hono/logger");i.use("*",p((...h)=>console.log("[Accelerate]",...h)))}i.use("*",async(p,h)=>(p.set("db",e),p.set("debug",!!o),p.set("platform",c),p.set("port",t),p.set("protocol","http"),p.set("serverState",r),p.set("shadowDBPort",r.shadowDatabasePort),await h()));let u=new n;return u.route("/",s),u.route("/",a),i.route("/",u),i}l();var Ct=require("fs/promises"),C=require("pathe"),H=require("proper-lockfile"),Re=require("std-env"),d=require("valibot");X();l();var gr=require("timers/promises"),_t=require("std-env");function $t(t,e){if(t==null)return!1;try{return _t.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var Ee=(0,d.pipe)((0,d.string)(),(0,d.url)()),kt=(0,d.object)({connectionString:Ee,prismaORMConnectionString:(0,d.optional)(Ee),terminalCommand:(0,d.optional)((0,d.string)())}),It=(0,d.object)({url:Ee}),we=(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(1)),hr=(0,d.object)({database:kt,http:It,ppg:It,shadowDatabase:kt}),yr=(0,d.object)({databasePort:we,exports:(0,d.optional)(hr),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:we,shadowDatabasePort:we,version:(0,d.literal)("1")}),Oe=Symbol("initialize"),De="default",T=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??A,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??De,this.persistenceMode=e.persistenceMode,this.pid=e.pid??Re.process.pid,this._port=e.port??A,this._shadowDatabasePort=e.shadowDatabasePort??A}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new Q(e):new Te(e);return await r[Oe](),r}static async fromServerDump(e){let{debug:r,name:o=De}=e??{},n=U(o),s=Q.getServerDumpPath(n),a=await qe(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:c,success:u}=(0,d.safeParse)((0,d.pipe)((0,d.string)(),(0,d.parseJson)(),yr),a);if(!u)throw r&&console.debug(`[State] Invalid server dump file at "${s}":
4
+ ${JSON.stringify(i,null,2)}`),new Error(`Invalid Prisma Dev state for "${o}".`);return new Q({databasePort:c.databasePort,debug:r,dryRun:!1,name:o,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(e){let{debug:r,globs:o}=e??{},n=(0,C.join)(U(De),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let s=await Ve(n,o);return r&&console.debug(`[State] found server names: ${JSON.stringify(s)}`),await Promise.all(s.map(a=>Pr(a,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},Te=class extends T{constructor(e){super({...e,databasePort:e?.databasePort??N,persistenceMode:"stateless",port:e?.port??q,shadowDatabasePort:e?.shadowDatabasePort??F})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[Oe](){}async close(){}async writeServerDump(){}},Q=class t extends T{#r;#e;#t;#s;#a;#n;#o;constructor(e){super({...e,persistenceMode:"stateful"}),this.#n=!1,this.#e=U(this.name),this.#r=(0,C.join)(this.#e,"db_dump.bak"),this.#t=(0,C.join)(this.#e,".lock"),this.#s=(0,C.join)(this.#e,".pglite"),this.#o=e?.serverDump??null,this.#a=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,C.join)(e,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#o?.exports}get pgliteDataDirPath(){return this.#s}async[Oe](){await Fe(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,H.lock)(this.#e,{lockfilePath:this.#t}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await T.scan({debug:this.debug,onlyMetadata:!0}),r=await Ke({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new se(this):e}}async close(){if(!this.#n)try{await(0,H.unlock)(this.#e,{lockfilePath:this.#t}),this.#n=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,e),e}}async writeServerDump(e){this.#o={name:this.name,version:"1",pid:Re.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,Ct.writeFile)(this.#a,`${JSON.stringify(this.#o,null,2)}
5
+ `,{encoding:"utf-8"})}};async function Pr(t,e){let{debug:r,onlyMetadata:o}=e||{},n=typeof t=="string"?t:t.name,s=typeof t!="string"?t:void 0,a={databasePort:s?.databasePort??-1,exports:s?.exports,name:n,pid:s?.pid,port:s?.port??-1,shadowDatabasePort:s?.shadowDatabasePort??-1,version:"1"};try{let i=s||await T.fromServerDump({debug:r,name:n});if(!i)return r&&console.debug(`[State] no server state found for name: ${n}`),{...a,status:"no_such_server"};a.databasePort=i.databasePort,a.exports=i.exports,a.pid=i.pid,a.port=i.port,a.shadowDatabasePort=i.shadowDatabasePort;let{exports:c,pid:u}=i;if(o)return{...a,status:"unknown"};if(!$t(u,r))return r&&console.debug(`[State] server state for "${n}" has no running process with PID: ${u}`),{...a,status:"not_running"};let p=U(n);try{if(!await(0,H.check)(p,{lockfilePath:(0,C.join)(p,".lock")}))return r&&console.debug(`[State] server state for "${n}" is not locked, indicating it is not running.`),{...a,status:"starting_up"}}catch(j){r&&console.error(`[State] server state for "${n}" failed to check lock:`,j)}if(!c)return{...a,status:"starting_up"};let{http:h}=c,{hc:b}=await import("hono/client"),x=await b(h.url).health.$get();if(!x.ok)return r&&console.debug(`[State] server state for "${n}" is not live: ${JSON.stringify(x)}`),{...a,status:"not_running"};let R=await x.json();return R.name!==t?(r&&console.debug(`[State] server state for "${n}" has mismatched health response: ${JSON.stringify(R)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(R)}`),{...a,status:"running"})}catch(i){return r&&console.error(`[State] failed to get server status for "${n}":`,i),{...a,status:"error"}}}var xe=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},se=class extends xe{#r;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#r=e}get server(){return T.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};async function Mt(t){let e=await T.createExclusively(t),[r,o]=await Promise.all([fe("database",e),fe("shadow_database",e)]),n=await At(r,e),s=`prisma+postgres://localhost:${n.port}/?${new URLSearchParams({api_key:ke({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(c,u){let h=(await Promise.allSettled(u.map(b=>b.close()))).filter(b=>b.status==="rejected").map(b=>new Error(b.reason));try{await c.close()}catch(b){h.push(b)}if(h.length>0)throw new AggregateError(h,"Failed to close some servers")}}var ae;process.once("SIGTERM",()=>{console.log("SIGTERM received, shutting down..."),process.removeAllListeners("SIGINT"),process.exitCode=143,ae?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{console.log("SIGINT received, shutting down..."),process.removeAllListeners("SIGTERM"),process.exitCode=130,ae?.close().finally(()=>process.exit())});async function br(){let[,,t]=process.argv;if(!t)return process.send?.({type:"error",error:'Missing "name" argument, server cannot be started'},void 0),process.exit(1);try{ae=await Mt({debug:!0,persistenceMode:"stateful",name:t}),process.send?.({type:"started",server:ae},void 0)}catch(e){console.error(e);let r=e instanceof Error?e.message:String(e);process.send?.({type:"error",error:r},void 0),await(0,Lt.setTimeout)(1e3),process.exit(1)}}br();
package/dist/daemon.d.cts CHANGED
@@ -1,2 +1,17 @@
1
+ import { Server } from './index.cjs';
2
+ import './state.cjs';
3
+ import 'valibot';
4
+ import './db.cjs';
5
+ import '@electric-sql/pglite';
1
6
 
2
- export { }
7
+ interface DaemonMessageStarted {
8
+ type: "started";
9
+ server: Omit<Server, "close">;
10
+ }
11
+ interface DaemonMessageError {
12
+ type: "error";
13
+ error: string;
14
+ }
15
+ type DaemonMessage = DaemonMessageStarted | DaemonMessageError;
16
+
17
+ export type { DaemonMessage, DaemonMessageError, DaemonMessageStarted };
package/dist/daemon.d.ts CHANGED
@@ -1,2 +1,17 @@
1
+ import { Server } from './index.js';
2
+ import './state.js';
3
+ import 'valibot';
4
+ import './db.js';
5
+ import '@electric-sql/pglite';
1
6
 
2
- export { }
7
+ interface DaemonMessageStarted {
8
+ type: "started";
9
+ server: Omit<Server, "close">;
10
+ }
11
+ interface DaemonMessageError {
12
+ type: "error";
13
+ error: string;
14
+ }
15
+ type DaemonMessage = DaemonMessageStarted | DaemonMessageError;
16
+
17
+ export type { DaemonMessage, DaemonMessageError, DaemonMessageStarted };
package/dist/daemon.js CHANGED
@@ -1 +1 @@
1
- import{setTimeout as t}from"timers/promises";var r;process.once("SIGTERM",()=>{process.removeAllListeners("SIGINT"),process.exitCode=143,r?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{process.removeAllListeners("SIGTERM"),process.exitCode=130,r?.close().finally(()=>process.exit())});async function n(){let[,,s]=process.argv;if(!s)return process.send?.({type:"error",error:'Missing "name" argument, server cannot be started'},void 0,{keepOpen:!1}),process.exit(1);try{let{unstable_startServer:e}=await import("./index.js");r=await e({debug:!0,persistenceMode:"stateful",name:s}),r.close=void 0,process.send?.({type:"started",server:r},void 0,{keepOpen:!1})}catch(e){let o=e instanceof Error?e.message:String(e);process.send?.({type:"error",error:o},void 0,{keepOpen:!1}),await t(1e3),process.exit(1)}}n();
1
+ import{a as o}from"./chunk-LAXEWQZE.js";import"./chunk-RBVZVBDC.js";import"./chunk-FZ7JBZR6.js";import"./chunk-LMPFMHCB.js";import"./chunk-7EOUKLQR.js";import"./chunk-EPFUMVT3.js";import{setTimeout as n}from"timers/promises";var r;process.once("SIGTERM",()=>{console.log("SIGTERM received, shutting down..."),process.removeAllListeners("SIGINT"),process.exitCode=143,r?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{console.log("SIGINT received, shutting down..."),process.removeAllListeners("SIGTERM"),process.exitCode=130,r?.close().finally(()=>process.exit())});async function a(){let[,,s]=process.argv;if(!s)return process.send?.({type:"error",error:'Missing "name" argument, server cannot be started'},void 0),process.exit(1);try{r=await o({debug:!0,persistenceMode:"stateful",name:s}),process.send?.({type:"started",server:r},void 0)}catch(e){console.error(e);let t=e instanceof Error?e.message:String(e);process.send?.({type:"error",error:t},void 0),await n(1e3),process.exit(1)}}a();
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as f}from"./chunk-RBVZVBDC.js";import{a as w,g as R}from"./chunk-FZ7JBZR6.js";import{a as h,b,c as A,f as d}from"./chunk-LMPFMHCB.js";import{a as u,c as v,d as g}from"./chunk-7EOUKLQR.js";import"./chunk-EPFUMVT3.js";import{createServer as D}from"http";import{promisify as O}from"util";import C from"@prisma/get-platform";async function P(a,e){let{port:r}=e;if(e.dryRun)return y(r,null);let t=await x(r,a,e),{promise:s,reject:S,resolve:c}=v(),{serve:i}=await import("@hono/node-server"),m=i({createServer:D,fetch:t.fetch,overrideGlobalObjects:!1,port:r},c);return m.on("error",o=>{if(typeof o=="object"&&"code"in o&&o.code==="EADDRINUSE")return S(new d(r));console.error("[Accelerate]",o)}),await s,y(r,m)}function y(a,e){return{async close(){e&&await Promise.allSettled([O(e.close.bind(e))(),g.stopAll()])},port:a,url:`http://localhost:${a}`}}async function x(a,e,r){let{debug:t}=r,[{Hono:s},{accelerateRoute:S},{utilityRoute:c}]=await Promise.all([import("hono/tiny"),import("./accelerate-MVW5ZKXM.js"),import("./utility-YJ4TFSMW.js")]),i=new s,m=await C.getPlatformInfo();if(t&&console.debug("[Accelerate] platform info: %s",JSON.stringify(m)),t){let{logger:n}=await import("hono/logger");i.use("*",n((...p)=>console.log("[Accelerate]",...p)))}i.use("*",async(n,p)=>(n.set("db",e),n.set("debug",!!t),n.set("platform",m),n.set("port",a),n.set("protocol","http"),n.set("serverState",r),n.set("shadowDBPort",r.shadowDatabasePort),await p()));let o=new s;return o.route("/",S),o.route("/",c),i.route("/",o),i}async function G(a){let e=await w.createExclusively(a),[r,t]=await Promise.all([f("database",e),f("shadow_database",e)]),s=await P(r,e),S=`prisma+postgres://localhost:${s.port}/?${new URLSearchParams({api_key:u({databaseUrl:r.prismaORMConnectionString,name:e.name,shadowDatabaseUrl:t.prismaORMConnectionString})}).toString()}`,c={database:{connectionString:r.connectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand},http:{url:s.url},ppg:{url:S},shadowDatabase:{connectionString:t.prismaORMConnectionString,prismaORMConnectionString:t.prismaORMConnectionString,terminalCommand:t.terminalCommand}};return await e.writeServerDump(c),{...c,close:()=>i(e,[s,r,t]),name:e.name};async function i(m,o){let p=(await Promise.allSettled(o.map(l=>l.close()))).filter(l=>l.status==="rejected").map(l=>new Error(l.reason));try{await m.close()}catch(l){p.push(l)}if(p.length>0)throw new AggregateError(p,"Failed to close some servers")}}export{h as DEFAULT_DATABASE_PORT,b as DEFAULT_SERVER_PORT,A as DEFAULT_SHADOW_DATABASE_PORT,d as PortNotAvailableError,R as ServerAlreadyRunningError,G as unstable_startServer};
1
+ import{a as f}from"./chunk-LAXEWQZE.js";import"./chunk-RBVZVBDC.js";import{g as e}from"./chunk-FZ7JBZR6.js";import{a,b,c,f as d}from"./chunk-LMPFMHCB.js";import"./chunk-7EOUKLQR.js";import"./chunk-EPFUMVT3.js";export{a as DEFAULT_DATABASE_PORT,b as DEFAULT_SERVER_PORT,c as DEFAULT_SHADOW_DATABASE_PORT,d as PortNotAvailableError,e as ServerAlreadyRunningError,f as unstable_startServer};
package/package.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "name": "@prisma/dev",
3
- "version": "0.0.0-dev.202510282348",
3
+ "version": "0.0.0-dev.202510290238",
4
4
  "description": "A local Prisma Postgres server for development and testing",
5
5
  "type": "module",
6
+ "author": "Igal Klebanov <igalklebanov@gmail.com>",
6
7
  "main": "./dist/index.cjs",
7
8
  "module": "./dist/index.js",
8
9
  "types": "./dist/index.d.ts",