@prisma/dev 0.0.0-dev.202512121242 → 0.0.0-dev.202512121402
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/accelerate-MVW5ZKXM.js +1 -0
- package/dist/chunk-7EOUKLQR.js +3 -0
- package/dist/chunk-EPFUMVT3.js +1 -0
- package/dist/chunk-FZ7JBZR6.js +3 -0
- package/dist/chunk-GW6BCATQ.js +1 -0
- package/dist/chunk-LMPFMHCB.js +1 -0
- package/dist/chunk-RBVZVBDC.js +1 -0
- package/dist/daemon.cjs +5 -86
- package/dist/daemon.js +1 -1
- package/dist/db.js +1 -1
- package/dist/index.cjs +5 -86
- package/dist/index.js +1 -1
- package/dist/state.js +1 -1
- package/dist/utility-YJ4TFSMW.js +1 -0
- package/package.json +2 -2
- package/dist/accelerate-B4RDPMOM.js +0 -1
- package/dist/chunk-ABDUHDM7.js +0 -82
- package/dist/chunk-GUJALUTC.js +0 -3
- package/dist/chunk-KUHNXXCE.js +0 -1
- package/dist/chunk-NLG6WPCX.js +0 -1
- package/dist/chunk-RODR7QVK.js +0 -1
- package/dist/chunk-UZV6WD53.js +0 -3
- package/dist/chunk-ZPA6K2XO.js +0 -1
- package/dist/utility-2R6QXHRL.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as i,d as H,e as h}from"./chunk-7EOUKLQR.js";import"./chunk-EPFUMVT3.js";import{HTTPException as re}from"hono/http-exception";import{Hono as oe}from"hono/tiny";import{validator as c}from"hono/validator";import{array as B,literal as U,minLength as k,object as D,pipe as F,safeParse as N,string as Q,union as X}from"valibot";var Y=D({tags:X([F(B(Q()),k(1)),U("all")])});async function b(e){let{output:n,success:t}=N(Y,await e.req.json(),{abortEarly:!0});return t?n:e.text("Invalid input",400)}import{parseDuration as g,parseSize as z,Server as G}from"@prisma/query-plan-executor";import{version as y}from"@prisma/query-plan-executor";var S;async function E(e){return S===void 0&&(S=await G.create({databaseUrl:e.get("db").connectionString,maxResponseSize:z("128 MiB"),queryTimeout:g("PT5M"),maxTransactionTimeout:g("PT5M"),maxTransactionWaitTime:g("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:e.get("debug")?"debug":"off"}})),S}import{Buffer as O}from"buffer";import{produceSchema as W}from"@mrleebo/prisma-ast";var f=new Map;async function T(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}function w(e){let n=e.req.param("schemaHash"),t=f.get(n);return t==null?e.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:n,schemas:t}}async function x(e,n,t){let r=O.from(e,"base64").toString("utf8"),o=W(r,s=>{s.datasource('"postgresql"',n.toString())});t&&console.log("[Accelerate] schema with override:",o);let a=await T(o);return{base64Override:O.from(o,"utf8").toString("base64"),overrideHash:a}}function d(e){let{req:n}=e;return{traceparent:n.header("traceparent"),"X-capture-telemetry":n.header("X-capture-telemetry")}}import{integer as I,looseObject as K,minValue as C,number as v,object as J,optional as Z,pipe as q,safeParse as R,string as A,union as ee}from"valibot";var te=J({isolation_level:Z(A()),max_wait:q(v(),I(),C(0)),timeout:q(v(),I(),C(0))});async function _(e){let{issues:n,output:t,success:r}=R(te,await e.req.json(),{abortEarly:!0});return r?t:e.json({EngineNotStarted:{reason:"InvalidRequest",issues:n}},400)}var ne=K({id:ee([A(),v()])});function M(e,n){let{output:t,success:r}=R(ne,e);return r?t:n.json({EngineMalfunction:{}},500)}var l=new oe;l.post("/invalidate",c("header",i),async e=>{let n=await b(e);return n instanceof Response?n:e.body(null)});var ae="/:clientVersion/:schemaHash",u=l.basePath(ae);l.route("/",u);var se=["/graphql","/itx/:transactionId/graphql"];u.on("POST",[...se],c("header",i),async e=>{let{req:n}=e;try{let t=await P(e);if(t instanceof Response)return t;let r=await n.text(),o=n.param("transactionId"),a=await t.request(r,{...d(e),"X-transaction-id":o});return e.text(a)}catch(t){return h(t,e)}});u.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],c("header",i),async e=>{let{req:n}=e;try{let t=await P(e);if(t instanceof Response)return t;let o=`${n.routePath.split("/").filter(Boolean).at(-1)}Transaction`,a=n.param("transactionId"),s=await t[o](a,d(e));return e.json(s)}catch(t){return h(t,e)}});u.put("/schema",c("header",i),async e=>{let{req:n}=e,t=await n.text();if(!t)return e.text("Missing schema",400);let r=n.param("schemaHash"),o=f.get(r);if(o==null){if(r!==await T(t))return e.text("Schema hash mismatch",400);let a=await x(t,e.get("db").prismaORMConnectionString,e.get("debug"));return f.set(r,{base64Original:t,...a}),e.text(r)}return t!==o.base64Original?e.text("Schema mismatch",400):e.text(r)});u.post("/transaction/start",c("header",i),async e=>{let{req:n}=e,t=await _(e);if(t instanceof Response)return t;try{let r=await P(e);if(r instanceof Response)return r;let o=await r.startTransaction(t,d(e)),a=M(o,e);if(a instanceof Response)return a;let{id:s}=a,V=n.param("clientVersion"),$=e.get("port"),j=e.get("protocol"),L=n.param("schemaHash");return e.json({...o,"data-proxy":{endpoint:`${j}://localhost:${$}/${V}/${L}/itx/${s}`}})}catch(r){return h(r,e)}});async function P(e){let{req:n}=e,t=w(e);if(t instanceof Response)return t;let{base64Override:r,overrideHash:o}=t.schemas;return await H.get({base64Schema:r,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||n.param("clientVersion"),debug:e.get("debug"),platform:e.get("platform"),schemaHash:o})}var ie=[["/connection-info","GET"],["/query","POST"],["/transaction/start","POST"],["/transaction/:transactionId/commit","POST"],["/transaction/:transactionId/query","POST"],["/transaction/:transactionId/rollback","POST"]];for(let[e,n]of ie)l.on(n,e,c("header",i),async t=>{let r=t.req.header("prisma-engine-hash");if(r!=="0.0.0"&&r!==y)throw new re(400,{message:`Using an HTTP connection string is not supported with Prisma Client version ${r} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${y}.`});return await(await E(t)).fetch(t.req.raw)});export{l as accelerateRoute};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{a as P,c as b,d as v}from"./chunk-EPFUMVT3.js";import{minLength as D,object as j,optional as B,parseJson as K,pipe as y,regex as R,safeParse as L,string as w,url as S}from"valibot";var A=/^(postgres|postgresql):\/\//,_=y(w(),K(),j({databaseUrl:y(w(),S(),R(A)),name:B(y(w(),D(1))),shadowDatabaseUrl:y(w(),S(),R(A))}));function W(r){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(r).sort(([[e],[n]])=>e.localeCompare(n)))),"utf8").toString("base64url")}function N(r){let e=Buffer.from(r,"base64url").toString("utf8"),{issues:n,output:s,success:t}=L(_,e,{abortEarly:!0});return t?[null,s]:[n]}var Y=async(r,e)=>{let{authorization:n}=r,{HTTPException:s}=await import("hono/http-exception");if(!n)throw new s(401,{message:"Missing API Key"});let[t,o="",i]=n.split(" ");if(t!=="Bearer"||i)throw new s(401,{message:"Invalid API Key"});let[a,p]=N(o);if(a)throw new s(401,{message:"Invalid API Key",cause:a.join(", ")});let{databaseUrl:m,name:c,shadowDatabaseUrl:l}=p,{name:d}=e.get("serverState");if(!c)throw new s(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 "${d}" server's output for the updated \`DATABASE_URL\` value.`});if(c!==d)throw new s(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${d}", but the API Key is for "${c}"`});let{hostname:h,port:f}=new URL(m),{port:E}=e.get("db"),{hostname:$,port:C}=new URL(l),H=e.get("shadowDBPort");if(h!=="localhost"||Number(f)!==E||$!=="localhost"||Number(C)!==H)throw new s(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:p}};import{spawn as Q}from"child_process";import{once as F}from"events";import{mkdir as U}from"fs/promises";import{join as V}from"path";import{setTimeout as z}from"timers/promises";function O(r){let e,n,s=new Promise((i,a)=>{e=i,n=a}),t=i=>{t=o=null,n(i),r?.onRejected?.(i),r?.onFulfilled?.()},o=i=>{o=t=null,e(i),r?.onResolved?.(i),r?.onFulfilled?.()};return{isFulfilled:()=>o===t,promise:s,reject:i=>t?.(i),resolve:i=>o?.(i)}}import{process as M}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:q,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:J,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:I}=M.env,x=class r{static#t=new Map;#e;#n;constructor(e){this.#e=e,this.#n=null}static async get(e){let{debug:n}=e,s=`${e.schemaHash}:${e.clientVersion}`;try{let t=r.#t.get(s);if(t)return t;let o=new r(e);return r.#t.set(s,o),n&&console.debug("[Query Engine] starting...",e),await o.start(),n&&console.debug("[Query Engine] started!"),o}finally{r.stopAll(s)}}static async stopAll(e){let s=(await Promise.allSettled(Array.from(r.#t.entries()).filter(([t])=>t!==e).map(async([t,o])=>{try{await o.stop()}finally{r.#t.delete(t)}}))).filter(t=>t.status==="rejected").map(t=>t.reason);if(s.length>0)throw new AggregateError(s,"Failed to stop engines")}async commitTransaction(e,n){return await this.#i(e,n,"commit")}async request(e,n){let{url:s}=await this.start(),t=this.#s(n),o=await fetch(s,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...t,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await u.fromResponse(o);return await o.text()}async rollbackTransaction(e,n){return await this.#i(e,n,"rollback")}async startTransaction(e,n){let{url:s}=await this.start(),t=this.#s(n),o=await fetch(`${s}/transaction/start`,{body:JSON.stringify(e),headers:{...t,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await u.fromResponse(o);return await o.json()}async start(){if(this.#n!=null)return await this.#n;let{promise:e,reject:n,resolve:s}=O();this.#n=e;let t=J||await this.#o();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",t);let{proxySignals:o}=await import("foreground-child/proxy-signals"),i=Q(t,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});o(i),i.stderr.setEncoding("utf8"),i.stdout.setEncoding("utf8");let a=c=>{let l=c.split(`
|
|
2
|
+
`).find(E=>E.includes("Started query engine http server"));if(!l)return;i.stdout.removeListener("data",a);let{fields:d}=JSON.parse(l);if(d==null)return n(new Error(`Unexpected data during initialization, "fields" are missing: ${c}`));let{ip:h,port:f}=d;if(h==null||f==null)return n(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: ${c}`));s({childProcess:i,url:`http://${h}:${f}`})},p=c=>{this.#n=null,n(new g(String(c))),i.removeListener("exit",m),i.kill()};i.once("error",p);let m=(c,l)=>{this.#n=null,n(new g(`Query Engine exited with code ${c} and signal ${l}`))};return i.once("exit",m),i.stdout.on("data",a),this.#e.debug&&(i.stderr.on("data",console.error.bind(console,"[Query Engine]")),i.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#n}async stop(){if(this.#n==null)return;let{childProcess:e}=await this.#n;e.exitCode==null&&e.signalCode==null&&(this.#n=null,e.kill(),await F(e,"exit"))}async#o(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#r();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let n=P(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",n),await U(n,{recursive:!0});let{binaryTarget:s}=this.#e.platform,t=s==="windows"?".exe":"",o=V(n,`query-engine-${s}${t}`);return this.#e.debug&&console.debug("[Query Engine] binary path",o),(q==="1"||await b(o)===!1)&&await this.#a({commitHash:e,extension:t,engineBinaryPath:o}),o}async#r(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let s=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!s)throw new Error("Couldn't find engines version in package.json");let t=s.split(".").at(-1);if(!t)throw new Error("Couldn't find commit hash in engines version");return t}async#a(e){let{commitHash:n,extension:s,engineBinaryPath:t}=e,{binaryTarget:o}=this.#e.platform,i=`https://binaries.prisma.sh/all_commits/${n}/${o}/query-engine${s}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",i);let a=await fetch(i);if(!a.ok)throw new Error(`Couldn't download engine. URL: ${i}, status code: ${a.status}`);I&&await z(Number(I)),await v(await a.arrayBuffer(),t),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",t)}#s(e){let n={};for(let[s,t]of Object.entries(e))t!=null&&(n[s]=t);return n}async#i(e,n,s){let{url:t}=await this.#n,o=this.#s(n),i=await fetch(`${t}/transaction/${e}/${s}`,{headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await u.fromResponse(i);try{return await i.json()}catch{return{}}}};function de(r,e){return console.error(r),r instanceof g?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:r.message}}}},500):r instanceof u?e.text(r.responseBody,r.statusCode):e.body(null,500)}var g=class extends Error{name="EngineStartError"},u=class r extends Error{constructor(n,s,t){super(`${n}: Query Engine response status ${s}, body: ${t}`);this.action=n;this.statusCode=s;this.responseBody=t}name="EngineHttpError";static async fromResponse(n){let s=new URL(n.url),t=await n.text();return new r(s.pathname,n.status,t)}};export{W as a,Y as b,O as c,x as d,de as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createWriteStream as w,WriteStream as A}from"fs";import{access as D,chmod as x,constants as P,mkdir as E,readdir as T,readFile as _,rm as F,writeFile as O}from"fs/promises";import{promisify as v}from"util";import{unzip as L}from"zlib";import o from"path";import g from"os";import c from"process";var n=g.homedir(),a=g.tmpdir(),{env:e}=c,h=r=>{let t=o.join(n,"Library");return{data:o.join(t,"Application Support",r),config:o.join(t,"Preferences",r),cache:o.join(t,"Caches",r),log:o.join(t,"Logs",r),temp:o.join(a,r)}},y=r=>{let t=e.APPDATA||o.join(n,"AppData","Roaming"),i=e.LOCALAPPDATA||o.join(n,"AppData","Local");return{data:o.join(i,r,"Data"),config:o.join(t,r,"Config"),cache:o.join(i,r,"Cache"),log:o.join(i,r,"Log"),temp:o.join(a,r)}},j=r=>{let t=o.basename(n);return{data:o.join(e.XDG_DATA_HOME||o.join(n,".local","share"),r),config:o.join(e.XDG_CONFIG_HOME||o.join(n,".config"),r),cache:o.join(e.XDG_CACHE_HOME||o.join(n,".cache"),r),log:o.join(e.XDG_STATE_HOME||o.join(n,".local","state"),r),temp:o.join(a,t,r)}};function p(r,{suffix:t="nodejs"}={}){if(typeof r!="string")throw new TypeError(`Expected a string, got ${typeof r}`);return t&&(r+=`-${t}`),c.platform==="darwin"?h(r):c.platform==="win32"?y(r):j(r)}import C from"zeptomatch";var l=p("prisma-dev"),G=v(L);function z(r,t){return`${l.cache}/engine/${r}/${t}`}function I(r){return`${l.data}/${r}`}async function J(r){try{return await D(r,P.F_OK),!0}catch(t){if(u(t))return!1;throw t}}async function K(r,t){let i=await G(r);await O(t,i),await x(t,"755")}async function q(r,t){await r.stream().pipeTo(A.toWeb(w(t,{encoding:"utf-8"})))}function u(r){return r!=null&&typeof r=="object"&&"code"in r&&r.code==="ENOENT"}async function Q(r){try{return await _(r,{encoding:"utf-8"})}catch(t){if(u(t))return null;throw t}}async function U(r){await E(r,{recursive:!0})}async function V(r,t){try{return(await T(r,{withFileTypes:!0})).reduce((f,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!t||C(t,s.name))&&f.push(s.name),f),[])}catch(i){if(u(i))return[];throw i}}async function Y(r){await F(r,{force:!0,recursive:!0})}export{z as a,I as b,J as c,K as d,q as e,Q as f,U as g,V as h,Y as i};
|
|
@@ -0,0 +1,3 @@
|
|
|
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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as d}from"./chunk-RBVZVBDC.js";import{a as w}from"./chunk-FZ7JBZR6.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-MVW5ZKXM.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 @@
|
|
|
1
|
+
import{checkPort as w,getPort as m,isUnsafePort as O}from"get-port-please";import{difference as T,range as $}from"remeda";var v=51214,h=51213,S=51215,p=65535,P=-1/0;async function E(s){let{debug:t,name:e,requestedPorts:n,servers:u}=s,{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:a}=x(e,u);t&&(console.debug(`ports used by other servers: ${Object.keys(r).join(", ")}`),console.debug(`ports used by "${e}" server last time: ${JSON.stringify(a)}`));let i={databasePort:P,port:P,shadowDatabasePort:P},o=["port","databasePort","shadowDatabasePort"];for(let c of o){let d=await k({debug:t,portKey:c,portsUsedByOtherServers:r,portsUsedByThisServerLastTime:a,requestedPorts:n})??await U({debug:t,pickedPorts:i,portKey:c,portsUsedByOtherServers:r,portsUsedByThisServerLastTime:a});t&&console.debug(`Got port for "${c}": ${d}`),i[c]=d}return t&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function k(s){let{debug:t,portKey:e,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:u,requestedPorts:r}=s,{[e]:a,...i}=r;if(g(a))return await B({debug:t,otherRequestedPorts:i,portKey:e,portsUsedByOtherServers:n,requestedPort:a}),a;let o=u?.[e]??P;if(!g(o))return t&&console.debug(`No port specified for "${e}". Trying to pick a new port.`),null;let c=o in n;return c||Object.values(i).includes(o)?(t&&console.debug(`Port ${o} that was used last time for this server, ${c?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await w(o)===!1?(t&&console.debug(`Port ${o}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(t&&console.debug(`Using port ${o} for "${e}" as it was used last time and is available.`),o)}async function U(s){let{debug:t,pickedPorts:e,portKey:n,portsUsedByOtherServers:u,portsUsedByThisServerLastTime:r}=s,a=Math.max(v,h,S)+1,i=[...Object.values(e),...Object.keys(u).map(Number),...Object.values(r||{})],o=Math.min(Math.max(a,...i)+100,p),c=T($(a,o),i),d={port:h,databasePort:v,shadowDatabasePort:S}[n];try{return await m({port:d in u||Object.values(e).includes(d)||Object.values(r||{}).includes(d)?void 0:d,ports:c})}catch(b){if(b instanceof Error&&b.name==="GetPortError"&&o+1<=p)return t&&console.debug(`Expanding port lookup to range [${o+1}, ${p}].`),await m({portRange:[o+1,p]});throw b}}function g(s){return s>=0}function x(s,t){let e={},n;for(let u of t){let{databasePort:r,port:a,shadowDatabasePort:i}=u;if(u.name===s){n={databasePort:r,port:a,shadowDatabasePort:i};continue}e[r]=!0,e[a]=!0,e[i]=!0}return{portsUsedByOtherServers:e,portsUsedByThisServerLastTime:n}}async function B(s){let{debug:t,otherRequestedPorts:e,portKey:n,portsUsedByOtherServers:u,requestedPort:r}=s;if(r in u)throw t&&console.error(`Port ${r} was requested for "${n}", but is already used by another server.`),new y(r);if(Object.values(e).includes(r))throw t&&console.error(`Port ${r} was requested for "${n}", but also for another key.`),new l(r);if(O(r))throw t&&console.error(`Port ${r} was requested for "${n}", but is unsafe.`),new f(r);if(await w(r)===!1)throw t&&console.error(`Port ${r} was requested for "${n}", but is not available.`),new f(r)}var f=class extends Error{constructor(e){super(`Port \`${e}\` is not available.`);this.port=e}name="PortNotAvailableError"},l=class extends Error{constructor(e){super(`Port number \`${e}\` was requested twice. Please choose a different port for each service.`);this.port=e}name="PortRequestedTwiceError"},y=class extends Error{constructor(e){super(`Port number \`${e}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=e}name="PortBelongsToAnotherServerError"};export{v as a,h as b,S as c,P as d,E as e,f};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{f as u}from"./chunk-LMPFMHCB.js";import{e as m}from"./chunk-EPFUMVT3.js";import{filename as D}from"pathe/utils";var n={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},P=`postgres://${n.username}:${n.password}@localhost`,S=new URLSearchParams({sslmode:n.sslMode}),w=new URLSearchParams({...Object.fromEntries(S.entries()),connection_limit:String(n.connectionLimit),connect_timeout:String(n.connectTimeout),max_idle_connection_lifetime:String(n.maxIdleConnectionLifetime),pool_timeout:String(n.poolTimeout),single_use_connections:"true",socket_timeout:String(n.socketTimeout)});async function L(e,o){let i=e==="database"?o.databasePort:o.shadowDatabasePort;if(o.dryRun)return g(e,o,{db:null,port:i,server:null});let{debug:a}=o,s=await(e==="shadow_database"?y:f)(o.pgliteDataDirPath,a);a&&s.onNotification((t,d)=>{console.debug(`[${e}][${t}] ${d}`)});let{PGLiteSocketServer:l}=await import("@electric-sql/pglite-socket"),r=new l({db:s,debug:a,inspect:a,port:i});a&&(r.addEventListener("listening",t=>{let{detail:d}=t;console.debug(`[${e}] server listening on ${JSON.stringify(d)}`)}),r.addEventListener("connection",t=>{let{clientAddress:d,clientPort:p}=t.detail;console.debug(`[${e}] client connected from ${d}:${p}`)}),r.addEventListener("error",t=>{let{detail:d}=t;console.error(`[${e}] server error:`,d)}));try{await r.start()}catch(t){throw t instanceof Error&&"code"in t&&t.code==="EADDRINUSE"?new u(i):t}return g(e,o,{db:s,port:i,server:r})}function g(e,o,i){let{debug:a}=o,{db:c,port:s,server:l}=i||{};return a&&console.debug(`[${e}] server started on port ${s}`),{...n,close:async()=>{let r=[];try{await l?.stop(),a&&console.debug(`[${e}] server stopped on port ${s}`)}catch(t){console.error(`[${e}] server stop error`,t),r.push(t)}if(e==="database")try{await c?.syncToFs(),a&&console.debug(`[${e}] synced to filesystem`)}catch(t){console.error(`[${e}] sync error`,t),r.push(t)}try{await c?.close(),a&&console.debug(`[${e}] closed`)}catch(t){console.error(`[${e}] close error`,t),r.push(t)}if(r.length>0)throw new AggregateError(r,`Failed to close ${e} properly`)},connectionString:b(s,S),dump:async r=>{e==="shadow_database"||!c||await v({db:c,debug:a,destinationPath:r})},port:s,prismaORMConnectionString:b(s,w),terminalCommand:`PGPASSWORD=${n.password} PGSSLMODE=${n.sslMode} psql -h localhost -p ${s} -U ${n.username} -d ${n.database}`}}function b(e,o){return`${P}:${e}/${n.database}?${o.toString()}`}async function f(e,o){let{PGlite:i}=await import("@electric-sql/pglite");return await i.create({database:n.database,dataDir:e,debug:o?5:void 0,relaxedDurability:!1,username:n.username})}async function y(e,o){let{PGlite:i}=await import("@electric-sql/pglite");return await i.create({database:n.database,dataDir:"memory://",debug:o?5:void 0,relaxedDurability:!1,username:n.username})}async function v(e){let{dataDir:o,db:i,debug:a,destinationPath:c}=e,s=i||await f(o,a),{pgDump:l}=await import("@electric-sql/pglite-tools/pg_dump"),r=await l({args:["--schema-only","--no-owner"],fileName:c?D(c):void 0,pg:await s.clone()});return c?(a&&console.debug(`[DB] Dumping database to ${c}`),await m(r,c)):(a&&console.debug("[DB] Dumping database to memory"),await r.text())}export{L as a,v as b};
|