@prisma/dev 0.0.0-dev.202506040041 → 0.0.0-dev.202506040104
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/index.js +4 -4
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{a as
|
|
3
|
-
`).find(
|
|
4
|
-
Received data: ${
|
|
2
|
+
import{a as k,b as L,c as j,d as N,e as it,f as at,g as ct,h as v,i as U}from"./chunk-A33H6MPG.js";import{HTTPException as P}from"hono/http-exception";import{object as le,optional as ue,parseJson as me,pipe as x,regex as q,safeParse as pe,string as H,url as M}from"valibot";var V=/^(postgres|postgresql):\/\//,ge=x(H(),me(),le({databaseUrl:x(H(),M(),q(V)),shadowDatabaseUrl:ue(x(H(),M(),q(V)))}));function K(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function fe(e){let t=Buffer.from(e,"base64url").toString("utf8"),{issues:n,output:r,success:o}=pe(ge,t,{abortEarly:!0});return o?[null,r]:[n]}var g=(e,t)=>{let{authorization:n}=e;if(!n)throw new P(401,{message:"Missing API Key"});let[r,o="",s]=n.split(" ");if(r!=="Bearer"||s)throw new P(401,{message:"Invalid API Key"});let[i,a]=fe(o);if(i)throw new P(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:c}=a;if(c!==t.var.db.connectionString)throw new P(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:a}};import{PGlite as G}from"@electric-sql/pglite";import{PGLiteSocketServer as he}from"@electric-sql/pglite-socket";import{pgDump as ye}from"@electric-sql/pglite-tools/pg_dump";import{filename as we}from"pathe/utils";var d={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},Se=`postgres://${d.username}:${d.password}@localhost`,be=new URLSearchParams({connection_limit:String(d.connectionLimit),connect_timeout:String(d.connectTimeout),max_idle_connection_lifetime:String(d.maxIdleConnectionLifetime),pool_timeout:String(d.poolTimeout),socket_timeout:String(d.socketTimeout),sslmode:d.sslMode});async function I(e,t){let n=e==="database"?t.databasePort:t.shadowDatabasePort;if(t.dryRun)return F(e,t,{db:null,port:n,server:null});let{debug:r}=t,s=await(e==="shadow_database"?Pe:Q)(t.pgliteDataDirPath,r);r&&s.onNotification((a,c)=>{console.debug(`[${e}][${a}] ${c}`)});let i=new he({db:s,debug:r,inspect:r,port:n});r&&(i.addEventListener("listening",a=>{let{detail:c}=a;console.debug(`[${e}] server listening on ${JSON.stringify(c)}`)}),i.addEventListener("connection",a=>{let{clientAddress:c,clientPort:l}=a.detail;console.debug(`[${e}] client connected from ${c}:${l}`)}),i.addEventListener("error",a=>{let{detail:c}=a;console.error(`[${e}] server error:`,c)}));try{await i.start()}catch(a){throw a instanceof Error&&"code"in a&&a.code==="EADDRINUSE"?new v(n,e):a}return F(e,t,{db:s,port:n,server:i})}function F(e,t,n){let{debug:r}=t,{db:o,port:s,server:i}=n||{};return r&&console.debug(`[${e}] server started on port ${s}`),{...d,close:async()=>{let a=[];try{await i?.stop(),r&&console.debug(`[${e}] server stopped on port ${s}`)}catch(c){console.error(`[${e}] server stop error`,c),a.push(c)}if(e==="database")try{await o?.syncToFs(),r&&console.debug(`[${e}] synced to filesystem`)}catch(c){console.error(`[${e}] sync error`,c),a.push(c)}try{await o?.close(),r&&console.debug(`[${e}] closed`)}catch(c){console.error(`[${e}] close error`,c),a.push(c)}if(a.length>0)throw new AggregateError(a,`Failed to close ${e} properly`)},connectionString:ve(s),dump:async a=>{e==="shadow_database"||!o||await Ee({db:o,debug:r,destinationPath:a})},port:s}}function ve(e){return`${Se}:${e}/${d.database}?${be.toString()}`}async function Q(e,t){return await G.create({database:d.database,dataDir:e,debug:t?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:d.username})}async function Pe(e,t){return await G.create({database:d.database,dataDir:"memory://",debug:t?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:d.username})}async function Ee(e){let{dataDir:t,db:n,debug:r,destinationPath:o}=e,s=n||await Q(t,r),i=await ye({args:["--quote-all-identifiers","--schema-only"],fileName:o?we(o):void 0,pg:s});return o?(r&&console.debug(`[DB] Dumping database to ${o}`),await N(i,o)):(r&&console.debug("[DB] Dumping database to memory"),await i.text())}import{createServer as et}from"http";import{promisify as tt}from"util";import{serve as nt}from"@hono/node-server";import rt from"@prisma/get-platform";function E(){let e,t,n=new Promise((s,i)=>{e=s,t=i}),r=s=>{r=o=null,t(s)},o=s=>{o=r=null,e(s)};return{promise:n,reject:s=>r?.(s),resolve:s=>o?.(s)}}import{logger as ot}from"hono/logger";import{Hono as ae}from"hono/tiny";import{Hono as ze}from"hono/tiny";import{validator as w}from"hono/validator";import{array as Te,literal as Re,minLength as De,object as Ae,pipe as xe,safeParse as He,string as Ie,union as Oe}from"valibot";var $e=Ae({tags:Oe([xe(Te(Ie()),De(1)),Re("all")])});async function J(e){let{output:t,success:n}=He($e,await e.req.json(),{abortEarly:!0});return n?t:e.text("Invalid input",400)}import{spawn as Ce}from"child_process";import{once as Be}from"events";import{mkdir as _e}from"fs/promises";import{join as ke}from"path";import{setTimeout as Le}from"timers/promises";import{proxySignals as je}from"foreground-child/proxy-signals";import{process as Ne}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Ue,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:qe,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:z}=Ne.env,h=class e{static#n=new Map;#e;#t;constructor(t){this.#e=t,this.#t=null}static async get(t){let{debug:n}=t,r=`${t.schemaHash}:${t.clientVersion}`;try{let o=e.#n.get(r);if(o)return o;let s=new e(t);return e.#n.set(r,s),n&&console.debug("[Query Engine] starting...",t),await s.start(),n&&console.debug("[Query Engine] started!"),s}finally{e.stopAll(r)}}static async stopAll(t){let r=(await Promise.allSettled(Array.from(e.#n.entries()).filter(([o])=>o!==t).map(async([o,s])=>{try{await s.stop()}finally{e.#n.delete(o)}}))).filter(o=>o.status==="rejected").map(o=>o.reason);if(r.length>0)throw new AggregateError(r,"Failed to stop engines")}async commitTransaction(t,n){return await this.#o(t,n,"commit")}async request(t,n){let{url:r}=await this.start(),o=this.#r(n),s=await fetch(r,{body:typeof t=="string"?t:JSON.stringify(t),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await f.fromResponse(s);return await s.text()}async rollbackTransaction(t,n){return await this.#o(t,n,"rollback")}async startTransaction(t,n){let{url:r}=await this.start(),o=this.#r(n),s=await fetch(`${r}/transaction/start`,{body:JSON.stringify(t),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await f.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:t,reject:n,resolve:r}=E();this.#t=t;let o=qe||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=Ce(o,["--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});je(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let i=l=>{let m=l.split(`
|
|
3
|
+
`).find(de=>de.includes("Started query engine http server"));if(!m)return;s.stdout.removeListener("data",i);let{fields:p}=JSON.parse(m);if(p==null)return n(new Error(`Unexpected data during initialization, "fields" are missing: ${l}`));let{ip:u,port:_}=p;if(u==null||_==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.
|
|
4
|
+
Received data: ${l}`));r({childProcess:s,url:`http://${u}:${_}`})},a=l=>{this.#t=null,n(new y(String(l))),s.removeListener("exit",c),s.kill()};s.once("error",a);let c=(l,m)=>{this.#t=null,n(new y(`Query Engine exited with code ${l} and signal ${m}`))};return s.once("exit",c),s.stdout.on("data",i),this.#e.debug&&(s.stderr.on("data",console.error.bind(console,"[Query Engine]")),s.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:t}=await this.#t;t.exitCode==null&&t.signalCode==null&&(this.#t=null,t.kill(),await Be(t,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let t=await this.#i();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",t);let n=k(this.#e.clientVersion,t);this.#e.debug&&console.debug("[Query Engine] cache directory path",n),await _e(n,{recursive:!0});let{platform:r}=this.#e.platform,o=r==="windows"?".exe":"",s=ke(n,`query-engine-${r}${o}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(Ue==="1"||await L(s)===!1)&&await this.#a({commitHash:t,extension:o,engineBinaryPath:s}),s}async#i(){let t=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!t.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${t.status}`);let r=(await t.json()).devDependencies?.["@prisma/engines-version"];if(!r)throw new Error("Couldn't find engines version in package.json");let o=r.split(".").at(-1);if(!o)throw new Error("Couldn't find commit hash in engines version");return o}async#a(t){let{commitHash:n,extension:r,engineBinaryPath:o}=t,{binaryTarget:s}=this.#e.platform,i=`https://binaries.prisma.sh/all_commits/${n}/${s}/query-engine${r}.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}`);z&&await Le(Number(z)),await j(await a.arrayBuffer(),o),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",o)}#r(t){let n={};for(let[r,o]of Object.entries(t))o!=null&&(n[r]=o);return n}async#o(t,n,r){let{url:o}=await this.#t,s=this.#r(n),i=await fetch(`${o}/transaction/${t}/${r}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await f.fromResponse(i);try{return await i.json()}catch{return{}}}};function T(e,t){return console.error(e),e instanceof y?t.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:e.message}}}},500):e instanceof f?t.text(e.responseBody,e.statusCode):t.body(null,500)}var y=class extends Error{name="EngineStartError"},f=class e extends Error{constructor(n,r,o){super(`${n}: Query Engine response status ${r}, body: ${o}`);this.action=n;this.statusCode=r;this.responseBody=o}name="EngineHttpError";static async fromResponse(n){let r=new URL(n.url),o=await n.text();return new e(r.pathname,n.status,o)}};import{Buffer as Y}from"buffer";var R=new Map;async function O(e){let n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}function X(e){let t=e.req.param("schemaHash"),n=R.get(t);return n==null?e.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:t,schemas:n}}var Me=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function W(e,t){let n=Y.from(e,"base64").toString("utf8"),r=`datasource db {
|
|
5
5
|
provider = "postgresql"
|
|
6
6
|
url = "${t.toString()}"
|
|
7
|
-
}`,o=n.replace(
|
|
7
|
+
}`,o=n.replace(Me,r),s=await O(o);return{base64Override:Y.from(o,"utf8").toString("base64"),overrideHash:s}}function D(e){let{req:t}=e;return{traceparent:t.header("traceparent"),"X-capture-telemetry":t.header("X-capture-telemetry")}}import{integer as Z,looseObject as Ve,minValue as ee,number as $,object as Ke,optional as Fe,pipe as te,safeParse as ne,string as re,union as Ge}from"valibot";var Qe=Ke({isolation_level:Fe(re()),max_wait:te($(),Z(),ee(0)),timeout:te($(),Z(),ee(0))});async function oe(e){let{issues:t,output:n,success:r}=ne(Qe,await e.req.json(),{abortEarly:!0});return r?n:e.json({EngineNotStarted:{reason:"InvalidRequest",issues:t}},400)}var Je=Ve({id:Ge([re(),$()])});function se(e,t){let{output:n,success:r}=ne(Je,e);return r?n:t.json({EngineMalfunction:{}},500)}var S=new ze;S.post("/invalidate",w("header",g),async e=>{let t=await J(e);return t instanceof Response?t:e.body(null)});var Ye="/:clientVersion/:schemaHash",b=S.basePath(Ye);S.route("/",b);var Xe=["/graphql","/itx/:transactionId/graphql"];b.on("POST",[...Xe],w("header",g),async e=>{let{req:t}=e;try{let n=await C(e);if(n instanceof Response)return n;let r=await t.text(),o=t.param("transactionId"),s=await n.request(r,{...D(e),"X-transaction-id":o});return e.text(s)}catch(n){return T(n,e)}});b.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],w("header",g),async e=>{let{req:t}=e;try{let n=await C(e);if(n instanceof Response)return n;let o=`${t.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=t.param("transactionId"),i=await n[o](s,D(e));return e.json(i)}catch(n){return T(n,e)}});b.put("/schema",w("header",g),async e=>{let{req:t}=e,n=await t.text();if(!n)return e.text("Missing schema",400);let r=t.param("schemaHash"),o=R.get(r);if(o==null){if(r!==await O(n))return e.text("Schema hash mismatch",400);let s=new URL(e.get("db").connectionString);s.searchParams.set("single_use_connections","true");let i=await W(n,s);return R.set(r,{base64Original:n,...i}),e.text(r)}return n!==o.base64Original?e.text("Schema mismatch",400):e.text(r)});b.post("/transaction/start",w("header",g),async e=>{let{req:t}=e,n=await oe(e);if(n instanceof Response)return n;try{let r=await C(e);if(r instanceof Response)return r;let o=await r.startTransaction(n,D(e)),s=se(o,e);if(s instanceof Response)return s;let{id:i}=s,a=t.param("clientVersion"),c=e.get("port"),l=e.get("protocol"),m=t.param("schemaHash");return e.json({...o,"data-proxy":{endpoint:`${l}://localhost:${c}/${a}/${m}/itx/${i}`}})}catch(r){return T(r,e)}});async function C(e){let{req:t}=e,n=X(e);if(n instanceof Response)return n;let{base64Override:r,overrideHash:o}=n.schemas;return await h.get({base64Schema:r,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||t.param("clientVersion"),debug:e.get("debug"),platform:e.get("platform"),schemaHash:o})}import{Hono as We}from"hono/tiny";import{StatusCodes as Ze}from"http-status-codes";var A=new We;A.post("/database/dump",async e=>{let n=await e.get("db").dump();return e.json(n,Ze.CREATED)});A.get("/health",e=>e.json({name:e.get("serverState").name}));async function ce(e,t){let{port:n}=t;if(t.dryRun)return ie(n,null);let r=await st(n,e,t),{promise:o,reject:s,resolve:i}=E(),a=nt({createServer:et,fetch:r.fetch,overrideGlobalObjects:!1,port:n},i);return a.on("error",c=>{if(typeof c=="object"&&"code"in c&&c.code==="EADDRINUSE")return s(new v(n,"server"));console.error("[Accelerate]",c)}),await o,ie(n,a)}function ie(e,t){return{async close(){t&&await Promise.allSettled([tt(t.close.bind(t))(),h.stopAll()])},port:e,url:`http://localhost:${e}`}}async function st(e,t,n){let{debug:r}=n,o=new ae,s=await rt.getPlatformInfo();return r&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),r&&o.use("*",ot((...i)=>console.log("[Accelerate]",...i))),o.use("*",async(i,a)=>(i.set("db",t),i.set("debug",!!r),i.set("platform",s),i.set("port",e),i.set("protocol","http"),i.set("serverState",n),await a())),o.route("/",B),o}var B=new ae;B.route("/",S);B.route("/",A);async function pn(e){let t=await U.create(e),[n,r]=await Promise.all([I("database",t),I("shadow_database",t)]),o=await ce(n,t),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:K({databaseUrl:n.connectionString,shadowDatabaseUrl:r.connectionString})}).toString()}`,i={database:{connectionString:n.connectionString},http:{url:o.url},ppg:{url:s},shadowDatabase:{connectionString:r.connectionString}};return await t.writeServerDump(i),{...i,close:()=>a(t,[o,n,r])};async function a(c,l){let p=(await Promise.allSettled(l.map(u=>u.close()))).filter(u=>u.status==="rejected").map(u=>new Error(u.reason));try{await c.close()}catch(u){p.push(u)}if(p.length>0)throw new AggregateError(p,"Failed to close some servers")}}export{it as DEFAULT_DATABASE_PORT,at as DEFAULT_SERVER_PORT,ct as DEFAULT_SHADOW_DATABASE_PORT,v as PortNotAvailableError,pn as unstable_startServer};
|