first commit

This commit is contained in:
Ichitux
2026-04-05 03:08:53 +02:00
commit 1082d36c12
28015 changed files with 3767672 additions and 0 deletions
+11
View File
@@ -0,0 +1,11 @@
import{b as a,d as R,e as h}from"./chunk-TF5C7XJX.js";import"./chunk-DWY47FQV.js";import{HTTPException as bn}from"hono/http-exception";import{Hono as En}from"hono/tiny";import{validator as u}from"hono/validator";import{array as Y,literal as Z,minLength as K,object as J,pipe as nn,safeParse as en,string as tn,union as rn}from"valibot";var on=J({tags:rn([nn(Y(tn()),K(1)),Z("all")])});async function L(n){let{output:r,success:e}=en(on,await n.req.json(),{abortEarly:!0});return e?r:n.text("Invalid input",400)}import{parseDuration as T,parseSize as sn,Server as an}from"@prisma/query-plan-executor";import{version as w}from"@prisma/query-plan-executor";var I;async function q(n){return I===void 0&&(I=await an.create({databaseUrl:n.get("db").connectionString,maxResponseSize:sn("128 MiB"),queryTimeout:T("PT5M"),maxTransactionTimeout:T("PT5M"),maxTransactionWaitTime:T("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:n.get("debug")?"debug":"off"}})),I}import{Buffer as B}from"buffer";var S=new Map;async function b(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}function M(n){let r=n.req.param("schemaHash"),e=S.get(r);return e==null?n.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:r,schemas:e}}async function j(n,r,e){let t=B.from(n,"base64").toString("utf8"),o=un(t,r.toString());e&&console.log("[Accelerate] schema with override:",o);let i=await b(o);return{base64Override:B.from(o,"utf8").toString("base64"),overrideHash:i}}var cn=" ";function un(n,r){let e=fn(n);if(!e)throw new Error("No datasource block found in schema.");let t=n.slice(e.openBraceIndex+1,e.closeBraceIndex),o=pn(t,r,hn(n,e.openBraceIndex));return`${n.slice(0,e.openBraceIndex+1)}${o}${n.slice(e.closeBraceIndex)}`}function fn(n){let r="datasource";for(let e=0;e<n.length;e+=1){let t=n[e];if(t==="/"&&n[e+1]==="/"){e=E(n,e+2);continue}if(t==="/"&&n[e+1]==="*"){e=C(n,e+2);continue}if(t==='"'){e=H(n,e+1);continue}if(n.startsWith(r,e)&&!_(n[e-1])&&!_(n[e+r.length])){let o=ln(n,e+r.length,"{");if(o===-1)return null;let i=mn(n,o);return i===-1?null:{closeBraceIndex:i,openBraceIndex:o}}}return null}function ln(n,r,e){for(let t=r;t<n.length;t+=1){let o=n[t];if(o==="/"&&n[t+1]==="/"){t=E(n,t+2);continue}if(o==="/"&&n[t+1]==="*"){t=C(n,t+2);continue}if(o==='"'){t=H(n,t+1);continue}if(o===e)return t}return-1}function mn(n,r){let e=0;for(let t=r;t<n.length;t+=1){let o=n[t];if(o==="/"&&n[t+1]==="/"){t=E(n,t+2);continue}if(o==="/"&&n[t+1]==="*"){t=C(n,t+2);continue}if(o==='"'){t=H(n,t+1);continue}if(o==="{"){e+=1;continue}if(o==="}"&&(e-=1,e===0))return t}return-1}function E(n,r){let e=r;for(;e<n.length&&n[e]!==`
`;)e+=1;return e}function C(n,r){let e=n.indexOf("*/",r);return e===-1?n.length:e+1}function H(n,r){let e=r;for(;e<n.length;){if(n[e]==="\\"){e+=2;continue}if(n[e]==='"')return e;e+=1}return n.length}function _(n){return n!=null&&/[A-Za-z0-9_]/.test(n)}function pn(n,r,e){let t=`"${yn(r)}"`,o=dn(n);for(let[d,A]of o.entries()){let{comment:X,code:G}=V(A.line),g=G.match(/^(\s*)url(\s*)=(\s*).*/);if(g)return o[d]={line:`${g[1]}url${g[2]}=${g[3]}${t}${X}`,terminator:A.terminator},P(o)}let i=Sn(n),s=gn(o,e),c=`${s}url = ${t}`;if(!n.includes(`
`)&&!n.includes("\r")){let d=n.trim();return d.length===0?`${i}${c}${i}${e}`:`${i}${s}${d}${i}${c}${i}${e}`}let f=o.at(-1);if(f&&f.terminator===""&&/^\s*$/.test(f.line))return`${P(o.slice(0,-1))}${c}${i}${e}`;let $=P(o),Q=$.endsWith(`
`)||$.endsWith("\r")?"":i;return`${$}${Q}${c}${i}${e}`}function dn(n){let r=[],e=0;for(let t=0;t<n.length;t+=1){if(n[t]==="\r"&&n[t+1]===`
`){r.push({line:n.slice(e,t),terminator:`\r
`}),t+=1,e=t+1;continue}(n[t]===`
`||n[t]==="\r")&&(r.push({line:n.slice(e,t),terminator:n[t]}),e=t+1)}return(e<n.length||n.length===0)&&r.push({line:n.slice(e),terminator:""}),r}function P(n){return n.map(r=>`${r.line}${r.terminator}`).join("")}function V(n){let r=!1,e=!1;for(let t=0;t<n.length;t+=1){let o=n[t];if(e){if(r){r=!1;continue}if(o==="\\"){r=!0;continue}o==='"'&&(e=!1);continue}if(o==='"'){e=!0;continue}if(o==="/"&&n[t+1]==="/")return{code:n.slice(0,t),comment:n.slice(t)}}return{code:n,comment:""}}function gn(n,r){for(let e of n){let{code:t}=V(e.line),o=t.match(/^([ \t]+)[A-Za-z_][A-Za-z0-9_]*\s*=/);if(o?.[1])return o[1]}return`${r}${cn}`}function hn(n,r){let e=n.lastIndexOf(`
`,r)+1,t=e;for(;n[t]===" "||n[t]===" ";)t+=1;return n.slice(e,t)}function Sn(n){return n.includes(`\r
`)?`\r
`:`
`}function yn(n){return n.replaceAll("\\","\\\\").replaceAll('"','\\"')}function y(n){let{req:r}=n;return{traceparent:r.header("traceparent"),"X-capture-telemetry":r.header("X-capture-telemetry")}}import{integer as D,looseObject as xn,minValue as N,number as O,object as $n,optional as Tn,pipe as U,safeParse as k,string as z,union as In}from"valibot";var wn=$n({isolation_level:Tn(z()),max_wait:U(O(),D(),N(0)),timeout:U(O(),D(),N(0))});async function F(n){let{issues:r,output:e,success:t}=k(wn,await n.req.json(),{abortEarly:!0});return t?e:n.json({EngineNotStarted:{reason:"InvalidRequest",issues:r}},400)}var Pn=xn({id:In([z(),O()])});function W(n,r){let{output:e,success:t}=k(Pn,n);return t?e:r.json({EngineMalfunction:{}},500)}var x=new En;x.post("/invalidate",u("header",a),async n=>{let r=await L(n);return r instanceof Response?r:n.body(null)});var Cn="/:clientVersion/:schemaHash",p=x.basePath(Cn);x.route("/",p);var Hn=["/graphql","/itx/:transactionId/graphql"];p.on("POST",[...Hn],u("header",a),async n=>{let{req:r}=n;try{let e=await v(n);if(e instanceof Response)return e;let t=await r.text(),o=r.param("transactionId"),i=await e.request(t,{...y(n),"X-transaction-id":o});return n.text(i)}catch(e){return h(e,n)}});p.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],u("header",a),async n=>{let{req:r}=n;try{let e=await v(n);if(e instanceof Response)return e;let o=`${r.routePath.split("/").filter(Boolean).at(-1)}Transaction`,i=r.param("transactionId"),s=await e[o](i,y(n));return n.json(s)}catch(e){return h(e,n)}});p.put("/schema",u("header",a),async n=>{let{req:r}=n,e=await r.text();if(!e)return n.text("Missing schema",400);let t=r.param("schemaHash"),o=S.get(t);if(o==null){if(t!==await b(e))return n.text("Schema hash mismatch",400);let i=await j(e,n.get("db").prismaORMConnectionString,n.get("debug"));return S.set(t,{base64Original:e,...i}),n.text(t)}return e!==o.base64Original?n.text("Schema mismatch",400):n.text(t)});p.post("/transaction/start",u("header",a),async n=>{let{req:r}=n,e=await F(n);if(e instanceof Response)return e;try{let t=await v(n);if(t instanceof Response)return t;let o=await t.startTransaction(e,y(n)),i=W(o,n);if(i instanceof Response)return i;let{id:s}=i,c=r.param("clientVersion"),f=r.param("schemaHash");return n.json({...o,"data-proxy":{endpoint:`${new URL(r.url).origin}/${c}/${f}/itx/${s}`}})}catch(t){return h(t,n)}});async function v(n){let{req:r}=n,e=M(n);if(e instanceof Response)return e;let{base64Override:t,overrideHash:o}=e.schemas;return await R.get({base64Schema:t,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||r.param("clientVersion"),debug:n.get("debug"),platform:n.get("platform"),schemaHash:o})}var On=[["/connection-info","GET"],["/query","POST"],["/transaction/start","POST"],["/transaction/:transactionId/commit","POST"],["/transaction/:transactionId/query","POST"],["/transaction/:transactionId/rollback","POST"]];for(let[n,r]of On)x.on(r,n,u("header",a),async e=>{let t=e.req.header("prisma-engine-hash");if(t!=="0.0.0"&&t!==w)throw new bn(400,{message:`Using an HTTP connection string is not supported with Prisma Client version ${t} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${w}.`});return await(await q(e)).fetch(e.req.raw)});export{x as accelerateRoute};
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
import{existsSync as d,readFileSync as L}from"fs";import{copyFile as p,mkdir as _,readFile as c}from"fs/promises";import{createRequire as S}from"module";import{dirname as B}from"path";import{fileURLToPath as i,pathToFileURL as y}from"url";var z=S(import.meta.url),E=["initdb.wasm","pglite.data","pglite.wasm"],b={amcheck:"amcheck.tar.gz",bloom:"bloom.tar.gz",btree_gin:"btree_gin.tar.gz",btree_gist:"btree_gist.tar.gz",citext:"citext.tar.gz",cube:"cube.tar.gz",dict_int:"dict_int.tar.gz",dict_xsyn:"dict_xsyn.tar.gz",earthdistance:"earthdistance.tar.gz",file_fdw:"file_fdw.tar.gz",fuzzystrmatch:"fuzzystrmatch.tar.gz",hstore:"hstore.tar.gz",intarray:"intarray.tar.gz",isn:"isn.tar.gz",lo:"lo.tar.gz",ltree:"ltree.tar.gz",pageinspect:"pageinspect.tar.gz",pg_buffercache:"pg_buffercache.tar.gz",pg_freespacemap:"pg_freespacemap.tar.gz",pg_surgery:"pg_surgery.tar.gz",pg_trgm:"pg_trgm.tar.gz",pg_visibility:"pg_visibility.tar.gz",pg_walinspect:"pg_walinspect.tar.gz",seg:"seg.tar.gz",tablefunc:"tablefunc.tar.gz",tcn:"tcn.tar.gz",tsm_system_rows:"tsm_system_rows.tar.gz",tsm_system_time:"tsm_system_time.tar.gz",unaccent:"unaccent.tar.gz",uuid_ossp:"uuid-ossp.tar.gz",vector:"vector.tar.gz"},w=[...E.map(e=>({fileName:e,kind:"core",name:e})),...Object.entries(b).map(([e,t])=>({fileName:t,kind:"extension",name:e}))],l=new Map,A=Symbol.for("@prisma/dev/bundled-pglite-runtime-asset-sources"),a=null;async function Y(e){let t=u(e),n=i(t);await _(n,{recursive:!0});let s=[];for(let r of v()){let m=new URL(r.fileName,t),f=i(m);await p(r.sourcePath,f),s.push({...r,destinationPath:f})}return s}function v(){let e=P();return w.map(t=>({...t,sourcePath:i(new URL(t.fileName,e))}))}async function K(){await N();let e=U();if(e)return await G(e),await x(e);let t=M(),n=t.href,s=l.get(n);return s||(s=D(t),l.set(n,s)),await s}function X(e){let t=globalThis;t[A]={extensions:Object.fromEntries(Object.entries(e.extensions).map(([n,s])=>[n,o(s)])),fsBundle:o(e.fsBundle),initdbWasm:o(e.initdbWasm),wasmModule:o(e.wasmModule)}}function o(e,t=import.meta.url){return e instanceof URL?e:/^(?:https?:|data:|file:)/.test(e)?new URL(e):e.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(e)?y(e):new URL(e,t)}async function x(e){let t=`bundled:${e.wasmModule.href}:${e.fsBundle.href}`,n=l.get(t);return n||(n=T(e),l.set(t,n)),await n}async function D(e){let[t,n]=await Promise.all([c(new URL("pglite.data",e)),c(new URL("pglite.wasm",e))]),s=h();return{extensions:Object.fromEntries(Object.entries(b).map(([r,m])=>[r,new URL(m,e)])),fsBundle:new Blob([Uint8Array.from(t)]),wasmModule:await s.compile(n)}}async function T(e){let[t,n]=await Promise.all([R(e.fsBundle),R(e.wasmModule)]),s=h();return{extensions:e.extensions,fsBundle:new Blob([Uint8Array.from(t)]),wasmModule:await s.compile(n)}}async function G(e){if(e.initdbWasm.protocol!=="file:")return;let t=new URL("initdb.wasm",u(new URL("./",e.initdbWasm))),n=i(t);d(n)||await p(i(e.initdbWasm),n)}function u(e){return e instanceof URL?g(e):g(y(e))}function g(e){return e.href.endsWith("/")?e:new URL(`${e.href}/`)}function P(){let e=z.resolve("@electric-sql/pglite");return u(B(e))}function M(){let e=u(new URL("./",import.meta.url));if(k(e))return e;if(I())return P();throw new Error("Unable to locate PGlite runtime assets. If you bundled @prisma/dev, copy them next to the bundle with copyPrismaDevRuntimeAssets().")}function k(e){return w.every(t=>d(i(new URL(t.fileName,e))))}function U(){return globalThis[A]??null}async function N(){!O()||U()||(a||(a=import("./runtime-assets-manifest.bun.js").then(()=>{}).catch(e=>{throw a=null,e})),await a)}function I(){let e=i(new URL("../package.json",import.meta.url));if(!d(e))return!1;try{return JSON.parse(L(e,"utf8")).name==="@prisma/dev"}catch{return!1}}function O(){return typeof globalThis.Bun<"u"}function h(){let e=globalThis.WebAssembly;if(!e)throw new Error("WebAssembly is not available in this runtime.");return e}async function R(e){if(e.protocol==="file:")return await c(e);let t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch runtime asset ${e.href}: ${t.status} ${t.statusText}`);return new Uint8Array(await t.arrayBuffer())}export{Y as a,v as b,K as c,X as d,o as e};
+3
View File
@@ -0,0 +1,3 @@
import{d as f,e as P,f as M}from"./chunk-X3G665AK.js";import{a as A,c,g as V,h as C,i as L,j as x}from"./chunk-DWY47FQV.js";import{writeFile as ae}from"fs/promises";import{join as m}from"pathe";import{check as se,lock as oe,unlock as ie}from"proper-lockfile";import{process as B}from"std-env";import{integer as G,literal as ne,minLength as k,minValue as K,number as Z,object as b,optional as h,parseJson as ue,pipe as l,safeParse as de,string as p,url as le}from"valibot";import{setTimeout as ee}from"timers/promises";import{process as D}from"std-env";function _(r,e){if(r==null)return!1;try{return D.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}async function j(r,e){if(!D.kill)return!1;try{D.kill(r,"SIGTERM")}catch(a){return e&&console.error(`Error killing process with PID ${r}:`,a),!1}let t=0;do{if(!_(r,e))return!0;await ee(100)}while(++t<50);try{return D.kill(r,"SIGKILL")}catch(a){return e&&console.error(`Error forcefully killing process with PID ${r}:`,a),!1}}import{join as q}from"pathe";var te="prisma-wal";function re(){return q(A.data,"durable-streams")}function F(r){return q(re(),r)}function xe(r,e=te){return new URL(`/v1/stream/${encodeURIComponent(e)}`,r).toString()}var S=l(p(),le()),H=b({connectionString:S,prismaORMConnectionString:h(S),terminalCommand:h(p())}),Y=b({url:S}),ce=b({serverUrl:S,sqlitePath:l(p(),k(1)),streamName:l(p(),k(1)),url:S}),me=b({streams:h(ce)}),E=l(Z(),G(),K(1)),he=b({database:H,http:Y,ppg:Y,shadowDatabase:H}),pe=b({databasePort:E,experimental:h(me),exports:h(he),name:l(p(),k(1)),pid:h(l(Z(),G(),K(0))),port:E,shadowDatabasePort:E,version:ne("1")}),O=Symbol("initialize"),I="default",be=new Set(["durable-streams"]),u=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;_streamsPort;constructor(e){this._databasePort=e.databasePort??P,this.databaseConnectTimeoutMillis=e.databaseConnectTimeoutMillis??6e4,this.databaseIdleTimeoutMillis=e.databaseIdleTimeoutMillis??1/0,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??I,this.persistenceMode=e.persistenceMode,this.pid=e.pid??B.pid,this.shadowDatabaseConnectTimeoutMillis=e.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=e.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=e.port??P,this._shadowDatabasePort=e.shadowDatabasePort??P,this._streamsPort=P}static async createExclusively(e){let t=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new g(e):new $(e);return await t[O](),t}static async fromServerDump(e){let{debug:t,name:a=I}=e??{},o=c(a),i=g.getServerDumpPath(o),s=await V(i);if(s==null)return t&&console.debug(`[State] No server dump file found at: ${i}`),null;t&&(console.debug(`[State] server dump file found at "${i}":`),console.debug(s));let{issues:n,output:d,success:v}=de(l(p(),ue(),pe),s);if(!v)throw t&&console.debug(`[State] Invalid server dump file at "${i}":
${JSON.stringify(n,null,2)}`),new Error(`Invalid Prisma Dev state for "${a}".`);return new g({databasePort:d.databasePort,debug:t,dryRun:!1,name:a,pid:d.pid,port:d.port,serverDump:d,shadowDatabasePort:d.shadowDatabasePort})}static async scan(e){let{debug:t,globs:a}=e??{},o=m(c(I),"..");t&&console.debug(`[State] scanning for server states in: ${o}`);let i=(await L(o,a)).filter(s=>!be.has(s));return t&&console.debug(`[State] found server names: ${JSON.stringify(i)}`),await Promise.all(i.map(s=>z(s,e)))}get databasePort(){return this._databasePort}set databasePort(e){this.#t("databasePort",e)}get port(){return this._port}set port(e){this.#t("port",e)}get shadowDatabasePort(){return this._shadowDatabasePort}get streamsPort(){return this._streamsPort}set shadowDatabasePort(e){this.#t("shadowDatabasePort",e)}#t(e,t){if(t<0||!Number.isInteger(t))throw new Error(`Invalid port number: ${t}`);let a=`_${e}`;if(this[a]!==f&&this[a]!==t)throw new Error(`\`${e}\` is already set to ${this[a]}, cannot change it to ${t}`);this[a]=t}},$=class extends u{constructor(e){super({...e,databasePort:e?.databasePort||f,persistenceMode:"stateless",port:e?.port||f,shadowDatabasePort:e?.shadowDatabasePort||f})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[O](){let e;try{e=await u.scan({debug:this.debug,onlyMetadata:!0})}catch(a){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",a),e=[]}let t=await M({debug:this.debug,name:this.dryRun?this.name:"",requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:e});this._databasePort=t.databasePort,this._port=t.port,this._shadowDatabasePort=t.shadowDatabasePort,this._streamsPort=t.streamsPort}async close(){}async writeServerDump(){}},g=class r extends u{#t;#e;#a;#o;#i;#s;#r;constructor(e){super({...e,persistenceMode:"stateful"}),this.#s=!1,this.#e=c(this.name),this.#t=m(this.#e,"db_dump.bak"),this.#a=m(this.#e,".lock"),this.#o=m(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#i=r.getServerDumpPath(this.#e)}static getServerDumpPath(e){return m(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get experimental(){return this.#r?.experimental}get pgliteDataDirPath(){return this.#o}async[O](){await C(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await oe(this.#e,{lockfilePath:this.#a}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await u.scan({debug:this.debug,onlyMetadata:!0}),t=await M({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:e});this._databasePort=t.databasePort,this._port=t.port,this._shadowDatabasePort=t.shadowDatabasePort,this._streamsPort=t.streamsPort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new T(this):e}}async close(){if(!this.#s)try{await ie(this.#e,{lockfilePath:this.#a}),this.#s=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,e),e}}async writeServerDump(e,t){this.#r={name:this.name,version:"1",pid:B.pid,port:this.port,databasePort:this.databasePort,experimental:t,shadowDatabasePort:this.shadowDatabasePort,exports:e},await ae(this.#i,`${JSON.stringify(this.#r,null,2)}
`,{encoding:"utf-8"})}};async function Ve(r,e){await Pe(r,e);let t=typeof r=="string"?r:r.name,a=c(t);await x(a),await x(F(t))}async function z(r,e){let{debug:t,onlyMetadata:a}=e||{},o=typeof r=="string"?r:r.name,i=typeof r!="string"?r:void 0,s={databasePort:i?.databasePort??-1,experimental:i?.experimental,exports:i?.exports,name:o,pid:i?.pid,port:i?.port??-1,shadowDatabasePort:i?.shadowDatabasePort??-1,version:"1"};try{let n=i||await u.fromServerDump({debug:t,name:o});if(!n)return t&&console.debug(`[State] no server state found for name: ${o}`),{...s,status:"no_such_server"};s.databasePort=n.databasePort,s.experimental=n.experimental,s.exports=n.exports,s.pid=n.pid,s.port=n.port,s.shadowDatabasePort=n.shadowDatabasePort;let{exports:d,pid:v}=n;if(a)return{...s,status:"unknown"};if(!_(v,t))return t&&console.debug(`[State] server state for "${o}" has no running process with PID: ${v}`),{...s,status:"not_running"};let N=c(o);try{if(!await se(N,{lockfilePath:m(N,".lock")}))return t&&console.debug(`[State] server state for "${o}" is not locked, indicating it is not running.`),{...s,status:"not_running"}}catch(Q){t&&console.error(`[State] server state for "${o}" failed to check lock:`,Q)}if(!d)return{...s,status:"starting_up"};let{http:W}=d,{hc:X}=await import("hono/client"),w=await X(W.url).health.$get();if(!w.ok)return t&&console.debug(`[State] server state for "${o}" is not live: ${JSON.stringify(w)}`),{...s,status:"not_running"};let y=await w.json();return y.name!==r?(t&&console.debug(`[State] server state for "${o}" has mismatched health response: ${JSON.stringify(y)}`),{...s,status:"unknown"}):(t&&console.debug(`[State] server state for "${r}" is live: ${JSON.stringify(y)}`),{...s,status:"running"})}catch(n){return t&&console.error(`[State] failed to get server status for "${o}":`,n),{...s,status:"error"}}}function fe(r){let{status:e}=r;return e==="running"||e==="starting_up"}async function Pe(r,e){let{pid:t,...a}=typeof r=="string"?await z(r,{debug:e}):r;if(!fe(a))return!1;let o=await u.fromServerDump({debug:e,name:a.name});if(t==null){e&&console.debug(`[State] No PID found for server "${a.name}" to kill.`);try{await o?.close()}catch{}return!1}let i=await j(t,e);try{await o?.close()}catch{}return i}var R=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},T=class extends R{#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{te as a,re as b,F as c,xe as d,u as e,Ve as f,z as g,fe as h,Pe as i,R as j,T as k};
+1
View File
@@ -0,0 +1 @@
import{createWriteStream as w,WriteStream as A}from"fs";import{access as D,chmod as x,constants as P,mkdir as T,readdir as E,readFile as _,rm as F,writeFile as O}from"fs/promises";import{promisify as v}from"util";import{unzip as C}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=t=>{let r=o.join(n,"Library");return{data:o.join(r,"Application Support",t),config:o.join(r,"Preferences",t),cache:o.join(r,"Caches",t),log:o.join(r,"Logs",t),temp:o.join(a,t)}},y=t=>{let r=e.APPDATA||o.join(n,"AppData","Roaming"),i=e.LOCALAPPDATA||o.join(n,"AppData","Local");return{data:o.join(i,t,"Data"),config:o.join(r,t,"Config"),cache:o.join(i,t,"Cache"),log:o.join(i,t,"Log"),temp:o.join(a,t)}},j=t=>{let r=o.basename(n);return{data:o.join(e.XDG_DATA_HOME||o.join(n,".local","share"),t),config:o.join(e.XDG_CONFIG_HOME||o.join(n,".config"),t),cache:o.join(e.XDG_CACHE_HOME||o.join(n,".cache"),t),log:o.join(e.XDG_STATE_HOME||o.join(n,".local","state"),t),temp:o.join(a,r,t)}};function p(t,{suffix:r="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return r&&(t+=`-${r}`),c.platform==="darwin"?h(t):c.platform==="win32"?y(t):j(t)}import L from"zeptomatch";var l=p("prisma-dev"),G=v(C);function z(t,r){return`${l.cache}/engine/${t}/${r}`}function B(t){return`${l.data}/${t}`}async function J(t){try{return await D(t,P.F_OK),!0}catch(r){if(u(r))return!1;throw r}}async function K(t,r){let i=await G(t);await O(r,i),await x(r,"755")}async function q(t,r){await t.stream().pipeTo(A.toWeb(w(r,{encoding:"utf8"})))}function u(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function Q(t){try{return await _(t,{encoding:"utf-8"})}catch(r){if(u(r))return null;throw r}}async function U(t){await T(t,{recursive:!0})}async function V(t,r){try{return(await E(t,{withFileTypes:!0})).reduce((f,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!r||L(r,s.name))&&f.push(s.name),f),[])}catch(i){if(u(i))return[];throw i}}async function Y(t){await F(t,{force:!0,recursive:!0})}export{l as a,z as b,B as c,J as d,K as e,q as f,Q as g,U as h,V as i,Y as j};
+3
View File
@@ -0,0 +1,3 @@
import{b as P,d as b,e as v}from"./chunk-DWY47FQV.js";import{minLength as B,object as j,optional as K,parseJson as L,pipe as y,regex as R,safeParse as _,string as w,url as A}from"valibot";var S=/^(postgres|postgresql):\/\//,N=y(w(),L(),j({databaseUrl:y(w(),A(),R(S)),name:K(y(w(),B(1))),shadowDatabaseUrl:y(w(),A(),R(S))}));function Y(r){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(r).sort(([[e],[n]])=>e.localeCompare(n)))),"utf8").toString("base64url")}function Q(r){let e=Buffer.from(r,"base64url").toString("utf8"),{issues:n,output:s,success:t}=_(N,e,{abortEarly:!0});return t?[null,s]:[n]}var X=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,m]=Q(o);if(a)throw new s(401,{message:"Invalid API Key",cause:a.join(", ")});let{databaseUrl:h,name:c,shadowDatabaseUrl:d}=m,l=e.get("name"),g=new URL(e.req.url).port;if(!c)throw new s(401,{message:`Wrong API Key; The Prisma Dev server running at port ${g} requires an API Key from a newer version of \`prisma dev\`. Check the "${l}" server's output for the updated \`DATABASE_URL\` value.`});if(c!==l)throw new s(401,{message:`Wrong API Key; The Prisma Dev server running at port ${g} is named "${l}", but the API Key is for "${c}"`});let{hostname:f,port:E}=new URL(h),{port:$}=e.get("db"),{hostname:C,port:D}=new URL(d),H=e.get("shadowDBPort");if(f!=="localhost"||Number(E)!==$||C!=="localhost"||Number(D)!==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:m}};import{spawn as U}from"child_process";import{once as F}from"events";import{mkdir as V}from"fs/promises";import{join as q}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:J,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:G,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=G||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=U(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 d=c.split(`
`).find(E=>E.includes("Started query engine http server"));if(!d)return;i.stdout.removeListener("data",a);let{fields:l}=JSON.parse(d);if(l==null)return n(new Error(`Unexpected data during initialization, "fields" are missing: ${c}`));let{ip:g,port:f}=l;if(g==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.
Received data: ${c}`));s({childProcess:i,url:`http://${g}:${f}`})},m=c=>{this.#n=null,n(new p(String(c))),i.removeListener("exit",h),i.kill()};i.once("error",m);let h=(c,d)=>{this.#n=null,n(new p(`Query Engine exited with code ${c} and signal ${d}`))};return i.once("exit",h),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 V(n,{recursive:!0});let{binaryTarget:s}=this.#e.platform,t=s==="windows"?".exe":"",o=q(n,`query-engine-${s}${t}`);return this.#e.debug&&console.debug("[Query Engine] binary path",o),(J==="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 ue(r,e){return console.error(r),r instanceof p?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:r.message}}}},500):r instanceof u?e.text(r.responseBody,r.statusCode):e.body(null,500)}var p=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{Y as a,X as b,O as c,x as d,ue as e};
+1
View File
@@ -0,0 +1 @@
import{checkPort as O,getPort as v,isUnsafePort as $}from"get-port-please";import{difference as x,range as k}from"remeda";var S=51214,g=51213,w=51215,T=51216,b=65535,R=0,d=-1/0;async function j(o){let{debug:r,name:e,requestedPorts:n,servers:u}=o,{portsUsedByOtherServers:t,portsUsedByThisServerLastTime:a}=_(e,u);r&&(console.debug(`ports used by other servers: ${Object.keys(t).join(", ")}`),console.debug(`ports used by "${e}" server last time: ${JSON.stringify(a)}`));let i={databasePort:d,port:d,shadowDatabasePort:d,streamsPort:d},s=["port","databasePort","shadowDatabasePort","streamsPort"];for(let c of s){let P=await A({debug:r,portKey:c,portsUsedByOtherServers:t,portsUsedByThisServerLastTime:a,requestedPorts:n})??await B({debug:r,pickedPorts:i,portKey:c,portsUsedByOtherServers:t,portsUsedByThisServerLastTime:a});r&&console.debug(`Got port for "${c}": ${P}`),i[c]=P}return r&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function A(o){let{debug:r,portKey:e,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:u,requestedPorts:t}=o,{[e]:a,...i}=t;if(m(a))return await E({debug:r,otherRequestedPorts:i,portKey:e,portsUsedByOtherServers:n,requestedPort:a}),a;let s=u?.[e]??d;if(!m(s))return r&&console.debug(`No port specified for "${e}". Trying to pick a new port.`),null;let c=s in n;return c||Object.values(i).includes(s)?(r&&console.debug(`Port ${s} that was used last time for this server, ${c?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await O(s)===!1?(r&&console.debug(`Port ${s}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(r&&console.debug(`Using port ${s} for "${e}" as it was used last time and is available.`),s)}async function B(o){let{debug:r,pickedPorts:e,portKey:n,portsUsedByOtherServers:u,portsUsedByThisServerLastTime:t}=o,a=Math.max(S,g,w,T)+1,i=Object.values(e).filter(p=>p!==void 0),s=t?D(t):[],c=[...i,...Object.keys(u).map(Number),...s],P=Math.min(Math.max(a,...c)+100,b),U=x(k(a,P),c),f={port:g,databasePort:S,shadowDatabasePort:w,streamsPort:T}[n];try{return await v({port:f in u||i.includes(f)||s.includes(f)?void 0:f,ports:U})}catch(p){if(p instanceof Error&&p.name==="GetPortError"&&P+1<=b)return r&&console.debug(`Expanding port lookup to range [${P+1}, ${b}].`),await v({portRange:[P+1,b]});throw p}}function m(o){return Number.isFinite(o)&&o>=0}function _(o,r){let e={},n;for(let u of r){let{databasePort:t,port:a,shadowDatabasePort:i}=u,s=q(u);if(u.name===o){n={databasePort:t,port:a,shadowDatabasePort:i,streamsPort:s};continue}e[t]=!0,e[a]=!0,e[i]=!0,m(s)&&(e[s]=!0)}return{portsUsedByOtherServers:e,portsUsedByThisServerLastTime:n}}function q(o){let r=o.experimental?.streams?.serverUrl;if(!r)return d;try{let e=Number(new URL(r).port);return Number.isInteger(e)&&e>0?e:d}catch{return d}}function D(o){return[o.port,o.databasePort,o.shadowDatabasePort,o.streamsPort]}async function E(o){let{debug:r,otherRequestedPorts:e,portKey:n,portsUsedByOtherServers:u,requestedPort:t}=o;if(t!==R){if(t in u)throw r&&console.error(`Port ${t} was requested for "${n}", but is already used by another server.`),new h(t);if(Object.values(e).includes(t))throw r&&console.error(`Port ${t} was requested for "${n}", but also for another key.`),new y(t);if($(t))throw r&&console.error(`Port ${t} was requested for "${n}", but is unsafe.`),new l(t);if(await O(t)===!1)throw r&&console.error(`Port ${t} was requested for "${n}", but is not available.`),new l(t)}}var l=class extends Error{constructor(e){super(`Port \`${e}\` is not available.`);this.port=e}name="PortNotAvailableError"},y=class extends Error{constructor(e){super(`Port number \`${e}\` was requested twice. Please choose a different port for each service.`);this.port=e}name="PortRequestedTwiceError"},h=class extends Error{constructor(e){super(`Port number \`${e}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=e}name="PortBelongsToAnotherServerError"};export{S as a,g as b,w as c,R as d,d as e,j as f,l as g};
+100
View File
File diff suppressed because one or more lines are too long
+114
View File
File diff suppressed because one or more lines are too long
+23
View File
@@ -0,0 +1,23 @@
import { ReadonlyServer } from './index.cjs';
import { E as ExperimentalStreams } from './state-DTMxyzXf.cjs';
import './db.cjs';
import '@electric-sql/pglite';
import './runtime-assets.cjs';
import 'valibot';
type DaemonServer = Omit<ReadonlyServer, "experimental"> & {
experimental?: {
streams?: ExperimentalStreams;
};
};
interface DaemonMessageStarted {
type: "started";
server: DaemonServer;
}
interface DaemonMessageError {
type: "error";
error: string;
}
type DaemonMessage = DaemonMessageStarted | DaemonMessageError;
export type { DaemonMessage, DaemonMessageError, DaemonMessageStarted };
+23
View File
@@ -0,0 +1,23 @@
import { ReadonlyServer } from './index.js';
import { E as ExperimentalStreams } from './state-DTMxyzXf.js';
import './db.js';
import '@electric-sql/pglite';
import './runtime-assets.js';
import 'valibot';
type DaemonServer = Omit<ReadonlyServer, "experimental"> & {
experimental?: {
streams?: ExperimentalStreams;
};
};
interface DaemonMessageStarted {
type: "started";
server: DaemonServer;
}
interface DaemonMessageError {
type: "error";
error: string;
}
type DaemonMessage = DaemonMessageStarted | DaemonMessageError;
export type { DaemonMessage, DaemonMessageError, DaemonMessageStarted };
+1
View File
@@ -0,0 +1 @@
import{a as t}from"./chunk-2O6J3K3T.js";import"./chunk-YL6J3L2T.js";import"./chunk-62DM64XC.js";import"./chunk-CC3P7GPW.js";import"./chunk-X3G665AK.js";import"./chunk-TF5C7XJX.js";import"./chunk-DWY47FQV.js";import{setTimeout as a}from"timers/promises";var e;process.once("SIGTERM",()=>{console.log("SIGTERM received, shutting down..."),process.removeAllListeners("SIGINT"),process.exitCode=143,e?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{console.log("SIGINT received, shutting down..."),process.removeAllListeners("SIGTERM"),process.exitCode=130,e?.close().finally(()=>process.exit())});async function n(){let[,,s]=process.argv;if(!s)return process.send?.({type:"error",error:'Missing "name" argument, server cannot be started'},void 0),process.exit(1);try{e=await t({debug:!0,persistenceMode:"stateful",name:s});let r={database:e.database,experimental:{streams:e.experimental.streams},http:e.http,name:e.name,ppg:e.ppg,shadowDatabase:e.shadowDatabase};process.send?.({type:"started",server:r},void 0)}catch(r){console.error(r);let o=r instanceof Error?r.message:String(r);process.send?.({type:"error",error:o},void 0),await a(1e3),process.exit(1)}}n();
+100
View File
File diff suppressed because one or more lines are too long
+71
View File
@@ -0,0 +1,71 @@
import { PGlite } from '@electric-sql/pglite';
import { c as ServerState } from './state-DTMxyzXf.cjs';
import 'valibot';
interface WalEvent {
oldRecord: Record<string, unknown> | null;
record: Record<string, unknown> | null;
schema: string;
table: string;
txid: string;
type: "delete" | "insert" | "update";
}
interface WalEventBridge {
close(): Promise<void>;
poll(): Promise<void>;
subscribe(callback: WalEventSubscriber): () => void;
}
interface WalEventBridgeOptions {
database?: string;
host?: string;
password?: string;
port?: number;
username?: string;
}
type WalEventSubscriber = (events: WalEvent[]) => void;
type PolledMessage = {
name: string;
text?: string;
};
declare function attachWalEventBridge(db: PGlite, _options?: WalEventBridgeOptions): Promise<WalEventBridge>;
declare function shouldPollWalAfterMessages(messages: PolledMessage[]): boolean;
declare function shouldPollWalAfterResponse(response: Uint8Array): boolean;
interface DBServer {
attachWalEventBridge(): Promise<WalEventBridge>;
close(): Promise<void>;
readonly connectionLimit: number;
readonly connectionString: string;
readonly connectTimeout: number;
readonly database: string;
dump(destinationPath: string): Promise<void>;
readonly maxIdleConnectionLifetime: number;
readonly password: string;
readonly poolTimeout: number;
readonly port: number;
readonly prismaORMConnectionString: string;
getPrimaryKeyColumns(schema: string, table: string): Promise<readonly string[]>;
readonly socketTimeout: number;
readonly sslMode: string;
readonly terminalCommand: string;
readonly username: string;
}
interface DBDump {
dumpPath: string;
}
type DBServerPurpose = "database" | "shadow_database";
declare function startDBServer(purpose: DBServerPurpose, serverState: ServerState): Promise<DBServer>;
type DumpDBOptions<D extends string> = {
dataDir: string;
db?: never;
debug?: boolean;
destinationPath?: D;
} | {
dataDir?: never;
db: PGlite;
debug?: boolean;
destinationPath?: D;
};
declare function dumpDB<D extends string = never>(options: DumpDBOptions<D>): Promise<[D] extends [never] ? string : void>;
export { type DBDump, type DBServer, type DBServerPurpose, type DumpDBOptions, type WalEvent, type WalEventBridge, attachWalEventBridge, dumpDB, shouldPollWalAfterMessages, shouldPollWalAfterResponse, startDBServer };
+71
View File
@@ -0,0 +1,71 @@
import { PGlite } from '@electric-sql/pglite';
import { c as ServerState } from './state-DTMxyzXf.js';
import 'valibot';
interface WalEvent {
oldRecord: Record<string, unknown> | null;
record: Record<string, unknown> | null;
schema: string;
table: string;
txid: string;
type: "delete" | "insert" | "update";
}
interface WalEventBridge {
close(): Promise<void>;
poll(): Promise<void>;
subscribe(callback: WalEventSubscriber): () => void;
}
interface WalEventBridgeOptions {
database?: string;
host?: string;
password?: string;
port?: number;
username?: string;
}
type WalEventSubscriber = (events: WalEvent[]) => void;
type PolledMessage = {
name: string;
text?: string;
};
declare function attachWalEventBridge(db: PGlite, _options?: WalEventBridgeOptions): Promise<WalEventBridge>;
declare function shouldPollWalAfterMessages(messages: PolledMessage[]): boolean;
declare function shouldPollWalAfterResponse(response: Uint8Array): boolean;
interface DBServer {
attachWalEventBridge(): Promise<WalEventBridge>;
close(): Promise<void>;
readonly connectionLimit: number;
readonly connectionString: string;
readonly connectTimeout: number;
readonly database: string;
dump(destinationPath: string): Promise<void>;
readonly maxIdleConnectionLifetime: number;
readonly password: string;
readonly poolTimeout: number;
readonly port: number;
readonly prismaORMConnectionString: string;
getPrimaryKeyColumns(schema: string, table: string): Promise<readonly string[]>;
readonly socketTimeout: number;
readonly sslMode: string;
readonly terminalCommand: string;
readonly username: string;
}
interface DBDump {
dumpPath: string;
}
type DBServerPurpose = "database" | "shadow_database";
declare function startDBServer(purpose: DBServerPurpose, serverState: ServerState): Promise<DBServer>;
type DumpDBOptions<D extends string> = {
dataDir: string;
db?: never;
debug?: boolean;
destinationPath?: D;
} | {
dataDir?: never;
db: PGlite;
debug?: boolean;
destinationPath?: D;
};
declare function dumpDB<D extends string = never>(options: DumpDBOptions<D>): Promise<[D] extends [never] ? string : void>;
export { type DBDump, type DBServer, type DBServerPurpose, type DumpDBOptions, type WalEvent, type WalEventBridge, attachWalEventBridge, dumpDB, shouldPollWalAfterMessages, shouldPollWalAfterResponse, startDBServer };
+1
View File
@@ -0,0 +1 @@
import{a,b,c,d,e}from"./chunk-YL6J3L2T.js";import"./chunk-62DM64XC.js";import"./chunk-X3G665AK.js";import"./chunk-DWY47FQV.js";export{a as attachWalEventBridge,e as dumpDB,b as shouldPollWalAfterMessages,c as shouldPollWalAfterResponse,d as startDBServer};
+114
View File
File diff suppressed because one or more lines are too long
+81
View File
@@ -0,0 +1,81 @@
import { a as Exports, E as ExperimentalStreams, S as ServerOptions } from './state-DTMxyzXf.cjs';
export { b as ServerAlreadyRunningError } from './state-DTMxyzXf.cjs';
import { WalEvent, DBServerPurpose } from './db.cjs';
export { CopiedPrismaDevRuntimeAsset, PrismaDevRuntimeAsset, copyPrismaDevRuntimeAssets, getPrismaDevRuntimeAssetManifest } from './runtime-assets.cjs';
import 'valibot';
import '@electric-sql/pglite';
/**
* A readonly batch of WAL events emitted together.
*
* @experimental This API may change without notice.
*/
type ExperimentalWalEventBatch = readonly WalEvent[];
/**
* Callback invoked when a batch of WAL events is available.
*
* @experimental This API may change without notice.
*/
type ExperimentalWalEventCallback = (events: ExperimentalWalEventBatch) => void;
/**
* The experimental public WAL event API returned from `startPrismaDevServer()`.
*
* @experimental This API may change without notice.
*/
interface ExperimentalWalEvents {
/**
* Subscribe to WAL event batches. The returned function unsubscribes the callback.
*/
subscribe(callback: ExperimentalWalEventCallback): () => void;
/**
* Create an async iterator that yields WAL event batches as they arrive.
*/
stream(): AsyncIterableIterator<ExperimentalWalEventBatch>;
}
/**
* Experimental capabilities exposed on the public programmatic server.
*
* @experimental This API may change without notice.
*/
interface ExperimentalServerFeatures {
readonly streams: ExperimentalStreams;
readonly wal: ExperimentalWalEvents;
}
interface ProgrammaticServer extends Exports {
close(): Promise<void>;
/**
* Experimental capabilities that may change without notice.
*
* @experimental
*/
experimental: ExperimentalServerFeatures;
name: string;
}
declare const DEFAULT_DATABASE_PORT = 51214;
declare const DEFAULT_SERVER_PORT = 51213;
declare const DEFAULT_SHADOW_DATABASE_PORT = 51215;
type PortAssignableService = DBServerPurpose | "server";
declare class PortNotAvailableError extends Error {
readonly port: number;
name: string;
constructor(port: number);
}
type ReadonlyServer = Omit<ProgrammaticServer, "close">;
/**
* Starts a `prisma dev` server instance programmatically.
*
* DO NOT USE IN PRODUCTION. This is only intended for development and testing purposes.
*
* The returned server also includes experimental capabilities under `server.experimental`,
* including WAL event subscriptions at `server.experimental.wal` and the
* colocated Prisma Streams endpoint metadata at `server.experimental.streams`.
*/
declare function startPrismaDevServer(options?: ServerOptions): Promise<ProgrammaticServer>;
/**
* @deprecated use {@link startPrismaDevServer} instead.
*/
declare function unstable_startServer(options?: ServerOptions): Promise<ProgrammaticServer>;
export { DEFAULT_DATABASE_PORT, DEFAULT_SERVER_PORT, DEFAULT_SHADOW_DATABASE_PORT, type ExperimentalServerFeatures, ExperimentalStreams, WalEvent as ExperimentalWalEvent, type ExperimentalWalEventBatch, type ExperimentalWalEvents, type PortAssignableService, PortNotAvailableError, type ReadonlyServer, type ProgrammaticServer as Server, ServerOptions, startPrismaDevServer, unstable_startServer };
+81
View File
@@ -0,0 +1,81 @@
import { a as Exports, E as ExperimentalStreams, S as ServerOptions } from './state-DTMxyzXf.js';
export { b as ServerAlreadyRunningError } from './state-DTMxyzXf.js';
import { WalEvent, DBServerPurpose } from './db.js';
export { CopiedPrismaDevRuntimeAsset, PrismaDevRuntimeAsset, copyPrismaDevRuntimeAssets, getPrismaDevRuntimeAssetManifest } from './runtime-assets.js';
import 'valibot';
import '@electric-sql/pglite';
/**
* A readonly batch of WAL events emitted together.
*
* @experimental This API may change without notice.
*/
type ExperimentalWalEventBatch = readonly WalEvent[];
/**
* Callback invoked when a batch of WAL events is available.
*
* @experimental This API may change without notice.
*/
type ExperimentalWalEventCallback = (events: ExperimentalWalEventBatch) => void;
/**
* The experimental public WAL event API returned from `startPrismaDevServer()`.
*
* @experimental This API may change without notice.
*/
interface ExperimentalWalEvents {
/**
* Subscribe to WAL event batches. The returned function unsubscribes the callback.
*/
subscribe(callback: ExperimentalWalEventCallback): () => void;
/**
* Create an async iterator that yields WAL event batches as they arrive.
*/
stream(): AsyncIterableIterator<ExperimentalWalEventBatch>;
}
/**
* Experimental capabilities exposed on the public programmatic server.
*
* @experimental This API may change without notice.
*/
interface ExperimentalServerFeatures {
readonly streams: ExperimentalStreams;
readonly wal: ExperimentalWalEvents;
}
interface ProgrammaticServer extends Exports {
close(): Promise<void>;
/**
* Experimental capabilities that may change without notice.
*
* @experimental
*/
experimental: ExperimentalServerFeatures;
name: string;
}
declare const DEFAULT_DATABASE_PORT = 51214;
declare const DEFAULT_SERVER_PORT = 51213;
declare const DEFAULT_SHADOW_DATABASE_PORT = 51215;
type PortAssignableService = DBServerPurpose | "server";
declare class PortNotAvailableError extends Error {
readonly port: number;
name: string;
constructor(port: number);
}
type ReadonlyServer = Omit<ProgrammaticServer, "close">;
/**
* Starts a `prisma dev` server instance programmatically.
*
* DO NOT USE IN PRODUCTION. This is only intended for development and testing purposes.
*
* The returned server also includes experimental capabilities under `server.experimental`,
* including WAL event subscriptions at `server.experimental.wal` and the
* colocated Prisma Streams endpoint metadata at `server.experimental.streams`.
*/
declare function startPrismaDevServer(options?: ServerOptions): Promise<ProgrammaticServer>;
/**
* @deprecated use {@link startPrismaDevServer} instead.
*/
declare function unstable_startServer(options?: ServerOptions): Promise<ProgrammaticServer>;
export { DEFAULT_DATABASE_PORT, DEFAULT_SERVER_PORT, DEFAULT_SHADOW_DATABASE_PORT, type ExperimentalServerFeatures, ExperimentalStreams, WalEvent as ExperimentalWalEvent, type ExperimentalWalEventBatch, type ExperimentalWalEvents, type PortAssignableService, PortNotAvailableError, type ReadonlyServer, type ProgrammaticServer as Server, ServerOptions, startPrismaDevServer, unstable_startServer };
+1
View File
@@ -0,0 +1 @@
import{a as h,b as i}from"./chunk-2O6J3K3T.js";import"./chunk-YL6J3L2T.js";import{a as e,b as f}from"./chunk-62DM64XC.js";import{k as g}from"./chunk-CC3P7GPW.js";import{a,b,c,g as d}from"./chunk-X3G665AK.js";import"./chunk-TF5C7XJX.js";import"./chunk-DWY47FQV.js";export{a as DEFAULT_DATABASE_PORT,b as DEFAULT_SERVER_PORT,c as DEFAULT_SHADOW_DATABASE_PORT,d as PortNotAvailableError,g as ServerAlreadyRunningError,e as copyPrismaDevRuntimeAssets,f as getPrismaDevRuntimeAssetManifest,h as startPrismaDevServer,i as unstable_startServer};
+77
View File
@@ -0,0 +1,77 @@
import {
registerBundledPGliteRuntimeAssetSources,
resolveBundledRuntimeAssetSource,
} from "./runtime-assets.js";
import initdbWasmAsset from "./runtime-assets/initdb.wasm";
import fsBundleAsset from "./runtime-assets/pglite.data";
import wasmModuleAsset from "./runtime-assets/pglite.wasm";
import amcheckAsset from "./runtime-assets/amcheck.tar.gz";
import bloomAsset from "./runtime-assets/bloom.tar.gz";
import btree_ginAsset from "./runtime-assets/btree_gin.tar.gz";
import btree_gistAsset from "./runtime-assets/btree_gist.tar.gz";
import citextAsset from "./runtime-assets/citext.tar.gz";
import cubeAsset from "./runtime-assets/cube.tar.gz";
import dict_intAsset from "./runtime-assets/dict_int.tar.gz";
import dict_xsynAsset from "./runtime-assets/dict_xsyn.tar.gz";
import earthdistanceAsset from "./runtime-assets/earthdistance.tar.gz";
import file_fdwAsset from "./runtime-assets/file_fdw.tar.gz";
import fuzzystrmatchAsset from "./runtime-assets/fuzzystrmatch.tar.gz";
import hstoreAsset from "./runtime-assets/hstore.tar.gz";
import intarrayAsset from "./runtime-assets/intarray.tar.gz";
import isnAsset from "./runtime-assets/isn.tar.gz";
import loAsset from "./runtime-assets/lo.tar.gz";
import ltreeAsset from "./runtime-assets/ltree.tar.gz";
import pageinspectAsset from "./runtime-assets/pageinspect.tar.gz";
import pg_buffercacheAsset from "./runtime-assets/pg_buffercache.tar.gz";
import pg_freespacemapAsset from "./runtime-assets/pg_freespacemap.tar.gz";
import pg_surgeryAsset from "./runtime-assets/pg_surgery.tar.gz";
import pg_trgmAsset from "./runtime-assets/pg_trgm.tar.gz";
import pg_visibilityAsset from "./runtime-assets/pg_visibility.tar.gz";
import pg_walinspectAsset from "./runtime-assets/pg_walinspect.tar.gz";
import segAsset from "./runtime-assets/seg.tar.gz";
import tablefuncAsset from "./runtime-assets/tablefunc.tar.gz";
import tcnAsset from "./runtime-assets/tcn.tar.gz";
import tsm_system_rowsAsset from "./runtime-assets/tsm_system_rows.tar.gz";
import tsm_system_timeAsset from "./runtime-assets/tsm_system_time.tar.gz";
import unaccentAsset from "./runtime-assets/unaccent.tar.gz";
import uuid_osspAsset from "./runtime-assets/uuid-ossp.tar.gz";
import vectorAsset from "./runtime-assets/vector.tar.gz";
registerBundledPGliteRuntimeAssetSources({
fsBundle: resolveBundledRuntimeAssetSource(fsBundleAsset, import.meta.url),
initdbWasm: resolveBundledRuntimeAssetSource(initdbWasmAsset, import.meta.url),
wasmModule: resolveBundledRuntimeAssetSource(wasmModuleAsset, import.meta.url),
extensions: {
"amcheck": resolveBundledRuntimeAssetSource(amcheckAsset, import.meta.url),
"bloom": resolveBundledRuntimeAssetSource(bloomAsset, import.meta.url),
"btree_gin": resolveBundledRuntimeAssetSource(btree_ginAsset, import.meta.url),
"btree_gist": resolveBundledRuntimeAssetSource(btree_gistAsset, import.meta.url),
"citext": resolveBundledRuntimeAssetSource(citextAsset, import.meta.url),
"cube": resolveBundledRuntimeAssetSource(cubeAsset, import.meta.url),
"dict_int": resolveBundledRuntimeAssetSource(dict_intAsset, import.meta.url),
"dict_xsyn": resolveBundledRuntimeAssetSource(dict_xsynAsset, import.meta.url),
"earthdistance": resolveBundledRuntimeAssetSource(earthdistanceAsset, import.meta.url),
"file_fdw": resolveBundledRuntimeAssetSource(file_fdwAsset, import.meta.url),
"fuzzystrmatch": resolveBundledRuntimeAssetSource(fuzzystrmatchAsset, import.meta.url),
"hstore": resolveBundledRuntimeAssetSource(hstoreAsset, import.meta.url),
"intarray": resolveBundledRuntimeAssetSource(intarrayAsset, import.meta.url),
"isn": resolveBundledRuntimeAssetSource(isnAsset, import.meta.url),
"lo": resolveBundledRuntimeAssetSource(loAsset, import.meta.url),
"ltree": resolveBundledRuntimeAssetSource(ltreeAsset, import.meta.url),
"pageinspect": resolveBundledRuntimeAssetSource(pageinspectAsset, import.meta.url),
"pg_buffercache": resolveBundledRuntimeAssetSource(pg_buffercacheAsset, import.meta.url),
"pg_freespacemap": resolveBundledRuntimeAssetSource(pg_freespacemapAsset, import.meta.url),
"pg_surgery": resolveBundledRuntimeAssetSource(pg_surgeryAsset, import.meta.url),
"pg_trgm": resolveBundledRuntimeAssetSource(pg_trgmAsset, import.meta.url),
"pg_visibility": resolveBundledRuntimeAssetSource(pg_visibilityAsset, import.meta.url),
"pg_walinspect": resolveBundledRuntimeAssetSource(pg_walinspectAsset, import.meta.url),
"seg": resolveBundledRuntimeAssetSource(segAsset, import.meta.url),
"tablefunc": resolveBundledRuntimeAssetSource(tablefuncAsset, import.meta.url),
"tcn": resolveBundledRuntimeAssetSource(tcnAsset, import.meta.url),
"tsm_system_rows": resolveBundledRuntimeAssetSource(tsm_system_rowsAsset, import.meta.url),
"tsm_system_time": resolveBundledRuntimeAssetSource(tsm_system_timeAsset, import.meta.url),
"unaccent": resolveBundledRuntimeAssetSource(unaccentAsset, import.meta.url),
"uuid_ossp": resolveBundledRuntimeAssetSource(uuid_osspAsset, import.meta.url),
"vector": resolveBundledRuntimeAssetSource(vectorAsset, import.meta.url),
},
});
File diff suppressed because one or more lines are too long
+26
View File
@@ -0,0 +1,26 @@
interface PGliteRuntimeAssets {
readonly extensions: Record<string, URL>;
readonly fsBundle: Blob;
readonly wasmModule: unknown;
}
interface PrismaDevRuntimeAsset {
readonly fileName: string;
readonly kind: "core" | "extension";
readonly name: string;
readonly sourcePath: string;
}
interface CopiedPrismaDevRuntimeAsset extends PrismaDevRuntimeAsset {
readonly destinationPath: string;
}
declare function copyPrismaDevRuntimeAssets(destinationDir: string | URL): Promise<CopiedPrismaDevRuntimeAsset[]>;
declare function getPrismaDevRuntimeAssetManifest(): readonly PrismaDevRuntimeAsset[];
declare function getPGliteRuntimeAssets(): Promise<PGliteRuntimeAssets>;
declare function registerBundledPGliteRuntimeAssetSources(sources: {
extensions: Record<string, string | URL>;
fsBundle: string | URL;
initdbWasm: string | URL;
wasmModule: string | URL;
}): void;
declare function resolveBundledRuntimeAssetSource(source: string | URL, baseURL?: string): URL;
export { type CopiedPrismaDevRuntimeAsset, type PrismaDevRuntimeAsset, copyPrismaDevRuntimeAssets, getPGliteRuntimeAssets, getPrismaDevRuntimeAssetManifest, registerBundledPGliteRuntimeAssetSources, resolveBundledRuntimeAssetSource };
+26
View File
@@ -0,0 +1,26 @@
interface PGliteRuntimeAssets {
readonly extensions: Record<string, URL>;
readonly fsBundle: Blob;
readonly wasmModule: unknown;
}
interface PrismaDevRuntimeAsset {
readonly fileName: string;
readonly kind: "core" | "extension";
readonly name: string;
readonly sourcePath: string;
}
interface CopiedPrismaDevRuntimeAsset extends PrismaDevRuntimeAsset {
readonly destinationPath: string;
}
declare function copyPrismaDevRuntimeAssets(destinationDir: string | URL): Promise<CopiedPrismaDevRuntimeAsset[]>;
declare function getPrismaDevRuntimeAssetManifest(): readonly PrismaDevRuntimeAsset[];
declare function getPGliteRuntimeAssets(): Promise<PGliteRuntimeAssets>;
declare function registerBundledPGliteRuntimeAssetSources(sources: {
extensions: Record<string, string | URL>;
fsBundle: string | URL;
initdbWasm: string | URL;
wasmModule: string | URL;
}): void;
declare function resolveBundledRuntimeAssetSource(source: string | URL, baseURL?: string): URL;
export { type CopiedPrismaDevRuntimeAsset, type PrismaDevRuntimeAsset, copyPrismaDevRuntimeAssets, getPGliteRuntimeAssets, getPrismaDevRuntimeAssetManifest, registerBundledPGliteRuntimeAssetSources, resolveBundledRuntimeAssetSource };
+1
View File
@@ -0,0 +1 @@
import{a,b,c,d,e}from"./chunk-62DM64XC.js";export{a as copyPrismaDevRuntimeAssets,c as getPGliteRuntimeAssets,b as getPrismaDevRuntimeAssetManifest,d as registerBundledPGliteRuntimeAssetSources,e as resolveBundledRuntimeAssetSource};
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+235
View File
@@ -0,0 +1,235 @@
import * as valibot from 'valibot';
import { InferOutput } from 'valibot';
interface ExperimentalStreams {
readonly serverUrl: string;
readonly sqlitePath: string;
readonly streamName: string;
readonly url: string;
}
interface ExperimentalServerMetadata {
readonly streams?: ExperimentalStreams;
}
declare const exportsSchema: valibot.ObjectSchema<{
readonly database: valibot.ObjectSchema<{
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
}, undefined>;
readonly http: valibot.ObjectSchema<{
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
}, undefined>;
readonly ppg: valibot.ObjectSchema<{
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
}, undefined>;
readonly shadowDatabase: valibot.ObjectSchema<{
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
}, undefined>;
}, undefined>;
type Exports = InferOutput<typeof exportsSchema>;
declare const serverDumpV1Schema: valibot.ObjectSchema<{
readonly databasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
readonly experimental: valibot.OptionalSchema<valibot.ObjectSchema<{
readonly streams: valibot.OptionalSchema<valibot.ObjectSchema<{
readonly serverUrl: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
readonly sqlitePath: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
readonly streamName: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
}, undefined>, undefined>;
}, undefined>, undefined>;
readonly exports: valibot.OptionalSchema<valibot.ObjectSchema<{
readonly database: valibot.ObjectSchema<{
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
}, undefined>;
readonly http: valibot.ObjectSchema<{
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
}, undefined>;
readonly ppg: valibot.ObjectSchema<{
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
}, undefined>;
readonly shadowDatabase: valibot.ObjectSchema<{
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
}, undefined>;
}, undefined>, undefined>;
readonly name: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
readonly pid: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 0, undefined>]>, undefined>;
readonly port: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
readonly shadowDatabasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
readonly version: valibot.LiteralSchema<"1", undefined>;
}, undefined>;
type ServerDumpV1 = InferOutput<typeof serverDumpV1Schema>;
interface ServerOptions {
/**
* Connection timeout in milliseconds for pending database connections.
*
* This option is currently not enforced by the multiplexed
* `@electric-sql/pglite-socket` server used by `@prisma/dev`.
* It is kept for API compatibility until upstream exposes a queue-timeout
* equivalent again.
*
* Default is 1 minute (60,000 milliseconds).
*/
databaseConnectTimeoutMillis?: number;
/**
* Idle timeout in milliseconds for open database connections.
*
* Re-starts ticking after each message received on a connection. When exceeded,
* that client connection is closed by the socket server.
*
* Is not applied by default.
*
* Use it with caution, as it may lead to unexpected disconnections. Best used
* with a pool client that can handle disconnections gracefully.
*
* Set it if you suffer from client hanging indefinitely as the active connection
* remain open forever.
*/
databaseIdleTimeoutMillis?: number;
/**
* The port the database server will listen on.
*
* Defaults to `51214`.
*
* An error is thrown if the port is already in use.
*/
databasePort?: number;
/**
* Whether to enable debug logging.
*
* Defaults to `false`.
*/
debug?: boolean;
/**
* Whether to run the server in dry run mode.
*
* Defaults to `false`.
*/
dryRun?: boolean;
/**
* The name of the server.
*
* Defaults to `default`.
*/
name?: string;
/**
* The persistence mode of the server.
*
* Default is `stateless`.
*/
persistenceMode?: PersistenceMode;
/**
* The port the server will listen on.
*
* Defaults to `51213`.
*
* An error is thrown if the port is already in use.
*/
port?: number;
/**
* Connection timeout in milliseconds for pending shadow database connections.
*
* Default is {@link databaseConnectTimeoutMillis}.
*/
shadowDatabaseConnectTimeoutMillis?: number;
/**
* Idle timeout in milliseconds for active shadow database connections.
*
* Default is {@link databaseIdleTimeoutMillis}.
*/
shadowDatabaseIdleTimeoutMillis?: number;
/**
* The port the shadow database server will listen on.
*
* Defaults to `51215`.
*
* An error is thrown if the port is already in use.
*/
shadowDatabasePort?: number;
}
type ResolvedServerOptions = Required<ServerOptions>;
type PersistenceMode = "stateless" | "stateful";
interface ScanOptions {
debug?: boolean;
globs?: string[];
onlyMetadata?: boolean;
}
declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
declare abstract class ServerState implements ResolvedServerOptions {
#private;
protected _databasePort: number;
readonly databaseConnectTimeoutMillis: number;
readonly databaseIdleTimeoutMillis: number;
readonly debug: boolean;
readonly dryRun: boolean;
readonly name: string;
readonly persistenceMode: PersistenceMode;
readonly pid: number | undefined;
readonly shadowDatabaseConnectTimeoutMillis: number;
readonly shadowDatabaseIdleTimeoutMillis: number;
protected _port: number;
protected _shadowDatabasePort: number;
protected _streamsPort: number;
protected constructor(options: Omit<ServerOptions, "persistenceMode"> & {
persistenceMode: PersistenceMode;
pid?: number | undefined;
});
static createExclusively(options: ServerOptions | undefined): Promise<ServerState>;
static fromServerDump(options?: Pick<ServerOptions, "debug" | "name">): Promise<StatefulServerState | null>;
static scan(options?: ScanOptions): Promise<ServerStatusV1[]>;
abstract get databaseDumpPath(): string;
abstract get pgliteDataDirPath(): string;
abstract [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
abstract close(): Promise<void>;
abstract writeServerDump(exports?: Exports, experimental?: ExperimentalServerMetadata): Promise<void>;
get databasePort(): number;
set databasePort(value: number);
get port(): number;
set port(value: number);
get shadowDatabasePort(): number;
get streamsPort(): number;
set shadowDatabasePort(value: number);
}
declare class StatefulServerState extends ServerState {
#private;
constructor(options: (Omit<ServerOptions, "persistenceMode"> & {
pid?: number | undefined;
serverDump?: ServerDumpV1;
}) | undefined);
static getServerDumpPath(dataDirPath: string): string;
get databaseDumpPath(): string;
get exports(): Exports | undefined;
get experimental(): ExperimentalServerMetadata | undefined;
get pgliteDataDirPath(): string;
[PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
close(): Promise<void>;
writeServerDump(exports?: Exports, experimental?: ExperimentalServerMetadata): Promise<void>;
}
interface ServerStatusV1 extends ServerDumpV1 {
status: "running" | "starting_up" | "not_running" | "no_such_server" | "unknown" | "error";
}
declare function deleteServer(nameOrStatus: string | ServerStatusV1, debug?: boolean): Promise<void>;
declare function getServerStatus(nameOrState: string | StatefulServerState, options?: ScanOptions): Promise<ServerStatusV1>;
declare function isServerRunning(server: ServerStatusV1): boolean;
declare function killServer(nameOrStatus: string | ServerStatusV1, debug?: boolean): Promise<boolean>;
/**
* @deprecated use `ServerAlreadyRunningError` instead. Will be removed in a future version.
*/
declare class ServerStateAlreadyExistsError extends Error {
name: string;
constructor(name: string);
}
declare class ServerAlreadyRunningError extends ServerStateAlreadyExistsError {
#private;
name: string;
constructor(server: ServerState);
get server(): Promise<ServerState | null>;
}
export { type ExperimentalStreams as E, type PersistenceMode as P, type ResolvedServerOptions as R, type ServerOptions as S, type Exports as a, ServerAlreadyRunningError as b, ServerState as c, type ScanOptions as d, type ServerDumpV1 as e, ServerStateAlreadyExistsError as f, type ServerStatusV1 as g, deleteServer as h, getServerStatus as i, isServerRunning as j, killServer as k };
+235
View File
@@ -0,0 +1,235 @@
import * as valibot from 'valibot';
import { InferOutput } from 'valibot';
interface ExperimentalStreams {
readonly serverUrl: string;
readonly sqlitePath: string;
readonly streamName: string;
readonly url: string;
}
interface ExperimentalServerMetadata {
readonly streams?: ExperimentalStreams;
}
declare const exportsSchema: valibot.ObjectSchema<{
readonly database: valibot.ObjectSchema<{
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
}, undefined>;
readonly http: valibot.ObjectSchema<{
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
}, undefined>;
readonly ppg: valibot.ObjectSchema<{
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
}, undefined>;
readonly shadowDatabase: valibot.ObjectSchema<{
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
}, undefined>;
}, undefined>;
type Exports = InferOutput<typeof exportsSchema>;
declare const serverDumpV1Schema: valibot.ObjectSchema<{
readonly databasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
readonly experimental: valibot.OptionalSchema<valibot.ObjectSchema<{
readonly streams: valibot.OptionalSchema<valibot.ObjectSchema<{
readonly serverUrl: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
readonly sqlitePath: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
readonly streamName: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
}, undefined>, undefined>;
}, undefined>, undefined>;
readonly exports: valibot.OptionalSchema<valibot.ObjectSchema<{
readonly database: valibot.ObjectSchema<{
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
}, undefined>;
readonly http: valibot.ObjectSchema<{
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
}, undefined>;
readonly ppg: valibot.ObjectSchema<{
readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
}, undefined>;
readonly shadowDatabase: valibot.ObjectSchema<{
readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
}, undefined>;
}, undefined>, undefined>;
readonly name: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
readonly pid: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 0, undefined>]>, undefined>;
readonly port: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
readonly shadowDatabasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
readonly version: valibot.LiteralSchema<"1", undefined>;
}, undefined>;
type ServerDumpV1 = InferOutput<typeof serverDumpV1Schema>;
interface ServerOptions {
/**
* Connection timeout in milliseconds for pending database connections.
*
* This option is currently not enforced by the multiplexed
* `@electric-sql/pglite-socket` server used by `@prisma/dev`.
* It is kept for API compatibility until upstream exposes a queue-timeout
* equivalent again.
*
* Default is 1 minute (60,000 milliseconds).
*/
databaseConnectTimeoutMillis?: number;
/**
* Idle timeout in milliseconds for open database connections.
*
* Re-starts ticking after each message received on a connection. When exceeded,
* that client connection is closed by the socket server.
*
* Is not applied by default.
*
* Use it with caution, as it may lead to unexpected disconnections. Best used
* with a pool client that can handle disconnections gracefully.
*
* Set it if you suffer from client hanging indefinitely as the active connection
* remain open forever.
*/
databaseIdleTimeoutMillis?: number;
/**
* The port the database server will listen on.
*
* Defaults to `51214`.
*
* An error is thrown if the port is already in use.
*/
databasePort?: number;
/**
* Whether to enable debug logging.
*
* Defaults to `false`.
*/
debug?: boolean;
/**
* Whether to run the server in dry run mode.
*
* Defaults to `false`.
*/
dryRun?: boolean;
/**
* The name of the server.
*
* Defaults to `default`.
*/
name?: string;
/**
* The persistence mode of the server.
*
* Default is `stateless`.
*/
persistenceMode?: PersistenceMode;
/**
* The port the server will listen on.
*
* Defaults to `51213`.
*
* An error is thrown if the port is already in use.
*/
port?: number;
/**
* Connection timeout in milliseconds for pending shadow database connections.
*
* Default is {@link databaseConnectTimeoutMillis}.
*/
shadowDatabaseConnectTimeoutMillis?: number;
/**
* Idle timeout in milliseconds for active shadow database connections.
*
* Default is {@link databaseIdleTimeoutMillis}.
*/
shadowDatabaseIdleTimeoutMillis?: number;
/**
* The port the shadow database server will listen on.
*
* Defaults to `51215`.
*
* An error is thrown if the port is already in use.
*/
shadowDatabasePort?: number;
}
type ResolvedServerOptions = Required<ServerOptions>;
type PersistenceMode = "stateless" | "stateful";
interface ScanOptions {
debug?: boolean;
globs?: string[];
onlyMetadata?: boolean;
}
declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
declare abstract class ServerState implements ResolvedServerOptions {
#private;
protected _databasePort: number;
readonly databaseConnectTimeoutMillis: number;
readonly databaseIdleTimeoutMillis: number;
readonly debug: boolean;
readonly dryRun: boolean;
readonly name: string;
readonly persistenceMode: PersistenceMode;
readonly pid: number | undefined;
readonly shadowDatabaseConnectTimeoutMillis: number;
readonly shadowDatabaseIdleTimeoutMillis: number;
protected _port: number;
protected _shadowDatabasePort: number;
protected _streamsPort: number;
protected constructor(options: Omit<ServerOptions, "persistenceMode"> & {
persistenceMode: PersistenceMode;
pid?: number | undefined;
});
static createExclusively(options: ServerOptions | undefined): Promise<ServerState>;
static fromServerDump(options?: Pick<ServerOptions, "debug" | "name">): Promise<StatefulServerState | null>;
static scan(options?: ScanOptions): Promise<ServerStatusV1[]>;
abstract get databaseDumpPath(): string;
abstract get pgliteDataDirPath(): string;
abstract [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
abstract close(): Promise<void>;
abstract writeServerDump(exports?: Exports, experimental?: ExperimentalServerMetadata): Promise<void>;
get databasePort(): number;
set databasePort(value: number);
get port(): number;
set port(value: number);
get shadowDatabasePort(): number;
get streamsPort(): number;
set shadowDatabasePort(value: number);
}
declare class StatefulServerState extends ServerState {
#private;
constructor(options: (Omit<ServerOptions, "persistenceMode"> & {
pid?: number | undefined;
serverDump?: ServerDumpV1;
}) | undefined);
static getServerDumpPath(dataDirPath: string): string;
get databaseDumpPath(): string;
get exports(): Exports | undefined;
get experimental(): ExperimentalServerMetadata | undefined;
get pgliteDataDirPath(): string;
[PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
close(): Promise<void>;
writeServerDump(exports?: Exports, experimental?: ExperimentalServerMetadata): Promise<void>;
}
interface ServerStatusV1 extends ServerDumpV1 {
status: "running" | "starting_up" | "not_running" | "no_such_server" | "unknown" | "error";
}
declare function deleteServer(nameOrStatus: string | ServerStatusV1, debug?: boolean): Promise<void>;
declare function getServerStatus(nameOrState: string | StatefulServerState, options?: ScanOptions): Promise<ServerStatusV1>;
declare function isServerRunning(server: ServerStatusV1): boolean;
declare function killServer(nameOrStatus: string | ServerStatusV1, debug?: boolean): Promise<boolean>;
/**
* @deprecated use `ServerAlreadyRunningError` instead. Will be removed in a future version.
*/
declare class ServerStateAlreadyExistsError extends Error {
name: string;
constructor(name: string);
}
declare class ServerAlreadyRunningError extends ServerStateAlreadyExistsError {
#private;
name: string;
constructor(server: ServerState);
get server(): Promise<ServerState | null>;
}
export { type ExperimentalStreams as E, type PersistenceMode as P, type ResolvedServerOptions as R, type ServerOptions as S, type Exports as a, ServerAlreadyRunningError as b, ServerState as c, type ScanOptions as d, type ServerDumpV1 as e, ServerStateAlreadyExistsError as f, type ServerStatusV1 as g, deleteServer as h, getServerStatus as i, isServerRunning as j, killServer as k };
+3
View File
File diff suppressed because one or more lines are too long
+2
View File
@@ -0,0 +1,2 @@
import 'valibot';
export { a as Exports, P as PersistenceMode, R as ResolvedServerOptions, d as ScanOptions, b as ServerAlreadyRunningError, e as ServerDumpV1, S as ServerOptions, c as ServerState, f as ServerStateAlreadyExistsError, g as ServerStatusV1, h as deleteServer, i as getServerStatus, j as isServerRunning, k as killServer } from './state-DTMxyzXf.cjs';
+2
View File
@@ -0,0 +1,2 @@
import 'valibot';
export { a as Exports, P as PersistenceMode, R as ResolvedServerOptions, d as ScanOptions, b as ServerAlreadyRunningError, e as ServerDumpV1, S as ServerOptions, c as ServerState, f as ServerStateAlreadyExistsError, g as ServerStatusV1, h as deleteServer, i as getServerStatus, j as isServerRunning, k as killServer } from './state-DTMxyzXf.js';
+1
View File
@@ -0,0 +1 @@
import{e as a,f as b,g as c,h as d,i as e,j as f,k as g}from"./chunk-CC3P7GPW.js";import"./chunk-X3G665AK.js";import"./chunk-DWY47FQV.js";export{g as ServerAlreadyRunningError,a as ServerState,f as ServerStateAlreadyExistsError,b as deleteServer,c as getServerStatus,d as isServerRunning,e as killServer};
+1
View File
@@ -0,0 +1 @@
import{Hono as n}from"hono/tiny";import{StatusCodes as p}from"http-status-codes";var o=new n;o.post("/database/dump",async t=>{let a=t.get("db"),e=t.get("databaseDumpPath");return await a.dump(e),t.json({dumpPath:e},p.CREATED)});var u=o.get("/health",t=>t.json({name:t.get("name")}));export{o as utilityRoute};
+107
View File
@@ -0,0 +1,107 @@
{
"name": "@prisma/dev",
"version": "0.24.3",
"description": "A local Prisma Postgres server for development and testing",
"type": "module",
"author": "Igal Klebanov <igalklebanov@gmail.com> (https://github.com/igalklebanov)",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"files": [
"dist"
],
"exports": {
".": {
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
},
"./internal/daemon": {
"import": {
"types": "./dist/daemon.d.ts",
"default": "./dist/daemon.js"
},
"require": {
"types": "./dist/daemon.d.cts",
"default": "./dist/daemon.cjs"
}
},
"./internal/db": {
"import": {
"types": "./dist/db.d.ts",
"default": "./dist/db.js"
},
"require": {
"types": "./dist/db.d.cts",
"default": "./dist/db.cjs"
}
},
"./internal/state": {
"import": {
"types": "./dist/state.d.ts",
"default": "./dist/state.js"
},
"require": {
"types": "./dist/state.d.cts",
"default": "./dist/state.cjs"
}
}
},
"keywords": [
"prisma",
"postgres",
"accelerate",
"local",
"development",
"dev",
"testing"
],
"license": "ISC",
"devDependencies": {
"@arethetypeswrong/cli": "0.18.2",
"@types/node": "25.0.9",
"@types/pako": "2.0.4",
"@types/pg": "8.15.6",
"@types/proper-lockfile": "4.1.4",
"env-paths": "3.0.0",
"pg": "8.16.0",
"pkg-types": "2.3.0",
"tsup": "8.5.1",
"typescript": "5.9.3",
"vitest": "4.0.17",
"common-stuff": "^0.0.0"
},
"dependencies": {
"@electric-sql/pglite": "0.4.1",
"@electric-sql/pglite-socket": "0.1.1",
"@electric-sql/pglite-tools": "0.3.1",
"@hono/node-server": "1.19.11",
"@prisma/get-platform": "7.2.0",
"@prisma/query-plan-executor": "7.2.0",
"@prisma/streams-local": "0.1.2",
"foreground-child": "3.3.1",
"get-port-please": "3.2.0",
"hono": "^4.12.8",
"http-status-codes": "2.3.0",
"pathe": "2.0.3",
"proper-lockfile": "4.1.2",
"remeda": "2.33.4",
"std-env": "3.10.0",
"valibot": "1.2.0",
"zeptomatch": "2.1.0"
},
"scripts": {
"build": "node ./scripts/generate-bun-runtime-assets.mjs && tsup && node ./scripts/generate-bun-runtime-assets.mjs --dist",
"check:exports": "attw . --pack --profile node16",
"dev": "node ./scripts/generate-bun-runtime-assets.mjs && tsup --watch",
"init": "node ./scripts/generate-bun-runtime-assets.mjs",
"lint": "eslint --fix .",
"test": "node ./scripts/generate-bun-runtime-assets.mjs && vitest run",
"typecheck": "node ./scripts/generate-bun-runtime-assets.mjs && tsc --noEmit"
}
}