@event-driven-io/pongo 0.16.0-alpha.9 → 0.16.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/README.md CHANGED
@@ -22,7 +22,7 @@ You can use Pongo syntax with explicit typing about supported syntax:
22
22
 
23
23
  ```ts
24
24
  import { pongoClient } from "@event-driven-io/pongo";
25
- import { v4 as uuid } from "uuid";
25
+ import { v7 as uuid } from "uuid";
26
26
 
27
27
  type User = { name: string; age: number };
28
28
 
@@ -61,7 +61,7 @@ Or use MongoDB compliant shim:
61
61
 
62
62
  ```ts
63
63
  import { MongoClient } from "@event-driven-io/pongo/shim";
64
- import { v4 as uuid } from "uuid";
64
+ import { v7 as uuid } from "uuid";
65
65
 
66
66
  type User = { name: string; age: number };
67
67
 
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } async function _asyncOptionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _dumbo = require('@event-driven-io/dumbo');var _uuid = require('uuid');var B=e=>e.connectorType===_dumbo.NodePostgresConnectorType,K= exports.d =e=>{let{connectionString:t,dbName:n}=e,o=_nullishCoalesce(n, () => (_dumbo.getDatabaseNameOrDefault.call(void 0, t))),i=_dumbo.dumbo.call(void 0, {connectionString:t,...e.connectionOptions}),r=new Map,g=async(d,p)=>(await _(y,p,i.execute)).command(d),u=async(d,p)=>(await _(y,p,i.execute)).query(d),y={connectorType:e.connectorType,databaseName:o,connect:()=>Promise.resolve(),close:()=>i.close(),collections:()=>[...r.values()],collection:d=>z({collectionName:d,db:y,pool:i,sqlBuilder:H(d),schema:e.schema?e.schema:{},errors:e.errors?e.errors:{}}),transaction:()=>i.transaction(),withTransaction:d=>i.withTransaction(d),schema:{get component(){return _dumbo.schemaComponent.call(void 0, "pongoDb",{components:[...r.values()].map(d=>d.schema.component)})},migrate:()=>_dumbo.runPostgreSQLMigrations.call(void 0, i,[...r.values()].flatMap(d=>d.schema.component.migrations({connector:"PostgreSQL:pg"})))},sql:{async query(d,p){return(await u(d,p)).rows},async command(d,p){return g(d,p)}}},R=_optionalChain([e, 'optionalAccess', _2 => _2.schema, 'optionalAccess', _3 => _3.definition, 'optionalAccess', _4 => _4.dbs]);if(R){let d=S(R).map(p=>p[1]).find(p=>p.name===n||p.name===o);if(d)return Y(y,d,r)}return y},ke= exports.e =e=>{let t=e.length>0&&typeof e[0]=="string"?e.map(n=>G(n)):e;return _dumbo.schemaComponent.call(void 0, "pongo:schema_component:db",{components:t})};var Oe=async(e,t)=>{let n=_optionalChain([t, 'optionalAccess', _5 => _5.session, 'optionalAccess', _6 => _6.transaction]);return!n||!n.isActive?null:await n.enlistDatabase(e)},_= exports.f =async(e,t,n)=>await _asyncNullishCoalesce(await _asyncOptionalChain([(await Oe(e,t)), 'optionalAccess', async _7 => _7.execute]), async () => (n)),z= exports.g =({db:e,collectionName:t,pool:n,sqlBuilder:o,schema:i,errors:r})=>{let g=n.execute,u=async(s,a)=>(await _(e,a,g)).command(s),y=async(s,a)=>(await _(e,a,g)).query(s),R=_optionalChain([i, 'optionalAccess', _8 => _8.autoMigration])!=="None",d=s=>(R=!1,_optionalChain([s, 'optionalAccess', _9 => _9.session])?u(o.createCollection(),s):u(o.createCollection())),p=s=>R?d(s):Promise.resolve(),m={dbName:e.databaseName,collectionName:t,createCollection:async s=>{await d(s)},insertOne:async(s,a)=>{await p(a);let c=_nullishCoalesce(s._id, () => (_uuid.v4.call(void 0, ))),l=_nullishCoalesce(s._version, () => (1n)),E=(await _asyncNullishCoalesce((await u(o.insertOne({...s,_id:c,_version:l}),a)).rowCount, async () => (0)))>0;return C({successful:E,insertedId:E?c:null,nextExpectedVersion:l},{operationName:"insertOne",collectionName:t,errors:r})},insertMany:async(s,a)=>{await p(a);let c=s.map(x=>({...x,_id:_nullishCoalesce(x._id, () => (_uuid.v4.call(void 0, ))),_version:_nullishCoalesce(x._version, () => (1n))})),l=await u(o.insertMany(c),a);return C({successful:l.rowCount===c.length,insertedCount:_nullishCoalesce(l.rowCount, () => (0)),insertedIds:l.rows.map(x=>x._id)},{operationName:"insertMany",collectionName:t,errors:r})},updateOne:async(s,a,c)=>{await p(c);let l=await u(o.updateOne(s,a,c),c);return C({successful:l.rows.length>0&&l.rows[0].modified===l.rows[0].matched,modifiedCount:Number(_nullishCoalesce(_optionalChain([l, 'access', _10 => _10.rows, 'access', _11 => _11[0], 'optionalAccess', _12 => _12.modified]), () => (0))),matchedCount:Number(_nullishCoalesce(_optionalChain([l, 'access', _13 => _13.rows, 'access', _14 => _14[0], 'optionalAccess', _15 => _15.matched]), () => (0))),nextExpectedVersion:_nullishCoalesce(_optionalChain([l, 'access', _16 => _16.rows, 'access', _17 => _17[0], 'optionalAccess', _18 => _18.version]), () => (0n))},{operationName:"updateOne",collectionName:t,errors:r})},replaceOne:async(s,a,c)=>{await p(c);let l=await u(o.replaceOne(s,a,c),c);return C({successful:l.rows.length>0&&l.rows[0].modified>0,modifiedCount:Number(_nullishCoalesce(_optionalChain([l, 'access', _19 => _19.rows, 'access', _20 => _20[0], 'optionalAccess', _21 => _21.modified]), () => (0))),matchedCount:Number(_nullishCoalesce(_optionalChain([l, 'access', _22 => _22.rows, 'access', _23 => _23[0], 'optionalAccess', _24 => _24.matched]), () => (0))),nextExpectedVersion:_nullishCoalesce(_optionalChain([l, 'access', _25 => _25.rows, 'access', _26 => _26[0], 'optionalAccess', _27 => _27.version]), () => (0n))},{operationName:"replaceOne",collectionName:t,errors:r})},updateMany:async(s,a,c)=>{await p(c);let l=await u(o.updateMany(s,a),c);return C({successful:!0,modifiedCount:_nullishCoalesce(l.rowCount, () => (0)),matchedCount:_nullishCoalesce(l.rowCount, () => (0))},{operationName:"updateMany",collectionName:t,errors:r})},deleteOne:async(s,a)=>{await p(a);let c=await u(o.deleteOne(_nullishCoalesce(s, () => ({})),a),a);return C({successful:c.rows.length>0&&c.rows[0].deleted>0,deletedCount:Number(_nullishCoalesce(_optionalChain([c, 'access', _28 => _28.rows, 'access', _29 => _29[0], 'optionalAccess', _30 => _30.deleted]), () => (0))),matchedCount:Number(_nullishCoalesce(_optionalChain([c, 'access', _31 => _31.rows, 'access', _32 => _32[0], 'optionalAccess', _33 => _33.matched]), () => (0)))},{operationName:"deleteOne",collectionName:t,errors:r})},deleteMany:async(s,a)=>{await p(a);let c=await u(o.deleteMany(_nullishCoalesce(s, () => ({}))),a);return C({successful:(_nullishCoalesce(c.rowCount, () => (0)))>0,deletedCount:_nullishCoalesce(c.rowCount, () => (0)),matchedCount:_nullishCoalesce(c.rowCount, () => (0))},{operationName:"deleteMany",collectionName:t,errors:r})},findOne:async(s,a)=>(await p(a),await _asyncNullishCoalesce(await _asyncOptionalChain([(await y(o.findOne(_nullishCoalesce(s, () => ({}))),a)), 'access', async _34 => _34.rows, 'access', async _35 => _35[0], 'optionalAccess', async _36 => _36.data]), async () => (null))),findOneAndDelete:async(s,a)=>{await p(a);let c=await m.findOne(s,a);return c===null?null:(await m.deleteOne(s,a),c)},findOneAndReplace:async(s,a,c)=>{await p(c);let l=await m.findOne(s,c);return l===null?null:(await m.replaceOne(s,a,c),l)},findOneAndUpdate:async(s,a,c)=>{await p(c);let l=await m.findOne(s,c);return l===null?null:(await m.updateOne(s,a,c),l)},handle:async(s,a,c)=>{let{expectedVersion:l,...x}=_nullishCoalesce(c, () => ({}));await p(c);let E={_id:s},P=await m.findOne(E,c),I=L(l);if(P==null&&l==="DOCUMENT_EXISTS"||P==null&&I!=null||P!=null&&l==="DOCUMENT_DOES_NOT_EXIST"||P!=null&&I!==null&&P._version!==I)return C({successful:!1,document:P},{operationName:"handle",collectionName:t,errors:r});let D=await a(P);if(P===D)return C({successful:!0,document:P},{operationName:"handle",collectionName:t,errors:r});if(!P&&D){let w={...D,_id:s},q=await m.insertOne({...w,_id:s},{...x,expectedVersion:"DOCUMENT_DOES_NOT_EXIST"});return{...q,document:{...w,_version:q.nextExpectedVersion}}}if(P&&!D)return{...await m.deleteOne(E,{...x,expectedVersion:_nullishCoalesce(I, () => ("DOCUMENT_EXISTS"))}),document:null};if(P&&D){let w=await m.replaceOne(E,D,{...x,expectedVersion:_nullishCoalesce(I, () => ("DOCUMENT_EXISTS"))});return{...w,document:{...D,_version:w.nextExpectedVersion}}}return C({successful:!0,document:P},{operationName:"handle",collectionName:t,errors:r})},find:async(s,a)=>(await p(a),(await y(o.find(_nullishCoalesce(s, () => ({}))))).rows.map(l=>l.data)),countDocuments:async(s,a)=>{await p(a);let{count:c}=await _dumbo.single.call(void 0, y(o.countDocuments(_nullishCoalesce(s, () => ({})))));return c},drop:async s=>(await p(s),(await _asyncNullishCoalesce(await _asyncOptionalChain([(await u(o.drop())), 'optionalAccess', async _37 => _37.rowCount]), async () => (0)))>0),rename:async(s,a)=>(await p(a),await u(o.rename(s)),t=s,m),sql:{async query(s,a){return await p(a),(await y(s,a)).rows},async command(s,a){return await p(a),u(s,a)}},schema:{get component(){return _dumbo.schemaComponent.call(void 0, "pongo:schema_component:collection",{migrations:o.migrations})},migrate:()=>_dumbo.runPostgreSQLMigrations.call(void 0, n,o.migrations())}};return m},G= exports.h =e=>_dumbo.schemaComponent.call(void 0, "pongo:schema_component:collection",{migrations:()=>V(e)});var ee={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},A= exports.j ={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},ye= exports.k =e=>e.startsWith("$"),te= exports.l =e=>Object.keys(e).some(ye);var Pe=e=>typeof e=="number"&&e===e,Se= exports.n =e=>typeof e=="string",v= exports.o =class e extends Error{constructor(t){let n=t&&typeof t=="object"&&"errorCode"in t?t.errorCode:Pe(t)?t:500,o=t&&typeof t=="object"&&"message"in t?t.message:Se(t)?t:`Error with status code '${n}' ocurred during Pongo processing`;super(o),this.errorCode=n,Object.setPrototypeOf(this,e.prototype)}},N= exports.p =class e extends v{constructor(t){super({errorCode:412,message:_nullishCoalesce(t, () => ("Expected document state does not match current one!"))}),Object.setPrototypeOf(this,e.prototype)}};require('pg');var F=e=>{let{connectorType:t}=e;if(!B(e))throw new Error(`Unsupported db type: ${t}`);return K(e)};var ne=e=>{let t=!1,n=!1,o=null,i=null;return{enlistDatabase:async r=>{if(i&&o!==r.databaseName)throw new Error("There's already other database assigned to transaction");return i&&o===r.databaseName||(o=r.databaseName,i=r.transaction(),await i.begin()),i},commit:async()=>{if(!i)throw new Error("No database transaction started!");if(!t){if(n)throw new Error("Transaction is not active!");t=!0,await i.commit(),i=null}},rollback:async r=>{if(!i)throw new Error("No database transaction started!");if(t)throw new Error("Cannot rollback commited transaction!");n||(n=!0,await i.rollback(r),i=null)},databaseName:o,isStarting:!1,isCommitted:t,get isActive(){return!t&&!n},get sqlExecutor(){if(i===null)throw new Error("No database transaction was started");return i.execute},options:e}};var U=e=>_optionalChain([e, 'optionalAccess', _38 => _38.isActive])===!0;function oe(e){if(!U(e))throw new Error("No active transaction exists!")}function Ce(e){if(U(e))throw new Error("Active transaction already exists!")}var j=e=>{let t=_optionalChain([e, 'optionalAccess', _39 => _39.explicit])===!0,n=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _40 => _40.defaultTransactionOptions]), () => ({get snapshotEnabled(){return!1}})),o=null,i=!1,r=d=>{Ce(o),o=ne(_nullishCoalesce(d, () => (n)))},g=async()=>{oe(o),await o.commit()},u=async()=>{oe(o),await o.rollback()},R={get hasEnded(){return i},explicit:t,defaultTransactionOptions:_nullishCoalesce(n, () => ({get snapshotEnabled(){return!1}})),get transaction(){return o},get snapshotEnabled(){return n.snapshotEnabled},endSession:async()=>{i||(i=!0,U(o)&&await o.rollback())},incrementTransactionNumber:()=>{},inTransaction:()=>U(o),startTransaction:r,commitTransaction:g,abortTransaction:u,withTransaction:async(d,p)=>{r(p);try{let m=await d(R);return await g(),m}catch(m){throw await u(),m}}};return R};var S=e=>Object.entries(e).map(([t,n])=>[t,n]);var dt="DOCUMENT_EXISTS",ut= exports.v ="DOCUMENT_DOES_NOT_EXIST",be= exports.w ="NO_CONCURRENCY_CHECK",he= exports.x =e=>e==="DOCUMENT_DOES_NOT_EXIST"||e==="DOCUMENT_EXISTS"||e==="NO_CONCURRENCY_CHECK",L= exports.y =e=>e===void 0||he(e)?null:e,gt= exports.z =e=>e?BigInt(e):be,C= exports.A =(e,t)=>{let n={...e,acknowledged:!0,successful:e.successful,assertSuccessful:o=>{let{successful:i}=e,{operationName:r,collectionName:g}=t;if(!i)throw new N(_nullishCoalesce(o, () => (`${r} on ${g} failed. Expected document state does not match current one! Result: ${_dumbo.JSONSerializer.serialize(e)}!`)))}};return _optionalChain([t, 'access', _41 => _41.errors, 'optionalAccess', _42 => _42.throwOnOperationFailures])&&n.assertSuccessful(),n};var Re=e=>({name:e});function fe(e,t){if(t===void 0){if(typeof e=="string")throw new Error("You need to provide colleciton definition");return{collections:e}}return e&&typeof e=="string"?{name:e,collections:t}:{collections:t}}var De=e=>({dbs:e}),St= exports.B ={client:De,db:fe,collection:Re},Y= exports.C =(e,t,n)=>{let o=Object.keys(t.collections);for(let i of o)n.set(i,e.collection(i));return new Proxy(e,{get(i,r){return _nullishCoalesce(n.get(r), () => (i[r]))}})},ie= exports.D =(e,t)=>{if(!t)return e;let n=Object.keys(t.dbs);return new Proxy(e,{get(o,i){return n.includes(i)?e.db(_optionalChain([t, 'access', _43 => _43.dbs, 'access', _44 => _44[i], 'optionalAccess', _45 => _45.name])):o[i]}})},Ee= exports.E =e=>({name:e.name,collections:S(e.collections).map(t=>({name:t[1].name}))}),Ct= exports.F =e=>{let t=S(e.dbs).map(n=>Ee(n[1]));return{databases:t,database:n=>t.find(o=>o.name===n)}};var wt=(e,t={})=>{let n=new Map,o=F(se({connectionString:e,clientOptions:t}));n.set(o.databaseName,o);let i={connect:async()=>(await o.connect(),i),close:async()=>{for(let r of n.values())await r.close()},db:r=>r?_nullishCoalesce(n.get(r), () => (n.set(r,F(se({connectionString:e,dbName:r,clientOptions:t}))).get(r))):o,startSession:j,withSession:async r=>{let g=j();try{return await r(g)}finally{await g.endSession()}}};return ie(i,_optionalChain([t, 'optionalAccess', _46 => _46.schema, 'optionalAccess', _47 => _47.definition]))},se= exports.H =e=>({connectorType:_dumbo.NodePostgresConnectorType,connectionString:e.connectionString,dbName:e.dbName,...e.clientOptions});var $=(e,t,n)=>{if(e==="_id"||e==="_version")return Le(e,t,n);switch(t){case"$eq":return _dumbo.sql.call(void 0, "(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",_dumbo.JSONSerializer.serialize(re(e,n)),e,_dumbo.JSONSerializer.serialize(n));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _dumbo.sql.call(void 0, `data #>> %L ${A[t]} %L`,`{${e.split(".").join(",")}}`,n);case"$in":return _dumbo.sql.call(void 0, "data #>> %L IN (%s)",`{${e.split(".").join(",")}}`,n.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$nin":return _dumbo.sql.call(void 0, "data #>> %L NOT IN (%s)",`{${e.split(".").join(",")}}`,n.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$elemMatch":{let o=S(n).map(([i,r])=>_dumbo.sql.call(void 0, '@."%s" == %s',i,_dumbo.JSONSerializer.serialize(r))).join(" && ");return _dumbo.sql.call(void 0, "jsonb_path_exists(data, '$.%s[*] ? (%s)')",e,o)}case"$all":return _dumbo.sql.call(void 0, "data @> %L::jsonb",_dumbo.JSONSerializer.serialize(re(e,n)));case"$size":return _dumbo.sql.call(void 0, "jsonb_array_length(data #> %L) = %L",`{${e.split(".").join(",")}}`,n);default:throw new Error(`Unsupported operator: ${t}`)}},Le=(e,t,n)=>{switch(t){case"$eq":return _dumbo.sql.call(void 0, `${e} = %L`,n);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _dumbo.sql.call(void 0, `${e} ${A[t]} %L`,n);case"$in":return _dumbo.sql.call(void 0, `${e} IN (%s)`,n.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$nin":return _dumbo.sql.call(void 0, `${e} NOT IN (%s)`,n.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));default:throw new Error(`Unsupported operator: ${t}`)}},re=(e,t)=>e.split(".").reverse().reduce((n,o)=>({[o]:n}),t);var ae="AND",h=e=>Object.entries(e).map(([t,n])=>_e(n)?Ie(t,n):$(t,"$eq",n)).join(` ${ae} `),Ie=(e,t)=>{let n=!te(t);return S(t).map(([o,i])=>n?$(`${e}.${o}`,ee.$eq,i):$(e,o,i)).join(` ${ae} `)},_e=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);var k=e=>S(e).reduce((t,[n,o])=>{switch(n){case"$set":return Qe(o,t);case"$unset":return Ne(o,t);case"$inc":return Ue(o,t);case"$push":return Me(o,t);default:return t}},_dumbo.sql.call(void 0, "data")),Qe=(e,t)=>_dumbo.sql.call(void 0, "%s || %L::jsonb",t,_dumbo.JSONSerializer.serialize(e)),Ne=(e,t)=>_dumbo.sql.call(void 0, "%s - %L",t,Object.keys(e).map(n=>`{${n}}`).join(", ")),Ue=(e,t)=>{for(let[n,o]of Object.entries(e))t=_dumbo.sql.call(void 0, typeof o=="bigint"?"jsonb_set(%s, '{%s}', to_jsonb((COALESCE((data->>'%s')::BIGINT, 0) + %L)::TEXT), true)":"jsonb_set(%s, '{%s}', to_jsonb(COALESCE((data->>'%s')::NUMERIC, 0) + %L), true)",t,n,n,o);return t},Me=(e,t)=>{for(let[n,o]of Object.entries(e))t=_dumbo.sql.call(void 0, "jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)",t,n,n,_dumbo.JSONSerializer.serialize([o]));return t};var le=e=>_dumbo.sql.call(void 0, `CREATE TABLE IF NOT EXISTS %I (
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } async function _asyncOptionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _dumbo = require('@event-driven-io/dumbo');var _uuid = require('uuid');var B=e=>e.connectorType===_dumbo.NodePostgresConnectorType,K= exports.d =e=>{let{connectionString:t,dbName:n}=e,o=_nullishCoalesce(n, () => (_dumbo.getDatabaseNameOrDefault.call(void 0, t))),i=_dumbo.dumbo.call(void 0, {connectionString:t,...e.connectionOptions}),r=new Map,g=async(d,p)=>(await _(y,p,i.execute)).command(d),u=async(d,p)=>(await _(y,p,i.execute)).query(d),y={connectorType:e.connectorType,databaseName:o,connect:()=>Promise.resolve(),close:()=>i.close(),collections:()=>[...r.values()],collection:d=>z({collectionName:d,db:y,pool:i,sqlBuilder:H(d),schema:e.schema?e.schema:{},errors:e.errors?e.errors:{}}),transaction:()=>i.transaction(),withTransaction:d=>i.withTransaction(d),schema:{get component(){return _dumbo.schemaComponent.call(void 0, "pongoDb",{components:[...r.values()].map(d=>d.schema.component)})},migrate:()=>_dumbo.runPostgreSQLMigrations.call(void 0, i,[...r.values()].flatMap(d=>d.schema.component.migrations({connector:"PostgreSQL:pg"})))},sql:{async query(d,p){return(await u(d,p)).rows},async command(d,p){return g(d,p)}}},R=_optionalChain([e, 'optionalAccess', _2 => _2.schema, 'optionalAccess', _3 => _3.definition, 'optionalAccess', _4 => _4.dbs]);if(R){let d=S(R).map(p=>p[1]).find(p=>p.name===n||p.name===o);if(d)return Y(y,d,r)}return y},We= exports.e =e=>{let t=e.length>0&&typeof e[0]=="string"?e.map(n=>G(n)):e;return _dumbo.schemaComponent.call(void 0, "pongo:schema_component:db",{components:t})};var Oe=async(e,t)=>{let n=_optionalChain([t, 'optionalAccess', _5 => _5.session, 'optionalAccess', _6 => _6.transaction]);return!n||!n.isActive?null:await n.enlistDatabase(e)},_= exports.f =async(e,t,n)=>await _asyncNullishCoalesce(await _asyncOptionalChain([(await Oe(e,t)), 'optionalAccess', async _7 => _7.execute]), async () => (n)),z= exports.g =({db:e,collectionName:t,pool:n,sqlBuilder:o,schema:i,errors:r})=>{let g=n.execute,u=async(s,a)=>(await _(e,a,g)).command(s),y=async(s,a)=>(await _(e,a,g)).query(s),R=_optionalChain([i, 'optionalAccess', _8 => _8.autoMigration])!=="None",d=s=>(R=!1,_optionalChain([s, 'optionalAccess', _9 => _9.session])?u(o.createCollection(),s):u(o.createCollection())),p=s=>R?d(s):Promise.resolve(),m={dbName:e.databaseName,collectionName:t,createCollection:async s=>{await d(s)},insertOne:async(s,a)=>{await p(a);let c=_nullishCoalesce(s._id, () => (_uuid.v7.call(void 0, ))),l=_nullishCoalesce(s._version, () => (1n)),E=(await _asyncNullishCoalesce((await u(o.insertOne({...s,_id:c,_version:l}),a)).rowCount, async () => (0)))>0;return C({successful:E,insertedId:E?c:null,nextExpectedVersion:l},{operationName:"insertOne",collectionName:t,errors:r})},insertMany:async(s,a)=>{await p(a);let c=s.map(x=>({...x,_id:_nullishCoalesce(x._id, () => (_uuid.v7.call(void 0, ))),_version:_nullishCoalesce(x._version, () => (1n))})),l=await u(o.insertMany(c),a);return C({successful:l.rowCount===c.length,insertedCount:_nullishCoalesce(l.rowCount, () => (0)),insertedIds:l.rows.map(x=>x._id)},{operationName:"insertMany",collectionName:t,errors:r})},updateOne:async(s,a,c)=>{await p(c);let l=await u(o.updateOne(s,a,c),c);return C({successful:l.rows.length>0&&l.rows[0].modified===l.rows[0].matched,modifiedCount:Number(_nullishCoalesce(_optionalChain([l, 'access', _10 => _10.rows, 'access', _11 => _11[0], 'optionalAccess', _12 => _12.modified]), () => (0))),matchedCount:Number(_nullishCoalesce(_optionalChain([l, 'access', _13 => _13.rows, 'access', _14 => _14[0], 'optionalAccess', _15 => _15.matched]), () => (0))),nextExpectedVersion:_nullishCoalesce(_optionalChain([l, 'access', _16 => _16.rows, 'access', _17 => _17[0], 'optionalAccess', _18 => _18.version]), () => (0n))},{operationName:"updateOne",collectionName:t,errors:r})},replaceOne:async(s,a,c)=>{await p(c);let l=await u(o.replaceOne(s,a,c),c);return C({successful:l.rows.length>0&&l.rows[0].modified>0,modifiedCount:Number(_nullishCoalesce(_optionalChain([l, 'access', _19 => _19.rows, 'access', _20 => _20[0], 'optionalAccess', _21 => _21.modified]), () => (0))),matchedCount:Number(_nullishCoalesce(_optionalChain([l, 'access', _22 => _22.rows, 'access', _23 => _23[0], 'optionalAccess', _24 => _24.matched]), () => (0))),nextExpectedVersion:_nullishCoalesce(_optionalChain([l, 'access', _25 => _25.rows, 'access', _26 => _26[0], 'optionalAccess', _27 => _27.version]), () => (0n))},{operationName:"replaceOne",collectionName:t,errors:r})},updateMany:async(s,a,c)=>{await p(c);let l=await u(o.updateMany(s,a),c);return C({successful:!0,modifiedCount:_nullishCoalesce(l.rowCount, () => (0)),matchedCount:_nullishCoalesce(l.rowCount, () => (0))},{operationName:"updateMany",collectionName:t,errors:r})},deleteOne:async(s,a)=>{await p(a);let c=await u(o.deleteOne(_nullishCoalesce(s, () => ({})),a),a);return C({successful:c.rows.length>0&&c.rows[0].deleted>0,deletedCount:Number(_nullishCoalesce(_optionalChain([c, 'access', _28 => _28.rows, 'access', _29 => _29[0], 'optionalAccess', _30 => _30.deleted]), () => (0))),matchedCount:Number(_nullishCoalesce(_optionalChain([c, 'access', _31 => _31.rows, 'access', _32 => _32[0], 'optionalAccess', _33 => _33.matched]), () => (0)))},{operationName:"deleteOne",collectionName:t,errors:r})},deleteMany:async(s,a)=>{await p(a);let c=await u(o.deleteMany(_nullishCoalesce(s, () => ({}))),a);return C({successful:(_nullishCoalesce(c.rowCount, () => (0)))>0,deletedCount:_nullishCoalesce(c.rowCount, () => (0)),matchedCount:_nullishCoalesce(c.rowCount, () => (0))},{operationName:"deleteMany",collectionName:t,errors:r})},findOne:async(s,a)=>(await p(a),await _asyncNullishCoalesce(await _asyncOptionalChain([(await y(o.findOne(_nullishCoalesce(s, () => ({}))),a)), 'access', async _34 => _34.rows, 'access', async _35 => _35[0], 'optionalAccess', async _36 => _36.data]), async () => (null))),findOneAndDelete:async(s,a)=>{await p(a);let c=await m.findOne(s,a);return c===null?null:(await m.deleteOne(s,a),c)},findOneAndReplace:async(s,a,c)=>{await p(c);let l=await m.findOne(s,c);return l===null?null:(await m.replaceOne(s,a,c),l)},findOneAndUpdate:async(s,a,c)=>{await p(c);let l=await m.findOne(s,c);return l===null?null:(await m.updateOne(s,a,c),l)},handle:async(s,a,c)=>{let{expectedVersion:l,...x}=_nullishCoalesce(c, () => ({}));await p(c);let E={_id:s},P=await m.findOne(E,c),L=I(l);if(P==null&&l==="DOCUMENT_EXISTS"||P==null&&L!=null||P!=null&&l==="DOCUMENT_DOES_NOT_EXIST"||P!=null&&L!==null&&P._version!==L)return C({successful:!1,document:P},{operationName:"handle",collectionName:t,errors:r});let D=await a(P);if(P===D)return C({successful:!0,document:P},{operationName:"handle",collectionName:t,errors:r});if(!P&&D){let w={...D,_id:s},q=await m.insertOne({...w,_id:s},{...x,expectedVersion:"DOCUMENT_DOES_NOT_EXIST"});return{...q,document:{...w,_version:q.nextExpectedVersion}}}if(P&&!D)return{...await m.deleteOne(E,{...x,expectedVersion:_nullishCoalesce(L, () => ("DOCUMENT_EXISTS"))}),document:null};if(P&&D){let w=await m.replaceOne(E,D,{...x,expectedVersion:_nullishCoalesce(L, () => ("DOCUMENT_EXISTS"))});return{...w,document:{...D,_version:w.nextExpectedVersion}}}return C({successful:!0,document:P},{operationName:"handle",collectionName:t,errors:r})},find:async(s,a)=>(await p(a),(await y(o.find(_nullishCoalesce(s, () => ({}))))).rows.map(l=>l.data)),countDocuments:async(s,a)=>{await p(a);let{count:c}=await _dumbo.single.call(void 0, y(o.countDocuments(_nullishCoalesce(s, () => ({})))));return c},drop:async s=>(await p(s),(await _asyncNullishCoalesce(await _asyncOptionalChain([(await u(o.drop())), 'optionalAccess', async _37 => _37.rowCount]), async () => (0)))>0),rename:async(s,a)=>(await p(a),await u(o.rename(s)),t=s,m),sql:{async query(s,a){return await p(a),(await y(s,a)).rows},async command(s,a){return await p(a),u(s,a)}},schema:{get component(){return _dumbo.schemaComponent.call(void 0, "pongo:schema_component:collection",{migrations:o.migrations})},migrate:()=>_dumbo.runPostgreSQLMigrations.call(void 0, n,o.migrations())}};return m},G= exports.h =e=>_dumbo.schemaComponent.call(void 0, "pongo:schema_component:collection",{migrations:()=>V(e)});var ee={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},A= exports.j ={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},ye= exports.k =e=>e.startsWith("$"),te= exports.l =e=>Object.keys(e).some(ye);var Pe=e=>typeof e=="number"&&e===e,Se= exports.n =e=>typeof e=="string",v= exports.o =class e extends Error{constructor(t){let n=t&&typeof t=="object"&&"errorCode"in t?t.errorCode:Pe(t)?t:500,o=t&&typeof t=="object"&&"message"in t?t.message:Se(t)?t:`Error with status code '${n}' ocurred during Pongo processing`;super(o),this.errorCode=n,Object.setPrototypeOf(this,e.prototype)}},N= exports.p =class e extends v{constructor(t){super({errorCode:412,message:_nullishCoalesce(t, () => ("Expected document state does not match current one!"))}),Object.setPrototypeOf(this,e.prototype)}};require('pg');var j=e=>{let{connectorType:t}=e;if(!B(e))throw new Error(`Unsupported db type: ${t}`);return K(e)};var ne=e=>{let t=!1,n=!1,o=null,i=null;return{enlistDatabase:async r=>{if(i&&o!==r.databaseName)throw new Error("There's already other database assigned to transaction");return i&&o===r.databaseName||(o=r.databaseName,i=r.transaction(),await i.begin()),i},commit:async()=>{if(!i)throw new Error("No database transaction started!");if(!t){if(n)throw new Error("Transaction is not active!");t=!0,await i.commit(),i=null}},rollback:async r=>{if(!i)throw new Error("No database transaction started!");if(t)throw new Error("Cannot rollback commited transaction!");n||(n=!0,await i.rollback(r),i=null)},databaseName:o,isStarting:!1,isCommitted:t,get isActive(){return!t&&!n},get sqlExecutor(){if(i===null)throw new Error("No database transaction was started");return i.execute},options:e}};var U=e=>_optionalChain([e, 'optionalAccess', _38 => _38.isActive])===!0;function oe(e){if(!U(e))throw new Error("No active transaction exists!")}function Ce(e){if(U(e))throw new Error("Active transaction already exists!")}var F=e=>{let t=_optionalChain([e, 'optionalAccess', _39 => _39.explicit])===!0,n=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _40 => _40.defaultTransactionOptions]), () => ({get snapshotEnabled(){return!1}})),o=null,i=!1,r=d=>{Ce(o),o=ne(_nullishCoalesce(d, () => (n)))},g=async()=>{oe(o),await o.commit()},u=async()=>{oe(o),await o.rollback()},R={get hasEnded(){return i},explicit:t,defaultTransactionOptions:_nullishCoalesce(n, () => ({get snapshotEnabled(){return!1}})),get transaction(){return o},get snapshotEnabled(){return n.snapshotEnabled},endSession:async()=>{i||(i=!0,U(o)&&await o.rollback())},incrementTransactionNumber:()=>{},inTransaction:()=>U(o),startTransaction:r,commitTransaction:g,abortTransaction:u,withTransaction:async(d,p)=>{r(p);try{let m=await d(R);return await g(),m}catch(m){throw await u(),m}}};return R};var S=e=>Object.entries(e).map(([t,n])=>[t,n]);var gt=e=>_nullishCoalesce(e, () => (_uuid.v7.call(void 0, ))),mt= exports.v ="DOCUMENT_EXISTS",Tt= exports.w ="DOCUMENT_DOES_NOT_EXIST",he= exports.x ="NO_CONCURRENCY_CHECK",Re= exports.y =e=>e==="DOCUMENT_DOES_NOT_EXIST"||e==="DOCUMENT_EXISTS"||e==="NO_CONCURRENCY_CHECK",I= exports.z =e=>e===void 0||Re(e)?null:e,Ot= exports.A =e=>e?BigInt(e):he,C= exports.B =(e,t)=>{let n={...e,acknowledged:!0,successful:e.successful,assertSuccessful:o=>{let{successful:i}=e,{operationName:r,collectionName:g}=t;if(!i)throw new N(_nullishCoalesce(o, () => (`${r} on ${g} failed. Expected document state does not match current one! Result: ${_dumbo.JSONSerializer.serialize(e)}!`)))}};return _optionalChain([t, 'access', _41 => _41.errors, 'optionalAccess', _42 => _42.throwOnOperationFailures])&&n.assertSuccessful(),n};var fe=e=>({name:e});function De(e,t){if(t===void 0){if(typeof e=="string")throw new Error("You need to provide colleciton definition");return{collections:e}}return e&&typeof e=="string"?{name:e,collections:t}:{collections:t}}var Ee=e=>({dbs:e}),bt= exports.C ={client:Ee,db:De,collection:fe},Y= exports.D =(e,t,n)=>{let o=Object.keys(t.collections);for(let i of o)n.set(i,e.collection(i));return new Proxy(e,{get(i,r){return _nullishCoalesce(n.get(r), () => (i[r]))}})},ie= exports.E =(e,t)=>{if(!t)return e;let n=Object.keys(t.dbs);return new Proxy(e,{get(o,i){return n.includes(i)?e.db(_optionalChain([t, 'access', _43 => _43.dbs, 'access', _44 => _44[i], 'optionalAccess', _45 => _45.name])):o[i]}})},we= exports.F =e=>({name:e.name,collections:S(e.collections).map(t=>({name:t[1].name}))}),ht= exports.G =e=>{let t=S(e.dbs).map(n=>we(n[1]));return{databases:t,database:n=>t.find(o=>o.name===n)}};var _t=(e,t={})=>{let n=new Map,o=j(se({connectionString:e,clientOptions:t}));n.set(o.databaseName,o);let i={connect:async()=>(await o.connect(),i),close:async()=>{for(let r of n.values())await r.close()},db:r=>r?_nullishCoalesce(n.get(r), () => (n.set(r,j(se({connectionString:e,dbName:r,clientOptions:t}))).get(r))):o,startSession:F,withSession:async r=>{let g=F();try{return await r(g)}finally{await g.endSession()}}};return ie(i,_optionalChain([t, 'optionalAccess', _46 => _46.schema, 'optionalAccess', _47 => _47.definition]))},se= exports.I =e=>({connectorType:_dumbo.NodePostgresConnectorType,connectionString:e.connectionString,dbName:e.dbName,...e.clientOptions});var $=(e,t,n)=>{if(e==="_id"||e==="_version")return Le(e,t,n);switch(t){case"$eq":return _dumbo.sql.call(void 0, "(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",_dumbo.JSONSerializer.serialize(re(e,n)),e,_dumbo.JSONSerializer.serialize(n));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _dumbo.sql.call(void 0, `data #>> %L ${A[t]} %L`,`{${e.split(".").join(",")}}`,n);case"$in":return _dumbo.sql.call(void 0, "data #>> %L IN (%s)",`{${e.split(".").join(",")}}`,n.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$nin":return _dumbo.sql.call(void 0, "data #>> %L NOT IN (%s)",`{${e.split(".").join(",")}}`,n.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$elemMatch":{let o=S(n).map(([i,r])=>_dumbo.sql.call(void 0, '@."%s" == %s',i,_dumbo.JSONSerializer.serialize(r))).join(" && ");return _dumbo.sql.call(void 0, "jsonb_path_exists(data, '$.%s[*] ? (%s)')",e,o)}case"$all":return _dumbo.sql.call(void 0, "data @> %L::jsonb",_dumbo.JSONSerializer.serialize(re(e,n)));case"$size":return _dumbo.sql.call(void 0, "jsonb_array_length(data #> %L) = %L",`{${e.split(".").join(",")}}`,n);default:throw new Error(`Unsupported operator: ${t}`)}},Le=(e,t,n)=>{switch(t){case"$eq":return _dumbo.sql.call(void 0, `${e} = %L`,n);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _dumbo.sql.call(void 0, `${e} ${A[t]} %L`,n);case"$in":return _dumbo.sql.call(void 0, `${e} IN (%s)`,n.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$nin":return _dumbo.sql.call(void 0, `${e} NOT IN (%s)`,n.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));default:throw new Error(`Unsupported operator: ${t}`)}},re=(e,t)=>e.split(".").reverse().reduce((n,o)=>({[o]:n}),t);var ae="AND",h=e=>Object.entries(e).map(([t,n])=>Qe(n)?_e(t,n):$(t,"$eq",n)).join(` ${ae} `),_e=(e,t)=>{let n=!te(t);return S(t).map(([o,i])=>n?$(`${e}.${o}`,ee.$eq,i):$(e,o,i)).join(` ${ae} `)},Qe=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);var k=e=>S(e).reduce((t,[n,o])=>{switch(n){case"$set":return Ne(o,t);case"$unset":return Ue(o,t);case"$inc":return Me(o,t);case"$push":return $e(o,t);default:return t}},_dumbo.sql.call(void 0, "data")),Ne=(e,t)=>_dumbo.sql.call(void 0, "%s || %L::jsonb",t,_dumbo.JSONSerializer.serialize(e)),Ue=(e,t)=>_dumbo.sql.call(void 0, "%s - %L",t,Object.keys(e).map(n=>`{${n}}`).join(", ")),Me=(e,t)=>{for(let[n,o]of Object.entries(e))t=_dumbo.sql.call(void 0, typeof o=="bigint"?"jsonb_set(%s, '{%s}', to_jsonb((COALESCE((data->>'%s')::BIGINT, 0) + %L)::TEXT), true)":"jsonb_set(%s, '{%s}', to_jsonb(COALESCE((data->>'%s')::NUMERIC, 0) + %L), true)",t,n,n,o);return t},$e=(e,t)=>{for(let[n,o]of Object.entries(e))t=_dumbo.sql.call(void 0, "jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)",t,n,n,_dumbo.JSONSerializer.serialize([o]));return t};var le=e=>_dumbo.sql.call(void 0, `CREATE TABLE IF NOT EXISTS %I (
2
2
  _id TEXT PRIMARY KEY,
3
3
  data JSONB NOT NULL,
4
4
  metadata JSONB NOT NULL DEFAULT '{}',
@@ -9,7 +9,7 @@
9
9
  _updated TIMESTAMPTZ NOT NULL DEFAULT now()
10
10
  )`,e),V= exports.a =e=>[_dumbo.sqlMigration.call(void 0, `pongoCollection:${e}:001:createtable`,[le(e)])],H= exports.b =e=>({migrations:()=>V(e),createCollection:()=>le(e),insertOne:t=>_dumbo.sql.call(void 0, "INSERT INTO %I (_id, data, _version) VALUES (%L, %L, %L) ON CONFLICT(_id) DO NOTHING;",e,t._id,_dumbo.JSONSerializer.serialize(t),_nullishCoalesce(t._version, () => (1n))),insertMany:t=>{let n=t.map(o=>_dumbo.sql.call(void 0, "(%L, %L, %L)",o._id,_dumbo.JSONSerializer.serialize(o),_nullishCoalesce(o._version, () => (1n)))).join(", ");return _dumbo.sql.call(void 0, `INSERT INTO %I (_id, data, _version) VALUES %s
11
11
  ON CONFLICT(_id) DO NOTHING
12
- RETURNING _id;`,e,n)},updateOne:(t,n,o)=>{let i=L(_optionalChain([o, 'optionalAccess', _48 => _48.expectedVersion])),r=i!=null?"AND %I._version = %L":"",g=i!=null?[e,i]:[],u=_dumbo.isSQL.call(void 0, t)?t:h(t),y=_dumbo.isSQL.call(void 0, n)?n:k(n);return _dumbo.sql.call(void 0, `WITH existing AS (
12
+ RETURNING _id;`,e,n)},updateOne:(t,n,o)=>{let i=I(_optionalChain([o, 'optionalAccess', _48 => _48.expectedVersion])),r=i!=null?"AND %I._version = %L":"",g=i!=null?[e,i]:[],u=_dumbo.isSQL.call(void 0, t)?t:h(t),y=_dumbo.isSQL.call(void 0, n)?n:k(n);return _dumbo.sql.call(void 0, `WITH existing AS (
13
13
  SELECT _id, _version as current_version
14
14
  FROM %I %s
15
15
  LIMIT 1
@@ -30,7 +30,7 @@
30
30
  COUNT(updated._id) over() AS modified
31
31
  FROM existing
32
32
  LEFT JOIN updated
33
- ON existing._id = updated._id;`,e,f(u),e,y,e,e,...g,e,e)},replaceOne:(t,n,o)=>{let i=L(_optionalChain([o, 'optionalAccess', _49 => _49.expectedVersion])),r=i!=null?"AND %I._version = %L":"",g=i!=null?[e,i]:[],u=_dumbo.isSQL.call(void 0, t)?t:h(t);return _dumbo.sql.call(void 0, `WITH existing AS (
33
+ ON existing._id = updated._id;`,e,f(u),e,y,e,e,...g,e,e)},replaceOne:(t,n,o)=>{let i=I(_optionalChain([o, 'optionalAccess', _49 => _49.expectedVersion])),r=i!=null?"AND %I._version = %L":"",g=i!=null?[e,i]:[],u=_dumbo.isSQL.call(void 0, t)?t:h(t);return _dumbo.sql.call(void 0, `WITH existing AS (
34
34
  SELECT _id, _version as current_version
35
35
  FROM %I %s
36
36
  LIMIT 1
@@ -55,7 +55,7 @@
55
55
  SET
56
56
  data = %s || jsonb_build_object('_version', (_version + 1)::text),
57
57
  _version = _version + 1
58
- %s;`,e,i,f(o))},deleteOne:(t,n)=>{let o=L(_optionalChain([n, 'optionalAccess', _50 => _50.expectedVersion])),i=o!=null?"AND %I._version = %L":"",r=o!=null?[e,o]:[],g=_dumbo.isSQL.call(void 0, t)?t:h(t);return _dumbo.sql.call(void 0, `WITH existing AS (
58
+ %s;`,e,i,f(o))},deleteOne:(t,n)=>{let o=I(_optionalChain([n, 'optionalAccess', _50 => _50.expectedVersion])),i=o!=null?"AND %I._version = %L":"",r=o!=null?[e,o]:[],g=_dumbo.isSQL.call(void 0, t)?t:h(t);return _dumbo.sql.call(void 0, `WITH existing AS (
59
59
  SELECT _id
60
60
  FROM %I %s
61
61
  LIMIT 1
@@ -72,5 +72,5 @@
72
72
  COUNT(deleted._id) over() AS deleted
73
73
  FROM existing
74
74
  LEFT JOIN deleted
75
- ON existing._id = deleted._id;`,e,f(g),e,e,...r,e)},deleteMany:t=>{let n=_dumbo.isSQL.call(void 0, t)?t:h(t);return _dumbo.sql.call(void 0, "DELETE FROM %I %s",e,f(n))},findOne:t=>{let n=_dumbo.isSQL.call(void 0, t)?t:h(t);return _dumbo.sql.call(void 0, "SELECT data FROM %I %s LIMIT 1;",e,f(n))},find:t=>{let n=_dumbo.isSQL.call(void 0, t)?t:h(t);return _dumbo.sql.call(void 0, "SELECT data FROM %I %s;",e,f(n))},countDocuments:t=>{let n=_dumbo.isSQL.call(void 0, t)?t:h(t);return _dumbo.sql.call(void 0, "SELECT COUNT(1) as count FROM %I %s;",e,f(n))},rename:t=>_dumbo.sql.call(void 0, "ALTER TABLE %I RENAME TO %I;",e,t),drop:(t=e)=>_dumbo.sql.call(void 0, "DROP TABLE IF EXISTS %I",t)}),f=e=>e.length>0?_dumbo.sql.call(void 0, "WHERE %s",e):_dumbo.rawSql.call(void 0, "");exports.a = V; exports.b = H; exports.c = B; exports.d = K; exports.e = ke; exports.f = _; exports.g = z; exports.h = G; exports.i = ee; exports.j = A; exports.k = ye; exports.l = te; exports.m = Pe; exports.n = Se; exports.o = v; exports.p = N; exports.q = F; exports.r = ne; exports.s = j; exports.t = S; exports.u = dt; exports.v = ut; exports.w = be; exports.x = he; exports.y = L; exports.z = gt; exports.A = C; exports.B = St; exports.C = Y; exports.D = ie; exports.E = Ee; exports.F = Ct; exports.G = wt; exports.H = se;
76
- //# sourceMappingURL=chunk-FJ56KM7M.cjs.map
75
+ ON existing._id = deleted._id;`,e,f(g),e,e,...r,e)},deleteMany:t=>{let n=_dumbo.isSQL.call(void 0, t)?t:h(t);return _dumbo.sql.call(void 0, "DELETE FROM %I %s",e,f(n))},findOne:t=>{let n=_dumbo.isSQL.call(void 0, t)?t:h(t);return _dumbo.sql.call(void 0, "SELECT data FROM %I %s LIMIT 1;",e,f(n))},find:t=>{let n=_dumbo.isSQL.call(void 0, t)?t:h(t);return _dumbo.sql.call(void 0, "SELECT data FROM %I %s;",e,f(n))},countDocuments:t=>{let n=_dumbo.isSQL.call(void 0, t)?t:h(t);return _dumbo.sql.call(void 0, "SELECT COUNT(1) as count FROM %I %s;",e,f(n))},rename:t=>_dumbo.sql.call(void 0, "ALTER TABLE %I RENAME TO %I;",e,t),drop:(t=e)=>_dumbo.sql.call(void 0, "DROP TABLE IF EXISTS %I",t)}),f=e=>e.length>0?_dumbo.sql.call(void 0, "WHERE %s",e):_dumbo.rawSql.call(void 0, "");exports.a = V; exports.b = H; exports.c = B; exports.d = K; exports.e = We; exports.f = _; exports.g = z; exports.h = G; exports.i = ee; exports.j = A; exports.k = ye; exports.l = te; exports.m = Pe; exports.n = Se; exports.o = v; exports.p = N; exports.q = j; exports.r = ne; exports.s = F; exports.t = S; exports.u = gt; exports.v = mt; exports.w = Tt; exports.x = he; exports.y = Re; exports.z = I; exports.A = Ot; exports.B = C; exports.C = bt; exports.D = Y; exports.E = ie; exports.F = we; exports.G = ht; exports.H = _t; exports.I = se;
76
+ //# sourceMappingURL=chunk-BLT4TSB5.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/postgres/sqlBuilder/index.ts","../src/core/collection/pongoCollection.ts","../src/postgres/dbClient.ts","../src/core/collection/query.ts","../src/core/errors/index.ts","../src/core/pongoClient.ts","../src/core/pongoDb.ts"],"names":["isPostgresClientOptions","options","NodePostgresConnectorType","postgresDb","connectionString","dbName","databaseName","getDatabaseNameOrDefault","pool","dumbo","collections","command","sql","transactionExecutorOrDefault","db","query","collectionName","pongoCollection","postgresSQLBuilder","handle","schemaComponent","c","runPostgreSQLMigrations","dbsSchema","dbSchema","objectEntries","e","proxyPongoDbWithSchema","pongoDbSchemaComponent","components","pongoCollectionSchemaComponent","enlistIntoTransactionIfActive","transaction","defaultSqlExecutor","SqlFor","schema","errors","sqlExecutor","shouldMigrate","createCollection","ensureCollectionCreated","collection","document","_id","uuid","_version","successful","operationResult","documents","rows","doc","result","d","filter","update","existingDoc","replacement","id","version","operationOptions","byId","existing","expectedVersion","expectedVersionValue","newDoc","insertResult","replaceResult","row","count","single","newName","pongoCollectionPostgreSQLMigrations","QueryOperators","OperatorMap","isOperator","key","hasOperators","value","isNumber","val","isString","PongoError","_PongoError","errorCode","message","ConcurrencyError","_ConcurrencyError","getPongoDb","type"],"mappings":"AAAA,g3CAQO,4BCMoB,ICedA,CAAAA,CACXC,CAAAA,EAEAA,CAAAA,CAAQ,aAAA,GAAkBC,gCAAAA,CAEfC,CAAAA,aACXF,CAAAA,EAC+B,CAC/B,GAAM,CAAE,gBAAA,CAAAG,CAAAA,CAAkB,MAAA,CAAAC,CAAO,CAAA,CAAIJ,CAAAA,CAC/BK,CAAAA,kBAAeD,CAAAA,SAAUE,6CAAAA,CAAyC,GAAA,CAElEC,CAAAA,CAAOC,0BAAAA,CACX,gBAAA,CAAAL,CAAAA,CACA,GAAGH,CAAAA,CAAQ,iBACb,CAAC,CAAA,CAEKS,CAAAA,CAAc,IAAI,GAAA,CAElBC,CAAAA,CAAU,KAAA,CACdC,CAAAA,CACAX,CAAAA,CAAAA,EAAAA,CAGE,MAAMY,CAAAA,CAA6BC,CAAAA,CAAIb,CAAAA,CAASO,CAAAA,CAAK,OAAO,CAAA,CAAA,CAC5D,OAAA,CAAgBI,CAAG,CAAA,CAEjBG,CAAAA,CAAQ,KAAA,CACZH,CAAAA,CACAX,CAAAA,CAAAA,EAAAA,CAEC,MAAMY,CAAAA,CA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A,CAAW,SAAS,CAClD,CACF,CAAA,CAEaG,CAAAA,aAAN,MAAMC,EAAAA,QAAyBL,CAAW,CAC/C,WAAA,CAAYG,CAAAA,CAAkB,CAC5B,KAAA,CAAM,CACJ,SAAA,CAAW,GAAA,CACX,OAAA,kBAASA,CAAAA,SAAW,uDACtB,CAAC,CAAA,CAGD,MAAA,CAAO,cAAA,CAAe,IAAA,CAAME,CAAAA,CAAiB,SAAS,CACxD,CACF,CAAA,CC3CA,cAKe,ICWFC,CAAAA,CAGXtF,CAAAA,EACY,CACZ,GAAM,CAAE,aAAA,CAAeuF,CAAK,CAAA,CAAIvF,CAAAA,CAEhC,EAAA,CAAI,CAACD,CAAAA,CAAwBC,CAAO,CAAA,CAClC,MAAM,IAAI,KAAA,CAAM,CAAA,qBAAA,EAAwBuF,CAAI,CAAA,CAAA;ANC5C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA8CE,GAAA;AAAA;AAsBA,oBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWqD,oCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoCrD,oCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWqD,oCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA8BrD,oCAAA;AAAA;AAAA;AAAA;AAuBA,SAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQqD,oCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmDF,oCAAA","file":"/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/chunk-FJ56KM7M.cjs","sourcesContent":["import {\n isSQL,\n JSONSerializer,\n rawSql,\n sql,\n sqlMigration,\n type SQL,\n type SQLMigration,\n} from '@event-driven-io/dumbo';\nimport {\n expectedVersionValue,\n type DeleteOneOptions,\n type OptionalUnlessRequiredIdAndVersion,\n type PongoCollectionSQLBuilder,\n type PongoFilter,\n type PongoUpdate,\n type ReplaceOneOptions,\n type UpdateOneOptions,\n type WithoutId,\n} from '../../core';\nimport { constructFilterQuery } from './filter';\nimport { buildUpdateQuery } from './update';\n\nconst createCollection = (collectionName: string): SQL =>\n sql(\n `CREATE TABLE IF NOT EXISTS %I (\n _id TEXT PRIMARY KEY, \n data JSONB NOT NULL, \n metadata JSONB NOT NULL DEFAULT '{}',\n _version BIGINT NOT NULL DEFAULT 1,\n _partition TEXT NOT NULL DEFAULT 'png_global',\n _archived BOOLEAN NOT NULL DEFAULT FALSE,\n _created TIMESTAMPTZ NOT NULL DEFAULT now(),\n _updated TIMESTAMPTZ NOT NULL DEFAULT now()\n )`,\n collectionName,\n );\n\nexport const pongoCollectionPostgreSQLMigrations = (collectionName: string) => [\n sqlMigration(`pongoCollection:${collectionName}:001:createtable`, [\n createCollection(collectionName),\n ]),\n];\n\nexport const postgresSQLBuilder = (\n collectionName: string,\n): PongoCollectionSQLBuilder => ({\n migrations: (): SQLMigration[] =>\n pongoCollectionPostgreSQLMigrations(collectionName),\n createCollection: (): SQL => createCollection(collectionName),\n insertOne: <T>(document: OptionalUnlessRequiredIdAndVersion<T>): SQL => {\n return sql(\n 'INSERT INTO %I (_id, data, _version) VALUES (%L, %L, %L) ON CONFLICT(_id) DO NOTHING;',\n collectionName,\n document._id,\n JSONSerializer.serialize(document),\n document._version ?? 1n,\n );\n },\n insertMany: <T>(documents: OptionalUnlessRequiredIdAndVersion<T>[]): SQL => {\n const values = documents\n .map((doc) =>\n sql(\n '(%L, %L, %L)',\n doc._id,\n JSONSerializer.serialize(doc),\n doc._version ?? 1n,\n ),\n )\n .join(', ');\n return sql(\n `INSERT INTO %I (_id, data, _version) VALUES %s \n ON CONFLICT(_id) DO NOTHING\n RETURNING _id;`,\n collectionName,\n values,\n );\n },\n updateOne: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n options?: UpdateOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionUpdate =\n expectedVersion != null ? 'AND %I._version = %L' : '';\n const expectedVersionParams =\n expectedVersion != null ? [collectionName, expectedVersion] : [];\n\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n const updateQuery = isSQL(update) ? update : buildUpdateQuery(update);\n\n return sql(\n `WITH existing AS (\n SELECT _id, _version as current_version\n FROM %I %s \n LIMIT 1\n ),\n updated AS (\n UPDATE %I \n SET \n data = %s || jsonb_build_object('_id', %I._id) || jsonb_build_object('_version', (_version + 1)::text),\n _version = _version + 1\n FROM existing \n WHERE %I._id = existing._id ${expectedVersionUpdate}\n RETURNING %I._id, %I._version\n )\n SELECT \n existing._id,\n COALESCE(updated._version, existing.current_version) AS version,\n COUNT(existing._id) over() AS matched,\n COUNT(updated._id) over() AS modified\n FROM existing\n LEFT JOIN updated \n ON existing._id = updated._id;`,\n collectionName,\n where(filterQuery),\n collectionName,\n updateQuery,\n collectionName,\n collectionName,\n ...expectedVersionParams,\n collectionName,\n collectionName,\n );\n },\n replaceOne: <T>(\n filter: PongoFilter<T> | SQL,\n document: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionUpdate =\n expectedVersion != null ? 'AND %I._version = %L' : '';\n const expectedVersionParams =\n expectedVersion != null ? [collectionName, expectedVersion] : [];\n\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql(\n `WITH existing AS (\n SELECT _id, _version as current_version\n FROM %I %s \n LIMIT 1\n ),\n updated AS (\n UPDATE %I \n SET \n data = %L || jsonb_build_object('_id', %I._id) || jsonb_build_object('_version', (_version + 1)::text),\n _version = _version + 1\n FROM existing \n WHERE %I._id = existing._id ${expectedVersionUpdate}\n RETURNING %I._id, %I._version\n )\n SELECT \n existing._id,\n COALESCE(updated._version, existing.current_version) AS version,\n COUNT(existing._id) over() AS matched,\n COUNT(updated._id) over() AS modified\n FROM existing\n LEFT JOIN updated \n ON existing._id = updated._id;`,\n collectionName,\n where(filterQuery),\n collectionName,\n JSONSerializer.serialize(document),\n collectionName,\n collectionName,\n ...expectedVersionParams,\n collectionName,\n collectionName,\n );\n },\n updateMany: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n ): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n const updateQuery = isSQL(update) ? update : buildUpdateQuery(update);\n\n return sql(\n `UPDATE %I \n SET \n data = %s || jsonb_build_object('_version', (_version + 1)::text),\n _version = _version + 1\n %s;`,\n collectionName,\n updateQuery,\n where(filterQuery),\n );\n },\n deleteOne: <T>(\n filter: PongoFilter<T> | SQL,\n options?: DeleteOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionUpdate =\n expectedVersion != null ? 'AND %I._version = %L' : '';\n const expectedVersionParams =\n expectedVersion != null ? [collectionName, expectedVersion] : [];\n\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql(\n `WITH existing AS (\n SELECT _id\n FROM %I %s \n LIMIT 1\n ),\n deleted AS (\n DELETE FROM %I\n USING existing\n WHERE %I._id = existing._id ${expectedVersionUpdate}\n RETURNING %I._id\n )\n SELECT \n existing._id,\n COUNT(existing._id) over() AS matched,\n COUNT(deleted._id) over() AS deleted\n FROM existing\n LEFT JOIN deleted \n ON existing._id = deleted._id;`,\n collectionName,\n where(filterQuery),\n collectionName,\n collectionName,\n ...expectedVersionParams,\n collectionName,\n );\n },\n deleteMany: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql('DELETE FROM %I %s', collectionName, where(filterQuery));\n },\n findOne: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql(\n 'SELECT data FROM %I %s LIMIT 1;',\n collectionName,\n where(filterQuery),\n );\n },\n find: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n return sql('SELECT data FROM %I %s;', collectionName, where(filterQuery));\n },\n countDocuments: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n return sql(\n 'SELECT COUNT(1) as count FROM %I %s;',\n collectionName,\n where(filterQuery),\n );\n },\n rename: (newName: string): SQL =>\n sql('ALTER TABLE %I RENAME TO %I;', collectionName, newName),\n drop: (targetName: string = collectionName): SQL =>\n sql('DROP TABLE IF EXISTS %I', targetName),\n});\n\nconst where = (filter: string): SQL =>\n filter.length > 0 ? sql('WHERE %s', filter) : rawSql('');\n","import {\n runPostgreSQLMigrations,\n schemaComponent,\n single,\n type DatabaseTransaction,\n type Dumbo,\n type MigrationStyle,\n type QueryResult,\n type QueryResultRow,\n type SchemaComponent,\n type SQL,\n type SQLExecutor,\n type SQLMigration,\n} from '@event-driven-io/dumbo';\nimport { v4 as uuid } from 'uuid';\nimport {\n expectedVersionValue,\n operationResult,\n type CollectionOperationOptions,\n type DeleteManyOptions,\n type DeleteOneOptions,\n type DocumentHandler,\n type HandleOptions,\n type InsertManyOptions,\n type InsertOneOptions,\n type OptionalUnlessRequiredIdAndVersion,\n type PongoCollection,\n type PongoDb,\n type PongoDeleteResult,\n type PongoDocument,\n type PongoFilter,\n type PongoHandleResult,\n type PongoInsertManyResult,\n type PongoInsertOneResult,\n type PongoUpdate,\n type PongoUpdateManyResult,\n type PongoUpdateResult,\n type ReplaceOneOptions,\n type UpdateManyOptions,\n type UpdateOneOptions,\n type WithIdAndVersion,\n type WithoutId,\n type WithVersion,\n} from '..';\nimport { pongoCollectionPostgreSQLMigrations } from '../../postgres';\n\nexport type PongoCollectionOptions<ConnectorType extends string = string> = {\n db: PongoDb<ConnectorType>;\n collectionName: string;\n pool: Dumbo;\n sqlBuilder: PongoCollectionSQLBuilder;\n schema?: { autoMigration?: MigrationStyle };\n errors?: { throwOnOperationFailures?: boolean };\n};\n\nconst enlistIntoTransactionIfActive = async <\n ConnectorType extends string = string,\n>(\n db: PongoDb<ConnectorType>,\n options: CollectionOperationOptions | undefined,\n): Promise<DatabaseTransaction | null> => {\n const transaction = options?.session?.transaction;\n\n if (!transaction || !transaction.isActive) return null;\n\n return await transaction.enlistDatabase(db);\n};\n\nexport const transactionExecutorOrDefault = async <\n ConnectorType extends string = string,\n>(\n db: PongoDb<ConnectorType>,\n options: CollectionOperationOptions | undefined,\n defaultSqlExecutor: SQLExecutor,\n): Promise<SQLExecutor> => {\n const existingTransaction = await enlistIntoTransactionIfActive(db, options);\n return existingTransaction?.execute ?? defaultSqlExecutor;\n};\n\nexport const pongoCollection = <\n T extends PongoDocument,\n ConnectorType extends string = string,\n>({\n db,\n collectionName,\n pool,\n sqlBuilder: SqlFor,\n schema,\n errors,\n}: PongoCollectionOptions<ConnectorType>): PongoCollection<T> => {\n const sqlExecutor = pool.execute;\n const command = async <Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (\n await transactionExecutorOrDefault(db, options, sqlExecutor)\n ).command<Result>(sql);\n\n const query = async <T extends QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (await transactionExecutorOrDefault(db, options, sqlExecutor)).query<T>(\n sql,\n );\n\n let shouldMigrate = schema?.autoMigration !== 'None';\n\n const createCollection = (options?: CollectionOperationOptions) => {\n shouldMigrate = false;\n\n if (options?.session) return command(SqlFor.createCollection(), options);\n else return command(SqlFor.createCollection());\n };\n\n const ensureCollectionCreated = (options?: CollectionOperationOptions) => {\n if (!shouldMigrate) {\n return Promise.resolve();\n }\n\n return createCollection(options);\n };\n\n const collection = {\n dbName: db.databaseName,\n collectionName,\n createCollection: async (options?: CollectionOperationOptions) => {\n await createCollection(options);\n },\n insertOne: async (\n document: OptionalUnlessRequiredIdAndVersion<T>,\n options?: InsertOneOptions,\n ): Promise<PongoInsertOneResult> => {\n await ensureCollectionCreated(options);\n\n const _id = (document._id as string | undefined | null) ?? uuid();\n const _version = document._version ?? 1n;\n\n const result = await command(\n SqlFor.insertOne({\n ...document,\n _id,\n _version,\n } as OptionalUnlessRequiredIdAndVersion<T>),\n options,\n );\n\n const successful = (result.rowCount ?? 0) > 0;\n\n return operationResult<PongoInsertOneResult>(\n {\n successful,\n insertedId: successful ? _id : null,\n nextExpectedVersion: _version,\n },\n { operationName: 'insertOne', collectionName, errors },\n );\n },\n insertMany: async (\n documents: OptionalUnlessRequiredIdAndVersion<T>[],\n options?: InsertManyOptions,\n ): Promise<PongoInsertManyResult> => {\n await ensureCollectionCreated(options);\n\n const rows = documents.map((doc) => ({\n ...doc,\n _id: (doc._id as string | undefined | null) ?? uuid(),\n _version: doc._version ?? 1n,\n }));\n\n const result = await command(\n SqlFor.insertMany(rows as OptionalUnlessRequiredIdAndVersion<T>[]),\n options,\n );\n\n return operationResult<PongoInsertManyResult>(\n {\n successful: result.rowCount === rows.length,\n insertedCount: result.rowCount ?? 0,\n insertedIds: result.rows.map((d) => d._id as string),\n },\n { operationName: 'insertMany', collectionName, errors },\n );\n },\n updateOne: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: UpdateOneOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command<UpdateSqlResult>(\n SqlFor.updateOne(filter, update, options),\n options,\n );\n\n return operationResult<PongoUpdateResult>(\n {\n successful:\n result.rows.length > 0 &&\n result.rows[0]!.modified === result.rows[0]!.matched,\n modifiedCount: Number(result.rows[0]?.modified ?? 0),\n matchedCount: Number(result.rows[0]?.matched ?? 0),\n nextExpectedVersion: result.rows[0]?.version ?? 0n,\n },\n { operationName: 'updateOne', collectionName, errors },\n );\n },\n replaceOne: async (\n filter: PongoFilter<T>,\n document: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command<UpdateSqlResult>(\n SqlFor.replaceOne(filter, document, options),\n options,\n );\n return operationResult<PongoUpdateResult>(\n {\n successful: result.rows.length > 0 && result.rows[0]!.modified > 0,\n modifiedCount: Number(result.rows[0]?.modified ?? 0),\n matchedCount: Number(result.rows[0]?.matched ?? 0),\n nextExpectedVersion: result.rows[0]?.version ?? 0n,\n },\n { operationName: 'replaceOne', collectionName, errors },\n );\n },\n updateMany: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: UpdateManyOptions,\n ): Promise<PongoUpdateManyResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.updateMany(filter, update), options);\n\n return operationResult<PongoUpdateManyResult>(\n {\n successful: true,\n modifiedCount: result.rowCount ?? 0,\n matchedCount: result.rowCount ?? 0,\n },\n { operationName: 'updateMany', collectionName, errors },\n );\n },\n deleteOne: async (\n filter?: PongoFilter<T>,\n options?: DeleteOneOptions,\n ): Promise<PongoDeleteResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command<DeleteSqlResult>(\n SqlFor.deleteOne(filter ?? {}, options),\n options,\n );\n return operationResult<PongoDeleteResult>(\n {\n successful: result.rows.length > 0 && result.rows[0]!.deleted! > 0,\n deletedCount: Number(result.rows[0]?.deleted ?? 0),\n matchedCount: Number(result.rows[0]?.matched ?? 0),\n },\n { operationName: 'deleteOne', collectionName, errors },\n );\n },\n deleteMany: async (\n filter?: PongoFilter<T>,\n options?: DeleteManyOptions,\n ): Promise<PongoDeleteResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.deleteMany(filter ?? {}), options);\n\n return operationResult<PongoDeleteResult>(\n {\n successful: (result.rowCount ?? 0) > 0,\n deletedCount: result.rowCount ?? 0,\n matchedCount: result.rowCount ?? 0,\n },\n { operationName: 'deleteMany', collectionName, errors },\n );\n },\n findOne: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const result = await query(SqlFor.findOne(filter ?? {}), options);\n return (result.rows[0]?.data ?? null) as WithIdAndVersion<T> | null;\n },\n findOneAndDelete: async (\n filter: PongoFilter<T>,\n options?: DeleteOneOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.deleteOne(filter, options);\n return existingDoc;\n },\n findOneAndReplace: async (\n filter: PongoFilter<T>,\n replacement: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.replaceOne(filter, replacement, options);\n\n return existingDoc;\n },\n findOneAndUpdate: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: UpdateOneOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.updateOne(filter, update, options);\n\n return existingDoc;\n },\n handle: async (\n id: string,\n handle: DocumentHandler<T>,\n options?: HandleOptions,\n ): Promise<PongoHandleResult<T>> => {\n const { expectedVersion: version, ...operationOptions } = options ?? {};\n await ensureCollectionCreated(options);\n\n const byId: PongoFilter<T> = { _id: id };\n\n const existing = (await collection.findOne(\n byId,\n options,\n )) as WithVersion<T>;\n\n const expectedVersion = expectedVersionValue(version);\n\n if (\n (existing == null && version === 'DOCUMENT_EXISTS') ||\n (existing == null && expectedVersion != null) ||\n (existing != null && version === 'DOCUMENT_DOES_NOT_EXIST') ||\n (existing != null &&\n expectedVersion !== null &&\n existing._version !== expectedVersion)\n ) {\n return operationResult<PongoHandleResult<T>>(\n {\n successful: false,\n document: existing as T,\n },\n { operationName: 'handle', collectionName, errors },\n );\n }\n\n const result = await handle(existing as T);\n\n if (existing === result)\n return operationResult<PongoHandleResult<T>>(\n {\n successful: true,\n document: existing as T,\n },\n { operationName: 'handle', collectionName, errors },\n );\n\n if (!existing && result) {\n const newDoc = { ...result, _id: id };\n const insertResult = await collection.insertOne(\n { ...newDoc, _id: id } as OptionalUnlessRequiredIdAndVersion<T>,\n {\n ...operationOptions,\n expectedVersion: 'DOCUMENT_DOES_NOT_EXIST',\n },\n );\n return {\n ...insertResult,\n document: {\n ...newDoc,\n _version: insertResult.nextExpectedVersion,\n } as T,\n };\n }\n\n if (existing && !result) {\n const deleteResult = await collection.deleteOne(byId, {\n ...operationOptions,\n expectedVersion: expectedVersion ?? 'DOCUMENT_EXISTS',\n });\n return { ...deleteResult, document: null };\n }\n\n if (existing && result) {\n const replaceResult = await collection.replaceOne(byId, result, {\n ...operationOptions,\n expectedVersion: expectedVersion ?? 'DOCUMENT_EXISTS',\n });\n return {\n ...replaceResult,\n document: {\n ...result,\n _version: replaceResult.nextExpectedVersion,\n } as T,\n };\n }\n\n return operationResult<PongoHandleResult<T>>(\n {\n successful: true,\n document: existing as T,\n },\n { operationName: 'handle', collectionName, errors },\n );\n },\n find: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<WithIdAndVersion<T>[]> => {\n await ensureCollectionCreated(options);\n\n const result = await query(SqlFor.find(filter ?? {}));\n return result.rows.map((row) => row.data as WithIdAndVersion<T>);\n },\n countDocuments: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<number> => {\n await ensureCollectionCreated(options);\n\n const { count } = await single(\n query<{ count: number }>(SqlFor.countDocuments(filter ?? {})),\n );\n return count;\n },\n drop: async (options?: CollectionOperationOptions): Promise<boolean> => {\n await ensureCollectionCreated(options);\n const result = await command(SqlFor.drop());\n return (result?.rowCount ?? 0) > 0;\n },\n rename: async (\n newName: string,\n options?: CollectionOperationOptions,\n ): Promise<PongoCollection<T>> => {\n await ensureCollectionCreated(options);\n await command(SqlFor.rename(newName));\n collectionName = newName;\n return collection;\n },\n\n sql: {\n async query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<Result[]> {\n await ensureCollectionCreated(options);\n\n const result = await query<Result>(sql, options);\n return result.rows;\n },\n async command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<QueryResult<Result>> {\n await ensureCollectionCreated(options);\n\n return command(sql, options);\n },\n },\n schema: {\n get component(): SchemaComponent {\n return schemaComponent('pongo:schema_component:collection', {\n migrations: SqlFor.migrations,\n });\n },\n migrate: () => runPostgreSQLMigrations(pool, SqlFor.migrations()), // TODO: This needs to change to support more connectors\n },\n };\n\n return collection;\n};\n\nexport const pongoCollectionSchemaComponent = (collectionName: string) =>\n schemaComponent('pongo:schema_component:collection', {\n migrations: () => pongoCollectionPostgreSQLMigrations(collectionName), // TODO: This needs to change to support more connectors\n });\n\nexport type PongoCollectionSQLBuilder = {\n migrations: () => SQLMigration[];\n createCollection: () => SQL;\n insertOne: <T>(document: OptionalUnlessRequiredIdAndVersion<T>) => SQL;\n insertMany: <T>(documents: OptionalUnlessRequiredIdAndVersion<T>[]) => SQL;\n updateOne: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n options?: UpdateOneOptions,\n ) => SQL;\n replaceOne: <T>(\n filter: PongoFilter<T> | SQL,\n document: WithoutId<T>,\n options?: ReplaceOneOptions,\n ) => SQL;\n updateMany: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n ) => SQL;\n deleteOne: <T>(\n filter: PongoFilter<T> | SQL,\n options?: DeleteOneOptions,\n ) => SQL;\n deleteMany: <T>(filter: PongoFilter<T> | SQL) => SQL;\n findOne: <T>(filter: PongoFilter<T> | SQL) => SQL;\n find: <T>(filter: PongoFilter<T> | SQL) => SQL;\n countDocuments: <T>(filter: PongoFilter<T> | SQL) => SQL;\n rename: (newName: string) => SQL;\n drop: () => SQL;\n};\n\ntype UpdateSqlResult = {\n matched: bigint;\n modified: bigint;\n version: bigint;\n};\n\ntype DeleteSqlResult = {\n matched: bigint | null;\n deleted: bigint | null;\n};\n","import {\n dumbo,\n getDatabaseNameOrDefault,\n NodePostgresConnectorType,\n runPostgreSQLMigrations,\n schemaComponent,\n SQL,\n type PostgresConnector,\n type PostgresPoolOptions,\n type QueryResult,\n type QueryResultRow,\n type SchemaComponent,\n} from '@event-driven-io/dumbo';\nimport type { Document } from 'mongodb';\nimport {\n objectEntries,\n pongoCollection,\n pongoCollectionSchemaComponent,\n proxyPongoDbWithSchema,\n transactionExecutorOrDefault,\n type CollectionOperationOptions,\n type PongoCollection,\n type PongoDb,\n type PongoDbClientOptions,\n} from '../core';\nimport { postgresSQLBuilder } from './sqlBuilder';\n\nexport type PostgresDbClientOptions = PongoDbClientOptions<PostgresConnector>;\n\nexport const isPostgresClientOptions = (\n options: PongoDbClientOptions,\n): options is PostgresDbClientOptions =>\n options.connectorType === NodePostgresConnectorType;\n\nexport const postgresDb = (\n options: PostgresDbClientOptions,\n): PongoDb<PostgresConnector> => {\n const { connectionString, dbName } = options;\n const databaseName = dbName ?? getDatabaseNameOrDefault(connectionString);\n\n const pool = dumbo<PostgresPoolOptions>({\n connectionString,\n ...options.connectionOptions,\n });\n\n const collections = new Map<string, PongoCollection<Document>>();\n\n const command = async <Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (\n await transactionExecutorOrDefault(db, options, pool.execute)\n ).command<Result>(sql);\n\n const query = async <T extends QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (await transactionExecutorOrDefault(db, options, pool.execute)).query<T>(\n sql,\n );\n\n const db: PongoDb<PostgresConnector> = {\n connectorType: options.connectorType,\n databaseName,\n connect: () => Promise.resolve(),\n close: () => pool.close(),\n\n collections: () => [...collections.values()],\n collection: (collectionName) =>\n pongoCollection({\n collectionName,\n db,\n pool,\n sqlBuilder: postgresSQLBuilder(collectionName),\n schema: options.schema ? options.schema : {},\n errors: options.errors ? options.errors : {},\n }),\n transaction: () => pool.transaction(),\n withTransaction: (handle) => pool.withTransaction(handle),\n\n schema: {\n get component(): SchemaComponent {\n return schemaComponent('pongoDb', {\n components: [...collections.values()].map((c) => c.schema.component),\n });\n },\n migrate: () =>\n runPostgreSQLMigrations(\n pool,\n [...collections.values()].flatMap((c) =>\n // TODO: This needs to change to support more connectors\n c.schema.component.migrations({ connector: 'PostgreSQL:pg' }),\n ),\n ),\n },\n\n sql: {\n async query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<Result[]> {\n const result = await query<Result>(sql, options);\n return result.rows;\n },\n async command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<QueryResult<Result>> {\n return command(sql, options);\n },\n },\n };\n\n const dbsSchema = options?.schema?.definition?.dbs;\n\n if (dbsSchema) {\n const dbSchema = objectEntries(dbsSchema)\n .map((e) => e[1])\n .find((db) => db.name === dbName || db.name === databaseName);\n\n if (dbSchema) return proxyPongoDbWithSchema(db, dbSchema, collections);\n }\n\n return db;\n};\n\nexport const pongoDbSchemaComponent = (\n collections: string[] | SchemaComponent[],\n) => {\n const components =\n collections.length > 0 && typeof collections[0] === 'string'\n ? collections.map((collectionName) =>\n pongoCollectionSchemaComponent(collectionName as string),\n )\n : (collections as SchemaComponent[]);\n\n return schemaComponent('pongo:schema_component:db', {\n components,\n });\n};\n","export const QueryOperators = {\n $eq: '$eq',\n $gt: '$gt',\n $gte: '$gte',\n $lt: '$lt',\n $lte: '$lte',\n $ne: '$ne',\n $in: '$in',\n $nin: '$nin',\n $elemMatch: '$elemMatch',\n $all: '$all',\n $size: '$size',\n};\n\nexport const OperatorMap = {\n $gt: '>',\n $gte: '>=',\n $lt: '<',\n $lte: '<=',\n $ne: '!=',\n};\n\nexport const isOperator = (key: string) => key.startsWith('$');\n\nexport const hasOperators = (value: Record<string, unknown>) =>\n Object.keys(value).some(isOperator);\n","export const isNumber = (val: unknown): val is number =>\n typeof val === 'number' && val === val;\n\nexport const isString = (val: unknown): val is string =>\n typeof val === 'string';\n\nexport class PongoError extends Error {\n public errorCode: number;\n\n constructor(\n options?: { errorCode: number; message?: string } | string | number,\n ) {\n const errorCode =\n options && typeof options === 'object' && 'errorCode' in options\n ? options.errorCode\n : isNumber(options)\n ? options\n : 500;\n const message =\n options && typeof options === 'object' && 'message' in options\n ? options.message\n : isString(options)\n ? options\n : `Error with status code '${errorCode}' ocurred during Pongo processing`;\n\n super(message);\n this.errorCode = errorCode;\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, PongoError.prototype);\n }\n}\n\nexport class ConcurrencyError extends PongoError {\n constructor(message?: string) {\n super({\n errorCode: 412,\n message: message ?? `Expected document state does not match current one!`,\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, ConcurrencyError.prototype);\n }\n}\n","import {\n NodePostgresConnectorType,\n type MigrationStyle,\n type NodePostgresConnection,\n} from '@event-driven-io/dumbo';\nimport pg from 'pg';\nimport type { PostgresDbClientOptions } from '../postgres';\nimport { getPongoDb, type AllowedDbClientOptions } from './pongoDb';\nimport { pongoSession } from './pongoSession';\nimport {\n proxyClientWithSchema,\n type PongoClientSchema,\n type PongoClientWithSchema,\n} from './schema';\nimport type { PongoClient, PongoDb, PongoSession } from './typing';\n\nexport type PooledPongoClientOptions =\n | {\n pool: pg.Pool;\n }\n | {\n pooled: true;\n }\n | {\n pool: pg.Pool;\n pooled: true;\n }\n | object;\n\nexport type NotPooledPongoOptions =\n | {\n client: pg.Client;\n }\n | {\n pooled: false;\n }\n | {\n client: pg.Client;\n pooled: false;\n }\n | {\n connection: NodePostgresConnection;\n pooled?: false;\n };\n\nexport type PongoClientOptions<\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n> = {\n schema?: { autoMigration?: MigrationStyle; definition?: TypedClientSchema };\n errors?: { throwOnOperationFailures?: boolean };\n connectionOptions?: PooledPongoClientOptions | NotPooledPongoOptions;\n};\n\nexport const pongoClient = <\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n connectionString: string,\n options: PongoClientOptions<TypedClientSchema> = {},\n): PongoClient & PongoClientWithSchema<TypedClientSchema> => {\n const dbClients = new Map<string, PongoDb>();\n\n const dbClient = getPongoDb<DbClientOptions>(\n clientToDbOptions({\n connectionString,\n clientOptions: options,\n }),\n );\n dbClients.set(dbClient.databaseName, dbClient);\n\n const pongoClient: PongoClient = {\n connect: async () => {\n await dbClient.connect();\n return pongoClient;\n },\n close: async () => {\n for (const db of dbClients.values()) {\n await db.close();\n }\n },\n db: (dbName?: string): PongoDb => {\n if (!dbName) return dbClient;\n\n return (\n dbClients.get(dbName) ??\n dbClients\n .set(\n dbName,\n getPongoDb<DbClientOptions>(\n clientToDbOptions({\n connectionString,\n dbName,\n clientOptions: options,\n }),\n ),\n )\n .get(dbName)!\n );\n },\n startSession: pongoSession,\n withSession: async <T>(\n callback: (session: PongoSession) => Promise<T>,\n ): Promise<T> => {\n const session = pongoSession();\n\n try {\n return await callback(session);\n } finally {\n await session.endSession();\n }\n },\n };\n\n return proxyClientWithSchema(pongoClient, options?.schema?.definition);\n};\n\nexport const clientToDbOptions = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(options: {\n connectionString: string;\n dbName?: string;\n clientOptions: PongoClientOptions;\n}): DbClientOptions => {\n const postgreSQLOptions: PostgresDbClientOptions = {\n connectorType: NodePostgresConnectorType,\n connectionString: options.connectionString,\n dbName: options.dbName,\n ...options.clientOptions,\n };\n\n return postgreSQLOptions as DbClientOptions;\n};\n","import {\n isPostgresClientOptions,\n postgresDb,\n type PostgresDbClientOptions,\n} from '../postgres';\nimport type { PongoClientOptions } from './pongoClient';\nimport type { PongoDb } from './typing';\n\nexport type PongoDbClientOptions<ConnectorType extends string = string> = {\n connectorType: ConnectorType;\n connectionString: string;\n dbName: string | undefined;\n} & PongoClientOptions;\n\nexport type AllowedDbClientOptions = PostgresDbClientOptions;\n\nexport const getPongoDb = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n options: DbClientOptions,\n): PongoDb => {\n const { connectorType: type } = options;\n // This is the place where in the future could come resolution of other database types\n if (!isPostgresClientOptions(options))\n throw new Error(`Unsupported db type: ${type}`);\n\n return postgresDb(options);\n};\n"]}
1
+ {"version":3,"sources":["../src/postgres/sqlBuilder/index.ts","../src/core/collection/pongoCollection.ts","../src/postgres/dbClient.ts","../src/core/collection/query.ts","../src/core/errors/index.ts","../src/core/pongoClient.ts","../src/core/pongoDb.ts"],"names":["isPostgresClientOptions","options","NodePostgresConnectorType","postgresDb","connectionString","dbName","databaseName","getDatabaseNameOrDefault","pool","dumbo","collections","command","sql","transactionExecutorOrDefault","db","query","collectionName","pongoCollection","postgresSQLBuilder","handle","schemaComponent","c","runPostgreSQLMigrations","dbsSchema","dbSchema","objectEntries","e","proxyPongoDbWithSchema","pongoDbSchemaComponent","components","pongoCollectionSchemaComponent","enlistIntoTransactionIfActive","transaction","defaultSqlExecutor","SqlFor","schema","errors","sqlExecutor","shouldMigrate","createCollection","ensureCollectionCreated","collection","document","_id","uuid","_version","successful","operationResult","documents","rows","doc","result","d","filter","update","existingDoc","replacement","id","version","operationOptions","byId","existing","expectedVersion","expectedVersionValue","newDoc","insertResult","replaceResult","row","count","single","newName","pongoCollectionPostgreSQLMigrations","QueryOperators","OperatorMap","isOperator","key","hasOperators","value","isNumber","val","isString","PongoError","_PongoError","errorCode","message","ConcurrencyError","_ConcurrencyError","getPongoDb","type"],"mappings":"AAAA,g3CAQO,4BCMoB,ICedA,CAAAA,CACXC,CAAAA,EAEAA,CAAAA,CAAQ,aAAA,GAAkBC,gCAAAA,CAEfC,CAAAA,aACXF,CAAAA,EAC+B,CAC/B,GAAM,CAAE,gBAAA,CAAAG,CAAAA,CAAkB,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AAA;AAAA;AAAA;AAoCrD,oCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWqD,oCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA8BrD,oCAAA;AAAA;AAAA;AAAA;AAuBA,SAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQqD,oCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmDF,oCAAA","file":"/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/chunk-BLT4TSB5.cjs","sourcesContent":["import {\n isSQL,\n JSONSerializer,\n rawSql,\n sql,\n sqlMigration,\n type SQL,\n type SQLMigration,\n} from '@event-driven-io/dumbo';\nimport {\n expectedVersionValue,\n type DeleteOneOptions,\n type OptionalUnlessRequiredIdAndVersion,\n type PongoCollectionSQLBuilder,\n type PongoFilter,\n type PongoUpdate,\n type ReplaceOneOptions,\n type UpdateOneOptions,\n type WithoutId,\n} from '../../core';\nimport { constructFilterQuery } from './filter';\nimport { buildUpdateQuery } from './update';\n\nconst createCollection = (collectionName: string): SQL =>\n sql(\n `CREATE TABLE IF NOT EXISTS %I (\n _id TEXT PRIMARY KEY, \n data JSONB NOT NULL, \n metadata JSONB NOT NULL DEFAULT '{}',\n _version BIGINT NOT NULL DEFAULT 1,\n _partition TEXT NOT NULL DEFAULT 'png_global',\n _archived BOOLEAN NOT NULL DEFAULT FALSE,\n _created TIMESTAMPTZ NOT NULL DEFAULT now(),\n _updated TIMESTAMPTZ NOT NULL DEFAULT now()\n )`,\n collectionName,\n );\n\nexport const pongoCollectionPostgreSQLMigrations = (collectionName: string) => [\n sqlMigration(`pongoCollection:${collectionName}:001:createtable`, [\n createCollection(collectionName),\n ]),\n];\n\nexport const postgresSQLBuilder = (\n collectionName: string,\n): PongoCollectionSQLBuilder => ({\n migrations: (): SQLMigration[] =>\n pongoCollectionPostgreSQLMigrations(collectionName),\n createCollection: (): SQL => createCollection(collectionName),\n insertOne: <T>(document: OptionalUnlessRequiredIdAndVersion<T>): SQL => {\n return sql(\n 'INSERT INTO %I (_id, data, _version) VALUES (%L, %L, %L) ON CONFLICT(_id) DO NOTHING;',\n collectionName,\n document._id,\n JSONSerializer.serialize(document),\n document._version ?? 1n,\n );\n },\n insertMany: <T>(documents: OptionalUnlessRequiredIdAndVersion<T>[]): SQL => {\n const values = documents\n .map((doc) =>\n sql(\n '(%L, %L, %L)',\n doc._id,\n JSONSerializer.serialize(doc),\n doc._version ?? 1n,\n ),\n )\n .join(', ');\n return sql(\n `INSERT INTO %I (_id, data, _version) VALUES %s \n ON CONFLICT(_id) DO NOTHING\n RETURNING _id;`,\n collectionName,\n values,\n );\n },\n updateOne: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n options?: UpdateOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionUpdate =\n expectedVersion != null ? 'AND %I._version = %L' : '';\n const expectedVersionParams =\n expectedVersion != null ? [collectionName, expectedVersion] : [];\n\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n const updateQuery = isSQL(update) ? update : buildUpdateQuery(update);\n\n return sql(\n `WITH existing AS (\n SELECT _id, _version as current_version\n FROM %I %s \n LIMIT 1\n ),\n updated AS (\n UPDATE %I \n SET \n data = %s || jsonb_build_object('_id', %I._id) || jsonb_build_object('_version', (_version + 1)::text),\n _version = _version + 1\n FROM existing \n WHERE %I._id = existing._id ${expectedVersionUpdate}\n RETURNING %I._id, %I._version\n )\n SELECT \n existing._id,\n COALESCE(updated._version, existing.current_version) AS version,\n COUNT(existing._id) over() AS matched,\n COUNT(updated._id) over() AS modified\n FROM existing\n LEFT JOIN updated \n ON existing._id = updated._id;`,\n collectionName,\n where(filterQuery),\n collectionName,\n updateQuery,\n collectionName,\n collectionName,\n ...expectedVersionParams,\n collectionName,\n collectionName,\n );\n },\n replaceOne: <T>(\n filter: PongoFilter<T> | SQL,\n document: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionUpdate =\n expectedVersion != null ? 'AND %I._version = %L' : '';\n const expectedVersionParams =\n expectedVersion != null ? [collectionName, expectedVersion] : [];\n\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql(\n `WITH existing AS (\n SELECT _id, _version as current_version\n FROM %I %s \n LIMIT 1\n ),\n updated AS (\n UPDATE %I \n SET \n data = %L || jsonb_build_object('_id', %I._id) || jsonb_build_object('_version', (_version + 1)::text),\n _version = _version + 1\n FROM existing \n WHERE %I._id = existing._id ${expectedVersionUpdate}\n RETURNING %I._id, %I._version\n )\n SELECT \n existing._id,\n COALESCE(updated._version, existing.current_version) AS version,\n COUNT(existing._id) over() AS matched,\n COUNT(updated._id) over() AS modified\n FROM existing\n LEFT JOIN updated \n ON existing._id = updated._id;`,\n collectionName,\n where(filterQuery),\n collectionName,\n JSONSerializer.serialize(document),\n collectionName,\n collectionName,\n ...expectedVersionParams,\n collectionName,\n collectionName,\n );\n },\n updateMany: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n ): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n const updateQuery = isSQL(update) ? update : buildUpdateQuery(update);\n\n return sql(\n `UPDATE %I \n SET \n data = %s || jsonb_build_object('_version', (_version + 1)::text),\n _version = _version + 1\n %s;`,\n collectionName,\n updateQuery,\n where(filterQuery),\n );\n },\n deleteOne: <T>(\n filter: PongoFilter<T> | SQL,\n options?: DeleteOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionUpdate =\n expectedVersion != null ? 'AND %I._version = %L' : '';\n const expectedVersionParams =\n expectedVersion != null ? [collectionName, expectedVersion] : [];\n\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql(\n `WITH existing AS (\n SELECT _id\n FROM %I %s \n LIMIT 1\n ),\n deleted AS (\n DELETE FROM %I\n USING existing\n WHERE %I._id = existing._id ${expectedVersionUpdate}\n RETURNING %I._id\n )\n SELECT \n existing._id,\n COUNT(existing._id) over() AS matched,\n COUNT(deleted._id) over() AS deleted\n FROM existing\n LEFT JOIN deleted \n ON existing._id = deleted._id;`,\n collectionName,\n where(filterQuery),\n collectionName,\n collectionName,\n ...expectedVersionParams,\n collectionName,\n );\n },\n deleteMany: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql('DELETE FROM %I %s', collectionName, where(filterQuery));\n },\n findOne: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql(\n 'SELECT data FROM %I %s LIMIT 1;',\n collectionName,\n where(filterQuery),\n );\n },\n find: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n return sql('SELECT data FROM %I %s;', collectionName, where(filterQuery));\n },\n countDocuments: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n return sql(\n 'SELECT COUNT(1) as count FROM %I %s;',\n collectionName,\n where(filterQuery),\n );\n },\n rename: (newName: string): SQL =>\n sql('ALTER TABLE %I RENAME TO %I;', collectionName, newName),\n drop: (targetName: string = collectionName): SQL =>\n sql('DROP TABLE IF EXISTS %I', targetName),\n});\n\nconst where = (filter: string): SQL =>\n filter.length > 0 ? sql('WHERE %s', filter) : rawSql('');\n","import {\n runPostgreSQLMigrations,\n schemaComponent,\n single,\n type DatabaseTransaction,\n type Dumbo,\n type MigrationStyle,\n type QueryResult,\n type QueryResultRow,\n type SchemaComponent,\n type SQL,\n type SQLExecutor,\n type SQLMigration,\n} from '@event-driven-io/dumbo';\nimport { v7 as uuid } from 'uuid';\nimport {\n expectedVersionValue,\n operationResult,\n type CollectionOperationOptions,\n type DeleteManyOptions,\n type DeleteOneOptions,\n type DocumentHandler,\n type HandleOptions,\n type InsertManyOptions,\n type InsertOneOptions,\n type OptionalUnlessRequiredIdAndVersion,\n type PongoCollection,\n type PongoDb,\n type PongoDeleteResult,\n type PongoDocument,\n type PongoFilter,\n type PongoHandleResult,\n type PongoInsertManyResult,\n type PongoInsertOneResult,\n type PongoUpdate,\n type PongoUpdateManyResult,\n type PongoUpdateResult,\n type ReplaceOneOptions,\n type UpdateManyOptions,\n type UpdateOneOptions,\n type WithIdAndVersion,\n type WithoutId,\n type WithVersion,\n} from '..';\nimport { pongoCollectionPostgreSQLMigrations } from '../../postgres';\n\nexport type PongoCollectionOptions<ConnectorType extends string = string> = {\n db: PongoDb<ConnectorType>;\n collectionName: string;\n pool: Dumbo;\n sqlBuilder: PongoCollectionSQLBuilder;\n schema?: { autoMigration?: MigrationStyle };\n errors?: { throwOnOperationFailures?: boolean };\n};\n\nconst enlistIntoTransactionIfActive = async <\n ConnectorType extends string = string,\n>(\n db: PongoDb<ConnectorType>,\n options: CollectionOperationOptions | undefined,\n): Promise<DatabaseTransaction | null> => {\n const transaction = options?.session?.transaction;\n\n if (!transaction || !transaction.isActive) return null;\n\n return await transaction.enlistDatabase(db);\n};\n\nexport const transactionExecutorOrDefault = async <\n ConnectorType extends string = string,\n>(\n db: PongoDb<ConnectorType>,\n options: CollectionOperationOptions | undefined,\n defaultSqlExecutor: SQLExecutor,\n): Promise<SQLExecutor> => {\n const existingTransaction = await enlistIntoTransactionIfActive(db, options);\n return existingTransaction?.execute ?? defaultSqlExecutor;\n};\n\nexport const pongoCollection = <\n T extends PongoDocument,\n ConnectorType extends string = string,\n>({\n db,\n collectionName,\n pool,\n sqlBuilder: SqlFor,\n schema,\n errors,\n}: PongoCollectionOptions<ConnectorType>): PongoCollection<T> => {\n const sqlExecutor = pool.execute;\n const command = async <Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (\n await transactionExecutorOrDefault(db, options, sqlExecutor)\n ).command<Result>(sql);\n\n const query = async <T extends QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (await transactionExecutorOrDefault(db, options, sqlExecutor)).query<T>(\n sql,\n );\n\n let shouldMigrate = schema?.autoMigration !== 'None';\n\n const createCollection = (options?: CollectionOperationOptions) => {\n shouldMigrate = false;\n\n if (options?.session) return command(SqlFor.createCollection(), options);\n else return command(SqlFor.createCollection());\n };\n\n const ensureCollectionCreated = (options?: CollectionOperationOptions) => {\n if (!shouldMigrate) {\n return Promise.resolve();\n }\n\n return createCollection(options);\n };\n\n const collection = {\n dbName: db.databaseName,\n collectionName,\n createCollection: async (options?: CollectionOperationOptions) => {\n await createCollection(options);\n },\n insertOne: async (\n document: OptionalUnlessRequiredIdAndVersion<T>,\n options?: InsertOneOptions,\n ): Promise<PongoInsertOneResult> => {\n await ensureCollectionCreated(options);\n\n const _id = (document._id as string | undefined | null) ?? uuid();\n const _version = document._version ?? 1n;\n\n const result = await command(\n SqlFor.insertOne({\n ...document,\n _id,\n _version,\n } as OptionalUnlessRequiredIdAndVersion<T>),\n options,\n );\n\n const successful = (result.rowCount ?? 0) > 0;\n\n return operationResult<PongoInsertOneResult>(\n {\n successful,\n insertedId: successful ? _id : null,\n nextExpectedVersion: _version,\n },\n { operationName: 'insertOne', collectionName, errors },\n );\n },\n insertMany: async (\n documents: OptionalUnlessRequiredIdAndVersion<T>[],\n options?: InsertManyOptions,\n ): Promise<PongoInsertManyResult> => {\n await ensureCollectionCreated(options);\n\n const rows = documents.map((doc) => ({\n ...doc,\n _id: (doc._id as string | undefined | null) ?? uuid(),\n _version: doc._version ?? 1n,\n }));\n\n const result = await command(\n SqlFor.insertMany(rows as OptionalUnlessRequiredIdAndVersion<T>[]),\n options,\n );\n\n return operationResult<PongoInsertManyResult>(\n {\n successful: result.rowCount === rows.length,\n insertedCount: result.rowCount ?? 0,\n insertedIds: result.rows.map((d) => d._id as string),\n },\n { operationName: 'insertMany', collectionName, errors },\n );\n },\n updateOne: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: UpdateOneOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command<UpdateSqlResult>(\n SqlFor.updateOne(filter, update, options),\n options,\n );\n\n return operationResult<PongoUpdateResult>(\n {\n successful:\n result.rows.length > 0 &&\n result.rows[0]!.modified === result.rows[0]!.matched,\n modifiedCount: Number(result.rows[0]?.modified ?? 0),\n matchedCount: Number(result.rows[0]?.matched ?? 0),\n nextExpectedVersion: result.rows[0]?.version ?? 0n,\n },\n { operationName: 'updateOne', collectionName, errors },\n );\n },\n replaceOne: async (\n filter: PongoFilter<T>,\n document: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command<UpdateSqlResult>(\n SqlFor.replaceOne(filter, document, options),\n options,\n );\n return operationResult<PongoUpdateResult>(\n {\n successful: result.rows.length > 0 && result.rows[0]!.modified > 0,\n modifiedCount: Number(result.rows[0]?.modified ?? 0),\n matchedCount: Number(result.rows[0]?.matched ?? 0),\n nextExpectedVersion: result.rows[0]?.version ?? 0n,\n },\n { operationName: 'replaceOne', collectionName, errors },\n );\n },\n updateMany: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: UpdateManyOptions,\n ): Promise<PongoUpdateManyResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.updateMany(filter, update), options);\n\n return operationResult<PongoUpdateManyResult>(\n {\n successful: true,\n modifiedCount: result.rowCount ?? 0,\n matchedCount: result.rowCount ?? 0,\n },\n { operationName: 'updateMany', collectionName, errors },\n );\n },\n deleteOne: async (\n filter?: PongoFilter<T>,\n options?: DeleteOneOptions,\n ): Promise<PongoDeleteResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command<DeleteSqlResult>(\n SqlFor.deleteOne(filter ?? {}, options),\n options,\n );\n return operationResult<PongoDeleteResult>(\n {\n successful: result.rows.length > 0 && result.rows[0]!.deleted! > 0,\n deletedCount: Number(result.rows[0]?.deleted ?? 0),\n matchedCount: Number(result.rows[0]?.matched ?? 0),\n },\n { operationName: 'deleteOne', collectionName, errors },\n );\n },\n deleteMany: async (\n filter?: PongoFilter<T>,\n options?: DeleteManyOptions,\n ): Promise<PongoDeleteResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.deleteMany(filter ?? {}), options);\n\n return operationResult<PongoDeleteResult>(\n {\n successful: (result.rowCount ?? 0) > 0,\n deletedCount: result.rowCount ?? 0,\n matchedCount: result.rowCount ?? 0,\n },\n { operationName: 'deleteMany', collectionName, errors },\n );\n },\n findOne: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const result = await query(SqlFor.findOne(filter ?? {}), options);\n return (result.rows[0]?.data ?? null) as WithIdAndVersion<T> | null;\n },\n findOneAndDelete: async (\n filter: PongoFilter<T>,\n options?: DeleteOneOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.deleteOne(filter, options);\n return existingDoc;\n },\n findOneAndReplace: async (\n filter: PongoFilter<T>,\n replacement: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.replaceOne(filter, replacement, options);\n\n return existingDoc;\n },\n findOneAndUpdate: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: UpdateOneOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.updateOne(filter, update, options);\n\n return existingDoc;\n },\n handle: async (\n id: string,\n handle: DocumentHandler<T>,\n options?: HandleOptions,\n ): Promise<PongoHandleResult<T>> => {\n const { expectedVersion: version, ...operationOptions } = options ?? {};\n await ensureCollectionCreated(options);\n\n const byId: PongoFilter<T> = { _id: id };\n\n const existing = (await collection.findOne(\n byId,\n options,\n )) as WithVersion<T>;\n\n const expectedVersion = expectedVersionValue(version);\n\n if (\n (existing == null && version === 'DOCUMENT_EXISTS') ||\n (existing == null && expectedVersion != null) ||\n (existing != null && version === 'DOCUMENT_DOES_NOT_EXIST') ||\n (existing != null &&\n expectedVersion !== null &&\n existing._version !== expectedVersion)\n ) {\n return operationResult<PongoHandleResult<T>>(\n {\n successful: false,\n document: existing as T,\n },\n { operationName: 'handle', collectionName, errors },\n );\n }\n\n const result = await handle(existing as T);\n\n if (existing === result)\n return operationResult<PongoHandleResult<T>>(\n {\n successful: true,\n document: existing as T,\n },\n { operationName: 'handle', collectionName, errors },\n );\n\n if (!existing && result) {\n const newDoc = { ...result, _id: id };\n const insertResult = await collection.insertOne(\n { ...newDoc, _id: id } as OptionalUnlessRequiredIdAndVersion<T>,\n {\n ...operationOptions,\n expectedVersion: 'DOCUMENT_DOES_NOT_EXIST',\n },\n );\n return {\n ...insertResult,\n document: {\n ...newDoc,\n _version: insertResult.nextExpectedVersion,\n } as T,\n };\n }\n\n if (existing && !result) {\n const deleteResult = await collection.deleteOne(byId, {\n ...operationOptions,\n expectedVersion: expectedVersion ?? 'DOCUMENT_EXISTS',\n });\n return { ...deleteResult, document: null };\n }\n\n if (existing && result) {\n const replaceResult = await collection.replaceOne(byId, result, {\n ...operationOptions,\n expectedVersion: expectedVersion ?? 'DOCUMENT_EXISTS',\n });\n return {\n ...replaceResult,\n document: {\n ...result,\n _version: replaceResult.nextExpectedVersion,\n } as T,\n };\n }\n\n return operationResult<PongoHandleResult<T>>(\n {\n successful: true,\n document: existing as T,\n },\n { operationName: 'handle', collectionName, errors },\n );\n },\n find: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<WithIdAndVersion<T>[]> => {\n await ensureCollectionCreated(options);\n\n const result = await query(SqlFor.find(filter ?? {}));\n return result.rows.map((row) => row.data as WithIdAndVersion<T>);\n },\n countDocuments: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<number> => {\n await ensureCollectionCreated(options);\n\n const { count } = await single(\n query<{ count: number }>(SqlFor.countDocuments(filter ?? {})),\n );\n return count;\n },\n drop: async (options?: CollectionOperationOptions): Promise<boolean> => {\n await ensureCollectionCreated(options);\n const result = await command(SqlFor.drop());\n return (result?.rowCount ?? 0) > 0;\n },\n rename: async (\n newName: string,\n options?: CollectionOperationOptions,\n ): Promise<PongoCollection<T>> => {\n await ensureCollectionCreated(options);\n await command(SqlFor.rename(newName));\n collectionName = newName;\n return collection;\n },\n\n sql: {\n async query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<Result[]> {\n await ensureCollectionCreated(options);\n\n const result = await query<Result>(sql, options);\n return result.rows;\n },\n async command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<QueryResult<Result>> {\n await ensureCollectionCreated(options);\n\n return command(sql, options);\n },\n },\n schema: {\n get component(): SchemaComponent {\n return schemaComponent('pongo:schema_component:collection', {\n migrations: SqlFor.migrations,\n });\n },\n migrate: () => runPostgreSQLMigrations(pool, SqlFor.migrations()), // TODO: This needs to change to support more connectors\n },\n };\n\n return collection;\n};\n\nexport const pongoCollectionSchemaComponent = (collectionName: string) =>\n schemaComponent('pongo:schema_component:collection', {\n migrations: () => pongoCollectionPostgreSQLMigrations(collectionName), // TODO: This needs to change to support more connectors\n });\n\nexport type PongoCollectionSQLBuilder = {\n migrations: () => SQLMigration[];\n createCollection: () => SQL;\n insertOne: <T>(document: OptionalUnlessRequiredIdAndVersion<T>) => SQL;\n insertMany: <T>(documents: OptionalUnlessRequiredIdAndVersion<T>[]) => SQL;\n updateOne: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n options?: UpdateOneOptions,\n ) => SQL;\n replaceOne: <T>(\n filter: PongoFilter<T> | SQL,\n document: WithoutId<T>,\n options?: ReplaceOneOptions,\n ) => SQL;\n updateMany: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n ) => SQL;\n deleteOne: <T>(\n filter: PongoFilter<T> | SQL,\n options?: DeleteOneOptions,\n ) => SQL;\n deleteMany: <T>(filter: PongoFilter<T> | SQL) => SQL;\n findOne: <T>(filter: PongoFilter<T> | SQL) => SQL;\n find: <T>(filter: PongoFilter<T> | SQL) => SQL;\n countDocuments: <T>(filter: PongoFilter<T> | SQL) => SQL;\n rename: (newName: string) => SQL;\n drop: () => SQL;\n};\n\ntype UpdateSqlResult = {\n matched: bigint;\n modified: bigint;\n version: bigint;\n};\n\ntype DeleteSqlResult = {\n matched: bigint | null;\n deleted: bigint | null;\n};\n","import {\n dumbo,\n getDatabaseNameOrDefault,\n NodePostgresConnectorType,\n runPostgreSQLMigrations,\n schemaComponent,\n SQL,\n type PostgresConnector,\n type PostgresPoolOptions,\n type QueryResult,\n type QueryResultRow,\n type SchemaComponent,\n} from '@event-driven-io/dumbo';\nimport type { Document } from 'mongodb';\nimport {\n objectEntries,\n pongoCollection,\n pongoCollectionSchemaComponent,\n proxyPongoDbWithSchema,\n transactionExecutorOrDefault,\n type CollectionOperationOptions,\n type PongoCollection,\n type PongoDb,\n type PongoDbClientOptions,\n} from '../core';\nimport { postgresSQLBuilder } from './sqlBuilder';\n\nexport type PostgresDbClientOptions = PongoDbClientOptions<PostgresConnector>;\n\nexport const isPostgresClientOptions = (\n options: PongoDbClientOptions,\n): options is PostgresDbClientOptions =>\n options.connectorType === NodePostgresConnectorType;\n\nexport const postgresDb = (\n options: PostgresDbClientOptions,\n): PongoDb<PostgresConnector> => {\n const { connectionString, dbName } = options;\n const databaseName = dbName ?? getDatabaseNameOrDefault(connectionString);\n\n const pool = dumbo<PostgresPoolOptions>({\n connectionString,\n ...options.connectionOptions,\n });\n\n const collections = new Map<string, PongoCollection<Document>>();\n\n const command = async <Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (\n await transactionExecutorOrDefault(db, options, pool.execute)\n ).command<Result>(sql);\n\n const query = async <T extends QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (await transactionExecutorOrDefault(db, options, pool.execute)).query<T>(\n sql,\n );\n\n const db: PongoDb<PostgresConnector> = {\n connectorType: options.connectorType,\n databaseName,\n connect: () => Promise.resolve(),\n close: () => pool.close(),\n\n collections: () => [...collections.values()],\n collection: (collectionName) =>\n pongoCollection({\n collectionName,\n db,\n pool,\n sqlBuilder: postgresSQLBuilder(collectionName),\n schema: options.schema ? options.schema : {},\n errors: options.errors ? options.errors : {},\n }),\n transaction: () => pool.transaction(),\n withTransaction: (handle) => pool.withTransaction(handle),\n\n schema: {\n get component(): SchemaComponent {\n return schemaComponent('pongoDb', {\n components: [...collections.values()].map((c) => c.schema.component),\n });\n },\n migrate: () =>\n runPostgreSQLMigrations(\n pool,\n [...collections.values()].flatMap((c) =>\n // TODO: This needs to change to support more connectors\n c.schema.component.migrations({ connector: 'PostgreSQL:pg' }),\n ),\n ),\n },\n\n sql: {\n async query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<Result[]> {\n const result = await query<Result>(sql, options);\n return result.rows;\n },\n async command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<QueryResult<Result>> {\n return command(sql, options);\n },\n },\n };\n\n const dbsSchema = options?.schema?.definition?.dbs;\n\n if (dbsSchema) {\n const dbSchema = objectEntries(dbsSchema)\n .map((e) => e[1])\n .find((db) => db.name === dbName || db.name === databaseName);\n\n if (dbSchema) return proxyPongoDbWithSchema(db, dbSchema, collections);\n }\n\n return db;\n};\n\nexport const pongoDbSchemaComponent = (\n collections: string[] | SchemaComponent[],\n) => {\n const components =\n collections.length > 0 && typeof collections[0] === 'string'\n ? collections.map((collectionName) =>\n pongoCollectionSchemaComponent(collectionName as string),\n )\n : (collections as SchemaComponent[]);\n\n return schemaComponent('pongo:schema_component:db', {\n components,\n });\n};\n","export const QueryOperators = {\n $eq: '$eq',\n $gt: '$gt',\n $gte: '$gte',\n $lt: '$lt',\n $lte: '$lte',\n $ne: '$ne',\n $in: '$in',\n $nin: '$nin',\n $elemMatch: '$elemMatch',\n $all: '$all',\n $size: '$size',\n};\n\nexport const OperatorMap = {\n $gt: '>',\n $gte: '>=',\n $lt: '<',\n $lte: '<=',\n $ne: '!=',\n};\n\nexport const isOperator = (key: string) => key.startsWith('$');\n\nexport const hasOperators = (value: Record<string, unknown>) =>\n Object.keys(value).some(isOperator);\n","export const isNumber = (val: unknown): val is number =>\n typeof val === 'number' && val === val;\n\nexport const isString = (val: unknown): val is string =>\n typeof val === 'string';\n\nexport class PongoError extends Error {\n public errorCode: number;\n\n constructor(\n options?: { errorCode: number; message?: string } | string | number,\n ) {\n const errorCode =\n options && typeof options === 'object' && 'errorCode' in options\n ? options.errorCode\n : isNumber(options)\n ? options\n : 500;\n const message =\n options && typeof options === 'object' && 'message' in options\n ? options.message\n : isString(options)\n ? options\n : `Error with status code '${errorCode}' ocurred during Pongo processing`;\n\n super(message);\n this.errorCode = errorCode;\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, PongoError.prototype);\n }\n}\n\nexport class ConcurrencyError extends PongoError {\n constructor(message?: string) {\n super({\n errorCode: 412,\n message: message ?? `Expected document state does not match current one!`,\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, ConcurrencyError.prototype);\n }\n}\n","import {\n NodePostgresConnectorType,\n type MigrationStyle,\n type NodePostgresConnection,\n} from '@event-driven-io/dumbo';\nimport pg from 'pg';\nimport type { PostgresDbClientOptions } from '../postgres';\nimport { getPongoDb, type AllowedDbClientOptions } from './pongoDb';\nimport { pongoSession } from './pongoSession';\nimport {\n proxyClientWithSchema,\n type PongoClientSchema,\n type PongoClientWithSchema,\n} from './schema';\nimport type { PongoClient, PongoDb, PongoSession } from './typing';\n\nexport type PooledPongoClientOptions =\n | {\n pool: pg.Pool;\n }\n | {\n pooled: true;\n }\n | {\n pool: pg.Pool;\n pooled: true;\n }\n | object;\n\nexport type NotPooledPongoOptions =\n | {\n client: pg.Client;\n }\n | {\n pooled: false;\n }\n | {\n client: pg.Client;\n pooled: false;\n }\n | {\n connection: NodePostgresConnection;\n pooled?: false;\n };\n\nexport type PongoClientOptions<\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n> = {\n schema?: { autoMigration?: MigrationStyle; definition?: TypedClientSchema };\n errors?: { throwOnOperationFailures?: boolean };\n connectionOptions?: PooledPongoClientOptions | NotPooledPongoOptions;\n};\n\nexport const pongoClient = <\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n connectionString: string,\n options: PongoClientOptions<TypedClientSchema> = {},\n): PongoClient & PongoClientWithSchema<TypedClientSchema> => {\n const dbClients = new Map<string, PongoDb>();\n\n const dbClient = getPongoDb<DbClientOptions>(\n clientToDbOptions({\n connectionString,\n clientOptions: options,\n }),\n );\n dbClients.set(dbClient.databaseName, dbClient);\n\n const pongoClient: PongoClient = {\n connect: async () => {\n await dbClient.connect();\n return pongoClient;\n },\n close: async () => {\n for (const db of dbClients.values()) {\n await db.close();\n }\n },\n db: (dbName?: string): PongoDb => {\n if (!dbName) return dbClient;\n\n return (\n dbClients.get(dbName) ??\n dbClients\n .set(\n dbName,\n getPongoDb<DbClientOptions>(\n clientToDbOptions({\n connectionString,\n dbName,\n clientOptions: options,\n }),\n ),\n )\n .get(dbName)!\n );\n },\n startSession: pongoSession,\n withSession: async <T>(\n callback: (session: PongoSession) => Promise<T>,\n ): Promise<T> => {\n const session = pongoSession();\n\n try {\n return await callback(session);\n } finally {\n await session.endSession();\n }\n },\n };\n\n return proxyClientWithSchema(pongoClient, options?.schema?.definition);\n};\n\nexport const clientToDbOptions = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(options: {\n connectionString: string;\n dbName?: string;\n clientOptions: PongoClientOptions;\n}): DbClientOptions => {\n const postgreSQLOptions: PostgresDbClientOptions = {\n connectorType: NodePostgresConnectorType,\n connectionString: options.connectionString,\n dbName: options.dbName,\n ...options.clientOptions,\n };\n\n return postgreSQLOptions as DbClientOptions;\n};\n","import {\n isPostgresClientOptions,\n postgresDb,\n type PostgresDbClientOptions,\n} from '../postgres';\nimport type { PongoClientOptions } from './pongoClient';\nimport type { PongoDb } from './typing';\n\nexport type PongoDbClientOptions<ConnectorType extends string = string> = {\n connectorType: ConnectorType;\n connectionString: string;\n dbName: string | undefined;\n} & PongoClientOptions;\n\nexport type AllowedDbClientOptions = PostgresDbClientOptions;\n\nexport const getPongoDb = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n options: DbClientOptions,\n): PongoDb => {\n const { connectorType: type } = options;\n // This is the place where in the future could come resolution of other database types\n if (!isPostgresClientOptions(options))\n throw new Error(`Unsupported db type: ${type}`);\n\n return postgresDb(options);\n};\n"]}
@@ -1,4 +1,4 @@
1
- import{isSQL as b,JSONSerializer as W,rawSql as $e,sql as O,sqlMigration as Ve}from"@event-driven-io/dumbo";import{runPostgreSQLMigrations as me,schemaComponent as Z,single as Te}from"@event-driven-io/dumbo";import{v4 as J}from"uuid";import{dumbo as pe,getDatabaseNameOrDefault as de,NodePostgresConnectorType as ue,runPostgreSQLMigrations as ge,schemaComponent as X}from"@event-driven-io/dumbo";var B=e=>e.connectorType===ue,K=e=>{let{connectionString:t,dbName:n}=e,o=n??de(t),i=pe({connectionString:t,...e.connectionOptions}),r=new Map,g=async(d,p)=>(await _(y,p,i.execute)).command(d),u=async(d,p)=>(await _(y,p,i.execute)).query(d),y={connectorType:e.connectorType,databaseName:o,connect:()=>Promise.resolve(),close:()=>i.close(),collections:()=>[...r.values()],collection:d=>z({collectionName:d,db:y,pool:i,sqlBuilder:H(d),schema:e.schema?e.schema:{},errors:e.errors?e.errors:{}}),transaction:()=>i.transaction(),withTransaction:d=>i.withTransaction(d),schema:{get component(){return X("pongoDb",{components:[...r.values()].map(d=>d.schema.component)})},migrate:()=>ge(i,[...r.values()].flatMap(d=>d.schema.component.migrations({connector:"PostgreSQL:pg"})))},sql:{async query(d,p){return(await u(d,p)).rows},async command(d,p){return g(d,p)}}},R=e?.schema?.definition?.dbs;if(R){let d=S(R).map(p=>p[1]).find(p=>p.name===n||p.name===o);if(d)return Y(y,d,r)}return y},ke=e=>{let t=e.length>0&&typeof e[0]=="string"?e.map(n=>G(n)):e;return X("pongo:schema_component:db",{components:t})};var Oe=async(e,t)=>{let n=t?.session?.transaction;return!n||!n.isActive?null:await n.enlistDatabase(e)},_=async(e,t,n)=>(await Oe(e,t))?.execute??n,z=({db:e,collectionName:t,pool:n,sqlBuilder:o,schema:i,errors:r})=>{let g=n.execute,u=async(s,a)=>(await _(e,a,g)).command(s),y=async(s,a)=>(await _(e,a,g)).query(s),R=i?.autoMigration!=="None",d=s=>(R=!1,s?.session?u(o.createCollection(),s):u(o.createCollection())),p=s=>R?d(s):Promise.resolve(),m={dbName:e.databaseName,collectionName:t,createCollection:async s=>{await d(s)},insertOne:async(s,a)=>{await p(a);let c=s._id??J(),l=s._version??1n,E=((await u(o.insertOne({...s,_id:c,_version:l}),a)).rowCount??0)>0;return C({successful:E,insertedId:E?c:null,nextExpectedVersion:l},{operationName:"insertOne",collectionName:t,errors:r})},insertMany:async(s,a)=>{await p(a);let c=s.map(x=>({...x,_id:x._id??J(),_version:x._version??1n})),l=await u(o.insertMany(c),a);return C({successful:l.rowCount===c.length,insertedCount:l.rowCount??0,insertedIds:l.rows.map(x=>x._id)},{operationName:"insertMany",collectionName:t,errors:r})},updateOne:async(s,a,c)=>{await p(c);let l=await u(o.updateOne(s,a,c),c);return C({successful:l.rows.length>0&&l.rows[0].modified===l.rows[0].matched,modifiedCount:Number(l.rows[0]?.modified??0),matchedCount:Number(l.rows[0]?.matched??0),nextExpectedVersion:l.rows[0]?.version??0n},{operationName:"updateOne",collectionName:t,errors:r})},replaceOne:async(s,a,c)=>{await p(c);let l=await u(o.replaceOne(s,a,c),c);return C({successful:l.rows.length>0&&l.rows[0].modified>0,modifiedCount:Number(l.rows[0]?.modified??0),matchedCount:Number(l.rows[0]?.matched??0),nextExpectedVersion:l.rows[0]?.version??0n},{operationName:"replaceOne",collectionName:t,errors:r})},updateMany:async(s,a,c)=>{await p(c);let l=await u(o.updateMany(s,a),c);return C({successful:!0,modifiedCount:l.rowCount??0,matchedCount:l.rowCount??0},{operationName:"updateMany",collectionName:t,errors:r})},deleteOne:async(s,a)=>{await p(a);let c=await u(o.deleteOne(s??{},a),a);return C({successful:c.rows.length>0&&c.rows[0].deleted>0,deletedCount:Number(c.rows[0]?.deleted??0),matchedCount:Number(c.rows[0]?.matched??0)},{operationName:"deleteOne",collectionName:t,errors:r})},deleteMany:async(s,a)=>{await p(a);let c=await u(o.deleteMany(s??{}),a);return C({successful:(c.rowCount??0)>0,deletedCount:c.rowCount??0,matchedCount:c.rowCount??0},{operationName:"deleteMany",collectionName:t,errors:r})},findOne:async(s,a)=>(await p(a),(await y(o.findOne(s??{}),a)).rows[0]?.data??null),findOneAndDelete:async(s,a)=>{await p(a);let c=await m.findOne(s,a);return c===null?null:(await m.deleteOne(s,a),c)},findOneAndReplace:async(s,a,c)=>{await p(c);let l=await m.findOne(s,c);return l===null?null:(await m.replaceOne(s,a,c),l)},findOneAndUpdate:async(s,a,c)=>{await p(c);let l=await m.findOne(s,c);return l===null?null:(await m.updateOne(s,a,c),l)},handle:async(s,a,c)=>{let{expectedVersion:l,...x}=c??{};await p(c);let E={_id:s},P=await m.findOne(E,c),I=L(l);if(P==null&&l==="DOCUMENT_EXISTS"||P==null&&I!=null||P!=null&&l==="DOCUMENT_DOES_NOT_EXIST"||P!=null&&I!==null&&P._version!==I)return C({successful:!1,document:P},{operationName:"handle",collectionName:t,errors:r});let D=await a(P);if(P===D)return C({successful:!0,document:P},{operationName:"handle",collectionName:t,errors:r});if(!P&&D){let w={...D,_id:s},q=await m.insertOne({...w,_id:s},{...x,expectedVersion:"DOCUMENT_DOES_NOT_EXIST"});return{...q,document:{...w,_version:q.nextExpectedVersion}}}if(P&&!D)return{...await m.deleteOne(E,{...x,expectedVersion:I??"DOCUMENT_EXISTS"}),document:null};if(P&&D){let w=await m.replaceOne(E,D,{...x,expectedVersion:I??"DOCUMENT_EXISTS"});return{...w,document:{...D,_version:w.nextExpectedVersion}}}return C({successful:!0,document:P},{operationName:"handle",collectionName:t,errors:r})},find:async(s,a)=>(await p(a),(await y(o.find(s??{}))).rows.map(l=>l.data)),countDocuments:async(s,a)=>{await p(a);let{count:c}=await Te(y(o.countDocuments(s??{})));return c},drop:async s=>(await p(s),((await u(o.drop()))?.rowCount??0)>0),rename:async(s,a)=>(await p(a),await u(o.rename(s)),t=s,m),sql:{async query(s,a){return await p(a),(await y(s,a)).rows},async command(s,a){return await p(a),u(s,a)}},schema:{get component(){return Z("pongo:schema_component:collection",{migrations:o.migrations})},migrate:()=>me(n,o.migrations())}};return m},G=e=>Z("pongo:schema_component:collection",{migrations:()=>V(e)});var ee={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},A={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},ye=e=>e.startsWith("$"),te=e=>Object.keys(e).some(ye);var Pe=e=>typeof e=="number"&&e===e,Se=e=>typeof e=="string",v=class e extends Error{errorCode;constructor(t){let n=t&&typeof t=="object"&&"errorCode"in t?t.errorCode:Pe(t)?t:500,o=t&&typeof t=="object"&&"message"in t?t.message:Se(t)?t:`Error with status code '${n}' ocurred during Pongo processing`;super(o),this.errorCode=n,Object.setPrototypeOf(this,e.prototype)}},N=class e extends v{constructor(t){super({errorCode:412,message:t??"Expected document state does not match current one!"}),Object.setPrototypeOf(this,e.prototype)}};import{NodePostgresConnectorType as we}from"@event-driven-io/dumbo";import"pg";var F=e=>{let{connectorType:t}=e;if(!B(e))throw new Error(`Unsupported db type: ${t}`);return K(e)};var ne=e=>{let t=!1,n=!1,o=null,i=null;return{enlistDatabase:async r=>{if(i&&o!==r.databaseName)throw new Error("There's already other database assigned to transaction");return i&&o===r.databaseName||(o=r.databaseName,i=r.transaction(),await i.begin()),i},commit:async()=>{if(!i)throw new Error("No database transaction started!");if(!t){if(n)throw new Error("Transaction is not active!");t=!0,await i.commit(),i=null}},rollback:async r=>{if(!i)throw new Error("No database transaction started!");if(t)throw new Error("Cannot rollback commited transaction!");n||(n=!0,await i.rollback(r),i=null)},databaseName:o,isStarting:!1,isCommitted:t,get isActive(){return!t&&!n},get sqlExecutor(){if(i===null)throw new Error("No database transaction was started");return i.execute},options:e}};var U=e=>e?.isActive===!0;function oe(e){if(!U(e))throw new Error("No active transaction exists!")}function Ce(e){if(U(e))throw new Error("Active transaction already exists!")}var j=e=>{let t=e?.explicit===!0,n=e?.defaultTransactionOptions??{get snapshotEnabled(){return!1}},o=null,i=!1,r=d=>{Ce(o),o=ne(d??n)},g=async()=>{oe(o),await o.commit()},u=async()=>{oe(o),await o.rollback()},R={get hasEnded(){return i},explicit:t,defaultTransactionOptions:n??{get snapshotEnabled(){return!1}},get transaction(){return o},get snapshotEnabled(){return n.snapshotEnabled},endSession:async()=>{i||(i=!0,U(o)&&await o.rollback())},incrementTransactionNumber:()=>{},inTransaction:()=>U(o),startTransaction:r,commitTransaction:g,abortTransaction:u,withTransaction:async(d,p)=>{r(p);try{let m=await d(R);return await g(),m}catch(m){throw await u(),m}}};return R};var S=e=>Object.entries(e).map(([t,n])=>[t,n]);import{JSONSerializer as xe}from"@event-driven-io/dumbo";var dt="DOCUMENT_EXISTS",ut="DOCUMENT_DOES_NOT_EXIST",be="NO_CONCURRENCY_CHECK",he=e=>e==="DOCUMENT_DOES_NOT_EXIST"||e==="DOCUMENT_EXISTS"||e==="NO_CONCURRENCY_CHECK",L=e=>e===void 0||he(e)?null:e,gt=e=>e?BigInt(e):be,C=(e,t)=>{let n={...e,acknowledged:!0,successful:e.successful,assertSuccessful:o=>{let{successful:i}=e,{operationName:r,collectionName:g}=t;if(!i)throw new N(o??`${r} on ${g} failed. Expected document state does not match current one! Result: ${xe.serialize(e)}!`)}};return t.errors?.throwOnOperationFailures&&n.assertSuccessful(),n};var Re=e=>({name:e});function fe(e,t){if(t===void 0){if(typeof e=="string")throw new Error("You need to provide colleciton definition");return{collections:e}}return e&&typeof e=="string"?{name:e,collections:t}:{collections:t}}var De=e=>({dbs:e}),St={client:De,db:fe,collection:Re},Y=(e,t,n)=>{let o=Object.keys(t.collections);for(let i of o)n.set(i,e.collection(i));return new Proxy(e,{get(i,r){return n.get(r)??i[r]}})},ie=(e,t)=>{if(!t)return e;let n=Object.keys(t.dbs);return new Proxy(e,{get(o,i){return n.includes(i)?e.db(t.dbs[i]?.name):o[i]}})},Ee=e=>({name:e.name,collections:S(e.collections).map(t=>({name:t[1].name}))}),Ct=e=>{let t=S(e.dbs).map(n=>Ee(n[1]));return{databases:t,database:n=>t.find(o=>o.name===n)}};var wt=(e,t={})=>{let n=new Map,o=F(se({connectionString:e,clientOptions:t}));n.set(o.databaseName,o);let i={connect:async()=>(await o.connect(),i),close:async()=>{for(let r of n.values())await r.close()},db:r=>r?n.get(r)??n.set(r,F(se({connectionString:e,dbName:r,clientOptions:t}))).get(r):o,startSession:j,withSession:async r=>{let g=j();try{return await r(g)}finally{await g.endSession()}}};return ie(i,t?.schema?.definition)},se=e=>({connectorType:we,connectionString:e.connectionString,dbName:e.dbName,...e.clientOptions});import{JSONSerializer as M,sql as T}from"@event-driven-io/dumbo";var $=(e,t,n)=>{if(e==="_id"||e==="_version")return Le(e,t,n);switch(t){case"$eq":return T("(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",M.serialize(re(e,n)),e,M.serialize(n));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return T(`data #>> %L ${A[t]} %L`,`{${e.split(".").join(",")}}`,n);case"$in":return T("data #>> %L IN (%s)",`{${e.split(".").join(",")}}`,n.map(o=>T("%L",o)).join(", "));case"$nin":return T("data #>> %L NOT IN (%s)",`{${e.split(".").join(",")}}`,n.map(o=>T("%L",o)).join(", "));case"$elemMatch":{let o=S(n).map(([i,r])=>T('@."%s" == %s',i,M.serialize(r))).join(" && ");return T("jsonb_path_exists(data, '$.%s[*] ? (%s)')",e,o)}case"$all":return T("data @> %L::jsonb",M.serialize(re(e,n)));case"$size":return T("jsonb_array_length(data #> %L) = %L",`{${e.split(".").join(",")}}`,n);default:throw new Error(`Unsupported operator: ${t}`)}},Le=(e,t,n)=>{switch(t){case"$eq":return T(`${e} = %L`,n);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return T(`${e} ${A[t]} %L`,n);case"$in":return T(`${e} IN (%s)`,n.map(o=>T("%L",o)).join(", "));case"$nin":return T(`${e} NOT IN (%s)`,n.map(o=>T("%L",o)).join(", "));default:throw new Error(`Unsupported operator: ${t}`)}},re=(e,t)=>e.split(".").reverse().reduce((n,o)=>({[o]:n}),t);var ae="AND",h=e=>Object.entries(e).map(([t,n])=>_e(n)?Ie(t,n):$(t,"$eq",n)).join(` ${ae} `),Ie=(e,t)=>{let n=!te(t);return S(t).map(([o,i])=>n?$(`${e}.${o}`,ee.$eq,i):$(e,o,i)).join(` ${ae} `)},_e=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);import{JSONSerializer as ce,sql as Q}from"@event-driven-io/dumbo";var k=e=>S(e).reduce((t,[n,o])=>{switch(n){case"$set":return Qe(o,t);case"$unset":return Ne(o,t);case"$inc":return Ue(o,t);case"$push":return Me(o,t);default:return t}},Q("data")),Qe=(e,t)=>Q("%s || %L::jsonb",t,ce.serialize(e)),Ne=(e,t)=>Q("%s - %L",t,Object.keys(e).map(n=>`{${n}}`).join(", ")),Ue=(e,t)=>{for(let[n,o]of Object.entries(e))t=Q(typeof o=="bigint"?"jsonb_set(%s, '{%s}', to_jsonb((COALESCE((data->>'%s')::BIGINT, 0) + %L)::TEXT), true)":"jsonb_set(%s, '{%s}', to_jsonb(COALESCE((data->>'%s')::NUMERIC, 0) + %L), true)",t,n,n,o);return t},Me=(e,t)=>{for(let[n,o]of Object.entries(e))t=Q("jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)",t,n,n,ce.serialize([o]));return t};var le=e=>O(`CREATE TABLE IF NOT EXISTS %I (
1
+ import{isSQL as b,JSONSerializer as W,rawSql as Ve,sql as O,sqlMigration as Ae}from"@event-driven-io/dumbo";import{runPostgreSQLMigrations as me,schemaComponent as Z,single as Te}from"@event-driven-io/dumbo";import{v7 as J}from"uuid";import{dumbo as pe,getDatabaseNameOrDefault as de,NodePostgresConnectorType as ue,runPostgreSQLMigrations as ge,schemaComponent as X}from"@event-driven-io/dumbo";var B=e=>e.connectorType===ue,K=e=>{let{connectionString:t,dbName:n}=e,o=n??de(t),i=pe({connectionString:t,...e.connectionOptions}),r=new Map,g=async(d,p)=>(await _(y,p,i.execute)).command(d),u=async(d,p)=>(await _(y,p,i.execute)).query(d),y={connectorType:e.connectorType,databaseName:o,connect:()=>Promise.resolve(),close:()=>i.close(),collections:()=>[...r.values()],collection:d=>z({collectionName:d,db:y,pool:i,sqlBuilder:H(d),schema:e.schema?e.schema:{},errors:e.errors?e.errors:{}}),transaction:()=>i.transaction(),withTransaction:d=>i.withTransaction(d),schema:{get component(){return X("pongoDb",{components:[...r.values()].map(d=>d.schema.component)})},migrate:()=>ge(i,[...r.values()].flatMap(d=>d.schema.component.migrations({connector:"PostgreSQL:pg"})))},sql:{async query(d,p){return(await u(d,p)).rows},async command(d,p){return g(d,p)}}},R=e?.schema?.definition?.dbs;if(R){let d=S(R).map(p=>p[1]).find(p=>p.name===n||p.name===o);if(d)return Y(y,d,r)}return y},We=e=>{let t=e.length>0&&typeof e[0]=="string"?e.map(n=>G(n)):e;return X("pongo:schema_component:db",{components:t})};var Oe=async(e,t)=>{let n=t?.session?.transaction;return!n||!n.isActive?null:await n.enlistDatabase(e)},_=async(e,t,n)=>(await Oe(e,t))?.execute??n,z=({db:e,collectionName:t,pool:n,sqlBuilder:o,schema:i,errors:r})=>{let g=n.execute,u=async(s,a)=>(await _(e,a,g)).command(s),y=async(s,a)=>(await _(e,a,g)).query(s),R=i?.autoMigration!=="None",d=s=>(R=!1,s?.session?u(o.createCollection(),s):u(o.createCollection())),p=s=>R?d(s):Promise.resolve(),m={dbName:e.databaseName,collectionName:t,createCollection:async s=>{await d(s)},insertOne:async(s,a)=>{await p(a);let c=s._id??J(),l=s._version??1n,E=((await u(o.insertOne({...s,_id:c,_version:l}),a)).rowCount??0)>0;return C({successful:E,insertedId:E?c:null,nextExpectedVersion:l},{operationName:"insertOne",collectionName:t,errors:r})},insertMany:async(s,a)=>{await p(a);let c=s.map(x=>({...x,_id:x._id??J(),_version:x._version??1n})),l=await u(o.insertMany(c),a);return C({successful:l.rowCount===c.length,insertedCount:l.rowCount??0,insertedIds:l.rows.map(x=>x._id)},{operationName:"insertMany",collectionName:t,errors:r})},updateOne:async(s,a,c)=>{await p(c);let l=await u(o.updateOne(s,a,c),c);return C({successful:l.rows.length>0&&l.rows[0].modified===l.rows[0].matched,modifiedCount:Number(l.rows[0]?.modified??0),matchedCount:Number(l.rows[0]?.matched??0),nextExpectedVersion:l.rows[0]?.version??0n},{operationName:"updateOne",collectionName:t,errors:r})},replaceOne:async(s,a,c)=>{await p(c);let l=await u(o.replaceOne(s,a,c),c);return C({successful:l.rows.length>0&&l.rows[0].modified>0,modifiedCount:Number(l.rows[0]?.modified??0),matchedCount:Number(l.rows[0]?.matched??0),nextExpectedVersion:l.rows[0]?.version??0n},{operationName:"replaceOne",collectionName:t,errors:r})},updateMany:async(s,a,c)=>{await p(c);let l=await u(o.updateMany(s,a),c);return C({successful:!0,modifiedCount:l.rowCount??0,matchedCount:l.rowCount??0},{operationName:"updateMany",collectionName:t,errors:r})},deleteOne:async(s,a)=>{await p(a);let c=await u(o.deleteOne(s??{},a),a);return C({successful:c.rows.length>0&&c.rows[0].deleted>0,deletedCount:Number(c.rows[0]?.deleted??0),matchedCount:Number(c.rows[0]?.matched??0)},{operationName:"deleteOne",collectionName:t,errors:r})},deleteMany:async(s,a)=>{await p(a);let c=await u(o.deleteMany(s??{}),a);return C({successful:(c.rowCount??0)>0,deletedCount:c.rowCount??0,matchedCount:c.rowCount??0},{operationName:"deleteMany",collectionName:t,errors:r})},findOne:async(s,a)=>(await p(a),(await y(o.findOne(s??{}),a)).rows[0]?.data??null),findOneAndDelete:async(s,a)=>{await p(a);let c=await m.findOne(s,a);return c===null?null:(await m.deleteOne(s,a),c)},findOneAndReplace:async(s,a,c)=>{await p(c);let l=await m.findOne(s,c);return l===null?null:(await m.replaceOne(s,a,c),l)},findOneAndUpdate:async(s,a,c)=>{await p(c);let l=await m.findOne(s,c);return l===null?null:(await m.updateOne(s,a,c),l)},handle:async(s,a,c)=>{let{expectedVersion:l,...x}=c??{};await p(c);let E={_id:s},P=await m.findOne(E,c),L=I(l);if(P==null&&l==="DOCUMENT_EXISTS"||P==null&&L!=null||P!=null&&l==="DOCUMENT_DOES_NOT_EXIST"||P!=null&&L!==null&&P._version!==L)return C({successful:!1,document:P},{operationName:"handle",collectionName:t,errors:r});let D=await a(P);if(P===D)return C({successful:!0,document:P},{operationName:"handle",collectionName:t,errors:r});if(!P&&D){let w={...D,_id:s},q=await m.insertOne({...w,_id:s},{...x,expectedVersion:"DOCUMENT_DOES_NOT_EXIST"});return{...q,document:{...w,_version:q.nextExpectedVersion}}}if(P&&!D)return{...await m.deleteOne(E,{...x,expectedVersion:L??"DOCUMENT_EXISTS"}),document:null};if(P&&D){let w=await m.replaceOne(E,D,{...x,expectedVersion:L??"DOCUMENT_EXISTS"});return{...w,document:{...D,_version:w.nextExpectedVersion}}}return C({successful:!0,document:P},{operationName:"handle",collectionName:t,errors:r})},find:async(s,a)=>(await p(a),(await y(o.find(s??{}))).rows.map(l=>l.data)),countDocuments:async(s,a)=>{await p(a);let{count:c}=await Te(y(o.countDocuments(s??{})));return c},drop:async s=>(await p(s),((await u(o.drop()))?.rowCount??0)>0),rename:async(s,a)=>(await p(a),await u(o.rename(s)),t=s,m),sql:{async query(s,a){return await p(a),(await y(s,a)).rows},async command(s,a){return await p(a),u(s,a)}},schema:{get component(){return Z("pongo:schema_component:collection",{migrations:o.migrations})},migrate:()=>me(n,o.migrations())}};return m},G=e=>Z("pongo:schema_component:collection",{migrations:()=>V(e)});var ee={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},A={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},ye=e=>e.startsWith("$"),te=e=>Object.keys(e).some(ye);var Pe=e=>typeof e=="number"&&e===e,Se=e=>typeof e=="string",v=class e extends Error{errorCode;constructor(t){let n=t&&typeof t=="object"&&"errorCode"in t?t.errorCode:Pe(t)?t:500,o=t&&typeof t=="object"&&"message"in t?t.message:Se(t)?t:`Error with status code '${n}' ocurred during Pongo processing`;super(o),this.errorCode=n,Object.setPrototypeOf(this,e.prototype)}},N=class e extends v{constructor(t){super({errorCode:412,message:t??"Expected document state does not match current one!"}),Object.setPrototypeOf(this,e.prototype)}};import{NodePostgresConnectorType as Ie}from"@event-driven-io/dumbo";import"pg";var j=e=>{let{connectorType:t}=e;if(!B(e))throw new Error(`Unsupported db type: ${t}`);return K(e)};var ne=e=>{let t=!1,n=!1,o=null,i=null;return{enlistDatabase:async r=>{if(i&&o!==r.databaseName)throw new Error("There's already other database assigned to transaction");return i&&o===r.databaseName||(o=r.databaseName,i=r.transaction(),await i.begin()),i},commit:async()=>{if(!i)throw new Error("No database transaction started!");if(!t){if(n)throw new Error("Transaction is not active!");t=!0,await i.commit(),i=null}},rollback:async r=>{if(!i)throw new Error("No database transaction started!");if(t)throw new Error("Cannot rollback commited transaction!");n||(n=!0,await i.rollback(r),i=null)},databaseName:o,isStarting:!1,isCommitted:t,get isActive(){return!t&&!n},get sqlExecutor(){if(i===null)throw new Error("No database transaction was started");return i.execute},options:e}};var U=e=>e?.isActive===!0;function oe(e){if(!U(e))throw new Error("No active transaction exists!")}function Ce(e){if(U(e))throw new Error("Active transaction already exists!")}var F=e=>{let t=e?.explicit===!0,n=e?.defaultTransactionOptions??{get snapshotEnabled(){return!1}},o=null,i=!1,r=d=>{Ce(o),o=ne(d??n)},g=async()=>{oe(o),await o.commit()},u=async()=>{oe(o),await o.rollback()},R={get hasEnded(){return i},explicit:t,defaultTransactionOptions:n??{get snapshotEnabled(){return!1}},get transaction(){return o},get snapshotEnabled(){return n.snapshotEnabled},endSession:async()=>{i||(i=!0,U(o)&&await o.rollback())},incrementTransactionNumber:()=>{},inTransaction:()=>U(o),startTransaction:r,commitTransaction:g,abortTransaction:u,withTransaction:async(d,p)=>{r(p);try{let m=await d(R);return await g(),m}catch(m){throw await u(),m}}};return R};var S=e=>Object.entries(e).map(([t,n])=>[t,n]);import{JSONSerializer as xe}from"@event-driven-io/dumbo";import{v7 as be}from"uuid";var gt=e=>e??be(),mt="DOCUMENT_EXISTS",Tt="DOCUMENT_DOES_NOT_EXIST",he="NO_CONCURRENCY_CHECK",Re=e=>e==="DOCUMENT_DOES_NOT_EXIST"||e==="DOCUMENT_EXISTS"||e==="NO_CONCURRENCY_CHECK",I=e=>e===void 0||Re(e)?null:e,Ot=e=>e?BigInt(e):he,C=(e,t)=>{let n={...e,acknowledged:!0,successful:e.successful,assertSuccessful:o=>{let{successful:i}=e,{operationName:r,collectionName:g}=t;if(!i)throw new N(o??`${r} on ${g} failed. Expected document state does not match current one! Result: ${xe.serialize(e)}!`)}};return t.errors?.throwOnOperationFailures&&n.assertSuccessful(),n};var fe=e=>({name:e});function De(e,t){if(t===void 0){if(typeof e=="string")throw new Error("You need to provide colleciton definition");return{collections:e}}return e&&typeof e=="string"?{name:e,collections:t}:{collections:t}}var Ee=e=>({dbs:e}),bt={client:Ee,db:De,collection:fe},Y=(e,t,n)=>{let o=Object.keys(t.collections);for(let i of o)n.set(i,e.collection(i));return new Proxy(e,{get(i,r){return n.get(r)??i[r]}})},ie=(e,t)=>{if(!t)return e;let n=Object.keys(t.dbs);return new Proxy(e,{get(o,i){return n.includes(i)?e.db(t.dbs[i]?.name):o[i]}})},we=e=>({name:e.name,collections:S(e.collections).map(t=>({name:t[1].name}))}),ht=e=>{let t=S(e.dbs).map(n=>we(n[1]));return{databases:t,database:n=>t.find(o=>o.name===n)}};var _t=(e,t={})=>{let n=new Map,o=j(se({connectionString:e,clientOptions:t}));n.set(o.databaseName,o);let i={connect:async()=>(await o.connect(),i),close:async()=>{for(let r of n.values())await r.close()},db:r=>r?n.get(r)??n.set(r,j(se({connectionString:e,dbName:r,clientOptions:t}))).get(r):o,startSession:F,withSession:async r=>{let g=F();try{return await r(g)}finally{await g.endSession()}}};return ie(i,t?.schema?.definition)},se=e=>({connectorType:Ie,connectionString:e.connectionString,dbName:e.dbName,...e.clientOptions});import{JSONSerializer as M,sql as T}from"@event-driven-io/dumbo";var $=(e,t,n)=>{if(e==="_id"||e==="_version")return Le(e,t,n);switch(t){case"$eq":return T("(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",M.serialize(re(e,n)),e,M.serialize(n));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return T(`data #>> %L ${A[t]} %L`,`{${e.split(".").join(",")}}`,n);case"$in":return T("data #>> %L IN (%s)",`{${e.split(".").join(",")}}`,n.map(o=>T("%L",o)).join(", "));case"$nin":return T("data #>> %L NOT IN (%s)",`{${e.split(".").join(",")}}`,n.map(o=>T("%L",o)).join(", "));case"$elemMatch":{let o=S(n).map(([i,r])=>T('@."%s" == %s',i,M.serialize(r))).join(" && ");return T("jsonb_path_exists(data, '$.%s[*] ? (%s)')",e,o)}case"$all":return T("data @> %L::jsonb",M.serialize(re(e,n)));case"$size":return T("jsonb_array_length(data #> %L) = %L",`{${e.split(".").join(",")}}`,n);default:throw new Error(`Unsupported operator: ${t}`)}},Le=(e,t,n)=>{switch(t){case"$eq":return T(`${e} = %L`,n);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return T(`${e} ${A[t]} %L`,n);case"$in":return T(`${e} IN (%s)`,n.map(o=>T("%L",o)).join(", "));case"$nin":return T(`${e} NOT IN (%s)`,n.map(o=>T("%L",o)).join(", "));default:throw new Error(`Unsupported operator: ${t}`)}},re=(e,t)=>e.split(".").reverse().reduce((n,o)=>({[o]:n}),t);var ae="AND",h=e=>Object.entries(e).map(([t,n])=>Qe(n)?_e(t,n):$(t,"$eq",n)).join(` ${ae} `),_e=(e,t)=>{let n=!te(t);return S(t).map(([o,i])=>n?$(`${e}.${o}`,ee.$eq,i):$(e,o,i)).join(` ${ae} `)},Qe=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);import{JSONSerializer as ce,sql as Q}from"@event-driven-io/dumbo";var k=e=>S(e).reduce((t,[n,o])=>{switch(n){case"$set":return Ne(o,t);case"$unset":return Ue(o,t);case"$inc":return Me(o,t);case"$push":return $e(o,t);default:return t}},Q("data")),Ne=(e,t)=>Q("%s || %L::jsonb",t,ce.serialize(e)),Ue=(e,t)=>Q("%s - %L",t,Object.keys(e).map(n=>`{${n}}`).join(", ")),Me=(e,t)=>{for(let[n,o]of Object.entries(e))t=Q(typeof o=="bigint"?"jsonb_set(%s, '{%s}', to_jsonb((COALESCE((data->>'%s')::BIGINT, 0) + %L)::TEXT), true)":"jsonb_set(%s, '{%s}', to_jsonb(COALESCE((data->>'%s')::NUMERIC, 0) + %L), true)",t,n,n,o);return t},$e=(e,t)=>{for(let[n,o]of Object.entries(e))t=Q("jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)",t,n,n,ce.serialize([o]));return t};var le=e=>O(`CREATE TABLE IF NOT EXISTS %I (
2
2
  _id TEXT PRIMARY KEY,
3
3
  data JSONB NOT NULL,
4
4
  metadata JSONB NOT NULL DEFAULT '{}',
@@ -7,9 +7,9 @@ import{isSQL as b,JSONSerializer as W,rawSql as $e,sql as O,sqlMigration as Ve}f
7
7
  _archived BOOLEAN NOT NULL DEFAULT FALSE,
8
8
  _created TIMESTAMPTZ NOT NULL DEFAULT now(),
9
9
  _updated TIMESTAMPTZ NOT NULL DEFAULT now()
10
- )`,e),V=e=>[Ve(`pongoCollection:${e}:001:createtable`,[le(e)])],H=e=>({migrations:()=>V(e),createCollection:()=>le(e),insertOne:t=>O("INSERT INTO %I (_id, data, _version) VALUES (%L, %L, %L) ON CONFLICT(_id) DO NOTHING;",e,t._id,W.serialize(t),t._version??1n),insertMany:t=>{let n=t.map(o=>O("(%L, %L, %L)",o._id,W.serialize(o),o._version??1n)).join(", ");return O(`INSERT INTO %I (_id, data, _version) VALUES %s
10
+ )`,e),V=e=>[Ae(`pongoCollection:${e}:001:createtable`,[le(e)])],H=e=>({migrations:()=>V(e),createCollection:()=>le(e),insertOne:t=>O("INSERT INTO %I (_id, data, _version) VALUES (%L, %L, %L) ON CONFLICT(_id) DO NOTHING;",e,t._id,W.serialize(t),t._version??1n),insertMany:t=>{let n=t.map(o=>O("(%L, %L, %L)",o._id,W.serialize(o),o._version??1n)).join(", ");return O(`INSERT INTO %I (_id, data, _version) VALUES %s
11
11
  ON CONFLICT(_id) DO NOTHING
12
- RETURNING _id;`,e,n)},updateOne:(t,n,o)=>{let i=L(o?.expectedVersion),r=i!=null?"AND %I._version = %L":"",g=i!=null?[e,i]:[],u=b(t)?t:h(t),y=b(n)?n:k(n);return O(`WITH existing AS (
12
+ RETURNING _id;`,e,n)},updateOne:(t,n,o)=>{let i=I(o?.expectedVersion),r=i!=null?"AND %I._version = %L":"",g=i!=null?[e,i]:[],u=b(t)?t:h(t),y=b(n)?n:k(n);return O(`WITH existing AS (
13
13
  SELECT _id, _version as current_version
14
14
  FROM %I %s
15
15
  LIMIT 1
@@ -30,7 +30,7 @@ import{isSQL as b,JSONSerializer as W,rawSql as $e,sql as O,sqlMigration as Ve}f
30
30
  COUNT(updated._id) over() AS modified
31
31
  FROM existing
32
32
  LEFT JOIN updated
33
- ON existing._id = updated._id;`,e,f(u),e,y,e,e,...g,e,e)},replaceOne:(t,n,o)=>{let i=L(o?.expectedVersion),r=i!=null?"AND %I._version = %L":"",g=i!=null?[e,i]:[],u=b(t)?t:h(t);return O(`WITH existing AS (
33
+ ON existing._id = updated._id;`,e,f(u),e,y,e,e,...g,e,e)},replaceOne:(t,n,o)=>{let i=I(o?.expectedVersion),r=i!=null?"AND %I._version = %L":"",g=i!=null?[e,i]:[],u=b(t)?t:h(t);return O(`WITH existing AS (
34
34
  SELECT _id, _version as current_version
35
35
  FROM %I %s
36
36
  LIMIT 1
@@ -55,7 +55,7 @@ import{isSQL as b,JSONSerializer as W,rawSql as $e,sql as O,sqlMigration as Ve}f
55
55
  SET
56
56
  data = %s || jsonb_build_object('_version', (_version + 1)::text),
57
57
  _version = _version + 1
58
- %s;`,e,i,f(o))},deleteOne:(t,n)=>{let o=L(n?.expectedVersion),i=o!=null?"AND %I._version = %L":"",r=o!=null?[e,o]:[],g=b(t)?t:h(t);return O(`WITH existing AS (
58
+ %s;`,e,i,f(o))},deleteOne:(t,n)=>{let o=I(n?.expectedVersion),i=o!=null?"AND %I._version = %L":"",r=o!=null?[e,o]:[],g=b(t)?t:h(t);return O(`WITH existing AS (
59
59
  SELECT _id
60
60
  FROM %I %s
61
61
  LIMIT 1
@@ -72,5 +72,5 @@ import{isSQL as b,JSONSerializer as W,rawSql as $e,sql as O,sqlMigration as Ve}f
72
72
  COUNT(deleted._id) over() AS deleted
73
73
  FROM existing
74
74
  LEFT JOIN deleted
75
- ON existing._id = deleted._id;`,e,f(g),e,e,...r,e)},deleteMany:t=>{let n=b(t)?t:h(t);return O("DELETE FROM %I %s",e,f(n))},findOne:t=>{let n=b(t)?t:h(t);return O("SELECT data FROM %I %s LIMIT 1;",e,f(n))},find:t=>{let n=b(t)?t:h(t);return O("SELECT data FROM %I %s;",e,f(n))},countDocuments:t=>{let n=b(t)?t:h(t);return O("SELECT COUNT(1) as count FROM %I %s;",e,f(n))},rename:t=>O("ALTER TABLE %I RENAME TO %I;",e,t),drop:(t=e)=>O("DROP TABLE IF EXISTS %I",t)}),f=e=>e.length>0?O("WHERE %s",e):$e("");export{V as a,H as b,B as c,K as d,ke as e,_ as f,z as g,G as h,ee as i,A as j,ye as k,te as l,Pe as m,Se as n,v as o,N as p,F as q,ne as r,j as s,S as t,dt as u,ut as v,be as w,he as x,L as y,gt as z,C as A,St as B,Y as C,ie as D,Ee as E,Ct as F,wt as G,se as H};
76
- //# sourceMappingURL=chunk-GFYGFSLO.js.map
75
+ ON existing._id = deleted._id;`,e,f(g),e,e,...r,e)},deleteMany:t=>{let n=b(t)?t:h(t);return O("DELETE FROM %I %s",e,f(n))},findOne:t=>{let n=b(t)?t:h(t);return O("SELECT data FROM %I %s LIMIT 1;",e,f(n))},find:t=>{let n=b(t)?t:h(t);return O("SELECT data FROM %I %s;",e,f(n))},countDocuments:t=>{let n=b(t)?t:h(t);return O("SELECT COUNT(1) as count FROM %I %s;",e,f(n))},rename:t=>O("ALTER TABLE %I RENAME TO %I;",e,t),drop:(t=e)=>O("DROP TABLE IF EXISTS %I",t)}),f=e=>e.length>0?O("WHERE %s",e):Ve("");export{V as a,H as b,B as c,K as d,We as e,_ as f,z as g,G as h,ee as i,A as j,ye as k,te as l,Pe as m,Se as n,v as o,N as p,j as q,ne as r,F as s,S as t,gt as u,mt as v,Tt as w,he as x,Re as y,I as z,Ot as A,C as B,bt as C,Y as D,ie as E,we as F,ht as G,_t as H,se as I};
76
+ //# sourceMappingURL=chunk-NUURKTSH.js.map