@event-driven-io/pongo 0.17.0-alpha.1 → 0.17.0-alpha.3

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/storage/postgresql/sqlBuilder/index.ts","../src/core/collection/pongoCollection.ts","../src/storage/postgresql/dbClient.ts","../src/core/collection/query.ts","../src/core/errors/index.ts","../src/core/pongoClient.ts","../src/core/pongoDb.ts","../src/core/pongoTransaction.ts","../src/core/pongoSession.ts","../src/core/typing/entries.ts","../src/core/typing/operations.ts","../src/core/schema/index.ts","../src/core/utils/deepEquals.ts","../src/storage/postgresql/sqlBuilder/filter/queryOperators.ts","../src/storage/postgresql/sqlBuilder/filter/index.ts","../src/storage/postgresql/sqlBuilder/update/index.ts"],"sourcesContent":["import {\n isSQL,\n JSONSerializer,\n rawSql,\n sql,\n sqlMigration,\n type SQL,\n type SQLMigration,\n} from '@event-driven-io/dumbo';\nimport {\n expectedVersionValue,\n type DeleteOneOptions,\n type OptionalUnlessRequiredIdAndVersion,\n type PongoCollectionSQLBuilder,\n type PongoFilter,\n type PongoUpdate,\n type ReplaceOneOptions,\n type UpdateOneOptions,\n type WithoutId,\n} from '../../../core';\nimport { constructFilterQuery } from './filter';\nimport { buildUpdateQuery } from './update';\n\nconst createCollection = (collectionName: string): SQL =>\n sql(\n `CREATE TABLE IF NOT EXISTS %I (\n _id TEXT PRIMARY KEY, \n data JSONB NOT NULL, \n metadata JSONB NOT NULL DEFAULT '{}',\n _version BIGINT NOT NULL DEFAULT 1,\n _partition TEXT NOT NULL DEFAULT 'png_global',\n _archived BOOLEAN NOT NULL DEFAULT FALSE,\n _created TIMESTAMPTZ NOT NULL DEFAULT now(),\n _updated TIMESTAMPTZ NOT NULL DEFAULT now()\n )`,\n collectionName,\n );\n\nexport const pongoCollectionPostgreSQLMigrations = (collectionName: string) => [\n sqlMigration(`pongoCollection:${collectionName}:001:createtable`, [\n createCollection(collectionName),\n ]),\n];\n\nexport const postgresSQLBuilder = (\n collectionName: string,\n): PongoCollectionSQLBuilder => ({\n migrations: (): SQLMigration[] =>\n pongoCollectionPostgreSQLMigrations(collectionName),\n createCollection: (): SQL => createCollection(collectionName),\n insertOne: <T>(document: OptionalUnlessRequiredIdAndVersion<T>): SQL => {\n return sql(\n 'INSERT INTO %I (_id, data, _version) VALUES (%L, %L, %L) ON CONFLICT(_id) DO NOTHING;',\n collectionName,\n document._id,\n JSONSerializer.serialize(document),\n document._version ?? 1n,\n );\n },\n insertMany: <T>(documents: OptionalUnlessRequiredIdAndVersion<T>[]): SQL => {\n const values = documents\n .map((doc) =>\n sql(\n '(%L, %L, %L)',\n doc._id,\n JSONSerializer.serialize(doc),\n doc._version ?? 1n,\n ),\n )\n .join(', ');\n return sql(\n `INSERT INTO %I (_id, data, _version) VALUES %s \n ON CONFLICT(_id) DO NOTHING\n RETURNING _id;`,\n collectionName,\n values,\n );\n },\n updateOne: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n options?: UpdateOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionUpdate =\n expectedVersion != null ? 'AND %I._version = %L' : '';\n const expectedVersionParams =\n expectedVersion != null ? [collectionName, expectedVersion] : [];\n\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n const updateQuery = isSQL(update) ? update : buildUpdateQuery(update);\n\n return sql(\n `WITH existing AS (\n SELECT _id, _version as current_version\n FROM %I %s \n LIMIT 1\n ),\n updated AS (\n UPDATE %I \n SET \n data = %s || jsonb_build_object('_id', %I._id) || jsonb_build_object('_version', (_version + 1)::text),\n _version = _version + 1\n FROM existing \n WHERE %I._id = existing._id ${expectedVersionUpdate}\n RETURNING %I._id, %I._version\n )\n SELECT \n existing._id,\n COALESCE(updated._version, existing.current_version) AS version,\n COUNT(existing._id) over() AS matched,\n COUNT(updated._id) over() AS modified\n FROM existing\n LEFT JOIN updated \n ON existing._id = updated._id;`,\n collectionName,\n where(filterQuery),\n collectionName,\n updateQuery,\n collectionName,\n collectionName,\n ...expectedVersionParams,\n collectionName,\n collectionName,\n );\n },\n replaceOne: <T>(\n filter: PongoFilter<T> | SQL,\n document: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionUpdate =\n expectedVersion != null ? 'AND %I._version = %L' : '';\n const expectedVersionParams =\n expectedVersion != null ? [collectionName, expectedVersion] : [];\n\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql(\n `WITH existing AS (\n SELECT _id, _version as current_version\n FROM %I %s \n LIMIT 1\n ),\n updated AS (\n UPDATE %I \n SET \n data = %L || jsonb_build_object('_id', %I._id) || jsonb_build_object('_version', (_version + 1)::text),\n _version = _version + 1\n FROM existing \n WHERE %I._id = existing._id ${expectedVersionUpdate}\n RETURNING %I._id, %I._version\n )\n SELECT \n existing._id,\n COALESCE(updated._version, existing.current_version) AS version,\n COUNT(existing._id) over() AS matched,\n COUNT(updated._id) over() AS modified\n FROM existing\n LEFT JOIN updated \n ON existing._id = updated._id;`,\n collectionName,\n where(filterQuery),\n collectionName,\n JSONSerializer.serialize(document),\n collectionName,\n collectionName,\n ...expectedVersionParams,\n collectionName,\n collectionName,\n );\n },\n updateMany: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n ): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n const updateQuery = isSQL(update) ? update : buildUpdateQuery(update);\n\n return sql(\n `UPDATE %I \n SET \n data = %s || jsonb_build_object('_version', (_version + 1)::text),\n _version = _version + 1\n %s;`,\n collectionName,\n updateQuery,\n where(filterQuery),\n );\n },\n deleteOne: <T>(\n filter: PongoFilter<T> | SQL,\n options?: DeleteOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionUpdate =\n expectedVersion != null ? 'AND %I._version = %L' : '';\n const expectedVersionParams =\n expectedVersion != null ? [collectionName, expectedVersion] : [];\n\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql(\n `WITH existing AS (\n SELECT _id\n FROM %I %s \n LIMIT 1\n ),\n deleted AS (\n DELETE FROM %I\n USING existing\n WHERE %I._id = existing._id ${expectedVersionUpdate}\n RETURNING %I._id\n )\n SELECT \n existing._id,\n COUNT(existing._id) over() AS matched,\n COUNT(deleted._id) over() AS deleted\n FROM existing\n LEFT JOIN deleted \n ON existing._id = deleted._id;`,\n collectionName,\n where(filterQuery),\n collectionName,\n collectionName,\n ...expectedVersionParams,\n collectionName,\n );\n },\n deleteMany: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql('DELETE FROM %I %s', collectionName, where(filterQuery));\n },\n findOne: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql(\n 'SELECT data FROM %I %s LIMIT 1;',\n collectionName,\n where(filterQuery),\n );\n },\n find: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n return sql('SELECT data FROM %I %s;', collectionName, where(filterQuery));\n },\n countDocuments: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n return sql(\n 'SELECT COUNT(1) as count FROM %I %s;',\n collectionName,\n where(filterQuery),\n );\n },\n rename: (newName: string): SQL =>\n sql('ALTER TABLE %I RENAME TO %I;', collectionName, newName),\n drop: (targetName: string = collectionName): SQL =>\n sql('DROP TABLE IF EXISTS %I', targetName),\n});\n\nconst where = (filter: string): SQL =>\n filter.length > 0 ? sql('WHERE %s', filter) : rawSql('');\n","import {\n schemaComponent,\n single,\n type ConnectorType,\n type DatabaseTransaction,\n type Dumbo,\n type MigrationStyle,\n type QueryResult,\n type QueryResultRow,\n type SchemaComponent,\n type SQL,\n type SQLExecutor,\n type SQLMigration,\n} from '@event-driven-io/dumbo';\nimport { runPostgreSQLMigrations } from '@event-driven-io/dumbo/pg';\nimport { v7 as uuid } from 'uuid';\nimport {\n deepEquals,\n expectedVersionValue,\n operationResult,\n type CollectionOperationOptions,\n type DeleteManyOptions,\n type DeleteOneOptions,\n type DocumentHandler,\n type HandleOptions,\n type InsertManyOptions,\n type InsertOneOptions,\n type OptionalUnlessRequiredIdAndVersion,\n type PongoCollection,\n type PongoDb,\n type PongoDeleteResult,\n type PongoDocument,\n type PongoFilter,\n type PongoHandleResult,\n type PongoInsertManyResult,\n type PongoInsertOneResult,\n type PongoUpdate,\n type PongoUpdateManyResult,\n type PongoUpdateResult,\n type ReplaceOneOptions,\n type UpdateManyOptions,\n type UpdateOneOptions,\n type WithIdAndVersion,\n type WithoutId,\n type WithVersion,\n} from '..';\nimport { pongoCollectionPostgreSQLMigrations } from '../../storage/postgresql';\n\nexport type PongoCollectionOptions<\n Connector extends ConnectorType = ConnectorType,\n> = {\n db: PongoDb<Connector>;\n collectionName: string;\n pool: Dumbo;\n sqlBuilder: PongoCollectionSQLBuilder;\n schema?: { autoMigration?: MigrationStyle };\n errors?: { throwOnOperationFailures?: boolean };\n};\n\nconst enlistIntoTransactionIfActive = async <\n Connector extends ConnectorType = ConnectorType,\n>(\n db: PongoDb<Connector>,\n options: CollectionOperationOptions | undefined,\n): Promise<DatabaseTransaction | null> => {\n const transaction = options?.session?.transaction;\n\n if (!transaction || !transaction.isActive) return null;\n\n return await transaction.enlistDatabase(db);\n};\n\nexport const transactionExecutorOrDefault = async <\n Connector extends ConnectorType = ConnectorType,\n>(\n db: PongoDb<Connector>,\n options: CollectionOperationOptions | undefined,\n defaultSqlExecutor: SQLExecutor,\n): Promise<SQLExecutor> => {\n const existingTransaction = await enlistIntoTransactionIfActive(db, options);\n return existingTransaction?.execute ?? defaultSqlExecutor;\n};\n\nexport const pongoCollection = <\n T extends PongoDocument,\n Connector extends ConnectorType = ConnectorType,\n>({\n db,\n collectionName,\n pool,\n sqlBuilder: SqlFor,\n schema,\n errors,\n}: PongoCollectionOptions<Connector>): PongoCollection<T> => {\n const sqlExecutor = pool.execute;\n const command = async <Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (\n await transactionExecutorOrDefault(db, options, sqlExecutor)\n ).command<Result>(sql);\n\n const query = async <T extends QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (await transactionExecutorOrDefault(db, options, sqlExecutor)).query<T>(\n sql,\n );\n\n let shouldMigrate = schema?.autoMigration !== 'None';\n\n const createCollection = (options?: CollectionOperationOptions) => {\n shouldMigrate = false;\n\n if (options?.session) return command(SqlFor.createCollection(), options);\n else return command(SqlFor.createCollection());\n };\n\n const ensureCollectionCreated = (options?: CollectionOperationOptions) => {\n if (!shouldMigrate) {\n return Promise.resolve();\n }\n\n return createCollection(options);\n };\n\n const collection = {\n dbName: db.databaseName,\n collectionName,\n createCollection: async (options?: CollectionOperationOptions) => {\n await createCollection(options);\n },\n insertOne: async (\n document: OptionalUnlessRequiredIdAndVersion<T>,\n options?: InsertOneOptions,\n ): Promise<PongoInsertOneResult> => {\n await ensureCollectionCreated(options);\n\n const _id = (document._id as string | undefined | null) ?? uuid();\n const _version = document._version ?? 1n;\n\n const result = await command(\n SqlFor.insertOne({\n ...document,\n _id,\n _version,\n } as OptionalUnlessRequiredIdAndVersion<T>),\n options,\n );\n\n const successful = (result.rowCount ?? 0) > 0;\n\n return operationResult<PongoInsertOneResult>(\n {\n successful,\n insertedId: successful ? _id : null,\n nextExpectedVersion: _version,\n },\n { operationName: 'insertOne', collectionName, errors },\n );\n },\n insertMany: async (\n documents: OptionalUnlessRequiredIdAndVersion<T>[],\n options?: InsertManyOptions,\n ): Promise<PongoInsertManyResult> => {\n await ensureCollectionCreated(options);\n\n const rows = documents.map((doc) => ({\n ...doc,\n _id: (doc._id as string | undefined | null) ?? uuid(),\n _version: doc._version ?? 1n,\n }));\n\n const result = await command(\n SqlFor.insertMany(rows as OptionalUnlessRequiredIdAndVersion<T>[]),\n options,\n );\n\n return operationResult<PongoInsertManyResult>(\n {\n successful: result.rowCount === rows.length,\n insertedCount: result.rowCount ?? 0,\n insertedIds: result.rows.map((d) => d._id as string),\n },\n { operationName: 'insertMany', collectionName, errors },\n );\n },\n updateOne: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: UpdateOneOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command<UpdateSqlResult>(\n SqlFor.updateOne(filter, update, options),\n options,\n );\n\n return operationResult<PongoUpdateResult>(\n {\n successful:\n result.rows.length > 0 &&\n result.rows[0]!.modified === result.rows[0]!.matched,\n modifiedCount: Number(result.rows[0]?.modified ?? 0),\n matchedCount: Number(result.rows[0]?.matched ?? 0),\n nextExpectedVersion: result.rows[0]?.version ?? 0n,\n },\n { operationName: 'updateOne', collectionName, errors },\n );\n },\n replaceOne: async (\n filter: PongoFilter<T>,\n document: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command<UpdateSqlResult>(\n SqlFor.replaceOne(filter, document, options),\n options,\n );\n return operationResult<PongoUpdateResult>(\n {\n successful: result.rows.length > 0 && result.rows[0]!.modified > 0,\n modifiedCount: Number(result.rows[0]?.modified ?? 0),\n matchedCount: Number(result.rows[0]?.matched ?? 0),\n nextExpectedVersion: result.rows[0]?.version ?? 0n,\n },\n { operationName: 'replaceOne', collectionName, errors },\n );\n },\n updateMany: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: UpdateManyOptions,\n ): Promise<PongoUpdateManyResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.updateMany(filter, update), options);\n\n return operationResult<PongoUpdateManyResult>(\n {\n successful: true,\n modifiedCount: result.rowCount ?? 0,\n matchedCount: result.rowCount ?? 0,\n },\n { operationName: 'updateMany', collectionName, errors },\n );\n },\n deleteOne: async (\n filter?: PongoFilter<T>,\n options?: DeleteOneOptions,\n ): Promise<PongoDeleteResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command<DeleteSqlResult>(\n SqlFor.deleteOne(filter ?? {}, options),\n options,\n );\n return operationResult<PongoDeleteResult>(\n {\n successful: result.rows.length > 0 && result.rows[0]!.deleted! > 0,\n deletedCount: Number(result.rows[0]?.deleted ?? 0),\n matchedCount: Number(result.rows[0]?.matched ?? 0),\n },\n { operationName: 'deleteOne', collectionName, errors },\n );\n },\n deleteMany: async (\n filter?: PongoFilter<T>,\n options?: DeleteManyOptions,\n ): Promise<PongoDeleteResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.deleteMany(filter ?? {}), options);\n\n return operationResult<PongoDeleteResult>(\n {\n successful: (result.rowCount ?? 0) > 0,\n deletedCount: result.rowCount ?? 0,\n matchedCount: result.rowCount ?? 0,\n },\n { operationName: 'deleteMany', collectionName, errors },\n );\n },\n findOne: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const result = await query(SqlFor.findOne(filter ?? {}), options);\n return (result.rows[0]?.data ?? null) as WithIdAndVersion<T> | null;\n },\n findOneAndDelete: async (\n filter: PongoFilter<T>,\n options?: DeleteOneOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.deleteOne(filter, options);\n return existingDoc;\n },\n findOneAndReplace: async (\n filter: PongoFilter<T>,\n replacement: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.replaceOne(filter, replacement, options);\n\n return existingDoc;\n },\n findOneAndUpdate: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: UpdateOneOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.updateOne(filter, update, options);\n\n return existingDoc;\n },\n handle: async (\n id: string,\n handle: DocumentHandler<T>,\n options?: HandleOptions,\n ): Promise<PongoHandleResult<T>> => {\n const { expectedVersion: version, ...operationOptions } = options ?? {};\n await ensureCollectionCreated(options);\n\n const byId: PongoFilter<T> = { _id: id };\n\n const existing = (await collection.findOne(\n byId,\n options,\n )) as WithVersion<T> | null;\n\n const expectedVersion = expectedVersionValue(version);\n\n if (\n (existing == null && version === 'DOCUMENT_EXISTS') ||\n (existing == null && expectedVersion != null) ||\n (existing != null && version === 'DOCUMENT_DOES_NOT_EXIST') ||\n (existing != null &&\n expectedVersion !== null &&\n existing._version !== expectedVersion)\n ) {\n return operationResult<PongoHandleResult<T>>(\n {\n successful: false,\n document: existing as T,\n },\n { operationName: 'handle', collectionName, errors },\n );\n }\n\n const result = await handle(\n existing !== null ? ({ ...existing } as T) : null,\n );\n\n if (deepEquals(existing as T | null, result))\n return operationResult<PongoHandleResult<T>>(\n {\n successful: true,\n document: existing as T | null,\n },\n { operationName: 'handle', collectionName, errors },\n );\n\n if (!existing && result) {\n const newDoc = { ...result, _id: id };\n const insertResult = await collection.insertOne(\n { ...newDoc, _id: id } as OptionalUnlessRequiredIdAndVersion<T>,\n {\n ...operationOptions,\n expectedVersion: 'DOCUMENT_DOES_NOT_EXIST',\n },\n );\n return {\n ...insertResult,\n document: {\n ...newDoc,\n _version: insertResult.nextExpectedVersion,\n } as T,\n };\n }\n\n if (existing && !result) {\n const deleteResult = await collection.deleteOne(byId, {\n ...operationOptions,\n expectedVersion: expectedVersion ?? 'DOCUMENT_EXISTS',\n });\n return { ...deleteResult, document: null };\n }\n\n if (existing && result) {\n const replaceResult = await collection.replaceOne(byId, result, {\n ...operationOptions,\n expectedVersion: expectedVersion ?? 'DOCUMENT_EXISTS',\n });\n return {\n ...replaceResult,\n document: {\n ...result,\n _version: replaceResult.nextExpectedVersion,\n } as T,\n };\n }\n\n return operationResult<PongoHandleResult<T>>(\n {\n successful: true,\n document: existing as T,\n },\n { operationName: 'handle', collectionName, errors },\n );\n },\n find: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<WithIdAndVersion<T>[]> => {\n await ensureCollectionCreated(options);\n\n const result = await query(SqlFor.find(filter ?? {}));\n return result.rows.map((row) => row.data as WithIdAndVersion<T>);\n },\n countDocuments: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<number> => {\n await ensureCollectionCreated(options);\n\n const { count } = await single(\n query<{ count: number }>(SqlFor.countDocuments(filter ?? {})),\n );\n return count;\n },\n drop: async (options?: CollectionOperationOptions): Promise<boolean> => {\n await ensureCollectionCreated(options);\n const result = await command(SqlFor.drop());\n return (result?.rowCount ?? 0) > 0;\n },\n rename: async (\n newName: string,\n options?: CollectionOperationOptions,\n ): Promise<PongoCollection<T>> => {\n await ensureCollectionCreated(options);\n await command(SqlFor.rename(newName));\n collectionName = newName;\n return collection;\n },\n\n sql: {\n async query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<Result[]> {\n await ensureCollectionCreated(options);\n\n const result = await query<Result>(sql, options);\n return result.rows;\n },\n async command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<QueryResult<Result>> {\n await ensureCollectionCreated(options);\n\n return command(sql, options);\n },\n },\n schema: {\n get component(): SchemaComponent {\n return schemaComponent('pongo:schema_component:collection', {\n migrations: SqlFor.migrations,\n });\n },\n migrate: () => runPostgreSQLMigrations(pool, SqlFor.migrations()), // TODO: This needs to change to support more connectors\n },\n };\n\n return collection;\n};\n\nexport const pongoCollectionSchemaComponent = (collectionName: string) =>\n schemaComponent('pongo:schema_component:collection', {\n migrations: () => pongoCollectionPostgreSQLMigrations(collectionName), // TODO: This needs to change to support more connectors\n });\n\nexport type PongoCollectionSQLBuilder = {\n migrations: () => SQLMigration[];\n createCollection: () => SQL;\n insertOne: <T>(document: OptionalUnlessRequiredIdAndVersion<T>) => SQL;\n insertMany: <T>(documents: OptionalUnlessRequiredIdAndVersion<T>[]) => SQL;\n updateOne: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n options?: UpdateOneOptions,\n ) => SQL;\n replaceOne: <T>(\n filter: PongoFilter<T> | SQL,\n document: WithoutId<T>,\n options?: ReplaceOneOptions,\n ) => SQL;\n updateMany: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n ) => SQL;\n deleteOne: <T>(\n filter: PongoFilter<T> | SQL,\n options?: DeleteOneOptions,\n ) => SQL;\n deleteMany: <T>(filter: PongoFilter<T> | SQL) => SQL;\n findOne: <T>(filter: PongoFilter<T> | SQL) => SQL;\n find: <T>(filter: PongoFilter<T> | SQL) => SQL;\n countDocuments: <T>(filter: PongoFilter<T> | SQL) => SQL;\n rename: (newName: string) => SQL;\n drop: () => SQL;\n};\n\ntype UpdateSqlResult = {\n matched: bigint;\n modified: bigint;\n version: bigint;\n};\n\ntype DeleteSqlResult = {\n matched: bigint | null;\n deleted: bigint | null;\n};\n","import {\n schemaComponent,\n SQL,\n type QueryResult,\n type QueryResultRow,\n type SchemaComponent,\n} from '@event-driven-io/dumbo';\nimport {\n dumbo,\n getDatabaseNameOrDefault,\n NodePostgresConnectorType,\n runPostgreSQLMigrations,\n type PostgresConnector,\n type PostgresPoolOptions,\n} from '@event-driven-io/dumbo/pg';\nimport type { Document } from 'mongodb';\nimport {\n objectEntries,\n pongoCollection,\n pongoCollectionSchemaComponent,\n proxyPongoDbWithSchema,\n transactionExecutorOrDefault,\n type CollectionOperationOptions,\n type PongoCollection,\n type PongoDb,\n type PongoDbClientOptions,\n} from '../../core';\nimport { postgresSQLBuilder } from './sqlBuilder';\n\nexport type PostgresDbClientOptions = PongoDbClientOptions<PostgresConnector>;\n\nexport const isPostgresClientOptions = (\n options: PongoDbClientOptions,\n): options is PostgresDbClientOptions =>\n options.connector === NodePostgresConnectorType;\n\nexport const postgresDb = (\n options: PostgresDbClientOptions,\n): PongoDb<PostgresConnector> => {\n const { connectionString, dbName } = options;\n const databaseName = dbName ?? getDatabaseNameOrDefault(connectionString);\n\n const pool = dumbo<PostgresPoolOptions>({\n connectionString,\n ...options.connectionOptions,\n });\n\n const collections = new Map<string, PongoCollection<Document>>();\n\n const command = async <Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (\n await transactionExecutorOrDefault(db, options, pool.execute)\n ).command<Result>(sql);\n\n const query = async <T extends QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (await transactionExecutorOrDefault(db, options, pool.execute)).query<T>(\n sql,\n );\n\n const db: PongoDb<PostgresConnector> = {\n connector: options.connector,\n databaseName,\n connect: () => Promise.resolve(),\n close: () => pool.close(),\n\n collections: () => [...collections.values()],\n collection: (collectionName) =>\n pongoCollection({\n collectionName,\n db,\n pool,\n sqlBuilder: postgresSQLBuilder(collectionName),\n schema: options.schema ? options.schema : {},\n errors: options.errors ? options.errors : {},\n }),\n transaction: () => pool.transaction(),\n withTransaction: (handle) => pool.withTransaction(handle),\n\n schema: {\n get component(): SchemaComponent {\n return schemaComponent('pongoDb', {\n components: [...collections.values()].map((c) => c.schema.component),\n });\n },\n migrate: () =>\n runPostgreSQLMigrations(\n pool,\n [...collections.values()].flatMap((c) =>\n // TODO: This needs to change to support more connectors\n c.schema.component.migrations({ connector: 'PostgreSQL:pg' }),\n ),\n ),\n },\n\n sql: {\n async query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<Result[]> {\n const result = await query<Result>(sql, options);\n return result.rows;\n },\n async command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<QueryResult<Result>> {\n return command(sql, options);\n },\n },\n };\n\n const dbsSchema = options?.schema?.definition?.dbs;\n\n if (dbsSchema) {\n const dbSchema = objectEntries(dbsSchema)\n .map((e) => e[1])\n .find((db) => db.name === dbName || db.name === databaseName);\n\n if (dbSchema) return proxyPongoDbWithSchema(db, dbSchema, collections);\n }\n\n return db;\n};\n\nexport const pongoDbSchemaComponent = (\n collections: string[] | SchemaComponent[],\n) => {\n const components =\n collections.length > 0 && typeof collections[0] === 'string'\n ? collections.map((collectionName) =>\n pongoCollectionSchemaComponent(collectionName as string),\n )\n : (collections as SchemaComponent[]);\n\n return schemaComponent('pongo:schema_component:db', {\n components,\n });\n};\n","export const QueryOperators = {\n $eq: '$eq',\n $gt: '$gt',\n $gte: '$gte',\n $lt: '$lt',\n $lte: '$lte',\n $ne: '$ne',\n $in: '$in',\n $nin: '$nin',\n $elemMatch: '$elemMatch',\n $all: '$all',\n $size: '$size',\n};\n\nexport const OperatorMap = {\n $gt: '>',\n $gte: '>=',\n $lt: '<',\n $lte: '<=',\n $ne: '!=',\n};\n\nexport const isOperator = (key: string) => key.startsWith('$');\n\nexport const hasOperators = (value: Record<string, unknown>) =>\n Object.keys(value).some(isOperator);\n","export const isNumber = (val: unknown): val is number =>\n typeof val === 'number' && val === val;\n\nexport const isString = (val: unknown): val is string =>\n typeof val === 'string';\n\nexport class PongoError extends Error {\n public errorCode: number;\n\n constructor(\n options?: { errorCode: number; message?: string } | string | number,\n ) {\n const errorCode =\n options && typeof options === 'object' && 'errorCode' in options\n ? options.errorCode\n : isNumber(options)\n ? options\n : 500;\n const message =\n options && typeof options === 'object' && 'message' in options\n ? options.message\n : isString(options)\n ? options\n : `Error with status code '${errorCode}' ocurred during Pongo processing`;\n\n super(message);\n this.errorCode = errorCode;\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, PongoError.prototype);\n }\n}\n\nexport class ConcurrencyError extends PongoError {\n constructor(message?: string) {\n super({\n errorCode: 412,\n message: message ?? `Expected document state does not match current one!`,\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, ConcurrencyError.prototype);\n }\n}\n","import { type MigrationStyle } from '@event-driven-io/dumbo';\nimport {\n NodePostgresConnectorType,\n type NodePostgresConnection,\n} from '@event-driven-io/dumbo/pg';\nimport pg from 'pg';\nimport type { PostgresDbClientOptions } from '../storage/postgresql';\nimport { getPongoDb, type AllowedDbClientOptions } from './pongoDb';\nimport { pongoSession } from './pongoSession';\nimport {\n proxyClientWithSchema,\n type PongoClientSchema,\n type PongoClientWithSchema,\n} from './schema';\nimport type { PongoClient, PongoDb, PongoSession } from './typing';\n\nexport type PooledPongoClientOptions =\n | {\n pool: pg.Pool;\n }\n | {\n pooled: true;\n }\n | {\n pool: pg.Pool;\n pooled: true;\n }\n | object;\n\nexport type NotPooledPongoOptions =\n | {\n client: pg.Client;\n }\n | {\n pooled: false;\n }\n | {\n client: pg.Client;\n pooled: false;\n }\n | {\n connection: NodePostgresConnection;\n pooled?: false;\n };\n\nexport type PongoClientOptions<\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n> = {\n schema?: { autoMigration?: MigrationStyle; definition?: TypedClientSchema };\n errors?: { throwOnOperationFailures?: boolean };\n connectionOptions?: PooledPongoClientOptions | NotPooledPongoOptions;\n};\n\nexport const pongoClient = <\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n connectionString: string,\n options: PongoClientOptions<TypedClientSchema> = {},\n): PongoClient & PongoClientWithSchema<TypedClientSchema> => {\n const dbClients = new Map<string, PongoDb>();\n\n const dbClient = getPongoDb<DbClientOptions>(\n clientToDbOptions({\n connectionString,\n clientOptions: options,\n }),\n );\n dbClients.set(dbClient.databaseName, dbClient);\n\n const pongoClient: PongoClient = {\n connect: async () => {\n await dbClient.connect();\n return pongoClient;\n },\n close: async () => {\n for (const db of dbClients.values()) {\n await db.close();\n }\n },\n db: (dbName?: string): PongoDb => {\n if (!dbName) return dbClient;\n\n return (\n dbClients.get(dbName) ??\n dbClients\n .set(\n dbName,\n getPongoDb<DbClientOptions>(\n clientToDbOptions({\n connectionString,\n dbName,\n clientOptions: options,\n }),\n ),\n )\n .get(dbName)!\n );\n },\n startSession: pongoSession,\n withSession: async <T>(\n callback: (session: PongoSession) => Promise<T>,\n ): Promise<T> => {\n const session = pongoSession();\n\n try {\n return await callback(session);\n } finally {\n await session.endSession();\n }\n },\n };\n\n return proxyClientWithSchema(pongoClient, options?.schema?.definition);\n};\n\nexport const clientToDbOptions = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(options: {\n connectionString: string;\n dbName?: string;\n clientOptions: PongoClientOptions;\n}): DbClientOptions => {\n const postgreSQLOptions: PostgresDbClientOptions = {\n connector: NodePostgresConnectorType,\n connectionString: options.connectionString,\n dbName: options.dbName,\n ...options.clientOptions,\n };\n\n return postgreSQLOptions as DbClientOptions;\n};\n","import type { ConnectorType } from '@event-driven-io/dumbo/src';\nimport {\n isPostgresClientOptions,\n postgresDb,\n type PostgresDbClientOptions,\n} from '../storage/postgresql';\nimport type { PongoClientOptions } from './pongoClient';\nimport type { PongoDb } from './typing';\n\nexport type PongoDbClientOptions<\n Connector extends ConnectorType = ConnectorType,\n> = {\n connector: Connector;\n connectionString: string;\n dbName: string | undefined;\n} & PongoClientOptions;\n\nexport type AllowedDbClientOptions = PostgresDbClientOptions;\n\nexport const getPongoDb = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n options: DbClientOptions,\n): PongoDb => {\n const { connector } = options;\n // This is the place where in the future could come resolution of other database types\n if (!isPostgresClientOptions(options))\n throw new Error(`Unsupported db type: ${connector}`);\n\n return postgresDb(options);\n};\n","import type { DatabaseTransaction } from '@event-driven-io/dumbo';\nimport type {\n PongoDb,\n PongoDbTransaction,\n PongoTransactionOptions,\n} from './typing';\n\nexport const pongoTransaction = (\n options: PongoTransactionOptions,\n): PongoDbTransaction => {\n let isCommitted = false;\n let isRolledBack = false;\n let databaseName: string | null = null;\n let transaction: DatabaseTransaction | null = null;\n\n return {\n enlistDatabase: async (db: PongoDb): Promise<DatabaseTransaction> => {\n if (transaction && databaseName !== db.databaseName)\n throw new Error(\n \"There's already other database assigned to transaction\",\n );\n\n if (transaction && databaseName === db.databaseName) return transaction;\n\n databaseName = db.databaseName;\n transaction = db.transaction();\n await transaction.begin();\n\n return transaction;\n },\n commit: async () => {\n if (!transaction) throw new Error('No database transaction started!');\n if (isCommitted) return;\n if (isRolledBack) throw new Error('Transaction is not active!');\n\n isCommitted = true;\n\n await transaction.commit();\n\n transaction = null;\n },\n rollback: async (error?: unknown) => {\n if (!transaction) throw new Error('No database transaction started!');\n if (isCommitted) throw new Error('Cannot rollback commited transaction!');\n if (isRolledBack) return;\n\n isRolledBack = true;\n\n await transaction.rollback(error);\n\n transaction = null;\n },\n databaseName,\n isStarting: false,\n isCommitted,\n get isActive() {\n return !isCommitted && !isRolledBack;\n },\n get sqlExecutor() {\n if (transaction === null)\n throw new Error('No database transaction was started');\n\n return transaction.execute;\n },\n options,\n };\n};\n","import { pongoTransaction } from './pongoTransaction';\nimport type {\n PongoDbTransaction,\n PongoSession,\n PongoTransactionOptions,\n} from './typing';\n\nexport type PongoSessionOptions = {\n explicit?: boolean;\n defaultTransactionOptions: PongoTransactionOptions;\n};\n\nconst isActive = (\n transaction: PongoDbTransaction | null,\n): transaction is PongoDbTransaction => transaction?.isActive === true;\n\nfunction assertInActiveTransaction(\n transaction: PongoDbTransaction | null,\n): asserts transaction is PongoDbTransaction {\n if (!isActive(transaction)) throw new Error('No active transaction exists!');\n}\n\nfunction assertNotInActiveTransaction(\n transaction: PongoDbTransaction | null,\n): asserts transaction is null {\n if (isActive(transaction))\n throw new Error('Active transaction already exists!');\n}\n\nexport const pongoSession = (options?: PongoSessionOptions): PongoSession => {\n const explicit = options?.explicit === true;\n const defaultTransactionOptions: PongoTransactionOptions =\n options?.defaultTransactionOptions ?? {\n get snapshotEnabled() {\n return false;\n },\n };\n\n let transaction: PongoDbTransaction | null = null;\n let hasEnded = false;\n\n const startTransaction = (options?: PongoTransactionOptions) => {\n assertNotInActiveTransaction(transaction);\n\n transaction = pongoTransaction(options ?? defaultTransactionOptions);\n };\n const commitTransaction = async () => {\n assertInActiveTransaction(transaction);\n\n await transaction.commit();\n };\n const abortTransaction = async () => {\n assertInActiveTransaction(transaction);\n\n await transaction.rollback();\n };\n\n const endSession = async (): Promise<void> => {\n if (hasEnded) return;\n hasEnded = true;\n\n if (isActive(transaction)) await transaction.rollback();\n };\n\n const session = {\n get hasEnded() {\n return hasEnded;\n },\n explicit,\n defaultTransactionOptions: defaultTransactionOptions ?? {\n get snapshotEnabled() {\n return false;\n },\n },\n get transaction() {\n return transaction;\n },\n get snapshotEnabled() {\n return defaultTransactionOptions.snapshotEnabled;\n },\n endSession,\n incrementTransactionNumber: () => {},\n inTransaction: () => isActive(transaction),\n startTransaction,\n commitTransaction,\n abortTransaction,\n withTransaction: async <T = unknown>(\n fn: (session: PongoSession) => Promise<T>,\n options?: PongoTransactionOptions,\n ): Promise<T> => {\n startTransaction(options);\n\n try {\n const result = await fn(session);\n await commitTransaction();\n return result;\n } catch (error) {\n await abortTransaction();\n throw error;\n }\n },\n };\n\n return session;\n};\n","type Entry<T> = {\n [K in keyof Required<T>]: [K, Required<T>[K]];\n}[keyof Required<T>];\n\ntype IterableEntry<T> = Entry<T> & {\n [Symbol.iterator](): Iterator<Entry<T>>;\n};\n\nexport const objectEntries = <T extends object>(obj: T): IterableEntry<T>[] =>\n Object.entries(obj).map(([key, value]) => [key as keyof T, value]);\n\nexport type NonPartial<T> = { [K in keyof Required<T>]: T[K] };\n","import {\n type ConnectorType,\n type DatabaseTransaction,\n type DatabaseTransactionFactory,\n JSONSerializer,\n type QueryResult,\n type QueryResultRow,\n type SchemaComponent,\n type SQL,\n type SQLExecutor,\n} from '@event-driven-io/dumbo';\nimport { v7 as uuid } from 'uuid';\nimport { ConcurrencyError } from '../errors';\n\nexport interface PongoClient {\n connect(): Promise<this>;\n\n close(): Promise<void>;\n\n db(dbName?: string): PongoDb;\n\n startSession(): PongoSession;\n\n withSession<T = unknown>(\n callback: (session: PongoSession) => Promise<T>,\n ): Promise<T>;\n}\n\nexport declare interface PongoTransactionOptions {\n get snapshotEnabled(): boolean;\n maxCommitTimeMS?: number;\n}\n\nexport interface PongoDbTransaction {\n get databaseName(): string | null;\n options: PongoTransactionOptions;\n enlistDatabase: (database: PongoDb) => Promise<DatabaseTransaction>;\n commit: () => Promise<void>;\n rollback: (error?: unknown) => Promise<void>;\n get sqlExecutor(): SQLExecutor;\n get isStarting(): boolean;\n get isActive(): boolean;\n get isCommitted(): boolean;\n}\n\nexport interface PongoSession {\n hasEnded: boolean;\n explicit: boolean;\n defaultTransactionOptions: PongoTransactionOptions;\n transaction: PongoDbTransaction | null;\n get snapshotEnabled(): boolean;\n\n endSession(): Promise<void>;\n incrementTransactionNumber(): void;\n inTransaction(): boolean;\n startTransaction(options?: PongoTransactionOptions): void;\n commitTransaction(): Promise<void>;\n abortTransaction(): Promise<void>;\n withTransaction<T = unknown>(\n fn: (session: PongoSession) => Promise<T>,\n options?: PongoTransactionOptions,\n ): Promise<T>;\n}\n\nexport interface PongoDb<Connector extends ConnectorType = ConnectorType>\n extends DatabaseTransactionFactory<Connector> {\n get connector(): Connector;\n get databaseName(): string;\n connect(): Promise<void>;\n close(): Promise<void>;\n collection<T extends PongoDocument>(name: string): PongoCollection<T>;\n collections(): ReadonlyArray<PongoCollection<PongoDocument>>;\n readonly schema: Readonly<{\n component: SchemaComponent;\n migrate(): Promise<void>;\n }>;\n sql: {\n query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<Result[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<QueryResult<Result>>;\n };\n}\n\nexport type CollectionOperationOptions = {\n session?: PongoSession;\n};\n\nexport type InsertOneOptions = {\n expectedVersion?: Extract<\n ExpectedDocumentVersion,\n 'DOCUMENT_DOES_NOT_EXIST' | 'NO_CONCURRENCY_CHECK'\n >;\n} & CollectionOperationOptions;\n\nexport type InsertManyOptions = {\n expectedVersion?: Extract<\n ExpectedDocumentVersion,\n 'DOCUMENT_DOES_NOT_EXIST' | 'NO_CONCURRENCY_CHECK'\n >;\n} & CollectionOperationOptions;\n\nexport type UpdateOneOptions = {\n expectedVersion?: Exclude<ExpectedDocumentVersion, 'DOCUMENT_DOES_NOT_EXIST'>;\n} & CollectionOperationOptions;\n\nexport type UpdateManyOptions = {\n expectedVersion?: Extract<\n ExpectedDocumentVersion,\n 'DOCUMENT_EXISTS' | 'NO_CONCURRENCY_CHECK'\n >;\n} & CollectionOperationOptions;\n\nexport type HandleOptions = {\n expectedVersion?: ExpectedDocumentVersion;\n} & CollectionOperationOptions;\n\nexport type ReplaceOneOptions = {\n expectedVersion?: Exclude<ExpectedDocumentVersion, 'DOCUMENT_DOES_NOT_EXIST'>;\n} & CollectionOperationOptions;\n\nexport type DeleteOneOptions = {\n expectedVersion?: Exclude<ExpectedDocumentVersion, 'DOCUMENT_DOES_NOT_EXIST'>;\n} & CollectionOperationOptions;\n\nexport type DeleteManyOptions = {\n expectedVersion?: Extract<\n ExpectedDocumentVersion,\n 'DOCUMENT_EXISTS' | 'NO_CONCURRENCY_CHECK'\n >;\n} & CollectionOperationOptions;\n\nexport interface PongoCollection<T extends PongoDocument> {\n readonly dbName: string;\n readonly collectionName: string;\n createCollection(options?: CollectionOperationOptions): Promise<void>;\n insertOne(\n document: OptionalUnlessRequiredId<T>,\n options?: InsertOneOptions,\n ): Promise<PongoInsertOneResult>;\n insertMany(\n documents: OptionalUnlessRequiredId<T>[],\n options?: CollectionOperationOptions,\n ): Promise<PongoInsertManyResult>;\n updateOne(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n options?: UpdateOneOptions,\n ): Promise<PongoUpdateResult>;\n replaceOne(\n filter: PongoFilter<T> | SQL,\n document: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): Promise<PongoUpdateResult>;\n updateMany(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n options?: UpdateManyOptions,\n ): Promise<PongoUpdateManyResult>;\n deleteOne(\n filter?: PongoFilter<T> | SQL,\n options?: DeleteOneOptions,\n ): Promise<PongoDeleteResult>;\n deleteMany(\n filter?: PongoFilter<T> | SQL,\n options?: DeleteManyOptions,\n ): Promise<PongoDeleteResult>;\n findOne(\n filter?: PongoFilter<T> | SQL,\n options?: CollectionOperationOptions,\n ): Promise<WithIdAndVersion<T> | null>;\n find(\n filter?: PongoFilter<T> | SQL,\n options?: CollectionOperationOptions,\n ): Promise<WithIdAndVersion<T>[]>;\n findOneAndDelete(\n filter: PongoFilter<T> | SQL,\n options?: DeleteOneOptions,\n ): Promise<WithIdAndVersion<T> | null>;\n findOneAndReplace(\n filter: PongoFilter<T> | SQL,\n replacement: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): Promise<WithIdAndVersion<T> | null>;\n findOneAndUpdate(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n options?: UpdateOneOptions,\n ): Promise<WithIdAndVersion<T> | null>;\n countDocuments(\n filter?: PongoFilter<T> | SQL,\n options?: CollectionOperationOptions,\n ): Promise<number>;\n drop(options?: CollectionOperationOptions): Promise<boolean>;\n rename(\n newName: string,\n options?: CollectionOperationOptions,\n ): Promise<PongoCollection<T>>;\n handle(\n id: string,\n handle: DocumentHandler<T>,\n options?: HandleOptions,\n ): Promise<PongoHandleResult<T>>;\n readonly schema: Readonly<{\n component: SchemaComponent;\n migrate(): Promise<void>;\n }>;\n sql: {\n query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<Result[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<QueryResult<Result>>;\n };\n}\n\nexport type ObjectId = string & { __brandId: 'ObjectId' };\nexport const ObjectId = (value?: string) => value ?? uuid();\n\nexport type HasId = { _id: string };\n\nexport declare type InferIdType<TSchema> = TSchema extends {\n _id: infer IdType;\n}\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Record<any, never> extends IdType\n ? never\n : IdType\n : TSchema extends {\n _id?: infer IdType;\n }\n ? unknown extends IdType\n ? ObjectId\n : IdType\n : ObjectId;\n\n/** TypeScript Omit (Exclude to be specific) does not work for objects with an \"any\" indexed type, and breaks discriminated unions @public */\nexport declare type EnhancedOmit<TRecordOrUnion, KeyUnion> =\n string extends keyof TRecordOrUnion\n ? TRecordOrUnion\n : // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TRecordOrUnion extends any\n ? Pick<TRecordOrUnion, Exclude<keyof TRecordOrUnion, KeyUnion>>\n : never;\n\nexport declare type OptionalUnlessRequiredId<TSchema> = TSchema extends {\n _id: string | ObjectId;\n}\n ? TSchema\n : OptionalId<TSchema>;\n\nexport declare type OptionalUnlessRequiredVersion<TSchema> = TSchema extends {\n _version: bigint;\n}\n ? TSchema\n : OptionalVersion<TSchema>;\n\nexport declare type OptionalUnlessRequiredIdAndVersion<TSchema> =\n OptionalUnlessRequiredId<TSchema> & OptionalUnlessRequiredVersion<TSchema>;\n\nexport declare type WithId<TSchema> = EnhancedOmit<TSchema, '_id'> & {\n _id: string | ObjectId;\n};\nexport type WithoutId<T> = Omit<T, '_id'>;\n\nexport declare type WithVersion<TSchema> = EnhancedOmit<TSchema, '_version'> & {\n _version: bigint;\n};\nexport type WithoutVersion<T> = Omit<T, '_version'>;\n\nexport type WithIdAndVersion<T> = WithId<WithVersion<T>>;\nexport type WithoutIdAndVersion<T> = WithoutId<WithoutVersion<T>>;\n\n/** @public */\nexport declare type RegExpOrString<T> = T extends string ? RegExp | T : T;\n\nexport declare interface Document {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n}\n\nexport declare type OptionalId<TSchema> = EnhancedOmit<TSchema, '_id'> & {\n _id?: string | ObjectId;\n};\nexport declare type OptionalVersion<TSchema> = EnhancedOmit<\n TSchema,\n '_version'\n> & {\n _version?: bigint;\n};\n\nexport declare interface ObjectIdLike {\n __id?: string | ObjectId;\n}\n\nexport declare type NonObjectIdLikeDocument = {\n [key in keyof ObjectIdLike]?: never;\n} & Document;\n\nexport declare type AlternativeType<T> =\n T extends ReadonlyArray<infer U> ? T | RegExpOrString<U> : RegExpOrString<T>;\n\nexport declare type Condition<T> =\n | AlternativeType<T>\n | PongoFilterOperator<AlternativeType<T>>;\n\nexport declare type PongoFilter<TSchema> =\n | {\n [P in keyof WithId<TSchema>]?: Condition<WithId<TSchema>[P]>;\n }\n | HasId; // TODO: & RootFilterOperators<WithId<TSchema>>;\n\nexport declare interface RootFilterOperators<TSchema> extends Document {\n $and?: PongoFilter<TSchema>[];\n $nor?: PongoFilter<TSchema>[];\n $or?: PongoFilter<TSchema>[];\n $text?: {\n $search: string;\n $language?: string;\n $caseSensitive?: boolean;\n $diacriticSensitive?: boolean;\n };\n $where?: string | ((this: TSchema) => boolean);\n $comment?: string | Document;\n}\n\nexport declare interface PongoFilterOperator<TValue>\n extends NonObjectIdLikeDocument {\n $eq?: TValue;\n $gt?: TValue;\n $gte?: TValue;\n $lt?: TValue;\n $lte?: TValue;\n $ne?: TValue;\n $in?: TValue[];\n $nin?: TValue[];\n // $eq?: TValue;\n // $gt?: TValue;\n // $gte?: TValue;\n // $in?: ReadonlyArray<TValue>;\n // $lt?: TValue;\n // $lte?: TValue;\n // $ne?: TValue;\n // $nin?: ReadonlyArray<TValue>;\n // $not?: TValue extends string ? FilterOperators<TValue> | RegExp : FilterOperators<TValue>;\n // /**\n // * When `true`, `$exists` matches the documents that contain the field,\n // * including documents where the field value is null.\n // */\n // $exists?: boolean;\n // $type?: BSONType | BSONTypeAlias;\n // $expr?: Record<string, any>;\n // $jsonSchema?: Record<string, any>;\n // $mod?: TValue extends number ? [number, number] : never;\n // $regex?: TValue extends string ? RegExp | BSONRegExp | string : never;\n // $options?: TValue extends string ? string : never;\n // $geoIntersects?: {\n // $geometry: Document;\n // };\n // $geoWithin?: Document;\n // $near?: Document;\n // $nearSphere?: Document;\n // $maxDistance?: number;\n // $all?: ReadonlyArray<any>;\n // $elemMatch?: Document;\n // $size?: TValue extends ReadonlyArray<any> ? number : never;\n // $bitsAllClear?: BitwiseFilter;\n // $bitsAllSet?: BitwiseFilter;\n // $bitsAnyClear?: BitwiseFilter;\n // $bitsAnySet?: BitwiseFilter;\n // $rand?: Record<string, never>;\n}\n\nexport type $set<T> = Partial<T>;\nexport type $unset<T> = { [P in keyof T]?: '' };\nexport type $inc<T> = { [P in keyof T]?: number | bigint };\nexport type $push<T> = { [P in keyof T]?: T[P] };\n\nexport type ExpectedDocumentVersionGeneral =\n | 'DOCUMENT_EXISTS'\n | 'DOCUMENT_DOES_NOT_EXIST'\n | 'NO_CONCURRENCY_CHECK';\n\nexport type ExpectedDocumentVersionValue = bigint & { __brand: 'sql' };\n\nexport type ExpectedDocumentVersion =\n | (bigint & { __brand: 'sql' })\n | bigint\n | ExpectedDocumentVersionGeneral;\n\nexport const DOCUMENT_EXISTS =\n 'DOCUMENT_EXISTS' as ExpectedDocumentVersionGeneral;\nexport const DOCUMENT_DOES_NOT_EXIST =\n 'DOCUMENT_DOES_NOT_EXIST' as ExpectedDocumentVersionGeneral;\nexport const NO_CONCURRENCY_CHECK =\n 'NO_CONCURRENCY_CHECK' as ExpectedDocumentVersionGeneral;\n\nexport const isGeneralExpectedDocumentVersion = (\n version: ExpectedDocumentVersion,\n): version is ExpectedDocumentVersionGeneral =>\n version === 'DOCUMENT_DOES_NOT_EXIST' ||\n version === 'DOCUMENT_EXISTS' ||\n version === 'NO_CONCURRENCY_CHECK';\n\nexport const expectedVersionValue = (\n version: ExpectedDocumentVersion | undefined,\n): ExpectedDocumentVersionValue | null =>\n version === undefined || isGeneralExpectedDocumentVersion(version)\n ? null\n : (version as ExpectedDocumentVersionValue);\n\nexport const expectedVersion = (\n version: number | bigint | string | undefined | null,\n): ExpectedDocumentVersion => {\n return version\n ? (BigInt(version) as ExpectedDocumentVersion)\n : NO_CONCURRENCY_CHECK;\n};\n\nexport type PongoUpdate<T> = {\n $set?: Partial<T>;\n $unset?: $unset<T>;\n $inc?: $inc<T>;\n $push?: $push<T>;\n};\n\nexport type OperationResult = {\n acknowledged: boolean;\n successful: boolean;\n\n assertSuccessful: (errorMessage?: string) => void;\n};\n\nexport const operationResult = <T extends OperationResult>(\n result: Omit<T, 'assertSuccess' | 'acknowledged' | 'assertSuccessful'>,\n options: {\n operationName: string;\n collectionName: string;\n errors?: { throwOnOperationFailures?: boolean } | undefined;\n },\n): T => {\n const operationResult: T = {\n ...result,\n acknowledged: true,\n successful: result.successful,\n assertSuccessful: (errorMessage?: string) => {\n const { successful } = result;\n const { operationName, collectionName } = options;\n\n if (!successful)\n throw new ConcurrencyError(\n errorMessage ??\n `${operationName} on ${collectionName} failed. Expected document state does not match current one! Result: ${JSONSerializer.serialize(result)}!`,\n );\n },\n } as T;\n\n if (options.errors?.throwOnOperationFailures)\n operationResult.assertSuccessful();\n\n return operationResult;\n};\n\nexport interface PongoInsertOneResult extends OperationResult {\n insertedId: string | null;\n nextExpectedVersion: bigint;\n}\n\nexport interface PongoInsertManyResult extends OperationResult {\n insertedIds: string[];\n insertedCount: number;\n}\n\nexport interface PongoUpdateResult extends OperationResult {\n matchedCount: number;\n modifiedCount: number;\n nextExpectedVersion: bigint;\n}\n\nexport interface PongoUpdateManyResult extends OperationResult {\n matchedCount: number;\n modifiedCount: number;\n}\n\nexport interface PongoDeleteResult extends OperationResult {\n matchedCount: number;\n deletedCount: number;\n}\n\nexport interface PongoDeleteManyResult extends OperationResult {\n deletedCount: number;\n}\n\nexport type PongoHandleResult<T> =\n | (PongoInsertOneResult & { document: T })\n | (PongoUpdateResult & { document: T })\n | (PongoDeleteResult & { document: null })\n | (OperationResult & { document: null });\n\nexport type PongoDocument = Record<string, unknown>;\n\nexport type DocumentHandler<T extends PongoDocument> =\n | ((document: T | null) => T | null)\n | ((document: T | null) => Promise<T | null>);\n","import type { ConnectorType } from '@event-driven-io/dumbo/src';\nimport {\n type Document,\n type PongoClient,\n type PongoCollection,\n type PongoDb,\n type PongoDocument,\n objectEntries,\n} from '../typing';\n\nexport interface PongoCollectionSchema<\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n T extends PongoDocument = PongoDocument,\n> {\n name: string;\n}\n\n// Database schema interface\nexport interface PongoDbSchema<\n T extends Record<string, PongoCollectionSchema> = Record<\n string,\n PongoCollectionSchema\n >,\n> {\n name?: string;\n collections: T;\n}\n\nexport interface PongoClientSchema<\n T extends Record<string, PongoDbSchema> = Record<string, PongoDbSchema>,\n> {\n dbs: T;\n}\n\nexport type CollectionsMap<T extends Record<string, PongoCollectionSchema>> = {\n [K in keyof T]: PongoCollection<\n T[K] extends PongoCollectionSchema<infer U> ? U : PongoDocument\n >;\n};\n\nexport type PongoDbWithSchema<\n T extends Record<string, PongoCollectionSchema>,\n Connector extends ConnectorType = ConnectorType,\n> = CollectionsMap<T> & PongoDb<Connector>;\n\nexport type DBsMap<\n T extends Record<string, PongoDbSchema>,\n Connector extends ConnectorType = ConnectorType,\n> = {\n [K in keyof T]: CollectionsMap<T[K]['collections']> & PongoDb<Connector>;\n};\n\nexport type PongoClientWithSchema<\n T extends PongoClientSchema,\n Connector extends ConnectorType = ConnectorType,\n> = DBsMap<T['dbs'], Connector> & PongoClient;\n\nconst pongoCollectionSchema = <T extends PongoDocument>(\n name: string,\n): PongoCollectionSchema<T> => ({\n name,\n});\n\nfunction pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(\n collections: T,\n): PongoDbSchema<T>;\nfunction pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(\n name: string,\n collections: T,\n): PongoDbSchema<T>;\nfunction pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(\n nameOrCollections: string | T,\n collections?: T,\n): PongoDbSchema<T> {\n if (collections === undefined) {\n if (typeof nameOrCollections === 'string') {\n throw new Error('You need to provide colleciton definition');\n }\n return {\n collections: nameOrCollections,\n };\n }\n\n return nameOrCollections && typeof nameOrCollections === 'string'\n ? {\n name: nameOrCollections,\n collections,\n }\n : { collections: collections };\n}\n\nconst pongoClientSchema = <T extends Record<string, PongoDbSchema>>(\n dbs: T,\n): PongoClientSchema<T> => ({\n dbs,\n});\n\nexport const pongoSchema = {\n client: pongoClientSchema,\n db: pongoDbSchema,\n collection: pongoCollectionSchema,\n};\n\n// Factory function to create DB instances\nexport const proxyPongoDbWithSchema = <\n T extends Record<string, PongoCollectionSchema>,\n Connector extends ConnectorType = ConnectorType,\n>(\n pongoDb: PongoDb<Connector>,\n dbSchema: PongoDbSchema<T>,\n collections: Map<string, PongoCollection<Document>>,\n): PongoDbWithSchema<T, Connector> => {\n const collectionNames = Object.keys(dbSchema.collections);\n\n for (const collectionName of collectionNames) {\n collections.set(collectionName, pongoDb.collection(collectionName));\n }\n\n return new Proxy(\n pongoDb as PongoDb<Connector> & {\n [key: string]: unknown;\n },\n {\n get(target, prop: string) {\n return collections.get(prop) ?? target[prop];\n },\n },\n ) as PongoDbWithSchema<T, Connector>;\n};\n\nexport const proxyClientWithSchema = <\n TypedClientSchema extends PongoClientSchema,\n>(\n client: PongoClient,\n schema: TypedClientSchema | undefined,\n): PongoClientWithSchema<TypedClientSchema> => {\n if (!schema) return client as PongoClientWithSchema<TypedClientSchema>;\n\n const dbNames = Object.keys(schema.dbs);\n\n return new Proxy(\n client as PongoClient & {\n [key: string]: unknown;\n },\n {\n get(target, prop: string) {\n if (dbNames.includes(prop)) return client.db(schema.dbs[prop]?.name);\n\n return target[prop];\n },\n },\n ) as PongoClientWithSchema<TypedClientSchema>;\n};\n\nexport type PongoCollectionSchemaMetadata = {\n name: string;\n};\n\nexport type PongoDbSchemaMetadata = {\n name?: string | undefined;\n collections: PongoCollectionSchemaMetadata[];\n};\n\nexport type PongoClientSchemaMetadata = {\n databases: PongoDbSchemaMetadata[];\n database: (name?: string) => PongoDbSchemaMetadata | undefined;\n};\n\nexport const toDbSchemaMetadata = <TypedDbSchema extends PongoDbSchema>(\n schema: TypedDbSchema,\n): PongoDbSchemaMetadata => ({\n name: schema.name,\n collections: objectEntries(schema.collections).map((c) => ({\n name: c[1].name,\n })),\n});\n\nexport const toClientSchemaMetadata = <\n TypedClientSchema extends PongoClientSchema,\n>(\n schema: TypedClientSchema,\n): PongoClientSchemaMetadata => {\n const databases = objectEntries(schema.dbs).map((e) =>\n toDbSchemaMetadata(e[1]),\n );\n\n return {\n databases,\n database: (name) => databases.find((db) => db.name === name),\n };\n};\n\nexport interface PongoSchemaConfig<\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n> {\n schema: TypedClientSchema;\n}\n","export const deepEquals = <T>(left: T, right: T): boolean => {\n if (isEquatable(left)) {\n return left.equals(right);\n }\n\n if (Array.isArray(left)) {\n return (\n Array.isArray(right) &&\n left.length === right.length &&\n left.every((val, index) => deepEquals(val, right[index]))\n );\n }\n\n if (\n typeof left !== 'object' ||\n typeof right !== 'object' ||\n left === null ||\n right === null\n ) {\n return left === right;\n }\n\n if (Array.isArray(right)) return false;\n\n const keys1 = Object.keys(left);\n const keys2 = Object.keys(right);\n\n if (\n keys1.length !== keys2.length ||\n !keys1.every((key) => keys2.includes(key))\n )\n return false;\n\n for (const key in left) {\n if (left[key] instanceof Function && right[key] instanceof Function)\n continue;\n\n const isEqual = deepEquals(left[key], right[key]);\n if (!isEqual) {\n return false;\n }\n }\n\n return true;\n};\n\nexport type Equatable<T> = { equals: (right: T) => boolean } & T;\n\nexport const isEquatable = <T>(left: T): left is Equatable<T> => {\n return (\n left &&\n typeof left === 'object' &&\n 'equals' in left &&\n typeof left['equals'] === 'function'\n );\n};\n","import { JSONSerializer, sql } from '@event-driven-io/dumbo';\nimport { objectEntries, OperatorMap } from '../../../../core';\n\nexport const handleOperator = (\n path: string,\n operator: string,\n value: unknown,\n): string => {\n if (path === '_id' || path === '_version') {\n return handleMetadataOperator(path, operator, value);\n }\n\n switch (operator) {\n case '$eq':\n return sql(\n `(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))`,\n JSONSerializer.serialize(buildNestedObject(path, value)),\n path,\n JSONSerializer.serialize(value),\n );\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return sql(\n `data #>> %L ${OperatorMap[operator]} %L`,\n `{${path.split('.').join(',')}}`,\n value,\n );\n case '$in':\n return sql(\n 'data #>> %L IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n case '$nin':\n return sql(\n 'data #>> %L NOT IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n case '$elemMatch': {\n const subQuery = objectEntries(value as Record<string, unknown>)\n .map(([subKey, subValue]) =>\n sql(`@.\"%s\" == %s`, subKey, JSONSerializer.serialize(subValue)),\n )\n .join(' && ');\n return sql(`jsonb_path_exists(data, '$.%s[*] ? (%s)')`, path, subQuery);\n }\n case '$all':\n return sql(\n 'data @> %L::jsonb',\n JSONSerializer.serialize(buildNestedObject(path, value)),\n );\n case '$size':\n return sql(\n 'jsonb_array_length(data #> %L) = %L',\n `{${path.split('.').join(',')}}`,\n value,\n );\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst handleMetadataOperator = (\n fieldName: string,\n operator: string,\n value: unknown,\n): string => {\n switch (operator) {\n case '$eq':\n return sql(`${fieldName} = %L`, value);\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return sql(`${fieldName} ${OperatorMap[operator]} %L`, value);\n case '$in':\n return sql(\n `${fieldName} IN (%s)`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n case '$nin':\n return sql(\n `${fieldName} NOT IN (%s)`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst buildNestedObject = (\n path: string,\n value: unknown,\n): Record<string, unknown> =>\n path\n .split('.')\n .reverse()\n .reduce((acc, key) => ({ [key]: acc }), value as Record<string, unknown>);\n","import {\n hasOperators,\n objectEntries,\n QueryOperators,\n type PongoFilter,\n} from '../../../../core';\nimport { handleOperator } from './queryOperators';\n\nexport * from './queryOperators';\n\nconst AND = 'AND';\n\nexport const constructFilterQuery = <T>(filter: PongoFilter<T>): string =>\n Object.entries(filter)\n .map(([key, value]) =>\n isRecord(value)\n ? constructComplexFilterQuery(key, value)\n : handleOperator(key, '$eq', value),\n )\n .join(` ${AND} `);\n\nconst constructComplexFilterQuery = (\n key: string,\n value: Record<string, unknown>,\n): string => {\n const isEquality = !hasOperators(value);\n\n return objectEntries(value)\n .map(\n ([nestedKey, val]) =>\n isEquality\n ? handleOperator(`${key}.${nestedKey}`, QueryOperators.$eq, val) // regular value\n : handleOperator(key, nestedKey, val), // operator\n )\n .join(` ${AND} `);\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n","import { JSONSerializer, sql, type SQL } from '@event-driven-io/dumbo';\nimport {\n objectEntries,\n type $inc,\n type $push,\n type $set,\n type $unset,\n type PongoUpdate,\n} from '../../../../core';\n\nexport const buildUpdateQuery = <T>(update: PongoUpdate<T>): SQL =>\n objectEntries(update).reduce((currentUpdateQuery, [op, value]) => {\n switch (op) {\n case '$set':\n return buildSetQuery(value, currentUpdateQuery);\n case '$unset':\n return buildUnsetQuery(value, currentUpdateQuery);\n case '$inc':\n return buildIncQuery(value, currentUpdateQuery);\n case '$push':\n return buildPushQuery(value, currentUpdateQuery);\n default:\n return currentUpdateQuery;\n }\n }, sql('data'));\n\nexport const buildSetQuery = <T>(set: $set<T>, currentUpdateQuery: SQL): SQL =>\n sql('%s || %L::jsonb', currentUpdateQuery, JSONSerializer.serialize(set));\n\nexport const buildUnsetQuery = <T>(\n unset: $unset<T>,\n currentUpdateQuery: SQL,\n): SQL =>\n sql(\n '%s - %L',\n currentUpdateQuery,\n Object.keys(unset)\n .map((k) => `{${k}}`)\n .join(', '),\n );\n\nexport const buildIncQuery = <T>(\n inc: $inc<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(inc)) {\n currentUpdateQuery = sql(\n typeof value === 'bigint'\n ? \"jsonb_set(%s, '{%s}', to_jsonb((COALESCE((data->>'%s')::BIGINT, 0) + %L)::TEXT), true)\"\n : \"jsonb_set(%s, '{%s}', to_jsonb(COALESCE((data->>'%s')::NUMERIC, 0) + %L), true)\",\n currentUpdateQuery,\n key,\n key,\n value,\n );\n }\n return currentUpdateQuery;\n};\n\nexport const buildPushQuery = <T>(\n push: $push<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(push)) {\n currentUpdateQuery = sql(\n \"jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)\",\n currentUpdateQuery,\n key,\n key,\n JSONSerializer.serialize([value]),\n );\n }\n return currentUpdateQuery;\n};\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA,kBAAAA;AAAA,EACA;AAAA,EACA,OAAAC;AAAA,EACA;AAAA,OAGK;;;ACRP;AAAA,EACE,mBAAAC;AAAA,EACA;AAAA,OAWK;AACP,SAAS,2BAAAC,gCAA+B;AACxC,SAAS,MAAM,YAAY;;;ACf3B;AAAA,EACE;AAAA,OAKK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAiBA,IAAM,0BAA0B,CACrC,YAEA,QAAQ,cAAc;AAEjB,IAAM,aAAa,CACxB,YAC+B;AAC/B,QAAM,EAAE,kBAAkB,OAAO,IAAI;AACrC,QAAM,eAAe,UAAU,yBAAyB,gBAAgB;AA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EAAE;","names":["JSONSerializer","sql","schemaComponent","runPostgreSQLMigrations","sql","options","db","sql","createCollection","expectedVersion","schemaComponent","runPostgreSQLMigrations","NodePostgresConnectorType","options","uuid","uuid","operationResult","pongoClient","NodePostgresConnectorType","JSONSerializer","JSONSerializer","JSONSerializer","sql","sql","JSONSerializer","sql","JSONSerializer","expectedVersion"]}
package/dist/cli.cjs CHANGED
@@ -5,7 +5,7 @@
5
5
 
6
6
 
7
7
 
8
- var _chunkLNVXUDQHcjs = require('./chunk-LNVXUDQH.cjs');
8
+ var _chunkATI5CCCTcjs = require('./chunk-ATI5CCCT.cjs');
9
9
 
10
10
  // src/cli.ts
11
11
  var _commander = require('commander');
@@ -92,7 +92,7 @@ var parseDefaultDbSchema = (imported) => {
92
92
  if (!imported.default.schema.dbs) {
93
93
  return missingDbs;
94
94
  }
95
- const dbs = _chunkLNVXUDQHcjs.objectEntries.call(void 0, imported.default.schema.dbs).map((db) => db[1]);
95
+ const dbs = _chunkATI5CCCTcjs.objectEntries.call(void 0, imported.default.schema.dbs).map((db) => db[1]);
96
96
  const defaultDb = dbs.find((db) => db.name === void 0);
97
97
  if (!defaultDb) {
98
98
  return missingDefaultDb;
@@ -100,11 +100,11 @@ var parseDefaultDbSchema = (imported) => {
100
100
  if (!defaultDb.collections) {
101
101
  return missingCollections;
102
102
  }
103
- const collections = _chunkLNVXUDQHcjs.objectEntries.call(void 0, defaultDb.collections).map((col) => col[1]);
103
+ const collections = _chunkATI5CCCTcjs.objectEntries.call(void 0, defaultDb.collections).map((col) => col[1]);
104
104
  if (collections.length === 0) {
105
105
  return missingCollections;
106
106
  }
107
- return _chunkLNVXUDQHcjs.toDbSchemaMetadata.call(void 0, defaultDb);
107
+ return _chunkATI5CCCTcjs.toDbSchemaMetadata.call(void 0, defaultDb);
108
108
  };
109
109
  var configCommand = new (0, _commander.Command)("config").description(
110
110
  "Manage Pongo configuration"
@@ -141,12 +141,12 @@ configCommand.command("sample").description("Generate or print sample configurat
141
141
  });
142
142
 
143
143
  // src/commandLine/migrate.ts
144
+ var _dumbo = require('@event-driven-io/dumbo');
144
145
 
145
146
 
146
147
 
147
148
 
148
-
149
- var _dumbo = require('@event-driven-io/dumbo');
149
+ var _pg = require('@event-driven-io/dumbo/pg');
150
150
 
151
151
  var migrateCommand = new (0, _commander.Command)("migrate").description(
152
152
  "Manage database migrations"
@@ -182,14 +182,14 @@ migrateCommand.command("run").description("Run database migrations").option(
182
182
  );
183
183
  process.exit(1);
184
184
  }
185
- const pool = _dumbo.dumbo.call(void 0, { connectionString });
185
+ const pool = _pg.dumbo.call(void 0, { connectionString });
186
186
  const migrations = collectionNames.flatMap(
187
- (collectionsName) => _chunkLNVXUDQHcjs.pongoCollectionSchemaComponent.call(void 0, collectionsName).migrations({
187
+ (collectionsName) => _chunkATI5CCCTcjs.pongoCollectionSchemaComponent.call(void 0, collectionsName).migrations({
188
188
  connector: "PostgreSQL:pg"
189
189
  // TODO: Provide connector here
190
190
  })
191
191
  );
192
- await _dumbo.runPostgreSQLMigrations.call(void 0, pool, migrations, {
192
+ await _pg.runPostgreSQLMigrations.call(void 0, pool, migrations, {
193
193
  dryRun
194
194
  });
195
195
  });
@@ -214,13 +214,13 @@ migrateCommand.command("sql").description("Generate SQL for database migration")
214
214
  );
215
215
  process.exit(1);
216
216
  }
217
- const coreMigrations = _dumbo.migrationTableSchemaComponent.migrations({
217
+ const coreMigrations = _pg.migrationTableSchemaComponent.migrations({
218
218
  connector: "PostgreSQL:pg"
219
219
  });
220
220
  const migrations = [
221
221
  ...coreMigrations,
222
222
  ...collectionNames.flatMap(
223
- (collectionName) => _chunkLNVXUDQHcjs.pongoCollectionSchemaComponent.call(void 0, collectionName).migrations({
223
+ (collectionName) => _chunkATI5CCCTcjs.pongoCollectionSchemaComponent.call(void 0, collectionName).migrations({
224
224
  connector: "PostgreSQL:pg"
225
225
  // TODO: Provide connector here
226
226
  })
@@ -310,7 +310,7 @@ var prettifyLogs = (logLevel) => {
310
310
  var startRepl = async (options) => {
311
311
  setLogLevel(_nullishCoalesce(process.env.DUMBO_LOG_LEVEL, () => ( options.logging.logLevel)));
312
312
  setLogStyle(_nullishCoalesce(process.env.DUMBO_LOG_STYLE, () => ( options.logging.logStyle)));
313
- console.log(_dumbo.color.green("Starting Pongo Shell (version: 0.17.0-alpha.1)"));
313
+ console.log(_dumbo.color.green("Starting Pongo Shell (version: 0.17.0-alpha.3)"));
314
314
  if (options.logging.printOptions) {
315
315
  console.log(_dumbo.color.green("With Options:"));
316
316
  console.log(_dumbo.prettyJson.call(void 0, options));
@@ -323,7 +323,7 @@ var startRepl = async (options) => {
323
323
  )
324
324
  );
325
325
  }
326
- const connectionCheck = await _dumbo.checkConnection.call(void 0, connectionString);
326
+ const connectionCheck = await _pg.checkConnection.call(void 0, connectionString);
327
327
  if (!connectionCheck.successful) {
328
328
  if (connectionCheck.errorType === "ConnectionRefused") {
329
329
  console.error(
@@ -355,12 +355,12 @@ var startRepl = async (options) => {
355
355
  if (options.schema.collections.length > 0) {
356
356
  const collectionsSchema = {};
357
357
  for (const collectionName of options.schema.collections) {
358
- collectionsSchema[collectionName] = _chunkLNVXUDQHcjs.pongoSchema.collection(collectionName);
358
+ collectionsSchema[collectionName] = _chunkATI5CCCTcjs.pongoSchema.collection(collectionName);
359
359
  }
360
- const schema = _chunkLNVXUDQHcjs.pongoSchema.client({
361
- database: _chunkLNVXUDQHcjs.pongoSchema.db(options.schema.database, collectionsSchema)
360
+ const schema = _chunkATI5CCCTcjs.pongoSchema.client({
361
+ database: _chunkATI5CCCTcjs.pongoSchema.db(options.schema.database, collectionsSchema)
362
362
  });
363
- const typedClient = _chunkLNVXUDQHcjs.pongoClient.call(void 0, connectionString, {
363
+ const typedClient = _chunkATI5CCCTcjs.pongoClient.call(void 0, connectionString, {
364
364
  schema: {
365
365
  definition: schema,
366
366
  autoMigration: options.schema.autoMigration
@@ -372,7 +372,7 @@ var startRepl = async (options) => {
372
372
  }
373
373
  pongo = typedClient;
374
374
  } else {
375
- pongo = _chunkLNVXUDQHcjs.pongoClient.call(void 0, connectionString, {
375
+ pongo = _chunkATI5CCCTcjs.pongoClient.call(void 0, connectionString, {
376
376
  schema: { autoMigration: options.schema.autoMigration }
377
377
  });
378
378
  db = pongo.db(options.schema.database);
package/dist/cli.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/cli.cjs","../src/cli.ts","../src/commandLine/configFile.ts","../src/commandLine/migrate.ts","../src/commandLine/shell.ts"],"names":[],"mappings":"AAAA;AACA;AACE;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACRA,sCAAwB;ADUxB;AACA;AEZA;AACA,gEAAe;AAQf,IAAM,eAAA,EAAiB,CAAC,KAAA,EAAA,GAA0B;AAChD,EAAA,GAAA,CAAI,KAAA,CAAM,OAAA,IAAW,CAAA,EAAG;AACtB,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,IAAI,UAAA,EAAY,KAAA,CAAM,MAAA,CAAO,CAAC,CAAA,CAAE,WAAA,CAAY,EAAA,EAAI,KAAA,CAAM,KAAA,CAAM,CAAC,CAAA;AAE7D,EAAA,GAAA,CAAI,SAAA,CAAU,QAAA,CAAS,GAAG,CAAA,EAAG;AAC3B,IAAA,UAAA,EAAY,SAAA,CAAU,KAAA,CAAM,CAAA,EAAG,CAAA,CAAE,CAAA;AAAA,EACnC;AAEA,EAAA,OAAO,SAAA;AACT,CAAA;AAEA,IAAM,aAAA,EAAe,CAAC,gBAAA,EAA4B,CAAC,OAAO,CAAA,EAAA,GAAM;AAC9D,EAAA,MAAM,MAAA,EAAQ,eAAA,CACX,GAAA;AAAA,IACC,CAAC,IAAA,EAAA,GACC,CAAA,YAAA,EAAe,cAAA,CAAe,IAAI,CAAC,CAAA,oDAAA;AAAA,EACvC,CAAA,CACC,IAAA,CAAK,IAAI,CAAA;AAEZ,EAAA,MAAM,YAAA,EAAc,eAAA,CACjB,GAAA;AAAA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AAA;AACH,EAAA;AACG,IAAA;AACI,MAAA;AACX,IAAA;AAEU,IAAA;AACb,EAAA;AAEc,EAAA;AACA,EAAA;AAGA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AAGL,EAAA;AACD,IAAA;AACO,IAAA;AACd,EAAA;AAEQ,EAAA;AACD,IAAA;AACO,IAAA;AACd,EAAA;AACH;AAEiB;AACH,EAAA;AACA,EAAA;AACd;AAEW;AACA;AAaL;AAGF,EAAA;AACA,EAAA;AAEM;AAEN,EAAA;AACA,EAAA;AACgB,EAAA;AAEP,IAAA;AACT,EAAA;AACC,EAAA;AAEF;AACC,EAAA;AACA,EAAA;AAEM;AAEN,EAAA;AACA,EAAA;AACA,EAAA;AAEM;AAGE,EAAA;AACF,EAAA;AAEA,EAAA;AACK,IAAA;AACP,MAAA;AACU,MAAA;AAGA,MAAA;AAKZ,IAAA;AACQ,IAAA;AACN,MAAA;AACA,MAAA;AACA,MAAA;AAGF,IAAA;AACA,IAAA;AACD,EAAA;AACF;AJ+Hc;AACA;AClbD;AAEH;AAEL;AACA;AACA;AAEM;AAEP;ADgbU;AACA;AACA","file":"/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/cli.cjs","sourcesContent":[null,"#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { configCommand, migrateCommand, shellCommand } from './commandLine';\n\nconst program = new Command();\n\nprogram.name('pongo').description('CLI tool for Pongo');\n\nprogram.addCommand(configCommand);\nprogram.addCommand(migrateCommand);\nprogram.addCommand(shellCommand);\n\nprogram.parse(process.argv);\n\nexport default program;\n","import { Command } from 'commander';\nimport fs from 'node:fs';\nimport {\n objectEntries,\n toDbSchemaMetadata,\n type PongoDbSchemaMetadata,\n type PongoSchemaConfig,\n} from '../core';\n\nconst formatTypeName = (input: string): string => {\n if (input.length === 0) {\n return input;\n }\n\n let formatted = input.charAt(0).toUpperCase() + input.slice(1);\n\n if (formatted.endsWith('s')) {\n formatted = formatted.slice(0, -1);\n }\n\n return formatted;\n};\n\nconst sampleConfig = (collectionNames: string[] = ['users']) => {\n const types = collectionNames\n .map(\n (name) =>\n `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 migrationTableSchemaComponent,\n runPostgreSQLMigrations,\n} from '@event-driven-io/dumbo';\nimport { Command } from 'commander';\nimport { pongoCollectionSchemaComponent } from '../core';\nimport { loadConfigFile } from './configFile';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n config?: string;\n dryRun?: boolean;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n 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 '-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 .action(async (options: MigrateRunOptions) => {\n const { collection, dryRun } = options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--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 pool = dumbo({ connectionString });\n\n const migrations = collectionNames.flatMap((collectionsName) =>\n pongoCollectionSchemaComponent(collectionsName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n );\n\n await runPostgreSQLMigrations(pool, migrations, {\n dryRun,\n });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option('-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 } = 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 coreMigrations = migrationTableSchemaComponent.migrations({\n connector: 'PostgreSQL:pg',\n });\n const migrations = [\n ...coreMigrations,\n ...collectionNames.flatMap((collectionName) =>\n pongoCollectionSchemaComponent(collectionName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n ),\n ];\n\n console.log('Printing SQL:');\n console.log(combineMigrations(...migrations));\n });\n","import {\n checkConnection,\n color,\n LogLevel,\n LogStyle,\n prettyJson,\n SQL,\n type MigrationStyle,\n} from '@event-driven-io/dumbo';\nimport Table from 'cli-table3';\nimport { Command } from 'commander';\nimport repl from 'node:repl';\nimport {\n pongoClient,\n pongoSchema,\n type PongoClient,\n type PongoCollectionSchema,\n type PongoDb,\n} from '../core';\n\nlet pongo: PongoClient;\n\nconst calculateColumnWidths = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n results: any[],\n columnNames: string[],\n): number[] => {\n const columnWidths = columnNames.map((col) => {\n const maxWidth = Math.max(\n col.length, // Header size\n ...results.map((result) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n result[col] ? String(result[col]).length : 0,\n ),\n );\n return maxWidth + 2; // Add padding\n });\n return columnWidths;\n};\n\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}) => {\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-alpha.1)'));\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 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 typedClient = pongoClient(connectionString, {\n schema: {\n definition: schema,\n autoMigration: options.schema.autoMigration,\n },\n });\n\n db = typedClient.database;\n\n for (const collectionName of options.schema.collections) {\n shell.context[collectionName] = typedClient.database[collectionName];\n }\n\n pongo = typedClient;\n } else {\n pongo = pongoClient(connectionString, {\n schema: { autoMigration: options.schema.autoMigration },\n });\n\n db = pongo.db(options.schema.database);\n }\n\n shell.context.pongo = pongo;\n shell.context.db = db;\n\n // helpers\n shell.context.SQL = SQL;\n shell.context.setLogLevel = setLogLevel;\n shell.context.setLogStyle = setLogStyle;\n shell.context.prettifyLogs = prettifyLogs;\n shell.context.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 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 '-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 });\n });\n\nexport { shellCommand };\n"]}
1
+ {"version":3,"sources":["/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/cli.cjs","../src/cli.ts","../src/commandLine/configFile.ts","../src/commandLine/migrate.ts","../src/commandLine/shell.ts"],"names":[],"mappings":"AAAA;AACA;AACE;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACRA,sCAAwB;ADUxB;AACA;AEZA;AACA,gEAAe;AAQf,IAAM,eAAA,EAAiB,CAAC,KAAA,EAAA,GAA0B;AAChD,EAAA,GAAA,CAAI,KAAA,CAAM,OAAA,IAAW,CAAA,EAAG;AACtB,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,IAAI,UAAA,EAAY,KAAA,CAAM,MAAA,CAAO,CAAC,CAAA,CAAE,WAAA,CAAY,EAAA,EAAI,KAAA,CAAM,KAAA,CAAM,CAAC,CAAA;AAE7D,EAAA,GAAA,CAAI,SAAA,CAAU,QAAA,CAAS,GAAG,CAAA,EAAG;AAC3B,IAAA,UAAA,EAAY,SAAA,CAAU,KAAA,CAAM,CAAA,EAAG,CAAA,CAAE,CAAA;AAAA,EACnC;AAEA,EAAA,OAAO,SAAA;AACT,CAAA;AAEA,IAAM,aAAA,EAAe,CAAC,gBAAA,EAA4B,CAAC,OAAO,CAAA,EAAA,GAAM;AAC9D,EAAA,MAAM,MAAA,EAAQ,eAAA,CACX,GAAA;AAAA,IACC,CAAC,IAAA,EAAA,GACC,CAAA,YAAA,EAAe,cAAA,CAAe,IAAI,CAAC,CAAA,oDAAA;AAAA,EACvC,CAAA,CACC,IAAA,CAAK,IAAI,CAAA;AAEZ,EAAA,MAAM,YAAA,EAAc,eAAA,CACjB,GAAA;AAAA,IACC,CAAC,IAAA,EAAA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A;AACI,MAAA;AACX,IAAA;AAEU,IAAA;AACb,EAAA;AAEc,EAAA;AACA,EAAA;AAGA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AAGL,EAAA;AACD,IAAA;AACO,IAAA;AACd,EAAA;AAEQ,EAAA;AACD,IAAA;AACO,IAAA;AACd,EAAA;AACH;AAEiB;AACH,EAAA;AACA,EAAA;AACd;AAEW;AACA;AAaL;AAGF,EAAA;AACA,EAAA;AAEM;AAEN,EAAA;AACA,EAAA;AACgB,EAAA;AAEP,IAAA;AACT,EAAA;AACC,EAAA;AAEF;AACC,EAAA;AACA,EAAA;AAEM;AAEN,EAAA;AACA,EAAA;AACA,EAAA;AAEM;AAGE,EAAA;AACF,EAAA;AAEA,EAAA;AACK,IAAA;AACP,MAAA;AACU,MAAA;AAGA,MAAA;AAKZ,IAAA;AACQ,IAAA;AACN,MAAA;AACA,MAAA;AACA,MAAA;AAGF,IAAA;AACA,IAAA;AACD,EAAA;AACF;AJ+Hc;AACA;AClbD;AAEH;AAEL;AACA;AACA;AAEM;AAEP;ADgbU;AACA;AACA","file":"/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/cli.cjs","sourcesContent":[null,"#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { configCommand, migrateCommand, shellCommand } from './commandLine';\n\nconst program = new Command();\n\nprogram.name('pongo').description('CLI tool for Pongo');\n\nprogram.addCommand(configCommand);\nprogram.addCommand(migrateCommand);\nprogram.addCommand(shellCommand);\n\nprogram.parse(process.argv);\n\nexport default program;\n","import { Command } from 'commander';\nimport fs from 'node:fs';\nimport {\n objectEntries,\n toDbSchemaMetadata,\n type PongoDbSchemaMetadata,\n type PongoSchemaConfig,\n} from '../core';\n\nconst formatTypeName = (input: string): string => {\n if (input.length === 0) {\n return input;\n }\n\n let formatted = input.charAt(0).toUpperCase() + input.slice(1);\n\n if (formatted.endsWith('s')) {\n formatted = formatted.slice(0, -1);\n }\n\n return formatted;\n};\n\nconst sampleConfig = (collectionNames: string[] = ['users']) => {\n const types = collectionNames\n .map(\n (name) =>\n `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 { combineMigrations } from '@event-driven-io/dumbo';\nimport {\n dumbo,\n migrationTableSchemaComponent,\n runPostgreSQLMigrations,\n} from '@event-driven-io/dumbo/pg';\nimport { Command } from 'commander';\nimport { pongoCollectionSchemaComponent } from '../core';\nimport { loadConfigFile } from './configFile';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n config?: string;\n dryRun?: boolean;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n 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 '-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 .action(async (options: MigrateRunOptions) => {\n const { collection, dryRun } = options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--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 pool = dumbo({ connectionString });\n\n const migrations = collectionNames.flatMap((collectionsName) =>\n pongoCollectionSchemaComponent(collectionsName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n );\n\n await runPostgreSQLMigrations(pool, migrations, {\n dryRun,\n });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option('-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 } = 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 coreMigrations = migrationTableSchemaComponent.migrations({\n connector: 'PostgreSQL:pg',\n });\n const migrations = [\n ...coreMigrations,\n ...collectionNames.flatMap((collectionName) =>\n pongoCollectionSchemaComponent(collectionName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n ),\n ];\n\n console.log('Printing SQL:');\n console.log(combineMigrations(...migrations));\n });\n","import {\n color,\n LogLevel,\n LogStyle,\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 pongoSchema,\n type PongoClient,\n type PongoCollectionSchema,\n type PongoDb,\n} from '../core';\n\nlet pongo: PongoClient;\n\nconst calculateColumnWidths = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n results: any[],\n columnNames: string[],\n): number[] => {\n const columnWidths = columnNames.map((col) => {\n const maxWidth = Math.max(\n col.length, // Header size\n ...results.map((result) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n result[col] ? String(result[col]).length : 0,\n ),\n );\n return maxWidth + 2; // Add padding\n });\n return columnWidths;\n};\n\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}) => {\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-alpha.3)'));\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 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 typedClient = pongoClient(connectionString, {\n schema: {\n definition: schema,\n autoMigration: options.schema.autoMigration,\n },\n });\n\n db = typedClient.database;\n\n for (const collectionName of options.schema.collections) {\n shell.context[collectionName] = typedClient.database[collectionName];\n }\n\n pongo = typedClient;\n } else {\n pongo = pongoClient(connectionString, {\n schema: { autoMigration: options.schema.autoMigration },\n });\n\n db = pongo.db(options.schema.database);\n }\n\n shell.context.pongo = pongo;\n shell.context.db = db;\n\n // helpers\n shell.context.SQL = SQL;\n shell.context.setLogLevel = setLogLevel;\n shell.context.setLogStyle = setLogStyle;\n shell.context.prettifyLogs = prettifyLogs;\n shell.context.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 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 '-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 });\n });\n\nexport { shellCommand };\n"]}
package/dist/cli.js CHANGED
@@ -5,7 +5,7 @@ import {
5
5
  pongoCollectionSchemaComponent,
6
6
  pongoSchema,
7
7
  toDbSchemaMetadata
8
- } from "./chunk-VZKV7AMY.js";
8
+ } from "./chunk-DRVOAVHN.js";
9
9
 
10
10
  // src/cli.ts
11
11
  import { Command as Command4 } from "commander";
@@ -141,12 +141,12 @@ configCommand.command("sample").description("Generate or print sample configurat
141
141
  });
142
142
 
143
143
  // src/commandLine/migrate.ts
144
+ import { combineMigrations } from "@event-driven-io/dumbo";
144
145
  import {
145
- combineMigrations,
146
146
  dumbo,
147
147
  migrationTableSchemaComponent,
148
148
  runPostgreSQLMigrations
149
- } from "@event-driven-io/dumbo";
149
+ } from "@event-driven-io/dumbo/pg";
150
150
  import { Command as Command2 } from "commander";
151
151
  var migrateCommand = new Command2("migrate").description(
152
152
  "Manage database migrations"
@@ -232,13 +232,13 @@ migrateCommand.command("sql").description("Generate SQL for database migration")
232
232
 
233
233
  // src/commandLine/shell.ts
234
234
  import {
235
- checkConnection,
236
235
  color,
237
236
  LogLevel,
238
237
  LogStyle,
239
238
  prettyJson,
240
239
  SQL
241
240
  } from "@event-driven-io/dumbo";
241
+ import { checkConnection } from "@event-driven-io/dumbo/pg";
242
242
  import Table from "cli-table3";
243
243
  import { Command as Command3 } from "commander";
244
244
  import repl from "node:repl";
@@ -310,7 +310,7 @@ var prettifyLogs = (logLevel) => {
310
310
  var startRepl = async (options) => {
311
311
  setLogLevel(process.env.DUMBO_LOG_LEVEL ?? options.logging.logLevel);
312
312
  setLogStyle(process.env.DUMBO_LOG_STYLE ?? options.logging.logStyle);
313
- console.log(color.green("Starting Pongo Shell (version: 0.17.0-alpha.1)"));
313
+ console.log(color.green("Starting Pongo Shell (version: 0.17.0-alpha.3)"));
314
314
  if (options.logging.printOptions) {
315
315
  console.log(color.green("With Options:"));
316
316
  console.log(prettyJson(options));