@event-driven-io/emmett-postgresql 0.20.0-alpha.7 → 0.20.0-alpha.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +2 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/index.js +16 -16
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +363 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +11 -11
- package/dist/cli.cjs +0 -2
- package/dist/cli.cjs.map +0 -1
- package/dist/index.cjs +0 -363
- package/dist/index.cjs.map +0 -1
package/dist/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _commander = require('commander');var e=new (0, _commander.Command)("migrate").description("Manage database migrations");e.command("run").description("Run database migrations").option("-cs, --connectionString <string>","Connection string for the database").option("-dr, --dryRun","Perform dry run without commiting changes",!1).action(t=>{(_nullishCoalesce(t.connectionString, () => (process.env.DB_CONNECTION_STRING)))||(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)),console.log("Nothing has happened, but test was successful")});e.command("sql").description("Generate SQL for database migration").option("--print","Print the SQL to the console (default)",!0).action(t=>{let{collection:n}=t;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)),console.log("Nothing has happened, but test was successful!")});var i={pluginType:"cli",name:"emmett-postgresql",registerCommands:t=>{t.addCommand(e)}},g= exports.default =i;exports.default = g;
|
|
2
2
|
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commandLine/migrate.ts","../src/cli.ts"],"sourcesContent":["import { Command } from 'commander';\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('-dr, --dryRun', 'Perform dry run without commiting changes', false)\n .action((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 console.log('Nothing has happened, but test was successful');\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\n console.log('Nothing has happened, but test was successful!');\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 type { EmmettCliPlugin } from '@event-driven-io/emmett';\nimport { migrateCommand } from './commandLine';\n\nconst cli: EmmettCliPlugin = {\n pluginType: 'cli',\n name: 'emmett-postgresql',\n registerCommands: (program) => {\n program.addCommand(migrateCommand);\n },\n};\n\nexport default cli;\n"]
|
|
1
|
+
{"version":3,"sources":["../src/commandLine/migrate.ts","../src/cli.ts"],"names":["migrateCommand","Command","options","collection","cli","program","cli_default"],"mappings":"AAAA,mNAAwB,IAeXA,CAAAA,CAAiB,IAAIC,uBAAAA,CAAQ,SAAS,CAAA,CAAE,WAAA,CACnD,4BACF,CAAA,CAEAD,CAAAA,CACG,OAAA,CAAQ,KAAK,CAAA,CACb,WAAA,CAAY,yBAAyB,CAAA,CACrC,MAAA,CACC,kCAAA,CACA,oCACF,CAAA,CAUC,MAAA,CAAO,eAAA,CAAiB,2CAAA,CAA6C,CAAA,CAAK,CAAA,CAC1E,MAAA,CAAQE,CAAAA,EAA+B,CAAA,kBAGpCA,CAAAA,CAAQ,gBAAA,SAAoB,OAAA,CAAQ,GAAA,CAAI,sBAAA,CAAA,EAAA,CAIxC,OAAA,CAAQ,KAAA,CACN,uJACF,CAAA,CACA,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,CAAA,CAGhB,OAAA,CAAQ,GAAA,CAAI,+CAA+C,CAyB7D,CAAC,CAAA,CAEHF,CAAAA,CACG,OAAA,CAAQ,KAAK,CAAA,CACb,WAAA,CAAY,qCAAqC,CAAA,CAUjD,MAAA,CAAO,SAAA,CAAW,wCAAA,CAA0C,CAAA,CAAI,CAAA,CAEhE,MAAA,CAAQE,CAAAA,EAA+B,CACtC,GAAM,CAAE,UAAA,CAAAC,CAAW,CAAA,CAAID,CAAAA,CAElBC,CAAAA,EAAAA,CACH,OAAA,CAAQ,KAAA,CACN,8GACF,CAAA,CACA,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,CAAA,CAGhB,OAAA,CAAQ,GAAA,CAAI,gDAAgD,CAe9D,CAAC,CAAA,CChHH,IAAMC,CAAAA,CAAuB,CAC3B,UAAA,CAAY,KAAA,CACZ,IAAA,CAAM,mBAAA,CACN,gBAAA,CAAmBC,CAAAA,EAAY,CAC7BA,CAAAA,CAAQ,UAAA,CAAWL,CAAc,CACnC,CACF,CAAA,CAEOM,CAAAA,mBAAQF,CAAAA,CAAAA,oBAAAA","file":"/home/runner/work/emmett/emmett/src/packages/emmett-postgresql/dist/cli.js","sourcesContent":["import { Command } from 'commander';\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('-dr, --dryRun', 'Perform dry run without commiting changes', false)\n .action((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 console.log('Nothing has happened, but test was successful');\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\n console.log('Nothing has happened, but test was successful!');\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 type { EmmettCliPlugin } from '@event-driven-io/emmett';\nimport { migrateCommand } from './commandLine';\n\nconst cli: EmmettCliPlugin = {\n pluginType: 'cli',\n name: 'emmett-postgresql',\n registerCommands: (program) => {\n program.addCommand(migrateCommand);\n },\n};\n\nexport default cli;\n"]}
|
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{Command as o}from"commander";var e=new o("migrate").description("Manage database migrations");e.command("run").description("Run database migrations").option("-cs, --connectionString <string>","Connection string for the database").option("-dr, --dryRun","Perform dry run without commiting changes",!1).action(t=>{(t.connectionString??process.env.DB_CONNECTION_STRING)||(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)),console.log("Nothing has happened, but test was successful")});e.command("sql").description("Generate SQL for database migration").option("--print","Print the SQL to the console (default)",!0).action(t=>{let{collection:n}=t;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)),console.log("Nothing has happened, but test was successful!")});var i={pluginType:"cli",name:"emmett-postgresql",registerCommands:t=>{t.addCommand(e)}},g=i;export{g as default};
|
|
2
|
+
//# sourceMappingURL=cli.mjs.map
|
package/dist/cli.mjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commandLine/migrate.ts","../src/cli.ts"],"sourcesContent":["import { Command } from 'commander';\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('-dr, --dryRun', 'Perform dry run without commiting changes', false)\n .action((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 console.log('Nothing has happened, but test was successful');\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\n console.log('Nothing has happened, but test was successful!');\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 type { EmmettCliPlugin } from '@event-driven-io/emmett';\nimport { migrateCommand } from './commandLine';\n\nconst cli: EmmettCliPlugin = {\n pluginType: 'cli',\n name: 'emmett-postgresql',\n registerCommands: (program) => {\n program.addCommand(migrateCommand);\n },\n};\n\nexport default cli;\n"],"mappings":"AAAA,OAAS,WAAAA,MAAe,YAejB,IAAMC,EAAiB,IAAID,EAAQ,SAAS,EAAE,YACnD,4BACF,EAEAC,EACG,QAAQ,KAAK,EACb,YAAY,yBAAyB,EACrC,OACC,mCACA,oCACF,EAUC,OAAO,gBAAiB,4CAA6C,EAAK,EAC1E,OAAQC,GAA+B,EAGpCA,EAAQ,kBAAoB,QAAQ,IAAI,wBAIxC,QAAQ,MACN,uJACF,EACA,QAAQ,KAAK,CAAC,GAGhB,QAAQ,IAAI,+CAA+C,CAyB7D,CAAC,EAEHD,EACG,QAAQ,KAAK,EACb,YAAY,qCAAqC,EAUjD,OAAO,UAAW,yCAA0C,EAAI,EAEhE,OAAQC,GAA+B,CACtC,GAAM,CAAE,WAAAC,CAAW,EAAID,EAElBC,IACH,QAAQ,MACN,8GACF,EACA,QAAQ,KAAK,CAAC,GAGhB,QAAQ,IAAI,gDAAgD,CAe9D,CAAC,EChHH,IAAMC,EAAuB,CAC3B,WAAY,MACZ,KAAM,oBACN,iBAAmBC,GAAY,CAC7BA,EAAQ,WAAWC,CAAc,CACnC,CACF,EAEOC,EAAQH","names":["Command","migrateCommand","options","collection","cli","program","migrateCommand","cli_default"]}
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3;var _dumbo = require('@event-driven-io/dumbo');require('commander');var z=(e=>(e.NOT_A_NONEMPTY_STRING="NOT_A_NONEMPTY_STRING",e.NOT_A_POSITIVE_NUMBER="NOT_A_POSITIVE_NUMBER",e.NOT_AN_UNSIGNED_BIGINT="NOT_AN_UNSIGNED_BIGINT",e))(z||{}),H=e=>typeof e=="number"&&e===e,Y=e=>typeof e=="string";var F=e=>typeof e=="function"&&e.prototype&&e.prototype.constructor===e,J=class K extends Error{constructor(t){let n=t&&typeof t=="object"&&"errorCode"in t?t.errorCode:H(t)?t:500,a=t&&typeof t=="object"&&"message"in t?t.message:Y(t)?t:`Error with status code '${n}' ocurred during Emmett processing`;super(a),this.errorCode=n,Object.setPrototypeOf(this,K.prototype)}},Z=class ee extends J{constructor(t,n,a){super({errorCode:412,message:_nullishCoalesce(a, () => (`Expected version ${n.toString()} does not match current ${_optionalChain([t, 'optionalAccess', _2 => _2.toString, 'call', _3 => _3()])}`))}),this.current=t,this.expected=n,Object.setPrototypeOf(this,ee.prototype)}};var _uuid = require('uuid');var _webstreamspolyfill = require('web-streams-polyfill');var _asyncretry = require('async-retry'); var _asyncretry2 = _interopRequireDefault(_asyncretry);var $=(e,t,n)=>({type:e,data:t,metadata:n});var xe="__emt:GlobalStreamCaughtUp";var te=e=>$(xe,e,{globalPosition:e.globalPosition});var j="STREAM_EXISTS",Q="STREAM_DOES_NOT_EXIST",O="NO_CONCURRENCY_CHECK",we=(e,t,n)=>t===O?!0:t==Q?e===n:t==j?e!==n:e===t,ne=(e,t,n)=>{if(t??=O,!we(e,t,n))throw new B(e,t)},B=class ae extends Z{constructor(t,n){super(_optionalChain([t, 'optionalAccess', _4 => _4.toString, 'call', _5 => _5()]),_optionalChain([n, 'optionalAccess', _6 => _6.toString, 'call', _7 => _7()])),Object.setPrototypeOf(this,ae.prototype)}};var Fe={ReadableStream:_webstreamspolyfill.ReadableStream,WritableStream:_webstreamspolyfill.WritableStream,TransformStream:_webstreamspolyfill.TransformStream},Qt=typeof process<"u"&&process.versions!=null&&process.versions.bun!=null,U;globalThis&&globalThis.WritableStream&&globalThis.ReadableStream&&globalThis.TransformStream?U=globalThis:U=Fe;var g=U;var Bt=class extends g.TransformStream{constructor(e){super({start:t=>{let n=0n;for(let a of e)t.enqueue(a),n=a.metadata.globalPosition;t.enqueue(te({globalPosition:n}))},transform:(t,n)=>{this._currentPosition=t.metadata.globalPosition,n.enqueue(t),!(this._currentPosition<this._logPosition)&&n.enqueue(te({globalPosition:this._currentPosition}))}}),this._currentPosition=this._logPosition=e.length>0?e[e.length-1].metadata.globalPosition:0n}set logPosition(e){this._logPosition=e}},$e=(e,t={})=>new oe(e,t),oe= (_class =class extends g.TransformStream{constructor(e,t={}){super({cancel:n=>{console.log("Stream was canceled. Reason:",n),this.stopChecking()}});_class.prototype.__init.call(this);_class.prototype.__init2.call(this);,this.onNoActiveReaderCallback=e,this.streamId=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _8 => _8.streamId]), () => (_uuid.v4.call(void 0, ))),this.onNoActiveReaderCallback=e,this.startChecking(_nullishCoalesce(_optionalChain([t, 'optionalAccess', _9 => _9.intervalCheckInMs]), () => (20)))}__init() {this.checkInterval=null}__init2() {this._isStopped=!1}get hasActiveSubscribers(){return!this._isStopped}startChecking(e){this.checkInterval=setInterval(()=>{this.checkNoActiveReader()},e)}stopChecking(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null,this._isStopped=!0,this.onNoActiveReaderCallback(this))}checkNoActiveReader(){!this.readable.locked&&!this._isStopped&&this.stopChecking()}}, _class);var u=(e,t)=>{if(je(e))return e.equals(t);if(Array.isArray(e))return Array.isArray(t)&&e.length===t.length&&e.every((o,i)=>u(o,t[i]));if(typeof e!="object"||typeof t!="object"||e===null||t===null)return e===t;if(Array.isArray(t))return!1;let n=Object.keys(e),a=Object.keys(t);if(n.length!==a.length||!n.every(o=>a.includes(o)))return!1;for(let o in e)if(!(e[o]instanceof Function&&t[o]instanceof Function)&&!u(e[o],t[o]))return!1;return!0},je=e=>e&&typeof e=="object"&&"equals"in e&&typeof e.equals=="function";var Be=async(e,t)=>t===void 0||t.retries===0?e():_asyncretry2.default.call(void 0, async n=>{try{return await e()}catch(a){throw _optionalChain([t, 'optionalAccess', _10 => _10.shouldRetryError])&&!t.shouldRetryError(a)&&n(a),a}},_nullishCoalesce(t, () => ({retries:0})));var re=e=>e;var Xe=class extends Error{constructor(e){super(`Cannot parse! ${e}`)}},P={stringify:(e,t)=>JSON.stringify(_optionalChain([t, 'optionalAccess', _11 => _11.map])?t.map(e):e,(n,a)=>typeof a=="bigint"?a.toString():a),parse:(e,t)=>{let n=JSON.parse(e,_optionalChain([t, 'optionalAccess', _12 => _12.reviver]));if(_optionalChain([t, 'optionalAccess', _13 => _13.typeCheck])&&!_optionalChain([t, 'optionalAccess', _14 => _14.typeCheck, 'call', _15 => _15(n)]))throw new Xe(e);return _optionalChain([t, 'optionalAccess', _16 => _16.map])?t.map(n):n}};var Ve=e=>new g.TransformStream({transform(t,n){e(t)&&n.enqueue(t)}}),Ge=e=>new g.TransformStream({transform(t,n){n.enqueue(e(t))}}),ke=(e,t)=>new ie(e,t),ie=class extends g.TransformStream{constructor(e,t){super({transform:n=>{this.accumulator=this.reducer(this.accumulator,n)},flush:n=>{n.enqueue(this.accumulator),n.terminate()}}),this.accumulator=t,this.reducer=e}},We=(e,t,n={forever:!0,minTimeout:25})=>new g.TransformStream({start(a){Be(()=>qe(e,t,a),n).catch(o=>{a.error(o)})}}),qe=async(e,t,n)=>{let a=e().getReader();try{let o;do{let i=await a.read();o=i.done,await t(i,n),o&&n.terminate()}while(!o)}finally{a.releaseLock()}},ze=e=>new se(e),se= (_class2 =class extends g.TransformStream{__init3() {this.count=0}constructor(e){super({transform:(t,n)=>{this.count++,this.count>this.skip&&n.enqueue(t)}});_class2.prototype.__init3.call(this);,this.skip=e}}, _class2),He=e=>new g.TransformStream({transform(t,n){n.enqueue(t),e(t)&&n.terminate()}}),Ye=e=>new g.TransformStream({async transform(t,n){if(!e(t)){n.enqueue(t);return}await Promise.resolve(),n.terminate()}}),Je=e=>new ce(e),ce= (_class3 =class extends g.TransformStream{__init4() {this.count=0}constructor(e){super({transform:(t,n)=>{this.count<this.limit?(this.count++,n.enqueue(t)):n.terminate()}});_class3.prototype.__init4.call(this);,this.limit=e}}, _class3),Ke=e=>new g.TransformStream({start(t){let n=setTimeout(()=>{t.terminate()},e),a=t.terminate.bind(t);t.terminate=()=>{clearTimeout(n),a()}},transform(t,n){n.enqueue(t)}}),Ze={filter:Ve,take:Je,TakeTransformStream:ce,skip:ze,SkipTransformStream:se,map:Ge,notifyAboutNoActiveReadersStream:$e,NotifyAboutNoActiveReadersStream:oe,reduce:ke,ReduceTransformStream:ie,retry:We,stopAfter:He,stopOn:Ye,waitAtMost:Ke},{retry:Wt}=Ze;var h=class extends Error{constructor(e){super(e)}};var me=e=>{throw new h(_nullishCoalesce(e, () => ("That should not ever happened, right?")))};var le=(e,t,n)=>{if(!u(e,t))throw new h(_nullishCoalesce(n, () => (`subObj:
|
|
2
2
|
${P.stringify(t)}
|
|
3
3
|
is not equal to
|
|
4
|
-
${P.stringify(e)}`)};function T(e,t){if(!e)throw new h(t
|
|
4
|
+
${P.stringify(e)}`)))};function T(e,t){if(!e)throw new h(_nullishCoalesce(t, () => ("Condition is false")))}function et(e,t){if(!e)throw new h(_nullishCoalesce(t, () => ("Condition is not truthy")))}function y(e,t,n){if(e!==t)throw new h(`${_nullishCoalesce(n, () => ("Objects are not equal"))}:
|
|
5
5
|
Expected: ${P.stringify(e)}
|
|
6
|
-
Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(n
|
|
6
|
+
Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(_nullishCoalesce(n, () => (`Objects are equal: ${P.stringify(e)}`)))}function X(e){de(e,null),et(e)}var A=e=>({isEmpty:()=>y(e.length,0),isNotEmpty:()=>de(e.length,0),hasSize:t=>y(e.length,t),containsElements:(...t)=>{T(t.every(n=>t.some(a=>u(n,a))))},containsExactlyInAnyOrder:(...t)=>{y(e.length,t.length),T(e.every(n=>t.some(a=>u(n,a))))},containsExactlyInAnyOrderElementsOf:t=>{y(e.length,t.length),T(e.every(n=>t.some(a=>u(n,a))))},containsExactlyElementsOf:t=>{y(e.length,t.length);for(let n=0;n<e.length;n++)T(u(e[n],t[n]))},containsExactly:t=>{y(e.length,1),T(u(e[0],t))},contains:t=>{T(e.some(n=>u(n,t)))},containsOnlyOnceElementsOf:t=>{T(t.map(n=>e.filter(a=>u(a,n)).length).filter(n=>n===1).length===t.length)},containsAnyOf:(...t)=>{T(e.some(n=>t.some(a=>u(n,a))))},allMatch:t=>{T(e.every(t))},anyMatches:t=>{T(e.some(t))},allMatchAsync:async t=>{for(let n of e)T(await t(n))}});require('pg');var _pongo = require('@event-driven-io/pongo');var L=(e,t)=>{let{pool:n,connectionString:a,inDatabase:o,inCollection:i}=t;return n.withConnection(async p=>{let m=_pongo.pongoClient.call(void 0, a,{connectionOptions:{connection:p}});try{let E=m.db(o).collection(i);return e(E)}finally{await m.close()}})},Ee=e=>{let{_id:t,_version:n,...a}=e;return a},nt=(e,t)=>("_id"in t&&y(t._id,e._id,`Document ids are not matching! Expected: ${t._id}, actual: ${e._id}`),le(Ee(e),Ee(t))),at= exports.documentExists =(e,t)=>n=>L(async a=>{let o=await a.findOne("withId"in t?{_id:t.withId}:t.matchingFilter);X(o),nt(o,e)},{...t,...n}),ot= exports.documentsAreTheSame =(e,t)=>n=>L(async a=>{let o=await a.find("withId"in t?{_id:t.withId}:t.matchingFilter);y(e.length,o.length,"Different Documents Count than expected");for(let i=0;i<e.length;i++)A(o).contains(e[i])},{...t,...n}),rt= exports.documentsMatchingHaveCount =(e,t)=>n=>L(async a=>{let o=await a.find("withId"in t?{_id:t.withId}:t.matchingFilter);y(e,o.length,"Different Documents Count than expected")},{...t,...n}),pe= exports.documentMatchingExists =e=>t=>L(async n=>{let a=await n.find("withId"in e?{_id:e.withId}:e.matchingFilter);A(a).isNotEmpty()},{...e,...t}),ve= exports.documentDoesNotExist =e=>t=>L(async n=>{let a=await n.findOne("withId"in e?{_id:e.withId}:e.matchingFilter);X(a)},{...e,...t}),rn= exports.expectPongoDocuments ={fromCollection:e=>({withId:t=>({toBeEqual:n=>at(n,{withId:t,inCollection:e}),toExist:()=>pe({withId:t,inCollection:e}),notToExist:()=>ve({withId:t,inCollection:e})}),matching:t=>({toBeTheSame:n=>ot(n,{matchingFilter:t,inCollection:e}),toHaveCount:n=>rt(n,{matchingFilter:t,inCollection:e}),toExist:()=>pe({matchingFilter:t,inCollection:e}),notToExist:()=>ve({matchingFilter:t,inCollection:e})})})};var st=({handle:e,canHandle:t})=>V({canHandle:t,handle:async(n,a)=>{let{connectionString:o,client:i}=a,p=_pongo.pongoClient.call(void 0, o,{connectionOptions:{client:i}});await e(n,{...a,pongo:p})}}),ct= exports.pongoMultiStreamProjection =e=>{let{collectionName:t,getDocumentId:n,canHandle:a}=e;return st({handle:async(o,{pongo:i})=>{let p=i.db().collection(t);for(let m of o)await p.handle(n(m),async E=>"initialState"in e?await e.evolve(_nullishCoalesce(E, () => (e.initialState())),m):await e.evolve(E,m))},canHandle:a})},dn= exports.pongoSingleStreamProjection =e=>ct({...e,getDocumentId:t=>t.metadata.streamName});var yn={for:e=>{{let{projection:t,...n}=e,{connectionString:a}=n;return o=>({when:(i,p)=>{let m=[],E=async c=>{let d=0n,l=_nullishCoalesce(_optionalChain([p, 'optionalAccess', _17 => _17.numberOfTimes]), () => (1));for(let v of[...o,...Array.from({length:l}).flatMap(()=>i)])m.push({...v,metadata:{globalPosition:++d,streamPosition:d,streamName:`test-${_uuid.v4.call(void 0, )}`,eventId:_uuid.v4.call(void 0, ),..._nullishCoalesce(v.metadata, () => ({}))}});await c.withTransaction(v=>x({events:m,projections:[t],connection:{connectionString:a,transaction:v}}))};return{then:async(c,d)=>{let l=_dumbo.dumbo.call(void 0, n);try{await E(l);let v=await c({pool:l,connectionString:a});v!==void 0&&v===!1&&me(_nullishCoalesce(d, () => ("Projection specification didn't match the criteria")))}finally{await l.close()}},thenThrows:async(...c)=>{let d=_dumbo.dumbo.call(void 0, n);try{throw await E(d),new h("Handler did not fail as expected")}catch(l){if(l instanceof h)throw l;if(c.length===0)return;if(!F(c[0])){T(c[0](l),`Error didn't match the error condition: ${_optionalChain([l, 'optionalAccess', _18 => _18.toString, 'call', _19 => _19()])}`);return}T(l instanceof c[0],`Caught error is not an instance of the expected type: ${_optionalChain([l, 'optionalAccess', _20 => _20.toString, 'call', _21 => _21()])}`),c[1]&&T(c[1](l),`Error didn't match the error condition: ${_optionalChain([l, 'optionalAccess', _22 => _22.toString, 'call', _23 => _23()])}`)}finally{await d.close()}}}}})}}},mt= exports.eventInStream =(e,t)=>({...t,metadata:{..._nullishCoalesce(t.metadata, () => ({})),streamName:_nullishCoalesce(_optionalChain([t, 'access', _24 => _24.metadata, 'optionalAccess', _25 => _25.streamName]), () => (e))}}),lt= exports.eventsInStream =(e,t)=>t.map(n=>mt(e,n)),fn= exports.newEventsInStream =lt,dt= exports.assertSQLQueryResultMatches =(e,t)=>async({pool:{execute:n}})=>{let a=await n.query(e);A(t).containsExactlyInAnyOrder(...a.rows)},hn= exports.expectSQL ={query:e=>({resultRows:{toBeTheSame:t=>dt(e,t)}})};var x=async e=>{let{projections:t,events:n,connection:{transaction:a,connectionString:o}}=e,i=n.map(E=>E.type),p=t.filter(E=>E.canHandle.some(c=>i.includes(c))),m=await a.connection.open();for(let E of p)await E.handle(n,{connectionString:o,client:m,transaction:a,execute:a.execute})},V= exports.postgreSQLProjection =e=>re(e),Et= exports.postgreSQLRawBatchSQLProjection =(e,...t)=>V({canHandle:t,handle:async(n,a)=>{let o=await e(n,a);await a.execute.batchCommand(o)}}),On= exports.postgreSQLRawSQLProjection =(e,...t)=>Et(async(n,a)=>{let o=[];for(let i of n)o.push(await e(i,a));return o},...t);var w="emt",_= exports.globalTag ="global",R= exports.defaultTag ="emt:default",Dn= exports.globalNames ={module:`${w}:module:${_}`,tenant:`${w}:tenant:${_}`},C={partition:{name:"partition"},isArchived:{name:"is_archived"}},s= exports.streamsTable ={name:`${w}_streams`,columns:{partition:C.partition,isArchived:C.isArchived}},r= exports.eventsTable ={name:`${w}_events`,columns:{partition:C.partition,isArchived:C.isArchived}};var ue=_dumbo.rawSql.call(void 0, `CREATE OR REPLACE FUNCTION emt_append_event(
|
|
7
7
|
v_event_ids text[],
|
|
8
8
|
v_events_data jsonb[],
|
|
9
9
|
v_events_metadata jsonb[],
|
|
@@ -85,7 +85,7 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(n??`Objects a
|
|
|
85
85
|
RETURN QUERY SELECT TRUE, v_next_stream_position, v_last_global_position, v_transaction_id;
|
|
86
86
|
END;
|
|
87
87
|
$$;
|
|
88
|
-
`),ge=(e,t,n,a,o)=>e.withTransaction(async i=>{let{execute:p}=i;if(a.length===0)return{success:!1,result:{success:!1}};let m;try{let v=Tt(o
|
|
88
|
+
`),ge= exports.appendToStream =(e,t,n,a,o)=>e.withTransaction(async i=>{let{execute:p}=i;if(a.length===0)return{success:!1,result:{success:!1}};let m;try{let v=Tt(_optionalChain([o, 'optionalAccess', _26 => _26.expectedStreamVersion])),I=a.map((N,f)=>({...N,metadata:{streamName:t,eventId:_uuid.v4.call(void 0, ),streamPosition:BigInt(f),...N.metadata}}));m=await gt(p,t,n,I,{expectedStreamVersion:v}),_optionalChain([o, 'optionalAccess', _27 => _27.preCommitHook])&&await o.preCommitHook(I,{transaction:i})}catch(v){if(!ut(v))throw v;m={success:!1,last_global_position:null,next_stream_position:null,transaction_id:null}}let{success:E,next_stream_position:c,last_global_position:d,transaction_id:l}=m;return{success:E,result:E&&c&&d&&l?{success:!0,nextStreamPosition:BigInt(c),lastGlobalPosition:BigInt(d),transactionId:l}:{success:!1}}}),Tt=e=>e===void 0||e===O||e==Q||e==j?null:e,ut=e=>e instanceof Error&&"code"in e&&e.code==="23505",gt=(e,t,n,a,o)=>_dumbo.single.call(void 0, e.command(_dumbo.sql.call(void 0, `SELECT * FROM emt_append_event(
|
|
89
89
|
ARRAY[%s]::text[],
|
|
90
90
|
ARRAY[%s]::jsonb[],
|
|
91
91
|
ARRAY[%s]::jsonb[],
|
|
@@ -95,7 +95,7 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(n??`Objects a
|
|
|
95
95
|
%L::text,
|
|
96
96
|
%s::bigint,
|
|
97
97
|
%L::text
|
|
98
|
-
)`,a.map(i=>
|
|
98
|
+
)`,a.map(i=>_dumbo.sql.call(void 0, "%L",i.metadata.eventId)).join(","),a.map(i=>_dumbo.sql.call(void 0, "%L",P.stringify(i.data))).join(","),a.map(i=>_dumbo.sql.call(void 0, "%L",P.stringify(_nullishCoalesce(i.metadata, () => ({}))))).join(","),a.map(()=>"'1'").join(","),a.map(i=>_dumbo.sql.call(void 0, "%L",i.type)).join(","),t,n,_nullishCoalesce(_optionalChain([o, 'optionalAccess', _28 => _28.expectedStreamVersion]), () => ("NULL")),_nullishCoalesce(_optionalChain([o, 'optionalAccess', _29 => _29.partition]), () => (R)))));var Se=_dumbo.rawSql.call(void 0, `CREATE TABLE IF NOT EXISTS ${s.name}(
|
|
99
99
|
stream_id TEXT NOT NULL,
|
|
100
100
|
stream_position BIGINT NOT NULL,
|
|
101
101
|
partition TEXT NOT NULL DEFAULT '${_}__${_}',
|
|
@@ -104,7 +104,7 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(n??`Objects a
|
|
|
104
104
|
is_archived BOOLEAN NOT NULL DEFAULT FALSE,
|
|
105
105
|
PRIMARY KEY (stream_id, stream_position, partition, is_archived),
|
|
106
106
|
UNIQUE (stream_id, partition, is_archived)
|
|
107
|
-
) PARTITION BY LIST (partition);`),ye=
|
|
107
|
+
) PARTITION BY LIST (partition);`),ye= exports.eventsTableSQL =_dumbo.rawSql.call(void 0, `
|
|
108
108
|
CREATE SEQUENCE IF NOT EXISTS emt_global_event_position;
|
|
109
109
|
|
|
110
110
|
CREATE TABLE IF NOT EXISTS ${r.name}(
|
|
@@ -121,7 +121,7 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(n??`Objects a
|
|
|
121
121
|
transaction_id XID8 NOT NULL,
|
|
122
122
|
created TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
123
123
|
PRIMARY KEY (stream_id, stream_position, partition, is_archived)
|
|
124
|
-
) PARTITION BY LIST (partition);`),fe=
|
|
124
|
+
) PARTITION BY LIST (partition);`),fe= exports.subscriptionsTableSQL =_dumbo.rawSql.call(void 0, `
|
|
125
125
|
CREATE TABLE IF NOT EXISTS emt_subscriptions(
|
|
126
126
|
subscription_id TEXT NOT NULL PRIMARY KEY,
|
|
127
127
|
version INT NOT NULL DEFAULT 1,
|
|
@@ -130,11 +130,11 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(n??`Objects a
|
|
|
130
130
|
last_processed_position BIGINT NOT NULL,
|
|
131
131
|
last_processed_transaction_id BIGINT NOT NULL
|
|
132
132
|
);
|
|
133
|
-
`),he=
|
|
133
|
+
`),he= exports.sanitizeNameSQL =_dumbo.rawSql.call(void 0, `CREATE OR REPLACE FUNCTION emt_sanitize_name(input_name TEXT) RETURNS TEXT AS $$
|
|
134
134
|
BEGIN
|
|
135
135
|
RETURN REGEXP_REPLACE(input_name, '[^a-zA-Z0-9_]', '_', 'g');
|
|
136
136
|
END;
|
|
137
|
-
$$ LANGUAGE plpgsql;`),Pe=
|
|
137
|
+
$$ LANGUAGE plpgsql;`),Pe= exports.addTablePartitions =_dumbo.rawSql.call(void 0, `
|
|
138
138
|
CREATE OR REPLACE FUNCTION emt_add_table_partition(tableName TEXT, partition_name TEXT) RETURNS void AS $$
|
|
139
139
|
DECLARE
|
|
140
140
|
v_main_partiton_name TEXT;
|
|
@@ -171,13 +171,13 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(n??`Objects a
|
|
|
171
171
|
v_archived_partiton_name, v_main_partiton_name
|
|
172
172
|
);
|
|
173
173
|
END;
|
|
174
|
-
$$ LANGUAGE plpgsql;`),Ie=
|
|
174
|
+
$$ LANGUAGE plpgsql;`),Ie= exports.addEventsPartitions =_dumbo.rawSql.call(void 0, `
|
|
175
175
|
CREATE OR REPLACE FUNCTION emt_add_partition(partition_name TEXT) RETURNS void AS $$
|
|
176
176
|
BEGIN
|
|
177
177
|
PERFORM emt_add_table_partition('${r.name}', partition_name);
|
|
178
178
|
PERFORM emt_add_table_partition('${s.name}', partition_name);
|
|
179
179
|
END;
|
|
180
|
-
$$ LANGUAGE plpgsql;`),Ne=
|
|
180
|
+
$$ LANGUAGE plpgsql;`),Ne= exports.addModuleSQL =_dumbo.rawSql.call(void 0, `
|
|
181
181
|
CREATE OR REPLACE FUNCTION add_module(new_module TEXT) RETURNS void AS $$
|
|
182
182
|
BEGIN
|
|
183
183
|
-- For ${r.name} table
|
|
@@ -219,7 +219,7 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(n??`Objects a
|
|
|
219
219
|
);
|
|
220
220
|
END;
|
|
221
221
|
$$ LANGUAGE plpgsql;
|
|
222
|
-
`),Oe=
|
|
222
|
+
`),Oe= exports.addTenantSQL =_dumbo.rawSql.call(void 0, `
|
|
223
223
|
CREATE OR REPLACE FUNCTION add_tenant(new_module TEXT, new_tenant TEXT) RETURNS void AS $$
|
|
224
224
|
BEGIN
|
|
225
225
|
-- For ${r.name} table
|
|
@@ -261,7 +261,7 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(n??`Objects a
|
|
|
261
261
|
);
|
|
262
262
|
END;
|
|
263
263
|
$$ LANGUAGE plpgsql;
|
|
264
|
-
`),Re=
|
|
264
|
+
`),Re= exports.addModuleForAllTenantsSQL =_dumbo.rawSql.call(void 0, `
|
|
265
265
|
CREATE OR REPLACE FUNCTION add_module_for_all_tenants(new_module TEXT) RETURNS void AS $$
|
|
266
266
|
DECLARE
|
|
267
267
|
tenant_record RECORD;
|
|
@@ -310,7 +310,7 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(n??`Objects a
|
|
|
310
310
|
END LOOP;
|
|
311
311
|
END;
|
|
312
312
|
$$ LANGUAGE plpgsql;
|
|
313
|
-
`),Ae=
|
|
313
|
+
`),Ae= exports.addTenantForAllModulesSQL =_dumbo.rawSql.call(void 0, `
|
|
314
314
|
CREATE OR REPLACE FUNCTION add_tenant_for_all_modules(new_tenant TEXT) RETURNS void AS $$
|
|
315
315
|
DECLARE
|
|
316
316
|
module_record RECORD;
|
|
@@ -357,7 +357,7 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(n??`Objects a
|
|
|
357
357
|
END LOOP;
|
|
358
358
|
END;
|
|
359
359
|
$$ LANGUAGE plpgsql;
|
|
360
|
-
`),Le=
|
|
360
|
+
`),Le= exports.addDefaultPartition =_dumbo.rawSql.call(void 0, `SELECT emt_add_partition('${R}');`);var De=async(e,t,n)=>{let a=n&&"from"in n?`AND stream_position >= ${n.from}`:"",o=Number(n&&"to"in n?n.to:n&&"maxCount"in n&&n.maxCount?n.from+n.maxCount:NaN),i=isNaN(o)?"":`AND stream_position <= ${o}`,p=await _dumbo.mapRows.call(void 0, e.query(_dumbo.sql.call(void 0, `SELECT stream_id, stream_position, global_position, event_data, event_metadata, event_schema_version, event_type, event_id
|
|
361
361
|
FROM ${r.name}
|
|
362
|
-
WHERE stream_id = %L AND partition = %L AND is_archived = FALSE ${a} ${i}`,t,n
|
|
362
|
+
WHERE stream_id = %L AND partition = %L AND is_archived = FALSE ${a} ${i}`,t,_nullishCoalesce(_optionalChain([n, 'optionalAccess', _30 => _30.partition]), () => (R)))),m=>{let E=$(m.event_type,m.event_data,m.event_metadata);return{...E,metadata:{...E.metadata,eventId:m.event_id,streamName:t,streamPosition:BigInt(m.stream_position),globalPosition:BigInt(m.global_position)}}});return p.length>0?{currentStreamVersion:p[p.length-1].metadata.streamPosition,events:p,streamExists:!0}:{currentStreamVersion:G,events:[],streamExists:!1}};var b=[Se,ye,fe,he,Pe,Ie,Ne,Oe,Re,Ae,ue,Le],k= exports.createEventStoreSchema =async e=>{await e.withTransaction(({execute:t})=>t.batchCommand(b))};var ht={projections:[],schema:{autoMigration:"CreateOrUpdate"}},G= exports.PostgreSQLEventStoreDefaultStreamVersion =0n,Pt= exports.getPostgreSQLEventStore =(e,t=ht)=>{let n={connectionString:e,...t.connectionOptions?t.connectionOptions:{}},a="dumbo"in n?n.dumbo:_dumbo.dumbo.call(void 0, n),o,i=_optionalChain([t, 'access', _31 => _31.schema, 'optionalAccess', _32 => _32.autoMigration])===void 0||_optionalChain([t, 'access', _33 => _33.schema, 'optionalAccess', _34 => _34.autoMigration])!=="None",p=()=>i?(o||(o=k(a)),o):Promise.resolve(),m=(_nullishCoalesce(t.projections, () => ([]))).filter(({type:c})=>c==="inline").map(({projection:c})=>c),E=m.length>0?(c,{transaction:d})=>x({projections:m,connection:{connectionString:e,transaction:d},events:c}):void 0;return{schema:{sql:()=>b.join(""),print:()=>console.log(b.join("")),migrate:async()=>{await(o=k(a))}},async aggregateStream(c,d){let{evolve:l,initialState:v,read:I}=d,N=_optionalChain([I, 'optionalAccess', _35 => _35.expectedStreamVersion]),f=v(),M=await this.readStream(c,d.read),W=M.currentStreamVersion;ne(W,N,G);for(let q of M.events)q&&(f=l(f,q));return{currentStreamVersion:W,state:f,streamExists:M.streamExists}},readStream:async(c,d)=>(await p(),De(a.execute,c,d)),appendToStream:async(c,d,l)=>{await p();let[v,...I]=c.split("-"),N=v&&I.length>0?v:"emt:unknown",f=await ge(a,c,N,d,{...l,preCommitHook:E});if(!f.success)throw new B(-1n,_nullishCoalesce(_optionalChain([l, 'optionalAccess', _36 => _36.expectedStreamVersion]), () => (O)));return{nextExpectedStreamVersion:f.nextStreamPosition,createdNewStream:f.nextStreamPosition>=BigInt(d.length)}},close:()=>a.close(),async withSession(c){return await a.withConnection(async d=>{let l={...t,connectionOptions:{connection:d}},v=Pt(e,l);return c({eventStore:v,close:()=>Promise.resolve()})})}}};exports.PostgreSQLEventStoreDefaultStreamVersion = G; exports.PostgreSQLProjectionSpec = yn; exports.addDefaultPartition = Le; exports.addEventsPartitions = Ie; exports.addModuleForAllTenantsSQL = Re; exports.addModuleSQL = Ne; exports.addTablePartitions = Pe; exports.addTenantForAllModulesSQL = Ae; exports.addTenantSQL = Oe; exports.appendEventsSQL = ue; exports.appendToStream = ge; exports.assertSQLQueryResultMatches = dt; exports.createEventStoreSchema = k; exports.defaultPostgreSQLOptions = ht; exports.defaultTag = R; exports.documentDoesNotExist = ve; exports.documentExists = at; exports.documentMatchingExists = pe; exports.documentsAreTheSame = ot; exports.documentsMatchingHaveCount = rt; exports.emmettPrefix = w; exports.eventInStream = mt; exports.eventsInStream = lt; exports.eventsTable = r; exports.eventsTableSQL = ye; exports.expectPongoDocuments = rn; exports.expectSQL = hn; exports.getPostgreSQLEventStore = Pt; exports.globalNames = Dn; exports.globalTag = _; exports.handleProjections = x; exports.newEventsInStream = fn; exports.pongoMultiStreamProjection = ct; exports.pongoProjection = st; exports.pongoSingleStreamProjection = dn; exports.postgreSQLProjection = V; exports.postgreSQLRawBatchSQLProjection = Et; exports.postgreSQLRawSQLProjection = On; exports.readStream = De; exports.sanitizeNameSQL = he; exports.schemaSQL = b; exports.streamsTable = s; exports.streamsTableSQL = Se; exports.subscriptionsTableSQL = fe;
|
|
363
363
|
//# sourceMappingURL=index.js.map
|