@event-driven-io/pongo 0.15.0-alpha.3 → 0.15.1

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/postgres/sqlBuilder/index.ts","../src/core/collection/pongoCollection.ts","../src/postgres/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/postgres/sqlBuilder/filter/queryOperators.ts","../src/postgres/sqlBuilder/filter/index.ts","../src/postgres/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) ? filter : 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) ? filter : 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 runPostgreSQLMigrations,\n schemaComponent,\n single,\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 { v4 as uuid } from 'uuid';\nimport {\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 '../../postgres';\n\nexport type PongoCollectionOptions<ConnectorType extends string = string> = {\n db: PongoDb<ConnectorType>;\n collectionName: string;\n pool: Dumbo;\n sqlBuilder: PongoCollectionSQLBuilder;\n schema?: { autoMigration?: MigrationStyle };\n errors?: { throwOnOperationFailures?: boolean };\n};\n\nconst enlistIntoTransactionIfActive = async <\n ConnectorType extends string = string,\n>(\n db: PongoDb<ConnectorType>,\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\nconst transactionExecutorOrDefault = async <\n ConnectorType extends string = string,\n>(\n db: PongoDb<ConnectorType>,\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 ConnectorType extends string = string,\n>({\n db,\n collectionName,\n pool,\n sqlBuilder: SqlFor,\n schema,\n errors,\n}: PongoCollectionOptions<ConnectorType>): 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: result.rows[0]!.modified === result.rows[0]!.matched,\n modifiedCount: Number(result.rows[0]!.modified),\n matchedCount: Number(result.rows[0]!.matched),\n nextExpectedVersion: result.rows[0]!.version,\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[0]!.modified > 0,\n modifiedCount: Number(result.rows[0]!.modified),\n matchedCount: Number(result.rows[0]!.matched),\n nextExpectedVersion: result.rows[0]!.version,\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[0]!.deleted! > 0,\n deletedCount: Number(result.rows[0]!.deleted!),\n matchedCount: Number(result.rows[0]!.matched!),\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>;\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(existing as T);\n\n if (existing === result)\n return operationResult<PongoHandleResult<T>>(\n {\n successful: true,\n document: existing as T,\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);\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);\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 dumbo,\n getDatabaseNameOrDefault,\n NodePostgresConnectorType,\n runPostgreSQLMigrations,\n schemaComponent,\n type PostgresConnector,\n type PostgresPoolOptions,\n type SchemaComponent,\n} from '@event-driven-io/dumbo';\nimport type { Document } from 'mongodb';\nimport {\n objectEntries,\n pongoCollection,\n pongoCollectionSchemaComponent,\n proxyPongoDbWithSchema,\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.connectorType === 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 db: PongoDb<PostgresConnector> = {\n connectorType: options.connectorType,\n databaseName,\n connect: () => Promise.resolve(),\n close: () => pool.close(),\n collection: (collectionName) =>\n pongoCollection({\n collectionName,\n db,\n pool,\n sqlBuilder: postgresSQLBuilder(collectionName),\n ...(options.schema ? options.schema : {}),\n ...(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\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 {\n NodePostgresConnectorType,\n type MigrationStyle,\n type NodePostgresConnection,\n} from '@event-driven-io/dumbo';\nimport pg from 'pg';\nimport type { PostgresDbClientOptions } from '../postgres';\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 connectorType: NodePostgresConnectorType,\n connectionString: options.connectionString,\n dbName: options.dbName,\n ...options.clientOptions,\n };\n\n return postgreSQLOptions as DbClientOptions;\n};\n","import {\n isPostgresClientOptions,\n postgresDb,\n type PostgresDbClientOptions,\n} from '../postgres';\nimport type { PongoClientOptions } from './pongoClient';\nimport type { PongoDb } from './typing';\n\nexport type PongoDbClientOptions<ConnectorType extends string = string> = {\n connectorType: ConnectorType;\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 { connectorType: type } = 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: ${type}`);\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 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 { 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<ConnectorType extends string = string>\n extends DatabaseTransactionFactory<ConnectorType> {\n get connectorType(): ConnectorType;\n get databaseName(): string;\n connect(): Promise<void>;\n close(): Promise<void>;\n collection<T extends PongoDocument>(name: string): PongoCollection<T>;\n readonly schema: Readonly<{\n component: SchemaComponent;\n migrate(): Promise<void>;\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' };\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 {\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 ConnectorType extends string = string,\n> = CollectionsMap<T> & PongoDb<ConnectorType>;\n\nexport type DBsMap<\n T extends Record<string, PongoDbSchema>,\n ConnectorType extends string = string,\n> = {\n [K in keyof T]: CollectionsMap<T[K]['collections']> & PongoDb<ConnectorType>;\n};\n\nexport type PongoClientWithSchema<\n T extends PongoClientSchema,\n ConnectorType extends string = string,\n> = DBsMap<T['dbs'], ConnectorType> & 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 | undefined,\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 ConnectorType extends string = string,\n>(\n pongoDb: PongoDb<ConnectorType>,\n dbSchema: PongoDbSchema<T>,\n collections: Map<string, PongoCollection<Document>>,\n): PongoDbWithSchema<T, ConnectorType> => {\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<ConnectorType> & {\n [key: string]: unknown;\n },\n {\n get(target, prop: string) {\n return collections.get(prop) ?? target[prop];\n },\n },\n ) as PongoDbWithSchema<T, ConnectorType>;\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","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,OACE,SAAAA,EACA,kBAAAC,EACA,UAAAC,GACA,OAAAC,EACA,gBAAAC,OAGK,yBCRP,OACE,2BAAAC,GACA,mBAAAC,EACA,UAAAC,OAUK,yBACP,OAAS,MAAMC,MAAY,OCd3B,OACE,SAAAC,GACA,4BAAAC,GACA,6BAAAC,GACA,2BAAAC,GACA,mBAAAC,MAIK,yBAeA,IAAMC,EACXC,GAEAA,EAAQ,gBAAkBC,GAEfC,EACXF,GAC+B,CAC/B,GAAM,CAAE,iBAAAG,EAAkB,OAAAC,CAAO,EAAIJ,EAC/BK,EAAeD,GAAUE,GAAyBH,CAAgB,EAElEI,EAAOC,GAA2B,CACtC,iBAAAL,EACA,GAAGH,EAAQ,iBACb,CAAC,EAEKS,EAAc,IAAI,IAElBC,EAAiC,CACrC,cAAeV,EAAQ,cACvB,aAAAK,EACA,QAAS,IAAM,QAAQ,QAAQ,EAC/B,MAAO,IAAME,EAAK,MAAM,EACxB,WAAaI,GACXC,EAAgB,CACd,eAAAD,EACA,GAAAD,EACA,KAAAH,EACA,WAAYM,EAAmBF,CAAc,EAC7C,GAAIX,EAAQ,OAASA,EAAQ,OAAS,CAAC,EACvC,GAAIA,EAAQ,OAASA,EAAQ,OAAS,CAAC,CACzC,CAAC,EACH,YAAa,IAAMO,EAAK,YAAY,EACpC,gBAAkBO,GAAWP,EAAK,gBAAgBO,CAAM,EAExD,OAAQ,CACN,IAAI,WAA6B,CAC/B,OAAOC,EAAgB,UAAW,CAChC,WAAY,CAAC,GAAGN,EAAY,OAAO,CAAC,EAAE,IAAKO,GAAMA,EAAE,OAAO,SAAS,CACrE,CAAC,CACH,EACA,QAAS,IACPC,GACEV,EACA,CAAC,GAAGE,EAAY,OA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CAAM,EAExE,OAAOT,EACL,kCACAD,EACAsB,EAAML,CAAW,CACnB,CACF,EACA,KAAUP,GAAsC,CAC9C,IAAMO,EAAcC,EAAMR,CAAM,EAAIA,EAASS,EAAqBT,CAAM,EACxE,OAAOT,EAAI,0BAA2BD,EAAgBsB,EAAML,CAAW,CAAC,CAC1E,EACA,eAAoBP,GAAsC,CACxD,IAAMO,EAAcC,EAAMR,CAAM,EAAIA,EAASS,EAAqBT,CAAM,EACxE,OAAOT,EACL,uCACAD,EACAsB,EAAML,CAAW,CACnB,CACF,EACA,OAASM,GACPtB,EAAI,+BAAgCD,EAAgBuB,CAAO,EAC7D,KAAM,CAACC,EAAqBxB,IAC1BC,EAAI,0BAA2BuB,CAAU,CAC7C,GAEMF,EAASZ,GACbA,EAAO,OAAS,EAAIT,EAAI,WAAYS,CAAM,EAAIe,GAAO,EAAE","names":["isSQL","JSONSerializer","rawSql","sql","sqlMigration","runPostgreSQLMigrations","schemaComponent","single","uuid","dumbo","getDatabaseNameOrDefault","NodePostgresConnectorType","runPostgreSQLMigrations","schemaComponent","isPostgresClientOptions","options","NodePostgresConnectorType","postgresDb","connectionString","dbName","databaseName","getDatabaseNameOrDefault","pool","dumbo","collections","db","collectionName","pongoCollection","postgresSQLBuilder","handle","schemaComponent","c","runPostgreSQLMigrations","dbsSchema","dbSchema","objectEntries","e","proxyPongoDbWithSchema","pongoDbSchemaComponent","components","pongoCollectionSchemaComponent","enlistIntoTransactionIfActive","db","options","transaction","transactionExecutorOrDefault","defaultSqlExecutor","pongoCollection","collectionName","pool","SqlFor","schema","errors","sqlExecutor","command","sql","query","shouldMigrate","createCollection","ensureCollectionCreated","collection","document","_id","uuid","_version","successful","operationResult","documents","rows","doc","result","d","filter","update","existingDoc","replacement","id","handle","version","operationOptions","byId","existing","expectedVersion","expectedVersionValue","newDoc","insertResult","replaceResult","row","count","single","newName","schemaComponent","runPostgreSQLMigrations","pongoCollectionSchemaComponent","pongoCollectionPostgreSQLMigrations","QueryOperators","OperatorMap","isOperator","key","hasOperators","value","isNumber","val","isString","PongoError","_PongoError","options","errorCode","message","ConcurrencyError","_ConcurrencyError","NodePostgresConnectorType","getPongoDb","options","type","isPostgresClientOptions","postgresDb","pongoTransaction","options","isCommitted","isRolledBack","databaseName","transaction","db","error","isActive","transaction","assertInActiveTransaction","assertNotInActiveTransaction","pongoSession","options","explicit","defaultTransactionOptions","hasEnded","startTransaction","pongoTransaction","commitTransaction","abortTransaction","session","fn","result","error","objectEntries","obj","key","value","JSONSerializer","DOCUMENT_EXISTS","DOCUMENT_DOES_NOT_EXIST","NO_CONCURRENCY_CHECK","isGeneralExpectedDocumentVersion","version","expectedVersionValue","expectedVersion","operationResult","result","options","errorMessage","successful","operationName","collectionName","ConcurrencyError","JSONSerializer","pongoCollectionSchema","name","pongoDbSchema","nameOrCollections","collections","pongoClientSchema","dbs","pongoSchema","proxyPongoDbWithSchema","pongoDb","dbSchema","collectionNames","collectionName","target","prop","proxyClientWithSchema","client","schema","dbNames","toDbSchemaMetadata","objectEntries","c","toClientSchemaMetadata","databases","e","db","pongoClient","connectionString","options","dbClients","dbClient","getPongoDb","clientToDbOptions","db","dbName","pongoSession","callback","session","proxyClientWithSchema","NodePostgresConnectorType","JSONSerializer","sql","handleOperator","path","operator","value","handleMetadataOperator","sql","JSONSerializer","buildNestedObject","OperatorMap","v","subQuery","objectEntries","subKey","subValue","fieldName","acc","key","AND","constructFilterQuery","filter","key","value","isRecord","constructComplexFilterQuery","handleOperator","isEquality","hasOperators","objectEntries","nestedKey","val","QueryOperators","JSONSerializer","sql","buildUpdateQuery","update","objectEntries","currentUpdateQuery","op","value","buildSetQuery","buildUnsetQuery","buildIncQuery","buildPushQuery","sql","set","JSONSerializer","unset","k","inc","key","push","createCollection","collectionName","sql","pongoCollectionPostgreSQLMigrations","sqlMigration","postgresSQLBuilder","document","JSONSerializer","documents","values","doc","filter","update","options","expectedVersion","expectedVersionValue","expectedVersionUpdate","expectedVersionParams","filterQuery","isSQL","constructFilterQuery","updateQuery","buildUpdateQuery","where","newName","targetName","rawSql"]}
package/dist/cli.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _chunk7GQ5BP22cjs = require('./chunk-7GQ5BP22.cjs');var _commander = require('commander');var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);var S=o=>{if(o.length===0)return o;let n=o.charAt(0).toUpperCase()+o.slice(1);return n.endsWith("s")&&(n=n.slice(0,-1)),n},a=(o=["users"])=>{let n=o.map(e=>`type ${S(e)} = { name: string; description: string; date: Date }`).join(`
3
- `),t=o.map(e=>` ${e}: pongoSchema.collection<${S(e)}>('${e}'),`).join(`
2
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _chunk2FFAJEOIcjs = require('./chunk-2FFAJEOI.cjs');var _commander = require('commander');var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);var C=o=>{if(o.length===0)return o;let n=o.charAt(0).toUpperCase()+o.slice(1);return n.endsWith("s")&&(n=n.slice(0,-1)),n},a=(o=["users"])=>{let n=o.map(e=>`type ${C(e)} = { name: string; description: string; date: Date }`).join(`
3
+ `),t=o.map(e=>` ${e}: pongoSchema.collection<${C(e)}>('${e}'),`).join(`
4
4
  `);return`import { pongoSchema } from '@event-driven-io/pongo';
5
5
 
6
6
  ${n}
@@ -11,17 +11,17 @@ export default {
11
11
  ${t}
12
12
  }),
13
13
  }),
14
- };`},E=`Error: Config should contain default export, e.g.
14
+ };`},O=`Error: Config should contain default export, e.g.
15
15
 
16
16
  ${a()}`,D=`Error: Config should contain schema property, e.g.
17
17
 
18
18
  ${a()}`,M=`Error: Config should have at least a single database defined, e.g.
19
19
 
20
- ${a()}`,O=`Error: Config should have a default database defined (without name or or with default database name), e.g.
20
+ ${a()}`,$=`Error: Config should have a default database defined (without name or or with default database name), e.g.
21
21
 
22
- ${a()}`,b=`Error: Database should have defined at least one collection, e.g.
22
+ ${a()}`,y=`Error: Database should have defined at least one collection, e.g.
23
23
 
24
- ${a()}`,C=async o=>{let n=new URL(o,`file://${process.cwd()}/`);try{let t=await Promise.resolve().then(() => _interopRequireWildcard(require(n.href))),e=$(t);return typeof e=="string"&&(console.error(e),process.exit(1)),e}catch (e2){console.error(`Error: Couldn't load file: ${n.href}`),process.exit(1)}},N=(o,n)=>{try{_fs2.default.writeFileSync(o,a(n),"utf8"),console.log(`Configuration file stored at: ${o}`)}catch(t){console.error(`Error: Couldn't store config file: ${o}!`),console.error(t),process.exit(1)}},$=o=>{if(!o.default)return E;if(!o.default.schema)return D;if(!o.default.schema.dbs)return M;let t=_chunk7GQ5BP22cjs.s.call(void 0, o.default.schema.dbs).map(r=>r[1]).find(r=>r.name===void 0);return t?!t.collections||_chunk7GQ5BP22cjs.s.call(void 0, t.collections).map(r=>r[1]).length===0?b:_chunk7GQ5BP22cjs.D.call(void 0, t):O},d=new (0, _commander.Command)("config").description("Manage Pongo configuration");d.command("sample").description("Generate or print sample configuration").option("-col, --collection <name>","Specify the collection name",(o,n)=>n.concat([o]),[]).option("-f, --file <path>","Path to configuration file with collection list").option("-g, --generate","Generate sample config file").option("-p, --print","Print sample config file").action(o=>{let n=o.collection.length>0?o.collection:["users"];!("print"in o)&&!("generate"in o)&&(console.error(`Error: Please provide either:
24
+ ${a()}`,x=async o=>{let n=new URL(o,`file://${process.cwd()}/`);try{let t=await Promise.resolve().then(() => _interopRequireWildcard(require(n.href))),e=T(t);return typeof e=="string"&&(console.error(e),process.exit(1)),e}catch (e2){console.error(`Error: Couldn't load file: ${n.href}`),process.exit(1)}},R=(o,n)=>{try{_fs2.default.writeFileSync(o,a(n),"utf8"),console.log(`Configuration file stored at: ${o}`)}catch(t){console.error(`Error: Couldn't store config file: ${o}!`),console.error(t),process.exit(1)}},T=o=>{if(!o.default)return O;if(!o.default.schema)return D;if(!o.default.schema.dbs)return M;let t=_chunk2FFAJEOIcjs.s.call(void 0, o.default.schema.dbs).map(r=>r[1]).find(r=>r.name===void 0);return t?!t.collections||_chunk2FFAJEOIcjs.s.call(void 0, t.collections).map(r=>r[1]).length===0?y:_chunk2FFAJEOIcjs.D.call(void 0, t):$},h=new (0, _commander.Command)("config").description("Manage Pongo configuration");h.command("sample").description("Generate or print sample configuration").option("-col, --collection <name>","Specify the collection name",(o,n)=>n.concat([o]),[]).option("-f, --file <path>","Path to configuration file with collection list").option("-g, --generate","Generate sample config file").option("-p, --print","Print sample config file").action(o=>{let n=o.collection.length>0?o.collection:["users"];!("print"in o)&&!("generate"in o)&&(console.error(`Error: Please provide either:
25
25
  --print param to print sample config or
26
- --generate to generate sample config file`),process.exit(1)),"print"in o?console.log(`${a(n)}`):"generate"in o&&(o.file||(console.error("Error: You need to provide a config file through a --file"),process.exit(1)),N(o.file,n))});var _dumbo = require('@event-driven-io/dumbo');var g=new (0, _commander.Command)("migrate").description("Manage database migrations");g.command("run").description("Run database migrations").option("-cs, --connectionString <string>","Connection string for the database").option("-col, --collection <name>","Specify the collection name",(o,n)=>n.concat([o]),[]).option("-f, --config <path>","Path to configuration file with Pongo config").option("-dr, --dryRun","Perform dry run without commiting changes",!1).action(async o=>{let{collection:n,dryRun:t}=o,e=_nullishCoalesce(o.connectionString, () => (process.env.DB_CONNECTION_STRING)),r;e||(console.error('Error: Connection string is required. Provide it either as a "--connectionString" parameter or through the DB_CONNECTION_STRING environment variable.'),process.exit(1)),o.config?r=(await C(o.config)).collections.map(P=>P.name):n?r=n:(console.error('Error: You need to provide at least one collection name. Provide it either through "--config" file or as a "--collection" parameter.'),process.exit(1));let i=_dumbo.dumbo.call(void 0, {connectionString:e}),x=r.flatMap(f=>_chunk7GQ5BP22cjs.g.call(void 0, f).migrations({connector:"PostgreSQL:pg"}));await _dumbo.runPostgreSQLMigrations.call(void 0, i,x,{dryRun:t})});g.command("sql").description("Generate SQL for database migration").option("-col, --collection <name>","Specify the collection name",(o,n)=>n.concat([o]),[]).option("--print","Print the SQL to the console (default)",!0).action(o=>{let{collection:n}=o;n||(console.error('Error: You need to provide at least one collection name is required. Provide it either as a "col" parameter.'),process.exit(1));let e=[..._dumbo.migrationTableSchemaComponent.migrations({connector:"PostgreSQL:pg"}),...n.flatMap(r=>_chunk7GQ5BP22cjs.g.call(void 0, r).migrations({connector:"PostgreSQL:pg"}))];console.log("Printing SQL:"),console.log(_dumbo.combineMigrations.call(void 0, ...e))});var _chalk = require('chalk'); var _chalk2 = _interopRequireDefault(_chalk);var _clitable3 = require('cli-table3'); var _clitable32 = _interopRequireDefault(_clitable3);var _repl = require('repl'); var _repl2 = _interopRequireDefault(_repl);var _=(o,n)=>n.map(e=>Math.max(e.length,...o.map(i=>i[e]?String(i[e]).length:0))+2),A=o=>Array.isArray(o)?F(o):o.toString(),F=o=>{if(o.length===0)return _chalk2.default.yellow("No documents found.");let n=Object.keys(o[0]),t=_(o,n),e=new (0, _clitable32.default)({head:n.map(r=>_chalk2.default.cyan(r)),colWidths:t});return o.forEach(r=>{e.push(n.map(i=>r[i]!==void 0?String(r[i]):""))}),e.toString()},U=o=>{let n=_repl2.default.start({prompt:_chalk2.default.green("pongo> "),useGlobal:!0,breakEvalOnSigint:!0,writer:A}),t=o.schema.collections.length>0?_chunk7GQ5BP22cjs.A.client({database:_chunk7GQ5BP22cjs.A.db({users:_chunk7GQ5BP22cjs.A.collection(o.schema.database)})}):void 0,e=_chunk7GQ5BP22cjs.F.call(void 0, o.connectionString,{...t?{schema:{definition:t}}:{}}),r=t?e.database:e.db(o.schema.database);n.context.db=r,n.on("exit",async()=>{console.log(_chalk2.default.yellow("Exiting Pongo Shell...")),await e.close(),process.exit()})},y=new (0, _commander.Command)("shell").description("Start an interactive Pongo shell").option("-cs, --connectionString <string>","Connection string for the database","postgresql://postgres:postgres@localhost:5432/postgres").option("-db, --database <string>","Database name to connect","postgres").option("-col, --collection <name>","Specify the collection name",(o,n)=>n.concat([o]),[]).action(o=>{let{collection:n,database:t}=o,e=_nullishCoalesce(o.connectionString, () => (process.env.DB_CONNECTION_STRING));console.log(_chalk2.default.green("Starting Pongo Shell. Use db.<collection>.<method>() to query.")),U({schema:{collections:n,database:t},connectionString:e})});var c=new _commander.Command;c.name("pongo").description("CLI tool for Pongo");c.addCommand(d);c.addCommand(g);c.addCommand(y);c.parse(process.argv);var mo=c;exports.default = mo;
26
+ --generate to generate sample config file`),process.exit(1)),"print"in o?console.log(`${a(n)}`):"generate"in o&&(o.file||(console.error("Error: You need to provide a config file through a --file"),process.exit(1)),R(o.file,n))});var _dumbo = require('@event-driven-io/dumbo');var g=new (0, _commander.Command)("migrate").description("Manage database migrations");g.command("run").description("Run database migrations").option("-cs, --connectionString <string>","Connection string for the database").option("-col, --collection <name>","Specify the collection name",(o,n)=>n.concat([o]),[]).option("-f, --config <path>","Path to configuration file with Pongo config").option("-dr, --dryRun","Perform dry run without commiting changes",!1).action(async o=>{let{collection:n,dryRun:t}=o,e=_nullishCoalesce(o.connectionString, () => (process.env.DB_CONNECTION_STRING)),r;e||(console.error('Error: Connection string is required. Provide it either as a "--connectionString" parameter or through the DB_CONNECTION_STRING environment variable.'),process.exit(1)),o.config?r=(await x(o.config)).collections.map(v=>v.name):n?r=n:(console.error('Error: You need to provide at least one collection name. Provide it either through "--config" file or as a "--collection" parameter.'),process.exit(1));let i=_dumbo.dumbo.call(void 0, {connectionString:e}),w=r.flatMap(u=>_chunk2FFAJEOIcjs.g.call(void 0, u).migrations({connector:"PostgreSQL:pg"}));await _dumbo.runPostgreSQLMigrations.call(void 0, i,w,{dryRun:t})});g.command("sql").description("Generate SQL for database migration").option("-col, --collection <name>","Specify the collection name",(o,n)=>n.concat([o]),[]).option("--print","Print the SQL to the console (default)",!0).action(o=>{let{collection:n}=o;n||(console.error('Error: You need to provide at least one collection name is required. Provide it either as a "col" parameter.'),process.exit(1));let e=[..._dumbo.migrationTableSchemaComponent.migrations({connector:"PostgreSQL:pg"}),...n.flatMap(r=>_chunk2FFAJEOIcjs.g.call(void 0, r).migrations({connector:"PostgreSQL:pg"}))];console.log("Printing SQL:"),console.log(_dumbo.combineMigrations.call(void 0, ...e))});var _chalk = require('chalk'); var _chalk2 = _interopRequireDefault(_chalk);var _clitable3 = require('cli-table3'); var _clitable32 = _interopRequireDefault(_clitable3);var _repl = require('repl'); var _repl2 = _interopRequireDefault(_repl);var m,k=(o,n)=>n.map(e=>Math.max(e.length,...o.map(i=>i[e]?String(i[e]).length:0))+2),B=o=>Array.isArray(o)?Y(o):_dumbo.JSONSerializer.serialize(o),Y=o=>{if(o.length===0)return _chalk2.default.yellow("No documents found.");let n=Object.keys(o[0]),t=k(o,n),e=new (0, _clitable32.default)({head:n.map(r=>_chalk2.default.cyan(r)),colWidths:t});return o.forEach(r=>{e.push(n.map(i=>r[i]!==void 0?String(r[i]):""))}),e.toString()},j=o=>{let n=_repl2.default.start({prompt:_chalk2.default.green("pongo> "),useGlobal:!0,breakEvalOnSigint:!0,writer:B}),t=o.schema.collections.length>0?_chunk2FFAJEOIcjs.A.client({database:_chunk2FFAJEOIcjs.A.db({users:_chunk2FFAJEOIcjs.A.collection(o.schema.database)})}):void 0;m=_chunk2FFAJEOIcjs.F.call(void 0, o.connectionString,{...t?{schema:{definition:t}}:{}});let e=t?m.database:m.db(o.schema.database);n.context.db=e,n.context.SQL=_dumbo.SQL,n.on("exit",async()=>{await p(),process.exit()}),n.on("SIGINT",async()=>{await p(),process.exit()})},p=async()=>{console.log(_chalk2.default.yellow("Exiting Pongo Shell...")),await m.close()};process.on("uncaughtException",p);process.on("SIGINT",p);var P=new (0, _commander.Command)("shell").description("Start an interactive Pongo shell").option("-cs, --connectionString <string>","Connection string for the database","postgresql://postgres:postgres@localhost:5432/postgres").option("-db, --database <string>","Database name to connect","postgres").option("-col, --collection <name>","Specify the collection name",(o,n)=>n.concat([o]),[]).action(o=>{let{collection:n,database:t}=o,e=_nullishCoalesce(o.connectionString, () => (process.env.DB_CONNECTION_STRING));console.log(_chalk2.default.green("Starting Pongo Shell. Use db.<collection>.<method>() to query.")),j({schema:{collections:n,database:t},connectionString:e})});var c=new _commander.Command;c.name("pongo").description("CLI tool for Pongo");c.addCommand(h);c.addCommand(g);c.addCommand(P);c.parse(process.argv);var So=c;exports.default = So;
27
27
  //# sourceMappingURL=cli.cjs.map
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import{A as l,D as h,F as u,g as m,s as p}from"./chunk-QO7XUM5F.js";import{Command as k}from"commander";import{Command as v}from"commander";import w from"node:fs";var S=o=>{if(o.length===0)return o;let n=o.charAt(0).toUpperCase()+o.slice(1);return n.endsWith("s")&&(n=n.slice(0,-1)),n},a=(o=["users"])=>{let n=o.map(e=>`type ${S(e)} = { name: string; description: string; date: Date }`).join(`
3
- `),t=o.map(e=>` ${e}: pongoSchema.collection<${S(e)}>('${e}'),`).join(`
2
+ import{A as l,D as S,F as b,g as d,s as f}from"./chunk-AG3WMJNZ.js";import{Command as z}from"commander";import{Command as E}from"commander";import N from"node:fs";var C=o=>{if(o.length===0)return o;let n=o.charAt(0).toUpperCase()+o.slice(1);return n.endsWith("s")&&(n=n.slice(0,-1)),n},a=(o=["users"])=>{let n=o.map(e=>`type ${C(e)} = { name: string; description: string; date: Date }`).join(`
3
+ `),t=o.map(e=>` ${e}: pongoSchema.collection<${C(e)}>('${e}'),`).join(`
4
4
  `);return`import { pongoSchema } from '@event-driven-io/pongo';
5
5
 
6
6
  ${n}
@@ -11,17 +11,17 @@ export default {
11
11
  ${t}
12
12
  }),
13
13
  }),
14
- };`},E=`Error: Config should contain default export, e.g.
14
+ };`},O=`Error: Config should contain default export, e.g.
15
15
 
16
16
  ${a()}`,D=`Error: Config should contain schema property, e.g.
17
17
 
18
18
  ${a()}`,M=`Error: Config should have at least a single database defined, e.g.
19
19
 
20
- ${a()}`,O=`Error: Config should have a default database defined (without name or or with default database name), e.g.
20
+ ${a()}`,$=`Error: Config should have a default database defined (without name or or with default database name), e.g.
21
21
 
22
- ${a()}`,b=`Error: Database should have defined at least one collection, e.g.
22
+ ${a()}`,y=`Error: Database should have defined at least one collection, e.g.
23
23
 
24
- ${a()}`,C=async o=>{let n=new URL(o,`file://${process.cwd()}/`);try{let t=await import(n.href),e=$(t);return typeof e=="string"&&(console.error(e),process.exit(1)),e}catch{console.error(`Error: Couldn't load file: ${n.href}`),process.exit(1)}},N=(o,n)=>{try{w.writeFileSync(o,a(n),"utf8"),console.log(`Configuration file stored at: ${o}`)}catch(t){console.error(`Error: Couldn't store config file: ${o}!`),console.error(t),process.exit(1)}},$=o=>{if(!o.default)return E;if(!o.default.schema)return D;if(!o.default.schema.dbs)return M;let t=p(o.default.schema.dbs).map(r=>r[1]).find(r=>r.name===void 0);return t?!t.collections||p(t.collections).map(r=>r[1]).length===0?b:h(t):O},d=new v("config").description("Manage Pongo configuration");d.command("sample").description("Generate or print sample configuration").option("-col, --collection <name>","Specify the collection name",(o,n)=>n.concat([o]),[]).option("-f, --file <path>","Path to configuration file with collection list").option("-g, --generate","Generate sample config file").option("-p, --print","Print sample config file").action(o=>{let n=o.collection.length>0?o.collection:["users"];!("print"in o)&&!("generate"in o)&&(console.error(`Error: Please provide either:
24
+ ${a()}`,x=async o=>{let n=new URL(o,`file://${process.cwd()}/`);try{let t=await import(n.href),e=T(t);return typeof e=="string"&&(console.error(e),process.exit(1)),e}catch{console.error(`Error: Couldn't load file: ${n.href}`),process.exit(1)}},R=(o,n)=>{try{N.writeFileSync(o,a(n),"utf8"),console.log(`Configuration file stored at: ${o}`)}catch(t){console.error(`Error: Couldn't store config file: ${o}!`),console.error(t),process.exit(1)}},T=o=>{if(!o.default)return O;if(!o.default.schema)return D;if(!o.default.schema.dbs)return M;let t=f(o.default.schema.dbs).map(r=>r[1]).find(r=>r.name===void 0);return t?!t.collections||f(t.collections).map(r=>r[1]).length===0?y:S(t):$},h=new E("config").description("Manage Pongo configuration");h.command("sample").description("Generate or print sample configuration").option("-col, --collection <name>","Specify the collection name",(o,n)=>n.concat([o]),[]).option("-f, --file <path>","Path to configuration file with collection list").option("-g, --generate","Generate sample config file").option("-p, --print","Print sample config file").action(o=>{let n=o.collection.length>0?o.collection:["users"];!("print"in o)&&!("generate"in o)&&(console.error(`Error: Please provide either:
25
25
  --print param to print sample config or
26
- --generate to generate sample config file`),process.exit(1)),"print"in o?console.log(`${a(n)}`):"generate"in o&&(o.file||(console.error("Error: You need to provide a config file through a --file"),process.exit(1)),N(o.file,n))});import{combineMigrations as R,dumbo as T,migrationTableSchemaComponent as L,runPostgreSQLMigrations as W}from"@event-driven-io/dumbo";import{Command as q}from"commander";var g=new q("migrate").description("Manage database migrations");g.command("run").description("Run database migrations").option("-cs, --connectionString <string>","Connection string for the database").option("-col, --collection <name>","Specify the collection name",(o,n)=>n.concat([o]),[]).option("-f, --config <path>","Path to configuration file with Pongo config").option("-dr, --dryRun","Perform dry run without commiting changes",!1).action(async o=>{let{collection:n,dryRun:t}=o,e=o.connectionString??process.env.DB_CONNECTION_STRING,r;e||(console.error('Error: Connection string is required. Provide it either as a "--connectionString" parameter or through the DB_CONNECTION_STRING environment variable.'),process.exit(1)),o.config?r=(await C(o.config)).collections.map(P=>P.name):n?r=n:(console.error('Error: You need to provide at least one collection name. Provide it either through "--config" file or as a "--collection" parameter.'),process.exit(1));let i=T({connectionString:e}),x=r.flatMap(f=>m(f).migrations({connector:"PostgreSQL:pg"}));await W(i,x,{dryRun:t})});g.command("sql").description("Generate SQL for database migration").option("-col, --collection <name>","Specify the collection name",(o,n)=>n.concat([o]),[]).option("--print","Print the SQL to the console (default)",!0).action(o=>{let{collection:n}=o;n||(console.error('Error: You need to provide at least one collection name is required. Provide it either as a "col" parameter.'),process.exit(1));let e=[...L.migrations({connector:"PostgreSQL:pg"}),...n.flatMap(r=>m(r).migrations({connector:"PostgreSQL:pg"}))];console.log("Printing SQL:"),console.log(R(...e))});import s from"chalk";import G from"cli-table3";import{Command as I}from"commander";import Q from"node:repl";var _=(o,n)=>n.map(e=>Math.max(e.length,...o.map(i=>i[e]?String(i[e]).length:0))+2),A=o=>Array.isArray(o)?F(o):o.toString(),F=o=>{if(o.length===0)return s.yellow("No documents found.");let n=Object.keys(o[0]),t=_(o,n),e=new G({head:n.map(r=>s.cyan(r)),colWidths:t});return o.forEach(r=>{e.push(n.map(i=>r[i]!==void 0?String(r[i]):""))}),e.toString()},U=o=>{let n=Q.start({prompt:s.green("pongo> "),useGlobal:!0,breakEvalOnSigint:!0,writer:A}),t=o.schema.collections.length>0?l.client({database:l.db({users:l.collection(o.schema.database)})}):void 0,e=u(o.connectionString,{...t?{schema:{definition:t}}:{}}),r=t?e.database:e.db(o.schema.database);n.context.db=r,n.on("exit",async()=>{console.log(s.yellow("Exiting Pongo Shell...")),await e.close(),process.exit()})},y=new I("shell").description("Start an interactive Pongo shell").option("-cs, --connectionString <string>","Connection string for the database","postgresql://postgres:postgres@localhost:5432/postgres").option("-db, --database <string>","Database name to connect","postgres").option("-col, --collection <name>","Specify the collection name",(o,n)=>n.concat([o]),[]).action(o=>{let{collection:n,database:t}=o,e=o.connectionString??process.env.DB_CONNECTION_STRING;console.log(s.green("Starting Pongo Shell. Use db.<collection>.<method>() to query.")),U({schema:{collections:n,database:t},connectionString:e})});var c=new k;c.name("pongo").description("CLI tool for Pongo");c.addCommand(d);c.addCommand(g);c.addCommand(y);c.parse(process.argv);var mo=c;export{mo as default};
26
+ --generate to generate sample config file`),process.exit(1)),"print"in o?console.log(`${a(n)}`):"generate"in o&&(o.file||(console.error("Error: You need to provide a config file through a --file"),process.exit(1)),R(o.file,n))});import{combineMigrations as I,dumbo as L,migrationTableSchemaComponent as G,runPostgreSQLMigrations as Q}from"@event-driven-io/dumbo";import{Command as W}from"commander";var g=new W("migrate").description("Manage database migrations");g.command("run").description("Run database migrations").option("-cs, --connectionString <string>","Connection string for the database").option("-col, --collection <name>","Specify the collection name",(o,n)=>n.concat([o]),[]).option("-f, --config <path>","Path to configuration file with Pongo config").option("-dr, --dryRun","Perform dry run without commiting changes",!1).action(async o=>{let{collection:n,dryRun:t}=o,e=o.connectionString??process.env.DB_CONNECTION_STRING,r;e||(console.error('Error: Connection string is required. Provide it either as a "--connectionString" parameter or through the DB_CONNECTION_STRING environment variable.'),process.exit(1)),o.config?r=(await x(o.config)).collections.map(v=>v.name):n?r=n:(console.error('Error: You need to provide at least one collection name. Provide it either through "--config" file or as a "--collection" parameter.'),process.exit(1));let i=L({connectionString:e}),w=r.flatMap(u=>d(u).migrations({connector:"PostgreSQL:pg"}));await Q(i,w,{dryRun:t})});g.command("sql").description("Generate SQL for database migration").option("-col, --collection <name>","Specify the collection name",(o,n)=>n.concat([o]),[]).option("--print","Print the SQL to the console (default)",!0).action(o=>{let{collection:n}=o;n||(console.error('Error: You need to provide at least one collection name is required. Provide it either as a "col" parameter.'),process.exit(1));let e=[...G.migrations({connector:"PostgreSQL:pg"}),...n.flatMap(r=>d(r).migrations({connector:"PostgreSQL:pg"}))];console.log("Printing SQL:"),console.log(I(...e))});import{JSONSerializer as q,SQL as _}from"@event-driven-io/dumbo";import s from"chalk";import A from"cli-table3";import{Command as F}from"commander";import U from"node:repl";var m,k=(o,n)=>n.map(e=>Math.max(e.length,...o.map(i=>i[e]?String(i[e]).length:0))+2),B=o=>Array.isArray(o)?Y(o):q.serialize(o),Y=o=>{if(o.length===0)return s.yellow("No documents found.");let n=Object.keys(o[0]),t=k(o,n),e=new A({head:n.map(r=>s.cyan(r)),colWidths:t});return o.forEach(r=>{e.push(n.map(i=>r[i]!==void 0?String(r[i]):""))}),e.toString()},j=o=>{let n=U.start({prompt:s.green("pongo> "),useGlobal:!0,breakEvalOnSigint:!0,writer:B}),t=o.schema.collections.length>0?l.client({database:l.db({users:l.collection(o.schema.database)})}):void 0;m=b(o.connectionString,{...t?{schema:{definition:t}}:{}});let e=t?m.database:m.db(o.schema.database);n.context.db=e,n.context.SQL=_,n.on("exit",async()=>{await p(),process.exit()}),n.on("SIGINT",async()=>{await p(),process.exit()})},p=async()=>{console.log(s.yellow("Exiting Pongo Shell...")),await m.close()};process.on("uncaughtException",p);process.on("SIGINT",p);var P=new F("shell").description("Start an interactive Pongo shell").option("-cs, --connectionString <string>","Connection string for the database","postgresql://postgres:postgres@localhost:5432/postgres").option("-db, --database <string>","Database name to connect","postgres").option("-col, --collection <name>","Specify the collection name",(o,n)=>n.concat([o]),[]).action(o=>{let{collection:n,database:t}=o,e=o.connectionString??process.env.DB_CONNECTION_STRING;console.log(s.green("Starting Pongo Shell. Use db.<collection>.<method>() to query.")),j({schema:{collections:n,database:t},connectionString:e})});var c=new z;c.name("pongo").description("CLI tool for Pongo");c.addCommand(h);c.addCommand(g);c.addCommand(P);c.parse(process.argv);var So=c;export{So as default};
27
27
  //# sourceMappingURL=cli.js.map
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/commandLine/configFile.ts","../src/commandLine/migrate.ts","../src/commandLine/shell.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { configCommand, migrateCommand, shellCommand } from './commandLine';\n\nconst program = new Command();\n\nprogram.name('pongo').description('CLI tool for Pongo');\n\nprogram.addCommand(configCommand);\nprogram.addCommand(migrateCommand);\nprogram.addCommand(shellCommand);\n\nprogram.parse(process.argv);\n\nexport default program;\n","import { Command } from 'commander';\nimport fs from 'node:fs';\nimport {\n objectEntries,\n toDbSchemaMetadata,\n type PongoDbSchemaMetadata,\n type PongoSchemaConfig,\n} from '../core';\n\nconst formatTypeName = (input: string): string => {\n if (input.length === 0) {\n return input;\n }\n\n let formatted = input.charAt(0).toUpperCase() + input.slice(1);\n\n if (formatted.endsWith('s')) {\n formatted = formatted.slice(0, -1);\n }\n\n return formatted;\n};\n\nconst sampleConfig = (collectionNames: string[] = ['users']) => {\n const types = collectionNames\n .map(\n (name) =>\n `type ${formatTypeName(name)} = { name: string; description: string; date: Date }`,\n )\n .join('\\n');\n\n const collections = collectionNames\n .map(\n (name) =>\n ` ${name}: pongoSchema.collection<${formatTypeName(name)}>('${name}'),`,\n )\n .join('\\n');\n\n return `import { pongoSchema } from '@event-driven-io/pongo';\n\n${types}\n\nexport default {\n schema: pongoSchema.client({\n database: pongoSchema.db({\n${collections}\n }),\n }),\n};`;\n};\n\nconst missingDefaultExport = `Error: Config should contain default export, e.g.\\n\\n${sampleConfig()}`;\nconst missingSchema = `Error: Config should contain schema property, e.g.\\n\\n${sampleConfig()}`;\nconst missingDbs = `Error: Config should have at least a single database defined, e.g.\\n\\n${sampleConfig()}`;\nconst missingDefaultDb = `Error: Config should have a default database defined (without name or or with default database name), e.g.\\n\\n${sampleConfig()}`;\nconst missingCollections = `Error: Database should have defined at least one collection, e.g.\\n\\n${sampleConfig()}`;\n\nexport const loadConfigFile = async (\n configPath: string,\n): Promise<PongoDbSchemaMetadata> => {\n const configUrl = new URL(configPath, `file://${process.cwd()}/`);\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const imported: Partial<{ default: PongoSchemaConfig }> = await import(\n configUrl.href\n );\n\n const parsed = parseDefaultDbSchema(imported);\n\n if (typeof parsed === 'string') {\n console.error(parsed);\n process.exit(1);\n }\n\n return parsed;\n } catch {\n console.error(`Error: Couldn't load file: ${configUrl.href}`);\n process.exit(1);\n }\n};\n\nexport const generateConfigFile = (\n configPath: string,\n collectionNames: string[],\n): void => {\n try {\n fs.writeFileSync(configPath, sampleConfig(collectionNames), 'utf8');\n console.log(`Configuration file stored at: ${configPath}`);\n } catch (error) {\n console.error(`Error: Couldn't store config file: ${configPath}!`);\n console.error(error);\n process.exit(1);\n }\n};\n\nexport const parseDefaultDbSchema = (\n imported: Partial<{ default: PongoSchemaConfig }>,\n): PongoDbSchemaMetadata | string => {\n if (!imported.default) {\n return missingDefaultExport;\n }\n\n if (!imported.default.schema) {\n return missingSchema;\n }\n\n if (!imported.default.schema.dbs) {\n return missingDbs;\n }\n\n const dbs = objectEntries(imported.default.schema.dbs).map((db) => db[1]);\n\n const defaultDb = dbs.find((db) => db.name === undefined);\n\n if (!defaultDb) {\n return missingDefaultDb;\n }\n\n if (!defaultDb.collections) {\n return missingCollections;\n }\n\n const collections = objectEntries(defaultDb.collections).map((col) => col[1]);\n\n if (collections.length === 0) {\n return missingCollections;\n }\n\n return toDbSchemaMetadata(defaultDb);\n};\n\ntype SampleConfigOptions =\n | {\n collection: string[];\n print?: boolean;\n }\n | {\n collection: string[];\n generate?: boolean;\n file?: string;\n };\n\nexport const configCommand = new Command('config').description(\n 'Manage Pongo configuration',\n);\n\nconfigCommand\n .command('sample')\n .description('Generate or print sample configuration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option(\n '-f, --file <path>',\n 'Path to configuration file with collection list',\n )\n .option('-g, --generate', 'Generate sample config file')\n .option('-p, --print', 'Print sample config file')\n .action((options: SampleConfigOptions) => {\n const collectionNames =\n options.collection.length > 0 ? options.collection : ['users'];\n\n if (!('print' in options) && !('generate' in options)) {\n console.error(\n 'Error: Please provide either:\\n--print param to print sample config or\\n--generate to generate sample config file',\n );\n process.exit(1);\n }\n\n if ('print' in options) {\n console.log(`${sampleConfig(collectionNames)}`);\n } else if ('generate' in options) {\n if (!options.file) {\n console.error(\n 'Error: You need to provide a config file through a --file',\n );\n process.exit(1);\n }\n\n generateConfigFile(options.file, collectionNames);\n }\n });\n","import {\n combineMigrations,\n dumbo,\n migrationTableSchemaComponent,\n runPostgreSQLMigrations,\n} from '@event-driven-io/dumbo';\nimport { Command } from 'commander';\nimport { pongoCollectionSchemaComponent } from '../core';\nimport { loadConfigFile } from './configFile';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n config?: string;\n dryRun?: boolean;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n collection: string[];\n}\n\nexport const migrateCommand = new Command('migrate').description(\n 'Manage database migrations',\n);\n\nmigrateCommand\n .command('run')\n .description('Run database migrations')\n .option(\n '-cs, --connectionString <string>',\n 'Connection string for the database',\n )\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option('-f, --config <path>', 'Path to configuration file with Pongo config')\n .option('-dr, --dryRun', 'Perform dry run without commiting changes', false)\n .action(async (options: MigrateRunOptions) => {\n const { collection, dryRun } = options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--connectionString\" parameter or through the DB_CONNECTION_STRING environment variable.',\n );\n process.exit(1);\n }\n\n if (options.config) {\n const config = await loadConfigFile(options.config);\n\n collectionNames = config.collections.map((c) => c.name);\n } else if (collection) {\n collectionNames = collection;\n } else {\n console.error(\n 'Error: You need to provide at least one collection name. Provide it either through \"--config\" file or as a \"--collection\" parameter.',\n );\n process.exit(1);\n }\n\n const pool = dumbo({ connectionString });\n\n const migrations = collectionNames.flatMap((collectionsName) =>\n pongoCollectionSchemaComponent(collectionsName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n );\n\n await runPostgreSQLMigrations(pool, migrations, {\n dryRun,\n });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option('--print', 'Print the SQL to the console (default)', true)\n //.option('--write <filename>', 'Write the SQL to a specified file')\n .action((options: MigrateSqlOptions) => {\n const { collection } = options;\n\n if (!collection) {\n console.error(\n 'Error: You need to provide at least one collection name is required. Provide it either as a \"col\" parameter.',\n );\n process.exit(1);\n }\n const coreMigrations = migrationTableSchemaComponent.migrations({\n connector: 'PostgreSQL:pg',\n });\n const migrations = [\n ...coreMigrations,\n ...collection.flatMap((collectionsName) =>\n pongoCollectionSchemaComponent(collectionsName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n ),\n ];\n\n console.log('Printing SQL:');\n console.log(combineMigrations(...migrations));\n });\n","import chalk from 'chalk';\nimport Table from 'cli-table3';\nimport { Command } from 'commander';\nimport repl from 'node:repl';\nimport { pongoClient, pongoSchema } from '../core';\n\nconst calculateColumnWidths = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n results: any[],\n columnNames: string[],\n): number[] => {\n const columnWidths = columnNames.map((col) => {\n const maxWidth = Math.max(\n col.length, // Header size\n ...results.map((result) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n result[col] ? String(result[col]).length : 0,\n ),\n );\n return maxWidth + 2; // Add padding\n });\n return columnWidths;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst printOutput = (obj: any): string => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access\n return Array.isArray(obj) ? displayResultsAsTable(obj) : obj.toString();\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst displayResultsAsTable = (results: any[]): string => {\n if (results.length === 0) {\n return chalk.yellow('No documents found.');\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n const columnNames = Object.keys(results[0]);\n\n const columnWidths = calculateColumnWidths(results, columnNames);\n\n const table = new Table({\n head: columnNames.map((col) => chalk.cyan(col)),\n colWidths: columnWidths,\n });\n\n results.forEach((result) => {\n table.push(\n columnNames.map((col) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n result[col] !== undefined ? String(result[col]) : '',\n ),\n );\n });\n\n return table.toString();\n};\n\nconst startRepl = (options: {\n schema: {\n database: string;\n collections: string[];\n };\n connectionString: string;\n}) => {\n const r = repl.start({\n prompt: chalk.green('pongo> '),\n useGlobal: true,\n breakEvalOnSigint: true,\n writer: printOutput,\n });\n\n const schema =\n options.schema.collections.length > 0\n ? pongoSchema.client({\n database: pongoSchema.db({\n users: pongoSchema.collection(options.schema.database),\n }),\n })\n : undefined;\n\n const pongo = pongoClient(options.connectionString, {\n ...(schema ? { schema: { definition: schema } } : {}),\n });\n\n const db = schema ? pongo.database : pongo.db(options.schema.database);\n\n r.context.db = db;\n\n // Intercept REPL output to display results as a table if they are arrays\n r.on('exit', async () => {\n console.log(chalk.yellow('Exiting Pongo Shell...'));\n await pongo.close();\n process.exit();\n });\n};\n\ninterface ShellOptions {\n database: string;\n collection: string[];\n connectionString: string;\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 'postgresql://postgres:postgres@localhost:5432/postgres',\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 .action((options: ShellOptions) => {\n const { collection, database } = options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n\n console.log(\n chalk.green(\n 'Starting Pongo Shell. Use db.<collection>.<method>() to query.',\n ),\n );\n startRepl({\n schema: { collections: collection, database },\n connectionString,\n });\n });\n\nexport { shellCommand };\n"],"mappings":";oEACA,OAAS,WAAAA,MAAe,YCDxB,OAAS,WAAAC,MAAe,YACxB,OAAOC,MAAQ,UAQf,IAAMC,EAAkBC,GAA0B,CAChD,GAAIA,EAAM,SAAW,EACnB,OAAOA,EAGT,IAAIC,EAAYD,EAAM,OAAO,CAAC,EAAE,YAAY,EAAIA,EAAM,MAAM,CAAC,EAE7D,OAAIC,EAAU,SAAS,GAAG,IACxBA,EAAYA,EAAU,MAAM,EAAG,EAAE,GAG5BA,CACT,EAEMC,EAAe,CAACC,EAA4B,CAAC,OAAO,IAAM,CAC9D,IAAMC,EAAQD,EACX,IACEE,GACC,QAAQN,EAAeM,CAAI,CAAC,sDAChC,EACC,KAAK;AAAA,CAAI,EAENC,EAAcH,EACjB,IACEE,GACC,SAASA,CAAI,4BAA4BN,EAAeM,CAAI,CAAC,MAAMA,CAAI,KAC3E,EACC,KAAK;AAAA,CAAI,EAEZ,MAAO;AAAA;AAAA,EAEPD,CAAK;AAAA;AAAA;AAAA;AAAA;AAAA,EAKLE,CAAW;AAAA;AAAA;AAAA,GAIb,EAEMC,EAAuB;AAAA;AAAA,EAAwDL,EAAa,CAAC,GAC7FM,EAAgB;AAAA;AAAA,EAAyDN,EAAa,CAAC,GACvFO,EAAa;AAAA;AAAA,EAAyEP,EAAa,CAAC,GACpGQ,EAAmB;AAAA;AAAA,EAAiHR,EAAa,CAAC,GAClJS,EAAqB;AAAA;AAAA,EAAwET,EAAa,CAAC,GAEpGU,EAAiB,MAC5BC,GACmC,CACnC,IAAMC,EAAY,IAAI,IAAID,EAAY,UAAU,QAAQ,IAAI,CAAC,GAAG,EAChE,GAAI,CAEF,IAAME,EAAoD,MAAM,OAC9DD,EAAU,MAGNE,EAASC,EAAqBF,CAAQ,EAE5C,OAAI,OAAOC,GAAW,WACpB,QAAQ,MAAMA,CAAM,EACpB,QAAQ,KAAK,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O,EAAE,YAAY,oBAAoB,EAEtDA,EAAQ,WAAWE,CAAa,EAChCF,EAAQ,WAAWG,CAAc,EACjCH,EAAQ,WAAWI,CAAY,EAE/BJ,EAAQ,MAAM,QAAQ,IAAI,EAE1B,IAAOK,GAAQL","names":["Command","Command","fs","formatTypeName","input","formatted","sampleConfig","collectionNames","types","name","collections","missingDefaultExport","missingSchema","missingDbs","missingDefaultDb","missingCollections","loadConfigFile","configPath","configUrl","imported","parsed","parseDefaultDbSchema","generateConfigFile","fs","error","defaultDb","objectEntries","db","col","toDbSchemaMetadata","configCommand","Command","value","previous","options","combineMigrations","dumbo","migrationTableSchemaComponent","runPostgreSQLMigrations","Command","migrateCommand","Command","value","previous","options","collection","dryRun","connectionString","collectionNames","loadConfigFile","c","pool","dumbo","migrations","collectionsName","pongoCollectionSchemaComponent","runPostgreSQLMigrations","migrationTableSchemaComponent","combineMigrations","chalk","Table","Command","repl","calculateColumnWidths","results","columnNames","col","result","printOutput","obj","displayResultsAsTable","chalk","columnWidths","table","Table","startRepl","options","r","repl","schema","pongoSchema","pongo","pongoClient","db","shellCommand","Command","value","previous","collection","database","connectionString","program","Command","configCommand","migrateCommand","shellCommand","cli_default"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/commandLine/configFile.ts","../src/commandLine/migrate.ts","../src/commandLine/shell.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { configCommand, migrateCommand, shellCommand } from './commandLine';\n\nconst program = new Command();\n\nprogram.name('pongo').description('CLI tool for Pongo');\n\nprogram.addCommand(configCommand);\nprogram.addCommand(migrateCommand);\nprogram.addCommand(shellCommand);\n\nprogram.parse(process.argv);\n\nexport default program;\n","import { Command } from 'commander';\nimport fs from 'node:fs';\nimport {\n objectEntries,\n toDbSchemaMetadata,\n type PongoDbSchemaMetadata,\n type PongoSchemaConfig,\n} from '../core';\n\nconst formatTypeName = (input: string): string => {\n if (input.length === 0) {\n return input;\n }\n\n let formatted = input.charAt(0).toUpperCase() + input.slice(1);\n\n if (formatted.endsWith('s')) {\n formatted = formatted.slice(0, -1);\n }\n\n return formatted;\n};\n\nconst sampleConfig = (collectionNames: string[] = ['users']) => {\n const types = collectionNames\n .map(\n (name) =>\n `type ${formatTypeName(name)} = { name: string; description: string; date: Date }`,\n )\n .join('\\n');\n\n const collections = collectionNames\n .map(\n (name) =>\n ` ${name}: pongoSchema.collection<${formatTypeName(name)}>('${name}'),`,\n )\n .join('\\n');\n\n return `import { pongoSchema } from '@event-driven-io/pongo';\n\n${types}\n\nexport default {\n schema: pongoSchema.client({\n database: pongoSchema.db({\n${collections}\n }),\n }),\n};`;\n};\n\nconst missingDefaultExport = `Error: Config should contain default export, e.g.\\n\\n${sampleConfig()}`;\nconst missingSchema = `Error: Config should contain schema property, e.g.\\n\\n${sampleConfig()}`;\nconst missingDbs = `Error: Config should have at least a single database defined, e.g.\\n\\n${sampleConfig()}`;\nconst missingDefaultDb = `Error: Config should have a default database defined (without name or or with default database name), e.g.\\n\\n${sampleConfig()}`;\nconst missingCollections = `Error: Database should have defined at least one collection, e.g.\\n\\n${sampleConfig()}`;\n\nexport const loadConfigFile = async (\n configPath: string,\n): Promise<PongoDbSchemaMetadata> => {\n const configUrl = new URL(configPath, `file://${process.cwd()}/`);\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const imported: Partial<{ default: PongoSchemaConfig }> = await import(\n configUrl.href\n );\n\n const parsed = parseDefaultDbSchema(imported);\n\n if (typeof parsed === 'string') {\n console.error(parsed);\n process.exit(1);\n }\n\n return parsed;\n } catch {\n console.error(`Error: Couldn't load file: ${configUrl.href}`);\n process.exit(1);\n }\n};\n\nexport const generateConfigFile = (\n configPath: string,\n collectionNames: string[],\n): void => {\n try {\n fs.writeFileSync(configPath, sampleConfig(collectionNames), 'utf8');\n console.log(`Configuration file stored at: ${configPath}`);\n } catch (error) {\n console.error(`Error: Couldn't store config file: ${configPath}!`);\n console.error(error);\n process.exit(1);\n }\n};\n\nexport const parseDefaultDbSchema = (\n imported: Partial<{ default: PongoSchemaConfig }>,\n): PongoDbSchemaMetadata | string => {\n if (!imported.default) {\n return missingDefaultExport;\n }\n\n if (!imported.default.schema) {\n return missingSchema;\n }\n\n if (!imported.default.schema.dbs) {\n return missingDbs;\n }\n\n const dbs = objectEntries(imported.default.schema.dbs).map((db) => db[1]);\n\n const defaultDb = dbs.find((db) => db.name === undefined);\n\n if (!defaultDb) {\n return missingDefaultDb;\n }\n\n if (!defaultDb.collections) {\n return missingCollections;\n }\n\n const collections = objectEntries(defaultDb.collections).map((col) => col[1]);\n\n if (collections.length === 0) {\n return missingCollections;\n }\n\n return toDbSchemaMetadata(defaultDb);\n};\n\ntype SampleConfigOptions =\n | {\n collection: string[];\n print?: boolean;\n }\n | {\n collection: string[];\n generate?: boolean;\n file?: string;\n };\n\nexport const configCommand = new Command('config').description(\n 'Manage Pongo configuration',\n);\n\nconfigCommand\n .command('sample')\n .description('Generate or print sample configuration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option(\n '-f, --file <path>',\n 'Path to configuration file with collection list',\n )\n .option('-g, --generate', 'Generate sample config file')\n .option('-p, --print', 'Print sample config file')\n .action((options: SampleConfigOptions) => {\n const collectionNames =\n options.collection.length > 0 ? options.collection : ['users'];\n\n if (!('print' in options) && !('generate' in options)) {\n console.error(\n 'Error: Please provide either:\\n--print param to print sample config or\\n--generate to generate sample config file',\n );\n process.exit(1);\n }\n\n if ('print' in options) {\n console.log(`${sampleConfig(collectionNames)}`);\n } else if ('generate' in options) {\n if (!options.file) {\n console.error(\n 'Error: You need to provide a config file through a --file',\n );\n process.exit(1);\n }\n\n generateConfigFile(options.file, collectionNames);\n }\n });\n","import {\n combineMigrations,\n dumbo,\n migrationTableSchemaComponent,\n runPostgreSQLMigrations,\n} from '@event-driven-io/dumbo';\nimport { Command } from 'commander';\nimport { pongoCollectionSchemaComponent } from '../core';\nimport { loadConfigFile } from './configFile';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n config?: string;\n dryRun?: boolean;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n collection: string[];\n}\n\nexport const migrateCommand = new Command('migrate').description(\n 'Manage database migrations',\n);\n\nmigrateCommand\n .command('run')\n .description('Run database migrations')\n .option(\n '-cs, --connectionString <string>',\n 'Connection string for the database',\n )\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option('-f, --config <path>', 'Path to configuration file with Pongo config')\n .option('-dr, --dryRun', 'Perform dry run without commiting changes', false)\n .action(async (options: MigrateRunOptions) => {\n const { collection, dryRun } = options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--connectionString\" parameter or through the DB_CONNECTION_STRING environment variable.',\n );\n process.exit(1);\n }\n\n if (options.config) {\n const config = await loadConfigFile(options.config);\n\n collectionNames = config.collections.map((c) => c.name);\n } else if (collection) {\n collectionNames = collection;\n } else {\n console.error(\n 'Error: You need to provide at least one collection name. Provide it either through \"--config\" file or as a \"--collection\" parameter.',\n );\n process.exit(1);\n }\n\n const pool = dumbo({ connectionString });\n\n const migrations = collectionNames.flatMap((collectionsName) =>\n pongoCollectionSchemaComponent(collectionsName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n );\n\n await runPostgreSQLMigrations(pool, migrations, {\n dryRun,\n });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option('--print', 'Print the SQL to the console (default)', true)\n //.option('--write <filename>', 'Write the SQL to a specified file')\n .action((options: MigrateSqlOptions) => {\n const { collection } = options;\n\n if (!collection) {\n console.error(\n 'Error: You need to provide at least one collection name is required. Provide it either as a \"col\" parameter.',\n );\n process.exit(1);\n }\n const coreMigrations = migrationTableSchemaComponent.migrations({\n connector: 'PostgreSQL:pg',\n });\n const migrations = [\n ...coreMigrations,\n ...collection.flatMap((collectionsName) =>\n pongoCollectionSchemaComponent(collectionsName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n ),\n ];\n\n console.log('Printing SQL:');\n console.log(combineMigrations(...migrations));\n });\n","import { JSONSerializer, SQL } from '@event-driven-io/dumbo';\nimport chalk from 'chalk';\nimport Table from 'cli-table3';\nimport { Command } from 'commander';\nimport repl from 'node:repl';\nimport { pongoClient, pongoSchema, type PongoClient } from '../core';\n\nlet pongo: PongoClient;\n\nconst calculateColumnWidths = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n results: any[],\n columnNames: string[],\n): number[] => {\n const columnWidths = columnNames.map((col) => {\n const maxWidth = Math.max(\n col.length, // Header size\n ...results.map((result) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n result[col] ? String(result[col]).length : 0,\n ),\n );\n return maxWidth + 2; // Add padding\n });\n return columnWidths;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst printOutput = (obj: any): string => {\n return Array.isArray(obj)\n ? displayResultsAsTable(obj)\n : JSONSerializer.serialize(obj);\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst displayResultsAsTable = (results: any[]): string => {\n if (results.length === 0) {\n return chalk.yellow('No documents found.');\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n const columnNames = Object.keys(results[0]);\n\n const columnWidths = calculateColumnWidths(results, columnNames);\n\n const table = new Table({\n head: columnNames.map((col) => chalk.cyan(col)),\n colWidths: columnWidths,\n });\n\n results.forEach((result) => {\n table.push(\n columnNames.map((col) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n result[col] !== undefined ? String(result[col]) : '',\n ),\n );\n });\n\n return table.toString();\n};\n\nconst startRepl = (options: {\n schema: {\n database: string;\n collections: string[];\n };\n connectionString: string;\n}) => {\n const r = repl.start({\n prompt: chalk.green('pongo> '),\n useGlobal: true,\n breakEvalOnSigint: true,\n writer: printOutput,\n });\n\n const schema =\n options.schema.collections.length > 0\n ? pongoSchema.client({\n database: pongoSchema.db({\n users: pongoSchema.collection(options.schema.database),\n }),\n })\n : undefined;\n\n pongo = pongoClient(options.connectionString, {\n ...(schema ? { schema: { definition: schema } } : {}),\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const db = schema\n ? // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n (pongo as any).database\n : pongo.db(options.schema.database);\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n r.context.db = db;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n r.context.SQL = SQL;\n\n // Intercept REPL output to display results as a table if they are arrays\n r.on('exit', async () => {\n await teardown();\n process.exit();\n });\n\n r.on('SIGINT', async () => {\n await teardown();\n process.exit();\n });\n};\n\nconst teardown = async () => {\n console.log(chalk.yellow('Exiting Pongo Shell...'));\n await pongo.close();\n};\n\nprocess.on('uncaughtException', teardown);\nprocess.on('SIGINT', teardown);\n\ninterface ShellOptions {\n database: string;\n collection: string[];\n connectionString: string;\n}\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 'postgresql://postgres:postgres@localhost:5432/postgres',\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 .action((options: ShellOptions) => {\n const { collection, database } = options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n\n console.log(\n chalk.green(\n 'Starting Pongo Shell. Use db.<collection>.<method>() to query.',\n ),\n );\n startRepl({\n schema: { collections: collection, database },\n connectionString,\n });\n });\n\nexport { shellCommand };\n"],"mappings":";oEACA,OAAS,WAAAA,MAAe,YCDxB,OAAS,WAAAC,MAAe,YACxB,OAAOC,MAAQ,UAQf,IAAMC,EAAkBC,GAA0B,CAChD,GAAIA,EAAM,SAAW,EACnB,OAAOA,EAGT,IAAIC,EAAYD,EAAM,OAAO,CAAC,EAAE,YAAY,EAAIA,EAAM,MAAM,CAAC,EAE7D,OAAIC,EAAU,SAAS,GAAG,IACxBA,EAAYA,EAAU,MAAM,EAAG,EAAE,GAG5BA,CACT,EAEMC,EAAe,CAACC,EAA4B,CAAC,OAAO,IAAM,CAC9D,IAAMC,EAAQD,EACX,IACEE,GACC,QAAQN,EAAeM,CAAI,CAAC,sDAChC,EACC,KAAK;AAAA,CAAI,EAENC,EAAcH,EACjB,IACEE,GACC,SAASA,CAAI,4BAA4BN,EAAeM,CAAI,CAAC,MAAMA,CAAI,KAC3E,EACC,KAAK;AAAA,CAAI,EAEZ,MAAO;AAAA;AAAA,EAEPD,CAAK;AAAA;AAAA;AAAA;AAAA;AAAA,EAKLE,CAAW;AAAA;AAAA;AAAA,GAIb,EAEMC,EAAuB;AAAA;AAAA,EAAwDL,EAAa,CAAC,GAC7FM,EAAgB;AAAA;AAAA,EAAyDN,EAAa,CAAC,GACvFO,EAAa;AAAA;AAAA,EAAyEP,EAAa,CAAC,GACpGQ,EAAmB;AAAA;AAAA,EAAiHR,EAAa,CAAC,GAClJS,EAAqB;AAAA;AAAA,EAAwET,EAAa,CAAC,GAEpGU,EAAiB,MAC5BC,GACmC,CACnC,IAAMC,EAAY,IAAI,IAAID,EAAY,UAAU,QAAQ,IAAI,CAAC,GAAG,EAChE,GAAI,CAEF,IAAME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AAO,2BAA4B,2BAA4B,UAAU,EACzE,OACC,4BACA,8BACA,CAACC,EAAeC,IAEPA,EAAS,OAAO,CAACD,CAAK,CAAC,EAEhC,CAAC,CACH,EACC,OAAQX,GAA0B,CACjC,GAAM,CAAE,WAAAa,EAAY,SAAAC,CAAS,EAAId,EAC3Be,EACJf,EAAQ,kBAAoB,QAAQ,IAAI,qBAE1C,QAAQ,IACNL,EAAM,MACJ,gEACF,CACF,EACAI,EAAU,CACR,OAAQ,CAAE,YAAac,EAAY,SAAAC,CAAS,EAC5C,iBAAAC,CACF,CAAC,CACH,CAAC,EHzJH,IAAMC,EAAU,IAAIC,EAEpBD,EAAQ,KAAK,OAAO,EAAE,YAAY,oBAAoB,EAEtDA,EAAQ,WAAWE,CAAa,EAChCF,EAAQ,WAAWG,CAAc,EACjCH,EAAQ,WAAWI,CAAY,EAE/BJ,EAAQ,MAAM,QAAQ,IAAI,EAE1B,IAAOK,GAAQL","names":["Command","Command","fs","formatTypeName","input","formatted","sampleConfig","collectionNames","types","name","collections","missingDefaultExport","missingSchema","missingDbs","missingDefaultDb","missingCollections","loadConfigFile","configPath","configUrl","imported","parsed","parseDefaultDbSchema","generateConfigFile","fs","error","defaultDb","objectEntries","db","col","toDbSchemaMetadata","configCommand","Command","value","previous","options","combineMigrations","dumbo","migrationTableSchemaComponent","runPostgreSQLMigrations","Command","migrateCommand","Command","value","previous","options","collection","dryRun","connectionString","collectionNames","loadConfigFile","c","pool","dumbo","migrations","collectionsName","pongoCollectionSchemaComponent","runPostgreSQLMigrations","migrationTableSchemaComponent","combineMigrations","JSONSerializer","SQL","chalk","Table","Command","repl","pongo","calculateColumnWidths","results","columnNames","col","result","printOutput","obj","displayResultsAsTable","JSONSerializer","chalk","columnWidths","table","Table","startRepl","options","r","repl","schema","pongoSchema","pongoClient","db","SQL","teardown","shellCommand","Command","value","previous","collection","database","connectionString","program","Command","configCommand","migrateCommand","shellCommand","cli_default"]}
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk7GQ5BP22cjs = require('./chunk-7GQ5BP22.cjs');exports.ConcurrencyError = _chunk7GQ5BP22cjs.o; exports.DOCUMENT_DOES_NOT_EXIST = _chunk7GQ5BP22cjs.u; exports.DOCUMENT_EXISTS = _chunk7GQ5BP22cjs.t; exports.NO_CONCURRENCY_CHECK = _chunk7GQ5BP22cjs.v; exports.OperatorMap = _chunk7GQ5BP22cjs.i; exports.PongoError = _chunk7GQ5BP22cjs.n; exports.QueryOperators = _chunk7GQ5BP22cjs.h; exports.clientToDbOptions = _chunk7GQ5BP22cjs.G; exports.expectedVersion = _chunk7GQ5BP22cjs.y; exports.expectedVersionValue = _chunk7GQ5BP22cjs.x; exports.getPongoDb = _chunk7GQ5BP22cjs.p; exports.hasOperators = _chunk7GQ5BP22cjs.k; exports.isGeneralExpectedDocumentVersion = _chunk7GQ5BP22cjs.w; exports.isNumber = _chunk7GQ5BP22cjs.l; exports.isOperator = _chunk7GQ5BP22cjs.j; exports.isPostgresClientOptions = _chunk7GQ5BP22cjs.c; exports.isString = _chunk7GQ5BP22cjs.m; exports.objectEntries = _chunk7GQ5BP22cjs.s; exports.operationResult = _chunk7GQ5BP22cjs.z; exports.pongoClient = _chunk7GQ5BP22cjs.F; exports.pongoCollection = _chunk7GQ5BP22cjs.f; exports.pongoCollectionPostgreSQLMigrations = _chunk7GQ5BP22cjs.a; exports.pongoCollectionSchemaComponent = _chunk7GQ5BP22cjs.g; exports.pongoDbSchemaComponent = _chunk7GQ5BP22cjs.e; exports.pongoSchema = _chunk7GQ5BP22cjs.A; exports.pongoSession = _chunk7GQ5BP22cjs.r; exports.pongoTransaction = _chunk7GQ5BP22cjs.q; exports.postgresDb = _chunk7GQ5BP22cjs.d; exports.postgresSQLBuilder = _chunk7GQ5BP22cjs.b; exports.proxyClientWithSchema = _chunk7GQ5BP22cjs.C; exports.proxyPongoDbWithSchema = _chunk7GQ5BP22cjs.B; exports.toClientSchemaMetadata = _chunk7GQ5BP22cjs.E; exports.toDbSchemaMetadata = _chunk7GQ5BP22cjs.D;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk2FFAJEOIcjs = require('./chunk-2FFAJEOI.cjs');exports.ConcurrencyError = _chunk2FFAJEOIcjs.o; exports.DOCUMENT_DOES_NOT_EXIST = _chunk2FFAJEOIcjs.u; exports.DOCUMENT_EXISTS = _chunk2FFAJEOIcjs.t; exports.NO_CONCURRENCY_CHECK = _chunk2FFAJEOIcjs.v; exports.OperatorMap = _chunk2FFAJEOIcjs.i; exports.PongoError = _chunk2FFAJEOIcjs.n; exports.QueryOperators = _chunk2FFAJEOIcjs.h; exports.clientToDbOptions = _chunk2FFAJEOIcjs.G; exports.expectedVersion = _chunk2FFAJEOIcjs.y; exports.expectedVersionValue = _chunk2FFAJEOIcjs.x; exports.getPongoDb = _chunk2FFAJEOIcjs.p; exports.hasOperators = _chunk2FFAJEOIcjs.k; exports.isGeneralExpectedDocumentVersion = _chunk2FFAJEOIcjs.w; exports.isNumber = _chunk2FFAJEOIcjs.l; exports.isOperator = _chunk2FFAJEOIcjs.j; exports.isPostgresClientOptions = _chunk2FFAJEOIcjs.c; exports.isString = _chunk2FFAJEOIcjs.m; exports.objectEntries = _chunk2FFAJEOIcjs.s; exports.operationResult = _chunk2FFAJEOIcjs.z; exports.pongoClient = _chunk2FFAJEOIcjs.F; exports.pongoCollection = _chunk2FFAJEOIcjs.f; exports.pongoCollectionPostgreSQLMigrations = _chunk2FFAJEOIcjs.a; exports.pongoCollectionSchemaComponent = _chunk2FFAJEOIcjs.g; exports.pongoDbSchemaComponent = _chunk2FFAJEOIcjs.e; exports.pongoSchema = _chunk2FFAJEOIcjs.A; exports.pongoSession = _chunk2FFAJEOIcjs.r; exports.pongoTransaction = _chunk2FFAJEOIcjs.q; exports.postgresDb = _chunk2FFAJEOIcjs.d; exports.postgresSQLBuilder = _chunk2FFAJEOIcjs.b; exports.proxyClientWithSchema = _chunk2FFAJEOIcjs.C; exports.proxyPongoDbWithSchema = _chunk2FFAJEOIcjs.B; exports.toClientSchemaMetadata = _chunk2FFAJEOIcjs.E; exports.toDbSchemaMetadata = _chunk2FFAJEOIcjs.D;
2
2
  //# sourceMappingURL=index.cjs.map
package/dist/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Dumbo, MigrationStyle, SchemaComponent, SQLMigration, SQL } from '@event-driven-io/dumbo';
2
- import { P as PongoDb, a as PongoDocument, b as PongoCollection, O as OptionalUnlessRequiredIdAndVersion, c as PongoFilter, d as PongoUpdate, U as UpdateOneOptions, W as WithoutId, R as ReplaceOneOptions, D as DeleteOneOptions, e as PongoTransactionOptions, f as PongoSession, g as PongoDbTransaction } from './pongoClient-BY509WFi.cjs';
3
- export { ab as $inc, ac as $push, a9 as $set, aa as $unset, A as AllowedDbClientOptions, a5 as AlternativeType, G as CollectionOperationOptions, C as CollectionsMap, a6 as Condition, r as DBsMap, ah as DOCUMENT_DOES_NOT_EXIST, ag as DOCUMENT_EXISTS, L as DeleteManyOptions, a0 as Document, av as DocumentHandler, T as EnhancedOmit, af as ExpectedDocumentVersion, ad as ExpectedDocumentVersionGeneral, ae as ExpectedDocumentVersionValue, K as HandleOptions, Q as HasId, S as InferIdType, H as InsertManyOptions, I as InsertOneOptions, ai as NO_CONCURRENCY_CHECK, a4 as NonObjectIdLikeDocument, N as NotPooledPongoOptions, M as ObjectId, a3 as ObjectIdLike, am as OperationResult, a1 as OptionalId, V as OptionalUnlessRequiredId, X as OptionalUnlessRequiredVersion, a2 as OptionalVersion, F as PongoClient, i as PongoClientOptions, o as PongoClientSchema, y as PongoClientSchemaMetadata, s as PongoClientWithSchema, m as PongoCollectionSchema, w as PongoCollectionSchemaMetadata, k as PongoDbClientOptions, n as PongoDbSchema, x as PongoDbSchemaMetadata, q as PongoDbWithSchema, at as PongoDeleteManyResult, as as PongoDeleteResult, a8 as PongoFilterOperator, au as PongoHandleResult, ap as PongoInsertManyResult, ao as PongoInsertOneResult, E as PongoSchemaConfig, ar as PongoUpdateManyResult, aq as PongoUpdateResult, h as PooledPongoClientOptions, aw as PostgresDbClientOptions, $ as RegExpOrString, a7 as RootFilterOperators, J as UpdateManyOptions, Y as WithId, Z as WithVersion, _ as WithoutVersion, j as clientToDbOptions, al as expectedVersion, ak as expectedVersionValue, l as getPongoDb, aj as isGeneralExpectedDocumentVersion, ax as isPostgresClientOptions, an as operationResult, p as pongoClient, az as pongoDbSchemaComponent, t as pongoSchema, ay as postgresDb, v as proxyClientWithSchema, u as proxyPongoDbWithSchema, B as toClientSchemaMetadata, z as toDbSchemaMetadata } from './pongoClient-BY509WFi.cjs';
2
+ import { P as PongoDb, a as PongoDocument, b as PongoCollection, O as OptionalUnlessRequiredIdAndVersion, c as PongoFilter, d as PongoUpdate, U as UpdateOneOptions, W as WithoutId, R as ReplaceOneOptions, D as DeleteOneOptions, e as PongoTransactionOptions, f as PongoSession, g as PongoDbTransaction } from './pongoClient-DkAUSd1N.cjs';
3
+ export { ad as $inc, ae as $push, ab as $set, ac as $unset, A as AllowedDbClientOptions, a7 as AlternativeType, G as CollectionOperationOptions, C as CollectionsMap, a8 as Condition, r as DBsMap, aj as DOCUMENT_DOES_NOT_EXIST, ai as DOCUMENT_EXISTS, L as DeleteManyOptions, a2 as Document, ax as DocumentHandler, T as EnhancedOmit, ah as ExpectedDocumentVersion, af as ExpectedDocumentVersionGeneral, ag as ExpectedDocumentVersionValue, K as HandleOptions, Q as HasId, S as InferIdType, H as InsertManyOptions, I as InsertOneOptions, ak as NO_CONCURRENCY_CHECK, a6 as NonObjectIdLikeDocument, N as NotPooledPongoOptions, M as ObjectId, a5 as ObjectIdLike, ao as OperationResult, a3 as OptionalId, V as OptionalUnlessRequiredId, X as OptionalUnlessRequiredVersion, a4 as OptionalVersion, F as PongoClient, i as PongoClientOptions, o as PongoClientSchema, y as PongoClientSchemaMetadata, s as PongoClientWithSchema, m as PongoCollectionSchema, w as PongoCollectionSchemaMetadata, k as PongoDbClientOptions, n as PongoDbSchema, x as PongoDbSchemaMetadata, q as PongoDbWithSchema, av as PongoDeleteManyResult, au as PongoDeleteResult, aa as PongoFilterOperator, aw as PongoHandleResult, ar as PongoInsertManyResult, aq as PongoInsertOneResult, E as PongoSchemaConfig, at as PongoUpdateManyResult, as as PongoUpdateResult, h as PooledPongoClientOptions, ay as PostgresDbClientOptions, a1 as RegExpOrString, a9 as RootFilterOperators, J as UpdateManyOptions, Y as WithId, $ as WithIdAndVersion, Z as WithVersion, a0 as WithoutIdAndVersion, _ as WithoutVersion, j as clientToDbOptions, an as expectedVersion, am as expectedVersionValue, l as getPongoDb, al as isGeneralExpectedDocumentVersion, az as isPostgresClientOptions, ap as operationResult, p as pongoClient, aB as pongoDbSchemaComponent, t as pongoSchema, aA as postgresDb, v as proxyClientWithSchema, u as proxyPongoDbWithSchema, B as toClientSchemaMetadata, z as toDbSchemaMetadata } from './pongoClient-DkAUSd1N.cjs';
4
4
  import 'pg';
5
5
 
6
6
  type PongoCollectionOptions<ConnectorType extends string = string> = {
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Dumbo, MigrationStyle, SchemaComponent, SQLMigration, SQL } from '@event-driven-io/dumbo';
2
- import { P as PongoDb, a as PongoDocument, b as PongoCollection, O as OptionalUnlessRequiredIdAndVersion, c as PongoFilter, d as PongoUpdate, U as UpdateOneOptions, W as WithoutId, R as ReplaceOneOptions, D as DeleteOneOptions, e as PongoTransactionOptions, f as PongoSession, g as PongoDbTransaction } from './pongoClient-BY509WFi.js';
3
- export { ab as $inc, ac as $push, a9 as $set, aa as $unset, A as AllowedDbClientOptions, a5 as AlternativeType, G as CollectionOperationOptions, C as CollectionsMap, a6 as Condition, r as DBsMap, ah as DOCUMENT_DOES_NOT_EXIST, ag as DOCUMENT_EXISTS, L as DeleteManyOptions, a0 as Document, av as DocumentHandler, T as EnhancedOmit, af as ExpectedDocumentVersion, ad as ExpectedDocumentVersionGeneral, ae as ExpectedDocumentVersionValue, K as HandleOptions, Q as HasId, S as InferIdType, H as InsertManyOptions, I as InsertOneOptions, ai as NO_CONCURRENCY_CHECK, a4 as NonObjectIdLikeDocument, N as NotPooledPongoOptions, M as ObjectId, a3 as ObjectIdLike, am as OperationResult, a1 as OptionalId, V as OptionalUnlessRequiredId, X as OptionalUnlessRequiredVersion, a2 as OptionalVersion, F as PongoClient, i as PongoClientOptions, o as PongoClientSchema, y as PongoClientSchemaMetadata, s as PongoClientWithSchema, m as PongoCollectionSchema, w as PongoCollectionSchemaMetadata, k as PongoDbClientOptions, n as PongoDbSchema, x as PongoDbSchemaMetadata, q as PongoDbWithSchema, at as PongoDeleteManyResult, as as PongoDeleteResult, a8 as PongoFilterOperator, au as PongoHandleResult, ap as PongoInsertManyResult, ao as PongoInsertOneResult, E as PongoSchemaConfig, ar as PongoUpdateManyResult, aq as PongoUpdateResult, h as PooledPongoClientOptions, aw as PostgresDbClientOptions, $ as RegExpOrString, a7 as RootFilterOperators, J as UpdateManyOptions, Y as WithId, Z as WithVersion, _ as WithoutVersion, j as clientToDbOptions, al as expectedVersion, ak as expectedVersionValue, l as getPongoDb, aj as isGeneralExpectedDocumentVersion, ax as isPostgresClientOptions, an as operationResult, p as pongoClient, az as pongoDbSchemaComponent, t as pongoSchema, ay as postgresDb, v as proxyClientWithSchema, u as proxyPongoDbWithSchema, B as toClientSchemaMetadata, z as toDbSchemaMetadata } from './pongoClient-BY509WFi.js';
2
+ import { P as PongoDb, a as PongoDocument, b as PongoCollection, O as OptionalUnlessRequiredIdAndVersion, c as PongoFilter, d as PongoUpdate, U as UpdateOneOptions, W as WithoutId, R as ReplaceOneOptions, D as DeleteOneOptions, e as PongoTransactionOptions, f as PongoSession, g as PongoDbTransaction } from './pongoClient-DkAUSd1N.js';
3
+ export { ad as $inc, ae as $push, ab as $set, ac as $unset, A as AllowedDbClientOptions, a7 as AlternativeType, G as CollectionOperationOptions, C as CollectionsMap, a8 as Condition, r as DBsMap, aj as DOCUMENT_DOES_NOT_EXIST, ai as DOCUMENT_EXISTS, L as DeleteManyOptions, a2 as Document, ax as DocumentHandler, T as EnhancedOmit, ah as ExpectedDocumentVersion, af as ExpectedDocumentVersionGeneral, ag as ExpectedDocumentVersionValue, K as HandleOptions, Q as HasId, S as InferIdType, H as InsertManyOptions, I as InsertOneOptions, ak as NO_CONCURRENCY_CHECK, a6 as NonObjectIdLikeDocument, N as NotPooledPongoOptions, M as ObjectId, a5 as ObjectIdLike, ao as OperationResult, a3 as OptionalId, V as OptionalUnlessRequiredId, X as OptionalUnlessRequiredVersion, a4 as OptionalVersion, F as PongoClient, i as PongoClientOptions, o as PongoClientSchema, y as PongoClientSchemaMetadata, s as PongoClientWithSchema, m as PongoCollectionSchema, w as PongoCollectionSchemaMetadata, k as PongoDbClientOptions, n as PongoDbSchema, x as PongoDbSchemaMetadata, q as PongoDbWithSchema, av as PongoDeleteManyResult, au as PongoDeleteResult, aa as PongoFilterOperator, aw as PongoHandleResult, ar as PongoInsertManyResult, aq as PongoInsertOneResult, E as PongoSchemaConfig, at as PongoUpdateManyResult, as as PongoUpdateResult, h as PooledPongoClientOptions, ay as PostgresDbClientOptions, a1 as RegExpOrString, a9 as RootFilterOperators, J as UpdateManyOptions, Y as WithId, $ as WithIdAndVersion, Z as WithVersion, a0 as WithoutIdAndVersion, _ as WithoutVersion, j as clientToDbOptions, an as expectedVersion, am as expectedVersionValue, l as getPongoDb, al as isGeneralExpectedDocumentVersion, az as isPostgresClientOptions, ap as operationResult, p as pongoClient, aB as pongoDbSchemaComponent, t as pongoSchema, aA as postgresDb, v as proxyClientWithSchema, u as proxyPongoDbWithSchema, B as toClientSchemaMetadata, z as toDbSchemaMetadata } from './pongoClient-DkAUSd1N.js';
4
4
  import 'pg';
5
5
 
6
6
  type PongoCollectionOptions<ConnectorType extends string = string> = {
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{A,B,C,D,E,F,G,a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d,m as g,n as h,o as i,p as j,q as k,r as l,s as n,t as q,u as s,v as u,w as v,x as w,y,z}from"./chunk-QO7XUM5F.js";export{i as ConcurrencyError,s as DOCUMENT_DOES_NOT_EXIST,q as DOCUMENT_EXISTS,u as NO_CONCURRENCY_CHECK,a as OperatorMap,h as PongoError,x as QueryOperators,G as clientToDbOptions,y as expectedVersion,w as expectedVersionValue,j as getPongoDb,c as hasOperators,v as isGeneralExpectedDocumentVersion,d as isNumber,b as isOperator,e as isPostgresClientOptions,g as isString,n as objectEntries,z as operationResult,F as pongoClient,p as pongoCollection,o as pongoCollectionPostgreSQLMigrations,t as pongoCollectionSchemaComponent,m as pongoDbSchemaComponent,A as pongoSchema,l as pongoSession,k as pongoTransaction,f as postgresDb,r as postgresSQLBuilder,C as proxyClientWithSchema,B as proxyPongoDbWithSchema,E as toClientSchemaMetadata,D as toDbSchemaMetadata};
1
+ import{A,B,C,D,E,F,G,a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d,m as g,n as h,o as i,p as j,q as k,r as l,s as n,t as q,u as s,v as u,w as v,x as w,y,z}from"./chunk-AG3WMJNZ.js";export{i as ConcurrencyError,s as DOCUMENT_DOES_NOT_EXIST,q as DOCUMENT_EXISTS,u as NO_CONCURRENCY_CHECK,a as OperatorMap,h as PongoError,x as QueryOperators,G as clientToDbOptions,y as expectedVersion,w as expectedVersionValue,j as getPongoDb,c as hasOperators,v as isGeneralExpectedDocumentVersion,d as isNumber,b as isOperator,e as isPostgresClientOptions,g as isString,n as objectEntries,z as operationResult,F as pongoClient,p as pongoCollection,o as pongoCollectionPostgreSQLMigrations,t as pongoCollectionSchemaComponent,m as pongoDbSchemaComponent,A as pongoSchema,l as pongoSession,k as pongoTransaction,f as postgresDb,r as postgresSQLBuilder,C as proxyClientWithSchema,B as proxyPongoDbWithSchema,E as toClientSchemaMetadata,D as toDbSchemaMetadata};
2
2
  //# sourceMappingURL=index.js.map