@event-driven-io/pongo 0.17.0-beta.41 → 0.17.0-beta.42

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 CHANGED
@@ -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.41)"));
231
+ console.log(_event_driven_io_dumbo.color.green("Starting Pongo Shell (version: 0.17.0-beta.42)"));
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.41)'));\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,K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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.42)'));\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,MAAI,OAAO,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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,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"}
package/dist/cli.js CHANGED
@@ -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.41)"));
200
+ console.log(color.green("Starting Pongo Shell (version: 0.17.0-beta.42)"));
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.41)'));\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,MAAI,OAAO,WAAW,UAAU;AAC9B,WAAQ,MAAM,OAAO;AACrB,WAAQ,KAAK,EAAE;;AAGjB,SAAO;SACD;AACN,UAAQ,MAAM,8BAA8B,UAAU,OAAO;AAC7D,UAAQ,KAAK,EAAE;;;AAInB,MAAa,sBACX,YACA,oBACS;AACT,KAAI;AACF,KAAG,cAAc,YAAY,aAAa,gB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D,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"}
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.42)'));\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,K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Ae;AAClC,QAAQ,WAAW,aAAa;AAEhC,QAAQ,MAAM,QAAQ,KAAK"}
@@ -1,7 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_core = require('./core-C9SB3XMx.cjs');
3
3
  const require_cli = require('./cli.cjs');
4
- const require_core$1 = require('./core-CkmE5dkK.cjs');
4
+ const require_core$1 = require('./core-q2eF-VHQ.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
 
@@ -1,5 +1,5 @@
1
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";
2
+ import { n as sqliteSQLBuilder, t as pongoCollectionSQLiteMigrations } from "./core-5npofT4H.js";
3
3
  import { JSONSerializer } from "@event-driven-io/dumbo";
4
4
  import { D1DriverType, d1Pool } from "@event-driven-io/dumbo/cloudflare";
5
5
 
@@ -1,18 +1,19 @@
1
1
  import { C as expectedVersionPredicate, F as hasOperators, N as OperatorMap, P as QueryOperators, j as objectEntries } from "./core-BHdOCUrr.js";
2
- import { SQL, isSQL, sqlMigration } from "@event-driven-io/dumbo";
2
+ import { JSONParam, SQL, isSQL, sqlMigration } from "@event-driven-io/dumbo";
3
+ import { SQLiteJSON } from "@event-driven-io/dumbo/sqlite";
3
4
 
4
5
  //#region src/storage/sqlite/core/sqlBuilder/filter/queryOperators.ts
5
6
  const handleOperator = (path, operator, value, serializer) => {
6
7
  if (path === "_id" || path === "_version") return handleMetadataOperator(path, operator, value);
7
8
  switch (operator) {
8
9
  case "$eq": {
9
- const jsonPath = buildJsonPath(path);
10
+ const jsonPath = SQLiteJSON.path(path);
10
11
  return SQL`(
11
- json_extract(data, '${SQL.plain(jsonPath)}') = ${value}
12
+ json_extract(data, ${jsonPath}) = ${value}
12
13
  OR (
13
- json_type(data, '${SQL.plain(jsonPath)}') = 'array'
14
+ json_type(data, ${jsonPath}) = 'array'
14
15
  AND EXISTS(
15
- SELECT 1 FROM json_each(data, '${SQL.plain(jsonPath)}')
16
+ SELECT 1 FROM json_each(data, ${jsonPath})
16
17
  WHERE json_each.value = ${value}
17
18
  )
18
19
  )
@@ -22,37 +23,26 @@ const handleOperator = (path, operator, value, serializer) => {
22
23
  case "$gte":
23
24
  case "$lt":
24
25
  case "$lte":
25
- case "$ne": {
26
- const jsonPath = buildJsonPath(path);
27
- return SQL`json_extract(data, '${SQL.plain(jsonPath)}') ${SQL.plain(OperatorMap[operator])} ${value}`;
28
- }
26
+ case "$ne": return SQL`json_extract(data, ${SQLiteJSON.path(path)}) ${SQL.plain(OperatorMap[operator])} ${value}`;
29
27
  case "$in": {
30
- const jsonPath = buildJsonPath(path);
28
+ const jsonPath = SQLiteJSON.path(path);
31
29
  const values = value;
32
- const inClause = SQL.merge(values.map((v) => SQL`${v}`), ", ");
33
- return SQL`json_extract(data, '${SQL.plain(jsonPath)}') IN (${inClause})`;
30
+ return SQL`json_extract(data, ${jsonPath}) IN (${SQL.merge(values.map((v) => SQL`${v}`), ", ")})`;
34
31
  }
35
32
  case "$nin": {
36
- const jsonPath = buildJsonPath(path);
33
+ const jsonPath = SQLiteJSON.path(path);
37
34
  const values = value;
38
- const inClause = SQL.merge(values.map((v) => SQL`${v}`), ", ");
39
- return SQL`json_extract(data, '${SQL.plain(jsonPath)}') NOT IN (${inClause})`;
35
+ return SQL`json_extract(data, ${jsonPath}) NOT IN (${SQL.merge(values.map((v) => SQL`${v}`), ", ")})`;
40
36
  }
41
37
  case "$elemMatch": {
42
- const subConditions = objectEntries(value).map(([subKey, subValue]) => {
43
- return `json_extract(value, '$.${subKey}') = json('${serializer.serialize(subValue)}')`;
44
- }).join(" AND ");
45
- const jsonPath = buildJsonPath(path);
46
- return SQL`EXISTS(SELECT 1 FROM json_each(data, '${SQL.plain(jsonPath)}') WHERE ${SQL.plain(subConditions)})`;
38
+ const subConditions = objectEntries(value).map(([subKey, subValue]) => SQL`json_extract(value, ${SQLiteJSON.path(subKey)}) = json(${JSONParam.value(subValue, serializer)})`);
39
+ return SQL`EXISTS(SELECT 1 FROM json_each(data, ${SQLiteJSON.path(path)}) WHERE ${SQL.merge(subConditions, " AND ")})`;
47
40
  }
48
41
  case "$all": {
49
- const jsonPath = buildJsonPath(path);
50
- return SQL`(SELECT COUNT(*) FROM json_each(json(${serializer.serialize(value)})) WHERE json_each.value NOT IN (SELECT value FROM json_each(data, '${SQL.plain(jsonPath)}'))) = 0`;
51
- }
52
- case "$size": {
53
- const jsonPath = buildJsonPath(path);
54
- return SQL`json_array_length(json_extract(data, '${SQL.plain(jsonPath)}')) = ${value}`;
42
+ const jsonPath = SQLiteJSON.path(path);
43
+ return SQL`(SELECT COUNT(*) FROM json_each(json(${JSONParam.value(value, serializer)})) WHERE json_each.value NOT IN (SELECT value FROM json_each(data, ${jsonPath}))) = 0`;
55
44
  }
45
+ case "$size": return SQL`json_array_length(json_extract(data, ${SQLiteJSON.path(path)})) = ${value}`;
56
46
  default: throw new Error(`Unsupported operator: ${operator}`);
57
47
  }
58
48
  };
@@ -77,9 +67,6 @@ const handleMetadataOperator = (fieldName, operator, value) => {
77
67
  default: throw new Error(`Unsupported operator: ${operator}`);
78
68
  }
79
69
  };
80
- const buildJsonPath = (path) => {
81
- return `$.${path}`;
82
- };
83
70
 
84
71
  //#endregion
85
72
  //#region src/storage/sqlite/core/sqlBuilder/filter/index.ts
@@ -142,24 +129,24 @@ const buildUpdateQuery = (update, serializer) => objectEntries(update).reduce((c
142
129
  default: return currentUpdateQuery;
143
130
  }
144
131
  }, SQL`data`);
145
- const buildSetQuery = (set, currentUpdateQuery, serializer) => SQL`json_patch(${currentUpdateQuery}, ${serializer.serialize(set)})`;
132
+ const buildSetQuery = (set, currentUpdateQuery, serializer) => SQL`json_patch(${currentUpdateQuery}, ${JSONParam.value(set, serializer)})`;
146
133
  const buildUnsetQuery = (unset, currentUpdateQuery) => {
147
134
  const keys = Object.keys(unset);
148
135
  let query = currentUpdateQuery;
149
- for (const key of keys) query = SQL`json_remove(${query}, '$.${SQL.plain(key)}')`;
136
+ for (const key of keys) query = SQL`json_remove(${query}, ${SQLiteJSON.path(key)})`;
150
137
  return query;
151
138
  };
152
139
  const buildIncQuery = (inc, currentUpdateQuery) => {
153
- for (const [key, value] of Object.entries(inc)) currentUpdateQuery = typeof value === "bigint" ? SQL`json_set(${currentUpdateQuery}, '$.${SQL.plain(key)}', CAST((COALESCE(json_extract(${currentUpdateQuery}, '$.${SQL.plain(key)}'), 0) + ${value}) AS TEXT))` : SQL`json_set(${currentUpdateQuery}, '$.${SQL.plain(key)}', COALESCE(json_extract(${currentUpdateQuery}, '$.${SQL.plain(key)}'), 0) + ${value})`;
140
+ for (const [key, value] of Object.entries(inc)) currentUpdateQuery = typeof value === "bigint" ? SQL`json_set(${currentUpdateQuery}, ${SQLiteJSON.path(key)}, CAST((COALESCE(json_extract(${currentUpdateQuery}, ${SQLiteJSON.path(key)}), 0) + ${value}) AS TEXT))` : SQL`json_set(${currentUpdateQuery}, ${SQLiteJSON.path(key)}, COALESCE(json_extract(${currentUpdateQuery}, ${SQLiteJSON.path(key)}), 0) + ${value})`;
154
141
  return currentUpdateQuery;
155
142
  };
156
143
  const buildPushQuery = (push, currentUpdateQuery, serializer) => {
157
144
  for (const [key, value] of Object.entries(push)) {
158
- const serializedValue = serializer.serialize(value);
159
- currentUpdateQuery = SQL`json_set(${currentUpdateQuery}, '$.${SQL.plain(key)}', CASE
160
- WHEN json_type(json_extract(${currentUpdateQuery}, '$.${SQL.plain(key)}')) = 'array'
161
- THEN json_insert(json_extract(${currentUpdateQuery}, '$.${SQL.plain(key)}'), '$[#]', json(${serializedValue}))
162
- ELSE json_array(json(${serializedValue}))
145
+ const serializedValue = JSONParam.value(value, serializer);
146
+ currentUpdateQuery = SQL`json_set(${currentUpdateQuery}, ${SQLiteJSON.path(key)}, CASE
147
+ WHEN json_type(json_extract(${currentUpdateQuery}, ${SQLiteJSON.path(key)})) = 'array'
148
+ THEN json_insert(json_extract(${currentUpdateQuery}, ${SQLiteJSON.path(key)}), '$[#]', json(${serializedValue}))
149
+ ELSE json(${JSONParam.arrayContaining(value, serializer)})
163
150
  END)`;
164
151
  }
165
152
  return currentUpdateQuery;
@@ -186,7 +173,7 @@ const pongoCollectionSQLiteMigrations = (collectionName) => [sqlMigration(`pongo
186
173
  const sqliteSQLBuilder = (collectionName, serializer) => ({
187
174
  createCollection: () => createCollection(collectionName),
188
175
  insertOne: (document) => {
189
- const serialized = document;
176
+ const serialized = JSONParam.document(document, serializer);
190
177
  const id = document._id;
191
178
  const version = document._version ?? 1n;
192
179
  return SQL`
@@ -195,7 +182,7 @@ const sqliteSQLBuilder = (collectionName, serializer) => ({
195
182
  RETURNING _id;`;
196
183
  },
197
184
  insertMany: (documents) => {
198
- const values = SQL.merge(documents.map((doc) => SQL`(${doc._id}, ${serializer.serialize(doc)}, ${doc._version ?? 1n})`), ",");
185
+ const values = SQL.merge(documents.map((doc) => SQL`(${doc._id}, ${JSONParam.document(doc, serializer)}, ${doc._version ?? 1n})`), ",");
199
186
  return SQL`
200
187
  INSERT OR IGNORE INTO ${SQL.identifier(collectionName)} (_id, data, _version) VALUES ${values}
201
188
  RETURNING _id;`;
@@ -204,7 +191,7 @@ const sqliteSQLBuilder = (collectionName, serializer) => ({
204
191
  const col = SQL.identifier(collectionName);
205
192
  return SQL`
206
193
  INSERT INTO ${col} (_id, data, _version)
207
- VALUES ${SQL.merge(documents.map((d) => SQL`(${d._id}, json_patch(${serializer.serialize(d)}, json_object('_id', ${d._id}, '_version', '1')), 1)`), ",")}
194
+ VALUES ${SQL.merge(documents.map((d) => SQL`(${d._id}, json_patch(${JSONParam.document(d, serializer)}, json_object('_id', ${d._id}, '_version', '1')), 1)`), ",")}
208
195
  ON CONFLICT(_id) DO UPDATE SET
209
196
  data = json_patch(excluded.data, json_object('_id', ${col}._id, '_version', cast(${col}._version + 1 as TEXT))),
210
197
  _version = ${col}._version + 1
@@ -237,7 +224,7 @@ const sqliteSQLBuilder = (collectionName, serializer) => ({
237
224
  return SQL`
238
225
  UPDATE ${SQL.identifier(collectionName)}
239
226
  SET
240
- data = json_patch(${serializer.serialize(document)}, json_object('_id', _id, '_version', cast(_version + 1 as TEXT))),
227
+ data = json_patch(${JSONParam.document(document, serializer)}, json_object('_id', _id, '_version', cast(_version + 1 as TEXT))),
241
228
  _version = _version + 1,
242
229
  _updated = datetime('now')
243
230
  WHERE _id = (
@@ -288,7 +275,7 @@ const sqliteSQLBuilder = (collectionName, serializer) => ({
288
275
  WITH replacements(_id, data, expected_version) AS (
289
276
  VALUES ${SQL.merge(documents.map((d) => {
290
277
  const expectedVersion = d._version;
291
- return expectedVersion !== void 0 ? SQL`(${d._id}, ${serializer.serialize(d)}, ${expectedVersion})` : SQL`(${d._id}, ${serializer.serialize(d)}, NULL)`;
278
+ return expectedVersion !== void 0 ? SQL`(${d._id}, ${JSONParam.document(d, serializer)}, ${expectedVersion})` : SQL`(${d._id}, ${JSONParam.document(d, serializer)}, NULL)`;
292
279
  }), ",")}
293
280
  )
294
281
  UPDATE ${col}
@@ -301,7 +288,7 @@ const sqliteSQLBuilder = (collectionName, serializer) => ({
301
288
  RETURNING ${col}._id, cast(${col}._version as TEXT) as version;`;
302
289
  return SQL`
303
290
  WITH replacements(_id, data) AS (
304
- VALUES ${SQL.merge(documents.map((d) => SQL`(${d._id}, ${serializer.serialize(d)})`), ",")}
291
+ VALUES ${SQL.merge(documents.map((d) => SQL`(${d._id}, ${JSONParam.document(d, serializer)})`), ",")}
305
292
  )
306
293
  UPDATE ${col}
307
294
  SET
@@ -338,7 +325,7 @@ const sqliteSQLBuilder = (collectionName, serializer) => ({
338
325
  query.push(where(filterQuery));
339
326
  if (options?.sort && Object.keys(options.sort).length > 0) {
340
327
  const clauses = Object.entries(options.sort).map(([field, dir]) => {
341
- const accessor = field === "_id" || field === "_version" ? SQL`${SQL.plain(field)}` : SQL`json_extract(data, '${SQL.plain(`$.${field}`)}')`;
328
+ const accessor = field === "_id" || field === "_version" ? SQL`${SQL.identifier(field)}` : SQL`json_extract(data, ${SQLiteJSON.path(field)})`;
342
329
  return dir === 1 ? SQL`${accessor} ASC` : SQL`${accessor} DESC`;
343
330
  });
344
331
  query.push(SQL`ORDER BY ${SQL.merge(clauses, ",")}`);
@@ -358,4 +345,4 @@ const where = (filterQuery) => SQL.check.isEmpty(filterQuery) ? SQL.EMPTY : SQL.
358
345
 
359
346
  //#endregion
360
347
  export { sqliteSQLBuilder as n, pongoCollectionSQLiteMigrations as t };
361
- //# sourceMappingURL=core-CH0SOCr3.js.map
348
+ //# sourceMappingURL=core-5npofT4H.js.map