@prisma/dev 0.25.0 → 0.25.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-QDQPFKGQ.js +107 -0
- package/dist/{chunk-MD3K2IUP.js → chunk-T75J7DN5.js} +1 -1
- package/dist/{chunk-J6FIMHSD.js → chunk-VSS2IOVU.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/index.cjs +24 -24
- package/dist/index.js +1 -1
- package/dist/vite.cjs +25 -25
- package/dist/vite.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-PP43TGA5.js +0 -107
|
@@ -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-DWY47FQV.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-VSS2IOVU.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{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-QDQPFKGQ.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};
|