@prisma/dev
Advanced tools
| import{b as g}from"./chunk-DEMTR4W3.js";import{a as h}from"./chunk-U3HKF6IL.js";import{a as B}from"./chunk-I2OHVRST.js";import"./chunk-UEE5SWKL.js";import{a as m,b as p,c as C}from"./chunk-T6L5TENJ.js";import{d as f}from"./chunk-JLSS5G22.js";f();import{text as X}from"stream/consumers";f();import{json as tn}from"stream/consumers";import{array as rn,literal as on,minLength as sn,object as an,pipe as cn,safeParse as un,string as ln,union as fn}from"valibot";var dn=an({tags:fn([cn(rn(ln()),sn(1)),on("all")])});async function L(n,r){let e;try{e=await tn(n)}catch{return p(r,"Invalid input",400),null}let{output:t,success:i}=un(dn,e,{abortEarly:!0});return i?t:(p(r,"Invalid input",400),null)}f();import{Buffer as _}from"buffer";var H=new Map;async function R(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(a=>a.toString(16).padStart(2,"0")).join("")}function V(n,r){let e=n.schemaHash;if(e==null)return m(r,{EngineNotStarted:{reason:"SchemaMissing"}},404),null;let t=H.get(e);return t==null?(m(r,{EngineNotStarted:{reason:"SchemaMissing"}},404),null):{schemaHash:e,schemas:t}}async function D(n,r,e){let t=_.from(n,"base64").toString("utf8"),i=pn(t,r.toString());e&&console.log("[Accelerate] schema with override:",i);let o=await R(i);return{base64Override:_.from(i,"utf8").toString("base64"),overrideHash:o}}var mn=" ";function pn(n,r){let e=gn(n);if(!e)throw new Error("No datasource block found in schema.");let t=n.slice(e.openBraceIndex+1,e.closeBraceIndex),i=yn(t,r,Tn(n,e.openBraceIndex));return`${n.slice(0,e.openBraceIndex+1)}${i}${n.slice(e.closeBraceIndex)}`}function gn(n){let r="datasource";for(let e=0;e<n.length;e+=1){let t=n[e];if(t==="/"&&n[e+1]==="/"){e=P(n,e+2);continue}if(t==="/"&&n[e+1]==="*"){e=v(n,e+2);continue}if(t==='"'){e=b(n,e+1);continue}if(n.startsWith(r,e)&&!N(n[e-1])&&!N(n[e+r.length])){let i=hn(n,e+r.length,"{");if(i===-1)return null;let o=Sn(n,i);return o===-1?null:{closeBraceIndex:o,openBraceIndex:i}}}return null}function hn(n,r,e){for(let t=r;t<n.length;t+=1){let i=n[t];if(i==="/"&&n[t+1]==="/"){t=P(n,t+2);continue}if(i==="/"&&n[t+1]==="*"){t=v(n,t+2);continue}if(i==='"'){t=b(n,t+1);continue}if(i===e)return t}return-1}function Sn(n,r){let e=0;for(let t=r;t<n.length;t+=1){let i=n[t];if(i==="/"&&n[t+1]==="/"){t=P(n,t+2);continue}if(i==="/"&&n[t+1]==="*"){t=v(n,t+2);continue}if(i==='"'){t=b(n,t+1);continue}if(i==="{"){e+=1;continue}if(i==="}"&&(e-=1,e===0))return t}return-1}function P(n,r){let e=r;for(;e<n.length&&n[e]!==` | ||
| `;)e+=1;return e}function v(n,r){let e=n.indexOf("*/",r);return e===-1?n.length:e+1}function b(n,r){let e=r;for(;e<n.length;){if(n[e]==="\\"){e+=2;continue}if(n[e]==='"')return e;e+=1}return n.length}function N(n){return n!=null&&/[A-Za-z0-9_]/.test(n)}function yn(n,r,e){let t=`"${Hn(r)}"`,i=In(n);for(let[d,S]of i.entries()){let{comment:w,code:en}=q(S.line),x=en.match(/^(\s*)url(\s*)=(\s*).*/);if(x)return i[d]={line:`${x[1]}url${x[2]}=${x[3]}${t}${w}`,terminator:S.terminator},O(i)}let o=xn(n),a=wn(i,e),u=`${a}url = ${t}`;if(!n.includes(` | ||
| `)&&!n.includes("\r")){let d=n.trim();return d.length===0?`${o}${u}${o}${e}`:`${o}${a}${d}${o}${u}${o}${e}`}let s=i.at(-1);if(s&&s.terminator===""&&/^\s*$/.test(s.line))return`${O(i.slice(0,-1))}${u}${o}${e}`;let c=O(i),l=c.endsWith(` | ||
| `)||c.endsWith("\r")?"":o;return`${c}${l}${u}${o}${e}`}function In(n){let r=[],e=0;for(let t=0;t<n.length;t+=1){if(n[t]==="\r"&&n[t+1]===` | ||
| `){r.push({line:n.slice(e,t),terminator:`\r | ||
| `}),t+=1,e=t+1;continue}(n[t]===` | ||
| `||n[t]==="\r")&&(r.push({line:n.slice(e,t),terminator:n[t]}),e=t+1)}return(e<n.length||n.length===0)&&r.push({line:n.slice(e),terminator:""}),r}function O(n){return n.map(r=>`${r.line}${r.terminator}`).join("")}function q(n){let r=!1,e=!1;for(let t=0;t<n.length;t+=1){let i=n[t];if(e){if(r){r=!1;continue}if(i==="\\"){r=!0;continue}i==='"'&&(e=!1);continue}if(i==='"'){e=!0;continue}if(i==="/"&&n[t+1]==="/")return{code:n.slice(0,t),comment:n.slice(t)}}return{code:n,comment:""}}function wn(n,r){for(let e of n){let{code:t}=q(e.line),i=t.match(/^([ \t]+)[A-Za-z_][A-Za-z0-9_]*\s*=/);if(i?.[1])return i[1]}return`${r}${mn}`}function Tn(n,r){let e=n.lastIndexOf(` | ||
| `,r)+1,t=e;for(;n[t]===" "||n[t]===" ";)t+=1;return n.slice(e,t)}function xn(n){return n.includes(`\r | ||
| `)?`\r | ||
| `:` | ||
| `}function Hn(n){return n.replaceAll("\\","\\\\").replaceAll('"','\\"')}f();function T(n,r){let e=n[r];return Array.isArray(e)?e.at(-1):e}f();import{Readable as U}from"stream";import{pipeline as En}from"stream/promises";var $n=new Set(["GET","HEAD"]);function j(n,r){let e=(n.method??"GET").toUpperCase(),t=`${r.origin}${n.url??"/"}`,i={headers:On(n.headers),method:e};return $n.has(e)||(i.body=U.toWeb(n),i.duplex="half"),new Request(t,i)}async function F(n,r){r.statusCode=n.status;for(let[e,t]of n.headers)r.setHeader(e,t);if(n.body===null){r.end();return}await En(U.fromWeb(n.body),r)}function On(n){let r=new Headers;for(let[e,t]of Object.entries(n))if(typeof t=="string")r.append(e,t);else if(Array.isArray(t))for(let i of t)r.append(e,i);return r}f();function E(n){return{traceparent:T(n.headers,"traceparent"),"X-capture-telemetry":T(n.headers,"x-capture-telemetry")}}f();import{json as Rn}from"stream/consumers";import{integer as k,looseObject as Pn,minValue as W,number as A,object as vn,optional as bn,pipe as G,safeParse as z,string as Y,union as An}from"valibot";var Mn=vn({isolation_level:bn(Y()),max_wait:G(A(),k(),W(0)),timeout:G(A(),k(),W(0))});async function J(n,r){let e;try{e=await Rn(n)}catch{return m(r,{EngineNotStarted:{reason:"InvalidRequest",issues:[]}},400),null}let{issues:t,output:i,success:o}=z(Mn,e,{abortEarly:!0});return o?i:(m(r,{EngineNotStarted:{reason:"InvalidRequest",issues:t}},400),null)}var Bn=Pn({id:An([Y(),A()])});function Q(n,r){let{output:e,success:t}=z(Bn,n);return t?e:(m(r,{EngineMalfunction:{}},500),null)}var Z,K,nn;function $(){return Z??=import("./engine-RSESCYD5.js"),Z}function Cn(){return nn??=import("./query-plan-executor-566O5VXO.js"),nn}async function Ln(){return K??=import("@prisma/get-platform").then(async({default:n})=>await n.getPlatformInfo()),await K}function he(n,r,e){n.on("POST","/invalidate",h(async(i,o)=>{g(i,r),await L(i,o)!==null&&C(o,200)},e));for(let i of["/:clientVersion/:schemaHash/graphql","/:clientVersion/:schemaHash/itx/:transactionId/graphql"])n.on("POST",i,h(async(o,a,u)=>{g(o,r);try{let s=await M(a,r,u);if(s===null)return;let c=await X(o),l=u.transactionId,d=await s.request(c,{...E(o),"X-transaction-id":l});p(a,d)}catch(s){let{handleEngineError:c}=await $();c(s,a)}},e));for(let i of["commit","rollback"])n.on("POST",`/:clientVersion/:schemaHash/itx/:transactionId/${i}`,h(async(o,a,u)=>{g(o,r);try{let s=await M(a,r,u);if(s===null)return;let c=u.transactionId;if(c==null){m(a,{EngineMalfunction:{}},500);return}let l=`${i}Transaction`,d=await s[l](c,E(o));m(a,d)}catch(s){let{handleEngineError:c}=await $();c(s,a)}},e));n.on("PUT","/:clientVersion/:schemaHash/schema",h(async(i,o,a)=>{g(i,r);let u=await X(i);if(!u){p(o,"Missing schema",400);return}let s=a.schemaHash;if(s==null){p(o,"Missing schema hash",400);return}let c=H.get(s);if(c==null){if(s!==await R(u)){p(o,"Schema hash mismatch",400);return}let l=await D(u,r.db.prismaORMConnectionString,r.debug);H.set(s,{base64Original:u,...l}),p(o,s);return}if(u!==c.base64Original){p(o,"Schema mismatch",400);return}p(o,s)},e)),n.on("POST","/:clientVersion/:schemaHash/transaction/start",h(async(i,o,a)=>{g(i,r);let u=await J(i,o);if(u!==null)try{let s=await M(o,r,a);if(s===null)return;let c=await s.startTransaction(u,E(i)),l=Q(c,o);if(l===null)return;let{id:d}=l,S=a.clientVersion,w=a.schemaHash;m(o,{...c,"data-proxy":{endpoint:`http://localhost:${r.port}/${S}/${w}/itx/${d}`}})}catch(s){let{handleEngineError:c}=await $();c(s,o)}},e));let t=[["GET","/connection-info"],["POST","/query"],["POST","/transaction/start"],["POST","/transaction/:transactionId/commit"],["POST","/transaction/:transactionId/query"],["POST","/transaction/:transactionId/rollback"]];for(let[i,o]of t)n.on(i,o,h(async(a,u)=>{g(a,r);let{getQueryPlanExecutorServer:s,queryPlanExecutorVersion:c}=await Cn(),l=T(a.headers,"prisma-engine-hash");if(l!=="0.0.0"&&l!==c)throw new B(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 ${c}.`);let d=await s(r),S=j(a,{origin:`http://localhost:${r.port}`}),w=await d.fetch(S);await F(w,u)},e))}async function M(n,r,e){let{Engine:t}=await $(),i=V(e,n);if(i===null)return null;let{base64Override:o,overrideHash:a}=i.schemas;return await t.get({base64Schema:o,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.clientVersion||"",debug:r.debug,platform:await Ln(),schemaHash:a})}export{he as registerAccelerateRoutes}; |
| import{a as r}from"./chunk-I2OHVRST.js";import{d as h}from"./chunk-JLSS5G22.js";h();import{minLength as S,object as B,optional as x,parseJson as O,pipe as n,regex as f,safeParse as T,string as s,url as l}from"valibot";var y=/^(postgres|postgresql):\/\//,E=n(s(),O(),B({databaseUrl:n(s(),l(),f(y)),name:x(n(s(),S(1))),shadowDatabaseUrl:n(s(),l(),f(y))}));function j(o){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(o).sort(([[e],[t]])=>e.localeCompare(t)))),"utf8").toString("base64url")}function U(o){let e=Buffer.from(o,"base64url").toString("utf8"),{issues:t,output:a,success:i}=T(E,e,{abortEarly:!0});return i?[null,a]:[t]}function k(o,e){let t=o.headers.authorization;if(!t)throw new r(401,"Missing API Key");let[a,i="",P]=t.split(" ");if(a!=="Bearer"||P)throw new r(401,"Invalid API Key");let[c,p]=U(i);if(c)throw new r(401,"Invalid API Key",{cause:c.join(", ")});let{databaseUrl:A,name:d,shadowDatabaseUrl:I}=p,u=e.name,m=e.port;if(!d)throw new r(401,`Wrong API Key; The Prisma Dev server running at port ${m} requires an API Key from a newer version of \`prisma dev\`. Check the "${u}" server's output for the updated \`DATABASE_URL\` value.`);if(d!==u)throw new r(401,`Wrong API Key; The Prisma Dev server running at port ${m} is named "${u}", but the API Key is for "${d}"`);let{hostname:w,port:g}=new URL(A),{port:b}=e.db,{hostname:K,port:v}=new URL(I),D=e.shadowDBPort;if(w!=="localhost"||Number(g)!==b||K!=="localhost"||Number(v)!==D)throw new r(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 p}export{j as a,k as b}; |
| import{e as p,f as g,g as _}from"./chunk-UEE5SWKL.js";import{a as V,c as h,g as C,h as L,i as U,j as M}from"./chunk-MN4XKQ55.js";import{d as m}from"./chunk-JLSS5G22.js";m();import{writeFile as se}from"fs/promises";import{join as b}from"pathe";import{check as oe,lock as ie,unlock as ne}from"proper-lockfile";import{process as K}from"std-env";import{integer as Q,literal as de,minLength as R,minValue as Z,number as z,object as f,optional as l,parseJson as ue,pipe as c,safeParse as le,string as P,url as ce}from"valibot";m();import{setTimeout as te}from"timers/promises";import{process as w}from"std-env";function I(r,e){if(r==null)return!1;try{return w.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}async function j(r,e){if(!w.kill)return!1;try{w.kill(r,"SIGTERM")}catch(a){return e&&console.error(`Error killing process with PID ${r}:`,a),!1}let t=0;do{if(!I(r,e))return!0;await te(100)}while(++t<50);try{return w.kill(r,"SIGKILL")}catch(a){return e&&console.error(`Error forcefully killing process with PID ${r}:`,a),!1}}m();import{join as Y}from"pathe";var re="prisma-wal",xe="prisma-queries";function ae(){return Y(V.data,"durable-streams")}function F(r){return Y(ae(),r)}function Me(r,e=re){return new URL(`/v1/stream/${encodeURIComponent(e)}`,r).toString()}var v=c(P(),ce()),G=f({connectionString:v,prismaORMConnectionString:l(v),terminalCommand:l(P())}),B=f({url:v}),H=f({serverUrl:v,sqlitePath:c(P(),R(1)),streamName:c(P(),R(1)),url:v}),me=f({queryInsights:l(H),streams:l(H)}),E=c(z(),Q(),Z(1)),he=f({database:G,http:B,ppg:B,shadowDatabase:G}),pe=f({databasePort:E,experimental:l(me),exports:l(he),name:c(P(),R(1)),pid:l(c(z(),Q(),Z(0))),port:E,shadowDatabasePort:E,version:de("1")}),N=Symbol("initialize"),k="default",be=new Set(["durable-streams"]),d=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;_streamsPort;constructor(e){this._databasePort=e.databasePort??g,this.databaseConnectTimeoutMillis=e.databaseConnectTimeoutMillis??6e4,this.databaseIdleTimeoutMillis=e.databaseIdleTimeoutMillis??1/0,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??k,this.persistenceMode=e.persistenceMode,this.pid=e.pid??K.pid,this.shadowDatabaseConnectTimeoutMillis=e.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=e.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=e.port??g,this._shadowDatabasePort=e.shadowDatabasePort??g,this._streamsPort=e.streamsPort??g}static async createExclusively(e){let t=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new S(e):new T(e);return await t[N](),t}static async fromServerDump(e){let{debug:t,name:a=k}=e??{},o=h(a),i=S.getServerDumpPath(o),s=await C(i);if(s==null)return t&&console.debug(`[State] No server dump file found at: ${i}`),null;t&&(console.debug(`[State] server dump file found at "${i}":`),console.debug(s));let{issues:n,output:u,success:D}=le(c(P(),ue(),pe),s);if(!D)throw t&&console.debug(`[State] Invalid server dump file at "${i}": | ||
| ${JSON.stringify(n,null,2)}`),new Error(`Invalid Prisma Dev state for "${a}".`);return new S({databasePort:u.databasePort,debug:t,dryRun:!1,name:a,pid:u.pid,port:u.port,serverDump:u,shadowDatabasePort:u.shadowDatabasePort})}static async scan(e){let{debug:t,globs:a}=e??{},o=b(h(k),"..");t&&console.debug(`[State] scanning for server states in: ${o}`);let i=(await U(o,a)).filter(s=>!be.has(s));return t&&console.debug(`[State] found server names: ${JSON.stringify(i)}`),await Promise.all(i.map(s=>W(s,e)))}get databasePort(){return this._databasePort}set databasePort(e){this.#t("databasePort",e)}get port(){return this._port}set port(e){this.#t("port",e)}get shadowDatabasePort(){return this._shadowDatabasePort}get streamsPort(){return this._streamsPort}set shadowDatabasePort(e){this.#t("shadowDatabasePort",e)}#t(e,t){if(t<0||!Number.isInteger(t))throw new Error(`Invalid port number: ${t}`);let a=`_${e}`;if(this[a]!==p&&this[a]!==t)throw new Error(`\`${e}\` is already set to ${this[a]}, cannot change it to ${t}`);this[a]=t}},T=class extends d{constructor(e){super({...e,databasePort:e?.databasePort||p,persistenceMode:"stateless",port:e?.port||p,shadowDatabasePort:e?.shadowDatabasePort||p,streamsPort:e?.streamsPort||p})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[N](){let e;try{e=await d.scan({debug:this.debug,onlyMetadata:!0})}catch(a){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",a),e=[]}let t=await _({debug:this.debug,name:this.dryRun?this.name:"",requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:e});this._databasePort=t.databasePort,this._port=t.port,this._shadowDatabasePort=t.shadowDatabasePort,this._streamsPort=t.streamsPort}async close(){}async writeServerDump(){}},S=class r extends d{#t;#e;#a;#o;#i;#s;#r;constructor(e){super({...e,persistenceMode:"stateful"}),this.#s=!1,this.#e=h(this.name),this.#t=b(this.#e,"db_dump.bak"),this.#a=b(this.#e,".lock"),this.#o=b(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#i=r.getServerDumpPath(this.#e)}static getServerDumpPath(e){return b(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get experimental(){return this.#r?.experimental}get pgliteDataDirPath(){return this.#o}async[N](){await L(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await ie(this.#e,{lockfilePath:this.#a}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await d.scan({debug:this.debug,onlyMetadata:!0}),t=await _({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:e});this._databasePort=t.databasePort,this._port=t.port,this._shadowDatabasePort=t.shadowDatabasePort,this._streamsPort=t.streamsPort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new O(this):e}}async close(){if(!this.#s)try{await ne(this.#e,{lockfilePath:this.#a}),this.#s=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,e),e}}async writeServerDump(e,t){this.#r={name:this.name,version:"1",pid:K.pid,port:this.port,databasePort:this.databasePort,experimental:t,shadowDatabasePort:this.shadowDatabasePort,exports:e},await se(this.#i,`${JSON.stringify(this.#r,null,2)} | ||
| `,{encoding:"utf-8"})}};async function Ce(r,e){await fe(r,e);let t=typeof r=="string"?r:r.name,a=h(t);await M(a),await M(F(t))}async function W(r,e){let{debug:t,onlyMetadata:a}=e||{},o=typeof r=="string"?r:r.name,i=typeof r!="string"?r:void 0,s={databasePort:i?.databasePort??-1,experimental:i?.experimental,exports:i?.exports,name:o,pid:i?.pid,port:i?.port??-1,shadowDatabasePort:i?.shadowDatabasePort??-1,version:"1"};try{let n=i||await d.fromServerDump({debug:t,name:o});if(!n)return t&&console.debug(`[State] no server state found for name: ${o}`),{...s,status:"no_such_server"};s.databasePort=n.databasePort,s.experimental=n.experimental,s.exports=n.exports,s.pid=n.pid,s.port=n.port,s.shadowDatabasePort=n.shadowDatabasePort;let{exports:u,pid:D}=n;if(a)return{...s,status:"unknown"};if(!I(D,t))return t&&console.debug(`[State] server state for "${o}" has no running process with PID: ${D}`),{...s,status:"not_running"};let A=h(o);try{if(!await oe(A,{lockfilePath:b(A,".lock")}))return t&&console.debug(`[State] server state for "${o}" is not locked, indicating it is not running.`),{...s,status:"not_running"}}catch(ee){t&&console.error(`[State] server state for "${o}" failed to check lock:`,ee)}if(!u)return{...s,status:"starting_up"};let{http:X}=u,y=await fetch(`${X.url}/health`,{headers:{connection:"close"}});if(!y.ok)return t&&console.debug(`[State] server state for "${o}" is not live: ${JSON.stringify(y)}`),{...s,status:"not_running"};let x=await y.json();return x.name!==r?(t&&console.debug(`[State] server state for "${o}" has mismatched health response: ${JSON.stringify(x)}`),{...s,status:"unknown"}):(t&&console.debug(`[State] server state for "${r}" is live: ${JSON.stringify(x)}`),{...s,status:"running"})}catch(n){return t&&console.error(`[State] failed to get server status for "${o}":`,n),{...s,status:"error"}}}function Pe(r){let{status:e}=r;return e==="running"||e==="starting_up"}async function fe(r,e){let{pid:t,...a}=typeof r=="string"?await W(r,{debug:e}):r;if(!Pe(a))return!1;let o=await d.fromServerDump({debug:e,name:a.name});if(t==null){e&&console.debug(`[State] No PID found for server "${a.name}" to kill.`);try{await o?.close()}catch{}return!1}let i=await j(t,e);try{await o?.close()}catch{}return i}var $=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},O=class extends ${#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return d.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};export{re as a,xe as b,ae as c,F as d,Me as e,d as f,Ce as g,W as h,Pe as i,fe as j,$ as k,O as l}; |
| import{d as y}from"./chunk-JLSS5G22.js";y();import{existsSync as u,readFileSync as B}from"fs";import{copyFile as A,mkdir as z,readFile as d}from"fs/promises";import{createRequire as E}from"module";import{dirname as v}from"path";import{fileURLToPath as r,pathToFileURL as w}from"url";var T=E(import.meta.url),x=["initdb.wasm","pglite.data","pglite.wasm"],p="pglite-seed.tar.gz",U={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"},P=[...x.map(e=>({fileName:e,kind:"core",name:e})),{fileName:p,kind:"core",name:p},...Object.entries(U).map(([e,t])=>({fileName:t,kind:"extension",name:e}))],f=new Map,L=Symbol.for("@prisma/dev/bundled-pglite-runtime-asset-sources"),c=null;async function H(e){let t=a(e),n=r(t);await z(n,{recursive:!0});let s=[];for(let i of G()){let g=new URL(i.fileName,t),m=r(g);await A(i.sourcePath,m),s.push({...i,destinationPath:m})}return s}function G(){let e=h(),t=a(new URL("./runtime-assets/",import.meta.url));return P.map(n=>({...n,sourcePath:r(l(n.fileName,e,t))}))}async function Q(){await C();let e=_();if(e)return await N(e),await I(e);let t=O(),n=t.href,s=f.get(n);return s||(s=k(t),f.set(n,s)),await s}function V(e){let t=globalThis;t[L]={extensions:Object.fromEntries(Object.entries(e.extensions).map(([n,s])=>[n,o(s)])),fsBundle:o(e.fsBundle),initdbWasm:o(e.initdbWasm),loadDataDir:o(e.loadDataDir),wasmModule:o(e.wasmModule)}}function o(e,t=import.meta.url){return e instanceof URL?e:/^(?:https?:|data:|file:)/.test(e)?new URL(e):e.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(e)?w(e):new URL(e,t)}async function I(e){let t=`bundled:${e.wasmModule.href}:${e.fsBundle.href}`,n=f.get(t);return n||(n=M(e),f.set(t,n)),await n}async function k(e){let t=a(new URL("./runtime-assets/",import.meta.url)),[n,s,i]=await Promise.all([d(l("pglite.data",e,t)),d(l(p,e,t)),d(l("pglite.wasm",e,t))]),g=S();return{extensions:Object.fromEntries(Object.entries(U).map(([m,D])=>[m,l(D,e,t)])),fsBundle:new Blob([Uint8Array.from(n)]),loadDataDir:new Blob([Uint8Array.from(s)]),wasmModule:await g.compile(i)}}async function M(e){let[t,n,s]=await Promise.all([R(e.fsBundle),R(e.loadDataDir),R(e.wasmModule)]),i=S();return{extensions:e.extensions,fsBundle:new Blob([Uint8Array.from(t)]),loadDataDir:new Blob([Uint8Array.from(n)]),wasmModule:await i.compile(s)}}async function N(e){if(e.initdbWasm.protocol!=="file:")return;let t=new URL("initdb.wasm",a(new URL("./",e.initdbWasm))),n=r(t);u(n)||await A(r(e.initdbWasm),n)}function a(e){return e instanceof URL?b(e):b(w(e))}function b(e){return e.href.endsWith("/")?e:new URL(`${e.href}/`)}function h(){let e=T.resolve("@electric-sql/pglite");return a(v(e))}function O(){let e=a(new URL("./",import.meta.url));if(W(e))return e;if(F())return h();throw new Error("Unable to locate PGlite runtime assets. If you bundled @prisma/dev, copy them next to the bundle with copyPrismaDevRuntimeAssets().")}function W(e){return P.every(t=>u(r(new URL(t.fileName,e))))}function _(){return globalThis[L]??null}async function C(){!j()||_()||(c||(c=import("./runtime-assets-manifest.bun.js").then(()=>{}).catch(e=>{throw c=null,e})),await c)}function F(){let e=r(new URL("../package.json",import.meta.url));if(!u(e))return!1;try{return JSON.parse(B(e,"utf8")).name==="@prisma/dev"}catch{return!1}}function j(){return typeof globalThis.Bun<"u"}function S(){let e=globalThis.WebAssembly;if(!e)throw new Error("WebAssembly is not available in this runtime.");return e}async function R(e){if(e.protocol==="file:")return await d(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 l(e,t,n){let s=new URL(e,t);if(u(r(s)))return s;if(n){let i=new URL(e,n);if(u(r(i)))return i}return s}export{H as a,G as b,Q as c,V as d,o as e}; |
| import{d as r}from"./chunk-JLSS5G22.js";r();var e=class extends Error{constructor(u,n,s){super(n,s);this.status=u}name="HTTPError"};export{e as a}; |
| var n=Object.create;var i=Object.defineProperty;var a=Object.getOwnPropertyDescriptor;var p=Object.getOwnPropertyNames;var c=Object.getPrototypeOf,f=Object.prototype.hasOwnProperty;var d=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,o)=>(typeof require<"u"?require:e)[o]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var l=(t,e)=>()=>(t&&(e=t(t=0)),e);var g=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var s=(t,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let m of p(e))!f.call(t,m)&&m!==o&&i(t,m,{get:()=>e[m],enumerable:!(r=a(e,m))||r.enumerable});return t};var h=(t,e,o)=>(o=t!=null?n(c(t)):{},s(e||!t||!t.__esModule?i(o,"default",{value:t,enumerable:!0}):o,t));import D from"path";import{fileURLToPath as L}from"url";var _=l(()=>{"use strict"});export{d as a,g as b,h as c,_ as d}; |
| import{d as c}from"./chunk-JLSS5G22.js";c();import{createWriteStream as A,WriteStream as D}from"fs";import{access as x,chmod as P,constants as T,mkdir as E,readdir as _,readFile as F,rm as O,writeFile as v}from"fs/promises";import{promisify as C}from"util";import{unzip as L}from"zlib";c();import o from"path";import l from"os";import a from"process";var n=l.homedir(),p=l.tmpdir(),{env:e}=a,y=t=>{let r=o.join(n,"Library");return{data:o.join(r,"Application Support",t),config:o.join(r,"Preferences",t),cache:o.join(r,"Caches",t),log:o.join(r,"Logs",t),temp:o.join(p,t)}},j=t=>{let r=e.APPDATA||o.join(n,"AppData","Roaming"),i=e.LOCALAPPDATA||o.join(n,"AppData","Local");return{data:o.join(i,t,"Data"),config:o.join(r,t,"Config"),cache:o.join(i,t,"Cache"),log:o.join(i,t,"Log"),temp:o.join(p,t)}},w=t=>{let r=o.basename(n);return{data:o.join(e.XDG_DATA_HOME||o.join(n,".local","share"),t),config:o.join(e.XDG_CONFIG_HOME||o.join(n,".config"),t),cache:o.join(e.XDG_CACHE_HOME||o.join(n,".cache"),t),log:o.join(e.XDG_STATE_HOME||o.join(n,".local","state"),t),temp:o.join(p,r,t)}};function u(t,{suffix:r="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return r&&(t+=`-${r}`),a.platform==="darwin"?y(t):a.platform==="win32"?j(t):w(t)}import G from"zeptomatch";var m=u("prisma-dev"),$=C(L);function B(t,r){return`${m.cache}/engine/${t}/${r}`}function J(t){return`${m.data}/${t}`}async function K(t){try{return await x(t,T.F_OK),!0}catch(r){if(f(r))return!1;throw r}}async function q(t,r){let i=await $(t);await v(r,i),await P(r,"755")}async function Q(t,r){await t.stream().pipeTo(D.toWeb(A(r,{encoding:"utf8"})))}function f(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function U(t){try{return await F(t,{encoding:"utf-8"})}catch(r){if(f(r))return null;throw r}}async function V(t){await E(t,{recursive:!0})}async function Y(t,r){try{return(await _(t,{withFileTypes:!0})).reduce((g,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!r||G(r,s.name))&&g.push(s.name),g),[])}catch(i){if(f(i))return[];throw i}}async function Z(t){await O(t,{force:!0,recursive:!0})}export{m as a,B as b,J as c,K as d,q as e,Q as f,U as g,V as h,Y as i,Z as j}; |
| import{a as et}from"./chunk-DEMTR4W3.js";import{a as rt,b as nt,f as Oe}from"./chunk-WQHUHPVC.js";import{a as it,b as Ie,c as at,d as Te,e as ae,f as ot}from"./chunk-GT33FFME.js";import{d as tt,j as Z}from"./chunk-MN4XKQ55.js";import{b as st}from"./chunk-T6L5TENJ.js";import{a as ie,b as P,c as Fr,d as h}from"./chunk-JLSS5G22.js";var ft=P((xs,ut)=>{"use strict";h();var lt=12,Qr=0,Ne=[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 Gr(t){var e=t.indexOf("%");if(e===-1)return t;for(var r=t.length,n="",s=0,i=0,a=e,o=lt;e>-1&&e<r;){var l=ct(t[e+1],4),f=ct(t[e+2],0),c=l|f,u=Ne[c];if(o=Ne[256+o+u],i=i<<6|c&Ne[364+u],o===lt)n+=t.slice(s,a),n+=i<=65535?String.fromCharCode(i):String.fromCharCode(55232+(i>>10),56320+(i&1023)),i=0,s=e+3,e=a=t.indexOf("%",s);else{if(o===Qr)return null;if(e+=3,e<r&&t.charCodeAt(e)===37)continue;return null}}return n+t.slice(s)}var Kr={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 ct(t,e){var r=Kr[t];return r===void 0?255:r<<e}ut.exports=Gr});var gt=P((Cs,mt)=>{"use strict";h();var ht=ft(),dt=/\+/g,pt=function(){};pt.prototype=Object.create(null);function Vr(t){let e=new pt;if(typeof t!="string")return e;let r=t.length,n="",s="",i=-1,a=-1,o=!1,l=!1,f=!1,c=!1,u=!1,d=0;for(let p=0;p<r+1;p++)if(d=p!==r?t.charCodeAt(p):38,d===38){if(u=a>i,u||(a=p),n=t.slice(i+1,a),u||n.length>0){f&&(n=n.replace(dt," ")),o&&(n=ht(n)||n),u&&(s=t.slice(a+1,p),c&&(s=s.replace(dt," ")),l&&(s=ht(s)||s));let x=e[n];x===void 0?e[n]=s:x.pop?x.push(s):e[n]=[x,s]}s="",i=p,a=p,o=!1,l=!1,f=!1,c=!1}else d===61?a<=i?a=p:l=!0:d===43?a>i?c=!0:f=!0:d===37&&(a>i?l=!0:o=!0);return e}mt.exports=Vr});var St=P((As,yt)=>{"use strict";h();var D=Array.from({length:256},(t,e)=>"%"+((e<16?"0":"")+e.toString(16)).toUpperCase()),zr=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 Yr(t){let e=t.length;if(e===0)return"";let r="",n=0,s=0;e:for(;s<e;s++){let i=t.charCodeAt(s);for(;i<128;){if(zr[i]!==1&&(n<s&&(r+=t.slice(n,s)),n=s+1,r+=D[i]),++s===e)break e;i=t.charCodeAt(s)}if(n<s&&(r+=t.slice(n,s)),i<2048){n=s+1,r+=D[192|i>>6]+D[128|i&63];continue}if(i<55296||i>=57344){n=s+1,r+=D[224|i>>12]+D[128|i>>6&63]+D[128|i&63];continue}if(++s,s>=e)throw new Error("URI malformed");let a=t.charCodeAt(s)&1023;n=s+1,i=65536+((i&1023)<<10|a),r+=D[240|i>>18]+D[128|i>>12&63]+D[128|i>>6&63]+D[128|i&63]}return n===0?t:n<e?r+t.slice(n):r}yt.exports={encodeString:Yr}});var bt=P((Os,Pt)=>{"use strict";h();var{encodeString:Me}=St();function vt(t){let e=typeof t;return e==="string"?Me(t):e==="bigint"?t.toString():e==="boolean"?t?"true":"false":e==="number"&&Number.isFinite(t)?t<1e21?""+t:Me(""+t):""}function Jr(t){let e="";if(t===null||typeof t!="object")return e;let r="&",n=Object.keys(t),s=n.length,i=0;for(let a=0;a<s;a++){let o=n[a],l=t[o],f=Me(o)+"=";if(a&&(e+=r),Array.isArray(l)){i=l.length;for(let c=0;c<i;c++)c&&(e+=r),e+=f,e+=vt(l[c])}else e+=f,e+=vt(l)}return e}Pt.exports=Jr});var Ct=P((Ts,ee)=>{"use strict";h();var Et=gt(),xt=bt(),wt={parse:Et,stringify:xt};ee.exports=wt;ee.exports.default=wt;ee.exports.parse=Et;ee.exports.stringify=xt});var At=P(Rt=>{"use strict";h();Object.defineProperty(Rt,"__esModule",{value:!0})});var _t=P(te=>{"use strict";h();Object.defineProperty(te,"__esModule",{value:!0});te.types=void 0;var Xr;(function(t){t[t.ROOT=0]="ROOT",t[t.GROUP=1]="GROUP",t[t.POSITION=2]="POSITION",t[t.SET=3]="SET",t[t.RANGE=4]="RANGE",t[t.REPETITION=5]="REPETITION",t[t.REFERENCE=6]="REFERENCE",t[t.CHAR=7]="CHAR"})(Xr=te.types||(te.types={}))});var It=P(Ot=>{"use strict";h();Object.defineProperty(Ot,"__esModule",{value:!0})});var B=P(U=>{"use strict";h();var Zr=U&&U.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),$e=U&&U.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Zr(e,t,r)};Object.defineProperty(U,"__esModule",{value:!0});$e(At(),U);$e(_t(),U);$e(It(),U)});var oe=P(_=>{"use strict";h();Object.defineProperty(_,"__esModule",{value:!0});_.anyChar=_.notWhitespace=_.whitespace=_.notInts=_.ints=_.notWords=_.words=void 0;var v=B(),Tt=()=>[{type:v.types.RANGE,from:48,to:57}],Nt=()=>[{type:v.types.CHAR,value:95},{type:v.types.RANGE,from:97,to:122},{type:v.types.RANGE,from:65,to:90},{type:v.types.RANGE,from:48,to:57}],Mt=()=>[{type:v.types.CHAR,value:9},{type:v.types.CHAR,value:10},{type:v.types.CHAR,value:11},{type:v.types.CHAR,value:12},{type:v.types.CHAR,value:13},{type:v.types.CHAR,value:32},{type:v.types.CHAR,value:160},{type:v.types.CHAR,value:5760},{type:v.types.RANGE,from:8192,to:8202},{type:v.types.CHAR,value:8232},{type:v.types.CHAR,value:8233},{type:v.types.CHAR,value:8239},{type:v.types.CHAR,value:8287},{type:v.types.CHAR,value:12288},{type:v.types.CHAR,value:65279}],en=()=>[{type:v.types.CHAR,value:10},{type:v.types.CHAR,value:13},{type:v.types.CHAR,value:8232},{type:v.types.CHAR,value:8233}];_.words=()=>({type:v.types.SET,set:Nt(),not:!1});_.notWords=()=>({type:v.types.SET,set:Nt(),not:!0});_.ints=()=>({type:v.types.SET,set:Tt(),not:!1});_.notInts=()=>({type:v.types.SET,set:Tt(),not:!0});_.whitespace=()=>({type:v.types.SET,set:Mt(),not:!1});_.notWhitespace=()=>({type:v.types.SET,set:Mt(),not:!0});_.anyChar=()=>({type:v.types.SET,set:en(),not:!0})});var Dt=P(T=>{"use strict";h();var tn=T&&T.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),rn=T&&T.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),nn=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&tn(e,t,r);return rn(e,t),e};Object.defineProperty(T,"__esModule",{value:!0});T.tokenizeClass=T.strToChars=void 0;var $t=B(),V=nn(oe()),sn="@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?";T.strToChars=t=>{let e=/(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|c([@A-Z[\\\]^?])|([0tnvfr]))/g;return t.replace(e,(r,n,s,i,a,o,l)=>{if(s)return r;let f=n?8:i?parseInt(i,16):a?parseInt(a,16):o?sn.indexOf(o):{0:0,t:9,n:10,v:11,f:12,r:13}[l],c=String.fromCharCode(f);return/[[\]{}^$.|?*+()]/.test(c)?`\\${c}`:c})};T.tokenizeClass=(t,e)=>{var r,n,s,i,a,o,l;let f=[],c,u,d=/\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(((?:\\)])|(((?:\\)?([^\]])))))|(\])|(?:\\)?([^])/g;for(;(c=d.exec(t))!==null;){let p=(l=(o=(a=(i=(s=(n=(r=c[1]&&V.words())!==null&&r!==void 0?r:c[2]&&V.ints())!==null&&n!==void 0?n:c[3]&&V.whitespace())!==null&&s!==void 0?s:c[4]&&V.notWords())!==null&&i!==void 0?i:c[5]&&V.notInts())!==null&&a!==void 0?a:c[6]&&V.notWhitespace())!==null&&o!==void 0?o:c[7]&&{type:$t.types.RANGE,from:(c[8]||c[9]).charCodeAt(0),to:(u=c[10]).charCodeAt(u.length-1)})!==null&&l!==void 0?l:(u=c[16])&&{type:$t.types.CHAR,value:u.charCodeAt(0)};if(p)f.push(p);else return[f,d.lastIndex]}throw new SyntaxError(`Invalid regular expression: /${e}/: Unterminated character class`)}});var De=P(j=>{"use strict";h();var an=j&&j.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),on=j&&j.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),qt=j&&j.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&an(e,t,r);return on(e,t),e};Object.defineProperty(j,"__esModule",{value:!0});j.tokenizer=void 0;var jt=qt(Dt()),R=B(),Q=qt(oe()),ln=/^[a-zA-Z_$]$/i,cn=/^[a-zA-Z0-9_$]$/i,kt=/\d/;j.tokenizer=t=>{let e=0,r,n={type:R.types.ROOT,stack:[]},s=n,i=n.stack,a=[],o=[],l=0,f=u=>{throw new SyntaxError(`Invalid regular expression: /${t}/: Nothing to repeat at column ${u-1}`)},c=jt.strToChars(t);for(;e<c.length;)switch(r=c[e++]){case"\\":if(e===c.length)throw new SyntaxError(`Invalid regular expression: /${t}/: \\ at end of pattern`);switch(r=c[e++]){case"b":i.push({type:R.types.POSITION,value:"b"});break;case"B":i.push({type:R.types.POSITION,value:"B"});break;case"w":i.push(Q.words());break;case"W":i.push(Q.notWords());break;case"d":i.push(Q.ints());break;case"D":i.push(Q.notInts());break;case"s":i.push(Q.whitespace());break;case"S":i.push(Q.notWhitespace());break;default:if(kt.test(r)){let u=r;for(;e<c.length&&kt.test(c[e]);)u+=c[e++];let d=parseInt(u,10),p={type:R.types.REFERENCE,value:d};i.push(p),o.push({reference:p,stack:i,index:i.length-1})}else i.push({type:R.types.CHAR,value:r.charCodeAt(0)})}break;case"^":i.push({type:R.types.POSITION,value:"^"});break;case"$":i.push({type:R.types.POSITION,value:"$"});break;case"[":{let u;c[e]==="^"?(u=!0,e++):u=!1;let d=jt.tokenizeClass(c.slice(e),t);e+=d[1],i.push({type:R.types.SET,set:d[0],not:u});break}case".":i.push(Q.anyChar());break;case"(":{let u={type:R.types.GROUP,stack:[],remember:!0};if(c[e]==="?")if(r=c[e+1],e+=2,r==="=")u.followedBy=!0,u.remember=!1;else if(r==="!")u.notFollowedBy=!0,u.remember=!1;else if(r==="<"){let d="";if(ln.test(c[e]))d+=c[e],e++;else throw new SyntaxError(`Invalid regular expression: /${t}/: Invalid capture group name, character '${c[e]}' after '<' at column ${e+1}`);for(;e<c.length&&cn.test(c[e]);)d+=c[e],e++;if(!d)throw new SyntaxError(`Invalid regular expression: /${t}/: Invalid capture group name, character '${c[e]}' after '<' at column ${e+1}`);if(c[e]!==">")throw new SyntaxError(`Invalid regular expression: /${t}/: Unclosed capture group name, expected '>', found '${c[e]}' at column ${e+1}`);u.name=d,e++}else if(r===":")u.remember=!1;else throw new SyntaxError(`Invalid regular expression: /${t}/: Invalid group, character '${r}' after '?' at column ${e-1}`);else l+=1;i.push(u),a.push(s),s=u,i=u.stack;break}case")":if(a.length===0)throw new SyntaxError(`Invalid regular expression: /${t}/: Unmatched ) at column ${e-1}`);s=a.pop(),i=s.options?s.options[s.options.length-1]:s.stack;break;case"|":{s.options||(s.options=[s.stack],delete s.stack);let u=[];s.options.push(u),i=u;break}case"{":{let u=/^(\d+)(,(\d+)?)?\}/.exec(c.slice(e)),d,p;u!==null?(i.length===0&&f(e),d=parseInt(u[1],10),p=u[2]?u[3]?parseInt(u[3],10):1/0:d,e+=u[0].length,i.push({type:R.types.REPETITION,min:d,max:p,value:i.pop()})):i.push({type:R.types.CHAR,value:123});break}case"?":i.length===0&&f(e),i.push({type:R.types.REPETITION,min:0,max:1,value:i.pop()});break;case"+":i.length===0&&f(e),i.push({type:R.types.REPETITION,min:1,max:1/0,value:i.pop()});break;case"*":i.length===0&&f(e),i.push({type:R.types.REPETITION,min:0,max:1/0,value:i.pop()});break;default:i.push({type:R.types.CHAR,value:r.charCodeAt(0)})}if(a.length!==0)throw new SyntaxError(`Invalid regular expression: /${t}/: Unterminated group`);return un(o,l),n};function un(t,e){for(let r of t.reverse())if(e<r.reference.value){r.reference.type=R.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 a of n.slice(s))r.stack.push({type:R.types.CHAR,value:a.charCodeAt(0)});r.stack.push(...i)}}}}});var Bt=P(O=>{"use strict";h();var fn=O&&O.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),hn=O&&O.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),dn=O&&O.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&fn(e,t,r);return hn(e,t),e};Object.defineProperty(O,"__esModule",{value:!0});O.NOTANYCHAR=O.WHITESPACE=O.WORDS=O.INTS=void 0;var le=dn(oe()),Ut=B();function ce(t){let e={},r=0;for(let n of t)n.type===Ut.types.CHAR&&(e[n.value]=!0),n.type===Ut.types.RANGE&&(e[`${n.from}-${n.to}`]=!0),r+=1;return{lookup:()=>Object.assign({},e),len:r}}O.INTS=ce(le.ints().set);O.WORDS=ce(le.words().set);O.WHITESPACE=ce(le.whitespace().set);O.NOTANYCHAR=ce(le.anyChar().set)});var Wt=P(N=>{"use strict";h();var pn=N&&N.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),mn=N&&N.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),gn=N&&N.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&pn(e,t,r);return mn(e,t),e};Object.defineProperty(N,"__esModule",{value:!0});N.writeSetTokens=N.setChar=void 0;var de=B(),ue=gn(Bt());function he(t){return t===94?"\\^":t===92?"\\\\":t===93?"\\]":t===45?"\\-":String.fromCharCode(t)}N.setChar=he;function fe(t,{lookup:e,len:r}){if(r!==t.length)return!1;let n=e();for(let s of t){if(s.type===de.types.SET)return!1;let i=s.type===de.types.CHAR?s.value:`${s.from}-${s.to}`;if(n[i])n[i]=!1;else return!1}return!0}function Ht(t,e=!1){if(fe(t.set,ue.INTS))return t.not?"\\D":"\\d";if(fe(t.set,ue.WORDS))return t.not?"\\W":"\\w";if(t.not&&fe(t.set,ue.NOTANYCHAR))return".";if(fe(t.set,ue.WHITESPACE))return t.not?"\\S":"\\s";let r="";for(let s=0;s<t.set.length;s++){let i=t.set[s];r+=yn(i)}let n=`${t.not?"^":""}${r}`;return e?n:`[${n}]`}N.writeSetTokens=Ht;function yn(t){return t.type===de.types.CHAR?he(t.value):t.type===de.types.RANGE?`${he(t.from)}-${he(t.to)}`:Ht(t,!0)}});var ke=P(z=>{"use strict";h();Object.defineProperty(z,"__esModule",{value:!0});z.reconstruct=void 0;var L=B(),je=Wt(),Lt=t=>t.map(z.reconstruct).join(""),Ft=t=>{if("options"in t)return t.options.map(Lt).join("|");if("stack"in t)return Lt(t.stack);throw new Error("options or stack must be Root or Group token")};z.reconstruct=t=>{switch(t.type){case L.types.ROOT:return Ft(t);case L.types.CHAR:{let e=String.fromCharCode(t.value);return(/[[\\{}$^.|?*+()]/.test(e)?"\\":"")+e}case L.types.POSITION:return t.value==="^"||t.value==="$"?t.value:`\\${t.value}`;case L.types.REFERENCE:return`\\${t.value}`;case L.types.SET:return je.writeSetTokens(t);case L.types.GROUP:return`(${t.name?`?<${t.name}>`:t.remember?"":t.followedBy?"?=":t.notFollowedBy?"?!":"?:"}${Ft(t)})`;case L.types.REPETITION:{let{min:e,max:r}=t,n;return e===0&&r===1?n="?":e===1&&r===1/0?n="+":e===0&&r===1/0?n="*":r===1/0?n=`{${e},}`:e===r?n=`{${e}}`:n=`{${e},${r}}`,`${z.reconstruct(t.value)}${n}`}case L.types.RANGE:return`${je.setChar(t.from)}-${je.setChar(t.to)}`;default:throw new Error(`Invalid token type ${t}`)}}});var Ue=P((M,pe)=>{"use strict";h();var Sn=M&&M.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),qe=M&&M.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Sn(e,t,r)};Object.defineProperty(M,"__esModule",{value:!0});M.types=void 0;var Qt=B();Object.defineProperty(M,"types",{enumerable:!0,get:function(){return Qt.types}});qe(De(),M);qe(ke(),M);var Gt=De(),vn=ke();qe(B(),M);M.default=Gt.tokenizer;pe.exports=Gt.tokenizer;pe.exports.types=Qt.types;pe.exports.reconstruct=vn.reconstruct});var Kt=P((ei,me)=>{"use strict";h();var Pn=Ue(),{types:bn}=Ue();function Be(t,e,r){let n,s,i;if(t.type===bn.REPETITION&&(r++,e.reps++,r>1||e.reps>e.limit))return!1;let a=t.options||t.value?.options;if(a){for(n=0,i=a.length;n<i;n++)if(s=Be({stack:a[n]},e,r),!s)return!1}let o=t.stack||t.value?.stack;if(!o)return!0;for(n=0,i=o.length;n<i;n++)if(s=Be(o[n],e,r),!s)return!1;return!0}function He(t,e){let r={reps:0,limit:e?.limit??25};En(t)?t=t.source:typeof t!="string"&&(t=String(t));try{return Be(Pn(t),r,0)}catch{return!1}}function En(t){return Object.prototype.toString.call(t)==="[object RegExp]"}me.exports=He;me.exports.default=He;me.exports.safeRegex=He});var We=P((ri,Vt)=>{"use strict";h();Vt.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,s,i;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(i=Object.keys(e),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 a=i[s];if(!t(e[a],r[a]))return!1}return!0}return e!==e&&r!==r}});var ge=P((si,zt)=>{"use strict";h();zt.exports={name:"__fmw_internal_strategy_merged_tree_http_method__",storage:function(){let t=new Map;return{get:e=>t.get(e)||null,set:(e,r)=>{t.set(e,r)}}},deriveConstraint:t=>t.method,mustMatchWhenDerived:!0}});var rr=P((ai,tr)=>{"use strict";h();var Yt=We(),Jt=ge(),Xt=Symbol("treeData");function Zt(t,e=""){let r="",n=Object.keys(t);for(let s=0;s<n.length;s++){let i=n[s],a=t[i],o=s===n.length-1,l=o?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",f=o?" ":"\u2502 ",u=(a[Xt]||"").replaceAll(` | ||
| `,` | ||
| `+e+f);r+=e+l+i+u+` | ||
| `,r+=Zt(a,e+f)}return r}function xn(t){let e=t.name||"";return e=e.replace("bound","").trim(),e=(e||"anonymous")+"()",e}function er(t){return Array.isArray(t)?t.map(e=>er(e)):typeof t=="symbol"?t.toString():typeof t=="function"?xn(t):t}function wn(t,e){if(!e.includeMeta)return{};let r=e.buildPrettyMeta(t),n={},s=e.includeMeta;Array.isArray(s)||(s=Reflect.ownKeys(r));for(let i of s){if(!Object.prototype.hasOwnProperty.call(r,i))continue;let a=i.toString(),o=r[i];if(o!=null){let l=JSON.stringify(er(o));n[a]=l}}return n}function Cn(t){let e="";for(let[r,n]of Object.entries(t))e+=` | ||
| \u2022 (${r}) ${n}`;return e}function Rn(t){let e={...t.opts.constraints},r=e[Jt.name];return delete e[Jt.name],{...t,method:r,opts:{constraints:e}}}function An(t){let e=` (${t.method})`,r=t.opts.constraints||{};return Object.keys(r).length!==0&&(e+=" "+JSON.stringify(r)),e+=Cn(t.metaData),e}function _n(t){return t.reduce((e,r)=>{for(let n of e)if(Yt(r.opts.constraints,n.opts.constraints)&&Yt(r.metaData,n.metaData))return n.method+=", "+r.method,e;return e.push(r),e},[])}function On(t,e,r){let n=t.routes;return r.method===void 0&&(n=n.map(Rn)),n=n.map(s=>(s.metaData=wn(s,r),s)),r.method===void 0&&(n=_n(n)),n.map(An).join(` | ||
| ${e}`)}function ye(t,e,r,n){if((t.isLeafNode||n.commonPrefix!==!1)&&(r=r||"(empty root node)",e=e[r]={},t.isLeafNode&&(e[Xt]=On(t,r,n)),r=""),t.staticChildren)for(let s of Object.values(t.staticChildren))ye(s,e,r+s.prefix,n);if(t.parametricChildren)for(let s of Object.values(t.parametricChildren)){let i=Array.from(s.nodePaths).join("|");ye(s,e,r+i,n)}t.wildcardChild&&ye(t.wildcardChild,e,"*",n)}function In(t,e){let r={};return ye(t,r,t.prefix,e),Zt(r)}tr.exports={prettyPrintTree:In}});var ir=P((li,sr)=>{"use strict";h();var nr=function(){};nr.prototype=Object.create(null);sr.exports={NullObject:nr}});var or=P((ui,ar)=>{"use strict";h();var{NullObject:Tn}=ir(),Nn=ge(),Le=class{constructor(){this.unconstrainedHandler=null,this.constraints=[],this.handlers=[],this.constrainedHandlerStores=null}getMatchingHandler(e){return e===void 0?this.unconstrainedHandler:this._getHandlerMatchingConstraints(e)}addHandler(e,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)},a=Object.keys(s);a.length===0&&(this.unconstrainedHandler=i);for(let l of a)this.constraints.includes(l)||(l==="version"?this.constraints.unshift(l):this.constraints.push(l));let o=a.includes(Nn.name);if(!o&&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((l,f)=>Object.keys(l.constraints).length-Object.keys(f.constraints).length),o||this._compileGetHandlerMatchingConstraints(e,s)}_compileCreateParamsObject(e){let r=[];r.push("const fn = function _createParamsObject (paramsArray) {"),r.push("const params = new NullObject()");for(let n=0;n<e.length;n++)r.push(`params['${e[n]}'] = paramsArray[${n}]`);return r.push("return params"),r.push("}"),r.push("return fn"),new Function("NullObject",r.join(` | ||
| `))(Tn)}_getHandlerMatchingConstraints(){return null}_buildConstraintStore(e,r){for(let n=0;n<this.handlers.length;n++){let i=this.handlers[n].constraints[r];if(i!==void 0){let a=e.get(i)||0;a|=1<<n,e.set(i,a)}}}_constrainedIndexBitmask(e){let r=0;for(let n=0;n<this.handlers.length;n++)this.handlers[n].constraints[e]!==void 0&&(r|=1<<n);return~r}_compileGetHandlerMatchingConstraints(e){this.constrainedHandlerStores={};for(let n of this.constraints){let s=e.newStoreForConstraint(n);this.constrainedHandlerStores[n]=s,this._buildConstraintStore(s,n)}let r=[];r.push(` | ||
| let candidates = ${(1<<this.handlers.length)-1} | ||
| let mask, matches | ||
| `);for(let n of this.constraints){r.push(` | ||
| mask = ${this._constrainedIndexBitmask(n)} | ||
| value = derivedConstraints.${n} | ||
| `);let i=e.strategies[n].mustMatchWhenDerived?"matches":"(matches | mask)";r.push(` | ||
| if (value === undefined) { | ||
| candidates &= mask | ||
| } else { | ||
| matches = this.constrainedHandlerStores.${n}.get(value) || 0 | ||
| candidates &= ${i} | ||
| } | ||
| if (candidates === 0) return null; | ||
| `)}for(let n in e.strategies){if(!Object.hasOwn(e.strategies,n))continue;e.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(` | ||
| `))}};ar.exports=Le});var cr=P((hi,lr)=>{"use strict";h();var Mn=or(),xe={STATIC:0,PARAMETRIC:1,WILDCARD:2},Se=class{constructor(){this.isLeafNode=!1,this.routes=null,this.handlerStorage=null}addRoute(e,r){this.routes===null&&(this.routes=[]),this.handlerStorage===null&&(this.handlerStorage=new Mn),this.isLeafNode=!0,this.routes.push(e),this.handlerStorage.addHandler(r,e)}},ve=class extends Se{constructor(){super(),this.staticChildren={}}findStaticMatchingChild(e,r){let n=this.staticChildren[e.charAt(r)];return n===void 0||!n.matchPrefix(e,r)?null:n}getStaticChild(e,r=0){if(e.length===r)return this;let n=this.findStaticMatchingChild(e,r);return n?n.getStaticChild(e,r+n.prefix.length):null}createStaticChild(e){if(e.length===0)return this;let r=this.staticChildren[e.charAt(0)];if(r){let s=1;for(;s<r.prefix.length;s++)if(e.charCodeAt(s)!==r.prefix.charCodeAt(s)){r=r.split(this,s);break}return r.createStaticChild(e.slice(s))}let n=e.charAt(0);return this.staticChildren[n]=new Pe(e),this.staticChildren[n]}},Pe=class t extends ve{constructor(e){super(),this.prefix=e,this.wildcardChild=null,this.parametricChildren=[],this.kind=xe.STATIC,this._compilePrefixMatch()}getParametricChild(e){let r=e&&e.source,n=this.parametricChildren.find(s=>(s.regex&&s.regex.source)===r);return n||null}createParametricChild(e,r,n){let s=this.getParametricChild(e);return s?(s.nodePaths.add(n),s):(s=new be(e,r,n),this.parametricChildren.push(s),this.parametricChildren.sort((i,a)=>i.isRegex?a.isRegex?i.staticSuffix===null?1:a.staticSuffix===null?-1:a.staticSuffix.endsWith(i.staticSuffix)?1:i.staticSuffix.endsWith(a.staticSuffix)?-1:0:-1:1),s)}getWildcardChild(){return this.wildcardChild}createWildcardChild(){return this.wildcardChild=this.getWildcardChild()||new Ee,this.wildcardChild}split(e,r){let n=this.prefix.slice(0,r),s=this.prefix.slice(r);this.prefix=s,this._compilePrefixMatch();let i=new t(n);return i.staticChildren[s.charAt(0)]=this,e.staticChildren[n.charAt(0)]=i,i}getNextNode(e,r,n,s){let i=this.findStaticMatchingChild(e,r),a=0;if(i===null){if(this.parametricChildren.length===0)return this.wildcardChild;i=this.parametricChildren[0],a=1}this.wildcardChild!==null&&n.push({paramsCount:s,brotherPathIndex:r,brotherNode:this.wildcardChild});for(let o=this.parametricChildren.length-1;o>=a;o--)n.push({paramsCount:s,brotherPathIndex:r,brotherNode:this.parametricChildren[o]});return i}_compilePrefixMatch(){if(this.prefix.length===1){this.matchPrefix=()=>!0;return}let e=[];for(let r=1;r<this.prefix.length;r++){let n=this.prefix.charCodeAt(r);e.push(`path.charCodeAt(i + ${r}) === ${n}`)}this.matchPrefix=new Function("path","i",`return ${e.join(" && ")}`)}},be=class extends ve{constructor(e,r,n){super(),this.isRegex=!!e,this.regex=e||null,this.staticSuffix=r||null,this.kind=xe.PARAMETRIC,this.nodePaths=new Set([n])}getNextNode(e,r){return this.findStaticMatchingChild(e,r)}},Ee=class extends Se{constructor(){super(),this.kind=xe.WILDCARD}getNextNode(){return null}};lr.exports={StaticNode:Pe,ParametricNode:be,WildcardNode:Ee,NODE_TYPES:xe}});var fr=P((pi,ur)=>{"use strict";h();var $n=ie("assert");function re(){if(!(this instanceof re))return new re;this.store=new Map,this.maxMajor=0,this.maxMinors={},this.maxPatches={}}re.prototype.set=function(t,e){if(typeof t!="string")throw new TypeError("Version should be a string");let[r,n,s]=t.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",e),this.store.set("*",e),this.store.set("x.x",e),this.store.set("x.x.x",e)),n>=(this.maxMinors[r]||0)&&(this.maxMinors[r]=n,this.store.set(`${r}.x`,e),this.store.set(`${r}.x.x`,e)),s>=(this.maxPatches[`${r}.${n}`]||0)&&(this.maxPatches[`${r}.${n}`]=s,this.store.set(`${r}.${n}.x`,e)),this.store.set(`${r}.${n}.${s}`,e),this};re.prototype.get=function(t){return this.store.get(t)};ur.exports={name:"version",mustMatchWhenDerived:!0,storage:re,validate(t){$n(typeof t=="string","Version should be a string")}}});var dr=P((gi,hr)=>{"use strict";h();var Dn=ie("assert");function jn(){let t=new Map,e=[],r=new Map;return{get:n=>{let s=t.get(n);if(s)return s;if(e.length!==0){if(r.has(n))return r.get(n);for(let i of e)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,""));e.push({host:i,value:s}),r.clear()}else t.set(n,s)}}}hr.exports={name:"host",mustMatchWhenDerived:!1,storage:jn,validate(t){Dn(typeof t=="string"||Object.prototype.toString.call(t)==="[object RegExp]","Host should be a string or a RegExp")}}});var mr=P((Si,pr)=>{"use strict";h();var kn=fr(),qn=dr(),Fe=ie("assert"),Qe=class{constructor(e){if(this.strategies={version:kn,host:qn},this.strategiesInUse=new Set,this.asyncStrategiesInUse=new Set,e)for(let r of Object.values(e))this.addConstraintStrategy(r)}isStrategyUsed(e){return this.strategiesInUse.has(e)||this.asyncStrategiesInUse.has(e)}hasConstraintStrategy(e){let r=this.strategies[e];return r!==void 0?r.isCustom||this.isStrategyUsed(e):!1}addConstraintStrategy(e){if(Fe(typeof e.name=="string"&&e.name!=="","strategy.name is required."),Fe(e.storage&&typeof e.storage=="function","strategy.storage function is required."),Fe(e.deriveConstraint&&typeof e.deriveConstraint=="function","strategy.deriveConstraint function is required."),this.strategies[e.name]&&this.strategies[e.name].isCustom)throw new Error(`There already exists a custom constraint with the name ${e.name}.`);if(this.isStrategyUsed(e.name))throw new Error(`There already exists a route with ${e.name} constraint.`);e.isCustom=!0,e.isAsync=e.deriveConstraint.length===3,this.strategies[e.name]=e,e.mustMatchWhenDerived&&this.noteUsage({[e.name]:e})}deriveConstraints(e,r,n){let s=this.deriveSyncConstraints(e,r);if(n===void 0)return s;this.deriveAsyncConstraints(s,e,r,n)}deriveSyncConstraints(e,r){}noteUsage(e){if(e){let r=this.strategiesInUse.size;for(let n in e){if(!Object.hasOwn(e,n))continue;this.strategies[n].isAsync?this.asyncStrategiesInUse.add(n):this.strategiesInUse.add(n)}r!==this.strategiesInUse.size&&this._buildDeriveConstraints()}}newStoreForConstraint(e){if(!this.strategies[e])throw new Error(`No strategy registered for constraint key ${e}`);return this.strategies[e].storage()}validateConstraints(e){for(let r in e){if(!Object.hasOwn(e,r))continue;let n=e[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(e,r,n,s){let i=this.asyncStrategiesInUse.size;if(i===0){s(null,e);return}let a=!1;e=e||{};for(let o of this.asyncStrategiesInUse)this.strategies[o].deriveConstraint(r,n,(f,c)=>{if(!a){if(f!==null){a=!0,s(f);return}e[o]=c,--i===0&&s(null,e)}})}_buildDeriveConstraints(){if(this.strategiesInUse.size===0)return;let e=["return {"];for(let r of this.strategiesInUse){let n=this.strategies[r];n.isCustom?e.push(` ${n.name}: this.strategies.${r}.deriveConstraint(req, ctx),`):r==="version"?e.push(" version: req.headers['accept-version'],"):e.push(" host: req.headers.host || req.headers[':authority'],")}e.push("}"),this.deriveSyncConstraints=new Function("req","ctx",e.join(` | ||
| `)).bind(this)}};pr.exports=Qe});var yr=P((Pi,gr)=>{"use strict";h();var Un=["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"];gr.exports=Un});var Pr=P((Ei,vr)=>{"use strict";h();function Sr(t,e){return t===50?e===53?"%":e===51?"#":e===52?"$":e===54?"&":e===66||e===98?"+":e===67||e===99?",":e===70||e===102?"/":null:t===51?e===65||e===97?":":e===66||e===98?";":e===68||e===100?"=":e===70||e===102?"?":null:t===52&&e===48?"@":null}function Bn(t,e){let r=!1,n=!1,s="";for(let a=1;a<t.length;a++){let o=t.charCodeAt(a);if(o===37){let l=t.charCodeAt(a+1),f=t.charCodeAt(a+2);Sr(l,f)===null?r=!0:(n=!0,l===50&&f===53&&(r=!0,t=t.slice(0,a+1)+"25"+t.slice(a+1),a+=2),a+=2)}else if(o===63||o===35||o===59&&e){s=t.slice(a+1),t=t.slice(0,a);break}}return{path:r?decodeURI(t):t,querystring:s,shouldDecodeParam:n}}function Hn(t){let e=t.indexOf("%");if(e===-1)return t;let r="",n=e;for(let s=e;s<t.length;s++)if(t.charCodeAt(s)===37){let i=t.charCodeAt(s+1),a=t.charCodeAt(s+2),o=Sr(i,a);r+=t.slice(n,s)+o,n=s+3}return t.slice(0,e)+r+t.slice(n)}vr.exports={safeDecodeURI:Bn,safeDecodeURIComponent:Hn}});var Tr=P((wi,Ir)=>{"use strict";h();var C=ie("assert"),Wn=Ct(),J=Kt(),Ve=We(),{prettyPrintTree:Ln}=rr(),{StaticNode:br,NODE_TYPES:Er}=cr(),Fn=mr(),Y=yr(),Ge=ge(),{safeDecodeURI:xr,safeDecodeURIComponent:Ke}=Pr(),wr=/^https?:\/\/.*?\//,G=/(\/:[^/()]*?)\?(\/?)/,Cr=/[.*+?^${}()|[\]\\]/g,Rr=/\/\/+/g;if(!J(wr))throw new Error("the FULL_PATH_REGEXP is not safe, update this module");if(!J(G))throw new Error("the OPTIONAL_PARAM_REGEXP is not safe, update this module");if(!J(Cr))throw new Error("the ESCAPE_REGEXP is not safe, update this module");if(!J(Rr))throw new Error("the REMOVE_DUPLICATE_SLASHES_REGEXP is not safe, update this module");function E(t){if(!(this instanceof E))return new E(t);t=t||{},this._opts=t,t.defaultRoute?(C(typeof t.defaultRoute=="function","The default route must be a function"),this.defaultRoute=t.defaultRoute):this.defaultRoute=null,t.onBadUrl?(C(typeof t.onBadUrl=="function","The bad url handler must be a function"),this.onBadUrl=t.onBadUrl):this.onBadUrl=null,t.buildPrettyMeta?(C(typeof t.buildPrettyMeta=="function","buildPrettyMeta must be a function"),this.buildPrettyMeta=t.buildPrettyMeta):this.buildPrettyMeta=Qn,t.querystringParser?(C(typeof t.querystringParser=="function","querystringParser must be a function"),this.querystringParser=t.querystringParser):this.querystringParser=e=>e.length===0?{}:Wn.parse(e),this.caseSensitive=t.caseSensitive===void 0?!0:t.caseSensitive,this.ignoreTrailingSlash=t.ignoreTrailingSlash||!1,this.ignoreDuplicateSlashes=t.ignoreDuplicateSlashes||!1,this.maxParamLength=t.maxParamLength||100,this.onMaxParamLength=t.onMaxParamLength||null,this.allowUnsafeRegex=t.allowUnsafeRegex||!1,this.constrainer=new Fn(t.constraints),this.useSemicolonDelimiter=t.useSemicolonDelimiter||!1,this.routes=[],this.trees=Object.create(null)}E.prototype.on=function(e,r,n,s,i){typeof n=="function"&&(s!==void 0&&(i=s),s=n,n={}),C(typeof r=="string","Path should be a string"),C(r.length>0,"The path could not be empty"),C(r[0]==="/"||r[0]==="*","The first character of a path should be `/` or `*`"),C(typeof s=="function","Handler should be a function");let a=r.match(G);if(a){C(r.length===a.index+a[0].length,"Optional Parameter needs to be the last parameter of the path");let f=r.replace(G,"$1$2"),c=r.replace(G,"$2")||"/";this.on(e,f,n,s,i),this.on(e,c,n,s,i);return}let o=r;this.ignoreDuplicateSlashes&&(r=we(r)),this.ignoreTrailingSlash&&(r=Ce(r));let l=Array.isArray(e)?e:[e];for(let f of l)C(typeof f=="string","Method should be a string"),C(Y.includes(f),`Method '${f}' is not an http method.`),this._on(f,r,n,s,i,o)};E.prototype._on=function(e,r,n,s,i){let a={};n.constraints!==void 0&&(C(typeof n.constraints=="object"&&n.constraints!==null,"Constraints should be an object"),Object.keys(n.constraints).length!==0&&(a=n.constraints)),this.constrainer.validateConstraints(a),this.constrainer.noteUsage(a),this.trees[e]===void 0&&(this.trees[e]=new br("/"));let o=r;if(o==="*"&&this.trees[e].prefix.length!==0){let d=this.trees[e];this.trees[e]=new br(""),this.trees[e].staticChildren["/"]=d}let l=this.trees[e],f=l.prefix.length,c=[];for(let d=0;d<=o.length;d++){if(o.charCodeAt(d)===58&&o.charCodeAt(d+1)===58){d++;continue}let p=o.charCodeAt(d)===58&&o.charCodeAt(d+1)!==58,x=o.charCodeAt(d)===42;if(p||x||d===o.length&&d!==f){let b=o.slice(f,d);this.caseSensitive||(b=b.toLowerCase()),b=b.replaceAll("::",":"),b=b.replaceAll("%","%25"),l=l.createStaticChild(b)}if(p){let b=!1,m=!0,A="",w=[],k=d+1;for(let g=k;;g++){let F=o.charCodeAt(g),X=F===40,I=F===45||F===46,$=F===47||g===o.length;if(X||I||$){let H=o.slice(k,g);if(c.push(H),b=b||X||I,X){let W=Or(o,g),K=o.slice(g,W+1);this.allowUnsafeRegex||C(J(new RegExp(K)),`The regex '${K}' is not safe!`),w.push(_r(K)),g=W+1,m=!0}else w.push(m?"(.*?)":`(${A}|(?:(?!${A}).)*)`),m=!1;let _e=g;for(;g<o.length;g++){let W=o.charCodeAt(g);if(W===47)break;if(W===58)if(o.charCodeAt(g+1)===58)g++;else break}let q=o.slice(_e,g);if(q&&(q=q.replaceAll("::",":"),q=q.replaceAll("%","%25"),w.push(A=Ar(q))),k=g+1,$||o.charCodeAt(g)===47||g===o.length){let W=b?"()"+q:q,K=o.slice(d,g);o=o.slice(0,d+1)+W+o.slice(g),d+=W.length;let Lr=b?new RegExp("^"+w.join("")+"$"):null;l=l.createParametricChild(Lr,q||null,K),f=d+1;break}}}}else if(x&&(c.push("*"),l=l.createWildcardChild(),f=d+1,d!==o.length-1))throw new Error("Wildcard must be the last character in the route")}this.caseSensitive||(o=o.toLowerCase()),o==="*"&&(o="/*");for(let d of this.routes){let p=d.opts.constraints||{};if(d.method===e&&d.pattern===o&&Ve(p,a))throw new Error(`Method '${e}' already declared for route '${o}' with constraints '${JSON.stringify(a)}'`)}let u={method:e,path:r,pattern:o,params:c,opts:n,handler:s,store:i};this.routes.push(u),l.addRoute(u,this.constrainer)};E.prototype.hasRoute=function(e,r,n){return this.findRoute(e,r,n)!==null};E.prototype.findRoute=function(e,r,n={}){if(this.trees[e]===void 0)return null;let s=r,i=this.trees[e],a=i.prefix.length,o=[];for(let l=0;l<=s.length;l++){if(s.charCodeAt(l)===58&&s.charCodeAt(l+1)===58){l++;continue}let f=s.charCodeAt(l)===58&&s.charCodeAt(l+1)!==58,c=s.charCodeAt(l)===42;if(f||c||l===s.length&&l!==a){let u=s.slice(a,l);if(this.caseSensitive||(u=u.toLowerCase()),u=u.replaceAll("::",":"),u=u.replaceAll("%","%25"),i=i.getStaticChild(u),i===null)return null}if(f){let u=!1,d=!0,p="",x=[],b=l+1;for(let m=b;;m++){let A=s.charCodeAt(m),w=A===40,k=A===45||A===46,g=A===47||m===s.length;if(w||k||g){let F=s.slice(b,m);if(o.push(F),u=u||w||k,w){let $=Or(s,m),H=s.slice(m,$+1);this.allowUnsafeRegex||C(J(new RegExp(H)),`The regex '${H}' is not safe!`),x.push(_r(H)),m=$+1,d=!0}else x.push(d?"(.*?)":`(${p}|(?:(?!${p}).)*)`),d=!1;let X=m;for(;m<s.length;m++){let $=s.charCodeAt(m);if($===47)break;if($===58)if(s.charCodeAt(m+1)===58)m++;else break}let I=s.slice(X,m);if(I&&(I=I.replaceAll("::",":"),I=I.replaceAll("%","%25"),x.push(p=Ar(I))),b=m+1,g||s.charCodeAt(m)===47||m===s.length){let $=u?"()"+I:I,H=s.slice(l,m);s=s.slice(0,l+1)+$+s.slice(m),l+=$.length;let _e=u?new RegExp("^"+x.join("")+"$"):null;if(i=i.getParametricChild(_e,I||null,H),i===null)return null;a=l+1;break}}}}else if(c&&(o.push("*"),i=i.getWildcardChild(),a=l+1,l!==s.length-1))throw new Error("Wildcard must be the last character in the route")}this.caseSensitive||(s=s.toLowerCase());for(let l of this.routes){let f=l.opts.constraints||{};if(l.method===e&&l.pattern===s&&Ve(f,n))return{handler:l.handler,store:l.store,params:l.params}}return null};E.prototype.hasConstraintStrategy=function(t){return this.constrainer.hasConstraintStrategy(t)};E.prototype.addConstraintStrategy=function(t){this.constrainer.addConstraintStrategy(t),this._rebuild(this.routes)};E.prototype.reset=function(){this.trees=Object.create(null),this.routes=[]};E.prototype.off=function(e,r,n){C(typeof r=="string","Path should be a string"),C(r.length>0,"The path could not be empty"),C(r[0]==="/"||r[0]==="*","The first character of a path should be `/` or `*`"),C(typeof n>"u"||typeof n=="object"&&!Array.isArray(n)&&n!==null,"Constraints should be an object or undefined.");let s=r.match(G);if(s){C(r.length===s.index+s[0].length,"Optional Parameter needs to be the last parameter of the path");let a=r.replace(G,"$1$2"),o=r.replace(G,"$2")||"/";this.off(e,a,n),this.off(e,o,n);return}this.ignoreDuplicateSlashes&&(r=we(r)),this.ignoreTrailingSlash&&(r=Ce(r));let i=Array.isArray(e)?e:[e];for(let a of i)this._off(a,r,n)};E.prototype._off=function(e,r,n){C(typeof e=="string","Method should be a string"),C(Y.includes(e),`Method '${e}' is not an http method.`);function s(l){return e!==l.method||r!==l.path}function i(l){return s(l)||!Ve(n,l.opts.constraints||{})}let a=n?i:s,o=this.routes.filter(a);this._rebuild(o)};E.prototype.lookup=function(e,r,n,s){if(typeof n=="function"&&(s=n,n=void 0),s===void 0){let i=this.constrainer.deriveConstraints(e,n),a=this.find(e.method,e.url,i);return this.callHandler(a,e,r,n)}this.constrainer.deriveConstraints(e,n,(i,a)=>{if(i!==null){s(i);return}try{let o=this.find(e.method,e.url,a),l=this.callHandler(o,e,r,n);s(null,l)}catch(o){s(o)}})};E.prototype.callHandler=function(e,r,n,s){return e===null?this._defaultRoute(r,n,s):s===void 0?e.handler(r,n,e.params,e.store,e.searchParams):e.handler.call(s,r,n,e.params,e.store,e.searchParams)};E.prototype.find=function(e,r,n){let s=this.trees[e];if(s===void 0)return null;r.charCodeAt(0)!==47&&(r=r.replace(wr,"/")),this.ignoreDuplicateSlashes&&(r=we(r));let i,a,o;try{i=xr(r,this.useSemicolonDelimiter),r=i.path,a=i.querystring,o=i.shouldDecodeParam}catch{return this._onBadUrl(r)}this.ignoreTrailingSlash&&(r=Ce(r));let l=r;this.caseSensitive===!1&&(r=r.toLowerCase());let f=this.maxParamLength,c=s.prefix.length,u=[],d=r.length,p=[],x=!1;for(;;){if(c===d&&s.isLeafNode){let m=s.handlerStorage.getMatchingHandler(n);if(m!==null)return{handler:m.handler,store:m.store,params:m._createParamsObject(u),searchParams:this.querystringParser(a)}}let b=s.getNextNode(r,c,p,u.length);if(b===null){if(p.length===0)return x&&this.onMaxParamLength?this._onMaxParamLength(l):null;let m=p.pop();c=m.brotherPathIndex,u.splice(m.paramsCount),b=m.brotherNode}for(s=b;;){if(s.kind===Er.STATIC){c+=s.prefix.length;break}if(s.kind===Er.WILDCARD){let w=l.slice(c);o&&(w=Ke(w)),u.push(w),c=d;break}let m=l.indexOf("/",c);m===-1&&(m=d);let A=l.slice(c,m);if(o&&(A=Ke(A)),s.isRegex){let w=s.regex.exec(A);if(w===null){if(p.length===0)return x&&this.onMaxParamLength?this._onMaxParamLength(l):null;let g=p.pop();c=g.brotherPathIndex,u.splice(g.paramsCount),s=g.brotherNode;continue}let k=!1;for(let g=1;g<w.length;g++)if((w[g]??"").length>f){k=!0;break}if(k){if(x=!0,p.length===0)return this.onMaxParamLength?this._onMaxParamLength(l):null;let g=p.pop();c=g.brotherPathIndex,u.splice(g.paramsCount),s=g.brotherNode;continue}for(let g=1;g<w.length;g++)u.push(w[g]??"")}else{if(A.length>f){if(x=!0,p.length===0)return this.onMaxParamLength?this._onMaxParamLength(l):null;let w=p.pop();c=w.brotherPathIndex,u.splice(w.paramsCount),s=w.brotherNode;continue}u.push(A)}c=m;break}}};E.prototype._rebuild=function(t){this.reset();for(let e of t){let{method:r,path:n,opts:s,handler:i,store:a}=e;this._on(r,n,s,i,a)}};E.prototype._defaultRoute=function(t,e,r){if(this.defaultRoute!==null)return r===void 0?this.defaultRoute(t,e):this.defaultRoute.call(r,t,e);e.statusCode=404,e.end()};E.prototype._onBadUrl=function(t){if(this.onBadUrl===null)return null;let e=this.onBadUrl;return{handler:(r,n,s)=>e(t,r,n),params:{},store:null}};E.prototype._onMaxParamLength=function(t){if(this.onMaxParamLength===null)return null;let e=this.onMaxParamLength;return{handler:(r,n,s)=>e(t,r,n),params:{},store:null}};E.prototype.prettyPrint=function(t={}){let e=t.method;t.buildPrettyMeta=this.buildPrettyMeta.bind(this);let r=null;if(e===void 0){let{version:n,host:s,...i}=this.constrainer.strategies;i[Ge.name]=Ge;let a=new E({...this._opts,constraints:i}),o=this.routes.map(l=>{let f={...l.opts.constraints,[Ge.name]:l.method};return{...l,method:"MERGED",opts:{constraints:f}}});a._rebuild(o),r=a.trees.MERGED}else r=this.trees[e];return r==null?"(empty tree)":Ln(r,t)};for(let t in Y){if(!Y.hasOwnProperty(t))continue;let e=Y[t],r=e.toLowerCase();E.prototype[r]=function(n,s,i){return this.on(e,n,s,i)}}E.prototype.all=function(t,e,r){this.on(Y,t,e,r)};E.sanitizeUrlPath=function(e,r){let n=xr(e,r);return n.shouldDecodeParam?Ke(n.path):n.path};E.removeDuplicateSlashes=we;E.trimLastSlash=Ce;Ir.exports=E;function Ar(t){return t.replace(Cr,"\\$&")}function we(t){return t.indexOf("//")!==-1?t.replace(Rr,"/"):t}function Ce(t){return t.length>1&&t.charCodeAt(t.length-1)===47?t.slice(0,-1):t}function _r(t){return t.charCodeAt(1)===94&&(t=t.slice(0,1)+t.slice(2)),t.charCodeAt(t.length-2)===36&&(t=t.slice(0,t.length-2)+t.slice(t.length-1)),t}function Or(t,e){let r=1;for(;e<t.length;){if(e++,t.charCodeAt(e)===92){e++;continue}if(t.charCodeAt(e)===41?r--:t.charCodeAt(e)===40&&r++,!r)return e}throw new TypeError('Invalid regexp expression in "'+t+'"')}function Qn(t){return t?t.store?Object.assign({},t.store):{}:{}}});h();h();h();var Nr=Fr(Tr(),1);async function Mr(t,e){let{port:r}=e;if(e.dryRun)return{async close(){},port:r,url:`http://localhost:${r}`};let n=!!e.debug,[{registerAccelerateRoutes:s},{registerUtilityRoutes:i},{createHTTPServer:a}]=await Promise.all([import("./accelerate-NQIUHBYP.js"),import("./utility-RVP4AU5Y.js"),import("./server-SSXVHZ7Q.js")]),o={databaseDumpPath:e.databaseDumpPath,db:t,debug:n,name:e.name,port:r,shadowDBPort:e.shadowDatabasePort},l=(0,Nr.default)({defaultRoute(c,u){st(u,"Not Found",404)},ignoreTrailingSlash:!1});s(l,o,n),i(l,o,n);let f=await a({router:l}).listen(r);return e.port=f.port,o.port=f.port,{async close(){let{Engine:c}=await import("./engine-RSESCYD5.js");await Promise.allSettled([f.close(),c.stopAll()])},port:f.port,url:f.url}}h();import{isDeepStrictEqual as $r}from"util";var Gn="application/json",Re={connection:"close","content-type":Gn},ze={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 Dr(t){return{...t,snapshot:async e=>await Kn(t.url,e)}}async function jr(t){let e={serverUrl:t.serverUrl,sqlitePath:t.sqlitePath,streamName:Ie,url:ae(t.serverUrl,Ie)};await zn(e);let r=new Ye({debug:t.debug,streamUrl:e.url}),n=t.bridge.subscribe(s=>{r.enqueue(s)});return{close:async()=>{n(),await r.close()},experimental:e}}async function Kn(t,e){if(!t)return rt();let r=await Vn(t);return nt(r,e)}async function Vn(t){let e=await fetch(`${t}?offset=-1&format=json`,{headers:{connection:"close"}});if(!e.ok)throw new Error(`Failed to read ${t}: HTTP ${e.status}`);return await e.json()}var Ye=class{#r;#t;#e;constructor(e){this.#r=e.debug,this.#t=Promise.resolve(),this.#e=e.streamUrl}enqueue(e){e.length!==0&&(this.#t=this.#t.then(async()=>{await Xn(this.#e,e),this.#r&&console.debug(`[streams] appended ${e.length} query insight record(s) to ${this.#e}`)}).catch(r=>{console.error("[streams] failed to ingest query insights into prisma-queries",r)}))}async close(){await this.#t}};async function zn(t){let e=await fetch(t.url,{headers:Re,method:"PUT"});if(!e.ok)throw await Ae(e,`Failed to create ${t.streamName}`);let r=await Jn(t);if(Yn(r,t.streamName))return;if(r.currentVersion>0)throw new Error(`Failed to install schema for ${t.streamName}: existing schema registry is incompatible and requires a lens migration`);let n=await fetch(`${t.url}/_schema`,{body:JSON.stringify(ze),headers:Re,method:"POST"});if(!n.ok)throw await Ae(n,`Failed to install schema for ${t.streamName}`)}function Yn(t,e){if(t.currentVersion<=0||t.schema!==e)return!1;let r=t.schemas[String(t.currentVersion)];return $r(r,ze.schema)&&$r(t.search,ze.search)}async function Jn(t){let e=await fetch(`${t.url}/_schema`,{headers:Re,method:"GET"});if(!e.ok)throw await Ae(e,`Failed to inspect schema for ${t.streamName}`);return await e.json()}async function Xn(t,e){let r=await fetch(t,{body:JSON.stringify(e),headers:Re,method:"POST"});if(!r.ok)throw await Ae(r,"Failed to append to prisma-queries")}async function Ae(t,e){let r=await t.text().catch(()=>"");return new Error(`${e}: HTTP ${t.status}${r?` ${r}`:""}`)}h();import{randomUUID as Zn}from"crypto";import{setTimeout as kr}from"timers/promises";import{isDeepStrictEqual as qr}from"util";import{process as es}from"std-env";var ts="application/json",ne={connection:"close","content-type":ts},rs={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},Je={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 Br(t){let{dbServer:e,debug:r,name:n,persistenceMode:s,port:i,queryInsightsBridge:a,walBridge:o}=t,l=s==="stateless",f=l?ps(n):n,c=Te(f),u=!l&&await tt(c);es.env.DS_LOCAL_DATA_ROOT=at(),l&&await Z(c);let d=await ss({debug:r,hadExistingStreamsData:u,name:f,port:i}),p={serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path,streamName:it,url:ae(d.exports.http.url)};try{await os(p);let x=await jr({bridge:a,debug:r,serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path}),b=new Xe({dbServer:e,debug:r,streamUrl:p.url}),m=o.subscribe(A=>{b.enqueue(A)});return{close:async()=>{m(),await b.close(),await x.close(),await d.close(),await kr(100),l&&await Z(c)},experimental:p,experimentalQueryInsights:x.experimental}}catch(x){throw await d.close().catch(()=>{}),await kr(100),l&&await Z(c).catch(()=>{}),x}}var ns=["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 ss(t){let{debug:e,hadExistingStreamsData:r,name:n,port:s}=t,{startLocalDurableStreamsServer:i}=await import("@prisma/streams-local"),a=()=>i({hostname:"127.0.0.1",name:n,port:s});try{return await a()}catch(o){if(!r||!is(o))throw o;return console.warn(`[streams] resetting incompatible durable streams data for "${n}"`),e&&console.debug(`[streams] original durable streams startup error for "${n}"`,o),await Z(Te(n)),await a()}}function is(t){return as(t).map(r=>r.toLowerCase()).some(r=>ns.some(n=>r.includes(n)))}function as(t){let e=[],r=[t],n=new Set;for(;r.length>0;){let s=r.shift();if(!(s==null||n.has(s))){if(n.add(s),typeof s=="string"){e.push(s);continue}if(s instanceof AggregateError)for(let i of s.errors)r.push(i);if(s instanceof Error){e.push(s.message);let i=s.cause;i!==void 0&&r.push(i)}}}return e}var Xe=class{#r;#t;#e;#n;#s;constructor(e){this.#r=e.dbServer,this.#t=e.debug,this.#e=Promise.resolve(),this.#n=e.streamUrl,this.#s=new Set}enqueue(e){e.length!==0&&(this.#e=this.#e.then(async()=>{let r=await this.#a(e);r.length!==0&&(await us(this.#n,r),this.#t&&console.debug(`[streams] appended ${r.length} state-protocol record(s) to ${this.#n}`))}).catch(r=>{console.error("[streams] failed to ingest WAL events into prisma-wal",r)}))}async close(){await this.#e}async#a(e){let r=[],n=new Date().toISOString();for(let s of e)r.push(...await this.#o(s,n));return r}async#o(e,r){let n=`${e.schema}.${e.table}`,s=await this.#r.getPrimaryKeyColumns(e.schema,e.table),i=Ur(e.record),a=Ur(e.oldRecord),o=this.#i(n,s,a),l=this.#i(n,s,i),f=e.txid===""?void 0:e.txid;return e.type==="insert"?i&&l?[{headers:{operation:"insert",timestamp:r,txid:f},key:l,old_value:null,type:n,value:i}]:[]:e.type==="delete"?a&&o?[{headers:{operation:"delete",timestamp:r,txid:f},key:o,old_value:a,type:n,value:null}]:[]:!i||!a||!o||!l?[]:o!==l?[{headers:{operation:"delete",timestamp:r,txid:f},key:o,old_value:a,type:n,value:null},{headers:{operation:"insert",timestamp:r,txid:f},key:l,old_value:null,type:n,value:i}]:[{headers:{operation:"update",timestamp:r,txid:f},key:l,old_value:a,type:n,value:i}]}#i(e,r,n){if(!n)return null;let s=fs(n,r);return s||(this.#s.has(e)||(this.#s.add(e),console.warn(`[streams] falling back to full-row keys for ${e} because no primary key could be resolved`)),hs(n))}};async function os(t){let e=await fetch(t.url,{headers:ne,method:"PUT"});if(!e.ok)throw await se(e,`Failed to create ${t.streamName}`);let r=await fetch(`${t.url}/_profile`,{body:JSON.stringify(rs),headers:ne,method:"POST"});if(!r.ok)throw await se(r,`Failed to configure ${t.streamName}`);let n=await ls(t);if(cs(n,t.streamName))return;if(n.currentVersion>0)throw new Error(`Failed to install schema for ${t.streamName}: existing schema registry is incompatible and requires a lens migration`);let s=await fetch(`${t.url}/_schema`,{body:JSON.stringify(Je),headers:ne,method:"POST"});if(!s.ok)throw await se(s,`Failed to install schema for ${t.streamName}`)}async function ls(t){let e=await fetch(`${t.url}/_schema`,{headers:ne,method:"GET"});if(!e.ok)throw await se(e,`Failed to inspect schema for ${t.streamName}`);return await e.json()}function cs(t,e){if(t.currentVersion<=0||t.schema!==e)return!1;let r=t.schemas[String(t.currentVersion)];return qr(r,Je.schema)&&qr(t.search,Je.search)}async function us(t,e){let r=await fetch(t,{body:JSON.stringify(e),headers:ne,method:"POST"});if(!r.ok)throw await se(r,"Failed to append to prisma-wal")}async function se(t,e){let r=await t.text().catch(()=>"");return new Error(`${e}: HTTP ${t.status}${r?` ${r}`:""}`)}function fs(t,e){if(e.length===0)return null;let r=[];for(let n of e){if(!Object.prototype.hasOwnProperty.call(t,n))return null;let s=ds(t[n]);if(s==null)return null;r.push(e.length===1?s:`${n}=${s}`)}return r.join("|")}function hs(t){return JSON.stringify(Ze(t))}function Ze(t){return Array.isArray(t)?t.map(e=>Ze(e)):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[r])=>e.localeCompare(r)).map(([e,r])=>[e,Ze(r)])):t}function Ur(t){return t?structuredClone(t):null}function ds(t){if(t===null)return"null";if(t===void 0)return"undefined";if(typeof t=="string")return t;if(typeof t=="number")return Number.isFinite(t)?String(t):null;if(typeof t=="bigint")return t.toString();if(typeof t=="boolean")return t?"true":"false";try{return JSON.stringify(t)}catch{return null}}function ps(t){return`${t}.${Zn().replaceAll("-","")}`}async function Hr(t){let e=await ot.createExclusively(t),r=null,n=null,s=null,i=null;try{[r,s]=await Promise.all([Oe("database",e),Oe("shadow_database",e)]);let a,o;e.dryRun?(a=Ss(),o=vs(),i=Ps()):(a=await r.attachWalEventBridge(),o=await r.attachQueryInsightsBridge(),i=await Br({dbServer:r,debug:e.debug,name:e.name,port:e.streamsPort,persistenceMode:e.persistenceMode,queryInsightsBridge:o,walBridge:a})),n=await Mr(r,e);let l=ms(r,s,n,e);await e.writeServerDump(l,e.dryRun?{}:{queryInsights:i.experimentalQueryInsights,streams:i.experimental});let f=ys(a),c=Dr(i.experimentalQueryInsights),u=r,d=s,p=n,x=i,b=async()=>{f.close(),await Wr(e,[p,x,u,d])};return{close:b,dbServer:r,httpServer:n,server:{...l,close:b,experimental:{queryInsights:c,streams:i.experimental,wal:f.api},name:e.name},serverState:e,shadowDbServer:s,streamsServer:i,queryInsightsBridge:o,walBridge:a}}catch(a){return await gs(e,[n,i,r,s],a)}}function ms(t,e,r,n){let s=`prisma+postgres://localhost:${r.port}/?${new URLSearchParams({api_key:et({databaseUrl:t.prismaORMConnectionString,name:n.name,shadowDatabaseUrl:e.prismaORMConnectionString})}).toString()}`;return{database:{connectionString:t.connectionString,prismaORMConnectionString:t.prismaORMConnectionString,terminalCommand:t.terminalCommand},http:{url:r.url},ppg:{url:s},shadowDatabase:{connectionString:e.prismaORMConnectionString,prismaORMConnectionString:e.prismaORMConnectionString,terminalCommand:e.terminalCommand}}}async function Wr(t,e){let r=[];for(let n of e)try{await n.close()}catch(s){r.push(s)}try{await t.close()}catch(n){r.push(n)}if(r.length>0)throw new AggregateError(r,"Failed to close some servers")}async function gs(t,e,r){try{await Wr(t,e.filter(n=>n!==null))}catch(n){throw new AggregateError([r,n],"Failed to start Prisma Dev server cleanly")}throw r}function ys(t){let e=new Set;return{api:{stream:()=>{let r=()=>{},n=bs(t,()=>{e.delete(r)});return r=()=>n.close(),e.add(r),n.stream},subscribe:r=>t.subscribe(r)},close:()=>{for(let r of[...e])r();e.clear()}}}function Ss(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function vs(){return{async close(){},subscribe(){return()=>{}}}}function Ps(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""},experimentalQueryInsights:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function bs(t,e){let r=[],n=!1,s=null,i=t.subscribe(o=>{if(!n){if(s){let l=s;s=null,l.resolve({done:!1,value:o});return}r.push(o)}}),a=()=>{if(!n&&(n=!0,i(),r.length=0,e(),s)){let o=s;s=null,o.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((o,l)=>{s={reject:l,resolve:o}})},return(){return a(),Promise.resolve({done:!0,value:void 0})},throw(o){let l=s;return a(),l&&l.reject(o),Promise.reject(o instanceof Error?o:new Error(String(o)))}}}}async function Es(t){let{server:e}=await Hr(t);return e}async function oa(t){return await Es(t)}export{Es as a,oa as b}; |
| import{d as r}from"./chunk-JLSS5G22.js";r();import{Buffer as s}from"buffer";function f(e,t,o=200){let n=s.from(JSON.stringify(t),"utf8");e.headersSent||(e.setHeader("Content-Type","application/json; charset=utf-8"),e.setHeader("Content-Length",n.byteLength),e.statusCode=o),e.end(n)}function d(e,t,o=200){let n=s.from(t,"utf8");e.headersSent||(e.setHeader("Content-Type","text/plain; charset=utf-8"),e.setHeader("Content-Length",n.byteLength),e.statusCode=o),e.end(n)}function u(e,t=204){e.headersSent||(e.statusCode=t,e.setHeader("Content-Length",0)),e.end()}function m(e,t){d(e,t.message,t.status)}export{f as a,d as b,u as c,m as d}; |
| import{a as d}from"./chunk-I2OHVRST.js";import{h as l}from"./chunk-UEE5SWKL.js";import{c as f,d as p}from"./chunk-T6L5TENJ.js";import{d as c}from"./chunk-JLSS5G22.js";c();import{createServer as u}from"http";import{promisify as y}from"util";function E(r,e){return async function(o,n,i){let t=e?Date.now():0;e&&n.once("finish",()=>{let a=Date.now()-t;console.log("[Accelerate]",`<-- ${o.method??"?"} ${o.url??""} ${n.statusCode} ${a}ms`)});try{await r(o,n,i)}catch(a){try{T(a,n,o,e)}catch(m){e&&console.error("[Accelerate]","error while handling handler error",m),n.destroyed||n.destroy()}}}}function T(r,e,s,o){if(e.destroyed||e.headersSent||e.writableEnded){o&&console.error("[Accelerate]",`error after response was no longer writable for ${s.method??"?"} ${s.url??""}`,r),e.destroy();return}if(r instanceof d){p(e,r);return}console.error("[Accelerate]",r);try{f(e,500)}catch(n){o&&console.error("[Accelerate]","failed to write 500 response (client likely disconnected)",n),e.destroy()}}function I(r){let{router:e}=r;return{async listen(s){let o=u((t,a)=>{e.lookup(t,a)}),i=(await P(o,s)).port;return o.on("error",t=>{console.error("[Accelerate]",t)}),{async close(){await y(o.close.bind(o))()},port:i,url:`http://localhost:${i}`}}}}function P(r,e){return new Promise((s,o)=>{let n=t=>{if(r.off("listening",i),typeof t=="object"&&t!==null&&"code"in t&&t.code==="EADDRINUSE"){o(new l(e));return}o(t)},i=()=>{r.off("error",n),s(r.address())};r.once("error",n),r.once("listening",i),r.listen(e)})}export{E as a,I as b}; |
| import{d as v}from"./chunk-JLSS5G22.js";v();import{checkPort as U,getPort as S,isUnsafePort as x}from"get-port-please";import{difference as k,range as R}from"remeda";var g=51214,w=51213,T=51215,O=51216,b=65535,A=0,d=-1/0;async function F(o){let{debug:r,name:e,requestedPorts:n,servers:u}=o,{portsUsedByOtherServers:t,portsUsedByThisServerLastTime:a}=q(e,u);r&&(console.debug(`ports used by other servers: ${Object.keys(t).join(", ")}`),console.debug(`ports used by "${e}" server last time: ${JSON.stringify(a)}`));let i={databasePort:d,port:d,shadowDatabasePort:d,streamsPort:d},s=["port","databasePort","shadowDatabasePort","streamsPort"];for(let c of s){let P=await B({debug:r,portKey:c,portsUsedByOtherServers:t,portsUsedByThisServerLastTime:a,requestedPorts:n})??await _({debug:r,pickedPorts:i,portKey:c,portsUsedByOtherServers:t,portsUsedByThisServerLastTime:a});r&&console.debug(`Got port for "${c}": ${P}`),i[c]=P}return r&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function B(o){let{debug:r,portKey:e,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:u,requestedPorts:t}=o,{[e]:a,...i}=t;if(m(a))return await L({debug:r,otherRequestedPorts:i,portKey:e,portsUsedByOtherServers:n,requestedPort:a}),a;let s=u?.[e]??d;if(!m(s))return r&&console.debug(`No port specified for "${e}". Trying to pick a new port.`),null;let c=s in n;return c||Object.values(i).includes(s)?(r&&console.debug(`Port ${s} that was used last time for this server, ${c?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await U(s)===!1?(r&&console.debug(`Port ${s}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(r&&console.debug(`Using port ${s} for "${e}" as it was used last time and is available.`),s)}async function _(o){let{debug:r,pickedPorts:e,portKey:n,portsUsedByOtherServers:u,portsUsedByThisServerLastTime:t}=o,a=Math.max(g,w,T,O)+1,i=Object.values(e).filter(p=>p!==void 0),s=t?E(t):[],c=[...i,...Object.keys(u).map(Number),...s],P=Math.min(Math.max(a,...c)+100,b),$=k(R(a,P),c),f={port:w,databasePort:g,shadowDatabasePort:T,streamsPort:O}[n];try{return await S({port:f in u||i.includes(f)||s.includes(f)?void 0:f,ports:$})}catch(p){if(p instanceof Error&&p.name==="GetPortError"&&P+1<=b)return r&&console.debug(`Expanding port lookup to range [${P+1}, ${b}].`),await S({portRange:[P+1,b]});throw p}}function m(o){return Number.isFinite(o)&&o>=0}function q(o,r){let e={},n;for(let u of r){let{databasePort:t,port:a,shadowDatabasePort:i}=u,s=D(u);if(u.name===o){n={databasePort:t,port:a,shadowDatabasePort:i,streamsPort:s};continue}e[t]=!0,e[a]=!0,e[i]=!0,m(s)&&(e[s]=!0)}return{portsUsedByOtherServers:e,portsUsedByThisServerLastTime:n}}function D(o){let r=o.experimental?.streams?.serverUrl;if(!r)return d;try{let e=Number(new URL(r).port);return Number.isInteger(e)&&e>0?e:d}catch{return d}}function E(o){return[o.port,o.databasePort,o.shadowDatabasePort,o.streamsPort]}async function L(o){let{debug:r,otherRequestedPorts:e,portKey:n,portsUsedByOtherServers:u,requestedPort:t}=o;if(t!==A){if(t in u)throw r&&console.error(`Port ${t} was requested for "${n}", but is already used by another server.`),new h(t);if(Object.values(e).includes(t))throw r&&console.error(`Port ${t} was requested for "${n}", but also for another key.`),new y(t);if(x(t))throw r&&console.error(`Port ${t} was requested for "${n}", but is unsafe.`),new l(t);if(await U(t)===!1)throw r&&console.error(`Port ${t} was requested for "${n}", but is not available.`),new l(t)}}var l=class extends Error{constructor(e){super(`Port \`${e}\` is not available.`);this.port=e}name="PortNotAvailableError"},y=class extends Error{constructor(e){super(`Port number \`${e}\` was requested twice. Please choose a different port for each service.`);this.port=e}name="PortRequestedTwiceError"},h=class extends Error{constructor(e){super(`Port number \`${e}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=e}name="PortBelongsToAnotherServerError"};export{g as a,w as b,T as c,O as d,A as e,d as f,F as g,l as h}; |
| import{c as N}from"./chunk-HM357TKK.js";import{h as I}from"./chunk-UEE5SWKL.js";import{d as O,f as C}from"./chunk-MN4XKQ55.js";import{d as S}from"./chunk-JLSS5G22.js";S();import{createConnection as qe,createServer as Fe}from"net";import{join as Ue}from"path";import{filename as We}from"pathe/utils";S();import{performance as H}from"perf_hooks";import{protocol as Pe}from"@electric-sql/pglite";S();import{Buffer as me}from"buffer";var Q=500,$=/(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+)/,pe=new RegExp(`(?:${$.source}\\.)*${$.source}`),ge=new RegExp(`(?:FROM|JOIN|UPDATE|INTO|TABLE)\\s+(${pe.source})`,"gi"),fe=/"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|(\w+)/g,G=/prismaQuery='([^']+)'/,ye=new Set([b(` | ||
| select b.oid, b.typarray | ||
| from pg_catalog.pg_type a | ||
| left join pg_catalog.pg_type b on b.oid = a.typelem | ||
| where a.typcategory = $1 | ||
| group by b.oid, b.typarray | ||
| order by b.oid | ||
| `),b('GRANT "pg_write_all_data" TO "prisma_application"'),b("SELECT SUM(reads)::BIGINT AS reads, SUM(writes)::BIGINT AS writes, SUM(COALESCE(extends, $1))::BIGINT AS extends FROM pg_stat_io"),b("SELECT pg_database_size(current_database())::BIGINT, SUM(pg_total_relation_size(relid))::BIGINT AS pg_total_relation_size FROM pg_stat_user_tables"),b("SELECT COUNT(*) AS cnt FROM pg_stat_activity WHERE pid <> pg_backend_pid() and xact_start notnull")]),Ee=[/^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 et(){return{generatedAt:Date.now(),queries:[]}}function b(e){return e.replace(/\s+/g," ").trim()}function k(e){return W(b(e))}function q(e){if(!e?.action||!e.model&&/raw/i.test(e.action))return null;let t=e.payload?W(JSON.stringify(e.payload)):"0";return`${e.model??""}.${e.action}:${t}`}function Se(e){let t=new Set;for(let r of e.matchAll(ge)){let n=r[1];if(!n)continue;let a;for(let s of n.matchAll(fe))a=s[1]??s[2]??s[3]??s[4];a&&!a.startsWith("pg_")&&t.add(a)}return Array.from(t)}function be(e){return ye.has(e)?!0:Ee.some(t=>t.test(e))}function F(e){if(be(b(e)))return null;let t=Se(e);return t.length===0&&/\bpg_\w+/i.test(e)?null:t}function R(e){if(Array.isArray(e))return e.map(R);if(e!==null&&typeof e=="object"){let t=e;return t.$type==="Param"?"<<redacted>>":Object.fromEntries(Object.entries(t).map(([r,n])=>[r,R(n)]))}return e}function U(e){let t=e.match(G);if(!t?.[1])return{cleanedSql:b(e),prismaQueryInfo:null};let r=e.replace(G,"");r=r.replace(/,\s*,/g,",").replace(/\/\*\s*,/g,"/*").replace(/,\s*\*\//g,"*/").replace(/\/\*\s*\*\//g,"").replace(/\s+/g," ").trim();let n=decodeURIComponent(t[1]),a=n.indexOf(":");if(a===-1)return{cleanedSql:r,prismaQueryInfo:{action:n,isRaw:!0}};let s=n.slice(0,a),d=n.slice(a+1),o=s.indexOf("."),u=o===-1?void 0:s.slice(0,o),c=o===-1?s:s.slice(o+1);if(!c)return{cleanedSql:r,prismaQueryInfo:null};let l;try{l=R(JSON.parse(me.from(d,"base64url").toString("utf8")))}catch{l=void 0}return{cleanedSql:r,prismaQueryInfo:{action:c,isRaw:!1,model:u,payload:l}}}function tt(e,t={}){let r=new Set(t.excludeApplications??[]),n=we(t.limit),a=typeof t.since=="number"&&Number.isFinite(t.since)?t.since:null,s=new Map;for(let o of e){if(o.applicationName&&r.has(o.applicationName))continue;let u=Date.parse(o.timestamp);if(!Number.isFinite(u))continue;let c=`${o.queryId}:${o.groupKey??""}`,l=s.get(c);if(!l){s.set(c,{count:1,duration:o.durationMs,groupKey:o.groupKey,id:c,lastSeen:u,maxDurationMs:o.durationMs,minDurationMs:o.durationMs,prismaQueryInfo:o.prismaQueryInfo,query:o.query,queryId:o.queryId,reads:o.reads,rowsReturned:o.rowsReturned,tables:o.tables,totalDurationMs:o.durationMs});continue}l.count+=1,l.lastSeen=Math.max(l.lastSeen,u),l.maxDurationMs=Math.max(l.maxDurationMs??o.durationMs,o.durationMs),l.minDurationMs=Math.min(l.minDurationMs??o.durationMs,o.durationMs),l.reads+=o.reads,l.rowsReturned+=o.rowsReturned,l.totalDurationMs+=o.durationMs,l.duration=l.totalDurationMs/l.count,!l.prismaQueryInfo&&o.prismaQueryInfo&&(l.prismaQueryInfo=o.prismaQueryInfo),l.tables.length===0&&o.tables.length>0&&(l.tables=o.tables)}let d=Array.from(s.values()).filter(o=>a===null||o.lastSeen>=a).sort((o,u)=>u.lastSeen-o.lastSeen).slice(0,n).map(({totalDurationMs:o,...u})=>u);return{generatedAt:Date.now(),queries:d}}function we(e){return typeof e=="number"&&Number.isInteger(e)&&Number.isSafeInteger(e)&&e>0?Math.min(e,Q):Q}function W(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 h=new WeakMap;function K(e){let t=h.get(e);if(t&&!t.closed)return t.bridge;let r=he(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,h.delete(e)),Promise.resolve()),subscribe:a=>(n.subscribers.add(a),()=>{n.subscribers.delete(a)})},closed:!1,originalClearQueueForHandler:r.clearQueueForHandler.bind(r),originalEnqueue:r.enqueue.bind(r),queryQueue:r,sessions:new Map,subscribers:new Set};return r.clearQueueForHandler=a=>{n.sessions.delete(a),n.originalClearQueueForHandler(a)},r.enqueue=async(a,s,d)=>{let o=Te(n,a),u=Re(s);Ie(o,u);let c=Ne(o,u);if(!c)return await n.originalEnqueue(a,s,d);let l={commandTags:[],dataRowCount:0},f=new Pe.Parser,i=H.now(),m=await n.originalEnqueue(a,s,w=>{f.parse(w,de=>{Be(l,de)}),d(w)}),g=Math.max(0,H.now()-i);return Le(n,{applicationName:c.applicationName,durationMs:g,query:c.query,responseStats:l}),m},h.set(e,n),n.bridge}async function Y(e){await h.get(e)?.bridge.close()}function he(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 Te(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 Ie(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 Ne(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 Re(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 a=t.readInt32BE(4);if(a===196608||a===196608)return _e(t)}if(t.length<5)return null;switch(String.fromCharCode(t[0]??0)){case"Q":return xe(t);case"P":return Ae(t);case"B":return De(t);case"E":return ve(t);case"C":return Me(t);default:return null}}function _e(e){let t=8,r=null;for(;t<e.length-1;){let n=E(e,t);if(!n||n.value==="")break;t=n.nextOffset;let a=E(e,t);if(!a)break;t=a.nextOffset,n.value==="application_name"&&(r=a.value)}return{applicationName:r,kind:"startup"}}function xe(e){let t=E(e,5);return t?{kind:"query",query:t.value}:null}function Ae(e){let t=E(e,5);if(!t)return null;let r=E(e,t.nextOffset);return r?{kind:"parse",query:r.value,statementName:t.value}:null}function De(e){let t=E(e,5);if(!t)return null;let r=E(e,t.nextOffset);return r?{kind:"bind",portalName:t.value,statementName:r.value}:null}function ve(e){let t=E(e,5);return t?{kind:"execute",portalName:t.value}:null}function Me(e){if(e.length<7)return null;let t=e[5];if(t===void 0)return null;let r=E(e,6);return r?{kind:"close",name:r.value,target:t===80?"portal":"statement"}:null}function E(e,t){let r=e.indexOf(0,t);return r===-1?null:{nextOffset:r+1,value:e.toString("utf8",t,r)}}function Be(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 Le(e,t){let r=U(t.query),n=F(r.cleanedSql);if(!n)return;let a=k(r.cleanedSql),s={applicationName:t.applicationName,durationMs:t.durationMs,groupKey:q(r.prismaQueryInfo),prismaQueryInfo:r.prismaQueryInfo,query:r.cleanedSql,queryId:a,reads:0,rowsReturned:Oe(t.responseStats),tables:n,timestamp:new Date().toISOString()};for(let d of e.subscribers)d([s])}function Oe(e){let t=e.commandTags.reduce((r,n)=>r+Ce(n),0);return Math.max(t,e.dataRowCount)}function Ce(e){let t=e.trim().split(/\s+/).at(-1);return!t||!/^\d+$/.test(t)?0:Number(t)}S();import{protocol as X}from"@electric-sql/pglite";var y="_prisma_dev_wal",D="events",j="install_all_triggers",z="capture_event",J="prisma_dev_wal_capture",P=new WeakMap,Qe=new Set(["ALTER","COMMIT","COPY","CREATE","DELETE","DROP","INSERT","MERGE","TRUNCATE","UPDATE"]);async function v(e,t){let r=P.get(e);if(r&&!r.closed)return r.bridge;let n=e.execProtocolRaw.bind(e),a=e.execProtocolRawStream.bind(e),s={bridge:{close:async()=>{s.closed||(s.closed=!0,s.subscribers.clear(),e.execProtocolRaw===d&&(e.execProtocolRaw=n),e.execProtocolRawStream===o&&(e.execProtocolRawStream=a),await s.pollPromise,P.delete(e))},poll:async()=>{await A(s,e)},subscribe:u=>(s.subscribers.add(u),()=>{s.subscribers.delete(u)})},closed:!1,ensureInfrastructurePromise:null,pendingPoll:!1,pollPromise:null,subscribers:new Set,suppressDepth:0},d=async(u,c)=>{let l=await n(u,c);return!s.closed&&s.suppressDepth===0&&Z(l)&&A(s,e),l},o=async(u,c)=>{let l=[],f=new X.Parser,i=c?.onRawData;await a(u,{...c,onRawData:m=>{f.parse(m,g=>{l.push(g)}),i?.(m)}}),!s.closed&&s.suppressDepth===0&&M(l)&&A(s,e)};return e.execProtocolRaw=d,e.execProtocolRawStream=o,P.set(e,s),await ee(s,e),s.bridge}async function V(e){let t=P.get(e);t&&await t.bridge.close()}function M(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&&Qe.has(r))return!0}return!1}function Z(e){if(e.length===0)return!1;let t=[];return new X.Parser().parse(e,n=>{t.push(n)}),M(t)}async function ee(e,t){e.ensureInfrastructurePromise??=B(e,t,async()=>{await t.exec(`CREATE SCHEMA IF NOT EXISTS "${y}"`),await t.exec(` | ||
| CREATE TABLE IF NOT EXISTS "${y}"."${D}" ( | ||
| id BIGSERIAL PRIMARY KEY, | ||
| txid BIGINT NOT NULL DEFAULT txid_current(), | ||
| schema_name TEXT NOT NULL, | ||
| table_name TEXT NOT NULL, | ||
| op TEXT NOT NULL, | ||
| row_data JSONB, | ||
| old_row_data JSONB, | ||
| created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() | ||
| ) | ||
| `),await t.exec(` | ||
| CREATE OR REPLACE FUNCTION "${y}"."${z}"() | ||
| RETURNS trigger | ||
| LANGUAGE plpgsql | ||
| AS $$ | ||
| BEGIN | ||
| IF TG_TABLE_SCHEMA = '${y}' THEN | ||
| RETURN COALESCE(NEW, OLD); | ||
| END IF; | ||
| INSERT INTO "${y}"."${D}" ( | ||
| txid, | ||
| schema_name, | ||
| table_name, | ||
| op, | ||
| row_data, | ||
| old_row_data | ||
| ) | ||
| VALUES ( | ||
| txid_current(), | ||
| TG_TABLE_SCHEMA, | ||
| TG_TABLE_NAME, | ||
| lower(TG_OP), | ||
| CASE WHEN TG_OP IN ('INSERT', 'UPDATE') THEN to_jsonb(NEW) ELSE NULL END, | ||
| CASE WHEN TG_OP IN ('UPDATE', 'DELETE') THEN to_jsonb(OLD) ELSE NULL END | ||
| ); | ||
| RETURN COALESCE(NEW, OLD); | ||
| END; | ||
| $$; | ||
| `),await t.exec(` | ||
| CREATE OR REPLACE FUNCTION "${y}"."${j}"() | ||
| RETURNS void | ||
| LANGUAGE plpgsql | ||
| AS $$ | ||
| DECLARE | ||
| target REGCLASS; | ||
| BEGIN | ||
| FOR target IN | ||
| SELECT c.oid::regclass | ||
| FROM pg_class AS c | ||
| JOIN pg_namespace AS n ON n.oid = c.relnamespace | ||
| WHERE c.relkind IN ('r', 'p') | ||
| AND n.nspname NOT IN ('${y}', 'information_schema', 'pg_catalog') | ||
| AND n.nspname NOT LIKE 'pg_temp_%' | ||
| AND n.nspname NOT LIKE 'pg_toast%' | ||
| LOOP | ||
| IF EXISTS ( | ||
| SELECT 1 | ||
| FROM pg_trigger | ||
| WHERE tgrelid = target | ||
| AND tgname = '${J}' | ||
| ) THEN | ||
| CONTINUE; | ||
| END IF; | ||
| EXECUTE format( | ||
| 'CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION "${y}"."${z}"()', | ||
| '${J}', | ||
| target::text | ||
| ); | ||
| END LOOP; | ||
| END; | ||
| $$; | ||
| `),await te(e,t)}),await e.ensureInfrastructurePromise}async function te(e,t){await B(e,t,async()=>{await t.query(`SELECT "${y}"."${j}"()`)})}async function $e(e,t){await ee(e,t),await te(e,t);let r=await B(e,t,async()=>await t.query(` | ||
| WITH drained AS ( | ||
| DELETE FROM "${y}"."${D}" | ||
| RETURNING txid, schema_name, table_name, op, row_data, old_row_data, id | ||
| ) | ||
| SELECT txid, schema_name, table_name, op, row_data, old_row_data | ||
| FROM drained | ||
| ORDER BY id | ||
| `));if(r.rows.length===0||e.subscribers.size===0)return;let n=r.rows.map(Ge);for(let a of e.subscribers)queueMicrotask(()=>{if(!e.closed&&e.subscribers.has(a))try{a(n)}catch(s){console.error("[WAL bridge] subscriber failed",s)}})}async function A(e,t){if(!e.closed){if(e.pollPromise){e.pendingPoll=!0,await e.pollPromise;return}e.pollPromise=(async()=>{do e.pendingPoll=!1,await $e(e,t);while(e.pendingPoll&&!e.closed)})().finally(()=>{e.pollPromise=null}),await e.pollPromise}}async function B(e,t,r){e.suppressDepth+=1;try{return await r()}finally{e.suppressDepth-=1,e.suppressDepth===0&&!e.closed&&P.get(t)!==e&&(e.closed=!0)}}function Ge(e){return{oldRecord:e.old_row_data,record:e.row_data,schema:e.schema_name,table:e.table_name,txid:String(e.txid),type:ke(e.op)}}function ke(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 He=10,ne="127.0.0.1",ae=128*1024*1024,oe=["-c","shared_buffers=16MB","-c","temp_buffers=1MB","-c","work_mem=1MB","-c","maintenance_work_mem=16MB","-c","wal_buffers=1MB"],p={connectionLimit:He,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},Ke=`postgres://${p.username}:${p.password}@localhost`,L=new URLSearchParams({sslmode:p.sslMode}),se=new URLSearchParams({...Object.fromEntries(L.entries()),connection_limit:String(p.connectionLimit),connect_timeout:String(p.connectTimeout),max_idle_connection_lifetime:String(p.maxIdleConnectionLifetime),pool_timeout:String(p.poolTimeout),socket_timeout:String(p.socketTimeout)});async function ie(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 ${p.username} WITH LOGIN SUPERUSER PASSWORD '${p.password}'`):await e.exec(`CREATE ROLE ${p.username} WITH LOGIN SUPERUSER PASSWORD '${p.password}'`),await e.exec(`SET ROLE ${p.username}`)}async function wt(e,t){if(e==="shadow_database"&&!t.dryRun)return await Ye(t);let r=e==="database"?t.databasePort:t.shadowDatabasePort;return t.dryRun?ue(e,t,{db:null,port:r,server:null}):await le(e,t,{port:r,updateServerStatePort:!0})}async function Ye(e,t=async()=>await le("shadow_database",e,{port:0,updateServerStatePort:!1})){let{debug:r}=e,n=null,a=null,s=!1,d=new Set,o=Fe(c),u=await ze(o,e.shadowDatabasePort);return e.shadowDatabasePort=u,r&&console.debug(`[shadow_database] lazy proxy listening on port ${u}`),{...p,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()=>{s=!0;for(let m of d)m.destroy();d.clear();let i=[];try{await Je(o),r&&console.debug(`[shadow_database] lazy proxy stopped on port ${u}`)}catch(m){console.error("[shadow_database] lazy proxy stop error",m),i.push(m)}try{await a?.catch(()=>null),await n?.close()}catch(m){console.error("[shadow_database] backend close error",m),i.push(m)}if(i.length>0)throw new AggregateError(i,"Failed to close shadow_database properly")},connectionString:T(u,L),dump:async()=>{},getPrimaryKeyColumns:()=>Promise.reject(new Error("Primary key resolution is only available for the primary database server")),port:u,prismaORMConnectionString:T(u,se),terminalCommand:`PGPASSWORD=${p.password} PGSSLMODE=${p.sslMode} psql -h localhost -p ${u} -U ${p.username} -d ${p.database}`};function c(i){d.add(i);let m=()=>{d.delete(i)};i.once("close",m),i.once("error",m),i.pause(),l(i)}async function l(i){try{let m=await f();if(s){i.destroy();return}let g=qe({host:ne,port:m.port});d.add(g);let w=()=>{d.delete(g)};g.once("close",w),g.once("error",w),i.once("close",()=>g.destroy()),i.once("error",()=>g.destroy()),g.once("error",()=>i.destroy()),g.once("connect",()=>{r&&console.debug(`[shadow_database] proxying connection to lazy backend on port ${m.port}`),i.resume(),i.pipe(g),g.pipe(i)})}catch(m){r&&console.error("[shadow_database] failed to start lazy backend",m),i.destroy(m instanceof Error?m:void 0)}}async function f(){if(n)return n;if(s)throw new Error("shadow_database is closed");return a||(r&&console.debug("[shadow_database] starting lazy backend..."),a=t().then(i=>(n=i,r&&console.debug(`[shadow_database] lazy backend started on port ${i.port}`),i)).catch(i=>{throw a=null,i})),await a}}async function le(e,t,r){let{debug:n}=t,{port:a,updateServerStatePort:s}=r,o=await(e==="shadow_database"?Xe:ce)(t.pgliteDataDirPath,n);n&&o.onNotification((i,m)=>{console.debug(`[${e}][${i}] ${m}`)});let{PGLiteSocketServer:u}=await import("@electric-sql/pglite-socket"),c=e==="shadow_database"?t.shadowDatabaseIdleTimeoutMillis:t.databaseIdleTimeoutMillis,l=new u({db:o,debug:n,idleTimeout:Number.isFinite(c)?c:0,inspect:n,maxConnections:p.connectionLimit,port:a});n&&(l.addEventListener("listening",i=>{let{detail:m}=i;console.debug(`[${e}] server listening on ${JSON.stringify(m)}`)}),l.addEventListener("connection",i=>{let{clientAddress:m,clientPort:g}=i.detail;console.debug(`[${e}] client connected from ${m}:${g}`)}),l.addEventListener("error",i=>{let{detail:m}=i;console.error(`[${e}] server error:`,m)}));try{await l.start()}catch(i){throw i instanceof Error&&"code"in i&&i.code==="EADDRINUSE"?new I(a):i}let f=Number(l.getServerConn().split(":").at(1));return s&&(t[e==="database"?"databasePort":"shadowDatabasePort"]=f),ue(e,t,{db:o,port:f,server:l})}function ue(e,t,r){let{debug:n}=t,{db:a,port:s,server:d}=r||{},o=new Map;return n&&console.debug(`[${e}] server started on port ${s}`),{...p,attachWalEventBridge:async()=>{if(e!=="database"||!a)throw new Error("WAL bridge is only available for the primary database server");return await v(a)},attachQueryInsightsBridge:()=>{if(e!=="database"||!d)throw new Error("Query insights are only available for the primary database server");return Promise.resolve(K(d))},close:async()=>{let u=[];try{await d?.stop(),n&&console.debug(`[${e}] server stopped on port ${s}`)}catch(c){console.error(`[${e}] server stop error`,c),u.push(c)}if(e==="database"){try{d&&await Y(d),n&&console.debug(`[${e}] closed query insights bridge`)}catch(c){console.error(`[${e}] query insights bridge close error`,c),u.push(c)}try{a&&await V(a),n&&console.debug(`[${e}] closed WAL bridge`)}catch(c){console.error(`[${e}] WAL bridge close error`,c),u.push(c)}try{await a?.syncToFs(),n&&console.debug(`[${e}] synced to filesystem`)}catch(c){console.error(`[${e}] sync error`,c),u.push(c)}}try{await a?.close(),n&&console.debug(`[${e}] closed`)}catch(c){console.error(`[${e}] close error`,c),u.push(c)}if(u.length>0)throw new AggregateError(u,`Failed to close ${e} properly`)},connectionString:T(s,L),dump:async u=>{e==="shadow_database"||!a||await Ve({db:a,debug:n,destinationPath:u})},getPrimaryKeyColumns:async(u,c)=>{if(e==="shadow_database"||!a)throw new Error("Primary key resolution is only available for the primary database server");let l=`${u}.${c}`,f=o.get(l);return f||(f=je(a,u,c).catch(i=>{throw o.delete(l),i}),o.set(l,f)),await f},port:s,prismaORMConnectionString:T(s,se),terminalCommand:`PGPASSWORD=${p.password} PGSSLMODE=${p.sslMode} psql -h localhost -p ${s} -U ${p.username} -d ${p.database}`}}function T(e,t){return`${Ke}:${e}/${p.database}?${t.toString()}`}async function ce(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await N(),a=e==="memory://"||!await O(Ue(e,"PG_VERSION")),s=await r.create({database:p.database,dataDir:e,debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:ae,loadDataDir:a?n.loadDataDir:void 0,relaxedDurability:!1,startParams:[...r.defaultStartParams,...oe],wasmModule:n.wasmModule});return await ie(s),s}async function ze(e,t){return await new Promise((r,n)=>{let a=o=>{if(d(),o.code==="EADDRINUSE"){n(new I(t));return}n(o)},s=()=>{let o=e.address();if(d(),!o||typeof o=="string"){n(new Error("Failed to determine TCP server port"));return}r(o.port)},d=()=>{e.off("error",a),e.off("listening",s)};e.once("error",a),e.once("listening",s),e.listen(t,ne)})}async function Je(e){await new Promise((t,r)=>{e.close(n=>{let a=n;if(a&&a.code!=="ERR_SERVER_NOT_RUNNING"){r(a);return}t()})})}async function Xe(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await N(),a=await r.create({database:p.database,dataDir:"memory://",debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:ae,loadDataDir:n.loadDataDir,relaxedDurability:!1,startParams:[...r.defaultStartParams,...oe],wasmModule:n.wasmModule});return await ie(a),a}async function je(e,t,r){let{rows:n}=await e.query(` | ||
| SELECT attribute.attname AS column_name | ||
| FROM pg_constraint pk_constraint | ||
| INNER JOIN pg_class relation | ||
| ON relation.oid = pk_constraint.conrelid | ||
| INNER JOIN pg_namespace namespace | ||
| ON namespace.oid = relation.relnamespace | ||
| INNER JOIN unnest(pk_constraint.conkey) WITH ORDINALITY AS keys(attnum, ordinality) | ||
| ON TRUE | ||
| INNER JOIN pg_attribute attribute | ||
| ON attribute.attrelid = relation.oid | ||
| AND attribute.attnum = keys.attnum | ||
| WHERE pk_constraint.contype = 'p' | ||
| AND namespace.nspname = ${re(t)} | ||
| AND relation.relname = ${re(r)} | ||
| ORDER BY keys.ordinality | ||
| `);return n.map(a=>a.column_name)}function re(e){return`'${e.replaceAll("'","''")}'`}async function Ve(e){let{dataDir:t,db:r,debug:n,destinationPath:a}=e,s=r||await ce(t,n),{pgDump:d}=await import("@electric-sql/pglite-tools/pg_dump"),o=await d({args:["--schema-only","--no-owner"],fileName:a?We(a):void 0,pg:await s.clone()});return a?(n&&console.debug(`[DB] Dumping database to ${a}`),await C(o,a)):(n&&console.debug("[DB] Dumping database to memory"),await o.text())}export{et as a,tt as b,v as c,M as d,Z as e,wt as f,Ye as g,Ve as h}; |
| import{b as w,d as y,e as E}from"./chunk-MN4XKQ55.js";import{a as v,b,c as R}from"./chunk-T6L5TENJ.js";import{d as g}from"./chunk-JLSS5G22.js";g();import{spawn as H}from"child_process";import{once as C}from"events";import{mkdir as A}from"fs/promises";import{join as j}from"path";import{setTimeout as B}from"timers/promises";g();function P(r){let e,t,s=new Promise((i,a)=>{e=i,t=a}),n=i=>{n=o=null,t(i),r?.onRejected?.(i),r?.onFulfilled?.()},o=i=>{o=n=null,e(i),r?.onResolved?.(i),r?.onFulfilled?.()};return{isFulfilled:()=>o===n,promise:s,reject:i=>n?.(i),resolve:i=>o?.(i)}}import{process as L}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:N,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:Q,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:S}=L.env,T=class r{static#t=new Map;#e;#n;constructor(e){this.#e=e,this.#n=null}static async get(e){let{debug:t}=e,s=`${e.schemaHash}:${e.clientVersion}`;try{let n=r.#t.get(s);if(n)return n;let o=new r(e);return r.#t.set(s,o),t&&console.debug("[Query Engine] starting...",e),await o.start(),t&&console.debug("[Query Engine] started!"),o}finally{r.stopAll(s)}}static async stopAll(e){let s=(await Promise.allSettled(Array.from(r.#t.entries()).filter(([n])=>n!==e).map(async([n,o])=>{try{await o.stop()}finally{r.#t.delete(n)}}))).filter(n=>n.status==="rejected").map(n=>n.reason);if(s.length>0)throw new AggregateError(s,"Failed to stop engines")}async commitTransaction(e,t){return await this.#s(e,t,"commit")}async request(e,t){let{url:s}=await this.start(),n=this.#i(t),o=await fetch(s,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...n,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await l.fromResponse(o);return await o.text()}async rollbackTransaction(e,t){return await this.#s(e,t,"rollback")}async startTransaction(e,t){let{url:s}=await this.start(),n=this.#i(t),o=await fetch(`${s}/transaction/start`,{body:JSON.stringify(e),headers:{...n,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await l.fromResponse(o);return await o.json()}async start(){if(this.#n!=null)return await this.#n;let{promise:e,reject:t,resolve:s}=P();this.#n=e;let n=Q||await this.#o();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",n);let{proxySignals:o}=await import("foreground-child/proxy-signals"),i=H(n,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});o(i),i.stderr.setEncoding("utf8"),i.stdout.setEncoding("utf8");let a=c=>{let u=c.split(` | ||
| `).find(O=>O.includes("Started query engine http server"));if(!u)return;i.stdout.removeListener("data",a);let{fields:m}=JSON.parse(u);if(m==null)return t(new Error(`Unexpected data during initialization, "fields" are missing: ${c}`));let{ip:h,port:f}=m;if(h==null||f==null)return t(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry. | ||
| Received data: ${c}`));s({childProcess:i,url:`http://${h}:${f}`})},k=c=>{this.#n=null,t(new d(String(c))),i.removeListener("exit",p),i.kill()};i.once("error",k);let p=(c,u)=>{this.#n=null,t(new d(`Query Engine exited with code ${c} and signal ${u}`))};return i.once("exit",p),i.stdout.on("data",a),this.#e.debug&&(i.stderr.on("data",console.error.bind(console,"[Query Engine]")),i.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#n}async stop(){if(this.#n==null)return;let{childProcess:e}=await this.#n;e.exitCode==null&&e.signalCode==null&&(this.#n=null,e.kill(),await C(e,"exit"))}async#o(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#r();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let t=w(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",t),await A(t,{recursive:!0});let{binaryTarget:s}=this.#e.platform,n=s==="windows"?".exe":"",o=j(t,`query-engine-${s}${n}`);return this.#e.debug&&console.debug("[Query Engine] binary path",o),(N==="1"||await y(o)===!1)&&await this.#a({commitHash:e,extension:n,engineBinaryPath:o}),o}async#r(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let s=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!s)throw new Error("Couldn't find engines version in package.json");let n=s.split(".").at(-1);if(!n)throw new Error("Couldn't find commit hash in engines version");return n}async#a(e){let{commitHash:t,extension:s,engineBinaryPath:n}=e,{binaryTarget:o}=this.#e.platform,i=`https://binaries.prisma.sh/all_commits/${t}/${o}/query-engine${s}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",i);let a=await fetch(i);if(!a.ok)throw new Error(`Couldn't download engine. URL: ${i}, status code: ${a.status}`);S&&await B(Number(S)),await E(await a.arrayBuffer(),n),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",n)}#i(e){let t={};for(let[s,n]of Object.entries(e))n!=null&&(t[s]=n);return t}async#s(e,t,s){let{url:n}=await this.#n,o=this.#i(t),i=await fetch(`${n}/transaction/${e}/${s}`,{headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await l.fromResponse(i);try{return await i.json()}catch{return{}}}};function W(r,e){if(console.error(r),r instanceof d){v(e,{EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:r.message}}}},500);return}if(r instanceof l){b(e,r.responseBody,r.statusCode);return}R(e,500)}var d=class extends Error{name="EngineStartError"},l=class r extends Error{constructor(t,s,n){super(`${t}: Query Engine response status ${s}, body: ${n}`);this.action=t;this.statusCode=s;this.responseBody=n}name="EngineHttpError";static async fromResponse(t){let s=new URL(t.url),n=await t.text();return new r(s.pathname,t.status,n)}};export{T as Engine,W as handleEngineError}; |
| import{d as o}from"./chunk-JLSS5G22.js";o();import{parseDuration as e,parseSize as n,Server as a}from"@prisma/query-plan-executor";import{version as f}from"@prisma/query-plan-executor";var r;async function m(t){return r===void 0&&(r=await a.create({databaseUrl:t.db.connectionString,maxResponseSize:n("128 MiB"),queryTimeout:e("PT5M"),maxTransactionTimeout:e("PT5M"),maxTransactionWaitTime:e("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:t.debug?"debug":"off"}})),r}export{m as getQueryPlanExecutorServer,f as queryPlanExecutorVersion}; |
| import{a,b}from"./chunk-U3HKF6IL.js";import"./chunk-I2OHVRST.js";import"./chunk-UEE5SWKL.js";import"./chunk-T6L5TENJ.js";import"./chunk-JLSS5G22.js";export{b as createHTTPServer,a as wrap}; |
| import{a as r}from"./chunk-U3HKF6IL.js";import"./chunk-I2OHVRST.js";import"./chunk-UEE5SWKL.js";import{a}from"./chunk-T6L5TENJ.js";import{d as p}from"./chunk-JLSS5G22.js";p();function u(o,e,m){o.on("POST","/database/dump",r(async(n,t)=>{await e.db.dump(e.databaseDumpPath),a(t,{dumpPath:e.databaseDumpPath},201)},m)),o.on("GET","/health",r((n,t)=>{a(t,{name:e.name})},m))}export{u as registerUtilityRoutes}; |
+1
-1
@@ -1,1 +0,1 @@ | ||
| import{a}from"./chunk-FB4QA6EA.js";import"./chunk-662IKR3V.js";import"./chunk-PP43TGA5.js";import"./chunk-KWCQYPJI.js";import"./chunk-HFONW2ZS.js";import"./chunk-ANHBRJRZ.js";import"./chunk-EDFHV3AK.js";import"./chunk-DWY47FQV.js";import"./chunk-DOJAPHLY.js";import{setTimeout as o}from"timers/promises";var e;process.once("SIGTERM",()=>{console.log("SIGTERM received, shutting down..."),process.removeAllListeners("SIGINT"),process.exitCode=143,e?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{console.log("SIGINT received, shutting down..."),process.removeAllListeners("SIGTERM"),process.exitCode=130,e?.close().finally(()=>process.exit())});async function n(){let[,,t]=process.argv;if(!t)return process.send?.({type:"error",error:'Missing "name" argument, server cannot be started'},void 0),process.exit(1);try{e=await a({debug:!0,persistenceMode:"stateful",name:t});let r=e.experimental.queryInsights,s={database:e.database,experimental:{queryInsights:{serverUrl:r.serverUrl,sqlitePath:r.sqlitePath,streamName:r.streamName,url:r.url},streams:e.experimental.streams},http:e.http,name:e.name,ppg:e.ppg,shadowDatabase:e.shadowDatabase};process.send?.({type:"started",server:s},void 0)}catch(r){console.error(r);let s=r instanceof Error?r.message:String(r);process.send?.({type:"error",error:s},void 0),await o(1e3),process.exit(1)}}n(); | ||
| import{a as o}from"./chunk-RN4YJIL3.js";import"./chunk-DEMTR4W3.js";import"./chunk-WQHUHPVC.js";import"./chunk-HM357TKK.js";import"./chunk-GT33FFME.js";import"./chunk-I2OHVRST.js";import"./chunk-UEE5SWKL.js";import"./chunk-MN4XKQ55.js";import"./chunk-T6L5TENJ.js";import{d as a}from"./chunk-JLSS5G22.js";a();import{setTimeout as n}from"timers/promises";var e;process.once("SIGTERM",()=>{console.log("SIGTERM received, shutting down..."),process.removeAllListeners("SIGINT"),process.exitCode=143,e?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{console.log("SIGINT received, shutting down..."),process.removeAllListeners("SIGTERM"),process.exitCode=130,e?.close().finally(()=>process.exit())});async function i(){let[,,t]=process.argv;if(!t)return process.send?.({type:"error",error:'Missing "name" argument, server cannot be started'},void 0),process.exit(1);try{e=await o({debug:!0,persistenceMode:"stateful",name:t});let r=e.experimental.queryInsights,s={database:e.database,experimental:{queryInsights:{serverUrl:r.serverUrl,sqlitePath:r.sqlitePath,streamName:r.streamName,url:r.url},streams:e.experimental.streams},http:e.http,name:e.name,ppg:e.ppg,shadowDatabase:e.shadowDatabase};process.send?.({type:"started",server:s},void 0)}catch(r){console.error(r);let s=r instanceof Error?r.message:String(r);process.send?.({type:"error",error:s},void 0),await n(1e3),process.exit(1)}}i(); |
+1
-1
@@ -1,1 +0,1 @@ | ||
| import{c as a,d as b,e as c,f as d,g as e,h as f}from"./chunk-PP43TGA5.js";import"./chunk-KWCQYPJI.js";import"./chunk-EDFHV3AK.js";import"./chunk-DWY47FQV.js";export{a as attachWalEventBridge,f as dumpDB,b as shouldPollWalAfterMessages,c as shouldPollWalAfterResponse,d as startDBServer,e as startLazyShadowDBServer}; | ||
| import{c as a,d as b,e as c,f as d,g as e,h as f}from"./chunk-WQHUHPVC.js";import"./chunk-HM357TKK.js";import"./chunk-UEE5SWKL.js";import"./chunk-MN4XKQ55.js";import"./chunk-JLSS5G22.js";export{a as attachWalEventBridge,f as dumpDB,b as shouldPollWalAfterMessages,c as shouldPollWalAfterResponse,d as startDBServer,e as startLazyShadowDBServer}; |
+1
-1
@@ -1,1 +0,1 @@ | ||
| import{a as i,b as j}from"./chunk-FB4QA6EA.js";import"./chunk-662IKR3V.js";import"./chunk-PP43TGA5.js";import{a as f,b as g}from"./chunk-KWCQYPJI.js";import{l as h}from"./chunk-HFONW2ZS.js";import"./chunk-ANHBRJRZ.js";import{a,b,c,d,h as e}from"./chunk-EDFHV3AK.js";import"./chunk-DWY47FQV.js";import"./chunk-DOJAPHLY.js";export{a as DEFAULT_DATABASE_PORT,b as DEFAULT_SERVER_PORT,c as DEFAULT_SHADOW_DATABASE_PORT,d as DEFAULT_STREAMS_PORT,e as PortNotAvailableError,h as ServerAlreadyRunningError,f as copyPrismaDevRuntimeAssets,g as getPrismaDevRuntimeAssetManifest,i as startPrismaDevServer,j as unstable_startServer}; | ||
| import{a as i,b as j}from"./chunk-RN4YJIL3.js";import"./chunk-DEMTR4W3.js";import"./chunk-WQHUHPVC.js";import{a as f,b as g}from"./chunk-HM357TKK.js";import{l as h}from"./chunk-GT33FFME.js";import"./chunk-I2OHVRST.js";import{a,b,c,d,h as e}from"./chunk-UEE5SWKL.js";import"./chunk-MN4XKQ55.js";import"./chunk-T6L5TENJ.js";import"./chunk-JLSS5G22.js";export{a as DEFAULT_DATABASE_PORT,b as DEFAULT_SERVER_PORT,c as DEFAULT_SHADOW_DATABASE_PORT,d as DEFAULT_STREAMS_PORT,e as PortNotAvailableError,h as ServerAlreadyRunningError,f as copyPrismaDevRuntimeAssets,g as getPrismaDevRuntimeAssetManifest,i as startPrismaDevServer,j as unstable_startServer}; |
@@ -1,1 +0,1 @@ | ||
| import{a,b,c,d,e}from"./chunk-KWCQYPJI.js";export{a as copyPrismaDevRuntimeAssets,c as getPGliteRuntimeAssets,b as getPrismaDevRuntimeAssetManifest,d as registerBundledPGliteRuntimeAssetSources,e as resolveBundledRuntimeAssetSource}; | ||
| import{a,b,c,d,e}from"./chunk-HM357TKK.js";import"./chunk-JLSS5G22.js";export{a as copyPrismaDevRuntimeAssets,c as getPGliteRuntimeAssets,b as getPrismaDevRuntimeAssetManifest,d as registerBundledPGliteRuntimeAssetSources,e as resolveBundledRuntimeAssetSource}; |
+1
-1
@@ -1,1 +0,1 @@ | ||
| import{f as a,g as b,h as c,i as d,j as e,k as f,l as g}from"./chunk-HFONW2ZS.js";import"./chunk-EDFHV3AK.js";import"./chunk-DWY47FQV.js";export{g as ServerAlreadyRunningError,a as ServerState,f as ServerStateAlreadyExistsError,b as deleteServer,c as getServerStatus,d as isServerRunning,e as killServer}; | ||
| import{f as a,g as b,h as c,i as d,j as e,k as f,l as g}from"./chunk-GT33FFME.js";import"./chunk-UEE5SWKL.js";import"./chunk-MN4XKQ55.js";import"./chunk-JLSS5G22.js";export{g as ServerAlreadyRunningError,a as ServerState,f as ServerStateAlreadyExistsError,b as deleteServer,c as getServerStatus,d as isServerRunning,e as killServer}; |
+2
-2
| { | ||
| "name": "@prisma/dev", | ||
| "version": "0.24.14", | ||
| "version": "0.24.15", | ||
| "description": "A local Prisma Postgres server for development and testing", | ||
@@ -73,2 +73,3 @@ "type": "module", | ||
| "env-paths": "3.0.0", | ||
| "find-my-way": "9.7.0", | ||
| "pg": "8.16.0", | ||
@@ -88,3 +89,2 @@ "pkg-types": "2.3.0", | ||
| "@prisma/streams-local": "0.1.11", | ||
| "find-my-way": "9.6.0", | ||
| "foreground-child": "3.3.1", | ||
@@ -91,0 +91,0 @@ "get-port-please": "3.2.0", |
| import{b as p}from"./chunk-662IKR3V.js";import{a as g}from"./chunk-SW3J2PL2.js";import{a as M}from"./chunk-ANHBRJRZ.js";import"./chunk-EDFHV3AK.js";import{a as d,b as m,c as B}from"./chunk-DOJAPHLY.js";import{text as Q}from"stream/consumers";import{json as en}from"stream/consumers";import{array as tn,literal as rn,minLength as on,object as sn,pipe as an,safeParse as cn,string as un,union as ln}from"valibot";var fn=sn({tags:ln([an(tn(un()),on(1)),rn("all")])});async function C(n,r){let e;try{e=await en(n)}catch{return m(r,"Invalid input",400),null}let{output:t,success:i}=cn(fn,e,{abortEarly:!0});return i?t:(m(r,"Invalid input",400),null)}import{Buffer as L}from"buffer";var x=new Map;async function O(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(a=>a.toString(16).padStart(2,"0")).join("")}function N(n,r){let e=n.schemaHash;if(e==null)return d(r,{EngineNotStarted:{reason:"SchemaMissing"}},404),null;let t=x.get(e);return t==null?(d(r,{EngineNotStarted:{reason:"SchemaMissing"}},404),null):{schemaHash:e,schemas:t}}async function V(n,r,e){let t=L.from(n,"base64").toString("utf8"),i=mn(t,r.toString());e&&console.log("[Accelerate] schema with override:",i);let o=await O(i);return{base64Override:L.from(i,"utf8").toString("base64"),overrideHash:o}}var dn=" ";function mn(n,r){let e=pn(n);if(!e)throw new Error("No datasource block found in schema.");let t=n.slice(e.openBraceIndex+1,e.closeBraceIndex),i=Sn(t,r,wn(n,e.openBraceIndex));return`${n.slice(0,e.openBraceIndex+1)}${i}${n.slice(e.closeBraceIndex)}`}function pn(n){let r="datasource";for(let e=0;e<n.length;e+=1){let t=n[e];if(t==="/"&&n[e+1]==="/"){e=R(n,e+2);continue}if(t==="/"&&n[e+1]==="*"){e=P(n,e+2);continue}if(t==='"'){e=v(n,e+1);continue}if(n.startsWith(r,e)&&!_(n[e-1])&&!_(n[e+r.length])){let i=gn(n,e+r.length,"{");if(i===-1)return null;let o=hn(n,i);return o===-1?null:{closeBraceIndex:o,openBraceIndex:i}}}return null}function gn(n,r,e){for(let t=r;t<n.length;t+=1){let i=n[t];if(i==="/"&&n[t+1]==="/"){t=R(n,t+2);continue}if(i==="/"&&n[t+1]==="*"){t=P(n,t+2);continue}if(i==='"'){t=v(n,t+1);continue}if(i===e)return t}return-1}function hn(n,r){let e=0;for(let t=r;t<n.length;t+=1){let i=n[t];if(i==="/"&&n[t+1]==="/"){t=R(n,t+2);continue}if(i==="/"&&n[t+1]==="*"){t=P(n,t+2);continue}if(i==='"'){t=v(n,t+1);continue}if(i==="{"){e+=1;continue}if(i==="}"&&(e-=1,e===0))return t}return-1}function R(n,r){let e=r;for(;e<n.length&&n[e]!==` | ||
| `;)e+=1;return e}function P(n,r){let e=n.indexOf("*/",r);return e===-1?n.length:e+1}function v(n,r){let e=r;for(;e<n.length;){if(n[e]==="\\"){e+=2;continue}if(n[e]==='"')return e;e+=1}return n.length}function _(n){return n!=null&&/[A-Za-z0-9_]/.test(n)}function Sn(n,r,e){let t=`"${xn(r)}"`,i=yn(n);for(let[f,h]of i.entries()){let{comment:I,code:nn}=D(h.line),T=nn.match(/^(\s*)url(\s*)=(\s*).*/);if(T)return i[f]={line:`${T[1]}url${T[2]}=${T[3]}${t}${I}`,terminator:h.terminator},$(i)}let o=Tn(n),a=In(i,e),u=`${a}url = ${t}`;if(!n.includes(` | ||
| `)&&!n.includes("\r")){let f=n.trim();return f.length===0?`${o}${u}${o}${e}`:`${o}${a}${f}${o}${u}${o}${e}`}let s=i.at(-1);if(s&&s.terminator===""&&/^\s*$/.test(s.line))return`${$(i.slice(0,-1))}${u}${o}${e}`;let c=$(i),l=c.endsWith(` | ||
| `)||c.endsWith("\r")?"":o;return`${c}${l}${u}${o}${e}`}function yn(n){let r=[],e=0;for(let t=0;t<n.length;t+=1){if(n[t]==="\r"&&n[t+1]===` | ||
| `){r.push({line:n.slice(e,t),terminator:`\r | ||
| `}),t+=1,e=t+1;continue}(n[t]===` | ||
| `||n[t]==="\r")&&(r.push({line:n.slice(e,t),terminator:n[t]}),e=t+1)}return(e<n.length||n.length===0)&&r.push({line:n.slice(e),terminator:""}),r}function $(n){return n.map(r=>`${r.line}${r.terminator}`).join("")}function D(n){let r=!1,e=!1;for(let t=0;t<n.length;t+=1){let i=n[t];if(e){if(r){r=!1;continue}if(i==="\\"){r=!0;continue}i==='"'&&(e=!1);continue}if(i==='"'){e=!0;continue}if(i==="/"&&n[t+1]==="/")return{code:n.slice(0,t),comment:n.slice(t)}}return{code:n,comment:""}}function In(n,r){for(let e of n){let{code:t}=D(e.line),i=t.match(/^([ \t]+)[A-Za-z_][A-Za-z0-9_]*\s*=/);if(i?.[1])return i[1]}return`${r}${dn}`}function wn(n,r){let e=n.lastIndexOf(` | ||
| `,r)+1,t=e;for(;n[t]===" "||n[t]===" ";)t+=1;return n.slice(e,t)}function Tn(n){return n.includes(`\r | ||
| `)?`\r | ||
| `:` | ||
| `}function xn(n){return n.replaceAll("\\","\\\\").replaceAll('"','\\"')}function w(n,r){let e=n[r];return Array.isArray(e)?e.at(-1):e}import{Readable as q}from"stream";import{pipeline as Hn}from"stream/promises";var En=new Set(["GET","HEAD"]);function U(n,r){let e=(n.method??"GET").toUpperCase(),t=`${r.origin}${n.url??"/"}`,i={headers:$n(n.headers),method:e};return En.has(e)||(i.body=q.toWeb(n),i.duplex="half"),new Request(t,i)}async function j(n,r){r.statusCode=n.status;for(let[e,t]of n.headers)r.setHeader(e,t);if(n.body===null){r.end();return}await Hn(q.fromWeb(n.body),r)}function $n(n){let r=new Headers;for(let[e,t]of Object.entries(n))if(typeof t=="string")r.append(e,t);else if(Array.isArray(t))for(let i of t)r.append(e,i);return r}function H(n){return{traceparent:w(n.headers,"traceparent"),"X-capture-telemetry":w(n.headers,"x-capture-telemetry")}}import{json as On}from"stream/consumers";import{integer as F,looseObject as Rn,minValue as k,number as b,object as Pn,optional as vn,pipe as W,safeParse as G,string as z,union as bn}from"valibot";var An=Pn({isolation_level:vn(z()),max_wait:W(b(),F(),k(0)),timeout:W(b(),F(),k(0))});async function Y(n,r){let e;try{e=await On(n)}catch{return d(r,{EngineNotStarted:{reason:"InvalidRequest",issues:[]}},400),null}let{issues:t,output:i,success:o}=G(An,e,{abortEarly:!0});return o?i:(d(r,{EngineNotStarted:{reason:"InvalidRequest",issues:t}},400),null)}var Mn=Rn({id:bn([z(),b()])});function J(n,r){let{output:e,success:t}=G(Mn,n);return t?e:(d(r,{EngineMalfunction:{}},500),null)}var X,Z,K;function E(){return X??=import("./engine-YTEOPVUP.js"),X}function Bn(){return K??=import("./query-plan-executor-ZS4544O3.js"),K}async function Cn(){return Z??=import("@prisma/get-platform").then(async({default:n})=>await n.getPlatformInfo()),await Z}function ge(n,r,e){n.on("POST","/invalidate",g(async(i,o)=>{p(i,r),await C(i,o)!==null&&B(o,200)},e));for(let i of["/:clientVersion/:schemaHash/graphql","/:clientVersion/:schemaHash/itx/:transactionId/graphql"])n.on("POST",i,g(async(o,a,u)=>{p(o,r);try{let s=await A(a,r,u);if(s===null)return;let c=await Q(o),l=u.transactionId,f=await s.request(c,{...H(o),"X-transaction-id":l});m(a,f)}catch(s){let{handleEngineError:c}=await E();c(s,a)}},e));for(let i of["commit","rollback"])n.on("POST",`/:clientVersion/:schemaHash/itx/:transactionId/${i}`,g(async(o,a,u)=>{p(o,r);try{let s=await A(a,r,u);if(s===null)return;let c=u.transactionId;if(c==null){d(a,{EngineMalfunction:{}},500);return}let l=`${i}Transaction`,f=await s[l](c,H(o));d(a,f)}catch(s){let{handleEngineError:c}=await E();c(s,a)}},e));n.on("PUT","/:clientVersion/:schemaHash/schema",g(async(i,o,a)=>{p(i,r);let u=await Q(i);if(!u){m(o,"Missing schema",400);return}let s=a.schemaHash;if(s==null){m(o,"Missing schema hash",400);return}let c=x.get(s);if(c==null){if(s!==await O(u)){m(o,"Schema hash mismatch",400);return}let l=await V(u,r.db.prismaORMConnectionString,r.debug);x.set(s,{base64Original:u,...l}),m(o,s);return}if(u!==c.base64Original){m(o,"Schema mismatch",400);return}m(o,s)},e)),n.on("POST","/:clientVersion/:schemaHash/transaction/start",g(async(i,o,a)=>{p(i,r);let u=await Y(i,o);if(u!==null)try{let s=await A(o,r,a);if(s===null)return;let c=await s.startTransaction(u,H(i)),l=J(c,o);if(l===null)return;let{id:f}=l,h=a.clientVersion,I=a.schemaHash;d(o,{...c,"data-proxy":{endpoint:`http://localhost:${r.port}/${h}/${I}/itx/${f}`}})}catch(s){let{handleEngineError:c}=await E();c(s,o)}},e));let t=[["GET","/connection-info"],["POST","/query"],["POST","/transaction/start"],["POST","/transaction/:transactionId/commit"],["POST","/transaction/:transactionId/query"],["POST","/transaction/:transactionId/rollback"]];for(let[i,o]of t)n.on(i,o,g(async(a,u)=>{p(a,r);let{getQueryPlanExecutorServer:s,queryPlanExecutorVersion:c}=await Bn(),l=w(a.headers,"prisma-engine-hash");if(l!=="0.0.0"&&l!==c)throw new M(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 ${c}.`);let f=await s(r),h=U(a,{origin:`http://localhost:${r.port}`}),I=await f.fetch(h);await j(I,u)},e))}async function A(n,r,e){let{Engine:t}=await E(),i=N(e,n);if(i===null)return null;let{base64Override:o,overrideHash:a}=i.schemas;return await t.get({base64Schema:o,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.clientVersion||"",debug:r.debug,platform:await Cn(),schemaHash:a})}export{ge as registerAccelerateRoutes}; |
| import{a as r}from"./chunk-ANHBRJRZ.js";import{minLength as D,object as S,optional as B,parseJson as x,pipe as n,regex as h,safeParse as O,string as s,url as f}from"valibot";var l=/^(postgres|postgresql):\/\//,T=n(s(),x(),S({databaseUrl:n(s(),f(),h(l)),name:B(n(s(),D(1))),shadowDatabaseUrl:n(s(),f(),h(l))}));function $(o){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(o).sort(([[e],[t]])=>e.localeCompare(t)))),"utf8").toString("base64url")}function E(o){let e=Buffer.from(o,"base64url").toString("utf8"),{issues:t,output:a,success:i}=O(T,e,{abortEarly:!0});return i?[null,a]:[t]}function j(o,e){let t=o.headers.authorization;if(!t)throw new r(401,"Missing API Key");let[a,i="",y]=t.split(" ");if(a!=="Bearer"||y)throw new r(401,"Invalid API Key");let[c,p]=E(i);if(c)throw new r(401,"Invalid API Key",{cause:c.join(", ")});let{databaseUrl:P,name:d,shadowDatabaseUrl:A}=p,u=e.name,m=e.port;if(!d)throw new r(401,`Wrong API Key; The Prisma Dev server running at port ${m} requires an API Key from a newer version of \`prisma dev\`. Check the "${u}" server's output for the updated \`DATABASE_URL\` value.`);if(d!==u)throw new r(401,`Wrong API Key; The Prisma Dev server running at port ${m} is named "${u}", but the API Key is for "${d}"`);let{hostname:I,port:w}=new URL(P),{port:g}=e.db,{hostname:b,port:K}=new URL(A),v=e.shadowDBPort;if(I!=="localhost"||Number(w)!==g||b!=="localhost"||Number(K)!==v)throw new r(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 p}export{$ as a,j as b}; |
| var r=class extends Error{constructor(t,e,n){super(e,n);this.status=t}name="HTTPError"};export{r as a}; |
| import{Buffer as r}from"buffer";function i(e,t,o=200){let n=r.from(JSON.stringify(t),"utf8");e.headersSent||(e.setHeader("Content-Type","application/json; charset=utf-8"),e.setHeader("Content-Length",n.byteLength),e.statusCode=o),e.end(n)}function s(e,t,o=200){let n=r.from(t,"utf8");e.headersSent||(e.setHeader("Content-Type","text/plain; charset=utf-8"),e.setHeader("Content-Length",n.byteLength),e.statusCode=o),e.end(n)}function f(e,t=204){e.headersSent||(e.statusCode=t,e.setHeader("Content-Length",0)),e.end()}function u(e,t){s(e,t.message,t.status)}export{i as a,s as b,f as c,u as d}; |
| import{createWriteStream as w,WriteStream as A}from"fs";import{access as D,chmod as x,constants as P,mkdir as T,readdir as E,readFile as _,rm as F,writeFile as O}from"fs/promises";import{promisify as v}from"util";import{unzip as C}from"zlib";import o from"path";import g from"os";import c from"process";var n=g.homedir(),a=g.tmpdir(),{env:e}=c,h=t=>{let r=o.join(n,"Library");return{data:o.join(r,"Application Support",t),config:o.join(r,"Preferences",t),cache:o.join(r,"Caches",t),log:o.join(r,"Logs",t),temp:o.join(a,t)}},y=t=>{let r=e.APPDATA||o.join(n,"AppData","Roaming"),i=e.LOCALAPPDATA||o.join(n,"AppData","Local");return{data:o.join(i,t,"Data"),config:o.join(r,t,"Config"),cache:o.join(i,t,"Cache"),log:o.join(i,t,"Log"),temp:o.join(a,t)}},j=t=>{let r=o.basename(n);return{data:o.join(e.XDG_DATA_HOME||o.join(n,".local","share"),t),config:o.join(e.XDG_CONFIG_HOME||o.join(n,".config"),t),cache:o.join(e.XDG_CACHE_HOME||o.join(n,".cache"),t),log:o.join(e.XDG_STATE_HOME||o.join(n,".local","state"),t),temp:o.join(a,r,t)}};function p(t,{suffix:r="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return r&&(t+=`-${r}`),c.platform==="darwin"?h(t):c.platform==="win32"?y(t):j(t)}import L from"zeptomatch";var l=p("prisma-dev"),G=v(C);function z(t,r){return`${l.cache}/engine/${t}/${r}`}function B(t){return`${l.data}/${t}`}async function J(t){try{return await D(t,P.F_OK),!0}catch(r){if(u(r))return!1;throw r}}async function K(t,r){let i=await G(t);await O(r,i),await x(r,"755")}async function q(t,r){await t.stream().pipeTo(A.toWeb(w(r,{encoding:"utf8"})))}function u(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function Q(t){try{return await _(t,{encoding:"utf-8"})}catch(r){if(u(r))return null;throw r}}async function U(t){await T(t,{recursive:!0})}async function V(t,r){try{return(await E(t,{withFileTypes:!0})).reduce((f,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!r||L(r,s.name))&&f.push(s.name),f),[])}catch(i){if(u(i))return[];throw i}}async function Y(t){await F(t,{force:!0,recursive:!0})}export{l as a,z as b,B as c,J as d,K as e,q as f,Q as g,U as h,V as i,Y as j}; |
| import{checkPort as O,getPort as v,isUnsafePort as $}from"get-port-please";import{difference as x,range as k}from"remeda";var S=51214,g=51213,w=51215,T=51216,b=65535,R=0,d=-1/0;async function j(o){let{debug:r,name:e,requestedPorts:n,servers:u}=o,{portsUsedByOtherServers:t,portsUsedByThisServerLastTime:a}=_(e,u);r&&(console.debug(`ports used by other servers: ${Object.keys(t).join(", ")}`),console.debug(`ports used by "${e}" server last time: ${JSON.stringify(a)}`));let i={databasePort:d,port:d,shadowDatabasePort:d,streamsPort:d},s=["port","databasePort","shadowDatabasePort","streamsPort"];for(let c of s){let P=await A({debug:r,portKey:c,portsUsedByOtherServers:t,portsUsedByThisServerLastTime:a,requestedPorts:n})??await B({debug:r,pickedPorts:i,portKey:c,portsUsedByOtherServers:t,portsUsedByThisServerLastTime:a});r&&console.debug(`Got port for "${c}": ${P}`),i[c]=P}return r&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function A(o){let{debug:r,portKey:e,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:u,requestedPorts:t}=o,{[e]:a,...i}=t;if(m(a))return await E({debug:r,otherRequestedPorts:i,portKey:e,portsUsedByOtherServers:n,requestedPort:a}),a;let s=u?.[e]??d;if(!m(s))return r&&console.debug(`No port specified for "${e}". Trying to pick a new port.`),null;let c=s in n;return c||Object.values(i).includes(s)?(r&&console.debug(`Port ${s} that was used last time for this server, ${c?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await O(s)===!1?(r&&console.debug(`Port ${s}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(r&&console.debug(`Using port ${s} for "${e}" as it was used last time and is available.`),s)}async function B(o){let{debug:r,pickedPorts:e,portKey:n,portsUsedByOtherServers:u,portsUsedByThisServerLastTime:t}=o,a=Math.max(S,g,w,T)+1,i=Object.values(e).filter(p=>p!==void 0),s=t?D(t):[],c=[...i,...Object.keys(u).map(Number),...s],P=Math.min(Math.max(a,...c)+100,b),U=x(k(a,P),c),f={port:g,databasePort:S,shadowDatabasePort:w,streamsPort:T}[n];try{return await v({port:f in u||i.includes(f)||s.includes(f)?void 0:f,ports:U})}catch(p){if(p instanceof Error&&p.name==="GetPortError"&&P+1<=b)return r&&console.debug(`Expanding port lookup to range [${P+1}, ${b}].`),await v({portRange:[P+1,b]});throw p}}function m(o){return Number.isFinite(o)&&o>=0}function _(o,r){let e={},n;for(let u of r){let{databasePort:t,port:a,shadowDatabasePort:i}=u,s=q(u);if(u.name===o){n={databasePort:t,port:a,shadowDatabasePort:i,streamsPort:s};continue}e[t]=!0,e[a]=!0,e[i]=!0,m(s)&&(e[s]=!0)}return{portsUsedByOtherServers:e,portsUsedByThisServerLastTime:n}}function q(o){let r=o.experimental?.streams?.serverUrl;if(!r)return d;try{let e=Number(new URL(r).port);return Number.isInteger(e)&&e>0?e:d}catch{return d}}function D(o){return[o.port,o.databasePort,o.shadowDatabasePort,o.streamsPort]}async function E(o){let{debug:r,otherRequestedPorts:e,portKey:n,portsUsedByOtherServers:u,requestedPort:t}=o;if(t!==R){if(t in u)throw r&&console.error(`Port ${t} was requested for "${n}", but is already used by another server.`),new h(t);if(Object.values(e).includes(t))throw r&&console.error(`Port ${t} was requested for "${n}", but also for another key.`),new y(t);if($(t))throw r&&console.error(`Port ${t} was requested for "${n}", but is unsafe.`),new l(t);if(await O(t)===!1)throw r&&console.error(`Port ${t} was requested for "${n}", but is not available.`),new l(t)}}var l=class extends Error{constructor(e){super(`Port \`${e}\` is not available.`);this.port=e}name="PortNotAvailableError"},y=class extends Error{constructor(e){super(`Port number \`${e}\` was requested twice. Please choose a different port for each service.`);this.port=e}name="PortRequestedTwiceError"},h=class extends Error{constructor(e){super(`Port number \`${e}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=e}name="PortBelongsToAnotherServerError"};export{S as a,g as b,w as c,T as d,R as e,d as f,j as g,l as h}; |
| import{a as D}from"./chunk-662IKR3V.js";import{a as q,b as W,f as x}from"./chunk-PP43TGA5.js";import{a as N,b as R,c as M,d as I,e as v,f as $}from"./chunk-HFONW2ZS.js";import{d as _,j as y}from"./chunk-DWY47FQV.js";import{b as O}from"./chunk-DOJAPHLY.js";import X from"find-my-way";async function C(r,e){let{port:t}=e;if(e.dryRun)return{async close(){},port:t,url:`http://localhost:${t}`};let n=!!e.debug,[{registerAccelerateRoutes:s},{registerUtilityRoutes:i},{createHTTPServer:l}]=await Promise.all([import("./accelerate-45DUGMGZ.js"),import("./utility-YEFNU35E.js"),import("./server-QR7P25DP.js")]),a={databaseDumpPath:e.databaseDumpPath,db:r,debug:n,name:e.name,port:t,shadowDBPort:e.shadowDatabasePort},o=X({defaultRoute(m,d){O(d,"Not Found",404)},ignoreTrailingSlash:!1});s(o,a,n),i(o,a,n);let c=await l({router:o}).listen(t);return e.port=c.port,a.port=c.port,{async close(){let{Engine:m}=await import("./engine-YTEOPVUP.js");await Promise.allSettled([c.close(),m.stopAll()])},port:c.port,url:c.url}}import{isDeepStrictEqual as U}from"util";var Z="application/json",P={connection:"close","content-type":Z},T={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 F(r){return{...r,snapshot:async e=>await ee(r.url,e)}}async function j(r){let e={serverUrl:r.serverUrl,sqlitePath:r.sqlitePath,streamName:R,url:v(r.serverUrl,R)};await te(e);let t=new k({debug:r.debug,streamUrl:e.url}),n=r.bridge.subscribe(s=>{t.enqueue(s)});return{close:async()=>{n(),await t.close()},experimental:e}}async function ee(r,e){if(!r)return q();let t=await re(r);return W(t,e)}async function re(r){let e=await fetch(`${r}?offset=-1&format=json`,{headers:{connection:"close"}});if(!e.ok)throw new Error(`Failed to read ${r}: HTTP ${e.status}`);return await e.json()}var k=class{#t;#r;#e;constructor(e){this.#t=e.debug,this.#r=Promise.resolve(),this.#e=e.streamUrl}enqueue(e){e.length!==0&&(this.#r=this.#r.then(async()=>{await ae(this.#e,e),this.#t&&console.debug(`[streams] appended ${e.length} query insight record(s) to ${this.#e}`)}).catch(t=>{console.error("[streams] failed to ingest query insights into prisma-queries",t)}))}async close(){await this.#r}};async function te(r){let e=await fetch(r.url,{headers:P,method:"PUT"});if(!e.ok)throw await b(e,`Failed to create ${r.streamName}`);let t=await se(r);if(ne(t,r.streamName))return;if(t.currentVersion>0)throw new Error(`Failed to install schema for ${r.streamName}: existing schema registry is incompatible and requires a lens migration`);let n=await fetch(`${r.url}/_schema`,{body:JSON.stringify(T),headers:P,method:"POST"});if(!n.ok)throw await b(n,`Failed to install schema for ${r.streamName}`)}function ne(r,e){if(r.currentVersion<=0||r.schema!==e)return!1;let t=r.schemas[String(r.currentVersion)];return U(t,T.schema)&&U(r.search,T.search)}async function se(r){let e=await fetch(`${r.url}/_schema`,{headers:P,method:"GET"});if(!e.ok)throw await b(e,`Failed to inspect schema for ${r.streamName}`);return await e.json()}async function ae(r,e){let t=await fetch(r,{body:JSON.stringify(e),headers:P,method:"POST"});if(!t.ok)throw await b(t,"Failed to append to prisma-queries")}async function b(r,e){let t=await r.text().catch(()=>"");return new Error(`${e}: HTTP ${r.status}${t?` ${t}`:""}`)}import{randomUUID as ie}from"crypto";import{setTimeout as H}from"timers/promises";import{isDeepStrictEqual as L}from"util";import{process as oe}from"std-env";var le="application/json",S={connection:"close","content-type":le},ce={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},A={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 V(r){let{dbServer:e,debug:t,name:n,persistenceMode:s,port:i,queryInsightsBridge:l,walBridge:a}=r,o=s==="stateless",c=o?we(n):n,m=I(c),d=!o&&await _(m);oe.env.DS_LOCAL_DATA_ROOT=M(),o&&await y(m);let u=await ue({debug:t,hadExistingStreamsData:d,name:c,port:i}),h={serverUrl:u.exports.http.url,sqlitePath:u.exports.sqlite.path,streamName:N,url:v(u.exports.http.url)};try{await he(h);let p=await j({bridge:l,debug:t,serverUrl:u.exports.http.url,sqlitePath:u.exports.sqlite.path}),g=new Q({dbServer:e,debug:t,streamUrl:h.url}),Y=a.subscribe(z=>{g.enqueue(z)});return{close:async()=>{Y(),await g.close(),await p.close(),await u.close(),await H(100),o&&await y(m)},experimental:h,experimentalQueryInsights:p.experimental}}catch(p){throw await u.close().catch(()=>{}),await H(100),o&&await y(m).catch(()=>{}),p}}var me=["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 ue(r){let{debug:e,hadExistingStreamsData:t,name:n,port:s}=r,{startLocalDurableStreamsServer:i}=await import("@prisma/streams-local"),l=()=>i({hostname:"127.0.0.1",name:n,port:s});try{return await l()}catch(a){if(!t||!pe(a))throw a;return console.warn(`[streams] resetting incompatible durable streams data for "${n}"`),e&&console.debug(`[streams] original durable streams startup error for "${n}"`,a),await y(I(n)),await l()}}function pe(r){return de(r).map(t=>t.toLowerCase()).some(t=>me.some(n=>t.includes(n)))}function de(r){let e=[],t=[r],n=new Set;for(;t.length>0;){let s=t.shift();if(!(s==null||n.has(s))){if(n.add(s),typeof s=="string"){e.push(s);continue}if(s instanceof AggregateError)for(let i of s.errors)t.push(i);if(s instanceof Error){e.push(s.message);let i=s.cause;i!==void 0&&t.push(i)}}}return e}var Q=class{#t;#r;#e;#n;#s;constructor(e){this.#t=e.dbServer,this.#r=e.debug,this.#e=Promise.resolve(),this.#n=e.streamUrl,this.#s=new Set}enqueue(e){e.length!==0&&(this.#e=this.#e.then(async()=>{let t=await this.#i(e);t.length!==0&&(await Se(this.#n,t),this.#r&&console.debug(`[streams] appended ${t.length} state-protocol record(s) to ${this.#n}`))}).catch(t=>{console.error("[streams] failed to ingest WAL events into prisma-wal",t)}))}async close(){await this.#e}async#i(e){let t=[],n=new Date().toISOString();for(let s of e)t.push(...await this.#o(s,n));return t}async#o(e,t){let n=`${e.schema}.${e.table}`,s=await this.#t.getPrimaryKeyColumns(e.schema,e.table),i=K(e.record),l=K(e.oldRecord),a=this.#a(n,s,l),o=this.#a(n,s,i),c=e.txid===""?void 0:e.txid;return e.type==="insert"?i&&o?[{headers:{operation:"insert",timestamp:t,txid:c},key:o,old_value:null,type:n,value:i}]:[]:e.type==="delete"?l&&a?[{headers:{operation:"delete",timestamp:t,txid:c},key:a,old_value:l,type:n,value:null}]:[]:!i||!l||!a||!o?[]:a!==o?[{headers:{operation:"delete",timestamp:t,txid:c},key:a,old_value:l,type:n,value:null},{headers:{operation:"insert",timestamp:t,txid:c},key:o,old_value:null,type:n,value:i}]:[{headers:{operation:"update",timestamp:t,txid:c},key:o,old_value:l,type:n,value:i}]}#a(e,t,n){if(!n)return null;let s=fe(n,t);return s||(this.#s.has(e)||(this.#s.add(e),console.warn(`[streams] falling back to full-row keys for ${e} because no primary key could be resolved`)),ve(n))}};async function he(r){let e=await fetch(r.url,{headers:S,method:"PUT"});if(!e.ok)throw await f(e,`Failed to create ${r.streamName}`);let t=await fetch(`${r.url}/_profile`,{body:JSON.stringify(ce),headers:S,method:"POST"});if(!t.ok)throw await f(t,`Failed to configure ${r.streamName}`);let n=await ge(r);if(ye(n,r.streamName))return;if(n.currentVersion>0)throw new Error(`Failed to install schema for ${r.streamName}: existing schema registry is incompatible and requires a lens migration`);let s=await fetch(`${r.url}/_schema`,{body:JSON.stringify(A),headers:S,method:"POST"});if(!s.ok)throw await f(s,`Failed to install schema for ${r.streamName}`)}async function ge(r){let e=await fetch(`${r.url}/_schema`,{headers:S,method:"GET"});if(!e.ok)throw await f(e,`Failed to inspect schema for ${r.streamName}`);return await e.json()}function ye(r,e){if(r.currentVersion<=0||r.schema!==e)return!1;let t=r.schemas[String(r.currentVersion)];return L(t,A.schema)&&L(r.search,A.search)}async function Se(r,e){let t=await fetch(r,{body:JSON.stringify(e),headers:S,method:"POST"});if(!t.ok)throw await f(t,"Failed to append to prisma-wal")}async function f(r,e){let t=await r.text().catch(()=>"");return new Error(`${e}: HTTP ${r.status}${t?` ${t}`:""}`)}function fe(r,e){if(e.length===0)return null;let t=[];for(let n of e){if(!Object.prototype.hasOwnProperty.call(r,n))return null;let s=Ee(r[n]);if(s==null)return null;t.push(e.length===1?s:`${n}=${s}`)}return t.join("|")}function ve(r){return JSON.stringify(B(r))}function B(r){return Array.isArray(r)?r.map(e=>B(e)):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,B(t)])):r}function K(r){return r?structuredClone(r):null}function Ee(r){if(r===null)return"null";if(r===void 0)return"undefined";if(typeof r=="string")return r;if(typeof r=="number")return Number.isFinite(r)?String(r):null;if(typeof r=="bigint")return r.toString();if(typeof r=="boolean")return r?"true":"false";try{return JSON.stringify(r)}catch{return null}}function we(r){return`${r}.${ie().replaceAll("-","")}`}async function J(r){let e=await $.createExclusively(r),t=null,n=null,s=null,i=null;try{[t,s]=await Promise.all([x("database",e),x("shadow_database",e)]);let l,a;e.dryRun?(l=Re(),a=Ie(),i=Te()):(l=await t.attachWalEventBridge(),a=await t.attachQueryInsightsBridge(),i=await V({dbServer:t,debug:e.debug,name:e.name,port:e.streamsPort,persistenceMode:e.persistenceMode,queryInsightsBridge:a,walBridge:l})),n=await C(t,e);let o=Pe(t,s,n,e);await e.writeServerDump(o,e.dryRun?{}:{queryInsights:i.experimentalQueryInsights,streams:i.experimental});let c=xe(l),m=F(i.experimentalQueryInsights),d=t,u=s,h=n,p=i,g=async()=>{c.close(),await G(e,[h,p,d,u])};return{close:g,dbServer:t,httpServer:n,server:{...o,close:g,experimental:{queryInsights:m,streams:i.experimental,wal:c.api},name:e.name},serverState:e,shadowDbServer:s,streamsServer:i,queryInsightsBridge:a,walBridge:l}}catch(l){return await be(e,[n,i,t,s],l)}}function Pe(r,e,t,n){let s=`prisma+postgres://localhost:${t.port}/?${new URLSearchParams({api_key:D({databaseUrl:r.prismaORMConnectionString,name:n.name,shadowDatabaseUrl:e.prismaORMConnectionString})}).toString()}`;return{database:{connectionString:r.connectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand},http:{url:t.url},ppg:{url:s},shadowDatabase:{connectionString:e.prismaORMConnectionString,prismaORMConnectionString:e.prismaORMConnectionString,terminalCommand:e.terminalCommand}}}async function G(r,e){let t=[];for(let n of e)try{await n.close()}catch(s){t.push(s)}try{await r.close()}catch(n){t.push(n)}if(t.length>0)throw new AggregateError(t,"Failed to close some servers")}async function be(r,e,t){try{await G(r,e.filter(n=>n!==null))}catch(n){throw new AggregateError([t,n],"Failed to start Prisma Dev server cleanly")}throw t}function xe(r){let e=new Set;return{api:{stream:()=>{let t=()=>{},n=ke(r,()=>{e.delete(t)});return t=()=>n.close(),e.add(t),n.stream},subscribe:t=>r.subscribe(t)},close:()=>{for(let t of[...e])t();e.clear()}}}function Re(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function Ie(){return{async close(){},subscribe(){return()=>{}}}}function Te(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""},experimentalQueryInsights:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function ke(r,e){let t=[],n=!1,s=null,i=r.subscribe(a=>{if(!n){if(s){let o=s;s=null,o.resolve({done:!1,value:a});return}t.push(a)}}),l=()=>{if(!n&&(n=!0,i(),t.length=0,e(),s)){let a=s;s=null,a.resolve({done:!0,value:void 0})}};return{close:l,stream:{[Symbol.asyncIterator](){return this},next(){return t.length>0?Promise.resolve({done:!1,value:t.shift()}):n?Promise.resolve({done:!0,value:void 0}):new Promise((a,o)=>{s={reject:o,resolve:a}})},return(){return l(),Promise.resolve({done:!0,value:void 0})},throw(a){let o=s;return l(),o&&o.reject(a),Promise.reject(a instanceof Error?a:new Error(String(a)))}}}}async function Ae(r){let{server:e}=await J(r);return e}async function pr(r){return await Ae(r)}export{Ae as a,pr as b}; |
| import{e as h,f,g as M}from"./chunk-EDFHV3AK.js";import{a as A,c as m,g as V,h as C,i as L,j as x}from"./chunk-DWY47FQV.js";import{writeFile as ae}from"fs/promises";import{join as p}from"pathe";import{check as se,lock as oe,unlock as ie}from"proper-lockfile";import{process as H}from"std-env";import{integer as K,literal as ne,minLength as k,minValue as Q,number as Z,object as P,optional as l,parseJson as de,pipe as c,safeParse as ue,string as b,url as le}from"valibot";import{setTimeout as ee}from"timers/promises";import{process as D}from"std-env";function _(r,e){if(r==null)return!1;try{return D.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}async function J(r,e){if(!D.kill)return!1;try{D.kill(r,"SIGTERM")}catch(a){return e&&console.error(`Error killing process with PID ${r}:`,a),!1}let t=0;do{if(!_(r,e))return!0;await ee(100)}while(++t<50);try{return D.kill(r,"SIGKILL")}catch(a){return e&&console.error(`Error forcefully killing process with PID ${r}:`,a),!1}}import{join as j}from"pathe";var te="prisma-wal",ye="prisma-queries";function re(){return j(A.data,"durable-streams")}function Y(r){return j(re(),r)}function xe(r,e=te){return new URL(`/v1/stream/${encodeURIComponent(e)}`,r).toString()}var S=c(b(),le()),F=P({connectionString:S,prismaORMConnectionString:l(S),terminalCommand:l(b())}),G=P({url:S}),B=P({serverUrl:S,sqlitePath:c(b(),k(1)),streamName:c(b(),k(1)),url:S}),ce=P({queryInsights:l(B),streams:l(B)}),I=c(Z(),K(),Q(1)),me=P({database:F,http:G,ppg:G,shadowDatabase:F}),he=P({databasePort:I,experimental:l(ce),exports:l(me),name:c(b(),k(1)),pid:l(c(Z(),K(),Q(0))),port:I,shadowDatabasePort:I,version:ne("1")}),O=Symbol("initialize"),E="default",pe=new Set(["durable-streams"]),d=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;_streamsPort;constructor(e){this._databasePort=e.databasePort??f,this.databaseConnectTimeoutMillis=e.databaseConnectTimeoutMillis??6e4,this.databaseIdleTimeoutMillis=e.databaseIdleTimeoutMillis??1/0,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??E,this.persistenceMode=e.persistenceMode,this.pid=e.pid??H.pid,this.shadowDatabaseConnectTimeoutMillis=e.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=e.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=e.port??f,this._shadowDatabasePort=e.shadowDatabasePort??f,this._streamsPort=e.streamsPort??f}static async createExclusively(e){let t=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new g(e):new R(e);return await t[O](),t}static async fromServerDump(e){let{debug:t,name:a=E}=e??{},o=m(a),i=g.getServerDumpPath(o),s=await V(i);if(s==null)return t&&console.debug(`[State] No server dump file found at: ${i}`),null;t&&(console.debug(`[State] server dump file found at "${i}":`),console.debug(s));let{issues:n,output:u,success:v}=ue(c(b(),de(),he),s);if(!v)throw t&&console.debug(`[State] Invalid server dump file at "${i}": | ||
| ${JSON.stringify(n,null,2)}`),new Error(`Invalid Prisma Dev state for "${a}".`);return new g({databasePort:u.databasePort,debug:t,dryRun:!1,name:a,pid:u.pid,port:u.port,serverDump:u,shadowDatabasePort:u.shadowDatabasePort})}static async scan(e){let{debug:t,globs:a}=e??{},o=p(m(E),"..");t&&console.debug(`[State] scanning for server states in: ${o}`);let i=(await L(o,a)).filter(s=>!pe.has(s));return t&&console.debug(`[State] found server names: ${JSON.stringify(i)}`),await Promise.all(i.map(s=>z(s,e)))}get databasePort(){return this._databasePort}set databasePort(e){this.#t("databasePort",e)}get port(){return this._port}set port(e){this.#t("port",e)}get shadowDatabasePort(){return this._shadowDatabasePort}get streamsPort(){return this._streamsPort}set shadowDatabasePort(e){this.#t("shadowDatabasePort",e)}#t(e,t){if(t<0||!Number.isInteger(t))throw new Error(`Invalid port number: ${t}`);let a=`_${e}`;if(this[a]!==h&&this[a]!==t)throw new Error(`\`${e}\` is already set to ${this[a]}, cannot change it to ${t}`);this[a]=t}},R=class extends d{constructor(e){super({...e,databasePort:e?.databasePort||h,persistenceMode:"stateless",port:e?.port||h,shadowDatabasePort:e?.shadowDatabasePort||h,streamsPort:e?.streamsPort||h})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[O](){let e;try{e=await d.scan({debug:this.debug,onlyMetadata:!0})}catch(a){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",a),e=[]}let t=await M({debug:this.debug,name:this.dryRun?this.name:"",requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:e});this._databasePort=t.databasePort,this._port=t.port,this._shadowDatabasePort=t.shadowDatabasePort,this._streamsPort=t.streamsPort}async close(){}async writeServerDump(){}},g=class r extends d{#t;#e;#a;#o;#i;#s;#r;constructor(e){super({...e,persistenceMode:"stateful"}),this.#s=!1,this.#e=m(this.name),this.#t=p(this.#e,"db_dump.bak"),this.#a=p(this.#e,".lock"),this.#o=p(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#i=r.getServerDumpPath(this.#e)}static getServerDumpPath(e){return p(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get experimental(){return this.#r?.experimental}get pgliteDataDirPath(){return this.#o}async[O](){await C(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await oe(this.#e,{lockfilePath:this.#a}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await d.scan({debug:this.debug,onlyMetadata:!0}),t=await M({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:e});this._databasePort=t.databasePort,this._port=t.port,this._shadowDatabasePort=t.shadowDatabasePort,this._streamsPort=t.streamsPort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new $(this):e}}async close(){if(!this.#s)try{await ie(this.#e,{lockfilePath:this.#a}),this.#s=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,e),e}}async writeServerDump(e,t){this.#r={name:this.name,version:"1",pid:H.pid,port:this.port,databasePort:this.databasePort,experimental:t,shadowDatabasePort:this.shadowDatabasePort,exports:e},await ae(this.#i,`${JSON.stringify(this.#r,null,2)} | ||
| `,{encoding:"utf-8"})}};async function Ve(r,e){await Pe(r,e);let t=typeof r=="string"?r:r.name,a=m(t);await x(a),await x(Y(t))}async function z(r,e){let{debug:t,onlyMetadata:a}=e||{},o=typeof r=="string"?r:r.name,i=typeof r!="string"?r:void 0,s={databasePort:i?.databasePort??-1,experimental:i?.experimental,exports:i?.exports,name:o,pid:i?.pid,port:i?.port??-1,shadowDatabasePort:i?.shadowDatabasePort??-1,version:"1"};try{let n=i||await d.fromServerDump({debug:t,name:o});if(!n)return t&&console.debug(`[State] no server state found for name: ${o}`),{...s,status:"no_such_server"};s.databasePort=n.databasePort,s.experimental=n.experimental,s.exports=n.exports,s.pid=n.pid,s.port=n.port,s.shadowDatabasePort=n.shadowDatabasePort;let{exports:u,pid:v}=n;if(a)return{...s,status:"unknown"};if(!_(v,t))return t&&console.debug(`[State] server state for "${o}" has no running process with PID: ${v}`),{...s,status:"not_running"};let N=m(o);try{if(!await se(N,{lockfilePath:p(N,".lock")}))return t&&console.debug(`[State] server state for "${o}" is not locked, indicating it is not running.`),{...s,status:"not_running"}}catch(X){t&&console.error(`[State] server state for "${o}" failed to check lock:`,X)}if(!u)return{...s,status:"starting_up"};let{http:W}=u,w=await fetch(`${W.url}/health`,{headers:{connection:"close"}});if(!w.ok)return t&&console.debug(`[State] server state for "${o}" is not live: ${JSON.stringify(w)}`),{...s,status:"not_running"};let y=await w.json();return y.name!==r?(t&&console.debug(`[State] server state for "${o}" has mismatched health response: ${JSON.stringify(y)}`),{...s,status:"unknown"}):(t&&console.debug(`[State] server state for "${r}" is live: ${JSON.stringify(y)}`),{...s,status:"running"})}catch(n){return t&&console.error(`[State] failed to get server status for "${o}":`,n),{...s,status:"error"}}}function be(r){let{status:e}=r;return e==="running"||e==="starting_up"}async function Pe(r,e){let{pid:t,...a}=typeof r=="string"?await z(r,{debug:e}):r;if(!be(a))return!1;let o=await d.fromServerDump({debug:e,name:a.name});if(t==null){e&&console.debug(`[State] No PID found for server "${a.name}" to kill.`);try{await o?.close()}catch{}return!1}let i=await J(t,e);try{await o?.close()}catch{}return i}var T=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},$=class extends T{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return d.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};export{te as a,ye as b,re as c,Y as d,xe as e,d as f,Ve as g,z as h,be as i,Pe as j,T as k,$ as l}; |
| import{existsSync as u,readFileSync as D}from"fs";import{copyFile as b,mkdir as B,readFile as d}from"fs/promises";import{createRequire as z}from"module";import{dirname as E}from"path";import{fileURLToPath as r,pathToFileURL as A}from"url";var v=z(import.meta.url),T=["initdb.wasm","pglite.data","pglite.wasm"],p="pglite-seed.tar.gz",w={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"},U=[...T.map(e=>({fileName:e,kind:"core",name:e})),{fileName:p,kind:"core",name:p},...Object.entries(w).map(([e,t])=>({fileName:t,kind:"extension",name:e}))],f=new Map,P=Symbol.for("@prisma/dev/bundled-pglite-runtime-asset-sources"),c=null;async function Z(e){let t=a(e),n=r(t);await B(n,{recursive:!0});let s=[];for(let i of x()){let g=new URL(i.fileName,t),m=r(g);await b(i.sourcePath,m),s.push({...i,destinationPath:m})}return s}function x(){let e=L(),t=a(new URL("./runtime-assets/",import.meta.url));return U.map(n=>({...n,sourcePath:r(l(n.fileName,e,t))}))}async function H(){await W();let e=h();if(e)return await M(e),await G(e);let t=N(),n=t.href,s=f.get(n);return s||(s=I(t),f.set(n,s)),await s}function Q(e){let t=globalThis;t[P]={extensions:Object.fromEntries(Object.entries(e.extensions).map(([n,s])=>[n,o(s)])),fsBundle:o(e.fsBundle),initdbWasm:o(e.initdbWasm),loadDataDir:o(e.loadDataDir),wasmModule:o(e.wasmModule)}}function o(e,t=import.meta.url){return e instanceof URL?e:/^(?:https?:|data:|file:)/.test(e)?new URL(e):e.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(e)?A(e):new URL(e,t)}async function G(e){let t=`bundled:${e.wasmModule.href}:${e.fsBundle.href}`,n=f.get(t);return n||(n=k(e),f.set(t,n)),await n}async function I(e){let t=a(new URL("./runtime-assets/",import.meta.url)),[n,s,i]=await Promise.all([d(l("pglite.data",e,t)),d(l(p,e,t)),d(l("pglite.wasm",e,t))]),g=_();return{extensions:Object.fromEntries(Object.entries(w).map(([m,S])=>[m,l(S,e,t)])),fsBundle:new Blob([Uint8Array.from(n)]),loadDataDir:new Blob([Uint8Array.from(s)]),wasmModule:await g.compile(i)}}async function k(e){let[t,n,s]=await Promise.all([R(e.fsBundle),R(e.loadDataDir),R(e.wasmModule)]),i=_();return{extensions:e.extensions,fsBundle:new Blob([Uint8Array.from(t)]),loadDataDir:new Blob([Uint8Array.from(n)]),wasmModule:await i.compile(s)}}async function M(e){if(e.initdbWasm.protocol!=="file:")return;let t=new URL("initdb.wasm",a(new URL("./",e.initdbWasm))),n=r(t);u(n)||await b(r(e.initdbWasm),n)}function a(e){return e instanceof URL?y(e):y(A(e))}function y(e){return e.href.endsWith("/")?e:new URL(`${e.href}/`)}function L(){let e=v.resolve("@electric-sql/pglite");return a(E(e))}function N(){let e=a(new URL("./",import.meta.url));if(O(e))return e;if(C())return L();throw new Error("Unable to locate PGlite runtime assets. If you bundled @prisma/dev, copy them next to the bundle with copyPrismaDevRuntimeAssets().")}function O(e){return U.every(t=>u(r(new URL(t.fileName,e))))}function h(){return globalThis[P]??null}async function W(){!F()||h()||(c||(c=import("./runtime-assets-manifest.bun.js").then(()=>{}).catch(e=>{throw c=null,e})),await c)}function C(){let e=r(new URL("../package.json",import.meta.url));if(!u(e))return!1;try{return JSON.parse(D(e,"utf8")).name==="@prisma/dev"}catch{return!1}}function F(){return typeof globalThis.Bun<"u"}function _(){let e=globalThis.WebAssembly;if(!e)throw new Error("WebAssembly is not available in this runtime.");return e}async function R(e){if(e.protocol==="file:")return await d(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 l(e,t,n){let s=new URL(e,t);if(u(r(s)))return s;if(n){let i=new URL(e,n);if(u(r(i)))return i}return s}export{Z as a,x as b,H as c,Q as d,o as e}; |
| import{c as I}from"./chunk-KWCQYPJI.js";import{h as T}from"./chunk-EDFHV3AK.js";import{d as L,f as O}from"./chunk-DWY47FQV.js";import{createConnection as ke,createServer as qe}from"net";import{join as Fe}from"path";import{filename as Ue}from"pathe/utils";import{performance as W}from"perf_hooks";import{protocol as we}from"@electric-sql/pglite";import{Buffer as de}from"buffer";var C=500,Q=/(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+)/,me=new RegExp(`(?:${Q.source}\\.)*${Q.source}`),pe=new RegExp(`(?:FROM|JOIN|UPDATE|INTO|TABLE)\\s+(${me.source})`,"gi"),ge=/"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|(\w+)/g,$=/prismaQuery='([^']+)'/,fe=new Set([S(` | ||
| select b.oid, b.typarray | ||
| from pg_catalog.pg_type a | ||
| left join pg_catalog.pg_type b on b.oid = a.typelem | ||
| where a.typcategory = $1 | ||
| group by b.oid, b.typarray | ||
| order by b.oid | ||
| `),S('GRANT "pg_write_all_data" TO "prisma_application"'),S("SELECT SUM(reads)::BIGINT AS reads, SUM(writes)::BIGINT AS writes, SUM(COALESCE(extends, $1))::BIGINT AS extends FROM pg_stat_io"),S("SELECT pg_database_size(current_database())::BIGINT, SUM(pg_total_relation_size(relid))::BIGINT AS pg_total_relation_size FROM pg_stat_user_tables"),S("SELECT COUNT(*) AS cnt FROM pg_stat_activity WHERE pid <> pg_backend_pid() and xact_start notnull")]),ye=[/^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 Ze(){return{generatedAt:Date.now(),queries:[]}}function S(e){return e.replace(/\s+/g," ").trim()}function G(e){return U(S(e))}function k(e){if(!e?.action||!e.model&&/raw/i.test(e.action))return null;let t=e.payload?U(JSON.stringify(e.payload)):"0";return`${e.model??""}.${e.action}:${t}`}function Ee(e){let t=new Set;for(let r of e.matchAll(pe)){let n=r[1];if(!n)continue;let a;for(let s of n.matchAll(ge))a=s[1]??s[2]??s[3]??s[4];a&&!a.startsWith("pg_")&&t.add(a)}return Array.from(t)}function Se(e){return fe.has(e)?!0:ye.some(t=>t.test(e))}function q(e){if(Se(S(e)))return null;let t=Ee(e);return t.length===0&&/\bpg_\w+/i.test(e)?null:t}function N(e){if(Array.isArray(e))return e.map(N);if(e!==null&&typeof e=="object"){let t=e;return t.$type==="Param"?"<<redacted>>":Object.fromEntries(Object.entries(t).map(([r,n])=>[r,N(n)]))}return e}function F(e){let t=e.match($);if(!t?.[1])return{cleanedSql:S(e),prismaQueryInfo:null};let r=e.replace($,"");r=r.replace(/,\s*,/g,",").replace(/\/\*\s*,/g,"/*").replace(/,\s*\*\//g,"*/").replace(/\/\*\s*\*\//g,"").replace(/\s+/g," ").trim();let n=decodeURIComponent(t[1]),a=n.indexOf(":");if(a===-1)return{cleanedSql:r,prismaQueryInfo:{action:n,isRaw:!0}};let s=n.slice(0,a),d=n.slice(a+1),o=s.indexOf("."),u=o===-1?void 0:s.slice(0,o),c=o===-1?s:s.slice(o+1);if(!c)return{cleanedSql:r,prismaQueryInfo:null};let l;try{l=N(JSON.parse(de.from(d,"base64url").toString("utf8")))}catch{l=void 0}return{cleanedSql:r,prismaQueryInfo:{action:c,isRaw:!1,model:u,payload:l}}}function et(e,t={}){let r=new Set(t.excludeApplications??[]),n=be(t.limit),a=typeof t.since=="number"&&Number.isFinite(t.since)?t.since:null,s=new Map;for(let o of e){if(o.applicationName&&r.has(o.applicationName))continue;let u=Date.parse(o.timestamp);if(!Number.isFinite(u))continue;let c=`${o.queryId}:${o.groupKey??""}`,l=s.get(c);if(!l){s.set(c,{count:1,duration:o.durationMs,groupKey:o.groupKey,id:c,lastSeen:u,maxDurationMs:o.durationMs,minDurationMs:o.durationMs,prismaQueryInfo:o.prismaQueryInfo,query:o.query,queryId:o.queryId,reads:o.reads,rowsReturned:o.rowsReturned,tables:o.tables,totalDurationMs:o.durationMs});continue}l.count+=1,l.lastSeen=Math.max(l.lastSeen,u),l.maxDurationMs=Math.max(l.maxDurationMs??o.durationMs,o.durationMs),l.minDurationMs=Math.min(l.minDurationMs??o.durationMs,o.durationMs),l.reads+=o.reads,l.rowsReturned+=o.rowsReturned,l.totalDurationMs+=o.durationMs,l.duration=l.totalDurationMs/l.count,!l.prismaQueryInfo&&o.prismaQueryInfo&&(l.prismaQueryInfo=o.prismaQueryInfo),l.tables.length===0&&o.tables.length>0&&(l.tables=o.tables)}let d=Array.from(s.values()).filter(o=>a===null||o.lastSeen>=a).sort((o,u)=>u.lastSeen-o.lastSeen).slice(0,n).map(({totalDurationMs:o,...u})=>u);return{generatedAt:Date.now(),queries:d}}function be(e){return typeof e=="number"&&Number.isInteger(e)&&Number.isSafeInteger(e)&&e>0?Math.min(e,C):C}function U(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 P=new WeakMap;function H(e){let t=P.get(e);if(t&&!t.closed)return t.bridge;let r=Pe(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,P.delete(e)),Promise.resolve()),subscribe:a=>(n.subscribers.add(a),()=>{n.subscribers.delete(a)})},closed:!1,originalClearQueueForHandler:r.clearQueueForHandler.bind(r),originalEnqueue:r.enqueue.bind(r),queryQueue:r,sessions:new Map,subscribers:new Set};return r.clearQueueForHandler=a=>{n.sessions.delete(a),n.originalClearQueueForHandler(a)},r.enqueue=async(a,s,d)=>{let o=he(n,a),u=Ne(s);Te(o,u);let c=Ie(o,u);if(!c)return await n.originalEnqueue(a,s,d);let l={commandTags:[],dataRowCount:0},f=new we.Parser,i=W.now(),m=await n.originalEnqueue(a,s,b=>{f.parse(b,ce=>{Me(l,ce)}),d(b)}),g=Math.max(0,W.now()-i);return Be(n,{applicationName:c.applicationName,durationMs:g,query:c.query,responseStats:l}),m},P.set(e,n),n.bridge}async function K(e){await P.get(e)?.bridge.close()}function Pe(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 he(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 Te(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 Ie(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 Ne(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 a=t.readInt32BE(4);if(a===196608||a===196608)return Re(t)}if(t.length<5)return null;switch(String.fromCharCode(t[0]??0)){case"Q":return _e(t);case"P":return xe(t);case"B":return Ae(t);case"E":return De(t);case"C":return ve(t);default:return null}}function Re(e){let t=8,r=null;for(;t<e.length-1;){let n=E(e,t);if(!n||n.value==="")break;t=n.nextOffset;let a=E(e,t);if(!a)break;t=a.nextOffset,n.value==="application_name"&&(r=a.value)}return{applicationName:r,kind:"startup"}}function _e(e){let t=E(e,5);return t?{kind:"query",query:t.value}:null}function xe(e){let t=E(e,5);if(!t)return null;let r=E(e,t.nextOffset);return r?{kind:"parse",query:r.value,statementName:t.value}:null}function Ae(e){let t=E(e,5);if(!t)return null;let r=E(e,t.nextOffset);return r?{kind:"bind",portalName:t.value,statementName:r.value}:null}function De(e){let t=E(e,5);return t?{kind:"execute",portalName:t.value}:null}function ve(e){if(e.length<7)return null;let t=e[5];if(t===void 0)return null;let r=E(e,6);return r?{kind:"close",name:r.value,target:t===80?"portal":"statement"}:null}function E(e,t){let r=e.indexOf(0,t);return r===-1?null:{nextOffset:r+1,value:e.toString("utf8",t,r)}}function Me(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 Be(e,t){let r=F(t.query),n=q(r.cleanedSql);if(!n)return;let a=G(r.cleanedSql),s={applicationName:t.applicationName,durationMs:t.durationMs,groupKey:k(r.prismaQueryInfo),prismaQueryInfo:r.prismaQueryInfo,query:r.cleanedSql,queryId:a,reads:0,rowsReturned:Le(t.responseStats),tables:n,timestamp:new Date().toISOString()};for(let d of e.subscribers)d([s])}function Le(e){let t=e.commandTags.reduce((r,n)=>r+Oe(n),0);return Math.max(t,e.dataRowCount)}function Oe(e){let t=e.trim().split(/\s+/).at(-1);return!t||!/^\d+$/.test(t)?0:Number(t)}import{protocol as J}from"@electric-sql/pglite";var y="_prisma_dev_wal",A="events",X="install_all_triggers",Y="capture_event",z="prisma_dev_wal_capture",w=new WeakMap,Ce=new Set(["ALTER","COMMIT","COPY","CREATE","DELETE","DROP","INSERT","MERGE","TRUNCATE","UPDATE"]);async function D(e,t){let r=w.get(e);if(r&&!r.closed)return r.bridge;let n=e.execProtocolRaw.bind(e),a=e.execProtocolRawStream.bind(e),s={bridge:{close:async()=>{s.closed||(s.closed=!0,s.subscribers.clear(),e.execProtocolRaw===d&&(e.execProtocolRaw=n),e.execProtocolRawStream===o&&(e.execProtocolRawStream=a),await s.pollPromise,w.delete(e))},poll:async()=>{await x(s,e)},subscribe:u=>(s.subscribers.add(u),()=>{s.subscribers.delete(u)})},closed:!1,ensureInfrastructurePromise:null,pendingPoll:!1,pollPromise:null,subscribers:new Set,suppressDepth:0},d=async(u,c)=>{let l=await n(u,c);return!s.closed&&s.suppressDepth===0&&V(l)&&x(s,e),l},o=async(u,c)=>{let l=[],f=new J.Parser,i=c?.onRawData;await a(u,{...c,onRawData:m=>{f.parse(m,g=>{l.push(g)}),i?.(m)}}),!s.closed&&s.suppressDepth===0&&v(l)&&x(s,e)};return e.execProtocolRaw=d,e.execProtocolRawStream=o,w.set(e,s),await Z(s,e),s.bridge}async function j(e){let t=w.get(e);t&&await t.bridge.close()}function v(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&&Ce.has(r))return!0}return!1}function V(e){if(e.length===0)return!1;let t=[];return new J.Parser().parse(e,n=>{t.push(n)}),v(t)}async function Z(e,t){e.ensureInfrastructurePromise??=M(e,t,async()=>{await t.exec(`CREATE SCHEMA IF NOT EXISTS "${y}"`),await t.exec(` | ||
| CREATE TABLE IF NOT EXISTS "${y}"."${A}" ( | ||
| id BIGSERIAL PRIMARY KEY, | ||
| txid BIGINT NOT NULL DEFAULT txid_current(), | ||
| schema_name TEXT NOT NULL, | ||
| table_name TEXT NOT NULL, | ||
| op TEXT NOT NULL, | ||
| row_data JSONB, | ||
| old_row_data JSONB, | ||
| created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() | ||
| ) | ||
| `),await t.exec(` | ||
| CREATE OR REPLACE FUNCTION "${y}"."${Y}"() | ||
| RETURNS trigger | ||
| LANGUAGE plpgsql | ||
| AS $$ | ||
| BEGIN | ||
| IF TG_TABLE_SCHEMA = '${y}' THEN | ||
| RETURN COALESCE(NEW, OLD); | ||
| END IF; | ||
| INSERT INTO "${y}"."${A}" ( | ||
| txid, | ||
| schema_name, | ||
| table_name, | ||
| op, | ||
| row_data, | ||
| old_row_data | ||
| ) | ||
| VALUES ( | ||
| txid_current(), | ||
| TG_TABLE_SCHEMA, | ||
| TG_TABLE_NAME, | ||
| lower(TG_OP), | ||
| CASE WHEN TG_OP IN ('INSERT', 'UPDATE') THEN to_jsonb(NEW) ELSE NULL END, | ||
| CASE WHEN TG_OP IN ('UPDATE', 'DELETE') THEN to_jsonb(OLD) ELSE NULL END | ||
| ); | ||
| RETURN COALESCE(NEW, OLD); | ||
| END; | ||
| $$; | ||
| `),await t.exec(` | ||
| CREATE OR REPLACE FUNCTION "${y}"."${X}"() | ||
| RETURNS void | ||
| LANGUAGE plpgsql | ||
| AS $$ | ||
| DECLARE | ||
| target REGCLASS; | ||
| BEGIN | ||
| FOR target IN | ||
| SELECT c.oid::regclass | ||
| FROM pg_class AS c | ||
| JOIN pg_namespace AS n ON n.oid = c.relnamespace | ||
| WHERE c.relkind IN ('r', 'p') | ||
| AND n.nspname NOT IN ('${y}', 'information_schema', 'pg_catalog') | ||
| AND n.nspname NOT LIKE 'pg_temp_%' | ||
| AND n.nspname NOT LIKE 'pg_toast%' | ||
| LOOP | ||
| IF EXISTS ( | ||
| SELECT 1 | ||
| FROM pg_trigger | ||
| WHERE tgrelid = target | ||
| AND tgname = '${z}' | ||
| ) THEN | ||
| CONTINUE; | ||
| END IF; | ||
| EXECUTE format( | ||
| 'CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION "${y}"."${Y}"()', | ||
| '${z}', | ||
| target::text | ||
| ); | ||
| END LOOP; | ||
| END; | ||
| $$; | ||
| `),await ee(e,t)}),await e.ensureInfrastructurePromise}async function ee(e,t){await M(e,t,async()=>{await t.query(`SELECT "${y}"."${X}"()`)})}async function Qe(e,t){await Z(e,t),await ee(e,t);let r=await M(e,t,async()=>await t.query(` | ||
| WITH drained AS ( | ||
| DELETE FROM "${y}"."${A}" | ||
| RETURNING txid, schema_name, table_name, op, row_data, old_row_data, id | ||
| ) | ||
| SELECT txid, schema_name, table_name, op, row_data, old_row_data | ||
| FROM drained | ||
| ORDER BY id | ||
| `));if(r.rows.length===0||e.subscribers.size===0)return;let n=r.rows.map($e);for(let a of e.subscribers)queueMicrotask(()=>{if(!e.closed&&e.subscribers.has(a))try{a(n)}catch(s){console.error("[WAL bridge] subscriber failed",s)}})}async function x(e,t){if(!e.closed){if(e.pollPromise){e.pendingPoll=!0,await e.pollPromise;return}e.pollPromise=(async()=>{do e.pendingPoll=!1,await Qe(e,t);while(e.pendingPoll&&!e.closed)})().finally(()=>{e.pollPromise=null}),await e.pollPromise}}async function M(e,t,r){e.suppressDepth+=1;try{return await r()}finally{e.suppressDepth-=1,e.suppressDepth===0&&!e.closed&&w.get(t)!==e&&(e.closed=!0)}}function $e(e){return{oldRecord:e.old_row_data,record:e.row_data,schema:e.schema_name,table:e.table_name,txid:String(e.txid),type:Ge(e.op)}}function Ge(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 We=10,re="127.0.0.1",ne=128*1024*1024,ae=["-c","shared_buffers=16MB","-c","temp_buffers=1MB","-c","work_mem=1MB","-c","maintenance_work_mem=16MB","-c","wal_buffers=1MB"],p={connectionLimit:We,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},He=`postgres://${p.username}:${p.password}@localhost`,B=new URLSearchParams({sslmode:p.sslMode}),oe=new URLSearchParams({...Object.fromEntries(B.entries()),connection_limit:String(p.connectionLimit),connect_timeout:String(p.connectTimeout),max_idle_connection_lifetime:String(p.maxIdleConnectionLifetime),pool_timeout:String(p.poolTimeout),socket_timeout:String(p.socketTimeout)});async function se(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 ${p.username} WITH LOGIN SUPERUSER PASSWORD '${p.password}'`):await e.exec(`CREATE ROLE ${p.username} WITH LOGIN SUPERUSER PASSWORD '${p.password}'`),await e.exec(`SET ROLE ${p.username}`)}async function bt(e,t){if(e==="shadow_database"&&!t.dryRun)return await Ke(t);let r=e==="database"?t.databasePort:t.shadowDatabasePort;return t.dryRun?le(e,t,{db:null,port:r,server:null}):await ie(e,t,{port:r,updateServerStatePort:!0})}async function Ke(e,t=async()=>await ie("shadow_database",e,{port:0,updateServerStatePort:!1})){let{debug:r}=e,n=null,a=null,s=!1,d=new Set,o=qe(c),u=await Ye(o,e.shadowDatabasePort);return e.shadowDatabasePort=u,r&&console.debug(`[shadow_database] lazy proxy listening on port ${u}`),{...p,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()=>{s=!0;for(let m of d)m.destroy();d.clear();let i=[];try{await ze(o),r&&console.debug(`[shadow_database] lazy proxy stopped on port ${u}`)}catch(m){console.error("[shadow_database] lazy proxy stop error",m),i.push(m)}try{await a?.catch(()=>null),await n?.close()}catch(m){console.error("[shadow_database] backend close error",m),i.push(m)}if(i.length>0)throw new AggregateError(i,"Failed to close shadow_database properly")},connectionString:h(u,B),dump:async()=>{},getPrimaryKeyColumns:()=>Promise.reject(new Error("Primary key resolution is only available for the primary database server")),port:u,prismaORMConnectionString:h(u,oe),terminalCommand:`PGPASSWORD=${p.password} PGSSLMODE=${p.sslMode} psql -h localhost -p ${u} -U ${p.username} -d ${p.database}`};function c(i){d.add(i);let m=()=>{d.delete(i)};i.once("close",m),i.once("error",m),i.pause(),l(i)}async function l(i){try{let m=await f();if(s){i.destroy();return}let g=ke({host:re,port:m.port});d.add(g);let b=()=>{d.delete(g)};g.once("close",b),g.once("error",b),i.once("close",()=>g.destroy()),i.once("error",()=>g.destroy()),g.once("error",()=>i.destroy()),g.once("connect",()=>{r&&console.debug(`[shadow_database] proxying connection to lazy backend on port ${m.port}`),i.resume(),i.pipe(g),g.pipe(i)})}catch(m){r&&console.error("[shadow_database] failed to start lazy backend",m),i.destroy(m instanceof Error?m:void 0)}}async function f(){if(n)return n;if(s)throw new Error("shadow_database is closed");return a||(r&&console.debug("[shadow_database] starting lazy backend..."),a=t().then(i=>(n=i,r&&console.debug(`[shadow_database] lazy backend started on port ${i.port}`),i)).catch(i=>{throw a=null,i})),await a}}async function ie(e,t,r){let{debug:n}=t,{port:a,updateServerStatePort:s}=r,o=await(e==="shadow_database"?Je:ue)(t.pgliteDataDirPath,n);n&&o.onNotification((i,m)=>{console.debug(`[${e}][${i}] ${m}`)});let{PGLiteSocketServer:u}=await import("@electric-sql/pglite-socket"),c=e==="shadow_database"?t.shadowDatabaseIdleTimeoutMillis:t.databaseIdleTimeoutMillis,l=new u({db:o,debug:n,idleTimeout:Number.isFinite(c)?c:0,inspect:n,maxConnections:p.connectionLimit,port:a});n&&(l.addEventListener("listening",i=>{let{detail:m}=i;console.debug(`[${e}] server listening on ${JSON.stringify(m)}`)}),l.addEventListener("connection",i=>{let{clientAddress:m,clientPort:g}=i.detail;console.debug(`[${e}] client connected from ${m}:${g}`)}),l.addEventListener("error",i=>{let{detail:m}=i;console.error(`[${e}] server error:`,m)}));try{await l.start()}catch(i){throw i instanceof Error&&"code"in i&&i.code==="EADDRINUSE"?new T(a):i}let f=Number(l.getServerConn().split(":").at(1));return s&&(t[e==="database"?"databasePort":"shadowDatabasePort"]=f),le(e,t,{db:o,port:f,server:l})}function le(e,t,r){let{debug:n}=t,{db:a,port:s,server:d}=r||{},o=new Map;return n&&console.debug(`[${e}] server started on port ${s}`),{...p,attachWalEventBridge:async()=>{if(e!=="database"||!a)throw new Error("WAL bridge is only available for the primary database server");return await D(a)},attachQueryInsightsBridge:()=>{if(e!=="database"||!d)throw new Error("Query insights are only available for the primary database server");return Promise.resolve(H(d))},close:async()=>{let u=[];try{await d?.stop(),n&&console.debug(`[${e}] server stopped on port ${s}`)}catch(c){console.error(`[${e}] server stop error`,c),u.push(c)}if(e==="database"){try{d&&await K(d),n&&console.debug(`[${e}] closed query insights bridge`)}catch(c){console.error(`[${e}] query insights bridge close error`,c),u.push(c)}try{a&&await j(a),n&&console.debug(`[${e}] closed WAL bridge`)}catch(c){console.error(`[${e}] WAL bridge close error`,c),u.push(c)}try{await a?.syncToFs(),n&&console.debug(`[${e}] synced to filesystem`)}catch(c){console.error(`[${e}] sync error`,c),u.push(c)}}try{await a?.close(),n&&console.debug(`[${e}] closed`)}catch(c){console.error(`[${e}] close error`,c),u.push(c)}if(u.length>0)throw new AggregateError(u,`Failed to close ${e} properly`)},connectionString:h(s,B),dump:async u=>{e==="shadow_database"||!a||await je({db:a,debug:n,destinationPath:u})},getPrimaryKeyColumns:async(u,c)=>{if(e==="shadow_database"||!a)throw new Error("Primary key resolution is only available for the primary database server");let l=`${u}.${c}`,f=o.get(l);return f||(f=Xe(a,u,c).catch(i=>{throw o.delete(l),i}),o.set(l,f)),await f},port:s,prismaORMConnectionString:h(s,oe),terminalCommand:`PGPASSWORD=${p.password} PGSSLMODE=${p.sslMode} psql -h localhost -p ${s} -U ${p.username} -d ${p.database}`}}function h(e,t){return`${He}:${e}/${p.database}?${t.toString()}`}async function ue(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await I(),a=e==="memory://"||!await L(Fe(e,"PG_VERSION")),s=await r.create({database:p.database,dataDir:e,debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:ne,loadDataDir:a?n.loadDataDir:void 0,relaxedDurability:!1,startParams:[...r.defaultStartParams,...ae],wasmModule:n.wasmModule});return await se(s),s}async function Ye(e,t){return await new Promise((r,n)=>{let a=o=>{if(d(),o.code==="EADDRINUSE"){n(new T(t));return}n(o)},s=()=>{let o=e.address();if(d(),!o||typeof o=="string"){n(new Error("Failed to determine TCP server port"));return}r(o.port)},d=()=>{e.off("error",a),e.off("listening",s)};e.once("error",a),e.once("listening",s),e.listen(t,re)})}async function ze(e){await new Promise((t,r)=>{e.close(n=>{let a=n;if(a&&a.code!=="ERR_SERVER_NOT_RUNNING"){r(a);return}t()})})}async function Je(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await I(),a=await r.create({database:p.database,dataDir:"memory://",debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:ne,loadDataDir:n.loadDataDir,relaxedDurability:!1,startParams:[...r.defaultStartParams,...ae],wasmModule:n.wasmModule});return await se(a),a}async function Xe(e,t,r){let{rows:n}=await e.query(` | ||
| SELECT attribute.attname AS column_name | ||
| FROM pg_constraint pk_constraint | ||
| INNER JOIN pg_class relation | ||
| ON relation.oid = pk_constraint.conrelid | ||
| INNER JOIN pg_namespace namespace | ||
| ON namespace.oid = relation.relnamespace | ||
| INNER JOIN unnest(pk_constraint.conkey) WITH ORDINALITY AS keys(attnum, ordinality) | ||
| ON TRUE | ||
| INNER JOIN pg_attribute attribute | ||
| ON attribute.attrelid = relation.oid | ||
| AND attribute.attnum = keys.attnum | ||
| WHERE pk_constraint.contype = 'p' | ||
| AND namespace.nspname = ${te(t)} | ||
| AND relation.relname = ${te(r)} | ||
| ORDER BY keys.ordinality | ||
| `);return n.map(a=>a.column_name)}function te(e){return`'${e.replaceAll("'","''")}'`}async function je(e){let{dataDir:t,db:r,debug:n,destinationPath:a}=e,s=r||await ue(t,n),{pgDump:d}=await import("@electric-sql/pglite-tools/pg_dump"),o=await d({args:["--schema-only","--no-owner"],fileName:a?Ue(a):void 0,pg:await s.clone()});return a?(n&&console.debug(`[DB] Dumping database to ${a}`),await O(o,a)):(n&&console.debug("[DB] Dumping database to memory"),await o.text())}export{Ze as a,et as b,D as c,v as d,V as e,bt as f,Ke as g,je as h}; |
| import{a as c}from"./chunk-ANHBRJRZ.js";import{h as d}from"./chunk-EDFHV3AK.js";import{c as l,d as f}from"./chunk-DOJAPHLY.js";import{createServer as m}from"http";import{promisify as u}from"util";function A(r,e){return async function(o,n,i){let t=e?Date.now():0;e&&n.once("finish",()=>{let a=Date.now()-t;console.log("[Accelerate]",`<-- ${o.method??"?"} ${o.url??""} ${n.statusCode} ${a}ms`)});try{await r(o,n,i)}catch(a){try{y(a,n,o,e)}catch(p){e&&console.error("[Accelerate]","error while handling handler error",p),n.destroyed||n.destroy()}}}}function y(r,e,s,o){if(e.destroyed||e.headersSent||e.writableEnded){o&&console.error("[Accelerate]",`error after response was no longer writable for ${s.method??"?"} ${s.url??""}`,r),e.destroy();return}if(r instanceof c){f(e,r);return}console.error("[Accelerate]",r);try{l(e,500)}catch(n){o&&console.error("[Accelerate]","failed to write 500 response (client likely disconnected)",n),e.destroy()}}function E(r){let{router:e}=r;return{async listen(s){let o=m((t,a)=>{e.lookup(t,a)}),i=(await T(o,s)).port;return o.on("error",t=>{console.error("[Accelerate]",t)}),{async close(){await u(o.close.bind(o))()},port:i,url:`http://localhost:${i}`}}}}function T(r,e){return new Promise((s,o)=>{let n=t=>{if(r.off("listening",i),typeof t=="object"&&t!==null&&"code"in t&&t.code==="EADDRINUSE"){o(new d(e));return}o(t)},i=()=>{r.off("error",n),s(r.address())};r.once("error",n),r.once("listening",i),r.listen(e)})}export{A as a,E as b}; |
| import{b as f,d as w,e as y}from"./chunk-DWY47FQV.js";import{a as E,b as v,c as b}from"./chunk-DOJAPHLY.js";import{spawn as $}from"child_process";import{once as H}from"events";import{mkdir as C}from"fs/promises";import{join as A}from"path";import{setTimeout as j}from"timers/promises";function R(r){let e,t,s=new Promise((i,a)=>{e=i,t=a}),n=i=>{n=o=null,t(i),r?.onRejected?.(i),r?.onFulfilled?.()},o=i=>{o=n=null,e(i),r?.onResolved?.(i),r?.onFulfilled?.()};return{isFulfilled:()=>o===n,promise:s,reject:i=>n?.(i),resolve:i=>o?.(i)}}import{process as B}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:L,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:N,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:P}=B.env,S=class r{static#t=new Map;#e;#n;constructor(e){this.#e=e,this.#n=null}static async get(e){let{debug:t}=e,s=`${e.schemaHash}:${e.clientVersion}`;try{let n=r.#t.get(s);if(n)return n;let o=new r(e);return r.#t.set(s,o),t&&console.debug("[Query Engine] starting...",e),await o.start(),t&&console.debug("[Query Engine] started!"),o}finally{r.stopAll(s)}}static async stopAll(e){let s=(await Promise.allSettled(Array.from(r.#t.entries()).filter(([n])=>n!==e).map(async([n,o])=>{try{await o.stop()}finally{r.#t.delete(n)}}))).filter(n=>n.status==="rejected").map(n=>n.reason);if(s.length>0)throw new AggregateError(s,"Failed to stop engines")}async commitTransaction(e,t){return await this.#s(e,t,"commit")}async request(e,t){let{url:s}=await this.start(),n=this.#i(t),o=await fetch(s,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...n,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await l.fromResponse(o);return await o.text()}async rollbackTransaction(e,t){return await this.#s(e,t,"rollback")}async startTransaction(e,t){let{url:s}=await this.start(),n=this.#i(t),o=await fetch(`${s}/transaction/start`,{body:JSON.stringify(e),headers:{...n,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await l.fromResponse(o);return await o.json()}async start(){if(this.#n!=null)return await this.#n;let{promise:e,reject:t,resolve:s}=R();this.#n=e;let n=N||await this.#o();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",n);let{proxySignals:o}=await import("foreground-child/proxy-signals"),i=$(n,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});o(i),i.stderr.setEncoding("utf8"),i.stdout.setEncoding("utf8");let a=c=>{let u=c.split(` | ||
| `).find(k=>k.includes("Started query engine http server"));if(!u)return;i.stdout.removeListener("data",a);let{fields:p}=JSON.parse(u);if(p==null)return t(new Error(`Unexpected data during initialization, "fields" are missing: ${c}`));let{ip:m,port:h}=p;if(m==null||h==null)return t(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry. | ||
| Received data: ${c}`));s({childProcess:i,url:`http://${m}:${h}`})},T=c=>{this.#n=null,t(new d(String(c))),i.removeListener("exit",g),i.kill()};i.once("error",T);let g=(c,u)=>{this.#n=null,t(new d(`Query Engine exited with code ${c} and signal ${u}`))};return i.once("exit",g),i.stdout.on("data",a),this.#e.debug&&(i.stderr.on("data",console.error.bind(console,"[Query Engine]")),i.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#n}async stop(){if(this.#n==null)return;let{childProcess:e}=await this.#n;e.exitCode==null&&e.signalCode==null&&(this.#n=null,e.kill(),await H(e,"exit"))}async#o(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#r();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let t=f(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",t),await C(t,{recursive:!0});let{binaryTarget:s}=this.#e.platform,n=s==="windows"?".exe":"",o=A(t,`query-engine-${s}${n}`);return this.#e.debug&&console.debug("[Query Engine] binary path",o),(L==="1"||await w(o)===!1)&&await this.#a({commitHash:e,extension:n,engineBinaryPath:o}),o}async#r(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let s=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!s)throw new Error("Couldn't find engines version in package.json");let n=s.split(".").at(-1);if(!n)throw new Error("Couldn't find commit hash in engines version");return n}async#a(e){let{commitHash:t,extension:s,engineBinaryPath:n}=e,{binaryTarget:o}=this.#e.platform,i=`https://binaries.prisma.sh/all_commits/${t}/${o}/query-engine${s}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",i);let a=await fetch(i);if(!a.ok)throw new Error(`Couldn't download engine. URL: ${i}, status code: ${a.status}`);P&&await j(Number(P)),await y(await a.arrayBuffer(),n),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",n)}#i(e){let t={};for(let[s,n]of Object.entries(e))n!=null&&(t[s]=n);return t}async#s(e,t,s){let{url:n}=await this.#n,o=this.#i(t),i=await fetch(`${n}/transaction/${e}/${s}`,{headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await l.fromResponse(i);try{return await i.json()}catch{return{}}}};function G(r,e){if(console.error(r),r instanceof d){E(e,{EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:r.message}}}},500);return}if(r instanceof l){v(e,r.responseBody,r.statusCode);return}b(e,500)}var d=class extends Error{name="EngineStartError"},l=class r extends Error{constructor(t,s,n){super(`${t}: Query Engine response status ${s}, body: ${n}`);this.action=t;this.statusCode=s;this.responseBody=n}name="EngineHttpError";static async fromResponse(t){let s=new URL(t.url),n=await t.text();return new r(s.pathname,t.status,n)}};export{S as Engine,G as handleEngineError}; |
| import{parseDuration as e,parseSize as o,Server as n}from"@prisma/query-plan-executor";import{version as c}from"@prisma/query-plan-executor";var r;async function u(t){return r===void 0&&(r=await n.create({databaseUrl:t.db.connectionString,maxResponseSize:o("128 MiB"),queryTimeout:e("PT5M"),maxTransactionTimeout:e("PT5M"),maxTransactionWaitTime:e("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:t.debug?"debug":"off"}})),r}export{u as getQueryPlanExecutorServer,c as queryPlanExecutorVersion}; |
| import{a,b}from"./chunk-SW3J2PL2.js";import"./chunk-ANHBRJRZ.js";import"./chunk-EDFHV3AK.js";import"./chunk-DOJAPHLY.js";export{b as createHTTPServer,a as wrap}; |
| import{a as r}from"./chunk-SW3J2PL2.js";import"./chunk-ANHBRJRZ.js";import"./chunk-EDFHV3AK.js";import{a}from"./chunk-DOJAPHLY.js";function h(o,e,m){o.on("POST","/database/dump",r(async(p,t)=>{await e.db.dump(e.databaseDumpPath),a(t,{dumpPath:e.databaseDumpPath},201)},m)),o.on("GET","/health",r((p,t)=>{a(t,{name:e.name})},m))}export{h as registerUtilityRoutes}; |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Uses eval
Supply chain riskPackage uses dynamic code execution (e.g., eval()), which is a dangerous practice. This can prevent the code from running in certain environments and increases the risk that the code may contain exploits or malicious behavior.
AI-detected potential code anomaly
Supply chain riskAI has identified unusual behaviors that may pose a security risk.
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 4 instances
AI-detected potential code anomaly
Supply chain riskAI has identified unusual behaviors that may pose a security risk.
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 4 instances
19155135
0.7%14
-6.67%77
1.32%2616
27.24%14
7.69%22
4.76%76
18.75%- Removed
- Removed
- Removed
- Removed
- Removed
- Removed