@event-driven-io/pongo 0.17.0-beta.39 → 0.17.0-beta.40
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 +2 -2
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +2 -2
- package/dist/cli.js.map +1 -1
- package/dist/cloudflare.cjs +2 -2
- package/dist/cloudflare.d.cts +2 -2
- package/dist/cloudflare.d.ts +2 -2
- package/dist/cloudflare.js +2 -2
- package/dist/{core-Dtn-d-91.js → core-BHdOCUrr.js} +111 -3
- package/dist/core-BHdOCUrr.js.map +1 -0
- package/dist/{core-BdTIuXiI.cjs → core-C9SB3XMx.cjs} +116 -2
- package/dist/core-C9SB3XMx.cjs.map +1 -0
- package/dist/{core-wHw_lMM5.js → core-CH0SOCr3.js} +65 -11
- package/dist/core-CH0SOCr3.js.map +1 -0
- package/dist/{core-BYk4wCpe.cjs → core-CkmE5dkK.cjs} +65 -11
- package/dist/core-CkmE5dkK.cjs.map +1 -0
- package/dist/{index-CL0zRxRl.d.ts → index-C3pnS1S_.d.cts} +23 -8
- package/dist/{index-Cxo6j266.d.ts → index-CZOmOsQt.d.ts} +2 -2
- package/dist/{index-DyNmc6tD.d.cts → index-FXnldVnn.d.cts} +2 -2
- package/dist/{index-BfOn92K5.d.cts → index-r7V4paf_.d.ts} +23 -8
- package/dist/index.cjs +2 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/pg.cjs +67 -10
- package/dist/pg.cjs.map +1 -1
- package/dist/pg.d.cts +1 -1
- package/dist/pg.d.ts +1 -1
- package/dist/pg.js +67 -10
- package/dist/pg.js.map +1 -1
- package/dist/shim.cjs +18 -8
- package/dist/shim.cjs.map +1 -1
- package/dist/shim.d.cts +1 -1
- package/dist/shim.d.ts +1 -1
- package/dist/shim.js +18 -8
- package/dist/shim.js.map +1 -1
- package/dist/sqlite3.cjs +2 -2
- package/dist/sqlite3.d.cts +2 -2
- package/dist/sqlite3.d.ts +2 -2
- package/dist/sqlite3.js +2 -2
- package/package.json +2 -2
- package/dist/core-BYk4wCpe.cjs.map +0 -1
- package/dist/core-BdTIuXiI.cjs.map +0 -1
- package/dist/core-Dtn-d-91.js.map +0 -1
- package/dist/core-wHw_lMM5.js.map +0 -1
package/dist/cli.cjs
CHANGED
|
@@ -27,7 +27,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
27
27
|
}) : target, mod));
|
|
28
28
|
|
|
29
29
|
//#endregion
|
|
30
|
-
const require_core = require('./core-
|
|
30
|
+
const require_core = require('./core-C9SB3XMx.cjs');
|
|
31
31
|
let _event_driven_io_dumbo = require("@event-driven-io/dumbo");
|
|
32
32
|
let commander = require("commander");
|
|
33
33
|
let node_fs = require("node:fs");
|
|
@@ -228,7 +228,7 @@ const prettifyLogs = (logLevel) => {
|
|
|
228
228
|
const startRepl = async (options) => {
|
|
229
229
|
setLogLevel(process.env.DUMBO_LOG_LEVEL ?? options.logging.logLevel);
|
|
230
230
|
setLogStyle(process.env.DUMBO_LOG_STYLE ?? options.logging.logStyle);
|
|
231
|
-
console.log(_event_driven_io_dumbo.color.green("Starting Pongo Shell (version: 0.17.0-beta.
|
|
231
|
+
console.log(_event_driven_io_dumbo.color.green("Starting Pongo Shell (version: 0.17.0-beta.40)"));
|
|
232
232
|
if (options.logging.printOptions) {
|
|
233
233
|
console.log(_event_driven_io_dumbo.color.green("With Options:"));
|
|
234
234
|
console.log((0, _event_driven_io_dumbo.prettyJson)(options));
|
package/dist/cli.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.cjs","names":["objectEntries","toDbSchemaMetadata","Command","Command","pongoDriverRegistry","pongoSchema","JSONSerializer","color","Table","LogStyle","pongoDriverRegistry","repl","pongoSchema","pongoClient","SQL","LogLevel","Command","Command"],"sources":["../src/commandLine/configFile.ts","../src/commandLine/migrate.ts","../src/commandLine/shell.ts","../src/cli.ts"],"sourcesContent":["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 `export 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 JSONSerializer,\n parseConnectionString,\n runSQLMigrations,\n type DatabaseDriverType,\n} from '@event-driven-io/dumbo';\nimport { Command } from 'commander';\nimport {\n pongoDriverRegistry,\n pongoSchema,\n type AnyPongoDriverOptions,\n type PongoCollectionSchema,\n type PongoDatabaseFactoryOptions,\n type PongoDocument,\n} from '../core';\nimport { loadConfigFile } from './configFile';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n databaseType?: string;\n databaseName?: string | undefined;\n databaseDriver: string;\n config?: string;\n dryRun?: boolean;\n timeoutMs?: number;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n databaseType: string;\n databaseName?: string | undefined;\n databaseDriver: string;\n config?: 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 '--dbt, --database-type <string>',\n 'Database type that should be used for connection (e.g., PostgreSQL or SQLite)',\n undefined,\n )\n .option(\n '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n )\n .option(\n '--dbn, --database-name <string>',\n 'Database name to connect to',\n undefined,\n )\n .option(\n '--cs, --connection-string <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 .option(\n '--t, --timeout <ms>',\n 'Set the migration timeout in milliseconds',\n parseInt,\n )\n .action(async (options: MigrateRunOptions) => {\n const { collection, dryRun, databaseName, databaseDriver, timeoutMs } =\n options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n\n const databaseType =\n options.databaseType ??\n parseConnectionString(connectionString).databaseType;\n\n let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--connection-string\" parameter or through the DB_CONNECTION_STRING environment variable.' +\n '\\nFor instance: --connection-string postgresql://postgres:postgres@localhost:5432/postgres',\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 driverType = `${databaseType}:${databaseDriver}` as const;\n\n const migrations = getMigrations({\n driverType,\n connectionString,\n databaseName,\n collectionNames,\n });\n\n const pool = dumbo({ connectionString, driverType });\n\n await runSQLMigrations(pool, migrations, {\n dryRun,\n migrationTimeoutMs: timeoutMs,\n });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n .option(\n '--dbt, --database-type <string>',\n 'Database type that should be used for connection (e.g., PostgreSQL or SQLite)',\n )\n .option(\n '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n )\n .option(\n '--dbn, --database-name <string>',\n 'Database name to connect to',\n undefined,\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('--print', 'Print the SQL to the console (default)', true)\n //.option('--write <filename>', 'Write the SQL to a specified file')\n .action(async (options: MigrateSqlOptions) => {\n const { collection, databaseName, databaseType, databaseDriver } = options;\n\n let collectionNames: string[];\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 driverType = `${databaseType}:${databaseDriver}` as const;\n\n const migrations = getMigrations({\n driverType,\n connectionString: undefined,\n databaseName,\n collectionNames,\n });\n\n console.log('Printing SQL:');\n console.log(combineMigrations(...migrations));\n });\n\nconst getMigrations = ({\n driverType,\n connectionString,\n databaseName,\n collectionNames,\n}: {\n driverType: DatabaseDriverType;\n connectionString: string | undefined;\n databaseName: string | undefined;\n collectionNames: string[];\n}) => {\n const driver = pongoDriverRegistry.tryGet(driverType);\n\n if (driver === null) {\n console.error(\n `Error: No database driver found for driver type \"${driverType}\". Make sure the driver is registered and the connection string is correct.`,\n );\n process.exit(1);\n }\n\n const dbDefinition = pongoSchema.db.from(databaseName, collectionNames);\n\n const driverOptions: PongoDatabaseFactoryOptions<\n Record<string, PongoCollectionSchema<PongoDocument>>,\n AnyPongoDriverOptions\n > = {\n schema: { definition: dbDefinition },\n serializer: JSONSerializer,\n };\n\n const customOptions = {\n connectionString,\n databaseName,\n };\n\n const db = driver.databaseFactory({ ...driverOptions, ...customOptions });\n\n return db.schema.component.migrations;\n};\n","import {\n color,\n LogLevel,\n LogStyle,\n parseConnectionString,\n prettyJson,\n SQL,\n type MigrationStyle,\n} from '@event-driven-io/dumbo';\nimport { checkConnection } from '@event-driven-io/dumbo/pg';\nimport Table from 'cli-table3';\nimport { Command } from 'commander';\nimport repl from 'node:repl';\nimport {\n pongoClient,\n pongoDriverRegistry,\n pongoSchema,\n type PongoClient,\n type PongoClientOptions,\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\nlet shouldDisplayResultsAsTable = false;\n\nconst printResultsAsTable = (print?: boolean) =>\n (shouldDisplayResultsAsTable = print === undefined || print === true);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst printOutput = (obj: any): string =>\n Array.isArray(obj) && shouldDisplayResultsAsTable\n ? displayResultsAsTable(obj)\n : prettyJson(obj);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst displayResultsAsTable = (results: any[]): string => {\n if (results.length === 0) {\n return color.yellow('No documents found.');\n }\n\n const columnNames = results\n\n .flatMap((result) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n typeof result === 'object' ? Object.keys(result) : typeof result,\n )\n .filter((value, index, array) => array.indexOf(value) === index);\n\n const columnWidths = calculateColumnWidths(results, columnNames);\n\n const table = new Table({\n head: columnNames.map((col) => color.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\n ? // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n Array.isArray(result[col])\n ? // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n displayResultsAsTable(result[col])\n : // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n prettyJson(result[col])\n : typeof result === 'object'\n ? ''\n : result != undefined && result != undefined\n ? prettyJson(result)\n : '',\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 printOptions: boolean;\n logLevel: LogLevel;\n logStyle: LogStyle;\n };\n schema: {\n database: string;\n collections: string[];\n autoMigration: MigrationStyle;\n };\n connectionString: string | undefined;\n databaseDriver: string;\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(color.green('Starting Pongo Shell (version: 0.17.0-beta.39)'));\n\n if (options.logging.printOptions) {\n console.log(color.green('With Options:'));\n console.log(prettyJson(options));\n }\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 color.yellow(\n `No connection string provided, using: 'postgresql://postgres:postgres@localhost:5432/postgres'`,\n ),\n );\n }\n\n const { databaseType } = parseConnectionString(connectionString);\n const driverType = `${databaseType}:${options.databaseDriver}` as const;\n\n const driver = pongoDriverRegistry.tryGet(driverType);\n\n if (driver === null) {\n console.error(\n `Error: No database driver found for driver type \"${driverType}\". Make sure the driver is installed and the connection string is correct.`,\n );\n process.exit(1);\n }\n\n const connectionCheck = await checkConnection(connectionString);\n\n if (!connectionCheck.successful) {\n if (connectionCheck.errorType === 'ConnectionRefused') {\n console.error(\n color.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 color.red(\n `Authentication failed. Check the username and password in the connection string.`,\n ),\n );\n } else {\n console.error(color.red('Error connecting to PostgreSQL server'));\n }\n console.log(color.red('Exiting Pongo Shell...'));\n process.exit();\n }\n\n console.log(color.green(`Successfully connected`));\n console.log(color.green('Use db.<collection>.<method>() to query.'));\n\n const shell = repl.start({\n prompt: color.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 driverOptions: PongoClientOptions = {\n driver,\n schema: {\n definition: schema,\n autoMigration: options.schema.autoMigration,\n },\n };\n\n // TODO: Find a better way to pass custom driver settings\n const customOptions = {\n connectionString,\n };\n\n const typedClient = pongoClient({\n ...driverOptions,\n ...customOptions,\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 const driverOptions: PongoClientOptions = {\n driver,\n schema: {\n autoMigration: options.schema.autoMigration,\n },\n };\n\n // TODO: Find a better way to pass custom driver settings\n const customOptions = {\n connectionString,\n };\n\n pongo = pongoClient({\n ...driverOptions,\n ...customOptions,\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.printResultsAsTable = printResultsAsTable;\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(color.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 databaseDriver: string;\n connectionString?: string;\n disableAutoMigrations: boolean;\n logStyle?: string;\n logLevel?: string;\n prettyLog?: boolean;\n printOptions?: boolean;\n}\n\nconst shellCommand = new Command('shell')\n .description('Start an interactive Pongo shell')\n .option(\n '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n 'pg',\n )\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('-o, --print-options', 'Print shell options')\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 printOptions: options.printOptions === true,\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 databaseDriver: options.databaseDriver,\n });\n });\n\nexport { shellCommand };\n","#!/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;\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CAAyC,CACpE,OAAO,OAAO,YAA0B;CACvC,MAAM,EAAE,YAAY,aAAa;CACjC,MAAM,mBAAmB,QAAQ;AAEjC,OAAM,UAAU;EACd,SAAS;GACP,cAAc,QAAQ,iBAAiB;GACvC,UAAU,QAAQ,YACdP,gCAAS,SACP,QAAQ,YAAqCA,gCAAS;GAC5D,UAAU,QAAQ,WACb,QAAQ,WACT,QAAQ,YACNM,gCAAS,OACTA,gCAAS;GAChB;EACD,QAAQ;GACN,aAAa;GACb;GACA,eAAe,QAAQ,wBACnB,SACA;GACL;EACD;EACA,gBAAgB,QAAQ;EACzB,CAAC;EACF;;;;ACjWJ,MAAM,UAAU,IAAIE,mBAAS;AAE7B,QAAQ,KAAK,QAAQ,CAAC,YAAY,qBAAqB;AAEvD,QAAQ,WAAW,cAAc;AACjC,QAAQ,WAAW,eAAe;AAClC,QAAQ,WAAW,aAAa;AAEhC,QAAQ,MAAM,QAAQ,KAAK"}
|
|
1
|
+
{"version":3,"file":"cli.cjs","names":["objectEntries","toDbSchemaMetadata","Command","Command","pongoDriverRegistry","pongoSchema","JSONSerializer","color","Table","LogStyle","pongoDriverRegistry","repl","pongoSchema","pongoClient","SQL","LogLevel","Command","Command"],"sources":["../src/commandLine/configFile.ts","../src/commandLine/migrate.ts","../src/commandLine/shell.ts","../src/cli.ts"],"sourcesContent":["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 `export 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 JSONSerializer,\n parseConnectionString,\n runSQLMigrations,\n type DatabaseDriverType,\n} from '@event-driven-io/dumbo';\nimport { Command } from 'commander';\nimport {\n pongoDriverRegistry,\n pongoSchema,\n type AnyPongoDriverOptions,\n type PongoCollectionSchema,\n type PongoDatabaseFactoryOptions,\n type PongoDocument,\n} from '../core';\nimport { loadConfigFile } from './configFile';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n databaseType?: string;\n databaseName?: string | undefined;\n databaseDriver: string;\n config?: string;\n dryRun?: boolean;\n timeoutMs?: number;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n databaseType: string;\n databaseName?: string | undefined;\n databaseDriver: string;\n config?: 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 '--dbt, --database-type <string>',\n 'Database type that should be used for connection (e.g., PostgreSQL or SQLite)',\n undefined,\n )\n .option(\n '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n )\n .option(\n '--dbn, --database-name <string>',\n 'Database name to connect to',\n undefined,\n )\n .option(\n '--cs, --connection-string <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 .option(\n '--t, --timeout <ms>',\n 'Set the migration timeout in milliseconds',\n parseInt,\n )\n .action(async (options: MigrateRunOptions) => {\n const { collection, dryRun, databaseName, databaseDriver, timeoutMs } =\n options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n\n const databaseType =\n options.databaseType ??\n parseConnectionString(connectionString).databaseType;\n\n let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--connection-string\" parameter or through the DB_CONNECTION_STRING environment variable.' +\n '\\nFor instance: --connection-string postgresql://postgres:postgres@localhost:5432/postgres',\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 driverType = `${databaseType}:${databaseDriver}` as const;\n\n const migrations = getMigrations({\n driverType,\n connectionString,\n databaseName,\n collectionNames,\n });\n\n const pool = dumbo({ connectionString, driverType });\n\n await runSQLMigrations(pool, migrations, {\n dryRun,\n migrationTimeoutMs: timeoutMs,\n });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n .option(\n '--dbt, --database-type <string>',\n 'Database type that should be used for connection (e.g., PostgreSQL or SQLite)',\n )\n .option(\n '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n )\n .option(\n '--dbn, --database-name <string>',\n 'Database name to connect to',\n undefined,\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('--print', 'Print the SQL to the console (default)', true)\n //.option('--write <filename>', 'Write the SQL to a specified file')\n .action(async (options: MigrateSqlOptions) => {\n const { collection, databaseName, databaseType, databaseDriver } = options;\n\n let collectionNames: string[];\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 driverType = `${databaseType}:${databaseDriver}` as const;\n\n const migrations = getMigrations({\n driverType,\n connectionString: undefined,\n databaseName,\n collectionNames,\n });\n\n console.log('Printing SQL:');\n console.log(combineMigrations(...migrations));\n });\n\nconst getMigrations = ({\n driverType,\n connectionString,\n databaseName,\n collectionNames,\n}: {\n driverType: DatabaseDriverType;\n connectionString: string | undefined;\n databaseName: string | undefined;\n collectionNames: string[];\n}) => {\n const driver = pongoDriverRegistry.tryGet(driverType);\n\n if (driver === null) {\n console.error(\n `Error: No database driver found for driver type \"${driverType}\". Make sure the driver is registered and the connection string is correct.`,\n );\n process.exit(1);\n }\n\n const dbDefinition = pongoSchema.db.from(databaseName, collectionNames);\n\n const driverOptions: PongoDatabaseFactoryOptions<\n Record<string, PongoCollectionSchema<PongoDocument>>,\n AnyPongoDriverOptions\n > = {\n schema: { definition: dbDefinition },\n serializer: JSONSerializer,\n };\n\n const customOptions = {\n connectionString,\n databaseName,\n };\n\n const db = driver.databaseFactory({ ...driverOptions, ...customOptions });\n\n return db.schema.component.migrations;\n};\n","import {\n color,\n LogLevel,\n LogStyle,\n parseConnectionString,\n prettyJson,\n SQL,\n type MigrationStyle,\n} from '@event-driven-io/dumbo';\nimport { checkConnection } from '@event-driven-io/dumbo/pg';\nimport Table from 'cli-table3';\nimport { Command } from 'commander';\nimport repl from 'node:repl';\nimport {\n pongoClient,\n pongoDriverRegistry,\n pongoSchema,\n type PongoClient,\n type PongoClientOptions,\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\nlet shouldDisplayResultsAsTable = false;\n\nconst printResultsAsTable = (print?: boolean) =>\n (shouldDisplayResultsAsTable = print === undefined || print === true);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst printOutput = (obj: any): string =>\n Array.isArray(obj) && shouldDisplayResultsAsTable\n ? displayResultsAsTable(obj)\n : prettyJson(obj);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst displayResultsAsTable = (results: any[]): string => {\n if (results.length === 0) {\n return color.yellow('No documents found.');\n }\n\n const columnNames = results\n\n .flatMap((result) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n typeof result === 'object' ? Object.keys(result) : typeof result,\n )\n .filter((value, index, array) => array.indexOf(value) === index);\n\n const columnWidths = calculateColumnWidths(results, columnNames);\n\n const table = new Table({\n head: columnNames.map((col) => color.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\n ? // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n Array.isArray(result[col])\n ? // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n displayResultsAsTable(result[col])\n : // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n prettyJson(result[col])\n : typeof result === 'object'\n ? ''\n : result != undefined && result != undefined\n ? prettyJson(result)\n : '',\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 printOptions: boolean;\n logLevel: LogLevel;\n logStyle: LogStyle;\n };\n schema: {\n database: string;\n collections: string[];\n autoMigration: MigrationStyle;\n };\n connectionString: string | undefined;\n databaseDriver: string;\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(color.green('Starting Pongo Shell (version: 0.17.0-beta.40)'));\n\n if (options.logging.printOptions) {\n console.log(color.green('With Options:'));\n console.log(prettyJson(options));\n }\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 color.yellow(\n `No connection string provided, using: 'postgresql://postgres:postgres@localhost:5432/postgres'`,\n ),\n );\n }\n\n const { databaseType } = parseConnectionString(connectionString);\n const driverType = `${databaseType}:${options.databaseDriver}` as const;\n\n const driver = pongoDriverRegistry.tryGet(driverType);\n\n if (driver === null) {\n console.error(\n `Error: No database driver found for driver type \"${driverType}\". Make sure the driver is installed and the connection string is correct.`,\n );\n process.exit(1);\n }\n\n const connectionCheck = await checkConnection(connectionString);\n\n if (!connectionCheck.successful) {\n if (connectionCheck.errorType === 'ConnectionRefused') {\n console.error(\n color.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 color.red(\n `Authentication failed. Check the username and password in the connection string.`,\n ),\n );\n } else {\n console.error(color.red('Error connecting to PostgreSQL server'));\n }\n console.log(color.red('Exiting Pongo Shell...'));\n process.exit();\n }\n\n console.log(color.green(`Successfully connected`));\n console.log(color.green('Use db.<collection>.<method>() to query.'));\n\n const shell = repl.start({\n prompt: color.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 driverOptions: PongoClientOptions = {\n driver,\n schema: {\n definition: schema,\n autoMigration: options.schema.autoMigration,\n },\n };\n\n // TODO: Find a better way to pass custom driver settings\n const customOptions = {\n connectionString,\n };\n\n const typedClient = pongoClient({\n ...driverOptions,\n ...customOptions,\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 const driverOptions: PongoClientOptions = {\n driver,\n schema: {\n autoMigration: options.schema.autoMigration,\n },\n };\n\n // TODO: Find a better way to pass custom driver settings\n const customOptions = {\n connectionString,\n };\n\n pongo = pongoClient({\n ...driverOptions,\n ...customOptions,\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.printResultsAsTable = printResultsAsTable;\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(color.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 databaseDriver: string;\n connectionString?: string;\n disableAutoMigrations: boolean;\n logStyle?: string;\n logLevel?: string;\n prettyLog?: boolean;\n printOptions?: boolean;\n}\n\nconst shellCommand = new Command('shell')\n .description('Start an interactive Pongo shell')\n .option(\n '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n 'pg',\n )\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('-o, --print-options', 'Print shell options')\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 printOptions: options.printOptions === true,\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 databaseDriver: options.databaseDriver,\n });\n });\n\nexport { shellCommand };\n","#!/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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,MAAM,kBAAkB,UAA0B;AAChD,KAAI,MAAM,WAAW,EACnB,QAAO;CAGT,IAAI,YAAY,MAAM,OAAO,EAAE,CAAC,aAAa,GAAG,MAAM,MAAM,EAAE;AAE9D,KAAI,UAAU,SAAS,IAAI,CACzB,aAAY,UAAU,MAAM,GAAG,GAAG;AAGpC,QAAO;;AAGT,MAAM,gBAAgB,kBAA4B,CAAC,QAAQ,KAAK;AAe9D,QAAO;;EAdO,gBACX,KACE,SACC,eAAe,eAAe,KAAK,CAAC,sDACvC,CACA,KAAK,KAWH,CAAC;;;;;EATc,gBACjB,KACE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QAAQ,KAAK,QAAQ,CAAC,YAAY,qBAAqB;AAEvD,QAAQ,WAAW,cAAc;AACjC,QAAQ,WAAW,eAAe;AAClC,QAAQ,WAAW,aAAa;AAEhC,QAAQ,MAAM,QAAQ,KAAK"}
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import { _ as toDbSchemaMetadata, j as objectEntries, o as pongoClient, p as pongoSchema, u as pongoDriverRegistry } from "./core-BHdOCUrr.js";
|
|
3
3
|
import { JSONSerializer, LogLevel, LogStyle, SQL, color, combineMigrations, dumbo, parseConnectionString, prettyJson, runSQLMigrations } from "@event-driven-io/dumbo";
|
|
4
4
|
import { Command } from "commander";
|
|
5
5
|
import fs from "node:fs";
|
|
@@ -197,7 +197,7 @@ const prettifyLogs = (logLevel) => {
|
|
|
197
197
|
const startRepl = async (options) => {
|
|
198
198
|
setLogLevel(process.env.DUMBO_LOG_LEVEL ?? options.logging.logLevel);
|
|
199
199
|
setLogStyle(process.env.DUMBO_LOG_STYLE ?? options.logging.logStyle);
|
|
200
|
-
console.log(color.green("Starting Pongo Shell (version: 0.17.0-beta.
|
|
200
|
+
console.log(color.green("Starting Pongo Shell (version: 0.17.0-beta.40)"));
|
|
201
201
|
if (options.logging.printOptions) {
|
|
202
202
|
console.log(color.green("With Options:"));
|
|
203
203
|
console.log(prettyJson(options));
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","names":[],"sources":["../src/commandLine/configFile.ts","../src/commandLine/migrate.ts","../src/commandLine/shell.ts","../src/cli.ts"],"sourcesContent":["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 `export 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 JSONSerializer,\n parseConnectionString,\n runSQLMigrations,\n type DatabaseDriverType,\n} from '@event-driven-io/dumbo';\nimport { Command } from 'commander';\nimport {\n pongoDriverRegistry,\n pongoSchema,\n type AnyPongoDriverOptions,\n type PongoCollectionSchema,\n type PongoDatabaseFactoryOptions,\n type PongoDocument,\n} from '../core';\nimport { loadConfigFile } from './configFile';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n databaseType?: string;\n databaseName?: string | undefined;\n databaseDriver: string;\n config?: string;\n dryRun?: boolean;\n timeoutMs?: number;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n databaseType: string;\n databaseName?: string | undefined;\n databaseDriver: string;\n config?: 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 '--dbt, --database-type <string>',\n 'Database type that should be used for connection (e.g., PostgreSQL or SQLite)',\n undefined,\n )\n .option(\n '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n )\n .option(\n '--dbn, --database-name <string>',\n 'Database name to connect to',\n undefined,\n )\n .option(\n '--cs, --connection-string <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 .option(\n '--t, --timeout <ms>',\n 'Set the migration timeout in milliseconds',\n parseInt,\n )\n .action(async (options: MigrateRunOptions) => {\n const { collection, dryRun, databaseName, databaseDriver, timeoutMs } =\n options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n\n const databaseType =\n options.databaseType ??\n parseConnectionString(connectionString).databaseType;\n\n let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--connection-string\" parameter or through the DB_CONNECTION_STRING environment variable.' +\n '\\nFor instance: --connection-string postgresql://postgres:postgres@localhost:5432/postgres',\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 driverType = `${databaseType}:${databaseDriver}` as const;\n\n const migrations = getMigrations({\n driverType,\n connectionString,\n databaseName,\n collectionNames,\n });\n\n const pool = dumbo({ connectionString, driverType });\n\n await runSQLMigrations(pool, migrations, {\n dryRun,\n migrationTimeoutMs: timeoutMs,\n });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n .option(\n '--dbt, --database-type <string>',\n 'Database type that should be used for connection (e.g., PostgreSQL or SQLite)',\n )\n .option(\n '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n )\n .option(\n '--dbn, --database-name <string>',\n 'Database name to connect to',\n undefined,\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('--print', 'Print the SQL to the console (default)', true)\n //.option('--write <filename>', 'Write the SQL to a specified file')\n .action(async (options: MigrateSqlOptions) => {\n const { collection, databaseName, databaseType, databaseDriver } = options;\n\n let collectionNames: string[];\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 driverType = `${databaseType}:${databaseDriver}` as const;\n\n const migrations = getMigrations({\n driverType,\n connectionString: undefined,\n databaseName,\n collectionNames,\n });\n\n console.log('Printing SQL:');\n console.log(combineMigrations(...migrations));\n });\n\nconst getMigrations = ({\n driverType,\n connectionString,\n databaseName,\n collectionNames,\n}: {\n driverType: DatabaseDriverType;\n connectionString: string | undefined;\n databaseName: string | undefined;\n collectionNames: string[];\n}) => {\n const driver = pongoDriverRegistry.tryGet(driverType);\n\n if (driver === null) {\n console.error(\n `Error: No database driver found for driver type \"${driverType}\". Make sure the driver is registered and the connection string is correct.`,\n );\n process.exit(1);\n }\n\n const dbDefinition = pongoSchema.db.from(databaseName, collectionNames);\n\n const driverOptions: PongoDatabaseFactoryOptions<\n Record<string, PongoCollectionSchema<PongoDocument>>,\n AnyPongoDriverOptions\n > = {\n schema: { definition: dbDefinition },\n serializer: JSONSerializer,\n };\n\n const customOptions = {\n connectionString,\n databaseName,\n };\n\n const db = driver.databaseFactory({ ...driverOptions, ...customOptions });\n\n return db.schema.component.migrations;\n};\n","import {\n color,\n LogLevel,\n LogStyle,\n parseConnectionString,\n prettyJson,\n SQL,\n type MigrationStyle,\n} from '@event-driven-io/dumbo';\nimport { checkConnection } from '@event-driven-io/dumbo/pg';\nimport Table from 'cli-table3';\nimport { Command } from 'commander';\nimport repl from 'node:repl';\nimport {\n pongoClient,\n pongoDriverRegistry,\n pongoSchema,\n type PongoClient,\n type PongoClientOptions,\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\nlet shouldDisplayResultsAsTable = false;\n\nconst printResultsAsTable = (print?: boolean) =>\n (shouldDisplayResultsAsTable = print === undefined || print === true);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst printOutput = (obj: any): string =>\n Array.isArray(obj) && shouldDisplayResultsAsTable\n ? displayResultsAsTable(obj)\n : prettyJson(obj);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst displayResultsAsTable = (results: any[]): string => {\n if (results.length === 0) {\n return color.yellow('No documents found.');\n }\n\n const columnNames = results\n\n .flatMap((result) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n typeof result === 'object' ? Object.keys(result) : typeof result,\n )\n .filter((value, index, array) => array.indexOf(value) === index);\n\n const columnWidths = calculateColumnWidths(results, columnNames);\n\n const table = new Table({\n head: columnNames.map((col) => color.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\n ? // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n Array.isArray(result[col])\n ? // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n displayResultsAsTable(result[col])\n : // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n prettyJson(result[col])\n : typeof result === 'object'\n ? ''\n : result != undefined && result != undefined\n ? prettyJson(result)\n : '',\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 printOptions: boolean;\n logLevel: LogLevel;\n logStyle: LogStyle;\n };\n schema: {\n database: string;\n collections: string[];\n autoMigration: MigrationStyle;\n };\n connectionString: string | undefined;\n databaseDriver: string;\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(color.green('Starting Pongo Shell (version: 0.17.0-beta.39)'));\n\n if (options.logging.printOptions) {\n console.log(color.green('With Options:'));\n console.log(prettyJson(options));\n }\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 color.yellow(\n `No connection string provided, using: 'postgresql://postgres:postgres@localhost:5432/postgres'`,\n ),\n );\n }\n\n const { databaseType } = parseConnectionString(connectionString);\n const driverType = `${databaseType}:${options.databaseDriver}` as const;\n\n const driver = pongoDriverRegistry.tryGet(driverType);\n\n if (driver === null) {\n console.error(\n `Error: No database driver found for driver type \"${driverType}\". Make sure the driver is installed and the connection string is correct.`,\n );\n process.exit(1);\n }\n\n const connectionCheck = await checkConnection(connectionString);\n\n if (!connectionCheck.successful) {\n if (connectionCheck.errorType === 'ConnectionRefused') {\n console.error(\n color.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 color.red(\n `Authentication failed. Check the username and password in the connection string.`,\n ),\n );\n } else {\n console.error(color.red('Error connecting to PostgreSQL server'));\n }\n console.log(color.red('Exiting Pongo Shell...'));\n process.exit();\n }\n\n console.log(color.green(`Successfully connected`));\n console.log(color.green('Use db.<collection>.<method>() to query.'));\n\n const shell = repl.start({\n prompt: color.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 driverOptions: PongoClientOptions = {\n driver,\n schema: {\n definition: schema,\n autoMigration: options.schema.autoMigration,\n },\n };\n\n // TODO: Find a better way to pass custom driver settings\n const customOptions = {\n connectionString,\n };\n\n const typedClient = pongoClient({\n ...driverOptions,\n ...customOptions,\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 const driverOptions: PongoClientOptions = {\n driver,\n schema: {\n autoMigration: options.schema.autoMigration,\n },\n };\n\n // TODO: Find a better way to pass custom driver settings\n const customOptions = {\n connectionString,\n };\n\n pongo = pongoClient({\n ...driverOptions,\n ...customOptions,\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.printResultsAsTable = printResultsAsTable;\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(color.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 databaseDriver: string;\n connectionString?: string;\n disableAutoMigrations: boolean;\n logStyle?: string;\n logLevel?: string;\n prettyLog?: boolean;\n printOptions?: boolean;\n}\n\nconst shellCommand = new Command('shell')\n .description('Start an interactive Pongo shell')\n .option(\n '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n 'pg',\n )\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('-o, --print-options', 'Print shell options')\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 printOptions: options.printOptions === true,\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 databaseDriver: options.databaseDriver,\n });\n });\n\nexport { shellCommand };\n","#!/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"],"mappings":";;;;;;;;;;AASA,MAAM,kBAAkB,UAA0B;AAChD,KAAI,MAAM,WAAW,EACnB,QAAO;CAGT,IAAI,YAAY,MAAM,OAAO,EAAE,CAAC,aAAa,GAAG,MAAM,MAAM,EAAE;AAE9D,KAAI,UAAU,SAAS,IAAI,CACzB,aAAY,UAAU,MAAM,GAAG,GAA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S;GAChB;EACD,QAAQ;GACN,aAAa;GACb;GACA,eAAe,QAAQ,wBACnB,SACA;GACL;EACD;EACA,gBAAgB,QAAQ;EACzB,CAAC;EACF;;;;ACjWJ,MAAM,UAAU,IAAI,SAAS;AAE7B,QAAQ,KAAK,QAAQ,CAAC,YAAY,qBAAqB;AAEvD,QAAQ,WAAW,cAAc;AACjC,QAAQ,WAAW,eAAe;AAClC,QAAQ,WAAW,aAAa;AAEhC,QAAQ,MAAM,QAAQ,KAAK"}
|
|
1
|
+
{"version":3,"file":"cli.js","names":[],"sources":["../src/commandLine/configFile.ts","../src/commandLine/migrate.ts","../src/commandLine/shell.ts","../src/cli.ts"],"sourcesContent":["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 `export 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 JSONSerializer,\n parseConnectionString,\n runSQLMigrations,\n type DatabaseDriverType,\n} from '@event-driven-io/dumbo';\nimport { Command } from 'commander';\nimport {\n pongoDriverRegistry,\n pongoSchema,\n type AnyPongoDriverOptions,\n type PongoCollectionSchema,\n type PongoDatabaseFactoryOptions,\n type PongoDocument,\n} from '../core';\nimport { loadConfigFile } from './configFile';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n databaseType?: string;\n databaseName?: string | undefined;\n databaseDriver: string;\n config?: string;\n dryRun?: boolean;\n timeoutMs?: number;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n databaseType: string;\n databaseName?: string | undefined;\n databaseDriver: string;\n config?: 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 '--dbt, --database-type <string>',\n 'Database type that should be used for connection (e.g., PostgreSQL or SQLite)',\n undefined,\n )\n .option(\n '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n )\n .option(\n '--dbn, --database-name <string>',\n 'Database name to connect to',\n undefined,\n )\n .option(\n '--cs, --connection-string <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 .option(\n '--t, --timeout <ms>',\n 'Set the migration timeout in milliseconds',\n parseInt,\n )\n .action(async (options: MigrateRunOptions) => {\n const { collection, dryRun, databaseName, databaseDriver, timeoutMs } =\n options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n\n const databaseType =\n options.databaseType ??\n parseConnectionString(connectionString).databaseType;\n\n let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--connection-string\" parameter or through the DB_CONNECTION_STRING environment variable.' +\n '\\nFor instance: --connection-string postgresql://postgres:postgres@localhost:5432/postgres',\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 driverType = `${databaseType}:${databaseDriver}` as const;\n\n const migrations = getMigrations({\n driverType,\n connectionString,\n databaseName,\n collectionNames,\n });\n\n const pool = dumbo({ connectionString, driverType });\n\n await runSQLMigrations(pool, migrations, {\n dryRun,\n migrationTimeoutMs: timeoutMs,\n });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n .option(\n '--dbt, --database-type <string>',\n 'Database type that should be used for connection (e.g., PostgreSQL or SQLite)',\n )\n .option(\n '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n )\n .option(\n '--dbn, --database-name <string>',\n 'Database name to connect to',\n undefined,\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('--print', 'Print the SQL to the console (default)', true)\n //.option('--write <filename>', 'Write the SQL to a specified file')\n .action(async (options: MigrateSqlOptions) => {\n const { collection, databaseName, databaseType, databaseDriver } = options;\n\n let collectionNames: string[];\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 driverType = `${databaseType}:${databaseDriver}` as const;\n\n const migrations = getMigrations({\n driverType,\n connectionString: undefined,\n databaseName,\n collectionNames,\n });\n\n console.log('Printing SQL:');\n console.log(combineMigrations(...migrations));\n });\n\nconst getMigrations = ({\n driverType,\n connectionString,\n databaseName,\n collectionNames,\n}: {\n driverType: DatabaseDriverType;\n connectionString: string | undefined;\n databaseName: string | undefined;\n collectionNames: string[];\n}) => {\n const driver = pongoDriverRegistry.tryGet(driverType);\n\n if (driver === null) {\n console.error(\n `Error: No database driver found for driver type \"${driverType}\". Make sure the driver is registered and the connection string is correct.`,\n );\n process.exit(1);\n }\n\n const dbDefinition = pongoSchema.db.from(databaseName, collectionNames);\n\n const driverOptions: PongoDatabaseFactoryOptions<\n Record<string, PongoCollectionSchema<PongoDocument>>,\n AnyPongoDriverOptions\n > = {\n schema: { definition: dbDefinition },\n serializer: JSONSerializer,\n };\n\n const customOptions = {\n connectionString,\n databaseName,\n };\n\n const db = driver.databaseFactory({ ...driverOptions, ...customOptions });\n\n return db.schema.component.migrations;\n};\n","import {\n color,\n LogLevel,\n LogStyle,\n parseConnectionString,\n prettyJson,\n SQL,\n type MigrationStyle,\n} from '@event-driven-io/dumbo';\nimport { checkConnection } from '@event-driven-io/dumbo/pg';\nimport Table from 'cli-table3';\nimport { Command } from 'commander';\nimport repl from 'node:repl';\nimport {\n pongoClient,\n pongoDriverRegistry,\n pongoSchema,\n type PongoClient,\n type PongoClientOptions,\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\nlet shouldDisplayResultsAsTable = false;\n\nconst printResultsAsTable = (print?: boolean) =>\n (shouldDisplayResultsAsTable = print === undefined || print === true);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst printOutput = (obj: any): string =>\n Array.isArray(obj) && shouldDisplayResultsAsTable\n ? displayResultsAsTable(obj)\n : prettyJson(obj);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst displayResultsAsTable = (results: any[]): string => {\n if (results.length === 0) {\n return color.yellow('No documents found.');\n }\n\n const columnNames = results\n\n .flatMap((result) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n typeof result === 'object' ? Object.keys(result) : typeof result,\n )\n .filter((value, index, array) => array.indexOf(value) === index);\n\n const columnWidths = calculateColumnWidths(results, columnNames);\n\n const table = new Table({\n head: columnNames.map((col) => color.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\n ? // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n Array.isArray(result[col])\n ? // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n displayResultsAsTable(result[col])\n : // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n prettyJson(result[col])\n : typeof result === 'object'\n ? ''\n : result != undefined && result != undefined\n ? prettyJson(result)\n : '',\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 printOptions: boolean;\n logLevel: LogLevel;\n logStyle: LogStyle;\n };\n schema: {\n database: string;\n collections: string[];\n autoMigration: MigrationStyle;\n };\n connectionString: string | undefined;\n databaseDriver: string;\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(color.green('Starting Pongo Shell (version: 0.17.0-beta.40)'));\n\n if (options.logging.printOptions) {\n console.log(color.green('With Options:'));\n console.log(prettyJson(options));\n }\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 color.yellow(\n `No connection string provided, using: 'postgresql://postgres:postgres@localhost:5432/postgres'`,\n ),\n );\n }\n\n const { databaseType } = parseConnectionString(connectionString);\n const driverType = `${databaseType}:${options.databaseDriver}` as const;\n\n const driver = pongoDriverRegistry.tryGet(driverType);\n\n if (driver === null) {\n console.error(\n `Error: No database driver found for driver type \"${driverType}\". Make sure the driver is installed and the connection string is correct.`,\n );\n process.exit(1);\n }\n\n const connectionCheck = await checkConnection(connectionString);\n\n if (!connectionCheck.successful) {\n if (connectionCheck.errorType === 'ConnectionRefused') {\n console.error(\n color.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 color.red(\n `Authentication failed. Check the username and password in the connection string.`,\n ),\n );\n } else {\n console.error(color.red('Error connecting to PostgreSQL server'));\n }\n console.log(color.red('Exiting Pongo Shell...'));\n process.exit();\n }\n\n console.log(color.green(`Successfully connected`));\n console.log(color.green('Use db.<collection>.<method>() to query.'));\n\n const shell = repl.start({\n prompt: color.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 driverOptions: PongoClientOptions = {\n driver,\n schema: {\n definition: schema,\n autoMigration: options.schema.autoMigration,\n },\n };\n\n // TODO: Find a better way to pass custom driver settings\n const customOptions = {\n connectionString,\n };\n\n const typedClient = pongoClient({\n ...driverOptions,\n ...customOptions,\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 const driverOptions: PongoClientOptions = {\n driver,\n schema: {\n autoMigration: options.schema.autoMigration,\n },\n };\n\n // TODO: Find a better way to pass custom driver settings\n const customOptions = {\n connectionString,\n };\n\n pongo = pongoClient({\n ...driverOptions,\n ...customOptions,\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.printResultsAsTable = printResultsAsTable;\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(color.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 databaseDriver: string;\n connectionString?: string;\n disableAutoMigrations: boolean;\n logStyle?: string;\n logLevel?: string;\n prettyLog?: boolean;\n printOptions?: boolean;\n}\n\nconst shellCommand = new Command('shell')\n .description('Start an interactive Pongo shell')\n .option(\n '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n 'pg',\n )\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('-o, --print-options', 'Print shell options')\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 printOptions: options.printOptions === true,\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 databaseDriver: options.databaseDriver,\n });\n });\n\nexport { shellCommand };\n","#!/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"],"mappings":";;;;;;;;;;AASA,MAAM,kBAAkB,UAA0B;AAChD,KAAI,MAAM,WAAW,EACnB,QAAO;CAGT,IAAI,YAAY,MAAM,OAAO,EAAE,CAAC,aAAa,GAAG,MAAM,MAAM,EAAE;AAE9D,KAAI,UAAU,SAAS,IAAI,CACzB,aAAY,UAAU,MAAM,GAAG,GAAG;AAGpC,QAAO;;AAGT,MAAM,gBAAgB,kBAA4B,CAAC,QAAQ,KAAK;AAe9D,QAAO;;EAdO,gBACX,KACE,SACC,eAAe,eAAe,KAAK,CAAC,sDACvC,CACA,KAAK,KAWH,CAAC;;;;;EATc,gBACjB,KACE,SACC,SAAS,KAAK,2BAA2B,eAAe,KAAK,CAAC,KAAK,KAAK,KAC3E,CACA,KAAK,KASG,CAAC;;;;;AAMd,MAAM,uBAAuB,wDAAwD,cAAc;AACnG,MAAM,gBAAgB,yDAAyD,cAAc;AAC7F,MAAM,aAAa,yEAAyE,cAAc;AAC1G,MAAM,mBAAmB,iHAAiH,cAAc;AACxJ,MAAM,qBAAqB,wEAAwE,cAAc;AAEjH,MAAa,iBAAiB,OAC5B,eACmC;CACnC,MAAM,YAAY,IAAI,IAAI,YAAY,UAAU,QAAQ,KAAK,CAAC,GAAG;AACjE,KAAI;EAMF,MAAM,SAAS,qBAAqB,MAJ4B,OAC9D,UAAU,MAGiC;AAE7C,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AQ,QAAQ,CACtC,YAAY,mCAAmC,CAC/C,OACC,qCACA,4GACA,KACD,CACA,OACC,qCACA,qCACD,CACA,OAAO,6BAA6B,4BAA4B,WAAW,CAC3E,OACC,8BACA,gCACC,OAAe,aAAuB;AAErC,QAAO,SAAS,OAAO,CAAC,MAAM,CAAC;GAEjC,EAAE,CACH,CACA,OACC,8CACA,+BACD,CACA,OAAO,uBAAuB,sBAAsB,CACpD,OACC,gCACA,+CACA,WACD,CACA,OAAO,qBAAqB,0BAA0B,MAAM,CAC5D,OAAO,oBAAoB,yCAAyC,CACpE,OAAO,OAAO,YAA0B;CACvC,MAAM,EAAE,YAAY,aAAa;CACjC,MAAM,mBAAmB,QAAQ;AAEjC,OAAM,UAAU;EACd,SAAS;GACP,cAAc,QAAQ,iBAAiB;GACvC,UAAU,QAAQ,YACd,SAAS,SACP,QAAQ,YAAqC,SAAS;GAC5D,UAAU,QAAQ,WACb,QAAQ,WACT,QAAQ,YACN,SAAS,OACT,SAAS;GAChB;EACD,QAAQ;GACN,aAAa;GACb;GACA,eAAe,QAAQ,wBACnB,SACA;GACL;EACD;EACA,gBAAgB,QAAQ;EACzB,CAAC;EACF;;;;ACjWJ,MAAM,UAAU,IAAI,SAAS;AAE7B,QAAQ,KAAK,QAAQ,CAAC,YAAY,qBAAqB;AAEvD,QAAQ,WAAW,cAAc;AACjC,QAAQ,WAAW,eAAe;AAClC,QAAQ,WAAW,aAAa;AAEhC,QAAQ,MAAM,QAAQ,KAAK"}
|
package/dist/cloudflare.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_core = require('./core-
|
|
2
|
+
const require_core = require('./core-C9SB3XMx.cjs');
|
|
3
3
|
const require_cli = require('./cli.cjs');
|
|
4
|
-
const require_core$1 = require('./core-
|
|
4
|
+
const require_core$1 = require('./core-CkmE5dkK.cjs');
|
|
5
5
|
let _event_driven_io_dumbo = require("@event-driven-io/dumbo");
|
|
6
6
|
let _event_driven_io_dumbo_cloudflare = require("@event-driven-io/dumbo/cloudflare");
|
|
7
7
|
|
package/dist/cloudflare.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as sqliteSQLBuilder, t as pongoCollectionSQLiteMigrations } from "./index-
|
|
1
|
+
import { _t as PongoDb, in as PongoDriverOptions, rn as PongoDriver } from "./index-C3pnS1S_.cjs";
|
|
2
|
+
import { n as sqliteSQLBuilder, t as pongoCollectionSQLiteMigrations } from "./index-FXnldVnn.cjs";
|
|
3
3
|
import { D1DriverType, D1PoolOptions } from "@event-driven-io/dumbo/cloudflare";
|
|
4
4
|
|
|
5
5
|
//#region src/storage/sqlite/d1/index.d.ts
|
package/dist/cloudflare.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as sqliteSQLBuilder, t as pongoCollectionSQLiteMigrations } from "./index-
|
|
1
|
+
import { _t as PongoDb, in as PongoDriverOptions, rn as PongoDriver } from "./index-r7V4paf_.js";
|
|
2
|
+
import { n as sqliteSQLBuilder, t as pongoCollectionSQLiteMigrations } from "./index-CZOmOsQt.js";
|
|
3
3
|
import { D1DriverType, D1PoolOptions } from "@event-driven-io/dumbo/cloudflare";
|
|
4
4
|
|
|
5
5
|
//#region src/storage/sqlite/d1/index.d.ts
|
package/dist/cloudflare.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as sqliteSQLBuilder, t as pongoCollectionSQLiteMigrations } from "./core-
|
|
1
|
+
import { L as PongoCollectionSchemaComponent, d as PongoDatabase, f as PongoDatabaseSchemaComponent, p as pongoSchema, u as pongoDriverRegistry } from "./core-BHdOCUrr.js";
|
|
2
|
+
import { n as sqliteSQLBuilder, t as pongoCollectionSQLiteMigrations } from "./core-CH0SOCr3.js";
|
|
3
3
|
import { JSONSerializer } from "@event-driven-io/dumbo";
|
|
4
4
|
import { D1DriverType, d1Pool } from "@event-driven-io/dumbo/cloudflare";
|
|
5
5
|
|
|
@@ -295,7 +295,7 @@ const pongoTransactionCache = (options) => {
|
|
|
295
295
|
|
|
296
296
|
//#endregion
|
|
297
297
|
//#region src/core/collection/filters/filters.ts
|
|
298
|
-
const asPlainObjectWithSingleKey = (filter, key) => filter && typeof filter === "object" && !Array.isArray(filter) && Object.keys(filter).length === 1 && key in filter ? filter : void 0;
|
|
298
|
+
const asPlainObjectWithSingleKey = (filter, key) => filter && typeof filter === "object" && !Array.isArray(filter) && Object.keys(filter).length === 1 && key in filter ? { [key]: filter[key] } : void 0;
|
|
299
299
|
const idFromFilter = (filter) => {
|
|
300
300
|
const idFilter = asPlainObjectWithSingleKey(filter, "_id");
|
|
301
301
|
return typeof idFilter?.["_id"] === "string" ? idFilter["_id"] : void 0;
|
|
@@ -582,6 +582,23 @@ const pongoCollection = ({ db, collectionName, pool, schemaComponent, schema, er
|
|
|
582
582
|
errors
|
|
583
583
|
});
|
|
584
584
|
};
|
|
585
|
+
const executeUpsert = async (storedRows, options) => {
|
|
586
|
+
const result = await command(SqlFor.insertOrReplace(storedRows), options);
|
|
587
|
+
const writtenIds = result.rows.map((r) => r._id);
|
|
588
|
+
const versions = new Map(result.rows.map((r) => [r._id, BigInt(r.version ?? 1n)]));
|
|
589
|
+
if (!options?.skipCache) {
|
|
590
|
+
const writtenSet = new Set(writtenIds);
|
|
591
|
+
const cacheEntries = storedRows.filter((r) => writtenSet.has(r._id)).map((r) => ({
|
|
592
|
+
...r,
|
|
593
|
+
_version: versions.get(r._id) ?? 1n
|
|
594
|
+
}));
|
|
595
|
+
if (cacheEntries.length > 0) await cacheSetMany(cacheEntries, options);
|
|
596
|
+
}
|
|
597
|
+
return {
|
|
598
|
+
writtenIds,
|
|
599
|
+
versions
|
|
600
|
+
};
|
|
601
|
+
};
|
|
585
602
|
const collection = {
|
|
586
603
|
dbName: db.databaseName,
|
|
587
604
|
collectionName,
|
|
@@ -597,6 +614,21 @@ const pongoCollection = ({ db, collectionName, pool, schemaComponent, schema, er
|
|
|
597
614
|
_id,
|
|
598
615
|
_version
|
|
599
616
|
});
|
|
617
|
+
if (options?.upsert) {
|
|
618
|
+
const { writtenIds, versions } = await executeUpsert([stored], options);
|
|
619
|
+
const successful = writtenIds.length > 0;
|
|
620
|
+
const nextExpectedVersion = versions.get(_id) ?? _version;
|
|
621
|
+
return operationResult({
|
|
622
|
+
successful,
|
|
623
|
+
insertedId: successful ? _id : null,
|
|
624
|
+
nextExpectedVersion
|
|
625
|
+
}, {
|
|
626
|
+
operationName: "insertOne",
|
|
627
|
+
collectionName,
|
|
628
|
+
serializer,
|
|
629
|
+
errors
|
|
630
|
+
});
|
|
631
|
+
}
|
|
600
632
|
const successful = ((await command(SqlFor.insertOne(stored), options)).rowCount ?? 0) > 0;
|
|
601
633
|
if (successful && !options?.skipCache) await cacheSet(stored, options);
|
|
602
634
|
return operationResult({
|
|
@@ -617,6 +649,19 @@ const pongoCollection = ({ db, collectionName, pool, schemaComponent, schema, er
|
|
|
617
649
|
_id: doc._id ?? v7(),
|
|
618
650
|
_version: doc._version ?? 1n
|
|
619
651
|
}).map((d) => toStored(d));
|
|
652
|
+
if (options?.upsert) {
|
|
653
|
+
const { writtenIds } = await executeUpsert(rows, options);
|
|
654
|
+
return operationResult({
|
|
655
|
+
successful: writtenIds.length === rows.length,
|
|
656
|
+
insertedCount: writtenIds.length,
|
|
657
|
+
insertedIds: writtenIds
|
|
658
|
+
}, {
|
|
659
|
+
operationName: "insertMany",
|
|
660
|
+
collectionName,
|
|
661
|
+
serializer,
|
|
662
|
+
errors
|
|
663
|
+
});
|
|
664
|
+
}
|
|
620
665
|
const result = await command(SqlFor.insertMany(rows), options);
|
|
621
666
|
if (!options?.skipCache) {
|
|
622
667
|
const insertedIdSet = new Set(result.rows.map((d) => d._id));
|
|
@@ -640,6 +685,8 @@ const pongoCollection = ({ db, collectionName, pool, schemaComponent, schema, er
|
|
|
640
685
|
successful: result.rows.length > 0 && result.rows[0].modified === result.rows[0].matched,
|
|
641
686
|
modifiedCount: Number(result.rows[0]?.modified ?? 0),
|
|
642
687
|
matchedCount: Number(result.rows[0]?.matched ?? 0),
|
|
688
|
+
upsertedId: null,
|
|
689
|
+
upsertedCount: 0,
|
|
643
690
|
nextExpectedVersion: BigInt(result.rows[0]?.version ?? 0n)
|
|
644
691
|
}, {
|
|
645
692
|
operationName: "updateOne",
|
|
@@ -655,12 +702,39 @@ const pongoCollection = ({ db, collectionName, pool, schemaComponent, schema, er
|
|
|
655
702
|
},
|
|
656
703
|
replaceOne: async (filter, document, options) => {
|
|
657
704
|
await ensureCollectionCreated(options);
|
|
705
|
+
const noConcurrencyCheck = options?.expectedVersion === void 0 || options.expectedVersion === "NO_CONCURRENCY_CHECK";
|
|
706
|
+
if (options?.upsert && noConcurrencyCheck) {
|
|
707
|
+
const _id = idFromFilter(filter) ?? v7();
|
|
708
|
+
const { writtenIds, versions } = await executeUpsert([toStored({
|
|
709
|
+
...document,
|
|
710
|
+
_id,
|
|
711
|
+
_version: 1n
|
|
712
|
+
})], options);
|
|
713
|
+
const written = writtenIds.length > 0;
|
|
714
|
+
const nextExpectedVersion = versions.get(_id) ?? 1n;
|
|
715
|
+
const inserted = written && nextExpectedVersion === 1n;
|
|
716
|
+
return operationResult({
|
|
717
|
+
successful: written,
|
|
718
|
+
modifiedCount: written && !inserted ? 1 : 0,
|
|
719
|
+
matchedCount: written && !inserted ? 1 : 0,
|
|
720
|
+
upsertedId: inserted ? _id : null,
|
|
721
|
+
upsertedCount: inserted ? 1 : 0,
|
|
722
|
+
nextExpectedVersion
|
|
723
|
+
}, {
|
|
724
|
+
operationName: "replaceOne",
|
|
725
|
+
collectionName,
|
|
726
|
+
serializer,
|
|
727
|
+
errors
|
|
728
|
+
});
|
|
729
|
+
}
|
|
658
730
|
const downcasted = downcast(document);
|
|
659
731
|
const result = await command(SqlFor.replaceOne(filter, downcasted, options), options);
|
|
660
732
|
const opResult = operationResult({
|
|
661
733
|
successful: result.rows.length > 0 && result.rows[0].modified > 0,
|
|
662
734
|
modifiedCount: Number(result.rows[0]?.modified ?? 0),
|
|
663
735
|
matchedCount: Number(result.rows[0]?.matched ?? 0),
|
|
736
|
+
upsertedId: null,
|
|
737
|
+
upsertedCount: 0,
|
|
664
738
|
nextExpectedVersion: BigInt(result.rows[0]?.version ?? 0n)
|
|
665
739
|
}, {
|
|
666
740
|
operationName: "replaceOne",
|
|
@@ -765,6 +839,29 @@ const pongoCollection = ({ db, collectionName, pool, schemaComponent, schema, er
|
|
|
765
839
|
replaceMany: async (documents, options) => {
|
|
766
840
|
await ensureCollectionCreated(options);
|
|
767
841
|
const rows = documents.map((d) => toStored(d));
|
|
842
|
+
if (options?.upsert) {
|
|
843
|
+
const versioned = documents.map((d) => "_version" in d && d._version !== void 0);
|
|
844
|
+
const hasVersions = versioned.some((v) => v);
|
|
845
|
+
const allVersioned = versioned.every((v) => v);
|
|
846
|
+
if (hasVersions && !allVersioned) throw new Error("replaceMany with upsert cannot mix documents with and without _version in a single batch");
|
|
847
|
+
if (!hasVersions) {
|
|
848
|
+
const { writtenIds, versions } = await executeUpsert(rows, options);
|
|
849
|
+
const conflictIds = documents.map((d) => d._id).filter((id) => !writtenIds.includes(id));
|
|
850
|
+
return operationResult({
|
|
851
|
+
successful: conflictIds.length === 0,
|
|
852
|
+
modifiedCount: writtenIds.length,
|
|
853
|
+
matchedCount: documents.length,
|
|
854
|
+
modifiedIds: [...writtenIds],
|
|
855
|
+
conflictIds: [...conflictIds],
|
|
856
|
+
nextExpectedVersions: versions
|
|
857
|
+
}, {
|
|
858
|
+
operationName: "replaceMany",
|
|
859
|
+
collectionName,
|
|
860
|
+
serializer,
|
|
861
|
+
errors
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
}
|
|
768
865
|
const result = await command(SqlFor.replaceMany(rows), options);
|
|
769
866
|
const modifiedIds = result.rows.map((row) => row._id);
|
|
770
867
|
const conflictIds = documents.map((d) => d._id).filter((id) => !modifiedIds.includes(id));
|
|
@@ -949,6 +1046,17 @@ const DOCUMENT_DOES_NOT_EXIST = "DOCUMENT_DOES_NOT_EXIST";
|
|
|
949
1046
|
const NO_CONCURRENCY_CHECK = "NO_CONCURRENCY_CHECK";
|
|
950
1047
|
const isGeneralExpectedDocumentVersion = (version) => version === "DOCUMENT_DOES_NOT_EXIST" || version === "DOCUMENT_EXISTS" || version === "NO_CONCURRENCY_CHECK";
|
|
951
1048
|
const expectedVersionValue = (version) => version === void 0 || isGeneralExpectedDocumentVersion(version) ? null : version;
|
|
1049
|
+
const expectedVersionPredicate = (version) => {
|
|
1050
|
+
if (version === void 0) return { operator: "none" };
|
|
1051
|
+
if (isGeneralExpectedDocumentVersion(version)) return version === "DOCUMENT_DOES_NOT_EXIST" ? {
|
|
1052
|
+
operator: "=",
|
|
1053
|
+
value: 0n
|
|
1054
|
+
} : { operator: "none" };
|
|
1055
|
+
return {
|
|
1056
|
+
operator: "=",
|
|
1057
|
+
value: version
|
|
1058
|
+
};
|
|
1059
|
+
};
|
|
952
1060
|
const expectedVersion = (version) => {
|
|
953
1061
|
return version ? BigInt(version) : NO_CONCURRENCY_CHECK;
|
|
954
1062
|
};
|
|
@@ -1317,5 +1425,5 @@ const mapParallel = (items, fn) => Promise.all(items.map(fn));
|
|
|
1317
1425
|
const mapAsync = (items, fn, options = { parallel: false }) => options?.parallel ? mapParallel(items, fn) : mapSequential(items, fn);
|
|
1318
1426
|
|
|
1319
1427
|
//#endregion
|
|
1320
|
-
export {
|
|
1321
|
-
//# sourceMappingURL=core-
|
|
1428
|
+
export { isString as A, DocumentCommandHandler as B, expectedVersionPredicate as C, ConcurrencyError as D, operationResult as E, hasOperators as F, noopCacheProvider as G, idFromFilter as H, isOperator as I, pongoCacheWrapper as J, lruCache as K, PongoCollectionSchemaComponent as L, PongoDatabaseCache as M, OperatorMap as N, PongoError as O, QueryOperators as P, pongoCollection as R, expectedVersion as S, isGeneralExpectedDocumentVersion as T, pongoTransactionCache as U, getIdsFromIdOnlyFilter as V, pongoCache as W, toDbSchemaMetadata as _, isEquatable as a, NO_CONCURRENCY_CHECK as b, pongoTransaction as c, PongoDatabase as d, PongoDatabaseSchemaComponent as f, toClientSchemaMetadata as g, proxyPongoDbWithSchema as h, deepEquals as i, objectEntries as j, isNumber as k, PongoDriverRegistry as l, proxyClientWithSchema as m, mapParallel as n, pongoClient as o, pongoSchema as p, identityMapCache as q, mapSequential as r, pongoSession as s, mapAsync as t, pongoDriverRegistry as u, DOCUMENT_DOES_NOT_EXIST as v, expectedVersionValue as w, ObjectId as x, DOCUMENT_EXISTS as y, transactionExecutorOrDefault as z };
|
|
1429
|
+
//# sourceMappingURL=core-BHdOCUrr.js.map
|