@event-driven-io/emmett 0.19.0-alpha.1 → 0.19.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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 d=(n=>(n.NOT_A_NONEMPTY_STRING="NOT_A_NONEMPTY_STRING",n.NOT_A_POSITIVE_NUMBER="NOT_A_POSITIVE_NUMBER",n.NOT_AN_UNSIGNED_BIGINT="NOT_AN_UNSIGNED_BIGINT",n))(d||{}),i= exports.e =t=>typeof t=="number"&&t===t,m= exports.f =t=>typeof t=="string",f= exports.g =t=>{if(!m(t)||t.length===0)throw new r("NOT_A_NONEMPTY_STRING");return t},E= exports.h =t=>{if(!i(t)||t<=0)throw new r("NOT_A_POSITIVE_NUMBER");return t},N= exports.i =t=>{let e=BigInt(t);if(e<0)throw new r("NOT_AN_UNSIGNED_BIGINT");return e};var C=t=>typeof t=="function"&&t.prototype&&t.prototype.constructor===t,o= exports.k =class t extends Error{constructor(e){let s=e&&typeof e=="object"&&"errorCode"in e?e.errorCode:i(e)?e:500,n=e&&typeof e=="object"&&"message"in e?e.message:m(e)?e:`Error with status code '${s}' ocurred during Emmett processing`;super(n),this.errorCode=s,Object.setPrototypeOf(this,t.prototype)}},g= exports.l =class t extends o{constructor(s,n,a){super({errorCode:412,message:_nullishCoalesce(a, () => (`Expected version ${n.toString()} does not match current ${_optionalChain([s, 'optionalAccess', _ => _.toString, 'call', _2 => _2()])}`))});this.current=s;this.expected=n;Object.setPrototypeOf(this,t.prototype)}},r= exports.m =class t extends o{constructor(e){super({errorCode:400,message:_nullishCoalesce(e, () => ("Validation Error ocurred during Emmett processing"))}),Object.setPrototypeOf(this,t.prototype)}},p= exports.n =class t extends o{constructor(e){super({errorCode:403,message:_nullishCoalesce(e, () => ("Illegal State ocurred during Emmett processing"))}),Object.setPrototypeOf(this,t.prototype)}},u= exports.o =class t extends o{constructor(e){super({errorCode:404,message:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _3 => _3.message]), () => ((_optionalChain([e, 'optionalAccess', _4 => _4.id])?e.type?`${e.type} with ${e.id} was not found during Emmett processing`:`State with ${e.id} was not found during Emmett processing`:_optionalChain([e, 'optionalAccess', _5 => _5.type])?`${e.type} was not found during Emmett processing`:"State was not found during Emmett processing")))}),Object.setPrototypeOf(this,t.prototype)}};var w=t=>new Intl.DateTimeFormat("en-CA",{timeZone:"UTC",year:"numeric",month:"2-digit",day:"2-digit"}).format(t),c= exports.b =t=>/^\d{4}-\d{2}-\d{2}$/.test(t),I= exports.c =t=>{let e=new Date(t+"T00:00:00Z");if(!c(t))throw new r("Invalid date format, must be yyyy-mm-dd");if(isNaN(e.getTime()))throw new r("Invalid date format");return e};require('commander');var S=t=>t!==void 0&&(typeof t=="string"||"name"in t&&t.name!==void 0&&typeof t.name=="string");exports.a = w; exports.b = c; exports.c = I; exports.d = d; exports.e = i; exports.f = m; exports.g = f; exports.h = E; exports.i = N; exports.j = C; exports.k = o; exports.l = g; exports.m = r; exports.n = p; exports.o = u; exports.p = S;
1
+ var d=(n=>(n.NOT_A_NONEMPTY_STRING="NOT_A_NONEMPTY_STRING",n.NOT_A_POSITIVE_NUMBER="NOT_A_POSITIVE_NUMBER",n.NOT_AN_UNSIGNED_BIGINT="NOT_AN_UNSIGNED_BIGINT",n))(d||{}),i=t=>typeof t=="number"&&t===t,m=t=>typeof t=="string",f=t=>{if(!m(t)||t.length===0)throw new r("NOT_A_NONEMPTY_STRING");return t},E=t=>{if(!i(t)||t<=0)throw new r("NOT_A_POSITIVE_NUMBER");return t},N=t=>{let e=BigInt(t);if(e<0)throw new r("NOT_AN_UNSIGNED_BIGINT");return e};var C=t=>typeof t=="function"&&t.prototype&&t.prototype.constructor===t,o=class t extends Error{errorCode;constructor(e){let s=e&&typeof e=="object"&&"errorCode"in e?e.errorCode:i(e)?e:500,n=e&&typeof e=="object"&&"message"in e?e.message:m(e)?e:`Error with status code '${s}' ocurred during Emmett processing`;super(n),this.errorCode=s,Object.setPrototypeOf(this,t.prototype)}},g=class t extends o{constructor(s,n,a){super({errorCode:412,message:a??`Expected version ${n.toString()} does not match current ${s?.toString()}`});this.current=s;this.expected=n;Object.setPrototypeOf(this,t.prototype)}},r=class t extends o{constructor(e){super({errorCode:400,message:e??"Validation Error ocurred during Emmett processing"}),Object.setPrototypeOf(this,t.prototype)}},p=class t extends o{constructor(e){super({errorCode:403,message:e??"Illegal State ocurred during Emmett processing"}),Object.setPrototypeOf(this,t.prototype)}},u=class t extends o{constructor(e){super({errorCode:404,message:e?.message??(e?.id?e.type?`${e.type} with ${e.id} was not found during Emmett processing`:`State with ${e.id} was not found during Emmett processing`:e?.type?`${e.type} was not found during Emmett processing`:"State was not found during Emmett processing")}),Object.setPrototypeOf(this,t.prototype)}};var w=t=>new Intl.DateTimeFormat("en-CA",{timeZone:"UTC",year:"numeric",month:"2-digit",day:"2-digit"}).format(t),c=t=>/^\d{4}-\d{2}-\d{2}$/.test(t),I=t=>{let e=new Date(t+"T00:00:00Z");if(!c(t))throw new r("Invalid date format, must be yyyy-mm-dd");if(isNaN(e.getTime()))throw new r("Invalid date format");return e};import"commander";var S=t=>t!==void 0&&(typeof t=="string"||"name"in t&&t.name!==void 0&&typeof t.name=="string");export{w as a,c as b,I as c,d,i as e,m as f,f as g,E as h,N as i,C as j,o as k,g as l,r as m,p as n,u as o,S as p};
2
2
  //# sourceMappingURL=chunk-6TXKRKDJ.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/validation/index.ts","../src/errors/index.ts"],"names":["ValidationErrors","isNumber","val","isString","assertNotEmptyString","value","ValidationError","assertPositiveNumber","assertUnsignedBigInt","number","isErrorConstructor","expect","EmmettError","_EmmettError","options","errorCode","message","ConcurrencyError","_ConcurrencyError","current","expected"],"mappings":"AAEO,qrBAAWA,CAAAA,CAAAA,CAAAA,CAAAA,EAAAA,CAChBA,CAAAA,CAAA,qBAAA,CAAwB,uBAAA,CACxBA,CAAAA,CAAA,qBAAA,CAAwB,uBAAA,CACxBA,CAAAA,CAAA,sBAAA,CAAyB,wBAAA,CAHTA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,EAAA,CAAA,CAAA,CAAA,CAMLC,CAAAA,aAAYC,CAAAA,EACvB,OAAOA,CAAAA,EAAQ,QAAA,EAAYA,CAAAA,GAAQA,CAAAA,CAExBC,CAAAA,aAAYD,CAAAA,EACvB,OAAOA,CAAAA,EAAQ,QAAA,CAEJE,CAAAA,aAAwBC,CAAAA,EAA2B,CAC9D,EAAA,CAAI,CAACF,CAAAA,CAASE,CAAK,CAAA,EAAKA,CAAAA,CAAM,MAAA,GAAW,CAAA,CACvC,MAAM,IAAIC,CAAAA,CAAgB,uBAAsC,CAAA,CAElE,OAAOD,CACT,CAAA,CAEaE,CAAAA,aAAwBF,CAAAA,EAA2B,CAC9D,EAAA,CAAI,CAACJ,CAAAA,CAASI,CAAK,CAAA,EAAKA,CAAAA,EAAS,CAAA,CAC/B,MAAM,IAAIC,CAAAA,CAAgB,uBAAsC,CAAA,CAElE,OAAOD,CACT,CAAA,CAEaG,CAAAA,aAAwBH,CAAAA,EAA0B,CAC7D,IAAMI,CAAAA,CAAS,MAAA,CAAOJ,CAAK,CAAA,CAC3B,EAAA,CAAII,CAAAA,CAAS,CAAA,CACX,MAAM,IAAIH,CAAAA,CAAgB,wBAAuC,CAAA,CAEnE,OAAOG,CACT,CAAA,CC3BO,IAAMC,CAAAA,CAEXC,CAAAA,EAIE,OAAOA,CAAAA,EAAW,UAAA,EAClBA,CAAAA,CAAO,SAAA,EAEPA,CAAAA,CAAO,SAAA,CAAU,WAAA,GAAgBA,CAAAA,CAIxBC,CAAAA,aAAN,MAAMC,EAAAA,QAAoB,KAAM,CAC9B,WAEP,CACEC,CAAAA,CACA,CACA,IAAMC,CAAAA,CACJD,CAAAA,EAAW,OAAOA,CAAAA,EAAY,QAAA,EAAY,WAAA,GAAeA,CAAAA,CACrDA,CAAAA,CAAQ,SAAA,CACRb,CAAAA,CAASa,CAAO,CAAA,CACdA,CAAAA,CACA,GAAA,CACFE,CAAAA,CACJF,CAAAA,EAAW,OAAOA,CAAAA,EAAY,QAAA,EAAY,SAAA,GAAaA,CAAAA,CACnDA,CAAAA,CAAQ,OAAA,CACRX,CAAAA,CAASW,CAAO,CAAA,CACdA,CAAAA,CACA,CAAA,wBAAA,EAA2BC,CAAS,CAAA,kCAAA,CAAA,CAE5C,KAAA,CAAMC,CAAO,CAAA,CACb,IAAA,CAAK,SAAA,CAAYD,CAAAA,CAGjB,MAAA,CAAO,cAAA,CAAe,IAAA,CAAMF,CAAAA,CAAY,SAAS,CACnD,CACF,CAAA,CAEaI,CAAAA,aAAN,MAAMC,EAAAA,QAAyBN,CAAY,CAChD,WAAA,CACSO,CAAAA,CACAC,CAAAA,CACPJ,CAAAA,CACA,CACA,KAAA,CAAM,CACJ,SAAA,CAAW,GAAA,CACX,OAAA,kBACEA,CAAAA,SACA,CAAA,iBAAA,EAAoBI,CAAAA,CAAS,QAAA,CAAS,CAAC,CAAA,wBAAA,kBAA2BD,CAAAA,2BAAS,QAAA,mBAAS,GAAC,CAAA,GAAA","file":"/home/runner/work/emmett/emmett/src/packages/emmett/dist/chunk-6TXKRKDJ.js","sourcesContent":["import { ValidationError } from '../errors';\n\nexport const enum ValidationErrors {\n NOT_A_NONEMPTY_STRING = 'NOT_A_NONEMPTY_STRING',\n NOT_A_POSITIVE_NUMBER = 'NOT_A_POSITIVE_NUMBER',\n NOT_AN_UNSIGNED_BIGINT = 'NOT_AN_UNSIGNED_BIGINT',\n}\n\nexport 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 const assertNotEmptyString = (value: unknown): string => {\n if (!isString(value) || value.length === 0) {\n throw new ValidationError(ValidationErrors.NOT_A_NONEMPTY_STRING);\n }\n return value;\n};\n\nexport const assertPositiveNumber = (value: unknown): number => {\n if (!isNumber(value) || value <= 0) {\n throw new ValidationError(ValidationErrors.NOT_A_POSITIVE_NUMBER);\n }\n return value;\n};\n\nexport const assertUnsignedBigInt = (value: string): bigint => {\n const number = BigInt(value);\n if (number < 0) {\n throw new ValidationError(ValidationErrors.NOT_AN_UNSIGNED_BIGINT);\n }\n return number;\n};\n\nexport * from './dates';\n","import { isNumber, isString } from '../validation';\n\nexport type ErrorConstructor<ErrorType extends Error> = new (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...args: any[]\n) => ErrorType;\n\nexport const isErrorConstructor = <ErrorType extends Error>(\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n expect: Function,\n): expect is ErrorConstructor<ErrorType> => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return (\n typeof expect === 'function' &&\n expect.prototype &&\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n expect.prototype.constructor === expect\n );\n};\n\nexport class EmmettError 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 Emmett processing`;\n\n super(message);\n this.errorCode = errorCode;\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, EmmettError.prototype);\n }\n}\n\nexport class ConcurrencyError extends EmmettError {\n constructor(\n public current: string | undefined,\n public expected: string,\n message?: string,\n ) {\n super({\n errorCode: 412,\n message:\n message ??\n `Expected version ${expected.toString()} does not match current ${current?.toString()}`,\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, ConcurrencyError.prototype);\n }\n}\n\nexport class ValidationError extends EmmettError {\n constructor(message?: string) {\n super({\n errorCode: 400,\n message: message ?? `Validation Error ocurred during Emmett processing`,\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, ValidationError.prototype);\n }\n}\n\nexport class IllegalStateError extends EmmettError {\n constructor(message?: string) {\n super({\n errorCode: 403,\n message: message ?? `Illegal State ocurred during Emmett processing`,\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, IllegalStateError.prototype);\n }\n}\n\nexport class NotFoundError extends EmmettError {\n constructor(options?: { id: string; type: string; message?: string }) {\n super({\n errorCode: 404,\n message:\n options?.message ??\n (options?.id\n ? options.type\n ? `${options.type} with ${options.id} was not found during Emmett processing`\n : `State with ${options.id} was not found during Emmett processing`\n : options?.type\n ? `${options.type} was not found during Emmett processing`\n : 'State was not found during Emmett processing'),\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, NotFoundError.prototype);\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/validation/index.ts","../src/errors/index.ts","../src/validation/dates.ts","../src/config/plugins/index.ts"],"sourcesContent":["import { ValidationError } from '../errors';\n\nexport const enum ValidationErrors {\n NOT_A_NONEMPTY_STRING = 'NOT_A_NONEMPTY_STRING',\n NOT_A_POSITIVE_NUMBER = 'NOT_A_POSITIVE_NUMBER',\n NOT_AN_UNSIGNED_BIGINT = 'NOT_AN_UNSIGNED_BIGINT',\n}\n\nexport 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 const assertNotEmptyString = (value: unknown): string => {\n if (!isString(value) || value.length === 0) {\n throw new ValidationError(ValidationErrors.NOT_A_NONEMPTY_STRING);\n }\n return value;\n};\n\nexport const assertPositiveNumber = (value: unknown): number => {\n if (!isNumber(value) || value <= 0) {\n throw new ValidationError(ValidationErrors.NOT_A_POSITIVE_NUMBER);\n }\n return value;\n};\n\nexport const assertUnsignedBigInt = (value: string): bigint => {\n const number = BigInt(value);\n if (number < 0) {\n throw new ValidationError(ValidationErrors.NOT_AN_UNSIGNED_BIGINT);\n }\n return number;\n};\n\nexport * from './dates';\n","import { isNumber, isString } from '../validation';\n\nexport type ErrorConstructor<ErrorType extends Error> = new (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...args: any[]\n) => ErrorType;\n\nexport const isErrorConstructor = <ErrorType extends Error>(\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n expect: Function,\n): expect is ErrorConstructor<ErrorType> => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return (\n typeof expect === 'function' &&\n expect.prototype &&\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n expect.prototype.constructor === expect\n );\n};\n\nexport class EmmettError 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 Emmett processing`;\n\n super(message);\n this.errorCode = errorCode;\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, EmmettError.prototype);\n }\n}\n\nexport class ConcurrencyError extends EmmettError {\n constructor(\n public current: string | undefined,\n public expected: string,\n message?: string,\n ) {\n super({\n errorCode: 412,\n message:\n message ??\n `Expected version ${expected.toString()} does not match current ${current?.toString()}`,\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, ConcurrencyError.prototype);\n }\n}\n\nexport class ValidationError extends EmmettError {\n constructor(message?: string) {\n super({\n errorCode: 400,\n message: message ?? `Validation Error ocurred during Emmett processing`,\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, ValidationError.prototype);\n }\n}\n\nexport class IllegalStateError extends EmmettError {\n constructor(message?: string) {\n super({\n errorCode: 403,\n message: message ?? `Illegal State ocurred during Emmett processing`,\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, IllegalStateError.prototype);\n }\n}\n\nexport class NotFoundError extends EmmettError {\n constructor(options?: { id: string; type: string; message?: string }) {\n super({\n errorCode: 404,\n message:\n options?.message ??\n (options?.id\n ? options.type\n ? `${options.type} with ${options.id} was not found during Emmett processing`\n : `State with ${options.id} was not found during Emmett processing`\n : options?.type\n ? `${options.type} was not found during Emmett processing`\n : 'State was not found during Emmett processing'),\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, NotFoundError.prototype);\n }\n}\n","import { ValidationError } from '../errors';\n\nexport const formatDateToUtcYYYYMMDD = (date: Date) => {\n // Use the 'en-CA' locale which formats as 'yyyy-mm-dd'\n const formatter = new Intl.DateTimeFormat('en-CA', {\n timeZone: 'UTC',\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n });\n\n // Format the date\n return formatter.format(date);\n};\n\n// Function to validate 'yyyy-mm-dd' format\nexport const isValidYYYYMMDD = (dateString: string) => {\n const regex = /^\\d{4}-\\d{2}-\\d{2}$/;\n return regex.test(dateString);\n};\n\nexport const parseDateFromUtcYYYYMMDD = (dateString: string) => {\n const date = new Date(dateString + 'T00:00:00Z');\n\n if (!isValidYYYYMMDD(dateString)) {\n throw new ValidationError('Invalid date format, must be yyyy-mm-dd');\n }\n\n if (isNaN(date.getTime())) {\n throw new ValidationError('Invalid date format');\n }\n\n return date;\n};\n","import { Command as CliCommand } from 'commander';\n\nexport type EmmettPluginConfig =\n | {\n name: string;\n register: EmmettPluginRegistration[];\n }\n | string;\n\nexport type EmmettPluginType = 'cli';\n\nexport type EmmettCliPluginRegistration = { pluginType: 'cli'; path?: string };\n\nexport type EmmettPluginRegistration = EmmettCliPluginRegistration;\n\nexport type EmmettCliPlugin = {\n pluginType: 'cli';\n name: string;\n registerCommands: (program: CliCommand) => Promise<void> | void;\n};\n\nexport type EmmettPlugin = EmmettCliPlugin;\n\nexport const isPluginConfig = (\n plugin: Partial<EmmettPluginConfig> | string | undefined,\n): plugin is EmmettPluginConfig =>\n plugin !== undefined &&\n (typeof plugin === 'string' ||\n ('name' in plugin &&\n plugin.name !== undefined &&\n typeof plugin.name === 'string'));\n"],"mappings":"AAEO,IAAWA,OAChBA,EAAA,sBAAwB,wBACxBA,EAAA,sBAAwB,wBACxBA,EAAA,uBAAyB,yBAHTA,OAAA,IAMLC,EAAYC,GACvB,OAAOA,GAAQ,UAAYA,IAAQA,EAExBC,EAAYD,GACvB,OAAOA,GAAQ,SAEJE,EAAwBC,GAA2B,CAC9D,GAAI,CAACF,EAASE,CAAK,GAAKA,EAAM,SAAW,EACvC,MAAM,IAAIC,EAAgB,uBAAsC,EAElE,OAAOD,CACT,EAEaE,EAAwBF,GAA2B,CAC9D,GAAI,CAACJ,EAASI,CAAK,GAAKA,GAAS,EAC/B,MAAM,IAAIC,EAAgB,uBAAsC,EAElE,OAAOD,CACT,EAEaG,EAAwBH,GAA0B,CAC7D,IAAMI,EAAS,OAAOJ,CAAK,EAC3B,GAAII,EAAS,EACX,MAAM,IAAIH,EAAgB,wBAAuC,EAEnE,OAAOG,CACT,EC3BO,IAAMC,EAEXC,GAIE,OAAOA,GAAW,YAClBA,EAAO,WAEPA,EAAO,UAAU,cAAgBA,EAIxBC,EAAN,MAAMC,UAAoB,KAAM,CAC9B,UAEP,YACEC,EACA,CACA,IAAMC,EACJD,GAAW,OAAOA,GAAY,UAAY,cAAeA,EACrDA,EAAQ,UACRE,EAASF,CAAO,EACdA,EACA,IACFG,EACJH,GAAW,OAAOA,GAAY,UAAY,YAAaA,EACnDA,EAAQ,QACRI,EAASJ,CAAO,EACdA,E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CAACD,EAAgBC,CAAU,EAC7B,MAAM,IAAIE,EAAgB,yCAAyC,EAGrE,GAAI,MAAMJ,EAAK,QAAQ,CAAC,EACtB,MAAM,IAAII,EAAgB,qBAAqB,EAGjD,OAAOJ,CACT,ECjCA,MAAsC,YAuB/B,IAAMK,EACXC,GAEAA,IAAW,SACV,OAAOA,GAAW,UAChB,SAAUA,GACTA,EAAO,OAAS,QAChB,OAAOA,EAAO,MAAS","names":["ValidationErrors","isNumber","val","isString","assertNotEmptyString","value","ValidationError","assertPositiveNumber","assertUnsignedBigInt","number","isErrorConstructor","expect","EmmettError","_EmmettError","options","errorCode","isNumber","message","isString","ConcurrencyError","_ConcurrencyError","current","expected","ValidationError","_ValidationError","IllegalStateError","_IllegalStateError","NotFoundError","_NotFoundError","formatDateToUtcYYYYMMDD","date","isValidYYYYMMDD","dateString","parseDateFromUtcYYYYMMDD","ValidationError","isPluginConfig","plugin"]}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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 d=(n=>(n.NOT_A_NONEMPTY_STRING="NOT_A_NONEMPTY_STRING",n.NOT_A_POSITIVE_NUMBER="NOT_A_POSITIVE_NUMBER",n.NOT_AN_UNSIGNED_BIGINT="NOT_AN_UNSIGNED_BIGINT",n))(d||{}),i= exports.e =t=>typeof t=="number"&&t===t,m= exports.f =t=>typeof t=="string",f= exports.g =t=>{if(!m(t)||t.length===0)throw new r("NOT_A_NONEMPTY_STRING");return t},E= exports.h =t=>{if(!i(t)||t<=0)throw new r("NOT_A_POSITIVE_NUMBER");return t},N= exports.i =t=>{let e=BigInt(t);if(e<0)throw new r("NOT_AN_UNSIGNED_BIGINT");return e};var C=t=>typeof t=="function"&&t.prototype&&t.prototype.constructor===t,o= exports.k =class t extends Error{constructor(e){let s=e&&typeof e=="object"&&"errorCode"in e?e.errorCode:i(e)?e:500,n=e&&typeof e=="object"&&"message"in e?e.message:m(e)?e:`Error with status code '${s}' ocurred during Emmett processing`;super(n),this.errorCode=s,Object.setPrototypeOf(this,t.prototype)}},g= exports.l =class t extends o{constructor(s,n,a){super({errorCode:412,message:_nullishCoalesce(a, () => (`Expected version ${n.toString()} does not match current ${_optionalChain([s, 'optionalAccess', _ => _.toString, 'call', _2 => _2()])}`))});this.current=s;this.expected=n;Object.setPrototypeOf(this,t.prototype)}},r= exports.m =class t extends o{constructor(e){super({errorCode:400,message:_nullishCoalesce(e, () => ("Validation Error ocurred during Emmett processing"))}),Object.setPrototypeOf(this,t.prototype)}},p= exports.n =class t extends o{constructor(e){super({errorCode:403,message:_nullishCoalesce(e, () => ("Illegal State ocurred during Emmett processing"))}),Object.setPrototypeOf(this,t.prototype)}},u= exports.o =class t extends o{constructor(e){super({errorCode:404,message:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _3 => _3.message]), () => ((_optionalChain([e, 'optionalAccess', _4 => _4.id])?e.type?`${e.type} with ${e.id} was not found during Emmett processing`:`State with ${e.id} was not found during Emmett processing`:_optionalChain([e, 'optionalAccess', _5 => _5.type])?`${e.type} was not found during Emmett processing`:"State was not found during Emmett processing")))}),Object.setPrototypeOf(this,t.prototype)}};var w=t=>new Intl.DateTimeFormat("en-CA",{timeZone:"UTC",year:"numeric",month:"2-digit",day:"2-digit"}).format(t),c= exports.b =t=>/^\d{4}-\d{2}-\d{2}$/.test(t),I= exports.c =t=>{let e=new Date(t+"T00:00:00Z");if(!c(t))throw new r("Invalid date format, must be yyyy-mm-dd");if(isNaN(e.getTime()))throw new r("Invalid date format");return e};require('commander');var S=t=>t!==void 0&&(typeof t=="string"||"name"in t&&t.name!==void 0&&typeof t.name=="string");exports.a = w; exports.b = c; exports.c = I; exports.d = d; exports.e = i; exports.f = m; exports.g = f; exports.h = E; exports.i = N; exports.j = C; exports.k = o; exports.l = g; exports.m = r; exports.n = p; exports.o = u; exports.p = S;
2
+ //# sourceMappingURL=chunk-CJZAVRMT.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/validation/index.ts","../src/errors/index.ts"],"names":["ValidationErrors","isNumber","val","isString","assertNotEmptyString","value","ValidationError","assertPositiveNumber","assertUnsignedBigInt","number","isErrorConstructor","expect","EmmettError","_EmmettError","options","errorCode","message","ConcurrencyError","_ConcurrencyError","current","expected"],"mappings":"AAEO,qrBAAWA,CAAAA,CAAAA,CAAAA,CAAAA,EAAAA,CAChBA,CAAAA,CAAA,qBAAA,CAAwB,uBAAA,CACxBA,CAAAA,CAAA,qBAAA,CAAwB,uBAAA,CACxBA,CAAAA,CAAA,sBAAA,CAAyB,wBAAA,CAHTA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,EAAA,CAAA,CAAA,CAAA,CAMLC,CAAAA,aAAYC,CAAAA,EACvB,OAAOA,CAAAA,EAAQ,QAAA,EAAYA,CAAAA,GAAQA,CAAAA,CAExBC,CAAAA,aAAYD,CAAAA,EACvB,OAAOA,CAAAA,EAAQ,QAAA,CAEJE,CAAAA,aAAwBC,CAAAA,EAA2B,CAC9D,EAAA,CAAI,CAACF,CAAAA,CAASE,CAAK,CAAA,EAAKA,CAAAA,CAAM,MAAA,GAAW,CAAA,CACvC,MAAM,IAAIC,CAAAA,CAAgB,uBAAsC,CAAA,CAElE,OAAOD,CACT,CAAA,CAEaE,CAAAA,aAAwBF,CAAAA,EAA2B,CAC9D,EAAA,CAAI,CAACJ,CAAAA,CAASI,CAAK,CAAA,EAAKA,CAAAA,EAAS,CAAA,CAC/B,MAAM,IAAIC,CAAAA,CAA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,CAAC,CAAA,wBAAA,kBAA2BD,CAAAA,2BAAS,QAAA,mBAAS,GAAC,CAAA,GAAA","file":"/home/runner/work/emmett/emmett/src/packages/emmett/dist/chunk-CJZAVRMT.cjs","sourcesContent":["import { ValidationError } from '../errors';\n\nexport const enum ValidationErrors {\n NOT_A_NONEMPTY_STRING = 'NOT_A_NONEMPTY_STRING',\n NOT_A_POSITIVE_NUMBER = 'NOT_A_POSITIVE_NUMBER',\n NOT_AN_UNSIGNED_BIGINT = 'NOT_AN_UNSIGNED_BIGINT',\n}\n\nexport 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 const assertNotEmptyString = (value: unknown): string => {\n if (!isString(value) || value.length === 0) {\n throw new ValidationError(ValidationErrors.NOT_A_NONEMPTY_STRING);\n }\n return value;\n};\n\nexport const assertPositiveNumber = (value: unknown): number => {\n if (!isNumber(value) || value <= 0) {\n throw new ValidationError(ValidationErrors.NOT_A_POSITIVE_NUMBER);\n }\n return value;\n};\n\nexport const assertUnsignedBigInt = (value: string): bigint => {\n const number = BigInt(value);\n if (number < 0) {\n throw new ValidationError(ValidationErrors.NOT_AN_UNSIGNED_BIGINT);\n }\n return number;\n};\n\nexport * from './dates';\n","import { isNumber, isString } from '../validation';\n\nexport type ErrorConstructor<ErrorType extends Error> = new (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...args: any[]\n) => ErrorType;\n\nexport const isErrorConstructor = <ErrorType extends Error>(\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n expect: Function,\n): expect is ErrorConstructor<ErrorType> => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return (\n typeof expect === 'function' &&\n expect.prototype &&\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n expect.prototype.constructor === expect\n );\n};\n\nexport class EmmettError 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 Emmett processing`;\n\n super(message);\n this.errorCode = errorCode;\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, EmmettError.prototype);\n }\n}\n\nexport class ConcurrencyError extends EmmettError {\n constructor(\n public current: string | undefined,\n public expected: string,\n message?: string,\n ) {\n super({\n errorCode: 412,\n message:\n message ??\n `Expected version ${expected.toString()} does not match current ${current?.toString()}`,\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, ConcurrencyError.prototype);\n }\n}\n\nexport class ValidationError extends EmmettError {\n constructor(message?: string) {\n super({\n errorCode: 400,\n message: message ?? `Validation Error ocurred during Emmett processing`,\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, ValidationError.prototype);\n }\n}\n\nexport class IllegalStateError extends EmmettError {\n constructor(message?: string) {\n super({\n errorCode: 403,\n message: message ?? `Illegal State ocurred during Emmett processing`,\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, IllegalStateError.prototype);\n }\n}\n\nexport class NotFoundError extends EmmettError {\n constructor(options?: { id: string; type: string; message?: string }) {\n super({\n errorCode: 404,\n message:\n options?.message ??\n (options?.id\n ? options.type\n ? `${options.type} with ${options.id} was not found during Emmett processing`\n : `State with ${options.id} was not found during Emmett processing`\n : options?.type\n ? `${options.type} was not found during Emmett processing`\n : 'State was not found during Emmett processing'),\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, NotFoundError.prototype);\n }\n}\n"]}
package/dist/cli.cjs ADDED
@@ -0,0 +1,16 @@
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(); } } 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 _chunkCJZAVRMTcjs = require('./chunk-CJZAVRMT.cjs');var _commander = require('commander');var _fs = require('fs');var _process = require('process');var s=(e=["emmett-expressjs"])=>`
3
+ export default {
4
+ plugins: ${e.length>0?`[
5
+ ${e.map(t=>`"${t}"`).join(`,
6
+ `)}
7
+ ]`:"[]"},
8
+ };
9
+ `,h= exports.generateConfigFile =(e,n)=>{try{_fs.writeFileSync.call(void 0, e,s(n),"utf8"),console.log(`Configuration file stored at: ${e}`)}catch(t){console.error(`Error: Couldn't store config file: ${e}!`),console.error(t),process.exit(1)}},C= exports.configCommand =new (0, _commander.Command)("config").description("Manage Pongo configuration");C.command("sample").description("Generate or print sample configuration").option("-plg, --plugins <name>","Specify the plugin name",(e,n)=>n.concat([e]),[]).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(e=>{let n=e.plugin.length>0?e.plugin:["@event-driven-io/emmett-expressjs"];!("print"in e)&&!("generate"in e)&&(console.error(`Error: Please provide either:
10
+ --print param to print sample config or
11
+ --generate to generate sample config file`),_process.exit.call(void 0, 1)),"print"in e?console.log(`${s(n)}`):"generate"in e&&(e.file||(console.error("Error: You need to provide a config file through a --file"),_process.exit.call(void 0, 1)),h(e.file,n))});var _path = require('path'); var _path2 = _interopRequireDefault(_path);var m={missingDefaultExport:`Error: Config should contain default export, e.g.
12
+
13
+ ${s()}`,missingPluginsPropertyExport:`Error: Config should contain default export with plugins array, e.g.
14
+
15
+ ${s()}`,wrongPluginStructure:"Error: Plugin config should be either string with plugin name or object with plugin name, e.g. { name: 'emmett-expressjs' }"},y= exports.importPluginsConfig =async e=>{let n=_path2.default.join(process.cwd(),_nullishCoalesce(_optionalChain([e, 'optionalAccess', _ => _.configPath]), () => ("./dist/emmett.config.js")));console.log("IMPORTING"+n);try{let t=await Promise.resolve().then(() => _interopRequireWildcard(require(n)));return t.default?!t.default.plugins||!Array.isArray(t.default.plugins)?new (0, _chunkCJZAVRMTcjs.k)(m.missingPluginsPropertyExport):t.default.plugins.every(_chunkCJZAVRMTcjs.p)?{plugins:t.default.plugins}:new (0, _chunkCJZAVRMTcjs.k)(m.wrongPluginStructure):new (0, _chunkCJZAVRMTcjs.k)(m.missingDefaultExport)}catch(t){return _optionalChain([e, 'optionalAccess', _2 => _2.configPath])?new (0, _chunkCJZAVRMTcjs.k)("Error: Couldn't load file:"+t.toString()):(console.warn("Didn`t find config file: "+n,t),{plugins:[]})}},u= exports.loadPlugins =async e=>{try{let n=await y({configPath:_optionalChain([e, 'optionalAccess', _3 => _3.configPath])});if(n instanceof _chunkCJZAVRMTcjs.k)throw n;if(n.plugins.length===0)return console.log(`No extensions specified in config ${_optionalChain([e, 'optionalAccess', _4 => _4.configPath])}.`),[];let i=x(n.plugins,_optionalChain([e, 'optionalAccess', _5 => _5.pluginType])).map(async r=>{let l=w(r,_optionalChain([e, 'optionalAccess', _6 => _6.pluginType]));try{let a=await Promise.resolve().then(() => _interopRequireWildcard(require(l)));if(console.info(`Loaded plugin: ${l}`),!a.default)throw new Error(`Plugin: ${l} is missing default export`);return a.default}catch(a){console.error(`Failed to load extension "${l}":`,a);return}});return(await Promise.all(i)).filter(r=>r!==void 0)}catch(n){return console.error(`Failed to load config ${_optionalChain([e, 'optionalAccess', _7 => _7.configPath])}:`,n),[]}},p= exports.registerCliPlugins =async(e,n)=>{let t=[];for(let i of n){let r=i.name;"registerCommands"in i||console.warn(`No registerCommands function found in ${r}`),await i.registerCommands(e),console.log(`Loaded extension: ${i.name}`),t.push(i)}},x=(e,n)=>e.filter(t=>typeof t=="string"||n&&(t.register===void 0||t.register.some(i=>i.pluginType===n))),w=(e,n)=>{if(typeof e=="string")return n?`${e}/${n}`:e;let t=_nullishCoalesce(_optionalChain([e, 'access', _8 => _8.register, 'access', _9 => _9.find, 'call', _10 => _10(i=>n&&i.pluginType===n), 'optionalAccess', _11 => _11.path]), () => (n));return t?`${e.name}/${t}`:e.name};var g=new _commander.Command;g.name("emmett").description("CLI tool for Emmett").option("--config <path>","Path to the configuration file");var v=async()=>{let e=process.argv.indexOf("--config"),n=e!==-1&&process.argv.length>e+1?process.argv[e+1]:void 0;try{let t=await u({pluginType:"cli",configPath:n});await p(g,t),g.parse(process.argv)}catch(t){console.error(`Failed to load config from ${n}:`,t)}};v().catch(e=>{console.error("CLI initialization failed:"),console.error(e)});var Y=g;exports.configCommand = C; exports.default = Y; exports.generateConfigFile = h; exports.importPluginsConfig = y; exports.loadPlugins = u; exports.registerCliPlugins = p; exports.sampleConfig = s;
16
+ //# sourceMappingURL=cli.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/emmett/emmett/src/packages/emmett/dist/cli.cjs","../src/cli.ts","../src/commandLine/config.ts","../src/commandLine/plugins.ts"],"names":["sampleConfig","plugins","p","generateConfigFile","configPath","collectionNames","writeFileSync"],"mappings":"AAAA;AACA,2lCAA+C,sCCAvB,wBCCM,kCACT,IAERA,CAAAA,CAAe,CAACC,CAAAA,CAAoB,CAAC,kBAAkB,CAAA,CAAA,EAM3D,CAAA;AAAA;AAAA,WAAA,EAJLA,CAAAA,CAAQ,MAAA,CAAS,CAAA,CACb,CAAA;AAAA,EAAMA,CAAAA,CAAQ,GAAA,CAAKC,CAAAA,EAAM,CAAA,CAAA,EAAIA,CAAC,CAAA,CAAA,CAAG,CAAA,CAAE,IAAA,CAAK,CAAA;AAAA,CAAK,CAAC,CAAA;AAAA,CAAA,CAAA,CAC9C,IAIiB,CAAA;AAAA;AAAA,CAAA,CAKZC,CAAAA,8BAAqB,CAChCC,CAAAA,CACAC,CAAAA,CAAAA,EACS,CACT,GAAI,CACFC,+BAAAA,CAAcF,CAAYJ,CAAAA,CAAaK,CAAe,CAAA,CAAG,MAAM,CAAA,CAC/D,OAAA,CAAQ,GAAA,CAAI,CAAA,8BAAA,EAAiCD,CAAU,CAAA,CAAA;AAiDnD;AAMiC,yCAAA;ACjEjB;AACQ;AAAA;AACR","file":"/home/runner/work/emmett/emmett/src/packages/emmett/dist/cli.cjs","sourcesContent":[null,"#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { loadPlugins, registerCliPlugins } from './commandLine';\n\nconst program = new Command();\n\nprogram\n .name('emmett')\n .description('CLI tool for Emmett')\n .option('--config <path>', 'Path to the configuration file');\n\n// Load extensions and parse CLI arguments\nconst initCLI = async () => {\n const configIndex = process.argv.indexOf('--config');\n\n const configPath =\n configIndex !== -1 && process.argv.length > configIndex + 1\n ? process.argv[configIndex + 1]\n : undefined;\n\n try {\n const plugins = await loadPlugins({\n pluginType: 'cli',\n configPath: configPath,\n });\n await registerCliPlugins(program, plugins);\n\n // Parse the CLI arguments\n program.parse(process.argv);\n } catch (err) {\n console.error(`Failed to load config from ${configPath}:`, err);\n }\n};\n\n//Initialize CLI and handle errors\ninitCLI().catch((err) => {\n console.error(`CLI initialization failed:`);\n console.error(err);\n});\n\nexport default program;\nexport * from './commandLine';\n","import { Command as CliCommand } from 'commander';\n// eslint-disable-next-line no-restricted-imports\nimport { writeFileSync } from 'node:fs';\nimport { exit } from 'process';\n\nexport const sampleConfig = (plugins: string[] = ['emmett-expressjs']) => {\n const pluginsNames =\n plugins.length > 0\n ? `[\\n${plugins.map((p) => `\"${p}\"`).join(',\\n')} \\n]`\n : '[]';\n\n return `\nexport default {\n plugins: ${pluginsNames},\n};\n`;\n};\n\nexport const generateConfigFile = (\n configPath: string,\n collectionNames: string[],\n): void => {\n try {\n 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 configCommand = new CliCommand('config').description(\n 'Manage Pongo configuration',\n);\n\ntype SampleConfigOptions =\n | {\n plugin: string[];\n print?: boolean;\n }\n | {\n plugin: string[];\n generate?: boolean;\n file?: string;\n };\n\nconfigCommand\n .command('sample')\n .description('Generate or print sample configuration')\n .option(\n '-plg, --plugins <name>',\n 'Specify the plugin name',\n (value: string, previous: string[]) => {\n // Accumulate plugins 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 plugins =\n options.plugin.length > 0\n ? options.plugin\n : ['@event-driven-io/emmett-expressjs'];\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 exit(1);\n }\n\n if ('print' in options) {\n console.log(`${sampleConfig(plugins)}`);\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 exit(1);\n }\n\n generateConfigFile(options.file, plugins);\n }\n });\n","import { Command as CliCommand } from 'commander';\nimport path from 'path';\nimport {\n isPluginConfig,\n type EmmettCliPlugin,\n type EmmettPlugin,\n type EmmettPluginConfig,\n type EmmettPluginsConfig,\n type EmmettPluginType,\n} from '../config';\nimport { EmmettError } from '../errors';\nimport { sampleConfig } from './config';\n\nconst PluginsConfigImportError = {\n missingDefaultExport: `Error: Config should contain default export, e.g.\\n\\n${sampleConfig()}`,\n missingPluginsPropertyExport: `Error: Config should contain default export with plugins array, e.g.\\n\\n${sampleConfig()}`,\n wrongPluginStructure: `Error: Plugin config should be either string with plugin name or object with plugin name, e.g. { name: 'emmett-expressjs' }`,\n};\nexport const importPluginsConfig = async (options?: {\n configPath?: string | undefined;\n}): Promise<EmmettPluginsConfig | EmmettError> => {\n const configPath = path.join(\n process.cwd(),\n options?.configPath ?? './dist/emmett.config.js',\n );\n\n console.log('IMPORTING' + configPath);\n\n try {\n const imported = (await import(configPath)) as {\n default: Partial<EmmettPluginsConfig>;\n };\n\n if (!imported.default) {\n return new EmmettError(PluginsConfigImportError.missingDefaultExport);\n }\n\n if (!imported.default.plugins || !Array.isArray(imported.default.plugins)) {\n return new EmmettError(\n PluginsConfigImportError.missingPluginsPropertyExport,\n );\n }\n\n if (!imported.default.plugins.every(isPluginConfig)) {\n return new EmmettError(PluginsConfigImportError.wrongPluginStructure);\n }\n\n return { plugins: imported.default.plugins };\n } catch (error) {\n if (!options?.configPath) {\n console.warn('Didn`t find config file: ' + configPath, error);\n return { plugins: [] };\n }\n return new EmmettError(\n `Error: Couldn't load file:` + (error as Error).toString(),\n );\n }\n};\n\nexport const loadPlugins = async (options?: {\n pluginType?: EmmettPluginType;\n configPath?: string;\n}): Promise<EmmettPlugin[]> => {\n try {\n const pluginsConfig = await importPluginsConfig({\n configPath: options?.configPath,\n });\n\n if (pluginsConfig instanceof EmmettError) throw pluginsConfig;\n\n if (pluginsConfig.plugins.length === 0) {\n console.log(`No extensions specified in config ${options?.configPath}.`);\n return [];\n }\n\n const pluginsToLoad = filterPluginsByType(\n pluginsConfig.plugins,\n options?.pluginType,\n );\n\n const pluginsPromises = pluginsToLoad.map(async (pluginConfig) => {\n const importPath = getImportPath(pluginConfig, options?.pluginType);\n try {\n const plugin = (await import(importPath)) as { default: EmmettPlugin };\n\n console.info(`Loaded plugin: ${importPath}`);\n\n if (!plugin.default) {\n throw new Error(`Plugin: ${importPath} is missing default export`);\n }\n\n return plugin.default;\n } catch (error) {\n console.error(`Failed to load extension \"${importPath}\":`, error);\n return undefined;\n }\n });\n\n return (await Promise.all(pluginsPromises)).filter(\n (plugin) => plugin !== undefined,\n );\n } catch (error) {\n console.error(`Failed to load config ${options?.configPath}:`, error);\n return [];\n }\n};\n\nexport const registerCliPlugins = async (\n program: CliCommand,\n plugins: EmmettCliPlugin[],\n): Promise<void> => {\n const result: EmmettCliPlugin[] = [];\n\n for (const plugin of plugins) {\n const pluginName = plugin.name;\n\n if (!('registerCommands' in plugin)) {\n console.warn(`No registerCommands function found in ${pluginName}`);\n }\n await plugin.registerCommands(program);\n console.log(`Loaded extension: ${plugin.name}`);\n result.push(plugin);\n }\n};\n\nconst filterPluginsByType = (\n plugins: EmmettPluginConfig[],\n pluginType?: EmmettPluginType,\n): EmmettPluginConfig[] =>\n plugins.filter(\n (p) =>\n typeof p === 'string' ||\n (pluginType &&\n (p.register === undefined ||\n p.register.some((r) => r.pluginType === pluginType))),\n );\n\nconst getImportPath = (\n pluginConfig: EmmettPluginConfig,\n pluginType: EmmettPluginType | undefined,\n) => {\n if (typeof pluginConfig === 'string') {\n return pluginType ? `${pluginConfig}/${pluginType}` : pluginConfig;\n }\n\n const pluginSubpath =\n pluginConfig.register.find((r) => pluginType && r.pluginType === pluginType)\n ?.path ?? pluginType;\n\n return pluginSubpath\n ? `${pluginConfig.name}/${pluginSubpath}`\n : pluginConfig.name;\n};\n"]}
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command } from 'commander';
3
- import { a as EmmettPluginsConfig, j as EmmettError, c as EmmettPluginType, g as EmmettPlugin, f as EmmettCliPlugin } from './index-D9zse73H.mjs';
3
+ import { a as EmmettPluginsConfig, j as EmmettError, c as EmmettPluginType, g as EmmettPlugin, f as EmmettCliPlugin } from './index-D9zse73H.cjs';
4
4
 
5
5
  declare const sampleConfig: (plugins?: string[]) => string;
6
6
  declare const generateConfigFile: (configPath: string, collectionNames: string[]) => void;
package/dist/cli.js CHANGED
@@ -1,16 +1,16 @@
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(); } } 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 _chunk6TXKRKDJjs = require('./chunk-6TXKRKDJ.js');var _commander = require('commander');require('ts-node/esm');var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);var _process = require('process'); var _process2 = _interopRequireDefault(_process);var r=(n=["emmett-expressjs"])=>`
2
+ import{k as o,p as f}from"./chunk-6TXKRKDJ.js";import{Command as $}from"commander";import{Command as d}from"commander";import{writeFileSync as P}from"node:fs";import{exit as c}from"process";var s=(e=["emmett-expressjs"])=>`
3
3
  export default {
4
- plugins: ${n.length>0?`[
5
- ${n.map(t=>`"${t}"`).join(`,
4
+ plugins: ${e.length>0?`[
5
+ ${e.map(t=>`"${t}"`).join(`,
6
6
  `)}
7
7
  ]`:"[]"},
8
8
  };
9
- `,h= exports.generateConfigFile =(n,e)=>{try{_fs2.default.writeFileSync(n,r(e),"utf8"),console.log(`Configuration file stored at: ${n}`)}catch(t){console.error(`Error: Couldn't store config file: ${n}!`),console.error(t),_process2.default.exit(1)}},C= exports.configCommand =new (0, _commander.Command)("config").description("Manage Pongo configuration");C.command("sample").description("Generate or print sample configuration").option("-plg, --plugins <name>","Specify the plugin name",(n,e)=>e.concat([n]),[]).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(n=>{let e=n.plugin.length>0?n.plugin:["@event-driven-io/emmett-expressjs"];!("print"in n)&&!("generate"in n)&&(console.error(`Error: Please provide either:
9
+ `,h=(e,n)=>{try{P(e,s(n),"utf8"),console.log(`Configuration file stored at: ${e}`)}catch(t){console.error(`Error: Couldn't store config file: ${e}!`),console.error(t),process.exit(1)}},C=new d("config").description("Manage Pongo configuration");C.command("sample").description("Generate or print sample configuration").option("-plg, --plugins <name>","Specify the plugin name",(e,n)=>n.concat([e]),[]).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(e=>{let n=e.plugin.length>0?e.plugin:["@event-driven-io/emmett-expressjs"];!("print"in e)&&!("generate"in e)&&(console.error(`Error: Please provide either:
10
10
  --print param to print sample config or
11
- --generate to generate sample config file`),_process2.default.exit(1)),"print"in n?console.log(`${r(e)}`):"generate"in n&&(n.file||(console.error("Error: You need to provide a config file through a --file"),_process2.default.exit(1)),h(n.file,e))});var _path = require('path'); var _path2 = _interopRequireDefault(_path);var f={missingDefaultExport:`Error: Config should contain default export, e.g.
11
+ --generate to generate sample config file`),c(1)),"print"in e?console.log(`${s(n)}`):"generate"in e&&(e.file||(console.error("Error: You need to provide a config file through a --file"),c(1)),h(e.file,n))});import"commander";import E from"path";var m={missingDefaultExport:`Error: Config should contain default export, e.g.
12
12
 
13
- ${r()}`,missingPluginsPropertyExport:`Error: Config should contain default export with plugins array, e.g.
13
+ ${s()}`,missingPluginsPropertyExport:`Error: Config should contain default export with plugins array, e.g.
14
14
 
15
- ${r()}`,wrongPluginStructure:"Error: Plugin config should be either string with plugin name or object with plugin name, e.g. { name: 'emmett-expressjs' }"},y= exports.importPluginsConfig =async n=>{let e=_path2.default.join(process.cwd(),_nullishCoalesce(_optionalChain([n, 'optionalAccess', _ => _.configPath]), () => ("emmett.config.mts")));try{let t=await Promise.resolve().then(() => _interopRequireWildcard(require(e)));return t.default?!t.default.plugins||!Array.isArray(t.default.plugins)?new (0, _chunk6TXKRKDJjs.k)(f.missingPluginsPropertyExport):t.default.plugins.every(_chunk6TXKRKDJjs.p)?{plugins:t.default.plugins}:new (0, _chunk6TXKRKDJjs.k)(f.wrongPluginStructure):new (0, _chunk6TXKRKDJjs.k)(f.missingDefaultExport)}catch(t){return _optionalChain([n, 'optionalAccess', _2 => _2.configPath])?new (0, _chunk6TXKRKDJjs.k)("Error: Couldn't load file:"+t.toString()):(console.warn("Didn`t find config file: "+e),{plugins:[]})}},c= exports.loadPlugins =async n=>{try{let e=await y({configPath:_optionalChain([n, 'optionalAccess', _3 => _3.configPath])});if(e instanceof _chunk6TXKRKDJjs.k)throw e;if(e.plugins.length===0)return console.log("No extensions specified in emmett.config.ts."),[];let o=x(e.plugins,_optionalChain([n, 'optionalAccess', _4 => _4.pluginType])).map(async l=>{let g=w(l,_optionalChain([n, 'optionalAccess', _5 => _5.pluginType]));try{let a=await Promise.resolve().then(() => _interopRequireWildcard(require(g)));return console.info(`Loaded plugin: ${g}`),a}catch(a){console.error(`Failed to load extension "${g}":`,a);return}});return(await Promise.all(o)).filter(l=>l!==void 0)}catch(e){return console.error("Failed to load emmett.config.ts:",e),[]}},u= exports.registerCliPlugins =async(n,e)=>{let t=[];for(let o of e)"registerCommands"in o&&console.warn(`No registerCommands function found in ${o.name}`),await o.registerCommands(n),console.log(`Loaded extension: ${o.name}`),t.push(o)},x=(n,e)=>n.filter(t=>typeof t=="string"||e&&(t.register===void 0||t.register.some(o=>o.pluginType===e))),w=(n,e)=>{if(typeof n=="string")return e?`${n}/${e}`:n;let t=_nullishCoalesce(_optionalChain([n, 'access', _6 => _6.register, 'access', _7 => _7.find, 'call', _8 => _8(o=>e&&o.pluginType===e), 'optionalAccess', _9 => _9.path]), () => (e));return t?`${n.name}/${t}`:n.name};var s=new _commander.Command;s.name("emmett").description("CLI tool for Emmett").option("--config <path>","Path to the configuration file","emmett.config.ts");var v=async()=>{let e=s.opts().config;try{let t=await c({pluginType:"cli",configPath:e});await u(s,t),s.parse(process.argv)}catch(t){console.error(`Failed to load config from ${e}:`,t)}};v().catch(n=>{console.error("CLI initialization failed:"),console.error(n)});var q=s;exports.configCommand = C; exports.default = q; exports.generateConfigFile = h; exports.importPluginsConfig = y; exports.loadPlugins = c; exports.registerCliPlugins = u; exports.sampleConfig = r;
15
+ ${s()}`,wrongPluginStructure:"Error: Plugin config should be either string with plugin name or object with plugin name, e.g. { name: 'emmett-expressjs' }"},y=async e=>{let n=E.join(process.cwd(),e?.configPath??"./dist/emmett.config.js");console.log("IMPORTING"+n);try{let t=await import(n);return t.default?!t.default.plugins||!Array.isArray(t.default.plugins)?new o(m.missingPluginsPropertyExport):t.default.plugins.every(f)?{plugins:t.default.plugins}:new o(m.wrongPluginStructure):new o(m.missingDefaultExport)}catch(t){return e?.configPath?new o("Error: Couldn't load file:"+t.toString()):(console.warn("Didn`t find config file: "+n,t),{plugins:[]})}},u=async e=>{try{let n=await y({configPath:e?.configPath});if(n instanceof o)throw n;if(n.plugins.length===0)return console.log(`No extensions specified in config ${e?.configPath}.`),[];let i=x(n.plugins,e?.pluginType).map(async r=>{let l=w(r,e?.pluginType);try{let a=await import(l);if(console.info(`Loaded plugin: ${l}`),!a.default)throw new Error(`Plugin: ${l} is missing default export`);return a.default}catch(a){console.error(`Failed to load extension "${l}":`,a);return}});return(await Promise.all(i)).filter(r=>r!==void 0)}catch(n){return console.error(`Failed to load config ${e?.configPath}:`,n),[]}},p=async(e,n)=>{let t=[];for(let i of n){let r=i.name;"registerCommands"in i||console.warn(`No registerCommands function found in ${r}`),await i.registerCommands(e),console.log(`Loaded extension: ${i.name}`),t.push(i)}},x=(e,n)=>e.filter(t=>typeof t=="string"||n&&(t.register===void 0||t.register.some(i=>i.pluginType===n))),w=(e,n)=>{if(typeof e=="string")return n?`${e}/${n}`:e;let t=e.register.find(i=>n&&i.pluginType===n)?.path??n;return t?`${e.name}/${t}`:e.name};var g=new $;g.name("emmett").description("CLI tool for Emmett").option("--config <path>","Path to the configuration file");var v=async()=>{let e=process.argv.indexOf("--config"),n=e!==-1&&process.argv.length>e+1?process.argv[e+1]:void 0;try{let t=await u({pluginType:"cli",configPath:n});await p(g,t),g.parse(process.argv)}catch(t){console.error(`Failed to load config from ${n}:`,t)}};v().catch(e=>{console.error("CLI initialization failed:"),console.error(e)});var Y=g;export{C as configCommand,Y as default,h as generateConfigFile,y as importPluginsConfig,u as loadPlugins,p as registerCliPlugins,s as sampleConfig};
16
16
  //# sourceMappingURL=cli.js.map
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/emmett/emmett/src/packages/emmett/dist/cli.js","../src/cli.ts","../src/commandLine/config.ts","../src/commandLine/plugins.ts"],"names":["sampleConfig","plugins","p","generateConfigFile","configPath","collectionNames","fs"],"mappings":"AAAA;AACA,ylCAAyC,sCCAjB,uBACjB,gECAQ,oFACK,IAEPA,CAAAA,CAAe,CAACC,CAAAA,CAAoB,CAAC,kBAAkB,CAAA,CAAA,EAM3D,CAAA;AAAA;AAAA,WAAA,EAJLA,CAAAA,CAAQ,MAAA,CAAS,CAAA,CACb,CAAA;AAAA,EAAMA,CAAAA,CAAQ,GAAA,CAAKC,CAAAA,EAAM,CAAA,CAAA,EAAIA,CAAC,CAAA,CAAA,CAAG,CAAA,CAAE,IAAA,CAAK,CAAA;AAAA,CAAK,CAAC,CAAA;AAAA,CAAA,CAAA,CAC9C,IAIiB,CAAA;AAAA;AAAA,CAAA,CAKZC,CAAAA,8BAAqB,CAChCC,CAAAA,CACAC,CAAAA,CAAAA,EACS,CACT,GAAI,CACFC,YAAAA,CAAG,aAAA,CAAcF,CAAAA,CAAYJ,CAAAA,CAAaK,CAAe,CAAA,CAAG,MAAM,CAAA,CAClE,OAAA,CAAQ,GAAA,CAAI,CAAA,8BAAA,EAAiCD,CAAU,CAAA,CAAA;AAiDnD;AAOO,yCAAA;AClES;AACQ;AAAA;AACR","file":"/home/runner/work/emmett/emmett/src/packages/emmett/dist/cli.js","sourcesContent":[null,"#!/usr/bin/env node\nimport { Command } from 'commander';\nimport 'ts-node/esm'; // Allows dynamic TypeScript imports\nimport { loadPlugins, registerCliPlugins } from './commandLine';\n\nconst program = new Command();\n\nprogram\n .name('emmett')\n .description('CLI tool for Emmett')\n .option(\n '--config <path>',\n 'Path to the configuration file',\n `emmett.config.ts`,\n );\n\n// Load extensions and parse CLI arguments\nconst initCLI = async () => {\n const options = program.opts<{ config: string }>();\n const configPath = options.config;\n\n try {\n const plugins = await loadPlugins({\n pluginType: 'cli',\n configPath: configPath,\n });\n await registerCliPlugins(program, plugins);\n\n // Parse the CLI arguments\n program.parse(process.argv);\n } catch (err) {\n console.error(`Failed to load config from ${configPath}:`, err);\n }\n};\n\n// Initialize CLI and handle errors\ninitCLI().catch((err) => {\n console.error(`CLI initialization failed:`);\n console.error(err);\n});\n\nexport default program;\nexport * from './commandLine';\n","import { Command as CliCommand } from 'commander';\n// eslint-disable-next-line no-restricted-imports\nimport fs from 'node:fs';\nimport process from 'process';\n\nexport const sampleConfig = (plugins: string[] = ['emmett-expressjs']) => {\n const pluginsNames =\n plugins.length > 0\n ? `[\\n${plugins.map((p) => `\"${p}\"`).join(',\\n')} \\n]`\n : '[]';\n\n return `\nexport default {\n plugins: ${pluginsNames},\n};\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 configCommand = new CliCommand('config').description(\n 'Manage Pongo configuration',\n);\n\ntype SampleConfigOptions =\n | {\n plugin: string[];\n print?: boolean;\n }\n | {\n plugin: string[];\n generate?: boolean;\n file?: string;\n };\n\nconfigCommand\n .command('sample')\n .description('Generate or print sample configuration')\n .option(\n '-plg, --plugins <name>',\n 'Specify the plugin name',\n (value: string, previous: string[]) => {\n // Accumulate plugins 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 plugins =\n options.plugin.length > 0\n ? options.plugin\n : ['@event-driven-io/emmett-expressjs'];\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(plugins)}`);\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, plugins);\n }\n });\n","import { Command as CliCommand } from 'commander';\nimport path from 'path';\nimport {\n isPluginConfig,\n type EmmettCliPlugin,\n type EmmettPlugin,\n type EmmettPluginConfig,\n type EmmettPluginsConfig,\n type EmmettPluginType,\n} from '../config';\nimport { EmmettError } from '../errors';\nimport { sampleConfig } from './config';\n\nconst PluginsConfigImportError = {\n missingDefaultExport: `Error: Config should contain default export, e.g.\\n\\n${sampleConfig()}`,\n missingPluginsPropertyExport: `Error: Config should contain default export with plugins array, e.g.\\n\\n${sampleConfig()}`,\n wrongPluginStructure: `Error: Plugin config should be either string with plugin name or object with plugin name, e.g. { name: 'emmett-expressjs' }`,\n};\nexport const importPluginsConfig = async (options?: {\n configPath?: string | undefined;\n}): Promise<EmmettPluginsConfig | EmmettError> => {\n const configPath = path.join(\n process.cwd(),\n options?.configPath ?? 'emmett.config.mts',\n );\n\n try {\n const imported = (await import(configPath)) as {\n default: Partial<EmmettPluginsConfig>;\n };\n\n if (!imported.default) {\n return new EmmettError(PluginsConfigImportError.missingDefaultExport);\n }\n\n if (!imported.default.plugins || !Array.isArray(imported.default.plugins)) {\n return new EmmettError(\n PluginsConfigImportError.missingPluginsPropertyExport,\n );\n }\n\n if (!imported.default.plugins.every(isPluginConfig)) {\n return new EmmettError(PluginsConfigImportError.wrongPluginStructure);\n }\n\n return { plugins: imported.default.plugins };\n } catch (error) {\n if (!options?.configPath) {\n console.warn('Didn`t find config file: ' + configPath);\n return { plugins: [] };\n }\n return new EmmettError(\n `Error: Couldn't load file:` + (error as Error).toString(),\n );\n }\n};\n\nexport const loadPlugins = async (options?: {\n pluginType?: EmmettPluginType;\n configPath?: string;\n}): Promise<EmmettPlugin[]> => {\n try {\n const pluginsConfig = await importPluginsConfig({\n configPath: options?.configPath,\n });\n\n if (pluginsConfig instanceof EmmettError) throw pluginsConfig;\n\n if (pluginsConfig.plugins.length === 0) {\n console.log('No extensions specified in emmett.config.ts.');\n return [];\n }\n\n const pluginsToLoad = filterPluginsByType(\n pluginsConfig.plugins,\n options?.pluginType,\n );\n\n const pluginsPromises = pluginsToLoad.map(async (pluginConfig) => {\n const importPath = getImportPath(pluginConfig, options?.pluginType);\n try {\n const plugin = (await import(importPath)) as EmmettPlugin;\n\n console.info(`Loaded plugin: ${importPath}`);\n\n return plugin;\n } catch (error) {\n console.error(`Failed to load extension \"${importPath}\":`, error);\n return undefined;\n }\n });\n\n return (await Promise.all(pluginsPromises)).filter(\n (plugin) => plugin !== undefined,\n );\n } catch (error) {\n console.error('Failed to load emmett.config.ts:', error);\n return [];\n }\n};\n\nexport const registerCliPlugins = async (\n program: CliCommand,\n plugins: EmmettCliPlugin[],\n): Promise<void> => {\n const result: EmmettCliPlugin[] = [];\n\n for (const plugin of plugins) {\n if ('registerCommands' in plugin) {\n console.warn(`No registerCommands function found in ${plugin.name}`);\n }\n await plugin.registerCommands(program);\n console.log(`Loaded extension: ${plugin.name}`);\n result.push(plugin);\n }\n};\n\nconst filterPluginsByType = (\n plugins: EmmettPluginConfig[],\n pluginType?: EmmettPluginType,\n): EmmettPluginConfig[] =>\n plugins.filter(\n (p) =>\n typeof p === 'string' ||\n (pluginType &&\n (p.register === undefined ||\n p.register.some((r) => r.pluginType === pluginType))),\n );\n\nconst getImportPath = (\n pluginConfig: EmmettPluginConfig,\n pluginType: EmmettPluginType | undefined,\n) => {\n if (typeof pluginConfig === 'string') {\n return pluginType ? `${pluginConfig}/${pluginType}` : pluginConfig;\n }\n\n const pluginSubpath =\n pluginConfig.register.find((r) => pluginType && r.pluginType === pluginType)\n ?.path ?? pluginType;\n\n return pluginSubpath\n ? `${pluginConfig.name}/${pluginSubpath}`\n : pluginConfig.name;\n};\n"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/commandLine/config.ts","../src/commandLine/plugins.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { loadPlugins, registerCliPlugins } from './commandLine';\n\nconst program = new Command();\n\nprogram\n .name('emmett')\n .description('CLI tool for Emmett')\n .option('--config <path>', 'Path to the configuration file');\n\n// Load extensions and parse CLI arguments\nconst initCLI = async () => {\n const configIndex = process.argv.indexOf('--config');\n\n const configPath =\n configIndex !== -1 && process.argv.length > configIndex + 1\n ? process.argv[configIndex + 1]\n : undefined;\n\n try {\n const plugins = await loadPlugins({\n pluginType: 'cli',\n configPath: configPath,\n });\n await registerCliPlugins(program, plugins);\n\n // Parse the CLI arguments\n program.parse(process.argv);\n } catch (err) {\n console.error(`Failed to load config from ${configPath}:`, err);\n }\n};\n\n//Initialize CLI and handle errors\ninitCLI().catch((err) => {\n console.error(`CLI initialization failed:`);\n console.error(err);\n});\n\nexport default program;\nexport * from './commandLine';\n","import { Command as CliCommand } from 'commander';\n// eslint-disable-next-line no-restricted-imports\nimport { writeFileSync } from 'node:fs';\nimport { exit } from 'process';\n\nexport const sampleConfig = (plugins: string[] = ['emmett-expressjs']) => {\n const pluginsNames =\n plugins.length > 0\n ? `[\\n${plugins.map((p) => `\"${p}\"`).join(',\\n')} \\n]`\n : '[]';\n\n return `\nexport default {\n plugins: ${pluginsNames},\n};\n`;\n};\n\nexport const generateConfigFile = (\n configPath: string,\n collectionNames: string[],\n): void => {\n try {\n 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 configCommand = new CliCommand('config').description(\n 'Manage Pongo configuration',\n);\n\ntype SampleConfigOptions =\n | {\n plugin: string[];\n print?: boolean;\n }\n | {\n plugin: string[];\n generate?: boolean;\n file?: string;\n };\n\nconfigCommand\n .command('sample')\n .description('Generate or print sample configuration')\n .option(\n '-plg, --plugins <name>',\n 'Specify the plugin name',\n (value: string, previous: string[]) => {\n // Accumulate plugins 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 plugins =\n options.plugin.length > 0\n ? options.plugin\n : ['@event-driven-io/emmett-expressjs'];\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 exit(1);\n }\n\n if ('print' in options) {\n console.log(`${sampleConfig(plugins)}`);\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 exit(1);\n }\n\n generateConfigFile(options.file, plugins);\n }\n });\n","import { Command as CliCommand } from 'commander';\nimport path from 'path';\nimport {\n isPluginConfig,\n type EmmettCliPlugin,\n type EmmettPlugin,\n type EmmettPluginConfig,\n type EmmettPluginsConfig,\n type EmmettPluginType,\n} from '../config';\nimport { EmmettError } from '../errors';\nimport { sampleConfig } from './config';\n\nconst PluginsConfigImportError = {\n missingDefaultExport: `Error: Config should contain default export, e.g.\\n\\n${sampleConfig()}`,\n missingPluginsPropertyExport: `Error: Config should contain default export with plugins array, e.g.\\n\\n${sampleConfig()}`,\n wrongPluginStructure: `Error: Plugin config should be either string with plugin name or object with plugin name, e.g. { name: 'emmett-expressjs' }`,\n};\nexport const importPluginsConfig = async (options?: {\n configPath?: string | undefined;\n}): Promise<EmmettPluginsConfig | EmmettError> => {\n const configPath = path.join(\n process.cwd(),\n options?.configPath ?? './dist/emmett.config.js',\n );\n\n console.log('IMPORTING' + configPath);\n\n try {\n const imported = (await import(configPath)) as {\n default: Partial<EmmettPluginsConfig>;\n };\n\n if (!imported.default) {\n return new EmmettError(PluginsConfigImportError.missingDefaultExport);\n }\n\n if (!imported.default.plugins || !Array.isArray(imported.default.plugins)) {\n return new EmmettError(\n PluginsConfigImportError.missingPluginsPropertyExport,\n );\n }\n\n if (!imported.default.plugins.every(isPluginConfig)) {\n return new EmmettError(PluginsConfigImportError.wrongPluginStructure);\n }\n\n return { plugins: imported.default.plugins };\n } catch (error) {\n if (!options?.configPath) {\n console.warn('Didn`t find config file: ' + configPath, error);\n return { plugins: [] };\n }\n return new EmmettError(\n `Error: Couldn't load file:` + (error as Error).toString(),\n );\n }\n};\n\nexport const loadPlugins = async (options?: {\n pluginType?: EmmettPluginType;\n configPath?: string;\n}): Promise<EmmettPlugin[]> => {\n try {\n const pluginsConfig = await importPluginsConfig({\n configPath: options?.configPath,\n });\n\n if (pluginsConfig instanceof EmmettError) throw pluginsConfig;\n\n if (pluginsConfig.plugins.length === 0) {\n console.log(`No extensions specified in config ${options?.configPath}.`);\n return [];\n }\n\n const pluginsToLoad = filterPluginsByType(\n pluginsConfig.plugins,\n options?.pluginType,\n );\n\n const pluginsPromises = pluginsToLoad.map(async (pluginConfig) => {\n const importPath = getImportPath(pluginConfig, options?.pluginType);\n try {\n const plugin = (await import(importPath)) as { default: EmmettPlugin };\n\n console.info(`Loaded plugin: ${importPath}`);\n\n if (!plugin.default) {\n throw new Error(`Plugin: ${importPath} is missing default export`);\n }\n\n return plugin.default;\n } catch (error) {\n console.error(`Failed to load extension \"${importPath}\":`, error);\n return undefined;\n }\n });\n\n return (await Promise.all(pluginsPromises)).filter(\n (plugin) => plugin !== undefined,\n );\n } catch (error) {\n console.error(`Failed to load config ${options?.configPath}:`, error);\n return [];\n }\n};\n\nexport const registerCliPlugins = async (\n program: CliCommand,\n plugins: EmmettCliPlugin[],\n): Promise<void> => {\n const result: EmmettCliPlugin[] = [];\n\n for (const plugin of plugins) {\n const pluginName = plugin.name;\n\n if (!('registerCommands' in plugin)) {\n console.warn(`No registerCommands function found in ${pluginName}`);\n }\n await plugin.registerCommands(program);\n console.log(`Loaded extension: ${plugin.name}`);\n result.push(plugin);\n }\n};\n\nconst filterPluginsByType = (\n plugins: EmmettPluginConfig[],\n pluginType?: EmmettPluginType,\n): EmmettPluginConfig[] =>\n plugins.filter(\n (p) =>\n typeof p === 'string' ||\n (pluginType &&\n (p.register === undefined ||\n p.register.some((r) => r.pluginType === pluginType))),\n );\n\nconst getImportPath = (\n pluginConfig: EmmettPluginConfig,\n pluginType: EmmettPluginType | undefined,\n) => {\n if (typeof pluginConfig === 'string') {\n return pluginType ? `${pluginConfig}/${pluginType}` : pluginConfig;\n }\n\n const pluginSubpath =\n pluginConfig.register.find((r) => pluginType && r.pluginType === pluginType)\n ?.path ?? pluginType;\n\n return pluginSubpath\n ? `${pluginConfig.name}/${pluginSubpath}`\n : pluginConfig.name;\n};\n"],"mappings":";+CACA,OAAS,WAAAA,MAAe,YCDxB,OAAS,WAAWC,MAAkB,YAEtC,OAAS,iBAAAC,MAAqB,UAC9B,OAAS,QAAAC,MAAY,UAEd,IAAMC,EAAe,CAACC,EAAoB,CAAC,kBAAkB,IAM3D;AAAA;AAAA,aAJLA,EAAQ,OAAS,EACb;AAAA,EAAMA,EAAQ,IAAKC,GAAM,IAAIA,CAAC,GAAG,EAAE,KAAK;AAAA,CAAK,CAAC;AAAA,GAC9C,IAIiB;AAAA;AAAA,EAKZC,EAAqB,CAChCC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AQ,CACvB,QAAQ,MAAM,4BAA4B,EAC1C,QAAQ,MAAMA,CAAG,CACnB,CAAC,EAED,IAAOC,EAAQT","names":["Command","CliCommand","writeFileSync","exit","sampleConfig","plugins","p","generateConfigFile","configPath","collectionNames","error","configCommand","value","previous","options","path","PluginsConfigImportError","sampleConfig","importPluginsConfig","options","configPath","path","imported","EmmettError","isPluginConfig","error","loadPlugins","pluginsConfig","pluginsPromises","filterPluginsByType","pluginConfig","importPath","getImportPath","plugin","registerCliPlugins","program","plugins","result","pluginName","pluginType","p","r","pluginSubpath","program","Command","initCLI","configIndex","configPath","plugins","loadPlugins","registerCliPlugins","err","cli_default"]}
package/dist/index.cjs ADDED
@@ -0,0 +1,17 @@
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 _chunkCJZAVRMTcjs = require('./chunk-CJZAVRMT.cjs');var H=t=>"withSession"in t,F= exports.nulloSessionFactory =t=>({withSession:e=>e({eventStore:t,close:()=>Promise.resolve()})});var U="STREAM_EXISTS",O= exports.STREAM_DOES_NOT_EXIST ="STREAM_DOES_NOT_EXIST",f= exports.NO_CONCURRENCY_CHECK ="NO_CONCURRENCY_CHECK",$= exports.matchesExpectedVersion =(t,e)=>e===f?!0:e==O?t===void 0:e==U?t!==void 0:t===e,M= exports.assertExpectedVersionMatchesCurrent =(t,e)=>{if(e??=f,!$(t,e))throw new V(t,e)},V= exports.ExpectedVersionConflictError =class t extends _chunkCJZAVRMTcjs.l{constructor(e,n){super(_optionalChain([e, 'optionalAccess', _2 => _2.toString, 'call', _3 => _3()]),_optionalChain([n, 'optionalAccess', _4 => _4.toString, 'call', _5 => _5()])),Object.setPrototypeOf(this,t.prototype)}};var _uuid = require('uuid');var he=()=>{let t=new Map,e=()=>Array.from(t.values()).map(n=>n.length).reduce((n,r)=>n+r,0);return{async aggregateStream(n,r){let{evolve:o,initialState:a,read:i}=r,d=await this.readStream(n,i);if(!d)return null;let c=_nullishCoalesce(_optionalChain([d, 'optionalAccess', _6 => _6.events]), () => ([]));return{currentStreamVersion:BigInt(c.length),state:c.reduce(o,a())}},readStream:(n,r)=>{let o=t.get(n),a=o?BigInt(o.length):void 0;M(a,_optionalChain([r, 'optionalAccess', _7 => _7.expectedStreamVersion]));let i=Number(r&&"from"in r?r.from:0),d=Number(r&&"to"in r?r.to:r&&"maxCount"in r&&r.maxCount?r.from+r.maxCount:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _8 => _8.length]), () => (1))),c=o&&o.length>0?o.map(y=>y).slice(i,d):[],T=o&&o.length>0?{currentStreamVersion:a,events:c}:null;return Promise.resolve(T)},appendToStream:(n,r,o)=>{let a=_nullishCoalesce(t.get(n), () => ([])),i=a.length>0?BigInt(a.length):void 0;M(i,_optionalChain([o, 'optionalAccess', _9 => _9.expectedStreamVersion]));let d=r.map((y,E)=>({...y,metadata:{..._nullishCoalesce(y.metadata, () => ({})),streamName:n,eventId:_uuid.v4.call(void 0, ),streamPosition:BigInt(a.length+E+1),globalPosition:BigInt(e()+E+1)}})),c=BigInt(d.slice(-1)[0].metadata.streamPosition);t.set(n,[...a,...d]);let T={nextExpectedStreamVersion:c};return Promise.resolve(T)}}};var I=(t,e,n=r=>r)=>async(r,o,a,i)=>await K(r,async({eventStore:c})=>{let T=n(o),y=await c.aggregateStream(T,{evolve:t,initialState:e,read:{expectedStreamVersion:_nullishCoalesce(_optionalChain([i, 'optionalAccess', _10 => _10.expectedStreamVersion]), () => (f))}}),E=_nullishCoalesce(_optionalChain([y, 'optionalAccess', _11 => _11.state]), () => (e())),B=_optionalChain([y, 'optionalAccess', _12 => _12.currentStreamVersion]),C=a(E),D=Array.isArray(C)?C:[C],q=_nullishCoalesce(_nullishCoalesce(_optionalChain([i, 'optionalAccess', _13 => _13.expectedStreamVersion]), () => (B)), () => (O));return{...await c.appendToStream(T,D,{...i,expectedStreamVersion:q}),newEvents:D,newState:D.reduce(t,E)}}),K=(t,e)=>(H(t)?t:F(t)).withSession(e);var Pe=({decide:t,evolve:e,initialState:n},r=o=>o)=>async(o,a,i,d)=>I(e,n,r)(o,a,c=>t(i,c),d);var Fe=(t,e,n)=>({type:t,data:e,metadata:n});var Ne=(t,e,n)=>({type:t,data:e,metadata:n});var _e=t=>({kind:"Reply",message:t}),Be= exports.send =t=>({kind:"Send",message:t}),qe= exports.publish =t=>({kind:"Publish",message:t}),Ue= exports.schedule =(t,e)=>({kind:"Schedule",message:t,when:e}),$e= exports.complete =()=>({kind:"Complete"}),Ge= exports.ignore =t=>({kind:"Ignore",reason:t}),Ke= exports.error =t=>({kind:"Error",reason:t}),Je= exports.accept =()=>({kind:"Accept"});var rt=()=>{let t=new Map,e=[];return{send:async n=>{let r=t.get(n.type);if(r===void 0||r.length===0)throw new (0, _chunkCJZAVRMTcjs.k)(`No handler registered for command ${n.type}!`);let o=r[0];await o(n)},publish:async n=>{let r=_nullishCoalesce(t.get(n.type), () => ([]));for(let o of r)await o(n)},schedule:(n,r)=>{e=[...e,{message:n,options:r}]},handle:(n,...r)=>{let o=[...t.keys()].filter(a=>r.includes(a));if(o.length>0)throw new (0, _chunkCJZAVRMTcjs.k)(`Cannot register handler for commands ${o.join(", ")} as they're already registered!`);for(let a of r)t.set(a,[n])},subscribe(n,...r){for(let o of r)t.has(o)||t.set(o,[]),t.set(o,[..._nullishCoalesce(t.get(o), () => ([])),n])},dequeue:()=>{let n=e;return e=[],n}}};var at=t=>t,J= exports.inlineProjections =t=>t.map(e=>({type:"inline",projection:e})),X= exports.asyncProjections =t=>t.map(e=>({type:"async",projection:e})),st= exports.projections ={inline:J,async:X};var w=class extends Error{constructor(e){super(`Cannot parse! ${e}`)}},u= exports.JSONParser ={stringify:(t,e)=>JSON.stringify(_optionalChain([e, 'optionalAccess', _14 => _14.map])?e.map(t):t,(n,r)=>typeof r=="bigint"?r.toString():r),parse:(t,e)=>{let n=JSON.parse(t,_optionalChain([e, 'optionalAccess', _15 => _15.reviver]));if(_optionalChain([e, 'optionalAccess', _16 => _16.typeCheck])&&!_optionalChain([e, 'optionalAccess', _17 => _17.typeCheck, 'call', _18 => _18(n)]))throw new w(t);return _optionalChain([e, 'optionalAccess', _19 => _19.map])?e.map(n):n}};var b=t=>{let e=t.reduce((o,a)=>o+a.length,0),n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.length;return n};var yt=async t=>{let e=[];for await(let n of t)e.push(n);return e};var v= (_class =class{constructor() { _class.prototype.__init.call(this); }__init() {this.buffer=[]}addToBuffer(e){this.buffer.push(e)}clearBuffer(){this.buffer=[]}hasCompleteMessage(){let e=b(this.buffer);return new TextDecoder().decode(e).includes(`
2
+ `)}decode(){if(!this.hasCompleteMessage())return null;let e=b(this.buffer),n=new TextDecoder().decode(e),r=n.indexOf(`
3
+ `);if(r===-1)return null;let o=n.slice(0,r),a=new Uint8Array(e.buffer,r+1);return this.buffer=a.byteLength>0?[a]:[],JSON.parse(o)}}, _class);var S= (_class2 =class{constructor(e){;_class2.prototype.__init2.call(this);this.transform=e;this.transform=e}__init2() {this.buffer=[]}addToBuffer(e){this.buffer.push(e)}clearBuffer(){this.buffer=[]}hasCompleteMessage(){return this.buffer.some(e=>e.includes(`
4
+ `))}decode(){let e=this.buffer.join("");if(!this.hasCompleteMessage()){if(e.trim().length>0)throw new Error("Unterminated string in JSON at position");return null}let n=e.indexOf(`
5
+ `),r=e.slice(0,n).trim();return this.buffer=[e.slice(n+1)],this.transform(r)}}, _class2);var x=class extends S{constructor(){super(e=>JSON.parse(e))}};var g= (_class3 =class{constructor() { _class3.prototype.__init3.call(this); }__init3() {this.buffer=null}addToBuffer(e){this.buffer=e}clearBuffer(){this.buffer=null}hasCompleteMessage(){return this.buffer!==null}decode(){if(!this.hasCompleteMessage()||!this.buffer)return null;let e=this.buffer;return this.clearBuffer(),e}}, _class3);var P=class{constructor(e){this.decoders=e}decoderFor(e){let n=this.decoders.find(r=>r[0](e));return n?n[1]:null}addToBuffer(e){_optionalChain([this, 'access', _20 => _20.decoderFor, 'call', _21 => _21(e), 'optionalAccess', _22 => _22.addToBuffer, 'call', _23 => _23(e)])}clearBuffer(){for(let e of this.decoders.map(n=>n[1]))e.clearBuffer()}hasCompleteMessage(){return this.decoders.some(e=>e[1].hasCompleteMessage())}decode(){return _nullishCoalesce(_optionalChain([this, 'access', _24 => _24.decoders, 'access', _25 => _25.map, 'call', _26 => _26(n=>n[1]), 'access', _27 => _27.find, 'call', _28 => _28(n=>n.hasCompleteMessage()), 'optionalAccess', _29 => _29.decode, 'call', _30 => _30()]), () => (null))}},h= exports.DefaultDecoder =class extends P{constructor(){super([[e=>typeof e=="string",new x],[e=>e instanceof Uint8Array,new v],[e=>typeof e=="object",new g]])}};var _asyncretry = require('async-retry'); var _asyncretry2 = _interopRequireDefault(_asyncretry);var _webstreamspolyfill = require('web-streams-polyfill');var Nt=(t,e=o=>o,n={forever:!0,minTimeout:25},r=new h)=>new (0, _webstreamspolyfill.TransformStream)({start(o){_asyncretry2.default.call(void 0, ()=>z(t,o,e,r),n).catch(a=>{o.error(a)})}}).readable,z=async(t,e,n,r)=>{let a=t().getReader();try{let i;do i=await Q(a,e,n,r);while(!i)}finally{a.releaseLock()}},Q=async(t,e,n,r)=>{let{done:o,value:a}=await t.read();return a&&r.addToBuffer(a),!o&&!r.hasCompleteMessage()?!1:(Z(r,n,e),o&&e.terminate(),o)},Z=(t,e,n)=>{try{let r=t.decode();if(!r)return;let o=e(r);n.enqueue(o)}catch(r){n.error(new Error(`Decoding error: ${_optionalChain([r, 'optionalAccess', _31 => _31.toString, 'call', _32 => _32()])}`))}};var m=(t,e)=>{if(ee(t))return t.equals(e);if(Array.isArray(t))return Array.isArray(e)&&t.length===e.length&&t.every((o,a)=>m(o,e[a]));if(typeof t!="object"||typeof e!="object"||t===null||e===null)return t===e;if(Array.isArray(e))return!1;let n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length||!n.every(o=>r.includes(o)))return!1;for(let o in t){if(t[o]instanceof Function&&e[o]instanceof Function)continue;if(!m(t[o],e[o]))return!1}return!0},ee= exports.isEquatable =t=>t&&typeof t=="object"&&"equals"in t&&typeof t.equals=="function";var Kt=t=>{let e,n,r=0;do({value:e,done:n}=t.next()),r+=e||0;while(!n);return r};var Xt=(t,e,n,r,o=()=>{})=>{let a=!1,i=t.map(d=>n(d)?(a=!0,r(d)):d).filter(d=>d!==void 0).map(d=>{if(!d)throw Error("That should not happen");return d});return!a&&o()!==void 0?[...t,e]:i};var p=class extends Error{constructor(e){super(e)}},N= exports.isSubset =(t,e)=>{let n=t,r=e;return k(n),k(r),Object.keys(r).every(o=>typeof r[o]=="object"?N(n[o],r[o]):r[o]===n[o])},nn= exports.assertFails =t=>{throw new p(_nullishCoalesce(t, () => ("That should not ever happened, right?")))},rn= exports.assertThrowsAsync =async(t,e)=>{try{throw await t(),new p("Function didn't throw expected error")}catch(n){let r=n;return e&&s(e(r)),r}},on= exports.assertThrows =(t,e)=>{try{throw t(),new p("Function didn't throw expected error")}catch(n){let r=n;return e&&s(e(r)),r}},W= exports.assertMatches =(t,e,n)=>{if(!N(t,e))throw new p(_nullishCoalesce(n, () => (`subObj:
6
+ ${u.stringify(e)}
7
+ is not subset of
8
+ ${u.stringify(t)}`)))},an= exports.assertDeepEqual =(t,e,n)=>{if(!m(t,e))throw new p(_nullishCoalesce(n, () => (`subObj:
9
+ ${u.stringify(e)}
10
+ is not equal to
11
+ ${u.stringify(t)}`)))},sn= exports.assertNotDeepEqual =(t,e,n)=>{if(m(t,e))throw new p(_nullishCoalesce(n, () => (`subObj:
12
+ ${u.stringify(e)}
13
+ is equals to
14
+ ${u.stringify(t)}`)))},dn= exports.assertThat =t=>({isEqualTo:e=>s(m(t,e))});function te(t,e){if(t)throw new p(_nullishCoalesce(e, () => ("Condition is false")))}function s(t,e){if(!t)throw new p(_nullishCoalesce(e, () => ("Condition is false")))}function k(t,e){if(!t)throw new p(_nullishCoalesce(e, () => ("Condition is not truthy")))}function l(t,e,n){if(t!==e)throw new p(`${_nullishCoalesce(n, () => ("Objects are not equal"))}:
15
+ Expected: ${u.stringify(t)}
16
+ Actual:${u.stringify(e)}`)}function _(t,e,n){if(t===e)throw new p(_nullishCoalesce(n, () => (`Objects are equal: ${u.stringify(t)}`)))}function mn(t){_(t,null),k(t)}function pn(t){l(t,null)}var cn=t=>e=>m(e,t),un= exports.argMatches =t=>e=>t(e);function ln(t){return{calledTimes:e=>{l(_optionalChain([t, 'access', _33 => _33.mock, 'optionalAccess', _34 => _34.calls, 'optionalAccess', _35 => _35.length]),e)},notCalled:()=>{l(_optionalChain([t, 'optionalAccess', _36 => _36.mock, 'optionalAccess', _37 => _37.calls, 'optionalAccess', _38 => _38.length]),0)},called:()=>{s(_optionalChain([t, 'access', _39 => _39.mock, 'optionalAccess', _40 => _40.calls, 'access', _41 => _41.length])!==void 0&&t.mock.calls.length>0)},calledWith:(...e)=>{s(_optionalChain([t, 'access', _42 => _42.mock, 'optionalAccess', _43 => _43.calls, 'access', _44 => _44.length])!==void 0&&t.mock.calls.length>=1&&t.mock.calls.some(n=>m(n.arguments,e)))},calledOnceWith:(...e)=>{s(_optionalChain([t, 'access', _45 => _45.mock, 'optionalAccess', _46 => _46.calls, 'access', _47 => _47.length])!==void 0&&t.mock.calls.length===1&&t.mock.calls.some(n=>m(n.arguments,e)))},calledWithArgumentMatching:(...e)=>{s(_optionalChain([t, 'access', _48 => _48.mock, 'optionalAccess', _49 => _49.calls, 'access', _50 => _50.length])!==void 0&&t.mock.calls.length>=1),s(_optionalChain([t, 'access', _51 => _51.mock, 'optionalAccess', _52 => _52.calls, 'access', _53 => _53.length])!==void 0&&t.mock.calls.length>=1&&t.mock.calls.some(n=>n.arguments&&n.arguments.length>=e.length&&e.every((r,o)=>r(n.arguments[o]))))},notCalledWithArgumentMatching:(...e)=>{te(_optionalChain([t, 'access', _54 => _54.mock, 'optionalAccess', _55 => _55.calls, 'access', _56 => _56.length])!==void 0&&t.mock.calls.length>=1&&t.mock.calls[0].arguments&&t.mock.calls[0].arguments.length>=e.length&&e.every((n,r)=>n(t.mock.calls[0].arguments[r])))}}}var yn=t=>({isEmpty:()=>l(t.length,0),isNotEmpty:()=>_(t.length,0),hasSize:e=>l(t.length,e),containsElements:(...e)=>{s(e.every(n=>e.some(r=>m(n,r))))},containsExactlyInAnyOrder:(...e)=>{l(t.length,e.length),s(t.every(n=>e.some(r=>m(n,r))))},containsExactlyInAnyOrderElementsOf:e=>{l(t.length,e.length),s(t.every(n=>e.some(r=>m(n,r))))},containsExactlyElementsOf:e=>{l(t.length,e.length);for(let n=0;n<t.length;n++)s(m(t[n],e[n]))},containsExactly:e=>{l(t.length,1),s(m(t[0],e))},contains:e=>{s(t.some(n=>m(n,e)))},containsOnlyOnceElementsOf:e=>{s(e.map(n=>t.filter(r=>m(r,n)).length).filter(n=>n===1).length===e.length)},containsAnyOf:(...e)=>{s(t.some(n=>e.some(r=>m(n,r))))},allMatch:e=>{s(t.every(e))},anyMatches:e=>{s(t.some(e))},allMatchAsync:async e=>{for(let n of t)s(await e(n))}});var vn={for:t=>e=>({when:n=>{let r=()=>{let a=(Array.isArray(e)?e:[e]).reduce(t.evolve,t.initialState());return t.decide(n,a)};return{then:o=>{let a=r(),i=Array.isArray(a)?a:[a],d=Array.isArray(o)?o:[o];W(i,d)},thenThrows:(...o)=>{try{throw r(),new p("Handler did not fail as expected")}catch(a){if(a instanceof p)throw a;if(o.length===0)return;if(!_chunkCJZAVRMTcjs.j.call(void 0, o[0])){s(o[0](a),`Error didn't match the error condition: ${_optionalChain([a, 'optionalAccess', _57 => _57.toString, 'call', _58 => _58()])}`);return}s(a instanceof o[0],`Caught error is not an instance of the expected type: ${_optionalChain([a, 'optionalAccess', _59 => _59.toString, 'call', _60 => _60()])}`),o[1]&&s(o[1](a),`Error didn't match the error condition: ${_optionalChain([a, 'optionalAccess', _61 => _61.toString, 'call', _62 => _62()])}`)}}}}})};var gn=t=>{let e=new Map;return{async aggregateStream(n,r){return t.aggregateStream(n,r)},readStream(n,r){return t.readStream(n,r)},appendToStream:async(n,r,o)=>{let a=await t.appendToStream(n,r,o),i=_nullishCoalesce(e.get(n), () => ([n,[]]));return e.set(n,[n,[...i[1],...r]]),a},appendedEvents:e,setup:async(n,r)=>t.appendToStream(n,r)}};exports.AssertionError = p; exports.BinaryJsonDecoder = v; exports.CommandHandler = I; exports.CompositeDecoder = P; exports.ConcurrencyError = _chunkCJZAVRMTcjs.l; exports.DeciderCommandHandler = Pe; exports.DeciderSpecification = vn; exports.DefaultDecoder = h; exports.EmmettError = _chunkCJZAVRMTcjs.k; exports.ExpectedVersionConflictError = V; exports.IllegalStateError = _chunkCJZAVRMTcjs.n; exports.JSONParser = u; exports.JsonDecoder = x; exports.NO_CONCURRENCY_CHECK = f; exports.NotFoundError = _chunkCJZAVRMTcjs.o; exports.ObjectDecoder = g; exports.ParseError = w; exports.STREAM_DOES_NOT_EXIST = O; exports.STREAM_EXISTS = U; exports.StringDecoder = S; exports.ValidationError = _chunkCJZAVRMTcjs.m; exports.ValidationErrors = _chunkCJZAVRMTcjs.d; exports.WrapEventStore = gn; exports.accept = Je; exports.argMatches = un; exports.argValue = cn; exports.assertDeepEqual = an; exports.assertEqual = l; exports.assertExpectedVersionMatchesCurrent = M; exports.assertFails = nn; exports.assertFalse = te; exports.assertIsNotNull = mn; exports.assertIsNull = pn; exports.assertMatches = W; exports.assertNotDeepEqual = sn; exports.assertNotEmptyString = _chunkCJZAVRMTcjs.g; exports.assertNotEqual = _; exports.assertOk = k; exports.assertPositiveNumber = _chunkCJZAVRMTcjs.h; exports.assertThat = dn; exports.assertThatArray = yn; exports.assertThrows = on; exports.assertThrowsAsync = rn; exports.assertTrue = s; exports.assertUnsignedBigInt = _chunkCJZAVRMTcjs.i; exports.asyncProjections = X; exports.canCreateEventStoreSession = H; exports.collectStream = yt; exports.command = Fe; exports.complete = $e; exports.concatUint8Arrays = b; exports.deepEquals = m; exports.error = Ke; exports.event = Ne; exports.formatDateToUtcYYYYMMDD = _chunkCJZAVRMTcjs.a; exports.getInMemoryEventStore = he; exports.getInMemoryMessageBus = rt; exports.ignore = Ge; exports.inlineProjections = J; exports.isEquatable = ee; exports.isErrorConstructor = _chunkCJZAVRMTcjs.j; exports.isNumber = _chunkCJZAVRMTcjs.e; exports.isPluginConfig = _chunkCJZAVRMTcjs.p; exports.isString = _chunkCJZAVRMTcjs.f; exports.isSubset = N; exports.isValidYYYYMMDD = _chunkCJZAVRMTcjs.b; exports.matchesExpectedVersion = $; exports.merge = Xt; exports.nulloSessionFactory = F; exports.parseDateFromUtcYYYYMMDD = _chunkCJZAVRMTcjs.c; exports.projection = at; exports.projections = st; exports.publish = qe; exports.reply = _e; exports.restream = Nt; exports.schedule = Ue; exports.send = Be; exports.sum = Kt; exports.verifyThat = ln;
17
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/emmett/emmett/src/packages/emmett/dist/index.cjs","../src/eventStore/eventStore.ts","../src/eventStore/expectedVersion.ts","../src/eventStore/inMemoryEventStore.ts","../src/commandHandling/handleCommand.ts","../src/commandHandling/handleCommandWithDecider.ts","../src/typing/command.ts","../src/typing/event.ts","../src/typing/workflow.ts","../src/messageBus/index.ts","../src/projections/index.ts","../src/serialization/json/JSONParser.ts","../src/streaming/decoders/binary.ts","../src/streaming/decoders/string.ts","../src/testing/assertions.ts","../src/testing/wrapEventStore.ts"],"names":["canCreateEventStoreSession","eventStore","nulloSessionFactory","callback","STREAM_EXISTS","STREAM_DOES_NOT_EXIST","NO_CONCURRENCY_CHECK","matchesExpectedVersion","current","expected","assertExpectedVersionMatchesCurrent","ExpectedVersionConflictError","_ExpectedVersionConflictError","ConcurrencyError","getInMemoryEventStore","streams","getAllEventsCount","s","p","c","streamName","options","evolve","initialState","read","result","events","currentStreamVersion","from","to","resultEvents","e","currentEvents","eventEnvelopes","event","index","randomUUID","positionOfLastEventInTheStream","CommandHandler","mapToStreamId","id","store","handle","withSession","aggregationResult","state","newEvents","expectedStreamVersion","DeciderCommandHandler","decide","command","type","data","metadata","reply","message","send","publish","schedule","when","complete","ignore","reason","error","accept","getInMemoryMessageBus","allHandlers","pendingMessages","handlers","EmmettError","commandHandler","handler","commandTypes","alreadyRegistered","registered","commandType","eventHandler","eventTypes","eventType","pending","projection","definition","inlineProjections","definitions","asyncProjections","projections","ParseError","text"],"mappings":"AAAA,+2BAA8J,ICoDjJA,CAAAA,CAIXC,CAAAA,EAEA,aAAA,GAAiBA,CAAAA,CAENC,CAAAA,+BAIXD,CAAAA,EAAAA,CAC6D,CAC7D,WAAA,CAAcE,CAAAA,EAMLA,CAAAA,CALgE,CACrE,UAAA,CAAAF,CAAAA,CACA,KAAA,CAAO,CAAA,CAAA,EAAM,OAAA,CAAQ,OAAA,CAAQ,CAC/B,CAE4B,CAEhC,CAAA,CAAA,CCzDO,IAAMG,CAAAA,CAAgB,eAAA,CAChBC,CAAAA,iCACX,uBAAA,CACWC,CAAAA,gCACX,sBAAA,CAEWC,CAAAA,kCAAyB,CAGpCC,CAAAA,CACAC,CAAAA,CAAAA,EAEIA,CAAAA,GAAaH,CAAAA,CAA6B,CAAA,CAAA,CAE1CG,CAAAA,EAAYJ,CAAAA,CAA8BG,CAAAA,GAAY,KAAA,CAAA,CAEtDC,CAAAA,EAAYL,CAAAA,CAAsBI,CAAAA,GAAY,KAAA,CAAA,CAE3CA,CAAAA,GAAYC,CAAAA,CAGRC,CAAAA,+CAAsC,CAGjDF,CA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A,CAAgB,CAAE,IAAA,CAAM,QAAA,CAAU,UAAA,CAAAA,CAAW,CAAA,CAAE,CAAA,CAErDI,CAAAA,4BAKXD,CAAAA,EAEAA,CAAAA,CAAY,GAAA,CAAKH,CAAAA,EAAAA,CAAgB,CAAE,IAAA,CAAM,OAAA,CAAS,UAAA,CAAAA,CAAW,CAAA,CAAE,CAAA,CAEpDK,EAAAA,uBAAc,CACzB,MAAA,CAAQH,CAAAA,CACR,KAAA,CAAOE,CACT,CAAA,CCvFO,IAAME,CAAAA,CAAN,MAAA,QAAyB,KAAM,CACpC,WAAA,CAAYC,CAAAA,CAAc,CACxB,KAAA,CAAM,CAAA,cAAA,EAAiBA,CAAI,CAAA,CAAA;AC2BS;ACXc;AAaJ;ACgC1C;AAA0C;AAAA;AAY1C;AAA0C;AAAA;AAY1C;AAA0C;AAAA;AAsCP;AAA8C,UAAA;ACpDzF,OAAA","file":"/home/runner/work/emmett/emmett/src/packages/emmett/dist/index.cjs","sourcesContent":[null,"import type { Event, ReadEvent, ReadEventMetadata } from '../typing';\nimport type { ExpectedStreamVersion } from './expectedVersion';\n\n// #region event-store\nexport interface EventStore<\n StreamVersion = DefaultStreamVersionType,\n ReadEventMetadataType extends ReadEventMetadata = ReadEventMetadata,\n> {\n aggregateStream<State, EventType extends Event>(\n streamName: string,\n options: AggregateStreamOptions<\n State,\n EventType,\n StreamVersion,\n ReadEventMetadataType\n >,\n ): Promise<AggregateStreamResult<State, StreamVersion> | null>;\n\n readStream<EventType extends Event>(\n streamName: string,\n options?: ReadStreamOptions<StreamVersion>,\n ): Promise<ReadStreamResult<EventType, StreamVersion, ReadEventMetadataType>>;\n\n appendToStream<EventType extends Event>(\n streamName: string,\n events: EventType[],\n options?: AppendToStreamOptions<StreamVersion>,\n ): Promise<AppendToStreamResult<StreamVersion>>;\n}\n\nexport type EventStoreSession<\n EventStoreType extends EventStore<StreamVersion>,\n StreamVersion = DefaultStreamVersionType,\n> = {\n eventStore: EventStoreType;\n close: () => Promise<void>;\n};\n\nexport interface EventStoreSessionFactory<\n EventStoreType extends EventStore<StreamVersion>,\n StreamVersion = DefaultStreamVersionType,\n> {\n withSession<T = unknown>(\n callback: (\n session: EventStoreSession<EventStoreType, StreamVersion>,\n ) => Promise<T>,\n ): Promise<T>;\n}\n\nexport type DefaultStreamVersionType = bigint;\n// #endregion event-store\n\nexport const canCreateEventStoreSession = <\n Store extends EventStore<StreamVersion>,\n StreamVersion = DefaultStreamVersionType,\n>(\n eventStore: Store | EventStoreSessionFactory<Store, StreamVersion>,\n): eventStore is EventStoreSessionFactory<Store, StreamVersion> =>\n 'withSession' in eventStore;\n\nexport const nulloSessionFactory = <\n EventStoreType extends EventStore<StreamVersion>,\n StreamVersion = DefaultStreamVersionType,\n>(\n eventStore: EventStoreType,\n): EventStoreSessionFactory<EventStoreType, StreamVersion> => ({\n withSession: (callback) => {\n const nulloSession: EventStoreSession<EventStoreType, StreamVersion> = {\n eventStore,\n close: () => Promise.resolve(),\n };\n\n return callback(nulloSession);\n },\n});\n\n////////////////////////////////////////////////////////////////////\n/// ReadStream types\n////////////////////////////////////////////////////////////////////\n\nexport type ReadStreamOptions<StreamVersion = DefaultStreamVersionType> = (\n | {\n from: StreamVersion;\n }\n | { to: StreamVersion }\n | { from: StreamVersion; maxCount?: bigint }\n | {\n expectedStreamVersion: ExpectedStreamVersion<StreamVersion>;\n }\n) & {\n expectedStreamVersion?: ExpectedStreamVersion<StreamVersion>;\n};\n\nexport type ReadStreamResult<\n EventType extends Event,\n StreamVersion = DefaultStreamVersionType,\n ReadEventMetadataType extends ReadEventMetadata = ReadEventMetadata,\n> = {\n currentStreamVersion: StreamVersion;\n events: ReadEvent<EventType, ReadEventMetadataType>[];\n} | null;\n\n////////////////////////////////////////////////////////////////////\n/// AggregateStream types\n////////////////////////////////////////////////////////////////////\n\ntype Evolve<\n State,\n EventType extends Event,\n ReadEventMetadataType extends ReadEventMetadata = ReadEventMetadata,\n> =\n | ((currentState: State, event: EventType) => State)\n | ((\n currentState: State,\n event: ReadEvent<EventType, ReadEventMetadataType>,\n ) => State)\n | ((currentState: State, event: ReadEvent<EventType>) => State);\n\nexport type AggregateStreamOptions<\n State,\n EventType extends Event,\n StreamVersion = DefaultStreamVersionType,\n ReadEventMetadataType extends ReadEventMetadata = ReadEventMetadata,\n> = {\n evolve: Evolve<State, EventType, ReadEventMetadataType>;\n initialState: () => State;\n read?: ReadStreamOptions<StreamVersion>;\n};\n\nexport type AggregateStreamResult<\n State,\n StreamVersion = DefaultStreamVersionType,\n> = {\n currentStreamVersion: StreamVersion;\n state: State;\n};\n\n////////////////////////////////////////////////////////////////////\n/// AppendToStream types\n////////////////////////////////////////////////////////////////////\n\nexport type AppendToStreamOptions<StreamVersion = DefaultStreamVersionType> = {\n expectedStreamVersion?: ExpectedStreamVersion<StreamVersion>;\n};\n\nexport type AppendToStreamResult<StreamVersion = DefaultStreamVersionType> = {\n nextExpectedStreamVersion: StreamVersion;\n};\n","import { ConcurrencyError } from '../errors';\nimport type { Flavour } from '../typing';\nimport type { DefaultStreamVersionType } from './eventStore';\n\nexport type ExpectedStreamVersion<VersionType = DefaultStreamVersionType> =\n | ExpectedStreamVersionWithValue<VersionType>\n | ExpectedStreamVersionGeneral;\n\nexport type ExpectedStreamVersionWithValue<\n VersionType = DefaultStreamVersionType,\n> = Flavour<VersionType, 'StreamVersion'>;\n\nexport type ExpectedStreamVersionGeneral = Flavour<\n 'STREAM_EXISTS' | 'STREAM_DOES_NOT_EXIST' | 'NO_CONCURRENCY_CHECK',\n 'StreamVersion'\n>;\n\nexport const STREAM_EXISTS = 'STREAM_EXISTS' as ExpectedStreamVersionGeneral;\nexport const STREAM_DOES_NOT_EXIST =\n 'STREAM_DOES_NOT_EXIST' as ExpectedStreamVersionGeneral;\nexport const NO_CONCURRENCY_CHECK =\n 'NO_CONCURRENCY_CHECK' as ExpectedStreamVersionGeneral;\n\nexport const matchesExpectedVersion = <\n StreamVersion = DefaultStreamVersionType,\n>(\n current: StreamVersion | undefined,\n expected: ExpectedStreamVersion<StreamVersion>,\n): boolean => {\n if (expected === NO_CONCURRENCY_CHECK) return true;\n\n if (expected == STREAM_DOES_NOT_EXIST) return current === undefined;\n\n if (expected == STREAM_EXISTS) return current !== undefined;\n\n return current === expected;\n};\n\nexport const assertExpectedVersionMatchesCurrent = <\n StreamVersion = DefaultStreamVersionType,\n>(\n current: StreamVersion | undefined,\n expected: ExpectedStreamVersion<StreamVersion> | undefined,\n): void => {\n expected ??= NO_CONCURRENCY_CHECK;\n\n if (!matchesExpectedVersion(current, expected))\n throw new ExpectedVersionConflictError(current, expected);\n};\n\nexport class ExpectedVersionConflictError<\n VersionType = DefaultStreamVersionType,\n> extends ConcurrencyError {\n constructor(\n current: VersionType | undefined,\n expected: ExpectedStreamVersion<VersionType>,\n ) {\n super(current?.toString(), expected?.toString());\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, ExpectedVersionConflictError.prototype);\n }\n}\n","import { v4 as randomUUID } from 'uuid';\nimport type {\n Event,\n ReadEvent,\n ReadEventMetadataWithGlobalPosition,\n} from '../typing';\nimport {\n type AggregateStreamOptions,\n type AggregateStreamResult,\n type AppendToStreamOptions,\n type AppendToStreamResult,\n type DefaultStreamVersionType,\n type EventStore,\n type ReadStreamOptions,\n type ReadStreamResult,\n} from './eventStore';\nimport { assertExpectedVersionMatchesCurrent } from './expectedVersion';\n\nexport type EventHandler<E extends Event = Event> = (\n eventEnvelope: ReadEvent<E>,\n) => void;\n\nexport const getInMemoryEventStore = (): EventStore<\n DefaultStreamVersionType,\n ReadEventMetadataWithGlobalPosition\n> => {\n const streams = new Map<string, ReadEvent[]>();\n\n const getAllEventsCount = () => {\n return Array.from<ReadEvent[]>(streams.values())\n .map((s) => s.length)\n .reduce((p, c) => p + c, 0);\n };\n\n return {\n async aggregateStream<State, EventType extends Event>(\n streamName: string,\n options: AggregateStreamOptions<State, EventType>,\n ): Promise<AggregateStreamResult<State> | null> {\n const { evolve, initialState, read } = options;\n\n const result = await this.readStream<EventType>(streamName, read);\n\n if (!result) return null;\n\n const events = result?.events ?? [];\n\n return {\n currentStreamVersion: BigInt(events.length),\n state: events.reduce(evolve, initialState()),\n };\n },\n\n readStream: <EventType extends Event>(\n streamName: string,\n options?: ReadStreamOptions,\n ): Promise<\n ReadStreamResult<\n EventType,\n DefaultStreamVersionType,\n ReadEventMetadataWithGlobalPosition\n >\n > => {\n const events = streams.get(streamName);\n const currentStreamVersion = events ? BigInt(events.length) : undefined;\n\n assertExpectedVersionMatchesCurrent(\n currentStreamVersion,\n options?.expectedStreamVersion,\n );\n\n const from = Number(options && 'from' in options ? options.from : 0);\n const to = Number(\n options && 'to' in options\n ? options.to\n : options && 'maxCount' in options && options.maxCount\n ? options.from + options.maxCount\n : (events?.length ?? 1),\n );\n\n const resultEvents =\n events && events.length > 0\n ? events\n .map(\n (e) =>\n e as ReadEvent<\n EventType,\n ReadEventMetadataWithGlobalPosition\n >,\n )\n .slice(from, to)\n : [];\n\n const result: ReadStreamResult<\n EventType,\n DefaultStreamVersionType,\n ReadEventMetadataWithGlobalPosition\n > =\n events && events.length > 0\n ? {\n currentStreamVersion: currentStreamVersion!,\n events: resultEvents,\n }\n : null;\n\n return Promise.resolve(result);\n },\n\n appendToStream: <EventType extends Event>(\n streamName: string,\n events: EventType[],\n options?: AppendToStreamOptions,\n ): Promise<AppendToStreamResult> => {\n const currentEvents = streams.get(streamName) ?? [];\n const currentStreamVersion =\n currentEvents.length > 0 ? BigInt(currentEvents.length) : undefined;\n\n assertExpectedVersionMatchesCurrent(\n currentStreamVersion,\n options?.expectedStreamVersion,\n );\n\n const eventEnvelopes: ReadEvent<\n EventType,\n ReadEventMetadataWithGlobalPosition\n >[] = events.map((event, index) => {\n return {\n ...event,\n metadata: {\n ...(event.metadata ?? {}),\n streamName,\n eventId: randomUUID(),\n streamPosition: BigInt(currentEvents.length + index + 1),\n globalPosition: BigInt(getAllEventsCount() + index + 1),\n },\n };\n });\n\n const positionOfLastEventInTheStream = BigInt(\n eventEnvelopes.slice(-1)[0]!.metadata.streamPosition,\n );\n\n streams.set(streamName, [...currentEvents, ...eventEnvelopes]);\n\n const result: AppendToStreamResult = {\n nextExpectedStreamVersion: positionOfLastEventInTheStream,\n };\n\n return Promise.resolve(result);\n },\n };\n};\n","import {\n canCreateEventStoreSession,\n NO_CONCURRENCY_CHECK,\n nulloSessionFactory,\n STREAM_DOES_NOT_EXIST,\n type AppendToStreamResult,\n type DefaultStreamVersionType,\n type EventStore,\n type EventStoreSession,\n type ExpectedStreamVersion,\n} from '../eventStore';\nimport type { Event } from '../typing';\n\n// #region command-handler\nexport type CommandHandlerResult<\n State,\n StreamEvent extends Event,\n StreamVersion = DefaultStreamVersionType,\n> = AppendToStreamResult<StreamVersion> & {\n newState: State;\n newEvents: StreamEvent[];\n};\n\nexport const CommandHandler =\n <State, StreamEvent extends Event, StreamVersion = DefaultStreamVersionType>(\n evolve: (state: State, event: StreamEvent) => State,\n initialState: () => State,\n mapToStreamId: (id: string) => string = (id) => id,\n ) =>\n async <Store extends EventStore<StreamVersion>>(\n store: Store,\n id: string,\n handle: (state: State) => StreamEvent | StreamEvent[],\n options?: Parameters<Store['appendToStream']>[2] & {\n expectedStreamVersion?: ExpectedStreamVersion<StreamVersion>;\n },\n ): Promise<CommandHandlerResult<State, StreamEvent, StreamVersion>> => {\n const result = await withSession<\n Store,\n StreamVersion,\n CommandHandlerResult<State, StreamEvent, StreamVersion>\n >(store, async ({ eventStore }) => {\n const streamName = mapToStreamId(id);\n\n // 1. Aggregate the stream\n const aggregationResult = await eventStore.aggregateStream<\n State,\n StreamEvent\n >(streamName, {\n evolve,\n initialState,\n read: {\n // expected stream version is passed to fail fast\n // if stream is in the wrong state\n expectedStreamVersion:\n options?.expectedStreamVersion ?? NO_CONCURRENCY_CHECK,\n },\n });\n\n // 2. Use the aggregate state or the initial one (when e.g. stream does not exist)\n const state = aggregationResult?.state ?? initialState();\n const currentStreamVersion = aggregationResult?.currentStreamVersion;\n\n // 3. Run business logic\n const result = handle(state);\n\n const newEvents = Array.isArray(result) ? result : [result];\n\n // Either use:\n // - provided expected stream version,\n // - current stream version got from stream aggregation,\n // - or expect stream not to exists otherwise.\n const expectedStreamVersion: ExpectedStreamVersion<StreamVersion> =\n options?.expectedStreamVersion ??\n currentStreamVersion ??\n STREAM_DOES_NOT_EXIST;\n\n // 4. Append result to the stream\n const appendResult = await eventStore.appendToStream(\n streamName,\n newEvents,\n {\n ...options,\n expectedStreamVersion,\n },\n );\n\n // 5. Return result with updated state\n return {\n ...appendResult,\n newEvents,\n newState: newEvents.reduce(evolve, state),\n };\n });\n\n return result;\n };\n// #endregion command-handler\n\nconst withSession = <\n EventStoreType extends EventStore<StreamVersion>,\n StreamVersion = DefaultStreamVersionType,\n T = unknown,\n>(\n eventStore: EventStoreType,\n callback: (\n session: EventStoreSession<EventStoreType, StreamVersion>,\n ) => Promise<T>,\n) => {\n const sessionFactory = canCreateEventStoreSession<\n EventStoreType,\n StreamVersion\n >(eventStore)\n ? eventStore\n : nulloSessionFactory<EventStoreType, StreamVersion>(eventStore);\n\n return sessionFactory.withSession(callback);\n};\n","import type {\n DefaultStreamVersionType,\n EventStore,\n ExpectedStreamVersion,\n} from '../eventStore';\nimport type { Command, Event } from '../typing';\nimport type { Decider } from '../typing/decider';\nimport { CommandHandler } from './handleCommand';\n\n// #region command-handler\nexport const DeciderCommandHandler =\n <\n State,\n CommandType extends Command,\n StreamEvent extends Event,\n StreamVersion = DefaultStreamVersionType,\n >(\n { decide, evolve, initialState }: Decider<State, CommandType, StreamEvent>,\n mapToStreamId: (id: string) => string = (id) => id,\n ) =>\n async (\n eventStore: EventStore<StreamVersion>,\n id: string,\n command: CommandType,\n options?: {\n expectedStreamVersion?: ExpectedStreamVersion<StreamVersion>;\n },\n ) =>\n CommandHandler<State, StreamEvent, StreamVersion>(\n evolve,\n initialState,\n mapToStreamId,\n )(eventStore, id, (state) => decide(command, state), options);\n// #endregion command-handler\n","import type { DefaultRecord, Flavour } from './';\nexport type Command<\n CommandType extends string = string,\n CommandData extends DefaultRecord = DefaultRecord,\n CommandMetaData extends DefaultRecord = DefaultCommandMetadata,\n> = Flavour<\n Readonly<{\n type: CommandType;\n data: Readonly<CommandData>;\n metadata?: CommandMetaData | undefined;\n }>,\n 'Command'\n>;\n\nexport type CommandTypeOf<T extends Command> = T['type'];\nexport type CommandDataOf<T extends Command> = T['data'];\nexport type CommandMetaDataOf<T extends Command> = T['metadata'];\n\nexport type CreateCommandType<\n CommandType extends string,\n CommandData extends DefaultRecord,\n CommandMetaData extends DefaultRecord | undefined,\n> = Readonly<{\n type: CommandType;\n data: CommandData;\n metadata?: CommandMetaData;\n}>;\n\nexport const command = <CommandType extends Command>(\n type: CommandTypeOf<CommandType>,\n data: CommandDataOf<CommandType>,\n metadata?: CommandMetaDataOf<CommandType>,\n): CreateCommandType<\n CommandTypeOf<CommandType>,\n CommandDataOf<CommandType>,\n CommandMetaDataOf<CommandType>\n> => {\n return {\n type,\n data,\n metadata,\n };\n};\n\nexport type DefaultCommandMetadata = { now: Date };\n","import type { DefaultRecord, Flavour } from './';\n\nexport type Event<\n EventType extends string = string,\n EventData extends DefaultRecord = DefaultRecord,\n EventMetaData extends DefaultRecord = DefaultRecord,\n> = Flavour<\n Readonly<{\n type: EventType;\n data: EventData;\n metadata?: EventMetaData;\n }>,\n 'Event'\n>;\n\nexport type EventTypeOf<T extends Event> = T['type'];\nexport type EventDataOf<T extends Event> = T['data'];\nexport type EventMetaDataOf<T extends Event> = T['metadata'];\n\nexport type CanHandle<T extends Event> = EventTypeOf<T>[];\n\nexport type CreateEventType<\n EventType extends string,\n EventData extends DefaultRecord,\n EventMetaData extends DefaultRecord | undefined,\n> = Readonly<{\n type: EventType;\n data: EventData;\n metadata?: EventMetaData;\n}>;\n\nexport const event = <EventType extends Event>(\n type: EventTypeOf<EventType>,\n data: EventDataOf<EventType>,\n metadata?: EventMetaDataOf<EventType>,\n): CreateEventType<\n EventTypeOf<EventType>,\n EventDataOf<EventType>,\n EventMetaDataOf<EventType>\n> => {\n return {\n type,\n data,\n metadata,\n };\n};\n\nexport type ReadEvent<\n EventType extends Event = Event,\n EventMetaDataType extends EventMetaDataOf<EventType> &\n ReadEventMetadata = EventMetaDataOf<EventType> & ReadEventMetadata,\n> = CreateEventType<\n EventTypeOf<EventType>,\n EventDataOf<EventType>,\n EventMetaDataType\n> &\n EventType & { metadata: EventMetaDataType };\n\nexport type ReadEventMetadata = Readonly<{\n eventId: string;\n streamPosition: bigint;\n streamName: string;\n}>;\n\nexport type ReadEventMetadataWithGlobalPosition = ReadEventMetadata & {\n globalPosition: bigint;\n};\n","import type { Command } from './command';\nimport type { Event } from './event';\n\n/// Inspired by https://blog.bittacklr.be/the-workflow-pattern.html\n\nexport type Workflow<\n Input extends Event | Command,\n State,\n Output extends Event | Command,\n> = {\n decide: (command: Input, state: State) => WorkflowOutput<Output>[];\n evolve: (currentState: State, event: WorkflowEvent<Output>) => State;\n initialState: () => State;\n};\n\nexport type WorkflowEvent<Output extends Command | Event> = Extract<\n Output,\n { __brand?: 'Event' }\n>;\n\nexport type WorkflowCommand<Output extends Command | Event> = Extract<\n Output,\n { __brand?: 'Command' }\n>;\n\nexport type WorkflowOutput<TOutput extends Command | Event> =\n | { kind: 'Reply'; message: TOutput }\n | { kind: 'Send'; message: WorkflowCommand<TOutput> }\n | { kind: 'Publish'; message: WorkflowEvent<TOutput> }\n | {\n kind: 'Schedule';\n message: TOutput;\n when: { afterInMs: number } | { at: Date };\n }\n | { kind: 'Complete' }\n | { kind: 'Accept' }\n | { kind: 'Ignore'; reason: string }\n | { kind: 'Error'; reason: string };\n\nexport const reply = <TOutput extends Command | Event>(\n message: TOutput,\n): WorkflowOutput<TOutput> => {\n return {\n kind: 'Reply',\n message,\n };\n};\n\nexport const send = <TOutput extends Command | Event>(\n message: WorkflowCommand<TOutput>,\n): WorkflowOutput<TOutput> => {\n return {\n kind: 'Send',\n message,\n };\n};\n\nexport const publish = <TOutput extends Command | Event>(\n message: WorkflowEvent<TOutput>,\n): WorkflowOutput<TOutput> => {\n return {\n kind: 'Publish',\n message,\n };\n};\n\nexport const schedule = <TOutput extends Command | Event>(\n message: TOutput,\n when: { afterInMs: number } | { at: Date },\n): WorkflowOutput<TOutput> => {\n return {\n kind: 'Schedule',\n message,\n when,\n };\n};\n\nexport const complete = <\n TOutput extends Command | Event,\n>(): WorkflowOutput<TOutput> => {\n return {\n kind: 'Complete',\n };\n};\n\nexport const ignore = <TOutput extends Command | Event>(\n reason: string,\n): WorkflowOutput<TOutput> => {\n return {\n kind: 'Ignore',\n reason,\n };\n};\n\nexport const error = <TOutput extends Command | Event>(\n reason: string,\n): WorkflowOutput<TOutput> => {\n return {\n kind: 'Error',\n reason,\n };\n};\n\nexport const accept = <\n TOutput extends Command | Event,\n>(): WorkflowOutput<TOutput> => {\n return { kind: 'Accept' };\n};\n","import { EmmettError } from '../errors';\nimport {\n type Command,\n type CommandTypeOf,\n type Event,\n type EventTypeOf,\n} from '../typing';\n\nexport interface CommandSender {\n send<CommandType extends Command = Command>(\n command: CommandType,\n ): Promise<void>;\n}\n\nexport interface EventsPublisher {\n publish<EventType extends Event = Event>(event: EventType): Promise<void>;\n}\n\nexport type ScheduleOptions = { afterInMs: number } | { at: Date };\n\nexport interface MessageScheduler<CommandOrEvent extends Command | Event> {\n schedule<MessageType extends CommandOrEvent>(\n message: MessageType,\n when?: ScheduleOptions,\n ): void;\n}\n\nexport interface CommandBus extends CommandSender, MessageScheduler<Command> {}\n\nexport interface EventBus extends EventsPublisher, MessageScheduler<Event> {}\n\nexport interface MessageBus extends CommandBus, EventBus {\n schedule<MessageType extends Command | Event>(\n message: MessageType,\n when?: ScheduleOptions,\n ): void;\n}\n\ntype CommandHandler<CommandType extends Command = Command> = (\n command: CommandType,\n) => Promise<void> | void;\n\nexport interface CommandProcessor {\n handle<CommandType extends Command>(\n commandHandler: CommandHandler<CommandType>,\n ...commandTypes: CommandTypeOf<CommandType>[]\n ): void;\n}\n\ntype EventHandler<EventType extends Event = Event> = (\n event: EventType,\n) => Promise<void> | void;\n\nexport interface EventProcessor {\n subscribe<EventType extends Event>(\n eventHandler: EventHandler<EventType>,\n ...eventTypes: EventTypeOf<EventType>[]\n ): void;\n}\n\nexport type ScheduledMessage = {\n message: Event | Command;\n options?: ScheduleOptions;\n};\n\nexport interface ScheduledMessageProcessor {\n dequeue(): ScheduledMessage[];\n}\n\nexport type MessageHandler = CommandHandler | EventHandler;\n\nexport type MessageProcessor = EventProcessor | CommandProcessor;\n\nexport const getInMemoryMessageBus = (): MessageBus &\n EventProcessor &\n CommandProcessor &\n ScheduledMessageProcessor => {\n const allHandlers = new Map<string, MessageHandler[]>();\n let pendingMessages: ScheduledMessage[] = [];\n\n return {\n send: async <CommandType extends Command = Command>(\n command: CommandType,\n ): Promise<void> => {\n const handlers = allHandlers.get(command.type);\n\n if (handlers === undefined || handlers.length === 0)\n throw new EmmettError(\n `No handler registered for command ${command.type}!`,\n );\n\n const commandHandler = handlers[0] as CommandHandler<CommandType>;\n\n await commandHandler(command);\n },\n\n publish: async <EventType extends Event = Event>(\n event: EventType,\n ): Promise<void> => {\n const handlers = allHandlers.get(event.type) ?? [];\n\n for (const handler of handlers) {\n const eventHandler = handler as EventHandler<EventType>;\n\n await eventHandler(event);\n }\n },\n\n schedule: <MessageType extends Command | Event>(\n message: MessageType,\n when?: ScheduleOptions,\n ): void => {\n pendingMessages = [...pendingMessages, { message, options: when }];\n },\n\n handle: <CommandType extends Command>(\n commandHandler: CommandHandler<CommandType>,\n ...commandTypes: CommandTypeOf<CommandType>[]\n ): void => {\n const alreadyRegistered = [...allHandlers.keys()].filter((registered) =>\n commandTypes.includes(registered),\n );\n\n if (alreadyRegistered.length > 0)\n throw new EmmettError(\n `Cannot register handler for commands ${alreadyRegistered.join(', ')} as they're already registered!`,\n );\n for (const commandType of commandTypes) {\n allHandlers.set(commandType, [commandHandler as MessageHandler]);\n }\n },\n\n subscribe<EventType extends Event>(\n eventHandler: EventHandler<EventType>,\n ...eventTypes: EventTypeOf<EventType>[]\n ): void {\n for (const eventType of eventTypes) {\n if (!allHandlers.has(eventType)) allHandlers.set(eventType, []);\n\n allHandlers.set(eventType, [\n ...(allHandlers.get(eventType) ?? []),\n eventHandler as MessageHandler,\n ]);\n }\n },\n\n dequeue: (): ScheduledMessage[] => {\n const pending = pendingMessages;\n pendingMessages = [];\n return pending;\n },\n };\n};\n","import type {\n CanHandle,\n DefaultRecord,\n Event,\n EventMetaDataOf,\n ReadEvent,\n ReadEventMetadata,\n} from '../typing';\n\nexport type ProjectionHandlingType = 'inline' | 'async';\n\nexport type ProjectionHandler<\n EventType extends Event = Event,\n EventMetaDataType extends EventMetaDataOf<EventType> &\n ReadEventMetadata = EventMetaDataOf<EventType> & ReadEventMetadata,\n ProjectionHandlerContext extends DefaultRecord = DefaultRecord,\n> = (\n events: ReadEvent<EventType, EventMetaDataType>[],\n context: ProjectionHandlerContext,\n) => Promise<void> | void;\n\nexport interface ProjectionDefinition<\n ProjectionHandlerContext extends DefaultRecord = DefaultRecord,\n> {\n name?: string;\n canHandle: CanHandle<Event>;\n handle: ProjectionHandler<Event, ReadEventMetadata, ProjectionHandlerContext>;\n}\n\nexport interface TypedProjectionDefinition<\n EventType extends Event = Event,\n EventMetaDataType extends EventMetaDataOf<EventType> &\n ReadEventMetadata = EventMetaDataOf<EventType> & ReadEventMetadata,\n ProjectionHandlerContext extends DefaultRecord = DefaultRecord,\n> {\n name?: string;\n canHandle: CanHandle<EventType>;\n handle: ProjectionHandler<\n EventType,\n EventMetaDataType,\n ProjectionHandlerContext\n >;\n}\n\nexport type ProjectionRegistration<\n HandlingType extends ProjectionHandlingType,\n ProjectionHandlerContext extends DefaultRecord = DefaultRecord,\n> = {\n type: HandlingType;\n projection: ProjectionDefinition<ProjectionHandlerContext>;\n};\n\nexport const projection = <\n EventType extends Event = Event,\n EventMetaDataType extends EventMetaDataOf<EventType> &\n ReadEventMetadata = EventMetaDataOf<EventType> & ReadEventMetadata,\n ProjectionHandlerContext extends DefaultRecord = DefaultRecord,\n ProjectionDefintionType extends TypedProjectionDefinition<\n EventType,\n EventMetaDataType,\n ProjectionHandlerContext\n > = ProjectionDefinition<ProjectionHandlerContext>,\n>(\n definition: ProjectionDefintionType,\n): ProjectionDefintionType => definition;\n\nexport const inlineProjections = <\n ProjectionHandlerContext extends DefaultRecord = DefaultRecord,\n ProjectionDefintionType extends\n ProjectionDefinition<ProjectionHandlerContext> = ProjectionDefinition<ProjectionHandlerContext>,\n>(\n definitions: ProjectionDefintionType[],\n): ProjectionRegistration<'inline', ProjectionHandlerContext>[] =>\n definitions.map((projection) => ({ type: 'inline', projection }));\n\nexport const asyncProjections = <\n ProjectionHandlerContext extends DefaultRecord = DefaultRecord,\n ProjectionDefintionType extends\n ProjectionDefinition<ProjectionHandlerContext> = ProjectionDefinition<ProjectionHandlerContext>,\n>(\n definitions: ProjectionDefintionType[],\n): ProjectionRegistration<'async', ProjectionHandlerContext>[] =>\n definitions.map((projection) => ({ type: 'async', projection }));\n\nexport const projections = {\n inline: inlineProjections,\n async: asyncProjections,\n};\n","export class ParseError extends Error {\n constructor(text: string) {\n super(`Cannot parse! ${text}`);\n }\n}\n\nexport type Mapper<From, To = From> =\n | ((value: unknown) => To)\n | ((value: Partial<From>) => To)\n | ((value: From) => To)\n | ((value: Partial<To>) => To)\n | ((value: To) => To)\n | ((value: Partial<To | From>) => To)\n | ((value: To | From) => To);\n\nexport type MapperArgs<From, To = From> = Partial<From> &\n From &\n Partial<To> &\n To;\n\nexport type ParseOptions<From, To = From> = {\n reviver?: (key: string, value: unknown) => unknown;\n map?: Mapper<From, To>;\n typeCheck?: <To>(value: unknown) => value is To;\n};\n\nexport type StringifyOptions<From, To = From> = {\n map?: Mapper<From, To>;\n};\n\nexport const JSONParser = {\n stringify: <From, To = From>(\n value: From,\n options?: StringifyOptions<From, To>,\n ) => {\n return JSON.stringify(\n options?.map ? options.map(value as MapperArgs<From, To>) : value,\n //TODO: Consider adding support to DateTime and adding specific format to mark that's a bigint\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n (_, v) => (typeof v === 'bigint' ? v.toString() : v),\n );\n },\n parse: <From, To = From>(\n text: string,\n options?: ParseOptions<From, To>,\n ): To | undefined => {\n const parsed: unknown = JSON.parse(text, options?.reviver);\n\n if (options?.typeCheck && !options?.typeCheck<To>(parsed))\n throw new ParseError(text);\n\n return options?.map\n ? options.map(parsed as MapperArgs<From, To>)\n : (parsed as To | undefined);\n },\n};\n","import type { Decoder } from '.';\nimport { concatUint8Arrays } from '../binaryArrays';\n\nexport class BinaryJsonDecoder<Decoded>\n implements Decoder<Uint8Array, Decoded>\n{\n private buffer: Uint8Array[] = [];\n\n addToBuffer(data: Uint8Array): void {\n this.buffer.push(data);\n }\n\n clearBuffer(): void {\n this.buffer = [];\n }\n\n hasCompleteMessage(): boolean {\n const combined = concatUint8Arrays(this.buffer);\n const text = new TextDecoder().decode(combined);\n return text.includes('\\n');\n }\n\n decode(): Decoded | null {\n if (!this.hasCompleteMessage()) {\n return null;\n }\n\n const combined = concatUint8Arrays(this.buffer);\n const text = new TextDecoder().decode(combined);\n const delimiterIndex = text.indexOf('\\n');\n\n if (delimiterIndex === -1) {\n return null;\n }\n\n const jsonString = text.slice(0, delimiterIndex);\n const remaining = new Uint8Array(combined.buffer, delimiterIndex + 1);\n this.buffer = remaining.byteLength > 0 ? [remaining] : [];\n\n return JSON.parse(jsonString) as Decoded;\n }\n}\n","import type { Decoder } from '.';\n\nexport class StringDecoder<Decoded> implements Decoder<string, Decoded> {\n protected buffer: string[] = [];\n\n constructor(private transform: (input: string) => Decoded) {\n this.transform = transform;\n }\n\n addToBuffer(data: string): void {\n this.buffer.push(data);\n }\n\n clearBuffer(): void {\n this.buffer = [];\n }\n\n hasCompleteMessage(): boolean {\n return this.buffer.some((chunk) => chunk.includes('\\n'));\n }\n\n decode(): Decoded | null {\n const completeString = this.buffer.join('');\n\n if (!this.hasCompleteMessage()) {\n if (completeString.trim().length > 0) {\n throw new Error('Unterminated string in JSON at position');\n }\n return null;\n }\n\n const delimiterIndex = completeString.indexOf('\\n');\n const message = completeString.slice(0, delimiterIndex).trim();\n this.buffer = [completeString.slice(delimiterIndex + 1)];\n\n return this.transform(message);\n }\n}\n","import { JSONParser } from '../serialization';\nimport type { DefaultRecord } from '../typing';\nimport { deepEquals } from '../utils';\n\nexport class AssertionError extends Error {\n constructor(message: string) {\n super(message);\n }\n}\nexport const isSubset = (superObj: unknown, subObj: unknown): boolean => {\n const sup = superObj as DefaultRecord;\n const sub = subObj as DefaultRecord;\n\n assertOk(sup);\n assertOk(sub);\n\n return Object.keys(sub).every((ele: string) => {\n if (typeof sub[ele] == 'object') {\n return isSubset(sup[ele], sub[ele]);\n }\n return sub[ele] === sup[ele];\n });\n};\n\nexport const assertFails = (message?: string) => {\n throw new AssertionError(message ?? 'That should not ever happened, right?');\n};\n\nexport const assertThrowsAsync = async <TError extends Error>(\n fun: () => Promise<void>,\n errorCheck?: (error: Error) => boolean,\n): Promise<TError> => {\n try {\n await fun();\n throw new AssertionError(\"Function didn't throw expected error\");\n } catch (error) {\n const typedError = error as TError;\n if (errorCheck) assertTrue(errorCheck(typedError));\n return typedError;\n }\n};\n\nexport const assertThrows = <TError extends Error>(\n fun: () => void,\n errorCheck?: (error: Error) => boolean,\n): TError => {\n try {\n fun();\n throw new AssertionError(\"Function didn't throw expected error\");\n } catch (error) {\n const typedError = error as TError;\n if (errorCheck) assertTrue(errorCheck(typedError));\n return typedError;\n }\n};\nexport const assertMatches = (\n actual: unknown,\n expected: unknown,\n message?: string,\n) => {\n if (!isSubset(actual, expected))\n throw new AssertionError(\n message ??\n `subObj:\\n${JSONParser.stringify(expected)}\\nis not subset of\\n${JSONParser.stringify(actual)}`,\n );\n};\n\nexport const assertDeepEqual = <T = unknown>(\n actual: T,\n expected: T,\n message?: string,\n) => {\n if (!deepEquals(actual, expected))\n throw new AssertionError(\n message ??\n `subObj:\\n${JSONParser.stringify(expected)}\\nis not equal to\\n${JSONParser.stringify(actual)}`,\n );\n};\n\nexport const assertNotDeepEqual = <T = unknown>(\n actual: T,\n expected: T,\n message?: string,\n) => {\n if (deepEquals(actual, expected))\n throw new AssertionError(\n message ??\n `subObj:\\n${JSONParser.stringify(expected)}\\nis equals to\\n${JSONParser.stringify(actual)}`,\n );\n};\n\nexport const assertThat = <T>(item: T) => {\n return {\n isEqualTo: (other: T) => assertTrue(deepEquals(item, other)),\n };\n};\n\nexport function assertFalse(\n condition: boolean,\n message?: string,\n): asserts condition is false {\n if (condition) throw new AssertionError(message ?? `Condition is false`);\n}\n\nexport function assertTrue(\n condition: boolean,\n message?: string,\n): asserts condition is true {\n if (!condition) throw new AssertionError(message ?? `Condition is false`);\n}\n\nexport function assertOk<T>(\n obj: T | null | undefined,\n message?: string,\n): asserts obj is T {\n if (!obj) throw new AssertionError(message ?? `Condition is not truthy`);\n}\n\nexport function assertEqual<T>(\n expected: T | null | undefined,\n actual: T | null | undefined,\n message?: string,\n): void {\n if (expected !== actual)\n throw new AssertionError(\n `${message ?? 'Objects are not equal'}:\\nExpected: ${JSONParser.stringify(expected)}\\nActual:${JSONParser.stringify(actual)}`,\n );\n}\n\nexport function assertNotEqual<T>(\n obj: T | null | undefined,\n other: T | null | undefined,\n message?: string,\n): void {\n if (obj === other)\n throw new AssertionError(\n message ?? `Objects are equal: ${JSONParser.stringify(obj)}`,\n );\n}\n\nexport function assertIsNotNull<T extends object | bigint>(\n result: T | null,\n): asserts result is T {\n assertNotEqual(result, null);\n assertOk(result);\n}\n\nexport function assertIsNull<T extends object>(\n result: T | null,\n): asserts result is null {\n assertEqual(result, null);\n}\n\ntype Call = {\n arguments: unknown[];\n result: unknown;\n target: unknown;\n this: unknown;\n};\n\nexport type ArgumentMatcher = (arg: unknown) => boolean;\n\nexport const argValue =\n <T>(value: T): ArgumentMatcher =>\n (arg) =>\n deepEquals(arg, value);\n\nexport const argMatches =\n <T>(matches: (arg: T) => boolean): ArgumentMatcher =>\n (arg) =>\n matches(arg as T);\n\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nexport type MockedFunction = Function & { mock?: { calls: Call[] } };\n\nexport function verifyThat(fn: MockedFunction) {\n return {\n calledTimes: (times: number) => {\n assertEqual(fn.mock?.calls?.length, times);\n },\n notCalled: () => {\n assertEqual(fn?.mock?.calls?.length, 0);\n },\n called: () => {\n assertTrue(\n fn.mock?.calls.length !== undefined && fn.mock.calls.length > 0,\n );\n },\n calledWith: (...args: unknown[]) => {\n assertTrue(\n fn.mock?.calls.length !== undefined &&\n fn.mock.calls.length >= 1 &&\n fn.mock.calls.some((call) => deepEquals(call.arguments, args)),\n );\n },\n calledOnceWith: (...args: unknown[]) => {\n assertTrue(\n fn.mock?.calls.length !== undefined &&\n fn.mock.calls.length === 1 &&\n fn.mock.calls.some((call) => deepEquals(call.arguments, args)),\n );\n },\n calledWithArgumentMatching: (...matches: ArgumentMatcher[]) => {\n assertTrue(\n fn.mock?.calls.length !== undefined && fn.mock.calls.length >= 1,\n );\n assertTrue(\n fn.mock?.calls.length !== undefined &&\n fn.mock.calls.length >= 1 &&\n fn.mock.calls.some(\n (call) =>\n call.arguments &&\n call.arguments.length >= matches.length &&\n matches.every((match, index) => match(call.arguments[index])),\n ),\n );\n },\n notCalledWithArgumentMatching: (...matches: ArgumentMatcher[]) => {\n assertFalse(\n fn.mock?.calls.length !== undefined &&\n fn.mock.calls.length >= 1 &&\n fn.mock.calls[0]!.arguments &&\n fn.mock.calls[0]!.arguments.length >= matches.length &&\n matches.every((match, index) =>\n match(fn.mock!.calls[0]!.arguments[index]),\n ),\n );\n },\n };\n}\n\nexport const assertThatArray = <T>(array: T[]) => {\n return {\n isEmpty: () => assertEqual(array.length, 0),\n isNotEmpty: () => assertNotEqual(array.length, 0),\n hasSize: (length: number) => assertEqual(array.length, length),\n containsElements: (...other: T[]) => {\n assertTrue(other.every((ts) => other.some((o) => deepEquals(ts, o))));\n },\n containsExactlyInAnyOrder: (...other: T[]) => {\n assertEqual(array.length, other.length);\n assertTrue(array.every((ts) => other.some((o) => deepEquals(ts, o))));\n },\n containsExactlyInAnyOrderElementsOf: (other: T[]) => {\n assertEqual(array.length, other.length);\n assertTrue(array.every((ts) => other.some((o) => deepEquals(ts, o))));\n },\n containsExactlyElementsOf: (other: T[]) => {\n assertEqual(array.length, other.length);\n for (let i = 0; i < array.length; i++) {\n assertTrue(deepEquals(array[i], other[i]));\n }\n },\n containsExactly: (elem: T) => {\n assertEqual(array.length, 1);\n assertTrue(deepEquals(array[0], elem));\n },\n contains: (elem: T) => {\n assertTrue(array.some((a) => deepEquals(a, elem)));\n },\n containsOnlyOnceElementsOf: (other: T[]) => {\n assertTrue(\n other\n .map((o) => array.filter((a) => deepEquals(a, o)).length)\n .filter((a) => a === 1).length === other.length,\n );\n },\n containsAnyOf: (...other: T[]) => {\n assertTrue(array.some((a) => other.some((o) => deepEquals(a, o))));\n },\n allMatch: (matches: (item: T) => boolean) => {\n assertTrue(array.every(matches));\n },\n anyMatches: (matches: (item: T) => boolean) => {\n assertTrue(array.some(matches));\n },\n allMatchAsync: async (\n matches: (item: T) => Promise<boolean>,\n ): Promise<void> => {\n for (const item of array) {\n assertTrue(await matches(item));\n }\n },\n };\n};\n","import type {\n AggregateStreamOptions,\n AggregateStreamResult,\n AppendToStreamOptions,\n AppendToStreamResult,\n DefaultStreamVersionType,\n EventStore,\n ReadStreamOptions,\n ReadStreamResult,\n} from '../eventStore';\nimport { type Event } from '../typing';\n\nexport type TestEventStream<EventType extends Event = Event> = [\n string,\n EventType[],\n];\n\nexport const WrapEventStore = <StreamVersion = DefaultStreamVersionType>(\n eventStore: EventStore<StreamVersion>,\n): EventStore<StreamVersion> & {\n appendedEvents: Map<string, TestEventStream>;\n setup<EventType extends Event>(\n streamName: string,\n events: EventType[],\n ): Promise<AppendToStreamResult<StreamVersion>>;\n} => {\n const appendedEvents = new Map<string, TestEventStream>();\n\n return {\n async aggregateStream<State, EventType extends Event>(\n streamName: string,\n options: AggregateStreamOptions<State, EventType, StreamVersion>,\n ): Promise<AggregateStreamResult<State, StreamVersion> | null> {\n return eventStore.aggregateStream(streamName, options);\n },\n\n readStream<EventType extends Event>(\n streamName: string,\n options?: ReadStreamOptions<StreamVersion>,\n ): Promise<ReadStreamResult<EventType, StreamVersion>> {\n return eventStore.readStream(streamName, options);\n },\n\n appendToStream: async <EventType extends Event>(\n streamName: string,\n events: EventType[],\n options?: AppendToStreamOptions<StreamVersion>,\n ): Promise<AppendToStreamResult<StreamVersion>> => {\n const result = await eventStore.appendToStream(\n streamName,\n events,\n options,\n );\n\n const currentStream = appendedEvents.get(streamName) ?? [streamName, []];\n\n appendedEvents.set(streamName, [\n streamName,\n [...currentStream[1], ...events],\n ]);\n\n return result;\n },\n\n appendedEvents,\n\n setup: async <EventType extends Event>(\n streamName: string,\n events: EventType[],\n ): Promise<AppendToStreamResult<StreamVersion>> => {\n return eventStore.appendToStream(streamName, events);\n },\n };\n};\n"]}
@@ -1,5 +1,5 @@
1
- import { C as ConcurrencyError, E as ErrorConstructor } from './index-D9zse73H.mjs';
2
- export { f as EmmettCliPlugin, d as EmmettCliPluginRegistration, j as EmmettError, g as EmmettPlugin, b as EmmettPluginConfig, e as EmmettPluginRegistration, c as EmmettPluginType, a as EmmettPluginsConfig, I as IllegalStateError, N as NotFoundError, V as ValidationError, h as isErrorConstructor, i as isPluginConfig } from './index-D9zse73H.mjs';
1
+ import { C as ConcurrencyError, E as ErrorConstructor } from './index-D9zse73H.cjs';
2
+ export { f as EmmettCliPlugin, d as EmmettCliPluginRegistration, j as EmmettError, g as EmmettPlugin, b as EmmettPluginConfig, e as EmmettPluginRegistration, c as EmmettPluginType, a as EmmettPluginsConfig, I as IllegalStateError, N as NotFoundError, V as ValidationError, h as isErrorConstructor, i as isPluginConfig } from './index-D9zse73H.cjs';
3
3
  import { ReadableStream } from 'web-streams-polyfill';
4
4
  import retry from 'async-retry';
5
5
  import 'commander';