@event-driven-io/pongo 0.16.0-alpha.6 → 0.16.0-alpha.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-BDSCD6MH.cjs +76 -0
- package/dist/chunk-BDSCD6MH.cjs.map +1 -0
- package/dist/chunk-CRUPVSHS.js +76 -0
- package/dist/chunk-CRUPVSHS.js.map +1 -0
- package/dist/cli.cjs +3 -3
- package/dist/cli.js +3 -3
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -4
- package/dist/index.d.ts +5 -4
- package/dist/index.js +1 -1
- package/dist/{pongoClient-DkAUSd1N.d.cts → pongoClient-CjXGu-SC.d.cts} +7 -2
- package/dist/{pongoClient-DkAUSd1N.d.ts → pongoClient-CjXGu-SC.d.ts} +7 -2
- package/dist/shim.cjs +1 -1
- package/dist/shim.d.cts +1 -1
- package/dist/shim.d.ts +1 -1
- package/dist/shim.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-P5Y6AANF.cjs +0 -76
- package/dist/chunk-P5Y6AANF.cjs.map +0 -1
- package/dist/chunk-S6SSZQB7.js +0 -76
- package/dist/chunk-S6SSZQB7.js.map +0 -1
package/dist/cli.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var
|
|
2
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _chunkBDSCD6MHcjs = require('./chunk-BDSCD6MH.cjs');var _commander = require('commander');var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);var E=o=>{if(o.length===0)return o;let e=o.charAt(0).toUpperCase()+o.slice(1);return e.endsWith("s")&&(e=e.slice(0,-1)),e},s=(o=["users"])=>{let e=o.map(n=>`type ${E(n)} = { name: string; description: string; date: Date }`).join(`
|
|
3
3
|
`),t=o.map(n=>` ${n}: pongoSchema.collection<${E(n)}>('${n}'),`).join(`
|
|
4
4
|
`);return`import { pongoSchema } from '@event-driven-io/pongo';
|
|
5
5
|
|
|
@@ -21,7 +21,7 @@ ${s()}`,_=`Error: Config should have a default database defined (without name or
|
|
|
21
21
|
|
|
22
22
|
${s()}`,O=`Error: Database should have defined at least one collection, e.g.
|
|
23
23
|
|
|
24
|
-
${s()}`,D=async o=>{let e=new URL(o,`file://${process.cwd()}/`);try{let t=await Promise.resolve().then(() => _interopRequireWildcard(require(e.href))),n=A(t);return typeof n=="string"&&(console.error(n),process.exit(1)),n}catch (e2){console.error(`Error: Couldn't load file: ${e.href}`),process.exit(1)}},$=(o,e)=>{try{_fs2.default.writeFileSync(o,s(e),"utf8"),console.log(`Configuration file stored at: ${o}`)}catch(t){console.error(`Error: Couldn't store config file: ${o}!`),console.error(t),process.exit(1)}},A=o=>{if(!o.default)return R;if(!o.default.schema)return T;if(!o.default.schema.dbs)return I;let t=
|
|
24
|
+
${s()}`,D=async o=>{let e=new URL(o,`file://${process.cwd()}/`);try{let t=await Promise.resolve().then(() => _interopRequireWildcard(require(e.href))),n=A(t);return typeof n=="string"&&(console.error(n),process.exit(1)),n}catch (e2){console.error(`Error: Couldn't load file: ${e.href}`),process.exit(1)}},$=(o,e)=>{try{_fs2.default.writeFileSync(o,s(e),"utf8"),console.log(`Configuration file stored at: ${o}`)}catch(t){console.error(`Error: Couldn't store config file: ${o}!`),console.error(t),process.exit(1)}},A=o=>{if(!o.default)return R;if(!o.default.schema)return T;if(!o.default.schema.dbs)return I;let t=_chunkBDSCD6MHcjs.t.call(void 0, o.default.schema.dbs).map(r=>r[1]).find(r=>r.name===void 0);return t?!t.collections||_chunkBDSCD6MHcjs.t.call(void 0, t.collections).map(r=>r[1]).length===0?O:_chunkBDSCD6MHcjs.E.call(void 0, t):_},C=new (0, _commander.Command)("config").description("Manage Pongo configuration");C.command("sample").description("Generate or print sample configuration").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-f, --file <path>","Path to configuration file with collection list").option("-g, --generate","Generate sample config file").option("-p, --print","Print sample config file").action(o=>{let e=o.collection.length>0?o.collection:["users"];!("print"in o)&&!("generate"in o)&&(console.error(`Error: Please provide either:
|
|
25
25
|
--print param to print sample config or
|
|
26
|
-
--generate to generate sample config file`),process.exit(1)),"print"in o?console.log(`${s(e)}`):"generate"in o&&(o.file||(console.error("Error: You need to provide a config file through a --file"),process.exit(1)),$(o.file,e))});var _dumbo = require('@event-driven-io/dumbo');var d=new (0, _commander.Command)("migrate").description("Manage database migrations");d.command("run").description("Run database migrations").option("-cs, --connectionString <string>","Connection string for the database").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-f, --config <path>","Path to configuration file with Pongo config").option("-dr, --dryRun","Perform dry run without commiting changes",!1).action(async o=>{let{collection:e,dryRun:t}=o,n=_nullishCoalesce(o.connectionString, () => (process.env.DB_CONNECTION_STRING)),r;n||(console.error('Error: Connection string is required. Provide it either as a "--connectionString" parameter or through the DB_CONNECTION_STRING environment variable.'),process.exit(1)),o.config?r=(await D(o.config)).collections.map(c=>c.name):e?r=e:(console.error('Error: You need to provide at least one collection name. Provide it either through "--config" file or as a "--collection" parameter.'),process.exit(1));let a=_dumbo.dumbo.call(void 0, {connectionString:n}),u=r.flatMap(l=>
|
|
26
|
+
--generate to generate sample config file`),process.exit(1)),"print"in o?console.log(`${s(e)}`):"generate"in o&&(o.file||(console.error("Error: You need to provide a config file through a --file"),process.exit(1)),$(o.file,e))});var _dumbo = require('@event-driven-io/dumbo');var d=new (0, _commander.Command)("migrate").description("Manage database migrations");d.command("run").description("Run database migrations").option("-cs, --connectionString <string>","Connection string for the database").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-f, --config <path>","Path to configuration file with Pongo config").option("-dr, --dryRun","Perform dry run without commiting changes",!1).action(async o=>{let{collection:e,dryRun:t}=o,n=_nullishCoalesce(o.connectionString, () => (process.env.DB_CONNECTION_STRING)),r;n||(console.error('Error: Connection string is required. Provide it either as a "--connectionString" parameter or through the DB_CONNECTION_STRING environment variable.'),process.exit(1)),o.config?r=(await D(o.config)).collections.map(c=>c.name):e?r=e:(console.error('Error: You need to provide at least one collection name. Provide it either through "--config" file or as a "--collection" parameter.'),process.exit(1));let a=_dumbo.dumbo.call(void 0, {connectionString:n}),u=r.flatMap(l=>_chunkBDSCD6MHcjs.h.call(void 0, l).migrations({connector:"PostgreSQL:pg"}));await _dumbo.runPostgreSQLMigrations.call(void 0, a,u,{dryRun:t})});d.command("sql").description("Generate SQL for database migration").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("--print","Print the SQL to the console (default)",!0).action(o=>{let{collection:e}=o;e||(console.error('Error: You need to provide at least one collection name is required. Provide it either as a "col" parameter.'),process.exit(1));let n=[..._dumbo.migrationTableSchemaComponent.migrations({connector:"PostgreSQL:pg"}),...e.flatMap(r=>_chunkBDSCD6MHcjs.h.call(void 0, r).migrations({connector:"PostgreSQL:pg"}))];console.log("Printing SQL:"),console.log(_dumbo.combineMigrations.call(void 0, ...n))});var _chalk = require('chalk'); var _chalk2 = _interopRequireDefault(_chalk);var _clitable3 = require('cli-table3'); var _clitable32 = _interopRequireDefault(_clitable3);var _repl = require('repl'); var _repl2 = _interopRequireDefault(_repl);var m,V=(o,e)=>e.map(n=>Math.max(n.length,...o.map(a=>a[n]?String(a[n]).length:0))+2),z=o=>Array.isArray(o)?H(o):_dumbo.prettyJson.call(void 0, o),H=o=>{if(o.length===0)return _chalk2.default.yellow("No documents found.");let e=Object.keys(o[0]),t=V(o,e),n=new (0, _clitable32.default)({head:e.map(r=>_chalk2.default.cyan(r)),colWidths:t});return o.forEach(r=>{n.push(e.map(a=>r[a]!==void 0?String(r[a]):""))}),n.toString()},v=o=>{process.env.DUMBO_LOG_LEVEL=o},x=o=>{process.env.DUMBO_LOG_STYLE=o},K=o=>{o!==void 0&&v(o),x(_dumbo.LogStyle.PRETTY)},X=async o=>{console.log(JSON.stringify(o)),v(_nullishCoalesce(process.env.DUMBO_LOG_LEVEL, () => (o.logging.logLevel))),x(_nullishCoalesce(process.env.DUMBO_LOG_STYLE, () => (o.logging.logStyle))),console.log(_chalk2.default.green("Starting Pongo Shell (version: 0.16.0-alpha.8)"));let e=_nullishCoalesce(_nullishCoalesce(o.connectionString, () => (process.env.DB_CONNECTION_STRING)), () => ("postgresql://postgres:postgres@localhost:5432/postgres"));(_nullishCoalesce(o.connectionString, () => (process.env.DB_CONNECTION_STRING)))||console.log(_chalk2.default.yellow("No connection string provided, using: 'postgresql://postgres:postgres@localhost:5432/postgres'"));let t=await _dumbo.checkConnection.call(void 0, e);t.successful||(t.errorType==="ConnectionRefused"?console.error(_chalk2.default.red("Connection was refused. Check if the PostgreSQL server is running and accessible.")):t.errorType==="Authentication"?console.error(_chalk2.default.red("Authentication failed. Check the username and password in the connection string.")):console.error(_chalk2.default.red("Error connecting to PostgreSQL server")),console.log(_chalk2.default.red("Exiting Pongo Shell...")),process.exit()),console.log(_chalk2.default.green("Successfully connected")),console.log(_chalk2.default.green("Use db.<collection>.<method>() to query."));let n=_repl2.default.start({prompt:_chalk2.default.green("pongo> "),useGlobal:!0,breakEvalOnSigint:!0,writer:z}),r;if(o.schema.collections.length>0){let a={};for(let c of o.schema.collections)a[c]=_chunkBDSCD6MHcjs.B.collection(c);let u=_chunkBDSCD6MHcjs.B.client({database:_chunkBDSCD6MHcjs.B.db(o.schema.database,a)}),l=_chunkBDSCD6MHcjs.G.call(void 0, e,{schema:{definition:u,autoMigration:o.schema.autoMigration}});r=l.database;for(let c of o.schema.collections)n.context[c]=l.database[c];m=l}else m=_chunkBDSCD6MHcjs.G.call(void 0, e,{schema:{autoMigration:o.schema.autoMigration}}),r=m.db(o.schema.database);n.context.pongo=m,n.context.db=r,n.context.SQL=_dumbo.SQL,n.context.setLogLevel=v,n.context.setLogStyle=x,n.context.prettifyLogs=K,n.context.LogStyle=_dumbo.LogStyle,n.context.LogLevel=_dumbo.LogLevel,n.on("exit",async()=>{await h(),process.exit()}),n.on("SIGINT",async()=>{await h(),process.exit()})},h=async()=>{console.log(_chalk2.default.yellow("Exiting Pongo Shell...")),await m.close()};process.on("uncaughtException",h);process.on("SIGINT",h);var M=new (0, _commander.Command)("shell").description("Start an interactive Pongo shell").option("-cs, --connectionString <string>","Connection string for the database").option("-db, --database <string>","Database name to connect","postgres").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-no-migrations, --disable-auto-migrations","Disable automatic migrations").option("-ll, --log-level <logLevel>","Log level: DISABLED, INFO, LOG, WARN, ERROR","DISABLED").option("-ls, --log-style","Log style: RAW, PRETTY","RAW").option("-p, --pretty-log","Turn on logging with prettified output").action(async o=>{console.log(JSON.stringify(o));let{collection:e,database:t}=o,n=o.connectionString;await X({logging:{logStyle:o.prettyLog?_dumbo.LogStyle.PRETTY:_nullishCoalesce(o.logStyle, () => (_dumbo.LogStyle.RAW)),logLevel:o.logLevel?o.logLevel:o.prettyLog?_dumbo.LogLevel.INFO:_dumbo.LogLevel.DISABLED},schema:{collections:e,database:t,autoMigration:o.disableAutoMigrations?"None":"CreateOrUpdate"},connectionString:n})});var g=new _commander.Command;g.name("pongo").description("CLI tool for Pongo");g.addCommand(C);g.addCommand(d);g.addCommand(M);g.parse(process.argv);var xo=g;exports.default = xo;
|
|
27
27
|
//# sourceMappingURL=cli.cjs.map
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
2
|
+
import{B as p,E as P,G as b,h as S,t as y}from"./chunk-CRUPVSHS.js";import{Command as Z}from"commander";import{Command as N}from"commander";import w from"node:fs";var E=o=>{if(o.length===0)return o;let e=o.charAt(0).toUpperCase()+o.slice(1);return e.endsWith("s")&&(e=e.slice(0,-1)),e},s=(o=["users"])=>{let e=o.map(n=>`type ${E(n)} = { name: string; description: string; date: Date }`).join(`
|
|
3
3
|
`),t=o.map(n=>` ${n}: pongoSchema.collection<${E(n)}>('${n}'),`).join(`
|
|
4
4
|
`);return`import { pongoSchema } from '@event-driven-io/pongo';
|
|
5
5
|
|
|
@@ -21,7 +21,7 @@ ${s()}`,_=`Error: Config should have a default database defined (without name or
|
|
|
21
21
|
|
|
22
22
|
${s()}`,O=`Error: Database should have defined at least one collection, e.g.
|
|
23
23
|
|
|
24
|
-
${s()}`,D=async o=>{let e=new URL(o,`file://${process.cwd()}/`);try{let t=await import(e.href),n=A(t);return typeof n=="string"&&(console.error(n),process.exit(1)),n}catch{console.error(`Error: Couldn't load file: ${e.href}`),process.exit(1)}},$=(o,e)=>{try{
|
|
24
|
+
${s()}`,D=async o=>{let e=new URL(o,`file://${process.cwd()}/`);try{let t=await import(e.href),n=A(t);return typeof n=="string"&&(console.error(n),process.exit(1)),n}catch{console.error(`Error: Couldn't load file: ${e.href}`),process.exit(1)}},$=(o,e)=>{try{w.writeFileSync(o,s(e),"utf8"),console.log(`Configuration file stored at: ${o}`)}catch(t){console.error(`Error: Couldn't store config file: ${o}!`),console.error(t),process.exit(1)}},A=o=>{if(!o.default)return R;if(!o.default.schema)return T;if(!o.default.schema.dbs)return I;let t=y(o.default.schema.dbs).map(r=>r[1]).find(r=>r.name===void 0);return t?!t.collections||y(t.collections).map(r=>r[1]).length===0?O:P(t):_},C=new N("config").description("Manage Pongo configuration");C.command("sample").description("Generate or print sample configuration").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-f, --file <path>","Path to configuration file with collection list").option("-g, --generate","Generate sample config file").option("-p, --print","Print sample config file").action(o=>{let e=o.collection.length>0?o.collection:["users"];!("print"in o)&&!("generate"in o)&&(console.error(`Error: Please provide either:
|
|
25
25
|
--print param to print sample config or
|
|
26
|
-
--generate to generate sample config file`),process.exit(1)),"print"in o?console.log(`${s(e)}`):"generate"in o&&(o.file||(console.error("Error: You need to provide a config file through a --file"),process.exit(1)),$(o.file,e))});import{combineMigrations as G,dumbo as W,migrationTableSchemaComponent as B,runPostgreSQLMigrations as Q}from"@event-driven-io/dumbo";import{Command as U}from"commander";var d=new U("migrate").description("Manage database migrations");d.command("run").description("Run database migrations").option("-cs, --connectionString <string>","Connection string for the database").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-f, --config <path>","Path to configuration file with Pongo config").option("-dr, --dryRun","Perform dry run without commiting changes",!1).action(async o=>{let{collection:e,dryRun:t}=o,n=o.connectionString??process.env.DB_CONNECTION_STRING,r;n||(console.error('Error: Connection string is required. Provide it either as a "--connectionString" parameter or through the DB_CONNECTION_STRING environment variable.'),process.exit(1)),o.config?r=(await D(o.config)).collections.map(c=>c.name):e?r=e:(console.error('Error: You need to provide at least one collection name. Provide it either through "--config" file or as a "--collection" parameter.'),process.exit(1));let a=W({connectionString:n}),u=r.flatMap(l=>S(l).migrations({connector:"PostgreSQL:pg"}));await Q(a,u,{dryRun:t})});d.command("sql").description("Generate SQL for database migration").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("--print","Print the SQL to the console (default)",!0).action(o=>{let{collection:e}=o;e||(console.error('Error: You need to provide at least one collection name is required. Provide it either as a "col" parameter.'),process.exit(1));let n=[...B.migrations({connector:"PostgreSQL:pg"}),...e.flatMap(r=>S(r).migrations({connector:"PostgreSQL:pg"}))];console.log("Printing SQL:"),console.log(G(...n))});import{checkConnection as q,LogLevel as L,LogStyle as f,prettyJson as Y,SQL as k}from"@event-driven-io/dumbo";import i from"chalk";import F from"cli-table3";import{Command as
|
|
26
|
+
--generate to generate sample config file`),process.exit(1)),"print"in o?console.log(`${s(e)}`):"generate"in o&&(o.file||(console.error("Error: You need to provide a config file through a --file"),process.exit(1)),$(o.file,e))});import{combineMigrations as G,dumbo as W,migrationTableSchemaComponent as B,runPostgreSQLMigrations as Q}from"@event-driven-io/dumbo";import{Command as U}from"commander";var d=new U("migrate").description("Manage database migrations");d.command("run").description("Run database migrations").option("-cs, --connectionString <string>","Connection string for the database").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-f, --config <path>","Path to configuration file with Pongo config").option("-dr, --dryRun","Perform dry run without commiting changes",!1).action(async o=>{let{collection:e,dryRun:t}=o,n=o.connectionString??process.env.DB_CONNECTION_STRING,r;n||(console.error('Error: Connection string is required. Provide it either as a "--connectionString" parameter or through the DB_CONNECTION_STRING environment variable.'),process.exit(1)),o.config?r=(await D(o.config)).collections.map(c=>c.name):e?r=e:(console.error('Error: You need to provide at least one collection name. Provide it either through "--config" file or as a "--collection" parameter.'),process.exit(1));let a=W({connectionString:n}),u=r.flatMap(l=>S(l).migrations({connector:"PostgreSQL:pg"}));await Q(a,u,{dryRun:t})});d.command("sql").description("Generate SQL for database migration").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("--print","Print the SQL to the console (default)",!0).action(o=>{let{collection:e}=o;e||(console.error('Error: You need to provide at least one collection name is required. Provide it either as a "col" parameter.'),process.exit(1));let n=[...B.migrations({connector:"PostgreSQL:pg"}),...e.flatMap(r=>S(r).migrations({connector:"PostgreSQL:pg"}))];console.log("Printing SQL:"),console.log(G(...n))});import{checkConnection as q,LogLevel as L,LogStyle as f,prettyJson as Y,SQL as k}from"@event-driven-io/dumbo";import i from"chalk";import F from"cli-table3";import{Command as J}from"commander";import j from"node:repl";var m,V=(o,e)=>e.map(n=>Math.max(n.length,...o.map(a=>a[n]?String(a[n]).length:0))+2),z=o=>Array.isArray(o)?H(o):Y(o),H=o=>{if(o.length===0)return i.yellow("No documents found.");let e=Object.keys(o[0]),t=V(o,e),n=new F({head:e.map(r=>i.cyan(r)),colWidths:t});return o.forEach(r=>{n.push(e.map(a=>r[a]!==void 0?String(r[a]):""))}),n.toString()},v=o=>{process.env.DUMBO_LOG_LEVEL=o},x=o=>{process.env.DUMBO_LOG_STYLE=o},K=o=>{o!==void 0&&v(o),x(f.PRETTY)},X=async o=>{console.log(JSON.stringify(o)),v(process.env.DUMBO_LOG_LEVEL??o.logging.logLevel),x(process.env.DUMBO_LOG_STYLE??o.logging.logStyle),console.log(i.green("Starting Pongo Shell (version: 0.16.0-alpha.8)"));let e=o.connectionString??process.env.DB_CONNECTION_STRING??"postgresql://postgres:postgres@localhost:5432/postgres";(o.connectionString??process.env.DB_CONNECTION_STRING)||console.log(i.yellow("No connection string provided, using: 'postgresql://postgres:postgres@localhost:5432/postgres'"));let t=await q(e);t.successful||(t.errorType==="ConnectionRefused"?console.error(i.red("Connection was refused. Check if the PostgreSQL server is running and accessible.")):t.errorType==="Authentication"?console.error(i.red("Authentication failed. Check the username and password in the connection string.")):console.error(i.red("Error connecting to PostgreSQL server")),console.log(i.red("Exiting Pongo Shell...")),process.exit()),console.log(i.green("Successfully connected")),console.log(i.green("Use db.<collection>.<method>() to query."));let n=j.start({prompt:i.green("pongo> "),useGlobal:!0,breakEvalOnSigint:!0,writer:z}),r;if(o.schema.collections.length>0){let a={};for(let c of o.schema.collections)a[c]=p.collection(c);let u=p.client({database:p.db(o.schema.database,a)}),l=b(e,{schema:{definition:u,autoMigration:o.schema.autoMigration}});r=l.database;for(let c of o.schema.collections)n.context[c]=l.database[c];m=l}else m=b(e,{schema:{autoMigration:o.schema.autoMigration}}),r=m.db(o.schema.database);n.context.pongo=m,n.context.db=r,n.context.SQL=k,n.context.setLogLevel=v,n.context.setLogStyle=x,n.context.prettifyLogs=K,n.context.LogStyle=f,n.context.LogLevel=L,n.on("exit",async()=>{await h(),process.exit()}),n.on("SIGINT",async()=>{await h(),process.exit()})},h=async()=>{console.log(i.yellow("Exiting Pongo Shell...")),await m.close()};process.on("uncaughtException",h);process.on("SIGINT",h);var M=new J("shell").description("Start an interactive Pongo shell").option("-cs, --connectionString <string>","Connection string for the database").option("-db, --database <string>","Database name to connect","postgres").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-no-migrations, --disable-auto-migrations","Disable automatic migrations").option("-ll, --log-level <logLevel>","Log level: DISABLED, INFO, LOG, WARN, ERROR","DISABLED").option("-ls, --log-style","Log style: RAW, PRETTY","RAW").option("-p, --pretty-log","Turn on logging with prettified output").action(async o=>{console.log(JSON.stringify(o));let{collection:e,database:t}=o,n=o.connectionString;await X({logging:{logStyle:o.prettyLog?f.PRETTY:o.logStyle??f.RAW,logLevel:o.logLevel?o.logLevel:o.prettyLog?L.INFO:L.DISABLED},schema:{collections:e,database:t,autoMigration:o.disableAutoMigrations?"None":"CreateOrUpdate"},connectionString:n})});var g=new Z;g.name("pongo").description("CLI tool for Pongo");g.addCommand(C);g.addCommand(d);g.addCommand(M);g.parse(process.argv);var xo=g;export{xo as default};
|
|
27
27
|
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/commandLine/configFile.ts","../src/commandLine/migrate.ts","../src/commandLine/shell.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { configCommand, migrateCommand, shellCommand } from './commandLine';\n\nconst program = new Command();\n\nprogram.name('pongo').description('CLI tool for Pongo');\n\nprogram.addCommand(configCommand);\nprogram.addCommand(migrateCommand);\nprogram.addCommand(shellCommand);\n\nprogram.parse(process.argv);\n\nexport default program;\n","import { Command } from 'commander';\nimport fs from 'node:fs';\nimport {\n objectEntries,\n toDbSchemaMetadata,\n type PongoDbSchemaMetadata,\n type PongoSchemaConfig,\n} from '../core';\n\nconst formatTypeName = (input: string): string => {\n if (input.length === 0) {\n return input;\n }\n\n let formatted = input.charAt(0).toUpperCase() + input.slice(1);\n\n if (formatted.endsWith('s')) {\n formatted = formatted.slice(0, -1);\n }\n\n return formatted;\n};\n\nconst sampleConfig = (collectionNames: string[] = ['users']) => {\n const types = collectionNames\n .map(\n (name) =>\n `type ${formatTypeName(name)} = { name: string; description: string; date: Date }`,\n )\n .join('\\n');\n\n const collections = collectionNames\n .map(\n (name) =>\n ` ${name}: pongoSchema.collection<${formatTypeName(name)}>('${name}'),`,\n )\n .join('\\n');\n\n return `import { pongoSchema } from '@event-driven-io/pongo';\n\n${types}\n\nexport default {\n schema: pongoSchema.client({\n database: pongoSchema.db({\n${collections}\n }),\n }),\n};`;\n};\n\nconst missingDefaultExport = `Error: Config should contain default export, e.g.\\n\\n${sampleConfig()}`;\nconst missingSchema = `Error: Config should contain schema property, e.g.\\n\\n${sampleConfig()}`;\nconst missingDbs = `Error: Config should have at least a single database defined, e.g.\\n\\n${sampleConfig()}`;\nconst missingDefaultDb = `Error: Config should have a default database defined (without name or or with default database name), e.g.\\n\\n${sampleConfig()}`;\nconst missingCollections = `Error: Database should have defined at least one collection, e.g.\\n\\n${sampleConfig()}`;\n\nexport const loadConfigFile = async (\n configPath: string,\n): Promise<PongoDbSchemaMetadata> => {\n const configUrl = new URL(configPath, `file://${process.cwd()}/`);\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const imported: Partial<{ default: PongoSchemaConfig }> = await import(\n configUrl.href\n );\n\n const parsed = parseDefaultDbSchema(imported);\n\n if (typeof parsed === 'string') {\n console.error(parsed);\n process.exit(1);\n }\n\n return parsed;\n } catch {\n console.error(`Error: Couldn't load file: ${configUrl.href}`);\n process.exit(1);\n }\n};\n\nexport const generateConfigFile = (\n configPath: string,\n collectionNames: string[],\n): void => {\n try {\n fs.writeFileSync(configPath, sampleConfig(collectionNames), 'utf8');\n console.log(`Configuration file stored at: ${configPath}`);\n } catch (error) {\n console.error(`Error: Couldn't store config file: ${configPath}!`);\n console.error(error);\n process.exit(1);\n }\n};\n\nexport const parseDefaultDbSchema = (\n imported: Partial<{ default: PongoSchemaConfig }>,\n): PongoDbSchemaMetadata | string => {\n if (!imported.default) {\n return missingDefaultExport;\n }\n\n if (!imported.default.schema) {\n return missingSchema;\n }\n\n if (!imported.default.schema.dbs) {\n return missingDbs;\n }\n\n const dbs = objectEntries(imported.default.schema.dbs).map((db) => db[1]);\n\n const defaultDb = dbs.find((db) => db.name === undefined);\n\n if (!defaultDb) {\n return missingDefaultDb;\n }\n\n if (!defaultDb.collections) {\n return missingCollections;\n }\n\n const collections = objectEntries(defaultDb.collections).map((col) => col[1]);\n\n if (collections.length === 0) {\n return missingCollections;\n }\n\n return toDbSchemaMetadata(defaultDb);\n};\n\ntype SampleConfigOptions =\n | {\n collection: string[];\n print?: boolean;\n }\n | {\n collection: string[];\n generate?: boolean;\n file?: string;\n };\n\nexport const configCommand = new Command('config').description(\n 'Manage Pongo configuration',\n);\n\nconfigCommand\n .command('sample')\n .description('Generate or print sample configuration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option(\n '-f, --file <path>',\n 'Path to configuration file with collection list',\n )\n .option('-g, --generate', 'Generate sample config file')\n .option('-p, --print', 'Print sample config file')\n .action((options: SampleConfigOptions) => {\n const collectionNames =\n options.collection.length > 0 ? options.collection : ['users'];\n\n if (!('print' in options) && !('generate' in options)) {\n console.error(\n 'Error: Please provide either:\\n--print param to print sample config or\\n--generate to generate sample config file',\n );\n process.exit(1);\n }\n\n if ('print' in options) {\n console.log(`${sampleConfig(collectionNames)}`);\n } else if ('generate' in options) {\n if (!options.file) {\n console.error(\n 'Error: You need to provide a config file through a --file',\n );\n process.exit(1);\n }\n\n generateConfigFile(options.file, collectionNames);\n }\n });\n","import {\n combineMigrations,\n dumbo,\n migrationTableSchemaComponent,\n runPostgreSQLMigrations,\n} from '@event-driven-io/dumbo';\nimport { Command } from 'commander';\nimport { pongoCollectionSchemaComponent } from '../core';\nimport { loadConfigFile } from './configFile';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n config?: string;\n dryRun?: boolean;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n collection: string[];\n}\n\nexport const migrateCommand = new Command('migrate').description(\n 'Manage database migrations',\n);\n\nmigrateCommand\n .command('run')\n .description('Run database migrations')\n .option(\n '-cs, --connectionString <string>',\n 'Connection string for the database',\n )\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option('-f, --config <path>', 'Path to configuration file with Pongo config')\n .option('-dr, --dryRun', 'Perform dry run without commiting changes', false)\n .action(async (options: MigrateRunOptions) => {\n const { collection, dryRun } = options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--connectionString\" parameter or through the DB_CONNECTION_STRING environment variable.',\n );\n process.exit(1);\n }\n\n if (options.config) {\n const config = await loadConfigFile(options.config);\n\n collectionNames = config.collections.map((c) => c.name);\n } else if (collection) {\n collectionNames = collection;\n } else {\n console.error(\n 'Error: You need to provide at least one collection name. Provide it either through \"--config\" file or as a \"--collection\" parameter.',\n );\n process.exit(1);\n }\n\n const pool = dumbo({ connectionString });\n\n const migrations = collectionNames.flatMap((collectionsName) =>\n pongoCollectionSchemaComponent(collectionsName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n );\n\n await runPostgreSQLMigrations(pool, migrations, {\n dryRun,\n });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option('--print', 'Print the SQL to the console (default)', true)\n //.option('--write <filename>', 'Write the SQL to a specified file')\n .action((options: MigrateSqlOptions) => {\n const { collection } = options;\n\n if (!collection) {\n console.error(\n 'Error: You need to provide at least one collection name is required. Provide it either as a \"col\" parameter.',\n );\n process.exit(1);\n }\n const coreMigrations = migrationTableSchemaComponent.migrations({\n connector: 'PostgreSQL:pg',\n });\n const migrations = [\n ...coreMigrations,\n ...collection.flatMap((collectionsName) =>\n pongoCollectionSchemaComponent(collectionsName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n ),\n ];\n\n console.log('Printing SQL:');\n console.log(combineMigrations(...migrations));\n });\n","import {\n checkConnection,\n LogLevel,\n LogStyle,\n prettyJson,\n SQL,\n type MigrationStyle,\n} from '@event-driven-io/dumbo';\nimport chalk from 'chalk';\nimport Table from 'cli-table3';\nimport { Command } from 'commander';\nimport repl from 'node:repl';\nimport {\n pongoClient,\n pongoSchema,\n type PongoClient,\n type PongoCollectionSchema,\n type PongoDb,\n} from '../core';\n\nlet pongo: PongoClient;\n\nconst calculateColumnWidths = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n results: any[],\n columnNames: string[],\n): number[] => {\n const columnWidths = columnNames.map((col) => {\n const maxWidth = Math.max(\n col.length, // Header size\n ...results.map((result) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n result[col] ? String(result[col]).length : 0,\n ),\n );\n return maxWidth + 2; // Add padding\n });\n return columnWidths;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst printOutput = (obj: any): string => {\n return Array.isArray(obj) ? displayResultsAsTable(obj) : prettyJson(obj);\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst displayResultsAsTable = (results: any[]): string => {\n if (results.length === 0) {\n return chalk.yellow('No documents found.');\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n const columnNames = Object.keys(results[0]);\n\n const columnWidths = calculateColumnWidths(results, columnNames);\n\n const table = new Table({\n head: columnNames.map((col) => chalk.cyan(col)),\n colWidths: columnWidths,\n });\n\n results.forEach((result) => {\n table.push(\n columnNames.map((col) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n result[col] !== undefined ? String(result[col]) : '',\n ),\n );\n });\n\n return table.toString();\n};\n\nconst setLogLevel = (logLevel: string) => {\n process.env.DUMBO_LOG_LEVEL = logLevel;\n};\n\nconst setLogStyle = (logLevel: string) => {\n process.env.DUMBO_LOG_STYLE = logLevel;\n};\n\nconst prettifyLogs = (logLevel?: string) => {\n if (logLevel !== undefined) setLogLevel(logLevel);\n setLogStyle(LogStyle.PRETTY);\n};\n\nconst startRepl = async (options: {\n logging: {\n logLevel: LogLevel;\n logStyle: LogStyle;\n };\n schema: {\n database: string;\n collections: string[];\n autoMigration: MigrationStyle;\n };\n connectionString: string | undefined;\n}) => {\n // TODO: This will change when we have proper tracing and logging config\n // For now, that's enough\n setLogLevel(process.env.DUMBO_LOG_LEVEL ?? options.logging.logLevel);\n setLogStyle(process.env.DUMBO_LOG_STYLE ?? options.logging.logStyle);\n\n console.log(chalk.green('Starting Pongo Shell (version: 0.16.0-alpha.6)'));\n\n const connectionString =\n options.connectionString ??\n process.env.DB_CONNECTION_STRING ??\n 'postgresql://postgres:postgres@localhost:5432/postgres';\n\n if (!(options.connectionString ?? process.env.DB_CONNECTION_STRING)) {\n console.log(\n chalk.yellow(\n `No connection string provided, using: 'postgresql://postgres:postgres@localhost:5432/postgres'`,\n ),\n );\n }\n\n const connectionCheck = await checkConnection(connectionString);\n\n if (!connectionCheck.successful) {\n if (connectionCheck.errorType === 'ConnectionRefused') {\n console.error(\n chalk.red(\n `Connection was refused. Check if the PostgreSQL server is running and accessible.`,\n ),\n );\n } else if (connectionCheck.errorType === 'Authentication') {\n console.error(\n chalk.red(\n `Authentication failed. Check the username and password in the connection string.`,\n ),\n );\n } else {\n console.error(chalk.red('Error connecting to PostgreSQL server'));\n }\n console.log(chalk.red('Exiting Pongo Shell...'));\n process.exit();\n }\n\n console.log(chalk.green(`Successfully connected`));\n console.log(chalk.green('Use db.<collection>.<method>() to query.'));\n\n const shell = repl.start({\n prompt: chalk.green('pongo> '),\n useGlobal: true,\n breakEvalOnSigint: true,\n writer: printOutput,\n });\n\n let db: PongoDb;\n\n if (options.schema.collections.length > 0) {\n const collectionsSchema: Record<string, PongoCollectionSchema> = {};\n\n for (const collectionName of options.schema.collections) {\n collectionsSchema[collectionName] =\n pongoSchema.collection(collectionName);\n }\n\n const schema = pongoSchema.client({\n database: pongoSchema.db(options.schema.database, collectionsSchema),\n });\n\n const typedClient = pongoClient(connectionString, {\n schema: {\n definition: schema,\n autoMigration: options.schema.autoMigration,\n },\n });\n\n db = typedClient.database;\n\n for (const collectionName of options.schema.collections) {\n shell.context[collectionName] = typedClient.database[collectionName];\n }\n\n pongo = typedClient;\n } else {\n pongo = pongoClient(connectionString, {\n schema: { autoMigration: options.schema.autoMigration },\n });\n\n db = pongo.db(options.schema.database);\n }\n\n shell.context.pongo = pongo;\n shell.context.db = db;\n\n // helpers\n shell.context.SQL = SQL;\n shell.context.setLogLevel = setLogLevel;\n shell.context.setLogStyle = setLogStyle;\n shell.context.prettifyLogs = prettifyLogs;\n shell.context.LogStyle = LogStyle;\n shell.context.LogLevel = LogLevel;\n\n // Intercept REPL output to display results as a table if they are arrays\n shell.on('exit', async () => {\n await teardown();\n process.exit();\n });\n\n shell.on('SIGINT', async () => {\n await teardown();\n process.exit();\n });\n};\n\nconst teardown = async () => {\n console.log(chalk.yellow('Exiting Pongo Shell...'));\n await pongo.close();\n};\n\nprocess.on('uncaughtException', teardown);\nprocess.on('SIGINT', teardown);\n\ninterface ShellOptions {\n database: string;\n collection: string[];\n connectionString?: string;\n disableAutoMigrations: boolean;\n logStyle?: string;\n logLevel?: string;\n prettyLog?: boolean;\n}\n\nconst shellCommand = new Command('shell')\n .description('Start an interactive Pongo shell')\n .option(\n '-cs, --connectionString <string>',\n 'Connection string for the database',\n )\n .option('-db, --database <string>', 'Database name to connect', 'postgres')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option(\n '-no-migrations, --disable-auto-migrations',\n 'Disable automatic migrations',\n )\n .option(\n '-ll, --log-level <logLevel>',\n 'Log level: DISABLED, INFO, LOG, WARN, ERROR',\n 'DISABLED',\n )\n .option('-ls, --log-style', 'Log style: RAW, PRETTY', 'RAW')\n .option('-p, --pretty-log', 'Turn on logging with prettified output')\n .action(async (options: ShellOptions) => {\n const { collection, database } = options;\n const connectionString = options.connectionString;\n\n await startRepl({\n logging: {\n logStyle: options.prettyLog\n ? LogStyle.PRETTY\n : ((options.logStyle as LogStyle | undefined) ?? LogStyle.RAW),\n logLevel: options.logLevel\n ? (options.logLevel as LogLevel)\n : options.prettyLog\n ? LogLevel.INFO\n : LogLevel.DISABLED,\n },\n schema: {\n collections: collection,\n database,\n autoMigration: options.disableAutoMigrations\n ? 'None'\n : 'CreateOrUpdate',\n },\n connectionString,\n });\n });\n\nexport { shellCommand };\n"],"mappings":";oEACA,OAAS,WAAAA,MAAe,YCDxB,OAAS,WAAAC,MAAe,YACxB,OAAOC,MAAQ,UAQf,IAAMC,EAAkBC,GAA0B,CAChD,GAAIA,EAAM,SAAW,EACnB,OAAOA,EAGT,IAAIC,EAAYD,EAAM,OAAO,CAAC,EAAE,YAAY,EAAIA,EAAM,MAAM,CAAC,EAE7D,OAAIC,EAAU,SAAS,GAAG,IACxBA,EAAYA,EAAU,MAAM,EAAG,EAAE,GA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CACd,QAAS,CACP,SAAUC,EAAQ,UACdF,EAAS,OACPE,EAAQ,UAAqCF,EAAS,IAC5D,SAAUE,EAAQ,SACbA,EAAQ,SACTA,EAAQ,UACNc,EAAS,KACTA,EAAS,QACjB,EACA,OAAQ,CACN,YAAaM,EACb,SAAAC,EACA,cAAerB,EAAQ,sBACnB,OACA,gBACN,EACA,iBAAAC,CACF,CAAC,CACH,CAAC,EHlRH,IAAMqB,EAAU,IAAIC,EAEpBD,EAAQ,KAAK,OAAO,EAAE,YAAY,oBAAoB,EAEtDA,EAAQ,WAAWE,CAAa,EAChCF,EAAQ,WAAWG,CAAc,EACjCH,EAAQ,WAAWI,CAAY,EAE/BJ,EAAQ,MAAM,QAAQ,IAAI,EAE1B,IAAOK,GAAQL","names":["Command","Command","fs","formatTypeName","input","formatted","sampleConfig","collectionNames","types","name","collections","missingDefaultExport","missingSchema","missingDbs","missingDefaultDb","missingCollections","loadConfigFile","configPath","configUrl","imported","parsed","parseDefaultDbSchema","generateConfigFile","fs","error","defaultDb","objectEntries","db","col","toDbSchemaMetadata","configCommand","Command","value","previous","options","combineMigrations","dumbo","migrationTableSchemaComponent","runPostgreSQLMigrations","Command","migrateCommand","Command","value","previous","options","collection","dryRun","connectionString","collectionNames","loadConfigFile","pool","dumbo","migrations","collectionsName","pongoCollectionSchemaComponent","runPostgreSQLMigrations","migrationTableSchemaComponent","combineMigrations","checkConnection","LogLevel","LogStyle","prettyJson","SQL","chalk","Table","Command","repl","pongo","calculateColumnWidths","results","columnNames","col","result","printOutput","obj","displayResultsAsTable","prettyJson","chalk","columnWidths","table","Table","setLogLevel","logLevel","setLogStyle","prettifyLogs","LogStyle","startRepl","options","connectionString","connectionCheck","checkConnection","shell","repl","db","collectionsSchema","collectionName","pongoSchema","schema","typedClient","pongoClient","SQL","LogLevel","teardown","shellCommand","Command","value","previous","collection","database","program","Command","configCommand","migrateCommand","shellCommand","cli_default"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/commandLine/configFile.ts","../src/commandLine/migrate.ts","../src/commandLine/shell.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { configCommand, migrateCommand, shellCommand } from './commandLine';\n\nconst program = new Command();\n\nprogram.name('pongo').description('CLI tool for Pongo');\n\nprogram.addCommand(configCommand);\nprogram.addCommand(migrateCommand);\nprogram.addCommand(shellCommand);\n\nprogram.parse(process.argv);\n\nexport default program;\n","import { Command } from 'commander';\nimport fs from 'node:fs';\nimport {\n objectEntries,\n toDbSchemaMetadata,\n type PongoDbSchemaMetadata,\n type PongoSchemaConfig,\n} from '../core';\n\nconst formatTypeName = (input: string): string => {\n if (input.length === 0) {\n return input;\n }\n\n let formatted = input.charAt(0).toUpperCase() + input.slice(1);\n\n if (formatted.endsWith('s')) {\n formatted = formatted.slice(0, -1);\n }\n\n return formatted;\n};\n\nconst sampleConfig = (collectionNames: string[] = ['users']) => {\n const types = collectionNames\n .map(\n (name) =>\n `type ${formatTypeName(name)} = { name: string; description: string; date: Date }`,\n )\n .join('\\n');\n\n const collections = collectionNames\n .map(\n (name) =>\n ` ${name}: pongoSchema.collection<${formatTypeName(name)}>('${name}'),`,\n )\n .join('\\n');\n\n return `import { pongoSchema } from '@event-driven-io/pongo';\n\n${types}\n\nexport default {\n schema: pongoSchema.client({\n database: pongoSchema.db({\n${collections}\n }),\n }),\n};`;\n};\n\nconst missingDefaultExport = `Error: Config should contain default export, e.g.\\n\\n${sampleConfig()}`;\nconst missingSchema = `Error: Config should contain schema property, e.g.\\n\\n${sampleConfig()}`;\nconst missingDbs = `Error: Config should have at least a single database defined, e.g.\\n\\n${sampleConfig()}`;\nconst missingDefaultDb = `Error: Config should have a default database defined (without name or or with default database name), e.g.\\n\\n${sampleConfig()}`;\nconst missingCollections = `Error: Database should have defined at least one collection, e.g.\\n\\n${sampleConfig()}`;\n\nexport const loadConfigFile = async (\n configPath: string,\n): Promise<PongoDbSchemaMetadata> => {\n const configUrl = new URL(configPath, `file://${process.cwd()}/`);\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const imported: Partial<{ default: PongoSchemaConfig }> = await import(\n configUrl.href\n );\n\n const parsed = parseDefaultDbSchema(imported);\n\n if (typeof parsed === 'string') {\n console.error(parsed);\n process.exit(1);\n }\n\n return parsed;\n } catch {\n console.error(`Error: Couldn't load file: ${configUrl.href}`);\n process.exit(1);\n }\n};\n\nexport const generateConfigFile = (\n configPath: string,\n collectionNames: string[],\n): void => {\n try {\n fs.writeFileSync(configPath, sampleConfig(collectionNames), 'utf8');\n console.log(`Configuration file stored at: ${configPath}`);\n } catch (error) {\n console.error(`Error: Couldn't store config file: ${configPath}!`);\n console.error(error);\n process.exit(1);\n }\n};\n\nexport const parseDefaultDbSchema = (\n imported: Partial<{ default: PongoSchemaConfig }>,\n): PongoDbSchemaMetadata | string => {\n if (!imported.default) {\n return missingDefaultExport;\n }\n\n if (!imported.default.schema) {\n return missingSchema;\n }\n\n if (!imported.default.schema.dbs) {\n return missingDbs;\n }\n\n const dbs = objectEntries(imported.default.schema.dbs).map((db) => db[1]);\n\n const defaultDb = dbs.find((db) => db.name === undefined);\n\n if (!defaultDb) {\n return missingDefaultDb;\n }\n\n if (!defaultDb.collections) {\n return missingCollections;\n }\n\n const collections = objectEntries(defaultDb.collections).map((col) => col[1]);\n\n if (collections.length === 0) {\n return missingCollections;\n }\n\n return toDbSchemaMetadata(defaultDb);\n};\n\ntype SampleConfigOptions =\n | {\n collection: string[];\n print?: boolean;\n }\n | {\n collection: string[];\n generate?: boolean;\n file?: string;\n };\n\nexport const configCommand = new Command('config').description(\n 'Manage Pongo configuration',\n);\n\nconfigCommand\n .command('sample')\n .description('Generate or print sample configuration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option(\n '-f, --file <path>',\n 'Path to configuration file with collection list',\n )\n .option('-g, --generate', 'Generate sample config file')\n .option('-p, --print', 'Print sample config file')\n .action((options: SampleConfigOptions) => {\n const collectionNames =\n options.collection.length > 0 ? options.collection : ['users'];\n\n if (!('print' in options) && !('generate' in options)) {\n console.error(\n 'Error: Please provide either:\\n--print param to print sample config or\\n--generate to generate sample config file',\n );\n process.exit(1);\n }\n\n if ('print' in options) {\n console.log(`${sampleConfig(collectionNames)}`);\n } else if ('generate' in options) {\n if (!options.file) {\n console.error(\n 'Error: You need to provide a config file through a --file',\n );\n process.exit(1);\n }\n\n generateConfigFile(options.file, collectionNames);\n }\n });\n","import {\n combineMigrations,\n dumbo,\n migrationTableSchemaComponent,\n runPostgreSQLMigrations,\n} from '@event-driven-io/dumbo';\nimport { Command } from 'commander';\nimport { pongoCollectionSchemaComponent } from '../core';\nimport { loadConfigFile } from './configFile';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n config?: string;\n dryRun?: boolean;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n collection: string[];\n}\n\nexport const migrateCommand = new Command('migrate').description(\n 'Manage database migrations',\n);\n\nmigrateCommand\n .command('run')\n .description('Run database migrations')\n .option(\n '-cs, --connectionString <string>',\n 'Connection string for the database',\n )\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option('-f, --config <path>', 'Path to configuration file with Pongo config')\n .option('-dr, --dryRun', 'Perform dry run without commiting changes', false)\n .action(async (options: MigrateRunOptions) => {\n const { collection, dryRun } = options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--connectionString\" parameter or through the DB_CONNECTION_STRING environment variable.',\n );\n process.exit(1);\n }\n\n if (options.config) {\n const config = await loadConfigFile(options.config);\n\n collectionNames = config.collections.map((c) => c.name);\n } else if (collection) {\n collectionNames = collection;\n } else {\n console.error(\n 'Error: You need to provide at least one collection name. Provide it either through \"--config\" file or as a \"--collection\" parameter.',\n );\n process.exit(1);\n }\n\n const pool = dumbo({ connectionString });\n\n const migrations = collectionNames.flatMap((collectionsName) =>\n pongoCollectionSchemaComponent(collectionsName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n );\n\n await runPostgreSQLMigrations(pool, migrations, {\n dryRun,\n });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option('--print', 'Print the SQL to the console (default)', true)\n //.option('--write <filename>', 'Write the SQL to a specified file')\n .action((options: MigrateSqlOptions) => {\n const { collection } = options;\n\n if (!collection) {\n console.error(\n 'Error: You need to provide at least one collection name is required. Provide it either as a \"col\" parameter.',\n );\n process.exit(1);\n }\n const coreMigrations = migrationTableSchemaComponent.migrations({\n connector: 'PostgreSQL:pg',\n });\n const migrations = [\n ...coreMigrations,\n ...collection.flatMap((collectionsName) =>\n pongoCollectionSchemaComponent(collectionsName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n ),\n ];\n\n console.log('Printing SQL:');\n console.log(combineMigrations(...migrations));\n });\n","import {\n checkConnection,\n LogLevel,\n LogStyle,\n prettyJson,\n SQL,\n type MigrationStyle,\n} from '@event-driven-io/dumbo';\nimport chalk from 'chalk';\nimport Table from 'cli-table3';\nimport { Command } from 'commander';\nimport repl from 'node:repl';\nimport {\n pongoClient,\n pongoSchema,\n type PongoClient,\n type PongoCollectionSchema,\n type PongoDb,\n} from '../core';\n\nlet pongo: PongoClient;\n\nconst calculateColumnWidths = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n results: any[],\n columnNames: string[],\n): number[] => {\n const columnWidths = columnNames.map((col) => {\n const maxWidth = Math.max(\n col.length, // Header size\n ...results.map((result) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n result[col] ? String(result[col]).length : 0,\n ),\n );\n return maxWidth + 2; // Add padding\n });\n return columnWidths;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst printOutput = (obj: any): string => {\n return Array.isArray(obj) ? displayResultsAsTable(obj) : prettyJson(obj);\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst displayResultsAsTable = (results: any[]): string => {\n if (results.length === 0) {\n return chalk.yellow('No documents found.');\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n const columnNames = Object.keys(results[0]);\n\n const columnWidths = calculateColumnWidths(results, columnNames);\n\n const table = new Table({\n head: columnNames.map((col) => chalk.cyan(col)),\n colWidths: columnWidths,\n });\n\n results.forEach((result) => {\n table.push(\n columnNames.map((col) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n result[col] !== undefined ? String(result[col]) : '',\n ),\n );\n });\n\n return table.toString();\n};\n\nconst setLogLevel = (logLevel: string) => {\n process.env.DUMBO_LOG_LEVEL = logLevel;\n};\n\nconst setLogStyle = (logLevel: string) => {\n process.env.DUMBO_LOG_STYLE = logLevel;\n};\n\nconst prettifyLogs = (logLevel?: string) => {\n if (logLevel !== undefined) setLogLevel(logLevel);\n setLogStyle(LogStyle.PRETTY);\n};\n\nconst startRepl = async (options: {\n logging: {\n logLevel: LogLevel;\n logStyle: LogStyle;\n };\n schema: {\n database: string;\n collections: string[];\n autoMigration: MigrationStyle;\n };\n connectionString: string | undefined;\n}) => {\n console.log(JSON.stringify(options));\n // TODO: This will change when we have proper tracing and logging config\n // For now, that's enough\n setLogLevel(process.env.DUMBO_LOG_LEVEL ?? options.logging.logLevel);\n setLogStyle(process.env.DUMBO_LOG_STYLE ?? options.logging.logStyle);\n\n console.log(chalk.green('Starting Pongo Shell (version: 0.16.0-alpha.8)'));\n\n const connectionString =\n options.connectionString ??\n process.env.DB_CONNECTION_STRING ??\n 'postgresql://postgres:postgres@localhost:5432/postgres';\n\n if (!(options.connectionString ?? process.env.DB_CONNECTION_STRING)) {\n console.log(\n chalk.yellow(\n `No connection string provided, using: 'postgresql://postgres:postgres@localhost:5432/postgres'`,\n ),\n );\n }\n\n const connectionCheck = await checkConnection(connectionString);\n\n if (!connectionCheck.successful) {\n if (connectionCheck.errorType === 'ConnectionRefused') {\n console.error(\n chalk.red(\n `Connection was refused. Check if the PostgreSQL server is running and accessible.`,\n ),\n );\n } else if (connectionCheck.errorType === 'Authentication') {\n console.error(\n chalk.red(\n `Authentication failed. Check the username and password in the connection string.`,\n ),\n );\n } else {\n console.error(chalk.red('Error connecting to PostgreSQL server'));\n }\n console.log(chalk.red('Exiting Pongo Shell...'));\n process.exit();\n }\n\n console.log(chalk.green(`Successfully connected`));\n console.log(chalk.green('Use db.<collection>.<method>() to query.'));\n\n const shell = repl.start({\n prompt: chalk.green('pongo> '),\n useGlobal: true,\n breakEvalOnSigint: true,\n writer: printOutput,\n });\n\n let db: PongoDb;\n\n if (options.schema.collections.length > 0) {\n const collectionsSchema: Record<string, PongoCollectionSchema> = {};\n\n for (const collectionName of options.schema.collections) {\n collectionsSchema[collectionName] =\n pongoSchema.collection(collectionName);\n }\n\n const schema = pongoSchema.client({\n database: pongoSchema.db(options.schema.database, collectionsSchema),\n });\n\n const typedClient = pongoClient(connectionString, {\n schema: {\n definition: schema,\n autoMigration: options.schema.autoMigration,\n },\n });\n\n db = typedClient.database;\n\n for (const collectionName of options.schema.collections) {\n shell.context[collectionName] = typedClient.database[collectionName];\n }\n\n pongo = typedClient;\n } else {\n pongo = pongoClient(connectionString, {\n schema: { autoMigration: options.schema.autoMigration },\n });\n\n db = pongo.db(options.schema.database);\n }\n\n shell.context.pongo = pongo;\n shell.context.db = db;\n\n // helpers\n shell.context.SQL = SQL;\n shell.context.setLogLevel = setLogLevel;\n shell.context.setLogStyle = setLogStyle;\n shell.context.prettifyLogs = prettifyLogs;\n shell.context.LogStyle = LogStyle;\n shell.context.LogLevel = LogLevel;\n\n // Intercept REPL output to display results as a table if they are arrays\n shell.on('exit', async () => {\n await teardown();\n process.exit();\n });\n\n shell.on('SIGINT', async () => {\n await teardown();\n process.exit();\n });\n};\n\nconst teardown = async () => {\n console.log(chalk.yellow('Exiting Pongo Shell...'));\n await pongo.close();\n};\n\nprocess.on('uncaughtException', teardown);\nprocess.on('SIGINT', teardown);\n\ninterface ShellOptions {\n database: string;\n collection: string[];\n connectionString?: string;\n disableAutoMigrations: boolean;\n logStyle?: string;\n logLevel?: string;\n prettyLog?: boolean;\n}\n\nconst shellCommand = new Command('shell')\n .description('Start an interactive Pongo shell')\n .option(\n '-cs, --connectionString <string>',\n 'Connection string for the database',\n )\n .option('-db, --database <string>', 'Database name to connect', 'postgres')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option(\n '-no-migrations, --disable-auto-migrations',\n 'Disable automatic migrations',\n )\n .option(\n '-ll, --log-level <logLevel>',\n 'Log level: DISABLED, INFO, LOG, WARN, ERROR',\n 'DISABLED',\n )\n .option('-ls, --log-style', 'Log style: RAW, PRETTY', 'RAW')\n .option('-p, --pretty-log', 'Turn on logging with prettified output')\n .action(async (options: ShellOptions) => {\n console.log(JSON.stringify(options));\n const { collection, database } = options;\n const connectionString = options.connectionString;\n\n await startRepl({\n logging: {\n logStyle: options.prettyLog\n ? LogStyle.PRETTY\n : ((options.logStyle as LogStyle | undefined) ?? LogStyle.RAW),\n logLevel: options.logLevel\n ? (options.logLevel as LogLevel)\n : options.prettyLog\n ? LogLevel.INFO\n : LogLevel.DISABLED,\n },\n schema: {\n collections: collection,\n database,\n autoMigration: options.disableAutoMigrations\n ? 'None'\n : 'CreateOrUpdate',\n },\n connectionString,\n });\n });\n\nexport { shellCommand };\n"],"mappings":";oEACA,OAAS,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C,4BACA,8BACA,CAACC,EAAeC,IAEPA,EAAS,OAAO,CAACD,CAAK,CAAC,EAEhC,CAAC,CACH,EACC,OACC,4CACA,8BACF,EACC,OACC,8BACA,8CACA,UACF,EACC,OAAO,mBAAoB,yBAA0B,KAAK,EAC1D,OAAO,mBAAoB,wCAAwC,EACnE,OAAO,MAAOlB,GAA0B,CACvC,QAAQ,IAAI,KAAK,UAAUA,CAAO,CAAC,EACnC,GAAM,CAAE,WAAAoB,EAAY,SAAAC,CAAS,EAAIrB,EAC3BC,EAAmBD,EAAQ,iBAEjC,MAAMD,EAAU,CACd,QAAS,CACP,SAAUC,EAAQ,UACdF,EAAS,OACPE,EAAQ,UAAqCF,EAAS,IAC5D,SAAUE,EAAQ,SACbA,EAAQ,SACTA,EAAQ,UACNc,EAAS,KACTA,EAAS,QACjB,EACA,OAAQ,CACN,YAAaM,EACb,SAAAC,EACA,cAAerB,EAAQ,sBACnB,OACA,gBACN,EACA,iBAAAC,CACF,CAAC,CACH,CAAC,EHpRH,IAAMqB,EAAU,IAAIC,EAEpBD,EAAQ,KAAK,OAAO,EAAE,YAAY,oBAAoB,EAEtDA,EAAQ,WAAWE,CAAa,EAChCF,EAAQ,WAAWG,CAAc,EACjCH,EAAQ,WAAWI,CAAY,EAE/BJ,EAAQ,MAAM,QAAQ,IAAI,EAE1B,IAAOK,GAAQL","names":["Command","Command","fs","formatTypeName","input","formatted","sampleConfig","collectionNames","types","name","collections","missingDefaultExport","missingSchema","missingDbs","missingDefaultDb","missingCollections","loadConfigFile","configPath","configUrl","imported","parsed","parseDefaultDbSchema","generateConfigFile","fs","error","defaultDb","objectEntries","db","col","toDbSchemaMetadata","configCommand","Command","value","previous","options","combineMigrations","dumbo","migrationTableSchemaComponent","runPostgreSQLMigrations","Command","migrateCommand","Command","value","previous","options","collection","dryRun","connectionString","collectionNames","loadConfigFile","pool","dumbo","migrations","collectionsName","pongoCollectionSchemaComponent","runPostgreSQLMigrations","migrationTableSchemaComponent","combineMigrations","checkConnection","LogLevel","LogStyle","prettyJson","SQL","chalk","Table","Command","repl","pongo","calculateColumnWidths","results","columnNames","col","result","printOutput","obj","displayResultsAsTable","prettyJson","chalk","columnWidths","table","Table","setLogLevel","logLevel","setLogStyle","prettifyLogs","LogStyle","startRepl","options","connectionString","connectionCheck","checkConnection","shell","repl","db","collectionsSchema","collectionName","pongoSchema","schema","typedClient","pongoClient","SQL","LogLevel","teardown","shellCommand","Command","value","previous","collection","database","program","Command","configCommand","migrateCommand","shellCommand","cli_default"]}
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkBDSCD6MHcjs = require('./chunk-BDSCD6MH.cjs');exports.ConcurrencyError = _chunkBDSCD6MHcjs.p; exports.DOCUMENT_DOES_NOT_EXIST = _chunkBDSCD6MHcjs.v; exports.DOCUMENT_EXISTS = _chunkBDSCD6MHcjs.u; exports.NO_CONCURRENCY_CHECK = _chunkBDSCD6MHcjs.w; exports.OperatorMap = _chunkBDSCD6MHcjs.j; exports.PongoError = _chunkBDSCD6MHcjs.o; exports.QueryOperators = _chunkBDSCD6MHcjs.i; exports.clientToDbOptions = _chunkBDSCD6MHcjs.H; exports.expectedVersion = _chunkBDSCD6MHcjs.z; exports.expectedVersionValue = _chunkBDSCD6MHcjs.y; exports.getPongoDb = _chunkBDSCD6MHcjs.q; exports.hasOperators = _chunkBDSCD6MHcjs.l; exports.isGeneralExpectedDocumentVersion = _chunkBDSCD6MHcjs.x; exports.isNumber = _chunkBDSCD6MHcjs.m; exports.isOperator = _chunkBDSCD6MHcjs.k; exports.isPostgresClientOptions = _chunkBDSCD6MHcjs.c; exports.isString = _chunkBDSCD6MHcjs.n; exports.objectEntries = _chunkBDSCD6MHcjs.t; exports.operationResult = _chunkBDSCD6MHcjs.A; exports.pongoClient = _chunkBDSCD6MHcjs.G; exports.pongoCollection = _chunkBDSCD6MHcjs.g; exports.pongoCollectionPostgreSQLMigrations = _chunkBDSCD6MHcjs.a; exports.pongoCollectionSchemaComponent = _chunkBDSCD6MHcjs.h; exports.pongoDbSchemaComponent = _chunkBDSCD6MHcjs.e; exports.pongoSchema = _chunkBDSCD6MHcjs.B; exports.pongoSession = _chunkBDSCD6MHcjs.s; exports.pongoTransaction = _chunkBDSCD6MHcjs.r; exports.postgresDb = _chunkBDSCD6MHcjs.d; exports.postgresSQLBuilder = _chunkBDSCD6MHcjs.b; exports.proxyClientWithSchema = _chunkBDSCD6MHcjs.D; exports.proxyPongoDbWithSchema = _chunkBDSCD6MHcjs.C; exports.toClientSchemaMetadata = _chunkBDSCD6MHcjs.F; exports.toDbSchemaMetadata = _chunkBDSCD6MHcjs.E; exports.transactionExecutorOrDefault = _chunkBDSCD6MHcjs.f;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/index.cjs"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/index.cjs"],"names":[],"mappings":"AAAA,iIAA6N,soDAA2xB","file":"/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/index.cjs"}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { Dumbo, MigrationStyle, SchemaComponent, SQLMigration, SQL } from '@event-driven-io/dumbo';
|
|
2
|
-
import { P as PongoDb, a as PongoDocument, b as PongoCollection, O as OptionalUnlessRequiredIdAndVersion, c as PongoFilter, d as PongoUpdate, U as UpdateOneOptions, W as WithoutId, R as ReplaceOneOptions, D as DeleteOneOptions, e as PongoTransactionOptions, f as PongoSession, g as PongoDbTransaction } from './pongoClient-
|
|
3
|
-
export { ad as $inc, ae as $push, ab as $set, ac as $unset, A as AllowedDbClientOptions, a7 as AlternativeType,
|
|
1
|
+
import { Dumbo, MigrationStyle, SQLExecutor, SchemaComponent, SQLMigration, SQL } from '@event-driven-io/dumbo';
|
|
2
|
+
import { P as PongoDb, C as CollectionOperationOptions, a as PongoDocument, b as PongoCollection, O as OptionalUnlessRequiredIdAndVersion, c as PongoFilter, d as PongoUpdate, U as UpdateOneOptions, W as WithoutId, R as ReplaceOneOptions, D as DeleteOneOptions, e as PongoTransactionOptions, f as PongoSession, g as PongoDbTransaction } from './pongoClient-CjXGu-SC.cjs';
|
|
3
|
+
export { ad as $inc, ae as $push, ab as $set, ac as $unset, A as AllowedDbClientOptions, a7 as AlternativeType, q as CollectionsMap, a8 as Condition, s as DBsMap, aj as DOCUMENT_DOES_NOT_EXIST, ai as DOCUMENT_EXISTS, L as DeleteManyOptions, a2 as Document, ax as DocumentHandler, T as EnhancedOmit, ah as ExpectedDocumentVersion, af as ExpectedDocumentVersionGeneral, ag as ExpectedDocumentVersionValue, K as HandleOptions, Q as HasId, S as InferIdType, H as InsertManyOptions, I as InsertOneOptions, ak as NO_CONCURRENCY_CHECK, a6 as NonObjectIdLikeDocument, N as NotPooledPongoOptions, M as ObjectId, a5 as ObjectIdLike, ao as OperationResult, a3 as OptionalId, V as OptionalUnlessRequiredId, X as OptionalUnlessRequiredVersion, a4 as OptionalVersion, G as PongoClient, i as PongoClientOptions, o as PongoClientSchema, z as PongoClientSchemaMetadata, t as PongoClientWithSchema, m as PongoCollectionSchema, x as PongoCollectionSchemaMetadata, k as PongoDbClientOptions, n as PongoDbSchema, y as PongoDbSchemaMetadata, r as PongoDbWithSchema, av as PongoDeleteManyResult, au as PongoDeleteResult, aa as PongoFilterOperator, aw as PongoHandleResult, ar as PongoInsertManyResult, aq as PongoInsertOneResult, F as PongoSchemaConfig, at as PongoUpdateManyResult, as as PongoUpdateResult, h as PooledPongoClientOptions, ay as PostgresDbClientOptions, a1 as RegExpOrString, a9 as RootFilterOperators, J as UpdateManyOptions, Y as WithId, $ as WithIdAndVersion, Z as WithVersion, a0 as WithoutIdAndVersion, _ as WithoutVersion, j as clientToDbOptions, an as expectedVersion, am as expectedVersionValue, l as getPongoDb, al as isGeneralExpectedDocumentVersion, az as isPostgresClientOptions, ap as operationResult, p as pongoClient, aB as pongoDbSchemaComponent, u as pongoSchema, aA as postgresDb, w as proxyClientWithSchema, v as proxyPongoDbWithSchema, E as toClientSchemaMetadata, B as toDbSchemaMetadata } from './pongoClient-CjXGu-SC.cjs';
|
|
4
4
|
import 'pg';
|
|
5
5
|
|
|
6
6
|
type PongoCollectionOptions<ConnectorType extends string = string> = {
|
|
@@ -15,6 +15,7 @@ type PongoCollectionOptions<ConnectorType extends string = string> = {
|
|
|
15
15
|
throwOnOperationFailures?: boolean;
|
|
16
16
|
};
|
|
17
17
|
};
|
|
18
|
+
declare const transactionExecutorOrDefault: <ConnectorType extends string = string>(db: PongoDb<ConnectorType>, options: CollectionOperationOptions | undefined, defaultSqlExecutor: SQLExecutor) => Promise<SQLExecutor>;
|
|
18
19
|
declare const pongoCollection: <T extends PongoDocument, ConnectorType extends string = string>({ db, collectionName, pool, sqlBuilder: SqlFor, schema, errors, }: PongoCollectionOptions<ConnectorType>) => PongoCollection<T>;
|
|
19
20
|
declare const pongoCollectionSchemaComponent: (collectionName: string) => SchemaComponent;
|
|
20
21
|
type PongoCollectionSQLBuilder = {
|
|
@@ -92,4 +93,4 @@ declare const pongoSession: (options?: PongoSessionOptions) => PongoSession;
|
|
|
92
93
|
|
|
93
94
|
declare const pongoTransaction: (options: PongoTransactionOptions) => PongoDbTransaction;
|
|
94
95
|
|
|
95
|
-
export { ConcurrencyError, DeleteOneOptions, type NonPartial, OperatorMap, OptionalUnlessRequiredIdAndVersion, PongoCollection, type PongoCollectionOptions, type PongoCollectionSQLBuilder, PongoDb, PongoDbTransaction, PongoDocument, PongoError, PongoFilter, PongoSession, type PongoSessionOptions, PongoTransactionOptions, PongoUpdate, QueryOperators, ReplaceOneOptions, UpdateOneOptions, WithoutId, hasOperators, isNumber, isOperator, isString, objectEntries, pongoCollection, pongoCollectionPostgreSQLMigrations, pongoCollectionSchemaComponent, pongoSession, pongoTransaction, postgresSQLBuilder };
|
|
96
|
+
export { CollectionOperationOptions, ConcurrencyError, DeleteOneOptions, type NonPartial, OperatorMap, OptionalUnlessRequiredIdAndVersion, PongoCollection, type PongoCollectionOptions, type PongoCollectionSQLBuilder, PongoDb, PongoDbTransaction, PongoDocument, PongoError, PongoFilter, PongoSession, type PongoSessionOptions, PongoTransactionOptions, PongoUpdate, QueryOperators, ReplaceOneOptions, UpdateOneOptions, WithoutId, hasOperators, isNumber, isOperator, isString, objectEntries, pongoCollection, pongoCollectionPostgreSQLMigrations, pongoCollectionSchemaComponent, pongoSession, pongoTransaction, postgresSQLBuilder, transactionExecutorOrDefault };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { Dumbo, MigrationStyle, SchemaComponent, SQLMigration, SQL } from '@event-driven-io/dumbo';
|
|
2
|
-
import { P as PongoDb, a as PongoDocument, b as PongoCollection, O as OptionalUnlessRequiredIdAndVersion, c as PongoFilter, d as PongoUpdate, U as UpdateOneOptions, W as WithoutId, R as ReplaceOneOptions, D as DeleteOneOptions, e as PongoTransactionOptions, f as PongoSession, g as PongoDbTransaction } from './pongoClient-
|
|
3
|
-
export { ad as $inc, ae as $push, ab as $set, ac as $unset, A as AllowedDbClientOptions, a7 as AlternativeType,
|
|
1
|
+
import { Dumbo, MigrationStyle, SQLExecutor, SchemaComponent, SQLMigration, SQL } from '@event-driven-io/dumbo';
|
|
2
|
+
import { P as PongoDb, C as CollectionOperationOptions, a as PongoDocument, b as PongoCollection, O as OptionalUnlessRequiredIdAndVersion, c as PongoFilter, d as PongoUpdate, U as UpdateOneOptions, W as WithoutId, R as ReplaceOneOptions, D as DeleteOneOptions, e as PongoTransactionOptions, f as PongoSession, g as PongoDbTransaction } from './pongoClient-CjXGu-SC.js';
|
|
3
|
+
export { ad as $inc, ae as $push, ab as $set, ac as $unset, A as AllowedDbClientOptions, a7 as AlternativeType, q as CollectionsMap, a8 as Condition, s as DBsMap, aj as DOCUMENT_DOES_NOT_EXIST, ai as DOCUMENT_EXISTS, L as DeleteManyOptions, a2 as Document, ax as DocumentHandler, T as EnhancedOmit, ah as ExpectedDocumentVersion, af as ExpectedDocumentVersionGeneral, ag as ExpectedDocumentVersionValue, K as HandleOptions, Q as HasId, S as InferIdType, H as InsertManyOptions, I as InsertOneOptions, ak as NO_CONCURRENCY_CHECK, a6 as NonObjectIdLikeDocument, N as NotPooledPongoOptions, M as ObjectId, a5 as ObjectIdLike, ao as OperationResult, a3 as OptionalId, V as OptionalUnlessRequiredId, X as OptionalUnlessRequiredVersion, a4 as OptionalVersion, G as PongoClient, i as PongoClientOptions, o as PongoClientSchema, z as PongoClientSchemaMetadata, t as PongoClientWithSchema, m as PongoCollectionSchema, x as PongoCollectionSchemaMetadata, k as PongoDbClientOptions, n as PongoDbSchema, y as PongoDbSchemaMetadata, r as PongoDbWithSchema, av as PongoDeleteManyResult, au as PongoDeleteResult, aa as PongoFilterOperator, aw as PongoHandleResult, ar as PongoInsertManyResult, aq as PongoInsertOneResult, F as PongoSchemaConfig, at as PongoUpdateManyResult, as as PongoUpdateResult, h as PooledPongoClientOptions, ay as PostgresDbClientOptions, a1 as RegExpOrString, a9 as RootFilterOperators, J as UpdateManyOptions, Y as WithId, $ as WithIdAndVersion, Z as WithVersion, a0 as WithoutIdAndVersion, _ as WithoutVersion, j as clientToDbOptions, an as expectedVersion, am as expectedVersionValue, l as getPongoDb, al as isGeneralExpectedDocumentVersion, az as isPostgresClientOptions, ap as operationResult, p as pongoClient, aB as pongoDbSchemaComponent, u as pongoSchema, aA as postgresDb, w as proxyClientWithSchema, v as proxyPongoDbWithSchema, E as toClientSchemaMetadata, B as toDbSchemaMetadata } from './pongoClient-CjXGu-SC.js';
|
|
4
4
|
import 'pg';
|
|
5
5
|
|
|
6
6
|
type PongoCollectionOptions<ConnectorType extends string = string> = {
|
|
@@ -15,6 +15,7 @@ type PongoCollectionOptions<ConnectorType extends string = string> = {
|
|
|
15
15
|
throwOnOperationFailures?: boolean;
|
|
16
16
|
};
|
|
17
17
|
};
|
|
18
|
+
declare const transactionExecutorOrDefault: <ConnectorType extends string = string>(db: PongoDb<ConnectorType>, options: CollectionOperationOptions | undefined, defaultSqlExecutor: SQLExecutor) => Promise<SQLExecutor>;
|
|
18
19
|
declare const pongoCollection: <T extends PongoDocument, ConnectorType extends string = string>({ db, collectionName, pool, sqlBuilder: SqlFor, schema, errors, }: PongoCollectionOptions<ConnectorType>) => PongoCollection<T>;
|
|
19
20
|
declare const pongoCollectionSchemaComponent: (collectionName: string) => SchemaComponent;
|
|
20
21
|
type PongoCollectionSQLBuilder = {
|
|
@@ -92,4 +93,4 @@ declare const pongoSession: (options?: PongoSessionOptions) => PongoSession;
|
|
|
92
93
|
|
|
93
94
|
declare const pongoTransaction: (options: PongoTransactionOptions) => PongoDbTransaction;
|
|
94
95
|
|
|
95
|
-
export { ConcurrencyError, DeleteOneOptions, type NonPartial, OperatorMap, OptionalUnlessRequiredIdAndVersion, PongoCollection, type PongoCollectionOptions, type PongoCollectionSQLBuilder, PongoDb, PongoDbTransaction, PongoDocument, PongoError, PongoFilter, PongoSession, type PongoSessionOptions, PongoTransactionOptions, PongoUpdate, QueryOperators, ReplaceOneOptions, UpdateOneOptions, WithoutId, hasOperators, isNumber, isOperator, isString, objectEntries, pongoCollection, pongoCollectionPostgreSQLMigrations, pongoCollectionSchemaComponent, pongoSession, pongoTransaction, postgresSQLBuilder };
|
|
96
|
+
export { CollectionOperationOptions, ConcurrencyError, DeleteOneOptions, type NonPartial, OperatorMap, OptionalUnlessRequiredIdAndVersion, PongoCollection, type PongoCollectionOptions, type PongoCollectionSQLBuilder, PongoDb, PongoDbTransaction, PongoDocument, PongoError, PongoFilter, PongoSession, type PongoSessionOptions, PongoTransactionOptions, PongoUpdate, QueryOperators, ReplaceOneOptions, UpdateOneOptions, WithoutId, hasOperators, isNumber, isOperator, isString, objectEntries, pongoCollection, pongoCollectionPostgreSQLMigrations, pongoCollectionSchemaComponent, pongoSession, pongoTransaction, postgresSQLBuilder, transactionExecutorOrDefault };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{A,B,C,D,E,F,G,a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d,m as g,n as h,o as i,p as j,q as k,r as l,s as n,t as q,u as s,v as u,w as v,x as w,y,z}from"./chunk-
|
|
1
|
+
import{A,B,C,D,E,F,G,H,a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d,m as g,n as h,o as i,p as j,q as k,r as l,s as n,t as q,u as s,v as u,w as v,x as w,y,z}from"./chunk-CRUPVSHS.js";export{j as ConcurrencyError,u as DOCUMENT_DOES_NOT_EXIST,s as DOCUMENT_EXISTS,v as NO_CONCURRENCY_CHECK,b as OperatorMap,i as PongoError,a as QueryOperators,H as clientToDbOptions,z as expectedVersion,y as expectedVersionValue,k as getPongoDb,d as hasOperators,w as isGeneralExpectedDocumentVersion,g as isNumber,c as isOperator,e as isPostgresClientOptions,h as isString,q as objectEntries,A as operationResult,G as pongoClient,t as pongoCollection,o as pongoCollectionPostgreSQLMigrations,x as pongoCollectionSchemaComponent,m as pongoDbSchemaComponent,B as pongoSchema,n as pongoSession,l as pongoTransaction,f as postgresDb,r as postgresSQLBuilder,D as proxyClientWithSchema,C as proxyPongoDbWithSchema,F as toClientSchemaMetadata,E as toDbSchemaMetadata,p as transactionExecutorOrDefault};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DatabaseTransaction, SQLExecutor, DatabaseTransactionFactory, SchemaComponent,
|
|
1
|
+
import { DatabaseTransaction, SQLExecutor, DatabaseTransactionFactory, SchemaComponent, QueryResultRow, SQL, QueryResult, PostgresConnector, NodePostgresConnection, MigrationStyle } from '@event-driven-io/dumbo';
|
|
2
2
|
import pg from 'pg';
|
|
3
3
|
|
|
4
4
|
interface PongoClient {
|
|
@@ -43,10 +43,15 @@ interface PongoDb<ConnectorType extends string = string> extends DatabaseTransac
|
|
|
43
43
|
connect(): Promise<void>;
|
|
44
44
|
close(): Promise<void>;
|
|
45
45
|
collection<T extends PongoDocument>(name: string): PongoCollection<T>;
|
|
46
|
+
collections(): ReadonlyArray<PongoCollection<PongoDocument>>;
|
|
46
47
|
readonly schema: Readonly<{
|
|
47
48
|
component: SchemaComponent;
|
|
48
49
|
migrate(): Promise<void>;
|
|
49
50
|
}>;
|
|
51
|
+
sql: {
|
|
52
|
+
query<Result extends QueryResultRow = QueryResultRow>(sql: SQL, options?: CollectionOperationOptions): Promise<Result[]>;
|
|
53
|
+
command<Result extends QueryResultRow = QueryResultRow>(sql: SQL, options?: CollectionOperationOptions): Promise<QueryResult<Result>>;
|
|
54
|
+
};
|
|
50
55
|
}
|
|
51
56
|
type CollectionOperationOptions = {
|
|
52
57
|
session?: PongoSession;
|
|
@@ -349,4 +354,4 @@ declare const clientToDbOptions: <DbClientOptions extends AllowedDbClientOptions
|
|
|
349
354
|
clientOptions: PongoClientOptions;
|
|
350
355
|
}) => DbClientOptions;
|
|
351
356
|
|
|
352
|
-
export { type WithIdAndVersion as $, type AllowedDbClientOptions as A,
|
|
357
|
+
export { type WithIdAndVersion as $, type AllowedDbClientOptions as A, toDbSchemaMetadata as B, type CollectionOperationOptions as C, type DeleteOneOptions as D, toClientSchemaMetadata as E, type PongoSchemaConfig as F, type PongoClient as G, type InsertManyOptions as H, type InsertOneOptions as I, type UpdateManyOptions as J, type HandleOptions as K, type DeleteManyOptions as L, type ObjectId as M, type NotPooledPongoOptions as N, type OptionalUnlessRequiredIdAndVersion as O, type PongoDb as P, type HasId as Q, type ReplaceOneOptions as R, type InferIdType as S, type EnhancedOmit as T, type UpdateOneOptions as U, type OptionalUnlessRequiredId as V, type WithoutId as W, type OptionalUnlessRequiredVersion as X, type WithId as Y, type WithVersion as Z, type WithoutVersion as _, type PongoDocument as a, type WithoutIdAndVersion as a0, type RegExpOrString as a1, type Document as a2, type OptionalId as a3, type OptionalVersion as a4, type ObjectIdLike as a5, type NonObjectIdLikeDocument as a6, type AlternativeType as a7, type Condition as a8, type RootFilterOperators as a9, postgresDb as aA, pongoDbSchemaComponent as aB, type PongoFilterOperator as aa, type $set as ab, type $unset as ac, type $inc as ad, type $push as ae, type ExpectedDocumentVersionGeneral as af, type ExpectedDocumentVersionValue as ag, type ExpectedDocumentVersion as ah, DOCUMENT_EXISTS as ai, DOCUMENT_DOES_NOT_EXIST as aj, NO_CONCURRENCY_CHECK as ak, isGeneralExpectedDocumentVersion as al, expectedVersionValue as am, expectedVersion as an, type OperationResult as ao, operationResult as ap, type PongoInsertOneResult as aq, type PongoInsertManyResult as ar, type PongoUpdateResult as as, type PongoUpdateManyResult as at, type PongoDeleteResult as au, type PongoDeleteManyResult as av, type PongoHandleResult as aw, type DocumentHandler as ax, type PostgresDbClientOptions as ay, isPostgresClientOptions as az, type PongoCollection as b, type PongoFilter as c, type PongoUpdate as d, type PongoTransactionOptions as e, type PongoSession as f, type PongoDbTransaction as g, type PooledPongoClientOptions as h, type PongoClientOptions as i, clientToDbOptions as j, type PongoDbClientOptions as k, getPongoDb as l, type PongoCollectionSchema as m, type PongoDbSchema as n, type PongoClientSchema as o, pongoClient as p, type CollectionsMap as q, type PongoDbWithSchema as r, type DBsMap as s, type PongoClientWithSchema as t, pongoSchema as u, proxyPongoDbWithSchema as v, proxyClientWithSchema as w, type PongoCollectionSchemaMetadata as x, type PongoDbSchemaMetadata as y, type PongoClientSchemaMetadata as z };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DatabaseTransaction, SQLExecutor, DatabaseTransactionFactory, SchemaComponent,
|
|
1
|
+
import { DatabaseTransaction, SQLExecutor, DatabaseTransactionFactory, SchemaComponent, QueryResultRow, SQL, QueryResult, PostgresConnector, NodePostgresConnection, MigrationStyle } from '@event-driven-io/dumbo';
|
|
2
2
|
import pg from 'pg';
|
|
3
3
|
|
|
4
4
|
interface PongoClient {
|
|
@@ -43,10 +43,15 @@ interface PongoDb<ConnectorType extends string = string> extends DatabaseTransac
|
|
|
43
43
|
connect(): Promise<void>;
|
|
44
44
|
close(): Promise<void>;
|
|
45
45
|
collection<T extends PongoDocument>(name: string): PongoCollection<T>;
|
|
46
|
+
collections(): ReadonlyArray<PongoCollection<PongoDocument>>;
|
|
46
47
|
readonly schema: Readonly<{
|
|
47
48
|
component: SchemaComponent;
|
|
48
49
|
migrate(): Promise<void>;
|
|
49
50
|
}>;
|
|
51
|
+
sql: {
|
|
52
|
+
query<Result extends QueryResultRow = QueryResultRow>(sql: SQL, options?: CollectionOperationOptions): Promise<Result[]>;
|
|
53
|
+
command<Result extends QueryResultRow = QueryResultRow>(sql: SQL, options?: CollectionOperationOptions): Promise<QueryResult<Result>>;
|
|
54
|
+
};
|
|
50
55
|
}
|
|
51
56
|
type CollectionOperationOptions = {
|
|
52
57
|
session?: PongoSession;
|
|
@@ -349,4 +354,4 @@ declare const clientToDbOptions: <DbClientOptions extends AllowedDbClientOptions
|
|
|
349
354
|
clientOptions: PongoClientOptions;
|
|
350
355
|
}) => DbClientOptions;
|
|
351
356
|
|
|
352
|
-
export { type WithIdAndVersion as $, type AllowedDbClientOptions as A,
|
|
357
|
+
export { type WithIdAndVersion as $, type AllowedDbClientOptions as A, toDbSchemaMetadata as B, type CollectionOperationOptions as C, type DeleteOneOptions as D, toClientSchemaMetadata as E, type PongoSchemaConfig as F, type PongoClient as G, type InsertManyOptions as H, type InsertOneOptions as I, type UpdateManyOptions as J, type HandleOptions as K, type DeleteManyOptions as L, type ObjectId as M, type NotPooledPongoOptions as N, type OptionalUnlessRequiredIdAndVersion as O, type PongoDb as P, type HasId as Q, type ReplaceOneOptions as R, type InferIdType as S, type EnhancedOmit as T, type UpdateOneOptions as U, type OptionalUnlessRequiredId as V, type WithoutId as W, type OptionalUnlessRequiredVersion as X, type WithId as Y, type WithVersion as Z, type WithoutVersion as _, type PongoDocument as a, type WithoutIdAndVersion as a0, type RegExpOrString as a1, type Document as a2, type OptionalId as a3, type OptionalVersion as a4, type ObjectIdLike as a5, type NonObjectIdLikeDocument as a6, type AlternativeType as a7, type Condition as a8, type RootFilterOperators as a9, postgresDb as aA, pongoDbSchemaComponent as aB, type PongoFilterOperator as aa, type $set as ab, type $unset as ac, type $inc as ad, type $push as ae, type ExpectedDocumentVersionGeneral as af, type ExpectedDocumentVersionValue as ag, type ExpectedDocumentVersion as ah, DOCUMENT_EXISTS as ai, DOCUMENT_DOES_NOT_EXIST as aj, NO_CONCURRENCY_CHECK as ak, isGeneralExpectedDocumentVersion as al, expectedVersionValue as am, expectedVersion as an, type OperationResult as ao, operationResult as ap, type PongoInsertOneResult as aq, type PongoInsertManyResult as ar, type PongoUpdateResult as as, type PongoUpdateManyResult as at, type PongoDeleteResult as au, type PongoDeleteManyResult as av, type PongoHandleResult as aw, type DocumentHandler as ax, type PostgresDbClientOptions as ay, isPostgresClientOptions as az, type PongoCollection as b, type PongoFilter as c, type PongoUpdate as d, type PongoTransactionOptions as e, type PongoSession as f, type PongoDbTransaction as g, type PooledPongoClientOptions as h, type PongoClientOptions as i, clientToDbOptions as j, type PongoDbClientOptions as k, getPongoDb as l, type PongoCollectionSchema as m, type PongoDbSchema as n, type PongoClientSchema as o, pongoClient as p, type CollectionsMap as q, type PongoDbWithSchema as r, type DBsMap as s, type PongoClientWithSchema as t, pongoSchema as u, proxyPongoDbWithSchema as v, proxyClientWithSchema as w, type PongoCollectionSchemaMetadata as x, type PongoDbSchemaMetadata as y, type PongoClientSchemaMetadata as z };
|
package/dist/shim.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return 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; } var _class;var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return 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; } var _class;var _chunkBDSCD6MHcjs = require('./chunk-BDSCD6MH.cjs');var s= (_class =class{__init() {this.documents=null}__init2() {this.index=0}constructor(e){;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);this.findDocumentsPromise=e}async toArray(){return this.findDocuments()}async forEach(e){let n=await this.findDocuments();for(let t of n)e(t);return Promise.resolve()}hasNext(){if(this.documents===null)throw Error("Error while fetching documents");return this.index<this.documents.length}async next(){let e=await this.findDocuments();return this.hasNext()?_nullishCoalesce(e[this.index++], () => (null)):null}async findDocuments(){return this.documents=await this.findDocumentsPromise,this.documents}}, _class);require('mongodb');var o=r=>_optionalChain([r, 'optionalAccess', _ => _.session])?{session:r.session}:void 0,d= exports.Collection =class{constructor(e){this.collection=e}get dbName(){return this.collection.dbName}get collectionName(){return this.collection.collectionName}get namespace(){return`${this.dbName}.${this.collectionName}`}get readConcern(){}get readPreference(){}get bsonOptions(){return{}}get writeConcern(){}get hint(){}set hint(e){throw new Error("Method not implemented.")}async insertOne(e,n){let t=await this.collection.insertOne(e,o(n));return{acknowledged:t.acknowledged,insertedId:t.insertedId}}async insertMany(e,n){let t=await this.collection.insertMany(e,o(n));return{acknowledged:t.acknowledged,insertedIds:t.insertedIds,insertedCount:t.insertedCount}}bulkWrite(e,n){throw new Error("Method not implemented.")}async updateOne(e,n,t){let i=await this.collection.updateOne(e,n,o(t));return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}replaceOne(e,n,t){return this.collection.replaceOne(e,n,o(t))}async updateMany(e,n,t){let i=await this.collection.updateMany(e,n,o(t));return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}async deleteOne(e,n){let t=await this.collection.deleteOne(e,o(n));return{acknowledged:t.acknowledged,deletedCount:t.deletedCount}}async deleteMany(e,n){let t=await this.collection.deleteMany(e,o(n));return{acknowledged:t.acknowledged,deletedCount:t.deletedCount}}async rename(e,n){return await this.collection.rename(e,o(n)),this}drop(e){return this.collection.drop(o(e))}async findOne(e,n){return await this.collection.findOne(e,o(n))}find(e,n){return new s(this.collection.find(e,o(n)))}options(e){throw new Error("Method not implemented.")}isCapped(e){throw new Error("Method not implemented.")}createIndex(e,n){throw new Error("Method not implemented.")}createIndexes(e,n){throw new Error("Method not implemented.")}dropIndex(e,n){throw new Error("Method not implemented.")}dropIndexes(e){throw new Error("Method not implemented.")}listIndexes(e){throw new Error("Method not implemented.")}indexExists(e,n){throw new Error("Method not implemented.")}indexInformation(e){throw new Error("Method not implemented.")}estimatedDocumentCount(e){return this.collection.countDocuments({},o(e))}countDocuments(e,n){return this.collection.countDocuments(e,o(n))}distinct(e,n,t){throw new Error("Method not implemented.")}indexes(e){throw new Error("Method not implemented.")}findOneAndDelete(e,n){return this.collection.findOneAndDelete(e,o(n))}findOneAndReplace(e,n,t){return this.collection.findOneAndReplace(e,n,o(t))}findOneAndUpdate(e,n,t){return this.collection.findOneAndUpdate(e,n,o(t))}aggregate(e,n){throw new Error("Method not implemented.")}watch(e,n){throw new Error("Method not implemented.")}initializeUnorderedBulkOp(e){throw new Error("Method not implemented.")}initializeOrderedBulkOp(e){throw new Error("Method not implemented.")}count(e,n){return this.collection.countDocuments(_nullishCoalesce(e, () => ({})),o(n))}listSearchIndexes(e,n){throw new Error("Method not implemented.")}createSearchIndex(e){throw new Error("Method not implemented.")}createSearchIndexes(e){throw new Error("Method not implemented.")}dropSearchIndex(e){throw new Error("Method not implemented.")}updateSearchIndex(e,n){throw new Error("Method not implemented.")}async createCollection(){await this.collection.createCollection()}async handle(e,n,t){return this.collection.handle(e.toString(),n,t)}};var l=class{constructor(e){this.pongoDb=e}get databaseName(){return this.pongoDb.databaseName}collection(e){return new d(this.pongoDb.collection(e))}};var u=class{constructor(e,n={}){this.pongoClient=_chunkBDSCD6MHcjs.G.call(void 0, e,n)}async connect(){return await this.pongoClient.connect(),this}async close(){await this.pongoClient.close()}db(e){return new l(this.pongoClient.db(e))}startSession(e){return _chunkBDSCD6MHcjs.s.call(void 0, )}async withSession(e,n){let t=typeof e=="function"?e:n,i=_chunkBDSCD6MHcjs.s.call(void 0, );try{return await t(i)}finally{await i.endSession()}}};exports.Collection = d; exports.Db = l; exports.FindCursor = s; exports.MongoClient = u;
|
|
2
2
|
//# sourceMappingURL=shim.cjs.map
|
package/dist/shim.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ClientSessionOptions } from 'http2';
|
|
2
2
|
import { Document, Collection as Collection$1, ObjectId, ClientSession, WithSessionCallback, ReadConcern, ReadPreference, BSONSerializeOptions, WriteConcern, Hint, OptionalUnlessRequiredId, InsertOneOptions, InsertOneResult, BulkWriteOptions, InsertManyResult, AnyBulkWriteOperation, BulkWriteResult, Filter, UpdateFilter, UpdateOptions, UpdateResult, WithoutId, ReplaceOptions, DeleteOptions, DeleteResult, RenameOptions, DropCollectionOptions, WithId, FindOptions, FindCursor as FindCursor$1, OperationOptions, IndexSpecification, CreateIndexesOptions, IndexDescription, CommandOperationOptions, AbstractCursorOptions, ListIndexesCursor, IndexInformationOptions, IndexDescriptionInfo, IndexDescriptionCompact, EstimatedDocumentCountOptions, CountDocumentsOptions, EnhancedOmit, Flatten, FindOneAndDeleteOptions, ModifyResult, FindOneAndReplaceOptions, FindOneAndUpdateOptions, AggregateOptions, AggregationCursor, ChangeStreamDocument, ChangeStreamOptions, ChangeStream, UnorderedBulkOperation, OrderedBulkOperation, CountOptions, ListSearchIndexesOptions, ListSearchIndexesCursor, SearchIndexDescription } from 'mongodb';
|
|
3
|
-
import { P as PongoDb, ax as DocumentHandler, K as HandleOptions, aw as PongoHandleResult, i as PongoClientOptions, b as PongoCollection } from './pongoClient-
|
|
3
|
+
import { P as PongoDb, ax as DocumentHandler, K as HandleOptions, aw as PongoHandleResult, i as PongoClientOptions, b as PongoCollection } from './pongoClient-CjXGu-SC.cjs';
|
|
4
4
|
import '@event-driven-io/dumbo';
|
|
5
5
|
import 'pg';
|
|
6
6
|
|
package/dist/shim.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ClientSessionOptions } from 'http2';
|
|
2
2
|
import { Document, Collection as Collection$1, ObjectId, ClientSession, WithSessionCallback, ReadConcern, ReadPreference, BSONSerializeOptions, WriteConcern, Hint, OptionalUnlessRequiredId, InsertOneOptions, InsertOneResult, BulkWriteOptions, InsertManyResult, AnyBulkWriteOperation, BulkWriteResult, Filter, UpdateFilter, UpdateOptions, UpdateResult, WithoutId, ReplaceOptions, DeleteOptions, DeleteResult, RenameOptions, DropCollectionOptions, WithId, FindOptions, FindCursor as FindCursor$1, OperationOptions, IndexSpecification, CreateIndexesOptions, IndexDescription, CommandOperationOptions, AbstractCursorOptions, ListIndexesCursor, IndexInformationOptions, IndexDescriptionInfo, IndexDescriptionCompact, EstimatedDocumentCountOptions, CountDocumentsOptions, EnhancedOmit, Flatten, FindOneAndDeleteOptions, ModifyResult, FindOneAndReplaceOptions, FindOneAndUpdateOptions, AggregateOptions, AggregationCursor, ChangeStreamDocument, ChangeStreamOptions, ChangeStream, UnorderedBulkOperation, OrderedBulkOperation, CountOptions, ListSearchIndexesOptions, ListSearchIndexesCursor, SearchIndexDescription } from 'mongodb';
|
|
3
|
-
import { P as PongoDb, ax as DocumentHandler, K as HandleOptions, aw as PongoHandleResult, i as PongoClientOptions, b as PongoCollection } from './pongoClient-
|
|
3
|
+
import { P as PongoDb, ax as DocumentHandler, K as HandleOptions, aw as PongoHandleResult, i as PongoClientOptions, b as PongoCollection } from './pongoClient-CjXGu-SC.js';
|
|
4
4
|
import '@event-driven-io/dumbo';
|
|
5
5
|
import 'pg';
|
|
6
6
|
|
package/dist/shim.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{G as p,s as a}from"./chunk-CRUPVSHS.js";var s=class{findDocumentsPromise;documents=null;index=0;constructor(e){this.findDocumentsPromise=e}async toArray(){return this.findDocuments()}async forEach(e){let n=await this.findDocuments();for(let t of n)e(t);return Promise.resolve()}hasNext(){if(this.documents===null)throw Error("Error while fetching documents");return this.index<this.documents.length}async next(){let e=await this.findDocuments();return this.hasNext()?e[this.index++]??null:null}async findDocuments(){return this.documents=await this.findDocumentsPromise,this.documents}};import"mongodb";var o=r=>r?.session?{session:r.session}:void 0,d=class{collection;constructor(e){this.collection=e}get dbName(){return this.collection.dbName}get collectionName(){return this.collection.collectionName}get namespace(){return`${this.dbName}.${this.collectionName}`}get readConcern(){}get readPreference(){}get bsonOptions(){return{}}get writeConcern(){}get hint(){}set hint(e){throw new Error("Method not implemented.")}async insertOne(e,n){let t=await this.collection.insertOne(e,o(n));return{acknowledged:t.acknowledged,insertedId:t.insertedId}}async insertMany(e,n){let t=await this.collection.insertMany(e,o(n));return{acknowledged:t.acknowledged,insertedIds:t.insertedIds,insertedCount:t.insertedCount}}bulkWrite(e,n){throw new Error("Method not implemented.")}async updateOne(e,n,t){let i=await this.collection.updateOne(e,n,o(t));return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}replaceOne(e,n,t){return this.collection.replaceOne(e,n,o(t))}async updateMany(e,n,t){let i=await this.collection.updateMany(e,n,o(t));return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}async deleteOne(e,n){let t=await this.collection.deleteOne(e,o(n));return{acknowledged:t.acknowledged,deletedCount:t.deletedCount}}async deleteMany(e,n){let t=await this.collection.deleteMany(e,o(n));return{acknowledged:t.acknowledged,deletedCount:t.deletedCount}}async rename(e,n){return await this.collection.rename(e,o(n)),this}drop(e){return this.collection.drop(o(e))}async findOne(e,n){return await this.collection.findOne(e,o(n))}find(e,n){return new s(this.collection.find(e,o(n)))}options(e){throw new Error("Method not implemented.")}isCapped(e){throw new Error("Method not implemented.")}createIndex(e,n){throw new Error("Method not implemented.")}createIndexes(e,n){throw new Error("Method not implemented.")}dropIndex(e,n){throw new Error("Method not implemented.")}dropIndexes(e){throw new Error("Method not implemented.")}listIndexes(e){throw new Error("Method not implemented.")}indexExists(e,n){throw new Error("Method not implemented.")}indexInformation(e){throw new Error("Method not implemented.")}estimatedDocumentCount(e){return this.collection.countDocuments({},o(e))}countDocuments(e,n){return this.collection.countDocuments(e,o(n))}distinct(e,n,t){throw new Error("Method not implemented.")}indexes(e){throw new Error("Method not implemented.")}findOneAndDelete(e,n){return this.collection.findOneAndDelete(e,o(n))}findOneAndReplace(e,n,t){return this.collection.findOneAndReplace(e,n,o(t))}findOneAndUpdate(e,n,t){return this.collection.findOneAndUpdate(e,n,o(t))}aggregate(e,n){throw new Error("Method not implemented.")}watch(e,n){throw new Error("Method not implemented.")}initializeUnorderedBulkOp(e){throw new Error("Method not implemented.")}initializeOrderedBulkOp(e){throw new Error("Method not implemented.")}count(e,n){return this.collection.countDocuments(e??{},o(n))}listSearchIndexes(e,n){throw new Error("Method not implemented.")}createSearchIndex(e){throw new Error("Method not implemented.")}createSearchIndexes(e){throw new Error("Method not implemented.")}dropSearchIndex(e){throw new Error("Method not implemented.")}updateSearchIndex(e,n){throw new Error("Method not implemented.")}async createCollection(){await this.collection.createCollection()}async handle(e,n,t){return this.collection.handle(e.toString(),n,t)}};var l=class{constructor(e){this.pongoDb=e}get databaseName(){return this.pongoDb.databaseName}collection(e){return new d(this.pongoDb.collection(e))}};var u=class{pongoClient;constructor(e,n={}){this.pongoClient=p(e,n)}async connect(){return await this.pongoClient.connect(),this}async close(){await this.pongoClient.close()}db(e){return new l(this.pongoClient.db(e))}startSession(e){return a()}async withSession(e,n){let t=typeof e=="function"?e:n,i=a();try{return await t(i)}finally{await i.endSession()}}};export{d as Collection,l as Db,s as FindCursor,u as MongoClient};
|
|
2
2
|
//# sourceMappingURL=shim.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@event-driven-io/pongo",
|
|
3
|
-
"version": "0.16.0-alpha.
|
|
3
|
+
"version": "0.16.0-alpha.8",
|
|
4
4
|
"description": "Pongo - Mongo with strong consistency on top of Postgres",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"scripts": {
|
|
@@ -87,7 +87,7 @@
|
|
|
87
87
|
"pongo": "./dist/cli.js"
|
|
88
88
|
},
|
|
89
89
|
"peerDependencies": {
|
|
90
|
-
"@event-driven-io/dumbo": "0.12.0-alpha.
|
|
90
|
+
"@event-driven-io/dumbo": "0.12.0-alpha.8",
|
|
91
91
|
"@types/mongodb": "^4.0.7",
|
|
92
92
|
"@types/pg": "^8.11.6",
|
|
93
93
|
"@types/uuid": "^10.0.0",
|