@prisma/dev 0.24.16 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,23 +1,23 @@
1
- "use strict";var jn=Object.create;var ge=Object.defineProperty;var Vn=Object.getOwnPropertyDescriptor;var Kn=Object.getOwnPropertyNames;var zn=Object.getPrototypeOf,Jn=Object.prototype.hasOwnProperty;var v=(e,t)=>()=>(e&&(t=e(e=0)),t);var V=(e,t)=>{for(var r in t)ge(e,r,{get:t[r],enumerable:!0})},qt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Kn(t))!Jn.call(e,s)&&s!==r&&ge(e,s,{get:()=>t[s],enumerable:!(n=Vn(t,s))||n.enumerable});return e};var D=(e,t,r)=>(r=e!=null?jn(zn(e)):{},qt(t||!e||!e.__esModule?ge(r,"default",{value:e,enumerable:!0}):r,e)),Yn=e=>qt(ge({},"__esModule",{value:!0}),e);var Xn,h,m=v(()=>{"use strict";Xn=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,h=Xn()});var A,fe=v(()=>{"use strict";m();A=class extends Error{constructor(r,n,s){super(n,s);this.status=r}name="HTTPError"}});function Ft(e){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([[t],[r]])=>t.localeCompare(r)))),"utf8").toString("base64url")}function es(e){let t=Buffer.from(e,"base64url").toString("utf8"),{issues:r,output:n,success:s}=(0,P.safeParse)(Zn,t,{abortEarly:!0});return s?[null,n]:[r]}function W(e,t){let r=e.headers.authorization;if(!r)throw new A(401,"Missing API Key");let[n,s="",o]=r.split(" ");if(n!=="Bearer"||o)throw new A(401,"Invalid API Key");let[a,i]=es(s);if(a)throw new A(401,"Invalid API Key",{cause:a.join(", ")});let{databaseUrl:c,name:u,shadowDatabaseUrl:l}=i,f=t.name,d=t.port;if(!u)throw new A(401,`Wrong API Key; The Prisma Dev server running at port ${d} requires an API Key from a newer version of \`prisma dev\`. Check the "${f}" server's output for the updated \`DATABASE_URL\` value.`);if(u!==f)throw new A(401,`Wrong API Key; The Prisma Dev server running at port ${d} is named "${f}", but the API Key is for "${u}"`);let{hostname:p,port:y}=new URL(c),{port:E}=t.db,{hostname:re,port:Ce}=new URL(l),Gn=t.shadowDBPort;if(p!=="localhost"||Number(y)!==E||re!=="localhost"||Number(Ce)!==Gn)throw new A(401,"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 i}var P,Ht,Zn,Ue=v(()=>{"use strict";m();P=require("valibot");fe();Ht=/^(postgres|postgresql):\/\//,Zn=(0,P.pipe)((0,P.string)(),(0,P.parseJson)(),(0,P.object)({databaseUrl:(0,P.pipe)((0,P.string)(),(0,P.url)(),(0,P.regex)(Ht)),name:(0,P.optional)((0,P.pipe)((0,P.string)(),(0,P.minLength)(1))),shadowDatabaseUrl:(0,P.pipe)((0,P.string)(),(0,P.url)(),(0,P.regex)(Ht))}))});function He(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),he.default.platform==="darwin"?ts(e):he.default.platform==="win32"?rs(e):ns(e)}var w,Qe,he,U,qe,K,ts,rs,ns,Wt=v(()=>{"use strict";m();w=D(require("path"),1),Qe=D(require("os"),1),he=D(require("process"),1),U=Qe.default.homedir(),qe=Qe.default.tmpdir(),{env:K}=he.default,ts=e=>{let t=w.default.join(U,"Library");return{data:w.default.join(t,"Application Support",e),config:w.default.join(t,"Preferences",e),cache:w.default.join(t,"Caches",e),log:w.default.join(t,"Logs",e),temp:w.default.join(qe,e)}},rs=e=>{let t=K.APPDATA||w.default.join(U,"AppData","Roaming"),r=K.LOCALAPPDATA||w.default.join(U,"AppData","Local");return{data:w.default.join(r,e,"Data"),config:w.default.join(t,e,"Config"),cache:w.default.join(r,e,"Cache"),log:w.default.join(r,e,"Log"),temp:w.default.join(qe,e)}},ns=e=>{let t=w.default.basename(U);return{data:w.default.join(K.XDG_DATA_HOME||w.default.join(U,".local","share"),e),config:w.default.join(K.XDG_CONFIG_HOME||w.default.join(U,".config"),e),cache:w.default.join(K.XDG_CACHE_HOME||w.default.join(U,".cache"),e),log:w.default.join(K.XDG_STATE_HOME||w.default.join(U,".local","state"),e),temp:w.default.join(qe,t,e)}}});function Kt(e,t){return`${Se.cache}/engine/${e}/${t}`}function ne(e){return`${Se.data}/${e}`}async function z(e){try{return await(0,R.access)(e,R.constants.F_OK),!0}catch(t){if(Fe(t))return!1;throw t}}async function zt(e,t){let r=await ss(e);await(0,R.writeFile)(t,r),await(0,R.chmod)(t,"755")}async function Jt(e,t){await e.stream().pipeTo(ye.WriteStream.toWeb((0,ye.createWriteStream)(t,{encoding:"utf8"})))}function Fe(e){return e!=null&&typeof e=="object"&&"code"in e&&e.code==="ENOENT"}async function Yt(e){try{return await(0,R.readFile)(e,{encoding:"utf-8"})}catch(t){if(Fe(t))return null;throw t}}async function Xt(e){await(0,R.mkdir)(e,{recursive:!0})}async function Zt(e,t){try{return(await(0,R.readdir)(e,{withFileTypes:!0})).reduce((n,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!t||(0,Vt.default)(t,s.name))&&n.push(s.name),n),[])}catch(r){if(Fe(r))return[];throw r}}async function J(e){await(0,R.rm)(e,{force:!0,recursive:!0})}var ye,R,Gt,jt,Vt,Se,ss,Y=v(()=>{"use strict";m();ye=require("fs"),R=require("fs/promises"),Gt=require("util"),jt=require("zlib");Wt();Vt=D(require("zeptomatch"),1),Se=He("prisma-dev"),ss=(0,Gt.promisify)(jt.unzip)});async function Ve(e){let{debug:t,name:r,requestedPorts:n,servers:s}=e,{portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a}=is(r,s);t&&(console.debug(`ports used by other servers: ${Object.keys(o).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(a)}`));let i={databasePort:_,port:_,shadowDatabasePort:_,streamsPort:_},c=["port","databasePort","shadowDatabasePort","streamsPort"];for(let u of c){let l=await os({debug:t,portKey:u,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a,requestedPorts:n})??await as({debug:t,pickedPorts:i,portKey:u,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a});t&&console.debug(`Got port for "${u}": ${l}`),i[u]=l}return t&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function os(e){let{debug:t,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s,requestedPorts:o}=e,{[r]:a,...i}=o;if(We(a))return await ls({debug:t,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:n,requestedPort:a}),a;let c=s?.[r]??_;if(!We(c))return t&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let u=c in n;return u||Object.values(i).includes(c)?(t&&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,Q.checkPort)(c)===!1?(t&&console.debug(`Port ${c}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(t&&console.debug(`Using port ${c} for "${r}" as it was used last time and is available.`),c)}async function as(e){let{debug:t,pickedPorts:r,portKey:n,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:o}=e,a=Math.max(Pe,we,Ee,ve)+1,i=Object.values(r).filter(p=>p!==void 0),c=o?us(o):[],u=[...i,...Object.keys(s).map(Number),...c],l=Math.min(Math.max(a,...u)+100,be),f=(0,Re.difference)((0,Re.range)(a,l),u),d={port:we,databasePort:Pe,shadowDatabasePort:Ee,streamsPort:ve}[n];try{return await(0,Q.getPort)({port:d in s||i.includes(d)||c.includes(d)?void 0:d,ports:f})}catch(p){if(p instanceof Error&&p.name==="GetPortError"&&l+1<=be)return t&&console.debug(`Expanding port lookup to range [${l+1}, ${be}].`),await(0,Q.getPort)({portRange:[l+1,be]});throw p}}function We(e){return Number.isFinite(e)&&e>=0}function is(e,t){let r={},n;for(let s of t){let{databasePort:o,port:a,shadowDatabasePort:i}=s,c=cs(s);if(s.name===e){n={databasePort:o,port:a,shadowDatabasePort:i,streamsPort:c};continue}r[o]=!0,r[a]=!0,r[i]=!0,We(c)&&(r[c]=!0)}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}function cs(e){let t=e.experimental?.streams?.serverUrl;if(!t)return _;try{let r=Number(new URL(t).port);return Number.isInteger(r)&&r>0?r:_}catch{return _}}function us(e){return[e.port,e.databasePort,e.shadowDatabasePort,e.streamsPort]}async function ls(e){let{debug:t,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:s,requestedPort:o}=e;if(o!==G){if(o in s)throw t&&console.error(`Port ${o} was requested for "${n}", but is already used by another server.`),new je(o);if(Object.values(r).includes(o))throw t&&console.error(`Port ${o} was requested for "${n}", but also for another key.`),new Ge(o);if((0,Q.isUnsafePort)(o))throw t&&console.error(`Port ${o} was requested for "${n}", but is unsafe.`),new N(o);if(await(0,Q.checkPort)(o)===!1)throw t&&console.error(`Port ${o} was requested for "${n}", but is not available.`),new N(o)}}var Q,Re,Pe,we,Ee,ve,be,G,_,N,Ge,je,se=v(()=>{"use strict";m();Q=require("get-port-please"),Re=require("remeda"),Pe=51214,we=51213,Ee=51215,ve=51216,be=65535,G=0,_=-1/0;N=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},Ge=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"},je=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"}});function T(e,t,r=200){let n=ct.Buffer.from(JSON.stringify(t),"utf8");e.headersSent||(e.setHeader("Content-Type","application/json; charset=utf-8"),e.setHeader("Content-Length",n.byteLength),e.statusCode=r),e.end(n)}function x(e,t,r=200){let n=ct.Buffer.from(t,"utf8");e.headersSent||(e.setHeader("Content-Type","text/plain; charset=utf-8"),e.setHeader("Content-Length",n.byteLength),e.statusCode=r),e.end(n)}function Z(e,t=204){e.headersSent||(e.statusCode=t,e.setHeader("Content-Length",0)),e.end()}function qr(e,t){x(e,t.message,t.status)}var ct,C=v(()=>{"use strict";m();ct=require("buffer")});async function Fr(e,t){let r;try{r=await(0,Hr.json)(e)}catch{return x(t,"Invalid input",400),null}let{output:n,success:s}=(0,I.safeParse)(so,r,{abortEarly:!0});return s?n:(x(t,"Invalid input",400),null)}var Hr,I,so,Wr=v(()=>{"use strict";m();Hr=require("stream/consumers"),I=require("valibot");C();so=(0,I.object)({tags:(0,I.union)([(0,I.pipe)((0,I.array)((0,I.string)()),(0,I.minLength)(1)),(0,I.literal)("all")])})});async function dt(e){let r=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(a=>a.toString(16).padStart(2,"0")).join("")}function jr(e,t){let r=e.schemaHash;if(r==null)return T(t,{EngineNotStarted:{reason:"SchemaMissing"}},404),null;let n=_e.get(r);return n==null?(T(t,{EngineNotStarted:{reason:"SchemaMissing"}},404),null):{schemaHash:r,schemas:n}}async function Vr(e,t,r){let n=lt.Buffer.from(e,"base64").toString("utf8"),s=ao(n,t.toString());r&&console.log("[Accelerate] schema with override:",s);let o=await dt(s);return{base64Override:lt.Buffer.from(s,"utf8").toString("base64"),overrideHash:o}}function ao(e,t){let r=io(e);if(!r)throw new Error("No datasource block found in schema.");let n=e.slice(r.openBraceIndex+1,r.closeBraceIndex),s=lo(n,t,go(e,r.openBraceIndex));return`${e.slice(0,r.openBraceIndex+1)}${s}${e.slice(r.closeBraceIndex)}`}function io(e){let t="datasource";for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="/"&&e[r+1]==="/"){r=mt(e,r+2);continue}if(n==="/"&&e[r+1]==="*"){r=pt(e,r+2);continue}if(n==='"'){r=gt(e,r+1);continue}if(e.startsWith(t,r)&&!Gr(e[r-1])&&!Gr(e[r+t.length])){let s=co(e,r+t.length,"{");if(s===-1)return null;let o=uo(e,s);return o===-1?null:{closeBraceIndex:o,openBraceIndex:s}}}return null}function co(e,t,r){for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=mt(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=pt(e,n+2);continue}if(s==='"'){n=gt(e,n+1);continue}if(s===r)return n}return-1}function uo(e,t){let r=0;for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=mt(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=pt(e,n+2);continue}if(s==='"'){n=gt(e,n+1);continue}if(s==="{"){r+=1;continue}if(s==="}"&&(r-=1,r===0))return n}return-1}function mt(e,t){let r=t;for(;r<e.length&&e[r]!==`
2
- `;)r+=1;return r}function pt(e,t){let r=e.indexOf("*/",t);return r===-1?e.length:r+1}function gt(e,t){let r=t;for(;r<e.length;){if(e[r]==="\\"){r+=2;continue}if(e[r]==='"')return r;r+=1}return e.length}function Gr(e){return e!=null&&/[A-Za-z0-9_]/.test(e)}function lo(e,t,r){let n=`"${ho(t)}"`,s=mo(e);for(let[f,d]of s.entries()){let{comment:p,code:y}=Kr(d.line),E=y.match(/^(\s*)url(\s*)=(\s*).*/);if(E)return s[f]={line:`${E[1]}url${E[2]}=${E[3]}${n}${p}`,terminator:d.terminator},ut(s)}let o=fo(e),a=po(s,r),i=`${a}url = ${n}`;if(!e.includes(`
1
+ "use strict";var zn=Object.create;var ge=Object.defineProperty;var Jn=Object.getOwnPropertyDescriptor;var Yn=Object.getOwnPropertyNames;var Xn=Object.getPrototypeOf,Zn=Object.prototype.hasOwnProperty;var v=(e,t)=>()=>(e&&(t=e(e=0)),t);var V=(e,t)=>{for(var r in t)ge(e,r,{get:t[r],enumerable:!0})},Ht=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Yn(t))!Zn.call(e,s)&&s!==r&&ge(e,s,{get:()=>t[s],enumerable:!(n=Jn(t,s))||n.enumerable});return e};var D=(e,t,r)=>(r=e!=null?zn(Xn(e)):{},Ht(t||!e||!e.__esModule?ge(r,"default",{value:e,enumerable:!0}):r,e)),es=e=>Ht(ge({},"__esModule",{value:!0}),e);var ts,h,m=v(()=>{"use strict";ts=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,h=ts()});var A,fe=v(()=>{"use strict";m();A=class extends Error{constructor(r,n,s){super(n,s);this.status=r}name="HTTPError"}});function Wt(e){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([[t],[r]])=>t.localeCompare(r)))),"utf8").toString("base64url")}function ns(e){let t=Buffer.from(e,"base64url").toString("utf8"),{issues:r,output:n,success:s}=(0,P.safeParse)(rs,t,{abortEarly:!0});return s?[null,n]:[r]}function W(e,t){let r=e.headers.authorization;if(!r)throw new A(401,"Missing API Key");let[n,s="",o]=r.split(" ");if(n!=="Bearer"||o)throw new A(401,"Invalid API Key");let[a,i]=ns(s);if(a)throw new A(401,"Invalid API Key",{cause:a.join(", ")});let{databaseUrl:c,name:u,shadowDatabaseUrl:l}=i,f=t.name,d=t.port;if(!u)throw new A(401,`Wrong API Key; The Prisma Dev server running at port ${d} requires an API Key from a newer version of \`prisma dev\`. Check the "${f}" server's output for the updated \`DATABASE_URL\` value.`);if(u!==f)throw new A(401,`Wrong API Key; The Prisma Dev server running at port ${d} is named "${f}", but the API Key is for "${u}"`);let{hostname:p,port:y}=new URL(c),{port:E}=t.db,{hostname:re,port:Ce}=new URL(l),Kn=t.shadowDBPort;if(p!=="localhost"||Number(y)!==E||re!=="localhost"||Number(Ce)!==Kn)throw new A(401,"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 i}var P,Ft,rs,Ue=v(()=>{"use strict";m();P=require("valibot");fe();Ft=/^(postgres|postgresql):\/\//,rs=(0,P.pipe)((0,P.string)(),(0,P.parseJson)(),(0,P.object)({databaseUrl:(0,P.pipe)((0,P.string)(),(0,P.url)(),(0,P.regex)(Ft)),name:(0,P.optional)((0,P.pipe)((0,P.string)(),(0,P.minLength)(1))),shadowDatabaseUrl:(0,P.pipe)((0,P.string)(),(0,P.url)(),(0,P.regex)(Ft))}))});function He(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),he.default.platform==="darwin"?ss(e):he.default.platform==="win32"?os(e):as(e)}var w,Qe,he,U,qe,K,ss,os,as,Gt=v(()=>{"use strict";m();w=D(require("path"),1),Qe=D(require("os"),1),he=D(require("process"),1),U=Qe.default.homedir(),qe=Qe.default.tmpdir(),{env:K}=he.default,ss=e=>{let t=w.default.join(U,"Library");return{data:w.default.join(t,"Application Support",e),config:w.default.join(t,"Preferences",e),cache:w.default.join(t,"Caches",e),log:w.default.join(t,"Logs",e),temp:w.default.join(qe,e)}},os=e=>{let t=K.APPDATA||w.default.join(U,"AppData","Roaming"),r=K.LOCALAPPDATA||w.default.join(U,"AppData","Local");return{data:w.default.join(r,e,"Data"),config:w.default.join(t,e,"Config"),cache:w.default.join(r,e,"Cache"),log:w.default.join(r,e,"Log"),temp:w.default.join(qe,e)}},as=e=>{let t=w.default.basename(U);return{data:w.default.join(K.XDG_DATA_HOME||w.default.join(U,".local","share"),e),config:w.default.join(K.XDG_CONFIG_HOME||w.default.join(U,".config"),e),cache:w.default.join(K.XDG_CACHE_HOME||w.default.join(U,".cache"),e),log:w.default.join(K.XDG_STATE_HOME||w.default.join(U,".local","state"),e),temp:w.default.join(qe,t,e)}}});function zt(e,t){return`${Se.cache}/engine/${e}/${t}`}function ne(e){return`${Se.data}/${e}`}async function z(e){try{return await(0,R.access)(e,R.constants.F_OK),!0}catch(t){if(Fe(t))return!1;throw t}}async function Jt(e,t){let r=await is(e);await(0,R.writeFile)(t,r),await(0,R.chmod)(t,"755")}async function Yt(e,t){await e.stream().pipeTo(ye.WriteStream.toWeb((0,ye.createWriteStream)(t,{encoding:"utf8"})))}function Fe(e){return e!=null&&typeof e=="object"&&"code"in e&&e.code==="ENOENT"}async function Xt(e){try{return await(0,R.readFile)(e,{encoding:"utf-8"})}catch(t){if(Fe(t))return null;throw t}}async function Zt(e){await(0,R.mkdir)(e,{recursive:!0})}async function er(e,t){try{return(await(0,R.readdir)(e,{withFileTypes:!0})).reduce((n,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!t||(0,Kt.default)(t,s.name))&&n.push(s.name),n),[])}catch(r){if(Fe(r))return[];throw r}}async function J(e){await(0,R.rm)(e,{force:!0,recursive:!0})}var ye,R,jt,Vt,Kt,Se,is,Y=v(()=>{"use strict";m();ye=require("fs"),R=require("fs/promises"),jt=require("util"),Vt=require("zlib");Gt();Kt=D(require("zeptomatch"),1),Se=He("prisma-dev"),is=(0,jt.promisify)(Vt.unzip)});async function Ve(e){let{debug:t,name:r,requestedPorts:n,servers:s}=e,{portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a}=ls(r,s);t&&(console.debug(`ports used by other servers: ${Object.keys(o).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(a)}`));let i={databasePort:_,port:_,shadowDatabasePort:_,streamsPort:_},c=["port","databasePort","shadowDatabasePort","streamsPort"];for(let u of c){let l=await cs({debug:t,portKey:u,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a,requestedPorts:n})??await us({debug:t,pickedPorts:i,portKey:u,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a});t&&console.debug(`Got port for "${u}": ${l}`),i[u]=l}return t&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function cs(e){let{debug:t,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s,requestedPorts:o}=e,{[r]:a,...i}=o;if(We(a))return await ps({debug:t,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:n,requestedPort:a}),a;let c=s?.[r]??_;if(!We(c))return t&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let u=c in n;return u||Object.values(i).includes(c)?(t&&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,Q.checkPort)(c)===!1?(t&&console.debug(`Port ${c}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(t&&console.debug(`Using port ${c} for "${r}" as it was used last time and is available.`),c)}async function us(e){let{debug:t,pickedPorts:r,portKey:n,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:o}=e,a=Math.max(Pe,we,Ee,ve)+1,i=Object.values(r).filter(p=>p!==void 0),c=o?ms(o):[],u=[...i,...Object.keys(s).map(Number),...c],l=Math.min(Math.max(a,...u)+100,be),f=(0,Re.difference)((0,Re.range)(a,l),u),d={port:we,databasePort:Pe,shadowDatabasePort:Ee,streamsPort:ve}[n];try{return await(0,Q.getPort)({port:d in s||i.includes(d)||c.includes(d)?void 0:d,ports:f})}catch(p){if(p instanceof Error&&p.name==="GetPortError"&&l+1<=be)return t&&console.debug(`Expanding port lookup to range [${l+1}, ${be}].`),await(0,Q.getPort)({portRange:[l+1,be]});throw p}}function We(e){return Number.isFinite(e)&&e>=0}function ls(e,t){let r={},n;for(let s of t){let{databasePort:o,port:a,shadowDatabasePort:i}=s,c=ds(s);if(s.name===e){n={databasePort:o,port:a,shadowDatabasePort:i,streamsPort:c};continue}r[o]=!0,r[a]=!0,r[i]=!0,We(c)&&(r[c]=!0)}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}function ds(e){let t=e.experimental?.streams?.serverUrl;if(!t)return _;try{let r=Number(new URL(t).port);return Number.isInteger(r)&&r>0?r:_}catch{return _}}function ms(e){return[e.port,e.databasePort,e.shadowDatabasePort,e.streamsPort]}async function ps(e){let{debug:t,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:s,requestedPort:o}=e;if(o!==G){if(o in s)throw t&&console.error(`Port ${o} was requested for "${n}", but is already used by another server.`),new je(o);if(Object.values(r).includes(o))throw t&&console.error(`Port ${o} was requested for "${n}", but also for another key.`),new Ge(o);if((0,Q.isUnsafePort)(o))throw t&&console.error(`Port ${o} was requested for "${n}", but is unsafe.`),new N(o);if(await(0,Q.checkPort)(o)===!1)throw t&&console.error(`Port ${o} was requested for "${n}", but is not available.`),new N(o)}}var Q,Re,Pe,we,Ee,ve,be,G,_,N,Ge,je,se=v(()=>{"use strict";m();Q=require("get-port-please"),Re=require("remeda"),Pe=51214,we=51213,Ee=51215,ve=51216,be=65535,G=0,_=-1/0;N=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},Ge=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"},je=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"}});function T(e,t,r=200){let n=ct.Buffer.from(JSON.stringify(t),"utf8");e.headersSent||(e.setHeader("Content-Type","application/json; charset=utf-8"),e.setHeader("Content-Length",n.byteLength),e.statusCode=r),e.end(n)}function x(e,t,r=200){let n=ct.Buffer.from(t,"utf8");e.headersSent||(e.setHeader("Content-Type","text/plain; charset=utf-8"),e.setHeader("Content-Length",n.byteLength),e.statusCode=r),e.end(n)}function Z(e,t=204){e.headersSent||(e.statusCode=t,e.setHeader("Content-Length",0)),e.end()}function Hr(e,t){x(e,t.message,t.status)}var ct,C=v(()=>{"use strict";m();ct=require("buffer")});async function Wr(e,t){let r;try{r=await(0,Fr.json)(e)}catch{return x(t,"Invalid input",400),null}let{output:n,success:s}=(0,I.safeParse)(io,r,{abortEarly:!0});return s?n:(x(t,"Invalid input",400),null)}var Fr,I,io,Gr=v(()=>{"use strict";m();Fr=require("stream/consumers"),I=require("valibot");C();io=(0,I.object)({tags:(0,I.union)([(0,I.pipe)((0,I.array)((0,I.string)()),(0,I.minLength)(1)),(0,I.literal)("all")])})});async function dt(e){let r=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(a=>a.toString(16).padStart(2,"0")).join("")}function Vr(e,t){let r=e.schemaHash;if(r==null)return T(t,{EngineNotStarted:{reason:"SchemaMissing"}},404),null;let n=_e.get(r);return n==null?(T(t,{EngineNotStarted:{reason:"SchemaMissing"}},404),null):{schemaHash:r,schemas:n}}async function Kr(e,t,r){let n=lt.Buffer.from(e,"base64").toString("utf8"),s=uo(n,t.toString());r&&console.log("[Accelerate] schema with override:",s);let o=await dt(s);return{base64Override:lt.Buffer.from(s,"utf8").toString("base64"),overrideHash:o}}function uo(e,t){let r=lo(e);if(!r)throw new Error("No datasource block found in schema.");let n=e.slice(r.openBraceIndex+1,r.closeBraceIndex),s=go(n,t,yo(e,r.openBraceIndex));return`${e.slice(0,r.openBraceIndex+1)}${s}${e.slice(r.closeBraceIndex)}`}function lo(e){let t="datasource";for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="/"&&e[r+1]==="/"){r=mt(e,r+2);continue}if(n==="/"&&e[r+1]==="*"){r=pt(e,r+2);continue}if(n==='"'){r=gt(e,r+1);continue}if(e.startsWith(t,r)&&!jr(e[r-1])&&!jr(e[r+t.length])){let s=mo(e,r+t.length,"{");if(s===-1)return null;let o=po(e,s);return o===-1?null:{closeBraceIndex:o,openBraceIndex:s}}}return null}function mo(e,t,r){for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=mt(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=pt(e,n+2);continue}if(s==='"'){n=gt(e,n+1);continue}if(s===r)return n}return-1}function po(e,t){let r=0;for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=mt(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=pt(e,n+2);continue}if(s==='"'){n=gt(e,n+1);continue}if(s==="{"){r+=1;continue}if(s==="}"&&(r-=1,r===0))return n}return-1}function mt(e,t){let r=t;for(;r<e.length&&e[r]!==`
2
+ `;)r+=1;return r}function pt(e,t){let r=e.indexOf("*/",t);return r===-1?e.length:r+1}function gt(e,t){let r=t;for(;r<e.length;){if(e[r]==="\\"){r+=2;continue}if(e[r]==='"')return r;r+=1}return e.length}function jr(e){return e!=null&&/[A-Za-z0-9_]/.test(e)}function go(e,t,r){let n=`"${bo(t)}"`,s=fo(e);for(let[f,d]of s.entries()){let{comment:p,code:y}=zr(d.line),E=y.match(/^(\s*)url(\s*)=(\s*).*/);if(E)return s[f]={line:`${E[1]}url${E[2]}=${E[3]}${n}${p}`,terminator:d.terminator},ut(s)}let o=So(e),a=ho(s,r),i=`${a}url = ${n}`;if(!e.includes(`
3
3
  `)&&!e.includes("\r")){let f=e.trim();return f.length===0?`${o}${i}${o}${r}`:`${o}${a}${f}${o}${i}${o}${r}`}let c=s.at(-1);if(c&&c.terminator===""&&/^\s*$/.test(c.line))return`${ut(s.slice(0,-1))}${i}${o}${r}`;let u=ut(s),l=u.endsWith(`
4
- `)||u.endsWith("\r")?"":o;return`${u}${l}${i}${o}${r}`}function mo(e){let t=[],r=0;for(let n=0;n<e.length;n+=1){if(e[n]==="\r"&&e[n+1]===`
4
+ `)||u.endsWith("\r")?"":o;return`${u}${l}${i}${o}${r}`}function fo(e){let t=[],r=0;for(let n=0;n<e.length;n+=1){if(e[n]==="\r"&&e[n+1]===`
5
5
  `){t.push({line:e.slice(r,n),terminator:`\r
6
6
  `}),n+=1,r=n+1;continue}(e[n]===`
7
- `||e[n]==="\r")&&(t.push({line:e.slice(r,n),terminator:e[n]}),r=n+1)}return(r<e.length||e.length===0)&&t.push({line:e.slice(r),terminator:""}),t}function ut(e){return e.map(t=>`${t.line}${t.terminator}`).join("")}function Kr(e){let t=!1,r=!1;for(let n=0;n<e.length;n+=1){let s=e[n];if(r){if(t){t=!1;continue}if(s==="\\"){t=!0;continue}s==='"'&&(r=!1);continue}if(s==='"'){r=!0;continue}if(s==="/"&&e[n+1]==="/")return{code:e.slice(0,n),comment:e.slice(n)}}return{code:e,comment:""}}function po(e,t){for(let r of e){let{code:n}=Kr(r.line),s=n.match(/^([ \t]+)[A-Za-z_][A-Za-z0-9_]*\s*=/);if(s?.[1])return s[1]}return`${t}${oo}`}function go(e,t){let r=e.lastIndexOf(`
8
- `,t)+1,n=r;for(;e[n]===" "||e[n]===" ";)n+=1;return e.slice(r,n)}function fo(e){return e.includes(`\r
7
+ `||e[n]==="\r")&&(t.push({line:e.slice(r,n),terminator:e[n]}),r=n+1)}return(r<e.length||e.length===0)&&t.push({line:e.slice(r),terminator:""}),t}function ut(e){return e.map(t=>`${t.line}${t.terminator}`).join("")}function zr(e){let t=!1,r=!1;for(let n=0;n<e.length;n+=1){let s=e[n];if(r){if(t){t=!1;continue}if(s==="\\"){t=!0;continue}s==='"'&&(r=!1);continue}if(s==='"'){r=!0;continue}if(s==="/"&&e[n+1]==="/")return{code:e.slice(0,n),comment:e.slice(n)}}return{code:e,comment:""}}function ho(e,t){for(let r of e){let{code:n}=zr(r.line),s=n.match(/^([ \t]+)[A-Za-z_][A-Za-z0-9_]*\s*=/);if(s?.[1])return s[1]}return`${t}${co}`}function yo(e,t){let r=e.lastIndexOf(`
8
+ `,t)+1,n=r;for(;e[n]===" "||e[n]===" ";)n+=1;return e.slice(r,n)}function So(e){return e.includes(`\r
9
9
  `)?`\r
10
10
  `:`
11
- `}function ho(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}var lt,_e,oo,zr=v(()=>{"use strict";m();lt=require("buffer");C();_e=new Map;oo=" "});function ie(e,t){let r=e[t];return Array.isArray(r)?r.at(-1):r}var ft=v(()=>{"use strict";m()});function Yr(e,t){let r=(e.method??"GET").toUpperCase(),n=`${t.origin}${e.url??"/"}`,s={headers:So(e.headers),method:r};return yo.has(r)||(s.body=ht.Readable.toWeb(e),s.duplex="half"),new Request(n,s)}async function Xr(e,t){t.statusCode=e.status;for(let[r,n]of e.headers)t.setHeader(r,n);if(e.body===null){t.end();return}await(0,Jr.pipeline)(ht.Readable.fromWeb(e.body),t)}function So(e){let t=new Headers;for(let[r,n]of Object.entries(e))if(typeof n=="string")t.append(r,n);else if(Array.isArray(n))for(let s of n)t.append(r,s);return t}var ht,Jr,yo,Zr=v(()=>{"use strict";m();ht=require("stream"),Jr=require("stream/promises"),yo=new Set(["GET","HEAD"])});var rn={};V(rn,{createHTTPServer:()=>Po,wrap:()=>M});function M(e,t){return async function(n,s,o){let a=t?Date.now():0;t&&s.once("finish",()=>{let i=Date.now()-a;console.log("[Accelerate]",`<-- ${n.method??"?"} ${n.url??""} ${s.statusCode} ${i}ms`)});try{await e(n,s,o)}catch(i){try{bo(i,s,n,t)}catch(c){t&&console.error("[Accelerate]","error while handling handler error",c),s.destroyed||s.destroy()}}}}function bo(e,t,r,n){if(t.destroyed||t.headersSent||t.writableEnded){n&&console.error("[Accelerate]",`error after response was no longer writable for ${r.method??"?"} ${r.url??""}`,e),t.destroy();return}if(e instanceof A){qr(t,e);return}console.error("[Accelerate]",e);try{Z(t,500)}catch(s){n&&console.error("[Accelerate]","failed to write 500 response (client likely disconnected)",s),t.destroy()}}function Po(e){let{router:t}=e;return{async listen(r){let n=(0,en.createServer)((a,i)=>{t.lookup(a,i)}),o=(await wo(n,r)).port;return n.on("error",a=>{console.error("[Accelerate]",a)}),{async close(){await(0,tn.promisify)(n.close.bind(n))()},port:o,url:`http://localhost:${o}`}}}}function wo(e,t){return new Promise((r,n)=>{let s=a=>{if(e.off("listening",o),typeof a=="object"&&a!==null&&"code"in a&&a.code==="EADDRINUSE"){n(new N(t));return}n(a)},o=()=>{e.off("error",s),r(e.address())};e.once("error",s),e.once("listening",o),e.listen(t)})}var en,tn,Oe=v(()=>{"use strict";m();en=require("http"),tn=require("util");se();fe();C()});function Ne(e){return{traceparent:ie(e.headers,"traceparent"),"X-capture-telemetry":ie(e.headers,"x-capture-telemetry")}}var nn=v(()=>{"use strict";m();ft()});async function on(e,t){let r;try{r=await(0,sn.json)(e)}catch{return T(t,{EngineNotStarted:{reason:"InvalidRequest",issues:[]}},400),null}let{issues:n,output:s,success:o}=(0,b.safeParse)(Eo,r,{abortEarly:!0});return o?s:(T(t,{EngineNotStarted:{reason:"InvalidRequest",issues:n}},400),null)}function an(e,t){let{output:r,success:n}=(0,b.safeParse)(vo,e);return n?r:(T(t,{EngineMalfunction:{}},500),null)}var sn,b,Eo,vo,cn=v(()=>{"use strict";m();sn=require("stream/consumers"),b=require("valibot");C();Eo=(0,b.object)({isolation_level:(0,b.optional)((0,b.string)()),max_wait:(0,b.pipe)((0,b.number)(),(0,b.integer)(),(0,b.minValue)(0)),timeout:(0,b.pipe)((0,b.number)(),(0,b.integer)(),(0,b.minValue)(0))});vo=(0,b.looseObject)({id:(0,b.union)([(0,b.string)(),(0,b.number)()])})});function un(e){let t,r,n=new Promise((a,i)=>{t=a,r=i}),s=a=>{s=o=null,r(a),e?.onRejected?.(a),e?.onFulfilled?.()},o=a=>{o=s=null,t(a),e?.onResolved?.(a),e?.onFulfilled?.()};return{isFulfilled:()=>o===s,promise:n,reject:a=>s?.(a),resolve:a=>o?.(a)}}var ln=v(()=>{"use strict";m()});var St={};V(St,{Engine:()=>yt,handleEngineError:()=>xo});function xo(e,t){if(console.error(e),e instanceof ce){T(t,{EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:e.message}}}},500);return}if(e instanceof ee){x(t,e.responseBody,e.statusCode);return}Z(t,500)}var mn,pn,gn,fn,hn,yn,Ro,To,dn,yt,ce,ee,bt=v(()=>{"use strict";m();mn=require("child_process"),pn=require("events"),gn=require("fs/promises"),fn=require("path"),hn=require("timers/promises");ln();yn=require("std-env");Y();C();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Ro,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:To,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:dn}=yn.process.env),yt=class e{static#r=new Map;#e;#t;constructor(t){this.#e=t,this.#t=null}static async get(t){let{debug:r}=t,n=`${t.schemaHash}:${t.clientVersion}`;try{let s=e.#r.get(n);if(s)return s;let o=new e(t);return e.#r.set(n,o),r&&console.debug("[Query Engine] starting...",t),await o.start(),r&&console.debug("[Query Engine] started!"),o}finally{e.stopAll(n)}}static async stopAll(t){let n=(await Promise.allSettled(Array.from(e.#r.entries()).filter(([s])=>s!==t).map(async([s,o])=>{try{await o.stop()}finally{e.#r.delete(s)}}))).filter(s=>s.status==="rejected").map(s=>s.reason);if(n.length>0)throw new AggregateError(n,"Failed to stop engines")}async commitTransaction(t,r){return await this.#i(t,r,"commit")}async request(t,r){let{url:n}=await this.start(),s=this.#n(r),o=await fetch(n,{body:typeof t=="string"?t:JSON.stringify(t),headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await ee.fromResponse(o);return await o.text()}async rollbackTransaction(t,r){return await this.#i(t,r,"rollback")}async startTransaction(t,r){let{url:n}=await this.start(),s=this.#n(r),o=await fetch(`${n}/transaction/start`,{body:JSON.stringify(t),headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await ee.fromResponse(o);return await o.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:t,reject:r,resolve:n}=un();this.#t=t;let s=To||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",s);let{proxySignals:o}=await import("foreground-child/proxy-signals"),a=(0,mn.spawn)(s,["--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});o(a),a.stderr.setEncoding("utf8"),a.stdout.setEncoding("utf8");let i=l=>{let f=l.split(`
11
+ `}function bo(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}var lt,_e,co,Jr=v(()=>{"use strict";m();lt=require("buffer");C();_e=new Map;co=" "});function ie(e,t){let r=e[t];return Array.isArray(r)?r.at(-1):r}var ft=v(()=>{"use strict";m()});function Xr(e,t){let r=(e.method??"GET").toUpperCase(),n=`${t.origin}${e.url??"/"}`,s={headers:wo(e.headers),method:r};return Po.has(r)||(s.body=ht.Readable.toWeb(e),s.duplex="half"),new Request(n,s)}async function Zr(e,t){t.statusCode=e.status;for(let[r,n]of e.headers)t.setHeader(r,n);if(e.body===null){t.end();return}await(0,Yr.pipeline)(ht.Readable.fromWeb(e.body),t)}function wo(e){let t=new Headers;for(let[r,n]of Object.entries(e))if(typeof n=="string")t.append(r,n);else if(Array.isArray(n))for(let s of n)t.append(r,s);return t}var ht,Yr,Po,en=v(()=>{"use strict";m();ht=require("stream"),Yr=require("stream/promises"),Po=new Set(["GET","HEAD"])});var nn={};V(nn,{createHTTPServer:()=>vo,wrap:()=>M});function M(e,t){return async function(n,s,o){let a=t?Date.now():0;t&&s.once("finish",()=>{let i=Date.now()-a;console.log("[Accelerate]",`<-- ${n.method??"?"} ${n.url??""} ${s.statusCode} ${i}ms`)});try{await e(n,s,o)}catch(i){try{Eo(i,s,n,t)}catch(c){t&&console.error("[Accelerate]","error while handling handler error",c),s.destroyed||s.destroy()}}}}function Eo(e,t,r,n){if(t.destroyed||t.headersSent||t.writableEnded){n&&console.error("[Accelerate]",`error after response was no longer writable for ${r.method??"?"} ${r.url??""}`,e),t.destroy();return}if(e instanceof A){Hr(t,e);return}console.error("[Accelerate]",e);try{Z(t,500)}catch(s){n&&console.error("[Accelerate]","failed to write 500 response (client likely disconnected)",s),t.destroy()}}function vo(e){let{router:t}=e;return{async listen(r){let n=(0,tn.createServer)((a,i)=>{t.lookup(a,i)}),o=(await Ro(n,r)).port;return n.on("error",a=>{console.error("[Accelerate]",a)}),{async close(){await(0,rn.promisify)(n.close.bind(n))()},port:o,url:`http://localhost:${o}`}}}}function Ro(e,t){return new Promise((r,n)=>{let s=a=>{if(e.off("listening",o),typeof a=="object"&&a!==null&&"code"in a&&a.code==="EADDRINUSE"){n(new N(t));return}n(a)},o=()=>{e.off("error",s),r(e.address())};e.once("error",s),e.once("listening",o),e.listen(t)})}var tn,rn,Oe=v(()=>{"use strict";m();tn=require("http"),rn=require("util");se();fe();C()});function Ne(e){return{traceparent:ie(e.headers,"traceparent"),"X-capture-telemetry":ie(e.headers,"x-capture-telemetry")}}var sn=v(()=>{"use strict";m();ft()});async function an(e,t){let r;try{r=await(0,on.json)(e)}catch{return T(t,{EngineNotStarted:{reason:"InvalidRequest",issues:[]}},400),null}let{issues:n,output:s,success:o}=(0,b.safeParse)(To,r,{abortEarly:!0});return o?s:(T(t,{EngineNotStarted:{reason:"InvalidRequest",issues:n}},400),null)}function cn(e,t){let{output:r,success:n}=(0,b.safeParse)(xo,e);return n?r:(T(t,{EngineMalfunction:{}},500),null)}var on,b,To,xo,un=v(()=>{"use strict";m();on=require("stream/consumers"),b=require("valibot");C();To=(0,b.object)({isolation_level:(0,b.optional)((0,b.string)()),max_wait:(0,b.pipe)((0,b.number)(),(0,b.integer)(),(0,b.minValue)(0)),timeout:(0,b.pipe)((0,b.number)(),(0,b.integer)(),(0,b.minValue)(0))});xo=(0,b.looseObject)({id:(0,b.union)([(0,b.string)(),(0,b.number)()])})});function ln(e){let t,r,n=new Promise((a,i)=>{t=a,r=i}),s=a=>{s=o=null,r(a),e?.onRejected?.(a),e?.onFulfilled?.()},o=a=>{o=s=null,t(a),e?.onResolved?.(a),e?.onFulfilled?.()};return{isFulfilled:()=>o===s,promise:n,reject:a=>s?.(a),resolve:a=>o?.(a)}}var dn=v(()=>{"use strict";m()});var St={};V(St,{Engine:()=>yt,handleEngineError:()=>Ao});function Ao(e,t){if(console.error(e),e instanceof ce){T(t,{EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:e.message}}}},500);return}if(e instanceof ee){x(t,e.responseBody,e.statusCode);return}Z(t,500)}var pn,gn,fn,hn,yn,Sn,Io,Do,mn,yt,ce,ee,bt=v(()=>{"use strict";m();pn=require("child_process"),gn=require("events"),fn=require("fs/promises"),hn=require("path"),yn=require("timers/promises");dn();Sn=require("std-env");Y();C();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Io,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:Do,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:mn}=Sn.process.env),yt=class e{static#r=new Map;#e;#t;constructor(t){this.#e=t,this.#t=null}static async get(t){let{debug:r}=t,n=`${t.schemaHash}:${t.clientVersion}`;try{let s=e.#r.get(n);if(s)return s;let o=new e(t);return e.#r.set(n,o),r&&console.debug("[Query Engine] starting...",t),await o.start(),r&&console.debug("[Query Engine] started!"),o}finally{e.stopAll(n)}}static async stopAll(t){let n=(await Promise.allSettled(Array.from(e.#r.entries()).filter(([s])=>s!==t).map(async([s,o])=>{try{await o.stop()}finally{e.#r.delete(s)}}))).filter(s=>s.status==="rejected").map(s=>s.reason);if(n.length>0)throw new AggregateError(n,"Failed to stop engines")}async commitTransaction(t,r){return await this.#i(t,r,"commit")}async request(t,r){let{url:n}=await this.start(),s=this.#n(r),o=await fetch(n,{body:typeof t=="string"?t:JSON.stringify(t),headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await ee.fromResponse(o);return await o.text()}async rollbackTransaction(t,r){return await this.#i(t,r,"rollback")}async startTransaction(t,r){let{url:n}=await this.start(),s=this.#n(r),o=await fetch(`${n}/transaction/start`,{body:JSON.stringify(t),headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await ee.fromResponse(o);return await o.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:t,reject:r,resolve:n}=ln();this.#t=t;let s=Do||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",s);let{proxySignals:o}=await import("foreground-child/proxy-signals"),a=(0,pn.spawn)(s,["--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});o(a),a.stderr.setEncoding("utf8"),a.stdout.setEncoding("utf8");let i=l=>{let f=l.split(`
12
12
  `).find(E=>E.includes("Started query engine http server"));if(!f)return;a.stdout.removeListener("data",i);let{fields:d}=JSON.parse(f);if(d==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${l}`));let{ip:p,port:y}=d;if(p==null||y==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.
13
- Received data: ${l}`));n({childProcess:a,url:`http://${p}:${y}`})},c=l=>{this.#t=null,r(new ce(String(l))),a.removeListener("exit",u),a.kill()};a.once("error",c);let u=(l,f)=>{this.#t=null,r(new ce(`Query Engine exited with code ${l} and signal ${f}`))};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:t}=await this.#t;t.exitCode==null&&t.signalCode==null&&(this.#t=null,t.kill(),await(0,pn.once)(t,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let t=await this.#o();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",t);let r=Kt(this.#e.clientVersion,t);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,gn.mkdir)(r,{recursive:!0});let{binaryTarget:n}=this.#e.platform,s=n==="windows"?".exe":"",o=(0,fn.join)(r,`query-engine-${n}${s}`);return this.#e.debug&&console.debug("[Query Engine] binary path",o),(Ro==="1"||await z(o)===!1)&&await this.#a({commitHash:t,extension:s,engineBinaryPath:o}),o}async#o(){let t=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!t.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${t.status}`);let n=(await t.json()).devDependencies?.["@prisma/engines-version"];if(!n)throw new Error("Couldn't find engines version in package.json");let s=n.split(".").at(-1);if(!s)throw new Error("Couldn't find commit hash in engines version");return s}async#a(t){let{commitHash:r,extension:n,engineBinaryPath:s}=t,{binaryTarget:o}=this.#e.platform,a=`https://binaries.prisma.sh/all_commits/${r}/${o}/query-engine${n}.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}`);dn&&await(0,hn.setTimeout)(Number(dn)),await zt(await i.arrayBuffer(),s),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",s)}#n(t){let r={};for(let[n,s]of Object.entries(t))s!=null&&(r[n]=s);return r}async#i(t,r,n){let{url:s}=await this.#t,o=this.#n(r),a=await fetch(`${s}/transaction/${t}/${n}`,{headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!a.ok)throw await ee.fromResponse(a);try{return await a.json()}catch{return{}}}};ce=class extends Error{name="EngineStartError"},ee=class e extends Error{constructor(r,n,s){super(`${r}: Query Engine response status ${n}, body: ${s}`);this.action=r;this.statusCode=n;this.responseBody=s}name="EngineHttpError";static async fromResponse(r){let n=new URL(r.url),s=await r.text();return new e(n.pathname,r.status,s)}}});var Sn={};V(Sn,{getQueryPlanExecutorServer:()=>Io,queryPlanExecutorVersion:()=>bn.version});async function Io(e){return Pt===void 0&&(Pt=await F.Server.create({databaseUrl:e.db.connectionString,maxResponseSize:(0,F.parseSize)("128 MiB"),queryTimeout:(0,F.parseDuration)("PT5M"),maxTransactionTimeout:(0,F.parseDuration)("PT5M"),maxTransactionWaitTime:(0,F.parseDuration)("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:e.debug?"debug":"off"}})),Pt}var F,bn,Pt,Pn=v(()=>{"use strict";m();F=require("@prisma/query-plan-executor"),bn=require("@prisma/query-plan-executor")});var Rn={};V(Rn,{registerAccelerateRoutes:()=>_o});function Me(){return wn??=Promise.resolve().then(()=>(bt(),St)),wn}function Do(){return vn??=Promise.resolve().then(()=>(Pn(),Sn)),vn}async function Ao(){return En??=import("@prisma/get-platform").then(async({default:e})=>await e.getPlatformInfo()),await En}function _o(e,t,r){e.on("POST","/invalidate",M(async(s,o)=>{W(s,t),await Fr(s,o)!==null&&Z(o,200)},r));for(let s of["/:clientVersion/:schemaHash/graphql","/:clientVersion/:schemaHash/itx/:transactionId/graphql"])e.on("POST",s,M(async(o,a,i)=>{W(o,t);try{let c=await wt(a,t,i);if(c===null)return;let u=await(0,Et.text)(o),l=i.transactionId,f=await c.request(u,{...Ne(o),"X-transaction-id":l});x(a,f)}catch(c){let{handleEngineError:u}=await Me();u(c,a)}},r));for(let s of["commit","rollback"])e.on("POST",`/:clientVersion/:schemaHash/itx/:transactionId/${s}`,M(async(o,a,i)=>{W(o,t);try{let c=await wt(a,t,i);if(c===null)return;let u=i.transactionId;if(u==null){T(a,{EngineMalfunction:{}},500);return}let l=`${s}Transaction`,f=await c[l](u,Ne(o));T(a,f)}catch(c){let{handleEngineError:u}=await Me();u(c,a)}},r));e.on("PUT","/:clientVersion/:schemaHash/schema",M(async(s,o,a)=>{W(s,t);let i=await(0,Et.text)(s);if(!i){x(o,"Missing schema",400);return}let c=a.schemaHash;if(c==null){x(o,"Missing schema hash",400);return}let u=_e.get(c);if(u==null){if(c!==await dt(i)){x(o,"Schema hash mismatch",400);return}let l=await Vr(i,t.db.prismaORMConnectionString,t.debug);_e.set(c,{base64Original:i,...l}),x(o,c);return}if(i!==u.base64Original){x(o,"Schema mismatch",400);return}x(o,c)},r)),e.on("POST","/:clientVersion/:schemaHash/transaction/start",M(async(s,o,a)=>{W(s,t);let i=await on(s,o);if(i!==null)try{let c=await wt(o,t,a);if(c===null)return;let u=await c.startTransaction(i,Ne(s)),l=an(u,o);if(l===null)return;let{id:f}=l,d=a.clientVersion,p=a.schemaHash;T(o,{...u,"data-proxy":{endpoint:`http://localhost:${t.port}/${d}/${p}/itx/${f}`}})}catch(c){let{handleEngineError:u}=await Me();u(c,o)}},r));let n=[["GET","/connection-info"],["POST","/query"],["POST","/transaction/start"],["POST","/transaction/:transactionId/commit"],["POST","/transaction/:transactionId/query"],["POST","/transaction/:transactionId/rollback"]];for(let[s,o]of n)e.on(s,o,M(async(a,i)=>{W(a,t);let{getQueryPlanExecutorServer:c,queryPlanExecutorVersion:u}=await Do(),l=ie(a.headers,"prisma-engine-hash");if(l!=="0.0.0"&&l!==u)throw new A(400,`Using an HTTP connection string is not supported with Prisma Client version ${l??"<missing>"} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${u}.`);let f=await c(t),d=Yr(a,{origin:`http://localhost:${t.port}`}),p=await f.fetch(d);await Xr(p,i)},r))}async function wt(e,t,r){let{Engine:n}=await Me(),s=jr(r,e);if(s===null)return null;let{base64Override:o,overrideHash:a}=s.schemas;return await n.get({base64Schema:o,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||r.clientVersion||"",debug:t.debug,platform:await Ao(),schemaHash:a})}var Et,wn,En,vn,Tn=v(()=>{"use strict";m();Et=require("stream/consumers");Ue();Wr();zr();ft();fe();Zr();C();Oe();nn();cn()});var xn={};V(xn,{registerUtilityRoutes:()=>Oo});function Oo(e,t,r){e.on("POST","/database/dump",M(async(n,s)=>{await t.db.dump(t.databaseDumpPath),T(s,{dumpPath:t.databaseDumpPath},201)},r)),e.on("GET","/health",M((n,s)=>{T(s,{name:t.name})},r))}var In=v(()=>{"use strict";m();C();Oe()});var pa={};V(pa,{DEFAULT_DATABASE_PORT:()=>Pe,DEFAULT_SERVER_PORT:()=>we,DEFAULT_SHADOW_DATABASE_PORT:()=>Ee,DEFAULT_STREAMS_PORT:()=>ve,PortNotAvailableError:()=>N,ServerAlreadyRunningError:()=>de,copyPrismaDevRuntimeAssets:()=>br,getPrismaDevRuntimeAssetManifest:()=>Xe,startPrismaDevServer:()=>Wn,unstable_startServer:()=>ma});module.exports=Yn(pa);m();m();Ue();m();var Ae=require("net"),Or=require("path"),Nr=require("pathe/utils");Y();se();m();var ze=require("perf_hooks"),dr=require("@electric-sql/pglite");m();var nr=require("buffer"),er=500,tr=/(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+)/,ds=new RegExp(`(?:${tr.source}\\.)*${tr.source}`),ms=new RegExp(`(?:FROM|JOIN|UPDATE|INTO|TABLE)\\s+(${ds.source})`,"gi"),ps=/"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|(\w+)/g,rr=/prismaQuery='([^']+)'/,gs=new Set([q(`
13
+ Received data: ${l}`));n({childProcess:a,url:`http://${p}:${y}`})},c=l=>{this.#t=null,r(new ce(String(l))),a.removeListener("exit",u),a.kill()};a.once("error",c);let u=(l,f)=>{this.#t=null,r(new ce(`Query Engine exited with code ${l} and signal ${f}`))};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:t}=await this.#t;t.exitCode==null&&t.signalCode==null&&(this.#t=null,t.kill(),await(0,gn.once)(t,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let t=await this.#o();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",t);let r=zt(this.#e.clientVersion,t);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,fn.mkdir)(r,{recursive:!0});let{binaryTarget:n}=this.#e.platform,s=n==="windows"?".exe":"",o=(0,hn.join)(r,`query-engine-${n}${s}`);return this.#e.debug&&console.debug("[Query Engine] binary path",o),(Io==="1"||await z(o)===!1)&&await this.#a({commitHash:t,extension:s,engineBinaryPath:o}),o}async#o(){let t=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!t.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${t.status}`);let n=(await t.json()).devDependencies?.["@prisma/engines-version"];if(!n)throw new Error("Couldn't find engines version in package.json");let s=n.split(".").at(-1);if(!s)throw new Error("Couldn't find commit hash in engines version");return s}async#a(t){let{commitHash:r,extension:n,engineBinaryPath:s}=t,{binaryTarget:o}=this.#e.platform,a=`https://binaries.prisma.sh/all_commits/${r}/${o}/query-engine${n}.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}`);mn&&await(0,yn.setTimeout)(Number(mn)),await Jt(await i.arrayBuffer(),s),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",s)}#n(t){let r={};for(let[n,s]of Object.entries(t))s!=null&&(r[n]=s);return r}async#i(t,r,n){let{url:s}=await this.#t,o=this.#n(r),a=await fetch(`${s}/transaction/${t}/${n}`,{headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!a.ok)throw await ee.fromResponse(a);try{return await a.json()}catch{return{}}}};ce=class extends Error{name="EngineStartError"},ee=class e extends Error{constructor(r,n,s){super(`${r}: Query Engine response status ${n}, body: ${s}`);this.action=r;this.statusCode=n;this.responseBody=s}name="EngineHttpError";static async fromResponse(r){let n=new URL(r.url),s=await r.text();return new e(n.pathname,r.status,s)}}});var bn={};V(bn,{getQueryPlanExecutorServer:()=>_o,queryPlanExecutorVersion:()=>Pn.version});async function _o(e){return Pt===void 0&&(Pt=await F.Server.create({databaseUrl:e.db.connectionString,maxResponseSize:(0,F.parseSize)("128 MiB"),queryTimeout:(0,F.parseDuration)("PT5M"),maxTransactionTimeout:(0,F.parseDuration)("PT5M"),maxTransactionWaitTime:(0,F.parseDuration)("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:e.debug?"debug":"off"}})),Pt}var F,Pn,Pt,wn=v(()=>{"use strict";m();F=require("@prisma/query-plan-executor"),Pn=require("@prisma/query-plan-executor")});var Tn={};V(Tn,{registerAccelerateRoutes:()=>Mo});function Me(){return En??=Promise.resolve().then(()=>(bt(),St)),En}function Oo(){return Rn??=Promise.resolve().then(()=>(wn(),bn)),Rn}async function No(){return vn??=import("@prisma/get-platform").then(async({default:e})=>await e.getPlatformInfo()),await vn}function Mo(e,t,r){e.on("POST","/invalidate",M(async(s,o)=>{W(s,t),await Wr(s,o)!==null&&Z(o,200)},r));for(let s of["/:clientVersion/:schemaHash/graphql","/:clientVersion/:schemaHash/itx/:transactionId/graphql"])e.on("POST",s,M(async(o,a,i)=>{W(o,t);try{let c=await wt(a,t,i);if(c===null)return;let u=await(0,Et.text)(o),l=i.transactionId,f=await c.request(u,{...Ne(o),"X-transaction-id":l});x(a,f)}catch(c){let{handleEngineError:u}=await Me();u(c,a)}},r));for(let s of["commit","rollback"])e.on("POST",`/:clientVersion/:schemaHash/itx/:transactionId/${s}`,M(async(o,a,i)=>{W(o,t);try{let c=await wt(a,t,i);if(c===null)return;let u=i.transactionId;if(u==null){T(a,{EngineMalfunction:{}},500);return}let l=`${s}Transaction`,f=await c[l](u,Ne(o));T(a,f)}catch(c){let{handleEngineError:u}=await Me();u(c,a)}},r));e.on("PUT","/:clientVersion/:schemaHash/schema",M(async(s,o,a)=>{W(s,t);let i=await(0,Et.text)(s);if(!i){x(o,"Missing schema",400);return}let c=a.schemaHash;if(c==null){x(o,"Missing schema hash",400);return}let u=_e.get(c);if(u==null){if(c!==await dt(i)){x(o,"Schema hash mismatch",400);return}let l=await Kr(i,t.db.prismaORMConnectionString,t.debug);_e.set(c,{base64Original:i,...l}),x(o,c);return}if(i!==u.base64Original){x(o,"Schema mismatch",400);return}x(o,c)},r)),e.on("POST","/:clientVersion/:schemaHash/transaction/start",M(async(s,o,a)=>{W(s,t);let i=await an(s,o);if(i!==null)try{let c=await wt(o,t,a);if(c===null)return;let u=await c.startTransaction(i,Ne(s)),l=cn(u,o);if(l===null)return;let{id:f}=l,d=a.clientVersion,p=a.schemaHash;T(o,{...u,"data-proxy":{endpoint:`http://localhost:${t.port}/${d}/${p}/itx/${f}`}})}catch(c){let{handleEngineError:u}=await Me();u(c,o)}},r));let n=[["GET","/connection-info"],["POST","/query"],["POST","/transaction/start"],["POST","/transaction/:transactionId/commit"],["POST","/transaction/:transactionId/query"],["POST","/transaction/:transactionId/rollback"]];for(let[s,o]of n)e.on(s,o,M(async(a,i)=>{W(a,t);let{getQueryPlanExecutorServer:c,queryPlanExecutorVersion:u}=await Oo(),l=ie(a.headers,"prisma-engine-hash");if(l!=="0.0.0"&&l!==u)throw new A(400,`Using an HTTP connection string is not supported with Prisma Client version ${l??"<missing>"} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${u}.`);let f=await c(t),d=Xr(a,{origin:`http://localhost:${t.port}`}),p=await f.fetch(d);await Zr(p,i)},r))}async function wt(e,t,r){let{Engine:n}=await Me(),s=Vr(r,e);if(s===null)return null;let{base64Override:o,overrideHash:a}=s.schemas;return await n.get({base64Schema:o,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||r.clientVersion||"",debug:t.debug,platform:await No(),schemaHash:a})}var Et,En,vn,Rn,xn=v(()=>{"use strict";m();Et=require("stream/consumers");Ue();Gr();Jr();ft();fe();en();C();Oe();sn();un()});var In={};V(In,{registerUtilityRoutes:()=>Bo});function Bo(e,t,r){e.on("POST","/database/dump",M(async(n,s)=>{await t.db.dump(t.databaseDumpPath),T(s,{dumpPath:t.databaseDumpPath},201)},r)),e.on("GET","/health",M((n,s)=>{T(s,{name:t.name})},r))}var Dn=v(()=>{"use strict";m();C();Oe()});var ya={};V(ya,{DEFAULT_DATABASE_PORT:()=>Pe,DEFAULT_SERVER_PORT:()=>we,DEFAULT_SHADOW_DATABASE_PORT:()=>Ee,DEFAULT_STREAMS_PORT:()=>ve,PortNotAvailableError:()=>N,ServerAlreadyRunningError:()=>de,copyPrismaDevRuntimeAssets:()=>Pr,getPrismaDevRuntimeAssetManifest:()=>Xe,getPrismaDevServerConnection:()=>jn,startPrismaDevServer:()=>Vn,unstable_startServer:()=>ha});module.exports=es(ya);m();m();Ue();m();var Ae=require("net"),Nr=require("path"),Mr=require("pathe/utils");Y();se();m();var ze=require("perf_hooks"),mr=require("@electric-sql/pglite");m();var sr=require("buffer"),tr=500,rr=/(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+)/,gs=new RegExp(`(?:${rr.source}\\.)*${rr.source}`),fs=new RegExp(`(?:FROM|JOIN|UPDATE|INTO|TABLE)\\s+(${gs.source})`,"gi"),hs=/"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|(\w+)/g,nr=/prismaQuery='([^']+)'/,ys=new Set([q(`
14
14
  select b.oid, b.typarray
15
15
  from pg_catalog.pg_type a
16
16
  left join pg_catalog.pg_type b on b.oid = a.typelem
17
17
  where a.typcategory = $1
18
18
  group by b.oid, b.typarray
19
19
  order by b.oid
20
- `),q('GRANT "pg_write_all_data" TO "prisma_application"'),q("SELECT SUM(reads)::BIGINT AS reads, SUM(writes)::BIGINT AS writes, SUM(COALESCE(extends, $1))::BIGINT AS extends FROM pg_stat_io"),q("SELECT pg_database_size(current_database())::BIGINT, SUM(pg_total_relation_size(relid))::BIGINT AS pg_total_relation_size FROM pg_stat_user_tables"),q("SELECT COUNT(*) AS cnt FROM pg_stat_activity WHERE pid <> pg_backend_pid() and xact_start notnull")]),fs=[/^BEGIN\b/i,/^COMMIT\b/i,/^ROLLBACK\b/i,/^SAVEPOINT\b/i,/^RELEASE\b/i,/^SET\b/i,/^SHOW\b/i,/^DISCARD\b/i,/^DEALLOCATE\b/i,/^CLOSE\b/i,/^CREATE EXTENSION\b/i,/^WITH state_assign\b/i];function sr(){return{generatedAt:Date.now(),queries:[]}}function q(e){return e.replace(/\s+/g," ").trim()}function or(e){return lr(q(e))}function ar(e){if(!e?.action||!e.model&&/raw/i.test(e.action))return null;let t=e.payload?lr(JSON.stringify(e.payload)):"0";return`${e.model??""}.${e.action}:${t}`}function hs(e){let t=new Set;for(let r of e.matchAll(ms)){let n=r[1];if(!n)continue;let s;for(let o of n.matchAll(ps))s=o[1]??o[2]??o[3]??o[4];s&&!s.startsWith("pg_")&&t.add(s)}return Array.from(t)}function ys(e){return gs.has(e)?!0:fs.some(t=>t.test(e))}function ir(e){if(ys(q(e)))return null;let t=hs(e);return t.length===0&&/\bpg_\w+/i.test(e)?null:t}function Ke(e){if(Array.isArray(e))return e.map(Ke);if(e!==null&&typeof e=="object"){let t=e;return t.$type==="Param"?"<<redacted>>":Object.fromEntries(Object.entries(t).map(([r,n])=>[r,Ke(n)]))}return e}function cr(e){let t=e.match(rr);if(!t?.[1])return{cleanedSql:q(e),prismaQueryInfo:null};let r=e.replace(rr,"");r=r.replace(/,\s*,/g,",").replace(/\/\*\s*,/g,"/*").replace(/,\s*\*\//g,"*/").replace(/\/\*\s*\*\//g,"").replace(/\s+/g," ").trim();let n=decodeURIComponent(t[1]),s=n.indexOf(":");if(s===-1)return{cleanedSql:r,prismaQueryInfo:{action:n,isRaw:!0}};let o=n.slice(0,s),a=n.slice(s+1),i=o.indexOf("."),c=i===-1?void 0:o.slice(0,i),u=i===-1?o:o.slice(i+1);if(!u)return{cleanedSql:r,prismaQueryInfo:null};let l;try{l=Ke(JSON.parse(nr.Buffer.from(a,"base64url").toString("utf8")))}catch{l=void 0}return{cleanedSql:r,prismaQueryInfo:{action:u,isRaw:!1,model:c,payload:l}}}function ur(e,t={}){let r=new Set(t.excludeApplications??[]),n=Ss(t.limit),s=typeof t.since=="number"&&Number.isFinite(t.since)?t.since:null,o=new Map;for(let i of e){if(i.applicationName&&r.has(i.applicationName))continue;let c=Date.parse(i.timestamp);if(!Number.isFinite(c))continue;let u=`${i.queryId}:${i.groupKey??""}`,l=o.get(u);if(!l){o.set(u,{count:1,duration:i.durationMs,groupKey:i.groupKey,id:u,lastSeen:c,maxDurationMs:i.durationMs,minDurationMs:i.durationMs,prismaQueryInfo:i.prismaQueryInfo,query:i.query,queryId:i.queryId,reads:i.reads,rowsReturned:i.rowsReturned,tables:i.tables,totalDurationMs:i.durationMs});continue}l.count+=1,l.lastSeen=Math.max(l.lastSeen,c),l.maxDurationMs=Math.max(l.maxDurationMs??i.durationMs,i.durationMs),l.minDurationMs=Math.min(l.minDurationMs??i.durationMs,i.durationMs),l.reads+=i.reads,l.rowsReturned+=i.rowsReturned,l.totalDurationMs+=i.durationMs,l.duration=l.totalDurationMs/l.count,!l.prismaQueryInfo&&i.prismaQueryInfo&&(l.prismaQueryInfo=i.prismaQueryInfo),l.tables.length===0&&i.tables.length>0&&(l.tables=i.tables)}let a=Array.from(o.values()).filter(i=>s===null||i.lastSeen>=s).sort((i,c)=>c.lastSeen-i.lastSeen).slice(0,n).map(({totalDurationMs:i,...c})=>c);return{generatedAt:Date.now(),queries:a}}function Ss(e){return typeof e=="number"&&Number.isInteger(e)&&Number.isSafeInteger(e)&&e>0?Math.min(e,er):er}function lr(e){let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t+e.charCodeAt(r)&4294967295;return(t>>>0).toString(36)}var Te=new WeakMap;function mr(e){let t=Te.get(e);if(t&&!t.closed)return t.bridge;let r=bs(e),n={bridge:{close:()=>(n.closed||(n.closed=!0,n.sessions.clear(),n.subscribers.clear(),n.queryQueue.enqueue=n.originalEnqueue,n.queryQueue.clearQueueForHandler=n.originalClearQueueForHandler,Te.delete(e)),Promise.resolve()),subscribe:s=>(n.subscribers.add(s),()=>{n.subscribers.delete(s)})},closed:!1,originalClearQueueForHandler:r.clearQueueForHandler.bind(r),originalEnqueue:r.enqueue.bind(r),queryQueue:r,sessions:new Map,subscribers:new Set};return r.clearQueueForHandler=s=>{n.sessions.delete(s),n.originalClearQueueForHandler(s)},r.enqueue=async(s,o,a)=>{let i=Ps(n,s),c=vs(o);ws(i,c);let u=Es(i,c);if(!u)return await n.originalEnqueue(s,o,a);let l={commandTags:[],dataRowCount:0},f=new dr.protocol.Parser,d=ze.performance.now(),p=await n.originalEnqueue(s,o,E=>{f.parse(E,re=>{_s(l,re)}),a(E)}),y=Math.max(0,ze.performance.now()-d);return Os(n,{applicationName:u.applicationName,durationMs:y,query:u.query,responseStats:l}),p},Te.set(e,n),n.bridge}async function pr(e){await Te.get(e)?.bridge.close()}function bs(e){let t=e.queryQueue;if(!t||typeof t.enqueue!="function"||typeof t.clearQueueForHandler!="function")throw new Error("PGLiteSocketServer query queue is unavailable for query insights capture");return t}function Ps(e,t){let r=e.sessions.get(t);if(r)return r;let n={applicationName:null,portals:new Map,statements:new Map};return e.sessions.set(t,n),n}function ws(e,t){if(t)switch(t.kind){case"startup":e.applicationName=t.applicationName;return;case"parse":e.statements.set(t.statementName,t.query);return;case"bind":{let r=e.statements.get(t.statementName);r&&e.portals.set(t.portalName,r);return}case"close":t.target==="portal"?e.portals.delete(t.name):e.statements.delete(t.name);return;default:return}}function Es(e,t){if(!t)return null;if(t.kind==="query")return{applicationName:e.applicationName,query:t.query};if(t.kind==="execute"){let r=e.portals.get(t.portalName);return r?{applicationName:e.applicationName,query:r}:null}return null}function vs(e){let t=Buffer.from(e);if(t.length<4)return null;let r=t.readInt32BE(0);if(t.length>=8&&r===t.length){let s=t.readInt32BE(4);if(s===196608||s===196608)return Rs(t)}if(t.length<5)return null;switch(String.fromCharCode(t[0]??0)){case"Q":return Ts(t);case"P":return xs(t);case"B":return Is(t);case"E":return Ds(t);case"C":return As(t);default:return null}}function Rs(e){let t=8,r=null;for(;t<e.length-1;){let n=k(e,t);if(!n||n.value==="")break;t=n.nextOffset;let s=k(e,t);if(!s)break;t=s.nextOffset,n.value==="application_name"&&(r=s.value)}return{applicationName:r,kind:"startup"}}function Ts(e){let t=k(e,5);return t?{kind:"query",query:t.value}:null}function xs(e){let t=k(e,5);if(!t)return null;let r=k(e,t.nextOffset);return r?{kind:"parse",query:r.value,statementName:t.value}:null}function Is(e){let t=k(e,5);if(!t)return null;let r=k(e,t.nextOffset);return r?{kind:"bind",portalName:t.value,statementName:r.value}:null}function Ds(e){let t=k(e,5);return t?{kind:"execute",portalName:t.value}:null}function As(e){if(e.length<7)return null;let t=e[5];if(t===void 0)return null;let r=k(e,6);return r?{kind:"close",name:r.value,target:t===80?"portal":"statement"}:null}function k(e,t){let r=e.indexOf(0,t);return r===-1?null:{nextOffset:r+1,value:e.toString("utf8",t,r)}}function _s(e,t){if(t.name==="dataRow"){e.dataRowCount+=1;return}t.name==="commandComplete"&&typeof t.text=="string"&&t.text.length>0&&e.commandTags.push(t.text)}function Os(e,t){let r=cr(t.query),n=ir(r.cleanedSql);if(!n)return;let s=or(r.cleanedSql),o={applicationName:t.applicationName,durationMs:t.durationMs,groupKey:ar(r.prismaQueryInfo),prismaQueryInfo:r.prismaQueryInfo,query:r.cleanedSql,queryId:s,reads:0,rowsReturned:Ns(t.responseStats),tables:n,timestamp:new Date().toISOString()};for(let a of e.subscribers)a([o])}function Ns(e){let t=e.commandTags.reduce((r,n)=>r+Ms(n),0);return Math.max(t,e.dataRowCount)}function Ms(e){let t=e.trim().split(/\s+/).at(-1);return!t||!/^\d+$/.test(t)?0:Number(t)}m();var H=require("fs"),B=require("fs/promises"),fr=require("module"),hr=require("path"),O=require("url"),Bs=(0,fr.createRequire)(h),Ls=["initdb.wasm","pglite.data","pglite.wasm"],Ye="pglite-seed.tar.gz",yr={amcheck:"amcheck.tar.gz",bloom:"bloom.tar.gz",btree_gin:"btree_gin.tar.gz",btree_gist:"btree_gist.tar.gz",citext:"citext.tar.gz",cube:"cube.tar.gz",dict_int:"dict_int.tar.gz",dict_xsyn:"dict_xsyn.tar.gz",earthdistance:"earthdistance.tar.gz",file_fdw:"file_fdw.tar.gz",fuzzystrmatch:"fuzzystrmatch.tar.gz",hstore:"hstore.tar.gz",intarray:"intarray.tar.gz",isn:"isn.tar.gz",lo:"lo.tar.gz",ltree:"ltree.tar.gz",pageinspect:"pageinspect.tar.gz",pg_buffercache:"pg_buffercache.tar.gz",pg_freespacemap:"pg_freespacemap.tar.gz",pg_surgery:"pg_surgery.tar.gz",pg_trgm:"pg_trgm.tar.gz",pg_visibility:"pg_visibility.tar.gz",pg_walinspect:"pg_walinspect.tar.gz",seg:"seg.tar.gz",tablefunc:"tablefunc.tar.gz",tcn:"tcn.tar.gz",tsm_system_rows:"tsm_system_rows.tar.gz",tsm_system_time:"tsm_system_time.tar.gz",unaccent:"unaccent.tar.gz",uuid_ossp:"uuid-ossp.tar.gz",vector:"vector.tar.gz"},Sr=[...Ls.map(e=>({fileName:e,kind:"core",name:e})),{fileName:Ye,kind:"core",name:Ye},...Object.entries(yr).map(([e,t])=>({fileName:t,kind:"extension",name:e}))],Ie=new Map,$s=Symbol.for("@prisma/dev/bundled-pglite-runtime-asset-sources"),xe=null;async function br(e){let t=X(e),r=(0,O.fileURLToPath)(t);await(0,B.mkdir)(r,{recursive:!0});let n=[];for(let s of Xe()){let o=new URL(s.fileName,t),a=(0,O.fileURLToPath)(o);await(0,B.copyFile)(s.sourcePath,a),n.push({...s,destinationPath:a})}return n}function Xe(){let e=Pr(),t=X(new URL("./runtime-assets/",h));return Sr.map(r=>({...r,sourcePath:(0,O.fileURLToPath)(oe(r.fileName,e,t))}))}async function Ze(){await Fs();let e=wr();if(e)return await Qs(e),await ks(e);let t=qs(),r=t.href,n=Ie.get(r);return n||(n=Cs(t),Ie.set(r,n)),await n}async function ks(e){let t=`bundled:${e.wasmModule.href}:${e.fsBundle.href}`,r=Ie.get(t);return r||(r=Us(e),Ie.set(t,r)),await r}async function Cs(e){let t=X(new URL("./runtime-assets/",h)),[r,n,s]=await Promise.all([(0,B.readFile)(oe("pglite.data",e,t)),(0,B.readFile)(oe(Ye,e,t)),(0,B.readFile)(oe("pglite.wasm",e,t))]),o=Er();return{extensions:Object.fromEntries(Object.entries(yr).map(([a,i])=>[a,oe(i,e,t)])),fsBundle:new Blob([Uint8Array.from(r)]),loadDataDir:new Blob([Uint8Array.from(n)]),wasmModule:await o.compile(s)}}async function Us(e){let[t,r,n]=await Promise.all([Je(e.fsBundle),Je(e.loadDataDir),Je(e.wasmModule)]),s=Er();return{extensions:e.extensions,fsBundle:new Blob([Uint8Array.from(t)]),loadDataDir:new Blob([Uint8Array.from(r)]),wasmModule:await s.compile(n)}}async function Qs(e){if(e.initdbWasm.protocol!=="file:")return;let t=new URL("initdb.wasm",X(new URL("./",e.initdbWasm))),r=(0,O.fileURLToPath)(t);(0,H.existsSync)(r)||await(0,B.copyFile)((0,O.fileURLToPath)(e.initdbWasm),r)}function X(e){return e instanceof URL?gr(e):gr((0,O.pathToFileURL)(e))}function gr(e){return e.href.endsWith("/")?e:new URL(`${e.href}/`)}function Pr(){let e=Bs.resolve("@electric-sql/pglite");return X((0,hr.dirname)(e))}function qs(){let e=X(new URL("./",h));if(Hs(e))return e;if(Ws())return Pr();throw new Error("Unable to locate PGlite runtime assets. If you bundled @prisma/dev, copy them next to the bundle with copyPrismaDevRuntimeAssets().")}function Hs(e){return Sr.every(t=>(0,H.existsSync)((0,O.fileURLToPath)(new URL(t.fileName,e))))}function wr(){return globalThis[$s]??null}async function Fs(){!Gs()||wr()||(xe||(xe=import("./runtime-assets-manifest.bun.js").then(()=>{}).catch(e=>{throw xe=null,e})),await xe)}function Ws(){let e=(0,O.fileURLToPath)(new URL("../package.json",h));if(!(0,H.existsSync)(e))return!1;try{return JSON.parse((0,H.readFileSync)(e,"utf8")).name==="@prisma/dev"}catch{return!1}}function Gs(){return typeof globalThis.Bun<"u"}function Er(){let e=globalThis.WebAssembly;if(!e)throw new Error("WebAssembly is not available in this runtime.");return e}async function Je(e){if(e.protocol==="file:")return await(0,B.readFile)(e);let t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch runtime asset ${e.href}: ${t.status} ${t.statusText}`);return new Uint8Array(await t.arrayBuffer())}function oe(e,t,r){let n=new URL(e,t);if((0,H.existsSync)((0,O.fileURLToPath)(n)))return n;if(r){let s=new URL(e,r);if((0,H.existsSync)((0,O.fileURLToPath)(s)))return s}return n}m();var rt=require("@electric-sql/pglite"),L="_prisma_dev_wal",tt="events",Tr="install_all_triggers",vr="capture_event",Rr="prisma_dev_wal_capture",ae=new WeakMap,js=new Set(["ALTER","COMMIT","COPY","CREATE","DELETE","DROP","INSERT","MERGE","TRUNCATE","UPDATE"]);async function nt(e,t){let r=ae.get(e);if(r&&!r.closed)return r.bridge;let n=e.execProtocolRaw.bind(e),s=e.execProtocolRawStream.bind(e),o={bridge:{close:async()=>{o.closed||(o.closed=!0,o.subscribers.clear(),e.execProtocolRaw===a&&(e.execProtocolRaw=n),e.execProtocolRawStream===i&&(e.execProtocolRawStream=s),await o.pollPromise,ae.delete(e))},poll:async()=>{await et(o,e)},subscribe:c=>(o.subscribers.add(c),()=>{o.subscribers.delete(c)})},closed:!1,ensureInfrastructurePromise:null,pendingPoll:!1,pollPromise:null,subscribers:new Set,suppressDepth:0},a=async(c,u)=>{let l=await n(c,u);return!o.closed&&o.suppressDepth===0&&Ir(l)&&et(o,e),l},i=async(c,u)=>{let l=[],f=new rt.protocol.Parser,d=u?.onRawData;await s(c,{...u,onRawData:p=>{f.parse(p,y=>{l.push(y)}),d?.(p)}}),!o.closed&&o.suppressDepth===0&&st(l)&&et(o,e)};return e.execProtocolRaw=a,e.execProtocolRawStream=i,ae.set(e,o),await Dr(o,e),o.bridge}async function xr(e){let t=ae.get(e);t&&await t.bridge.close()}function st(e){for(let t of e){if(t.name!=="commandComplete"||typeof t.text!="string")continue;let r=t.text.split(/\s+/,1)[0]?.toUpperCase();if(r&&js.has(r))return!0}return!1}function Ir(e){if(e.length===0)return!1;let t=[];return new rt.protocol.Parser().parse(e,n=>{t.push(n)}),st(t)}async function Dr(e,t){e.ensureInfrastructurePromise??=ot(e,t,async()=>{await t.exec(`CREATE SCHEMA IF NOT EXISTS "${L}"`),await t.exec(`
20
+ `),q('GRANT "pg_write_all_data" TO "prisma_application"'),q("SELECT SUM(reads)::BIGINT AS reads, SUM(writes)::BIGINT AS writes, SUM(COALESCE(extends, $1))::BIGINT AS extends FROM pg_stat_io"),q("SELECT pg_database_size(current_database())::BIGINT, SUM(pg_total_relation_size(relid))::BIGINT AS pg_total_relation_size FROM pg_stat_user_tables"),q("SELECT COUNT(*) AS cnt FROM pg_stat_activity WHERE pid <> pg_backend_pid() and xact_start notnull")]),Ss=[/^BEGIN\b/i,/^COMMIT\b/i,/^ROLLBACK\b/i,/^SAVEPOINT\b/i,/^RELEASE\b/i,/^SET\b/i,/^SHOW\b/i,/^DISCARD\b/i,/^DEALLOCATE\b/i,/^CLOSE\b/i,/^CREATE EXTENSION\b/i,/^WITH state_assign\b/i];function or(){return{generatedAt:Date.now(),queries:[]}}function q(e){return e.replace(/\s+/g," ").trim()}function ar(e){return dr(q(e))}function ir(e){if(!e?.action||!e.model&&/raw/i.test(e.action))return null;let t=e.payload?dr(JSON.stringify(e.payload)):"0";return`${e.model??""}.${e.action}:${t}`}function bs(e){let t=new Set;for(let r of e.matchAll(fs)){let n=r[1];if(!n)continue;let s;for(let o of n.matchAll(hs))s=o[1]??o[2]??o[3]??o[4];s&&!s.startsWith("pg_")&&t.add(s)}return Array.from(t)}function Ps(e){return ys.has(e)?!0:Ss.some(t=>t.test(e))}function cr(e){if(Ps(q(e)))return null;let t=bs(e);return t.length===0&&/\bpg_\w+/i.test(e)?null:t}function Ke(e){if(Array.isArray(e))return e.map(Ke);if(e!==null&&typeof e=="object"){let t=e;return t.$type==="Param"?"<<redacted>>":Object.fromEntries(Object.entries(t).map(([r,n])=>[r,Ke(n)]))}return e}function ur(e){let t=e.match(nr);if(!t?.[1])return{cleanedSql:q(e),prismaQueryInfo:null};let r=e.replace(nr,"");r=r.replace(/,\s*,/g,",").replace(/\/\*\s*,/g,"/*").replace(/,\s*\*\//g,"*/").replace(/\/\*\s*\*\//g,"").replace(/\s+/g," ").trim();let n=decodeURIComponent(t[1]),s=n.indexOf(":");if(s===-1)return{cleanedSql:r,prismaQueryInfo:{action:n,isRaw:!0}};let o=n.slice(0,s),a=n.slice(s+1),i=o.indexOf("."),c=i===-1?void 0:o.slice(0,i),u=i===-1?o:o.slice(i+1);if(!u)return{cleanedSql:r,prismaQueryInfo:null};let l;try{l=Ke(JSON.parse(sr.Buffer.from(a,"base64url").toString("utf8")))}catch{l=void 0}return{cleanedSql:r,prismaQueryInfo:{action:u,isRaw:!1,model:c,payload:l}}}function lr(e,t={}){let r=new Set(t.excludeApplications??[]),n=ws(t.limit),s=typeof t.since=="number"&&Number.isFinite(t.since)?t.since:null,o=new Map;for(let i of e){if(i.applicationName&&r.has(i.applicationName))continue;let c=Date.parse(i.timestamp);if(!Number.isFinite(c))continue;let u=`${i.queryId}:${i.groupKey??""}`,l=o.get(u);if(!l){o.set(u,{count:1,duration:i.durationMs,groupKey:i.groupKey,id:u,lastSeen:c,maxDurationMs:i.durationMs,minDurationMs:i.durationMs,prismaQueryInfo:i.prismaQueryInfo,query:i.query,queryId:i.queryId,reads:i.reads,rowsReturned:i.rowsReturned,tables:i.tables,totalDurationMs:i.durationMs});continue}l.count+=1,l.lastSeen=Math.max(l.lastSeen,c),l.maxDurationMs=Math.max(l.maxDurationMs??i.durationMs,i.durationMs),l.minDurationMs=Math.min(l.minDurationMs??i.durationMs,i.durationMs),l.reads+=i.reads,l.rowsReturned+=i.rowsReturned,l.totalDurationMs+=i.durationMs,l.duration=l.totalDurationMs/l.count,!l.prismaQueryInfo&&i.prismaQueryInfo&&(l.prismaQueryInfo=i.prismaQueryInfo),l.tables.length===0&&i.tables.length>0&&(l.tables=i.tables)}let a=Array.from(o.values()).filter(i=>s===null||i.lastSeen>=s).sort((i,c)=>c.lastSeen-i.lastSeen).slice(0,n).map(({totalDurationMs:i,...c})=>c);return{generatedAt:Date.now(),queries:a}}function ws(e){return typeof e=="number"&&Number.isInteger(e)&&Number.isSafeInteger(e)&&e>0?Math.min(e,tr):tr}function dr(e){let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t+e.charCodeAt(r)&4294967295;return(t>>>0).toString(36)}var Te=new WeakMap;function pr(e){let t=Te.get(e);if(t&&!t.closed)return t.bridge;let r=Es(e),n={bridge:{close:()=>(n.closed||(n.closed=!0,n.sessions.clear(),n.subscribers.clear(),n.queryQueue.enqueue=n.originalEnqueue,n.queryQueue.clearQueueForHandler=n.originalClearQueueForHandler,Te.delete(e)),Promise.resolve()),subscribe:s=>(n.subscribers.add(s),()=>{n.subscribers.delete(s)})},closed:!1,originalClearQueueForHandler:r.clearQueueForHandler.bind(r),originalEnqueue:r.enqueue.bind(r),queryQueue:r,sessions:new Map,subscribers:new Set};return r.clearQueueForHandler=s=>{n.sessions.delete(s),n.originalClearQueueForHandler(s)},r.enqueue=async(s,o,a)=>{let i=vs(n,s),c=xs(o);Rs(i,c);let u=Ts(i,c);if(!u)return await n.originalEnqueue(s,o,a);let l={commandTags:[],dataRowCount:0},f=new mr.protocol.Parser,d=ze.performance.now(),p=await n.originalEnqueue(s,o,E=>{f.parse(E,re=>{Ms(l,re)}),a(E)}),y=Math.max(0,ze.performance.now()-d);return Bs(n,{applicationName:u.applicationName,durationMs:y,query:u.query,responseStats:l}),p},Te.set(e,n),n.bridge}async function gr(e){await Te.get(e)?.bridge.close()}function Es(e){let t=e.queryQueue;if(!t||typeof t.enqueue!="function"||typeof t.clearQueueForHandler!="function")throw new Error("PGLiteSocketServer query queue is unavailable for query insights capture");return t}function vs(e,t){let r=e.sessions.get(t);if(r)return r;let n={applicationName:null,portals:new Map,statements:new Map};return e.sessions.set(t,n),n}function Rs(e,t){if(t)switch(t.kind){case"startup":e.applicationName=t.applicationName;return;case"parse":e.statements.set(t.statementName,t.query);return;case"bind":{let r=e.statements.get(t.statementName);r&&e.portals.set(t.portalName,r);return}case"close":t.target==="portal"?e.portals.delete(t.name):e.statements.delete(t.name);return;default:return}}function Ts(e,t){if(!t)return null;if(t.kind==="query")return{applicationName:e.applicationName,query:t.query};if(t.kind==="execute"){let r=e.portals.get(t.portalName);return r?{applicationName:e.applicationName,query:r}:null}return null}function xs(e){let t=Buffer.from(e);if(t.length<4)return null;let r=t.readInt32BE(0);if(t.length>=8&&r===t.length){let s=t.readInt32BE(4);if(s===196608||s===196608)return Is(t)}if(t.length<5)return null;switch(String.fromCharCode(t[0]??0)){case"Q":return Ds(t);case"P":return As(t);case"B":return _s(t);case"E":return Os(t);case"C":return Ns(t);default:return null}}function Is(e){let t=8,r=null;for(;t<e.length-1;){let n=k(e,t);if(!n||n.value==="")break;t=n.nextOffset;let s=k(e,t);if(!s)break;t=s.nextOffset,n.value==="application_name"&&(r=s.value)}return{applicationName:r,kind:"startup"}}function Ds(e){let t=k(e,5);return t?{kind:"query",query:t.value}:null}function As(e){let t=k(e,5);if(!t)return null;let r=k(e,t.nextOffset);return r?{kind:"parse",query:r.value,statementName:t.value}:null}function _s(e){let t=k(e,5);if(!t)return null;let r=k(e,t.nextOffset);return r?{kind:"bind",portalName:t.value,statementName:r.value}:null}function Os(e){let t=k(e,5);return t?{kind:"execute",portalName:t.value}:null}function Ns(e){if(e.length<7)return null;let t=e[5];if(t===void 0)return null;let r=k(e,6);return r?{kind:"close",name:r.value,target:t===80?"portal":"statement"}:null}function k(e,t){let r=e.indexOf(0,t);return r===-1?null:{nextOffset:r+1,value:e.toString("utf8",t,r)}}function Ms(e,t){if(t.name==="dataRow"){e.dataRowCount+=1;return}t.name==="commandComplete"&&typeof t.text=="string"&&t.text.length>0&&e.commandTags.push(t.text)}function Bs(e,t){let r=ur(t.query),n=cr(r.cleanedSql);if(!n)return;let s=ar(r.cleanedSql),o={applicationName:t.applicationName,durationMs:t.durationMs,groupKey:ir(r.prismaQueryInfo),prismaQueryInfo:r.prismaQueryInfo,query:r.cleanedSql,queryId:s,reads:0,rowsReturned:Ls(t.responseStats),tables:n,timestamp:new Date().toISOString()};for(let a of e.subscribers)a([o])}function Ls(e){let t=e.commandTags.reduce((r,n)=>r+$s(n),0);return Math.max(t,e.dataRowCount)}function $s(e){let t=e.trim().split(/\s+/).at(-1);return!t||!/^\d+$/.test(t)?0:Number(t)}m();var H=require("fs"),B=require("fs/promises"),hr=require("module"),yr=require("path"),O=require("url"),ks=(0,hr.createRequire)(h),Cs=["initdb.wasm","pglite.data","pglite.wasm"],Ye="pglite-seed.tar.gz",Sr={amcheck:"amcheck.tar.gz",bloom:"bloom.tar.gz",btree_gin:"btree_gin.tar.gz",btree_gist:"btree_gist.tar.gz",citext:"citext.tar.gz",cube:"cube.tar.gz",dict_int:"dict_int.tar.gz",dict_xsyn:"dict_xsyn.tar.gz",earthdistance:"earthdistance.tar.gz",file_fdw:"file_fdw.tar.gz",fuzzystrmatch:"fuzzystrmatch.tar.gz",hstore:"hstore.tar.gz",intarray:"intarray.tar.gz",isn:"isn.tar.gz",lo:"lo.tar.gz",ltree:"ltree.tar.gz",pageinspect:"pageinspect.tar.gz",pg_buffercache:"pg_buffercache.tar.gz",pg_freespacemap:"pg_freespacemap.tar.gz",pg_surgery:"pg_surgery.tar.gz",pg_trgm:"pg_trgm.tar.gz",pg_visibility:"pg_visibility.tar.gz",pg_walinspect:"pg_walinspect.tar.gz",seg:"seg.tar.gz",tablefunc:"tablefunc.tar.gz",tcn:"tcn.tar.gz",tsm_system_rows:"tsm_system_rows.tar.gz",tsm_system_time:"tsm_system_time.tar.gz",unaccent:"unaccent.tar.gz",uuid_ossp:"uuid-ossp.tar.gz",vector:"vector.tar.gz"},br=[...Cs.map(e=>({fileName:e,kind:"core",name:e})),{fileName:Ye,kind:"core",name:Ye},...Object.entries(Sr).map(([e,t])=>({fileName:t,kind:"extension",name:e}))],Ie=new Map,Us=Symbol.for("@prisma/dev/bundled-pglite-runtime-asset-sources"),xe=null;async function Pr(e){let t=X(e),r=(0,O.fileURLToPath)(t);await(0,B.mkdir)(r,{recursive:!0});let n=[];for(let s of Xe()){let o=new URL(s.fileName,t),a=(0,O.fileURLToPath)(o);await(0,B.copyFile)(s.sourcePath,a),n.push({...s,destinationPath:a})}return n}function Xe(){let e=wr(),t=X(new URL("./runtime-assets/",h));return br.map(r=>({...r,sourcePath:(0,O.fileURLToPath)(oe(r.fileName,e,t))}))}async function Ze(){await js();let e=Er();if(e)return await Fs(e),await Qs(e);let t=Ws(),r=t.href,n=Ie.get(r);return n||(n=qs(t),Ie.set(r,n)),await n}async function Qs(e){let t=`bundled:${e.wasmModule.href}:${e.fsBundle.href}`,r=Ie.get(t);return r||(r=Hs(e),Ie.set(t,r)),await r}async function qs(e){let t=X(new URL("./runtime-assets/",h)),[r,n,s]=await Promise.all([(0,B.readFile)(oe("pglite.data",e,t)),(0,B.readFile)(oe(Ye,e,t)),(0,B.readFile)(oe("pglite.wasm",e,t))]),o=vr();return{extensions:Object.fromEntries(Object.entries(Sr).map(([a,i])=>[a,oe(i,e,t)])),fsBundle:new Blob([Uint8Array.from(r)]),loadDataDir:new Blob([Uint8Array.from(n)]),wasmModule:await o.compile(s)}}async function Hs(e){let[t,r,n]=await Promise.all([Je(e.fsBundle),Je(e.loadDataDir),Je(e.wasmModule)]),s=vr();return{extensions:e.extensions,fsBundle:new Blob([Uint8Array.from(t)]),loadDataDir:new Blob([Uint8Array.from(r)]),wasmModule:await s.compile(n)}}async function Fs(e){if(e.initdbWasm.protocol!=="file:")return;let t=new URL("initdb.wasm",X(new URL("./",e.initdbWasm))),r=(0,O.fileURLToPath)(t);(0,H.existsSync)(r)||await(0,B.copyFile)((0,O.fileURLToPath)(e.initdbWasm),r)}function X(e){return e instanceof URL?fr(e):fr((0,O.pathToFileURL)(e))}function fr(e){return e.href.endsWith("/")?e:new URL(`${e.href}/`)}function wr(){let e=ks.resolve("@electric-sql/pglite");return X((0,yr.dirname)(e))}function Ws(){let e=X(new URL("./",h));if(Gs(e))return e;if(Vs())return wr();throw new Error("Unable to locate PGlite runtime assets. If you bundled @prisma/dev, copy them next to the bundle with copyPrismaDevRuntimeAssets().")}function Gs(e){return br.every(t=>(0,H.existsSync)((0,O.fileURLToPath)(new URL(t.fileName,e))))}function Er(){return globalThis[Us]??null}async function js(){!Ks()||Er()||(xe||(xe=import("./runtime-assets-manifest.bun.js").then(()=>{}).catch(e=>{throw xe=null,e})),await xe)}function Vs(){let e=(0,O.fileURLToPath)(new URL("../package.json",h));if(!(0,H.existsSync)(e))return!1;try{return JSON.parse((0,H.readFileSync)(e,"utf8")).name==="@prisma/dev"}catch{return!1}}function Ks(){return typeof globalThis.Bun<"u"}function vr(){let e=globalThis.WebAssembly;if(!e)throw new Error("WebAssembly is not available in this runtime.");return e}async function Je(e){if(e.protocol==="file:")return await(0,B.readFile)(e);let t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch runtime asset ${e.href}: ${t.status} ${t.statusText}`);return new Uint8Array(await t.arrayBuffer())}function oe(e,t,r){let n=new URL(e,t);if((0,H.existsSync)((0,O.fileURLToPath)(n)))return n;if(r){let s=new URL(e,r);if((0,H.existsSync)((0,O.fileURLToPath)(s)))return s}return n}m();var rt=require("@electric-sql/pglite"),L="_prisma_dev_wal",tt="events",xr="install_all_triggers",Rr="capture_event",Tr="prisma_dev_wal_capture",ae=new WeakMap,zs=new Set(["ALTER","COMMIT","COPY","CREATE","DELETE","DROP","INSERT","MERGE","TRUNCATE","UPDATE"]);async function nt(e,t){let r=ae.get(e);if(r&&!r.closed)return r.bridge;let n=e.execProtocolRaw.bind(e),s=e.execProtocolRawStream.bind(e),o={bridge:{close:async()=>{o.closed||(o.closed=!0,o.subscribers.clear(),e.execProtocolRaw===a&&(e.execProtocolRaw=n),e.execProtocolRawStream===i&&(e.execProtocolRawStream=s),await o.pollPromise,ae.delete(e))},poll:async()=>{await et(o,e)},subscribe:c=>(o.subscribers.add(c),()=>{o.subscribers.delete(c)})},closed:!1,ensureInfrastructurePromise:null,pendingPoll:!1,pollPromise:null,subscribers:new Set,suppressDepth:0},a=async(c,u)=>{let l=await n(c,u);return!o.closed&&o.suppressDepth===0&&Dr(l)&&et(o,e),l},i=async(c,u)=>{let l=[],f=new rt.protocol.Parser,d=u?.onRawData;await s(c,{...u,onRawData:p=>{f.parse(p,y=>{l.push(y)}),d?.(p)}}),!o.closed&&o.suppressDepth===0&&st(l)&&et(o,e)};return e.execProtocolRaw=a,e.execProtocolRawStream=i,ae.set(e,o),await Ar(o,e),o.bridge}async function Ir(e){let t=ae.get(e);t&&await t.bridge.close()}function st(e){for(let t of e){if(t.name!=="commandComplete"||typeof t.text!="string")continue;let r=t.text.split(/\s+/,1)[0]?.toUpperCase();if(r&&zs.has(r))return!0}return!1}function Dr(e){if(e.length===0)return!1;let t=[];return new rt.protocol.Parser().parse(e,n=>{t.push(n)}),st(t)}async function Ar(e,t){e.ensureInfrastructurePromise??=ot(e,t,async()=>{await t.exec(`CREATE SCHEMA IF NOT EXISTS "${L}"`),await t.exec(`
21
21
  CREATE TABLE IF NOT EXISTS "${L}"."${tt}" (
22
22
  id BIGSERIAL PRIMARY KEY,
23
23
  txid BIGINT NOT NULL DEFAULT txid_current(),
@@ -29,7 +29,7 @@ Received data: ${l}`));n({childProcess:a,url:`http://${p}:${y}`})},c=l=>{this.#t
29
29
  created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()
30
30
  )
31
31
  `),await t.exec(`
32
- CREATE OR REPLACE FUNCTION "${L}"."${vr}"()
32
+ CREATE OR REPLACE FUNCTION "${L}"."${Rr}"()
33
33
  RETURNS trigger
34
34
  LANGUAGE plpgsql
35
35
  AS $$
@@ -59,7 +59,7 @@ Received data: ${l}`));n({childProcess:a,url:`http://${p}:${y}`})},c=l=>{this.#t
59
59
  END;
60
60
  $$;
61
61
  `),await t.exec(`
62
- CREATE OR REPLACE FUNCTION "${L}"."${Tr}"()
62
+ CREATE OR REPLACE FUNCTION "${L}"."${xr}"()
63
63
  RETURNS void
64
64
  LANGUAGE plpgsql
65
65
  AS $$
@@ -79,20 +79,20 @@ Received data: ${l}`));n({childProcess:a,url:`http://${p}:${y}`})},c=l=>{this.#t
79
79
  SELECT 1
80
80
  FROM pg_trigger
81
81
  WHERE tgrelid = target
82
- AND tgname = '${Rr}'
82
+ AND tgname = '${Tr}'
83
83
  ) THEN
84
84
  CONTINUE;
85
85
  END IF;
86
86
 
87
87
  EXECUTE format(
88
- 'CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION "${L}"."${vr}"()',
89
- '${Rr}',
88
+ 'CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION "${L}"."${Rr}"()',
89
+ '${Tr}',
90
90
  target::text
91
91
  );
92
92
  END LOOP;
93
93
  END;
94
94
  $$;
95
- `),await Ar(e,t)}),await e.ensureInfrastructurePromise}async function Ar(e,t){await ot(e,t,async()=>{await t.query(`SELECT "${L}"."${Tr}"()`)})}async function Vs(e,t){await Dr(e,t),await Ar(e,t);let r=await ot(e,t,async()=>await t.query(`
95
+ `),await _r(e,t)}),await e.ensureInfrastructurePromise}async function _r(e,t){await ot(e,t,async()=>{await t.query(`SELECT "${L}"."${xr}"()`)})}async function Js(e,t){await Ar(e,t),await _r(e,t);let r=await ot(e,t,async()=>await t.query(`
96
96
  WITH drained AS (
97
97
  DELETE FROM "${L}"."${tt}"
98
98
  RETURNING txid, schema_name, table_name, op, row_data, old_row_data, id
@@ -100,7 +100,7 @@ Received data: ${l}`));n({childProcess:a,url:`http://${p}:${y}`})},c=l=>{this.#t
100
100
  SELECT txid, schema_name, table_name, op, row_data, old_row_data
101
101
  FROM drained
102
102
  ORDER BY id
103
- `));if(r.rows.length===0||e.subscribers.size===0)return;let n=r.rows.map(Ks);for(let s of e.subscribers)queueMicrotask(()=>{if(!e.closed&&e.subscribers.has(s))try{s(n)}catch(o){console.error("[WAL bridge] subscriber failed",o)}})}async function et(e,t){if(!e.closed){if(e.pollPromise){e.pendingPoll=!0,await e.pollPromise;return}e.pollPromise=(async()=>{do e.pendingPoll=!1,await Vs(e,t);while(e.pendingPoll&&!e.closed)})().finally(()=>{e.pollPromise=null}),await e.pollPromise}}async function ot(e,t,r){e.suppressDepth+=1;try{return await r()}finally{e.suppressDepth-=1,e.suppressDepth===0&&!e.closed&&ae.get(t)!==e&&(e.closed=!0)}}function Ks(e){return{oldRecord:e.old_row_data,record:e.row_data,schema:e.schema_name,table:e.table_name,txid:String(e.txid),type:zs(e.op)}}function zs(e){switch(e.toLowerCase()){case"delete":return"delete";case"insert":return"insert";case"update":return"update";default:throw new Error(`Unsupported WAL bridge operation: ${e}`)}}var Js=10,Mr="127.0.0.1",Br=128*1024*1024,Lr=["-c","shared_buffers=16MB","-c","temp_buffers=1MB","-c","work_mem=1MB","-c","maintenance_work_mem=16MB","-c","wal_buffers=1MB"],S={connectionLimit:Js,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},Ys=`postgres://${S.username}:${S.password}@localhost`,at=new URLSearchParams({sslmode:S.sslMode}),$r=new URLSearchParams({...Object.fromEntries(at.entries()),connection_limit:String(S.connectionLimit),connect_timeout:String(S.connectTimeout),max_idle_connection_lifetime:String(S.maxIdleConnectionLifetime),pool_timeout:String(S.poolTimeout),socket_timeout:String(S.socketTimeout)});async function kr(e){let{rows:t}=await e.query("SELECT EXISTS(SELECT 1 FROM pg_roles WHERE rolname = 'postgres') AS exists");t[0]?.exists?await e.exec(`ALTER ROLE ${S.username} WITH LOGIN SUPERUSER PASSWORD '${S.password}'`):await e.exec(`CREATE ROLE ${S.username} WITH LOGIN SUPERUSER PASSWORD '${S.password}'`),await e.exec(`SET ROLE ${S.username}`)}async function it(e,t){if(e==="shadow_database"&&!t.dryRun)return await Xs(t);let r=e==="database"?t.databasePort:t.shadowDatabasePort;return t.dryRun?Ur(e,t,{db:null,port:r,server:null}):await Cr(e,t,{port:r,updateServerStatePort:!0})}async function Xs(e,t=async()=>await Cr("shadow_database",e,{port:0,updateServerStatePort:!1})){let{debug:r}=e,n=null,s=null,o=!1,a=new Set,i=(0,Ae.createServer)(u),c=await Zs(i,e.shadowDatabasePort);return e.shadowDatabasePort=c,r&&console.debug(`[shadow_database] lazy proxy listening on port ${c}`),{...S,attachWalEventBridge:()=>Promise.reject(new Error("WAL bridge is only available for the primary database server")),attachQueryInsightsBridge:()=>Promise.reject(new Error("Query insights are only available for the primary database server")),close:async()=>{o=!0;for(let p of a)p.destroy();a.clear();let d=[];try{await eo(i),r&&console.debug(`[shadow_database] lazy proxy stopped on port ${c}`)}catch(p){console.error("[shadow_database] lazy proxy stop error",p),d.push(p)}try{await s?.catch(()=>null),await n?.close()}catch(p){console.error("[shadow_database] backend close error",p),d.push(p)}if(d.length>0)throw new AggregateError(d,"Failed to close shadow_database properly")},connectionString:De(c,at),dump:async()=>{},getPrimaryKeyColumns:()=>Promise.reject(new Error("Primary key resolution is only available for the primary database server")),port:c,prismaORMConnectionString:De(c,$r),terminalCommand:`PGPASSWORD=${S.password} PGSSLMODE=${S.sslMode} psql -h localhost -p ${c} -U ${S.username} -d ${S.database}`};function u(d){a.add(d);let p=()=>{a.delete(d)};d.once("close",p),d.once("error",p),d.pause(),l(d)}async function l(d){try{let p=await f();if(o){d.destroy();return}let y=(0,Ae.createConnection)({host:Mr,port:p.port});a.add(y);let E=()=>{a.delete(y)};y.once("close",E),y.once("error",E),d.once("close",()=>y.destroy()),d.once("error",()=>y.destroy()),y.once("error",()=>d.destroy()),y.once("connect",()=>{r&&console.debug(`[shadow_database] proxying connection to lazy backend on port ${p.port}`),d.resume(),d.pipe(y),y.pipe(d)})}catch(p){r&&console.error("[shadow_database] failed to start lazy backend",p),d.destroy(p instanceof Error?p:void 0)}}async function f(){if(n)return n;if(o)throw new Error("shadow_database is closed");return s||(r&&console.debug("[shadow_database] starting lazy backend..."),s=t().then(d=>(n=d,r&&console.debug(`[shadow_database] lazy backend started on port ${d.port}`),d)).catch(d=>{throw s=null,d})),await s}}async function Cr(e,t,r){let{debug:n}=t,{port:s,updateServerStatePort:o}=r,i=await(e==="shadow_database"?to:Qr)(t.pgliteDataDirPath,n);n&&i.onNotification((d,p)=>{console.debug(`[${e}][${d}] ${p}`)});let{PGLiteSocketServer:c}=await import("@electric-sql/pglite-socket"),u=e==="shadow_database"?t.shadowDatabaseIdleTimeoutMillis:t.databaseIdleTimeoutMillis,l=new c({db:i,debug:n,idleTimeout:Number.isFinite(u)?u:0,inspect:n,maxConnections:S.connectionLimit,port:s});n&&(l.addEventListener("listening",d=>{let{detail:p}=d;console.debug(`[${e}] server listening on ${JSON.stringify(p)}`)}),l.addEventListener("connection",d=>{let{clientAddress:p,clientPort:y}=d.detail;console.debug(`[${e}] client connected from ${p}:${y}`)}),l.addEventListener("error",d=>{let{detail:p}=d;console.error(`[${e}] server error:`,p)}));try{await l.start()}catch(d){throw d instanceof Error&&"code"in d&&d.code==="EADDRINUSE"?new N(s):d}let f=Number(l.getServerConn().split(":").at(1));return o&&(t[e==="database"?"databasePort":"shadowDatabasePort"]=f),Ur(e,t,{db:i,port:f,server:l})}function Ur(e,t,r){let{debug:n}=t,{db:s,port:o,server:a}=r||{},i=new Map;return n&&console.debug(`[${e}] server started on port ${o}`),{...S,attachWalEventBridge:async()=>{if(e!=="database"||!s)throw new Error("WAL bridge is only available for the primary database server");return await nt(s)},attachQueryInsightsBridge:()=>{if(e!=="database"||!a)throw new Error("Query insights are only available for the primary database server");return Promise.resolve(mr(a))},close:async()=>{let c=[];try{await a?.stop(),n&&console.debug(`[${e}] server stopped on port ${o}`)}catch(u){console.error(`[${e}] server stop error`,u),c.push(u)}if(e==="database"){try{a&&await pr(a),n&&console.debug(`[${e}] closed query insights bridge`)}catch(u){console.error(`[${e}] query insights bridge close error`,u),c.push(u)}try{s&&await xr(s),n&&console.debug(`[${e}] closed WAL bridge`)}catch(u){console.error(`[${e}] WAL bridge close error`,u),c.push(u)}try{await s?.syncToFs(),n&&console.debug(`[${e}] synced to filesystem`)}catch(u){console.error(`[${e}] sync error`,u),c.push(u)}}try{await s?.close(),n&&console.debug(`[${e}] closed`)}catch(u){console.error(`[${e}] close error`,u),c.push(u)}if(c.length>0)throw new AggregateError(c,`Failed to close ${e} properly`)},connectionString:De(o,at),dump:async c=>{e==="shadow_database"||!s||await no({db:s,debug:n,destinationPath:c})},getPrimaryKeyColumns:async(c,u)=>{if(e==="shadow_database"||!s)throw new Error("Primary key resolution is only available for the primary database server");let l=`${c}.${u}`,f=i.get(l);return f||(f=ro(s,c,u).catch(d=>{throw i.delete(l),d}),i.set(l,f)),await f},port:o,prismaORMConnectionString:De(o,$r),terminalCommand:`PGPASSWORD=${S.password} PGSSLMODE=${S.sslMode} psql -h localhost -p ${o} -U ${S.username} -d ${S.database}`}}function De(e,t){return`${Ys}:${e}/${S.database}?${t.toString()}`}async function Qr(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await Ze(),s=e==="memory://"||!await z((0,Or.join)(e,"PG_VERSION")),o=await r.create({database:S.database,dataDir:e,debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:Br,loadDataDir:s?n.loadDataDir:void 0,relaxedDurability:!1,startParams:[...r.defaultStartParams,...Lr],wasmModule:n.wasmModule});return await kr(o),o}async function Zs(e,t){return await new Promise((r,n)=>{let s=i=>{if(a(),i.code==="EADDRINUSE"){n(new N(t));return}n(i)},o=()=>{let i=e.address();if(a(),!i||typeof i=="string"){n(new Error("Failed to determine TCP server port"));return}r(i.port)},a=()=>{e.off("error",s),e.off("listening",o)};e.once("error",s),e.once("listening",o),e.listen(t,Mr)})}async function eo(e){await new Promise((t,r)=>{e.close(n=>{let s=n;if(s&&s.code!=="ERR_SERVER_NOT_RUNNING"){r(s);return}t()})})}async function to(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await Ze(),s=await r.create({database:S.database,dataDir:"memory://",debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:Br,loadDataDir:n.loadDataDir,relaxedDurability:!1,startParams:[...r.defaultStartParams,...Lr],wasmModule:n.wasmModule});return await kr(s),s}async function ro(e,t,r){let{rows:n}=await e.query(`
103
+ `));if(r.rows.length===0||e.subscribers.size===0)return;let n=r.rows.map(Ys);for(let s of e.subscribers)queueMicrotask(()=>{if(!e.closed&&e.subscribers.has(s))try{s(n)}catch(o){console.error("[WAL bridge] subscriber failed",o)}})}async function et(e,t){if(!e.closed){if(e.pollPromise){e.pendingPoll=!0,await e.pollPromise;return}e.pollPromise=(async()=>{do e.pendingPoll=!1,await Js(e,t);while(e.pendingPoll&&!e.closed)})().finally(()=>{e.pollPromise=null}),await e.pollPromise}}async function ot(e,t,r){e.suppressDepth+=1;try{return await r()}finally{e.suppressDepth-=1,e.suppressDepth===0&&!e.closed&&ae.get(t)!==e&&(e.closed=!0)}}function Ys(e){return{oldRecord:e.old_row_data,record:e.row_data,schema:e.schema_name,table:e.table_name,txid:String(e.txid),type:Xs(e.op)}}function Xs(e){switch(e.toLowerCase()){case"delete":return"delete";case"insert":return"insert";case"update":return"update";default:throw new Error(`Unsupported WAL bridge operation: ${e}`)}}var Zs=10,Br="127.0.0.1",Lr=128*1024*1024,$r=["-c","shared_buffers=16MB","-c","temp_buffers=1MB","-c","work_mem=1MB","-c","maintenance_work_mem=16MB","-c","wal_buffers=1MB"],S={connectionLimit:Zs,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},eo=`postgres://${S.username}:${S.password}@localhost`,at=new URLSearchParams({sslmode:S.sslMode}),kr=new URLSearchParams({...Object.fromEntries(at.entries()),connection_limit:String(S.connectionLimit),connect_timeout:String(S.connectTimeout),max_idle_connection_lifetime:String(S.maxIdleConnectionLifetime),pool_timeout:String(S.poolTimeout),socket_timeout:String(S.socketTimeout)});async function Cr(e){let{rows:t}=await e.query("SELECT EXISTS(SELECT 1 FROM pg_roles WHERE rolname = 'postgres') AS exists");t[0]?.exists?await e.exec(`ALTER ROLE ${S.username} WITH LOGIN SUPERUSER PASSWORD '${S.password}'`):await e.exec(`CREATE ROLE ${S.username} WITH LOGIN SUPERUSER PASSWORD '${S.password}'`),await e.exec(`SET ROLE ${S.username}`)}async function it(e,t){if(e==="shadow_database"&&!t.dryRun)return await to(t);let r=e==="database"?t.databasePort:t.shadowDatabasePort;return t.dryRun?Qr(e,t,{db:null,port:r,server:null}):await Ur(e,t,{port:r,updateServerStatePort:!0})}async function to(e,t=async()=>await Ur("shadow_database",e,{port:0,updateServerStatePort:!1})){let{debug:r}=e,n=null,s=null,o=!1,a=new Set,i=(0,Ae.createServer)(u),c=await ro(i,e.shadowDatabasePort);return e.shadowDatabasePort=c,r&&console.debug(`[shadow_database] lazy proxy listening on port ${c}`),{...S,attachWalEventBridge:()=>Promise.reject(new Error("WAL bridge is only available for the primary database server")),attachQueryInsightsBridge:()=>Promise.reject(new Error("Query insights are only available for the primary database server")),close:async()=>{o=!0;for(let p of a)p.destroy();a.clear();let d=[];try{await no(i),r&&console.debug(`[shadow_database] lazy proxy stopped on port ${c}`)}catch(p){console.error("[shadow_database] lazy proxy stop error",p),d.push(p)}try{await s?.catch(()=>null),await n?.close()}catch(p){console.error("[shadow_database] backend close error",p),d.push(p)}if(d.length>0)throw new AggregateError(d,"Failed to close shadow_database properly")},connectionString:De(c,at),dump:async()=>{},getPrimaryKeyColumns:()=>Promise.reject(new Error("Primary key resolution is only available for the primary database server")),port:c,prismaORMConnectionString:De(c,kr),terminalCommand:`PGPASSWORD=${S.password} PGSSLMODE=${S.sslMode} psql -h localhost -p ${c} -U ${S.username} -d ${S.database}`};function u(d){a.add(d);let p=()=>{a.delete(d)};d.once("close",p),d.once("error",p),d.pause(),l(d)}async function l(d){try{let p=await f();if(o){d.destroy();return}let y=(0,Ae.createConnection)({host:Br,port:p.port});a.add(y);let E=()=>{a.delete(y)};y.once("close",E),y.once("error",E),d.once("close",()=>y.destroy()),d.once("error",()=>y.destroy()),y.once("error",()=>d.destroy()),y.once("connect",()=>{r&&console.debug(`[shadow_database] proxying connection to lazy backend on port ${p.port}`),d.resume(),d.pipe(y),y.pipe(d)})}catch(p){r&&console.error("[shadow_database] failed to start lazy backend",p),d.destroy(p instanceof Error?p:void 0)}}async function f(){if(n)return n;if(o)throw new Error("shadow_database is closed");return s||(r&&console.debug("[shadow_database] starting lazy backend..."),s=t().then(d=>(n=d,r&&console.debug(`[shadow_database] lazy backend started on port ${d.port}`),d)).catch(d=>{throw s=null,d})),await s}}async function Ur(e,t,r){let{debug:n}=t,{port:s,updateServerStatePort:o}=r,i=await(e==="shadow_database"?so:qr)(t.pgliteDataDirPath,n);n&&i.onNotification((d,p)=>{console.debug(`[${e}][${d}] ${p}`)});let{PGLiteSocketServer:c}=await import("@electric-sql/pglite-socket"),u=e==="shadow_database"?t.shadowDatabaseIdleTimeoutMillis:t.databaseIdleTimeoutMillis,l=new c({db:i,debug:n,idleTimeout:Number.isFinite(u)?u:0,inspect:n,maxConnections:S.connectionLimit,port:s});n&&(l.addEventListener("listening",d=>{let{detail:p}=d;console.debug(`[${e}] server listening on ${JSON.stringify(p)}`)}),l.addEventListener("connection",d=>{let{clientAddress:p,clientPort:y}=d.detail;console.debug(`[${e}] client connected from ${p}:${y}`)}),l.addEventListener("error",d=>{let{detail:p}=d;console.error(`[${e}] server error:`,p)}));try{await l.start()}catch(d){throw d instanceof Error&&"code"in d&&d.code==="EADDRINUSE"?new N(s):d}let f=Number(l.getServerConn().split(":").at(1));return o&&(t[e==="database"?"databasePort":"shadowDatabasePort"]=f),Qr(e,t,{db:i,port:f,server:l})}function Qr(e,t,r){let{debug:n}=t,{db:s,port:o,server:a}=r||{},i=new Map;return n&&console.debug(`[${e}] server started on port ${o}`),{...S,attachWalEventBridge:async()=>{if(e!=="database"||!s)throw new Error("WAL bridge is only available for the primary database server");return await nt(s)},attachQueryInsightsBridge:()=>{if(e!=="database"||!a)throw new Error("Query insights are only available for the primary database server");return Promise.resolve(pr(a))},close:async()=>{let c=[];try{await a?.stop(),n&&console.debug(`[${e}] server stopped on port ${o}`)}catch(u){console.error(`[${e}] server stop error`,u),c.push(u)}if(e==="database"){try{a&&await gr(a),n&&console.debug(`[${e}] closed query insights bridge`)}catch(u){console.error(`[${e}] query insights bridge close error`,u),c.push(u)}try{s&&await Ir(s),n&&console.debug(`[${e}] closed WAL bridge`)}catch(u){console.error(`[${e}] WAL bridge close error`,u),c.push(u)}try{await s?.syncToFs(),n&&console.debug(`[${e}] synced to filesystem`)}catch(u){console.error(`[${e}] sync error`,u),c.push(u)}}try{await s?.close(),n&&console.debug(`[${e}] closed`)}catch(u){console.error(`[${e}] close error`,u),c.push(u)}if(c.length>0)throw new AggregateError(c,`Failed to close ${e} properly`)},connectionString:De(o,at),dump:async c=>{e==="shadow_database"||!s||await ao({db:s,debug:n,destinationPath:c})},getPrimaryKeyColumns:async(c,u)=>{if(e==="shadow_database"||!s)throw new Error("Primary key resolution is only available for the primary database server");let l=`${c}.${u}`,f=i.get(l);return f||(f=oo(s,c,u).catch(d=>{throw i.delete(l),d}),i.set(l,f)),await f},port:o,prismaORMConnectionString:De(o,kr),terminalCommand:`PGPASSWORD=${S.password} PGSSLMODE=${S.sslMode} psql -h localhost -p ${o} -U ${S.username} -d ${S.database}`}}function De(e,t){return`${eo}:${e}/${S.database}?${t.toString()}`}async function qr(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await Ze(),s=e==="memory://"||!await z((0,Nr.join)(e,"PG_VERSION")),o=await r.create({database:S.database,dataDir:e,debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:Lr,loadDataDir:s?n.loadDataDir:void 0,relaxedDurability:!1,startParams:[...r.defaultStartParams,...$r],wasmModule:n.wasmModule});return await Cr(o),o}async function ro(e,t){return await new Promise((r,n)=>{let s=i=>{if(a(),i.code==="EADDRINUSE"){n(new N(t));return}n(i)},o=()=>{let i=e.address();if(a(),!i||typeof i=="string"){n(new Error("Failed to determine TCP server port"));return}r(i.port)},a=()=>{e.off("error",s),e.off("listening",o)};e.once("error",s),e.once("listening",o),e.listen(t,Br)})}async function no(e){await new Promise((t,r)=>{e.close(n=>{let s=n;if(s&&s.code!=="ERR_SERVER_NOT_RUNNING"){r(s);return}t()})})}async function so(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await Ze(),s=await r.create({database:S.database,dataDir:"memory://",debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:Lr,loadDataDir:n.loadDataDir,relaxedDurability:!1,startParams:[...r.defaultStartParams,...$r],wasmModule:n.wasmModule});return await Cr(s),s}async function oo(e,t,r){let{rows:n}=await e.query(`
104
104
  SELECT attribute.attname AS column_name
105
105
  FROM pg_constraint pk_constraint
106
106
  INNER JOIN pg_class relation
@@ -113,9 +113,9 @@ Received data: ${l}`));n({childProcess:a,url:`http://${p}:${y}`})},c=l=>{this.#t
113
113
  ON attribute.attrelid = relation.oid
114
114
  AND attribute.attnum = keys.attnum
115
115
  WHERE pk_constraint.contype = 'p'
116
- AND namespace.nspname = ${_r(t)}
117
- AND relation.relname = ${_r(r)}
116
+ AND namespace.nspname = ${Or(t)}
117
+ AND relation.relname = ${Or(r)}
118
118
  ORDER BY keys.ordinality
119
- `);return n.map(s=>s.column_name)}function _r(e){return`'${e.replaceAll("'","''")}'`}async function no(e){let{dataDir:t,db:r,debug:n,destinationPath:s}=e,o=r||await Qr(t,n),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),i=await a({args:["--schema-only","--no-owner"],fileName:s?(0,Nr.filename)(s):void 0,pg:await o.clone()});return s?(n&&console.debug(`[DB] Dumping database to ${s}`),await Jt(i,s)):(n&&console.debug("[DB] Dumping database to memory"),await i.text())}m();var Dn=D(require("find-my-way"),1);C();async function An(e,t){let{port:r}=t;if(t.dryRun)return{async close(){},port:r,url:`http://localhost:${r}`};let n=!!t.debug,[{registerAccelerateRoutes:s},{registerUtilityRoutes:o},{createHTTPServer:a}]=await Promise.all([Promise.resolve().then(()=>(Tn(),Rn)),Promise.resolve().then(()=>(In(),xn)),Promise.resolve().then(()=>(Oe(),rn))]),i={databaseDumpPath:t.databaseDumpPath,db:e,debug:n,name:t.name,port:r,shadowDBPort:t.shadowDatabasePort},c=(0,Dn.default)({defaultRoute(l,f){x(f,"Not Found",404)},ignoreTrailingSlash:!1});s(c,i,n),o(c,i,n);let u=await a({router:c}).listen(r);return t.port=u.port,i.port=u.port,{async close(){let{Engine:l}=await Promise.resolve().then(()=>(bt(),St));await Promise.allSettled([u.close(),l.stopAll()])},port:u.port,url:u.url}}m();var It=require("util");m();var vt=require("pathe");Y();var Rt="prisma-wal",Tt="prisma-queries";function xt(){return(0,vt.join)(Se.data,"durable-streams")}function Be(e){return(0,vt.join)(xt(),e)}function Le(e,t=Rt){return new URL(`/v1/stream/${encodeURIComponent(t)}`,e).toString()}var No="application/json",$e={connection:"close","content-type":No},Dt={apiVersion:"durable.streams/schema-registry/v1",schema:{additionalProperties:!0,properties:{applicationName:{type:["string","null"]},durationMs:{type:"number"},groupKey:{type:["string","null"]},query:{type:"string"},queryId:{type:"string"},reads:{type:"number"},rowsReturned:{type:"number"},tables:{items:{type:"string"},type:"array"},timestamp:{format:"date-time",type:"string"}},required:["durationMs","query","queryId","reads","rowsReturned","tables","timestamp"],type:"object"},search:{aliases:{applicationName:"applicationName",groupKey:"groupKey",queryId:"queryId"},fields:{applicationName:{bindings:[{jsonPointer:"/applicationName",version:1}],exact:!0,exists:!0,kind:"keyword"},eventTime:{bindings:[{jsonPointer:"/timestamp",version:1}],column:!0,exact:!0,exists:!0,kind:"date",sortable:!0},groupKey:{bindings:[{jsonPointer:"/groupKey",version:1}],exact:!0,exists:!0,kind:"keyword"},queryId:{bindings:[{jsonPointer:"/queryId",version:1}],exact:!0,exists:!0,kind:"keyword"}},primaryTimestampField:"eventTime"}};function _n(e){return{...e,snapshot:async t=>await Mo(e.url,t)}}async function On(e){let t={serverUrl:e.serverUrl,sqlitePath:e.sqlitePath,streamName:Tt,url:Le(e.serverUrl,Tt)};await Lo(t);let r=new At({debug:e.debug,streamUrl:t.url}),n=e.bridge.subscribe(s=>{r.enqueue(s)});return{close:async()=>{n(),await r.close()},experimental:t}}async function Mo(e,t){if(!e)return sr();let r=await Bo(e);return ur(r,t)}async function Bo(e){let t=await fetch(`${e}?offset=-1&format=json`,{headers:{connection:"close"}});if(!t.ok)throw new Error(`Failed to read ${e}: HTTP ${t.status}`);return await t.json()}var At=class{#r;#e;#t;constructor(t){this.#r=t.debug,this.#e=Promise.resolve(),this.#t=t.streamUrl}enqueue(t){t.length!==0&&(this.#e=this.#e.then(async()=>{await Co(this.#t,t),this.#r&&console.debug(`[streams] appended ${t.length} query insight record(s) to ${this.#t}`)}).catch(r=>{console.error("[streams] failed to ingest query insights into prisma-queries",r)}))}async close(){await this.#e}};async function Lo(e){let t=await fetch(e.url,{headers:$e,method:"PUT"});if(!t.ok)throw await ke(t,`Failed to create ${e.streamName}`);let r=await ko(e);if($o(r,e.streamName))return;if(r.currentVersion>0)throw new Error(`Failed to install schema for ${e.streamName}: existing schema registry is incompatible and requires a lens migration`);let n=await fetch(`${e.url}/_schema`,{body:JSON.stringify(Dt),headers:$e,method:"POST"});if(!n.ok)throw await ke(n,`Failed to install schema for ${e.streamName}`)}function $o(e,t){if(e.currentVersion<=0||e.schema!==t)return!1;let r=e.schemas[String(e.currentVersion)];return(0,It.isDeepStrictEqual)(r,Dt.schema)&&(0,It.isDeepStrictEqual)(e.search,Dt.search)}async function ko(e){let t=await fetch(`${e.url}/_schema`,{headers:$e,method:"GET"});if(!t.ok)throw await ke(t,`Failed to inspect schema for ${e.streamName}`);return await t.json()}async function Co(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:$e,method:"POST"});if(!r.ok)throw await ke(r,"Failed to append to prisma-queries")}async function ke(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}m();var kn=require("fs/promises"),j=require("pathe"),te=require("proper-lockfile"),Bt=require("std-env"),g=require("valibot");Y();m();var Uo=require("timers/promises"),Nn=require("std-env");function Mn(e,t){if(e==null)return!1;try{return Nn.process.kill?.(e,0)??!0}catch(r){return t&&console.error(`Error checking if process with PID ${e} exists:`,r),!1}}se();var le=(0,g.pipe)((0,g.string)(),(0,g.url)()),Bn=(0,g.object)({connectionString:le,prismaORMConnectionString:(0,g.optional)(le),terminalCommand:(0,g.optional)((0,g.string)())}),Ln=(0,g.object)({url:le}),$n=(0,g.object)({serverUrl:le,sqlitePath:(0,g.pipe)((0,g.string)(),(0,g.minLength)(1)),streamName:(0,g.pipe)((0,g.string)(),(0,g.minLength)(1)),url:le}),Qo=(0,g.object)({queryInsights:(0,g.optional)($n),streams:(0,g.optional)($n)}),_t=(0,g.pipe)((0,g.number)(),(0,g.integer)(),(0,g.minValue)(1)),qo=(0,g.object)({database:Bn,http:Ln,ppg:Ln,shadowDatabase:Bn}),Ho=(0,g.object)({databasePort:_t,experimental:(0,g.optional)(Qo),exports:(0,g.optional)(qo),name:(0,g.pipe)((0,g.string)(),(0,g.minLength)(1)),pid:(0,g.optional)((0,g.pipe)((0,g.number)(),(0,g.integer)(),(0,g.minValue)(0))),port:_t,shadowDatabasePort:_t,version:(0,g.literal)("1")}),Lt=Symbol("initialize"),Ot="default",Fo=new Set(["durable-streams"]),$=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;_streamsPort;constructor(t){this._databasePort=t.databasePort??_,this.databaseConnectTimeoutMillis=t.databaseConnectTimeoutMillis??6e4,this.databaseIdleTimeoutMillis=t.databaseIdleTimeoutMillis??1/0,this.debug=t.debug??!1,this.dryRun=t.dryRun??!1,this.name=t.name??Ot,this.persistenceMode=t.persistenceMode,this.pid=t.pid??Bt.process.pid,this.shadowDatabaseConnectTimeoutMillis=t.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=t.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=t.port??_,this._shadowDatabasePort=t.shadowDatabasePort??_,this._streamsPort=t.streamsPort??_}static async createExclusively(t){let r=t?.dryRun!==!0&&t?.persistenceMode==="stateful"?new ue(t):new Nt(t);return await r[Lt](),r}static async fromServerDump(t){let{debug:r,name:n=Ot}=t??{},s=ne(n),o=ue.getServerDumpPath(s),a=await Yt(o);if(a==null)return r&&console.debug(`[State] No server dump file found at: ${o}`),null;r&&(console.debug(`[State] server dump file found at "${o}":`),console.debug(a));let{issues:i,output:c,success:u}=(0,g.safeParse)((0,g.pipe)((0,g.string)(),(0,g.parseJson)(),Ho),a);if(!u)throw r&&console.debug(`[State] Invalid server dump file at "${o}":
120
- ${JSON.stringify(i,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new ue({databasePort:c.databasePort,debug:r,dryRun:!1,name:n,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(t){let{debug:r,globs:n}=t??{},s=(0,j.join)(ne(Ot),"..");r&&console.debug(`[State] scanning for server states in: ${s}`);let o=(await Zt(s,n)).filter(a=>!Fo.has(a));return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(a=>Wo(a,t)))}get databasePort(){return this._databasePort}set databasePort(t){this.#r("databasePort",t)}get port(){return this._port}set port(t){this.#r("port",t)}get shadowDatabasePort(){return this._shadowDatabasePort}get streamsPort(){return this._streamsPort}set shadowDatabasePort(t){this.#r("shadowDatabasePort",t)}#r(t,r){if(r<0||!Number.isInteger(r))throw new Error(`Invalid port number: ${r}`);let n=`_${t}`;if(this[n]!==G&&this[n]!==r)throw new Error(`\`${t}\` is already set to ${this[n]}, cannot change it to ${r}`);this[n]=r}},Nt=class extends ${constructor(t){super({...t,databasePort:t?.databasePort||G,persistenceMode:"stateless",port:t?.port||G,shadowDatabasePort:t?.shadowDatabasePort||G,streamsPort:t?.streamsPort||G})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[Lt](){let t;try{t=await $.scan({debug:this.debug,onlyMetadata:!0})}catch(n){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",n),t=[]}let r=await Ve({debug:this.debug,name:this.dryRun?this.name:"",requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:t});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,this._streamsPort=r.streamsPort}async close(){}async writeServerDump(){}},ue=class e extends ${#r;#e;#t;#s;#o;#a;#n;constructor(t){super({...t,persistenceMode:"stateful"}),this.#a=!1,this.#e=ne(this.name),this.#r=(0,j.join)(this.#e,"db_dump.bak"),this.#t=(0,j.join)(this.#e,".lock"),this.#s=(0,j.join)(this.#e,".pglite"),this.#n=t?.serverDump??null,this.#o=e.getServerDumpPath(this.#e)}static getServerDumpPath(t){return(0,j.join)(t,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#n?.exports}get experimental(){return this.#n?.experimental}get pgliteDataDirPath(){return this.#s}async[Lt](){await Xt(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,te.lock)(this.#e,{lockfilePath:this.#t}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let t=await $.scan({debug:this.debug,onlyMetadata:!0}),r=await Ve({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:t});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,this._streamsPort=r.streamsPort,await this.writeServerDump()}catch(t){throw t instanceof Error&&"code"in t&&t.code==="ELOCKED"?new de(this):t}}async close(){if(!this.#a)try{await(0,te.unlock)(this.#e,{lockfilePath:this.#t}),this.#a=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(t){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,t),t}}async writeServerDump(t,r){this.#n={name:this.name,version:"1",pid:Bt.process.pid,port:this.port,databasePort:this.databasePort,experimental:r,shadowDatabasePort:this.shadowDatabasePort,exports:t},await(0,kn.writeFile)(this.#o,`${JSON.stringify(this.#n,null,2)}
121
- `,{encoding:"utf-8"})}};async function Wo(e,t){let{debug:r,onlyMetadata:n}=t||{},s=typeof e=="string"?e:e.name,o=typeof e!="string"?e:void 0,a={databasePort:o?.databasePort??-1,experimental:o?.experimental,exports:o?.exports,name:s,pid:o?.pid,port:o?.port??-1,shadowDatabasePort:o?.shadowDatabasePort??-1,version:"1"};try{let i=o||await $.fromServerDump({debug:r,name:s});if(!i)return r&&console.debug(`[State] no server state found for name: ${s}`),{...a,status:"no_such_server"};a.databasePort=i.databasePort,a.experimental=i.experimental,a.exports=i.exports,a.pid=i.pid,a.port=i.port,a.shadowDatabasePort=i.shadowDatabasePort;let{exports:c,pid:u}=i;if(n)return{...a,status:"unknown"};if(!Mn(u,r))return r&&console.debug(`[State] server state for "${s}" has no running process with PID: ${u}`),{...a,status:"not_running"};let l=ne(s);try{if(!await(0,te.check)(l,{lockfilePath:(0,j.join)(l,".lock")}))return r&&console.debug(`[State] server state for "${s}" is not locked, indicating it is not running.`),{...a,status:"not_running"}}catch(y){r&&console.error(`[State] server state for "${s}" failed to check lock:`,y)}if(!c)return{...a,status:"starting_up"};let{http:f}=c,d=await fetch(`${f.url}/health`,{headers:{connection:"close"}});if(!d.ok)return r&&console.debug(`[State] server state for "${s}" is not live: ${JSON.stringify(d)}`),{...a,status:"not_running"};let p=await d.json();return p.name!==e?(r&&console.debug(`[State] server state for "${s}" has mismatched health response: ${JSON.stringify(p)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${e}" is live: ${JSON.stringify(p)}`),{...a,status:"running"})}catch(i){return r&&console.error(`[State] failed to get server status for "${s}":`,i),{...a,status:"error"}}}var Mt=class extends Error{name="ServerStateAlreadyExistsError";constructor(t){super(`A Prisma Dev server with the name "${t}" is already running.`)}},de=class extends Mt{#r;name="ServerAlreadyRunningError";constructor(t){super(t.name),this.#r=t}get server(){return $.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};m();var Un=require("crypto"),$t=require("timers/promises"),kt=require("util"),Qn=require("std-env");Y();var Go="application/json",me={connection:"close","content-type":Go},jo={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},Ct={apiVersion:"durable.streams/schema-registry/v1",schema:{additionalProperties:!0,properties:{headers:{properties:{operation:{type:"string"},timestamp:{format:"date-time",type:"string"}},required:["timestamp","operation"],type:"object"},key:{type:"string"},type:{type:"string"}},required:["type","key","headers"],type:"object"},search:{aliases:{rowKey:"key",table:"type"},fields:{eventTime:{bindings:[{jsonPointer:"/headers/timestamp",version:1}],column:!0,exact:!0,exists:!0,kind:"date",sortable:!0},key:{bindings:[{jsonPointer:"/key",version:1}],exact:!0,exists:!0,kind:"keyword"},operation:{bindings:[{jsonPointer:"/headers/operation",version:1}],exact:!0,exists:!0,kind:"keyword"},type:{bindings:[{jsonPointer:"/type",version:1}],exact:!0,exists:!0,kind:"keyword"}},primaryTimestampField:"eventTime"}};async function qn(e){let{dbServer:t,debug:r,name:n,persistenceMode:s,port:o,queryInsightsBridge:a,walBridge:i}=e,c=s==="stateless",u=c?sa(n):n,l=Be(u),f=!c&&await z(l);Qn.process.env.DS_LOCAL_DATA_ROOT=xt(),c&&await J(l);let d=await Ko({debug:r,hadExistingStreamsData:f,name:u,port:o}),p={serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path,streamName:Rt,url:Le(d.exports.http.url)};try{await Yo(p);let y=await On({bridge:a,debug:r,serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path}),E=new Ut({dbServer:t,debug:r,streamUrl:p.url}),re=i.subscribe(Ce=>{E.enqueue(Ce)});return{close:async()=>{re(),await E.close(),await y.close(),await d.close(),await(0,$t.setTimeout)(100),c&&await J(l)},experimental:p,experimentalQueryInsights:y.experimental}}catch(y){throw await d.close().catch(()=>{}),await(0,$t.setTimeout)(100),c&&await J(l).catch(()=>{}),y}}var Vo=["database disk image is malformed","duplicate column name:","file is not a database","malformed database schema","no such column:","no such table:","schema_version row missing after migration","unexpected schema version:"];async function Ko(e){let{debug:t,hadExistingStreamsData:r,name:n,port:s}=e,{startLocalDurableStreamsServer:o}=await import("@prisma/streams-local"),a=()=>o({hostname:"127.0.0.1",name:n,port:s});try{return await a()}catch(i){if(!r||!zo(i))throw i;return console.warn(`[streams] resetting incompatible durable streams data for "${n}"`),t&&console.debug(`[streams] original durable streams startup error for "${n}"`,i),await J(Be(n)),await a()}}function zo(e){return Jo(e).map(r=>r.toLowerCase()).some(r=>Vo.some(n=>r.includes(n)))}function Jo(e){let t=[],r=[e],n=new Set;for(;r.length>0;){let s=r.shift();if(!(s==null||n.has(s))){if(n.add(s),typeof s=="string"){t.push(s);continue}if(s instanceof AggregateError)for(let o of s.errors)r.push(o);if(s instanceof Error){t.push(s.message);let o=s.cause;o!==void 0&&r.push(o)}}}return t}var Ut=class{#r;#e;#t;#s;#o;constructor(t){this.#r=t.dbServer,this.#e=t.debug,this.#t=Promise.resolve(),this.#s=t.streamUrl,this.#o=new Set}enqueue(t){t.length!==0&&(this.#t=this.#t.then(async()=>{let r=await this.#a(t);r.length!==0&&(await ea(this.#s,r),this.#e&&console.debug(`[streams] appended ${r.length} state-protocol record(s) to ${this.#s}`))}).catch(r=>{console.error("[streams] failed to ingest WAL events into prisma-wal",r)}))}async close(){await this.#t}async#a(t){let r=[],n=new Date().toISOString();for(let s of t)r.push(...await this.#n(s,n));return r}async#n(t,r){let n=`${t.schema}.${t.table}`,s=await this.#r.getPrimaryKeyColumns(t.schema,t.table),o=Cn(t.record),a=Cn(t.oldRecord),i=this.#i(n,s,a),c=this.#i(n,s,o),u=t.txid===""?void 0:t.txid;return t.type==="insert"?o&&c?[{headers:{operation:"insert",timestamp:r,txid:u},key:c,old_value:null,type:n,value:o}]:[]:t.type==="delete"?a&&i?[{headers:{operation:"delete",timestamp:r,txid:u},key:i,old_value:a,type:n,value:null}]:[]:!o||!a||!i||!c?[]:i!==c?[{headers:{operation:"delete",timestamp:r,txid:u},key:i,old_value:a,type:n,value:null},{headers:{operation:"insert",timestamp:r,txid:u},key:c,old_value:null,type:n,value:o}]:[{headers:{operation:"update",timestamp:r,txid:u},key:c,old_value:a,type:n,value:o}]}#i(t,r,n){if(!n)return null;let s=ta(n,r);return s||(this.#o.has(t)||(this.#o.add(t),console.warn(`[streams] falling back to full-row keys for ${t} because no primary key could be resolved`)),ra(n))}};async function Yo(e){let t=await fetch(e.url,{headers:me,method:"PUT"});if(!t.ok)throw await pe(t,`Failed to create ${e.streamName}`);let r=await fetch(`${e.url}/_profile`,{body:JSON.stringify(jo),headers:me,method:"POST"});if(!r.ok)throw await pe(r,`Failed to configure ${e.streamName}`);let n=await Xo(e);if(Zo(n,e.streamName))return;if(n.currentVersion>0)throw new Error(`Failed to install schema for ${e.streamName}: existing schema registry is incompatible and requires a lens migration`);let s=await fetch(`${e.url}/_schema`,{body:JSON.stringify(Ct),headers:me,method:"POST"});if(!s.ok)throw await pe(s,`Failed to install schema for ${e.streamName}`)}async function Xo(e){let t=await fetch(`${e.url}/_schema`,{headers:me,method:"GET"});if(!t.ok)throw await pe(t,`Failed to inspect schema for ${e.streamName}`);return await t.json()}function Zo(e,t){if(e.currentVersion<=0||e.schema!==t)return!1;let r=e.schemas[String(e.currentVersion)];return(0,kt.isDeepStrictEqual)(r,Ct.schema)&&(0,kt.isDeepStrictEqual)(e.search,Ct.search)}async function ea(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:me,method:"POST"});if(!r.ok)throw await pe(r,"Failed to append to prisma-wal")}async function pe(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}function ta(e,t){if(t.length===0)return null;let r=[];for(let n of t){if(!Object.prototype.hasOwnProperty.call(e,n))return null;let s=na(e[n]);if(s==null)return null;r.push(t.length===1?s:`${n}=${s}`)}return r.join("|")}function ra(e){return JSON.stringify(Qt(e))}function Qt(e){return Array.isArray(e)?e.map(t=>Qt(t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Qt(r)])):e}function Cn(e){return e?structuredClone(e):null}function na(e){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return e;if(typeof e=="number")return Number.isFinite(e)?String(e):null;if(typeof e=="bigint")return e.toString();if(typeof e=="boolean")return e?"true":"false";try{return JSON.stringify(e)}catch{return null}}function sa(e){return`${e}.${(0,Un.randomUUID)().replaceAll("-","")}`}async function Hn(e){let t=await $.createExclusively(e),r=null,n=null,s=null,o=null;try{[r,s]=await Promise.all([it("database",t),it("shadow_database",t)]);let a,i;t.dryRun?(a=ca(),i=ua(),o=la()):(a=await r.attachWalEventBridge(),i=await r.attachQueryInsightsBridge(),o=await qn({dbServer:r,debug:t.debug,name:t.name,port:t.streamsPort,persistenceMode:t.persistenceMode,queryInsightsBridge:i,walBridge:a})),n=await An(r,t);let c=oa(r,s,n,t);await t.writeServerDump(c,t.dryRun?{}:{queryInsights:o.experimentalQueryInsights,streams:o.experimental});let u=ia(a),l=_n(o.experimentalQueryInsights),f=r,d=s,p=n,y=o,E=async()=>{u.close(),await Fn(t,[p,y,f,d])};return{close:E,dbServer:r,httpServer:n,server:{...c,close:E,experimental:{queryInsights:l,streams:o.experimental,wal:u.api},name:t.name},serverState:t,shadowDbServer:s,streamsServer:o,queryInsightsBridge:i,walBridge:a}}catch(a){return await aa(t,[n,o,r,s],a)}}function oa(e,t,r,n){let s=`prisma+postgres://localhost:${r.port}/?${new URLSearchParams({api_key:Ft({databaseUrl:e.prismaORMConnectionString,name:n.name,shadowDatabaseUrl:t.prismaORMConnectionString})}).toString()}`;return{database:{connectionString:e.connectionString,prismaORMConnectionString:e.prismaORMConnectionString,terminalCommand:e.terminalCommand},http:{url:r.url},ppg:{url:s},shadowDatabase:{connectionString:t.prismaORMConnectionString,prismaORMConnectionString:t.prismaORMConnectionString,terminalCommand:t.terminalCommand}}}async function Fn(e,t){let r=[];for(let n of t)try{await n.close()}catch(s){r.push(s)}try{await e.close()}catch(n){r.push(n)}if(r.length>0)throw new AggregateError(r,"Failed to close some servers")}async function aa(e,t,r){try{await Fn(e,t.filter(n=>n!==null))}catch(n){throw new AggregateError([r,n],"Failed to start Prisma Dev server cleanly")}throw r}function ia(e){let t=new Set;return{api:{stream:()=>{let r=()=>{},n=da(e,()=>{t.delete(r)});return r=()=>n.close(),t.add(r),n.stream},subscribe:r=>e.subscribe(r)},close:()=>{for(let r of[...t])r();t.clear()}}}function ca(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function ua(){return{async close(){},subscribe(){return()=>{}}}}function la(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""},experimentalQueryInsights:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function da(e,t){let r=[],n=!1,s=null,o=e.subscribe(i=>{if(!n){if(s){let c=s;s=null,c.resolve({done:!1,value:i});return}r.push(i)}}),a=()=>{if(!n&&(n=!0,o(),r.length=0,t(),s)){let i=s;s=null,i.resolve({done:!0,value:void 0})}};return{close:a,stream:{[Symbol.asyncIterator](){return this},next(){return r.length>0?Promise.resolve({done:!1,value:r.shift()}):n?Promise.resolve({done:!0,value:void 0}):new Promise((i,c)=>{s={reject:c,resolve:i}})},return(){return a(),Promise.resolve({done:!0,value:void 0})},throw(i){let c=s;return a(),c&&c.reject(i),Promise.reject(i instanceof Error?i:new Error(String(i)))}}}}se();async function Wn(e){let{server:t}=await Hn(e);return t}async function ma(e){return await Wn(e)}0&&(module.exports={DEFAULT_DATABASE_PORT,DEFAULT_SERVER_PORT,DEFAULT_SHADOW_DATABASE_PORT,DEFAULT_STREAMS_PORT,PortNotAvailableError,ServerAlreadyRunningError,copyPrismaDevRuntimeAssets,getPrismaDevRuntimeAssetManifest,startPrismaDevServer,unstable_startServer});
119
+ `);return n.map(s=>s.column_name)}function Or(e){return`'${e.replaceAll("'","''")}'`}async function ao(e){let{dataDir:t,db:r,debug:n,destinationPath:s}=e,o=r||await qr(t,n),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),i=await a({args:["--schema-only","--no-owner"],fileName:s?(0,Mr.filename)(s):void 0,pg:await o.clone()});return s?(n&&console.debug(`[DB] Dumping database to ${s}`),await Yt(i,s)):(n&&console.debug("[DB] Dumping database to memory"),await i.text())}m();var An=D(require("find-my-way"),1);C();async function _n(e,t){let{port:r}=t;if(t.dryRun)return{async close(){},port:r,url:`http://localhost:${r}`};let n=!!t.debug,[{registerAccelerateRoutes:s},{registerUtilityRoutes:o},{createHTTPServer:a}]=await Promise.all([Promise.resolve().then(()=>(xn(),Tn)),Promise.resolve().then(()=>(Dn(),In)),Promise.resolve().then(()=>(Oe(),nn))]),i={databaseDumpPath:t.databaseDumpPath,db:e,debug:n,name:t.name,port:r,shadowDBPort:t.shadowDatabasePort},c=(0,An.default)({defaultRoute(l,f){x(f,"Not Found",404)},ignoreTrailingSlash:!1});s(c,i,n),o(c,i,n);let u=await a({router:c}).listen(r);return t.port=u.port,i.port=u.port,{async close(){let{Engine:l}=await Promise.resolve().then(()=>(bt(),St));await Promise.allSettled([u.close(),l.stopAll()])},port:u.port,url:u.url}}m();var It=require("util");m();var vt=require("pathe");Y();var Rt="prisma-wal",Tt="prisma-queries";function xt(){return(0,vt.join)(Se.data,"durable-streams")}function Be(e){return(0,vt.join)(xt(),e)}function Le(e,t=Rt){return new URL(`/v1/stream/${encodeURIComponent(t)}`,e).toString()}var Lo="application/json",$e={connection:"close","content-type":Lo},Dt={apiVersion:"durable.streams/schema-registry/v1",schema:{additionalProperties:!0,properties:{applicationName:{type:["string","null"]},durationMs:{type:"number"},groupKey:{type:["string","null"]},query:{type:"string"},queryId:{type:"string"},reads:{type:"number"},rowsReturned:{type:"number"},tables:{items:{type:"string"},type:"array"},timestamp:{format:"date-time",type:"string"}},required:["durationMs","query","queryId","reads","rowsReturned","tables","timestamp"],type:"object"},search:{aliases:{applicationName:"applicationName",groupKey:"groupKey",queryId:"queryId"},fields:{applicationName:{bindings:[{jsonPointer:"/applicationName",version:1}],exact:!0,exists:!0,kind:"keyword"},eventTime:{bindings:[{jsonPointer:"/timestamp",version:1}],column:!0,exact:!0,exists:!0,kind:"date",sortable:!0},groupKey:{bindings:[{jsonPointer:"/groupKey",version:1}],exact:!0,exists:!0,kind:"keyword"},queryId:{bindings:[{jsonPointer:"/queryId",version:1}],exact:!0,exists:!0,kind:"keyword"}},primaryTimestampField:"eventTime"}};function On(e){return{...e,snapshot:async t=>await $o(e.url,t)}}async function Nn(e){let t={serverUrl:e.serverUrl,sqlitePath:e.sqlitePath,streamName:Tt,url:Le(e.serverUrl,Tt)};await Co(t);let r=new At({debug:e.debug,streamUrl:t.url}),n=e.bridge.subscribe(s=>{r.enqueue(s)});return{close:async()=>{n(),await r.close()},experimental:t}}async function $o(e,t){if(!e)return or();let r=await ko(e);return lr(r,t)}async function ko(e){let t=await fetch(`${e}?offset=-1&format=json`,{headers:{connection:"close"}});if(!t.ok)throw new Error(`Failed to read ${e}: HTTP ${t.status}`);return await t.json()}var At=class{#r;#e;#t;constructor(t){this.#r=t.debug,this.#e=Promise.resolve(),this.#t=t.streamUrl}enqueue(t){t.length!==0&&(this.#e=this.#e.then(async()=>{await qo(this.#t,t),this.#r&&console.debug(`[streams] appended ${t.length} query insight record(s) to ${this.#t}`)}).catch(r=>{console.error("[streams] failed to ingest query insights into prisma-queries",r)}))}async close(){await this.#e}};async function Co(e){let t=await fetch(e.url,{headers:$e,method:"PUT"});if(!t.ok)throw await ke(t,`Failed to create ${e.streamName}`);let r=await Qo(e);if(Uo(r,e.streamName))return;if(r.currentVersion>0)throw new Error(`Failed to install schema for ${e.streamName}: existing schema registry is incompatible and requires a lens migration`);let n=await fetch(`${e.url}/_schema`,{body:JSON.stringify(Dt),headers:$e,method:"POST"});if(!n.ok)throw await ke(n,`Failed to install schema for ${e.streamName}`)}function Uo(e,t){if(e.currentVersion<=0||e.schema!==t)return!1;let r=e.schemas[String(e.currentVersion)];return(0,It.isDeepStrictEqual)(r,Dt.schema)&&(0,It.isDeepStrictEqual)(e.search,Dt.search)}async function Qo(e){let t=await fetch(`${e.url}/_schema`,{headers:$e,method:"GET"});if(!t.ok)throw await ke(t,`Failed to inspect schema for ${e.streamName}`);return await t.json()}async function qo(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:$e,method:"POST"});if(!r.ok)throw await ke(r,"Failed to append to prisma-queries")}async function ke(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}m();var Cn=require("fs/promises"),j=require("pathe"),te=require("proper-lockfile"),Bt=require("std-env"),g=require("valibot");Y();m();var Ho=require("timers/promises"),Mn=require("std-env");function Bn(e,t){if(e==null)return!1;try{return Mn.process.kill?.(e,0)??!0}catch(r){return t&&console.error(`Error checking if process with PID ${e} exists:`,r),!1}}se();var le=(0,g.pipe)((0,g.string)(),(0,g.url)()),Ln=(0,g.object)({connectionString:le,prismaORMConnectionString:(0,g.optional)(le),terminalCommand:(0,g.optional)((0,g.string)())}),$n=(0,g.object)({url:le}),kn=(0,g.object)({serverUrl:le,sqlitePath:(0,g.pipe)((0,g.string)(),(0,g.minLength)(1)),streamName:(0,g.pipe)((0,g.string)(),(0,g.minLength)(1)),url:le}),Fo=(0,g.object)({queryInsights:(0,g.optional)(kn),streams:(0,g.optional)(kn)}),_t=(0,g.pipe)((0,g.number)(),(0,g.integer)(),(0,g.minValue)(1)),Wo=(0,g.object)({database:Ln,http:$n,ppg:$n,shadowDatabase:Ln}),Go=(0,g.object)({databasePort:_t,experimental:(0,g.optional)(Fo),exports:(0,g.optional)(Wo),name:(0,g.pipe)((0,g.string)(),(0,g.minLength)(1)),pid:(0,g.optional)((0,g.pipe)((0,g.number)(),(0,g.integer)(),(0,g.minValue)(0))),port:_t,shadowDatabasePort:_t,version:(0,g.literal)("1")}),Lt=Symbol("initialize"),Ot="default",jo=new Set(["durable-streams"]),$=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;_streamsPort;constructor(t){this._databasePort=t.databasePort??_,this.databaseConnectTimeoutMillis=t.databaseConnectTimeoutMillis??6e4,this.databaseIdleTimeoutMillis=t.databaseIdleTimeoutMillis??1/0,this.debug=t.debug??!1,this.dryRun=t.dryRun??!1,this.name=t.name??Ot,this.persistenceMode=t.persistenceMode,this.pid=t.pid??Bt.process.pid,this.shadowDatabaseConnectTimeoutMillis=t.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=t.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=t.port??_,this._shadowDatabasePort=t.shadowDatabasePort??_,this._streamsPort=t.streamsPort??_}static async createExclusively(t){let r=t?.dryRun!==!0&&t?.persistenceMode==="stateful"?new ue(t):new Nt(t);return await r[Lt](),r}static async fromServerDump(t){let{debug:r,name:n=Ot}=t??{},s=ne(n),o=ue.getServerDumpPath(s),a=await Xt(o);if(a==null)return r&&console.debug(`[State] No server dump file found at: ${o}`),null;r&&(console.debug(`[State] server dump file found at "${o}":`),console.debug(a));let{issues:i,output:c,success:u}=(0,g.safeParse)((0,g.pipe)((0,g.string)(),(0,g.parseJson)(),Go),a);if(!u)throw r&&console.debug(`[State] Invalid server dump file at "${o}":
120
+ ${JSON.stringify(i,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new ue({databasePort:c.databasePort,debug:r,dryRun:!1,name:n,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(t){let{debug:r,globs:n}=t??{},s=(0,j.join)(ne(Ot),"..");r&&console.debug(`[State] scanning for server states in: ${s}`);let o=(await er(s,n)).filter(a=>!jo.has(a));return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(a=>$t(a,t)))}get databasePort(){return this._databasePort}set databasePort(t){this.#r("databasePort",t)}get port(){return this._port}set port(t){this.#r("port",t)}get shadowDatabasePort(){return this._shadowDatabasePort}get streamsPort(){return this._streamsPort}set shadowDatabasePort(t){this.#r("shadowDatabasePort",t)}#r(t,r){if(r<0||!Number.isInteger(r))throw new Error(`Invalid port number: ${r}`);let n=`_${t}`;if(this[n]!==G&&this[n]!==r)throw new Error(`\`${t}\` is already set to ${this[n]}, cannot change it to ${r}`);this[n]=r}},Nt=class extends ${constructor(t){super({...t,databasePort:t?.databasePort||G,persistenceMode:"stateless",port:t?.port||G,shadowDatabasePort:t?.shadowDatabasePort||G,streamsPort:t?.streamsPort||G})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[Lt](){let t;try{t=await $.scan({debug:this.debug,onlyMetadata:!0})}catch(n){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",n),t=[]}let r=await Ve({debug:this.debug,name:this.dryRun?this.name:"",requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:t});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,this._streamsPort=r.streamsPort}async close(){}async writeServerDump(){}},ue=class e extends ${#r;#e;#t;#s;#o;#a;#n;constructor(t){super({...t,persistenceMode:"stateful"}),this.#a=!1,this.#e=ne(this.name),this.#r=(0,j.join)(this.#e,"db_dump.bak"),this.#t=(0,j.join)(this.#e,".lock"),this.#s=(0,j.join)(this.#e,".pglite"),this.#n=t?.serverDump??null,this.#o=e.getServerDumpPath(this.#e)}static getServerDumpPath(t){return(0,j.join)(t,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#n?.exports}get experimental(){return this.#n?.experimental}get pgliteDataDirPath(){return this.#s}async[Lt](){await Zt(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,te.lock)(this.#e,{lockfilePath:this.#t}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let t=await $.scan({debug:this.debug,onlyMetadata:!0}),r=await Ve({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:t});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,this._streamsPort=r.streamsPort,await this.writeServerDump()}catch(t){throw t instanceof Error&&"code"in t&&t.code==="ELOCKED"?new de(this):t}}async close(){if(!this.#a)try{await(0,te.unlock)(this.#e,{lockfilePath:this.#t}),this.#a=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(t){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,t),t}}async writeServerDump(t,r){this.#n={name:this.name,version:"1",pid:Bt.process.pid,port:this.port,databasePort:this.databasePort,experimental:r,shadowDatabasePort:this.shadowDatabasePort,exports:t},await(0,Cn.writeFile)(this.#o,`${JSON.stringify(this.#n,null,2)}
121
+ `,{encoding:"utf-8"})}};async function $t(e,t){let{debug:r,onlyMetadata:n}=t||{},s=typeof e=="string"?e:e.name,o=typeof e!="string"?e:void 0,a={databasePort:o?.databasePort??-1,experimental:o?.experimental,exports:o?.exports,name:s,pid:o?.pid,port:o?.port??-1,shadowDatabasePort:o?.shadowDatabasePort??-1,version:"1"};try{let i=o||await $.fromServerDump({debug:r,name:s});if(!i)return r&&console.debug(`[State] no server state found for name: ${s}`),{...a,status:"no_such_server"};a.databasePort=i.databasePort,a.experimental=i.experimental,a.exports=i.exports,a.pid=i.pid,a.port=i.port,a.shadowDatabasePort=i.shadowDatabasePort;let{exports:c,pid:u}=i;if(n)return{...a,status:"unknown"};if(!Bn(u,r))return r&&console.debug(`[State] server state for "${s}" has no running process with PID: ${u}`),{...a,status:"not_running"};let l=ne(s);try{if(!await(0,te.check)(l,{lockfilePath:(0,j.join)(l,".lock")}))return r&&console.debug(`[State] server state for "${s}" is not locked, indicating it is not running.`),{...a,status:"not_running"}}catch(y){r&&console.error(`[State] server state for "${s}" failed to check lock:`,y)}if(!c)return{...a,status:"starting_up"};let{http:f}=c,d=await fetch(`${f.url}/health`,{headers:{connection:"close"}});if(!d.ok)return r&&console.debug(`[State] server state for "${s}" is not live: ${JSON.stringify(d)}`),{...a,status:"not_running"};let p=await d.json();return p.name!==e?(r&&console.debug(`[State] server state for "${s}" has mismatched health response: ${JSON.stringify(p)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${e}" is live: ${JSON.stringify(p)}`),{...a,status:"running"})}catch(i){return r&&console.error(`[State] failed to get server status for "${s}":`,i),{...a,status:"error"}}}function Un(e){let{status:t}=e;return t==="running"||t==="starting_up"}var Mt=class extends Error{name="ServerStateAlreadyExistsError";constructor(t){super(`A Prisma Dev server with the name "${t}" is already running.`)}},de=class extends Mt{#r;name="ServerAlreadyRunningError";constructor(t){super(t.name),this.#r=t}get server(){return $.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};m();var qn=require("crypto"),kt=require("timers/promises"),Ct=require("util"),Hn=require("std-env");Y();var Vo="application/json",me={connection:"close","content-type":Vo},Ko={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},Ut={apiVersion:"durable.streams/schema-registry/v1",schema:{additionalProperties:!0,properties:{headers:{properties:{operation:{type:"string"},timestamp:{format:"date-time",type:"string"}},required:["timestamp","operation"],type:"object"},key:{type:"string"},type:{type:"string"}},required:["type","key","headers"],type:"object"},search:{aliases:{rowKey:"key",table:"type"},fields:{eventTime:{bindings:[{jsonPointer:"/headers/timestamp",version:1}],column:!0,exact:!0,exists:!0,kind:"date",sortable:!0},key:{bindings:[{jsonPointer:"/key",version:1}],exact:!0,exists:!0,kind:"keyword"},operation:{bindings:[{jsonPointer:"/headers/operation",version:1}],exact:!0,exists:!0,kind:"keyword"},type:{bindings:[{jsonPointer:"/type",version:1}],exact:!0,exists:!0,kind:"keyword"}},primaryTimestampField:"eventTime"}};async function Fn(e){let{dbServer:t,debug:r,name:n,persistenceMode:s,port:o,queryInsightsBridge:a,walBridge:i}=e,c=s==="stateless",u=c?aa(n):n,l=Be(u),f=!c&&await z(l);Hn.process.env.DS_LOCAL_DATA_ROOT=xt(),c&&await J(l);let d=await Jo({debug:r,hadExistingStreamsData:f,name:u,port:o}),p={serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path,streamName:Rt,url:Le(d.exports.http.url)};try{await Zo(p);let y=await Nn({bridge:a,debug:r,serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path}),E=new Qt({dbServer:t,debug:r,streamUrl:p.url}),re=i.subscribe(Ce=>{E.enqueue(Ce)});return{close:async()=>{re(),await E.close(),await y.close(),await d.close(),await(0,kt.setTimeout)(100),c&&await J(l)},experimental:p,experimentalQueryInsights:y.experimental}}catch(y){throw await d.close().catch(()=>{}),await(0,kt.setTimeout)(100),c&&await J(l).catch(()=>{}),y}}var zo=["database disk image is malformed","duplicate column name:","file is not a database","malformed database schema","no such column:","no such table:","schema_version row missing after migration","unexpected schema version:"];async function Jo(e){let{debug:t,hadExistingStreamsData:r,name:n,port:s}=e,{startLocalDurableStreamsServer:o}=await import("@prisma/streams-local"),a=()=>o({hostname:"127.0.0.1",name:n,port:s});try{return await a()}catch(i){if(!r||!Yo(i))throw i;return console.warn(`[streams] resetting incompatible durable streams data for "${n}"`),t&&console.debug(`[streams] original durable streams startup error for "${n}"`,i),await J(Be(n)),await a()}}function Yo(e){return Xo(e).map(r=>r.toLowerCase()).some(r=>zo.some(n=>r.includes(n)))}function Xo(e){let t=[],r=[e],n=new Set;for(;r.length>0;){let s=r.shift();if(!(s==null||n.has(s))){if(n.add(s),typeof s=="string"){t.push(s);continue}if(s instanceof AggregateError)for(let o of s.errors)r.push(o);if(s instanceof Error){t.push(s.message);let o=s.cause;o!==void 0&&r.push(o)}}}return t}var Qt=class{#r;#e;#t;#s;#o;constructor(t){this.#r=t.dbServer,this.#e=t.debug,this.#t=Promise.resolve(),this.#s=t.streamUrl,this.#o=new Set}enqueue(t){t.length!==0&&(this.#t=this.#t.then(async()=>{let r=await this.#a(t);r.length!==0&&(await ra(this.#s,r),this.#e&&console.debug(`[streams] appended ${r.length} state-protocol record(s) to ${this.#s}`))}).catch(r=>{console.error("[streams] failed to ingest WAL events into prisma-wal",r)}))}async close(){await this.#t}async#a(t){let r=[],n=new Date().toISOString();for(let s of t)r.push(...await this.#n(s,n));return r}async#n(t,r){let n=`${t.schema}.${t.table}`,s=await this.#r.getPrimaryKeyColumns(t.schema,t.table),o=Qn(t.record),a=Qn(t.oldRecord),i=this.#i(n,s,a),c=this.#i(n,s,o),u=t.txid===""?void 0:t.txid;return t.type==="insert"?o&&c?[{headers:{operation:"insert",timestamp:r,txid:u},key:c,old_value:null,type:n,value:o}]:[]:t.type==="delete"?a&&i?[{headers:{operation:"delete",timestamp:r,txid:u},key:i,old_value:a,type:n,value:null}]:[]:!o||!a||!i||!c?[]:i!==c?[{headers:{operation:"delete",timestamp:r,txid:u},key:i,old_value:a,type:n,value:null},{headers:{operation:"insert",timestamp:r,txid:u},key:c,old_value:null,type:n,value:o}]:[{headers:{operation:"update",timestamp:r,txid:u},key:c,old_value:a,type:n,value:o}]}#i(t,r,n){if(!n)return null;let s=na(n,r);return s||(this.#o.has(t)||(this.#o.add(t),console.warn(`[streams] falling back to full-row keys for ${t} because no primary key could be resolved`)),sa(n))}};async function Zo(e){let t=await fetch(e.url,{headers:me,method:"PUT"});if(!t.ok)throw await pe(t,`Failed to create ${e.streamName}`);let r=await fetch(`${e.url}/_profile`,{body:JSON.stringify(Ko),headers:me,method:"POST"});if(!r.ok)throw await pe(r,`Failed to configure ${e.streamName}`);let n=await ea(e);if(ta(n,e.streamName))return;if(n.currentVersion>0)throw new Error(`Failed to install schema for ${e.streamName}: existing schema registry is incompatible and requires a lens migration`);let s=await fetch(`${e.url}/_schema`,{body:JSON.stringify(Ut),headers:me,method:"POST"});if(!s.ok)throw await pe(s,`Failed to install schema for ${e.streamName}`)}async function ea(e){let t=await fetch(`${e.url}/_schema`,{headers:me,method:"GET"});if(!t.ok)throw await pe(t,`Failed to inspect schema for ${e.streamName}`);return await t.json()}function ta(e,t){if(e.currentVersion<=0||e.schema!==t)return!1;let r=e.schemas[String(e.currentVersion)];return(0,Ct.isDeepStrictEqual)(r,Ut.schema)&&(0,Ct.isDeepStrictEqual)(e.search,Ut.search)}async function ra(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:me,method:"POST"});if(!r.ok)throw await pe(r,"Failed to append to prisma-wal")}async function pe(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}function na(e,t){if(t.length===0)return null;let r=[];for(let n of t){if(!Object.prototype.hasOwnProperty.call(e,n))return null;let s=oa(e[n]);if(s==null)return null;r.push(t.length===1?s:`${n}=${s}`)}return r.join("|")}function sa(e){return JSON.stringify(qt(e))}function qt(e){return Array.isArray(e)?e.map(t=>qt(t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,qt(r)])):e}function Qn(e){return e?structuredClone(e):null}function oa(e){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return e;if(typeof e=="number")return Number.isFinite(e)?String(e):null;if(typeof e=="bigint")return e.toString();if(typeof e=="boolean")return e?"true":"false";try{return JSON.stringify(e)}catch{return null}}function aa(e){return`${e}.${(0,qn.randomUUID)().replaceAll("-","")}`}async function Wn(e){let t=await $.createExclusively(e),r=null,n=null,s=null,o=null;try{[r,s]=await Promise.all([it("database",t),it("shadow_database",t)]);let a,i;t.dryRun?(a=la(),i=da(),o=ma()):(a=await r.attachWalEventBridge(),i=await r.attachQueryInsightsBridge(),o=await Fn({dbServer:r,debug:t.debug,name:t.name,port:t.streamsPort,persistenceMode:t.persistenceMode,queryInsightsBridge:i,walBridge:a})),n=await _n(r,t);let c=ia(r,s,n,t);await t.writeServerDump(c,t.dryRun?{}:{queryInsights:o.experimentalQueryInsights,streams:o.experimental});let u=ua(a),l=On(o.experimentalQueryInsights),f=r,d=s,p=n,y=o,E=async()=>{u.close(),await Gn(t,[p,y,f,d])};return{close:E,dbServer:r,httpServer:n,server:{...c,close:E,experimental:{queryInsights:l,streams:o.experimental,wal:u.api},name:t.name},serverState:t,shadowDbServer:s,streamsServer:o,queryInsightsBridge:i,walBridge:a}}catch(a){return await ca(t,[n,o,r,s],a)}}function ia(e,t,r,n){let s=`prisma+postgres://localhost:${r.port}/?${new URLSearchParams({api_key:Wt({databaseUrl:e.prismaORMConnectionString,name:n.name,shadowDatabaseUrl:t.prismaORMConnectionString})}).toString()}`;return{database:{connectionString:e.connectionString,prismaORMConnectionString:e.prismaORMConnectionString,terminalCommand:e.terminalCommand},http:{url:r.url},ppg:{url:s},shadowDatabase:{connectionString:t.prismaORMConnectionString,prismaORMConnectionString:t.prismaORMConnectionString,terminalCommand:t.terminalCommand}}}async function Gn(e,t){let r=[];for(let n of t)try{await n.close()}catch(s){r.push(s)}try{await e.close()}catch(n){r.push(n)}if(r.length>0)throw new AggregateError(r,"Failed to close some servers")}async function ca(e,t,r){try{await Gn(e,t.filter(n=>n!==null))}catch(n){throw new AggregateError([r,n],"Failed to start Prisma Dev server cleanly")}throw r}function ua(e){let t=new Set;return{api:{stream:()=>{let r=()=>{},n=pa(e,()=>{t.delete(r)});return r=()=>n.close(),t.add(r),n.stream},subscribe:r=>e.subscribe(r)},close:()=>{for(let r of[...t])r();t.clear()}}}function la(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function da(){return{async close(){},subscribe(){return()=>{}}}}function ma(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""},experimentalQueryInsights:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function pa(e,t){let r=[],n=!1,s=null,o=e.subscribe(i=>{if(!n){if(s){let c=s;s=null,c.resolve({done:!1,value:i});return}r.push(i)}}),a=()=>{if(!n&&(n=!0,o(),r.length=0,t(),s)){let i=s;s=null,i.resolve({done:!0,value:void 0})}};return{close:a,stream:{[Symbol.asyncIterator](){return this},next(){return r.length>0?Promise.resolve({done:!1,value:r.shift()}):n?Promise.resolve({done:!0,value:void 0}):new Promise((i,c)=>{s={reject:c,resolve:i}})},return(){return a(),Promise.resolve({done:!0,value:void 0})},throw(i){let c=s;return a(),c&&c.reject(i),Promise.reject(i instanceof Error?i:new Error(String(i)))}}}}se();m();var ga="default";function fa(e){return{databaseUrl:e.database.prismaORMConnectionString??e.database.connectionString,prismaPostgresUrl:e.ppg.url,shadowDatabaseUrl:e.shadowDatabase.prismaORMConnectionString??e.shadowDatabase.connectionString}}async function jn(e){let{debug:t,name:r=ga}=e??{},n=await $t(r,{debug:t});return!Un(n)||!n.exports?null:{...fa(n.exports),name:n.name}}async function Vn(e){let{server:t}=await Wn(e);return t}async function ha(e){return await Vn(e)}0&&(module.exports={DEFAULT_DATABASE_PORT,DEFAULT_SERVER_PORT,DEFAULT_SHADOW_DATABASE_PORT,DEFAULT_STREAMS_PORT,PortNotAvailableError,ServerAlreadyRunningError,copyPrismaDevRuntimeAssets,getPrismaDevRuntimeAssetManifest,getPrismaDevServerConnection,startPrismaDevServer,unstable_startServer});
package/dist/index.d.cts CHANGED
@@ -65,6 +65,57 @@ declare class PortNotAvailableError extends Error {
65
65
  constructor(port: number);
66
66
  }
67
67
 
68
+ interface PrismaDevConnectionStrings {
69
+ /**
70
+ * Direct TCP connection string for the main database.
71
+ */
72
+ readonly databaseUrl: string;
73
+ /**
74
+ * The `prisma+postgres://` HTTP connection string. Carries an API key.
75
+ */
76
+ readonly prismaPostgresUrl: string;
77
+ /**
78
+ * Direct TCP connection string for the shadow database, which
79
+ * `prisma migrate dev` requires.
80
+ */
81
+ readonly shadowDatabaseUrl: string;
82
+ }
83
+ interface PrismaDevServerConnection extends PrismaDevConnectionStrings {
84
+ /**
85
+ * The server name that was looked up.
86
+ */
87
+ readonly name: string;
88
+ }
89
+ interface GetPrismaDevServerConnectionOptions {
90
+ /**
91
+ * Whether to log the lookup's debug output.
92
+ *
93
+ * Defaults to `false`.
94
+ */
95
+ debug?: boolean;
96
+ /**
97
+ * Name of the server to look up.
98
+ *
99
+ * Defaults to `default`.
100
+ */
101
+ name?: string;
102
+ }
103
+ /**
104
+ * Reads the connection strings of a running `stateful` server by name.
105
+ *
106
+ * This is the supported way for a process outside the one hosting the database
107
+ * to address it. A migration, a seed script, or `psql` cannot see the
108
+ * `process.env` of the Vite dev server that started the database, and a named
109
+ * `stateful` server keeps its ports across restarts, so a lookup by name is
110
+ * stable where a hardcoded connection string is not.
111
+ *
112
+ * Resolves to `null` when no server of that name is running, or when one is
113
+ * still starting up and has not published its endpoints yet. Only `stateful`
114
+ * servers are visible: a `stateless` server writes no state and can only be
115
+ * addressed through the handle that started it.
116
+ */
117
+ declare function getPrismaDevServerConnection(options?: GetPrismaDevServerConnectionOptions): Promise<PrismaDevServerConnection | null>;
118
+
68
119
  type ReadonlyServer = Omit<ProgrammaticServer, "close">;
69
120
  /**
70
121
  * Starts a `prisma dev` server instance programmatically.
@@ -82,4 +133,4 @@ declare function startPrismaDevServer(options?: ServerOptions): Promise<Programm
82
133
  */
83
134
  declare function unstable_startServer(options?: ServerOptions): Promise<ProgrammaticServer>;
84
135
 
85
- export { DEFAULT_DATABASE_PORT, DEFAULT_SERVER_PORT, DEFAULT_SHADOW_DATABASE_PORT, DEFAULT_STREAMS_PORT, ExperimentalQueryInsights, type ExperimentalServerFeatures, ExperimentalStreams, WalEvent as ExperimentalWalEvent, type ExperimentalWalEventBatch, type ExperimentalWalEvents, type PortAssignableService, PortNotAvailableError, type ReadonlyServer, type ProgrammaticServer as Server, ServerOptions, startPrismaDevServer, unstable_startServer };
136
+ export { DEFAULT_DATABASE_PORT, DEFAULT_SERVER_PORT, DEFAULT_SHADOW_DATABASE_PORT, DEFAULT_STREAMS_PORT, ExperimentalQueryInsights, type ExperimentalServerFeatures, ExperimentalStreams, WalEvent as ExperimentalWalEvent, type ExperimentalWalEventBatch, type ExperimentalWalEvents, type GetPrismaDevServerConnectionOptions, type PortAssignableService, PortNotAvailableError, type PrismaDevConnectionStrings, type PrismaDevServerConnection, type ReadonlyServer, type ProgrammaticServer as Server, ServerOptions, getPrismaDevServerConnection, startPrismaDevServer, unstable_startServer };