@prisma/dev 0.24.3 → 0.24.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-DLTTSFDI.js +1 -0
- package/dist/daemon.cjs +23 -23
- package/dist/daemon.js +1 -1
- package/dist/index.cjs +24 -24
- package/dist/index.js +1 -1
- package/package.json +15 -14
- package/dist/chunk-2O6J3K3T.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as h}from"./chunk-YL6J3L2T.js";import{a as D,b as k,c as y,d as W,e as B}from"./chunk-CC3P7GPW.js";import{g}from"./chunk-X3G665AK.js";import{a as R,c as A,d as T}from"./chunk-TF5C7XJX.js";import{j as v}from"./chunk-DWY47FQV.js";import{createServer as U}from"http";import{promisify as H}from"util";import L from"@prisma/get-platform";async function C(r,e){let{port:t}=e;if(e.dryRun)return O(t,null);let n=await V(r,e),{promise:a,reject:l,resolve:i}=A(),{serve:o}=await import("@hono/node-server"),s=o({createServer:U,fetch:n.fetch,overrideGlobalObjects:!1,port:t},i);s.on("error",m=>{if(typeof m=="object"&&"code"in m&&m.code==="EADDRINUSE")return l(new g(t));console.error("[Accelerate]",m)});let{port:c}=await a;return e.port=c,O(c,s)}function O(r,e){return{async close(){e&&await Promise.allSettled([H(e.close.bind(e))(),T.stopAll()])},port:r,url:`http://localhost:${r}`}}async function V(r,e){let{debug:t}=e,[{Hono:n},{accelerateRoute:a},{utilityRoute:l}]=await Promise.all([import("hono/tiny"),import("./accelerate-HWGEFOM5.js"),import("./utility-Q5A254LJ.js")]),i=new n,o=await L.getPlatformInfo();if(t&&console.debug("[Accelerate] platform info: %s",JSON.stringify(o)),t){let{logger:c}=await import("hono/logger");i.use("*",c((...m)=>console.log("[Accelerate]",...m)))}i.use("*",async(c,m)=>(c.set("databaseDumpPath",e.databaseDumpPath),c.set("db",r),c.set("debug",!!t),c.set("name",e.name),c.set("platform",o),c.set("shadowDBPort",e.shadowDatabasePort),await m()));let s=new n;return s.route("/",a),s.route("/",l),i.route("/",s),i}import{randomUUID as q}from"crypto";import{setTimeout as _}from"timers/promises";import{isDeepStrictEqual as N}from"util";import{process as K}from"std-env";var J="application/json",d={connection:"close","content-type":J},G={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},E={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 I(r){let{dbServer:e,debug:t,name:n,persistenceMode:a,port:l,walBridge:i}=r,o=a==="stateless",s=o?te(n):n;K.env.DS_LOCAL_DATA_ROOT=k(),o&&await v(y(s));let{startLocalDurableStreamsServer:c}=await import("@prisma/streams-local"),m=await c({hostname:"127.0.0.1",name:s,port:l}),p={serverUrl:m.exports.http.url,sqlitePath:m.exports.sqlite.path,streamName:D,url:W(m.exports.http.url)};try{await z(p);let u=new b({dbServer:e,debug:t,streamUrl:p.url}),f=i.subscribe(F=>{u.enqueue(F)});return{close:async()=>{f(),await u.close(),await m.close(),await _(100),o&&await v(y(s))},experimental:p}}catch(u){throw await m.close().catch(()=>{}),await _(100),o&&await v(y(s)).catch(()=>{}),u}}var b=class{#n;#a;#e;#r;#t;constructor(e){this.#n=e.dbServer,this.#a=e.debug,this.#e=Promise.resolve(),this.#r=e.streamUrl,this.#t=new Set}enqueue(e){e.length!==0&&(this.#e=this.#e.then(async()=>{let t=await this.#s(e);t.length!==0&&(await X(this.#r,t),this.#a&&console.debug(`[streams] appended ${t.length} state-protocol record(s) to ${this.#r}`))}).catch(t=>{console.error("[streams] failed to ingest WAL events into prisma-wal",t)}))}async close(){await this.#e}async#s(e){let t=[],n=new Date().toISOString();for(let a of e)t.push(...await this.#i(a,n));return t}async#i(e,t){let n=`${e.schema}.${e.table}`,a=await this.#n.getPrimaryKeyColumns(e.schema,e.table),l=$(e.record),i=$(e.oldRecord),o=this.#o(n,a,i),s=this.#o(n,a,l),c=e.txid===""?void 0:e.txid;return e.type==="insert"?l&&s?[{headers:{operation:"insert",timestamp:t,txid:c},key:s,oldValue:null,type:n,value:l}]:[]:e.type==="delete"?i&&o?[{headers:{operation:"delete",timestamp:t,txid:c},key:o,oldValue:i,type:n,value:null}]:[]:!l||!i||!o||!s?[]:o!==s?[{headers:{operation:"delete",timestamp:t,txid:c},key:o,oldValue:i,type:n,value:null},{headers:{operation:"insert",timestamp:t,txid:c},key:s,oldValue:null,type:n,value:l}]:[{headers:{operation:"update",timestamp:t,txid:c},key:s,oldValue:i,type:n,value:l}]}#o(e,t,n){if(!n)return null;let a=Z(n,t);return a||(this.#t.has(e)||(this.#t.add(e),console.warn(`[streams] falling back to full-row keys for ${e} because no primary key could be resolved`)),ee(n))}};async function z(r){let e=await fetch(r.url,{headers:d,method:"PUT"});if(!e.ok)throw await S(e,`Failed to create ${r.streamName}`);let t=await fetch(`${r.url}/_profile`,{body:JSON.stringify(G),headers:d,method:"POST"});if(!t.ok)throw await S(t,`Failed to configure ${r.streamName}`);let n=await Q(r);if(Y(n,r.streamName))return;if(n.currentVersion>0)throw new Error(`Failed to install schema for ${r.streamName}: existing schema registry is incompatible and requires a lens migration`);let a=await fetch(`${r.url}/_schema`,{body:JSON.stringify(E),headers:d,method:"POST"});if(!a.ok)throw await S(a,`Failed to install schema for ${r.streamName}`)}async function Q(r){let e=await fetch(`${r.url}/_schema`,{headers:d,method:"GET"});if(!e.ok)throw await S(e,`Failed to inspect schema for ${r.streamName}`);return await e.json()}function Y(r,e){if(r.currentVersion<=0||r.schema!==e)return!1;let t=r.schemas[String(r.currentVersion)];return N(t,E.schema)&&N(r.search,E.search)}async function X(r,e){let t=await fetch(r,{body:JSON.stringify(e),headers:d,method:"POST"});if(!t.ok)throw await S(t,"Failed to append to prisma-wal")}async function S(r,e){let t=await r.text().catch(()=>"");return new Error(`${e}: HTTP ${r.status}${t?` ${t}`:""}`)}function Z(r,e){if(e.length===0)return null;let t=[];for(let n of e){if(!Object.prototype.hasOwnProperty.call(r,n))return null;let a=re(r[n]);if(a==null)return null;t.push(e.length===1?a:`${n}=${a}`)}return t.join("|")}function ee(r){return JSON.stringify(x(r))}function x(r){return Array.isArray(r)?r.map(e=>x(e)):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,x(t)])):r}function $(r){return r?structuredClone(r):null}function re(r){if(r===null)return"null";if(r===void 0)return"undefined";if(typeof r=="string")return r;if(typeof r=="number")return Number.isFinite(r)?String(r):null;if(typeof r=="bigint")return r.toString();if(typeof r=="boolean")return r?"true":"false";try{return JSON.stringify(r)}catch{return null}}function te(r){return`${r}.${q().replaceAll("-","")}`}async function M(r){let e=await B.createExclusively(r),t=null,n=null,a=null,l=null;try{[t,a]=await Promise.all([h("database",e),h("shadow_database",e)]);let i;e.dryRun?(i=se(),l=ie()):(i=await t.attachWalEventBridge(),l=await I({dbServer:t,debug:e.debug,name:e.name,port:e.streamsPort,persistenceMode:e.persistenceMode,walBridge:i})),n=await C(t,e);let o=ne(t,a,n,e);await e.writeServerDump(o,e.dryRun?{}:{streams:l.experimental});let s=oe(i),c=t,m=a,p=n,u=l,f=async()=>{s.close(),await j(e,[p,u,c,m])};return{close:f,dbServer:t,httpServer:n,server:{...o,close:f,experimental:{streams:l.experimental,wal:s.api},name:e.name},serverState:e,shadowDbServer:a,streamsServer:l,walBridge:i}}catch(i){return await ae(e,[n,l,t,a],i)}}function ne(r,e,t,n){let a=`prisma+postgres://localhost:${t.port}/?${new URLSearchParams({api_key:R({databaseUrl:r.prismaORMConnectionString,name:n.name,shadowDatabaseUrl:e.prismaORMConnectionString})}).toString()}`;return{database:{connectionString:r.connectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand},http:{url:t.url},ppg:{url:a},shadowDatabase:{connectionString:e.prismaORMConnectionString,prismaORMConnectionString:e.prismaORMConnectionString,terminalCommand:e.terminalCommand}}}async function j(r,e){let n=(await Promise.allSettled(e.map(a=>a.close()))).filter(a=>a.status==="rejected").map(a=>new Error(a.reason));try{await r.close()}catch(a){n.push(a)}if(n.length>0)throw new AggregateError(n,"Failed to close some servers")}async function ae(r,e,t){try{await j(r,e.filter(n=>n!==null))}catch(n){throw new AggregateError([t,n],"Failed to start Prisma Dev server cleanly")}throw t}function oe(r){let e=new Set;return{api:{stream:()=>{let t=()=>{},n=le(r,()=>{e.delete(t)});return t=()=>n.close(),e.add(t),n.stream},subscribe:t=>r.subscribe(t)},close:()=>{for(let t of[...e])t();e.clear()}}}function se(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function ie(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function le(r,e){let t=[],n=!1,a=null,l=r.subscribe(o=>{if(!n){if(a){let s=a;a=null,s.resolve({done:!1,value:o});return}t.push(o)}}),i=()=>{if(!n&&(n=!0,l(),t.length=0,e(),a)){let o=a;a=null,o.resolve({done:!0,value:void 0})}};return{close:i,stream:{[Symbol.asyncIterator](){return this},next(){return t.length>0?Promise.resolve({done:!1,value:t.shift()}):n?Promise.resolve({done:!0,value:void 0}):new Promise((o,s)=>{a={reject:s,resolve:o}})},return(){return i(),Promise.resolve({done:!0,value:void 0})},throw(o){let s=a;return i(),s&&s.reject(o),Promise.reject(o instanceof Error?o:new Error(String(o)))}}}}async function ce(r){let{server:e}=await M(r);return e}async function Ue(r){return await ce(r)}export{ce as a,Ue as b};
|
package/dist/daemon.cjs
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var Fr=Object.create;var se=Object.defineProperty;var qr=Object.getOwnPropertyDescriptor;var Vr=Object.getOwnPropertyNames;var Kr=Object.getPrototypeOf,zr=Object.prototype.hasOwnProperty;var T=(e,t)=>()=>(e&&(t=e(e=0)),t);var ut=(e,t)=>{for(var r in t)se(e,r,{get:t[r],enumerable:!0})},dt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Vr(t))!zr.call(e,s)&&s!==r&&se(e,s,{get:()=>t[s],enumerable:!(n=qr(t,s))||n.enumerable});return e};var w=(e,t,r)=>(r=e!=null?Fr(Kr(e)):{},dt(t||!e||!e.__esModule?se(r,"default",{value:e,enumerable:!0}):r,e)),Jr=e=>dt(se({},"__esModule",{value:!0}),e);var Qr,f,m=T(()=>{"use strict";Qr=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,f=Qr()});function pt(e){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([[t],[r]])=>t.localeCompare(r)))),"utf8").toString("base64url")}function Xr(e){let t=Buffer.from(e,"base64url").toString("utf8"),{issues:r,output:n,success:s}=(0,y.safeParse)(Yr,t,{abortEarly:!0});return s?[null,n]:[r]}var y,mt,Yr,B,Pe=T(()=>{"use strict";m();y=require("valibot"),mt=/^(postgres|postgresql):\/\//,Yr=(0,y.pipe)((0,y.string)(),(0,y.parseJson)(),(0,y.object)({databaseUrl:(0,y.pipe)((0,y.string)(),(0,y.url)(),(0,y.regex)(mt)),name:(0,y.optional)((0,y.pipe)((0,y.string)(),(0,y.minLength)(1))),shadowDatabaseUrl:(0,y.pipe)((0,y.string)(),(0,y.url)(),(0,y.regex)(mt))}));B=async(e,t)=>{let{authorization:r}=e,{HTTPException:n}=await import("hono/http-exception");if(!r)throw new n(401,{message:"Missing API Key"});let[s,o="",a]=r.split(" ");if(s!=="Bearer"||a)throw new n(401,{message:"Invalid API Key"});let[c,i]=Xr(o);if(c)throw new n(401,{message:"Invalid API Key",cause:c.join(", ")});let{databaseUrl:l,name:u,shadowDatabaseUrl:p}=i,g=t.get("name"),P=new URL(t.req.url).port;if(!u)throw new n(401,{message:`Wrong API Key; The Prisma Dev server running at port ${P} requires an API Key from a newer version of \`prisma dev\`. Check the "${g}" server's output for the updated \`DATABASE_URL\` value.`});if(u!==g)throw new n(401,{message:`Wrong API Key; The Prisma Dev server running at port ${P} is named "${g}", but the API Key is for "${u}"`});let{hostname:R,port:D}=new URL(l),{port:Wr}=t.get("db"),{hostname:Hr,port:Gr}=new URL(p),jr=t.get("shadowDBPort");if(R!=="localhost"||Number(D)!==Wr||Hr!=="localhost"||Number(Gr)!==jr)throw new n(401,{message:"Wrong API Key; Check your Prisma schema's `provider.url` value (probably defined in `.env`'s `DATABASE_URL` environment variable) is aligned with `prisma dev`'s output"});return{decodedAPIKey:i}}});function we(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),oe.default.platform==="darwin"?Zr(e):oe.default.platform==="win32"?en(e):tn(e)}var b,be,oe,L,Se,W,Zr,en,tn,gt=T(()=>{"use strict";m();b=w(require("path"),1),be=w(require("os"),1),oe=w(require("process"),1),L=be.default.homedir(),Se=be.default.tmpdir(),{env:W}=oe.default,Zr=e=>{let t=b.default.join(L,"Library");return{data:b.default.join(t,"Application Support",e),config:b.default.join(t,"Preferences",e),cache:b.default.join(t,"Caches",e),log:b.default.join(t,"Logs",e),temp:b.default.join(Se,e)}},en=e=>{let t=W.APPDATA||b.default.join(L,"AppData","Roaming"),r=W.LOCALAPPDATA||b.default.join(L,"AppData","Local");return{data:b.default.join(r,e,"Data"),config:b.default.join(t,e,"Config"),cache:b.default.join(r,e,"Cache"),log:b.default.join(r,e,"Log"),temp:b.default.join(Se,e)}},tn=e=>{let t=b.default.basename(L);return{data:b.default.join(W.XDG_DATA_HOME||b.default.join(L,".local","share"),e),config:b.default.join(W.XDG_CONFIG_HOME||b.default.join(L,".config"),e),cache:b.default.join(W.XDG_CACHE_HOME||b.default.join(L,".cache"),e),log:b.default.join(W.XDG_STATE_HOME||b.default.join(L,".local","state"),e),temp:b.default.join(Se,t,e)}}});function Pt(e,t){return`${ie.cache}/engine/${e}/${t}`}function K(e){return`${ie.data}/${e}`}async function bt(e){try{return await(0,v.access)(e,v.constants.F_OK),!0}catch(t){if(ve(t))return!1;throw t}}async function St(e,t){let r=await rn(e);await(0,v.writeFile)(t,r),await(0,v.chmod)(t,"755")}async function wt(e,t){await e.stream().pipeTo(ae.WriteStream.toWeb((0,ae.createWriteStream)(t,{encoding:"utf8"})))}function ve(e){return e!=null&&typeof e=="object"&&"code"in e&&e.code==="ENOENT"}async function vt(e){try{return await(0,v.readFile)(e,{encoding:"utf-8"})}catch(t){if(ve(t))return null;throw t}}async function Et(e){await(0,v.mkdir)(e,{recursive:!0})}async function Rt(e,t){try{return(await(0,v.readdir)(e,{withFileTypes:!0})).reduce((n,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!t||(0,yt.default)(t,s.name))&&n.push(s.name),n),[])}catch(r){if(ve(r))return[];throw r}}async function z(e){await(0,v.rm)(e,{force:!0,recursive:!0})}var ae,v,ft,ht,yt,ie,rn,H=T(()=>{"use strict";m();ae=require("fs"),v=require("fs/promises"),ft=require("util"),ht=require("zlib");gt();yt=w(require("zeptomatch"),1),ie=we("prisma-dev"),rn=(0,ft.promisify)(ht.unzip)});function me(e){let t,r,n=new Promise((a,c)=>{t=a,r=c}),s=a=>{s=o=null,r(a),e?.onRejected?.(a),e?.onFulfilled?.()},o=a=>{o=s=null,t(a),e?.onResolved?.(a),e?.onFulfilled?.()};return{isFulfilled:()=>o===s,promise:n,reject:a=>s?.(a),resolve:a=>o?.(a)}}var Ue=T(()=>{"use strict";m()});function pe(e,t){return console.error(e),e instanceof Q?t.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:e.message}}}},500):e instanceof F?t.text(e.responseBody,e.statusCode):t.body(null,500)}var zt,Jt,Qt,Yt,Xt,Zt,Nn,Bn,Kt,q,Q,F,We=T(()=>{"use strict";m();zt=require("child_process"),Jt=require("events"),Qt=require("fs/promises"),Yt=require("path"),Xt=require("timers/promises");Ue();Zt=require("std-env");H();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Nn,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:Bn,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:Kt}=Zt.process.env),q=class e{static#r=new Map;#e;#t;constructor(t){this.#e=t,this.#t=null}static async get(t){let{debug:r}=t,n=`${t.schemaHash}:${t.clientVersion}`;try{let s=e.#r.get(n);if(s)return s;let o=new e(t);return e.#r.set(n,o),r&&console.debug("[Query Engine] starting...",t),await o.start(),r&&console.debug("[Query Engine] started!"),o}finally{e.stopAll(n)}}static async stopAll(t){let n=(await Promise.allSettled(Array.from(e.#r.entries()).filter(([s])=>s!==t).map(async([s,o])=>{try{await o.stop()}finally{e.#r.delete(s)}}))).filter(s=>s.status==="rejected").map(s=>s.reason);if(n.length>0)throw new AggregateError(n,"Failed to stop engines")}async commitTransaction(t,r){return await this.#i(t,r,"commit")}async request(t,r){let{url:n}=await this.start(),s=this.#n(r),o=await fetch(n,{body:typeof t=="string"?t:JSON.stringify(t),headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await F.fromResponse(o);return await o.text()}async rollbackTransaction(t,r){return await this.#i(t,r,"rollback")}async startTransaction(t,r){let{url:n}=await this.start(),s=this.#n(r),o=await fetch(`${n}/transaction/start`,{body:JSON.stringify(t),headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await F.fromResponse(o);return await o.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:t,reject:r,resolve:n}=me();this.#t=t;let s=Bn||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",s);let{proxySignals:o}=await import("foreground-child/proxy-signals"),a=(0,zt.spawn)(s,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});o(a),a.stderr.setEncoding("utf8"),a.stdout.setEncoding("utf8");let c=u=>{let p=u.split(`
|
|
2
2
|
`).find(D=>D.includes("Started query engine http server"));if(!p)return;a.stdout.removeListener("data",c);let{fields:g}=JSON.parse(p);if(g==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${u}`));let{ip:P,port:R}=g;if(P==null||R==null)return r(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
|
|
3
|
-
Received data: ${u}`));n({childProcess:a,url:`http://${P}:${R}`})},i=u=>{this.#t=null,r(new Q(String(u))),a.removeListener("exit",l),a.kill()};a.once("error",i);let l=(u,p)=>{this.#t=null,r(new Q(`Query Engine exited with code ${u} and signal ${p}`))};return a.once("exit",l),a.stdout.on("data",c),this.#e.debug&&(a.stderr.on("data",console.error.bind(console,"[Query Engine]")),a.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:t}=await this.#t;t.exitCode==null&&t.signalCode==null&&(this.#t=null,t.kill(),await(0,
|
|
4
|
-
`;)r+=1;return r}function
|
|
5
|
-
`)&&!e.includes("\r")){let p=e.trim();return p.length===0?`${o}${c}${o}${r}`:`${o}${a}${p}${o}${c}${o}${r}`}let i=s.at(-1);if(i&&i.terminator===""&&/^\s*$/.test(i.line))return`${
|
|
6
|
-
`)||l.endsWith("\r")?"":o;return`${l}${u}${c}${o}${r}`}function
|
|
3
|
+
Received data: ${u}`));n({childProcess:a,url:`http://${P}:${R}`})},i=u=>{this.#t=null,r(new Q(String(u))),a.removeListener("exit",l),a.kill()};a.once("error",i);let l=(u,p)=>{this.#t=null,r(new Q(`Query Engine exited with code ${u} and signal ${p}`))};return a.once("exit",l),a.stdout.on("data",c),this.#e.debug&&(a.stderr.on("data",console.error.bind(console,"[Query Engine]")),a.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:t}=await this.#t;t.exitCode==null&&t.signalCode==null&&(this.#t=null,t.kill(),await(0,Jt.once)(t,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let t=await this.#o();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",t);let r=Pt(this.#e.clientVersion,t);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,Qt.mkdir)(r,{recursive:!0});let{binaryTarget:n}=this.#e.platform,s=n==="windows"?".exe":"",o=(0,Yt.join)(r,`query-engine-${n}${s}`);return this.#e.debug&&console.debug("[Query Engine] binary path",o),(Nn==="1"||await bt(o)===!1)&&await this.#a({commitHash:t,extension:s,engineBinaryPath:o}),o}async#o(){let t=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!t.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${t.status}`);let n=(await t.json()).devDependencies?.["@prisma/engines-version"];if(!n)throw new Error("Couldn't find engines version in package.json");let s=n.split(".").at(-1);if(!s)throw new Error("Couldn't find commit hash in engines version");return s}async#a(t){let{commitHash:r,extension:n,engineBinaryPath:s}=t,{binaryTarget:o}=this.#e.platform,a=`https://binaries.prisma.sh/all_commits/${r}/${o}/query-engine${n}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",a);let c=await fetch(a);if(!c.ok)throw new Error(`Couldn't download engine. URL: ${a}, status code: ${c.status}`);Kt&&await(0,Xt.setTimeout)(Number(Kt)),await St(await c.arrayBuffer(),s),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",s)}#n(t){let r={};for(let[n,s]of Object.entries(t))s!=null&&(r[n]=s);return r}async#i(t,r,n){let{url:s}=await this.#t,o=this.#n(r),a=await fetch(`${s}/transaction/${t}/${n}`,{headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!a.ok)throw await F.fromResponse(a);try{return await a.json()}catch{return{}}}};Q=class extends Error{name="EngineStartError"},F=class e extends Error{constructor(r,n,s){super(`${r}: Query Engine response status ${n}, body: ${s}`);this.action=r;this.statusCode=n;this.responseBody=s}name="EngineHttpError";static async fromResponse(r){let n=new URL(r.url),s=await r.text();return new e(n.pathname,r.status,s)}}});async function er(e){let{output:t,success:r}=(0,E.safeParse)(Cn,await e.req.json(),{abortEarly:!0});return r?t:e.text("Invalid input",400)}var E,Cn,tr=T(()=>{"use strict";m();E=require("valibot"),Cn=(0,E.object)({tags:(0,E.union)([(0,E.pipe)((0,E.array)((0,E.string)()),(0,E.minLength)(1)),(0,E.literal)("all")])})});async function rr(e){return He===void 0&&(He=await N.Server.create({databaseUrl:e.get("db").connectionString,maxResponseSize:(0,N.parseSize)("128 MiB"),queryTimeout:(0,N.parseDuration)("PT5M"),maxTransactionTimeout:(0,N.parseDuration)("PT5M"),maxTransactionWaitTime:(0,N.parseDuration)("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:e.get("debug")?"debug":"off"}})),He}var N,ge,He,nr=T(()=>{"use strict";m();N=require("@prisma/query-plan-executor"),ge=require("@prisma/query-plan-executor")});async function Fe(e){let r=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(a=>a.toString(16).padStart(2,"0")).join("")}function or(e){let t=e.req.param("schemaHash"),r=fe.get(t);return r==null?e.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:t,schemas:r}}async function ar(e,t,r){let n=je.Buffer.from(e,"base64").toString("utf8"),s=Mn(n,t.toString());r&&console.log("[Accelerate] schema with override:",s);let o=await Fe(s);return{base64Override:je.Buffer.from(s,"utf8").toString("base64"),overrideHash:o}}function Mn(e,t){let r=Un(e);if(!r)throw new Error("No datasource block found in schema.");let n=e.slice(r.openBraceIndex+1,r.closeBraceIndex),s=Gn(n,t,qn(e,r.openBraceIndex));return`${e.slice(0,r.openBraceIndex+1)}${s}${e.slice(r.closeBraceIndex)}`}function Un(e){let t="datasource";for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="/"&&e[r+1]==="/"){r=qe(e,r+2);continue}if(n==="/"&&e[r+1]==="*"){r=Ve(e,r+2);continue}if(n==='"'){r=Ke(e,r+1);continue}if(e.startsWith(t,r)&&!sr(e[r-1])&&!sr(e[r+t.length])){let s=Wn(e,r+t.length,"{");if(s===-1)return null;let o=Hn(e,s);return o===-1?null:{closeBraceIndex:o,openBraceIndex:s}}}return null}function Wn(e,t,r){for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=qe(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=Ve(e,n+2);continue}if(s==='"'){n=Ke(e,n+1);continue}if(s===r)return n}return-1}function Hn(e,t){let r=0;for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=qe(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=Ve(e,n+2);continue}if(s==='"'){n=Ke(e,n+1);continue}if(s==="{"){r+=1;continue}if(s==="}"&&(r-=1,r===0))return n}return-1}function qe(e,t){let r=t;for(;r<e.length&&e[r]!==`
|
|
4
|
+
`;)r+=1;return r}function Ve(e,t){let r=e.indexOf("*/",t);return r===-1?e.length:r+1}function Ke(e,t){let r=t;for(;r<e.length;){if(e[r]==="\\"){r+=2;continue}if(e[r]==='"')return r;r+=1}return e.length}function sr(e){return e!=null&&/[A-Za-z0-9_]/.test(e)}function Gn(e,t,r){let n=`"${Kn(t)}"`,s=jn(e);for(let[p,g]of s.entries()){let{comment:P,code:R}=ir(g.line),D=R.match(/^(\s*)url(\s*)=(\s*).*/);if(D)return s[p]={line:`${D[1]}url${D[2]}=${D[3]}${n}${P}`,terminator:g.terminator},Ge(s)}let o=Vn(e),a=Fn(s,r),c=`${a}url = ${n}`;if(!e.includes(`
|
|
5
|
+
`)&&!e.includes("\r")){let p=e.trim();return p.length===0?`${o}${c}${o}${r}`:`${o}${a}${p}${o}${c}${o}${r}`}let i=s.at(-1);if(i&&i.terminator===""&&/^\s*$/.test(i.line))return`${Ge(s.slice(0,-1))}${c}${o}${r}`;let l=Ge(s),u=l.endsWith(`
|
|
6
|
+
`)||l.endsWith("\r")?"":o;return`${l}${u}${c}${o}${r}`}function jn(e){let t=[],r=0;for(let n=0;n<e.length;n+=1){if(e[n]==="\r"&&e[n+1]===`
|
|
7
7
|
`){t.push({line:e.slice(r,n),terminator:`\r
|
|
8
8
|
`}),n+=1,r=n+1;continue}(e[n]===`
|
|
9
|
-
`||e[n]==="\r")&&(t.push({line:e.slice(r,n),terminator:e[n]}),r=n+1)}return(r<e.length||e.length===0)&&t.push({line:e.slice(r),terminator:""}),t}function
|
|
10
|
-
`,t)+1,n=r;for(;e[n]===" "||e[n]===" ";)n+=1;return e.slice(r,n)}function
|
|
9
|
+
`||e[n]==="\r")&&(t.push({line:e.slice(r,n),terminator:e[n]}),r=n+1)}return(r<e.length||e.length===0)&&t.push({line:e.slice(r),terminator:""}),t}function Ge(e){return e.map(t=>`${t.line}${t.terminator}`).join("")}function ir(e){let t=!1,r=!1;for(let n=0;n<e.length;n+=1){let s=e[n];if(r){if(t){t=!1;continue}if(s==="\\"){t=!0;continue}s==='"'&&(r=!1);continue}if(s==='"'){r=!0;continue}if(s==="/"&&e[n+1]==="/")return{code:e.slice(0,n),comment:e.slice(n)}}return{code:e,comment:""}}function Fn(e,t){for(let r of e){let{code:n}=ir(r.line),s=n.match(/^([ \t]+)[A-Za-z_][A-Za-z0-9_]*\s*=/);if(s?.[1])return s[1]}return`${t}${kn}`}function qn(e,t){let r=e.lastIndexOf(`
|
|
10
|
+
`,t)+1,n=r;for(;e[n]===" "||e[n]===" ";)n+=1;return e.slice(r,n)}function Vn(e){return e.includes(`\r
|
|
11
11
|
`)?`\r
|
|
12
12
|
`:`
|
|
13
|
-
`}function qn(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}var He,pe,Bn,ar=T(()=>{"use strict";m();He=require("buffer"),pe=new Map;Bn=" "});function ge(e){let{req:t}=e;return{traceparent:t.header("traceparent"),"X-capture-telemetry":t.header("X-capture-telemetry")}}var ir=T(()=>{"use strict";m()});async function cr(e){let{issues:t,output:r,success:n}=(0,h.safeParse)(Vn,await e.req.json(),{abortEarly:!0});return n?r:e.json({EngineNotStarted:{reason:"InvalidRequest",issues:t}},400)}function lr(e,t){let{output:r,success:n}=(0,h.safeParse)(zn,e);return n?r:t.json({EngineMalfunction:{}},500)}var h,Vn,zn,ur=T(()=>{"use strict";m();h=require("valibot"),Vn=(0,h.object)({isolation_level:(0,h.optional)((0,h.string)()),max_wait:(0,h.pipe)((0,h.number)(),(0,h.integer)(),(0,h.minValue)(0)),timeout:(0,h.pipe)((0,h.number)(),(0,h.integer)(),(0,h.minValue)(0))});zn=(0,h.looseObject)({id:(0,h.union)([(0,h.string)(),(0,h.number)()])})});var pr={};ct(pr,{accelerateRoute:()=>Y});async function Ve(e){let{req:t}=e,r=nr(e);if(r instanceof Response)return r;let{base64Override:n,overrideHash:s}=r.schemas;return await q.get({base64Schema:n,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||t.param("clientVersion"),debug:e.get("debug"),platform:e.get("platform"),schemaHash:s})}var dr,mr,k,Y,Kn,X,Jn,Qn,gr=T(()=>{"use strict";m();dr=require("hono/http-exception"),mr=require("hono/tiny"),k=require("hono/validator");he();Zt();ke();tr();ar();ir();ur();Y=new mr.Hono;Y.post("/invalidate",(0,k.validator)("header",B),async e=>{let t=await Xt(e);return t instanceof Response?t:e.body(null)});Kn="/:clientVersion/:schemaHash",X=Y.basePath(Kn);Y.route("/",X);Jn=["/graphql","/itx/:transactionId/graphql"];X.on("POST",[...Jn],(0,k.validator)("header",B),async e=>{let{req:t}=e;try{let r=await Ve(e);if(r instanceof Response)return r;let n=await t.text(),s=t.param("transactionId"),o=await r.request(n,{...ge(e),"X-transaction-id":s});return e.text(o)}catch(r){return de(r,e)}});X.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,k.validator)("header",B),async e=>{let{req:t}=e;try{let r=await Ve(e);if(r instanceof Response)return r;let s=`${t.routePath.split("/").filter(Boolean).at(-1)}Transaction`,o=t.param("transactionId"),a=await r[s](o,ge(e));return e.json(a)}catch(r){return de(r,e)}});X.put("/schema",(0,k.validator)("header",B),async e=>{let{req:t}=e,r=await t.text();if(!r)return e.text("Missing schema",400);let n=t.param("schemaHash"),s=pe.get(n);if(s==null){if(n!==await Ge(r))return e.text("Schema hash mismatch",400);let o=await sr(r,e.get("db").prismaORMConnectionString,e.get("debug"));return pe.set(n,{base64Original:r,...o}),e.text(n)}return r!==s.base64Original?e.text("Schema mismatch",400):e.text(n)});X.post("/transaction/start",(0,k.validator)("header",B),async e=>{let{req:t}=e,r=await cr(e);if(r instanceof Response)return r;try{let n=await Ve(e);if(n instanceof Response)return n;let s=await n.startTransaction(r,ge(e)),o=lr(s,e);if(o instanceof Response)return o;let{id:a}=o,c=t.param("clientVersion"),i=t.param("schemaHash");return e.json({...s,"data-proxy":{endpoint:`${new URL(t.url).origin}/${c}/${i}/itx/${a}`}})}catch(n){return de(n,e)}});Qn=[["/connection-info","GET"],["/query","POST"],["/transaction/start","POST"],["/transaction/:transactionId/commit","POST"],["/transaction/:transactionId/query","POST"],["/transaction/:transactionId/rollback","POST"]];for(let[e,t]of Qn)Y.on(t,e,(0,k.validator)("header",B),async r=>{let n=r.req.header("prisma-engine-hash");if(n!=="0.0.0"&&n!==me.version)throw new dr.HTTPException(400,{message:`Using an HTTP connection string is not supported with Prisma Client version ${n} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${me.version}.`});return await(await er(r)).fetch(r.req.raw)})});var yr={};ct(yr,{utilityRoute:()=>ze});var fr,hr,ze,fo,Pr=T(()=>{"use strict";m();fr=require("hono/tiny"),hr=require("http-status-codes"),ze=new fr.Hono;ze.post("/database/dump",async e=>{let t=e.get("db"),r=e.get("databaseDumpPath");return await t.dump(r),e.json({dumpPath:r},hr.StatusCodes.CREATED)});fo=ze.get("/health",e=>e.json({name:e.get("name")}))});var Ss={};module.exports=zr(Ss);m();var Mr=require("timers/promises");m();m();he();m();var Ht=require("pathe/utils");H();m();var $=require("get-port-please"),ie=require("remeda"),we=51214,ve=51213,Ee=51215,Et=51216,ae=65535,G=0,x=-1/0;async function De(e){let{debug:t,name:r,requestedPorts:n,servers:s}=e,{portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a}=nn(r,s);t&&(console.debug(`ports used by other servers: ${Object.keys(o).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(a)}`));let c={databasePort:x,port:x,shadowDatabasePort:x,streamsPort:x},i=["port","databasePort","shadowDatabasePort","streamsPort"];for(let l of i){let u=await tn({debug:t,portKey:l,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a,requestedPorts:n})??await rn({debug:t,pickedPorts:c,portKey:l,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a});t&&console.debug(`Got port for "${l}": ${u}`),c[l]=u}return t&&console.debug(`Picked ports: ${JSON.stringify(c)}`),c}async function tn(e){let{debug:t,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s,requestedPorts:o}=e,{[r]:a,...c}=o;if(Re(a))return await an({debug:t,otherRequestedPorts:c,portKey:r,portsUsedByOtherServers:n,requestedPort:a}),a;let i=s?.[r]??x;if(!Re(i))return t&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let l=i in n;return l||Object.values(c).includes(i)?(t&&console.debug(`Port ${i} that was used last time for this server, ${l?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,$.checkPort)(i)===!1?(t&&console.debug(`Port ${i}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(t&&console.debug(`Using port ${i} for "${r}" as it was used last time and is available.`),i)}async function rn(e){let{debug:t,pickedPorts:r,portKey:n,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:o}=e,a=Math.max(we,ve,Ee,Et)+1,c=Object.values(r).filter(P=>P!==void 0),i=o?on(o):[],l=[...c,...Object.keys(s).map(Number),...i],u=Math.min(Math.max(a,...l)+100,ae),p=(0,ie.difference)((0,ie.range)(a,u),l),g={port:ve,databasePort:we,shadowDatabasePort:Ee,streamsPort:Et}[n];try{return await(0,$.getPort)({port:g in s||c.includes(g)||i.includes(g)?void 0:g,ports:p})}catch(P){if(P instanceof Error&&P.name==="GetPortError"&&u+1<=ae)return t&&console.debug(`Expanding port lookup to range [${u+1}, ${ae}].`),await(0,$.getPort)({portRange:[u+1,ae]});throw P}}function Re(e){return Number.isFinite(e)&&e>=0}function nn(e,t){let r={},n;for(let s of t){let{databasePort:o,port:a,shadowDatabasePort:c}=s,i=sn(s);if(s.name===e){n={databasePort:o,port:a,shadowDatabasePort:c,streamsPort:i};continue}r[o]=!0,r[a]=!0,r[c]=!0,Re(i)&&(r[i]=!0)}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}function sn(e){let t=e.experimental?.streams?.serverUrl;if(!t)return x;try{let r=Number(new URL(t).port);return Number.isInteger(r)&&r>0?r:x}catch{return x}}function on(e){return[e.port,e.databasePort,e.shadowDatabasePort,e.streamsPort]}async function an(e){let{debug:t,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:s,requestedPort:o}=e;if(o!==G){if(o in s)throw t&&console.error(`Port ${o} was requested for "${n}", but is already used by another server.`),new xe(o);if(Object.values(r).includes(o))throw t&&console.error(`Port ${o} was requested for "${n}", but also for another key.`),new Te(o);if((0,$.isUnsafePort)(o))throw t&&console.error(`Port ${o} was requested for "${n}", but is unsafe.`),new O(o);if(await(0,$.checkPort)(o)===!1)throw t&&console.error(`Port ${o} was requested for "${n}", but is not available.`),new O(o)}}var O=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},Te=class extends Error{constructor(r){super(`Port number \`${r}\` was requested twice. Please choose a different port for each service.`);this.port=r}name="PortRequestedTwiceError"},xe=class extends Error{constructor(r){super(`Port number \`${r}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=r}name="PortBelongsToAnotherServerError"};m();var j=require("fs"),C=require("fs/promises"),xt=require("module"),Dt=require("path"),M=require("url"),cn=(0,xt.createRequire)(f),ln=["initdb.wasm","pglite.data","pglite.wasm"],At={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"},un=[...ln.map(e=>({fileName:e,kind:"core",name:e})),...Object.entries(At).map(([e,t])=>({fileName:t,kind:"extension",name:e}))],le=new Map,dn=Symbol.for("@prisma/dev/bundled-pglite-runtime-asset-sources"),ce=null;async function Ae(){await bn();let e=_t();if(e)return await fn(e),await mn(e);let t=yn(),r=t.href,n=le.get(r);return n||(n=pn(t),le.set(r,n)),await n}async function mn(e){let t=`bundled:${e.wasmModule.href}:${e.fsBundle.href}`,r=le.get(t);return r||(r=gn(e),le.set(t,r)),await r}async function pn(e){let[t,r]=await Promise.all([(0,C.readFile)(new URL("pglite.data",e)),(0,C.readFile)(new URL("pglite.wasm",e))]),n=Ot();return{extensions:Object.fromEntries(Object.entries(At).map(([s,o])=>[s,new URL(o,e)])),fsBundle:new Blob([Uint8Array.from(t)]),wasmModule:await n.compile(r)}}async function gn(e){let[t,r]=await Promise.all([Tt(e.fsBundle),Tt(e.wasmModule)]),n=Ot();return{extensions:e.extensions,fsBundle:new Blob([Uint8Array.from(t)]),wasmModule:await n.compile(r)}}async function fn(e){if(e.initdbWasm.protocol!=="file:")return;let t=new URL("initdb.wasm",_e(new URL("./",e.initdbWasm))),r=(0,M.fileURLToPath)(t);(0,j.existsSync)(r)||await(0,C.copyFile)((0,M.fileURLToPath)(e.initdbWasm),r)}function _e(e){return e instanceof URL?Rt(e):Rt((0,M.pathToFileURL)(e))}function Rt(e){return e.href.endsWith("/")?e:new URL(`${e.href}/`)}function hn(){let e=cn.resolve("@electric-sql/pglite");return _e((0,Dt.dirname)(e))}function yn(){let e=_e(new URL("./",f));if(Pn(e))return e;if(Sn())return hn();throw new Error("Unable to locate PGlite runtime assets. If you bundled @prisma/dev, copy them next to the bundle with copyPrismaDevRuntimeAssets().")}function Pn(e){return un.every(t=>(0,j.existsSync)((0,M.fileURLToPath)(new URL(t.fileName,e))))}function _t(){return globalThis[dn]??null}async function bn(){!wn()||_t()||(ce||(ce=import("./runtime-assets-manifest.bun.js").then(()=>{}).catch(e=>{throw ce=null,e})),await ce)}function Sn(){let e=(0,M.fileURLToPath)(new URL("../package.json",f));if(!(0,j.existsSync)(e))return!1;try{return JSON.parse((0,j.readFileSync)(e,"utf8")).name==="@prisma/dev"}catch{return!1}}function wn(){return typeof globalThis.Bun<"u"}function Ot(){let e=globalThis.WebAssembly;if(!e)throw new Error("WebAssembly is not available in this runtime.");return e}async function Tt(e){if(e.protocol==="file:")return await(0,C.readFile)(e);let t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch runtime asset ${e.href}: ${t.status} ${t.statusText}`);return new Uint8Array(await t.arrayBuffer())}m();var Le=require("@electric-sql/pglite"),A="_prisma_dev_wal",Ie="events",$t="install_all_triggers",It="capture_event",Lt="prisma_dev_wal_capture",J=new WeakMap,vn=new Set(["ALTER","COMMIT","COPY","CREATE","DELETE","DROP","INSERT","MERGE","TRUNCATE","UPDATE"]);async function $e(e,t){let r=J.get(e);if(r&&!r.closed)return r.bridge;let n=e.execProtocolRaw.bind(e),s=e.execProtocolRawStream.bind(e),o={bridge:{close:async()=>{o.closed||(o.closed=!0,o.subscribers.clear(),e.execProtocolRaw===a&&(e.execProtocolRaw=n),e.execProtocolRawStream===c&&(e.execProtocolRawStream=s),await o.pollPromise,J.delete(e))},poll:async()=>{await Oe(o,e)},subscribe:i=>(o.subscribers.add(i),()=>{o.subscribers.delete(i)})},closed:!1,ensureInfrastructurePromise:null,pendingPoll:!1,pollPromise:null,subscribers:new Set,suppressDepth:0},a=async(i,l)=>{let u=await n(i,l);return!o.closed&&o.suppressDepth===0&&Bt(u)&&Oe(o,e),u},c=async(i,l)=>{let u=[],p=new Le.protocol.Parser,g=l?.onRawData;await s(i,{...l,onRawData:P=>{p.parse(P,R=>{u.push(R)}),g?.(P)}}),!o.closed&&o.suppressDepth===0&&Ne(u)&&Oe(o,e)};return e.execProtocolRaw=a,e.execProtocolRawStream=c,J.set(e,o),await Ct(o,e),o.bridge}async function Nt(e){let t=J.get(e);t&&await t.bridge.close()}function Ne(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&&vn.has(r))return!0}return!1}function Bt(e){if(e.length===0)return!1;let t=[];return new Le.protocol.Parser().parse(e,n=>{t.push(n)}),Ne(t)}async function Ct(e,t){e.ensureInfrastructurePromise??=Be(e,t,async()=>{await t.exec(`CREATE SCHEMA IF NOT EXISTS "${A}"`),await t.exec(`
|
|
14
|
-
CREATE TABLE IF NOT EXISTS "${A}"."${
|
|
13
|
+
`}function Kn(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}var je,fe,kn,cr=T(()=>{"use strict";m();je=require("buffer"),fe=new Map;kn=" "});function he(e){let{req:t}=e;return{traceparent:t.header("traceparent"),"X-capture-telemetry":t.header("X-capture-telemetry")}}var lr=T(()=>{"use strict";m()});async function ur(e){let{issues:t,output:r,success:n}=(0,h.safeParse)(zn,await e.req.json(),{abortEarly:!0});return n?r:e.json({EngineNotStarted:{reason:"InvalidRequest",issues:t}},400)}function dr(e,t){let{output:r,success:n}=(0,h.safeParse)(Jn,e);return n?r:t.json({EngineMalfunction:{}},500)}var h,zn,Jn,mr=T(()=>{"use strict";m();h=require("valibot"),zn=(0,h.object)({isolation_level:(0,h.optional)((0,h.string)()),max_wait:(0,h.pipe)((0,h.number)(),(0,h.integer)(),(0,h.minValue)(0)),timeout:(0,h.pipe)((0,h.number)(),(0,h.integer)(),(0,h.minValue)(0))});Jn=(0,h.looseObject)({id:(0,h.union)([(0,h.string)(),(0,h.number)()])})});var fr={};ut(fr,{accelerateRoute:()=>Y});async function ze(e){let{req:t}=e,r=or(e);if(r instanceof Response)return r;let{base64Override:n,overrideHash:s}=r.schemas;return await q.get({base64Schema:n,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||t.param("clientVersion"),debug:e.get("debug"),platform:e.get("platform"),schemaHash:s})}var pr,gr,M,Y,Qn,X,Yn,Xn,hr=T(()=>{"use strict";m();pr=require("hono/http-exception"),gr=require("hono/tiny"),M=require("hono/validator");Pe();tr();We();nr();cr();lr();mr();Y=new gr.Hono;Y.post("/invalidate",(0,M.validator)("header",B),async e=>{let t=await er(e);return t instanceof Response?t:e.body(null)});Qn="/:clientVersion/:schemaHash",X=Y.basePath(Qn);Y.route("/",X);Yn=["/graphql","/itx/:transactionId/graphql"];X.on("POST",[...Yn],(0,M.validator)("header",B),async e=>{let{req:t}=e;try{let r=await ze(e);if(r instanceof Response)return r;let n=await t.text(),s=t.param("transactionId"),o=await r.request(n,{...he(e),"X-transaction-id":s});return e.text(o)}catch(r){return pe(r,e)}});X.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,M.validator)("header",B),async e=>{let{req:t}=e;try{let r=await ze(e);if(r instanceof Response)return r;let s=`${t.routePath.split("/").filter(Boolean).at(-1)}Transaction`,o=t.param("transactionId"),a=await r[s](o,he(e));return e.json(a)}catch(r){return pe(r,e)}});X.put("/schema",(0,M.validator)("header",B),async e=>{let{req:t}=e,r=await t.text();if(!r)return e.text("Missing schema",400);let n=t.param("schemaHash"),s=fe.get(n);if(s==null){if(n!==await Fe(r))return e.text("Schema hash mismatch",400);let o=await ar(r,e.get("db").prismaORMConnectionString,e.get("debug"));return fe.set(n,{base64Original:r,...o}),e.text(n)}return r!==s.base64Original?e.text("Schema mismatch",400):e.text(n)});X.post("/transaction/start",(0,M.validator)("header",B),async e=>{let{req:t}=e,r=await ur(e);if(r instanceof Response)return r;try{let n=await ze(e);if(n instanceof Response)return n;let s=await n.startTransaction(r,he(e)),o=dr(s,e);if(o instanceof Response)return o;let{id:a}=o,c=t.param("clientVersion"),i=t.param("schemaHash");return e.json({...s,"data-proxy":{endpoint:`${new URL(t.url).origin}/${c}/${i}/itx/${a}`}})}catch(n){return pe(n,e)}});Xn=[["/connection-info","GET"],["/query","POST"],["/transaction/start","POST"],["/transaction/:transactionId/commit","POST"],["/transaction/:transactionId/query","POST"],["/transaction/:transactionId/rollback","POST"]];for(let[e,t]of Xn)Y.on(t,e,(0,M.validator)("header",B),async r=>{let n=r.req.header("prisma-engine-hash");if(n!=="0.0.0"&&n!==ge.version)throw new pr.HTTPException(400,{message:`Using an HTTP connection string is not supported with Prisma Client version ${n} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${ge.version}.`});return await(await rr(r)).fetch(r.req.raw)})});var br={};ut(br,{utilityRoute:()=>Je});var yr,Pr,Je,bo,Sr=T(()=>{"use strict";m();yr=require("hono/tiny"),Pr=require("http-status-codes"),Je=new yr.Hono;Je.post("/database/dump",async e=>{let t=e.get("db"),r=e.get("databaseDumpPath");return await t.dump(r),e.json({dumpPath:r},Pr.StatusCodes.CREATED)});bo=Je.get("/health",e=>e.json({name:e.get("name")}))});var Rs={};module.exports=Jr(Rs);m();var Ur=require("timers/promises");m();m();Pe();m();var jt=require("pathe/utils");H();m();var $=require("get-port-please"),le=require("remeda"),Ee=51214,Re=51213,Te=51215,Tt=51216,ce=65535,G=0,x=-1/0;async function _e(e){let{debug:t,name:r,requestedPorts:n,servers:s}=e,{portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a}=on(r,s);t&&(console.debug(`ports used by other servers: ${Object.keys(o).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(a)}`));let c={databasePort:x,port:x,shadowDatabasePort:x,streamsPort:x},i=["port","databasePort","shadowDatabasePort","streamsPort"];for(let l of i){let u=await nn({debug:t,portKey:l,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a,requestedPorts:n})??await sn({debug:t,pickedPorts:c,portKey:l,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a});t&&console.debug(`Got port for "${l}": ${u}`),c[l]=u}return t&&console.debug(`Picked ports: ${JSON.stringify(c)}`),c}async function nn(e){let{debug:t,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s,requestedPorts:o}=e,{[r]:a,...c}=o;if(xe(a))return await ln({debug:t,otherRequestedPorts:c,portKey:r,portsUsedByOtherServers:n,requestedPort:a}),a;let i=s?.[r]??x;if(!xe(i))return t&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let l=i in n;return l||Object.values(c).includes(i)?(t&&console.debug(`Port ${i} that was used last time for this server, ${l?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,$.checkPort)(i)===!1?(t&&console.debug(`Port ${i}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(t&&console.debug(`Using port ${i} for "${r}" as it was used last time and is available.`),i)}async function sn(e){let{debug:t,pickedPorts:r,portKey:n,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:o}=e,a=Math.max(Ee,Re,Te,Tt)+1,c=Object.values(r).filter(P=>P!==void 0),i=o?cn(o):[],l=[...c,...Object.keys(s).map(Number),...i],u=Math.min(Math.max(a,...l)+100,ce),p=(0,le.difference)((0,le.range)(a,u),l),g={port:Re,databasePort:Ee,shadowDatabasePort:Te,streamsPort:Tt}[n];try{return await(0,$.getPort)({port:g in s||c.includes(g)||i.includes(g)?void 0:g,ports:p})}catch(P){if(P instanceof Error&&P.name==="GetPortError"&&u+1<=ce)return t&&console.debug(`Expanding port lookup to range [${u+1}, ${ce}].`),await(0,$.getPort)({portRange:[u+1,ce]});throw P}}function xe(e){return Number.isFinite(e)&&e>=0}function on(e,t){let r={},n;for(let s of t){let{databasePort:o,port:a,shadowDatabasePort:c}=s,i=an(s);if(s.name===e){n={databasePort:o,port:a,shadowDatabasePort:c,streamsPort:i};continue}r[o]=!0,r[a]=!0,r[c]=!0,xe(i)&&(r[i]=!0)}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}function an(e){let t=e.experimental?.streams?.serverUrl;if(!t)return x;try{let r=Number(new URL(t).port);return Number.isInteger(r)&&r>0?r:x}catch{return x}}function cn(e){return[e.port,e.databasePort,e.shadowDatabasePort,e.streamsPort]}async function ln(e){let{debug:t,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:s,requestedPort:o}=e;if(o!==G){if(o in s)throw t&&console.error(`Port ${o} was requested for "${n}", but is already used by another server.`),new Ae(o);if(Object.values(r).includes(o))throw t&&console.error(`Port ${o} was requested for "${n}", but also for another key.`),new De(o);if((0,$.isUnsafePort)(o))throw t&&console.error(`Port ${o} was requested for "${n}", but is unsafe.`),new O(o);if(await(0,$.checkPort)(o)===!1)throw t&&console.error(`Port ${o} was requested for "${n}", but is not available.`),new O(o)}}var O=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},De=class extends Error{constructor(r){super(`Port number \`${r}\` was requested twice. Please choose a different port for each service.`);this.port=r}name="PortRequestedTwiceError"},Ae=class extends Error{constructor(r){super(`Port number \`${r}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=r}name="PortBelongsToAnotherServerError"};m();var j=require("fs"),C=require("fs/promises"),At=require("module"),_t=require("path"),k=require("url"),un=(0,At.createRequire)(f),dn=["initdb.wasm","pglite.data","pglite.wasm"],Ot={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"},mn=[...dn.map(e=>({fileName:e,kind:"core",name:e})),...Object.entries(Ot).map(([e,t])=>({fileName:t,kind:"extension",name:e}))],de=new Map,pn=Symbol.for("@prisma/dev/bundled-pglite-runtime-asset-sources"),ue=null;async function Oe(){await wn();let e=It();if(e)return await yn(e),await gn(e);let t=bn(),r=t.href,n=de.get(r);return n||(n=fn(t),de.set(r,n)),await n}async function gn(e){let t=`bundled:${e.wasmModule.href}:${e.fsBundle.href}`,r=de.get(t);return r||(r=hn(e),de.set(t,r)),await r}async function fn(e){let[t,r]=await Promise.all([(0,C.readFile)(new URL("pglite.data",e)),(0,C.readFile)(new URL("pglite.wasm",e))]),n=Lt();return{extensions:Object.fromEntries(Object.entries(Ot).map(([s,o])=>[s,new URL(o,e)])),fsBundle:new Blob([Uint8Array.from(t)]),wasmModule:await n.compile(r)}}async function hn(e){let[t,r]=await Promise.all([Dt(e.fsBundle),Dt(e.wasmModule)]),n=Lt();return{extensions:e.extensions,fsBundle:new Blob([Uint8Array.from(t)]),wasmModule:await n.compile(r)}}async function yn(e){if(e.initdbWasm.protocol!=="file:")return;let t=new URL("initdb.wasm",Ie(new URL("./",e.initdbWasm))),r=(0,k.fileURLToPath)(t);(0,j.existsSync)(r)||await(0,C.copyFile)((0,k.fileURLToPath)(e.initdbWasm),r)}function Ie(e){return e instanceof URL?xt(e):xt((0,k.pathToFileURL)(e))}function xt(e){return e.href.endsWith("/")?e:new URL(`${e.href}/`)}function Pn(){let e=un.resolve("@electric-sql/pglite");return Ie((0,_t.dirname)(e))}function bn(){let e=Ie(new URL("./",f));if(Sn(e))return e;if(vn())return Pn();throw new Error("Unable to locate PGlite runtime assets. If you bundled @prisma/dev, copy them next to the bundle with copyPrismaDevRuntimeAssets().")}function Sn(e){return mn.every(t=>(0,j.existsSync)((0,k.fileURLToPath)(new URL(t.fileName,e))))}function It(){return globalThis[pn]??null}async function wn(){!En()||It()||(ue||(ue=import("./runtime-assets-manifest.bun.js").then(()=>{}).catch(e=>{throw ue=null,e})),await ue)}function vn(){let e=(0,k.fileURLToPath)(new URL("../package.json",f));if(!(0,j.existsSync)(e))return!1;try{return JSON.parse((0,j.readFileSync)(e,"utf8")).name==="@prisma/dev"}catch{return!1}}function En(){return typeof globalThis.Bun<"u"}function Lt(){let e=globalThis.WebAssembly;if(!e)throw new Error("WebAssembly is not available in this runtime.");return e}async function Dt(e){if(e.protocol==="file:")return await(0,C.readFile)(e);let t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch runtime asset ${e.href}: ${t.status} ${t.statusText}`);return new Uint8Array(await t.arrayBuffer())}m();var Ne=require("@electric-sql/pglite"),A="_prisma_dev_wal",$e="events",Bt="install_all_triggers",$t="capture_event",Nt="prisma_dev_wal_capture",J=new WeakMap,Rn=new Set(["ALTER","COMMIT","COPY","CREATE","DELETE","DROP","INSERT","MERGE","TRUNCATE","UPDATE"]);async function Be(e,t){let r=J.get(e);if(r&&!r.closed)return r.bridge;let n=e.execProtocolRaw.bind(e),s=e.execProtocolRawStream.bind(e),o={bridge:{close:async()=>{o.closed||(o.closed=!0,o.subscribers.clear(),e.execProtocolRaw===a&&(e.execProtocolRaw=n),e.execProtocolRawStream===c&&(e.execProtocolRawStream=s),await o.pollPromise,J.delete(e))},poll:async()=>{await Le(o,e)},subscribe:i=>(o.subscribers.add(i),()=>{o.subscribers.delete(i)})},closed:!1,ensureInfrastructurePromise:null,pendingPoll:!1,pollPromise:null,subscribers:new Set,suppressDepth:0},a=async(i,l)=>{let u=await n(i,l);return!o.closed&&o.suppressDepth===0&&kt(u)&&Le(o,e),u},c=async(i,l)=>{let u=[],p=new Ne.protocol.Parser,g=l?.onRawData;await s(i,{...l,onRawData:P=>{p.parse(P,R=>{u.push(R)}),g?.(P)}}),!o.closed&&o.suppressDepth===0&&Ce(u)&&Le(o,e)};return e.execProtocolRaw=a,e.execProtocolRawStream=c,J.set(e,o),await Mt(o,e),o.bridge}async function Ct(e){let t=J.get(e);t&&await t.bridge.close()}function Ce(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&&Rn.has(r))return!0}return!1}function kt(e){if(e.length===0)return!1;let t=[];return new Ne.protocol.Parser().parse(e,n=>{t.push(n)}),Ce(t)}async function Mt(e,t){e.ensureInfrastructurePromise??=ke(e,t,async()=>{await t.exec(`CREATE SCHEMA IF NOT EXISTS "${A}"`),await t.exec(`
|
|
14
|
+
CREATE TABLE IF NOT EXISTS "${A}"."${$e}" (
|
|
15
15
|
id BIGSERIAL PRIMARY KEY,
|
|
16
16
|
txid BIGINT NOT NULL DEFAULT txid_current(),
|
|
17
17
|
schema_name TEXT NOT NULL,
|
|
@@ -22,7 +22,7 @@ Received data: ${u}`));n({childProcess:a,url:`http://${P}:${R}`})},i=u=>{this.#t
|
|
|
22
22
|
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()
|
|
23
23
|
)
|
|
24
24
|
`),await t.exec(`
|
|
25
|
-
CREATE OR REPLACE FUNCTION "${A}"."${
|
|
25
|
+
CREATE OR REPLACE FUNCTION "${A}"."${$t}"()
|
|
26
26
|
RETURNS trigger
|
|
27
27
|
LANGUAGE plpgsql
|
|
28
28
|
AS $$
|
|
@@ -31,7 +31,7 @@ Received data: ${u}`));n({childProcess:a,url:`http://${P}:${R}`})},i=u=>{this.#t
|
|
|
31
31
|
RETURN COALESCE(NEW, OLD);
|
|
32
32
|
END IF;
|
|
33
33
|
|
|
34
|
-
INSERT INTO "${A}"."${
|
|
34
|
+
INSERT INTO "${A}"."${$e}" (
|
|
35
35
|
txid,
|
|
36
36
|
schema_name,
|
|
37
37
|
table_name,
|
|
@@ -52,7 +52,7 @@ Received data: ${u}`));n({childProcess:a,url:`http://${P}:${R}`})},i=u=>{this.#t
|
|
|
52
52
|
END;
|
|
53
53
|
$$;
|
|
54
54
|
`),await t.exec(`
|
|
55
|
-
CREATE OR REPLACE FUNCTION "${A}"."${
|
|
55
|
+
CREATE OR REPLACE FUNCTION "${A}"."${Bt}"()
|
|
56
56
|
RETURNS void
|
|
57
57
|
LANGUAGE plpgsql
|
|
58
58
|
AS $$
|
|
@@ -72,28 +72,28 @@ Received data: ${u}`));n({childProcess:a,url:`http://${P}:${R}`})},i=u=>{this.#t
|
|
|
72
72
|
SELECT 1
|
|
73
73
|
FROM pg_trigger
|
|
74
74
|
WHERE tgrelid = target
|
|
75
|
-
AND tgname = '${
|
|
75
|
+
AND tgname = '${Nt}'
|
|
76
76
|
) THEN
|
|
77
77
|
CONTINUE;
|
|
78
78
|
END IF;
|
|
79
79
|
|
|
80
80
|
EXECUTE format(
|
|
81
|
-
'CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION "${A}"."${
|
|
82
|
-
'${
|
|
81
|
+
'CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION "${A}"."${$t}"()',
|
|
82
|
+
'${Nt}',
|
|
83
83
|
target::text
|
|
84
84
|
);
|
|
85
85
|
END LOOP;
|
|
86
86
|
END;
|
|
87
87
|
$$;
|
|
88
|
-
`),await
|
|
88
|
+
`),await Ut(e,t)}),await e.ensureInfrastructurePromise}async function Ut(e,t){await ke(e,t,async()=>{await t.query(`SELECT "${A}"."${Bt}"()`)})}async function Tn(e,t){await Mt(e,t),await Ut(e,t);let r=await ke(e,t,async()=>await t.query(`
|
|
89
89
|
WITH drained AS (
|
|
90
|
-
DELETE FROM "${A}"."${
|
|
90
|
+
DELETE FROM "${A}"."${$e}"
|
|
91
91
|
RETURNING txid, schema_name, table_name, op, row_data, old_row_data, id
|
|
92
92
|
)
|
|
93
93
|
SELECT txid, schema_name, table_name, op, row_data, old_row_data
|
|
94
94
|
FROM drained
|
|
95
95
|
ORDER BY id
|
|
96
|
-
`));if(r.rows.length===0||e.subscribers.size===0)return;let n=r.rows.map(
|
|
96
|
+
`));if(r.rows.length===0||e.subscribers.size===0)return;let n=r.rows.map(xn);for(let s of e.subscribers)queueMicrotask(()=>{if(!e.closed&&e.subscribers.has(s))try{s(n)}catch(o){console.error("[WAL bridge] subscriber failed",o)}})}async function Le(e,t){if(!e.closed){if(e.pollPromise){e.pendingPoll=!0,await e.pollPromise;return}e.pollPromise=(async()=>{do e.pendingPoll=!1,await Tn(e,t);while(e.pendingPoll&&!e.closed)})().finally(()=>{e.pollPromise=null}),await e.pollPromise}}async function ke(e,t,r){e.suppressDepth+=1;try{return await r()}finally{e.suppressDepth-=1,e.suppressDepth===0&&!e.closed&&J.get(t)!==e&&(e.closed=!0)}}function xn(e){return{oldRecord:e.old_row_data,record:e.row_data,schema:e.schema_name,table:e.table_name,txid:String(e.txid),type:Dn(e.op)}}function Dn(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 An=10,S={connectionLimit:An,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},_n=`postgres://${S.username}:${S.password}@localhost`,Ft=new URLSearchParams({sslmode:S.sslMode}),On=new URLSearchParams({...Object.fromEntries(Ft.entries()),connection_limit:String(S.connectionLimit),connect_timeout:String(S.connectTimeout),max_idle_connection_lifetime:String(S.maxIdleConnectionLifetime),pool_timeout:String(S.poolTimeout),socket_timeout:String(S.socketTimeout)});async function qt(e){let{rows:t}=await e.query("SELECT EXISTS(SELECT 1 FROM pg_roles WHERE rolname = 'postgres') AS exists");t[0]?.exists?await e.exec(`ALTER ROLE ${S.username} WITH LOGIN SUPERUSER PASSWORD '${S.password}'`):await e.exec(`CREATE ROLE ${S.username} WITH LOGIN SUPERUSER PASSWORD '${S.password}'`),await e.exec(`SET ROLE ${S.username}`)}async function Me(e,t){let r=e==="database"?t.databasePort:t.shadowDatabasePort;if(t.dryRun)return Wt(e,t,{db:null,port:r,server:null});let{debug:n}=t,o=await(e==="shadow_database"?In:Vt)(t.pgliteDataDirPath,n);n&&o.onNotification((u,p)=>{console.debug(`[${e}][${u}] ${p}`)});let{PGLiteSocketServer:a}=await import("@electric-sql/pglite-socket"),c=e==="shadow_database"?t.shadowDatabaseIdleTimeoutMillis:t.databaseIdleTimeoutMillis,i=new a({db:o,debug:n,idleTimeout:Number.isFinite(c)?c:0,inspect:n,maxConnections:S.connectionLimit,port:r});n&&(i.addEventListener("listening",u=>{let{detail:p}=u;console.debug(`[${e}] server listening on ${JSON.stringify(p)}`)}),i.addEventListener("connection",u=>{let{clientAddress:p,clientPort:g}=u.detail;console.debug(`[${e}] client connected from ${p}:${g}`)}),i.addEventListener("error",u=>{let{detail:p}=u;console.error(`[${e}] server error:`,p)}));try{await i.start()}catch(u){throw u instanceof Error&&"code"in u&&u.code==="EADDRINUSE"?new O(r):u}let l=Number(i.getServerConn().split(":").at(1));return t[e==="database"?"databasePort":"shadowDatabasePort"]=l,Wt(e,t,{db:o,port:l,server:i})}function Wt(e,t,r){let{debug:n}=t,{db:s,port:o,server:a}=r||{},c=new Map;return n&&console.debug(`[${e}] server started on port ${o}`),{...S,attachWalEventBridge:async()=>{if(e!=="database"||!s)throw new Error("WAL bridge is only available for the primary database server");return await Be(s)},close:async()=>{let i=[];try{await a?.stop(),n&&console.debug(`[${e}] server stopped on port ${o}`)}catch(l){console.error(`[${e}] server stop error`,l),i.push(l)}if(e==="database"){try{s&&await Ct(s),n&&console.debug(`[${e}] closed WAL bridge`)}catch(l){console.error(`[${e}] WAL bridge close error`,l),i.push(l)}try{await s?.syncToFs(),n&&console.debug(`[${e}] synced to filesystem`)}catch(l){console.error(`[${e}] sync error`,l),i.push(l)}}try{await s?.close(),n&&console.debug(`[${e}] closed`)}catch(l){console.error(`[${e}] close error`,l),i.push(l)}if(i.length>0)throw new AggregateError(i,`Failed to close ${e} properly`)},connectionString:Ht(o,Ft),dump:async i=>{e==="shadow_database"||!s||await $n({db:s,debug:n,destinationPath:i})},getPrimaryKeyColumns:async(i,l)=>{if(e==="shadow_database"||!s)throw new Error("Primary key resolution is only available for the primary database server");let u=`${i}.${l}`,p=c.get(u);return p||(p=Ln(s,i,l).catch(g=>{throw c.delete(u),g}),c.set(u,p)),await p},port:o,prismaORMConnectionString:Ht(o,On),terminalCommand:`PGPASSWORD=${S.password} PGSSLMODE=${S.sslMode} psql -h localhost -p ${o} -U ${S.username} -d ${S.database}`}}function Ht(e,t){return`${_n}:${e}/${S.database}?${t.toString()}`}async function Vt(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await Oe(),s=await r.create({database:S.database,dataDir:e,debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,relaxedDurability:!1,wasmModule:n.wasmModule});return await qt(s),s}async function In(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await Oe(),s=await r.create({database:S.database,dataDir:"memory://",debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,relaxedDurability:!1,wasmModule:n.wasmModule});return await qt(s),s}async function Ln(e,t,r){let{rows:n}=await e.query(`
|
|
97
97
|
SELECT attribute.attname AS column_name
|
|
98
98
|
FROM pg_constraint pk_constraint
|
|
99
99
|
INNER JOIN pg_class relation
|
|
@@ -106,9 +106,9 @@ Received data: ${u}`));n({childProcess:a,url:`http://${P}:${R}`})},i=u=>{this.#t
|
|
|
106
106
|
ON attribute.attrelid = relation.oid
|
|
107
107
|
AND attribute.attnum = keys.attnum
|
|
108
108
|
WHERE pk_constraint.contype = 'p'
|
|
109
|
-
AND namespace.nspname = ${
|
|
110
|
-
AND relation.relname = ${
|
|
109
|
+
AND namespace.nspname = ${Gt(t)}
|
|
110
|
+
AND relation.relname = ${Gt(r)}
|
|
111
111
|
ORDER BY keys.ordinality
|
|
112
|
-
`);return n.map(s=>s.column_name)}function
|
|
113
|
-
${JSON.stringify(c,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new ee({databasePort:i.databasePort,debug:r,dryRun:!1,name:n,pid:i.pid,port:i.port,serverDump:i,shadowDatabasePort:i.shadowDatabasePort})}static async scan(t){let{debug:r,globs:n}=t??{},s=(0,U.join)(
|
|
114
|
-
`,{encoding:"utf-8"})}};async function ss(e,t){let{debug:r,onlyMetadata:n}=t||{},s=typeof e=="string"?e:e.name,o=typeof e!="string"?e:void 0,a={databasePort:o?.databasePort??-1,experimental:o?.experimental,exports:o?.exports,name:s,pid:o?.pid,port:o?.port??-1,shadowDatabasePort:o?.shadowDatabasePort??-1,version:"1"};try{let c=o||await _.fromServerDump({debug:r,name:s});if(!c)return r&&console.debug(`[State] no server state found for name: ${s}`),{...a,status:"no_such_server"};a.databasePort=c.databasePort,a.experimental=c.experimental,a.exports=c.exports,a.pid=c.pid,a.port=c.port,a.shadowDatabasePort=c.shadowDatabasePort;let{exports:i,pid:l}=c;if(n)return{...a,status:"unknown"};if(!Tr(l,r))return r&&console.debug(`[State] server state for "${s}" has no running process with PID: ${l}`),{...a,status:"not_running"};let u=z(s);try{if(!await(0,V.check)(u,{lockfilePath:(0,U.join)(u,".lock")}))return r&&console.debug(`[State] server state for "${s}" is not locked, indicating it is not running.`),{...a,status:"not_running"}}catch(D){r&&console.error(`[State] server state for "${s}" failed to check lock:`,D)}if(!i)return{...a,status:"starting_up"};let{http:p}=i,{hc:g}=await import("hono/client"),P=await g(p.url).health.$get();if(!P.ok)return r&&console.debug(`[State] server state for "${s}" is not live: ${JSON.stringify(P)}`),{...a,status:"not_running"};let R=await P.json();return R.name!==e?(r&&console.debug(`[State] server state for "${s}" has mismatched health response: ${JSON.stringify(R)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${e}" is live: ${JSON.stringify(R)}`),{...a,status:"running"})}catch(c){return r&&console.error(`[State] failed to get server status for "${s}":`,c),{...a,status:"error"}}}var et=class extends Error{name="ServerStateAlreadyExistsError";constructor(t){super(`A Prisma Dev server with the name "${t}" is already running.`)}},fe=class extends et{#r;name="ServerAlreadyRunningError";constructor(t){super(t.name),this.#r=t}get server(){return _.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};m();var Ir=require("crypto"),nt=require("timers/promises"),Lr=require("std-env");H();var os="application/json",st={connection:"close","content-type":os},as={interpreter:{apiVersion:"durable.streams/stream-interpreter/v1",format:"durable.streams/state-protocol/v1",touch:{enabled:!0,onMissingBefore:"coarse"}}};async function $r(e){let{dbServer:t,debug:r,name:n,persistenceMode:s,port:o,walBridge:a}=e,c=s==="stateless",i=c?ms(n):n;Lr.process.env.DS_LOCAL_DATA_ROOT=Qe(),c&&await K(Z(i));let{startLocalDurableStreamsServer:l}=await import("@prisma/streams-local"),u=await l({hostname:"127.0.0.1",name:i,port:o}),p={serverUrl:u.exports.http.url,sqlitePath:u.exports.sqlite.path,streamName:Je,url:xr(u.exports.http.url)};try{await is(p);let g=new ot({dbServer:t,debug:r,streamUrl:p.url}),P=a.subscribe(R=>{g.enqueue(R)});return{close:async()=>{P(),await g.close(),await u.close(),await(0,nt.setTimeout)(100),c&&await K(Z(i))},experimental:p}}catch(g){throw await u.close().catch(()=>{}),await(0,nt.setTimeout)(100),c&&await K(Z(i)).catch(()=>{}),g}}var ot=class{#r;#e;#t;#s;#o;constructor(t){this.#r=t.dbServer,this.#e=t.debug,this.#t=Promise.resolve(),this.#s=t.streamUrl,this.#o=new Set}enqueue(t){t.length!==0&&(this.#t=this.#t.then(async()=>{let r=await this.#a(t);r.length!==0&&(await cs(this.#s,r),this.#e&&console.debug(`[streams] appended ${r.length} state-protocol record(s) to ${this.#s}`))}).catch(r=>{console.error("[streams] failed to ingest WAL events into prisma-wal",r)}))}async close(){await this.#t}async#a(t){let r=[],n=new Date().toISOString();for(let s of t)r.push(...await this.#n(s,n));return r}async#n(t,r){let n=`${t.schema}.${t.table}`,s=await this.#r.getPrimaryKeyColumns(t.schema,t.table),o=Or(t.record),a=Or(t.oldRecord),c=this.#i(n,s,a),i=this.#i(n,s,o),l=t.txid===""?void 0:t.txid;return t.type==="insert"?o&&i?[{headers:{operation:"insert",timestamp:r,txid:l},key:i,oldValue:null,type:n,value:o}]:[]:t.type==="delete"?a&&c?[{headers:{operation:"delete",timestamp:r,txid:l},key:c,oldValue:a,type:n,value:null}]:[]:!o||!a||!c||!i?[]:c!==i?[{headers:{operation:"delete",timestamp:r,txid:l},key:c,oldValue:a,type:n,value:null},{headers:{operation:"insert",timestamp:r,txid:l},key:i,oldValue:null,type:n,value:o}]:[{headers:{operation:"update",timestamp:r,txid:l},key:i,oldValue:a,type:n,value:o}]}#i(t,r,n){if(!n)return null;let s=ls(n,r);return s||(this.#o.has(t)||(this.#o.add(t),console.warn(`[streams] falling back to full-row keys for ${t} because no primary key could be resolved`)),us(n))}};async function is(e){let t=await fetch(e.url,{headers:st,method:"PUT"});if(!t.ok)throw await at(t,`Failed to create ${e.streamName}`);let r=await fetch(`${e.url}/_schema`,{body:JSON.stringify(as),headers:st,method:"POST"});if(!r.ok)throw await at(r,`Failed to configure ${e.streamName}`)}async function cs(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:st,method:"POST"});if(!r.ok)throw await at(r,"Failed to append to prisma-wal")}async function at(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}function ls(e,t){if(t.length===0)return null;let r=[];for(let n of t){if(!Object.prototype.hasOwnProperty.call(e,n))return null;let s=ds(e[n]);if(s==null)return null;r.push(t.length===1?s:`${n}=${s}`)}return r.join("|")}function us(e){return JSON.stringify(it(e))}function it(e){return Array.isArray(e)?e.map(t=>it(t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,it(r)])):e}function Or(e){return e?structuredClone(e):null}function ds(e){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return e;if(typeof e=="number")return Number.isFinite(e)?String(e):null;if(typeof e=="bigint")return e.toString();if(typeof e=="boolean")return e?"true":"false";try{return JSON.stringify(e)}catch{return null}}function ms(e){return`${e}.${(0,Ir.randomUUID)().replaceAll("-","")}`}async function Nr(e){let t=await _.createExclusively(e),r=null,n=null,s=null,o=null;try{[r,s]=await Promise.all([Ce("database",t),Ce("shadow_database",t)]);let a;t.dryRun?(a=hs(),o=ys()):(a=await r.attachWalEventBridge(),o=await $r({dbServer:r,debug:t.debug,name:t.name,port:t.streamsPort,persistenceMode:t.persistenceMode,walBridge:a})),n=await Er(r,t);let c=ps(r,s,n,t);await t.writeServerDump(c,t.dryRun?{}:{streams:o.experimental});let i=fs(a),l=r,u=s,p=n,g=o,P=async()=>{i.close(),await Br(t,[p,g,l,u])};return{close:P,dbServer:r,httpServer:n,server:{...c,close:P,experimental:{streams:o.experimental,wal:i.api},name:t.name},serverState:t,shadowDbServer:s,streamsServer:o,walBridge:a}}catch(a){return await gs(t,[n,o,r,s],a)}}function ps(e,t,r,n){let s=`prisma+postgres://localhost:${r.port}/?${new URLSearchParams({api_key:dt({databaseUrl:e.prismaORMConnectionString,name:n.name,shadowDatabaseUrl:t.prismaORMConnectionString})}).toString()}`;return{database:{connectionString:e.connectionString,prismaORMConnectionString:e.prismaORMConnectionString,terminalCommand:e.terminalCommand},http:{url:r.url},ppg:{url:s},shadowDatabase:{connectionString:t.prismaORMConnectionString,prismaORMConnectionString:t.prismaORMConnectionString,terminalCommand:t.terminalCommand}}}async function Br(e,t){let n=(await Promise.allSettled(t.map(s=>s.close()))).filter(s=>s.status==="rejected").map(s=>new Error(s.reason));try{await e.close()}catch(s){n.push(s)}if(n.length>0)throw new AggregateError(n,"Failed to close some servers")}async function gs(e,t,r){try{await Br(e,t.filter(n=>n!==null))}catch(n){throw new AggregateError([r,n],"Failed to start Prisma Dev server cleanly")}throw r}function fs(e){let t=new Set;return{api:{stream:()=>{let r=()=>{},n=Ps(e,()=>{t.delete(r)});return r=()=>n.close(),t.add(r),n.stream},subscribe:r=>e.subscribe(r)},close:()=>{for(let r of[...t])r();t.clear()}}}function hs(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function ys(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function Ps(e,t){let r=[],n=!1,s=null,o=e.subscribe(c=>{if(!n){if(s){let i=s;s=null,i.resolve({done:!1,value:c});return}r.push(c)}}),a=()=>{if(!n&&(n=!0,o(),r.length=0,t(),s)){let c=s;s=null,c.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((c,i)=>{s={reject:i,resolve:c}})},return(){return a(),Promise.resolve({done:!0,value:void 0})},throw(c){let i=s;return a(),i&&i.reject(c),Promise.reject(c instanceof Error?c:new Error(String(c)))}}}}async function Cr(e){let{server:t}=await Nr(e);return t}var I;process.once("SIGTERM",()=>{console.log("SIGTERM received, shutting down..."),process.removeAllListeners("SIGINT"),process.exitCode=143,I?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{console.log("SIGINT received, shutting down..."),process.removeAllListeners("SIGTERM"),process.exitCode=130,I?.close().finally(()=>process.exit())});async function bs(){let[,,e]=process.argv;if(!e)return process.send?.({type:"error",error:'Missing "name" argument, server cannot be started'},void 0),process.exit(1);try{I=await Cr({debug:!0,persistenceMode:"stateful",name:e});let t={database:I.database,experimental:{streams:I.experimental.streams},http:I.http,name:I.name,ppg:I.ppg,shadowDatabase:I.shadowDatabase};process.send?.({type:"started",server:t},void 0)}catch(t){console.error(t);let r=t instanceof Error?t.message:String(t);process.send?.({type:"error",error:r},void 0),await(0,Mr.setTimeout)(1e3),process.exit(1)}}bs();
|
|
112
|
+
`);return n.map(s=>s.column_name)}function Gt(e){return`'${e.replaceAll("'","''")}'`}async function $n(e){let{dataDir:t,db:r,debug:n,destinationPath:s}=e,o=r||await Vt(t,n),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),c=await a({args:["--schema-only","--no-owner"],fileName:s?(0,jt.filename)(s):void 0,pg:await o.clone()});return s?(n&&console.debug(`[DB] Dumping database to ${s}`),await wt(c,s)):(n&&console.debug("[DB] Dumping database to memory"),await c.text())}m();var vr=require("http"),Er=require("util"),Rr=w(require("@prisma/get-platform"),1);Ue();We();async function Tr(e,t){let{port:r}=t;if(t.dryRun)return wr(r,null);let n=await Zn(e,t),{promise:s,reject:o,resolve:a}=me(),{serve:c}=await import("@hono/node-server"),i=c({createServer:vr.createServer,fetch:n.fetch,overrideGlobalObjects:!1,port:r},a);i.on("error",u=>{if(typeof u=="object"&&"code"in u&&u.code==="EADDRINUSE")return o(new O(r));console.error("[Accelerate]",u)});let{port:l}=await s;return t.port=l,wr(l,i)}function wr(e,t){return{async close(){t&&await Promise.allSettled([(0,Er.promisify)(t.close.bind(t))(),q.stopAll()])},port:e,url:`http://localhost:${e}`}}async function Zn(e,t){let{debug:r}=t,[{Hono:n},{accelerateRoute:s},{utilityRoute:o}]=await Promise.all([import("hono/tiny"),Promise.resolve().then(()=>(hr(),fr)),Promise.resolve().then(()=>(Sr(),br))]),a=new n,c=await Rr.default.getPlatformInfo();if(r&&console.debug("[Accelerate] platform info: %s",JSON.stringify(c)),r){let{logger:l}=await import("hono/logger");a.use("*",l((...u)=>console.log("[Accelerate]",...u)))}a.use("*",async(l,u)=>(l.set("databaseDumpPath",t.databaseDumpPath),l.set("db",e),l.set("debug",!!r),l.set("name",t.name),l.set("platform",c),l.set("shadowDBPort",t.shadowDatabasePort),await u()));let i=new n;return i.route("/",s),i.route("/",o),a.route("/",i),a}m();var Ir=require("fs/promises"),U=require("pathe"),V=require("proper-lockfile"),nt=require("std-env"),d=require("valibot");H();m();var es=require("timers/promises"),xr=require("std-env");function Dr(e,t){if(e==null)return!1;try{return xr.process.kill?.(e,0)??!0}catch(r){return t&&console.error(`Error checking if process with PID ${e} exists:`,r),!1}}m();var Qe=require("pathe");H();var Ye="prisma-wal";function Xe(){return(0,Qe.join)(ie.data,"durable-streams")}function Z(e){return(0,Qe.join)(Xe(),e)}function Ar(e,t=Ye){return new URL(`/v1/stream/${encodeURIComponent(t)}`,e).toString()}var te=(0,d.pipe)((0,d.string)(),(0,d.url)()),_r=(0,d.object)({connectionString:te,prismaORMConnectionString:(0,d.optional)(te),terminalCommand:(0,d.optional)((0,d.string)())}),Or=(0,d.object)({url:te}),ts=(0,d.object)({serverUrl:te,sqlitePath:(0,d.pipe)((0,d.string)(),(0,d.minLength)(1)),streamName:(0,d.pipe)((0,d.string)(),(0,d.minLength)(1)),url:te}),rs=(0,d.object)({streams:(0,d.optional)(ts)}),Ze=(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(1)),ns=(0,d.object)({database:_r,http:Or,ppg:Or,shadowDatabase:_r}),ss=(0,d.object)({databasePort:Ze,experimental:(0,d.optional)(rs),exports:(0,d.optional)(ns),name:(0,d.pipe)((0,d.string)(),(0,d.minLength)(1)),pid:(0,d.optional)((0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(0))),port:Ze,shadowDatabasePort:Ze,version:(0,d.literal)("1")}),st=Symbol("initialize"),et="default",os=new Set(["durable-streams"]),_=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;_streamsPort;constructor(t){this._databasePort=t.databasePort??x,this.databaseConnectTimeoutMillis=t.databaseConnectTimeoutMillis??6e4,this.databaseIdleTimeoutMillis=t.databaseIdleTimeoutMillis??1/0,this.debug=t.debug??!1,this.dryRun=t.dryRun??!1,this.name=t.name??et,this.persistenceMode=t.persistenceMode,this.pid=t.pid??nt.process.pid,this.shadowDatabaseConnectTimeoutMillis=t.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=t.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=t.port??x,this._shadowDatabasePort=t.shadowDatabasePort??x,this._streamsPort=x}static async createExclusively(t){let r=t?.dryRun!==!0&&t?.persistenceMode==="stateful"?new ee(t):new tt(t);return await r[st](),r}static async fromServerDump(t){let{debug:r,name:n=et}=t??{},s=K(n),o=ee.getServerDumpPath(s),a=await vt(o);if(a==null)return r&&console.debug(`[State] No server dump file found at: ${o}`),null;r&&(console.debug(`[State] server dump file found at "${o}":`),console.debug(a));let{issues:c,output:i,success:l}=(0,d.safeParse)((0,d.pipe)((0,d.string)(),(0,d.parseJson)(),ss),a);if(!l)throw r&&console.debug(`[State] Invalid server dump file at "${o}":
|
|
113
|
+
${JSON.stringify(c,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new ee({databasePort:i.databasePort,debug:r,dryRun:!1,name:n,pid:i.pid,port:i.port,serverDump:i,shadowDatabasePort:i.shadowDatabasePort})}static async scan(t){let{debug:r,globs:n}=t??{},s=(0,U.join)(K(et),"..");r&&console.debug(`[State] scanning for server states in: ${s}`);let o=(await Rt(s,n)).filter(a=>!os.has(a));return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(a=>as(a,t)))}get databasePort(){return this._databasePort}set databasePort(t){this.#r("databasePort",t)}get port(){return this._port}set port(t){this.#r("port",t)}get shadowDatabasePort(){return this._shadowDatabasePort}get streamsPort(){return this._streamsPort}set shadowDatabasePort(t){this.#r("shadowDatabasePort",t)}#r(t,r){if(r<0||!Number.isInteger(r))throw new Error(`Invalid port number: ${r}`);let n=`_${t}`;if(this[n]!==G&&this[n]!==r)throw new Error(`\`${t}\` is already set to ${this[n]}, cannot change it to ${r}`);this[n]=r}},tt=class extends _{constructor(t){super({...t,databasePort:t?.databasePort||G,persistenceMode:"stateless",port:t?.port||G,shadowDatabasePort:t?.shadowDatabasePort||G})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[st](){let t;try{t=await _.scan({debug:this.debug,onlyMetadata:!0})}catch(n){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",n),t=[]}let r=await _e({debug:this.debug,name:this.dryRun?this.name:"",requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:t});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,this._streamsPort=r.streamsPort}async close(){}async writeServerDump(){}},ee=class e extends _{#r;#e;#t;#s;#o;#a;#n;constructor(t){super({...t,persistenceMode:"stateful"}),this.#a=!1,this.#e=K(this.name),this.#r=(0,U.join)(this.#e,"db_dump.bak"),this.#t=(0,U.join)(this.#e,".lock"),this.#s=(0,U.join)(this.#e,".pglite"),this.#n=t?.serverDump??null,this.#o=e.getServerDumpPath(this.#e)}static getServerDumpPath(t){return(0,U.join)(t,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#n?.exports}get experimental(){return this.#n?.experimental}get pgliteDataDirPath(){return this.#s}async[st](){await Et(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,V.lock)(this.#e,{lockfilePath:this.#t}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let t=await _.scan({debug:this.debug,onlyMetadata:!0}),r=await _e({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:t});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,this._streamsPort=r.streamsPort,await this.writeServerDump()}catch(t){throw t instanceof Error&&"code"in t&&t.code==="ELOCKED"?new ye(this):t}}async close(){if(!this.#a)try{await(0,V.unlock)(this.#e,{lockfilePath:this.#t}),this.#a=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(t){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,t),t}}async writeServerDump(t,r){this.#n={name:this.name,version:"1",pid:nt.process.pid,port:this.port,databasePort:this.databasePort,experimental:r,shadowDatabasePort:this.shadowDatabasePort,exports:t},await(0,Ir.writeFile)(this.#o,`${JSON.stringify(this.#n,null,2)}
|
|
114
|
+
`,{encoding:"utf-8"})}};async function as(e,t){let{debug:r,onlyMetadata:n}=t||{},s=typeof e=="string"?e:e.name,o=typeof e!="string"?e:void 0,a={databasePort:o?.databasePort??-1,experimental:o?.experimental,exports:o?.exports,name:s,pid:o?.pid,port:o?.port??-1,shadowDatabasePort:o?.shadowDatabasePort??-1,version:"1"};try{let c=o||await _.fromServerDump({debug:r,name:s});if(!c)return r&&console.debug(`[State] no server state found for name: ${s}`),{...a,status:"no_such_server"};a.databasePort=c.databasePort,a.experimental=c.experimental,a.exports=c.exports,a.pid=c.pid,a.port=c.port,a.shadowDatabasePort=c.shadowDatabasePort;let{exports:i,pid:l}=c;if(n)return{...a,status:"unknown"};if(!Dr(l,r))return r&&console.debug(`[State] server state for "${s}" has no running process with PID: ${l}`),{...a,status:"not_running"};let u=K(s);try{if(!await(0,V.check)(u,{lockfilePath:(0,U.join)(u,".lock")}))return r&&console.debug(`[State] server state for "${s}" is not locked, indicating it is not running.`),{...a,status:"not_running"}}catch(D){r&&console.error(`[State] server state for "${s}" failed to check lock:`,D)}if(!i)return{...a,status:"starting_up"};let{http:p}=i,{hc:g}=await import("hono/client"),P=await g(p.url).health.$get();if(!P.ok)return r&&console.debug(`[State] server state for "${s}" is not live: ${JSON.stringify(P)}`),{...a,status:"not_running"};let R=await P.json();return R.name!==e?(r&&console.debug(`[State] server state for "${s}" has mismatched health response: ${JSON.stringify(R)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${e}" is live: ${JSON.stringify(R)}`),{...a,status:"running"})}catch(c){return r&&console.error(`[State] failed to get server status for "${s}":`,c),{...a,status:"error"}}}var rt=class extends Error{name="ServerStateAlreadyExistsError";constructor(t){super(`A Prisma Dev server with the name "${t}" is already running.`)}},ye=class extends rt{#r;name="ServerAlreadyRunningError";constructor(t){super(t.name),this.#r=t}get server(){return _.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};m();var $r=require("crypto"),ot=require("timers/promises"),at=require("util"),Nr=require("std-env");H();var is="application/json",re={connection:"close","content-type":is},cs={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},it={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(e){let{dbServer:t,debug:r,name:n,persistenceMode:s,port:o,walBridge:a}=e,c=s==="stateless",i=c?hs(n):n;Nr.process.env.DS_LOCAL_DATA_ROOT=Xe(),c&&await z(Z(i));let{startLocalDurableStreamsServer:l}=await import("@prisma/streams-local"),u=await l({hostname:"127.0.0.1",name:i,port:o}),p={serverUrl:u.exports.http.url,sqlitePath:u.exports.sqlite.path,streamName:Ye,url:Ar(u.exports.http.url)};try{await ls(p);let g=new ct({dbServer:t,debug:r,streamUrl:p.url}),P=a.subscribe(R=>{g.enqueue(R)});return{close:async()=>{P(),await g.close(),await u.close(),await(0,ot.setTimeout)(100),c&&await z(Z(i))},experimental:p}}catch(g){throw await u.close().catch(()=>{}),await(0,ot.setTimeout)(100),c&&await z(Z(i)).catch(()=>{}),g}}var ct=class{#r;#e;#t;#s;#o;constructor(t){this.#r=t.dbServer,this.#e=t.debug,this.#t=Promise.resolve(),this.#s=t.streamUrl,this.#o=new Set}enqueue(t){t.length!==0&&(this.#t=this.#t.then(async()=>{let r=await this.#a(t);r.length!==0&&(await ms(this.#s,r),this.#e&&console.debug(`[streams] appended ${r.length} state-protocol record(s) to ${this.#s}`))}).catch(r=>{console.error("[streams] failed to ingest WAL events into prisma-wal",r)}))}async close(){await this.#t}async#a(t){let r=[],n=new Date().toISOString();for(let s of t)r.push(...await this.#n(s,n));return r}async#n(t,r){let n=`${t.schema}.${t.table}`,s=await this.#r.getPrimaryKeyColumns(t.schema,t.table),o=Lr(t.record),a=Lr(t.oldRecord),c=this.#i(n,s,a),i=this.#i(n,s,o),l=t.txid===""?void 0:t.txid;return t.type==="insert"?o&&i?[{headers:{operation:"insert",timestamp:r,txid:l},key:i,oldValue:null,type:n,value:o}]:[]:t.type==="delete"?a&&c?[{headers:{operation:"delete",timestamp:r,txid:l},key:c,oldValue:a,type:n,value:null}]:[]:!o||!a||!c||!i?[]:c!==i?[{headers:{operation:"delete",timestamp:r,txid:l},key:c,oldValue:a,type:n,value:null},{headers:{operation:"insert",timestamp:r,txid:l},key:i,oldValue:null,type:n,value:o}]:[{headers:{operation:"update",timestamp:r,txid:l},key:i,oldValue:a,type:n,value:o}]}#i(t,r,n){if(!n)return null;let s=ps(n,r);return s||(this.#o.has(t)||(this.#o.add(t),console.warn(`[streams] falling back to full-row keys for ${t} because no primary key could be resolved`)),gs(n))}};async function ls(e){let t=await fetch(e.url,{headers:re,method:"PUT"});if(!t.ok)throw await ne(t,`Failed to create ${e.streamName}`);let r=await fetch(`${e.url}/_profile`,{body:JSON.stringify(cs),headers:re,method:"POST"});if(!r.ok)throw await ne(r,`Failed to configure ${e.streamName}`);let n=await us(e);if(ds(n,e.streamName))return;if(n.currentVersion>0)throw new Error(`Failed to install schema for ${e.streamName}: existing schema registry is incompatible and requires a lens migration`);let s=await fetch(`${e.url}/_schema`,{body:JSON.stringify(it),headers:re,method:"POST"});if(!s.ok)throw await ne(s,`Failed to install schema for ${e.streamName}`)}async function us(e){let t=await fetch(`${e.url}/_schema`,{headers:re,method:"GET"});if(!t.ok)throw await ne(t,`Failed to inspect schema for ${e.streamName}`);return await t.json()}function ds(e,t){if(e.currentVersion<=0||e.schema!==t)return!1;let r=e.schemas[String(e.currentVersion)];return(0,at.isDeepStrictEqual)(r,it.schema)&&(0,at.isDeepStrictEqual)(e.search,it.search)}async function ms(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:re,method:"POST"});if(!r.ok)throw await ne(r,"Failed to append to prisma-wal")}async function ne(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}function ps(e,t){if(t.length===0)return null;let r=[];for(let n of t){if(!Object.prototype.hasOwnProperty.call(e,n))return null;let s=fs(e[n]);if(s==null)return null;r.push(t.length===1?s:`${n}=${s}`)}return r.join("|")}function gs(e){return JSON.stringify(lt(e))}function lt(e){return Array.isArray(e)?e.map(t=>lt(t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,lt(r)])):e}function Lr(e){return e?structuredClone(e):null}function fs(e){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return e;if(typeof e=="number")return Number.isFinite(e)?String(e):null;if(typeof e=="bigint")return e.toString();if(typeof e=="boolean")return e?"true":"false";try{return JSON.stringify(e)}catch{return null}}function hs(e){return`${e}.${(0,$r.randomUUID)().replaceAll("-","")}`}async function Cr(e){let t=await _.createExclusively(e),r=null,n=null,s=null,o=null;try{[r,s]=await Promise.all([Me("database",t),Me("shadow_database",t)]);let a;t.dryRun?(a=Ss(),o=ws()):(a=await r.attachWalEventBridge(),o=await Br({dbServer:r,debug:t.debug,name:t.name,port:t.streamsPort,persistenceMode:t.persistenceMode,walBridge:a})),n=await Tr(r,t);let c=ys(r,s,n,t);await t.writeServerDump(c,t.dryRun?{}:{streams:o.experimental});let i=bs(a),l=r,u=s,p=n,g=o,P=async()=>{i.close(),await kr(t,[p,g,l,u])};return{close:P,dbServer:r,httpServer:n,server:{...c,close:P,experimental:{streams:o.experimental,wal:i.api},name:t.name},serverState:t,shadowDbServer:s,streamsServer:o,walBridge:a}}catch(a){return await Ps(t,[n,o,r,s],a)}}function ys(e,t,r,n){let s=`prisma+postgres://localhost:${r.port}/?${new URLSearchParams({api_key:pt({databaseUrl:e.prismaORMConnectionString,name:n.name,shadowDatabaseUrl:t.prismaORMConnectionString})}).toString()}`;return{database:{connectionString:e.connectionString,prismaORMConnectionString:e.prismaORMConnectionString,terminalCommand:e.terminalCommand},http:{url:r.url},ppg:{url:s},shadowDatabase:{connectionString:t.prismaORMConnectionString,prismaORMConnectionString:t.prismaORMConnectionString,terminalCommand:t.terminalCommand}}}async function kr(e,t){let n=(await Promise.allSettled(t.map(s=>s.close()))).filter(s=>s.status==="rejected").map(s=>new Error(s.reason));try{await e.close()}catch(s){n.push(s)}if(n.length>0)throw new AggregateError(n,"Failed to close some servers")}async function Ps(e,t,r){try{await kr(e,t.filter(n=>n!==null))}catch(n){throw new AggregateError([r,n],"Failed to start Prisma Dev server cleanly")}throw r}function bs(e){let t=new Set;return{api:{stream:()=>{let r=()=>{},n=vs(e,()=>{t.delete(r)});return r=()=>n.close(),t.add(r),n.stream},subscribe:r=>e.subscribe(r)},close:()=>{for(let r of[...t])r();t.clear()}}}function Ss(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function ws(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function vs(e,t){let r=[],n=!1,s=null,o=e.subscribe(c=>{if(!n){if(s){let i=s;s=null,i.resolve({done:!1,value:c});return}r.push(c)}}),a=()=>{if(!n&&(n=!0,o(),r.length=0,t(),s)){let c=s;s=null,c.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((c,i)=>{s={reject:i,resolve:c}})},return(){return a(),Promise.resolve({done:!0,value:void 0})},throw(c){let i=s;return a(),i&&i.reject(c),Promise.reject(c instanceof Error?c:new Error(String(c)))}}}}async function Mr(e){let{server:t}=await Cr(e);return t}var I;process.once("SIGTERM",()=>{console.log("SIGTERM received, shutting down..."),process.removeAllListeners("SIGINT"),process.exitCode=143,I?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{console.log("SIGINT received, shutting down..."),process.removeAllListeners("SIGTERM"),process.exitCode=130,I?.close().finally(()=>process.exit())});async function Es(){let[,,e]=process.argv;if(!e)return process.send?.({type:"error",error:'Missing "name" argument, server cannot be started'},void 0),process.exit(1);try{I=await Mr({debug:!0,persistenceMode:"stateful",name:e});let t={database:I.database,experimental:{streams:I.experimental.streams},http:I.http,name:I.name,ppg:I.ppg,shadowDatabase:I.shadowDatabase};process.send?.({type:"started",server:t},void 0)}catch(t){console.error(t);let r=t instanceof Error?t.message:String(t);process.send?.({type:"error",error:r},void 0),await(0,Ur.setTimeout)(1e3),process.exit(1)}}Es();
|
package/dist/daemon.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as t}from"./chunk-
|
|
1
|
+
import{a as t}from"./chunk-DLTTSFDI.js";import"./chunk-YL6J3L2T.js";import"./chunk-62DM64XC.js";import"./chunk-CC3P7GPW.js";import"./chunk-X3G665AK.js";import"./chunk-TF5C7XJX.js";import"./chunk-DWY47FQV.js";import{setTimeout as a}from"timers/promises";var e;process.once("SIGTERM",()=>{console.log("SIGTERM received, shutting down..."),process.removeAllListeners("SIGINT"),process.exitCode=143,e?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{console.log("SIGINT received, shutting down..."),process.removeAllListeners("SIGTERM"),process.exitCode=130,e?.close().finally(()=>process.exit())});async function n(){let[,,s]=process.argv;if(!s)return process.send?.({type:"error",error:'Missing "name" argument, server cannot be started'},void 0),process.exit(1);try{e=await t({debug:!0,persistenceMode:"stateful",name:s});let r={database:e.database,experimental:{streams:e.experimental.streams},http:e.http,name:e.name,ppg:e.ppg,shadowDatabase:e.shadowDatabase};process.send?.({type:"started",server:r},void 0)}catch(r){console.error(r);let o=r instanceof Error?r.message:String(r);process.send?.({type:"error",error:o},void 0),await a(1e3),process.exit(1)}}n();
|
package/dist/index.cjs
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).find(A=>A.includes("Started query engine http server"));if(!p)return;a.stdout.removeListener("data",c);let{fields:g}=JSON.parse(p);if(g==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${u}`));let{ip:
|
|
3
|
-
Received data: ${u}`));n({childProcess:a,url:`http://${
|
|
4
|
-
`;)r+=1;return r}function
|
|
5
|
-
`)&&!e.includes("\r")){let p=e.trim();return p.length===0?`${
|
|
6
|
-
`)||l.endsWith("\r")?"":
|
|
1
|
+
"use strict";var Vr=Object.create;var se=Object.defineProperty;var Kr=Object.getOwnPropertyDescriptor;var zr=Object.getOwnPropertyNames;var Jr=Object.getPrototypeOf,Qr=Object.prototype.hasOwnProperty;var T=(e,t)=>()=>(e&&(t=e(e=0)),t);var we=(e,t)=>{for(var r in t)se(e,r,{get:t[r],enumerable:!0})},dt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of zr(t))!Qr.call(e,s)&&s!==r&&se(e,s,{get:()=>t[s],enumerable:!(n=Kr(t,s))||n.enumerable});return e};var w=(e,t,r)=>(r=e!=null?Vr(Jr(e)):{},dt(t||!e||!e.__esModule?se(r,"default",{value:e,enumerable:!0}):r,e)),Yr=e=>dt(se({},"__esModule",{value:!0}),e);var Xr,h,m=T(()=>{"use strict";Xr=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,h=Xr()});function pt(e){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([[t],[r]])=>t.localeCompare(r)))),"utf8").toString("base64url")}function en(e){let t=Buffer.from(e,"base64url").toString("utf8"),{issues:r,output:n,success:s}=(0,y.safeParse)(Zr,t,{abortEarly:!0});return s?[null,n]:[r]}var y,mt,Zr,C,ve=T(()=>{"use strict";m();y=require("valibot"),mt=/^(postgres|postgresql):\/\//,Zr=(0,y.pipe)((0,y.string)(),(0,y.parseJson)(),(0,y.object)({databaseUrl:(0,y.pipe)((0,y.string)(),(0,y.url)(),(0,y.regex)(mt)),name:(0,y.optional)((0,y.pipe)((0,y.string)(),(0,y.minLength)(1))),shadowDatabaseUrl:(0,y.pipe)((0,y.string)(),(0,y.url)(),(0,y.regex)(mt))}));C=async(e,t)=>{let{authorization:r}=e,{HTTPException:n}=await import("hono/http-exception");if(!r)throw new n(401,{message:"Missing API Key"});let[s,o="",a]=r.split(" ");if(s!=="Bearer"||a)throw new n(401,{message:"Invalid API Key"});let[c,i]=en(o);if(c)throw new n(401,{message:"Invalid API Key",cause:c.join(", ")});let{databaseUrl:l,name:u,shadowDatabaseUrl:p}=i,g=t.get("name"),P=new URL(t.req.url).port;if(!u)throw new n(401,{message:`Wrong API Key; The Prisma Dev server running at port ${P} requires an API Key from a newer version of \`prisma dev\`. Check the "${g}" server's output for the updated \`DATABASE_URL\` value.`});if(u!==g)throw new n(401,{message:`Wrong API Key; The Prisma Dev server running at port ${P} is named "${g}", but the API Key is for "${u}"`});let{hostname:R,port:A}=new URL(l),{port:Gr}=t.get("db"),{hostname:jr,port:Fr}=new URL(p),qr=t.get("shadowDBPort");if(R!=="localhost"||Number(A)!==Gr||jr!=="localhost"||Number(Fr)!==qr)throw new n(401,{message:"Wrong API Key; Check your Prisma schema's `provider.url` value (probably defined in `.env`'s `DATABASE_URL` environment variable) is aligned with `prisma dev`'s output"});return{decodedAPIKey:i}}});function Te(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),oe.default.platform==="darwin"?tn(e):oe.default.platform==="win32"?rn(e):nn(e)}var b,Ee,oe,$,Re,M,tn,rn,nn,gt=T(()=>{"use strict";m();b=w(require("path"),1),Ee=w(require("os"),1),oe=w(require("process"),1),$=Ee.default.homedir(),Re=Ee.default.tmpdir(),{env:M}=oe.default,tn=e=>{let t=b.default.join($,"Library");return{data:b.default.join(t,"Application Support",e),config:b.default.join(t,"Preferences",e),cache:b.default.join(t,"Caches",e),log:b.default.join(t,"Logs",e),temp:b.default.join(Re,e)}},rn=e=>{let t=M.APPDATA||b.default.join($,"AppData","Roaming"),r=M.LOCALAPPDATA||b.default.join($,"AppData","Local");return{data:b.default.join(r,e,"Data"),config:b.default.join(t,e,"Config"),cache:b.default.join(r,e,"Cache"),log:b.default.join(r,e,"Log"),temp:b.default.join(Re,e)}},nn=e=>{let t=b.default.basename($);return{data:b.default.join(M.XDG_DATA_HOME||b.default.join($,".local","share"),e),config:b.default.join(M.XDG_CONFIG_HOME||b.default.join($,".config"),e),cache:b.default.join(M.XDG_CACHE_HOME||b.default.join($,".cache"),e),log:b.default.join(M.XDG_STATE_HOME||b.default.join($,".local","state"),e),temp:b.default.join(Re,t,e)}}});function Pt(e,t){return`${ie.cache}/engine/${e}/${t}`}function V(e){return`${ie.data}/${e}`}async function bt(e){try{return await(0,v.access)(e,v.constants.F_OK),!0}catch(t){if(xe(t))return!1;throw t}}async function St(e,t){let r=await sn(e);await(0,v.writeFile)(t,r),await(0,v.chmod)(t,"755")}async function wt(e,t){await e.stream().pipeTo(ae.WriteStream.toWeb((0,ae.createWriteStream)(t,{encoding:"utf8"})))}function xe(e){return e!=null&&typeof e=="object"&&"code"in e&&e.code==="ENOENT"}async function vt(e){try{return await(0,v.readFile)(e,{encoding:"utf-8"})}catch(t){if(xe(t))return null;throw t}}async function Et(e){await(0,v.mkdir)(e,{recursive:!0})}async function Rt(e,t){try{return(await(0,v.readdir)(e,{withFileTypes:!0})).reduce((n,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!t||(0,yt.default)(t,s.name))&&n.push(s.name),n),[])}catch(r){if(xe(r))return[];throw r}}async function K(e){await(0,v.rm)(e,{force:!0,recursive:!0})}var ae,v,ft,ht,yt,ie,sn,W=T(()=>{"use strict";m();ae=require("fs"),v=require("fs/promises"),ft=require("util"),ht=require("zlib");gt();yt=w(require("zeptomatch"),1),ie=Te("prisma-dev"),sn=(0,ft.promisify)(ht.unzip)});function he(e){let t,r,n=new Promise((a,c)=>{t=a,r=c}),s=a=>{s=o=null,r(a),e?.onRejected?.(a),e?.onFulfilled?.()},o=a=>{o=s=null,t(a),e?.onResolved?.(a),e?.onFulfilled?.()};return{isFulfilled:()=>o===s,promise:n,reject:a=>s?.(a),resolve:a=>o?.(a)}}var We=T(()=>{"use strict";m()});function ye(e,t){return console.error(e),e instanceof J?t.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:e.message}}}},500):e instanceof j?t.text(e.responseBody,e.statusCode):t.body(null,500)}var Yt,Xt,Zt,er,tr,rr,Nn,Bn,Qt,F,J,j,He=T(()=>{"use strict";m();Yt=require("child_process"),Xt=require("events"),Zt=require("fs/promises"),er=require("path"),tr=require("timers/promises");We();rr=require("std-env");W();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Nn,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:Bn,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:Qt}=rr.process.env),F=class e{static#r=new Map;#e;#t;constructor(t){this.#e=t,this.#t=null}static async get(t){let{debug:r}=t,n=`${t.schemaHash}:${t.clientVersion}`;try{let s=e.#r.get(n);if(s)return s;let o=new e(t);return e.#r.set(n,o),r&&console.debug("[Query Engine] starting...",t),await o.start(),r&&console.debug("[Query Engine] started!"),o}finally{e.stopAll(n)}}static async stopAll(t){let n=(await Promise.allSettled(Array.from(e.#r.entries()).filter(([s])=>s!==t).map(async([s,o])=>{try{await o.stop()}finally{e.#r.delete(s)}}))).filter(s=>s.status==="rejected").map(s=>s.reason);if(n.length>0)throw new AggregateError(n,"Failed to stop engines")}async commitTransaction(t,r){return await this.#i(t,r,"commit")}async request(t,r){let{url:n}=await this.start(),s=this.#n(r),o=await fetch(n,{body:typeof t=="string"?t:JSON.stringify(t),headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await j.fromResponse(o);return await o.text()}async rollbackTransaction(t,r){return await this.#i(t,r,"rollback")}async startTransaction(t,r){let{url:n}=await this.start(),s=this.#n(r),o=await fetch(`${n}/transaction/start`,{body:JSON.stringify(t),headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await j.fromResponse(o);return await o.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:t,reject:r,resolve:n}=he();this.#t=t;let s=Bn||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",s);let{proxySignals:o}=await import("foreground-child/proxy-signals"),a=(0,Yt.spawn)(s,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});o(a),a.stderr.setEncoding("utf8"),a.stdout.setEncoding("utf8");let c=u=>{let p=u.split(`
|
|
2
|
+
`).find(A=>A.includes("Started query engine http server"));if(!p)return;a.stdout.removeListener("data",c);let{fields:g}=JSON.parse(p);if(g==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${u}`));let{ip:P,port:R}=g;if(P==null||R==null)return r(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
|
|
3
|
+
Received data: ${u}`));n({childProcess:a,url:`http://${P}:${R}`})},i=u=>{this.#t=null,r(new J(String(u))),a.removeListener("exit",l),a.kill()};a.once("error",i);let l=(u,p)=>{this.#t=null,r(new J(`Query Engine exited with code ${u} and signal ${p}`))};return a.once("exit",l),a.stdout.on("data",c),this.#e.debug&&(a.stderr.on("data",console.error.bind(console,"[Query Engine]")),a.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:t}=await this.#t;t.exitCode==null&&t.signalCode==null&&(this.#t=null,t.kill(),await(0,Xt.once)(t,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let t=await this.#o();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",t);let r=Pt(this.#e.clientVersion,t);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,Zt.mkdir)(r,{recursive:!0});let{binaryTarget:n}=this.#e.platform,s=n==="windows"?".exe":"",o=(0,er.join)(r,`query-engine-${n}${s}`);return this.#e.debug&&console.debug("[Query Engine] binary path",o),(Nn==="1"||await bt(o)===!1)&&await this.#a({commitHash:t,extension:s,engineBinaryPath:o}),o}async#o(){let t=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!t.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${t.status}`);let n=(await t.json()).devDependencies?.["@prisma/engines-version"];if(!n)throw new Error("Couldn't find engines version in package.json");let s=n.split(".").at(-1);if(!s)throw new Error("Couldn't find commit hash in engines version");return s}async#a(t){let{commitHash:r,extension:n,engineBinaryPath:s}=t,{binaryTarget:o}=this.#e.platform,a=`https://binaries.prisma.sh/all_commits/${r}/${o}/query-engine${n}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",a);let c=await fetch(a);if(!c.ok)throw new Error(`Couldn't download engine. URL: ${a}, status code: ${c.status}`);Qt&&await(0,tr.setTimeout)(Number(Qt)),await St(await c.arrayBuffer(),s),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",s)}#n(t){let r={};for(let[n,s]of Object.entries(t))s!=null&&(r[n]=s);return r}async#i(t,r,n){let{url:s}=await this.#t,o=this.#n(r),a=await fetch(`${s}/transaction/${t}/${n}`,{headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!a.ok)throw await j.fromResponse(a);try{return await a.json()}catch{return{}}}};J=class extends Error{name="EngineStartError"},j=class e extends Error{constructor(r,n,s){super(`${r}: Query Engine response status ${n}, body: ${s}`);this.action=r;this.statusCode=n;this.responseBody=s}name="EngineHttpError";static async fromResponse(r){let n=new URL(r.url),s=await r.text();return new e(n.pathname,r.status,s)}}});async function nr(e){let{output:t,success:r}=(0,E.safeParse)(Cn,await e.req.json(),{abortEarly:!0});return r?t:e.text("Invalid input",400)}var E,Cn,sr=T(()=>{"use strict";m();E=require("valibot"),Cn=(0,E.object)({tags:(0,E.union)([(0,E.pipe)((0,E.array)((0,E.string)()),(0,E.minLength)(1)),(0,E.literal)("all")])})});async function or(e){return Ge===void 0&&(Ge=await B.Server.create({databaseUrl:e.get("db").connectionString,maxResponseSize:(0,B.parseSize)("128 MiB"),queryTimeout:(0,B.parseDuration)("PT5M"),maxTransactionTimeout:(0,B.parseDuration)("PT5M"),maxTransactionWaitTime:(0,B.parseDuration)("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:e.get("debug")?"debug":"off"}})),Ge}var B,Pe,Ge,ar=T(()=>{"use strict";m();B=require("@prisma/query-plan-executor"),Pe=require("@prisma/query-plan-executor")});async function qe(e){let r=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(a=>a.toString(16).padStart(2,"0")).join("")}function cr(e){let t=e.req.param("schemaHash"),r=be.get(t);return r==null?e.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:t,schemas:r}}async function lr(e,t,r){let n=Fe.Buffer.from(e,"base64").toString("utf8"),s=Un(n,t.toString());r&&console.log("[Accelerate] schema with override:",s);let o=await qe(s);return{base64Override:Fe.Buffer.from(s,"utf8").toString("base64"),overrideHash:o}}function Un(e,t){let r=Mn(e);if(!r)throw new Error("No datasource block found in schema.");let n=e.slice(r.openBraceIndex+1,r.closeBraceIndex),s=Gn(n,t,qn(e,r.openBraceIndex));return`${e.slice(0,r.openBraceIndex+1)}${s}${e.slice(r.closeBraceIndex)}`}function Mn(e){let t="datasource";for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="/"&&e[r+1]==="/"){r=Ve(e,r+2);continue}if(n==="/"&&e[r+1]==="*"){r=Ke(e,r+2);continue}if(n==='"'){r=ze(e,r+1);continue}if(e.startsWith(t,r)&&!ir(e[r-1])&&!ir(e[r+t.length])){let s=Wn(e,r+t.length,"{");if(s===-1)return null;let o=Hn(e,s);return o===-1?null:{closeBraceIndex:o,openBraceIndex:s}}}return null}function Wn(e,t,r){for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=Ve(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=Ke(e,n+2);continue}if(s==='"'){n=ze(e,n+1);continue}if(s===r)return n}return-1}function Hn(e,t){let r=0;for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=Ve(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=Ke(e,n+2);continue}if(s==='"'){n=ze(e,n+1);continue}if(s==="{"){r+=1;continue}if(s==="}"&&(r-=1,r===0))return n}return-1}function Ve(e,t){let r=t;for(;r<e.length&&e[r]!==`
|
|
4
|
+
`;)r+=1;return r}function Ke(e,t){let r=e.indexOf("*/",t);return r===-1?e.length:r+1}function ze(e,t){let r=t;for(;r<e.length;){if(e[r]==="\\"){r+=2;continue}if(e[r]==='"')return r;r+=1}return e.length}function ir(e){return e!=null&&/[A-Za-z0-9_]/.test(e)}function Gn(e,t,r){let n=`"${Kn(t)}"`,s=jn(e);for(let[p,g]of s.entries()){let{comment:P,code:R}=ur(g.line),A=R.match(/^(\s*)url(\s*)=(\s*).*/);if(A)return s[p]={line:`${A[1]}url${A[2]}=${A[3]}${n}${P}`,terminator:g.terminator},je(s)}let o=Vn(e),a=Fn(s,r),c=`${a}url = ${n}`;if(!e.includes(`
|
|
5
|
+
`)&&!e.includes("\r")){let p=e.trim();return p.length===0?`${o}${c}${o}${r}`:`${o}${a}${p}${o}${c}${o}${r}`}let i=s.at(-1);if(i&&i.terminator===""&&/^\s*$/.test(i.line))return`${je(s.slice(0,-1))}${c}${o}${r}`;let l=je(s),u=l.endsWith(`
|
|
6
|
+
`)||l.endsWith("\r")?"":o;return`${l}${u}${c}${o}${r}`}function jn(e){let t=[],r=0;for(let n=0;n<e.length;n+=1){if(e[n]==="\r"&&e[n+1]===`
|
|
7
7
|
`){t.push({line:e.slice(r,n),terminator:`\r
|
|
8
8
|
`}),n+=1,r=n+1;continue}(e[n]===`
|
|
9
|
-
`||e[n]==="\r")&&(t.push({line:e.slice(r,n),terminator:e[n]}),r=n+1)}return(r<e.length||e.length===0)&&t.push({line:e.slice(r),terminator:""}),t}function
|
|
10
|
-
`,t)+1,n=r;for(;e[n]===" "||e[n]===" ";)n+=1;return e.slice(r,n)}function
|
|
9
|
+
`||e[n]==="\r")&&(t.push({line:e.slice(r,n),terminator:e[n]}),r=n+1)}return(r<e.length||e.length===0)&&t.push({line:e.slice(r),terminator:""}),t}function je(e){return e.map(t=>`${t.line}${t.terminator}`).join("")}function ur(e){let t=!1,r=!1;for(let n=0;n<e.length;n+=1){let s=e[n];if(r){if(t){t=!1;continue}if(s==="\\"){t=!0;continue}s==='"'&&(r=!1);continue}if(s==='"'){r=!0;continue}if(s==="/"&&e[n+1]==="/")return{code:e.slice(0,n),comment:e.slice(n)}}return{code:e,comment:""}}function Fn(e,t){for(let r of e){let{code:n}=ur(r.line),s=n.match(/^([ \t]+)[A-Za-z_][A-Za-z0-9_]*\s*=/);if(s?.[1])return s[1]}return`${t}${kn}`}function qn(e,t){let r=e.lastIndexOf(`
|
|
10
|
+
`,t)+1,n=r;for(;e[n]===" "||e[n]===" ";)n+=1;return e.slice(r,n)}function Vn(e){return e.includes(`\r
|
|
11
11
|
`)?`\r
|
|
12
12
|
`:`
|
|
13
|
-
`}function qn(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}var Ge,Pe,Bn,lr=T(()=>{"use strict";m();Ge=require("buffer"),Pe=new Map;Bn=" "});function ye(e){let{req:t}=e;return{traceparent:t.header("traceparent"),"X-capture-telemetry":t.header("X-capture-telemetry")}}var ur=T(()=>{"use strict";m()});async function dr(e){let{issues:t,output:r,success:n}=(0,f.safeParse)(Vn,await e.req.json(),{abortEarly:!0});return n?r:e.json({EngineNotStarted:{reason:"InvalidRequest",issues:t}},400)}function mr(e,t){let{output:r,success:n}=(0,f.safeParse)(zn,e);return n?r:t.json({EngineMalfunction:{}},500)}var f,Vn,zn,pr=T(()=>{"use strict";m();f=require("valibot"),Vn=(0,f.object)({isolation_level:(0,f.optional)((0,f.string)()),max_wait:(0,f.pipe)((0,f.number)(),(0,f.integer)(),(0,f.minValue)(0)),timeout:(0,f.pipe)((0,f.number)(),(0,f.integer)(),(0,f.minValue)(0))});zn=(0,f.looseObject)({id:(0,f.union)([(0,f.string)(),(0,f.number)()])})});var hr={};be(hr,{accelerateRoute:()=>Q});async function ze(e){let{req:t}=e,r=ar(e);if(r instanceof Response)return r;let{base64Override:n,overrideHash:o}=r.schemas;return await F.get({base64Schema:n,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||t.param("clientVersion"),debug:e.get("debug"),platform:e.get("platform"),schemaHash:o})}var gr,fr,k,Q,Kn,Y,Jn,Qn,Pr=T(()=>{"use strict";m();gr=require("hono/http-exception"),fr=require("hono/tiny"),k=require("hono/validator");Se();rr();Me();or();lr();ur();pr();Q=new fr.Hono;Q.post("/invalidate",(0,k.validator)("header",C),async e=>{let t=await tr(e);return t instanceof Response?t:e.body(null)});Kn="/:clientVersion/:schemaHash",Y=Q.basePath(Kn);Q.route("/",Y);Jn=["/graphql","/itx/:transactionId/graphql"];Y.on("POST",[...Jn],(0,k.validator)("header",C),async e=>{let{req:t}=e;try{let r=await ze(e);if(r instanceof Response)return r;let n=await t.text(),o=t.param("transactionId"),s=await r.request(n,{...ye(e),"X-transaction-id":o});return e.text(s)}catch(r){return fe(r,e)}});Y.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,k.validator)("header",C),async e=>{let{req:t}=e;try{let r=await ze(e);if(r instanceof Response)return r;let o=`${t.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=t.param("transactionId"),a=await r[o](s,ye(e));return e.json(a)}catch(r){return fe(r,e)}});Y.put("/schema",(0,k.validator)("header",C),async e=>{let{req:t}=e,r=await t.text();if(!r)return e.text("Missing schema",400);let n=t.param("schemaHash"),o=Pe.get(n);if(o==null){if(n!==await je(r))return e.text("Schema hash mismatch",400);let s=await ir(r,e.get("db").prismaORMConnectionString,e.get("debug"));return Pe.set(n,{base64Original:r,...s}),e.text(n)}return r!==o.base64Original?e.text("Schema mismatch",400):e.text(n)});Y.post("/transaction/start",(0,k.validator)("header",C),async e=>{let{req:t}=e,r=await dr(e);if(r instanceof Response)return r;try{let n=await ze(e);if(n instanceof Response)return n;let o=await n.startTransaction(r,ye(e)),s=mr(o,e);if(s instanceof Response)return s;let{id:a}=s,c=t.param("clientVersion"),i=t.param("schemaHash");return e.json({...o,"data-proxy":{endpoint:`${new URL(t.url).origin}/${c}/${i}/itx/${a}`}})}catch(n){return fe(n,e)}});Qn=[["/connection-info","GET"],["/query","POST"],["/transaction/start","POST"],["/transaction/:transactionId/commit","POST"],["/transaction/:transactionId/query","POST"],["/transaction/:transactionId/rollback","POST"]];for(let[e,t]of Qn)Q.on(t,e,(0,k.validator)("header",C),async r=>{let n=r.req.header("prisma-engine-hash");if(n!=="0.0.0"&&n!==he.version)throw new gr.HTTPException(400,{message:`Using an HTTP connection string is not supported with Prisma Client version ${n} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${he.version}.`});return await(await nr(r)).fetch(r.req.raw)})});var Sr={};be(Sr,{utilityRoute:()=>Ke});var yr,br,Ke,fs,wr=T(()=>{"use strict";m();yr=require("hono/tiny"),br=require("http-status-codes"),Ke=new yr.Hono;Ke.post("/database/dump",async e=>{let t=e.get("db"),r=e.get("databaseDumpPath");return await t.dump(r),e.json({dumpPath:r},br.StatusCodes.CREATED)});fs=Ke.get("/health",e=>e.json({name:e.get("name")}))});var wo={};be(wo,{DEFAULT_DATABASE_PORT:()=>ie,DEFAULT_SERVER_PORT:()=>ce,DEFAULT_SHADOW_DATABASE_PORT:()=>le,PortNotAvailableError:()=>D,ServerAlreadyRunningError:()=>te,copyPrismaDevRuntimeAssets:()=>Ot,getPrismaDevRuntimeAssetManifest:()=>_e,startPrismaDevServer:()=>Mr,unstable_startServer:()=>So});module.exports=Jr(wo);m();m();Se();m();var Ft=require("pathe/utils");W();m();var N=require("get-port-please"),ue=require("remeda"),ie=51214,ce=51213,le=51215,vt=51216,ae=65535,H=0,x=-1/0;async function De(e){let{debug:t,name:r,requestedPorts:n,servers:o}=e,{portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a}=sn(r,o);t&&(console.debug(`ports used by other servers: ${Object.keys(s).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(a)}`));let c={databasePort:x,port:x,shadowDatabasePort:x,streamsPort:x},i=["port","databasePort","shadowDatabasePort","streamsPort"];for(let l of i){let u=await nn({debug:t,portKey:l,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a,requestedPorts:n})??await on({debug:t,pickedPorts:c,portKey:l,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a});t&&console.debug(`Got port for "${l}": ${u}`),c[l]=u}return t&&console.debug(`Picked ports: ${JSON.stringify(c)}`),c}async function nn(e){let{debug:t,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:o,requestedPorts:s}=e,{[r]:a,...c}=s;if(Te(a))return await ln({debug:t,otherRequestedPorts:c,portKey:r,portsUsedByOtherServers:n,requestedPort:a}),a;let i=o?.[r]??x;if(!Te(i))return t&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let l=i in n;return l||Object.values(c).includes(i)?(t&&console.debug(`Port ${i} that was used last time for this server, ${l?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,N.checkPort)(i)===!1?(t&&console.debug(`Port ${i}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(t&&console.debug(`Using port ${i} for "${r}" as it was used last time and is available.`),i)}async function on(e){let{debug:t,pickedPorts:r,portKey:n,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:s}=e,a=Math.max(ie,ce,le,vt)+1,c=Object.values(r).filter(y=>y!==void 0),i=s?cn(s):[],l=[...c,...Object.keys(o).map(Number),...i],u=Math.min(Math.max(a,...l)+100,ae),p=(0,ue.difference)((0,ue.range)(a,u),l),g={port:ce,databasePort:ie,shadowDatabasePort:le,streamsPort:vt}[n];try{return await(0,N.getPort)({port:g in o||c.includes(g)||i.includes(g)?void 0:g,ports:p})}catch(y){if(y instanceof Error&&y.name==="GetPortError"&&u+1<=ae)return t&&console.debug(`Expanding port lookup to range [${u+1}, ${ae}].`),await(0,N.getPort)({portRange:[u+1,ae]});throw y}}function Te(e){return Number.isFinite(e)&&e>=0}function sn(e,t){let r={},n;for(let o of t){let{databasePort:s,port:a,shadowDatabasePort:c}=o,i=an(o);if(o.name===e){n={databasePort:s,port:a,shadowDatabasePort:c,streamsPort:i};continue}r[s]=!0,r[a]=!0,r[c]=!0,Te(i)&&(r[i]=!0)}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}function an(e){let t=e.experimental?.streams?.serverUrl;if(!t)return x;try{let r=Number(new URL(t).port);return Number.isInteger(r)&&r>0?r:x}catch{return x}}function cn(e){return[e.port,e.databasePort,e.shadowDatabasePort,e.streamsPort]}async function ln(e){let{debug:t,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:o,requestedPort:s}=e;if(s!==H){if(s in o)throw t&&console.error(`Port ${s} was requested for "${n}", but is already used by another server.`),new Ae(s);if(Object.values(r).includes(s))throw t&&console.error(`Port ${s} was requested for "${n}", but also for another key.`),new xe(s);if((0,N.isUnsafePort)(s))throw t&&console.error(`Port ${s} was requested for "${n}", but is unsafe.`),new D(s);if(await(0,N.checkPort)(s)===!1)throw t&&console.error(`Port ${s} was requested for "${n}", but is not available.`),new D(s)}}var D=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},xe=class extends Error{constructor(r){super(`Port number \`${r}\` was requested twice. Please choose a different port for each service.`);this.port=r}name="PortRequestedTwiceError"},Ae=class extends Error{constructor(r){super(`Port number \`${r}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=r}name="PortBelongsToAnotherServerError"};m();var G=require("fs"),L=require("fs/promises"),xt=require("module"),At=require("path"),_=require("url"),un=(0,xt.createRequire)(h),dn=["initdb.wasm","pglite.data","pglite.wasm"],Dt={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"},_t=[...dn.map(e=>({fileName:e,kind:"core",name:e})),...Object.entries(Dt).map(([e,t])=>({fileName:t,kind:"extension",name:e}))],me=new Map,mn=Symbol.for("@prisma/dev/bundled-pglite-runtime-asset-sources"),de=null;async function Ot(e){let t=pe(e),r=(0,_.fileURLToPath)(t);await(0,L.mkdir)(r,{recursive:!0});let n=[];for(let o of _e()){let s=new URL(o.fileName,t),a=(0,_.fileURLToPath)(s);await(0,L.copyFile)(o.sourcePath,a),n.push({...o,destinationPath:a})}return n}function _e(){let e=It();return _t.map(t=>({...t,sourcePath:(0,_.fileURLToPath)(new URL(t.fileName,e))}))}async function Oe(){await bn();let e=Lt();if(e)return await hn(e),await pn(e);let t=Pn(),r=t.href,n=me.get(r);return n||(n=gn(t),me.set(r,n)),await n}async function pn(e){let t=`bundled:${e.wasmModule.href}:${e.fsBundle.href}`,r=me.get(t);return r||(r=fn(e),me.set(t,r)),await r}async function gn(e){let[t,r]=await Promise.all([(0,L.readFile)(new URL("pglite.data",e)),(0,L.readFile)(new URL("pglite.wasm",e))]),n=$t();return{extensions:Object.fromEntries(Object.entries(Dt).map(([o,s])=>[o,new URL(s,e)])),fsBundle:new Blob([Uint8Array.from(t)]),wasmModule:await n.compile(r)}}async function fn(e){let[t,r]=await Promise.all([Tt(e.fsBundle),Tt(e.wasmModule)]),n=$t();return{extensions:e.extensions,fsBundle:new Blob([Uint8Array.from(t)]),wasmModule:await n.compile(r)}}async function hn(e){if(e.initdbWasm.protocol!=="file:")return;let t=new URL("initdb.wasm",pe(new URL("./",e.initdbWasm))),r=(0,_.fileURLToPath)(t);(0,G.existsSync)(r)||await(0,L.copyFile)((0,_.fileURLToPath)(e.initdbWasm),r)}function pe(e){return e instanceof URL?Rt(e):Rt((0,_.pathToFileURL)(e))}function Rt(e){return e.href.endsWith("/")?e:new URL(`${e.href}/`)}function It(){let e=un.resolve("@electric-sql/pglite");return pe((0,At.dirname)(e))}function Pn(){let e=pe(new URL("./",h));if(yn(e))return e;if(Sn())return It();throw new Error("Unable to locate PGlite runtime assets. If you bundled @prisma/dev, copy them next to the bundle with copyPrismaDevRuntimeAssets().")}function yn(e){return _t.every(t=>(0,G.existsSync)((0,_.fileURLToPath)(new URL(t.fileName,e))))}function Lt(){return globalThis[mn]??null}async function bn(){!wn()||Lt()||(de||(de=import("./runtime-assets-manifest.bun.js").then(()=>{}).catch(e=>{throw de=null,e})),await de)}function Sn(){let e=(0,_.fileURLToPath)(new URL("../package.json",h));if(!(0,G.existsSync)(e))return!1;try{return JSON.parse((0,G.readFileSync)(e,"utf8")).name==="@prisma/dev"}catch{return!1}}function wn(){return typeof globalThis.Bun<"u"}function $t(){let e=globalThis.WebAssembly;if(!e)throw new Error("WebAssembly is not available in this runtime.");return e}async function Tt(e){if(e.protocol==="file:")return await(0,L.readFile)(e);let t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch runtime asset ${e.href}: ${t.status} ${t.statusText}`);return new Uint8Array(await t.arrayBuffer())}m();var $e=require("@electric-sql/pglite"),O="_prisma_dev_wal",Le="events",Ct="install_all_triggers",Nt="capture_event",Bt="prisma_dev_wal_capture",K=new WeakMap,En=new Set(["ALTER","COMMIT","COPY","CREATE","DELETE","DROP","INSERT","MERGE","TRUNCATE","UPDATE"]);async function Ne(e,t){let r=K.get(e);if(r&&!r.closed)return r.bridge;let n=e.execProtocolRaw.bind(e),o=e.execProtocolRawStream.bind(e),s={bridge:{close:async()=>{s.closed||(s.closed=!0,s.subscribers.clear(),e.execProtocolRaw===a&&(e.execProtocolRaw=n),e.execProtocolRawStream===c&&(e.execProtocolRawStream=o),await s.pollPromise,K.delete(e))},poll:async()=>{await Ie(s,e)},subscribe:i=>(s.subscribers.add(i),()=>{s.subscribers.delete(i)})},closed:!1,ensureInfrastructurePromise:null,pendingPoll:!1,pollPromise:null,subscribers:new Set,suppressDepth:0},a=async(i,l)=>{let u=await n(i,l);return!s.closed&&s.suppressDepth===0&&Ut(u)&&Ie(s,e),u},c=async(i,l)=>{let u=[],p=new $e.protocol.Parser,g=l?.onRawData;await o(i,{...l,onRawData:y=>{p.parse(y,R=>{u.push(R)}),g?.(y)}}),!s.closed&&s.suppressDepth===0&&Be(u)&&Ie(s,e)};return e.execProtocolRaw=a,e.execProtocolRawStream=c,K.set(e,s),await Mt(s,e),s.bridge}async function kt(e){let t=K.get(e);t&&await t.bridge.close()}function Be(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&&En.has(r))return!0}return!1}function Ut(e){if(e.length===0)return!1;let t=[];return new $e.protocol.Parser().parse(e,n=>{t.push(n)}),Be(t)}async function Mt(e,t){e.ensureInfrastructurePromise??=Ce(e,t,async()=>{await t.exec(`CREATE SCHEMA IF NOT EXISTS "${O}"`),await t.exec(`
|
|
14
|
-
CREATE TABLE IF NOT EXISTS "${O}"."${
|
|
13
|
+
`}function Kn(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}var Fe,be,kn,dr=T(()=>{"use strict";m();Fe=require("buffer"),be=new Map;kn=" "});function Se(e){let{req:t}=e;return{traceparent:t.header("traceparent"),"X-capture-telemetry":t.header("X-capture-telemetry")}}var mr=T(()=>{"use strict";m()});async function pr(e){let{issues:t,output:r,success:n}=(0,f.safeParse)(zn,await e.req.json(),{abortEarly:!0});return n?r:e.json({EngineNotStarted:{reason:"InvalidRequest",issues:t}},400)}function gr(e,t){let{output:r,success:n}=(0,f.safeParse)(Jn,e);return n?r:t.json({EngineMalfunction:{}},500)}var f,zn,Jn,fr=T(()=>{"use strict";m();f=require("valibot"),zn=(0,f.object)({isolation_level:(0,f.optional)((0,f.string)()),max_wait:(0,f.pipe)((0,f.number)(),(0,f.integer)(),(0,f.minValue)(0)),timeout:(0,f.pipe)((0,f.number)(),(0,f.integer)(),(0,f.minValue)(0))});Jn=(0,f.looseObject)({id:(0,f.union)([(0,f.string)(),(0,f.number)()])})});var Pr={};we(Pr,{accelerateRoute:()=>Q});async function Je(e){let{req:t}=e,r=cr(e);if(r instanceof Response)return r;let{base64Override:n,overrideHash:s}=r.schemas;return await F.get({base64Schema:n,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||t.param("clientVersion"),debug:e.get("debug"),platform:e.get("platform"),schemaHash:s})}var hr,yr,k,Q,Qn,Y,Yn,Xn,br=T(()=>{"use strict";m();hr=require("hono/http-exception"),yr=require("hono/tiny"),k=require("hono/validator");ve();sr();He();ar();dr();mr();fr();Q=new yr.Hono;Q.post("/invalidate",(0,k.validator)("header",C),async e=>{let t=await nr(e);return t instanceof Response?t:e.body(null)});Qn="/:clientVersion/:schemaHash",Y=Q.basePath(Qn);Q.route("/",Y);Yn=["/graphql","/itx/:transactionId/graphql"];Y.on("POST",[...Yn],(0,k.validator)("header",C),async e=>{let{req:t}=e;try{let r=await Je(e);if(r instanceof Response)return r;let n=await t.text(),s=t.param("transactionId"),o=await r.request(n,{...Se(e),"X-transaction-id":s});return e.text(o)}catch(r){return ye(r,e)}});Y.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,k.validator)("header",C),async e=>{let{req:t}=e;try{let r=await Je(e);if(r instanceof Response)return r;let s=`${t.routePath.split("/").filter(Boolean).at(-1)}Transaction`,o=t.param("transactionId"),a=await r[s](o,Se(e));return e.json(a)}catch(r){return ye(r,e)}});Y.put("/schema",(0,k.validator)("header",C),async e=>{let{req:t}=e,r=await t.text();if(!r)return e.text("Missing schema",400);let n=t.param("schemaHash"),s=be.get(n);if(s==null){if(n!==await qe(r))return e.text("Schema hash mismatch",400);let o=await lr(r,e.get("db").prismaORMConnectionString,e.get("debug"));return be.set(n,{base64Original:r,...o}),e.text(n)}return r!==s.base64Original?e.text("Schema mismatch",400):e.text(n)});Y.post("/transaction/start",(0,k.validator)("header",C),async e=>{let{req:t}=e,r=await pr(e);if(r instanceof Response)return r;try{let n=await Je(e);if(n instanceof Response)return n;let s=await n.startTransaction(r,Se(e)),o=gr(s,e);if(o instanceof Response)return o;let{id:a}=o,c=t.param("clientVersion"),i=t.param("schemaHash");return e.json({...s,"data-proxy":{endpoint:`${new URL(t.url).origin}/${c}/${i}/itx/${a}`}})}catch(n){return ye(n,e)}});Xn=[["/connection-info","GET"],["/query","POST"],["/transaction/start","POST"],["/transaction/:transactionId/commit","POST"],["/transaction/:transactionId/query","POST"],["/transaction/:transactionId/rollback","POST"]];for(let[e,t]of Xn)Q.on(t,e,(0,k.validator)("header",C),async r=>{let n=r.req.header("prisma-engine-hash");if(n!=="0.0.0"&&n!==Pe.version)throw new hr.HTTPException(400,{message:`Using an HTTP connection string is not supported with Prisma Client version ${n} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${Pe.version}.`});return await(await or(r)).fetch(r.req.raw)})});var vr={};we(vr,{utilityRoute:()=>Qe});var Sr,wr,Qe,bo,Er=T(()=>{"use strict";m();Sr=require("hono/tiny"),wr=require("http-status-codes"),Qe=new Sr.Hono;Qe.post("/database/dump",async e=>{let t=e.get("db"),r=e.get("databaseDumpPath");return await t.dump(r),e.json({dumpPath:r},wr.StatusCodes.CREATED)});bo=Qe.get("/health",e=>e.json({name:e.get("name")}))});var Rs={};we(Rs,{DEFAULT_DATABASE_PORT:()=>le,DEFAULT_SERVER_PORT:()=>ue,DEFAULT_SHADOW_DATABASE_PORT:()=>de,PortNotAvailableError:()=>D,ServerAlreadyRunningError:()=>te,copyPrismaDevRuntimeAssets:()=>Lt,getPrismaDevRuntimeAssetManifest:()=>Ie,startPrismaDevServer:()=>Hr,unstable_startServer:()=>Es});module.exports=Yr(Rs);m();m();ve();m();var Vt=require("pathe/utils");W();m();var N=require("get-port-please"),me=require("remeda"),le=51214,ue=51213,de=51215,Tt=51216,ce=65535,H=0,x=-1/0;async function Oe(e){let{debug:t,name:r,requestedPorts:n,servers:s}=e,{portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a}=cn(r,s);t&&(console.debug(`ports used by other servers: ${Object.keys(o).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(a)}`));let c={databasePort:x,port:x,shadowDatabasePort:x,streamsPort:x},i=["port","databasePort","shadowDatabasePort","streamsPort"];for(let l of i){let u=await on({debug:t,portKey:l,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a,requestedPorts:n})??await an({debug:t,pickedPorts:c,portKey:l,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a});t&&console.debug(`Got port for "${l}": ${u}`),c[l]=u}return t&&console.debug(`Picked ports: ${JSON.stringify(c)}`),c}async function on(e){let{debug:t,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s,requestedPorts:o}=e,{[r]:a,...c}=o;if(Ae(a))return await dn({debug:t,otherRequestedPorts:c,portKey:r,portsUsedByOtherServers:n,requestedPort:a}),a;let i=s?.[r]??x;if(!Ae(i))return t&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let l=i in n;return l||Object.values(c).includes(i)?(t&&console.debug(`Port ${i} that was used last time for this server, ${l?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,N.checkPort)(i)===!1?(t&&console.debug(`Port ${i}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(t&&console.debug(`Using port ${i} for "${r}" as it was used last time and is available.`),i)}async function an(e){let{debug:t,pickedPorts:r,portKey:n,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:o}=e,a=Math.max(le,ue,de,Tt)+1,c=Object.values(r).filter(P=>P!==void 0),i=o?un(o):[],l=[...c,...Object.keys(s).map(Number),...i],u=Math.min(Math.max(a,...l)+100,ce),p=(0,me.difference)((0,me.range)(a,u),l),g={port:ue,databasePort:le,shadowDatabasePort:de,streamsPort:Tt}[n];try{return await(0,N.getPort)({port:g in s||c.includes(g)||i.includes(g)?void 0:g,ports:p})}catch(P){if(P instanceof Error&&P.name==="GetPortError"&&u+1<=ce)return t&&console.debug(`Expanding port lookup to range [${u+1}, ${ce}].`),await(0,N.getPort)({portRange:[u+1,ce]});throw P}}function Ae(e){return Number.isFinite(e)&&e>=0}function cn(e,t){let r={},n;for(let s of t){let{databasePort:o,port:a,shadowDatabasePort:c}=s,i=ln(s);if(s.name===e){n={databasePort:o,port:a,shadowDatabasePort:c,streamsPort:i};continue}r[o]=!0,r[a]=!0,r[c]=!0,Ae(i)&&(r[i]=!0)}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}function ln(e){let t=e.experimental?.streams?.serverUrl;if(!t)return x;try{let r=Number(new URL(t).port);return Number.isInteger(r)&&r>0?r:x}catch{return x}}function un(e){return[e.port,e.databasePort,e.shadowDatabasePort,e.streamsPort]}async function dn(e){let{debug:t,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:s,requestedPort:o}=e;if(o!==H){if(o in s)throw t&&console.error(`Port ${o} was requested for "${n}", but is already used by another server.`),new _e(o);if(Object.values(r).includes(o))throw t&&console.error(`Port ${o} was requested for "${n}", but also for another key.`),new De(o);if((0,N.isUnsafePort)(o))throw t&&console.error(`Port ${o} was requested for "${n}", but is unsafe.`),new D(o);if(await(0,N.checkPort)(o)===!1)throw t&&console.error(`Port ${o} was requested for "${n}", but is not available.`),new D(o)}}var D=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},De=class extends Error{constructor(r){super(`Port number \`${r}\` was requested twice. Please choose a different port for each service.`);this.port=r}name="PortRequestedTwiceError"},_e=class extends Error{constructor(r){super(`Port number \`${r}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=r}name="PortBelongsToAnotherServerError"};m();var G=require("fs"),L=require("fs/promises"),Dt=require("module"),_t=require("path"),_=require("url"),mn=(0,Dt.createRequire)(h),pn=["initdb.wasm","pglite.data","pglite.wasm"],Ot={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"},It=[...pn.map(e=>({fileName:e,kind:"core",name:e})),...Object.entries(Ot).map(([e,t])=>({fileName:t,kind:"extension",name:e}))],ge=new Map,gn=Symbol.for("@prisma/dev/bundled-pglite-runtime-asset-sources"),pe=null;async function Lt(e){let t=fe(e),r=(0,_.fileURLToPath)(t);await(0,L.mkdir)(r,{recursive:!0});let n=[];for(let s of Ie()){let o=new URL(s.fileName,t),a=(0,_.fileURLToPath)(o);await(0,L.copyFile)(s.sourcePath,a),n.push({...s,destinationPath:a})}return n}function Ie(){let e=$t();return It.map(t=>({...t,sourcePath:(0,_.fileURLToPath)(new URL(t.fileName,e))}))}async function Le(){await wn();let e=Nt();if(e)return await Pn(e),await fn(e);let t=bn(),r=t.href,n=ge.get(r);return n||(n=hn(t),ge.set(r,n)),await n}async function fn(e){let t=`bundled:${e.wasmModule.href}:${e.fsBundle.href}`,r=ge.get(t);return r||(r=yn(e),ge.set(t,r)),await r}async function hn(e){let[t,r]=await Promise.all([(0,L.readFile)(new URL("pglite.data",e)),(0,L.readFile)(new URL("pglite.wasm",e))]),n=Bt();return{extensions:Object.fromEntries(Object.entries(Ot).map(([s,o])=>[s,new URL(o,e)])),fsBundle:new Blob([Uint8Array.from(t)]),wasmModule:await n.compile(r)}}async function yn(e){let[t,r]=await Promise.all([At(e.fsBundle),At(e.wasmModule)]),n=Bt();return{extensions:e.extensions,fsBundle:new Blob([Uint8Array.from(t)]),wasmModule:await n.compile(r)}}async function Pn(e){if(e.initdbWasm.protocol!=="file:")return;let t=new URL("initdb.wasm",fe(new URL("./",e.initdbWasm))),r=(0,_.fileURLToPath)(t);(0,G.existsSync)(r)||await(0,L.copyFile)((0,_.fileURLToPath)(e.initdbWasm),r)}function fe(e){return e instanceof URL?xt(e):xt((0,_.pathToFileURL)(e))}function xt(e){return e.href.endsWith("/")?e:new URL(`${e.href}/`)}function $t(){let e=mn.resolve("@electric-sql/pglite");return fe((0,_t.dirname)(e))}function bn(){let e=fe(new URL("./",h));if(Sn(e))return e;if(vn())return $t();throw new Error("Unable to locate PGlite runtime assets. If you bundled @prisma/dev, copy them next to the bundle with copyPrismaDevRuntimeAssets().")}function Sn(e){return It.every(t=>(0,G.existsSync)((0,_.fileURLToPath)(new URL(t.fileName,e))))}function Nt(){return globalThis[gn]??null}async function wn(){!En()||Nt()||(pe||(pe=import("./runtime-assets-manifest.bun.js").then(()=>{}).catch(e=>{throw pe=null,e})),await pe)}function vn(){let e=(0,_.fileURLToPath)(new URL("../package.json",h));if(!(0,G.existsSync)(e))return!1;try{return JSON.parse((0,G.readFileSync)(e,"utf8")).name==="@prisma/dev"}catch{return!1}}function En(){return typeof globalThis.Bun<"u"}function Bt(){let e=globalThis.WebAssembly;if(!e)throw new Error("WebAssembly is not available in this runtime.");return e}async function At(e){if(e.protocol==="file:")return await(0,L.readFile)(e);let t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch runtime asset ${e.href}: ${t.status} ${t.statusText}`);return new Uint8Array(await t.arrayBuffer())}m();var Be=require("@electric-sql/pglite"),O="_prisma_dev_wal",Ne="events",Ut="install_all_triggers",Ct="capture_event",kt="prisma_dev_wal_capture",z=new WeakMap,Rn=new Set(["ALTER","COMMIT","COPY","CREATE","DELETE","DROP","INSERT","MERGE","TRUNCATE","UPDATE"]);async function Ce(e,t){let r=z.get(e);if(r&&!r.closed)return r.bridge;let n=e.execProtocolRaw.bind(e),s=e.execProtocolRawStream.bind(e),o={bridge:{close:async()=>{o.closed||(o.closed=!0,o.subscribers.clear(),e.execProtocolRaw===a&&(e.execProtocolRaw=n),e.execProtocolRawStream===c&&(e.execProtocolRawStream=s),await o.pollPromise,z.delete(e))},poll:async()=>{await $e(o,e)},subscribe:i=>(o.subscribers.add(i),()=>{o.subscribers.delete(i)})},closed:!1,ensureInfrastructurePromise:null,pendingPoll:!1,pollPromise:null,subscribers:new Set,suppressDepth:0},a=async(i,l)=>{let u=await n(i,l);return!o.closed&&o.suppressDepth===0&&Wt(u)&&$e(o,e),u},c=async(i,l)=>{let u=[],p=new Be.protocol.Parser,g=l?.onRawData;await s(i,{...l,onRawData:P=>{p.parse(P,R=>{u.push(R)}),g?.(P)}}),!o.closed&&o.suppressDepth===0&&ke(u)&&$e(o,e)};return e.execProtocolRaw=a,e.execProtocolRawStream=c,z.set(e,o),await Ht(o,e),o.bridge}async function Mt(e){let t=z.get(e);t&&await t.bridge.close()}function ke(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&&Rn.has(r))return!0}return!1}function Wt(e){if(e.length===0)return!1;let t=[];return new Be.protocol.Parser().parse(e,n=>{t.push(n)}),ke(t)}async function Ht(e,t){e.ensureInfrastructurePromise??=Ue(e,t,async()=>{await t.exec(`CREATE SCHEMA IF NOT EXISTS "${O}"`),await t.exec(`
|
|
14
|
+
CREATE TABLE IF NOT EXISTS "${O}"."${Ne}" (
|
|
15
15
|
id BIGSERIAL PRIMARY KEY,
|
|
16
16
|
txid BIGINT NOT NULL DEFAULT txid_current(),
|
|
17
17
|
schema_name TEXT NOT NULL,
|
|
@@ -22,7 +22,7 @@ Received data: ${u}`));n({childProcess:a,url:`http://${y}:${R}`})},i=u=>{this.#t
|
|
|
22
22
|
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()
|
|
23
23
|
)
|
|
24
24
|
`),await t.exec(`
|
|
25
|
-
CREATE OR REPLACE FUNCTION "${O}"."${
|
|
25
|
+
CREATE OR REPLACE FUNCTION "${O}"."${Ct}"()
|
|
26
26
|
RETURNS trigger
|
|
27
27
|
LANGUAGE plpgsql
|
|
28
28
|
AS $$
|
|
@@ -31,7 +31,7 @@ Received data: ${u}`));n({childProcess:a,url:`http://${y}:${R}`})},i=u=>{this.#t
|
|
|
31
31
|
RETURN COALESCE(NEW, OLD);
|
|
32
32
|
END IF;
|
|
33
33
|
|
|
34
|
-
INSERT INTO "${O}"."${
|
|
34
|
+
INSERT INTO "${O}"."${Ne}" (
|
|
35
35
|
txid,
|
|
36
36
|
schema_name,
|
|
37
37
|
table_name,
|
|
@@ -52,7 +52,7 @@ Received data: ${u}`));n({childProcess:a,url:`http://${y}:${R}`})},i=u=>{this.#t
|
|
|
52
52
|
END;
|
|
53
53
|
$$;
|
|
54
54
|
`),await t.exec(`
|
|
55
|
-
CREATE OR REPLACE FUNCTION "${O}"."${
|
|
55
|
+
CREATE OR REPLACE FUNCTION "${O}"."${Ut}"()
|
|
56
56
|
RETURNS void
|
|
57
57
|
LANGUAGE plpgsql
|
|
58
58
|
AS $$
|
|
@@ -72,28 +72,28 @@ Received data: ${u}`));n({childProcess:a,url:`http://${y}:${R}`})},i=u=>{this.#t
|
|
|
72
72
|
SELECT 1
|
|
73
73
|
FROM pg_trigger
|
|
74
74
|
WHERE tgrelid = target
|
|
75
|
-
AND tgname = '${
|
|
75
|
+
AND tgname = '${kt}'
|
|
76
76
|
) THEN
|
|
77
77
|
CONTINUE;
|
|
78
78
|
END IF;
|
|
79
79
|
|
|
80
80
|
EXECUTE format(
|
|
81
|
-
'CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION "${O}"."${
|
|
82
|
-
'${
|
|
81
|
+
'CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION "${O}"."${Ct}"()',
|
|
82
|
+
'${kt}',
|
|
83
83
|
target::text
|
|
84
84
|
);
|
|
85
85
|
END LOOP;
|
|
86
86
|
END;
|
|
87
87
|
$$;
|
|
88
|
-
`),await
|
|
88
|
+
`),await Gt(e,t)}),await e.ensureInfrastructurePromise}async function Gt(e,t){await Ue(e,t,async()=>{await t.query(`SELECT "${O}"."${Ut}"()`)})}async function Tn(e,t){await Ht(e,t),await Gt(e,t);let r=await Ue(e,t,async()=>await t.query(`
|
|
89
89
|
WITH drained AS (
|
|
90
|
-
DELETE FROM "${O}"."${
|
|
90
|
+
DELETE FROM "${O}"."${Ne}"
|
|
91
91
|
RETURNING txid, schema_name, table_name, op, row_data, old_row_data, id
|
|
92
92
|
)
|
|
93
93
|
SELECT txid, schema_name, table_name, op, row_data, old_row_data
|
|
94
94
|
FROM drained
|
|
95
95
|
ORDER BY id
|
|
96
|
-
`));if(r.rows.length===0||e.subscribers.size===0)return;let n=r.rows.map(
|
|
96
|
+
`));if(r.rows.length===0||e.subscribers.size===0)return;let n=r.rows.map(xn);for(let s of e.subscribers)queueMicrotask(()=>{if(!e.closed&&e.subscribers.has(s))try{s(n)}catch(o){console.error("[WAL bridge] subscriber failed",o)}})}async function $e(e,t){if(!e.closed){if(e.pollPromise){e.pendingPoll=!0,await e.pollPromise;return}e.pollPromise=(async()=>{do e.pendingPoll=!1,await Tn(e,t);while(e.pendingPoll&&!e.closed)})().finally(()=>{e.pollPromise=null}),await e.pollPromise}}async function Ue(e,t,r){e.suppressDepth+=1;try{return await r()}finally{e.suppressDepth-=1,e.suppressDepth===0&&!e.closed&&z.get(t)!==e&&(e.closed=!0)}}function xn(e){return{oldRecord:e.old_row_data,record:e.row_data,schema:e.schema_name,table:e.table_name,txid:String(e.txid),type:An(e.op)}}function An(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 Dn=10,S={connectionLimit:Dn,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},_n=`postgres://${S.username}:${S.password}@localhost`,Kt=new URLSearchParams({sslmode:S.sslMode}),On=new URLSearchParams({...Object.fromEntries(Kt.entries()),connection_limit:String(S.connectionLimit),connect_timeout:String(S.connectTimeout),max_idle_connection_lifetime:String(S.maxIdleConnectionLifetime),pool_timeout:String(S.poolTimeout),socket_timeout:String(S.socketTimeout)});async function zt(e){let{rows:t}=await e.query("SELECT EXISTS(SELECT 1 FROM pg_roles WHERE rolname = 'postgres') AS exists");t[0]?.exists?await e.exec(`ALTER ROLE ${S.username} WITH LOGIN SUPERUSER PASSWORD '${S.password}'`):await e.exec(`CREATE ROLE ${S.username} WITH LOGIN SUPERUSER PASSWORD '${S.password}'`),await e.exec(`SET ROLE ${S.username}`)}async function Me(e,t){let r=e==="database"?t.databasePort:t.shadowDatabasePort;if(t.dryRun)return jt(e,t,{db:null,port:r,server:null});let{debug:n}=t,o=await(e==="shadow_database"?In:Jt)(t.pgliteDataDirPath,n);n&&o.onNotification((u,p)=>{console.debug(`[${e}][${u}] ${p}`)});let{PGLiteSocketServer:a}=await import("@electric-sql/pglite-socket"),c=e==="shadow_database"?t.shadowDatabaseIdleTimeoutMillis:t.databaseIdleTimeoutMillis,i=new a({db:o,debug:n,idleTimeout:Number.isFinite(c)?c:0,inspect:n,maxConnections:S.connectionLimit,port:r});n&&(i.addEventListener("listening",u=>{let{detail:p}=u;console.debug(`[${e}] server listening on ${JSON.stringify(p)}`)}),i.addEventListener("connection",u=>{let{clientAddress:p,clientPort:g}=u.detail;console.debug(`[${e}] client connected from ${p}:${g}`)}),i.addEventListener("error",u=>{let{detail:p}=u;console.error(`[${e}] server error:`,p)}));try{await i.start()}catch(u){throw u instanceof Error&&"code"in u&&u.code==="EADDRINUSE"?new D(r):u}let l=Number(i.getServerConn().split(":").at(1));return t[e==="database"?"databasePort":"shadowDatabasePort"]=l,jt(e,t,{db:o,port:l,server:i})}function jt(e,t,r){let{debug:n}=t,{db:s,port:o,server:a}=r||{},c=new Map;return n&&console.debug(`[${e}] server started on port ${o}`),{...S,attachWalEventBridge:async()=>{if(e!=="database"||!s)throw new Error("WAL bridge is only available for the primary database server");return await Ce(s)},close:async()=>{let i=[];try{await a?.stop(),n&&console.debug(`[${e}] server stopped on port ${o}`)}catch(l){console.error(`[${e}] server stop error`,l),i.push(l)}if(e==="database"){try{s&&await Mt(s),n&&console.debug(`[${e}] closed WAL bridge`)}catch(l){console.error(`[${e}] WAL bridge close error`,l),i.push(l)}try{await s?.syncToFs(),n&&console.debug(`[${e}] synced to filesystem`)}catch(l){console.error(`[${e}] sync error`,l),i.push(l)}}try{await s?.close(),n&&console.debug(`[${e}] closed`)}catch(l){console.error(`[${e}] close error`,l),i.push(l)}if(i.length>0)throw new AggregateError(i,`Failed to close ${e} properly`)},connectionString:Ft(o,Kt),dump:async i=>{e==="shadow_database"||!s||await $n({db:s,debug:n,destinationPath:i})},getPrimaryKeyColumns:async(i,l)=>{if(e==="shadow_database"||!s)throw new Error("Primary key resolution is only available for the primary database server");let u=`${i}.${l}`,p=c.get(u);return p||(p=Ln(s,i,l).catch(g=>{throw c.delete(u),g}),c.set(u,p)),await p},port:o,prismaORMConnectionString:Ft(o,On),terminalCommand:`PGPASSWORD=${S.password} PGSSLMODE=${S.sslMode} psql -h localhost -p ${o} -U ${S.username} -d ${S.database}`}}function Ft(e,t){return`${_n}:${e}/${S.database}?${t.toString()}`}async function Jt(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await Le(),s=await r.create({database:S.database,dataDir:e,debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,relaxedDurability:!1,wasmModule:n.wasmModule});return await zt(s),s}async function In(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await Le(),s=await r.create({database:S.database,dataDir:"memory://",debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,relaxedDurability:!1,wasmModule:n.wasmModule});return await zt(s),s}async function Ln(e,t,r){let{rows:n}=await e.query(`
|
|
97
97
|
SELECT attribute.attname AS column_name
|
|
98
98
|
FROM pg_constraint pk_constraint
|
|
99
99
|
INNER JOIN pg_class relation
|
|
@@ -106,9 +106,9 @@ Received data: ${u}`));n({childProcess:a,url:`http://${y}:${R}`})},i=u=>{this.#t
|
|
|
106
106
|
ON attribute.attrelid = relation.oid
|
|
107
107
|
AND attribute.attnum = keys.attnum
|
|
108
108
|
WHERE pk_constraint.contype = 'p'
|
|
109
|
-
AND namespace.nspname = ${
|
|
110
|
-
AND relation.relname = ${
|
|
109
|
+
AND namespace.nspname = ${qt(t)}
|
|
110
|
+
AND relation.relname = ${qt(r)}
|
|
111
111
|
ORDER BY keys.ordinality
|
|
112
|
-
`);return n.map(
|
|
113
|
-
${JSON.stringify(c,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new Z({databasePort:i.databasePort,debug:r,dryRun:!1,name:n,pid:i.pid,port:i.port,serverDump:i,shadowDatabasePort:i.shadowDatabasePort})}static async scan(t){let{debug:r,globs:n}=t??{},
|
|
114
|
-
`,{encoding:"utf-8"})}};async function oo(e,t){let{debug:r,onlyMetadata:n}=t||{},o=typeof e=="string"?e:e.name,s=typeof e!="string"?e:void 0,a={databasePort:s?.databasePort??-1,experimental:s?.experimental,exports:s?.exports,name:o,pid:s?.pid,port:s?.port??-1,shadowDatabasePort:s?.shadowDatabasePort??-1,version:"1"};try{let c=s||await I.fromServerDump({debug:r,name:o});if(!c)return r&&console.debug(`[State] no server state found for name: ${o}`),{...a,status:"no_such_server"};a.databasePort=c.databasePort,a.experimental=c.experimental,a.exports=c.exports,a.pid=c.pid,a.port=c.port,a.shadowDatabasePort=c.shadowDatabasePort;let{exports:i,pid:l}=c;if(n)return{...a,status:"unknown"};if(!Dr(l,r))return r&&console.debug(`[State] server state for "${o}" has no running process with PID: ${l}`),{...a,status:"not_running"};let u=V(o);try{if(!await(0,q.check)(u,{lockfilePath:(0,U.join)(u,".lock")}))return r&&console.debug(`[State] server state for "${o}" is not locked, indicating it is not running.`),{...a,status:"not_running"}}catch(A){r&&console.error(`[State] server state for "${o}" failed to check lock:`,A)}if(!i)return{...a,status:"starting_up"};let{http:p}=i,{hc:g}=await import("hono/client"),y=await g(p.url).health.$get();if(!y.ok)return r&&console.debug(`[State] server state for "${o}" is not live: ${JSON.stringify(y)}`),{...a,status:"not_running"};let R=await y.json();return R.name!==e?(r&&console.debug(`[State] server state for "${o}" has mismatched health response: ${JSON.stringify(R)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${e}" is live: ${JSON.stringify(R)}`),{...a,status:"running"})}catch(c){return r&&console.error(`[State] failed to get server status for "${o}":`,c),{...a,status:"error"}}}var tt=class extends Error{name="ServerStateAlreadyExistsError";constructor(t){super(`A Prisma Dev server with the name "${t}" is already running.`)}},te=class extends tt{#r;name="ServerAlreadyRunningError";constructor(t){super(t.name),this.#r=t}get server(){return I.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};m();var Nr=require("crypto"),ot=require("timers/promises"),Br=require("std-env");W();var so="application/json",st={connection:"close","content-type":so},ao={interpreter:{apiVersion:"durable.streams/stream-interpreter/v1",format:"durable.streams/state-protocol/v1",touch:{enabled:!0,onMissingBefore:"coarse"}}};async function Cr(e){let{dbServer:t,debug:r,name:n,persistenceMode:o,port:s,walBridge:a}=e,c=o==="stateless",i=c?po(n):n;Br.process.env.DS_LOCAL_DATA_ROOT=Ye(),c&&await z(X(i));let{startLocalDurableStreamsServer:l}=await import("@prisma/streams-local"),u=await l({hostname:"127.0.0.1",name:i,port:s}),p={serverUrl:u.exports.http.url,sqlitePath:u.exports.sqlite.path,streamName:Qe,url:_r(u.exports.http.url)};try{await io(p);let g=new at({dbServer:t,debug:r,streamUrl:p.url}),y=a.subscribe(R=>{g.enqueue(R)});return{close:async()=>{y(),await g.close(),await u.close(),await(0,ot.setTimeout)(100),c&&await z(X(i))},experimental:p}}catch(g){throw await u.close().catch(()=>{}),await(0,ot.setTimeout)(100),c&&await z(X(i)).catch(()=>{}),g}}var at=class{#r;#e;#t;#o;#s;constructor(t){this.#r=t.dbServer,this.#e=t.debug,this.#t=Promise.resolve(),this.#o=t.streamUrl,this.#s=new Set}enqueue(t){t.length!==0&&(this.#t=this.#t.then(async()=>{let r=await this.#a(t);r.length!==0&&(await co(this.#o,r),this.#e&&console.debug(`[streams] appended ${r.length} state-protocol record(s) to ${this.#o}`))}).catch(r=>{console.error("[streams] failed to ingest WAL events into prisma-wal",r)}))}async close(){await this.#t}async#a(t){let r=[],n=new Date().toISOString();for(let o of t)r.push(...await this.#n(o,n));return r}async#n(t,r){let n=`${t.schema}.${t.table}`,o=await this.#r.getPrimaryKeyColumns(t.schema,t.table),s=$r(t.record),a=$r(t.oldRecord),c=this.#i(n,o,a),i=this.#i(n,o,s),l=t.txid===""?void 0:t.txid;return t.type==="insert"?s&&i?[{headers:{operation:"insert",timestamp:r,txid:l},key:i,oldValue:null,type:n,value:s}]:[]:t.type==="delete"?a&&c?[{headers:{operation:"delete",timestamp:r,txid:l},key:c,oldValue:a,type:n,value:null}]:[]:!s||!a||!c||!i?[]:c!==i?[{headers:{operation:"delete",timestamp:r,txid:l},key:c,oldValue:a,type:n,value:null},{headers:{operation:"insert",timestamp:r,txid:l},key:i,oldValue:null,type:n,value:s}]:[{headers:{operation:"update",timestamp:r,txid:l},key:i,oldValue:a,type:n,value:s}]}#i(t,r,n){if(!n)return null;let o=lo(n,r);return o||(this.#s.has(t)||(this.#s.add(t),console.warn(`[streams] falling back to full-row keys for ${t} because no primary key could be resolved`)),uo(n))}};async function io(e){let t=await fetch(e.url,{headers:st,method:"PUT"});if(!t.ok)throw await it(t,`Failed to create ${e.streamName}`);let r=await fetch(`${e.url}/_schema`,{body:JSON.stringify(ao),headers:st,method:"POST"});if(!r.ok)throw await it(r,`Failed to configure ${e.streamName}`)}async function co(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:st,method:"POST"});if(!r.ok)throw await it(r,"Failed to append to prisma-wal")}async function it(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}function lo(e,t){if(t.length===0)return null;let r=[];for(let n of t){if(!Object.prototype.hasOwnProperty.call(e,n))return null;let o=mo(e[n]);if(o==null)return null;r.push(t.length===1?o:`${n}=${o}`)}return r.join("|")}function uo(e){return JSON.stringify(ct(e))}function ct(e){return Array.isArray(e)?e.map(t=>ct(t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,ct(r)])):e}function $r(e){return e?structuredClone(e):null}function mo(e){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return e;if(typeof e=="number")return Number.isFinite(e)?String(e):null;if(typeof e=="bigint")return e.toString();if(typeof e=="boolean")return e?"true":"false";try{return JSON.stringify(e)}catch{return null}}function po(e){return`${e}.${(0,Nr.randomUUID)().replaceAll("-","")}`}async function kr(e){let t=await I.createExclusively(e),r=null,n=null,o=null,s=null;try{[r,o]=await Promise.all([ke("database",t),ke("shadow_database",t)]);let a;t.dryRun?(a=Po(),s=yo()):(a=await r.attachWalEventBridge(),s=await Cr({dbServer:r,debug:t.debug,name:t.name,port:t.streamsPort,persistenceMode:t.persistenceMode,walBridge:a})),n=await xr(r,t);let c=go(r,o,n,t);await t.writeServerDump(c,t.dryRun?{}:{streams:s.experimental});let i=ho(a),l=r,u=o,p=n,g=s,y=async()=>{i.close(),await Ur(t,[p,g,l,u])};return{close:y,dbServer:r,httpServer:n,server:{...c,close:y,experimental:{streams:s.experimental,wal:i.api},name:t.name},serverState:t,shadowDbServer:o,streamsServer:s,walBridge:a}}catch(a){return await fo(t,[n,s,r,o],a)}}function go(e,t,r,n){let o=`prisma+postgres://localhost:${r.port}/?${new URLSearchParams({api_key:dt({databaseUrl:e.prismaORMConnectionString,name:n.name,shadowDatabaseUrl:t.prismaORMConnectionString})}).toString()}`;return{database:{connectionString:e.connectionString,prismaORMConnectionString:e.prismaORMConnectionString,terminalCommand:e.terminalCommand},http:{url:r.url},ppg:{url:o},shadowDatabase:{connectionString:t.prismaORMConnectionString,prismaORMConnectionString:t.prismaORMConnectionString,terminalCommand:t.terminalCommand}}}async function Ur(e,t){let n=(await Promise.allSettled(t.map(o=>o.close()))).filter(o=>o.status==="rejected").map(o=>new Error(o.reason));try{await e.close()}catch(o){n.push(o)}if(n.length>0)throw new AggregateError(n,"Failed to close some servers")}async function fo(e,t,r){try{await Ur(e,t.filter(n=>n!==null))}catch(n){throw new AggregateError([r,n],"Failed to start Prisma Dev server cleanly")}throw r}function ho(e){let t=new Set;return{api:{stream:()=>{let r=()=>{},n=bo(e,()=>{t.delete(r)});return r=()=>n.close(),t.add(r),n.stream},subscribe:r=>e.subscribe(r)},close:()=>{for(let r of[...t])r();t.clear()}}}function Po(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function yo(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function bo(e,t){let r=[],n=!1,o=null,s=e.subscribe(c=>{if(!n){if(o){let i=o;o=null,i.resolve({done:!1,value:c});return}r.push(c)}}),a=()=>{if(!n&&(n=!0,s(),r.length=0,t(),o)){let c=o;o=null,c.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((c,i)=>{o={reject:i,resolve:c}})},return(){return a(),Promise.resolve({done:!0,value:void 0})},throw(c){let i=o;return a(),i&&i.reject(c),Promise.reject(c instanceof Error?c:new Error(String(c)))}}}}async function Mr(e){let{server:t}=await kr(e);return t}async function So(e){return await Mr(e)}0&&(module.exports={DEFAULT_DATABASE_PORT,DEFAULT_SERVER_PORT,DEFAULT_SHADOW_DATABASE_PORT,PortNotAvailableError,ServerAlreadyRunningError,copyPrismaDevRuntimeAssets,getPrismaDevRuntimeAssetManifest,startPrismaDevServer,unstable_startServer});
|
|
112
|
+
`);return n.map(s=>s.column_name)}function qt(e){return`'${e.replaceAll("'","''")}'`}async function $n(e){let{dataDir:t,db:r,debug:n,destinationPath:s}=e,o=r||await Jt(t,n),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),c=await a({args:["--schema-only","--no-owner"],fileName:s?(0,Vt.filename)(s):void 0,pg:await o.clone()});return s?(n&&console.debug(`[DB] Dumping database to ${s}`),await wt(c,s)):(n&&console.debug("[DB] Dumping database to memory"),await c.text())}m();var Tr=require("http"),xr=require("util"),Ar=w(require("@prisma/get-platform"),1);We();He();async function Dr(e,t){let{port:r}=t;if(t.dryRun)return Rr(r,null);let n=await Zn(e,t),{promise:s,reject:o,resolve:a}=he(),{serve:c}=await import("@hono/node-server"),i=c({createServer:Tr.createServer,fetch:n.fetch,overrideGlobalObjects:!1,port:r},a);i.on("error",u=>{if(typeof u=="object"&&"code"in u&&u.code==="EADDRINUSE")return o(new D(r));console.error("[Accelerate]",u)});let{port:l}=await s;return t.port=l,Rr(l,i)}function Rr(e,t){return{async close(){t&&await Promise.allSettled([(0,xr.promisify)(t.close.bind(t))(),F.stopAll()])},port:e,url:`http://localhost:${e}`}}async function Zn(e,t){let{debug:r}=t,[{Hono:n},{accelerateRoute:s},{utilityRoute:o}]=await Promise.all([import("hono/tiny"),Promise.resolve().then(()=>(br(),Pr)),Promise.resolve().then(()=>(Er(),vr))]),a=new n,c=await Ar.default.getPlatformInfo();if(r&&console.debug("[Accelerate] platform info: %s",JSON.stringify(c)),r){let{logger:l}=await import("hono/logger");a.use("*",l((...u)=>console.log("[Accelerate]",...u)))}a.use("*",async(l,u)=>(l.set("databaseDumpPath",t.databaseDumpPath),l.set("db",e),l.set("debug",!!r),l.set("name",t.name),l.set("platform",c),l.set("shadowDBPort",t.shadowDatabasePort),await u()));let i=new n;return i.route("/",s),i.route("/",o),a.route("/",i),a}m();var Nr=require("fs/promises"),U=require("pathe"),q=require("proper-lockfile"),st=require("std-env"),d=require("valibot");W();m();var es=require("timers/promises"),_r=require("std-env");function Or(e,t){if(e==null)return!1;try{return _r.process.kill?.(e,0)??!0}catch(r){return t&&console.error(`Error checking if process with PID ${e} exists:`,r),!1}}m();var Ye=require("pathe");W();var Xe="prisma-wal";function Ze(){return(0,Ye.join)(ie.data,"durable-streams")}function X(e){return(0,Ye.join)(Ze(),e)}function Ir(e,t=Xe){return new URL(`/v1/stream/${encodeURIComponent(t)}`,e).toString()}var ee=(0,d.pipe)((0,d.string)(),(0,d.url)()),Lr=(0,d.object)({connectionString:ee,prismaORMConnectionString:(0,d.optional)(ee),terminalCommand:(0,d.optional)((0,d.string)())}),$r=(0,d.object)({url:ee}),ts=(0,d.object)({serverUrl:ee,sqlitePath:(0,d.pipe)((0,d.string)(),(0,d.minLength)(1)),streamName:(0,d.pipe)((0,d.string)(),(0,d.minLength)(1)),url:ee}),rs=(0,d.object)({streams:(0,d.optional)(ts)}),et=(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(1)),ns=(0,d.object)({database:Lr,http:$r,ppg:$r,shadowDatabase:Lr}),ss=(0,d.object)({databasePort:et,experimental:(0,d.optional)(rs),exports:(0,d.optional)(ns),name:(0,d.pipe)((0,d.string)(),(0,d.minLength)(1)),pid:(0,d.optional)((0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(0))),port:et,shadowDatabasePort:et,version:(0,d.literal)("1")}),ot=Symbol("initialize"),tt="default",os=new Set(["durable-streams"]),I=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;_streamsPort;constructor(t){this._databasePort=t.databasePort??x,this.databaseConnectTimeoutMillis=t.databaseConnectTimeoutMillis??6e4,this.databaseIdleTimeoutMillis=t.databaseIdleTimeoutMillis??1/0,this.debug=t.debug??!1,this.dryRun=t.dryRun??!1,this.name=t.name??tt,this.persistenceMode=t.persistenceMode,this.pid=t.pid??st.process.pid,this.shadowDatabaseConnectTimeoutMillis=t.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=t.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=t.port??x,this._shadowDatabasePort=t.shadowDatabasePort??x,this._streamsPort=x}static async createExclusively(t){let r=t?.dryRun!==!0&&t?.persistenceMode==="stateful"?new Z(t):new rt(t);return await r[ot](),r}static async fromServerDump(t){let{debug:r,name:n=tt}=t??{},s=V(n),o=Z.getServerDumpPath(s),a=await vt(o);if(a==null)return r&&console.debug(`[State] No server dump file found at: ${o}`),null;r&&(console.debug(`[State] server dump file found at "${o}":`),console.debug(a));let{issues:c,output:i,success:l}=(0,d.safeParse)((0,d.pipe)((0,d.string)(),(0,d.parseJson)(),ss),a);if(!l)throw r&&console.debug(`[State] Invalid server dump file at "${o}":
|
|
113
|
+
${JSON.stringify(c,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new Z({databasePort:i.databasePort,debug:r,dryRun:!1,name:n,pid:i.pid,port:i.port,serverDump:i,shadowDatabasePort:i.shadowDatabasePort})}static async scan(t){let{debug:r,globs:n}=t??{},s=(0,U.join)(V(tt),"..");r&&console.debug(`[State] scanning for server states in: ${s}`);let o=(await Rt(s,n)).filter(a=>!os.has(a));return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(a=>as(a,t)))}get databasePort(){return this._databasePort}set databasePort(t){this.#r("databasePort",t)}get port(){return this._port}set port(t){this.#r("port",t)}get shadowDatabasePort(){return this._shadowDatabasePort}get streamsPort(){return this._streamsPort}set shadowDatabasePort(t){this.#r("shadowDatabasePort",t)}#r(t,r){if(r<0||!Number.isInteger(r))throw new Error(`Invalid port number: ${r}`);let n=`_${t}`;if(this[n]!==H&&this[n]!==r)throw new Error(`\`${t}\` is already set to ${this[n]}, cannot change it to ${r}`);this[n]=r}},rt=class extends I{constructor(t){super({...t,databasePort:t?.databasePort||H,persistenceMode:"stateless",port:t?.port||H,shadowDatabasePort:t?.shadowDatabasePort||H})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[ot](){let t;try{t=await I.scan({debug:this.debug,onlyMetadata:!0})}catch(n){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",n),t=[]}let r=await Oe({debug:this.debug,name:this.dryRun?this.name:"",requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:t});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,this._streamsPort=r.streamsPort}async close(){}async writeServerDump(){}},Z=class e extends I{#r;#e;#t;#s;#o;#a;#n;constructor(t){super({...t,persistenceMode:"stateful"}),this.#a=!1,this.#e=V(this.name),this.#r=(0,U.join)(this.#e,"db_dump.bak"),this.#t=(0,U.join)(this.#e,".lock"),this.#s=(0,U.join)(this.#e,".pglite"),this.#n=t?.serverDump??null,this.#o=e.getServerDumpPath(this.#e)}static getServerDumpPath(t){return(0,U.join)(t,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#n?.exports}get experimental(){return this.#n?.experimental}get pgliteDataDirPath(){return this.#s}async[ot](){await Et(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,q.lock)(this.#e,{lockfilePath:this.#t}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let t=await I.scan({debug:this.debug,onlyMetadata:!0}),r=await Oe({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:t});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,this._streamsPort=r.streamsPort,await this.writeServerDump()}catch(t){throw t instanceof Error&&"code"in t&&t.code==="ELOCKED"?new te(this):t}}async close(){if(!this.#a)try{await(0,q.unlock)(this.#e,{lockfilePath:this.#t}),this.#a=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(t){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,t),t}}async writeServerDump(t,r){this.#n={name:this.name,version:"1",pid:st.process.pid,port:this.port,databasePort:this.databasePort,experimental:r,shadowDatabasePort:this.shadowDatabasePort,exports:t},await(0,Nr.writeFile)(this.#o,`${JSON.stringify(this.#n,null,2)}
|
|
114
|
+
`,{encoding:"utf-8"})}};async function as(e,t){let{debug:r,onlyMetadata:n}=t||{},s=typeof e=="string"?e:e.name,o=typeof e!="string"?e:void 0,a={databasePort:o?.databasePort??-1,experimental:o?.experimental,exports:o?.exports,name:s,pid:o?.pid,port:o?.port??-1,shadowDatabasePort:o?.shadowDatabasePort??-1,version:"1"};try{let c=o||await I.fromServerDump({debug:r,name:s});if(!c)return r&&console.debug(`[State] no server state found for name: ${s}`),{...a,status:"no_such_server"};a.databasePort=c.databasePort,a.experimental=c.experimental,a.exports=c.exports,a.pid=c.pid,a.port=c.port,a.shadowDatabasePort=c.shadowDatabasePort;let{exports:i,pid:l}=c;if(n)return{...a,status:"unknown"};if(!Or(l,r))return r&&console.debug(`[State] server state for "${s}" has no running process with PID: ${l}`),{...a,status:"not_running"};let u=V(s);try{if(!await(0,q.check)(u,{lockfilePath:(0,U.join)(u,".lock")}))return r&&console.debug(`[State] server state for "${s}" is not locked, indicating it is not running.`),{...a,status:"not_running"}}catch(A){r&&console.error(`[State] server state for "${s}" failed to check lock:`,A)}if(!i)return{...a,status:"starting_up"};let{http:p}=i,{hc:g}=await import("hono/client"),P=await g(p.url).health.$get();if(!P.ok)return r&&console.debug(`[State] server state for "${s}" is not live: ${JSON.stringify(P)}`),{...a,status:"not_running"};let R=await P.json();return R.name!==e?(r&&console.debug(`[State] server state for "${s}" has mismatched health response: ${JSON.stringify(R)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${e}" is live: ${JSON.stringify(R)}`),{...a,status:"running"})}catch(c){return r&&console.error(`[State] failed to get server status for "${s}":`,c),{...a,status:"error"}}}var nt=class extends Error{name="ServerStateAlreadyExistsError";constructor(t){super(`A Prisma Dev server with the name "${t}" is already running.`)}},te=class extends nt{#r;name="ServerAlreadyRunningError";constructor(t){super(t.name),this.#r=t}get server(){return I.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};m();var Cr=require("crypto"),at=require("timers/promises"),it=require("util"),kr=require("std-env");W();var is="application/json",re={connection:"close","content-type":is},cs={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},ct={apiVersion:"durable.streams/schema-registry/v1",schema:{additionalProperties:!0,properties:{headers:{properties:{operation:{type:"string"},timestamp:{format:"date-time",type:"string"}},required:["timestamp","operation"],type:"object"},key:{type:"string"},type:{type:"string"}},required:["type","key","headers"],type:"object"},search:{aliases:{rowKey:"key",table:"type"},fields:{eventTime:{bindings:[{jsonPointer:"/headers/timestamp",version:1}],column:!0,exact:!0,exists:!0,kind:"date",sortable:!0},key:{bindings:[{jsonPointer:"/key",version:1}],exact:!0,exists:!0,kind:"keyword"},operation:{bindings:[{jsonPointer:"/headers/operation",version:1}],exact:!0,exists:!0,kind:"keyword"},type:{bindings:[{jsonPointer:"/type",version:1}],exact:!0,exists:!0,kind:"keyword"}},primaryTimestampField:"eventTime"}};async function Ur(e){let{dbServer:t,debug:r,name:n,persistenceMode:s,port:o,walBridge:a}=e,c=s==="stateless",i=c?hs(n):n;kr.process.env.DS_LOCAL_DATA_ROOT=Ze(),c&&await K(X(i));let{startLocalDurableStreamsServer:l}=await import("@prisma/streams-local"),u=await l({hostname:"127.0.0.1",name:i,port:o}),p={serverUrl:u.exports.http.url,sqlitePath:u.exports.sqlite.path,streamName:Xe,url:Ir(u.exports.http.url)};try{await ls(p);let g=new lt({dbServer:t,debug:r,streamUrl:p.url}),P=a.subscribe(R=>{g.enqueue(R)});return{close:async()=>{P(),await g.close(),await u.close(),await(0,at.setTimeout)(100),c&&await K(X(i))},experimental:p}}catch(g){throw await u.close().catch(()=>{}),await(0,at.setTimeout)(100),c&&await K(X(i)).catch(()=>{}),g}}var lt=class{#r;#e;#t;#s;#o;constructor(t){this.#r=t.dbServer,this.#e=t.debug,this.#t=Promise.resolve(),this.#s=t.streamUrl,this.#o=new Set}enqueue(t){t.length!==0&&(this.#t=this.#t.then(async()=>{let r=await this.#a(t);r.length!==0&&(await ms(this.#s,r),this.#e&&console.debug(`[streams] appended ${r.length} state-protocol record(s) to ${this.#s}`))}).catch(r=>{console.error("[streams] failed to ingest WAL events into prisma-wal",r)}))}async close(){await this.#t}async#a(t){let r=[],n=new Date().toISOString();for(let s of t)r.push(...await this.#n(s,n));return r}async#n(t,r){let n=`${t.schema}.${t.table}`,s=await this.#r.getPrimaryKeyColumns(t.schema,t.table),o=Br(t.record),a=Br(t.oldRecord),c=this.#i(n,s,a),i=this.#i(n,s,o),l=t.txid===""?void 0:t.txid;return t.type==="insert"?o&&i?[{headers:{operation:"insert",timestamp:r,txid:l},key:i,oldValue:null,type:n,value:o}]:[]:t.type==="delete"?a&&c?[{headers:{operation:"delete",timestamp:r,txid:l},key:c,oldValue:a,type:n,value:null}]:[]:!o||!a||!c||!i?[]:c!==i?[{headers:{operation:"delete",timestamp:r,txid:l},key:c,oldValue:a,type:n,value:null},{headers:{operation:"insert",timestamp:r,txid:l},key:i,oldValue:null,type:n,value:o}]:[{headers:{operation:"update",timestamp:r,txid:l},key:i,oldValue:a,type:n,value:o}]}#i(t,r,n){if(!n)return null;let s=ps(n,r);return s||(this.#o.has(t)||(this.#o.add(t),console.warn(`[streams] falling back to full-row keys for ${t} because no primary key could be resolved`)),gs(n))}};async function ls(e){let t=await fetch(e.url,{headers:re,method:"PUT"});if(!t.ok)throw await ne(t,`Failed to create ${e.streamName}`);let r=await fetch(`${e.url}/_profile`,{body:JSON.stringify(cs),headers:re,method:"POST"});if(!r.ok)throw await ne(r,`Failed to configure ${e.streamName}`);let n=await us(e);if(ds(n,e.streamName))return;if(n.currentVersion>0)throw new Error(`Failed to install schema for ${e.streamName}: existing schema registry is incompatible and requires a lens migration`);let s=await fetch(`${e.url}/_schema`,{body:JSON.stringify(ct),headers:re,method:"POST"});if(!s.ok)throw await ne(s,`Failed to install schema for ${e.streamName}`)}async function us(e){let t=await fetch(`${e.url}/_schema`,{headers:re,method:"GET"});if(!t.ok)throw await ne(t,`Failed to inspect schema for ${e.streamName}`);return await t.json()}function ds(e,t){if(e.currentVersion<=0||e.schema!==t)return!1;let r=e.schemas[String(e.currentVersion)];return(0,it.isDeepStrictEqual)(r,ct.schema)&&(0,it.isDeepStrictEqual)(e.search,ct.search)}async function ms(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:re,method:"POST"});if(!r.ok)throw await ne(r,"Failed to append to prisma-wal")}async function ne(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}function ps(e,t){if(t.length===0)return null;let r=[];for(let n of t){if(!Object.prototype.hasOwnProperty.call(e,n))return null;let s=fs(e[n]);if(s==null)return null;r.push(t.length===1?s:`${n}=${s}`)}return r.join("|")}function gs(e){return JSON.stringify(ut(e))}function ut(e){return Array.isArray(e)?e.map(t=>ut(t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,ut(r)])):e}function Br(e){return e?structuredClone(e):null}function fs(e){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return e;if(typeof e=="number")return Number.isFinite(e)?String(e):null;if(typeof e=="bigint")return e.toString();if(typeof e=="boolean")return e?"true":"false";try{return JSON.stringify(e)}catch{return null}}function hs(e){return`${e}.${(0,Cr.randomUUID)().replaceAll("-","")}`}async function Mr(e){let t=await I.createExclusively(e),r=null,n=null,s=null,o=null;try{[r,s]=await Promise.all([Me("database",t),Me("shadow_database",t)]);let a;t.dryRun?(a=Ss(),o=ws()):(a=await r.attachWalEventBridge(),o=await Ur({dbServer:r,debug:t.debug,name:t.name,port:t.streamsPort,persistenceMode:t.persistenceMode,walBridge:a})),n=await Dr(r,t);let c=ys(r,s,n,t);await t.writeServerDump(c,t.dryRun?{}:{streams:o.experimental});let i=bs(a),l=r,u=s,p=n,g=o,P=async()=>{i.close(),await Wr(t,[p,g,l,u])};return{close:P,dbServer:r,httpServer:n,server:{...c,close:P,experimental:{streams:o.experimental,wal:i.api},name:t.name},serverState:t,shadowDbServer:s,streamsServer:o,walBridge:a}}catch(a){return await Ps(t,[n,o,r,s],a)}}function ys(e,t,r,n){let s=`prisma+postgres://localhost:${r.port}/?${new URLSearchParams({api_key:pt({databaseUrl:e.prismaORMConnectionString,name:n.name,shadowDatabaseUrl:t.prismaORMConnectionString})}).toString()}`;return{database:{connectionString:e.connectionString,prismaORMConnectionString:e.prismaORMConnectionString,terminalCommand:e.terminalCommand},http:{url:r.url},ppg:{url:s},shadowDatabase:{connectionString:t.prismaORMConnectionString,prismaORMConnectionString:t.prismaORMConnectionString,terminalCommand:t.terminalCommand}}}async function Wr(e,t){let n=(await Promise.allSettled(t.map(s=>s.close()))).filter(s=>s.status==="rejected").map(s=>new Error(s.reason));try{await e.close()}catch(s){n.push(s)}if(n.length>0)throw new AggregateError(n,"Failed to close some servers")}async function Ps(e,t,r){try{await Wr(e,t.filter(n=>n!==null))}catch(n){throw new AggregateError([r,n],"Failed to start Prisma Dev server cleanly")}throw r}function bs(e){let t=new Set;return{api:{stream:()=>{let r=()=>{},n=vs(e,()=>{t.delete(r)});return r=()=>n.close(),t.add(r),n.stream},subscribe:r=>e.subscribe(r)},close:()=>{for(let r of[...t])r();t.clear()}}}function Ss(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function ws(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function vs(e,t){let r=[],n=!1,s=null,o=e.subscribe(c=>{if(!n){if(s){let i=s;s=null,i.resolve({done:!1,value:c});return}r.push(c)}}),a=()=>{if(!n&&(n=!0,o(),r.length=0,t(),s)){let c=s;s=null,c.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((c,i)=>{s={reject:i,resolve:c}})},return(){return a(),Promise.resolve({done:!0,value:void 0})},throw(c){let i=s;return a(),i&&i.reject(c),Promise.reject(c instanceof Error?c:new Error(String(c)))}}}}async function Hr(e){let{server:t}=await Mr(e);return t}async function Es(e){return await Hr(e)}0&&(module.exports={DEFAULT_DATABASE_PORT,DEFAULT_SERVER_PORT,DEFAULT_SHADOW_DATABASE_PORT,PortNotAvailableError,ServerAlreadyRunningError,copyPrismaDevRuntimeAssets,getPrismaDevRuntimeAssetManifest,startPrismaDevServer,unstable_startServer});
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as h,b as i}from"./chunk-
|
|
1
|
+
import{a as h,b as i}from"./chunk-DLTTSFDI.js";import"./chunk-YL6J3L2T.js";import{a as e,b as f}from"./chunk-62DM64XC.js";import{k as g}from"./chunk-CC3P7GPW.js";import{a,b,c,g as d}from"./chunk-X3G665AK.js";import"./chunk-TF5C7XJX.js";import"./chunk-DWY47FQV.js";export{a as DEFAULT_DATABASE_PORT,b as DEFAULT_SERVER_PORT,c as DEFAULT_SHADOW_DATABASE_PORT,d as PortNotAvailableError,g as ServerAlreadyRunningError,e as copyPrismaDevRuntimeAssets,f as getPrismaDevRuntimeAssetManifest,h as startPrismaDevServer,i as unstable_startServer};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma/dev",
|
|
3
|
-
"version": "0.24.
|
|
3
|
+
"version": "0.24.4",
|
|
4
4
|
"description": "A local Prisma Postgres server for development and testing",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"author": "Igal Klebanov <igalklebanov@gmail.com> (https://github.com/igalklebanov)",
|
|
@@ -52,6 +52,16 @@
|
|
|
52
52
|
}
|
|
53
53
|
}
|
|
54
54
|
},
|
|
55
|
+
"scripts": {
|
|
56
|
+
"build": "node ./scripts/generate-bun-runtime-assets.mjs && tsup && node ./scripts/generate-bun-runtime-assets.mjs --dist",
|
|
57
|
+
"check:exports": "attw . --pack --profile node16",
|
|
58
|
+
"dev": "node ./scripts/generate-bun-runtime-assets.mjs && tsup --watch",
|
|
59
|
+
"init": "node ./scripts/generate-bun-runtime-assets.mjs",
|
|
60
|
+
"lint": "eslint --fix .",
|
|
61
|
+
"prepublishOnly": "pnpm build && pnpm check:exports",
|
|
62
|
+
"test": "node ./scripts/generate-bun-runtime-assets.mjs && vitest run",
|
|
63
|
+
"typecheck": "node ./scripts/generate-bun-runtime-assets.mjs && tsc --noEmit"
|
|
64
|
+
},
|
|
55
65
|
"keywords": [
|
|
56
66
|
"prisma",
|
|
57
67
|
"postgres",
|
|
@@ -68,13 +78,13 @@
|
|
|
68
78
|
"@types/pako": "2.0.4",
|
|
69
79
|
"@types/pg": "8.15.6",
|
|
70
80
|
"@types/proper-lockfile": "4.1.4",
|
|
81
|
+
"common-stuff": "workspace:^",
|
|
71
82
|
"env-paths": "3.0.0",
|
|
72
83
|
"pg": "8.16.0",
|
|
73
84
|
"pkg-types": "2.3.0",
|
|
74
85
|
"tsup": "8.5.1",
|
|
75
86
|
"typescript": "5.9.3",
|
|
76
|
-
"vitest": "4.0.17"
|
|
77
|
-
"common-stuff": "^0.0.0"
|
|
87
|
+
"vitest": "4.0.17"
|
|
78
88
|
},
|
|
79
89
|
"dependencies": {
|
|
80
90
|
"@electric-sql/pglite": "0.4.1",
|
|
@@ -83,7 +93,7 @@
|
|
|
83
93
|
"@hono/node-server": "1.19.11",
|
|
84
94
|
"@prisma/get-platform": "7.2.0",
|
|
85
95
|
"@prisma/query-plan-executor": "7.2.0",
|
|
86
|
-
"@prisma/streams-local": "0.1.
|
|
96
|
+
"@prisma/streams-local": "0.1.3",
|
|
87
97
|
"foreground-child": "3.3.1",
|
|
88
98
|
"get-port-please": "3.2.0",
|
|
89
99
|
"hono": "^4.12.8",
|
|
@@ -94,14 +104,5 @@
|
|
|
94
104
|
"std-env": "3.10.0",
|
|
95
105
|
"valibot": "1.2.0",
|
|
96
106
|
"zeptomatch": "2.1.0"
|
|
97
|
-
},
|
|
98
|
-
"scripts": {
|
|
99
|
-
"build": "node ./scripts/generate-bun-runtime-assets.mjs && tsup && node ./scripts/generate-bun-runtime-assets.mjs --dist",
|
|
100
|
-
"check:exports": "attw . --pack --profile node16",
|
|
101
|
-
"dev": "node ./scripts/generate-bun-runtime-assets.mjs && tsup --watch",
|
|
102
|
-
"init": "node ./scripts/generate-bun-runtime-assets.mjs",
|
|
103
|
-
"lint": "eslint --fix .",
|
|
104
|
-
"test": "node ./scripts/generate-bun-runtime-assets.mjs && vitest run",
|
|
105
|
-
"typecheck": "node ./scripts/generate-bun-runtime-assets.mjs && tsc --noEmit"
|
|
106
107
|
}
|
|
107
|
-
}
|
|
108
|
+
}
|
package/dist/chunk-2O6J3K3T.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as g}from"./chunk-YL6J3L2T.js";import{a as D,b as T,c as S,d as W,e as B}from"./chunk-CC3P7GPW.js";import{g as f}from"./chunk-X3G665AK.js";import{a as x,c as R,d as A}from"./chunk-TF5C7XJX.js";import{j as v}from"./chunk-DWY47FQV.js";import{createServer as $}from"http";import{promisify as H}from"util";import F from"@prisma/get-platform";async function k(t,e){let{port:r}=e;if(e.dryRun)return O(r,null);let n=await j(t,e),{promise:a,reject:l,resolve:i}=R(),{serve:o}=await import("@hono/node-server"),s=o({createServer:$,fetch:n.fetch,overrideGlobalObjects:!1,port:r},i);s.on("error",m=>{if(typeof m=="object"&&"code"in m&&m.code==="EADDRINUSE")return l(new f(r));console.error("[Accelerate]",m)});let{port:c}=await a;return e.port=c,O(c,s)}function O(t,e){return{async close(){e&&await Promise.allSettled([H(e.close.bind(e))(),A.stopAll()])},port:t,url:`http://localhost:${t}`}}async function j(t,e){let{debug:r}=e,[{Hono:n},{accelerateRoute:a},{utilityRoute:l}]=await Promise.all([import("hono/tiny"),import("./accelerate-HWGEFOM5.js"),import("./utility-Q5A254LJ.js")]),i=new n,o=await F.getPlatformInfo();if(r&&console.debug("[Accelerate] platform info: %s",JSON.stringify(o)),r){let{logger:c}=await import("hono/logger");i.use("*",c((...m)=>console.log("[Accelerate]",...m)))}i.use("*",async(c,m)=>(c.set("databaseDumpPath",e.databaseDumpPath),c.set("db",t),c.set("debug",!!r),c.set("name",e.name),c.set("platform",o),c.set("shadowDBPort",e.shadowDatabasePort),await m()));let s=new n;return s.route("/",a),s.route("/",l),i.route("/",s),i}import{randomUUID as L}from"crypto";import{setTimeout as C}from"timers/promises";import{process as K}from"std-env";var V="application/json",E={connection:"close","content-type":V},q={interpreter:{apiVersion:"durable.streams/stream-interpreter/v1",format:"durable.streams/state-protocol/v1",touch:{enabled:!0,onMissingBefore:"coarse"}}};async function N(t){let{dbServer:e,debug:r,name:n,persistenceMode:a,port:l,walBridge:i}=t,o=a==="stateless",s=o?X(n):n;K.env.DS_LOCAL_DATA_ROOT=T(),o&&await v(S(s));let{startLocalDurableStreamsServer:c}=await import("@prisma/streams-local"),m=await c({hostname:"127.0.0.1",name:s,port:l}),p={serverUrl:m.exports.http.url,sqlitePath:m.exports.sqlite.path,streamName:D,url:W(m.exports.http.url)};try{await J(p);let u=new P({dbServer:e,debug:r,streamUrl:p.url}),d=i.subscribe(U=>{u.enqueue(U)});return{close:async()=>{d(),await u.close(),await m.close(),await C(100),o&&await v(S(s))},experimental:p}}catch(u){throw await m.close().catch(()=>{}),await C(100),o&&await v(S(s)).catch(()=>{}),u}}var P=class{#n;#a;#e;#r;#t;constructor(e){this.#n=e.dbServer,this.#a=e.debug,this.#e=Promise.resolve(),this.#r=e.streamUrl,this.#t=new Set}enqueue(e){e.length!==0&&(this.#e=this.#e.then(async()=>{let r=await this.#s(e);r.length!==0&&(await z(this.#r,r),this.#a&&console.debug(`[streams] appended ${r.length} state-protocol record(s) to ${this.#r}`))}).catch(r=>{console.error("[streams] failed to ingest WAL events into prisma-wal",r)}))}async close(){await this.#e}async#s(e){let r=[],n=new Date().toISOString();for(let a of e)r.push(...await this.#i(a,n));return r}async#i(e,r){let n=`${e.schema}.${e.table}`,a=await this.#n.getPrimaryKeyColumns(e.schema,e.table),l=_(e.record),i=_(e.oldRecord),o=this.#o(n,a,i),s=this.#o(n,a,l),c=e.txid===""?void 0:e.txid;return e.type==="insert"?l&&s?[{headers:{operation:"insert",timestamp:r,txid:c},key:s,oldValue:null,type:n,value:l}]:[]:e.type==="delete"?i&&o?[{headers:{operation:"delete",timestamp:r,txid:c},key:o,oldValue:i,type:n,value:null}]:[]:!l||!i||!o||!s?[]:o!==s?[{headers:{operation:"delete",timestamp:r,txid:c},key:o,oldValue:i,type:n,value:null},{headers:{operation:"insert",timestamp:r,txid:c},key:s,oldValue:null,type:n,value:l}]:[{headers:{operation:"update",timestamp:r,txid:c},key:s,oldValue:i,type:n,value:l}]}#o(e,r,n){if(!n)return null;let a=G(n,r);return a||(this.#t.has(e)||(this.#t.add(e),console.warn(`[streams] falling back to full-row keys for ${e} because no primary key could be resolved`)),Q(n))}};async function J(t){let e=await fetch(t.url,{headers:E,method:"PUT"});if(!e.ok)throw await w(e,`Failed to create ${t.streamName}`);let r=await fetch(`${t.url}/_schema`,{body:JSON.stringify(q),headers:E,method:"POST"});if(!r.ok)throw await w(r,`Failed to configure ${t.streamName}`)}async function z(t,e){let r=await fetch(t,{body:JSON.stringify(e),headers:E,method:"POST"});if(!r.ok)throw await w(r,"Failed to append to prisma-wal")}async function w(t,e){let r=await t.text().catch(()=>"");return new Error(`${e}: HTTP ${t.status}${r?` ${r}`:""}`)}function G(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 a=Y(t[n]);if(a==null)return null;r.push(e.length===1?a:`${n}=${a}`)}return r.join("|")}function Q(t){return JSON.stringify(b(t))}function b(t){return Array.isArray(t)?t.map(e=>b(e)):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[r])=>e.localeCompare(r)).map(([e,r])=>[e,b(r)])):t}function _(t){return t?structuredClone(t):null}function Y(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 X(t){return`${t}.${L().replaceAll("-","")}`}async function I(t){let e=await B.createExclusively(t),r=null,n=null,a=null,l=null;try{[r,a]=await Promise.all([g("database",e),g("shadow_database",e)]);let i;e.dryRun?(i=te(),l=ne()):(i=await r.attachWalEventBridge(),l=await N({dbServer:r,debug:e.debug,name:e.name,port:e.streamsPort,persistenceMode:e.persistenceMode,walBridge:i})),n=await k(r,e);let o=Z(r,a,n,e);await e.writeServerDump(o,e.dryRun?{}:{streams:l.experimental});let s=re(i),c=r,m=a,p=n,u=l,d=async()=>{s.close(),await M(e,[p,u,c,m])};return{close:d,dbServer:r,httpServer:n,server:{...o,close:d,experimental:{streams:l.experimental,wal:s.api},name:e.name},serverState:e,shadowDbServer:a,streamsServer:l,walBridge:i}}catch(i){return await ee(e,[n,l,r,a],i)}}function Z(t,e,r,n){let a=`prisma+postgres://localhost:${r.port}/?${new URLSearchParams({api_key:x({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:a},shadowDatabase:{connectionString:e.prismaORMConnectionString,prismaORMConnectionString:e.prismaORMConnectionString,terminalCommand:e.terminalCommand}}}async function M(t,e){let n=(await Promise.allSettled(e.map(a=>a.close()))).filter(a=>a.status==="rejected").map(a=>new Error(a.reason));try{await t.close()}catch(a){n.push(a)}if(n.length>0)throw new AggregateError(n,"Failed to close some servers")}async function ee(t,e,r){try{await M(t,e.filter(n=>n!==null))}catch(n){throw new AggregateError([r,n],"Failed to start Prisma Dev server cleanly")}throw r}function re(t){let e=new Set;return{api:{stream:()=>{let r=()=>{},n=ae(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 te(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function ne(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function ae(t,e){let r=[],n=!1,a=null,l=t.subscribe(o=>{if(!n){if(a){let s=a;a=null,s.resolve({done:!1,value:o});return}r.push(o)}}),i=()=>{if(!n&&(n=!0,l(),r.length=0,e(),a)){let o=a;a=null,o.resolve({done:!0,value:void 0})}};return{close:i,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,s)=>{a={reject:s,resolve:o}})},return(){return i(),Promise.resolve({done:!0,value:void 0})},throw(o){let s=a;return i(),s&&s.reject(o),Promise.reject(o instanceof Error?o:new Error(String(o)))}}}}async function oe(t){let{server:e}=await I(t);return e}async function Ie(t){return await oe(t)}export{oe as a,Ie as b};
|