@event-driven-io/pongo 0.16.0-alpha.5 → 0.16.0-alpha.7
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/cli.cjs +1 -1
- package/dist/cli.js +3 -3
- package/dist/cli.js.map +1 -1
- package/package.json +2 -2
package/dist/cli.cjs
CHANGED
|
@@ -23,5 +23,5 @@ ${s()}`,O=`Error: Database should have defined at least one collection, e.g.
|
|
|
23
23
|
|
|
24
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=_chunkP5Y6AANFcjs.s.call(void 0, o.default.schema.dbs).map(r=>r[1]).find(r=>r.name===void 0);return t?!t.collections||_chunkP5Y6AANFcjs.s.call(void 0, t.collections).map(r=>r[1]).length===0?O:_chunkP5Y6AANFcjs.D.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=>_chunkP5Y6AANFcjs.g.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=>_chunkP5Y6AANFcjs.g.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,
|
|
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=>_chunkP5Y6AANFcjs.g.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=>_chunkP5Y6AANFcjs.g.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.7)"));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]=_chunkP5Y6AANFcjs.A.collection(c);let u=_chunkP5Y6AANFcjs.A.client({database:_chunkP5Y6AANFcjs.A.db(o.schema.database,a)}),l=_chunkP5Y6AANFcjs.F.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=_chunkP5Y6AANFcjs.F.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{A as p,D as P,F as b,g as S,s as y}from"./chunk-S6SSZQB7.js";import{Command as Z}from"commander";import{Command as
|
|
2
|
+
import{A as p,D as P,F as b,g as S,s as y}from"./chunk-S6SSZQB7.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.7)"));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.5)'));\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: { definition: schema },\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 noAutoMigrations: 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, --no-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.noAutoMigrations ? 'None' : '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,GAG5BA,CACT,EAEMC,EAAe,CAACC,EAA4B,CAAC,OAAO,IAAM,CAC9D,IAAMC,EAAQD,EACX,IACEE,GACC,QAAQN,EAAeM,CAAI,CAAC,sDAChC,EACC,KAAK;AAAA,CAAI,EAENC,EAAcH,EACjB,IACEE,GACC,SAASA,CAAI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OAAS,gBACrD,EACA,iBAAAC,CACF,CAAC,CACH,CAAC,EH7QH,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.7)'));\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,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,EAE7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AAOlB,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/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.7",
|
|
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.7",
|
|
91
91
|
"@types/mongodb": "^4.0.7",
|
|
92
92
|
"@types/pg": "^8.11.6",
|
|
93
93
|
"@types/uuid": "^10.0.0",
|