@prisma/dev 0.16.1 → 0.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-Z3KIQH3D.js → chunk-4Q54Y6ZK.js} +1 -1
- package/dist/chunk-ZCVJ53EE.js +3 -0
- package/dist/daemon.cjs +5 -5
- package/dist/daemon.js +1 -1
- package/dist/index.cjs +5 -5
- package/dist/index.js +1 -1
- package/dist/state.cjs +3 -3
- package/dist/state.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-FZ7JBZR6.js +0 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as d}from"./chunk-RBVZVBDC.js";import{a as w}from"./chunk-
|
|
1
|
+
import{a as d}from"./chunk-RBVZVBDC.js";import{a as w}from"./chunk-ZCVJ53EE.js";import{f as u}from"./chunk-LMPFMHCB.js";import{a as f,c as v,d as g}from"./chunk-7EOUKLQR.js";import{createServer as A}from"http";import{promisify as R}from"util";import T from"@prisma/get-platform";async function P(o,e){let{port:r}=e;if(e.dryRun)return y(r,null);let t=await D(r,o,e),{promise:s,reject:S,resolve:l}=v(),{serve:i}=await import("@hono/node-server"),m=i({createServer:A,fetch:t.fetch,overrideGlobalObjects:!1,port:r},l);return m.on("error",n=>{if(typeof n=="object"&&"code"in n&&n.code==="EADDRINUSE")return S(new u(r));console.error("[Accelerate]",n)}),await s,y(r,m)}function y(o,e){return{async close(){e&&await Promise.allSettled([R(e.close.bind(e))(),g.stopAll()])},port:o,url:`http://localhost:${o}`}}async function D(o,e,r){let{debug:t}=r,[{Hono:s},{accelerateRoute:S},{utilityRoute:l}]=await Promise.all([import("hono/tiny"),import("./accelerate-UHQZHRYG.js"),import("./utility-YJ4TFSMW.js")]),i=new s,m=await T.getPlatformInfo();if(t&&console.debug("[Accelerate] platform info: %s",JSON.stringify(m)),t){let{logger:a}=await import("hono/logger");i.use("*",a((...p)=>console.log("[Accelerate]",...p)))}i.use("*",async(a,p)=>(a.set("db",e),a.set("debug",!!t),a.set("platform",m),a.set("port",o),a.set("protocol","http"),a.set("serverState",r),a.set("shadowDBPort",r.shadowDatabasePort),await p()));let n=new s;return n.route("/",S),n.route("/",l),i.route("/",n),i}async function E(o){let e=await w.createExclusively(o),[r,t]=await Promise.all([d("database",e),d("shadow_database",e)]),s=await P(r,e),S=`prisma+postgres://localhost:${s.port}/?${new URLSearchParams({api_key:f({databaseUrl:r.prismaORMConnectionString,name:e.name,shadowDatabaseUrl:t.prismaORMConnectionString})}).toString()}`,l={database:{connectionString:r.connectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand},http:{url:s.url},ppg:{url:S},shadowDatabase:{connectionString:t.prismaORMConnectionString,prismaORMConnectionString:t.prismaORMConnectionString,terminalCommand:t.terminalCommand}};return await e.writeServerDump(l),{...l,close:()=>i(e,[s,r,t]),name:e.name};async function i(m,n){let p=(await Promise.allSettled(n.map(c=>c.close()))).filter(c=>c.status==="rejected").map(c=>new Error(c.reason));try{await m.close()}catch(c){p.push(c)}if(p.length>0)throw new AggregateError(p,"Failed to close some servers")}}async function J(o){return await E(o)}export{E as a,J as b};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{d as f,e as w}from"./chunk-LMPFMHCB.js";import{b as c,f as O,g as V,h as N,i as T}from"./chunk-EPFUMVT3.js";import{writeFile as z}from"fs/promises";import{join as l}from"pathe";import{check as Q,lock as W,unlock as X}from"proper-lockfile";import{process as j}from"std-env";import{integer as C,literal as ee,minLength as te,minValue as F,number as q,object as P,optional as g,parseJson as re,pipe as h,safeParse as se,string as v,url as ae}from"valibot";import{setTimeout as Z}from"timers/promises";import{process as b}from"std-env";function y(r,e){if(r==null)return!1;try{return b.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}async function A(r,e){if(!b.kill)return!1;try{b.kill(r,"SIGTERM")}catch(o){return e&&console.error(`Error killing process with PID ${r}:`,o),!1}let t=0;do{if(!y(r,e))return!0;await Z(100)}while(++t<50);try{return b.kill(r,"SIGKILL")}catch(o){return e&&console.error(`Error forcefully killing process with PID ${r}:`,o),!1}}var _=h(v(),ae()),L=P({connectionString:_,prismaORMConnectionString:g(_),terminalCommand:g(v())}),J=P({url:_}),x=h(q(),C(),F(1)),oe=P({database:L,http:J,ppg:J,shadowDatabase:L}),ne=P({databasePort:x,exports:g(oe),name:h(v(),te(1)),pid:g(h(q(),C(),F(0))),port:x,shadowDatabasePort:x,version:ee("1")}),E=Symbol("initialize"),k="default",u=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??f,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??k,this.persistenceMode=e.persistenceMode,this.pid=e.pid??j.pid,this._port=e.port??f,this._shadowDatabasePort=e.shadowDatabasePort??f}static async createExclusively(e){let t=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new p(e):new $(e);return await t[E](),t}static async fromServerDump(e){let{debug:t,name:o=k}=e??{},a=c(o),n=p.getServerDumpPath(a),s=await O(n);if(s==null)return t&&console.debug(`[State] No server dump file found at: ${n}`),null;t&&(console.debug(`[State] server dump file found at "${n}":`),console.debug(s));let{issues:i,output:d,success:m}=se(h(v(),re(),ne),s);if(!m)throw t&&console.debug(`[State] Invalid server dump file at "${n}":
|
|
2
|
+
${JSON.stringify(i,null,2)}`),new Error(`Invalid Prisma Dev state for "${o}".`);return new p({databasePort:d.databasePort,debug:t,dryRun:!1,name:o,pid:d.pid,port:d.port,serverDump:d,shadowDatabasePort:d.shadowDatabasePort})}static async scan(e){let{debug:t,globs:o}=e??{},a=l(c(k),"..");t&&console.debug(`[State] scanning for server states in: ${a}`);let n=await N(a,o);return t&&console.debug(`[State] found server names: ${JSON.stringify(n)}`),await Promise.all(n.map(s=>H(s,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},$=class extends u{constructor(e){super({...e,databasePort:e?.databasePort,persistenceMode:"stateless",port:e?.port,shadowDatabasePort:e?.shadowDatabasePort})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[E](){let e;try{e=await u.scan({debug:this.debug,onlyMetadata:!0})}catch(o){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",o),e=[]}let t=await w({debug:this.debug,name:this.dryRun?this.name:"",requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=t.databasePort,this._port=t.port,this._shadowDatabasePort=t.shadowDatabasePort}async close(){}async writeServerDump(){}},p=class r extends u{#t;#e;#s;#o;#n;#a;#r;constructor(e){super({...e,persistenceMode:"stateful"}),this.#a=!1,this.#e=c(this.name),this.#t=l(this.#e,"db_dump.bak"),this.#s=l(this.#e,".lock"),this.#o=l(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#n=r.getServerDumpPath(this.#e)}static getServerDumpPath(e){return l(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get pgliteDataDirPath(){return this.#o}async[E](){await V(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await W(this.#e,{lockfilePath:this.#s}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await u.scan({debug:this.debug,onlyMetadata:!0}),t=await w({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=t.databasePort,this._port=t.port,this._shadowDatabasePort=t.shadowDatabasePort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new I(this):e}}async close(){if(!this.#a)try{await X(this.#e,{lockfilePath:this.#s}),this.#a=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,e),e}}async writeServerDump(e){this.#r={name:this.name,version:"1",pid:j.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await z(this.#n,`${JSON.stringify(this.#r,null,2)}
|
|
3
|
+
`,{encoding:"utf-8"})}};async function De(r,e){await ue(r,e);let t=c(typeof r=="string"?r:r.name);await T(t)}async function H(r,e){let{debug:t,onlyMetadata:o}=e||{},a=typeof r=="string"?r:r.name,n=typeof r!="string"?r:void 0,s={databasePort:n?.databasePort??-1,exports:n?.exports,name:a,pid:n?.pid,port:n?.port??-1,shadowDatabasePort:n?.shadowDatabasePort??-1,version:"1"};try{let i=n||await u.fromServerDump({debug:t,name:a});if(!i)return t&&console.debug(`[State] no server state found for name: ${a}`),{...s,status:"no_such_server"};s.databasePort=i.databasePort,s.exports=i.exports,s.pid=i.pid,s.port=i.port,s.shadowDatabasePort=i.shadowDatabasePort;let{exports:d,pid:m}=i;if(o)return{...s,status:"unknown"};if(!y(m,t))return t&&console.debug(`[State] server state for "${a}" has no running process with PID: ${m}`),{...s,status:"not_running"};let R=c(a);try{if(!await Q(R,{lockfilePath:l(R,".lock")}))return t&&console.debug(`[State] server state for "${a}" is not locked, indicating it is not running.`),{...s,status:"starting_up"}}catch(G){t&&console.error(`[State] server state for "${a}" failed to check lock:`,G)}if(!d)return{...s,status:"starting_up"};let{http:K}=d,{hc:B}=await import("hono/client"),S=await B(K.url).health.$get();if(!S.ok)return t&&console.debug(`[State] server state for "${a}" is not live: ${JSON.stringify(S)}`),{...s,status:"not_running"};let D=await S.json();return D.name!==r?(t&&console.debug(`[State] server state for "${a}" has mismatched health response: ${JSON.stringify(D)}`),{...s,status:"unknown"}):(t&&console.debug(`[State] server state for "${r}" is live: ${JSON.stringify(D)}`),{...s,status:"running"})}catch(i){return t&&console.error(`[State] failed to get server status for "${a}":`,i),{...s,status:"error"}}}function ie(r){let{status:e}=r;return e==="running"||e==="starting_up"}async function ue(r,e){let{pid:t,...o}=typeof r=="string"?await H(r,{debug:e}):r;if(!ie(o))return!1;let a=await u.fromServerDump({debug:e,name:o.name});if(t==null){e&&console.debug(`[State] No PID found for server "${o.name}" to kill.`);try{await a?.close()}catch{}return!1}let n=await A(t,e);try{await a?.close()}catch{}return n}var M=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},I=class extends M{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return u.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};export{u as a,De as b,H as c,ie as d,ue as e,M as f,I as g};
|
package/dist/daemon.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var Nt=Object.create;var
|
|
2
|
-
`).find(j=>j.includes("Started query engine http server"));if(!
|
|
3
|
-
Received data: ${p}`));o({childProcess:a,url:`http://${x}:${R}`})},c=p=>{this.#t=null,r(new V(String(p))),a.removeListener("exit",u),a.kill()};a.once("error",c);let u=(p,h)=>{this.#t=null,r(new V(`Query Engine exited with code ${p} and signal ${h}`))};return a.once("exit",u),a.stdout.on("data",i),this.#e.debug&&(a.stderr.on("data",console.error.bind(console,"[Query Engine]")),a.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:e}=await this.#t;e.exitCode==null&&e.signalCode==null&&(this.#t=null,e.kill(),await(0,tt.once)(e,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#a();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let r=je(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,rt.mkdir)(r,{recursive:!0});let{binaryTarget:o}=this.#e.platform,n=o==="windows"?".exe":"",s=(0,ot.join)(r,`query-engine-${o}${n}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(ar==="1"||await Ne(s)===!1)&&await this.#n({commitHash:e,extension:n,engineBinaryPath:s}),s}async#a(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let o=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!o)throw new Error("Couldn't find engines version in package.json");let n=o.split(".").at(-1);if(!n)throw new Error("Couldn't find commit hash in engines version");return n}async#n(e){let{commitHash:r,extension:o,engineBinaryPath:n}=e,{binaryTarget:s}=this.#e.platform,a=`https://binaries.prisma.sh/all_commits/${r}/${s}/query-engine${o}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",a);let i=await fetch(a);if(!i.ok)throw new Error(`Couldn't download engine. URL: ${a}, status code: ${i.status}`);Ze&&await(0,nt.setTimeout)(Number(Ze)),await Ue(await i.arrayBuffer(),n),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",n)}#o(e){let r={};for(let[o,n]of Object.entries(e))n!=null&&(r[o]=n);return r}async#i(e,r,o){let{url:n}=await this.#t,s=this.#o(r),a=await fetch(`${n}/transaction/${e}/${o}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!a.ok)throw await L.fromResponse(a);try{return await a.json()}catch{return{}}}};V=class extends Error{name="EngineStartError"},L=class t extends Error{constructor(r,o,n){super(`${r}: Query Engine response status ${o}, body: ${n}`);this.action=r;this.statusCode=o;this.responseBody=n}name="EngineHttpError";static async fromResponse(r){let o=new URL(r.url),n=await r.text();return new t(o.pathname,r.status,n)}}});async function at(t){let{output:e,success:r}=(0,S.safeParse)(cr,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var S,cr,it=D(()=>{"use strict";l();S=require("valibot"),cr=(0,S.object)({tags:(0,S.union)([(0,S.pipe)((0,S.array)((0,S.string)()),(0,S.minLength)(1)),(0,S.literal)("all")])})});async function ct(t){return Pe===void 0&&(Pe=await _.Server.create({databaseUrl:t.get("db").connectionString,maxResponseSize:(0,_.parseSize)("128 MiB"),queryTimeout:(0,_.parseDuration)("PT5M"),maxTransactionTimeout:(0,_.parseDuration)("PT5M"),maxTransactionWaitTime:(0,_.parseDuration)("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:t.get("debug")?"debug":"off"}})),Pe}var _,re,Pe,ut=D(()=>{"use strict";l();_=require("@prisma/query-plan-executor"),re=require("@prisma/query-plan-executor")});async function Se(t){let r=new TextEncoder().encode(t),o=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o)).map(a=>a.toString(16).padStart(2,"0")).join("")}function dt(t){let e=t.req.param("schemaHash"),r=ne.get(e);return r==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:r}}async function lt(t,e,r){let o=be.Buffer.from(t,"base64").toString("utf8"),n=(0,oe.getSchema)(o),s=n.list.find(u=>u.type==="datasource");if(!s)throw new Error("No datasource block found in schema.");let a=s.assignments.find(u=>u.type==="assignment"&&u.key==="url");a?a.value=`"${e.toString()}"`:s.assignments.push({key:"url",type:"assignment",value:`"${e.toString()}"`});let i=(0,oe.printSchema)(n);r&&console.log("[Accelerate] schema with override:",i);let c=await Se(i);return{base64Override:be.Buffer.from(i,"utf8").toString("base64"),overrideHash:c}}var be,oe,ne,pt=D(()=>{"use strict";l();be=require("buffer"),oe=require("@mrleebo/prisma-ast"),ne=new Map});function se(t){let{req:e}=t;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}var mt=D(()=>{"use strict";l()});async function ft(t){let{issues:e,output:r,success:o}=(0,m.safeParse)(ur,await t.req.json(),{abortEarly:!0});return o?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}function gt(t,e){let{output:r,success:o}=(0,m.safeParse)(dr,t);return o?r:e.json({EngineMalfunction:{}},500)}var m,ur,dr,ht=D(()=>{"use strict";l();m=require("valibot"),ur=(0,m.object)({isolation_level:(0,m.optional)((0,m.string)()),max_wait:(0,m.pipe)((0,m.number)(),(0,m.integer)(),(0,m.minValue)(0)),timeout:(0,m.pipe)((0,m.number)(),(0,m.integer)(),(0,m.minValue)(0))});dr=(0,m.looseObject)({id:(0,m.union)([(0,m.string)(),(0,m.number)()])})});var bt={};$e(bt,{accelerateRoute:()=>G});async function ve(t){let{req:e}=t,r=dt(t);if(r instanceof Response)return r;let{base64Override:o,overrideHash:n}=r.schemas;return await B.get({base64Schema:o,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.param("clientVersion"),debug:t.get("debug"),platform:t.get("platform"),schemaHash:n})}var yt,Pt,I,G,lr,K,pr,mr,St=D(()=>{"use strict";l();yt=require("hono/http-exception"),Pt=require("hono/tiny"),I=require("hono/validator");ce();it();ye();ut();pt();mt();ht();G=new Pt.Hono;G.post("/invalidate",(0,I.validator)("header",k),async t=>{let e=await at(t);return e instanceof Response?e:t.body(null)});lr="/:clientVersion/:schemaHash",K=G.basePath(lr);G.route("/",K);pr=["/graphql","/itx/:transactionId/graphql"];K.on("POST",[...pr],(0,I.validator)("header",k),async t=>{let{req:e}=t;try{let r=await ve(t);if(r instanceof Response)return r;let o=await e.text(),n=e.param("transactionId"),s=await r.request(o,{...se(t),"X-transaction-id":n});return t.text(s)}catch(r){return te(r,t)}});K.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,I.validator)("header",k),async t=>{let{req:e}=t;try{let r=await ve(t);if(r instanceof Response)return r;let n=`${e.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=e.param("transactionId"),a=await r[n](s,se(t));return t.json(a)}catch(r){return te(r,t)}});K.put("/schema",(0,I.validator)("header",k),async t=>{let{req:e}=t,r=await e.text();if(!r)return t.text("Missing schema",400);let o=e.param("schemaHash"),n=ne.get(o);if(n==null){if(o!==await Se(r))return t.text("Schema hash mismatch",400);let s=await lt(r,t.get("db").prismaORMConnectionString,t.get("debug"));return ne.set(o,{base64Original:r,...s}),t.text(o)}return r!==n.base64Original?t.text("Schema mismatch",400):t.text(o)});K.post("/transaction/start",(0,I.validator)("header",k),async t=>{let{req:e}=t,r=await ft(t);if(r instanceof Response)return r;try{let o=await ve(t);if(o instanceof Response)return o;let n=await o.startTransaction(r,se(t)),s=gt(n,t);if(s instanceof Response)return s;let{id:a}=s,i=e.param("clientVersion"),c=t.get("port"),u=t.get("protocol"),p=e.param("schemaHash");return t.json({...n,"data-proxy":{endpoint:`${u}://localhost:${c}/${i}/${p}/itx/${a}`}})}catch(o){return te(o,t)}});mr=[["/connection-info","GET"],["/query","POST"],["/transaction/start","POST"],["/transaction/:transactionId/commit","POST"],["/transaction/:transactionId/query","POST"],["/transaction/:transactionId/rollback","POST"]];for(let[t,e]of mr)G.on(e,t,(0,I.validator)("header",k),async r=>{let o=r.req.header("prisma-engine-hash");if(o!=="0.0.0"&&o!==re.version)throw new yt.HTTPException(400,{message:`Using an HTTP connection string is not supported with Prisma Client version ${o} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${re.version}.`});return await(await ct(r)).fetch(r.req.raw)})});var Dt={};$e(Dt,{utilityRoute:()=>we});var vt,wt,we,io,Et=D(()=>{"use strict";l();vt=require("hono/tiny"),wt=require("http-status-codes"),we=new vt.Hono;we.post("/database/dump",async t=>{let e=t.get("db"),r=t.get("serverState");return await e.dump(r.databaseDumpPath),t.json({dumpPath:r.databaseDumpPath},wt.StatusCodes.CREATED)});io=we.get("/health",t=>t.json({name:t.get("serverState").name}))});var Sr={};module.exports=Gt(Sr);l();var Lt=require("timers/promises");l();ce();l();var ze=require("pathe/utils");X();l();var $=require("get-port-please"),Z=require("remeda"),U=51214,q=51213,F=51215,Y=65535,A=-1/0;async function Qe(t){let{debug:e,name:r,requestedPorts:o,servers:n}=t,{portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a}=er(r,n);e&&(console.debug(`ports used by other servers: ${Object.keys(s).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(a)}`));let i={databasePort:A,port:A,shadowDatabasePort:A},c=["port","databasePort","shadowDatabasePort"];for(let u of c){let p=await Yt({debug:e,portKey:u,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a,requestedPorts:o})??await Zt({debug:e,pickedPorts:i,portKey:u,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a});e&&console.debug(`Got port for "${u}": ${p}`),i[u]=p}return e&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function Yt(t){let{debug:e,portKey:r,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:n,requestedPorts:s}=t,{[r]:a,...i}=s;if(Ke(a))return await tr({debug:e,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:o,requestedPort:a}),a;let c=n?.[r]??A;if(!Ke(c))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let u=c in o;return u||Object.values(i).includes(c)?(e&&console.debug(`Port ${c} that was used last time for this server, ${u?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,$.checkPort)(c)===!1?(e&&console.debug(`Port ${c}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(e&&console.debug(`Using port ${c} for "${r}" as it was used last time and is available.`),c)}async function Zt(t){let{debug:e,pickedPorts:r,portKey:o,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s}=t,a=Math.max(U,q,F)+1,i=[...Object.values(r),...Object.keys(n).map(Number),...Object.values(s||{})],c=Math.min(Math.max(a,...i)+100,Y),u=(0,Z.difference)((0,Z.range)(a,c),i),p={port:q,databasePort:U,shadowDatabasePort:F}[o];try{return await(0,$.getPort)({port:p in n||Object.values(r).includes(p)||Object.values(s||{}).includes(p)?void 0:p,ports:u})}catch(h){if(h instanceof Error&&h.name==="GetPortError"&&c+1<=Y)return e&&console.debug(`Expanding port lookup to range [${c+1}, ${Y}].`),await(0,$.getPort)({portRange:[c+1,Y]});throw h}}function Ke(t){return t>=0}function er(t,e){let r={},o;for(let n of e){let{databasePort:s,port:a,shadowDatabasePort:i}=n;if(n.name===t){o={databasePort:s,port:a,shadowDatabasePort:i};continue}r[s]=!0,r[a]=!0,r[i]=!0}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:o}}async function tr(t){let{debug:e,otherRequestedPorts:r,portKey:o,portsUsedByOtherServers:n,requestedPort:s}=t;if(s in n)throw e&&console.error(`Port ${s} was requested for "${o}", but is already used by another server.`),new fe(s);if(Object.values(r).includes(s))throw e&&console.error(`Port ${s} was requested for "${o}", but also for another key.`),new me(s);if((0,$.isUnsafePort)(s))throw e&&console.error(`Port ${s} was requested for "${o}", but is unsafe.`),new E(s);if(await(0,$.checkPort)(s)===!1)throw e&&console.error(`Port ${s} was requested for "${o}", but is not available.`),new E(s)}var E=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},me=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"},fe=class extends Error{constructor(r){super(`Port number \`${r}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=r}name="PortBelongsToAnotherServerError"};var P={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},rr=`postgres://${P.username}:${P.password}@localhost`,Xe=new URLSearchParams({sslmode:P.sslMode}),or=new URLSearchParams({...Object.fromEntries(Xe.entries()),connection_limit:String(P.connectionLimit),connect_timeout:String(P.connectTimeout),max_idle_connection_lifetime:String(P.maxIdleConnectionLifetime),pool_timeout:String(P.poolTimeout),single_use_connections:"true",socket_timeout:String(P.socketTimeout)});async function ge(t,e){let r=t==="database"?e.databasePort:e.shadowDatabasePort;if(e.dryRun)return Je(t,e,{db:null,port:r,server:null});let{debug:o}=e,s=await(t==="shadow_database"?nr:Ye)(e.pgliteDataDirPath,o);o&&s.onNotification((c,u)=>{console.debug(`[${t}][${c}] ${u}`)});let{PGLiteSocketServer:a}=await import("@electric-sql/pglite-socket"),i=new a({db:s,debug:o,inspect:o,port:r});o&&(i.addEventListener("listening",c=>{let{detail:u}=c;console.debug(`[${t}] server listening on ${JSON.stringify(u)}`)}),i.addEventListener("connection",c=>{let{clientAddress:u,clientPort:p}=c.detail;console.debug(`[${t}] client connected from ${u}:${p}`)}),i.addEventListener("error",c=>{let{detail:u}=c;console.error(`[${t}] server error:`,u)}));try{await i.start()}catch(c){throw c instanceof Error&&"code"in c&&c.code==="EADDRINUSE"?new E(r):c}return Je(t,e,{db:s,port:r,server:i})}function Je(t,e,r){let{debug:o}=e,{db:n,port:s,server:a}=r||{};return o&&console.debug(`[${t}] server started on port ${s}`),{...P,close:async()=>{let i=[];try{await a?.stop(),o&&console.debug(`[${t}] server stopped on port ${s}`)}catch(c){console.error(`[${t}] server stop error`,c),i.push(c)}if(t==="database")try{await n?.syncToFs(),o&&console.debug(`[${t}] synced to filesystem`)}catch(c){console.error(`[${t}] sync error`,c),i.push(c)}try{await n?.close(),o&&console.debug(`[${t}] closed`)}catch(c){console.error(`[${t}] close error`,c),i.push(c)}if(i.length>0)throw new AggregateError(i,`Failed to close ${t} properly`)},connectionString:We(s,Xe),dump:async i=>{t==="shadow_database"||!n||await sr({db:n,debug:o,destinationPath:i})},port:s,prismaORMConnectionString:We(s,or),terminalCommand:`PGPASSWORD=${P.password} PGSSLMODE=${P.sslMode} psql -h localhost -p ${s} -U ${P.username} -d ${P.database}`}}function We(t,e){return`${rr}:${t}/${P.database}?${e.toString()}`}async function Ye(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:P.database,dataDir:t,debug:e?5:void 0,relaxedDurability:!1,username:P.username})}async function nr(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:P.database,dataDir:"memory://",debug:e?5:void 0,relaxedDurability:!1,username:P.username})}async function sr(t){let{dataDir:e,db:r,debug:o,destinationPath:n}=t,s=r||await Ye(e,o),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),i=await a({args:["--schema-only","--no-owner"],fileName:n?(0,ze.filename)(n):void 0,pg:await s.clone()});return n?(o&&console.debug(`[DB] Dumping database to ${n}`),await qe(i,n)):(o&&console.debug("[DB] Dumping database to memory"),await i.text())}l();var xt=require("http"),Rt=require("util"),Ot=v(require("@prisma/get-platform"),1);he();ye();async function At(t,e){let{port:r}=e;if(e.dryRun)return Tt(r,null);let o=await fr(r,t,e),{promise:n,reject:s,resolve:a}=ee(),{serve:i}=await import("@hono/node-server"),c=i({createServer:xt.createServer,fetch:o.fetch,overrideGlobalObjects:!1,port:r},a);return c.on("error",u=>{if(typeof u=="object"&&"code"in u&&u.code==="EADDRINUSE")return s(new E(r));console.error("[Accelerate]",u)}),await n,Tt(r,c)}function Tt(t,e){return{async close(){e&&await Promise.allSettled([(0,Rt.promisify)(e.close.bind(e))(),B.stopAll()])},port:t,url:`http://localhost:${t}`}}async function fr(t,e,r){let{debug:o}=r,[{Hono:n},{accelerateRoute:s},{utilityRoute:a}]=await Promise.all([import("hono/tiny"),Promise.resolve().then(()=>(St(),bt)),Promise.resolve().then(()=>(Et(),Dt))]),i=new n,c=await Ot.default.getPlatformInfo();if(o&&console.debug("[Accelerate] platform info: %s",JSON.stringify(c)),o){let{logger:p}=await import("hono/logger");i.use("*",p((...h)=>console.log("[Accelerate]",...h)))}i.use("*",async(p,h)=>(p.set("db",e),p.set("debug",!!o),p.set("platform",c),p.set("port",t),p.set("protocol","http"),p.set("serverState",r),p.set("shadowDBPort",r.shadowDatabasePort),await h()));let u=new n;return u.route("/",s),u.route("/",a),i.route("/",u),i}l();var Ct=require("fs/promises"),C=require("pathe"),H=require("proper-lockfile"),Oe=require("std-env"),d=require("valibot");X();l();var gr=require("timers/promises"),$t=require("std-env");function _t(t,e){if(t==null)return!1;try{return $t.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var Te=(0,d.pipe)((0,d.string)(),(0,d.url)()),kt=(0,d.object)({connectionString:Te,prismaORMConnectionString:(0,d.optional)(Te),terminalCommand:(0,d.optional)((0,d.string)())}),It=(0,d.object)({url:Te}),De=(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(1)),hr=(0,d.object)({database:kt,http:It,ppg:It,shadowDatabase:kt}),yr=(0,d.object)({databasePort:De,exports:(0,d.optional)(hr),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:De,shadowDatabasePort:De,version:(0,d.literal)("1")}),Ae=Symbol("initialize"),Ee="default",T=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??A,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??Ee,this.persistenceMode=e.persistenceMode,this.pid=e.pid??Oe.process.pid,this._port=e.port??A,this._shadowDatabasePort=e.shadowDatabasePort??A}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new Q(e):new xe(e);return await r[Ae](),r}static async fromServerDump(e){let{debug:r,name:o=Ee}=e??{},n=N(o),s=Q.getServerDumpPath(n),a=await Fe(s);if(a==null)return r&&console.debug(`[State] No server dump file found at: ${s}`),null;r&&(console.debug(`[State] server dump file found at "${s}":`),console.debug(a));let{issues:i,output:c,success:u}=(0,d.safeParse)((0,d.pipe)((0,d.string)(),(0,d.parseJson)(),yr),a);if(!u)throw r&&console.debug(`[State] Invalid server dump file at "${s}":
|
|
4
|
-
${JSON.stringify(i,null,2)}`),new Error(`Invalid Prisma Dev state for "${o}".`);return new
|
|
5
|
-
`,{encoding:"utf-8"})}};async function Pr(t,e){let{debug:r,onlyMetadata:o}=e||{},n=typeof t=="string"?t:t.name,s=typeof t!="string"?t:void 0,a={databasePort:s?.databasePort??-1,exports:s?.exports,name:n,pid:s?.pid,port:s?.port??-1,shadowDatabasePort:s?.shadowDatabasePort??-1,version:"1"};try{let i=s||await
|
|
1
|
+
"use strict";var Nt=Object.create;var G=Object.defineProperty;var Ut=Object.getOwnPropertyDescriptor;var qt=Object.getOwnPropertyNames;var Vt=Object.getPrototypeOf,Ft=Object.prototype.hasOwnProperty;var D=(t,e)=>()=>(t&&(e=t(t=0)),e);var _e=(t,e)=>{for(var r in e)G(t,r,{get:e[r],enumerable:!0})},ke=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of qt(e))!Ft.call(t,n)&&n!==r&&G(t,n,{get:()=>e[n],enumerable:!(o=Ut(e,n))||o.enumerable});return t};var v=(t,e,r)=>(r=t!=null?Nt(Vt(t)):{},ke(e||!t||!t.__esModule?G(r,"default",{value:t,enumerable:!0}):r,t)),Gt=t=>ke(G({},"__esModule",{value:!0}),t);var l=D(()=>{"use strict"});function Ce(t){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([[e],[r]])=>e.localeCompare(r)))),"utf8").toString("base64url")}function Qt(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:o,success:n}=(0,f.safeParse)(Kt,e,{abortEarly:!0});return n?[null,o]:[r]}var f,Ie,Kt,k,se=D(()=>{"use strict";l();f=require("valibot"),Ie=/^(postgres|postgresql):\/\//,Kt=(0,f.pipe)((0,f.string)(),(0,f.parseJson)(),(0,f.object)({databaseUrl:(0,f.pipe)((0,f.string)(),(0,f.url)(),(0,f.regex)(Ie)),name:(0,f.optional)((0,f.pipe)((0,f.string)(),(0,f.minLength)(1))),shadowDatabaseUrl:(0,f.pipe)((0,f.string)(),(0,f.url)(),(0,f.regex)(Ie))}));k=async(t,e)=>{let{authorization:r}=t,{HTTPException:o}=await import("hono/http-exception");if(!r)throw new o(401,{message:"Missing API Key"});let[n,s="",a]=r.split(" ");if(n!=="Bearer"||a)throw new o(401,{message:"Invalid API Key"});let[i,c]=Qt(s);if(i)throw new o(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:u,name:p,shadowDatabaseUrl:g}=c,{name:b}=e.get("serverState");if(!p)throw new o(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} requires an API Key from a newer version of \`prisma dev\`. Check the "${b}" server's output for the updated \`DATABASE_URL\` value.`});if(p!==b)throw new o(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${b}", but the API Key is for "${p}"`});let{hostname:x,port:R}=new URL(u),{port:j}=e.get("db"),{hostname:Lt,port:Bt}=new URL(g),jt=e.get("shadowDBPort");if(x!=="localhost"||Number(R)!==j||Lt!=="localhost"||Number(Bt)!==jt)throw new o(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:c}}});function ce(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),K.default.platform==="darwin"?Jt(t):K.default.platform==="win32"?Wt(t):zt(t)}var h,ae,K,O,ie,M,Jt,Wt,zt,Me=D(()=>{"use strict";l();h=v(require("path"),1),ae=v(require("os"),1),K=v(require("process"),1),O=ae.default.homedir(),ie=ae.default.tmpdir(),{env:M}=K.default,Jt=t=>{let e=h.default.join(O,"Library");return{data:h.default.join(e,"Application Support",t),config:h.default.join(e,"Preferences",t),cache:h.default.join(e,"Caches",t),log:h.default.join(e,"Logs",t),temp:h.default.join(ie,t)}},Wt=t=>{let e=M.APPDATA||h.default.join(O,"AppData","Roaming"),r=M.LOCALAPPDATA||h.default.join(O,"AppData","Local");return{data:h.default.join(r,t,"Data"),config:h.default.join(e,t,"Config"),cache:h.default.join(r,t,"Cache"),log:h.default.join(r,t,"Log"),temp:h.default.join(ie,t)}},zt=t=>{let e=h.default.basename(O);return{data:h.default.join(M.XDG_DATA_HOME||h.default.join(O,".local","share"),t),config:h.default.join(M.XDG_CONFIG_HOME||h.default.join(O,".config"),t),cache:h.default.join(M.XDG_CACHE_HOME||h.default.join(O,".cache"),t),log:h.default.join(M.XDG_STATE_HOME||h.default.join(O,".local","state"),t),temp:h.default.join(ie,e,t)}}});function Ne(t,e){return`${je.cache}/engine/${t}/${e}`}function N(t){return`${je.data}/${t}`}async function Ue(t){try{return await(0,w.access)(t,w.constants.F_OK),!0}catch(e){if(ue(e))return!1;throw e}}async function qe(t,e){let r=await Xt(t);await(0,w.writeFile)(e,r),await(0,w.chmod)(e,"755")}async function Ve(t,e){await t.stream().pipeTo(Q.WriteStream.toWeb((0,Q.createWriteStream)(e,{encoding:"utf-8"})))}function ue(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function Fe(t){try{return await(0,w.readFile)(t,{encoding:"utf-8"})}catch(e){if(ue(e))return null;throw e}}async function Ge(t){await(0,w.mkdir)(t,{recursive:!0})}async function Ke(t,e){try{return(await(0,w.readdir)(t,{withFileTypes:!0})).reduce((o,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&(!e||(0,Be.default)(e,n.name))&&o.push(n.name),o),[])}catch(r){if(ue(r))return[];throw r}}var Q,w,He,Le,Be,je,Xt,J=D(()=>{"use strict";l();Q=require("fs"),w=require("fs/promises"),He=require("util"),Le=require("zlib");Me();Be=v(require("zeptomatch"),1),je=ce("prisma-dev"),Xt=(0,He.promisify)(Le.unzip)});function X(t){let e,r,o=new Promise((a,i)=>{e=a,r=i}),n=a=>{n=s=null,r(a),t?.onRejected?.(a),t?.onFulfilled?.()},s=a=>{s=n=null,e(a),t?.onResolved?.(a),t?.onFulfilled?.()};return{isFulfilled:()=>s===n,promise:o,reject:a=>n?.(a),resolve:a=>s?.(a)}}var ye=D(()=>{"use strict";l()});function Y(t,e){return console.error(t),t instanceof U?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof H?e.text(t.responseBody,t.statusCode):e.body(null,500)}var et,tt,rt,ot,nt,st,ar,ir,Ze,L,U,H,Pe=D(()=>{"use strict";l();et=require("child_process"),tt=require("events"),rt=require("fs/promises"),ot=require("path"),nt=require("timers/promises");ye();st=require("std-env");J();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:ar,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:ir,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:Ze}=st.process.env),L=class t{static#r=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let{debug:r}=e,o=`${e.schemaHash}:${e.clientVersion}`;try{let n=t.#r.get(o);if(n)return n;let s=new t(e);return t.#r.set(o,s),r&&console.debug("[Query Engine] starting...",e),await s.start(),r&&console.debug("[Query Engine] started!"),s}finally{t.stopAll(o)}}static async stopAll(e){let o=(await Promise.allSettled(Array.from(t.#r.entries()).filter(([n])=>n!==e).map(async([n,s])=>{try{await s.stop()}finally{t.#r.delete(n)}}))).filter(n=>n.status==="rejected").map(n=>n.reason);if(o.length>0)throw new AggregateError(o,"Failed to stop engines")}async commitTransaction(e,r){return await this.#i(e,r,"commit")}async request(e,r){let{url:o}=await this.start(),n=this.#o(r),s=await fetch(o,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...n,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await H.fromResponse(s);return await s.text()}async rollbackTransaction(e,r){return await this.#i(e,r,"rollback")}async startTransaction(e,r){let{url:o}=await this.start(),n=this.#o(r),s=await fetch(`${o}/transaction/start`,{body:JSON.stringify(e),headers:{...n,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await H.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:r,resolve:o}=X();this.#t=e;let n=ir||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",n);let{proxySignals:s}=await import("foreground-child/proxy-signals"),a=(0,et.spawn)(n,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});s(a),a.stderr.setEncoding("utf8"),a.stdout.setEncoding("utf8");let i=p=>{let g=p.split(`
|
|
2
|
+
`).find(j=>j.includes("Started query engine http server"));if(!g)return;a.stdout.removeListener("data",i);let{fields:b}=JSON.parse(g);if(b==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${p}`));let{ip:x,port:R}=b;if(x==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: ${p}`));o({childProcess:a,url:`http://${x}:${R}`})},c=p=>{this.#t=null,r(new U(String(p))),a.removeListener("exit",u),a.kill()};a.once("error",c);let u=(p,g)=>{this.#t=null,r(new U(`Query Engine exited with code ${p} and signal ${g}`))};return a.once("exit",u),a.stdout.on("data",i),this.#e.debug&&(a.stderr.on("data",console.error.bind(console,"[Query Engine]")),a.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:e}=await this.#t;e.exitCode==null&&e.signalCode==null&&(this.#t=null,e.kill(),await(0,tt.once)(e,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#a();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let r=Ne(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,rt.mkdir)(r,{recursive:!0});let{binaryTarget:o}=this.#e.platform,n=o==="windows"?".exe":"",s=(0,ot.join)(r,`query-engine-${o}${n}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(ar==="1"||await Ue(s)===!1)&&await this.#n({commitHash:e,extension:n,engineBinaryPath:s}),s}async#a(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let o=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!o)throw new Error("Couldn't find engines version in package.json");let n=o.split(".").at(-1);if(!n)throw new Error("Couldn't find commit hash in engines version");return n}async#n(e){let{commitHash:r,extension:o,engineBinaryPath:n}=e,{binaryTarget:s}=this.#e.platform,a=`https://binaries.prisma.sh/all_commits/${r}/${s}/query-engine${o}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",a);let i=await fetch(a);if(!i.ok)throw new Error(`Couldn't download engine. URL: ${a}, status code: ${i.status}`);Ze&&await(0,nt.setTimeout)(Number(Ze)),await qe(await i.arrayBuffer(),n),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",n)}#o(e){let r={};for(let[o,n]of Object.entries(e))n!=null&&(r[o]=n);return r}async#i(e,r,o){let{url:n}=await this.#t,s=this.#o(r),a=await fetch(`${n}/transaction/${e}/${o}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!a.ok)throw await H.fromResponse(a);try{return await a.json()}catch{return{}}}};U=class extends Error{name="EngineStartError"},H=class t extends Error{constructor(r,o,n){super(`${r}: Query Engine response status ${o}, body: ${n}`);this.action=r;this.statusCode=o;this.responseBody=n}name="EngineHttpError";static async fromResponse(r){let o=new URL(r.url),n=await r.text();return new t(o.pathname,r.status,n)}}});async function at(t){let{output:e,success:r}=(0,S.safeParse)(cr,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var S,cr,it=D(()=>{"use strict";l();S=require("valibot"),cr=(0,S.object)({tags:(0,S.union)([(0,S.pipe)((0,S.array)((0,S.string)()),(0,S.minLength)(1)),(0,S.literal)("all")])})});async function ct(t){return be===void 0&&(be=await _.Server.create({databaseUrl:t.get("db").connectionString,maxResponseSize:(0,_.parseSize)("128 MiB"),queryTimeout:(0,_.parseDuration)("PT5M"),maxTransactionTimeout:(0,_.parseDuration)("PT5M"),maxTransactionWaitTime:(0,_.parseDuration)("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:t.get("debug")?"debug":"off"}})),be}var _,Z,be,ut=D(()=>{"use strict";l();_=require("@prisma/query-plan-executor"),Z=require("@prisma/query-plan-executor")});async function ve(t){let r=new TextEncoder().encode(t),o=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o)).map(a=>a.toString(16).padStart(2,"0")).join("")}function dt(t){let e=t.req.param("schemaHash"),r=te.get(e);return r==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:r}}async function lt(t,e,r){let o=Se.Buffer.from(t,"base64").toString("utf8"),n=(0,ee.getSchema)(o),s=n.list.find(u=>u.type==="datasource");if(!s)throw new Error("No datasource block found in schema.");let a=s.assignments.find(u=>u.type==="assignment"&&u.key==="url");a?a.value=`"${e.toString()}"`:s.assignments.push({key:"url",type:"assignment",value:`"${e.toString()}"`});let i=(0,ee.printSchema)(n);r&&console.log("[Accelerate] schema with override:",i);let c=await ve(i);return{base64Override:Se.Buffer.from(i,"utf8").toString("base64"),overrideHash:c}}var Se,ee,te,pt=D(()=>{"use strict";l();Se=require("buffer"),ee=require("@mrleebo/prisma-ast"),te=new Map});function re(t){let{req:e}=t;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}var mt=D(()=>{"use strict";l()});async function ft(t){let{issues:e,output:r,success:o}=(0,m.safeParse)(ur,await t.req.json(),{abortEarly:!0});return o?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}function ht(t,e){let{output:r,success:o}=(0,m.safeParse)(dr,t);return o?r:e.json({EngineMalfunction:{}},500)}var m,ur,dr,gt=D(()=>{"use strict";l();m=require("valibot"),ur=(0,m.object)({isolation_level:(0,m.optional)((0,m.string)()),max_wait:(0,m.pipe)((0,m.number)(),(0,m.integer)(),(0,m.minValue)(0)),timeout:(0,m.pipe)((0,m.number)(),(0,m.integer)(),(0,m.minValue)(0))});dr=(0,m.looseObject)({id:(0,m.union)([(0,m.string)(),(0,m.number)()])})});var bt={};_e(bt,{accelerateRoute:()=>q});async function we(t){let{req:e}=t,r=dt(t);if(r instanceof Response)return r;let{base64Override:o,overrideHash:n}=r.schemas;return await L.get({base64Schema:o,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.param("clientVersion"),debug:t.get("debug"),platform:t.get("platform"),schemaHash:n})}var yt,Pt,I,q,lr,V,pr,mr,St=D(()=>{"use strict";l();yt=require("hono/http-exception"),Pt=require("hono/tiny"),I=require("hono/validator");se();it();Pe();ut();pt();mt();gt();q=new Pt.Hono;q.post("/invalidate",(0,I.validator)("header",k),async t=>{let e=await at(t);return e instanceof Response?e:t.body(null)});lr="/:clientVersion/:schemaHash",V=q.basePath(lr);q.route("/",V);pr=["/graphql","/itx/:transactionId/graphql"];V.on("POST",[...pr],(0,I.validator)("header",k),async t=>{let{req:e}=t;try{let r=await we(t);if(r instanceof Response)return r;let o=await e.text(),n=e.param("transactionId"),s=await r.request(o,{...re(t),"X-transaction-id":n});return t.text(s)}catch(r){return Y(r,t)}});V.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,I.validator)("header",k),async t=>{let{req:e}=t;try{let r=await we(t);if(r instanceof Response)return r;let n=`${e.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=e.param("transactionId"),a=await r[n](s,re(t));return t.json(a)}catch(r){return Y(r,t)}});V.put("/schema",(0,I.validator)("header",k),async t=>{let{req:e}=t,r=await e.text();if(!r)return t.text("Missing schema",400);let o=e.param("schemaHash"),n=te.get(o);if(n==null){if(o!==await ve(r))return t.text("Schema hash mismatch",400);let s=await lt(r,t.get("db").prismaORMConnectionString,t.get("debug"));return te.set(o,{base64Original:r,...s}),t.text(o)}return r!==n.base64Original?t.text("Schema mismatch",400):t.text(o)});V.post("/transaction/start",(0,I.validator)("header",k),async t=>{let{req:e}=t,r=await ft(t);if(r instanceof Response)return r;try{let o=await we(t);if(o instanceof Response)return o;let n=await o.startTransaction(r,re(t)),s=ht(n,t);if(s instanceof Response)return s;let{id:a}=s,i=e.param("clientVersion"),c=t.get("port"),u=t.get("protocol"),p=e.param("schemaHash");return t.json({...n,"data-proxy":{endpoint:`${u}://localhost:${c}/${i}/${p}/itx/${a}`}})}catch(o){return Y(o,t)}});mr=[["/connection-info","GET"],["/query","POST"],["/transaction/start","POST"],["/transaction/:transactionId/commit","POST"],["/transaction/:transactionId/query","POST"],["/transaction/:transactionId/rollback","POST"]];for(let[t,e]of mr)q.on(e,t,(0,I.validator)("header",k),async r=>{let o=r.req.header("prisma-engine-hash");if(o!=="0.0.0"&&o!==Z.version)throw new yt.HTTPException(400,{message:`Using an HTTP connection string is not supported with Prisma Client version ${o} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${Z.version}.`});return await(await ct(r)).fetch(r.req.raw)})});var Dt={};_e(Dt,{utilityRoute:()=>De});var vt,wt,De,io,Et=D(()=>{"use strict";l();vt=require("hono/tiny"),wt=require("http-status-codes"),De=new vt.Hono;De.post("/database/dump",async t=>{let e=t.get("db"),r=t.get("serverState");return await e.dump(r.databaseDumpPath),t.json({dumpPath:r.databaseDumpPath},wt.StatusCodes.CREATED)});io=De.get("/health",t=>t.json({name:t.get("serverState").name}))});var Sr={};module.exports=Gt(Sr);l();var Ht=require("timers/promises");l();se();l();var ze=require("pathe/utils");J();l();var $=require("get-port-please"),z=require("remeda"),de=51214,le=51213,pe=51215,W=65535,A=-1/0;async function he(t){let{debug:e,name:r,requestedPorts:o,servers:n}=t,{portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a}=er(r,n);e&&(console.debug(`ports used by other servers: ${Object.keys(s).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(a)}`));let i={databasePort:A,port:A,shadowDatabasePort:A},c=["port","databasePort","shadowDatabasePort"];for(let u of c){let p=await Yt({debug:e,portKey:u,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a,requestedPorts:o})??await Zt({debug:e,pickedPorts:i,portKey:u,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a});e&&console.debug(`Got port for "${u}": ${p}`),i[u]=p}return e&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function Yt(t){let{debug:e,portKey:r,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:n,requestedPorts:s}=t,{[r]:a,...i}=s;if(Qe(a))return await tr({debug:e,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:o,requestedPort:a}),a;let c=n?.[r]??A;if(!Qe(c))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let u=c in o;return u||Object.values(i).includes(c)?(e&&console.debug(`Port ${c} that was used last time for this server, ${u?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,$.checkPort)(c)===!1?(e&&console.debug(`Port ${c}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(e&&console.debug(`Using port ${c} for "${r}" as it was used last time and is available.`),c)}async function Zt(t){let{debug:e,pickedPorts:r,portKey:o,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s}=t,a=Math.max(de,le,pe)+1,i=[...Object.values(r),...Object.keys(n).map(Number),...Object.values(s||{})],c=Math.min(Math.max(a,...i)+100,W),u=(0,z.difference)((0,z.range)(a,c),i),p={port:le,databasePort:de,shadowDatabasePort:pe}[o];try{return await(0,$.getPort)({port:p in n||Object.values(r).includes(p)||Object.values(s||{}).includes(p)?void 0:p,ports:u})}catch(g){if(g instanceof Error&&g.name==="GetPortError"&&c+1<=W)return e&&console.debug(`Expanding port lookup to range [${c+1}, ${W}].`),await(0,$.getPort)({portRange:[c+1,W]});throw g}}function Qe(t){return t>=0}function er(t,e){let r={},o;for(let n of e){let{databasePort:s,port:a,shadowDatabasePort:i}=n;if(n.name===t){o={databasePort:s,port:a,shadowDatabasePort:i};continue}r[s]=!0,r[a]=!0,r[i]=!0}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:o}}async function tr(t){let{debug:e,otherRequestedPorts:r,portKey:o,portsUsedByOtherServers:n,requestedPort:s}=t;if(s in n)throw e&&console.error(`Port ${s} was requested for "${o}", but is already used by another server.`),new fe(s);if(Object.values(r).includes(s))throw e&&console.error(`Port ${s} was requested for "${o}", but also for another key.`),new me(s);if((0,$.isUnsafePort)(s))throw e&&console.error(`Port ${s} was requested for "${o}", but is unsafe.`),new T(s);if(await(0,$.checkPort)(s)===!1)throw e&&console.error(`Port ${s} was requested for "${o}", but is not available.`),new T(s)}var T=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},me=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"},fe=class extends Error{constructor(r){super(`Port number \`${r}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=r}name="PortBelongsToAnotherServerError"};var P={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},rr=`postgres://${P.username}:${P.password}@localhost`,Xe=new URLSearchParams({sslmode:P.sslMode}),or=new URLSearchParams({...Object.fromEntries(Xe.entries()),connection_limit:String(P.connectionLimit),connect_timeout:String(P.connectTimeout),max_idle_connection_lifetime:String(P.maxIdleConnectionLifetime),pool_timeout:String(P.poolTimeout),single_use_connections:"true",socket_timeout:String(P.socketTimeout)});async function ge(t,e){let r=t==="database"?e.databasePort:e.shadowDatabasePort;if(e.dryRun)return Je(t,e,{db:null,port:r,server:null});let{debug:o}=e,s=await(t==="shadow_database"?nr:Ye)(e.pgliteDataDirPath,o);o&&s.onNotification((c,u)=>{console.debug(`[${t}][${c}] ${u}`)});let{PGLiteSocketServer:a}=await import("@electric-sql/pglite-socket"),i=new a({db:s,debug:o,inspect:o,port:r});o&&(i.addEventListener("listening",c=>{let{detail:u}=c;console.debug(`[${t}] server listening on ${JSON.stringify(u)}`)}),i.addEventListener("connection",c=>{let{clientAddress:u,clientPort:p}=c.detail;console.debug(`[${t}] client connected from ${u}:${p}`)}),i.addEventListener("error",c=>{let{detail:u}=c;console.error(`[${t}] server error:`,u)}));try{await i.start()}catch(c){throw c instanceof Error&&"code"in c&&c.code==="EADDRINUSE"?new T(r):c}return Je(t,e,{db:s,port:r,server:i})}function Je(t,e,r){let{debug:o}=e,{db:n,port:s,server:a}=r||{};return o&&console.debug(`[${t}] server started on port ${s}`),{...P,close:async()=>{let i=[];try{await a?.stop(),o&&console.debug(`[${t}] server stopped on port ${s}`)}catch(c){console.error(`[${t}] server stop error`,c),i.push(c)}if(t==="database")try{await n?.syncToFs(),o&&console.debug(`[${t}] synced to filesystem`)}catch(c){console.error(`[${t}] sync error`,c),i.push(c)}try{await n?.close(),o&&console.debug(`[${t}] closed`)}catch(c){console.error(`[${t}] close error`,c),i.push(c)}if(i.length>0)throw new AggregateError(i,`Failed to close ${t} properly`)},connectionString:We(s,Xe),dump:async i=>{t==="shadow_database"||!n||await sr({db:n,debug:o,destinationPath:i})},port:s,prismaORMConnectionString:We(s,or),terminalCommand:`PGPASSWORD=${P.password} PGSSLMODE=${P.sslMode} psql -h localhost -p ${s} -U ${P.username} -d ${P.database}`}}function We(t,e){return`${rr}:${t}/${P.database}?${e.toString()}`}async function Ye(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:P.database,dataDir:t,debug:e?5:void 0,relaxedDurability:!1,username:P.username})}async function nr(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:P.database,dataDir:"memory://",debug:e?5:void 0,relaxedDurability:!1,username:P.username})}async function sr(t){let{dataDir:e,db:r,debug:o,destinationPath:n}=t,s=r||await Ye(e,o),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),i=await a({args:["--schema-only","--no-owner"],fileName:n?(0,ze.filename)(n):void 0,pg:await s.clone()});return n?(o&&console.debug(`[DB] Dumping database to ${n}`),await Ve(i,n)):(o&&console.debug("[DB] Dumping database to memory"),await i.text())}l();var xt=require("http"),Rt=require("util"),Ot=v(require("@prisma/get-platform"),1);ye();Pe();async function At(t,e){let{port:r}=e;if(e.dryRun)return Tt(r,null);let o=await fr(r,t,e),{promise:n,reject:s,resolve:a}=X(),{serve:i}=await import("@hono/node-server"),c=i({createServer:xt.createServer,fetch:o.fetch,overrideGlobalObjects:!1,port:r},a);return c.on("error",u=>{if(typeof u=="object"&&"code"in u&&u.code==="EADDRINUSE")return s(new T(r));console.error("[Accelerate]",u)}),await n,Tt(r,c)}function Tt(t,e){return{async close(){e&&await Promise.allSettled([(0,Rt.promisify)(e.close.bind(e))(),L.stopAll()])},port:t,url:`http://localhost:${t}`}}async function fr(t,e,r){let{debug:o}=r,[{Hono:n},{accelerateRoute:s},{utilityRoute:a}]=await Promise.all([import("hono/tiny"),Promise.resolve().then(()=>(St(),bt)),Promise.resolve().then(()=>(Et(),Dt))]),i=new n,c=await Ot.default.getPlatformInfo();if(o&&console.debug("[Accelerate] platform info: %s",JSON.stringify(c)),o){let{logger:p}=await import("hono/logger");i.use("*",p((...g)=>console.log("[Accelerate]",...g)))}i.use("*",async(p,g)=>(p.set("db",e),p.set("debug",!!o),p.set("platform",c),p.set("port",t),p.set("protocol","http"),p.set("serverState",r),p.set("shadowDBPort",r.shadowDatabasePort),await g()));let u=new n;return u.route("/",s),u.route("/",a),i.route("/",u),i}l();var Ct=require("fs/promises"),C=require("pathe"),B=require("proper-lockfile"),Ae=require("std-env"),d=require("valibot");J();l();var hr=require("timers/promises"),$t=require("std-env");function _t(t,e){if(t==null)return!1;try{return $t.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var xe=(0,d.pipe)((0,d.string)(),(0,d.url)()),kt=(0,d.object)({connectionString:xe,prismaORMConnectionString:(0,d.optional)(xe),terminalCommand:(0,d.optional)((0,d.string)())}),It=(0,d.object)({url:xe}),Ee=(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(1)),gr=(0,d.object)({database:kt,http:It,ppg:It,shadowDatabase:kt}),yr=(0,d.object)({databasePort:Ee,exports:(0,d.optional)(gr),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:Ee,shadowDatabasePort:Ee,version:(0,d.literal)("1")}),$e=Symbol("initialize"),Te="default",E=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??A,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??Te,this.persistenceMode=e.persistenceMode,this.pid=e.pid??Ae.process.pid,this._port=e.port??A,this._shadowDatabasePort=e.shadowDatabasePort??A}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new F(e):new Re(e);return await r[$e](),r}static async fromServerDump(e){let{debug:r,name:o=Te}=e??{},n=N(o),s=F.getServerDumpPath(n),a=await Fe(s);if(a==null)return r&&console.debug(`[State] No server dump file found at: ${s}`),null;r&&(console.debug(`[State] server dump file found at "${s}":`),console.debug(a));let{issues:i,output:c,success:u}=(0,d.safeParse)((0,d.pipe)((0,d.string)(),(0,d.parseJson)(),yr),a);if(!u)throw r&&console.debug(`[State] Invalid server dump file at "${s}":
|
|
4
|
+
${JSON.stringify(i,null,2)}`),new Error(`Invalid Prisma Dev state for "${o}".`);return new F({databasePort:c.databasePort,debug:r,dryRun:!1,name:o,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(e){let{debug:r,globs:o}=e??{},n=(0,C.join)(N(Te),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let s=await Ke(n,o);return r&&console.debug(`[State] found server names: ${JSON.stringify(s)}`),await Promise.all(s.map(a=>Pr(a,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},Re=class extends E{constructor(e){super({...e,databasePort:e?.databasePort,persistenceMode:"stateless",port:e?.port,shadowDatabasePort:e?.shadowDatabasePort})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[$e](){let e;try{e=await E.scan({debug:this.debug,onlyMetadata:!0})}catch(o){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",o),e=[]}let r=await he({debug:this.debug,name:this.dryRun?this.name:"",requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort}async close(){}async writeServerDump(){}},F=class t extends E{#r;#e;#t;#s;#a;#n;#o;constructor(e){super({...e,persistenceMode:"stateful"}),this.#n=!1,this.#e=N(this.name),this.#r=(0,C.join)(this.#e,"db_dump.bak"),this.#t=(0,C.join)(this.#e,".lock"),this.#s=(0,C.join)(this.#e,".pglite"),this.#o=e?.serverDump??null,this.#a=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,C.join)(e,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#o?.exports}get pgliteDataDirPath(){return this.#s}async[$e](){await Ge(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,B.lock)(this.#e,{lockfilePath:this.#t}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await E.scan({debug:this.debug,onlyMetadata:!0}),r=await he({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new oe(this):e}}async close(){if(!this.#n)try{await(0,B.unlock)(this.#e,{lockfilePath:this.#t}),this.#n=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,e),e}}async writeServerDump(e){this.#o={name:this.name,version:"1",pid:Ae.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,Ct.writeFile)(this.#a,`${JSON.stringify(this.#o,null,2)}
|
|
5
|
+
`,{encoding:"utf-8"})}};async function Pr(t,e){let{debug:r,onlyMetadata:o}=e||{},n=typeof t=="string"?t:t.name,s=typeof t!="string"?t:void 0,a={databasePort:s?.databasePort??-1,exports:s?.exports,name:n,pid:s?.pid,port:s?.port??-1,shadowDatabasePort:s?.shadowDatabasePort??-1,version:"1"};try{let i=s||await E.fromServerDump({debug:r,name:n});if(!i)return r&&console.debug(`[State] no server state found for name: ${n}`),{...a,status:"no_such_server"};a.databasePort=i.databasePort,a.exports=i.exports,a.pid=i.pid,a.port=i.port,a.shadowDatabasePort=i.shadowDatabasePort;let{exports:c,pid:u}=i;if(o)return{...a,status:"unknown"};if(!_t(u,r))return r&&console.debug(`[State] server state for "${n}" has no running process with PID: ${u}`),{...a,status:"not_running"};let p=N(n);try{if(!await(0,B.check)(p,{lockfilePath:(0,C.join)(p,".lock")}))return r&&console.debug(`[State] server state for "${n}" is not locked, indicating it is not running.`),{...a,status:"starting_up"}}catch(j){r&&console.error(`[State] server state for "${n}" failed to check lock:`,j)}if(!c)return{...a,status:"starting_up"};let{http:g}=c,{hc:b}=await import("hono/client"),x=await b(g.url).health.$get();if(!x.ok)return r&&console.debug(`[State] server state for "${n}" is not live: ${JSON.stringify(x)}`),{...a,status:"not_running"};let R=await x.json();return R.name!==t?(r&&console.debug(`[State] server state for "${n}" has mismatched health response: ${JSON.stringify(R)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(R)}`),{...a,status:"running"})}catch(i){return r&&console.error(`[State] failed to get server status for "${n}":`,i),{...a,status:"error"}}}var Oe=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},oe=class extends Oe{#r;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#r=e}get server(){return E.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};async function Mt(t){let e=await E.createExclusively(t),[r,o]=await Promise.all([ge("database",e),ge("shadow_database",e)]),n=await At(r,e),s=`prisma+postgres://localhost:${n.port}/?${new URLSearchParams({api_key:Ce({databaseUrl:r.prismaORMConnectionString,name:e.name,shadowDatabaseUrl:o.prismaORMConnectionString})}).toString()}`,a={database:{connectionString:r.connectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand},http:{url:n.url},ppg:{url:s},shadowDatabase:{connectionString:o.prismaORMConnectionString,prismaORMConnectionString:o.prismaORMConnectionString,terminalCommand:o.terminalCommand}};return await e.writeServerDump(a),{...a,close:()=>i(e,[n,r,o]),name:e.name};async function i(c,u){let g=(await Promise.allSettled(u.map(b=>b.close()))).filter(b=>b.status==="rejected").map(b=>new Error(b.reason));try{await c.close()}catch(b){g.push(b)}if(g.length>0)throw new AggregateError(g,"Failed to close some servers")}}var ne;process.once("SIGTERM",()=>{console.log("SIGTERM received, shutting down..."),process.removeAllListeners("SIGINT"),process.exitCode=143,ne?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{console.log("SIGINT received, shutting down..."),process.removeAllListeners("SIGTERM"),process.exitCode=130,ne?.close().finally(()=>process.exit())});async function br(){let[,,t]=process.argv;if(!t)return process.send?.({type:"error",error:'Missing "name" argument, server cannot be started'},void 0),process.exit(1);try{ne=await Mt({debug:!0,persistenceMode:"stateful",name:t}),process.send?.({type:"started",server:ne},void 0)}catch(e){console.error(e);let r=e instanceof Error?e.message:String(e);process.send?.({type:"error",error:r},void 0),await(0,Ht.setTimeout)(1e3),process.exit(1)}}br();
|
package/dist/daemon.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as o}from"./chunk-
|
|
1
|
+
import{a as o}from"./chunk-4Q54Y6ZK.js";import"./chunk-RBVZVBDC.js";import"./chunk-ZCVJ53EE.js";import"./chunk-LMPFMHCB.js";import"./chunk-7EOUKLQR.js";import"./chunk-EPFUMVT3.js";import{setTimeout as n}from"timers/promises";var r;process.once("SIGTERM",()=>{console.log("SIGTERM received, shutting down..."),process.removeAllListeners("SIGINT"),process.exitCode=143,r?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{console.log("SIGINT received, shutting down..."),process.removeAllListeners("SIGTERM"),process.exitCode=130,r?.close().finally(()=>process.exit())});async function a(){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{r=await o({debug:!0,persistenceMode:"stateful",name:s}),process.send?.({type:"started",server:r},void 0)}catch(e){console.error(e);let t=e instanceof Error?e.message:String(e);process.send?.({type:"error",error:t},void 0),await n(1e3),process.exit(1)}}a();
|
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).find(
|
|
3
|
-
Received data: ${l}`));o({childProcess:a,url:`http://${R}:${x}`})},c=l=>{this.#t=null,r(new V(String(l))),a.removeListener("exit",u),a.kill()};a.once("error",c);let u=(l,g)=>{this.#t=null,r(new V(`Query Engine exited with code ${l} and signal ${g}`))};return a.once("exit",u),a.stdout.on("data",i),this.#e.debug&&(a.stderr.on("data",console.error.bind(console,"[Query Engine]")),a.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:e}=await this.#t;e.exitCode==null&&e.signalCode==null&&(this.#t=null,e.kill(),await(0,et.once)(e,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#a();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let r=je(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,tt.mkdir)(r,{recursive:!0});let{binaryTarget:o}=this.#e.platform,n=o==="windows"?".exe":"",s=(0,rt.join)(r,`query-engine-${o}${n}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(nr==="1"||await Me(s)===!1)&&await this.#n({commitHash:e,extension:n,engineBinaryPath:s}),s}async#a(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let o=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!o)throw new Error("Couldn't find engines version in package.json");let n=o.split(".").at(-1);if(!n)throw new Error("Couldn't find commit hash in engines version");return n}async#n(e){let{commitHash:r,extension:o,engineBinaryPath:n}=e,{binaryTarget:s}=this.#e.platform,a=`https://binaries.prisma.sh/all_commits/${r}/${s}/query-engine${o}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",a);let i=await fetch(a);if(!i.ok)throw new Error(`Couldn't download engine. URL: ${a}, status code: ${i.status}`);Ye&&await(0,ot.setTimeout)(Number(Ye)),await Ue(await i.arrayBuffer(),n),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",n)}#o(e){let r={};for(let[o,n]of Object.entries(e))n!=null&&(r[o]=n);return r}async#i(e,r,o){let{url:n}=await this.#t,s=this.#o(r),a=await fetch(`${n}/transaction/${e}/${o}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!a.ok)throw await M.fromResponse(a);try{return await a.json()}catch{return{}}}};V=class extends Error{name="EngineStartError"},M=class t extends Error{constructor(r,o,n){super(`${r}: Query Engine response status ${o}, body: ${n}`);this.action=r;this.statusCode=o;this.responseBody=n}name="EngineHttpError";static async fromResponse(r){let o=new URL(r.url),n=await r.text();return new t(o.pathname,r.status,n)}}});async function st(t){let{output:e,success:r}=(0,S.safeParse)(ar,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var S,ar,at=D(()=>{"use strict";p();S=require("valibot"),ar=(0,S.object)({tags:(0,S.union)([(0,S.pipe)((0,S.array)((0,S.string)()),(0,S.minLength)(1)),(0,S.literal)("all")])})});async function it(t){return Pe===void 0&&(Pe=await _.Server.create({databaseUrl:t.get("db").connectionString,maxResponseSize:(0,_.parseSize)("128 MiB"),queryTimeout:(0,_.parseDuration)("PT5M"),maxTransactionTimeout:(0,_.parseDuration)("PT5M"),maxTransactionWaitTime:(0,_.parseDuration)("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:t.get("debug")?"debug":"off"}})),Pe}var _,oe,Pe,ct=D(()=>{"use strict";p();_=require("@prisma/query-plan-executor"),oe=require("@prisma/query-plan-executor")});async function Se(t){let r=new TextEncoder().encode(t),o=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o)).map(a=>a.toString(16).padStart(2,"0")).join("")}function ut(t){let e=t.req.param("schemaHash"),r=se.get(e);return r==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:r}}async function dt(t,e,r){let o=be.Buffer.from(t,"base64").toString("utf8"),n=(0,ne.getSchema)(o),s=n.list.find(u=>u.type==="datasource");if(!s)throw new Error("No datasource block found in schema.");let a=s.assignments.find(u=>u.type==="assignment"&&u.key==="url");a?a.value=`"${e.toString()}"`:s.assignments.push({key:"url",type:"assignment",value:`"${e.toString()}"`});let i=(0,ne.printSchema)(n);r&&console.log("[Accelerate] schema with override:",i);let c=await Se(i);return{base64Override:be.Buffer.from(i,"utf8").toString("base64"),overrideHash:c}}var be,ne,se,lt=D(()=>{"use strict";p();be=require("buffer"),ne=require("@mrleebo/prisma-ast"),se=new Map});function ae(t){let{req:e}=t;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}var pt=D(()=>{"use strict";p()});async function mt(t){let{issues:e,output:r,success:o}=(0,m.safeParse)(ir,await t.req.json(),{abortEarly:!0});return o?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}function ft(t,e){let{output:r,success:o}=(0,m.safeParse)(cr,t);return o?r:e.json({EngineMalfunction:{}},500)}var m,ir,cr,ht=D(()=>{"use strict";p();m=require("valibot"),ir=(0,m.object)({isolation_level:(0,m.optional)((0,m.string)()),max_wait:(0,m.pipe)((0,m.number)(),(0,m.integer)(),(0,m.minValue)(0)),timeout:(0,m.pipe)((0,m.number)(),(0,m.integer)(),(0,m.minValue)(0))});cr=(0,m.looseObject)({id:(0,m.union)([(0,m.string)(),(0,m.number)()])})});var Pt={};ie(Pt,{accelerateRoute:()=>G});async function we(t){let{req:e}=t,r=ut(t);if(r instanceof Response)return r;let{base64Override:o,overrideHash:n}=r.schemas;return await U.get({base64Schema:o,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.param("clientVersion"),debug:t.get("debug"),platform:t.get("platform"),schemaHash:n})}var gt,yt,I,G,ur,K,dr,lr,bt=D(()=>{"use strict";p();gt=require("hono/http-exception"),yt=require("hono/tiny"),I=require("hono/validator");ce();at();ye();ct();lt();pt();ht();G=new yt.Hono;G.post("/invalidate",(0,I.validator)("header",k),async t=>{let e=await st(t);return e instanceof Response?e:t.body(null)});ur="/:clientVersion/:schemaHash",K=G.basePath(ur);G.route("/",K);dr=["/graphql","/itx/:transactionId/graphql"];K.on("POST",[...dr],(0,I.validator)("header",k),async t=>{let{req:e}=t;try{let r=await we(t);if(r instanceof Response)return r;let o=await e.text(),n=e.param("transactionId"),s=await r.request(o,{...ae(t),"X-transaction-id":n});return t.text(s)}catch(r){return re(r,t)}});K.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,I.validator)("header",k),async t=>{let{req:e}=t;try{let r=await we(t);if(r instanceof Response)return r;let n=`${e.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=e.param("transactionId"),a=await r[n](s,ae(t));return t.json(a)}catch(r){return re(r,t)}});K.put("/schema",(0,I.validator)("header",k),async t=>{let{req:e}=t,r=await e.text();if(!r)return t.text("Missing schema",400);let o=e.param("schemaHash"),n=se.get(o);if(n==null){if(o!==await Se(r))return t.text("Schema hash mismatch",400);let s=await dt(r,t.get("db").prismaORMConnectionString,t.get("debug"));return se.set(o,{base64Original:r,...s}),t.text(o)}return r!==n.base64Original?t.text("Schema mismatch",400):t.text(o)});K.post("/transaction/start",(0,I.validator)("header",k),async t=>{let{req:e}=t,r=await mt(t);if(r instanceof Response)return r;try{let o=await we(t);if(o instanceof Response)return o;let n=await o.startTransaction(r,ae(t)),s=ft(n,t);if(s instanceof Response)return s;let{id:a}=s,i=e.param("clientVersion"),c=t.get("port"),u=t.get("protocol"),l=e.param("schemaHash");return t.json({...n,"data-proxy":{endpoint:`${u}://localhost:${c}/${i}/${l}/itx/${a}`}})}catch(o){return re(o,t)}});lr=[["/connection-info","GET"],["/query","POST"],["/transaction/start","POST"],["/transaction/:transactionId/commit","POST"],["/transaction/:transactionId/query","POST"],["/transaction/:transactionId/rollback","POST"]];for(let[t,e]of lr)G.on(e,t,(0,I.validator)("header",k),async r=>{let o=r.req.header("prisma-engine-hash");if(o!=="0.0.0"&&o!==oe.version)throw new gt.HTTPException(400,{message:`Using an HTTP connection string is not supported with Prisma Client version ${o} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${oe.version}.`});return await(await it(r)).fetch(r.req.raw)})});var vt={};ie(vt,{utilityRoute:()=>ve});var St,wt,ve,so,Dt=D(()=>{"use strict";p();St=require("hono/tiny"),wt=require("http-status-codes"),ve=new St.Hono;ve.post("/database/dump",async t=>{let e=t.get("db"),r=t.get("serverState");return await e.dump(r.databaseDumpPath),t.json({dumpPath:r.databaseDumpPath},wt.StatusCodes.CREATED)});so=ve.get("/health",t=>t.json({name:t.get("serverState").name}))});var Pr={};ie(Pr,{DEFAULT_DATABASE_PORT:()=>H,DEFAULT_SERVER_PORT:()=>L,DEFAULT_SHADOW_DATABASE_PORT:()=>j,PortNotAvailableError:()=>E,ServerAlreadyRunningError:()=>J,startPrismaDevServer:()=>Ct,unstable_startServer:()=>yr});module.exports=Ft(Pr);p();ce();p();var We=require("pathe/utils");Y();p();var $=require("get-port-please"),ee=require("remeda"),H=51214,L=51213,j=51215,Z=65535,A=-1/0;async function Ke(t){let{debug:e,name:r,requestedPorts:o,servers:n}=t,{portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a}=Yt(r,n);e&&(console.debug(`ports used by other servers: ${Object.keys(s).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(a)}`));let i={databasePort:A,port:A,shadowDatabasePort:A},c=["port","databasePort","shadowDatabasePort"];for(let u of c){let l=await zt({debug:e,portKey:u,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a,requestedPorts:o})??await Xt({debug:e,pickedPorts:i,portKey:u,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a});e&&console.debug(`Got port for "${u}": ${l}`),i[u]=l}return e&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function zt(t){let{debug:e,portKey:r,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:n,requestedPorts:s}=t,{[r]:a,...i}=s;if(Ge(a))return await Zt({debug:e,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:o,requestedPort:a}),a;let c=n?.[r]??A;if(!Ge(c))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let u=c in o;return u||Object.values(i).includes(c)?(e&&console.debug(`Port ${c} that was used last time for this server, ${u?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,$.checkPort)(c)===!1?(e&&console.debug(`Port ${c}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(e&&console.debug(`Using port ${c} for "${r}" as it was used last time and is available.`),c)}async function Xt(t){let{debug:e,pickedPorts:r,portKey:o,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s}=t,a=Math.max(H,L,j)+1,i=[...Object.values(r),...Object.keys(n).map(Number),...Object.values(s||{})],c=Math.min(Math.max(a,...i)+100,Z),u=(0,ee.difference)((0,ee.range)(a,c),i),l={port:L,databasePort:H,shadowDatabasePort:j}[o];try{return await(0,$.getPort)({port:l in n||Object.values(r).includes(l)||Object.values(s||{}).includes(l)?void 0:l,ports:u})}catch(g){if(g instanceof Error&&g.name==="GetPortError"&&c+1<=Z)return e&&console.debug(`Expanding port lookup to range [${c+1}, ${Z}].`),await(0,$.getPort)({portRange:[c+1,Z]});throw g}}function Ge(t){return t>=0}function Yt(t,e){let r={},o;for(let n of e){let{databasePort:s,port:a,shadowDatabasePort:i}=n;if(n.name===t){o={databasePort:s,port:a,shadowDatabasePort:i};continue}r[s]=!0,r[a]=!0,r[i]=!0}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:o}}async function Zt(t){let{debug:e,otherRequestedPorts:r,portKey:o,portsUsedByOtherServers:n,requestedPort:s}=t;if(s in n)throw e&&console.error(`Port ${s} was requested for "${o}", but is already used by another server.`),new fe(s);if(Object.values(r).includes(s))throw e&&console.error(`Port ${s} was requested for "${o}", but also for another key.`),new me(s);if((0,$.isUnsafePort)(s))throw e&&console.error(`Port ${s} was requested for "${o}", but is unsafe.`),new E(s);if(await(0,$.checkPort)(s)===!1)throw e&&console.error(`Port ${s} was requested for "${o}", but is not available.`),new E(s)}var E=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},me=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"},fe=class extends Error{constructor(r){super(`Port number \`${r}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=r}name="PortBelongsToAnotherServerError"};var y={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},er=`postgres://${y.username}:${y.password}@localhost`,ze=new URLSearchParams({sslmode:y.sslMode}),tr=new URLSearchParams({...Object.fromEntries(ze.entries()),connection_limit:String(y.connectionLimit),connect_timeout:String(y.connectTimeout),max_idle_connection_lifetime:String(y.maxIdleConnectionLifetime),pool_timeout:String(y.poolTimeout),single_use_connections:"true",socket_timeout:String(y.socketTimeout)});async function he(t,e){let r=t==="database"?e.databasePort:e.shadowDatabasePort;if(e.dryRun)return Qe(t,e,{db:null,port:r,server:null});let{debug:o}=e,s=await(t==="shadow_database"?rr:Xe)(e.pgliteDataDirPath,o);o&&s.onNotification((c,u)=>{console.debug(`[${t}][${c}] ${u}`)});let{PGLiteSocketServer:a}=await import("@electric-sql/pglite-socket"),i=new a({db:s,debug:o,inspect:o,port:r});o&&(i.addEventListener("listening",c=>{let{detail:u}=c;console.debug(`[${t}] server listening on ${JSON.stringify(u)}`)}),i.addEventListener("connection",c=>{let{clientAddress:u,clientPort:l}=c.detail;console.debug(`[${t}] client connected from ${u}:${l}`)}),i.addEventListener("error",c=>{let{detail:u}=c;console.error(`[${t}] server error:`,u)}));try{await i.start()}catch(c){throw c instanceof Error&&"code"in c&&c.code==="EADDRINUSE"?new E(r):c}return Qe(t,e,{db:s,port:r,server:i})}function Qe(t,e,r){let{debug:o}=e,{db:n,port:s,server:a}=r||{};return o&&console.debug(`[${t}] server started on port ${s}`),{...y,close:async()=>{let i=[];try{await a?.stop(),o&&console.debug(`[${t}] server stopped on port ${s}`)}catch(c){console.error(`[${t}] server stop error`,c),i.push(c)}if(t==="database")try{await n?.syncToFs(),o&&console.debug(`[${t}] synced to filesystem`)}catch(c){console.error(`[${t}] sync error`,c),i.push(c)}try{await n?.close(),o&&console.debug(`[${t}] closed`)}catch(c){console.error(`[${t}] close error`,c),i.push(c)}if(i.length>0)throw new AggregateError(i,`Failed to close ${t} properly`)},connectionString:Je(s,ze),dump:async i=>{t==="shadow_database"||!n||await or({db:n,debug:o,destinationPath:i})},port:s,prismaORMConnectionString:Je(s,tr),terminalCommand:`PGPASSWORD=${y.password} PGSSLMODE=${y.sslMode} psql -h localhost -p ${s} -U ${y.username} -d ${y.database}`}}function Je(t,e){return`${er}:${t}/${y.database}?${e.toString()}`}async function Xe(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:y.database,dataDir:t,debug:e?5:void 0,relaxedDurability:!1,username:y.username})}async function rr(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:y.database,dataDir:"memory://",debug:e?5:void 0,relaxedDurability:!1,username:y.username})}async function or(t){let{dataDir:e,db:r,debug:o,destinationPath:n}=t,s=r||await Xe(e,o),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),i=await a({args:["--schema-only","--no-owner"],fileName:n?(0,We.filename)(n):void 0,pg:await s.clone()});return n?(o&&console.debug(`[DB] Dumping database to ${n}`),await Ne(i,n)):(o&&console.debug("[DB] Dumping database to memory"),await i.text())}p();var Tt=require("http"),Rt=require("util"),xt=w(require("@prisma/get-platform"),1);ge();ye();async function Ot(t,e){let{port:r}=e;if(e.dryRun)return Et(r,null);let o=await pr(r,t,e),{promise:n,reject:s,resolve:a}=te(),{serve:i}=await import("@hono/node-server"),c=i({createServer:Tt.createServer,fetch:o.fetch,overrideGlobalObjects:!1,port:r},a);return c.on("error",u=>{if(typeof u=="object"&&"code"in u&&u.code==="EADDRINUSE")return s(new E(r));console.error("[Accelerate]",u)}),await n,Et(r,c)}function Et(t,e){return{async close(){e&&await Promise.allSettled([(0,Rt.promisify)(e.close.bind(e))(),U.stopAll()])},port:t,url:`http://localhost:${t}`}}async function pr(t,e,r){let{debug:o}=r,[{Hono:n},{accelerateRoute:s},{utilityRoute:a}]=await Promise.all([import("hono/tiny"),Promise.resolve().then(()=>(bt(),Pt)),Promise.resolve().then(()=>(Dt(),vt))]),i=new n,c=await xt.default.getPlatformInfo();if(o&&console.debug("[Accelerate] platform info: %s",JSON.stringify(c)),o){let{logger:l}=await import("hono/logger");i.use("*",l((...g)=>console.log("[Accelerate]",...g)))}i.use("*",async(l,g)=>(l.set("db",e),l.set("debug",!!o),l.set("platform",c),l.set("port",t),l.set("protocol","http"),l.set("serverState",r),l.set("shadowDBPort",r.shadowDatabasePort),await g()));let u=new n;return u.route("/",s),u.route("/",a),i.route("/",u),i}p();var It=require("fs/promises"),C=require("pathe"),N=require("proper-lockfile"),Oe=require("std-env"),d=require("valibot");Y();p();var mr=require("timers/promises"),At=require("std-env");function $t(t,e){if(t==null)return!1;try{return At.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var Te=(0,d.pipe)((0,d.string)(),(0,d.url)()),_t=(0,d.object)({connectionString:Te,prismaORMConnectionString:(0,d.optional)(Te),terminalCommand:(0,d.optional)((0,d.string)())}),kt=(0,d.object)({url:Te}),De=(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(1)),fr=(0,d.object)({database:_t,http:kt,ppg:kt,shadowDatabase:_t}),hr=(0,d.object)({databasePort:De,exports:(0,d.optional)(fr),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:De,shadowDatabasePort:De,version:(0,d.literal)("1")}),Ae=Symbol("initialize"),Ee="default",T=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??A,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??Ee,this.persistenceMode=e.persistenceMode,this.pid=e.pid??Oe.process.pid,this._port=e.port??A,this._shadowDatabasePort=e.shadowDatabasePort??A}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new Q(e):new Re(e);return await r[Ae](),r}static async fromServerDump(e){let{debug:r,name:o=Ee}=e??{},n=F(o),s=Q.getServerDumpPath(n),a=await qe(s);if(a==null)return r&&console.debug(`[State] No server dump file found at: ${s}`),null;r&&(console.debug(`[State] server dump file found at "${s}":`),console.debug(a));let{issues:i,output:c,success:u}=(0,d.safeParse)((0,d.pipe)((0,d.string)(),(0,d.parseJson)(),hr),a);if(!u)throw r&&console.debug(`[State] Invalid server dump file at "${s}":
|
|
4
|
-
${JSON.stringify(i,null,2)}`),new Error(`Invalid Prisma Dev state for "${o}".`);return new
|
|
5
|
-
`,{encoding:"utf-8"})}};async function gr(t,e){let{debug:r,onlyMetadata:o}=e||{},n=typeof t=="string"?t:t.name,s=typeof t!="string"?t:void 0,a={databasePort:s?.databasePort??-1,exports:s?.exports,name:n,pid:s?.pid,port:s?.port??-1,shadowDatabasePort:s?.shadowDatabasePort??-1,version:"1"};try{let i=s||await T.fromServerDump({debug:r,name:n});if(!i)return r&&console.debug(`[State] no server state found for name: ${n}`),{...a,status:"no_such_server"};a.databasePort=i.databasePort,a.exports=i.exports,a.pid=i.pid,a.port=i.port,a.shadowDatabasePort=i.shadowDatabasePort;let{exports:c,pid:u}=i;if(o)return{...a,status:"unknown"};if(!$t(u,r))return r&&console.debug(`[State] server state for "${n}" has no running process with PID: ${u}`),{...a,status:"not_running"};let l=
|
|
1
|
+
"use strict";var Mt=Object.create;var K=Object.defineProperty;var jt=Object.getOwnPropertyDescriptor;var Nt=Object.getOwnPropertyNames;var Ut=Object.getPrototypeOf,qt=Object.prototype.hasOwnProperty;var D=(t,e)=>()=>(t&&(e=t(t=0)),e);var ie=(t,e)=>{for(var r in e)K(t,r,{get:e[r],enumerable:!0})},_e=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Nt(e))!qt.call(t,n)&&n!==r&&K(t,n,{get:()=>e[n],enumerable:!(o=jt(e,n))||o.enumerable});return t};var w=(t,e,r)=>(r=t!=null?Mt(Ut(t)):{},_e(e||!t||!t.__esModule?K(r,"default",{value:t,enumerable:!0}):r,t)),Vt=t=>_e(K({},"__esModule",{value:!0}),t);var p=D(()=>{"use strict"});function Ie(t){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([[e],[r]])=>e.localeCompare(r)))),"utf8").toString("base64url")}function Gt(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:o,success:n}=(0,f.safeParse)(Ft,e,{abortEarly:!0});return n?[null,o]:[r]}var f,ke,Ft,k,ce=D(()=>{"use strict";p();f=require("valibot"),ke=/^(postgres|postgresql):\/\//,Ft=(0,f.pipe)((0,f.string)(),(0,f.parseJson)(),(0,f.object)({databaseUrl:(0,f.pipe)((0,f.string)(),(0,f.url)(),(0,f.regex)(ke)),name:(0,f.optional)((0,f.pipe)((0,f.string)(),(0,f.minLength)(1))),shadowDatabaseUrl:(0,f.pipe)((0,f.string)(),(0,f.url)(),(0,f.regex)(ke))}));k=async(t,e)=>{let{authorization:r}=t,{HTTPException:o}=await import("hono/http-exception");if(!r)throw new o(401,{message:"Missing API Key"});let[n,s="",a]=r.split(" ");if(n!=="Bearer"||a)throw new o(401,{message:"Invalid API Key"});let[i,c]=Gt(s);if(i)throw new o(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:u,name:l,shadowDatabaseUrl:g}=c,{name:b}=e.get("serverState");if(!l)throw new o(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} requires an API Key from a newer version of \`prisma dev\`. Check the "${b}" server's output for the updated \`DATABASE_URL\` value.`});if(l!==b)throw new o(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${b}", but the API Key is for "${l}"`});let{hostname:x,port:R}=new URL(u),{port:j}=e.get("db"),{hostname:Ht,port:Bt}=new URL(g),Lt=e.get("shadowDBPort");if(x!=="localhost"||Number(R)!==j||Ht!=="localhost"||Number(Bt)!==Lt)throw new o(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:c}}});function le(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),Q.default.platform==="darwin"?Kt(t):Q.default.platform==="win32"?Qt(t):Jt(t)}var h,ue,Q,O,de,H,Kt,Qt,Jt,Ce=D(()=>{"use strict";p();h=w(require("path"),1),ue=w(require("os"),1),Q=w(require("process"),1),O=ue.default.homedir(),de=ue.default.tmpdir(),{env:H}=Q.default,Kt=t=>{let e=h.default.join(O,"Library");return{data:h.default.join(e,"Application Support",t),config:h.default.join(e,"Preferences",t),cache:h.default.join(e,"Caches",t),log:h.default.join(e,"Logs",t),temp:h.default.join(de,t)}},Qt=t=>{let e=H.APPDATA||h.default.join(O,"AppData","Roaming"),r=H.LOCALAPPDATA||h.default.join(O,"AppData","Local");return{data:h.default.join(r,t,"Data"),config:h.default.join(e,t,"Config"),cache:h.default.join(r,t,"Cache"),log:h.default.join(r,t,"Log"),temp:h.default.join(de,t)}},Jt=t=>{let e=h.default.basename(O);return{data:h.default.join(H.XDG_DATA_HOME||h.default.join(O,".local","share"),t),config:h.default.join(H.XDG_CONFIG_HOME||h.default.join(O,".config"),t),cache:h.default.join(H.XDG_CACHE_HOME||h.default.join(O,".cache"),t),log:h.default.join(H.XDG_STATE_HOME||h.default.join(O,".local","state"),t),temp:h.default.join(de,e,t)}}});function je(t,e){return`${Me.cache}/engine/${t}/${e}`}function N(t){return`${Me.data}/${t}`}async function Ne(t){try{return await(0,v.access)(t,v.constants.F_OK),!0}catch(e){if(pe(e))return!1;throw e}}async function Ue(t,e){let r=await Wt(t);await(0,v.writeFile)(e,r),await(0,v.chmod)(e,"755")}async function qe(t,e){await t.stream().pipeTo(J.WriteStream.toWeb((0,J.createWriteStream)(e,{encoding:"utf-8"})))}function pe(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function Ve(t){try{return await(0,v.readFile)(t,{encoding:"utf-8"})}catch(e){if(pe(e))return null;throw e}}async function Fe(t){await(0,v.mkdir)(t,{recursive:!0})}async function Ge(t,e){try{return(await(0,v.readdir)(t,{withFileTypes:!0})).reduce((o,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&(!e||(0,Le.default)(e,n.name))&&o.push(n.name),o),[])}catch(r){if(pe(r))return[];throw r}}var J,v,He,Be,Le,Me,Wt,W=D(()=>{"use strict";p();J=require("fs"),v=require("fs/promises"),He=require("util"),Be=require("zlib");Ce();Le=w(require("zeptomatch"),1),Me=le("prisma-dev"),Wt=(0,He.promisify)(Be.unzip)});function te(t){let e,r,o=new Promise((a,i)=>{e=a,r=i}),n=a=>{n=s=null,r(a),t?.onRejected?.(a),t?.onFulfilled?.()},s=a=>{s=n=null,e(a),t?.onResolved?.(a),t?.onFulfilled?.()};return{isFulfilled:()=>s===n,promise:o,reject:a=>n?.(a),resolve:a=>s?.(a)}}var ye=D(()=>{"use strict";p()});function re(t,e){return console.error(t),t instanceof U?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof B?e.text(t.responseBody,t.statusCode):e.body(null,500)}var Ze,et,tt,rt,ot,nt,nr,sr,Ye,L,U,B,Pe=D(()=>{"use strict";p();Ze=require("child_process"),et=require("events"),tt=require("fs/promises"),rt=require("path"),ot=require("timers/promises");ye();nt=require("std-env");W();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:nr,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:sr,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:Ye}=nt.process.env),L=class t{static#r=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let{debug:r}=e,o=`${e.schemaHash}:${e.clientVersion}`;try{let n=t.#r.get(o);if(n)return n;let s=new t(e);return t.#r.set(o,s),r&&console.debug("[Query Engine] starting...",e),await s.start(),r&&console.debug("[Query Engine] started!"),s}finally{t.stopAll(o)}}static async stopAll(e){let o=(await Promise.allSettled(Array.from(t.#r.entries()).filter(([n])=>n!==e).map(async([n,s])=>{try{await s.stop()}finally{t.#r.delete(n)}}))).filter(n=>n.status==="rejected").map(n=>n.reason);if(o.length>0)throw new AggregateError(o,"Failed to stop engines")}async commitTransaction(e,r){return await this.#i(e,r,"commit")}async request(e,r){let{url:o}=await this.start(),n=this.#o(r),s=await fetch(o,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...n,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await B.fromResponse(s);return await s.text()}async rollbackTransaction(e,r){return await this.#i(e,r,"rollback")}async startTransaction(e,r){let{url:o}=await this.start(),n=this.#o(r),s=await fetch(`${o}/transaction/start`,{body:JSON.stringify(e),headers:{...n,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await B.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:r,resolve:o}=te();this.#t=e;let n=sr||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",n);let{proxySignals:s}=await import("foreground-child/proxy-signals"),a=(0,Ze.spawn)(n,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});s(a),a.stderr.setEncoding("utf8"),a.stdout.setEncoding("utf8");let i=l=>{let g=l.split(`
|
|
2
|
+
`).find(j=>j.includes("Started query engine http server"));if(!g)return;a.stdout.removeListener("data",i);let{fields:b}=JSON.parse(g);if(b==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${l}`));let{ip:x,port:R}=b;if(x==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: ${l}`));o({childProcess:a,url:`http://${x}:${R}`})},c=l=>{this.#t=null,r(new U(String(l))),a.removeListener("exit",u),a.kill()};a.once("error",c);let u=(l,g)=>{this.#t=null,r(new U(`Query Engine exited with code ${l} and signal ${g}`))};return a.once("exit",u),a.stdout.on("data",i),this.#e.debug&&(a.stderr.on("data",console.error.bind(console,"[Query Engine]")),a.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:e}=await this.#t;e.exitCode==null&&e.signalCode==null&&(this.#t=null,e.kill(),await(0,et.once)(e,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#a();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let r=je(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,tt.mkdir)(r,{recursive:!0});let{binaryTarget:o}=this.#e.platform,n=o==="windows"?".exe":"",s=(0,rt.join)(r,`query-engine-${o}${n}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(nr==="1"||await Ne(s)===!1)&&await this.#n({commitHash:e,extension:n,engineBinaryPath:s}),s}async#a(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let o=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!o)throw new Error("Couldn't find engines version in package.json");let n=o.split(".").at(-1);if(!n)throw new Error("Couldn't find commit hash in engines version");return n}async#n(e){let{commitHash:r,extension:o,engineBinaryPath:n}=e,{binaryTarget:s}=this.#e.platform,a=`https://binaries.prisma.sh/all_commits/${r}/${s}/query-engine${o}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",a);let i=await fetch(a);if(!i.ok)throw new Error(`Couldn't download engine. URL: ${a}, status code: ${i.status}`);Ye&&await(0,ot.setTimeout)(Number(Ye)),await Ue(await i.arrayBuffer(),n),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",n)}#o(e){let r={};for(let[o,n]of Object.entries(e))n!=null&&(r[o]=n);return r}async#i(e,r,o){let{url:n}=await this.#t,s=this.#o(r),a=await fetch(`${n}/transaction/${e}/${o}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!a.ok)throw await B.fromResponse(a);try{return await a.json()}catch{return{}}}};U=class extends Error{name="EngineStartError"},B=class t extends Error{constructor(r,o,n){super(`${r}: Query Engine response status ${o}, body: ${n}`);this.action=r;this.statusCode=o;this.responseBody=n}name="EngineHttpError";static async fromResponse(r){let o=new URL(r.url),n=await r.text();return new t(o.pathname,r.status,n)}}});async function st(t){let{output:e,success:r}=(0,S.safeParse)(ar,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var S,ar,at=D(()=>{"use strict";p();S=require("valibot"),ar=(0,S.object)({tags:(0,S.union)([(0,S.pipe)((0,S.array)((0,S.string)()),(0,S.minLength)(1)),(0,S.literal)("all")])})});async function it(t){return be===void 0&&(be=await _.Server.create({databaseUrl:t.get("db").connectionString,maxResponseSize:(0,_.parseSize)("128 MiB"),queryTimeout:(0,_.parseDuration)("PT5M"),maxTransactionTimeout:(0,_.parseDuration)("PT5M"),maxTransactionWaitTime:(0,_.parseDuration)("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:t.get("debug")?"debug":"off"}})),be}var _,oe,be,ct=D(()=>{"use strict";p();_=require("@prisma/query-plan-executor"),oe=require("@prisma/query-plan-executor")});async function we(t){let r=new TextEncoder().encode(t),o=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o)).map(a=>a.toString(16).padStart(2,"0")).join("")}function ut(t){let e=t.req.param("schemaHash"),r=se.get(e);return r==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:r}}async function dt(t,e,r){let o=Se.Buffer.from(t,"base64").toString("utf8"),n=(0,ne.getSchema)(o),s=n.list.find(u=>u.type==="datasource");if(!s)throw new Error("No datasource block found in schema.");let a=s.assignments.find(u=>u.type==="assignment"&&u.key==="url");a?a.value=`"${e.toString()}"`:s.assignments.push({key:"url",type:"assignment",value:`"${e.toString()}"`});let i=(0,ne.printSchema)(n);r&&console.log("[Accelerate] schema with override:",i);let c=await we(i);return{base64Override:Se.Buffer.from(i,"utf8").toString("base64"),overrideHash:c}}var Se,ne,se,lt=D(()=>{"use strict";p();Se=require("buffer"),ne=require("@mrleebo/prisma-ast"),se=new Map});function ae(t){let{req:e}=t;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}var pt=D(()=>{"use strict";p()});async function mt(t){let{issues:e,output:r,success:o}=(0,m.safeParse)(ir,await t.req.json(),{abortEarly:!0});return o?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}function ft(t,e){let{output:r,success:o}=(0,m.safeParse)(cr,t);return o?r:e.json({EngineMalfunction:{}},500)}var m,ir,cr,ht=D(()=>{"use strict";p();m=require("valibot"),ir=(0,m.object)({isolation_level:(0,m.optional)((0,m.string)()),max_wait:(0,m.pipe)((0,m.number)(),(0,m.integer)(),(0,m.minValue)(0)),timeout:(0,m.pipe)((0,m.number)(),(0,m.integer)(),(0,m.minValue)(0))});cr=(0,m.looseObject)({id:(0,m.union)([(0,m.string)(),(0,m.number)()])})});var Pt={};ie(Pt,{accelerateRoute:()=>q});async function ve(t){let{req:e}=t,r=ut(t);if(r instanceof Response)return r;let{base64Override:o,overrideHash:n}=r.schemas;return await L.get({base64Schema:o,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.param("clientVersion"),debug:t.get("debug"),platform:t.get("platform"),schemaHash:n})}var gt,yt,I,q,ur,V,dr,lr,bt=D(()=>{"use strict";p();gt=require("hono/http-exception"),yt=require("hono/tiny"),I=require("hono/validator");ce();at();Pe();ct();lt();pt();ht();q=new yt.Hono;q.post("/invalidate",(0,I.validator)("header",k),async t=>{let e=await st(t);return e instanceof Response?e:t.body(null)});ur="/:clientVersion/:schemaHash",V=q.basePath(ur);q.route("/",V);dr=["/graphql","/itx/:transactionId/graphql"];V.on("POST",[...dr],(0,I.validator)("header",k),async t=>{let{req:e}=t;try{let r=await ve(t);if(r instanceof Response)return r;let o=await e.text(),n=e.param("transactionId"),s=await r.request(o,{...ae(t),"X-transaction-id":n});return t.text(s)}catch(r){return re(r,t)}});V.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,I.validator)("header",k),async t=>{let{req:e}=t;try{let r=await ve(t);if(r instanceof Response)return r;let n=`${e.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=e.param("transactionId"),a=await r[n](s,ae(t));return t.json(a)}catch(r){return re(r,t)}});V.put("/schema",(0,I.validator)("header",k),async t=>{let{req:e}=t,r=await e.text();if(!r)return t.text("Missing schema",400);let o=e.param("schemaHash"),n=se.get(o);if(n==null){if(o!==await we(r))return t.text("Schema hash mismatch",400);let s=await dt(r,t.get("db").prismaORMConnectionString,t.get("debug"));return se.set(o,{base64Original:r,...s}),t.text(o)}return r!==n.base64Original?t.text("Schema mismatch",400):t.text(o)});V.post("/transaction/start",(0,I.validator)("header",k),async t=>{let{req:e}=t,r=await mt(t);if(r instanceof Response)return r;try{let o=await ve(t);if(o instanceof Response)return o;let n=await o.startTransaction(r,ae(t)),s=ft(n,t);if(s instanceof Response)return s;let{id:a}=s,i=e.param("clientVersion"),c=t.get("port"),u=t.get("protocol"),l=e.param("schemaHash");return t.json({...n,"data-proxy":{endpoint:`${u}://localhost:${c}/${i}/${l}/itx/${a}`}})}catch(o){return re(o,t)}});lr=[["/connection-info","GET"],["/query","POST"],["/transaction/start","POST"],["/transaction/:transactionId/commit","POST"],["/transaction/:transactionId/query","POST"],["/transaction/:transactionId/rollback","POST"]];for(let[t,e]of lr)q.on(e,t,(0,I.validator)("header",k),async r=>{let o=r.req.header("prisma-engine-hash");if(o!=="0.0.0"&&o!==oe.version)throw new gt.HTTPException(400,{message:`Using an HTTP connection string is not supported with Prisma Client version ${o} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${oe.version}.`});return await(await it(r)).fetch(r.req.raw)})});var vt={};ie(vt,{utilityRoute:()=>De});var St,wt,De,so,Dt=D(()=>{"use strict";p();St=require("hono/tiny"),wt=require("http-status-codes"),De=new St.Hono;De.post("/database/dump",async t=>{let e=t.get("db"),r=t.get("serverState");return await e.dump(r.databaseDumpPath),t.json({dumpPath:r.databaseDumpPath},wt.StatusCodes.CREATED)});so=De.get("/health",t=>t.json({name:t.get("serverState").name}))});var Pr={};ie(Pr,{DEFAULT_DATABASE_PORT:()=>X,DEFAULT_SERVER_PORT:()=>Y,DEFAULT_SHADOW_DATABASE_PORT:()=>Z,PortNotAvailableError:()=>E,ServerAlreadyRunningError:()=>G,startPrismaDevServer:()=>Ct,unstable_startServer:()=>yr});module.exports=Vt(Pr);p();ce();p();var We=require("pathe/utils");W();p();var $=require("get-port-please"),ee=require("remeda"),X=51214,Y=51213,Z=51215,z=65535,A=-1/0;async function he(t){let{debug:e,name:r,requestedPorts:o,servers:n}=t,{portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a}=Yt(r,n);e&&(console.debug(`ports used by other servers: ${Object.keys(s).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(a)}`));let i={databasePort:A,port:A,shadowDatabasePort:A},c=["port","databasePort","shadowDatabasePort"];for(let u of c){let l=await zt({debug:e,portKey:u,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a,requestedPorts:o})??await Xt({debug:e,pickedPorts:i,portKey:u,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a});e&&console.debug(`Got port for "${u}": ${l}`),i[u]=l}return e&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function zt(t){let{debug:e,portKey:r,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:n,requestedPorts:s}=t,{[r]:a,...i}=s;if(Ke(a))return await Zt({debug:e,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:o,requestedPort:a}),a;let c=n?.[r]??A;if(!Ke(c))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let u=c in o;return u||Object.values(i).includes(c)?(e&&console.debug(`Port ${c} that was used last time for this server, ${u?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,$.checkPort)(c)===!1?(e&&console.debug(`Port ${c}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(e&&console.debug(`Using port ${c} for "${r}" as it was used last time and is available.`),c)}async function Xt(t){let{debug:e,pickedPorts:r,portKey:o,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s}=t,a=Math.max(X,Y,Z)+1,i=[...Object.values(r),...Object.keys(n).map(Number),...Object.values(s||{})],c=Math.min(Math.max(a,...i)+100,z),u=(0,ee.difference)((0,ee.range)(a,c),i),l={port:Y,databasePort:X,shadowDatabasePort:Z}[o];try{return await(0,$.getPort)({port:l in n||Object.values(r).includes(l)||Object.values(s||{}).includes(l)?void 0:l,ports:u})}catch(g){if(g instanceof Error&&g.name==="GetPortError"&&c+1<=z)return e&&console.debug(`Expanding port lookup to range [${c+1}, ${z}].`),await(0,$.getPort)({portRange:[c+1,z]});throw g}}function Ke(t){return t>=0}function Yt(t,e){let r={},o;for(let n of e){let{databasePort:s,port:a,shadowDatabasePort:i}=n;if(n.name===t){o={databasePort:s,port:a,shadowDatabasePort:i};continue}r[s]=!0,r[a]=!0,r[i]=!0}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:o}}async function Zt(t){let{debug:e,otherRequestedPorts:r,portKey:o,portsUsedByOtherServers:n,requestedPort:s}=t;if(s in n)throw e&&console.error(`Port ${s} was requested for "${o}", but is already used by another server.`),new fe(s);if(Object.values(r).includes(s))throw e&&console.error(`Port ${s} was requested for "${o}", but also for another key.`),new me(s);if((0,$.isUnsafePort)(s))throw e&&console.error(`Port ${s} was requested for "${o}", but is unsafe.`),new E(s);if(await(0,$.checkPort)(s)===!1)throw e&&console.error(`Port ${s} was requested for "${o}", but is not available.`),new E(s)}var E=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},me=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"},fe=class extends Error{constructor(r){super(`Port number \`${r}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=r}name="PortBelongsToAnotherServerError"};var y={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},er=`postgres://${y.username}:${y.password}@localhost`,ze=new URLSearchParams({sslmode:y.sslMode}),tr=new URLSearchParams({...Object.fromEntries(ze.entries()),connection_limit:String(y.connectionLimit),connect_timeout:String(y.connectTimeout),max_idle_connection_lifetime:String(y.maxIdleConnectionLifetime),pool_timeout:String(y.poolTimeout),single_use_connections:"true",socket_timeout:String(y.socketTimeout)});async function ge(t,e){let r=t==="database"?e.databasePort:e.shadowDatabasePort;if(e.dryRun)return Qe(t,e,{db:null,port:r,server:null});let{debug:o}=e,s=await(t==="shadow_database"?rr:Xe)(e.pgliteDataDirPath,o);o&&s.onNotification((c,u)=>{console.debug(`[${t}][${c}] ${u}`)});let{PGLiteSocketServer:a}=await import("@electric-sql/pglite-socket"),i=new a({db:s,debug:o,inspect:o,port:r});o&&(i.addEventListener("listening",c=>{let{detail:u}=c;console.debug(`[${t}] server listening on ${JSON.stringify(u)}`)}),i.addEventListener("connection",c=>{let{clientAddress:u,clientPort:l}=c.detail;console.debug(`[${t}] client connected from ${u}:${l}`)}),i.addEventListener("error",c=>{let{detail:u}=c;console.error(`[${t}] server error:`,u)}));try{await i.start()}catch(c){throw c instanceof Error&&"code"in c&&c.code==="EADDRINUSE"?new E(r):c}return Qe(t,e,{db:s,port:r,server:i})}function Qe(t,e,r){let{debug:o}=e,{db:n,port:s,server:a}=r||{};return o&&console.debug(`[${t}] server started on port ${s}`),{...y,close:async()=>{let i=[];try{await a?.stop(),o&&console.debug(`[${t}] server stopped on port ${s}`)}catch(c){console.error(`[${t}] server stop error`,c),i.push(c)}if(t==="database")try{await n?.syncToFs(),o&&console.debug(`[${t}] synced to filesystem`)}catch(c){console.error(`[${t}] sync error`,c),i.push(c)}try{await n?.close(),o&&console.debug(`[${t}] closed`)}catch(c){console.error(`[${t}] close error`,c),i.push(c)}if(i.length>0)throw new AggregateError(i,`Failed to close ${t} properly`)},connectionString:Je(s,ze),dump:async i=>{t==="shadow_database"||!n||await or({db:n,debug:o,destinationPath:i})},port:s,prismaORMConnectionString:Je(s,tr),terminalCommand:`PGPASSWORD=${y.password} PGSSLMODE=${y.sslMode} psql -h localhost -p ${s} -U ${y.username} -d ${y.database}`}}function Je(t,e){return`${er}:${t}/${y.database}?${e.toString()}`}async function Xe(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:y.database,dataDir:t,debug:e?5:void 0,relaxedDurability:!1,username:y.username})}async function rr(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:y.database,dataDir:"memory://",debug:e?5:void 0,relaxedDurability:!1,username:y.username})}async function or(t){let{dataDir:e,db:r,debug:o,destinationPath:n}=t,s=r||await Xe(e,o),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),i=await a({args:["--schema-only","--no-owner"],fileName:n?(0,We.filename)(n):void 0,pg:await s.clone()});return n?(o&&console.debug(`[DB] Dumping database to ${n}`),await qe(i,n)):(o&&console.debug("[DB] Dumping database to memory"),await i.text())}p();var Tt=require("http"),xt=require("util"),Rt=w(require("@prisma/get-platform"),1);ye();Pe();async function Ot(t,e){let{port:r}=e;if(e.dryRun)return Et(r,null);let o=await pr(r,t,e),{promise:n,reject:s,resolve:a}=te(),{serve:i}=await import("@hono/node-server"),c=i({createServer:Tt.createServer,fetch:o.fetch,overrideGlobalObjects:!1,port:r},a);return c.on("error",u=>{if(typeof u=="object"&&"code"in u&&u.code==="EADDRINUSE")return s(new E(r));console.error("[Accelerate]",u)}),await n,Et(r,c)}function Et(t,e){return{async close(){e&&await Promise.allSettled([(0,xt.promisify)(e.close.bind(e))(),L.stopAll()])},port:t,url:`http://localhost:${t}`}}async function pr(t,e,r){let{debug:o}=r,[{Hono:n},{accelerateRoute:s},{utilityRoute:a}]=await Promise.all([import("hono/tiny"),Promise.resolve().then(()=>(bt(),Pt)),Promise.resolve().then(()=>(Dt(),vt))]),i=new n,c=await Rt.default.getPlatformInfo();if(o&&console.debug("[Accelerate] platform info: %s",JSON.stringify(c)),o){let{logger:l}=await import("hono/logger");i.use("*",l((...g)=>console.log("[Accelerate]",...g)))}i.use("*",async(l,g)=>(l.set("db",e),l.set("debug",!!o),l.set("platform",c),l.set("port",t),l.set("protocol","http"),l.set("serverState",r),l.set("shadowDBPort",r.shadowDatabasePort),await g()));let u=new n;return u.route("/",s),u.route("/",a),i.route("/",u),i}p();var It=require("fs/promises"),C=require("pathe"),M=require("proper-lockfile"),Ae=require("std-env"),d=require("valibot");W();p();var mr=require("timers/promises"),At=require("std-env");function $t(t,e){if(t==null)return!1;try{return At.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var xe=(0,d.pipe)((0,d.string)(),(0,d.url)()),_t=(0,d.object)({connectionString:xe,prismaORMConnectionString:(0,d.optional)(xe),terminalCommand:(0,d.optional)((0,d.string)())}),kt=(0,d.object)({url:xe}),Ee=(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(1)),fr=(0,d.object)({database:_t,http:kt,ppg:kt,shadowDatabase:_t}),hr=(0,d.object)({databasePort:Ee,exports:(0,d.optional)(fr),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:Ee,shadowDatabasePort:Ee,version:(0,d.literal)("1")}),$e=Symbol("initialize"),Te="default",T=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??A,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??Te,this.persistenceMode=e.persistenceMode,this.pid=e.pid??Ae.process.pid,this._port=e.port??A,this._shadowDatabasePort=e.shadowDatabasePort??A}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new F(e):new Re(e);return await r[$e](),r}static async fromServerDump(e){let{debug:r,name:o=Te}=e??{},n=N(o),s=F.getServerDumpPath(n),a=await Ve(s);if(a==null)return r&&console.debug(`[State] No server dump file found at: ${s}`),null;r&&(console.debug(`[State] server dump file found at "${s}":`),console.debug(a));let{issues:i,output:c,success:u}=(0,d.safeParse)((0,d.pipe)((0,d.string)(),(0,d.parseJson)(),hr),a);if(!u)throw r&&console.debug(`[State] Invalid server dump file at "${s}":
|
|
4
|
+
${JSON.stringify(i,null,2)}`),new Error(`Invalid Prisma Dev state for "${o}".`);return new F({databasePort:c.databasePort,debug:r,dryRun:!1,name:o,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(e){let{debug:r,globs:o}=e??{},n=(0,C.join)(N(Te),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let s=await Ge(n,o);return r&&console.debug(`[State] found server names: ${JSON.stringify(s)}`),await Promise.all(s.map(a=>gr(a,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},Re=class extends T{constructor(e){super({...e,databasePort:e?.databasePort,persistenceMode:"stateless",port:e?.port,shadowDatabasePort:e?.shadowDatabasePort})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[$e](){let e;try{e=await T.scan({debug:this.debug,onlyMetadata:!0})}catch(o){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",o),e=[]}let r=await he({debug:this.debug,name:this.dryRun?this.name:"",requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort}async close(){}async writeServerDump(){}},F=class t extends T{#r;#e;#t;#s;#a;#n;#o;constructor(e){super({...e,persistenceMode:"stateful"}),this.#n=!1,this.#e=N(this.name),this.#r=(0,C.join)(this.#e,"db_dump.bak"),this.#t=(0,C.join)(this.#e,".lock"),this.#s=(0,C.join)(this.#e,".pglite"),this.#o=e?.serverDump??null,this.#a=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,C.join)(e,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#o?.exports}get pgliteDataDirPath(){return this.#s}async[$e](){await Fe(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,M.lock)(this.#e,{lockfilePath:this.#t}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await T.scan({debug:this.debug,onlyMetadata:!0}),r=await he({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new G(this):e}}async close(){if(!this.#n)try{await(0,M.unlock)(this.#e,{lockfilePath:this.#t}),this.#n=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,e),e}}async writeServerDump(e){this.#o={name:this.name,version:"1",pid:Ae.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,It.writeFile)(this.#a,`${JSON.stringify(this.#o,null,2)}
|
|
5
|
+
`,{encoding:"utf-8"})}};async function gr(t,e){let{debug:r,onlyMetadata:o}=e||{},n=typeof t=="string"?t:t.name,s=typeof t!="string"?t:void 0,a={databasePort:s?.databasePort??-1,exports:s?.exports,name:n,pid:s?.pid,port:s?.port??-1,shadowDatabasePort:s?.shadowDatabasePort??-1,version:"1"};try{let i=s||await T.fromServerDump({debug:r,name:n});if(!i)return r&&console.debug(`[State] no server state found for name: ${n}`),{...a,status:"no_such_server"};a.databasePort=i.databasePort,a.exports=i.exports,a.pid=i.pid,a.port=i.port,a.shadowDatabasePort=i.shadowDatabasePort;let{exports:c,pid:u}=i;if(o)return{...a,status:"unknown"};if(!$t(u,r))return r&&console.debug(`[State] server state for "${n}" has no running process with PID: ${u}`),{...a,status:"not_running"};let l=N(n);try{if(!await(0,M.check)(l,{lockfilePath:(0,C.join)(l,".lock")}))return r&&console.debug(`[State] server state for "${n}" is not locked, indicating it is not running.`),{...a,status:"starting_up"}}catch(j){r&&console.error(`[State] server state for "${n}" failed to check lock:`,j)}if(!c)return{...a,status:"starting_up"};let{http:g}=c,{hc:b}=await import("hono/client"),x=await b(g.url).health.$get();if(!x.ok)return r&&console.debug(`[State] server state for "${n}" is not live: ${JSON.stringify(x)}`),{...a,status:"not_running"};let R=await x.json();return R.name!==t?(r&&console.debug(`[State] server state for "${n}" has mismatched health response: ${JSON.stringify(R)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(R)}`),{...a,status:"running"})}catch(i){return r&&console.error(`[State] failed to get server status for "${n}":`,i),{...a,status:"error"}}}var Oe=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},G=class extends Oe{#r;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#r=e}get server(){return T.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};async function Ct(t){let e=await T.createExclusively(t),[r,o]=await Promise.all([ge("database",e),ge("shadow_database",e)]),n=await Ot(r,e),s=`prisma+postgres://localhost:${n.port}/?${new URLSearchParams({api_key:Ie({databaseUrl:r.prismaORMConnectionString,name:e.name,shadowDatabaseUrl:o.prismaORMConnectionString})}).toString()}`,a={database:{connectionString:r.connectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand},http:{url:n.url},ppg:{url:s},shadowDatabase:{connectionString:o.prismaORMConnectionString,prismaORMConnectionString:o.prismaORMConnectionString,terminalCommand:o.terminalCommand}};return await e.writeServerDump(a),{...a,close:()=>i(e,[n,r,o]),name:e.name};async function i(c,u){let g=(await Promise.allSettled(u.map(b=>b.close()))).filter(b=>b.status==="rejected").map(b=>new Error(b.reason));try{await c.close()}catch(b){g.push(b)}if(g.length>0)throw new AggregateError(g,"Failed to close some servers")}}async function yr(t){return await Ct(t)}0&&(module.exports={DEFAULT_DATABASE_PORT,DEFAULT_SERVER_PORT,DEFAULT_SHADOW_DATABASE_PORT,PortNotAvailableError,ServerAlreadyRunningError,startPrismaDevServer,unstable_startServer});
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as f,b as g}from"./chunk-
|
|
1
|
+
import{a as f,b as g}from"./chunk-4Q54Y6ZK.js";import"./chunk-RBVZVBDC.js";import{g as e}from"./chunk-ZCVJ53EE.js";import{a,b,c,f as d}from"./chunk-LMPFMHCB.js";import"./chunk-7EOUKLQR.js";import"./chunk-EPFUMVT3.js";export{a as DEFAULT_DATABASE_PORT,b as DEFAULT_SERVER_PORT,c as DEFAULT_SHADOW_DATABASE_PORT,d as PortNotAvailableError,e as ServerAlreadyRunningError,f as startPrismaDevServer,g as unstable_startServer};
|
package/dist/state.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var ye=Object.create;var
|
|
2
|
-
${JSON.stringify(c,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new
|
|
3
|
-
`,{encoding:"utf-8"})}};async function
|
|
1
|
+
"use strict";var ye=Object.create;var O=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var we=Object.getOwnPropertyNames;var Se=Object.getPrototypeOf,De=Object.prototype.hasOwnProperty;var xe=(t,e)=>{for(var r in e)O(t,r,{get:e[r],enumerable:!0})},z=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of we(e))!De.call(t,s)&&s!==r&&O(t,s,{get:()=>e[s],enumerable:!(n=ve(e,s))||n.enumerable});return t};var D=(t,e,r)=>(r=t!=null?ye(Se(t)):{},z(e||!t||!t.__esModule?O(r,"default",{value:t,enumerable:!0}):r,t)),ke=t=>z(O({},"__esModule",{value:!0}),t);var Be={};xe(Be,{ServerAlreadyRunningError:()=>j,ServerState:()=>h,ServerStateAlreadyExistsError:()=>R,deleteServer:()=>Ie,getServerStatus:()=>X,isServerRunning:()=>me,killServer:()=>Pe});module.exports=ke(Be);var he=require("fs/promises"),g=require("pathe"),w=require("proper-lockfile"),J=require("std-env"),a=require("valibot");var Y=require("fs"),l=require("fs/promises"),Z=require("util"),Q=require("zlib");var d=D(require("path"),1),I=D(require("os"),1),$=D(require("process"),1),m=I.default.homedir(),B=I.default.tmpdir(),{env:y}=$.default,Oe=t=>{let e=d.default.join(m,"Library");return{data:d.default.join(e,"Application Support",t),config:d.default.join(e,"Preferences",t),cache:d.default.join(e,"Caches",t),log:d.default.join(e,"Logs",t),temp:d.default.join(B,t)}},$e=t=>{let e=y.APPDATA||d.default.join(m,"AppData","Roaming"),r=y.LOCALAPPDATA||d.default.join(m,"AppData","Local");return{data:d.default.join(r,t,"Data"),config:d.default.join(e,t,"Config"),cache:d.default.join(r,t,"Cache"),log:d.default.join(r,t,"Log"),temp:d.default.join(B,t)}},_e=t=>{let e=d.default.basename(m);return{data:d.default.join(y.XDG_DATA_HOME||d.default.join(m,".local","share"),t),config:d.default.join(y.XDG_CONFIG_HOME||d.default.join(m,".config"),t),cache:d.default.join(y.XDG_CACHE_HOME||d.default.join(m,".cache"),t),log:d.default.join(y.XDG_STATE_HOME||d.default.join(m,".local","state"),t),temp:d.default.join(B,e,t)}};function N(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),$.default.platform==="darwin"?Oe(t):$.default.platform==="win32"?$e(t):_e(t)}var ee=D(require("zeptomatch"),1),Te=N("prisma-dev"),Fe=(0,Z.promisify)(Q.unzip);function v(t){return`${Te.data}/${t}`}function te(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function re(t){try{return await(0,l.readFile)(t,{encoding:"utf-8"})}catch(e){if(te(e))return null;throw e}}async function se(t){await(0,l.mkdir)(t,{recursive:!0})}async function oe(t,e){try{return(await(0,l.readdir)(t,{withFileTypes:!0})).reduce((n,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!e||(0,ee.default)(e,s.name))&&n.push(s.name),n),[])}catch(r){if(te(r))return[];throw r}}async function ae(t){await(0,l.rm)(t,{force:!0,recursive:!0})}var ne=require("timers/promises"),x=require("std-env");function U(t,e){if(t==null)return!1;try{return x.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}async function ie(t,e){if(!x.process.kill)return!1;try{x.process.kill(t,"SIGTERM")}catch(n){return e&&console.error(`Error killing process with PID ${t}:`,n),!1}let r=0;do{if(!U(t,e))return!0;await(0,ne.setTimeout)(100)}while(++r<50);try{return x.process.kill(t,"SIGKILL")}catch(n){return e&&console.error(`Error forcefully killing process with PID ${t}:`,n),!1}}var b=require("get-port-please"),A=require("remeda"),ce=51214,ue=51213,de=51215,T=65535,P=-1/0;async function F(t){let{debug:e,name:r,requestedPorts:n,servers:s}=t,{portsUsedByOtherServers:o,portsUsedByThisServerLastTime:i}=Re(r,s);e&&(console.debug(`ports used by other servers: ${Object.keys(o).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(i)}`));let c={databasePort:P,port:P,shadowDatabasePort:P},u=["port","databasePort","shadowDatabasePort"];for(let p of u){let f=await Ee({debug:e,portKey:p,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:i,requestedPorts:n})??await Ae({debug:e,pickedPorts:c,portKey:p,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:i});e&&console.debug(`Got port for "${p}": ${f}`),c[p]=f}return e&&console.debug(`Picked ports: ${JSON.stringify(c)}`),c}async function Ee(t){let{debug:e,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s,requestedPorts:o}=t,{[r]:i,...c}=o;if(pe(i))return await je({debug:e,otherRequestedPorts:c,portKey:r,portsUsedByOtherServers:n,requestedPort:i}),i;let u=s?.[r]??P;if(!pe(u))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let p=u in n;return p||Object.values(c).includes(u)?(e&&console.debug(`Port ${u} that was used last time for this server, ${p?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,b.checkPort)(u)===!1?(e&&console.debug(`Port ${u}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(e&&console.debug(`Using port ${u} for "${r}" as it was used last time and is available.`),u)}async function Ae(t){let{debug:e,pickedPorts:r,portKey:n,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:o}=t,i=Math.max(ce,ue,de)+1,c=[...Object.values(r),...Object.keys(s).map(Number),...Object.values(o||{})],u=Math.min(Math.max(i,...c)+100,T),p=(0,A.difference)((0,A.range)(i,u),c),f={port:ue,databasePort:ce,shadowDatabasePort:de}[n];try{return await(0,b.getPort)({port:f in s||Object.values(r).includes(f)||Object.values(o||{}).includes(f)?void 0:f,ports:p})}catch(S){if(S instanceof Error&&S.name==="GetPortError"&&u+1<=T)return e&&console.debug(`Expanding port lookup to range [${u+1}, ${T}].`),await(0,b.getPort)({portRange:[u+1,T]});throw S}}function pe(t){return t>=0}function Re(t,e){let r={},n;for(let s of e){let{databasePort:o,port:i,shadowDatabasePort:c}=s;if(s.name===t){n={databasePort:o,port:i,shadowDatabasePort:c};continue}r[o]=!0,r[i]=!0,r[c]=!0}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}async function je(t){let{debug:e,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:s,requestedPort:o}=t;if(o in s)throw e&&console.error(`Port ${o} was requested for "${n}", but is already used by another server.`),new q(o);if(Object.values(r).includes(o))throw e&&console.error(`Port ${o} was requested for "${n}", but also for another key.`),new V(o);if((0,b.isUnsafePort)(o))throw e&&console.error(`Port ${o} was requested for "${n}", but is unsafe.`),new E(o);if(await(0,b.checkPort)(o)===!1)throw e&&console.error(`Port ${o} was requested for "${n}", but is not available.`),new E(o)}var E=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},V=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"},q=class extends Error{constructor(r){super(`Port number \`${r}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=r}name="PortBelongsToAnotherServerError"};var G=(0,a.pipe)((0,a.string)(),(0,a.url)()),le=(0,a.object)({connectionString:G,prismaORMConnectionString:(0,a.optional)(G),terminalCommand:(0,a.optional)((0,a.string)())}),fe=(0,a.object)({url:G}),C=(0,a.pipe)((0,a.number)(),(0,a.integer)(),(0,a.minValue)(1)),Me=(0,a.object)({database:le,http:fe,ppg:fe,shadowDatabase:le}),Le=(0,a.object)({databasePort:C,exports:(0,a.optional)(Me),name:(0,a.pipe)((0,a.string)(),(0,a.minLength)(1)),pid:(0,a.optional)((0,a.pipe)((0,a.number)(),(0,a.integer)(),(0,a.minValue)(0))),port:C,shadowDatabasePort:C,version:(0,a.literal)("1")}),W=Symbol("initialize"),K="default",h=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??P,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??K,this.persistenceMode=e.persistenceMode,this.pid=e.pid??J.process.pid,this._port=e.port??P,this._shadowDatabasePort=e.shadowDatabasePort??P}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new k(e):new H(e);return await r[W](),r}static async fromServerDump(e){let{debug:r,name:n=K}=e??{},s=v(n),o=k.getServerDumpPath(s),i=await re(o);if(i==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(i));let{issues:c,output:u,success:p}=(0,a.safeParse)((0,a.pipe)((0,a.string)(),(0,a.parseJson)(),Le),i);if(!p)throw r&&console.debug(`[State] Invalid server dump file at "${o}":
|
|
2
|
+
${JSON.stringify(c,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new k({databasePort:u.databasePort,debug:r,dryRun:!1,name:n,pid:u.pid,port:u.port,serverDump:u,shadowDatabasePort:u.shadowDatabasePort})}static async scan(e){let{debug:r,globs:n}=e??{},s=(0,g.join)(v(K),"..");r&&console.debug(`[State] scanning for server states in: ${s}`);let o=await oe(s,n);return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(i=>X(i,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},H=class extends h{constructor(e){super({...e,databasePort:e?.databasePort,persistenceMode:"stateless",port:e?.port,shadowDatabasePort:e?.shadowDatabasePort})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[W](){let e;try{e=await h.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),e=[]}let r=await F({debug:this.debug,name:this.dryRun?this.name:"",requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort}async close(){}async writeServerDump(){}},k=class t extends h{#t;#e;#s;#a;#n;#o;#r;constructor(e){super({...e,persistenceMode:"stateful"}),this.#o=!1,this.#e=v(this.name),this.#t=(0,g.join)(this.#e,"db_dump.bak"),this.#s=(0,g.join)(this.#e,".lock"),this.#a=(0,g.join)(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#n=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,g.join)(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get pgliteDataDirPath(){return this.#a}async[W](){await se(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,w.lock)(this.#e,{lockfilePath:this.#s}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await h.scan({debug:this.debug,onlyMetadata:!0}),r=await F({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new j(this):e}}async close(){if(!this.#o)try{await(0,w.unlock)(this.#e,{lockfilePath:this.#s}),this.#o=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,e),e}}async writeServerDump(e){this.#r={name:this.name,version:"1",pid:J.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,he.writeFile)(this.#n,`${JSON.stringify(this.#r,null,2)}
|
|
3
|
+
`,{encoding:"utf-8"})}};async function Ie(t,e){await Pe(t,e);let r=v(typeof t=="string"?t:t.name);await ae(r)}async function X(t,e){let{debug:r,onlyMetadata:n}=e||{},s=typeof t=="string"?t:t.name,o=typeof t!="string"?t:void 0,i={databasePort:o?.databasePort??-1,exports:o?.exports,name:s,pid:o?.pid,port:o?.port??-1,shadowDatabasePort:o?.shadowDatabasePort??-1,version:"1"};try{let c=o||await h.fromServerDump({debug:r,name:s});if(!c)return r&&console.debug(`[State] no server state found for name: ${s}`),{...i,status:"no_such_server"};i.databasePort=c.databasePort,i.exports=c.exports,i.pid=c.pid,i.port=c.port,i.shadowDatabasePort=c.shadowDatabasePort;let{exports:u,pid:p}=c;if(n)return{...i,status:"unknown"};if(!U(p,r))return r&&console.debug(`[State] server state for "${s}" has no running process with PID: ${p}`),{...i,status:"not_running"};let f=v(s);try{if(!await(0,w.check)(f,{lockfilePath:(0,g.join)(f,".lock")}))return r&&console.debug(`[State] server state for "${s}" is not locked, indicating it is not running.`),{...i,status:"starting_up"}}catch(ge){r&&console.error(`[State] server state for "${s}" failed to check lock:`,ge)}if(!u)return{...i,status:"starting_up"};let{http:S}=u,{hc:be}=await import("hono/client"),M=await be(S.url).health.$get();if(!M.ok)return r&&console.debug(`[State] server state for "${s}" is not live: ${JSON.stringify(M)}`),{...i,status:"not_running"};let L=await M.json();return L.name!==t?(r&&console.debug(`[State] server state for "${s}" has mismatched health response: ${JSON.stringify(L)}`),{...i,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(L)}`),{...i,status:"running"})}catch(c){return r&&console.error(`[State] failed to get server status for "${s}":`,c),{...i,status:"error"}}}function me(t){let{status:e}=t;return e==="running"||e==="starting_up"}async function Pe(t,e){let{pid:r,...n}=typeof t=="string"?await X(t,{debug:e}):t;if(!me(n))return!1;let s=await h.fromServerDump({debug:e,name:n.name});if(r==null){e&&console.debug(`[State] No PID found for server "${n.name}" to kill.`);try{await s?.close()}catch{}return!1}let o=await ie(r,e);try{await s?.close()}catch{}return o}var R=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},j=class extends R{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return h.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};0&&(module.exports={ServerAlreadyRunningError,ServerState,ServerStateAlreadyExistsError,deleteServer,getServerStatus,isServerRunning,killServer});
|
package/dist/state.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g}from"./chunk-
|
|
1
|
+
import{a,b,c,d,e,f,g}from"./chunk-ZCVJ53EE.js";import"./chunk-LMPFMHCB.js";import"./chunk-EPFUMVT3.js";export{g as ServerAlreadyRunningError,a as ServerState,f as ServerStateAlreadyExistsError,b as deleteServer,c as getServerStatus,d as isServerRunning,e as killServer};
|
package/package.json
CHANGED
package/dist/chunk-FZ7JBZR6.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{a as V,b as N,c as L,d as f,e as F}from"./chunk-LMPFMHCB.js";import{b as d,f as O,g as I,h as A,i as T}from"./chunk-EPFUMVT3.js";import{writeFile as X}from"fs/promises";import{join as l}from"pathe";import{check as ee,lock as te,unlock as re}from"proper-lockfile";import{process as B}from"std-env";import{integer as C,literal as se,minLength as ae,minValue as H,number as K,object as P,optional as g,parseJson as oe,pipe as h,safeParse as ne,string as v,url as ie}from"valibot";import{setTimeout as Q}from"timers/promises";import{process as b}from"std-env";function y(t,e){if(t==null)return!1;try{return b.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}async function J(t,e){if(!b.kill)return!1;try{b.kill(t,"SIGTERM")}catch(n){return e&&console.error(`Error killing process with PID ${t}:`,n),!1}let r=0;do{if(!y(t,e))return!0;await Q(100)}while(++r<50);try{return b.kill(t,"SIGKILL")}catch(n){return e&&console.error(`Error forcefully killing process with PID ${t}:`,n),!1}}var _=h(v(),ie()),U=P({connectionString:_,prismaORMConnectionString:g(_),terminalCommand:g(v())}),j=P({url:_}),w=h(K(),C(),H(1)),ue=P({database:U,http:j,ppg:j,shadowDatabase:U}),ce=P({databasePort:w,exports:g(ue),name:h(v(),ae(1)),pid:g(h(K(),C(),H(0))),port:w,shadowDatabasePort:w,version:se("1")}),R=Symbol("initialize"),x="default",c=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??f,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??x,this.persistenceMode=e.persistenceMode,this.pid=e.pid??B.pid,this._port=e.port??f,this._shadowDatabasePort=e.shadowDatabasePort??f}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new p(e):new k(e);return await r[R](),r}static async fromServerDump(e){let{debug:r,name:n=x}=e??{},a=d(n),o=p.getServerDumpPath(a),s=await O(o);if(s==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(s));let{issues:i,output:u,success:m}=ne(h(v(),oe(),ce),s);if(!m)throw r&&console.debug(`[State] Invalid server dump file at "${o}":
|
|
2
|
-
${JSON.stringify(i,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new p({databasePort:u.databasePort,debug:r,dryRun:!1,name:n,pid:u.pid,port:u.port,serverDump:u,shadowDatabasePort:u.shadowDatabasePort})}static async scan(e){let{debug:r,globs:n}=e??{},a=l(d(x),"..");r&&console.debug(`[State] scanning for server states in: ${a}`);let o=await A(a,n);return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(s=>q(s,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},k=class extends c{constructor(e){super({...e,databasePort:e?.databasePort??V,persistenceMode:"stateless",port:e?.port??N,shadowDatabasePort:e?.shadowDatabasePort??L})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[R](){}async close(){}async writeServerDump(){}},p=class t extends c{#t;#e;#s;#o;#n;#a;#r;constructor(e){super({...e,persistenceMode:"stateful"}),this.#a=!1,this.#e=d(this.name),this.#t=l(this.#e,"db_dump.bak"),this.#s=l(this.#e,".lock"),this.#o=l(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#n=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return l(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get pgliteDataDirPath(){return this.#o}async[R](){await I(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await te(this.#e,{lockfilePath:this.#s}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await c.scan({debug:this.debug,onlyMetadata:!0}),r=await F({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new E(this):e}}async close(){if(!this.#a)try{await re(this.#e,{lockfilePath:this.#s}),this.#a=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,e),e}}async writeServerDump(e){this.#r={name:this.name,version:"1",pid:B.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await X(this.#n,`${JSON.stringify(this.#r,null,2)}
|
|
3
|
-
`,{encoding:"utf-8"})}};async function xe(t,e){await le(t,e);let r=d(typeof t=="string"?t:t.name);await T(r)}async function q(t,e){let{debug:r,onlyMetadata:n}=e||{},a=typeof t=="string"?t:t.name,o=typeof t!="string"?t:void 0,s={databasePort:o?.databasePort??-1,exports:o?.exports,name:a,pid:o?.pid,port:o?.port??-1,shadowDatabasePort:o?.shadowDatabasePort??-1,version:"1"};try{let i=o||await c.fromServerDump({debug:r,name:a});if(!i)return r&&console.debug(`[State] no server state found for name: ${a}`),{...s,status:"no_such_server"};s.databasePort=i.databasePort,s.exports=i.exports,s.pid=i.pid,s.port=i.port,s.shadowDatabasePort=i.shadowDatabasePort;let{exports:u,pid:m}=i;if(n)return{...s,status:"unknown"};if(!y(m,r))return r&&console.debug(`[State] server state for "${a}" has no running process with PID: ${m}`),{...s,status:"not_running"};let M=d(a);try{if(!await ee(M,{lockfilePath:l(M,".lock")}))return r&&console.debug(`[State] server state for "${a}" is not locked, indicating it is not running.`),{...s,status:"starting_up"}}catch(Z){r&&console.error(`[State] server state for "${a}" failed to check lock:`,Z)}if(!u)return{...s,status:"starting_up"};let{http:G}=u,{hc:Y}=await import("hono/client"),S=await Y(G.url).health.$get();if(!S.ok)return r&&console.debug(`[State] server state for "${a}" is not live: ${JSON.stringify(S)}`),{...s,status:"not_running"};let D=await S.json();return D.name!==t?(r&&console.debug(`[State] server state for "${a}" has mismatched health response: ${JSON.stringify(D)}`),{...s,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(D)}`),{...s,status:"running"})}catch(i){return r&&console.error(`[State] failed to get server status for "${a}":`,i),{...s,status:"error"}}}function de(t){let{status:e}=t;return e==="running"||e==="starting_up"}async function le(t,e){let{pid:r,...n}=typeof t=="string"?await q(t,{debug:e}):t;if(!de(n))return!1;let a=await c.fromServerDump({debug:e,name:n.name});if(r==null){e&&console.debug(`[State] No PID found for server "${n.name}" to kill.`);try{await a?.close()}catch{}return!1}let o=await J(r,e);try{await a?.close()}catch{}return o}var $=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},E=class extends ${#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return c.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};export{c as a,xe as b,q as c,de as d,le as e,$ as f,E as g};
|