@prisma/dev 0.25.0 → 0.25.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{accelerate-TRR43YJ5.js → accelerate-KNP4MGMV.js} +1 -1
- package/dist/{chunk-J6FIMHSD.js → chunk-AVDGCP6B.js} +1 -1
- package/dist/chunk-GK3XD2W4.js +3 -0
- package/dist/chunk-MGHBCHO2.js +107 -0
- package/dist/{chunk-MD3K2IUP.js → chunk-S2WDC6AE.js} +1 -1
- package/dist/{chunk-DWY47FQV.js → chunk-ZEM5OLPM.js} +1 -1
- package/dist/daemon.cjs +24 -24
- package/dist/daemon.js +1 -1
- package/dist/db.cjs +15 -15
- package/dist/db.js +1 -1
- package/dist/{engine-YTEOPVUP.js → engine-XTNCE4RM.js} +1 -1
- package/dist/index.cjs +24 -24
- package/dist/index.js +1 -1
- package/dist/state.cjs +3 -3
- package/dist/state.js +1 -1
- package/dist/vite.cjs +25 -25
- package/dist/vite.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-HFONW2ZS.js +0 -3
- package/dist/chunk-PP43TGA5.js +0 -107
|
@@ -8,4 +8,4 @@ import{b as p}from"./chunk-662IKR3V.js";import{a as g}from"./chunk-SW3J2PL2.js";
|
|
|
8
8
|
`,r)+1,t=e;for(;n[t]===" "||n[t]===" ";)t+=1;return n.slice(e,t)}function Tn(n){return n.includes(`\r
|
|
9
9
|
`)?`\r
|
|
10
10
|
`:`
|
|
11
|
-
`}function xn(n){return n.replaceAll("\\","\\\\").replaceAll('"','\\"')}function w(n,r){let e=n[r];return Array.isArray(e)?e.at(-1):e}import{Readable as q}from"stream";import{pipeline as Hn}from"stream/promises";var En=new Set(["GET","HEAD"]);function U(n,r){let e=(n.method??"GET").toUpperCase(),t=`${r.origin}${n.url??"/"}`,i={headers:$n(n.headers),method:e};return En.has(e)||(i.body=q.toWeb(n),i.duplex="half"),new Request(t,i)}async function j(n,r){r.statusCode=n.status;for(let[e,t]of n.headers)r.setHeader(e,t);if(n.body===null){r.end();return}await Hn(q.fromWeb(n.body),r)}function $n(n){let r=new Headers;for(let[e,t]of Object.entries(n))if(typeof t=="string")r.append(e,t);else if(Array.isArray(t))for(let i of t)r.append(e,i);return r}function H(n){return{traceparent:w(n.headers,"traceparent"),"X-capture-telemetry":w(n.headers,"x-capture-telemetry")}}import{json as On}from"stream/consumers";import{integer as F,looseObject as Rn,minValue as k,number as b,object as Pn,optional as vn,pipe as W,safeParse as G,string as z,union as bn}from"valibot";var An=Pn({isolation_level:vn(z()),max_wait:W(b(),F(),k(0)),timeout:W(b(),F(),k(0))});async function Y(n,r){let e;try{e=await On(n)}catch{return d(r,{EngineNotStarted:{reason:"InvalidRequest",issues:[]}},400),null}let{issues:t,output:i,success:o}=G(An,e,{abortEarly:!0});return o?i:(d(r,{EngineNotStarted:{reason:"InvalidRequest",issues:t}},400),null)}var Mn=Rn({id:bn([z(),b()])});function J(n,r){let{output:e,success:t}=G(Mn,n);return t?e:(d(r,{EngineMalfunction:{}},500),null)}var X,Z,K;function E(){return X??=import("./engine-
|
|
11
|
+
`}function xn(n){return n.replaceAll("\\","\\\\").replaceAll('"','\\"')}function w(n,r){let e=n[r];return Array.isArray(e)?e.at(-1):e}import{Readable as q}from"stream";import{pipeline as Hn}from"stream/promises";var En=new Set(["GET","HEAD"]);function U(n,r){let e=(n.method??"GET").toUpperCase(),t=`${r.origin}${n.url??"/"}`,i={headers:$n(n.headers),method:e};return En.has(e)||(i.body=q.toWeb(n),i.duplex="half"),new Request(t,i)}async function j(n,r){r.statusCode=n.status;for(let[e,t]of n.headers)r.setHeader(e,t);if(n.body===null){r.end();return}await Hn(q.fromWeb(n.body),r)}function $n(n){let r=new Headers;for(let[e,t]of Object.entries(n))if(typeof t=="string")r.append(e,t);else if(Array.isArray(t))for(let i of t)r.append(e,i);return r}function H(n){return{traceparent:w(n.headers,"traceparent"),"X-capture-telemetry":w(n.headers,"x-capture-telemetry")}}import{json as On}from"stream/consumers";import{integer as F,looseObject as Rn,minValue as k,number as b,object as Pn,optional as vn,pipe as W,safeParse as G,string as z,union as bn}from"valibot";var An=Pn({isolation_level:vn(z()),max_wait:W(b(),F(),k(0)),timeout:W(b(),F(),k(0))});async function Y(n,r){let e;try{e=await On(n)}catch{return d(r,{EngineNotStarted:{reason:"InvalidRequest",issues:[]}},400),null}let{issues:t,output:i,success:o}=G(An,e,{abortEarly:!0});return o?i:(d(r,{EngineNotStarted:{reason:"InvalidRequest",issues:t}},400),null)}var Mn=Rn({id:bn([z(),b()])});function J(n,r){let{output:e,success:t}=G(Mn,n);return t?e:(d(r,{EngineMalfunction:{}},500),null)}var X,Z,K;function E(){return X??=import("./engine-XTNCE4RM.js"),X}function Bn(){return K??=import("./query-plan-executor-ZS4544O3.js"),K}async function Cn(){return Z??=import("@prisma/get-platform").then(async({default:n})=>await n.getPlatformInfo()),await Z}function ge(n,r,e){n.on("POST","/invalidate",g(async(i,o)=>{p(i,r),await C(i,o)!==null&&B(o,200)},e));for(let i of["/:clientVersion/:schemaHash/graphql","/:clientVersion/:schemaHash/itx/:transactionId/graphql"])n.on("POST",i,g(async(o,a,u)=>{p(o,r);try{let s=await A(a,r,u);if(s===null)return;let c=await Q(o),l=u.transactionId,f=await s.request(c,{...H(o),"X-transaction-id":l});m(a,f)}catch(s){let{handleEngineError:c}=await E();c(s,a)}},e));for(let i of["commit","rollback"])n.on("POST",`/:clientVersion/:schemaHash/itx/:transactionId/${i}`,g(async(o,a,u)=>{p(o,r);try{let s=await A(a,r,u);if(s===null)return;let c=u.transactionId;if(c==null){d(a,{EngineMalfunction:{}},500);return}let l=`${i}Transaction`,f=await s[l](c,H(o));d(a,f)}catch(s){let{handleEngineError:c}=await E();c(s,a)}},e));n.on("PUT","/:clientVersion/:schemaHash/schema",g(async(i,o,a)=>{p(i,r);let u=await Q(i);if(!u){m(o,"Missing schema",400);return}let s=a.schemaHash;if(s==null){m(o,"Missing schema hash",400);return}let c=x.get(s);if(c==null){if(s!==await O(u)){m(o,"Schema hash mismatch",400);return}let l=await V(u,r.db.prismaORMConnectionString,r.debug);x.set(s,{base64Original:u,...l}),m(o,s);return}if(u!==c.base64Original){m(o,"Schema mismatch",400);return}m(o,s)},e)),n.on("POST","/:clientVersion/:schemaHash/transaction/start",g(async(i,o,a)=>{p(i,r);let u=await Y(i,o);if(u!==null)try{let s=await A(o,r,a);if(s===null)return;let c=await s.startTransaction(u,H(i)),l=J(c,o);if(l===null)return;let{id:f}=l,h=a.clientVersion,I=a.schemaHash;d(o,{...c,"data-proxy":{endpoint:`http://localhost:${r.port}/${h}/${I}/itx/${f}`}})}catch(s){let{handleEngineError:c}=await E();c(s,o)}},e));let t=[["GET","/connection-info"],["POST","/query"],["POST","/transaction/start"],["POST","/transaction/:transactionId/commit"],["POST","/transaction/:transactionId/query"],["POST","/transaction/:transactionId/rollback"]];for(let[i,o]of t)n.on(i,o,g(async(a,u)=>{p(a,r);let{getQueryPlanExecutorServer:s,queryPlanExecutorVersion:c}=await Bn(),l=w(a.headers,"prisma-engine-hash");if(l!=="0.0.0"&&l!==c)throw new M(400,`Using an HTTP connection string is not supported with Prisma Client version ${l??"<missing>"} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${c}.`);let f=await s(r),h=U(a,{origin:`http://localhost:${r.port}`}),I=await f.fetch(h);await j(I,u)},e))}async function A(n,r,e){let{Engine:t}=await E(),i=N(e,n);if(i===null)return null;let{base64Override:o,overrideHash:a}=i.schemas;return await t.get({base64Schema:o,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.clientVersion||"",debug:r.debug,platform:await Cn(),schemaHash:a})}export{ge as registerAccelerateRoutes};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as q}from"./chunk-662IKR3V.js";import{a as W,b as _,f as x}from"./chunk-PP43TGA5.js";import{a as O,b as R,c as A,d as I,e as v,f as M,h as $,i as U}from"./chunk-HFONW2ZS.js";import{d as C,j as y}from"./chunk-DWY47FQV.js";import{b as N}from"./chunk-DOJAPHLY.js";import Z from"find-my-way";async function F(r,e){let{port:t}=e;if(e.dryRun)return{async close(){},port:t,url:`http://localhost:${t}`};let n=!!e.debug,[{registerAccelerateRoutes:s},{registerUtilityRoutes:i},{createHTTPServer:l}]=await Promise.all([import("./accelerate-TRR43YJ5.js"),import("./utility-YEFNU35E.js"),import("./server-QR7P25DP.js")]),a={databaseDumpPath:e.databaseDumpPath,db:r,debug:n,name:e.name,port:t,shadowDBPort:e.shadowDatabasePort},o=Z({defaultRoute(u,p){N(p,"Not Found",404)},ignoreTrailingSlash:!1});s(o,a,n),i(o,a,n);let c=await l({router:o}).listen(t);return e.port=c.port,a.port=c.port,{async close(){let{Engine:u}=await import("./engine-YTEOPVUP.js");await Promise.allSettled([c.close(),u.stopAll()])},port:c.port,url:c.url}}import{isDeepStrictEqual as j}from"util";var ee="application/json",E={connection:"close","content-type":ee},T={apiVersion:"durable.streams/schema-registry/v1",schema:{additionalProperties:!0,properties:{applicationName:{type:["string","null"]},durationMs:{type:"number"},groupKey:{type:["string","null"]},query:{type:"string"},queryId:{type:"string"},reads:{type:"number"},rowsReturned:{type:"number"},tables:{items:{type:"string"},type:"array"},timestamp:{format:"date-time",type:"string"}},required:["durationMs","query","queryId","reads","rowsReturned","tables","timestamp"],type:"object"},search:{aliases:{applicationName:"applicationName",groupKey:"groupKey",queryId:"queryId"},fields:{applicationName:{bindings:[{jsonPointer:"/applicationName",version:1}],exact:!0,exists:!0,kind:"keyword"},eventTime:{bindings:[{jsonPointer:"/timestamp",version:1}],column:!0,exact:!0,exists:!0,kind:"date",sortable:!0},groupKey:{bindings:[{jsonPointer:"/groupKey",version:1}],exact:!0,exists:!0,kind:"keyword"},queryId:{bindings:[{jsonPointer:"/queryId",version:1}],exact:!0,exists:!0,kind:"keyword"}},primaryTimestampField:"eventTime"}};function H(r){return{...r,snapshot:async e=>await re(r.url,e)}}async function K(r){let e={serverUrl:r.serverUrl,sqlitePath:r.sqlitePath,streamName:R,url:v(r.serverUrl,R)};await ne(e);let t=new k({debug:r.debug,streamUrl:e.url}),n=r.bridge.subscribe(s=>{t.enqueue(s)});return{close:async()=>{n(),await t.close()},experimental:e}}async function re(r,e){if(!r)return W();let t=await te(r);return _(t,e)}async function te(r){let e=await fetch(`${r}?offset=-1&format=json`,{headers:{connection:"close"}});if(!e.ok)throw new Error(`Failed to read ${r}: HTTP ${e.status}`);return await e.json()}var k=class{#t;#r;#e;constructor(e){this.#t=e.debug,this.#r=Promise.resolve(),this.#e=e.streamUrl}enqueue(e){e.length!==0&&(this.#r=this.#r.then(async()=>{await ie(this.#e,e),this.#t&&console.debug(`[streams] appended ${e.length} query insight record(s) to ${this.#e}`)}).catch(t=>{console.error("[streams] failed to ingest query insights into prisma-queries",t)}))}async close(){await this.#r}};async function ne(r){let e=await fetch(r.url,{headers:E,method:"PUT"});if(!e.ok)throw await P(e,`Failed to create ${r.streamName}`);let t=await ae(r);if(se(t,r.streamName))return;if(t.currentVersion>0)throw new Error(`Failed to install schema for ${r.streamName}: existing schema registry is incompatible and requires a lens migration`);let n=await fetch(`${r.url}/_schema`,{body:JSON.stringify(T),headers:E,method:"POST"});if(!n.ok)throw await P(n,`Failed to install schema for ${r.streamName}`)}function se(r,e){if(r.currentVersion<=0||r.schema!==e)return!1;let t=r.schemas[String(r.currentVersion)];return j(t,T.schema)&&j(r.search,T.search)}async function ae(r){let e=await fetch(`${r.url}/_schema`,{headers:E,method:"GET"});if(!e.ok)throw await P(e,`Failed to inspect schema for ${r.streamName}`);return await e.json()}async function ie(r,e){let t=await fetch(r,{body:JSON.stringify(e),headers:E,method:"POST"});if(!t.ok)throw await P(t,"Failed to append to prisma-queries")}async function P(r,e){let t=await r.text().catch(()=>"");return new Error(`${e}: HTTP ${r.status}${t?` ${t}`:""}`)}import{randomUUID as oe}from"crypto";import{setTimeout as L}from"timers/promises";import{isDeepStrictEqual as V}from"util";import{process as le}from"std-env";var ce="application/json",S={connection:"close","content-type":ce},ue={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},B={apiVersion:"durable.streams/schema-registry/v1",schema:{additionalProperties:!0,properties:{headers:{properties:{operation:{type:"string"},timestamp:{format:"date-time",type:"string"}},required:["timestamp","operation"],type:"object"},key:{type:"string"},type:{type:"string"}},required:["type","key","headers"],type:"object"},search:{aliases:{rowKey:"key",table:"type"},fields:{eventTime:{bindings:[{jsonPointer:"/headers/timestamp",version:1}],column:!0,exact:!0,exists:!0,kind:"date",sortable:!0},key:{bindings:[{jsonPointer:"/key",version:1}],exact:!0,exists:!0,kind:"keyword"},operation:{bindings:[{jsonPointer:"/headers/operation",version:1}],exact:!0,exists:!0,kind:"keyword"},type:{bindings:[{jsonPointer:"/type",version:1}],exact:!0,exists:!0,kind:"keyword"}},primaryTimestampField:"eventTime"}};async function G(r){let{dbServer:e,debug:t,name:n,persistenceMode:s,port:i,queryInsightsBridge:l,walBridge:a}=r,o=s==="stateless",c=o?Ee(n):n,u=I(c),p=!o&&await C(u);le.env.DS_LOCAL_DATA_ROOT=A(),o&&await y(u);let m=await de({debug:t,hadExistingStreamsData:p,name:c,port:i}),g={serverUrl:m.exports.http.url,sqlitePath:m.exports.sqlite.path,streamName:O,url:v(m.exports.http.url)};try{await he(g);let d=await K({bridge:l,debug:t,serverUrl:m.exports.http.url,sqlitePath:m.exports.sqlite.path}),h=new D({dbServer:e,debug:t,streamUrl:g.url}),z=a.subscribe(X=>{h.enqueue(X)});return{close:async()=>{z(),await h.close(),await d.close(),await m.close(),await L(100),o&&await y(u)},experimental:g,experimentalQueryInsights:d.experimental}}catch(d){throw await m.close().catch(()=>{}),await L(100),o&&await y(u).catch(()=>{}),d}}var me=["database disk image is malformed","duplicate column name:","file is not a database","malformed database schema","no such column:","no such table:","schema_version row missing after migration","unexpected schema version:"];async function de(r){let{debug:e,hadExistingStreamsData:t,name:n,port:s}=r,{startLocalDurableStreamsServer:i}=await import("@prisma/streams-local"),l=()=>i({hostname:"127.0.0.1",name:n,port:s});try{return await l()}catch(a){if(!t||!pe(a))throw a;return console.warn(`[streams] resetting incompatible durable streams data for "${n}"`),e&&console.debug(`[streams] original durable streams startup error for "${n}"`,a),await y(I(n)),await l()}}function pe(r){return ge(r).map(t=>t.toLowerCase()).some(t=>me.some(n=>t.includes(n)))}function ge(r){let e=[],t=[r],n=new Set;for(;t.length>0;){let s=t.shift();if(!(s==null||n.has(s))){if(n.add(s),typeof s=="string"){e.push(s);continue}if(s instanceof AggregateError)for(let i of s.errors)t.push(i);if(s instanceof Error){e.push(s.message);let i=s.cause;i!==void 0&&t.push(i)}}}return e}var D=class{#t;#r;#e;#n;#s;constructor(e){this.#t=e.dbServer,this.#r=e.debug,this.#e=Promise.resolve(),this.#n=e.streamUrl,this.#s=new Set}enqueue(e){e.length!==0&&(this.#e=this.#e.then(async()=>{let t=await this.#i(e);t.length!==0&&(await fe(this.#n,t),this.#r&&console.debug(`[streams] appended ${t.length} state-protocol record(s) to ${this.#n}`))}).catch(t=>{console.error("[streams] failed to ingest WAL events into prisma-wal",t)}))}async close(){await this.#e}async#i(e){let t=[],n=new Date().toISOString();for(let s of e)t.push(...await this.#o(s,n));return t}async#o(e,t){let n=`${e.schema}.${e.table}`,s=await this.#t.getPrimaryKeyColumns(e.schema,e.table),i=J(e.record),l=J(e.oldRecord),a=this.#a(n,s,l),o=this.#a(n,s,i),c=e.txid===""?void 0:e.txid;return e.type==="insert"?i&&o?[{headers:{operation:"insert",timestamp:t,txid:c},key:o,old_value:null,type:n,value:i}]:[]:e.type==="delete"?l&&a?[{headers:{operation:"delete",timestamp:t,txid:c},key:a,old_value:l,type:n,value:null}]:[]:!i||!l||!a||!o?[]:a!==o?[{headers:{operation:"delete",timestamp:t,txid:c},key:a,old_value:l,type:n,value:null},{headers:{operation:"insert",timestamp:t,txid:c},key:o,old_value:null,type:n,value:i}]:[{headers:{operation:"update",timestamp:t,txid:c},key:o,old_value:l,type:n,value:i}]}#a(e,t,n){if(!n)return null;let s=ve(n,t);return s||(this.#s.has(e)||(this.#s.add(e),console.warn(`[streams] falling back to full-row keys for ${e} because no primary key could be resolved`)),we(n))}};async function he(r){let e=await fetch(r.url,{headers:S,method:"PUT"});if(!e.ok)throw await f(e,`Failed to create ${r.streamName}`);let t=await fetch(`${r.url}/_profile`,{body:JSON.stringify(ue),headers:S,method:"POST"});if(!t.ok)throw await f(t,`Failed to configure ${r.streamName}`);let n=await ye(r);if(Se(n,r.streamName))return;if(n.currentVersion>0)throw new Error(`Failed to install schema for ${r.streamName}: existing schema registry is incompatible and requires a lens migration`);let s=await fetch(`${r.url}/_schema`,{body:JSON.stringify(B),headers:S,method:"POST"});if(!s.ok)throw await f(s,`Failed to install schema for ${r.streamName}`)}async function ye(r){let e=await fetch(`${r.url}/_schema`,{headers:S,method:"GET"});if(!e.ok)throw await f(e,`Failed to inspect schema for ${r.streamName}`);return await e.json()}function Se(r,e){if(r.currentVersion<=0||r.schema!==e)return!1;let t=r.schemas[String(r.currentVersion)];return V(t,B.schema)&&V(r.search,B.search)}async function fe(r,e){let t=await fetch(r,{body:JSON.stringify(e),headers:S,method:"POST"});if(!t.ok)throw await f(t,"Failed to append to prisma-wal")}async function f(r,e){let t=await r.text().catch(()=>"");return new Error(`${e}: HTTP ${r.status}${t?` ${t}`:""}`)}function ve(r,e){if(e.length===0)return null;let t=[];for(let n of e){if(!Object.prototype.hasOwnProperty.call(r,n))return null;let s=be(r[n]);if(s==null)return null;t.push(e.length===1?s:`${n}=${s}`)}return t.join("|")}function we(r){return JSON.stringify(Q(r))}function Q(r){return Array.isArray(r)?r.map(e=>Q(e)):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Q(t)])):r}function J(r){return r?structuredClone(r):null}function be(r){if(r===null)return"null";if(r===void 0)return"undefined";if(typeof r=="string")return r;if(typeof r=="number")return Number.isFinite(r)?String(r):null;if(typeof r=="bigint")return r.toString();if(typeof r=="boolean")return r?"true":"false";try{return JSON.stringify(r)}catch{return null}}function Ee(r){return`${r}.${oe().replaceAll("-","")}`}async function tr(r){let e=await M.createExclusively(r),t=null,n=null,s=null,i=null;try{[t,s]=await Promise.all([x("database",e),x("shadow_database",e)]);let l,a;e.dryRun?(l=Ie(),a=Te(),i=ke()):(l=await t.attachWalEventBridge(),a=await t.attachQueryInsightsBridge(),i=await G({dbServer:t,debug:e.debug,name:e.name,port:e.streamsPort,persistenceMode:e.persistenceMode,queryInsightsBridge:a,walBridge:l})),n=await F(t,e);let o=Pe(t,s,n,e);await e.writeServerDump(o,e.dryRun?{}:{queryInsights:i.experimentalQueryInsights,streams:i.experimental});let c=Re(l),u=H(i.experimentalQueryInsights),p=t,m=s,g=n,d=i,h=async()=>{c.close(),await Y(e,[g,d,p,m])};return{close:h,dbServer:t,httpServer:n,server:{...o,close:h,experimental:{queryInsights:u,streams:i.experimental,wal:c.api},name:e.name},serverState:e,shadowDbServer:s,streamsServer:i,queryInsightsBridge:a,walBridge:l}}catch(l){return await xe(e,[n,i,t,s],l)}}function Pe(r,e,t,n){let s=`prisma+postgres://localhost:${t.port}/?${new URLSearchParams({api_key:q({databaseUrl:r.prismaORMConnectionString,name:n.name,shadowDatabaseUrl:e.prismaORMConnectionString})}).toString()}`;return{database:{connectionString:r.connectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand},http:{url:t.url},ppg:{url:s},shadowDatabase:{connectionString:e.prismaORMConnectionString,prismaORMConnectionString:e.prismaORMConnectionString,terminalCommand:e.terminalCommand}}}async function Y(r,e){let t=[];for(let n of e)try{await n.close()}catch(s){t.push(s)}try{await r.close()}catch(n){t.push(n)}if(t.length>0)throw new AggregateError(t,"Failed to close some servers")}async function xe(r,e,t){try{await Y(r,e.filter(n=>n!==null))}catch(n){throw new AggregateError([t,n],"Failed to start Prisma Dev server cleanly")}throw t}function Re(r){let e=new Set;return{api:{stream:()=>{let t=()=>{},n=Be(r,()=>{e.delete(t)});return t=()=>n.close(),e.add(t),n.stream},subscribe:t=>r.subscribe(t)},close:()=>{for(let t of[...e])t();e.clear()}}}function Ie(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function Te(){return{async close(){},subscribe(){return()=>{}}}}function ke(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""},experimentalQueryInsights:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function Be(r,e){let t=[],n=!1,s=null,i=r.subscribe(a=>{if(!n){if(s){let o=s;s=null,o.resolve({done:!1,value:a});return}t.push(a)}}),l=()=>{if(!n&&(n=!0,i(),t.length=0,e(),s)){let a=s;s=null,a.resolve({done:!0,value:void 0})}};return{close:l,stream:{[Symbol.asyncIterator](){return this},next(){return t.length>0?Promise.resolve({done:!1,value:t.shift()}):n?Promise.resolve({done:!0,value:void 0}):new Promise((a,o)=>{s={reject:o,resolve:a}})},return(){return l(),Promise.resolve({done:!0,value:void 0})},throw(a){let o=s;return l(),o&&o.reject(a),Promise.reject(a instanceof Error?a:new Error(String(a)))}}}}var De="default";function Qe(r){return{databaseUrl:r.database.prismaORMConnectionString??r.database.connectionString,prismaPostgresUrl:r.ppg.url,shadowDatabaseUrl:r.shadowDatabase.prismaORMConnectionString??r.shadowDatabase.connectionString}}async function ir(r){let{debug:e,name:t=De}=r??{},n=await $(t,{debug:e});return!U(n)||!n.exports?null:{...Qe(n.exports),name:n.name}}export{tr as a,Qe as b,ir as c};
|
|
1
|
+
import{a as q}from"./chunk-662IKR3V.js";import{a as W,b as _,f as x}from"./chunk-MGHBCHO2.js";import{a as O,b as R,c as A,d as I,e as v,f as M,h as $,i as U}from"./chunk-GK3XD2W4.js";import{d as C,k as y}from"./chunk-ZEM5OLPM.js";import{b as N}from"./chunk-DOJAPHLY.js";import Z from"find-my-way";async function F(r,e){let{port:t}=e;if(e.dryRun)return{async close(){},port:t,url:`http://localhost:${t}`};let n=!!e.debug,[{registerAccelerateRoutes:s},{registerUtilityRoutes:i},{createHTTPServer:l}]=await Promise.all([import("./accelerate-KNP4MGMV.js"),import("./utility-YEFNU35E.js"),import("./server-QR7P25DP.js")]),a={databaseDumpPath:e.databaseDumpPath,db:r,debug:n,name:e.name,port:t,shadowDBPort:e.shadowDatabasePort},o=Z({defaultRoute(u,p){N(p,"Not Found",404)},ignoreTrailingSlash:!1});s(o,a,n),i(o,a,n);let c=await l({router:o}).listen(t);return e.port=c.port,a.port=c.port,{async close(){let{Engine:u}=await import("./engine-XTNCE4RM.js");await Promise.allSettled([c.close(),u.stopAll()])},port:c.port,url:c.url}}import{isDeepStrictEqual as j}from"util";var ee="application/json",E={connection:"close","content-type":ee},T={apiVersion:"durable.streams/schema-registry/v1",schema:{additionalProperties:!0,properties:{applicationName:{type:["string","null"]},durationMs:{type:"number"},groupKey:{type:["string","null"]},query:{type:"string"},queryId:{type:"string"},reads:{type:"number"},rowsReturned:{type:"number"},tables:{items:{type:"string"},type:"array"},timestamp:{format:"date-time",type:"string"}},required:["durationMs","query","queryId","reads","rowsReturned","tables","timestamp"],type:"object"},search:{aliases:{applicationName:"applicationName",groupKey:"groupKey",queryId:"queryId"},fields:{applicationName:{bindings:[{jsonPointer:"/applicationName",version:1}],exact:!0,exists:!0,kind:"keyword"},eventTime:{bindings:[{jsonPointer:"/timestamp",version:1}],column:!0,exact:!0,exists:!0,kind:"date",sortable:!0},groupKey:{bindings:[{jsonPointer:"/groupKey",version:1}],exact:!0,exists:!0,kind:"keyword"},queryId:{bindings:[{jsonPointer:"/queryId",version:1}],exact:!0,exists:!0,kind:"keyword"}},primaryTimestampField:"eventTime"}};function H(r){return{...r,snapshot:async e=>await re(r.url,e)}}async function K(r){let e={serverUrl:r.serverUrl,sqlitePath:r.sqlitePath,streamName:R,url:v(r.serverUrl,R)};await ne(e);let t=new k({debug:r.debug,streamUrl:e.url}),n=r.bridge.subscribe(s=>{t.enqueue(s)});return{close:async()=>{n(),await t.close()},experimental:e}}async function re(r,e){if(!r)return W();let t=await te(r);return _(t,e)}async function te(r){let e=await fetch(`${r}?offset=-1&format=json`,{headers:{connection:"close"}});if(!e.ok)throw new Error(`Failed to read ${r}: HTTP ${e.status}`);return await e.json()}var k=class{#t;#r;#e;constructor(e){this.#t=e.debug,this.#r=Promise.resolve(),this.#e=e.streamUrl}enqueue(e){e.length!==0&&(this.#r=this.#r.then(async()=>{await ie(this.#e,e),this.#t&&console.debug(`[streams] appended ${e.length} query insight record(s) to ${this.#e}`)}).catch(t=>{console.error("[streams] failed to ingest query insights into prisma-queries",t)}))}async close(){await this.#r}};async function ne(r){let e=await fetch(r.url,{headers:E,method:"PUT"});if(!e.ok)throw await P(e,`Failed to create ${r.streamName}`);let t=await ae(r);if(se(t,r.streamName))return;if(t.currentVersion>0)throw new Error(`Failed to install schema for ${r.streamName}: existing schema registry is incompatible and requires a lens migration`);let n=await fetch(`${r.url}/_schema`,{body:JSON.stringify(T),headers:E,method:"POST"});if(!n.ok)throw await P(n,`Failed to install schema for ${r.streamName}`)}function se(r,e){if(r.currentVersion<=0||r.schema!==e)return!1;let t=r.schemas[String(r.currentVersion)];return j(t,T.schema)&&j(r.search,T.search)}async function ae(r){let e=await fetch(`${r.url}/_schema`,{headers:E,method:"GET"});if(!e.ok)throw await P(e,`Failed to inspect schema for ${r.streamName}`);return await e.json()}async function ie(r,e){let t=await fetch(r,{body:JSON.stringify(e),headers:E,method:"POST"});if(!t.ok)throw await P(t,"Failed to append to prisma-queries")}async function P(r,e){let t=await r.text().catch(()=>"");return new Error(`${e}: HTTP ${r.status}${t?` ${t}`:""}`)}import{randomUUID as oe}from"crypto";import{setTimeout as L}from"timers/promises";import{isDeepStrictEqual as V}from"util";import{process as le}from"std-env";var ce="application/json",S={connection:"close","content-type":ce},ue={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},B={apiVersion:"durable.streams/schema-registry/v1",schema:{additionalProperties:!0,properties:{headers:{properties:{operation:{type:"string"},timestamp:{format:"date-time",type:"string"}},required:["timestamp","operation"],type:"object"},key:{type:"string"},type:{type:"string"}},required:["type","key","headers"],type:"object"},search:{aliases:{rowKey:"key",table:"type"},fields:{eventTime:{bindings:[{jsonPointer:"/headers/timestamp",version:1}],column:!0,exact:!0,exists:!0,kind:"date",sortable:!0},key:{bindings:[{jsonPointer:"/key",version:1}],exact:!0,exists:!0,kind:"keyword"},operation:{bindings:[{jsonPointer:"/headers/operation",version:1}],exact:!0,exists:!0,kind:"keyword"},type:{bindings:[{jsonPointer:"/type",version:1}],exact:!0,exists:!0,kind:"keyword"}},primaryTimestampField:"eventTime"}};async function G(r){let{dbServer:e,debug:t,name:n,persistenceMode:s,port:i,queryInsightsBridge:l,walBridge:a}=r,o=s==="stateless",c=o?Ee(n):n,u=I(c),p=!o&&await C(u);le.env.DS_LOCAL_DATA_ROOT=A(),o&&await y(u);let m=await de({debug:t,hadExistingStreamsData:p,name:c,port:i}),g={serverUrl:m.exports.http.url,sqlitePath:m.exports.sqlite.path,streamName:O,url:v(m.exports.http.url)};try{await he(g);let d=await K({bridge:l,debug:t,serverUrl:m.exports.http.url,sqlitePath:m.exports.sqlite.path}),h=new D({dbServer:e,debug:t,streamUrl:g.url}),z=a.subscribe(X=>{h.enqueue(X)});return{close:async()=>{z(),await h.close(),await d.close(),await m.close(),await L(100),o&&await y(u)},experimental:g,experimentalQueryInsights:d.experimental}}catch(d){throw await m.close().catch(()=>{}),await L(100),o&&await y(u).catch(()=>{}),d}}var me=["database disk image is malformed","duplicate column name:","file is not a database","malformed database schema","no such column:","no such table:","schema_version row missing after migration","unexpected schema version:"];async function de(r){let{debug:e,hadExistingStreamsData:t,name:n,port:s}=r,{startLocalDurableStreamsServer:i}=await import("@prisma/streams-local"),l=()=>i({hostname:"127.0.0.1",name:n,port:s});try{return await l()}catch(a){if(!t||!pe(a))throw a;return console.warn(`[streams] resetting incompatible durable streams data for "${n}"`),e&&console.debug(`[streams] original durable streams startup error for "${n}"`,a),await y(I(n)),await l()}}function pe(r){return ge(r).map(t=>t.toLowerCase()).some(t=>me.some(n=>t.includes(n)))}function ge(r){let e=[],t=[r],n=new Set;for(;t.length>0;){let s=t.shift();if(!(s==null||n.has(s))){if(n.add(s),typeof s=="string"){e.push(s);continue}if(s instanceof AggregateError)for(let i of s.errors)t.push(i);if(s instanceof Error){e.push(s.message);let i=s.cause;i!==void 0&&t.push(i)}}}return e}var D=class{#t;#r;#e;#n;#s;constructor(e){this.#t=e.dbServer,this.#r=e.debug,this.#e=Promise.resolve(),this.#n=e.streamUrl,this.#s=new Set}enqueue(e){e.length!==0&&(this.#e=this.#e.then(async()=>{let t=await this.#i(e);t.length!==0&&(await fe(this.#n,t),this.#r&&console.debug(`[streams] appended ${t.length} state-protocol record(s) to ${this.#n}`))}).catch(t=>{console.error("[streams] failed to ingest WAL events into prisma-wal",t)}))}async close(){await this.#e}async#i(e){let t=[],n=new Date().toISOString();for(let s of e)t.push(...await this.#o(s,n));return t}async#o(e,t){let n=`${e.schema}.${e.table}`,s=await this.#t.getPrimaryKeyColumns(e.schema,e.table),i=J(e.record),l=J(e.oldRecord),a=this.#a(n,s,l),o=this.#a(n,s,i),c=e.txid===""?void 0:e.txid;return e.type==="insert"?i&&o?[{headers:{operation:"insert",timestamp:t,txid:c},key:o,old_value:null,type:n,value:i}]:[]:e.type==="delete"?l&&a?[{headers:{operation:"delete",timestamp:t,txid:c},key:a,old_value:l,type:n,value:null}]:[]:!i||!l||!a||!o?[]:a!==o?[{headers:{operation:"delete",timestamp:t,txid:c},key:a,old_value:l,type:n,value:null},{headers:{operation:"insert",timestamp:t,txid:c},key:o,old_value:null,type:n,value:i}]:[{headers:{operation:"update",timestamp:t,txid:c},key:o,old_value:l,type:n,value:i}]}#a(e,t,n){if(!n)return null;let s=ve(n,t);return s||(this.#s.has(e)||(this.#s.add(e),console.warn(`[streams] falling back to full-row keys for ${e} because no primary key could be resolved`)),we(n))}};async function he(r){let e=await fetch(r.url,{headers:S,method:"PUT"});if(!e.ok)throw await f(e,`Failed to create ${r.streamName}`);let t=await fetch(`${r.url}/_profile`,{body:JSON.stringify(ue),headers:S,method:"POST"});if(!t.ok)throw await f(t,`Failed to configure ${r.streamName}`);let n=await ye(r);if(Se(n,r.streamName))return;if(n.currentVersion>0)throw new Error(`Failed to install schema for ${r.streamName}: existing schema registry is incompatible and requires a lens migration`);let s=await fetch(`${r.url}/_schema`,{body:JSON.stringify(B),headers:S,method:"POST"});if(!s.ok)throw await f(s,`Failed to install schema for ${r.streamName}`)}async function ye(r){let e=await fetch(`${r.url}/_schema`,{headers:S,method:"GET"});if(!e.ok)throw await f(e,`Failed to inspect schema for ${r.streamName}`);return await e.json()}function Se(r,e){if(r.currentVersion<=0||r.schema!==e)return!1;let t=r.schemas[String(r.currentVersion)];return V(t,B.schema)&&V(r.search,B.search)}async function fe(r,e){let t=await fetch(r,{body:JSON.stringify(e),headers:S,method:"POST"});if(!t.ok)throw await f(t,"Failed to append to prisma-wal")}async function f(r,e){let t=await r.text().catch(()=>"");return new Error(`${e}: HTTP ${r.status}${t?` ${t}`:""}`)}function ve(r,e){if(e.length===0)return null;let t=[];for(let n of e){if(!Object.prototype.hasOwnProperty.call(r,n))return null;let s=be(r[n]);if(s==null)return null;t.push(e.length===1?s:`${n}=${s}`)}return t.join("|")}function we(r){return JSON.stringify(Q(r))}function Q(r){return Array.isArray(r)?r.map(e=>Q(e)):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Q(t)])):r}function J(r){return r?structuredClone(r):null}function be(r){if(r===null)return"null";if(r===void 0)return"undefined";if(typeof r=="string")return r;if(typeof r=="number")return Number.isFinite(r)?String(r):null;if(typeof r=="bigint")return r.toString();if(typeof r=="boolean")return r?"true":"false";try{return JSON.stringify(r)}catch{return null}}function Ee(r){return`${r}.${oe().replaceAll("-","")}`}async function tr(r){let e=await M.createExclusively(r),t=null,n=null,s=null,i=null;try{[t,s]=await Promise.all([x("database",e),x("shadow_database",e)]);let l,a;e.dryRun?(l=Ie(),a=Te(),i=ke()):(l=await t.attachWalEventBridge(),a=await t.attachQueryInsightsBridge(),i=await G({dbServer:t,debug:e.debug,name:e.name,port:e.streamsPort,persistenceMode:e.persistenceMode,queryInsightsBridge:a,walBridge:l})),n=await F(t,e);let o=Pe(t,s,n,e);await e.writeServerDump(o,e.dryRun?{}:{queryInsights:i.experimentalQueryInsights,streams:i.experimental});let c=Re(l),u=H(i.experimentalQueryInsights),p=t,m=s,g=n,d=i,h=async()=>{c.close(),await Y(e,[g,d,p,m])};return{close:h,dbServer:t,httpServer:n,server:{...o,close:h,experimental:{queryInsights:u,streams:i.experimental,wal:c.api},name:e.name},serverState:e,shadowDbServer:s,streamsServer:i,queryInsightsBridge:a,walBridge:l}}catch(l){return await xe(e,[n,i,t,s],l)}}function Pe(r,e,t,n){let s=`prisma+postgres://localhost:${t.port}/?${new URLSearchParams({api_key:q({databaseUrl:r.prismaORMConnectionString,name:n.name,shadowDatabaseUrl:e.prismaORMConnectionString})}).toString()}`;return{database:{connectionString:r.connectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand},http:{url:t.url},ppg:{url:s},shadowDatabase:{connectionString:e.prismaORMConnectionString,prismaORMConnectionString:e.prismaORMConnectionString,terminalCommand:e.terminalCommand}}}async function Y(r,e){let t=[];for(let n of e)try{await n.close()}catch(s){t.push(s)}try{await r.close()}catch(n){t.push(n)}if(t.length>0)throw new AggregateError(t,"Failed to close some servers")}async function xe(r,e,t){try{await Y(r,e.filter(n=>n!==null))}catch(n){throw new AggregateError([t,n],"Failed to start Prisma Dev server cleanly")}throw t}function Re(r){let e=new Set;return{api:{stream:()=>{let t=()=>{},n=Be(r,()=>{e.delete(t)});return t=()=>n.close(),e.add(t),n.stream},subscribe:t=>r.subscribe(t)},close:()=>{for(let t of[...e])t();e.clear()}}}function Ie(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function Te(){return{async close(){},subscribe(){return()=>{}}}}function ke(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""},experimentalQueryInsights:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function Be(r,e){let t=[],n=!1,s=null,i=r.subscribe(a=>{if(!n){if(s){let o=s;s=null,o.resolve({done:!1,value:a});return}t.push(a)}}),l=()=>{if(!n&&(n=!0,i(),t.length=0,e(),s)){let a=s;s=null,a.resolve({done:!0,value:void 0})}};return{close:l,stream:{[Symbol.asyncIterator](){return this},next(){return t.length>0?Promise.resolve({done:!1,value:t.shift()}):n?Promise.resolve({done:!0,value:void 0}):new Promise((a,o)=>{s={reject:o,resolve:a}})},return(){return l(),Promise.resolve({done:!0,value:void 0})},throw(a){let o=s;return l(),o&&o.reject(a),Promise.reject(a instanceof Error?a:new Error(String(a)))}}}}var De="default";function Qe(r){return{databaseUrl:r.database.prismaORMConnectionString??r.database.connectionString,prismaPostgresUrl:r.ppg.url,shadowDatabaseUrl:r.shadowDatabase.prismaORMConnectionString??r.shadowDatabase.connectionString}}async function ir(r){let{debug:e,name:t=De}=r??{},n=await $(t,{debug:e});return!U(n)||!n.exports?null:{...Qe(n.exports),name:n.name}}export{tr as a,Qe as b,ir as c};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{e as b,f as g,g as M}from"./chunk-EDFHV3AK.js";import{a as C,c as h,g as V,h as q,i as U,j as J,k as p}from"./chunk-ZEM5OLPM.js";import{mkdir as ue,stat as le,writeFile as de}from"fs/promises";import{join as d}from"pathe";import{check as ce,lock as Y,unlock as me}from"proper-lockfile";import{process as z}from"std-env";import{integer as W,literal as he,minLength as R,minValue as ee,number as te,object as P,optional as c,parseJson as pe,pipe as m,safeParse as be,string as f,url as fe}from"valibot";import{setTimeout as oe}from"timers/promises";import{process as v}from"std-env";function _(r,e){if(r==null)return!1;try{return v.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}async function B(r,e){if(!v.kill)return!1;try{v.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 oe(100)}while(++t<50);try{return v.kill(r,"SIGKILL")}catch(a){return e&&console.error(`Error forcefully killing process with PID ${r}:`,a),!1}}import{join as H}from"pathe";var ie="prisma-wal",Ie="prisma-queries";function ne(){return H(C.data,"durable-streams")}function K(r){return H(ne(),r)}function Re(r,e=ie){return new URL(`/v1/stream/${encodeURIComponent(e)}`,r).toString()}var S=m(f(),fe()),G=P({connectionString:S,prismaORMConnectionString:c(S),terminalCommand:c(f())}),Q=P({url:S}),X=P({serverUrl:S,sqlitePath:m(f(),R(1)),streamName:m(f(),R(1)),url:S}),Pe=P({queryInsights:c(X),streams:c(X)}),k=m(te(),W(),ee(1)),ge=P({database:G,http:Q,ppg:Q,shadowDatabase:G}),we=P({databasePort:k,experimental:c(Pe),exports:c(ge),name:m(f(),R(1)),pid:c(m(te(),W(),ee(0))),port:k,shadowDatabasePort:k,version:he("1")}),L=Symbol("initialize"),Se=1e4,E="default",ye=new Set(["durable-streams"]);function Z(r){return r instanceof Error&&"code"in r&&r.code==="ELOCKED"}async function I(r){try{return await le(r)}catch(e){if(V(e))return null;throw e}}var u=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;_streamsPort;constructor(e){this._databasePort=e.databasePort??g,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??E,this.persistenceMode=e.persistenceMode,this.pid=e.pid??z.pid,this.shadowDatabaseConnectTimeoutMillis=e.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=e.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=e.port??g,this._shadowDatabasePort=e.shadowDatabasePort??g,this._streamsPort=e.streamsPort??g}static async createExclusively(e){let t=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new w(e):new T(e);return await t[L](),t}static async fromServerDump(e){let{debug:t,name:a=E}=e??{},o=h(a),i=w.getServerDumpPath(o),s=await q(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:l,success:y}=be(m(f(),pe(),we),s);if(!y)throw t&&console.debug(`[State] Invalid server dump file at "${i}":
|
|
2
|
+
${JSON.stringify(n,null,2)}`),new Error(`Invalid Prisma Dev state for "${a}".`);return new w({databasePort:l.databasePort,debug:t,dryRun:!1,name:a,pid:l.pid,port:l.port,serverDump:l,shadowDatabasePort:l.shadowDatabasePort})}static async scan(e){let{debug:t,globs:a}=e??{},o=d(h(E),"..");t&&console.debug(`[State] scanning for server states in: ${o}`);let i=(await J(o,a)).filter(s=>!ye.has(s));return t&&console.debug(`[State] found server names: ${JSON.stringify(i)}`),await Promise.all(i.map(s=>N(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]!==b&&this[a]!==t)throw new Error(`\`${e}\` is already set to ${this[a]}, cannot change it to ${t}`);this[a]=t}},T=class extends u{constructor(e){super({...e,databasePort:e?.databasePort||b,persistenceMode:"stateless",port:e?.port||b,shadowDatabasePort:e?.shadowDatabasePort||b,streamsPort:e?.streamsPort||b})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[L](){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(){}},w=class r extends u{#t;#o;#e;#r;#i;#n;#s;#a;constructor(e){super({...e,persistenceMode:"stateful"}),this.#s=!1,this.#e=h(this.name),this.#t=d(this.#e,".lock-break"),this.#o=d(this.#e,"db_dump.bak"),this.#r=d(this.#e,".lock"),this.#i=d(this.#e,".pglite"),this.#a=e?.serverDump??null,this.#n=r.getServerDumpPath(this.#e)}static getServerDumpPath(e){return d(e,"server.json")}get databaseDumpPath(){return this.#o}get exports(){return this.#a?.exports}get experimental(){return this.#a?.experimental}get pgliteDataDirPath(){return this.#i}async[L](){await U(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await this.#u(),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 Z(e)?new O(this):e}}async#u(){try{await Y(this.#e,{lockfilePath:this.#r});return}catch(e){if(!Z(e)||!await this.#l())throw e}await Y(this.#e,{lockfilePath:this.#r})}async#l(){let e=await I(this.#r);if(e==null)return!0;let t=await N(this.name,{debug:this.debug});if(re(t)||t.status==="unknown"||!await this.#d())return!1;try{let a=await I(this.#r);return a==null?!0:a.ino!==e.ino||a.mtimeMs!==e.mtimeMs?!1:(this.debug&&console.debug(`[State] breaking lock left behind by dead server "${this.name}" (status: ${t.status})`),await p(this.#r),!0)}finally{await p(this.#t)}}async#d(){for(let e=0;e<2;e++){try{return await ue(this.#t),!0}catch(a){if(!(a instanceof Error&&"code"in a&&a.code==="EEXIST"))throw a}let t=await I(this.#t);if(t!=null&&Date.now()-t.mtimeMs<Se)return!1;await p(this.#t)}return!1}async close(){if(!this.#s)try{await me(this.#e,{lockfilePath:this.#r}),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.#a={name:this.name,version:"1",pid:z.pid,port:this.port,databasePort:this.databasePort,experimental:t,shadowDatabasePort:this.shadowDatabasePort,exports:e},await de(this.#n,`${JSON.stringify(this.#a,null,2)}
|
|
3
|
+
`,{encoding:"utf-8"})}};async function Fe(r,e){await ve(r,e);let t=typeof r=="string"?r:r.name,a=h(t);await p(a),await p(K(t))}async function N(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:l,pid:y}=n;if(a)return{...s,status:"unknown"};if(!_(y,t))return t&&console.debug(`[State] server state for "${o}" has no running process with PID: ${y}`),{...s,status:"not_running"};let A=h(o);try{if(!await ce(A,{lockfilePath:d(A,".lock")}))return t&&console.debug(`[State] server state for "${o}" is not locked, indicating it is not running.`),{...s,status:"not_running"}}catch(se){t&&console.error(`[State] server state for "${o}" failed to check lock:`,se)}if(!l)return{...s,status:"starting_up"};let{http:ae}=l,D=await fetch(`${ae.url}/health`,{headers:{connection:"close"}});if(!D.ok)return t&&console.debug(`[State] server state for "${o}" is not live: ${JSON.stringify(D)}`),{...s,status:"not_running"};let x=await D.json();return x.name!==r?(t&&console.debug(`[State] server state for "${o}" has mismatched health response: ${JSON.stringify(x)}`),{...s,status:"unknown"}):(t&&console.debug(`[State] server state for "${r}" is live: ${JSON.stringify(x)}`),{...s,status:"running"})}catch(n){return t&&console.error(`[State] failed to get server status for "${o}":`,n),{...s,status:"error"}}}function re(r){let{status:e}=r;return e==="running"||e==="starting_up"}async function ve(r,e){let{pid:t,...a}=typeof r=="string"?await N(r,{debug:e}):r;if(!re(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 B(t,e);try{await o?.close()}catch{}return i}var $=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},O=class extends ${#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{ie as a,Ie as b,ne as c,K as d,Re as e,u as f,Fe as g,N as h,re as i,ve as j,$ as k,O as l};
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import{c as I}from"./chunk-KWCQYPJI.js";import{h as _}from"./chunk-EDFHV3AK.js";import{d as O,f as Q}from"./chunk-ZEM5OLPM.js";import{createConnection as He,createServer as Ye}from"net";import{join as Ke}from"path";import{filename as ze}from"pathe/utils";import{performance as H}from"perf_hooks";import{protocol as he}from"@electric-sql/pglite";import{Buffer as pe}from"buffer";var C=500,F=/(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+)/,ge=new RegExp(`(?:${F.source}\\.)*${F.source}`),fe=new RegExp(`(?:FROM|JOIN|UPDATE|INTO|TABLE)\\s+(${ge.source})`,"gi"),ye=/"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|(\w+)/g,$=/prismaQuery='([^']+)'/,Ee=new Set([b(`
|
|
2
|
+
select b.oid, b.typarray
|
|
3
|
+
from pg_catalog.pg_type a
|
|
4
|
+
left join pg_catalog.pg_type b on b.oid = a.typelem
|
|
5
|
+
where a.typcategory = $1
|
|
6
|
+
group by b.oid, b.typarray
|
|
7
|
+
order by b.oid
|
|
8
|
+
`),b('GRANT "pg_write_all_data" TO "prisma_application"'),b("SELECT SUM(reads)::BIGINT AS reads, SUM(writes)::BIGINT AS writes, SUM(COALESCE(extends, $1))::BIGINT AS extends FROM pg_stat_io"),b("SELECT pg_database_size(current_database())::BIGINT, SUM(pg_total_relation_size(relid))::BIGINT AS pg_total_relation_size FROM pg_stat_user_tables"),b("SELECT COUNT(*) AS cnt FROM pg_stat_activity WHERE pid <> pg_backend_pid() and xact_start notnull")]),be=[/^BEGIN\b/i,/^COMMIT\b/i,/^ROLLBACK\b/i,/^SAVEPOINT\b/i,/^RELEASE\b/i,/^SET\b/i,/^SHOW\b/i,/^DISCARD\b/i,/^DEALLOCATE\b/i,/^CLOSE\b/i,/^CREATE EXTENSION\b/i,/^WITH state_assign\b/i];function at(){return{generatedAt:Date.now(),queries:[]}}function b(e){return e.replace(/\s+/g," ").trim()}function k(e){return W(b(e))}function G(e){if(!e?.action||!e.model&&/raw/i.test(e.action))return null;let t=e.payload?W(JSON.stringify(e.payload)):"0";return`${e.model??""}.${e.action}:${t}`}function Se(e){let t=new Set;for(let r of e.matchAll(fe)){let n=r[1];if(!n)continue;let a;for(let o of n.matchAll(ye))a=o[1]??o[2]??o[3]??o[4];a&&!a.startsWith("pg_")&&t.add(a)}return Array.from(t)}function we(e){return Ee.has(e)?!0:be.some(t=>t.test(e))}function q(e){if(we(b(e)))return null;let t=Se(e);return t.length===0&&/\bpg_\w+/i.test(e)?null:t}function x(e){if(Array.isArray(e))return e.map(x);if(e!==null&&typeof e=="object"){let t=e;return t.$type==="Param"?"<<redacted>>":Object.fromEntries(Object.entries(t).map(([r,n])=>[r,x(n)]))}return e}function U(e){let t=e.match($);if(!t?.[1])return{cleanedSql:b(e),prismaQueryInfo:null};let r=e.replace($,"");r=r.replace(/,\s*,/g,",").replace(/\/\*\s*,/g,"/*").replace(/,\s*\*\//g,"*/").replace(/\/\*\s*\*\//g,"").replace(/\s+/g," ").trim();let n=decodeURIComponent(t[1]),a=n.indexOf(":");if(a===-1)return{cleanedSql:r,prismaQueryInfo:{action:n,isRaw:!0}};let o=n.slice(0,a),d=n.slice(a+1),s=o.indexOf("."),u=s===-1?void 0:o.slice(0,s),c=s===-1?o:o.slice(s+1);if(!c)return{cleanedSql:r,prismaQueryInfo:null};let i;try{i=x(JSON.parse(pe.from(d,"base64url").toString("utf8")))}catch{i=void 0}return{cleanedSql:r,prismaQueryInfo:{action:c,isRaw:!1,model:u,payload:i}}}function ot(e,t={}){let r=new Set(t.excludeApplications??[]),n=Pe(t.limit),a=typeof t.since=="number"&&Number.isFinite(t.since)?t.since:null,o=new Map;for(let s of e){if(s.applicationName&&r.has(s.applicationName))continue;let u=Date.parse(s.timestamp);if(!Number.isFinite(u))continue;let c=`${s.queryId}:${s.groupKey??""}`,i=o.get(c);if(!i){o.set(c,{count:1,duration:s.durationMs,groupKey:s.groupKey,id:c,lastSeen:u,maxDurationMs:s.durationMs,minDurationMs:s.durationMs,prismaQueryInfo:s.prismaQueryInfo,query:s.query,queryId:s.queryId,reads:s.reads,rowsReturned:s.rowsReturned,tables:s.tables,totalDurationMs:s.durationMs});continue}i.count+=1,i.lastSeen=Math.max(i.lastSeen,u),i.maxDurationMs=Math.max(i.maxDurationMs??s.durationMs,s.durationMs),i.minDurationMs=Math.min(i.minDurationMs??s.durationMs,s.durationMs),i.reads+=s.reads,i.rowsReturned+=s.rowsReturned,i.totalDurationMs+=s.durationMs,i.duration=i.totalDurationMs/i.count,!i.prismaQueryInfo&&s.prismaQueryInfo&&(i.prismaQueryInfo=s.prismaQueryInfo),i.tables.length===0&&s.tables.length>0&&(i.tables=s.tables)}let d=Array.from(o.values()).filter(s=>a===null||s.lastSeen>=a).sort((s,u)=>u.lastSeen-s.lastSeen).slice(0,n).map(({totalDurationMs:s,...u})=>u);return{generatedAt:Date.now(),queries:d}}function Pe(e){return typeof e=="number"&&Number.isInteger(e)&&Number.isSafeInteger(e)&&e>0?Math.min(e,C):C}function W(e){let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t+e.charCodeAt(r)&4294967295;return(t>>>0).toString(36)}function T(e){let t=e.queryQueue;if(!t||typeof t.enqueue!="function"||typeof t.clearQueueForHandler!="function")throw new Error("PGLiteSocketServer query queue is unavailable");return t}var R=new WeakMap;function Y(e){let t=R.get(e);if(t&&!t.closed)return t.bridge;let r=T(e),n={bridge:{close:()=>(n.closed||(n.closed=!0,n.sessions.clear(),n.subscribers.clear(),n.queryQueue.enqueue=n.originalEnqueue,n.queryQueue.clearQueueForHandler=n.originalClearQueueForHandler,R.delete(e)),Promise.resolve()),subscribe:a=>(n.subscribers.add(a),()=>{n.subscribers.delete(a)})},closed:!1,originalClearQueueForHandler:r.clearQueueForHandler.bind(r),originalEnqueue:r.enqueue.bind(r),queryQueue:r,sessions:new Map,subscribers:new Set};return r.clearQueueForHandler=a=>{n.sessions.delete(a),n.originalClearQueueForHandler(a)},r.enqueue=async(a,o,d)=>{let s=Te(n,a),u=_e(o);Re(s,u);let c=Ne(s,u);if(!c)return await n.originalEnqueue(a,o,d);let i={commandTags:[],dataRowCount:0},f=new he.Parser,l=H.now(),m=await n.originalEnqueue(a,o,S=>{f.parse(S,me=>{Be(i,me)}),d(S)}),g=Math.max(0,H.now()-l);return Le(n,{applicationName:c.applicationName,durationMs:g,query:c.query,responseStats:i}),m},R.set(e,n),n.bridge}async function K(e){await R.get(e)?.bridge.close()}function Te(e,t){let r=e.sessions.get(t);if(r)return r;let n={applicationName:null,portals:new Map,statements:new Map};return e.sessions.set(t,n),n}function Re(e,t){if(t)switch(t.kind){case"startup":e.applicationName=t.applicationName;return;case"parse":e.statements.set(t.statementName,t.query);return;case"bind":{let r=e.statements.get(t.statementName);r&&e.portals.set(t.portalName,r);return}case"close":t.target==="portal"?e.portals.delete(t.name):e.statements.delete(t.name);return;default:return}}function Ne(e,t){if(!t)return null;if(t.kind==="query")return{applicationName:e.applicationName,query:t.query};if(t.kind==="execute"){let r=e.portals.get(t.portalName);return r?{applicationName:e.applicationName,query:r}:null}return null}function _e(e){let t=Buffer.from(e);if(t.length<4)return null;let r=t.readInt32BE(0);if(t.length>=8&&r===t.length){let a=t.readInt32BE(4);if(a===196608||a===196608)return Ie(t)}if(t.length<5)return null;switch(String.fromCharCode(t[0]??0)){case"Q":return xe(t);case"P":return Ae(t);case"B":return De(t);case"E":return ve(t);case"C":return Me(t);default:return null}}function Ie(e){let t=8,r=null;for(;t<e.length-1;){let n=E(e,t);if(!n||n.value==="")break;t=n.nextOffset;let a=E(e,t);if(!a)break;t=a.nextOffset,n.value==="application_name"&&(r=a.value)}return{applicationName:r,kind:"startup"}}function xe(e){let t=E(e,5);return t?{kind:"query",query:t.value}:null}function Ae(e){let t=E(e,5);if(!t)return null;let r=E(e,t.nextOffset);return r?{kind:"parse",query:r.value,statementName:t.value}:null}function De(e){let t=E(e,5);if(!t)return null;let r=E(e,t.nextOffset);return r?{kind:"bind",portalName:t.value,statementName:r.value}:null}function ve(e){let t=E(e,5);return t?{kind:"execute",portalName:t.value}:null}function Me(e){if(e.length<7)return null;let t=e[5];if(t===void 0)return null;let r=E(e,6);return r?{kind:"close",name:r.value,target:t===80?"portal":"statement"}:null}function E(e,t){let r=e.indexOf(0,t);return r===-1?null:{nextOffset:r+1,value:e.toString("utf8",t,r)}}function Be(e,t){if(t.name==="dataRow"){e.dataRowCount+=1;return}t.name==="commandComplete"&&typeof t.text=="string"&&t.text.length>0&&e.commandTags.push(t.text)}function Le(e,t){let r=U(t.query),n=q(r.cleanedSql);if(!n)return;let a=k(r.cleanedSql),o={applicationName:t.applicationName,durationMs:t.durationMs,groupKey:G(r.prismaQueryInfo),prismaQueryInfo:r.prismaQueryInfo,query:r.cleanedSql,queryId:a,reads:0,rowsReturned:Oe(t.responseStats),tables:n,timestamp:new Date().toISOString()};for(let d of e.subscribers)d([o])}function Oe(e){let t=e.commandTags.reduce((r,n)=>r+Qe(n),0);return Math.max(t,e.dataRowCount)}function Qe(e){let t=e.trim().split(/\s+/).at(-1);return!t||!/^\d+$/.test(t)?0:Number(t)}var Ce=new Set([66,67,68,69,72,80,100]),Fe=90;function $e(e){let t=e[0];return t!==void 0&&Ce.has(t)}function ke(){let e=Buffer.alloc(0);return{filter(t,r){e=e.length===0?Buffer.from(t):Buffer.concat([e,t]);let n=[],a=0;for(;e.length-a>=5;){let d=1+e.readInt32BE(a+1);if(d<5){n.push(e.subarray(a)),a=e.length;break}if(e.length-a<d)break;r&&e[a]===Fe||n.push(e.subarray(a,a+d)),a+=d}e=e.subarray(a);let o=n[0];return n.length===1&&o?o:Buffer.concat(n)},get holdsPartialFrame(){return e.length>0}}}function z(e){let t=T(e),r=t.enqueue.bind(t),n=t.clearQueueForHandler.bind(t),a=new Map;t.clearQueueForHandler=o=>{a.delete(o),n(o)},t.enqueue=async(o,d,s)=>{let u=$e(d),c=a.get(o);if(!u&&!c)return await r(o,d,s);c||(c=ke(),a.set(o,c));let i=c;try{return await r(o,d,f=>{let l=i.filter(f,u);l.length>0&&s(l)})}finally{i.holdsPartialFrame||a.delete(o)}}}import{protocol as j}from"@electric-sql/pglite";var y="_prisma_dev_wal",D="events",V="install_all_triggers",J="capture_event",X="prisma_dev_wal_capture",h=new WeakMap,Ge=new Set(["ALTER","COMMIT","COPY","CREATE","DELETE","DROP","INSERT","MERGE","TRUNCATE","UPDATE"]);async function v(e,t){let r=h.get(e);if(r&&!r.closed)return r.bridge;let n=e.execProtocolRaw.bind(e),a=e.execProtocolRawStream.bind(e),o={bridge:{close:async()=>{o.closed||(o.closed=!0,o.subscribers.clear(),e.execProtocolRaw===d&&(e.execProtocolRaw=n),e.execProtocolRawStream===s&&(e.execProtocolRawStream=a),await o.pollPromise,h.delete(e))},poll:async()=>{await A(o,e)},subscribe:u=>(o.subscribers.add(u),()=>{o.subscribers.delete(u)})},closed:!1,ensureInfrastructurePromise:null,pendingPoll:!1,pollPromise:null,subscribers:new Set,suppressDepth:0},d=async(u,c)=>{let i=await n(u,c);return!o.closed&&o.suppressDepth===0&&ee(i)&&A(o,e),i},s=async(u,c)=>{let i=[],f=new j.Parser,l=c?.onRawData;await a(u,{...c,onRawData:m=>{f.parse(m,g=>{i.push(g)}),l?.(m)}}),!o.closed&&o.suppressDepth===0&&M(i)&&A(o,e)};return e.execProtocolRaw=d,e.execProtocolRawStream=s,h.set(e,o),await te(o,e),o.bridge}async function Z(e){let t=h.get(e);t&&await t.bridge.close()}function M(e){for(let t of e){if(t.name!=="commandComplete"||typeof t.text!="string")continue;let r=t.text.split(/\s+/,1)[0]?.toUpperCase();if(r&&Ge.has(r))return!0}return!1}function ee(e){if(e.length===0)return!1;let t=[];return new j.Parser().parse(e,n=>{t.push(n)}),M(t)}async function te(e,t){e.ensureInfrastructurePromise??=B(e,t,async()=>{await t.exec(`CREATE SCHEMA IF NOT EXISTS "${y}"`),await t.exec(`
|
|
9
|
+
CREATE TABLE IF NOT EXISTS "${y}"."${D}" (
|
|
10
|
+
id BIGSERIAL PRIMARY KEY,
|
|
11
|
+
txid BIGINT NOT NULL DEFAULT txid_current(),
|
|
12
|
+
schema_name TEXT NOT NULL,
|
|
13
|
+
table_name TEXT NOT NULL,
|
|
14
|
+
op TEXT NOT NULL,
|
|
15
|
+
row_data JSONB,
|
|
16
|
+
old_row_data JSONB,
|
|
17
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()
|
|
18
|
+
)
|
|
19
|
+
`),await t.exec(`
|
|
20
|
+
CREATE OR REPLACE FUNCTION "${y}"."${J}"()
|
|
21
|
+
RETURNS trigger
|
|
22
|
+
LANGUAGE plpgsql
|
|
23
|
+
AS $$
|
|
24
|
+
BEGIN
|
|
25
|
+
IF TG_TABLE_SCHEMA = '${y}' THEN
|
|
26
|
+
RETURN COALESCE(NEW, OLD);
|
|
27
|
+
END IF;
|
|
28
|
+
|
|
29
|
+
INSERT INTO "${y}"."${D}" (
|
|
30
|
+
txid,
|
|
31
|
+
schema_name,
|
|
32
|
+
table_name,
|
|
33
|
+
op,
|
|
34
|
+
row_data,
|
|
35
|
+
old_row_data
|
|
36
|
+
)
|
|
37
|
+
VALUES (
|
|
38
|
+
txid_current(),
|
|
39
|
+
TG_TABLE_SCHEMA,
|
|
40
|
+
TG_TABLE_NAME,
|
|
41
|
+
lower(TG_OP),
|
|
42
|
+
CASE WHEN TG_OP IN ('INSERT', 'UPDATE') THEN to_jsonb(NEW) ELSE NULL END,
|
|
43
|
+
CASE WHEN TG_OP IN ('UPDATE', 'DELETE') THEN to_jsonb(OLD) ELSE NULL END
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
RETURN COALESCE(NEW, OLD);
|
|
47
|
+
END;
|
|
48
|
+
$$;
|
|
49
|
+
`),await t.exec(`
|
|
50
|
+
CREATE OR REPLACE FUNCTION "${y}"."${V}"()
|
|
51
|
+
RETURNS void
|
|
52
|
+
LANGUAGE plpgsql
|
|
53
|
+
AS $$
|
|
54
|
+
DECLARE
|
|
55
|
+
target REGCLASS;
|
|
56
|
+
BEGIN
|
|
57
|
+
FOR target IN
|
|
58
|
+
SELECT c.oid::regclass
|
|
59
|
+
FROM pg_class AS c
|
|
60
|
+
JOIN pg_namespace AS n ON n.oid = c.relnamespace
|
|
61
|
+
WHERE c.relkind IN ('r', 'p')
|
|
62
|
+
AND n.nspname NOT IN ('${y}', 'information_schema', 'pg_catalog')
|
|
63
|
+
AND n.nspname NOT LIKE 'pg_temp_%'
|
|
64
|
+
AND n.nspname NOT LIKE 'pg_toast%'
|
|
65
|
+
LOOP
|
|
66
|
+
IF EXISTS (
|
|
67
|
+
SELECT 1
|
|
68
|
+
FROM pg_trigger
|
|
69
|
+
WHERE tgrelid = target
|
|
70
|
+
AND tgname = '${X}'
|
|
71
|
+
) THEN
|
|
72
|
+
CONTINUE;
|
|
73
|
+
END IF;
|
|
74
|
+
|
|
75
|
+
EXECUTE format(
|
|
76
|
+
'CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION "${y}"."${J}"()',
|
|
77
|
+
'${X}',
|
|
78
|
+
target::text
|
|
79
|
+
);
|
|
80
|
+
END LOOP;
|
|
81
|
+
END;
|
|
82
|
+
$$;
|
|
83
|
+
`),await re(e,t)}),await e.ensureInfrastructurePromise}async function re(e,t){await B(e,t,async()=>{await t.query(`SELECT "${y}"."${V}"()`)})}async function qe(e,t){await te(e,t),await re(e,t);let r=await B(e,t,async()=>await t.query(`
|
|
84
|
+
WITH drained AS (
|
|
85
|
+
DELETE FROM "${y}"."${D}"
|
|
86
|
+
RETURNING txid, schema_name, table_name, op, row_data, old_row_data, id
|
|
87
|
+
)
|
|
88
|
+
SELECT txid, schema_name, table_name, op, row_data, old_row_data
|
|
89
|
+
FROM drained
|
|
90
|
+
ORDER BY id
|
|
91
|
+
`));if(r.rows.length===0||e.subscribers.size===0)return;let n=r.rows.map(Ue);for(let a of e.subscribers)queueMicrotask(()=>{if(!e.closed&&e.subscribers.has(a))try{a(n)}catch(o){console.error("[WAL bridge] subscriber failed",o)}})}async function A(e,t){if(!e.closed){if(e.pollPromise){e.pendingPoll=!0,await e.pollPromise;return}e.pollPromise=(async()=>{do e.pendingPoll=!1,await qe(e,t);while(e.pendingPoll&&!e.closed)})().finally(()=>{e.pollPromise=null}),await e.pollPromise}}async function B(e,t,r){e.suppressDepth+=1;try{return await r()}finally{e.suppressDepth-=1,e.suppressDepth===0&&!e.closed&&h.get(t)!==e&&(e.closed=!0)}}function Ue(e){return{oldRecord:e.old_row_data,record:e.row_data,schema:e.schema_name,table:e.table_name,txid:String(e.txid),type:We(e.op)}}function We(e){switch(e.toLowerCase()){case"delete":return"delete";case"insert":return"insert";case"update":return"update";default:throw new Error(`Unsupported WAL bridge operation: ${e}`)}}var Je=10,ae="127.0.0.1",oe=128*1024*1024,se=["-c","shared_buffers=16MB","-c","temp_buffers=1MB","-c","work_mem=1MB","-c","maintenance_work_mem=16MB","-c","wal_buffers=1MB"],p={connectionLimit:Je,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},Xe=`postgres://${p.username}:${p.password}@localhost`,L=new URLSearchParams({sslmode:p.sslMode}),ie=new URLSearchParams({...Object.fromEntries(L.entries()),connection_limit:String(p.connectionLimit),connect_timeout:String(p.connectTimeout),max_idle_connection_lifetime:String(p.maxIdleConnectionLifetime),pool_timeout:String(p.poolTimeout),socket_timeout:String(p.socketTimeout)});async function le(e){let{rows:t}=await e.query("SELECT EXISTS(SELECT 1 FROM pg_roles WHERE rolname = 'postgres') AS exists");t[0]?.exists?await e.exec(`ALTER ROLE ${p.username} WITH LOGIN SUPERUSER PASSWORD '${p.password}'`):await e.exec(`CREATE ROLE ${p.username} WITH LOGIN SUPERUSER PASSWORD '${p.password}'`),await e.exec(`SET ROLE ${p.username}`)}async function vt(e,t){if(e==="shadow_database"&&!t.dryRun)return await je(t);let r=e==="database"?t.databasePort:t.shadowDatabasePort;return t.dryRun?ce(e,t,{db:null,port:r,server:null}):await ue(e,t,{port:r,updateServerStatePort:!0})}async function je(e,t=async()=>await ue("shadow_database",e,{port:0,updateServerStatePort:!1})){let{debug:r}=e,n=null,a=null,o=!1,d=new Set,s=Ye(c),u=await Ve(s,e.shadowDatabasePort);return e.shadowDatabasePort=u,r&&console.debug(`[shadow_database] lazy proxy listening on port ${u}`),{...p,attachWalEventBridge:()=>Promise.reject(new Error("WAL bridge is only available for the primary database server")),attachQueryInsightsBridge:()=>Promise.reject(new Error("Query insights are only available for the primary database server")),close:async()=>{o=!0;for(let m of d)m.destroy();d.clear();let l=[];try{await Ze(s),r&&console.debug(`[shadow_database] lazy proxy stopped on port ${u}`)}catch(m){console.error("[shadow_database] lazy proxy stop error",m),l.push(m)}try{await a?.catch(()=>null),await n?.close()}catch(m){console.error("[shadow_database] backend close error",m),l.push(m)}if(l.length>0)throw new AggregateError(l,"Failed to close shadow_database properly")},connectionString:N(u,L),dump:async()=>{},getPrimaryKeyColumns:()=>Promise.reject(new Error("Primary key resolution is only available for the primary database server")),port:u,prismaORMConnectionString:N(u,ie),terminalCommand:`PGPASSWORD=${p.password} PGSSLMODE=${p.sslMode} psql -h localhost -p ${u} -U ${p.username} -d ${p.database}`};function c(l){d.add(l);let m=()=>{d.delete(l)};l.once("close",m),l.once("error",m),l.pause(),i(l)}async function i(l){try{let m=await f();if(o){l.destroy();return}let g=He({host:ae,port:m.port});d.add(g);let S=()=>{d.delete(g)};g.once("close",S),g.once("error",S),l.once("close",()=>g.destroy()),l.once("error",()=>g.destroy()),g.once("error",()=>l.destroy()),g.once("connect",()=>{r&&console.debug(`[shadow_database] proxying connection to lazy backend on port ${m.port}`),l.resume(),l.pipe(g),g.pipe(l)})}catch(m){r&&console.error("[shadow_database] failed to start lazy backend",m),l.destroy(m instanceof Error?m:void 0)}}async function f(){if(n)return n;if(o)throw new Error("shadow_database is closed");return a||(r&&console.debug("[shadow_database] starting lazy backend..."),a=t().then(l=>(n=l,r&&console.debug(`[shadow_database] lazy backend started on port ${l.port}`),l)).catch(l=>{throw a=null,l})),await a}}async function ue(e,t,r){let{debug:n}=t,{port:a,updateServerStatePort:o}=r,s=await(e==="shadow_database"?et:de)(t.pgliteDataDirPath,n);n&&s.onNotification((l,m)=>{console.debug(`[${e}][${l}] ${m}`)});let{PGLiteSocketServer:u}=await import("@electric-sql/pglite-socket"),c=e==="shadow_database"?t.shadowDatabaseIdleTimeoutMillis:t.databaseIdleTimeoutMillis,i=new u({db:s,debug:n,idleTimeout:Number.isFinite(c)?c:0,inspect:n,maxConnections:p.connectionLimit,port:a});z(i),n&&(i.addEventListener("listening",l=>{let{detail:m}=l;console.debug(`[${e}] server listening on ${JSON.stringify(m)}`)}),i.addEventListener("connection",l=>{let{clientAddress:m,clientPort:g}=l.detail;console.debug(`[${e}] client connected from ${m}:${g}`)}),i.addEventListener("error",l=>{let{detail:m}=l;console.error(`[${e}] server error:`,m)}));try{await i.start()}catch(l){throw l instanceof Error&&"code"in l&&l.code==="EADDRINUSE"?new _(a):l}let f=Number(i.getServerConn().split(":").at(1));return o&&(t[e==="database"?"databasePort":"shadowDatabasePort"]=f),ce(e,t,{db:s,port:f,server:i})}function ce(e,t,r){let{debug:n}=t,{db:a,port:o,server:d}=r||{},s=new Map;return n&&console.debug(`[${e}] server started on port ${o}`),{...p,attachWalEventBridge:async()=>{if(e!=="database"||!a)throw new Error("WAL bridge is only available for the primary database server");return await v(a)},attachQueryInsightsBridge:()=>{if(e!=="database"||!d)throw new Error("Query insights are only available for the primary database server");return Promise.resolve(Y(d))},close:async()=>{let u=[];try{await d?.stop(),n&&console.debug(`[${e}] server stopped on port ${o}`)}catch(c){console.error(`[${e}] server stop error`,c),u.push(c)}if(e==="database"){try{d&&await K(d),n&&console.debug(`[${e}] closed query insights bridge`)}catch(c){console.error(`[${e}] query insights bridge close error`,c),u.push(c)}try{a&&await Z(a),n&&console.debug(`[${e}] closed WAL bridge`)}catch(c){console.error(`[${e}] WAL bridge close error`,c),u.push(c)}try{await a?.syncToFs(),n&&console.debug(`[${e}] synced to filesystem`)}catch(c){console.error(`[${e}] sync error`,c),u.push(c)}}try{await a?.close(),n&&console.debug(`[${e}] closed`)}catch(c){console.error(`[${e}] close error`,c),u.push(c)}if(u.length>0)throw new AggregateError(u,`Failed to close ${e} properly`)},connectionString:N(o,L),dump:async u=>{e==="shadow_database"||!a||await rt({db:a,debug:n,destinationPath:u})},getPrimaryKeyColumns:async(u,c)=>{if(e==="shadow_database"||!a)throw new Error("Primary key resolution is only available for the primary database server");let i=`${u}.${c}`,f=s.get(i);return f||(f=tt(a,u,c).catch(l=>{throw s.delete(i),l}),s.set(i,f)),await f},port:o,prismaORMConnectionString:N(o,ie),terminalCommand:`PGPASSWORD=${p.password} PGSSLMODE=${p.sslMode} psql -h localhost -p ${o} -U ${p.username} -d ${p.database}`}}function N(e,t){return`${Xe}:${e}/${p.database}?${t.toString()}`}async function de(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await I(),a=e==="memory://"||!await O(Ke(e,"PG_VERSION")),o=await r.create({database:p.database,dataDir:e,debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:oe,loadDataDir:a?n.loadDataDir:void 0,relaxedDurability:!1,startParams:[...r.defaultStartParams,...se],wasmModule:n.wasmModule});return await le(o),o}async function Ve(e,t){return await new Promise((r,n)=>{let a=s=>{if(d(),s.code==="EADDRINUSE"){n(new _(t));return}n(s)},o=()=>{let s=e.address();if(d(),!s||typeof s=="string"){n(new Error("Failed to determine TCP server port"));return}r(s.port)},d=()=>{e.off("error",a),e.off("listening",o)};e.once("error",a),e.once("listening",o),e.listen(t,ae)})}async function Ze(e){await new Promise((t,r)=>{e.close(n=>{let a=n;if(a&&a.code!=="ERR_SERVER_NOT_RUNNING"){r(a);return}t()})})}async function et(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await I(),a=await r.create({database:p.database,dataDir:"memory://",debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:oe,loadDataDir:n.loadDataDir,relaxedDurability:!1,startParams:[...r.defaultStartParams,...se],wasmModule:n.wasmModule});return await le(a),a}async function tt(e,t,r){let{rows:n}=await e.query(`
|
|
92
|
+
SELECT attribute.attname AS column_name
|
|
93
|
+
FROM pg_constraint pk_constraint
|
|
94
|
+
INNER JOIN pg_class relation
|
|
95
|
+
ON relation.oid = pk_constraint.conrelid
|
|
96
|
+
INNER JOIN pg_namespace namespace
|
|
97
|
+
ON namespace.oid = relation.relnamespace
|
|
98
|
+
INNER JOIN unnest(pk_constraint.conkey) WITH ORDINALITY AS keys(attnum, ordinality)
|
|
99
|
+
ON TRUE
|
|
100
|
+
INNER JOIN pg_attribute attribute
|
|
101
|
+
ON attribute.attrelid = relation.oid
|
|
102
|
+
AND attribute.attnum = keys.attnum
|
|
103
|
+
WHERE pk_constraint.contype = 'p'
|
|
104
|
+
AND namespace.nspname = ${ne(t)}
|
|
105
|
+
AND relation.relname = ${ne(r)}
|
|
106
|
+
ORDER BY keys.ordinality
|
|
107
|
+
`);return n.map(a=>a.column_name)}function ne(e){return`'${e.replaceAll("'","''")}'`}async function rt(e){let{dataDir:t,db:r,debug:n,destinationPath:a}=e,o=r||await de(t,n),{pgDump:d}=await import("@electric-sql/pglite-tools/pg_dump"),s=await d({args:["--schema-only","--no-owner"],fileName:a?ze(a):void 0,pg:await o.clone()});return a?(n&&console.debug(`[DB] Dumping database to ${a}`),await Q(s,a)):(n&&console.debug("[DB] Dumping database to memory"),await s.text())}export{at as a,ot as b,v as c,M as d,ee as e,vt as f,je as g,rt as h};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as r}from"./chunk-
|
|
1
|
+
import{a as r}from"./chunk-AVDGCP6B.js";async function s(e){let{server:t}=await r(e);return t}async function A(e){return await s(e)}export{s as a,A as b};
|
|
@@ -1 +1 @@
|
|
|
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,
|
|
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,u as g,Q as h,U as i,V as j,Y as k};
|