@prisma/dev 0.24.14 → 0.24.15
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/accelerate-NQIUHBYP.js +11 -0
- package/dist/chunk-DEMTR4W3.js +1 -0
- package/dist/chunk-GT33FFME.js +3 -0
- package/dist/chunk-HM357TKK.js +1 -0
- package/dist/chunk-I2OHVRST.js +1 -0
- package/dist/chunk-JLSS5G22.js +1 -0
- package/dist/chunk-MN4XKQ55.js +1 -0
- package/dist/chunk-RN4YJIL3.js +23 -0
- package/dist/chunk-T6L5TENJ.js +1 -0
- package/dist/chunk-U3HKF6IL.js +1 -0
- package/dist/chunk-UEE5SWKL.js +1 -0
- package/dist/{chunk-PP43TGA5.js → chunk-WQHUHPVC.js} +15 -15
- package/dist/daemon.cjs +49 -27
- package/dist/daemon.js +1 -1
- package/dist/db.js +1 -1
- package/dist/engine-RSESCYD5.js +3 -0
- package/dist/index.cjs +49 -27
- package/dist/index.js +1 -1
- package/dist/query-plan-executor-566O5VXO.js +1 -0
- package/dist/runtime-assets.js +1 -1
- package/dist/server-SSXVHZ7Q.js +1 -0
- package/dist/state.js +1 -1
- package/dist/utility-RVP4AU5Y.js +1 -0
- package/package.json +2 -2
- package/dist/accelerate-45DUGMGZ.js +0 -11
- package/dist/chunk-662IKR3V.js +0 -1
- package/dist/chunk-ANHBRJRZ.js +0 -1
- package/dist/chunk-DOJAPHLY.js +0 -1
- package/dist/chunk-DWY47FQV.js +0 -1
- package/dist/chunk-EDFHV3AK.js +0 -1
- package/dist/chunk-FB4QA6EA.js +0 -1
- package/dist/chunk-HFONW2ZS.js +0 -3
- package/dist/chunk-KWCQYPJI.js +0 -1
- package/dist/chunk-SW3J2PL2.js +0 -1
- package/dist/engine-YTEOPVUP.js +0 -3
- package/dist/query-plan-executor-ZS4544O3.js +0 -1
- package/dist/server-QR7P25DP.js +0 -1
- package/dist/utility-YEFNU35E.js +0 -1
package/dist/daemon.cjs
CHANGED
|
@@ -1,24 +1,46 @@
|
|
|
1
|
-
"use strict";var Wn=Object.create;var me=Object.defineProperty;var Gn=Object.getOwnPropertyDescriptor;var jn=Object.getOwnPropertyNames;var Vn=Object.getPrototypeOf,Kn=Object.prototype.hasOwnProperty;var v=(e,t)=>()=>(e&&(t=e(e=0)),t);var re=(e,t)=>{for(var r in t)me(e,r,{get:t[r],enumerable:!0})},qt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of jn(t))!Kn.call(e,s)&&s!==r&&me(e,s,{get:()=>t[s],enumerable:!(n=Gn(t,s))||n.enumerable});return e};var D=(e,t,r)=>(r=e!=null?Wn(Vn(e)):{},qt(t||!e||!e.__esModule?me(r,"default",{value:e,enumerable:!0}):r,e)),zn=e=>qt(me({},"__esModule",{value:!0}),e);var Jn,h,m=v(()=>{"use strict";Jn=()=>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=Jn()});var A,pe=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 Xn(e){let t=Buffer.from(e,"base64url").toString("utf8"),{issues:r,output:n,success:s}=(0,P.safeParse)(Yn,t,{abortEarly:!0});return s?[null,n]:[r]}function G(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]=Xn(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:te,port:Le}=new URL(l),Fn=t.shadowDBPort;if(p!=="localhost"||Number(y)!==E||te!=="localhost"||Number(Le)!==Fn)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,Yn,$e=v(()=>{"use strict";m();P=require("valibot");pe();Ht=/^(postgres|postgresql):\/\//,Yn=(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 Ue(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),ge.default.platform==="darwin"?Zn(e):ge.default.platform==="win32"?es(e):ts(e)}var w,ke,ge,U,Ce,K,Zn,es,ts,Wt=v(()=>{"use strict";m();w=D(require("path"),1),ke=D(require("os"),1),ge=D(require("process"),1),U=ke.default.homedir(),Ce=ke.default.tmpdir(),{env:K}=ge.default,Zn=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(Ce,e)}},es=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(Ce,e)}},ts=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(Ce,t,e)}}});function Kt(e,t){return`${he.cache}/engine/${e}/${t}`}function ne(e){return`${he.data}/${e}`}async function z(e){try{return await(0,R.access)(e,R.constants.F_OK),!0}catch(t){if(Qe(t))return!1;throw t}}async function zt(e,t){let r=await rs(e);await(0,R.writeFile)(t,r),await(0,R.chmod)(t,"755")}async function Jt(e,t){await e.stream().pipeTo(fe.WriteStream.toWeb((0,fe.createWriteStream)(t,{encoding:"utf8"})))}function Qe(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(Qe(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(Qe(r))return[];throw r}}async function J(e){await(0,R.rm)(e,{force:!0,recursive:!0})}var fe,R,Gt,jt,Vt,he,rs,Y=v(()=>{"use strict";m();fe=require("fs"),R=require("fs/promises"),Gt=require("util"),jt=require("zlib");Wt();Vt=D(require("zeptomatch"),1),he=Ue("prisma-dev"),rs=(0,Gt.promisify)(jt.unzip)});async function Ke(e){let{debug:t,name:r,requestedPorts:n,servers:s}=e,{portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a}=os(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 ns({debug:t,portKey:u,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a,requestedPorts:n})??await ss({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 ns(e){let{debug:t,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s,requestedPorts:o}=e,{[r]:a,...i}=o;if(Ge(a))return await cs({debug:t,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:n,requestedPort:a}),a;let c=s?.[r]??_;if(!Ge(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 ss(e){let{debug:t,pickedPorts:r,portKey:n,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:o}=e,a=Math.max(qe,He,Fe,We)+1,i=Object.values(r).filter(p=>p!==void 0),c=o?is(o):[],u=[...i,...Object.keys(s).map(Number),...c],l=Math.min(Math.max(a,...u)+100,ye),f=(0,Se.difference)((0,Se.range)(a,l),u),d={port:He,databasePort:qe,shadowDatabasePort:Fe,streamsPort:We}[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<=ye)return t&&console.debug(`Expanding port lookup to range [${l+1}, ${ye}].`),await(0,Q.getPort)({portRange:[l+1,ye]});throw p}}function Ge(e){return Number.isFinite(e)&&e>=0}function os(e,t){let r={},n;for(let s of t){let{databasePort:o,port:a,shadowDatabasePort:i}=s,c=as(s);if(s.name===e){n={databasePort:o,port:a,shadowDatabasePort:i,streamsPort:c};continue}r[o]=!0,r[a]=!0,r[i]=!0,Ge(c)&&(r[c]=!0)}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}function as(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 is(e){return[e.port,e.databasePort,e.shadowDatabasePort,e.streamsPort]}async function cs(e){let{debug:t,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:s,requestedPort:o}=e;if(o!==j){if(o in s)throw t&&console.error(`Port ${o} was requested for "${n}", but is already used by another server.`),new Ve(o);if(Object.values(r).includes(o))throw t&&console.error(`Port ${o} was requested for "${n}", but also for another key.`),new je(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,Se,qe,He,Fe,We,ye,j,_,N,je,Ve,se=v(()=>{"use strict";m();Q=require("get-port-please"),Se=require("remeda"),qe=51214,He=51213,Fe=51215,We=51216,ye=65535,j=0,_=-1/0;N=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},je=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"},Ve=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 X(e,t=204){e.headersSent||(e.statusCode=t,e.setHeader("Content-Length",0)),e.end()}function Cr(e,t){x(e,t.message,t.status)}var ct,C=v(()=>{"use strict";m();ct=require("buffer")});async function Qr(e,t){let r;try{r=await(0,Ur.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 Ur,I,so,qr=v(()=>{"use strict";m();Ur=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 Fr(e,t){let r=e.schemaHash;if(r==null)return T(t,{EngineNotStarted:{reason:"SchemaMissing"}},404),null;let n=xe.get(r);return n==null?(T(t,{EngineNotStarted:{reason:"SchemaMissing"}},404),null):{schemaHash:r,schemas:n}}async function Wr(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)&&!Hr(e[r-1])&&!Hr(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
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
"use strict";var No=Object.create;var Ve=Object.defineProperty;var Mo=Object.getOwnPropertyDescriptor;var $o=Object.getOwnPropertyNames;var Lo=Object.getPrototypeOf,Bo=Object.prototype.hasOwnProperty;var D=(e,t)=>()=>(e&&(t=e(e=0)),t);var E=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),$e=(e,t)=>{for(var r in t)Ve(e,r,{get:t[r],enumerable:!0})},on=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of $o(t))!Bo.call(e,s)&&s!==r&&Ve(e,s,{get:()=>t[s],enumerable:!(n=Mo(t,s))||n.enumerable});return e};var U=(e,t,r)=>(r=e!=null?No(Lo(e)):{},on(t||!e||!e.__esModule?Ve(r,"default",{value:e,enumerable:!0}):r,e)),ko=e=>on(Ve({},"__esModule",{value:!0}),e);var Uo,h,f=D(()=>{"use strict";Uo=()=>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=Uo()});var H,Ke=D(()=>{"use strict";f();H=class extends Error{constructor(r,n,s){super(n,s);this.status=r}name="HTTPError"}});function cn(e){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([[t],[r]])=>t.localeCompare(r)))),"utf8").toString("base64url")}function qo(e){let t=Buffer.from(e,"base64url").toString("utf8"),{issues:r,output:n,success:s}=(0,x.safeParse)(Ho,t,{abortEarly:!0});return s?[null,n]:[r]}function ye(e,t){let r=e.headers.authorization;if(!r)throw new H(401,"Missing API Key");let[n,s="",i]=r.split(" ");if(n!=="Bearer"||i)throw new H(401,"Invalid API Key");let[o,a]=qo(s);if(o)throw new H(401,"Invalid API Key",{cause:o.join(", ")});let{databaseUrl:c,name:u,shadowDatabaseUrl:l}=a,m=t.name,d=t.port;if(!u)throw new H(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 "${m}" server's output for the updated \`DATABASE_URL\` value.`);if(u!==m)throw new H(401,`Wrong API Key; The Prisma Dev server running at port ${d} is named "${m}", but the API Key is for "${u}"`);let{hostname:p,port:y}=new URL(c),{port:b}=t.db,{hostname:S,port:O}=new URL(l),I=t.shadowDBPort;if(p!=="localhost"||Number(y)!==b||S!=="localhost"||Number(O)!==I)throw new H(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 a}var x,an,Ho,Bt=D(()=>{"use strict";f();x=require("valibot");Ke();an=/^(postgres|postgresql):\/\//,Ho=(0,x.pipe)((0,x.string)(),(0,x.parseJson)(),(0,x.object)({databaseUrl:(0,x.pipe)((0,x.string)(),(0,x.url)(),(0,x.regex)(an)),name:(0,x.optional)((0,x.pipe)((0,x.string)(),(0,x.minLength)(1))),shadowDatabaseUrl:(0,x.pipe)((0,x.string)(),(0,x.url)(),(0,x.regex)(an))}))});function Ht(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),Je.default.platform==="darwin"?jo(e):Je.default.platform==="win32"?Qo(e):Fo(e)}var A,kt,Je,le,Ut,ve,jo,Qo,Fo,ln=D(()=>{"use strict";f();A=U(require("path"),1),kt=U(require("os"),1),Je=U(require("process"),1),le=kt.default.homedir(),Ut=kt.default.tmpdir(),{env:ve}=Je.default,jo=e=>{let t=A.default.join(le,"Library");return{data:A.default.join(t,"Application Support",e),config:A.default.join(t,"Preferences",e),cache:A.default.join(t,"Caches",e),log:A.default.join(t,"Logs",e),temp:A.default.join(Ut,e)}},Qo=e=>{let t=ve.APPDATA||A.default.join(le,"AppData","Roaming"),r=ve.LOCALAPPDATA||A.default.join(le,"AppData","Local");return{data:A.default.join(r,e,"Data"),config:A.default.join(t,e,"Config"),cache:A.default.join(r,e,"Cache"),log:A.default.join(r,e,"Log"),temp:A.default.join(Ut,e)}},Fo=e=>{let t=A.default.basename(le);return{data:A.default.join(ve.XDG_DATA_HOME||A.default.join(le,".local","share"),e),config:A.default.join(ve.XDG_CONFIG_HOME||A.default.join(le,".config"),e),cache:A.default.join(ve.XDG_CACHE_HOME||A.default.join(le,".cache"),e),log:A.default.join(ve.XDG_STATE_HOME||A.default.join(le,".local","state"),e),temp:A.default.join(Ut,t,e)}}});function mn(e,t){return`${Xe.cache}/engine/${e}/${t}`}function Le(e){return`${Xe.data}/${e}`}async function Re(e){try{return await(0,N.access)(e,N.constants.F_OK),!0}catch(t){if(qt(t))return!1;throw t}}async function pn(e,t){let r=await Wo(e);await(0,N.writeFile)(t,r),await(0,N.chmod)(t,"755")}async function hn(e,t){await e.stream().pipeTo(Ye.WriteStream.toWeb((0,Ye.createWriteStream)(t,{encoding:"utf8"})))}function qt(e){return e!=null&&typeof e=="object"&&"code"in e&&e.code==="ENOENT"}async function gn(e){try{return await(0,N.readFile)(e,{encoding:"utf-8"})}catch(t){if(qt(t))return null;throw t}}async function yn(e){await(0,N.mkdir)(e,{recursive:!0})}async function Sn(e,t){try{return(await(0,N.readdir)(e,{withFileTypes:!0})).reduce((n,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!t||(0,fn.default)(t,s.name))&&n.push(s.name),n),[])}catch(r){if(qt(r))return[];throw r}}async function xe(e){await(0,N.rm)(e,{force:!0,recursive:!0})}var Ye,N,un,dn,fn,Xe,Wo,Te=D(()=>{"use strict";f();Ye=require("fs"),N=require("fs/promises"),un=require("util"),dn=require("zlib");ln();fn=U(require("zeptomatch"),1),Xe=Ht("prisma-dev"),Wo=(0,un.promisify)(dn.unzip)});async function Kt(e){let{debug:t,name:r,requestedPorts:n,servers:s}=e,{portsUsedByOtherServers:i,portsUsedByThisServerLastTime:o}=Vo(r,s);t&&(console.debug(`ports used by other servers: ${Object.keys(i).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(o)}`));let a={databasePort:q,port:q,shadowDatabasePort:q,streamsPort:q},c=["port","databasePort","shadowDatabasePort","streamsPort"];for(let u of c){let l=await Go({debug:t,portKey:u,portsUsedByOtherServers:i,portsUsedByThisServerLastTime:o,requestedPorts:n})??await zo({debug:t,pickedPorts:a,portKey:u,portsUsedByOtherServers:i,portsUsedByThisServerLastTime:o});t&&console.debug(`Got port for "${u}": ${l}`),a[u]=l}return t&&console.debug(`Picked ports: ${JSON.stringify(a)}`),a}async function Go(e){let{debug:t,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s,requestedPorts:i}=e,{[r]:o,...a}=i;if(Gt(o))return await Yo({debug:t,otherRequestedPorts:a,portKey:r,portsUsedByOtherServers:n,requestedPort:o}),o;let c=s?.[r]??q;if(!Gt(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(a).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,ue.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 zo(e){let{debug:t,pickedPorts:r,portKey:n,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:i}=e,o=Math.max(jt,Qt,Ft,Wt)+1,a=Object.values(r).filter(p=>p!==void 0),c=i?Jo(i):[],u=[...a,...Object.keys(s).map(Number),...c],l=Math.min(Math.max(o,...u)+100,Ze),m=(0,et.difference)((0,et.range)(o,l),u),d={port:Qt,databasePort:jt,shadowDatabasePort:Ft,streamsPort:Wt}[n];try{return await(0,ue.getPort)({port:d in s||a.includes(d)||c.includes(d)?void 0:d,ports:m})}catch(p){if(p instanceof Error&&p.name==="GetPortError"&&l+1<=Ze)return t&&console.debug(`Expanding port lookup to range [${l+1}, ${Ze}].`),await(0,ue.getPort)({portRange:[l+1,Ze]});throw p}}function Gt(e){return Number.isFinite(e)&&e>=0}function Vo(e,t){let r={},n;for(let s of t){let{databasePort:i,port:o,shadowDatabasePort:a}=s,c=Ko(s);if(s.name===e){n={databasePort:i,port:o,shadowDatabasePort:a,streamsPort:c};continue}r[i]=!0,r[o]=!0,r[a]=!0,Gt(c)&&(r[c]=!0)}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}function Ko(e){let t=e.experimental?.streams?.serverUrl;if(!t)return q;try{let r=Number(new URL(t).port);return Number.isInteger(r)&&r>0?r:q}catch{return q}}function Jo(e){return[e.port,e.databasePort,e.shadowDatabasePort,e.streamsPort]}async function Yo(e){let{debug:t,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:s,requestedPort:i}=e;if(i!==Se){if(i in s)throw t&&console.error(`Port ${i} was requested for "${n}", but is already used by another server.`),new Vt(i);if(Object.values(r).includes(i))throw t&&console.error(`Port ${i} was requested for "${n}", but also for another key.`),new zt(i);if((0,ue.isUnsafePort)(i))throw t&&console.error(`Port ${i} was requested for "${n}", but is unsafe.`),new V(i);if(await(0,ue.checkPort)(i)===!1)throw t&&console.error(`Port ${i} was requested for "${n}", but is not available.`),new V(i)}}var ue,et,jt,Qt,Ft,Wt,Ze,Se,q,V,zt,Vt,Be=D(()=>{"use strict";f();ue=require("get-port-please"),et=require("remeda"),jt=51214,Qt=51213,Ft=51215,Wt=51216,Ze=65535,Se=0,q=-1/0;V=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},zt=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"},Vt=class extends Error{constructor(r){super(`Port number \`${r}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=r}name="PortBelongsToAnotherServerError"}});var os=E((Nu,is)=>{"use strict";f();var ns=12,za=0,lr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,7,7,7,7,7,7,7,7,7,7,7,7,8,7,7,10,9,9,9,11,4,4,4,4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,24,36,48,60,72,84,96,0,12,12,12,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0,0,0,0,0,0,24,24,24,0,0,0,0,0,0,0,0,0,24,24,0,0,0,0,0,0,0,0,0,0,48,48,48,0,0,0,0,0,0,0,0,0,0,48,48,0,0,0,0,0,0,0,0,0,48,0,0,0,0,0,0,0,0,0,0,127,63,63,63,0,31,15,15,15,7,7,7];function Va(e){var t=e.indexOf("%");if(t===-1)return e;for(var r=e.length,n="",s=0,i=0,o=t,a=ns;t>-1&&t<r;){var c=ss(e[t+1],4),u=ss(e[t+2],0),l=c|u,m=lr[l];if(a=lr[256+a+m],i=i<<6|l&lr[364+m],a===ns)n+=e.slice(s,o),n+=i<=65535?String.fromCharCode(i):String.fromCharCode(55232+(i>>10),56320+(i&1023)),i=0,s=t+3,t=o=e.indexOf("%",s);else{if(a===za)return null;if(t+=3,t<r&&e.charCodeAt(t)===37)continue;return null}}return n+e.slice(s)}var Ka={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};function ss(e,t){var r=Ka[e];return r===void 0?255:r<<t}is.exports=Va});var ds=E(($u,us)=>{"use strict";f();var as=os(),cs=/\+/g,ls=function(){};ls.prototype=Object.create(null);function Ja(e){let t=new ls;if(typeof e!="string")return t;let r=e.length,n="",s="",i=-1,o=-1,a=!1,c=!1,u=!1,l=!1,m=!1,d=0;for(let p=0;p<r+1;p++)if(d=p!==r?e.charCodeAt(p):38,d===38){if(m=o>i,m||(o=p),n=e.slice(i+1,o),m||n.length>0){u&&(n=n.replace(cs," ")),a&&(n=as(n)||n),m&&(s=e.slice(o+1,p),l&&(s=s.replace(cs," ")),c&&(s=as(s)||s));let y=t[n];y===void 0?t[n]=s:y.pop?y.push(s):t[n]=[y,s]}s="",i=p,o=p,a=!1,c=!1,u=!1,l=!1}else d===61?o<=i?o=p:c=!0:d===43?o>i?l=!0:u=!0:d===37&&(o>i?c=!0:a=!0);return t}us.exports=Ja});var ms=E((Bu,fs)=>{"use strict";f();var J=Array.from({length:256},(e,t)=>"%"+((t<16?"0":"")+t.toString(16)).toUpperCase()),Ya=new Int8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,1,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,0]);function Xa(e){let t=e.length;if(t===0)return"";let r="",n=0,s=0;e:for(;s<t;s++){let i=e.charCodeAt(s);for(;i<128;){if(Ya[i]!==1&&(n<s&&(r+=e.slice(n,s)),n=s+1,r+=J[i]),++s===t)break e;i=e.charCodeAt(s)}if(n<s&&(r+=e.slice(n,s)),i<2048){n=s+1,r+=J[192|i>>6]+J[128|i&63];continue}if(i<55296||i>=57344){n=s+1,r+=J[224|i>>12]+J[128|i>>6&63]+J[128|i&63];continue}if(++s,s>=t)throw new Error("URI malformed");let o=e.charCodeAt(s)&1023;n=s+1,i=65536+((i&1023)<<10|o),r+=J[240|i>>18]+J[128|i>>12&63]+J[128|i>>6&63]+J[128|i&63]}return n===0?e:n<t?r+e.slice(n):r}fs.exports={encodeString:Xa}});var gs=E((Uu,hs)=>{"use strict";f();var{encodeString:ur}=ms();function ps(e){let t=typeof e;return t==="string"?ur(e):t==="bigint"?e.toString():t==="boolean"?e?"true":"false":t==="number"&&Number.isFinite(e)?e<1e21?""+e:ur(""+e):""}function Za(e){let t="";if(e===null||typeof e!="object")return t;let r="&",n=Object.keys(e),s=n.length,i=0;for(let o=0;o<s;o++){let a=n[o],c=e[a],u=ur(a)+"=";if(o&&(t+=r),Array.isArray(c)){i=c.length;for(let l=0;l<i;l++)l&&(t+=r),t+=u,t+=ps(c[l])}else t+=u,t+=ps(c)}return t}hs.exports=Za});var Ps=E((qu,Ue)=>{"use strict";f();var ys=ds(),Ss=gs(),bs={parse:ys,stringify:Ss};Ue.exports=bs;Ue.exports.default=bs;Ue.exports.parse=ys;Ue.exports.stringify=Ss});var Es=E(ws=>{"use strict";f();Object.defineProperty(ws,"__esModule",{value:!0})});var vs=E(He=>{"use strict";f();Object.defineProperty(He,"__esModule",{value:!0});He.types=void 0;var ec;(function(e){e[e.ROOT=0]="ROOT",e[e.GROUP=1]="GROUP",e[e.POSITION=2]="POSITION",e[e.SET=3]="SET",e[e.RANGE=4]="RANGE",e[e.REPETITION=5]="REPETITION",e[e.REFERENCE=6]="REFERENCE",e[e.CHAR=7]="CHAR"})(ec=He.types||(He.types={}))});var xs=E(Rs=>{"use strict";f();Object.defineProperty(Rs,"__esModule",{value:!0})});var ie=E(se=>{"use strict";f();var tc=se&&se.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),dr=se&&se.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&tc(t,e,r)};Object.defineProperty(se,"__esModule",{value:!0});dr(Es(),se);dr(vs(),se);dr(xs(),se)});var ct=E(M=>{"use strict";f();Object.defineProperty(M,"__esModule",{value:!0});M.anyChar=M.notWhitespace=M.whitespace=M.notInts=M.ints=M.notWords=M.words=void 0;var w=ie(),Ts=()=>[{type:w.types.RANGE,from:48,to:57}],Is=()=>[{type:w.types.CHAR,value:95},{type:w.types.RANGE,from:97,to:122},{type:w.types.RANGE,from:65,to:90},{type:w.types.RANGE,from:48,to:57}],As=()=>[{type:w.types.CHAR,value:9},{type:w.types.CHAR,value:10},{type:w.types.CHAR,value:11},{type:w.types.CHAR,value:12},{type:w.types.CHAR,value:13},{type:w.types.CHAR,value:32},{type:w.types.CHAR,value:160},{type:w.types.CHAR,value:5760},{type:w.types.RANGE,from:8192,to:8202},{type:w.types.CHAR,value:8232},{type:w.types.CHAR,value:8233},{type:w.types.CHAR,value:8239},{type:w.types.CHAR,value:8287},{type:w.types.CHAR,value:12288},{type:w.types.CHAR,value:65279}],rc=()=>[{type:w.types.CHAR,value:10},{type:w.types.CHAR,value:13},{type:w.types.CHAR,value:8232},{type:w.types.CHAR,value:8233}];M.words=()=>({type:w.types.SET,set:Is(),not:!1});M.notWords=()=>({type:w.types.SET,set:Is(),not:!0});M.ints=()=>({type:w.types.SET,set:Ts(),not:!1});M.notInts=()=>({type:w.types.SET,set:Ts(),not:!0});M.whitespace=()=>({type:w.types.SET,set:As(),not:!1});M.notWhitespace=()=>({type:w.types.SET,set:As(),not:!0});M.anyChar=()=>({type:w.types.SET,set:rc(),not:!0})});var Ds=E(Q=>{"use strict";f();var nc=Q&&Q.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),sc=Q&&Q.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),ic=Q&&Q.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&nc(t,e,r);return sc(t,e),t};Object.defineProperty(Q,"__esModule",{value:!0});Q.tokenizeClass=Q.strToChars=void 0;var _s=ie(),Ie=ic(ct()),oc="@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?";Q.strToChars=e=>{let t=/(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|c([@A-Z[\\\]^?])|([0tnvfr]))/g;return e.replace(t,(r,n,s,i,o,a,c)=>{if(s)return r;let u=n?8:i?parseInt(i,16):o?parseInt(o,16):a?oc.indexOf(a):{0:0,t:9,n:10,v:11,f:12,r:13}[c],l=String.fromCharCode(u);return/[[\]{}^$.|?*+()]/.test(l)?`\\${l}`:l})};Q.tokenizeClass=(e,t)=>{var r,n,s,i,o,a,c;let u=[],l,m,d=/\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(((?:\\)])|(((?:\\)?([^\]])))))|(\])|(?:\\)?([^])/g;for(;(l=d.exec(e))!==null;){let p=(c=(a=(o=(i=(s=(n=(r=l[1]&&Ie.words())!==null&&r!==void 0?r:l[2]&&Ie.ints())!==null&&n!==void 0?n:l[3]&&Ie.whitespace())!==null&&s!==void 0?s:l[4]&&Ie.notWords())!==null&&i!==void 0?i:l[5]&&Ie.notInts())!==null&&o!==void 0?o:l[6]&&Ie.notWhitespace())!==null&&a!==void 0?a:l[7]&&{type:_s.types.RANGE,from:(l[8]||l[9]).charCodeAt(0),to:(m=l[10]).charCodeAt(m.length-1)})!==null&&c!==void 0?c:(m=l[16])&&{type:_s.types.CHAR,value:m.charCodeAt(0)};if(p)u.push(p);else return[u,d.lastIndex]}throw new SyntaxError(`Invalid regular expression: /${t}/: Unterminated character class`)}});var fr=E(Y=>{"use strict";f();var ac=Y&&Y.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),cc=Y&&Y.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Ns=Y&&Y.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&ac(t,e,r);return cc(t,e),t};Object.defineProperty(Y,"__esModule",{value:!0});Y.tokenizer=void 0;var Os=Ns(Ds()),C=ie(),be=Ns(ct()),lc=/^[a-zA-Z_$]$/i,uc=/^[a-zA-Z0-9_$]$/i,Cs=/\d/;Y.tokenizer=e=>{let t=0,r,n={type:C.types.ROOT,stack:[]},s=n,i=n.stack,o=[],a=[],c=0,u=m=>{throw new SyntaxError(`Invalid regular expression: /${e}/: Nothing to repeat at column ${m-1}`)},l=Os.strToChars(e);for(;t<l.length;)switch(r=l[t++]){case"\\":if(t===l.length)throw new SyntaxError(`Invalid regular expression: /${e}/: \\ at end of pattern`);switch(r=l[t++]){case"b":i.push({type:C.types.POSITION,value:"b"});break;case"B":i.push({type:C.types.POSITION,value:"B"});break;case"w":i.push(be.words());break;case"W":i.push(be.notWords());break;case"d":i.push(be.ints());break;case"D":i.push(be.notInts());break;case"s":i.push(be.whitespace());break;case"S":i.push(be.notWhitespace());break;default:if(Cs.test(r)){let m=r;for(;t<l.length&&Cs.test(l[t]);)m+=l[t++];let d=parseInt(m,10),p={type:C.types.REFERENCE,value:d};i.push(p),a.push({reference:p,stack:i,index:i.length-1})}else i.push({type:C.types.CHAR,value:r.charCodeAt(0)})}break;case"^":i.push({type:C.types.POSITION,value:"^"});break;case"$":i.push({type:C.types.POSITION,value:"$"});break;case"[":{let m;l[t]==="^"?(m=!0,t++):m=!1;let d=Os.tokenizeClass(l.slice(t),e);t+=d[1],i.push({type:C.types.SET,set:d[0],not:m});break}case".":i.push(be.anyChar());break;case"(":{let m={type:C.types.GROUP,stack:[],remember:!0};if(l[t]==="?")if(r=l[t+1],t+=2,r==="=")m.followedBy=!0,m.remember=!1;else if(r==="!")m.notFollowedBy=!0,m.remember=!1;else if(r==="<"){let d="";if(lc.test(l[t]))d+=l[t],t++;else throw new SyntaxError(`Invalid regular expression: /${e}/: Invalid capture group name, character '${l[t]}' after '<' at column ${t+1}`);for(;t<l.length&&uc.test(l[t]);)d+=l[t],t++;if(!d)throw new SyntaxError(`Invalid regular expression: /${e}/: Invalid capture group name, character '${l[t]}' after '<' at column ${t+1}`);if(l[t]!==">")throw new SyntaxError(`Invalid regular expression: /${e}/: Unclosed capture group name, expected '>', found '${l[t]}' at column ${t+1}`);m.name=d,t++}else if(r===":")m.remember=!1;else throw new SyntaxError(`Invalid regular expression: /${e}/: Invalid group, character '${r}' after '?' at column ${t-1}`);else c+=1;i.push(m),o.push(s),s=m,i=m.stack;break}case")":if(o.length===0)throw new SyntaxError(`Invalid regular expression: /${e}/: Unmatched ) at column ${t-1}`);s=o.pop(),i=s.options?s.options[s.options.length-1]:s.stack;break;case"|":{s.options||(s.options=[s.stack],delete s.stack);let m=[];s.options.push(m),i=m;break}case"{":{let m=/^(\d+)(,(\d+)?)?\}/.exec(l.slice(t)),d,p;m!==null?(i.length===0&&u(t),d=parseInt(m[1],10),p=m[2]?m[3]?parseInt(m[3],10):1/0:d,t+=m[0].length,i.push({type:C.types.REPETITION,min:d,max:p,value:i.pop()})):i.push({type:C.types.CHAR,value:123});break}case"?":i.length===0&&u(t),i.push({type:C.types.REPETITION,min:0,max:1,value:i.pop()});break;case"+":i.length===0&&u(t),i.push({type:C.types.REPETITION,min:1,max:1/0,value:i.pop()});break;case"*":i.length===0&&u(t),i.push({type:C.types.REPETITION,min:0,max:1/0,value:i.pop()});break;default:i.push({type:C.types.CHAR,value:r.charCodeAt(0)})}if(o.length!==0)throw new SyntaxError(`Invalid regular expression: /${e}/: Unterminated group`);return dc(a,c),n};function dc(e,t){for(let r of e.reverse())if(t<r.reference.value){r.reference.type=C.types.CHAR;let n=r.reference.value.toString();if(r.reference.value=parseInt(n,8),!/^[0-7]+$/.test(n)){let s=0;for(;n[s]!=="8"&&n[s]!=="9";)s+=1;if(s===0?(r.reference.value=n.charCodeAt(0),s+=1):r.reference.value=parseInt(n.slice(0,s),8),n.length>s){let i=r.stack.splice(r.index+1);for(let o of n.slice(s))r.stack.push({type:C.types.CHAR,value:o.charCodeAt(0)});r.stack.push(...i)}}}}});var $s=E($=>{"use strict";f();var fc=$&&$.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),mc=$&&$.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),pc=$&&$.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&fc(t,e,r);return mc(t,e),t};Object.defineProperty($,"__esModule",{value:!0});$.NOTANYCHAR=$.WHITESPACE=$.WORDS=$.INTS=void 0;var lt=pc(ct()),Ms=ie();function ut(e){let t={},r=0;for(let n of e)n.type===Ms.types.CHAR&&(t[n.value]=!0),n.type===Ms.types.RANGE&&(t[`${n.from}-${n.to}`]=!0),r+=1;return{lookup:()=>Object.assign({},t),len:r}}$.INTS=ut(lt.ints().set);$.WORDS=ut(lt.words().set);$.WHITESPACE=ut(lt.whitespace().set);$.NOTANYCHAR=ut(lt.anyChar().set)});var Bs=E(F=>{"use strict";f();var hc=F&&F.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),gc=F&&F.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),yc=F&&F.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&hc(t,e,r);return gc(t,e),t};Object.defineProperty(F,"__esModule",{value:!0});F.writeSetTokens=F.setChar=void 0;var pt=ie(),dt=yc($s());function mt(e){return e===94?"\\^":e===92?"\\\\":e===93?"\\]":e===45?"\\-":String.fromCharCode(e)}F.setChar=mt;function ft(e,{lookup:t,len:r}){if(r!==e.length)return!1;let n=t();for(let s of e){if(s.type===pt.types.SET)return!1;let i=s.type===pt.types.CHAR?s.value:`${s.from}-${s.to}`;if(n[i])n[i]=!1;else return!1}return!0}function Ls(e,t=!1){if(ft(e.set,dt.INTS))return e.not?"\\D":"\\d";if(ft(e.set,dt.WORDS))return e.not?"\\W":"\\w";if(e.not&&ft(e.set,dt.NOTANYCHAR))return".";if(ft(e.set,dt.WHITESPACE))return e.not?"\\S":"\\s";let r="";for(let s=0;s<e.set.length;s++){let i=e.set[s];r+=Sc(i)}let n=`${e.not?"^":""}${r}`;return t?n:`[${n}]`}F.writeSetTokens=Ls;function Sc(e){return e.type===pt.types.CHAR?mt(e.value):e.type===pt.types.RANGE?`${mt(e.from)}-${mt(e.to)}`:Ls(e,!0)}});var pr=E(Ae=>{"use strict";f();Object.defineProperty(Ae,"__esModule",{value:!0});Ae.reconstruct=void 0;var pe=ie(),mr=Bs(),ks=e=>e.map(Ae.reconstruct).join(""),Us=e=>{if("options"in e)return e.options.map(ks).join("|");if("stack"in e)return ks(e.stack);throw new Error("options or stack must be Root or Group token")};Ae.reconstruct=e=>{switch(e.type){case pe.types.ROOT:return Us(e);case pe.types.CHAR:{let t=String.fromCharCode(e.value);return(/[[\\{}$^.|?*+()]/.test(t)?"\\":"")+t}case pe.types.POSITION:return e.value==="^"||e.value==="$"?e.value:`\\${e.value}`;case pe.types.REFERENCE:return`\\${e.value}`;case pe.types.SET:return mr.writeSetTokens(e);case pe.types.GROUP:return`(${e.name?`?<${e.name}>`:e.remember?"":e.followedBy?"?=":e.notFollowedBy?"?!":"?:"}${Us(e)})`;case pe.types.REPETITION:{let{min:t,max:r}=e,n;return t===0&&r===1?n="?":t===1&&r===1/0?n="+":t===0&&r===1/0?n="*":r===1/0?n=`{${t},}`:t===r?n=`{${t}}`:n=`{${t},${r}}`,`${Ae.reconstruct(e.value)}${n}`}case pe.types.RANGE:return`${mr.setChar(e.from)}-${mr.setChar(e.to)}`;default:throw new Error(`Invalid token type ${e}`)}}});var gr=E((W,ht)=>{"use strict";f();var bc=W&&W.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),hr=W&&W.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&bc(t,e,r)};Object.defineProperty(W,"__esModule",{value:!0});W.types=void 0;var Hs=ie();Object.defineProperty(W,"types",{enumerable:!0,get:function(){return Hs.types}});hr(fr(),W);hr(pr(),W);var qs=fr(),Pc=pr();hr(ie(),W);W.default=qs.tokenizer;ht.exports=qs.tokenizer;ht.exports.types=Hs.types;ht.exports.reconstruct=Pc.reconstruct});var js=E((ud,gt)=>{"use strict";f();var wc=gr(),{types:Ec}=gr();function yr(e,t,r){let n,s,i;if(e.type===Ec.REPETITION&&(r++,t.reps++,r>1||t.reps>t.limit))return!1;let o=e.options||e.value?.options;if(o){for(n=0,i=o.length;n<i;n++)if(s=yr({stack:o[n]},t,r),!s)return!1}let a=e.stack||e.value?.stack;if(!a)return!0;for(n=0,i=a.length;n<i;n++)if(s=yr(a[n],t,r),!s)return!1;return!0}function Sr(e,t){let r={reps:0,limit:t?.limit??25};vc(e)?e=e.source:typeof e!="string"&&(e=String(e));try{return yr(wc(e),r,0)}catch{return!1}}function vc(e){return Object.prototype.toString.call(e)==="[object RegExp]"}gt.exports=Sr;gt.exports.default=Sr;gt.exports.safeRegex=Sr});var br=E((fd,Qs)=>{"use strict";f();Qs.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,s,i;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!e(t[s],r[s]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(i=Object.keys(t),n=i.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[s]))return!1;for(s=n;s--!==0;){var o=i[s];if(!e(t[o],r[o]))return!1}return!0}return t!==t&&r!==r}});var yt=E((pd,Fs)=>{"use strict";f();Fs.exports={name:"__fmw_internal_strategy_merged_tree_http_method__",storage:function(){let e=new Map;return{get:t=>e.get(t)||null,set:(t,r)=>{e.set(t,r)}}},deriveConstraint:e=>e.method,mustMatchWhenDerived:!0}});var Ys=E((gd,Js)=>{"use strict";f();var Ws=br(),Gs=yt(),zs=Symbol("treeData");function Vs(e,t=""){let r="",n=Object.keys(e);for(let s=0;s<n.length;s++){let i=n[s],o=e[i],a=s===n.length-1,c=a?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",u=a?" ":"\u2502 ",m=(o[zs]||"").replaceAll(`
|
|
2
|
+
`,`
|
|
3
|
+
`+t+u);r+=t+c+i+m+`
|
|
4
|
+
`,r+=Vs(o,t+u)}return r}function Rc(e){let t=e.name||"";return t=t.replace("bound","").trim(),t=(t||"anonymous")+"()",t}function Ks(e){return Array.isArray(e)?e.map(t=>Ks(t)):typeof e=="symbol"?e.toString():typeof e=="function"?Rc(e):e}function xc(e,t){if(!t.includeMeta)return{};let r=t.buildPrettyMeta(e),n={},s=t.includeMeta;Array.isArray(s)||(s=Reflect.ownKeys(r));for(let i of s){if(!Object.prototype.hasOwnProperty.call(r,i))continue;let o=i.toString(),a=r[i];if(a!=null){let c=JSON.stringify(Ks(a));n[o]=c}}return n}function Tc(e){let t="";for(let[r,n]of Object.entries(e))t+=`
|
|
5
|
+
\u2022 (${r}) ${n}`;return t}function Ic(e){let t={...e.opts.constraints},r=t[Gs.name];return delete t[Gs.name],{...e,method:r,opts:{constraints:t}}}function Ac(e){let t=` (${e.method})`,r=e.opts.constraints||{};return Object.keys(r).length!==0&&(t+=" "+JSON.stringify(r)),t+=Tc(e.metaData),t}function _c(e){return e.reduce((t,r)=>{for(let n of t)if(Ws(r.opts.constraints,n.opts.constraints)&&Ws(r.metaData,n.metaData))return n.method+=", "+r.method,t;return t.push(r),t},[])}function Dc(e,t,r){let n=e.routes;return r.method===void 0&&(n=n.map(Ic)),n=n.map(s=>(s.metaData=xc(s,r),s)),r.method===void 0&&(n=_c(n)),n.map(Ac).join(`
|
|
6
|
+
${t}`)}function St(e,t,r,n){if((e.isLeafNode||n.commonPrefix!==!1)&&(r=r||"(empty root node)",t=t[r]={},e.isLeafNode&&(t[zs]=Dc(e,r,n)),r=""),e.staticChildren)for(let s of Object.values(e.staticChildren))St(s,t,r+s.prefix,n);if(e.parametricChildren)for(let s of Object.values(e.parametricChildren)){let i=Array.from(s.nodePaths).join("|");St(s,t,r+i,n)}e.wildcardChild&&St(e.wildcardChild,t,"*",n)}function Oc(e,t){let r={};return St(e,r,e.prefix,t),Vs(r)}Js.exports={prettyPrintTree:Oc}});var ei=E((Sd,Zs)=>{"use strict";f();var Xs=function(){};Xs.prototype=Object.create(null);Zs.exports={NullObject:Xs}});var ri=E((Pd,ti)=>{"use strict";f();var{NullObject:Cc}=ei(),Nc=yt(),Pr=class{constructor(){this.unconstrainedHandler=null,this.constraints=[],this.handlers=[],this.constrainedHandlerStores=null}getMatchingHandler(t){return t===void 0?this.unconstrainedHandler:this._getHandlerMatchingConstraints(t)}addHandler(t,r){let n=r.params,s=r.opts.constraints||{},i={params:n,constraints:s,handler:r.handler,store:r.store||null,_createParamsObject:this._compileCreateParamsObject(n)},o=Object.keys(s);o.length===0&&(this.unconstrainedHandler=i);for(let c of o)this.constraints.includes(c)||(c==="version"?this.constraints.unshift(c):this.constraints.push(c));let a=o.includes(Nc.name);if(!a&&this.handlers.length>=31)throw new Error("find-my-way supports a maximum of 31 route handlers per node when there are constraints, limit reached");this.handlers.push(i),this.handlers.sort((c,u)=>Object.keys(c.constraints).length-Object.keys(u.constraints).length),a||this._compileGetHandlerMatchingConstraints(t,s)}_compileCreateParamsObject(t){let r=[];r.push("const fn = function _createParamsObject (paramsArray) {"),r.push("const params = new NullObject()");for(let n=0;n<t.length;n++)r.push(`params['${t[n]}'] = paramsArray[${n}]`);return r.push("return params"),r.push("}"),r.push("return fn"),new Function("NullObject",r.join(`
|
|
7
|
+
`))(Cc)}_getHandlerMatchingConstraints(){return null}_buildConstraintStore(t,r){for(let n=0;n<this.handlers.length;n++){let i=this.handlers[n].constraints[r];if(i!==void 0){let o=t.get(i)||0;o|=1<<n,t.set(i,o)}}}_constrainedIndexBitmask(t){let r=0;for(let n=0;n<this.handlers.length;n++)this.handlers[n].constraints[t]!==void 0&&(r|=1<<n);return~r}_compileGetHandlerMatchingConstraints(t){this.constrainedHandlerStores={};for(let n of this.constraints){let s=t.newStoreForConstraint(n);this.constrainedHandlerStores[n]=s,this._buildConstraintStore(s,n)}let r=[];r.push(`
|
|
8
|
+
let candidates = ${(1<<this.handlers.length)-1}
|
|
9
|
+
let mask, matches
|
|
10
|
+
`);for(let n of this.constraints){r.push(`
|
|
11
|
+
mask = ${this._constrainedIndexBitmask(n)}
|
|
12
|
+
value = derivedConstraints.${n}
|
|
13
|
+
`);let i=t.strategies[n].mustMatchWhenDerived?"matches":"(matches | mask)";r.push(`
|
|
14
|
+
if (value === undefined) {
|
|
15
|
+
candidates &= mask
|
|
16
|
+
} else {
|
|
17
|
+
matches = this.constrainedHandlerStores.${n}.get(value) || 0
|
|
18
|
+
candidates &= ${i}
|
|
19
|
+
}
|
|
20
|
+
if (candidates === 0) return null;
|
|
21
|
+
`)}for(let n in t.strategies){if(!Object.hasOwn(t.strategies,n))continue;t.strategies[n].mustMatchWhenDerived&&!this.constraints.includes(n)&&r.push(`if (derivedConstraints.${n} !== undefined) return null`)}r.push("return this.handlers[31 - Math.clz32(candidates)]"),this._getHandlerMatchingConstraints=new Function("derivedConstraints",r.join(`
|
|
22
|
+
`))}};ti.exports=Pr});var si=E((Ed,ni)=>{"use strict";f();var Mc=ri(),Rt={STATIC:0,PARAMETRIC:1,WILDCARD:2},bt=class{constructor(){this.isLeafNode=!1,this.routes=null,this.handlerStorage=null}addRoute(t,r){this.routes===null&&(this.routes=[]),this.handlerStorage===null&&(this.handlerStorage=new Mc),this.isLeafNode=!0,this.routes.push(t),this.handlerStorage.addHandler(r,t)}},Pt=class extends bt{constructor(){super(),this.staticChildren={}}findStaticMatchingChild(t,r){let n=this.staticChildren[t.charAt(r)];return n===void 0||!n.matchPrefix(t,r)?null:n}getStaticChild(t,r=0){if(t.length===r)return this;let n=this.findStaticMatchingChild(t,r);return n?n.getStaticChild(t,r+n.prefix.length):null}createStaticChild(t){if(t.length===0)return this;let r=this.staticChildren[t.charAt(0)];if(r){let s=1;for(;s<r.prefix.length;s++)if(t.charCodeAt(s)!==r.prefix.charCodeAt(s)){r=r.split(this,s);break}return r.createStaticChild(t.slice(s))}let n=t.charAt(0);return this.staticChildren[n]=new wt(t),this.staticChildren[n]}},wt=class e extends Pt{constructor(t){super(),this.prefix=t,this.wildcardChild=null,this.parametricChildren=[],this.kind=Rt.STATIC,this._compilePrefixMatch()}getParametricChild(t){let r=t&&t.source,n=this.parametricChildren.find(s=>(s.regex&&s.regex.source)===r);return n||null}createParametricChild(t,r,n){let s=this.getParametricChild(t);return s?(s.nodePaths.add(n),s):(s=new Et(t,r,n),this.parametricChildren.push(s),this.parametricChildren.sort((i,o)=>i.isRegex?o.isRegex?i.staticSuffix===null?1:o.staticSuffix===null?-1:o.staticSuffix.endsWith(i.staticSuffix)?1:i.staticSuffix.endsWith(o.staticSuffix)?-1:0:-1:1),s)}getWildcardChild(){return this.wildcardChild}createWildcardChild(){return this.wildcardChild=this.getWildcardChild()||new vt,this.wildcardChild}split(t,r){let n=this.prefix.slice(0,r),s=this.prefix.slice(r);this.prefix=s,this._compilePrefixMatch();let i=new e(n);return i.staticChildren[s.charAt(0)]=this,t.staticChildren[n.charAt(0)]=i,i}getNextNode(t,r,n,s){let i=this.findStaticMatchingChild(t,r),o=0;if(i===null){if(this.parametricChildren.length===0)return this.wildcardChild;i=this.parametricChildren[0],o=1}this.wildcardChild!==null&&n.push({paramsCount:s,brotherPathIndex:r,brotherNode:this.wildcardChild});for(let a=this.parametricChildren.length-1;a>=o;a--)n.push({paramsCount:s,brotherPathIndex:r,brotherNode:this.parametricChildren[a]});return i}_compilePrefixMatch(){if(this.prefix.length===1){this.matchPrefix=()=>!0;return}let t=[];for(let r=1;r<this.prefix.length;r++){let n=this.prefix.charCodeAt(r);t.push(`path.charCodeAt(i + ${r}) === ${n}`)}this.matchPrefix=new Function("path","i",`return ${t.join(" && ")}`)}},Et=class extends Pt{constructor(t,r,n){super(),this.isRegex=!!t,this.regex=t||null,this.staticSuffix=r||null,this.kind=Rt.PARAMETRIC,this.nodePaths=new Set([n])}getNextNode(t,r){return this.findStaticMatchingChild(t,r)}},vt=class extends bt{constructor(){super(),this.kind=Rt.WILDCARD}getNextNode(){return null}};ni.exports={StaticNode:wt,ParametricNode:Et,WildcardNode:vt,NODE_TYPES:Rt}});var oi=E((Rd,ii)=>{"use strict";f();var $c=require("assert");function qe(){if(!(this instanceof qe))return new qe;this.store=new Map,this.maxMajor=0,this.maxMinors={},this.maxPatches={}}qe.prototype.set=function(e,t){if(typeof e!="string")throw new TypeError("Version should be a string");let[r,n,s]=e.split(".",3);if(isNaN(r))throw new TypeError("Major version must be a numeric value");return r=Number(r),n=Number(n)||0,s=Number(s)||0,r>=this.maxMajor&&(this.maxMajor=r,this.store.set("x",t),this.store.set("*",t),this.store.set("x.x",t),this.store.set("x.x.x",t)),n>=(this.maxMinors[r]||0)&&(this.maxMinors[r]=n,this.store.set(`${r}.x`,t),this.store.set(`${r}.x.x`,t)),s>=(this.maxPatches[`${r}.${n}`]||0)&&(this.maxPatches[`${r}.${n}`]=s,this.store.set(`${r}.${n}.x`,t)),this.store.set(`${r}.${n}.${s}`,t),this};qe.prototype.get=function(e){return this.store.get(e)};ii.exports={name:"version",mustMatchWhenDerived:!0,storage:qe,validate(e){$c(typeof e=="string","Version should be a string")}}});var ci=E((Td,ai)=>{"use strict";f();var Lc=require("assert");function Bc(){let e=new Map,t=[],r=new Map;return{get:n=>{let s=e.get(n);if(s)return s;if(t.length!==0){if(r.has(n))return r.get(n);for(let i of t)if(i.host.test(n))return r.set(n,i.value),i.value;r.set(n,void 0)}},set:(n,s)=>{if(n instanceof RegExp){let i=new RegExp(n.source,n.flags.replace(/[gy]/g,""));t.push({host:i,value:s}),r.clear()}else e.set(n,s)}}}ai.exports={name:"host",mustMatchWhenDerived:!1,storage:Bc,validate(e){Lc(typeof e=="string"||Object.prototype.toString.call(e)==="[object RegExp]","Host should be a string or a RegExp")}}});var ui=E((Ad,li)=>{"use strict";f();var kc=oi(),Uc=ci(),wr=require("assert"),Er=class{constructor(t){if(this.strategies={version:kc,host:Uc},this.strategiesInUse=new Set,this.asyncStrategiesInUse=new Set,t)for(let r of Object.values(t))this.addConstraintStrategy(r)}isStrategyUsed(t){return this.strategiesInUse.has(t)||this.asyncStrategiesInUse.has(t)}hasConstraintStrategy(t){let r=this.strategies[t];return r!==void 0?r.isCustom||this.isStrategyUsed(t):!1}addConstraintStrategy(t){if(wr(typeof t.name=="string"&&t.name!=="","strategy.name is required."),wr(t.storage&&typeof t.storage=="function","strategy.storage function is required."),wr(t.deriveConstraint&&typeof t.deriveConstraint=="function","strategy.deriveConstraint function is required."),this.strategies[t.name]&&this.strategies[t.name].isCustom)throw new Error(`There already exists a custom constraint with the name ${t.name}.`);if(this.isStrategyUsed(t.name))throw new Error(`There already exists a route with ${t.name} constraint.`);t.isCustom=!0,t.isAsync=t.deriveConstraint.length===3,this.strategies[t.name]=t,t.mustMatchWhenDerived&&this.noteUsage({[t.name]:t})}deriveConstraints(t,r,n){let s=this.deriveSyncConstraints(t,r);if(n===void 0)return s;this.deriveAsyncConstraints(s,t,r,n)}deriveSyncConstraints(t,r){}noteUsage(t){if(t){let r=this.strategiesInUse.size;for(let n in t){if(!Object.hasOwn(t,n))continue;this.strategies[n].isAsync?this.asyncStrategiesInUse.add(n):this.strategiesInUse.add(n)}r!==this.strategiesInUse.size&&this._buildDeriveConstraints()}}newStoreForConstraint(t){if(!this.strategies[t])throw new Error(`No strategy registered for constraint key ${t}`);return this.strategies[t].storage()}validateConstraints(t){for(let r in t){if(!Object.hasOwn(t,r))continue;let n=t[r];if(typeof n>"u")throw new Error("Can't pass an undefined constraint value, must pass null or no key at all");let s=this.strategies[r];if(!s)throw new Error(`No strategy registered for constraint key ${r}`);s.validate&&s.validate(n)}}deriveAsyncConstraints(t,r,n,s){let i=this.asyncStrategiesInUse.size;if(i===0){s(null,t);return}let o=!1;t=t||{};for(let a of this.asyncStrategiesInUse)this.strategies[a].deriveConstraint(r,n,(u,l)=>{if(!o){if(u!==null){o=!0,s(u);return}t[a]=l,--i===0&&s(null,t)}})}_buildDeriveConstraints(){if(this.strategiesInUse.size===0)return;let t=["return {"];for(let r of this.strategiesInUse){let n=this.strategies[r];n.isCustom?t.push(` ${n.name}: this.strategies.${r}.deriveConstraint(req, ctx),`):r==="version"?t.push(" version: req.headers['accept-version'],"):t.push(" host: req.headers.host || req.headers[':authority'],")}t.push("}"),this.deriveSyncConstraints=new Function("req","ctx",t.join(`
|
|
23
|
+
`)).bind(this)}};li.exports=Er});var fi=E((Dd,di)=>{"use strict";f();var Hc=["ACL","BIND","CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LINK","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCALENDAR","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","QUERY","REBIND","REPORT","SEARCH","SOURCE","SUBSCRIBE","TRACE","UNBIND","UNLINK","UNLOCK","UNSUBSCRIBE"];di.exports=Hc});var hi=E((Cd,pi)=>{"use strict";f();function mi(e,t){return e===50?t===53?"%":t===51?"#":t===52?"$":t===54?"&":t===66||t===98?"+":t===67||t===99?",":t===70||t===102?"/":null:e===51?t===65||t===97?":":t===66||t===98?";":t===68||t===100?"=":t===70||t===102?"?":null:e===52&&t===48?"@":null}function qc(e,t){let r=!1,n=!1,s="";for(let o=1;o<e.length;o++){let a=e.charCodeAt(o);if(a===37){let c=e.charCodeAt(o+1),u=e.charCodeAt(o+2);mi(c,u)===null?r=!0:(n=!0,c===50&&u===53&&(r=!0,e=e.slice(0,o+1)+"25"+e.slice(o+1),o+=2),o+=2)}else if(a===63||a===35||a===59&&t){s=e.slice(o+1),e=e.slice(0,o);break}}return{path:r?decodeURI(e):e,querystring:s,shouldDecodeParam:n}}function jc(e){let t=e.indexOf("%");if(t===-1)return e;let r="",n=t;for(let s=t;s<e.length;s++)if(e.charCodeAt(s)===37){let i=e.charCodeAt(s+1),o=e.charCodeAt(s+2),a=mi(i,o);r+=e.slice(n,s)+a,n=s+3}return e.slice(0,t)+r+e.slice(n)}pi.exports={safeDecodeURI:qc,safeDecodeURIComponent:jc}});var Ti=E((Md,xi)=>{"use strict";f();var _=require("assert"),Qc=Ps(),De=js(),xr=br(),{prettyPrintTree:Fc}=Ys(),{StaticNode:gi,NODE_TYPES:yi}=si(),Wc=ui(),_e=fi(),vr=yt(),{safeDecodeURI:Si,safeDecodeURIComponent:Rr}=hi(),bi=/^https?:\/\/.*?\//,Pe=/(\/:[^/()]*?)\?(\/?)/,Pi=/[.*+?^${}()|[\]\\]/g,wi=/\/\/+/g;if(!De(bi))throw new Error("the FULL_PATH_REGEXP is not safe, update this module");if(!De(Pe))throw new Error("the OPTIONAL_PARAM_REGEXP is not safe, update this module");if(!De(Pi))throw new Error("the ESCAPE_REGEXP is not safe, update this module");if(!De(wi))throw new Error("the REMOVE_DUPLICATE_SLASHES_REGEXP is not safe, update this module");function T(e){if(!(this instanceof T))return new T(e);e=e||{},this._opts=e,e.defaultRoute?(_(typeof e.defaultRoute=="function","The default route must be a function"),this.defaultRoute=e.defaultRoute):this.defaultRoute=null,e.onBadUrl?(_(typeof e.onBadUrl=="function","The bad url handler must be a function"),this.onBadUrl=e.onBadUrl):this.onBadUrl=null,e.buildPrettyMeta?(_(typeof e.buildPrettyMeta=="function","buildPrettyMeta must be a function"),this.buildPrettyMeta=e.buildPrettyMeta):this.buildPrettyMeta=Gc,e.querystringParser?(_(typeof e.querystringParser=="function","querystringParser must be a function"),this.querystringParser=e.querystringParser):this.querystringParser=t=>t.length===0?{}:Qc.parse(t),this.caseSensitive=e.caseSensitive===void 0?!0:e.caseSensitive,this.ignoreTrailingSlash=e.ignoreTrailingSlash||!1,this.ignoreDuplicateSlashes=e.ignoreDuplicateSlashes||!1,this.maxParamLength=e.maxParamLength||100,this.onMaxParamLength=e.onMaxParamLength||null,this.allowUnsafeRegex=e.allowUnsafeRegex||!1,this.constrainer=new Wc(e.constraints),this.useSemicolonDelimiter=e.useSemicolonDelimiter||!1,this.routes=[],this.trees=Object.create(null)}T.prototype.on=function(t,r,n,s,i){typeof n=="function"&&(s!==void 0&&(i=s),s=n,n={}),_(typeof r=="string","Path should be a string"),_(r.length>0,"The path could not be empty"),_(r[0]==="/"||r[0]==="*","The first character of a path should be `/` or `*`"),_(typeof s=="function","Handler should be a function");let o=r.match(Pe);if(o){_(r.length===o.index+o[0].length,"Optional Parameter needs to be the last parameter of the path");let u=r.replace(Pe,"$1$2"),l=r.replace(Pe,"$2")||"/";this.on(t,u,n,s,i),this.on(t,l,n,s,i);return}let a=r;this.ignoreDuplicateSlashes&&(r=xt(r)),this.ignoreTrailingSlash&&(r=Tt(r));let c=Array.isArray(t)?t:[t];for(let u of c)_(typeof u=="string","Method should be a string"),_(_e.includes(u),`Method '${u}' is not an http method.`),this._on(u,r,n,s,i,a)};T.prototype._on=function(t,r,n,s,i){let o={};n.constraints!==void 0&&(_(typeof n.constraints=="object"&&n.constraints!==null,"Constraints should be an object"),Object.keys(n.constraints).length!==0&&(o=n.constraints)),this.constrainer.validateConstraints(o),this.constrainer.noteUsage(o),this.trees[t]===void 0&&(this.trees[t]=new gi("/"));let a=r;if(a==="*"&&this.trees[t].prefix.length!==0){let d=this.trees[t];this.trees[t]=new gi(""),this.trees[t].staticChildren["/"]=d}let c=this.trees[t],u=c.prefix.length,l=[];for(let d=0;d<=a.length;d++){if(a.charCodeAt(d)===58&&a.charCodeAt(d+1)===58){d++;continue}let p=a.charCodeAt(d)===58&&a.charCodeAt(d+1)!==58,y=a.charCodeAt(d)===42;if(p||y||d===a.length&&d!==u){let b=a.slice(u,d);this.caseSensitive||(b=b.toLowerCase()),b=b.replaceAll("::",":"),b=b.replaceAll("%","%25"),c=c.createStaticChild(b)}if(p){let b=!1,S=!0,O="",I=[],ee=d+1;for(let P=ee;;P++){let ge=a.charCodeAt(P),Me=ge===40,j=ge===45||ge===46,G=ge===47||P===a.length;if(Me||j||G){let ae=a.slice(ee,P);if(l.push(ae),b=b||Me||j,Me){let ce=Ri(a,P),Ee=a.slice(P,ce+1);this.allowUnsafeRegex||_(De(new RegExp(Ee)),`The regex '${Ee}' is not safe!`),I.push(vi(Ee)),P=ce+1,S=!0}else I.push(S?"(.*?)":`(${O}|(?:(?!${O}).)*)`),S=!1;let Lt=P;for(;P<a.length;P++){let ce=a.charCodeAt(P);if(ce===47)break;if(ce===58)if(a.charCodeAt(P+1)===58)P++;else break}let te=a.slice(Lt,P);if(te&&(te=te.replaceAll("::",":"),te=te.replaceAll("%","%25"),I.push(O=Ei(te))),ee=P+1,G||a.charCodeAt(P)===47||P===a.length){let ce=b?"()"+te:te,Ee=a.slice(d,P);a=a.slice(0,d+1)+ce+a.slice(P),d+=ce.length;let Co=b?new RegExp("^"+I.join("")+"$"):null;c=c.createParametricChild(Co,te||null,Ee),u=d+1;break}}}}else if(y&&(l.push("*"),c=c.createWildcardChild(),u=d+1,d!==a.length-1))throw new Error("Wildcard must be the last character in the route")}this.caseSensitive||(a=a.toLowerCase()),a==="*"&&(a="/*");for(let d of this.routes){let p=d.opts.constraints||{};if(d.method===t&&d.pattern===a&&xr(p,o))throw new Error(`Method '${t}' already declared for route '${a}' with constraints '${JSON.stringify(o)}'`)}let m={method:t,path:r,pattern:a,params:l,opts:n,handler:s,store:i};this.routes.push(m),c.addRoute(m,this.constrainer)};T.prototype.hasRoute=function(t,r,n){return this.findRoute(t,r,n)!==null};T.prototype.findRoute=function(t,r,n={}){if(this.trees[t]===void 0)return null;let s=r,i=this.trees[t],o=i.prefix.length,a=[];for(let c=0;c<=s.length;c++){if(s.charCodeAt(c)===58&&s.charCodeAt(c+1)===58){c++;continue}let u=s.charCodeAt(c)===58&&s.charCodeAt(c+1)!==58,l=s.charCodeAt(c)===42;if(u||l||c===s.length&&c!==o){let m=s.slice(o,c);if(this.caseSensitive||(m=m.toLowerCase()),m=m.replaceAll("::",":"),m=m.replaceAll("%","%25"),i=i.getStaticChild(m),i===null)return null}if(u){let m=!1,d=!0,p="",y=[],b=c+1;for(let S=b;;S++){let O=s.charCodeAt(S),I=O===40,ee=O===45||O===46,P=O===47||S===s.length;if(I||ee||P){let ge=s.slice(b,S);if(a.push(ge),m=m||I||ee,I){let G=Ri(s,S),ae=s.slice(S,G+1);this.allowUnsafeRegex||_(De(new RegExp(ae)),`The regex '${ae}' is not safe!`),y.push(vi(ae)),S=G+1,d=!0}else y.push(d?"(.*?)":`(${p}|(?:(?!${p}).)*)`),d=!1;let Me=S;for(;S<s.length;S++){let G=s.charCodeAt(S);if(G===47)break;if(G===58)if(s.charCodeAt(S+1)===58)S++;else break}let j=s.slice(Me,S);if(j&&(j=j.replaceAll("::",":"),j=j.replaceAll("%","%25"),y.push(p=Ei(j))),b=S+1,P||s.charCodeAt(S)===47||S===s.length){let G=m?"()"+j:j,ae=s.slice(c,S);s=s.slice(0,c+1)+G+s.slice(S),c+=G.length;let Lt=m?new RegExp("^"+y.join("")+"$"):null;if(i=i.getParametricChild(Lt,j||null,ae),i===null)return null;o=c+1;break}}}}else if(l&&(a.push("*"),i=i.getWildcardChild(),o=c+1,c!==s.length-1))throw new Error("Wildcard must be the last character in the route")}this.caseSensitive||(s=s.toLowerCase());for(let c of this.routes){let u=c.opts.constraints||{};if(c.method===t&&c.pattern===s&&xr(u,n))return{handler:c.handler,store:c.store,params:c.params}}return null};T.prototype.hasConstraintStrategy=function(e){return this.constrainer.hasConstraintStrategy(e)};T.prototype.addConstraintStrategy=function(e){this.constrainer.addConstraintStrategy(e),this._rebuild(this.routes)};T.prototype.reset=function(){this.trees=Object.create(null),this.routes=[]};T.prototype.off=function(t,r,n){_(typeof r=="string","Path should be a string"),_(r.length>0,"The path could not be empty"),_(r[0]==="/"||r[0]==="*","The first character of a path should be `/` or `*`"),_(typeof n>"u"||typeof n=="object"&&!Array.isArray(n)&&n!==null,"Constraints should be an object or undefined.");let s=r.match(Pe);if(s){_(r.length===s.index+s[0].length,"Optional Parameter needs to be the last parameter of the path");let o=r.replace(Pe,"$1$2"),a=r.replace(Pe,"$2")||"/";this.off(t,o,n),this.off(t,a,n);return}this.ignoreDuplicateSlashes&&(r=xt(r)),this.ignoreTrailingSlash&&(r=Tt(r));let i=Array.isArray(t)?t:[t];for(let o of i)this._off(o,r,n)};T.prototype._off=function(t,r,n){_(typeof t=="string","Method should be a string"),_(_e.includes(t),`Method '${t}' is not an http method.`);function s(c){return t!==c.method||r!==c.path}function i(c){return s(c)||!xr(n,c.opts.constraints||{})}let o=n?i:s,a=this.routes.filter(o);this._rebuild(a)};T.prototype.lookup=function(t,r,n,s){if(typeof n=="function"&&(s=n,n=void 0),s===void 0){let i=this.constrainer.deriveConstraints(t,n),o=this.find(t.method,t.url,i);return this.callHandler(o,t,r,n)}this.constrainer.deriveConstraints(t,n,(i,o)=>{if(i!==null){s(i);return}try{let a=this.find(t.method,t.url,o),c=this.callHandler(a,t,r,n);s(null,c)}catch(a){s(a)}})};T.prototype.callHandler=function(t,r,n,s){return t===null?this._defaultRoute(r,n,s):s===void 0?t.handler(r,n,t.params,t.store,t.searchParams):t.handler.call(s,r,n,t.params,t.store,t.searchParams)};T.prototype.find=function(t,r,n){let s=this.trees[t];if(s===void 0)return null;r.charCodeAt(0)!==47&&(r=r.replace(bi,"/")),this.ignoreDuplicateSlashes&&(r=xt(r));let i,o,a;try{i=Si(r,this.useSemicolonDelimiter),r=i.path,o=i.querystring,a=i.shouldDecodeParam}catch{return this._onBadUrl(r)}this.ignoreTrailingSlash&&(r=Tt(r));let c=r;this.caseSensitive===!1&&(r=r.toLowerCase());let u=this.maxParamLength,l=s.prefix.length,m=[],d=r.length,p=[],y=!1;for(;;){if(l===d&&s.isLeafNode){let S=s.handlerStorage.getMatchingHandler(n);if(S!==null)return{handler:S.handler,store:S.store,params:S._createParamsObject(m),searchParams:this.querystringParser(o)}}let b=s.getNextNode(r,l,p,m.length);if(b===null){if(p.length===0)return y&&this.onMaxParamLength?this._onMaxParamLength(c):null;let S=p.pop();l=S.brotherPathIndex,m.splice(S.paramsCount),b=S.brotherNode}for(s=b;;){if(s.kind===yi.STATIC){l+=s.prefix.length;break}if(s.kind===yi.WILDCARD){let I=c.slice(l);a&&(I=Rr(I)),m.push(I),l=d;break}let S=c.indexOf("/",l);S===-1&&(S=d);let O=c.slice(l,S);if(a&&(O=Rr(O)),s.isRegex){let I=s.regex.exec(O);if(I===null){if(p.length===0)return y&&this.onMaxParamLength?this._onMaxParamLength(c):null;let P=p.pop();l=P.brotherPathIndex,m.splice(P.paramsCount),s=P.brotherNode;continue}let ee=!1;for(let P=1;P<I.length;P++)if((I[P]??"").length>u){ee=!0;break}if(ee){if(y=!0,p.length===0)return this.onMaxParamLength?this._onMaxParamLength(c):null;let P=p.pop();l=P.brotherPathIndex,m.splice(P.paramsCount),s=P.brotherNode;continue}for(let P=1;P<I.length;P++)m.push(I[P]??"")}else{if(O.length>u){if(y=!0,p.length===0)return this.onMaxParamLength?this._onMaxParamLength(c):null;let I=p.pop();l=I.brotherPathIndex,m.splice(I.paramsCount),s=I.brotherNode;continue}m.push(O)}l=S;break}}};T.prototype._rebuild=function(e){this.reset();for(let t of e){let{method:r,path:n,opts:s,handler:i,store:o}=t;this._on(r,n,s,i,o)}};T.prototype._defaultRoute=function(e,t,r){if(this.defaultRoute!==null)return r===void 0?this.defaultRoute(e,t):this.defaultRoute.call(r,e,t);t.statusCode=404,t.end()};T.prototype._onBadUrl=function(e){if(this.onBadUrl===null)return null;let t=this.onBadUrl;return{handler:(r,n,s)=>t(e,r,n),params:{},store:null}};T.prototype._onMaxParamLength=function(e){if(this.onMaxParamLength===null)return null;let t=this.onMaxParamLength;return{handler:(r,n,s)=>t(e,r,n),params:{},store:null}};T.prototype.prettyPrint=function(e={}){let t=e.method;e.buildPrettyMeta=this.buildPrettyMeta.bind(this);let r=null;if(t===void 0){let{version:n,host:s,...i}=this.constrainer.strategies;i[vr.name]=vr;let o=new T({...this._opts,constraints:i}),a=this.routes.map(c=>{let u={...c.opts.constraints,[vr.name]:c.method};return{...c,method:"MERGED",opts:{constraints:u}}});o._rebuild(a),r=o.trees.MERGED}else r=this.trees[t];return r==null?"(empty tree)":Fc(r,e)};for(let e in _e){if(!_e.hasOwnProperty(e))continue;let t=_e[e],r=t.toLowerCase();T.prototype[r]=function(n,s,i){return this.on(t,n,s,i)}}T.prototype.all=function(e,t,r){this.on(_e,e,t,r)};T.sanitizeUrlPath=function(t,r){let n=Si(t,r);return n.shouldDecodeParam?Rr(n.path):n.path};T.removeDuplicateSlashes=xt;T.trimLastSlash=Tt;xi.exports=T;function Ei(e){return e.replace(Pi,"\\$&")}function xt(e){return e.indexOf("//")!==-1?e.replace(wi,"/"):e}function Tt(e){return e.length>1&&e.charCodeAt(e.length-1)===47?e.slice(0,-1):e}function vi(e){return e.charCodeAt(1)===94&&(e=e.slice(0,1)+e.slice(2)),e.charCodeAt(e.length-2)===36&&(e=e.slice(0,e.length-2)+e.slice(e.length-1)),e}function Ri(e,t){let r=1;for(;t<e.length;){if(t++,e.charCodeAt(t)===92){t++;continue}if(e.charCodeAt(t)===41?r--:e.charCodeAt(t)===40&&r++,!r)return t}throw new TypeError('Invalid regexp expression in "'+e+'"')}function Gc(e){return e?e.store?Object.assign({},e.store):{}:{}}});function L(e,t,r=200){let n=Tr.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 B(e,t,r=200){let n=Tr.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 Oe(e,t=204){e.headersSent||(e.statusCode=t,e.setHeader("Content-Length",0)),e.end()}function Ii(e,t){B(e,t.message,t.status)}var Tr,oe=D(()=>{"use strict";f();Tr=require("buffer")});async function _i(e,t){let r;try{r=await(0,Ai.json)(e)}catch{return B(t,"Invalid input",400),null}let{output:n,success:s}=(0,k.safeParse)(zc,r,{abortEarly:!0});return s?n:(B(t,"Invalid input",400),null)}var Ai,k,zc,Di=D(()=>{"use strict";f();Ai=require("stream/consumers"),k=require("valibot");oe();zc=(0,k.object)({tags:(0,k.union)([(0,k.pipe)((0,k.array)((0,k.string)()),(0,k.minLength)(1)),(0,k.literal)("all")])})});async function _r(e){let r=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}function Ci(e,t){let r=e.schemaHash;if(r==null)return L(t,{EngineNotStarted:{reason:"SchemaMissing"}},404),null;let n=It.get(r);return n==null?(L(t,{EngineNotStarted:{reason:"SchemaMissing"}},404),null):{schemaHash:r,schemas:n}}async function Ni(e,t,r){let n=Ar.Buffer.from(e,"base64").toString("utf8"),s=Kc(n,t.toString());r&&console.log("[Accelerate] schema with override:",s);let i=await _r(s);return{base64Override:Ar.Buffer.from(s,"utf8").toString("base64"),overrideHash:i}}function Kc(e,t){let r=Jc(e);if(!r)throw new Error("No datasource block found in schema.");let n=e.slice(r.openBraceIndex+1,r.closeBraceIndex),s=Zc(n,t,rl(e,r.openBraceIndex));return`${e.slice(0,r.openBraceIndex+1)}${s}${e.slice(r.closeBraceIndex)}`}function Jc(e){let t="datasource";for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="/"&&e[r+1]==="/"){r=Dr(e,r+2);continue}if(n==="/"&&e[r+1]==="*"){r=Or(e,r+2);continue}if(n==='"'){r=Cr(e,r+1);continue}if(e.startsWith(t,r)&&!Oi(e[r-1])&&!Oi(e[r+t.length])){let s=Yc(e,r+t.length,"{");if(s===-1)return null;let i=Xc(e,s);return i===-1?null:{closeBraceIndex:i,openBraceIndex:s}}}return null}function Yc(e,t,r){for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=Dr(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=Or(e,n+2);continue}if(s==='"'){n=Cr(e,n+1);continue}if(s===r)return n}return-1}function Xc(e,t){let r=0;for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=Dr(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=Or(e,n+2);continue}if(s==='"'){n=Cr(e,n+1);continue}if(s==="{"){r+=1;continue}if(s==="}"&&(r-=1,r===0))return n}return-1}function Dr(e,t){let r=t;for(;r<e.length&&e[r]!==`
|
|
24
|
+
`;)r+=1;return r}function Or(e,t){let r=e.indexOf("*/",t);return r===-1?e.length:r+1}function Cr(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 Oi(e){return e!=null&&/[A-Za-z0-9_]/.test(e)}function Zc(e,t,r){let n=`"${sl(t)}"`,s=el(e);for(let[m,d]of s.entries()){let{comment:p,code:y}=Mi(d.line),b=y.match(/^(\s*)url(\s*)=(\s*).*/);if(b)return s[m]={line:`${b[1]}url${b[2]}=${b[3]}${n}${p}`,terminator:d.terminator},Ir(s)}let i=nl(e),o=tl(s,r),a=`${o}url = ${n}`;if(!e.includes(`
|
|
25
|
+
`)&&!e.includes("\r")){let m=e.trim();return m.length===0?`${i}${a}${i}${r}`:`${i}${o}${m}${i}${a}${i}${r}`}let c=s.at(-1);if(c&&c.terminator===""&&/^\s*$/.test(c.line))return`${Ir(s.slice(0,-1))}${a}${i}${r}`;let u=Ir(s),l=u.endsWith(`
|
|
26
|
+
`)||u.endsWith("\r")?"":i;return`${u}${l}${a}${i}${r}`}function el(e){let t=[],r=0;for(let n=0;n<e.length;n+=1){if(e[n]==="\r"&&e[n+1]===`
|
|
5
27
|
`){t.push({line:e.slice(r,n),terminator:`\r
|
|
6
28
|
`}),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
|
|
8
|
-
`,t)+1,n=r;for(;e[n]===" "||e[n]===" ";)n+=1;return e.slice(r,n)}function
|
|
29
|
+
`||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 Ir(e){return e.map(t=>`${t.line}${t.terminator}`).join("")}function Mi(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 tl(e,t){for(let r of e){let{code:n}=Mi(r.line),s=n.match(/^([ \t]+)[A-Za-z_][A-Za-z0-9_]*\s*=/);if(s?.[1])return s[1]}return`${t}${Vc}`}function rl(e,t){let r=e.lastIndexOf(`
|
|
30
|
+
`,t)+1,n=r;for(;e[n]===" "||e[n]===" ";)n+=1;return e.slice(r,n)}function nl(e){return e.includes(`\r
|
|
9
31
|
`)?`\r
|
|
10
32
|
`:`
|
|
11
|
-
`}function
|
|
12
|
-
`).find(
|
|
13
|
-
Received data: ${l}`));n({childProcess:
|
|
33
|
+
`}function sl(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}var Ar,It,Vc,$i=D(()=>{"use strict";f();Ar=require("buffer");oe();It=new Map;Vc=" "});function je(e,t){let r=e[t];return Array.isArray(r)?r.at(-1):r}var Nr=D(()=>{"use strict";f()});function Bi(e,t){let r=(e.method??"GET").toUpperCase(),n=`${t.origin}${e.url??"/"}`,s={headers:ol(e.headers),method:r};return il.has(r)||(s.body=Mr.Readable.toWeb(e),s.duplex="half"),new Request(n,s)}async function ki(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,Li.pipeline)(Mr.Readable.fromWeb(e.body),t)}function ol(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 Mr,Li,il,Ui=D(()=>{"use strict";f();Mr=require("stream"),Li=require("stream/promises"),il=new Set(["GET","HEAD"])});var ji={};$e(ji,{createHTTPServer:()=>cl,wrap:()=>z});function z(e,t){return async function(n,s,i){let o=t?Date.now():0;t&&s.once("finish",()=>{let a=Date.now()-o;console.log("[Accelerate]",`<-- ${n.method??"?"} ${n.url??""} ${s.statusCode} ${a}ms`)});try{await e(n,s,i)}catch(a){try{al(a,s,n,t)}catch(c){t&&console.error("[Accelerate]","error while handling handler error",c),s.destroyed||s.destroy()}}}}function al(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 H){Ii(t,e);return}console.error("[Accelerate]",e);try{Oe(t,500)}catch(s){n&&console.error("[Accelerate]","failed to write 500 response (client likely disconnected)",s),t.destroy()}}function cl(e){let{router:t}=e;return{async listen(r){let n=(0,Hi.createServer)((o,a)=>{t.lookup(o,a)}),i=(await ll(n,r)).port;return n.on("error",o=>{console.error("[Accelerate]",o)}),{async close(){await(0,qi.promisify)(n.close.bind(n))()},port:i,url:`http://localhost:${i}`}}}}function ll(e,t){return new Promise((r,n)=>{let s=o=>{if(e.off("listening",i),typeof o=="object"&&o!==null&&"code"in o&&o.code==="EADDRINUSE"){n(new V(t));return}n(o)},i=()=>{e.off("error",s),r(e.address())};e.once("error",s),e.once("listening",i),e.listen(t)})}var Hi,qi,At=D(()=>{"use strict";f();Hi=require("http"),qi=require("util");Be();Ke();oe()});function _t(e){return{traceparent:je(e.headers,"traceparent"),"X-capture-telemetry":je(e.headers,"x-capture-telemetry")}}var Qi=D(()=>{"use strict";f();Nr()});async function Wi(e,t){let r;try{r=await(0,Fi.json)(e)}catch{return L(t,{EngineNotStarted:{reason:"InvalidRequest",issues:[]}},400),null}let{issues:n,output:s,success:i}=(0,R.safeParse)(ul,r,{abortEarly:!0});return i?s:(L(t,{EngineNotStarted:{reason:"InvalidRequest",issues:n}},400),null)}function Gi(e,t){let{output:r,success:n}=(0,R.safeParse)(dl,e);return n?r:(L(t,{EngineMalfunction:{}},500),null)}var Fi,R,ul,dl,zi=D(()=>{"use strict";f();Fi=require("stream/consumers"),R=require("valibot");oe();ul=(0,R.object)({isolation_level:(0,R.optional)((0,R.string)()),max_wait:(0,R.pipe)((0,R.number)(),(0,R.integer)(),(0,R.minValue)(0)),timeout:(0,R.pipe)((0,R.number)(),(0,R.integer)(),(0,R.minValue)(0))});dl=(0,R.looseObject)({id:(0,R.union)([(0,R.string)(),(0,R.number)()])})});function Vi(e){let t,r,n=new Promise((o,a)=>{t=o,r=a}),s=o=>{s=i=null,r(o),e?.onRejected?.(o),e?.onFulfilled?.()},i=o=>{i=s=null,t(o),e?.onResolved?.(o),e?.onFulfilled?.()};return{isFulfilled:()=>i===s,promise:n,reject:o=>s?.(o),resolve:o=>i?.(o)}}var Ki=D(()=>{"use strict";f()});var Lr={};$e(Lr,{Engine:()=>$r,handleEngineError:()=>pl});function pl(e,t){if(console.error(e),e instanceof Qe){L(t,{EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:e.message}}}},500);return}if(e instanceof Ce){B(t,e.responseBody,e.statusCode);return}Oe(t,500)}var Yi,Xi,Zi,eo,to,ro,fl,ml,Ji,$r,Qe,Ce,Br=D(()=>{"use strict";f();Yi=require("child_process"),Xi=require("events"),Zi=require("fs/promises"),eo=require("path"),to=require("timers/promises");Ki();ro=require("std-env");Te();oe();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:fl,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:ml,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:Ji}=ro.process.env),$r=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 i=new e(t);return e.#r.set(n,i),r&&console.debug("[Query Engine] starting...",t),await i.start(),r&&console.debug("[Query Engine] started!"),i}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,i])=>{try{await i.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.#a(t,r,"commit")}async request(t,r){let{url:n}=await this.start(),s=this.#n(r),i=await fetch(n,{body:typeof t=="string"?t:JSON.stringify(t),headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await Ce.fromResponse(i);return await i.text()}async rollbackTransaction(t,r){return await this.#a(t,r,"rollback")}async startTransaction(t,r){let{url:n}=await this.start(),s=this.#n(r),i=await fetch(`${n}/transaction/start`,{body:JSON.stringify(t),headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await Ce.fromResponse(i);return await i.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:t,reject:r,resolve:n}=Vi();this.#t=t;let s=ml||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",s);let{proxySignals:i}=await import("foreground-child/proxy-signals"),o=(0,Yi.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});i(o),o.stderr.setEncoding("utf8"),o.stdout.setEncoding("utf8");let a=l=>{let m=l.split(`
|
|
34
|
+
`).find(b=>b.includes("Started query engine http server"));if(!m)return;o.stdout.removeListener("data",a);let{fields:d}=JSON.parse(m);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.
|
|
35
|
+
Received data: ${l}`));n({childProcess:o,url:`http://${p}:${y}`})},c=l=>{this.#t=null,r(new Qe(String(l))),o.removeListener("exit",u),o.kill()};o.once("error",c);let u=(l,m)=>{this.#t=null,r(new Qe(`Query Engine exited with code ${l} and signal ${m}`))};return o.once("exit",u),o.stdout.on("data",a),this.#e.debug&&(o.stderr.on("data",console.error.bind(console,"[Query Engine]")),o.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,Xi.once)(t,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let t=await this.#i();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",t);let r=mn(this.#e.clientVersion,t);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,Zi.mkdir)(r,{recursive:!0});let{binaryTarget:n}=this.#e.platform,s=n==="windows"?".exe":"",i=(0,eo.join)(r,`query-engine-${n}${s}`);return this.#e.debug&&console.debug("[Query Engine] binary path",i),(fl==="1"||await Re(i)===!1)&&await this.#o({commitHash:t,extension:s,engineBinaryPath:i}),i}async#i(){let t=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!t.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${t.status}`);let 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#o(t){let{commitHash:r,extension:n,engineBinaryPath:s}=t,{binaryTarget:i}=this.#e.platform,o=`https://binaries.prisma.sh/all_commits/${r}/${i}/query-engine${n}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",o);let a=await fetch(o);if(!a.ok)throw new Error(`Couldn't download engine. URL: ${o}, status code: ${a.status}`);Ji&&await(0,to.setTimeout)(Number(Ji)),await pn(await a.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#a(t,r,n){let{url:s}=await this.#t,i=this.#n(r),o=await fetch(`${s}/transaction/${t}/${n}`,{headers:{...i,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await Ce.fromResponse(o);try{return await o.json()}catch{return{}}}};Qe=class extends Error{name="EngineStartError"},Ce=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 no={};$e(no,{getQueryPlanExecutorServer:()=>hl,queryPlanExecutorVersion:()=>so.version});async function hl(e){return kr===void 0&&(kr=await he.Server.create({databaseUrl:e.db.connectionString,maxResponseSize:(0,he.parseSize)("128 MiB"),queryTimeout:(0,he.parseDuration)("PT5M"),maxTransactionTimeout:(0,he.parseDuration)("PT5M"),maxTransactionWaitTime:(0,he.parseDuration)("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:e.debug?"debug":"off"}})),kr}var he,so,kr,io=D(()=>{"use strict";f();he=require("@prisma/query-plan-executor"),so=require("@prisma/query-plan-executor")});var lo={};$e(lo,{registerAccelerateRoutes:()=>Sl});function Dt(){return oo??=Promise.resolve().then(()=>(Br(),Lr)),oo}function gl(){return co??=Promise.resolve().then(()=>(io(),no)),co}async function yl(){return ao??=import("@prisma/get-platform").then(async({default:e})=>await e.getPlatformInfo()),await ao}function Sl(e,t,r){e.on("POST","/invalidate",z(async(s,i)=>{ye(s,t),await _i(s,i)!==null&&Oe(i,200)},r));for(let s of["/:clientVersion/:schemaHash/graphql","/:clientVersion/:schemaHash/itx/:transactionId/graphql"])e.on("POST",s,z(async(i,o,a)=>{ye(i,t);try{let c=await Ur(o,t,a);if(c===null)return;let u=await(0,Hr.text)(i),l=a.transactionId,m=await c.request(u,{..._t(i),"X-transaction-id":l});B(o,m)}catch(c){let{handleEngineError:u}=await Dt();u(c,o)}},r));for(let s of["commit","rollback"])e.on("POST",`/:clientVersion/:schemaHash/itx/:transactionId/${s}`,z(async(i,o,a)=>{ye(i,t);try{let c=await Ur(o,t,a);if(c===null)return;let u=a.transactionId;if(u==null){L(o,{EngineMalfunction:{}},500);return}let l=`${s}Transaction`,m=await c[l](u,_t(i));L(o,m)}catch(c){let{handleEngineError:u}=await Dt();u(c,o)}},r));e.on("PUT","/:clientVersion/:schemaHash/schema",z(async(s,i,o)=>{ye(s,t);let a=await(0,Hr.text)(s);if(!a){B(i,"Missing schema",400);return}let c=o.schemaHash;if(c==null){B(i,"Missing schema hash",400);return}let u=It.get(c);if(u==null){if(c!==await _r(a)){B(i,"Schema hash mismatch",400);return}let l=await Ni(a,t.db.prismaORMConnectionString,t.debug);It.set(c,{base64Original:a,...l}),B(i,c);return}if(a!==u.base64Original){B(i,"Schema mismatch",400);return}B(i,c)},r)),e.on("POST","/:clientVersion/:schemaHash/transaction/start",z(async(s,i,o)=>{ye(s,t);let a=await Wi(s,i);if(a!==null)try{let c=await Ur(i,t,o);if(c===null)return;let u=await c.startTransaction(a,_t(s)),l=Gi(u,i);if(l===null)return;let{id:m}=l,d=o.clientVersion,p=o.schemaHash;L(i,{...u,"data-proxy":{endpoint:`http://localhost:${t.port}/${d}/${p}/itx/${m}`}})}catch(c){let{handleEngineError:u}=await Dt();u(c,i)}},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,i]of n)e.on(s,i,z(async(o,a)=>{ye(o,t);let{getQueryPlanExecutorServer:c,queryPlanExecutorVersion:u}=await gl(),l=je(o.headers,"prisma-engine-hash");if(l!=="0.0.0"&&l!==u)throw new H(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 m=await c(t),d=Bi(o,{origin:`http://localhost:${t.port}`}),p=await m.fetch(d);await ki(p,a)},r))}async function Ur(e,t,r){let{Engine:n}=await Dt(),s=Ci(r,e);if(s===null)return null;let{base64Override:i,overrideHash:o}=s.schemas;return await n.get({base64Schema:i,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||r.clientVersion||"",debug:t.debug,platform:await yl(),schemaHash:o})}var Hr,oo,ao,co,uo=D(()=>{"use strict";f();Hr=require("stream/consumers");Bt();Di();$i();Nr();Ke();Ui();oe();At();Qi();zi()});var fo={};$e(fo,{registerUtilityRoutes:()=>bl});function bl(e,t,r){e.on("POST","/database/dump",z(async(n,s)=>{await t.db.dump(t.databaseDumpPath),L(s,{dumpPath:t.databaseDumpPath},201)},r)),e.on("GET","/health",z((n,s)=>{L(s,{name:t.name})},r))}var mo=D(()=>{"use strict";f();oe();At()});var tu={};module.exports=ko(tu);f();var Oo=require("timers/promises");f();f();Bt();f();var at=require("net"),zn=require("path"),Vn=require("pathe/utils");Te();Be();f();var Yt=require("perf_hooks"),Dn=require("@electric-sql/pglite");f();var En=require("buffer"),bn=500,Pn=/(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+)/,Xo=new RegExp(`(?:${Pn.source}\\.)*${Pn.source}`),Zo=new RegExp(`(?:FROM|JOIN|UPDATE|INTO|TABLE)\\s+(${Xo.source})`,"gi"),ea=/"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|(\w+)/g,wn=/prismaQuery='([^']+)'/,ta=new Set([de(`
|
|
14
36
|
select b.oid, b.typarray
|
|
15
37
|
from pg_catalog.pg_type a
|
|
16
38
|
left join pg_catalog.pg_type b on b.oid = a.typelem
|
|
17
39
|
where a.typcategory = $1
|
|
18
40
|
group by b.oid, b.typarray
|
|
19
41
|
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")]),ps=[/^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 gs(e){let t=new Set;for(let r of e.matchAll(ls)){let n=r[1];if(!n)continue;let s;for(let o of n.matchAll(ds))s=o[1]??o[2]??o[3]??o[4];s&&!s.startsWith("pg_")&&t.add(s)}return Array.from(t)}function fs(e){return ms.has(e)?!0:ps.some(t=>t.test(e))}function ir(e){if(fs(q(e)))return null;let t=gs(e);return t.length===0&&/\bpg_\w+/i.test(e)?null:t}function ze(e){if(Array.isArray(e))return e.map(ze);if(e!==null&&typeof e=="object"){let t=e;return t.$type==="Param"?"<<redacted>>":Object.fromEntries(Object.entries(t).map(([r,n])=>[r,ze(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=ze(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=hs(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 hs(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 be=new WeakMap;function mr(e){let t=be.get(e);if(t&&!t.closed)return t.bridge;let r=ys(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,be.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=Ss(n,s),c=ws(o);bs(i,c);let u=Ps(i,c);if(!u)return await n.originalEnqueue(s,o,a);let l={commandTags:[],dataRowCount:0},f=new dr.protocol.Parser,d=Je.performance.now(),p=await n.originalEnqueue(s,o,E=>{f.parse(E,te=>{Ds(l,te)}),a(E)}),y=Math.max(0,Je.performance.now()-d);return As(n,{applicationName:u.applicationName,durationMs:y,query:u.query,responseStats:l}),p},be.set(e,n),n.bridge}async function pr(e){await be.get(e)?.bridge.close()}function ys(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 Ss(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 bs(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 Ps(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 ws(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 Es(t)}if(t.length<5)return null;switch(String.fromCharCode(t[0]??0)){case"Q":return vs(t);case"P":return Rs(t);case"B":return Ts(t);case"E":return xs(t);case"C":return Is(t);default:return null}}function Es(e){let t=8,r=null;for(;t<e.length-1;){let n=$(e,t);if(!n||n.value==="")break;t=n.nextOffset;let s=$(e,t);if(!s)break;t=s.nextOffset,n.value==="application_name"&&(r=s.value)}return{applicationName:r,kind:"startup"}}function vs(e){let t=$(e,5);return t?{kind:"query",query:t.value}:null}function Rs(e){let t=$(e,5);if(!t)return null;let r=$(e,t.nextOffset);return r?{kind:"parse",query:r.value,statementName:t.value}:null}function Ts(e){let t=$(e,5);if(!t)return null;let r=$(e,t.nextOffset);return r?{kind:"bind",portalName:t.value,statementName:r.value}:null}function xs(e){let t=$(e,5);return t?{kind:"execute",portalName:t.value}:null}function Is(e){if(e.length<7)return null;let t=e[5];if(t===void 0)return null;let r=$(e,6);return r?{kind:"close",name:r.value,target:t===80?"portal":"statement"}:null}function $(e,t){let r=e.indexOf(0,t);return r===-1?null:{nextOffset:r+1,value:e.toString("utf8",t,r)}}function Ds(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 As(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:_s(t.responseStats),tables:n,timestamp:new Date().toISOString()};for(let a of e.subscribers)a([o])}function _s(e){let t=e.commandTags.reduce((r,n)=>r+Os(n),0);return Math.max(t,e.dataRowCount)}function Os(e){let t=e.trim().split(/\s+/).at(-1);return!t||!/^\d+$/.test(t)?0:Number(t)}m();var F=require("fs"),H=require("fs/promises"),fr=require("module"),hr=require("path"),k=require("url"),Ns=(0,fr.createRequire)(h),Ms=["initdb.wasm","pglite.data","pglite.wasm"],Xe="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"},Bs=[...Ms.map(e=>({fileName:e,kind:"core",name:e})),{fileName:Xe,kind:"core",name:Xe},...Object.entries(yr).map(([e,t])=>({fileName:t,kind:"extension",name:e}))],Ee=new Map,Ls=Symbol.for("@prisma/dev/bundled-pglite-runtime-asset-sources"),Pe=null;async function Ze(){await Fs();let e=Sr();if(e)return await Us(e),await $s(e);let t=qs(),r=t.href,n=Ee.get(r);return n||(n=ks(t),Ee.set(r,n)),await n}async function $s(e){let t=`bundled:${e.wasmModule.href}:${e.fsBundle.href}`,r=Ee.get(t);return r||(r=Cs(e),Ee.set(t,r)),await r}async function ks(e){let t=ve(new URL("./runtime-assets/",h)),[r,n,s]=await Promise.all([(0,H.readFile)(we("pglite.data",e,t)),(0,H.readFile)(we(Xe,e,t)),(0,H.readFile)(we("pglite.wasm",e,t))]),o=br();return{extensions:Object.fromEntries(Object.entries(yr).map(([a,i])=>[a,we(i,e,t)])),fsBundle:new Blob([Uint8Array.from(r)]),loadDataDir:new Blob([Uint8Array.from(n)]),wasmModule:await o.compile(s)}}async function Cs(e){let[t,r,n]=await Promise.all([Ye(e.fsBundle),Ye(e.loadDataDir),Ye(e.wasmModule)]),s=br();return{extensions:e.extensions,fsBundle:new Blob([Uint8Array.from(t)]),loadDataDir:new Blob([Uint8Array.from(r)]),wasmModule:await s.compile(n)}}async function Us(e){if(e.initdbWasm.protocol!=="file:")return;let t=new URL("initdb.wasm",ve(new URL("./",e.initdbWasm))),r=(0,k.fileURLToPath)(t);(0,F.existsSync)(r)||await(0,H.copyFile)((0,k.fileURLToPath)(e.initdbWasm),r)}function ve(e){return e instanceof URL?gr(e):gr((0,k.pathToFileURL)(e))}function gr(e){return e.href.endsWith("/")?e:new URL(`${e.href}/`)}function Qs(){let e=Ns.resolve("@electric-sql/pglite");return ve((0,hr.dirname)(e))}function qs(){let e=ve(new URL("./",h));if(Hs(e))return e;if(Ws())return Qs();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 Bs.every(t=>(0,F.existsSync)((0,k.fileURLToPath)(new URL(t.fileName,e))))}function Sr(){return globalThis[Ls]??null}async function Fs(){!Gs()||Sr()||(Pe||(Pe=import("./runtime-assets-manifest.bun.js").then(()=>{}).catch(e=>{throw Pe=null,e})),await Pe)}function Ws(){let e=(0,k.fileURLToPath)(new URL("../package.json",h));if(!(0,F.existsSync)(e))return!1;try{return JSON.parse((0,F.readFileSync)(e,"utf8")).name==="@prisma/dev"}catch{return!1}}function Gs(){return typeof globalThis.Bun<"u"}function br(){let e=globalThis.WebAssembly;if(!e)throw new Error("WebAssembly is not available in this runtime.");return e}async function Ye(e){if(e.protocol==="file:")return await(0,H.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 we(e,t,r){let n=new URL(e,t);if((0,F.existsSync)((0,k.fileURLToPath)(n)))return n;if(r){let s=new URL(e,r);if((0,F.existsSync)((0,k.fileURLToPath)(s)))return s}return n}m();var rt=require("@electric-sql/pglite"),M="_prisma_dev_wal",tt="events",Er="install_all_triggers",Pr="capture_event",wr="prisma_dev_wal_capture",oe=new WeakMap,js=new Set(["ALTER","COMMIT","COPY","CREATE","DELETE","DROP","INSERT","MERGE","TRUNCATE","UPDATE"]);async function nt(e,t){let r=oe.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,oe.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&&Rr(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,oe.set(e,o),await Tr(o,e),o.bridge}async function vr(e){let t=oe.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 Rr(e){if(e.length===0)return!1;let t=[];return new rt.protocol.Parser().parse(e,n=>{t.push(n)}),st(t)}async function Tr(e,t){e.ensureInfrastructurePromise??=ot(e,t,async()=>{await t.exec(`CREATE SCHEMA IF NOT EXISTS "${M}"`),await t.exec(`
|
|
21
|
-
CREATE TABLE IF NOT EXISTS "${
|
|
42
|
+
`),de('GRANT "pg_write_all_data" TO "prisma_application"'),de("SELECT SUM(reads)::BIGINT AS reads, SUM(writes)::BIGINT AS writes, SUM(COALESCE(extends, $1))::BIGINT AS extends FROM pg_stat_io"),de("SELECT pg_database_size(current_database())::BIGINT, SUM(pg_total_relation_size(relid))::BIGINT AS pg_total_relation_size FROM pg_stat_user_tables"),de("SELECT COUNT(*) AS cnt FROM pg_stat_activity WHERE pid <> pg_backend_pid() and xact_start notnull")]),ra=[/^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 vn(){return{generatedAt:Date.now(),queries:[]}}function de(e){return e.replace(/\s+/g," ").trim()}function Rn(e){return _n(de(e))}function xn(e){if(!e?.action||!e.model&&/raw/i.test(e.action))return null;let t=e.payload?_n(JSON.stringify(e.payload)):"0";return`${e.model??""}.${e.action}:${t}`}function na(e){let t=new Set;for(let r of e.matchAll(Zo)){let n=r[1];if(!n)continue;let s;for(let i of n.matchAll(ea))s=i[1]??i[2]??i[3]??i[4];s&&!s.startsWith("pg_")&&t.add(s)}return Array.from(t)}function sa(e){return ta.has(e)?!0:ra.some(t=>t.test(e))}function Tn(e){if(sa(de(e)))return null;let t=na(e);return t.length===0&&/\bpg_\w+/i.test(e)?null:t}function Jt(e){if(Array.isArray(e))return e.map(Jt);if(e!==null&&typeof e=="object"){let t=e;return t.$type==="Param"?"<<redacted>>":Object.fromEntries(Object.entries(t).map(([r,n])=>[r,Jt(n)]))}return e}function In(e){let t=e.match(wn);if(!t?.[1])return{cleanedSql:de(e),prismaQueryInfo:null};let r=e.replace(wn,"");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 i=n.slice(0,s),o=n.slice(s+1),a=i.indexOf("."),c=a===-1?void 0:i.slice(0,a),u=a===-1?i:i.slice(a+1);if(!u)return{cleanedSql:r,prismaQueryInfo:null};let l;try{l=Jt(JSON.parse(En.Buffer.from(o,"base64url").toString("utf8")))}catch{l=void 0}return{cleanedSql:r,prismaQueryInfo:{action:u,isRaw:!1,model:c,payload:l}}}function An(e,t={}){let r=new Set(t.excludeApplications??[]),n=ia(t.limit),s=typeof t.since=="number"&&Number.isFinite(t.since)?t.since:null,i=new Map;for(let a of e){if(a.applicationName&&r.has(a.applicationName))continue;let c=Date.parse(a.timestamp);if(!Number.isFinite(c))continue;let u=`${a.queryId}:${a.groupKey??""}`,l=i.get(u);if(!l){i.set(u,{count:1,duration:a.durationMs,groupKey:a.groupKey,id:u,lastSeen:c,maxDurationMs:a.durationMs,minDurationMs:a.durationMs,prismaQueryInfo:a.prismaQueryInfo,query:a.query,queryId:a.queryId,reads:a.reads,rowsReturned:a.rowsReturned,tables:a.tables,totalDurationMs:a.durationMs});continue}l.count+=1,l.lastSeen=Math.max(l.lastSeen,c),l.maxDurationMs=Math.max(l.maxDurationMs??a.durationMs,a.durationMs),l.minDurationMs=Math.min(l.minDurationMs??a.durationMs,a.durationMs),l.reads+=a.reads,l.rowsReturned+=a.rowsReturned,l.totalDurationMs+=a.durationMs,l.duration=l.totalDurationMs/l.count,!l.prismaQueryInfo&&a.prismaQueryInfo&&(l.prismaQueryInfo=a.prismaQueryInfo),l.tables.length===0&&a.tables.length>0&&(l.tables=a.tables)}let o=Array.from(i.values()).filter(a=>s===null||a.lastSeen>=s).sort((a,c)=>c.lastSeen-a.lastSeen).slice(0,n).map(({totalDurationMs:a,...c})=>c);return{generatedAt:Date.now(),queries:o}}function ia(e){return typeof e=="number"&&Number.isInteger(e)&&Number.isSafeInteger(e)&&e>0?Math.min(e,bn):bn}function _n(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 tt=new WeakMap;function On(e){let t=tt.get(e);if(t&&!t.closed)return t.bridge;let r=oa(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,tt.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,i,o)=>{let a=aa(n,s),c=ua(i);ca(a,c);let u=la(a,c);if(!u)return await n.originalEnqueue(s,i,o);let l={commandTags:[],dataRowCount:0},m=new Dn.protocol.Parser,d=Yt.performance.now(),p=await n.originalEnqueue(s,i,b=>{m.parse(b,S=>{ya(l,S)}),o(b)}),y=Math.max(0,Yt.performance.now()-d);return Sa(n,{applicationName:u.applicationName,durationMs:y,query:u.query,responseStats:l}),p},tt.set(e,n),n.bridge}async function Cn(e){await tt.get(e)?.bridge.close()}function oa(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 aa(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 ca(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 la(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 ua(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 da(t)}if(t.length<5)return null;switch(String.fromCharCode(t[0]??0)){case"Q":return fa(t);case"P":return ma(t);case"B":return pa(t);case"E":return ha(t);case"C":return ga(t);default:return null}}function da(e){let t=8,r=null;for(;t<e.length-1;){let n=re(e,t);if(!n||n.value==="")break;t=n.nextOffset;let s=re(e,t);if(!s)break;t=s.nextOffset,n.value==="application_name"&&(r=s.value)}return{applicationName:r,kind:"startup"}}function fa(e){let t=re(e,5);return t?{kind:"query",query:t.value}:null}function ma(e){let t=re(e,5);if(!t)return null;let r=re(e,t.nextOffset);return r?{kind:"parse",query:r.value,statementName:t.value}:null}function pa(e){let t=re(e,5);if(!t)return null;let r=re(e,t.nextOffset);return r?{kind:"bind",portalName:t.value,statementName:r.value}:null}function ha(e){let t=re(e,5);return t?{kind:"execute",portalName:t.value}:null}function ga(e){if(e.length<7)return null;let t=e[5];if(t===void 0)return null;let r=re(e,6);return r?{kind:"close",name:r.value,target:t===80?"portal":"statement"}:null}function re(e,t){let r=e.indexOf(0,t);return r===-1?null:{nextOffset:r+1,value:e.toString("utf8",t,r)}}function ya(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 Sa(e,t){let r=In(t.query),n=Tn(r.cleanedSql);if(!n)return;let s=Rn(r.cleanedSql),i={applicationName:t.applicationName,durationMs:t.durationMs,groupKey:xn(r.prismaQueryInfo),prismaQueryInfo:r.prismaQueryInfo,query:r.cleanedSql,queryId:s,reads:0,rowsReturned:ba(t.responseStats),tables:n,timestamp:new Date().toISOString()};for(let o of e.subscribers)o([i])}function ba(e){let t=e.commandTags.reduce((r,n)=>r+Pa(n),0);return Math.max(t,e.dataRowCount)}function Pa(e){let t=e.trim().split(/\s+/).at(-1);return!t||!/^\d+$/.test(t)?0:Number(t)}f();var me=require("fs"),fe=require("fs/promises"),Mn=require("module"),$n=require("path"),ne=require("url"),wa=(0,Mn.createRequire)(h),Ea=["initdb.wasm","pglite.data","pglite.wasm"],Zt="pglite-seed.tar.gz",Ln={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"},va=[...Ea.map(e=>({fileName:e,kind:"core",name:e})),{fileName:Zt,kind:"core",name:Zt},...Object.entries(Ln).map(([e,t])=>({fileName:t,kind:"extension",name:e}))],st=new Map,Ra=Symbol.for("@prisma/dev/bundled-pglite-runtime-asset-sources"),rt=null;async function er(){await Ca();let e=Bn();if(e)return await Aa(e),await xa(e);let t=Da(),r=t.href,n=st.get(r);return n||(n=Ta(t),st.set(r,n)),await n}async function xa(e){let t=`bundled:${e.wasmModule.href}:${e.fsBundle.href}`,r=st.get(t);return r||(r=Ia(e),st.set(t,r)),await r}async function Ta(e){let t=it(new URL("./runtime-assets/",h)),[r,n,s]=await Promise.all([(0,fe.readFile)(nt("pglite.data",e,t)),(0,fe.readFile)(nt(Zt,e,t)),(0,fe.readFile)(nt("pglite.wasm",e,t))]),i=kn();return{extensions:Object.fromEntries(Object.entries(Ln).map(([o,a])=>[o,nt(a,e,t)])),fsBundle:new Blob([Uint8Array.from(r)]),loadDataDir:new Blob([Uint8Array.from(n)]),wasmModule:await i.compile(s)}}async function Ia(e){let[t,r,n]=await Promise.all([Xt(e.fsBundle),Xt(e.loadDataDir),Xt(e.wasmModule)]),s=kn();return{extensions:e.extensions,fsBundle:new Blob([Uint8Array.from(t)]),loadDataDir:new Blob([Uint8Array.from(r)]),wasmModule:await s.compile(n)}}async function Aa(e){if(e.initdbWasm.protocol!=="file:")return;let t=new URL("initdb.wasm",it(new URL("./",e.initdbWasm))),r=(0,ne.fileURLToPath)(t);(0,me.existsSync)(r)||await(0,fe.copyFile)((0,ne.fileURLToPath)(e.initdbWasm),r)}function it(e){return e instanceof URL?Nn(e):Nn((0,ne.pathToFileURL)(e))}function Nn(e){return e.href.endsWith("/")?e:new URL(`${e.href}/`)}function _a(){let e=wa.resolve("@electric-sql/pglite");return it((0,$n.dirname)(e))}function Da(){let e=it(new URL("./",h));if(Oa(e))return e;if(Na())return _a();throw new Error("Unable to locate PGlite runtime assets. If you bundled @prisma/dev, copy them next to the bundle with copyPrismaDevRuntimeAssets().")}function Oa(e){return va.every(t=>(0,me.existsSync)((0,ne.fileURLToPath)(new URL(t.fileName,e))))}function Bn(){return globalThis[Ra]??null}async function Ca(){!Ma()||Bn()||(rt||(rt=import("./runtime-assets-manifest.bun.js").then(()=>{}).catch(e=>{throw rt=null,e})),await rt)}function Na(){let e=(0,ne.fileURLToPath)(new URL("../package.json",h));if(!(0,me.existsSync)(e))return!1;try{return JSON.parse((0,me.readFileSync)(e,"utf8")).name==="@prisma/dev"}catch{return!1}}function Ma(){return typeof globalThis.Bun<"u"}function kn(){let e=globalThis.WebAssembly;if(!e)throw new Error("WebAssembly is not available in this runtime.");return e}async function Xt(e){if(e.protocol==="file:")return await(0,fe.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 nt(e,t,r){let n=new URL(e,t);if((0,me.existsSync)((0,ne.fileURLToPath)(n)))return n;if(r){let s=new URL(e,r);if((0,me.existsSync)((0,ne.fileURLToPath)(s)))return s}return n}f();var nr=require("@electric-sql/pglite"),K="_prisma_dev_wal",rr="events",qn="install_all_triggers",Un="capture_event",Hn="prisma_dev_wal_capture",ke=new WeakMap,$a=new Set(["ALTER","COMMIT","COPY","CREATE","DELETE","DROP","INSERT","MERGE","TRUNCATE","UPDATE"]);async function sr(e,t){let r=ke.get(e);if(r&&!r.closed)return r.bridge;let n=e.execProtocolRaw.bind(e),s=e.execProtocolRawStream.bind(e),i={bridge:{close:async()=>{i.closed||(i.closed=!0,i.subscribers.clear(),e.execProtocolRaw===o&&(e.execProtocolRaw=n),e.execProtocolRawStream===a&&(e.execProtocolRawStream=s),await i.pollPromise,ke.delete(e))},poll:async()=>{await tr(i,e)},subscribe:c=>(i.subscribers.add(c),()=>{i.subscribers.delete(c)})},closed:!1,ensureInfrastructurePromise:null,pendingPoll:!1,pollPromise:null,subscribers:new Set,suppressDepth:0},o=async(c,u)=>{let l=await n(c,u);return!i.closed&&i.suppressDepth===0&&Qn(l)&&tr(i,e),l},a=async(c,u)=>{let l=[],m=new nr.protocol.Parser,d=u?.onRawData;await s(c,{...u,onRawData:p=>{m.parse(p,y=>{l.push(y)}),d?.(p)}}),!i.closed&&i.suppressDepth===0&&ir(l)&&tr(i,e)};return e.execProtocolRaw=o,e.execProtocolRawStream=a,ke.set(e,i),await Fn(i,e),i.bridge}async function jn(e){let t=ke.get(e);t&&await t.bridge.close()}function ir(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&&$a.has(r))return!0}return!1}function Qn(e){if(e.length===0)return!1;let t=[];return new nr.protocol.Parser().parse(e,n=>{t.push(n)}),ir(t)}async function Fn(e,t){e.ensureInfrastructurePromise??=or(e,t,async()=>{await t.exec(`CREATE SCHEMA IF NOT EXISTS "${K}"`),await t.exec(`
|
|
43
|
+
CREATE TABLE IF NOT EXISTS "${K}"."${rr}" (
|
|
22
44
|
id BIGSERIAL PRIMARY KEY,
|
|
23
45
|
txid BIGINT NOT NULL DEFAULT txid_current(),
|
|
24
46
|
schema_name TEXT NOT NULL,
|
|
@@ -29,16 +51,16 @@ Received data: ${l}`));n({childProcess:a,url:`http://${p}:${y}`})},c=l=>{this.#t
|
|
|
29
51
|
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()
|
|
30
52
|
)
|
|
31
53
|
`),await t.exec(`
|
|
32
|
-
CREATE OR REPLACE FUNCTION "${
|
|
54
|
+
CREATE OR REPLACE FUNCTION "${K}"."${Un}"()
|
|
33
55
|
RETURNS trigger
|
|
34
56
|
LANGUAGE plpgsql
|
|
35
57
|
AS $$
|
|
36
58
|
BEGIN
|
|
37
|
-
IF TG_TABLE_SCHEMA = '${
|
|
59
|
+
IF TG_TABLE_SCHEMA = '${K}' THEN
|
|
38
60
|
RETURN COALESCE(NEW, OLD);
|
|
39
61
|
END IF;
|
|
40
62
|
|
|
41
|
-
INSERT INTO "${
|
|
63
|
+
INSERT INTO "${K}"."${rr}" (
|
|
42
64
|
txid,
|
|
43
65
|
schema_name,
|
|
44
66
|
table_name,
|
|
@@ -59,7 +81,7 @@ Received data: ${l}`));n({childProcess:a,url:`http://${p}:${y}`})},c=l=>{this.#t
|
|
|
59
81
|
END;
|
|
60
82
|
$$;
|
|
61
83
|
`),await t.exec(`
|
|
62
|
-
CREATE OR REPLACE FUNCTION "${
|
|
84
|
+
CREATE OR REPLACE FUNCTION "${K}"."${qn}"()
|
|
63
85
|
RETURNS void
|
|
64
86
|
LANGUAGE plpgsql
|
|
65
87
|
AS $$
|
|
@@ -71,7 +93,7 @@ Received data: ${l}`));n({childProcess:a,url:`http://${p}:${y}`})},c=l=>{this.#t
|
|
|
71
93
|
FROM pg_class AS c
|
|
72
94
|
JOIN pg_namespace AS n ON n.oid = c.relnamespace
|
|
73
95
|
WHERE c.relkind IN ('r', 'p')
|
|
74
|
-
AND n.nspname NOT IN ('${
|
|
96
|
+
AND n.nspname NOT IN ('${K}', 'information_schema', 'pg_catalog')
|
|
75
97
|
AND n.nspname NOT LIKE 'pg_temp_%'
|
|
76
98
|
AND n.nspname NOT LIKE 'pg_toast%'
|
|
77
99
|
LOOP
|
|
@@ -79,28 +101,28 @@ Received data: ${l}`));n({childProcess:a,url:`http://${p}:${y}`})},c=l=>{this.#t
|
|
|
79
101
|
SELECT 1
|
|
80
102
|
FROM pg_trigger
|
|
81
103
|
WHERE tgrelid = target
|
|
82
|
-
AND tgname = '${
|
|
104
|
+
AND tgname = '${Hn}'
|
|
83
105
|
) THEN
|
|
84
106
|
CONTINUE;
|
|
85
107
|
END IF;
|
|
86
108
|
|
|
87
109
|
EXECUTE format(
|
|
88
|
-
'CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION "${
|
|
89
|
-
'${
|
|
110
|
+
'CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION "${K}"."${Un}"()',
|
|
111
|
+
'${Hn}',
|
|
90
112
|
target::text
|
|
91
113
|
);
|
|
92
114
|
END LOOP;
|
|
93
115
|
END;
|
|
94
116
|
$$;
|
|
95
|
-
`),await
|
|
117
|
+
`),await Wn(e,t)}),await e.ensureInfrastructurePromise}async function Wn(e,t){await or(e,t,async()=>{await t.query(`SELECT "${K}"."${qn}"()`)})}async function La(e,t){await Fn(e,t),await Wn(e,t);let r=await or(e,t,async()=>await t.query(`
|
|
96
118
|
WITH drained AS (
|
|
97
|
-
DELETE FROM "${
|
|
119
|
+
DELETE FROM "${K}"."${rr}"
|
|
98
120
|
RETURNING txid, schema_name, table_name, op, row_data, old_row_data, id
|
|
99
121
|
)
|
|
100
122
|
SELECT txid, schema_name, table_name, op, row_data, old_row_data
|
|
101
123
|
FROM drained
|
|
102
124
|
ORDER BY id
|
|
103
|
-
`));if(r.rows.length===0||e.subscribers.size===0)return;let n=r.rows.map(
|
|
125
|
+
`));if(r.rows.length===0||e.subscribers.size===0)return;let n=r.rows.map(Ba);for(let s of e.subscribers)queueMicrotask(()=>{if(!e.closed&&e.subscribers.has(s))try{s(n)}catch(i){console.error("[WAL bridge] subscriber failed",i)}})}async function tr(e,t){if(!e.closed){if(e.pollPromise){e.pendingPoll=!0,await e.pollPromise;return}e.pollPromise=(async()=>{do e.pendingPoll=!1,await La(e,t);while(e.pendingPoll&&!e.closed)})().finally(()=>{e.pollPromise=null}),await e.pollPromise}}async function or(e,t,r){e.suppressDepth+=1;try{return await r()}finally{e.suppressDepth-=1,e.suppressDepth===0&&!e.closed&&ke.get(t)!==e&&(e.closed=!0)}}function Ba(e){return{oldRecord:e.old_row_data,record:e.row_data,schema:e.schema_name,table:e.table_name,txid:String(e.txid),type:ka(e.op)}}function ka(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 Ua=10,Kn="127.0.0.1",Jn=128*1024*1024,Yn=["-c","shared_buffers=16MB","-c","temp_buffers=1MB","-c","work_mem=1MB","-c","maintenance_work_mem=16MB","-c","wal_buffers=1MB"],v={connectionLimit:Ua,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},Ha=`postgres://${v.username}:${v.password}@localhost`,ar=new URLSearchParams({sslmode:v.sslMode}),Xn=new URLSearchParams({...Object.fromEntries(ar.entries()),connection_limit:String(v.connectionLimit),connect_timeout:String(v.connectTimeout),max_idle_connection_lifetime:String(v.maxIdleConnectionLifetime),pool_timeout:String(v.poolTimeout),socket_timeout:String(v.socketTimeout)});async function Zn(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 ${v.username} WITH LOGIN SUPERUSER PASSWORD '${v.password}'`):await e.exec(`CREATE ROLE ${v.username} WITH LOGIN SUPERUSER PASSWORD '${v.password}'`),await e.exec(`SET ROLE ${v.username}`)}async function cr(e,t){if(e==="shadow_database"&&!t.dryRun)return await qa(t);let r=e==="database"?t.databasePort:t.shadowDatabasePort;return t.dryRun?ts(e,t,{db:null,port:r,server:null}):await es(e,t,{port:r,updateServerStatePort:!0})}async function qa(e,t=async()=>await es("shadow_database",e,{port:0,updateServerStatePort:!1})){let{debug:r}=e,n=null,s=null,i=!1,o=new Set,a=(0,at.createServer)(u),c=await ja(a,e.shadowDatabasePort);return e.shadowDatabasePort=c,r&&console.debug(`[shadow_database] lazy proxy listening on port ${c}`),{...v,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()=>{i=!0;for(let p of o)p.destroy();o.clear();let d=[];try{await Qa(a),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:ot(c,ar),dump:async()=>{},getPrimaryKeyColumns:()=>Promise.reject(new Error("Primary key resolution is only available for the primary database server")),port:c,prismaORMConnectionString:ot(c,Xn),terminalCommand:`PGPASSWORD=${v.password} PGSSLMODE=${v.sslMode} psql -h localhost -p ${c} -U ${v.username} -d ${v.database}`};function u(d){o.add(d);let p=()=>{o.delete(d)};d.once("close",p),d.once("error",p),d.pause(),l(d)}async function l(d){try{let p=await m();if(i){d.destroy();return}let y=(0,at.createConnection)({host:Kn,port:p.port});o.add(y);let b=()=>{o.delete(y)};y.once("close",b),y.once("error",b),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 m(){if(n)return n;if(i)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 es(e,t,r){let{debug:n}=t,{port:s,updateServerStatePort:i}=r,a=await(e==="shadow_database"?Fa:rs)(t.pgliteDataDirPath,n);n&&a.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:a,debug:n,idleTimeout:Number.isFinite(u)?u:0,inspect:n,maxConnections:v.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 V(s):d}let m=Number(l.getServerConn().split(":").at(1));return i&&(t[e==="database"?"databasePort":"shadowDatabasePort"]=m),ts(e,t,{db:a,port:m,server:l})}function ts(e,t,r){let{debug:n}=t,{db:s,port:i,server:o}=r||{},a=new Map;return n&&console.debug(`[${e}] server started on port ${i}`),{...v,attachWalEventBridge:async()=>{if(e!=="database"||!s)throw new Error("WAL bridge is only available for the primary database server");return await sr(s)},attachQueryInsightsBridge:()=>{if(e!=="database"||!o)throw new Error("Query insights are only available for the primary database server");return Promise.resolve(On(o))},close:async()=>{let c=[];try{await o?.stop(),n&&console.debug(`[${e}] server stopped on port ${i}`)}catch(u){console.error(`[${e}] server stop error`,u),c.push(u)}if(e==="database"){try{o&&await Cn(o),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 jn(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:ot(i,ar),dump:async c=>{e==="shadow_database"||!s||await Ga({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}`,m=a.get(l);return m||(m=Wa(s,c,u).catch(d=>{throw a.delete(l),d}),a.set(l,m)),await m},port:i,prismaORMConnectionString:ot(i,Xn),terminalCommand:`PGPASSWORD=${v.password} PGSSLMODE=${v.sslMode} psql -h localhost -p ${i} -U ${v.username} -d ${v.database}`}}function ot(e,t){return`${Ha}:${e}/${v.database}?${t.toString()}`}async function rs(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await er(),s=e==="memory://"||!await Re((0,zn.join)(e,"PG_VERSION")),i=await r.create({database:v.database,dataDir:e,debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:Jn,loadDataDir:s?n.loadDataDir:void 0,relaxedDurability:!1,startParams:[...r.defaultStartParams,...Yn],wasmModule:n.wasmModule});return await Zn(i),i}async function ja(e,t){return await new Promise((r,n)=>{let s=a=>{if(o(),a.code==="EADDRINUSE"){n(new V(t));return}n(a)},i=()=>{let a=e.address();if(o(),!a||typeof a=="string"){n(new Error("Failed to determine TCP server port"));return}r(a.port)},o=()=>{e.off("error",s),e.off("listening",i)};e.once("error",s),e.once("listening",i),e.listen(t,Kn)})}async function Qa(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 Fa(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await er(),s=await r.create({database:v.database,dataDir:"memory://",debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:Jn,loadDataDir:n.loadDataDir,relaxedDurability:!1,startParams:[...r.defaultStartParams,...Yn],wasmModule:n.wasmModule});return await Zn(s),s}async function Wa(e,t,r){let{rows:n}=await e.query(`
|
|
104
126
|
SELECT attribute.attname AS column_name
|
|
105
127
|
FROM pg_constraint pk_constraint
|
|
106
128
|
INNER JOIN pg_class relation
|
|
@@ -113,9 +135,9 @@ Received data: ${l}`));n({childProcess:a,url:`http://${p}:${y}`})},c=l=>{this.#t
|
|
|
113
135
|
ON attribute.attrelid = relation.oid
|
|
114
136
|
AND attribute.attnum = keys.attnum
|
|
115
137
|
WHERE pk_constraint.contype = 'p'
|
|
116
|
-
AND namespace.nspname = ${
|
|
117
|
-
AND relation.relname = ${
|
|
138
|
+
AND namespace.nspname = ${Gn(t)}
|
|
139
|
+
AND relation.relname = ${Gn(r)}
|
|
118
140
|
ORDER BY keys.ordinality
|
|
119
|
-
`);return n.map(s=>s.column_name)}function
|
|
120
|
-
${JSON.stringify(
|
|
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 B.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(!_n(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,ee.check)(l,{lockfilePath:(0,V.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.`)}},Be=class extends Mt{#r;name="ServerAlreadyRunningError";constructor(t){super(t.name),this.#r=t}get server(){return B.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};m();var $n=require("crypto"),$t=require("timers/promises"),kt=require("util"),kn=require("std-env");Y();var Go="application/json",le={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 Cn(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=_e(u),f=!c&&await z(l);kn.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:Oe(d.exports.http.url)};try{await Yo(p);let y=await Dn({bridge:a,debug:r,serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path}),E=new Ut({dbServer:t,debug:r,streamUrl:p.url}),te=i.subscribe(Le=>{E.enqueue(Le)});return{close:async()=>{te(),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(_e(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=Ln(t.record),a=Ln(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:le,method:"PUT"});if(!t.ok)throw await de(t,`Failed to create ${e.streamName}`);let r=await fetch(`${e.url}/_profile`,{body:JSON.stringify(jo),headers:le,method:"POST"});if(!r.ok)throw await de(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:le,method:"POST"});if(!s.ok)throw await de(s,`Failed to install schema for ${e.streamName}`)}async function Xo(e){let t=await fetch(`${e.url}/_schema`,{headers:le,method:"GET"});if(!t.ok)throw await de(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:le,method:"POST"});if(!r.ok)throw await de(r,"Failed to append to prisma-wal")}async function de(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 Ln(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,$n.randomUUID)().replaceAll("-","")}`}async function Un(e){let t=await B.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 Cn({dbServer:r,debug:t.debug,name:t.name,port:t.streamsPort,persistenceMode:t.persistenceMode,queryInsightsBridge:i,walBridge:a})),n=await xn(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=In(o.experimentalQueryInsights),f=r,d=s,p=n,y=o,E=async()=>{u.close(),await Qn(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 Qn(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 Qn(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 qn(e){let{server:t}=await Un(e);return t}var L;process.once("SIGTERM",()=>{console.log("SIGTERM received, shutting down..."),process.removeAllListeners("SIGINT"),process.exitCode=143,L?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{console.log("SIGINT received, shutting down..."),process.removeAllListeners("SIGTERM"),process.exitCode=130,L?.close().finally(()=>process.exit())});async function ma(){let[,,e]=process.argv;if(!e)return process.send?.({type:"error",error:'Missing "name" argument, server cannot be started'},void 0),process.exit(1);try{L=await qn({debug:!0,persistenceMode:"stateful",name:e});let t=L.experimental.queryInsights,r={database:L.database,experimental:{queryInsights:{serverUrl:t.serverUrl,sqlitePath:t.sqlitePath,streamName:t.streamName,url:t.url},streams:L.experimental.streams},http:L.http,name:L.name,ppg:L.ppg,shadowDatabase:L.shadowDatabase};process.send?.({type:"started",server:r},void 0)}catch(t){console.error(t);let r=t instanceof Error?t.message:String(t);process.send?.({type:"error",error:r},void 0),await(0,Hn.setTimeout)(1e3),process.exit(1)}}ma();
|
|
141
|
+
`);return n.map(s=>s.column_name)}function Gn(e){return`'${e.replaceAll("'","''")}'`}async function Ga(e){let{dataDir:t,db:r,debug:n,destinationPath:s}=e,i=r||await rs(t,n),{pgDump:o}=await import("@electric-sql/pglite-tools/pg_dump"),a=await o({args:["--schema-only","--no-owner"],fileName:s?(0,Vn.filename)(s):void 0,pg:await i.clone()});return s?(n&&console.debug(`[DB] Dumping database to ${s}`),await hn(a,s)):(n&&console.debug("[DB] Dumping database to memory"),await a.text())}f();var po=U(Ti(),1);oe();async function ho(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:i},{createHTTPServer:o}]=await Promise.all([Promise.resolve().then(()=>(uo(),lo)),Promise.resolve().then(()=>(mo(),fo)),Promise.resolve().then(()=>(At(),ji))]),a={databaseDumpPath:t.databaseDumpPath,db:e,debug:n,name:t.name,port:r,shadowDBPort:t.shadowDatabasePort},c=(0,po.default)({defaultRoute(l,m){B(m,"Not Found",404)},ignoreTrailingSlash:!1});s(c,a,n),i(c,a,n);let u=await o({router:c}).listen(r);return t.port=u.port,a.port=u.port,{async close(){let{Engine:l}=await Promise.resolve().then(()=>(Br(),Lr));await Promise.allSettled([u.close(),l.stopAll()])},port:u.port,url:u.url}}f();var Wr=require("util");f();var qr=require("pathe");Te();var jr="prisma-wal",Qr="prisma-queries";function Fr(){return(0,qr.join)(Xe.data,"durable-streams")}function Ot(e){return(0,qr.join)(Fr(),e)}function Ct(e,t=jr){return new URL(`/v1/stream/${encodeURIComponent(t)}`,e).toString()}var Pl="application/json",Nt={connection:"close","content-type":Pl},Gr={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 go(e){return{...e,snapshot:async t=>await wl(e.url,t)}}async function yo(e){let t={serverUrl:e.serverUrl,sqlitePath:e.sqlitePath,streamName:Qr,url:Ct(e.serverUrl,Qr)};await vl(t);let r=new zr({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 wl(e,t){if(!e)return vn();let r=await El(e);return An(r,t)}async function El(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 zr=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 Tl(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 vl(e){let t=await fetch(e.url,{headers:Nt,method:"PUT"});if(!t.ok)throw await Mt(t,`Failed to create ${e.streamName}`);let r=await xl(e);if(Rl(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(Gr),headers:Nt,method:"POST"});if(!n.ok)throw await Mt(n,`Failed to install schema for ${e.streamName}`)}function Rl(e,t){if(e.currentVersion<=0||e.schema!==t)return!1;let r=e.schemas[String(e.currentVersion)];return(0,Wr.isDeepStrictEqual)(r,Gr.schema)&&(0,Wr.isDeepStrictEqual)(e.search,Gr.search)}async function xl(e){let t=await fetch(`${e.url}/_schema`,{headers:Nt,method:"GET"});if(!t.ok)throw await Mt(t,`Failed to inspect schema for ${e.streamName}`);return await t.json()}async function Tl(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:Nt,method:"POST"});if(!r.ok)throw await Mt(r,"Failed to append to prisma-queries")}async function Mt(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}f();var vo=require("fs/promises"),we=require("pathe"),Ne=require("proper-lockfile"),Xr=require("std-env"),g=require("valibot");Te();f();var Il=require("timers/promises"),So=require("std-env");function bo(e,t){if(e==null)return!1;try{return So.process.kill?.(e,0)??!0}catch(r){return t&&console.error(`Error checking if process with PID ${e} exists:`,r),!1}}Be();var We=(0,g.pipe)((0,g.string)(),(0,g.url)()),Po=(0,g.object)({connectionString:We,prismaORMConnectionString:(0,g.optional)(We),terminalCommand:(0,g.optional)((0,g.string)())}),wo=(0,g.object)({url:We}),Eo=(0,g.object)({serverUrl:We,sqlitePath:(0,g.pipe)((0,g.string)(),(0,g.minLength)(1)),streamName:(0,g.pipe)((0,g.string)(),(0,g.minLength)(1)),url:We}),Al=(0,g.object)({queryInsights:(0,g.optional)(Eo),streams:(0,g.optional)(Eo)}),Vr=(0,g.pipe)((0,g.number)(),(0,g.integer)(),(0,g.minValue)(1)),_l=(0,g.object)({database:Po,http:wo,ppg:wo,shadowDatabase:Po}),Dl=(0,g.object)({databasePort:Vr,experimental:(0,g.optional)(Al),exports:(0,g.optional)(_l),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:Vr,shadowDatabasePort:Vr,version:(0,g.literal)("1")}),Zr=Symbol("initialize"),Kr="default",Ol=new Set(["durable-streams"]),X=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;_streamsPort;constructor(t){this._databasePort=t.databasePort??q,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??Kr,this.persistenceMode=t.persistenceMode,this.pid=t.pid??Xr.process.pid,this.shadowDatabaseConnectTimeoutMillis=t.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=t.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=t.port??q,this._shadowDatabasePort=t.shadowDatabasePort??q,this._streamsPort=t.streamsPort??q}static async createExclusively(t){let r=t?.dryRun!==!0&&t?.persistenceMode==="stateful"?new Fe(t):new Jr(t);return await r[Zr](),r}static async fromServerDump(t){let{debug:r,name:n=Kr}=t??{},s=Le(n),i=Fe.getServerDumpPath(s),o=await gn(i);if(o==null)return r&&console.debug(`[State] No server dump file found at: ${i}`),null;r&&(console.debug(`[State] server dump file found at "${i}":`),console.debug(o));let{issues:a,output:c,success:u}=(0,g.safeParse)((0,g.pipe)((0,g.string)(),(0,g.parseJson)(),Dl),o);if(!u)throw r&&console.debug(`[State] Invalid server dump file at "${i}":
|
|
142
|
+
${JSON.stringify(a,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new Fe({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,we.join)(Le(Kr),"..");r&&console.debug(`[State] scanning for server states in: ${s}`);let i=(await Sn(s,n)).filter(o=>!Ol.has(o));return r&&console.debug(`[State] found server names: ${JSON.stringify(i)}`),await Promise.all(i.map(o=>Cl(o,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]!==Se&&this[n]!==r)throw new Error(`\`${t}\` is already set to ${this[n]}, cannot change it to ${r}`);this[n]=r}},Jr=class extends X{constructor(t){super({...t,databasePort:t?.databasePort||Se,persistenceMode:"stateless",port:t?.port||Se,shadowDatabasePort:t?.shadowDatabasePort||Se,streamsPort:t?.streamsPort||Se})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[Zr](){let t;try{t=await X.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 Kt({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(){}},Fe=class e extends X{#r;#e;#t;#s;#i;#o;#n;constructor(t){super({...t,persistenceMode:"stateful"}),this.#o=!1,this.#e=Le(this.name),this.#r=(0,we.join)(this.#e,"db_dump.bak"),this.#t=(0,we.join)(this.#e,".lock"),this.#s=(0,we.join)(this.#e,".pglite"),this.#n=t?.serverDump??null,this.#i=e.getServerDumpPath(this.#e)}static getServerDumpPath(t){return(0,we.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[Zr](){await yn(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,Ne.lock)(this.#e,{lockfilePath:this.#t}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let t=await X.scan({debug:this.debug,onlyMetadata:!0}),r=await Kt({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 $t(this):t}}async close(){if(!this.#o)try{await(0,Ne.unlock)(this.#e,{lockfilePath:this.#t}),this.#o=!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:Xr.process.pid,port:this.port,databasePort:this.databasePort,experimental:r,shadowDatabasePort:this.shadowDatabasePort,exports:t},await(0,vo.writeFile)(this.#i,`${JSON.stringify(this.#n,null,2)}
|
|
143
|
+
`,{encoding:"utf-8"})}};async function Cl(e,t){let{debug:r,onlyMetadata:n}=t||{},s=typeof e=="string"?e:e.name,i=typeof e!="string"?e:void 0,o={databasePort:i?.databasePort??-1,experimental:i?.experimental,exports:i?.exports,name:s,pid:i?.pid,port:i?.port??-1,shadowDatabasePort:i?.shadowDatabasePort??-1,version:"1"};try{let a=i||await X.fromServerDump({debug:r,name:s});if(!a)return r&&console.debug(`[State] no server state found for name: ${s}`),{...o,status:"no_such_server"};o.databasePort=a.databasePort,o.experimental=a.experimental,o.exports=a.exports,o.pid=a.pid,o.port=a.port,o.shadowDatabasePort=a.shadowDatabasePort;let{exports:c,pid:u}=a;if(n)return{...o,status:"unknown"};if(!bo(u,r))return r&&console.debug(`[State] server state for "${s}" has no running process with PID: ${u}`),{...o,status:"not_running"};let l=Le(s);try{if(!await(0,Ne.check)(l,{lockfilePath:(0,we.join)(l,".lock")}))return r&&console.debug(`[State] server state for "${s}" is not locked, indicating it is not running.`),{...o,status:"not_running"}}catch(y){r&&console.error(`[State] server state for "${s}" failed to check lock:`,y)}if(!c)return{...o,status:"starting_up"};let{http:m}=c,d=await fetch(`${m.url}/health`,{headers:{connection:"close"}});if(!d.ok)return r&&console.debug(`[State] server state for "${s}" is not live: ${JSON.stringify(d)}`),{...o,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)}`),{...o,status:"unknown"}):(r&&console.debug(`[State] server state for "${e}" is live: ${JSON.stringify(p)}`),{...o,status:"running"})}catch(a){return r&&console.error(`[State] failed to get server status for "${s}":`,a),{...o,status:"error"}}}var Yr=class extends Error{name="ServerStateAlreadyExistsError";constructor(t){super(`A Prisma Dev server with the name "${t}" is already running.`)}},$t=class extends Yr{#r;name="ServerAlreadyRunningError";constructor(t){super(t.name),this.#r=t}get server(){return X.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};f();var xo=require("crypto"),en=require("timers/promises"),tn=require("util"),To=require("std-env");Te();var Nl="application/json",Ge={connection:"close","content-type":Nl},Ml={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},rn={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 Io(e){let{dbServer:t,debug:r,name:n,persistenceMode:s,port:i,queryInsightsBridge:o,walBridge:a}=e,c=s==="stateless",u=c?Gl(n):n,l=Ot(u),m=!c&&await Re(l);To.process.env.DS_LOCAL_DATA_ROOT=Fr(),c&&await xe(l);let d=await Ll({debug:r,hadExistingStreamsData:m,name:u,port:i}),p={serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path,streamName:jr,url:Ct(d.exports.http.url)};try{await Ul(p);let y=await yo({bridge:o,debug:r,serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path}),b=new nn({dbServer:t,debug:r,streamUrl:p.url}),S=a.subscribe(O=>{b.enqueue(O)});return{close:async()=>{S(),await b.close(),await y.close(),await d.close(),await(0,en.setTimeout)(100),c&&await xe(l)},experimental:p,experimentalQueryInsights:y.experimental}}catch(y){throw await d.close().catch(()=>{}),await(0,en.setTimeout)(100),c&&await xe(l).catch(()=>{}),y}}var $l=["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 Ll(e){let{debug:t,hadExistingStreamsData:r,name:n,port:s}=e,{startLocalDurableStreamsServer:i}=await import("@prisma/streams-local"),o=()=>i({hostname:"127.0.0.1",name:n,port:s});try{return await o()}catch(a){if(!r||!Bl(a))throw a;return console.warn(`[streams] resetting incompatible durable streams data for "${n}"`),t&&console.debug(`[streams] original durable streams startup error for "${n}"`,a),await xe(Ot(n)),await o()}}function Bl(e){return kl(e).map(r=>r.toLowerCase()).some(r=>$l.some(n=>r.includes(n)))}function kl(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 i of s.errors)r.push(i);if(s instanceof Error){t.push(s.message);let i=s.cause;i!==void 0&&r.push(i)}}}return t}var nn=class{#r;#e;#t;#s;#i;constructor(t){this.#r=t.dbServer,this.#e=t.debug,this.#t=Promise.resolve(),this.#s=t.streamUrl,this.#i=new Set}enqueue(t){t.length!==0&&(this.#t=this.#t.then(async()=>{let r=await this.#o(t);r.length!==0&&(await jl(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#o(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),i=Ro(t.record),o=Ro(t.oldRecord),a=this.#a(n,s,o),c=this.#a(n,s,i),u=t.txid===""?void 0:t.txid;return t.type==="insert"?i&&c?[{headers:{operation:"insert",timestamp:r,txid:u},key:c,old_value:null,type:n,value:i}]:[]:t.type==="delete"?o&&a?[{headers:{operation:"delete",timestamp:r,txid:u},key:a,old_value:o,type:n,value:null}]:[]:!i||!o||!a||!c?[]:a!==c?[{headers:{operation:"delete",timestamp:r,txid:u},key:a,old_value:o,type:n,value:null},{headers:{operation:"insert",timestamp:r,txid:u},key:c,old_value:null,type:n,value:i}]:[{headers:{operation:"update",timestamp:r,txid:u},key:c,old_value:o,type:n,value:i}]}#a(t,r,n){if(!n)return null;let s=Ql(n,r);return s||(this.#i.has(t)||(this.#i.add(t),console.warn(`[streams] falling back to full-row keys for ${t} because no primary key could be resolved`)),Fl(n))}};async function Ul(e){let t=await fetch(e.url,{headers:Ge,method:"PUT"});if(!t.ok)throw await ze(t,`Failed to create ${e.streamName}`);let r=await fetch(`${e.url}/_profile`,{body:JSON.stringify(Ml),headers:Ge,method:"POST"});if(!r.ok)throw await ze(r,`Failed to configure ${e.streamName}`);let n=await Hl(e);if(ql(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(rn),headers:Ge,method:"POST"});if(!s.ok)throw await ze(s,`Failed to install schema for ${e.streamName}`)}async function Hl(e){let t=await fetch(`${e.url}/_schema`,{headers:Ge,method:"GET"});if(!t.ok)throw await ze(t,`Failed to inspect schema for ${e.streamName}`);return await t.json()}function ql(e,t){if(e.currentVersion<=0||e.schema!==t)return!1;let r=e.schemas[String(e.currentVersion)];return(0,tn.isDeepStrictEqual)(r,rn.schema)&&(0,tn.isDeepStrictEqual)(e.search,rn.search)}async function jl(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:Ge,method:"POST"});if(!r.ok)throw await ze(r,"Failed to append to prisma-wal")}async function ze(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}function Ql(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=Wl(e[n]);if(s==null)return null;r.push(t.length===1?s:`${n}=${s}`)}return r.join("|")}function Fl(e){return JSON.stringify(sn(e))}function sn(e){return Array.isArray(e)?e.map(t=>sn(t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,sn(r)])):e}function Ro(e){return e?structuredClone(e):null}function Wl(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 Gl(e){return`${e}.${(0,xo.randomUUID)().replaceAll("-","")}`}async function Ao(e){let t=await X.createExclusively(e),r=null,n=null,s=null,i=null;try{[r,s]=await Promise.all([cr("database",t),cr("shadow_database",t)]);let o,a;t.dryRun?(o=Jl(),a=Yl(),i=Xl()):(o=await r.attachWalEventBridge(),a=await r.attachQueryInsightsBridge(),i=await Io({dbServer:r,debug:t.debug,name:t.name,port:t.streamsPort,persistenceMode:t.persistenceMode,queryInsightsBridge:a,walBridge:o})),n=await ho(r,t);let c=zl(r,s,n,t);await t.writeServerDump(c,t.dryRun?{}:{queryInsights:i.experimentalQueryInsights,streams:i.experimental});let u=Kl(o),l=go(i.experimentalQueryInsights),m=r,d=s,p=n,y=i,b=async()=>{u.close(),await _o(t,[p,y,m,d])};return{close:b,dbServer:r,httpServer:n,server:{...c,close:b,experimental:{queryInsights:l,streams:i.experimental,wal:u.api},name:t.name},serverState:t,shadowDbServer:s,streamsServer:i,queryInsightsBridge:a,walBridge:o}}catch(o){return await Vl(t,[n,i,r,s],o)}}function zl(e,t,r,n){let s=`prisma+postgres://localhost:${r.port}/?${new URLSearchParams({api_key:cn({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 _o(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 Vl(e,t,r){try{await _o(e,t.filter(n=>n!==null))}catch(n){throw new AggregateError([r,n],"Failed to start Prisma Dev server cleanly")}throw r}function Kl(e){let t=new Set;return{api:{stream:()=>{let r=()=>{},n=Zl(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 Jl(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function Yl(){return{async close(){},subscribe(){return()=>{}}}}function Xl(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""},experimentalQueryInsights:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function Zl(e,t){let r=[],n=!1,s=null,i=e.subscribe(a=>{if(!n){if(s){let c=s;s=null,c.resolve({done:!1,value:a});return}r.push(a)}}),o=()=>{if(!n&&(n=!0,i(),r.length=0,t(),s)){let a=s;s=null,a.resolve({done:!0,value:void 0})}};return{close:o,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((a,c)=>{s={reject:c,resolve:a}})},return(){return o(),Promise.resolve({done:!0,value:void 0})},throw(a){let c=s;return o(),c&&c.reject(a),Promise.reject(a instanceof Error?a:new Error(String(a)))}}}}Be();async function Do(e){let{server:t}=await Ao(e);return t}var Z;process.once("SIGTERM",()=>{console.log("SIGTERM received, shutting down..."),process.removeAllListeners("SIGINT"),process.exitCode=143,Z?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{console.log("SIGINT received, shutting down..."),process.removeAllListeners("SIGTERM"),process.exitCode=130,Z?.close().finally(()=>process.exit())});async function eu(){let[,,e]=process.argv;if(!e)return process.send?.({type:"error",error:'Missing "name" argument, server cannot be started'},void 0),process.exit(1);try{Z=await Do({debug:!0,persistenceMode:"stateful",name:e});let t=Z.experimental.queryInsights,r={database:Z.database,experimental:{queryInsights:{serverUrl:t.serverUrl,sqlitePath:t.sqlitePath,streamName:t.streamName,url:t.url},streams:Z.experimental.streams},http:Z.http,name:Z.name,ppg:Z.ppg,shadowDatabase:Z.shadowDatabase};process.send?.({type:"started",server:r},void 0)}catch(t){console.error(t);let r=t instanceof Error?t.message:String(t);process.send?.({type:"error",error:r},void 0),await(0,Oo.setTimeout)(1e3),process.exit(1)}}eu();
|