@prisma/dev 0.24.14 → 0.24.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,11 @@
1
+ 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]!==`
2
+ `;)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(`
3
+ `)&&!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(`
4
+ `)||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]===`
5
+ `){r.push({line:n.slice(e,t),terminator:`\r
6
+ `}),t+=1,e=t+1;continue}(n[t]===`
7
+ `||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(`
8
+ `,r)+1,t=e;for(;n[t]===" "||n[t]===" ";)t+=1;return n.slice(e,t)}function xn(n){return n.includes(`\r
9
+ `)?`\r
10
+ `:`
11
+ `}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};
@@ -0,0 +1 @@
1
+ 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};
@@ -0,0 +1,3 @@
1
+ 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}":
2
+ ${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)}
3
+ `,{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};
@@ -0,0 +1 @@
1
+ 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};
@@ -0,0 +1 @@
1
+ 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};
@@ -0,0 +1 @@
1
+ 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};
@@ -0,0 +1 @@
1
+ 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};
@@ -0,0 +1,23 @@
1
+ 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(`
2
+ `,`
3
+ `+e+f);r+=e+l+i+u+`
4
+ `,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+=`
5
+ \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(`
6
+ ${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(`
7
+ `))(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(`
8
+ let candidates = ${(1<<this.handlers.length)-1}
9
+ let mask, matches
10
+ `);for(let n of this.constraints){r.push(`
11
+ mask = ${this._constrainedIndexBitmask(n)}
12
+ value = derivedConstraints.${n}
13
+ `);let i=e.strategies[n].mustMatchWhenDerived?"matches":"(matches | mask)";r.push(`
14
+ if (value === undefined) {
15
+ candidates &= mask
16
+ } else {
17
+ matches = this.constrainedHandlerStores.${n}.get(value) || 0
18
+ candidates &= ${i}
19
+ }
20
+ if (candidates === 0) return null;
21
+ `)}for(let n in 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(`
22
+ `))}};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(`
23
+ `)).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};
@@ -0,0 +1 @@
1
+ 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};
@@ -0,0 +1 @@
1
+ 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};
@@ -0,0 +1 @@
1
+ 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};
@@ -1,12 +1,12 @@
1
- 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(`
1
+ 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(`
2
2
  select b.oid, b.typarray
3
3
  from pg_catalog.pg_type a
4
4
  left join pg_catalog.pg_type b on b.oid = a.typelem
5
5
  where a.typcategory = $1
6
6
  group by b.oid, b.typarray
7
7
  order by b.oid
8
- `),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(`
9
- CREATE TABLE IF NOT EXISTS "${y}"."${A}" (
8
+ `),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(`
9
+ CREATE TABLE IF NOT EXISTS "${y}"."${D}" (
10
10
  id BIGSERIAL PRIMARY KEY,
11
11
  txid BIGINT NOT NULL DEFAULT txid_current(),
12
12
  schema_name TEXT NOT NULL,
@@ -17,7 +17,7 @@ import{c as I}from"./chunk-KWCQYPJI.js";import{h as T}from"./chunk-EDFHV3AK.js";
17
17
  created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()
18
18
  )
19
19
  `),await t.exec(`
20
- CREATE OR REPLACE FUNCTION "${y}"."${Y}"()
20
+ CREATE OR REPLACE FUNCTION "${y}"."${z}"()
21
21
  RETURNS trigger
22
22
  LANGUAGE plpgsql
23
23
  AS $$
@@ -26,7 +26,7 @@ import{c as I}from"./chunk-KWCQYPJI.js";import{h as T}from"./chunk-EDFHV3AK.js";
26
26
  RETURN COALESCE(NEW, OLD);
27
27
  END IF;
28
28
 
29
- INSERT INTO "${y}"."${A}" (
29
+ INSERT INTO "${y}"."${D}" (
30
30
  txid,
31
31
  schema_name,
32
32
  table_name,
@@ -47,7 +47,7 @@ import{c as I}from"./chunk-KWCQYPJI.js";import{h as T}from"./chunk-EDFHV3AK.js";
47
47
  END;
48
48
  $$;
49
49
  `),await t.exec(`
50
- CREATE OR REPLACE FUNCTION "${y}"."${X}"()
50
+ CREATE OR REPLACE FUNCTION "${y}"."${j}"()
51
51
  RETURNS void
52
52
  LANGUAGE plpgsql
53
53
  AS $$
@@ -67,28 +67,28 @@ import{c as I}from"./chunk-KWCQYPJI.js";import{h as T}from"./chunk-EDFHV3AK.js";
67
67
  SELECT 1
68
68
  FROM pg_trigger
69
69
  WHERE tgrelid = target
70
- AND tgname = '${z}'
70
+ AND tgname = '${J}'
71
71
  ) THEN
72
72
  CONTINUE;
73
73
  END IF;
74
74
 
75
75
  EXECUTE format(
76
- 'CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION "${y}"."${Y}"()',
77
- '${z}',
76
+ 'CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION "${y}"."${z}"()',
77
+ '${J}',
78
78
  target::text
79
79
  );
80
80
  END LOOP;
81
81
  END;
82
82
  $$;
83
- `),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(`
83
+ `),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(`
84
84
  WITH drained AS (
85
- DELETE FROM "${y}"."${A}"
85
+ DELETE FROM "${y}"."${D}"
86
86
  RETURNING txid, schema_name, table_name, op, row_data, old_row_data, id
87
87
  )
88
88
  SELECT txid, schema_name, table_name, op, row_data, old_row_data
89
89
  FROM drained
90
90
  ORDER BY id
91
- `));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(`
91
+ `));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(`
92
92
  SELECT attribute.attname AS column_name
93
93
  FROM pg_constraint pk_constraint
94
94
  INNER JOIN pg_class relation
@@ -101,7 +101,7 @@ import{c as I}from"./chunk-KWCQYPJI.js";import{h as T}from"./chunk-EDFHV3AK.js";
101
101
  ON attribute.attrelid = relation.oid
102
102
  AND attribute.attnum = keys.attnum
103
103
  WHERE pk_constraint.contype = 'p'
104
- AND namespace.nspname = ${te(t)}
105
- AND relation.relname = ${te(r)}
104
+ AND namespace.nspname = ${re(t)}
105
+ AND relation.relname = ${re(r)}
106
106
  ORDER BY keys.ordinality
107
- `);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};
107
+ `);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};