@event-driven-io/emmett 0.20.0-alpha.9 → 0.20.0

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,EACA,2BA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AAgBC,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,CAAgB,uBA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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"]}
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');var _fs = require('fs');var _process = require('process');var s=(e=["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
4
  plugins: ${e.length>0?`[
5
5
  ${e.map(t=>`"${t}"`).join(`,
6
6
  `)}
7
7
  ]`:"[]"},
8
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:
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`),_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.
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
13
  ${s()}`,missingPluginsPropertyExport:`Error: Config should contain default export with plugins array, e.g.
14
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, _chunk6TXKRKDJjs.k)(m.missingPluginsPropertyExport):t.default.plugins.every(_chunk6TXKRKDJjs.p)?{plugins:t.default.plugins}:new (0, _chunk6TXKRKDJjs.k)(m.wrongPluginStructure):new (0, _chunk6TXKRKDJjs.k)(m.missingDefaultExport)}catch(t){return _optionalChain([e, 'optionalAccess', _2 => _2.configPath])?new (0, _chunk6TXKRKDJjs.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 _chunk6TXKRKDJjs.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;
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","writeFileSync"],"mappings":"AAAA;AACA,ylCAA8C,sCCAtB,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.js","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
+ {"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,EACAC,IACS,CACT,GAAI,CACFP,EAAcM,EAAYJ,EAAaK,CAAe,EAAG,MAAM,EAC/D,QAAQ,IAAI,iCAAiCD,CAAU,EAAE,CAC3D,OAASE,EAAO,CACd,QAAQ,MAAM,sCAAsCF,CAAU,GAAG,EACjE,QAAQ,MAAME,CAAK,EACnB,QAAQ,KAAK,CAAC,C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qBF,EAAO,IAAI,EAAE,EAC9CI,EAAO,KAAKJ,CAAM,CACpB,CACF,EAEMJ,EAAsB,CAC1BO,EACAG,IAEAH,EAAQ,OACLI,GACC,OAAOA,GAAM,UACZD,IACEC,EAAE,WAAa,QACdA,EAAE,SAAS,KAAMC,GAAMA,EAAE,aAAeF,CAAU,EAC1D,EAEIP,EAAgB,CACpBF,EACAS,IACG,CACH,GAAI,OAAOT,GAAiB,SAC1B,OAAOS,EAAa,GAAGT,CAAY,IAAIS,CAAU,GAAKT,EAGxD,IAAMY,EACJZ,EAAa,SAAS,KAAMW,GAAMF,GAAcE,EAAE,aAAeF,CAAU,GACvE,MAAQA,EAEd,OAAOG,EACH,GAAGZ,EAAa,IAAI,IAAIY,CAAa,GACrCZ,EAAa,IACnB,EFpJA,IAAMa,EAAU,IAAIC,EAEpBD,EACG,KAAK,QAAQ,EACb,YAAY,qBAAqB,EACjC,OAAO,kBAAmB,gCAAgC,EAG7D,IAAME,EAAU,SAAY,CAC1B,IAAMC,EAAc,QAAQ,KAAK,QAAQ,UAAU,EAE7CC,EACJD,IAAgB,IAAM,QAAQ,KAAK,OAASA,EAAc,EACtD,QAAQ,KAAKA,EAAc,CAAC,EAC5B,OAEN,GAAI,CACF,IAAME,EAAU,MAAMC,EAAY,CAChC,WAAY,MACZ,WAAYF,CACd,CAAC,EACD,MAAMG,EAAmBP,EAASK,CAAO,EAGzCL,EAAQ,MAAM,QAAQ,IAAI,CAC5B,OAASQ,EAAK,CACZ,QAAQ,MAAM,8BAA8BJ,CAAU,IAAKI,CAAG,CAChE,CACF,EAGAN,EAAQ,EAAE,MAAOM,GAAQ,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 _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 _class; var _class2; var _class3; var _class4; var _class5; var _class6;var _chunkCJZAVRMTcjs = require('./chunk-CJZAVRMT.cjs');var L=t=>"withSession"in t,Y= exports.nulloSessionFactory =t=>({withSession:e=>e({eventStore:t,close:()=>Promise.resolve()})});var ot=(t,e,r)=>({type:t,data:e,metadata:r});var z=(t,e,r)=>({type:t,data:e,metadata:r});var it=t=>({kind:"Reply",message:t}),mt= exports.send =t=>({kind:"Send",message:t}),dt= exports.publish =t=>({kind:"Publish",message:t}),pt= exports.schedule =(t,e)=>({kind:"Schedule",message:t,when:e}),lt= exports.complete =()=>({kind:"Complete"}),ct= exports.ignore =t=>({kind:"Ignore",reason:t}),ut= exports.error =t=>({kind:"Error",reason:t}),ft= exports.accept =()=>({kind:"Accept"});var F="__emt:GlobalStreamCaughtUp",Q= exports.isGlobalStreamCaughtUp =t=>t.type===F,Ct= exports.caughtUpEventFrom =t=>e=>e.type===F&&_optionalChain([e, 'access', _2 => _2.metadata, 'optionalAccess', _3 => _3.globalPosition])>=t,N= exports.globalStreamCaughtUp =t=>z(F,t,{globalPosition:t.globalPosition}),Rt= exports.isSubscriptionEvent =t=>Q(t),bt= exports.isNotInternalEvent =t=>!Q(t);var he="STREAM_EXISTS",W= exports.STREAM_DOES_NOT_EXIST ="STREAM_DOES_NOT_EXIST",O= exports.NO_CONCURRENCY_CHECK ="NO_CONCURRENCY_CHECK",Ce= exports.matchesExpectedVersion =(t,e,r)=>e===O?!0:e==W?t===r:e==he?t!==r:t===e,_= exports.assertExpectedVersionMatchesCurrent =(t,e,r)=>{if(e??=O,!Ce(t,e,r))throw new D(t,e)},D= exports.ExpectedVersionConflictError =class t extends _chunkCJZAVRMTcjs.l{constructor(e,r){super(_optionalChain([e, 'optionalAccess', _4 => _4.toString, 'call', _5 => _5()]),_optionalChain([r, 'optionalAccess', _6 => _6.toString, 'call', _7 => _7()])),Object.setPrototypeOf(this,t.prototype)}},Z= exports.isExpectedVersionConflictError =t=>t instanceof D;var _uuid = require('uuid');var _webstreamspolyfill = require('web-streams-polyfill');var Oe={ReadableStream:_webstreamspolyfill.ReadableStream,WritableStream:_webstreamspolyfill.WritableStream,TransformStream:_webstreamspolyfill.TransformStream};var Vt=typeof process<"u"&&process.versions!=null&&process.versions.bun!=null,w;if(globalThis&&globalThis.WritableStream&&globalThis.ReadableStream&&globalThis.TransformStream)w=globalThis;else try{w=await Promise.resolve().then(() => _interopRequireWildcard(require("stream/web")))}catch (e2){w=Oe}var s=w;var ee=t=>new G(t),G= exports.CaughtUpTransformStream =class extends s.TransformStream{constructor(e){super({start:r=>{let n=0n;for(let o of e)r.enqueue(o),n=o.metadata.globalPosition;r.enqueue(N({globalPosition:n}))},transform:(r,n)=>{this._currentPosition=r.metadata.globalPosition,n.enqueue(r),!(this._currentPosition<this._logPosition)&&n.enqueue(N({globalPosition:this._currentPosition}))}}),this._currentPosition=this._logPosition=e.length>0?e[e.length-1].metadata.globalPosition:0n}set logPosition(e){this._logPosition=e}};var M=(t,e={})=>new E(t,e),E= (_class =class extends s.TransformStream{constructor(r,n={}){super({cancel:o=>{console.log("Stream was canceled. Reason:",o),this.stopChecking()}});_class.prototype.__init.call(this);_class.prototype.__init2.call(this);;this.onNoActiveReaderCallback=r;this.streamId=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _8 => _8.streamId]), () => (_uuid.v4.call(void 0, ))),this.onNoActiveReaderCallback=r,this.startChecking(_nullishCoalesce(_optionalChain([n, 'optionalAccess', _9 => _9.intervalCheckInMs]), () => (20)))}__init() {this.checkInterval=null}__init2() {this._isStopped=!1}get hasActiveSubscribers(){return!this._isStopped}startChecking(r){this.checkInterval=setInterval(()=>{this.checkNoActiveReader()},r)}stopChecking(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null,this._isStopped=!0,this.onNoActiveReaderCallback(this))}checkNoActiveReader(){!this.readable.locked&&!this._isStopped&&this.stopChecking()}}, _class);var te=async(t,e)=>{if(t.writable.locked)return!1;let r=t.writable.getWriter();if(await r.ready,!t.readable.locked)return!1;try{for(let n of e)await r.write(n)}catch(n){console.log(n)}finally{await r.close()}return!0};var re=()=>{let t=[],e=new Map;return{notify:async r=>{if(r.length!==0){t.push(...r);for(let n of e.values())n.logPosition=r[r.length-1].metadata.globalPosition,await te(n,r)}},stream:()=>{let r=_uuid.v4.call(void 0, ),n=ee(t);return e.set(r,n),n.readable.pipeThrough(M(o=>{e.has(o.streamId)&&e.delete(o.streamId)},{streamId:r}))}}};var x=0n,or= exports.getInMemoryEventStore =()=>{let t=new Map,e=re(),r=()=>Array.from(t.values()).map(n=>n.length).reduce((n,o)=>n+o,0);return{async aggregateStream(n,o){let{evolve:a,initialState:m,read:d}=o,c=await this.readStream(n,d),v=_nullishCoalesce(_optionalChain([c, 'optionalAccess', _10 => _10.events]), () => ([]));return{currentStreamVersion:BigInt(v.length),state:v.reduce(a,m()),streamExists:c.streamExists}},readStream:(n,o)=>{let a=t.get(n),m=a?BigInt(a.length):x;_(m,_optionalChain([o, 'optionalAccess', _11 => _11.expectedStreamVersion]),x);let d=Number(o&&"from"in o?o.from:0),c=Number(o&&"to"in o?o.to:o&&"maxCount"in o&&o.maxCount?o.from+o.maxCount:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _12 => _12.length]), () => (1))),v=a!==void 0&&a.length>0?a.map(y=>y).slice(d,c):[],T={currentStreamVersion:m,events:v,streamExists:a!==void 0&&a.length>0};return Promise.resolve(T)},appendToStream:async(n,o,a)=>{let m=_nullishCoalesce(t.get(n), () => ([])),d=m.length>0?BigInt(m.length):x;_(d,_optionalChain([a, 'optionalAccess', _13 => _13.expectedStreamVersion]),x);let c=o.map((y,S)=>({...y,metadata:{..._nullishCoalesce(y.metadata, () => ({})),streamName:n,eventId:_uuid.v4.call(void 0, ),streamPosition:BigInt(m.length+S+1),globalPosition:BigInt(r()+S+1)}})),v=BigInt(c.slice(-1)[0].metadata.streamPosition);return t.set(n,[...m,...c]),await e.notify(c),{nextExpectedStreamVersion:v,createdNewStream:d===x}}}};var p=(t,e)=>{if(Pe(t))return t.equals(e);if(Array.isArray(t))return Array.isArray(e)&&t.length===e.length&&t.every((o,a)=>p(o,e[a]));if(typeof t!="object"||typeof e!="object"||t===null||e===null)return t===e;if(Array.isArray(e))return!1;let r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length||!r.every(o=>n.includes(o)))return!1;for(let o in t){if(t[o]instanceof Function&&e[o]instanceof Function)continue;if(!p(t[o],e[o]))return!1}return!0},Pe= exports.isEquatable =t=>t&&typeof t=="object"&&"equals"in t&&typeof t.equals=="function";var ur=t=>{let e,r,n=0;do({value:e,done:r}=t.next()),n+=e||0;while(!r);return n};var yr=(t,e,r,n,o=()=>{})=>{let a=!1,m=t.map(d=>r(d)?(a=!0,n(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]:m};var _asyncretry = require('async-retry'); var _asyncretry2 = _interopRequireDefault(_asyncretry);var ne={retries:0},V= exports.asyncRetry =async(t,e)=>e===void 0||e.retries===0?t():_asyncretry2.default.call(void 0, async r=>{try{return await t()}catch(n){throw _optionalChain([e, 'optionalAccess', _14 => _14.shouldRetryError])&&!e.shouldRetryError(n)&&r(n),n}},_nullishCoalesce(e, () => ({retries:0})));var oe={retries:3,minTimeout:100,factor:1.5,shouldRetryError:Z},Ae=t=>t===void 0?ne:"onVersionConflict"in t?typeof t.onVersionConflict=="boolean"?oe:typeof t.onVersionConflict=="number"?{...oe,retries:t.onVersionConflict}:t.onVersionConflict:t,ae= exports.CommandHandler =t=>async(e,r,n,o)=>V(async()=>await Ie(e,async({eventStore:m})=>{let{evolve:d,initialState:c}=t,T=(_nullishCoalesce(t.mapToStreamId, () => ((ge=>ge))))(r),y=await m.aggregateStream(T,{evolve:d,initialState:c,read:{expectedStreamVersion:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _15 => _15.expectedStreamVersion]), () => (O))}}),S=y.state,J=y.currentStreamVersion,H=await n(S),b=Array.isArray(H)?H:[H];if(b.length===0)return{newEvents:[],newState:S,nextExpectedStreamVersion:J,createdNewStream:!1};let xe=_nullishCoalesce(_optionalChain([o, 'optionalAccess', _16 => _16.expectedStreamVersion]), () => ((y.streamExists?J:W)));return{...await m.appendToStream(T,b,{...o,expectedStreamVersion:xe}),newEvents:b,newState:b.reduce(d,S)}}),Ae(o&&"retry"in o?o.retry:t.retry)),Ie=(t,e)=>(L(t)?t:Y(t)).withSession(e);var wr=t=>async(e,r,n,o)=>{let{decide:a,...m}=t;return ae(m)(e,r,d=>a(n,d),o)};var Hr=()=>{let t=new Map,e=[];return{send:async r=>{let n=t.get(r.type);if(n===void 0||n.length===0)throw new (0, _chunkCJZAVRMTcjs.k)(`No handler registered for command ${r.type}!`);let o=n[0];await o(r)},publish:async r=>{let n=_nullishCoalesce(t.get(r.type), () => ([]));for(let o of n)await o(r)},schedule:(r,n)=>{e=[...e,{message:r,options:n}]},handle:(r,...n)=>{let o=[...t.keys()].filter(a=>n.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 n)t.set(a,[r])},subscribe(r,...n){for(let o of n)t.has(o)||t.set(o,[]),t.set(o,[..._nullishCoalesce(t.get(o), () => ([])),r])},dequeue:()=>{let r=e;return e=[],r}}};var Fr=t=>t,He= exports.inlineProjections =t=>t.map(e=>({type:"inline",projection:e})),je= exports.asyncProjections =t=>t.map(e=>({type:"async",projection:e})),Nr= exports.projections ={inline:He,async:je};var q=class extends Error{constructor(e){super(`Cannot parse! ${e}`)}},u= exports.JSONParser ={stringify:(t,e)=>JSON.stringify(_optionalChain([e, 'optionalAccess', _17 => _17.map])?e.map(t):t,(r,n)=>typeof n=="bigint"?n.toString():n),parse:(t,e)=>{let r=JSON.parse(t,_optionalChain([e, 'optionalAccess', _18 => _18.reviver]));if(_optionalChain([e, 'optionalAccess', _19 => _19.typeCheck])&&!_optionalChain([e, 'optionalAccess', _20 => _20.typeCheck, 'call', _21 => _21(r)]))throw new q(t);return _optionalChain([e, 'optionalAccess', _22 => _22.map])?e.map(r):r}};var B=t=>{let e=t.reduce((o,a)=>o+a.length,0),r=new Uint8Array(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r};var Jr=async t=>{let e=[];for await(let r of t)e.push(r);return e};var P= (_class2 =class{constructor() { _class2.prototype.__init3.call(this); }__init3() {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),r=new TextDecoder().decode(e),n=r.indexOf(`
3
+ `);if(n===-1)return null;let o=r.slice(0,n),a=new Uint8Array(e.buffer,n+1);return this.buffer=a.byteLength>0?[a]:[],JSON.parse(o)}}, _class2);var k= (_class3 =class{constructor(e){;_class3.prototype.__init4.call(this);this.transform=e;this.transform=e}__init4() {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 r=e.indexOf(`
5
+ `),n=e.slice(0,r).trim();return this.buffer=[e.slice(r+1)],this.transform(n)}}, _class3);var A=class extends k{constructor(){super(e=>JSON.parse(e))}};var I= (_class4 =class{constructor() { _class4.prototype.__init5.call(this); }__init5() {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}}, _class4);var U=class{constructor(e){this.decoders=e}decoderFor(e){let r=this.decoders.find(n=>n[0](e));return r?r[1]:null}addToBuffer(e){_optionalChain([this, 'access', _23 => _23.decoderFor, 'call', _24 => _24(e), 'optionalAccess', _25 => _25.addToBuffer, 'call', _26 => _26(e)])}clearBuffer(){for(let e of this.decoders.map(r=>r[1]))e.clearBuffer()}hasCompleteMessage(){return this.decoders.some(e=>e[1].hasCompleteMessage())}decode(){return _nullishCoalesce(_optionalChain([this, 'access', _27 => _27.decoders, 'access', _28 => _28.map, 'call', _29 => _29(r=>r[1]), 'access', _30 => _30.find, 'call', _31 => _31(r=>r.hasCompleteMessage()), 'optionalAccess', _32 => _32.decode, 'call', _33 => _33()]), () => (null))}},g= exports.DefaultDecoder =class extends U{constructor(){super([[e=>typeof e=="string",new A],[e=>e instanceof Uint8Array,new P],[e=>typeof e=="object",new I]])}};var se=t=>new s.ReadableStream({start(e){for(let r of t)e.enqueue(r);e.close()}});var fn={fromArray:se};var ie=t=>new s.TransformStream({transform(e,r){t(e)&&r.enqueue(e)}});var me=t=>new s.TransformStream({transform(e,r){r.enqueue(t(e))}});var de=(t,e)=>new h(t,e),h=class extends s.TransformStream{constructor(e,r){super({transform:n=>{this.accumulator=this.reducer(this.accumulator,n)},flush:n=>{n.enqueue(this.accumulator),n.terminate()}}),this.accumulator=r,this.reducer=e}};var pe=(t,e,r={forever:!0,minTimeout:25})=>new s.TransformStream({start(n){V(()=>Fe(t,e,n),r).catch(o=>{n.error(o)})}}),Fe=async(t,e,r)=>{let o=t().getReader();try{let a;do{let m=await o.read();a=m.done,await e(m,r),a&&r.terminate()}while(!a)}finally{o.releaseLock()}};var le=t=>new C(t),C= (_class5 =class extends s.TransformStream{__init6() {this.count=0}constructor(e){super({transform:(r,n)=>{this.count++,this.count>this.skip&&n.enqueue(r)}});_class5.prototype.__init6.call(this);,this.skip=e}}, _class5);var ce=t=>new s.TransformStream({transform(e,r){r.enqueue(e),t(e)&&r.terminate()}});var ue=t=>new s.TransformStream({async transform(e,r){if(!t(e)){r.enqueue(e);return}await Promise.resolve(),r.terminate()}});var fe=t=>new R(t),R= (_class6 =class extends s.TransformStream{__init7() {this.count=0}constructor(e){super({transform:(r,n)=>{this.count<this.limit?(this.count++,n.enqueue(r)):n.terminate()}});_class6.prototype.__init7.call(this);,this.limit=e}}, _class6);var ye=t=>new s.TransformStream({start(e){let r=setTimeout(()=>{e.terminate()},t),n=e.terminate.bind(e);e.terminate=()=>{clearTimeout(r),n()}},transform(e,r){r.enqueue(e)}});var ve={filter:ie,take:fe,TakeTransformStream:R,skip:le,SkipTransformStream:C,map:me,notifyAboutNoActiveReadersStream:M,NotifyAboutNoActiveReadersStream:E,reduce:de,ReduceTransformStream:h,retry:pe,stopAfter:ce,stopOn:ue,waitAtMost:ye};var{retry:Ne}=ve,Ln= exports.restream =(t,e=o=>o,r={forever:!0,minTimeout:25},n=new g)=>Ne(t,We(e,n),r).readable,We=(t=r=>r,e=new g)=>(r,n)=>{let{done:o,value:a}=r;a&&e.addToBuffer(a),!(!o&&!e.hasCompleteMessage())&&_e(e,t,n)},_e=(t,e,r)=>{try{let n=t.decode();if(!n)return;let o=e(n);r.enqueue(o)}catch(n){r.error(new Error(`Decoding error: ${_optionalChain([n, 'optionalAccess', _34 => _34.toString, 'call', _35 => _35()])}`))}};var l=class extends Error{constructor(e){super(e)}},Se= exports.isSubset =(t,e)=>{let r=t,n=e;return $(r),$(n),Object.keys(n).every(o=>typeof n[o]=="object"?Se(r[o],n[o]):n[o]===r[o])},so= exports.assertFails =t=>{throw new l(_nullishCoalesce(t, () => ("That should not ever happened, right?")))},io= exports.assertThrowsAsync =async(t,e)=>{try{throw await t(),new l("Function didn't throw expected error")}catch(r){let n=r;return e&&i(e(n)),n}},mo= exports.assertThrows =(t,e)=>{try{throw t(),new l("Function didn't throw expected error")}catch(r){let n=r;return e&&i(e(n)),n}},po= exports.assertRejects =async(t,e)=>{try{throw await t,new l("Function didn't throw expected error")}catch(r){if(!e)return;e instanceof Error?Ge(r,e):i(e(r))}},Te= exports.assertMatches =(t,e,r)=>{if(!Se(t,e))throw new l(_nullishCoalesce(r, () => (`subObj:
6
+ ${u.stringify(e)}
7
+ is not subset of
8
+ ${u.stringify(t)}`)))},Ge= exports.assertDeepEqual =(t,e,r)=>{if(!p(t,e))throw new l(_nullishCoalesce(r, () => (`subObj:
9
+ ${u.stringify(e)}
10
+ is not equal to
11
+ ${u.stringify(t)}`)))},lo= exports.assertNotDeepEqual =(t,e,r)=>{if(p(t,e))throw new l(_nullishCoalesce(r, () => (`subObj:
12
+ ${u.stringify(e)}
13
+ is equals to
14
+ ${u.stringify(t)}`)))},co= exports.assertThat =t=>({isEqualTo:e=>i(p(t,e))});function qe(t,e){if(t)throw new l(_nullishCoalesce(e, () => ("Condition is false")))}function i(t,e){if(!t)throw new l(_nullishCoalesce(e, () => ("Condition is false")))}function $(t,e){if(!t)throw new l(_nullishCoalesce(e, () => ("Condition is not truthy")))}function f(t,e,r){if(t!==e)throw new l(`${_nullishCoalesce(r, () => ("Objects are not equal"))}:
15
+ Expected: ${u.stringify(t)}
16
+ Actual:${u.stringify(e)}`)}function Ee(t,e,r){if(t===e)throw new l(_nullishCoalesce(r, () => (`Objects are equal: ${u.stringify(t)}`)))}function uo(t){Ee(t,null),$(t)}function fo(t){f(t,null)}var yo=t=>e=>p(e,t),vo= exports.argMatches =t=>e=>t(e);function So(t){return{calledTimes:e=>{f(_optionalChain([t, 'access', _36 => _36.mock, 'optionalAccess', _37 => _37.calls, 'optionalAccess', _38 => _38.length]),e)},notCalled:()=>{f(_optionalChain([t, 'optionalAccess', _39 => _39.mock, 'optionalAccess', _40 => _40.calls, 'optionalAccess', _41 => _41.length]),0)},called:()=>{i(_optionalChain([t, 'access', _42 => _42.mock, 'optionalAccess', _43 => _43.calls, 'access', _44 => _44.length])!==void 0&&t.mock.calls.length>0)},calledWith:(...e)=>{i(_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(r=>p(r.arguments,e)))},calledOnceWith:(...e)=>{i(_optionalChain([t, 'access', _48 => _48.mock, 'optionalAccess', _49 => _49.calls, 'access', _50 => _50.length])!==void 0&&t.mock.calls.length===1&&t.mock.calls.some(r=>p(r.arguments,e)))},calledWithArgumentMatching:(...e)=>{i(_optionalChain([t, 'access', _51 => _51.mock, 'optionalAccess', _52 => _52.calls, 'access', _53 => _53.length])!==void 0&&t.mock.calls.length>=1),i(_optionalChain([t, 'access', _54 => _54.mock, 'optionalAccess', _55 => _55.calls, 'access', _56 => _56.length])!==void 0&&t.mock.calls.length>=1&&t.mock.calls.some(r=>r.arguments&&r.arguments.length>=e.length&&e.every((n,o)=>n(r.arguments[o]))))},notCalledWithArgumentMatching:(...e)=>{qe(_optionalChain([t, 'access', _57 => _57.mock, 'optionalAccess', _58 => _58.calls, 'access', _59 => _59.length])!==void 0&&t.mock.calls.length>=1&&t.mock.calls[0].arguments&&t.mock.calls[0].arguments.length>=e.length&&e.every((r,n)=>r(t.mock.calls[0].arguments[n])))}}}var To=t=>({isEmpty:()=>f(t.length,0),isNotEmpty:()=>Ee(t.length,0),hasSize:e=>f(t.length,e),containsElements:(...e)=>{i(e.every(r=>e.some(n=>p(r,n))))},containsExactlyInAnyOrder:(...e)=>{f(t.length,e.length),i(t.every(r=>e.some(n=>p(r,n))))},containsExactlyInAnyOrderElementsOf:e=>{f(t.length,e.length),i(t.every(r=>e.some(n=>p(r,n))))},containsExactlyElementsOf:e=>{f(t.length,e.length);for(let r=0;r<t.length;r++)i(p(t[r],e[r]))},containsExactly:e=>{f(t.length,1),i(p(t[0],e))},contains:e=>{i(t.some(r=>p(r,e)))},containsOnlyOnceElementsOf:e=>{i(e.map(r=>t.filter(n=>p(n,r)).length).filter(r=>r===1).length===e.length)},containsAnyOf:(...e)=>{i(t.some(r=>e.some(n=>p(r,n))))},allMatch:e=>{i(t.every(e))},anyMatches:e=>{i(t.some(e))},allMatchAsync:async e=>{for(let r of t)i(await e(r))}});var ho={for:t=>e=>({when:r=>{let n=()=>{let a=(Array.isArray(e)?e:[e]).reduce(t.evolve,t.initialState());return t.decide(r,a)};return{then:o=>{let a=n(),m=Array.isArray(a)?a:[a],d=Array.isArray(o)?o:[o];Te(m,d)},thenThrows:(...o)=>{try{throw n(),new l("Handler did not fail as expected")}catch(a){if(a instanceof l)throw a;if(o.length===0)return;if(!_chunkCJZAVRMTcjs.j.call(void 0, o[0])){i(o[0](a),`Error didn't match the error condition: ${_optionalChain([a, 'optionalAccess', _60 => _60.toString, 'call', _61 => _61()])}`);return}i(a instanceof o[0],`Caught error is not an instance of the expected type: ${_optionalChain([a, 'optionalAccess', _62 => _62.toString, 'call', _63 => _63()])}`),o[1]&&i(o[1](a),`Error didn't match the error condition: ${_optionalChain([a, 'optionalAccess', _64 => _64.toString, 'call', _65 => _65()])}`)}}}}})};var bo=t=>{let e=new Map;return{async aggregateStream(r,n){return t.aggregateStream(r,n)},readStream(r,n){return t.readStream(r,n)},appendToStream:async(r,n,o)=>{let a=await t.appendToStream(r,n,o),m=_nullishCoalesce(e.get(r), () => ([r,[]]));return e.set(r,[r,[...m[1],...n]]),a},appendedEvents:e,setup:async(r,n)=>t.appendToStream(r,n)}};exports.AssertionError = l; exports.BinaryJsonDecoder = P; exports.CaughtUpTransformStream = G; exports.CommandHandler = ae; exports.CommandHandlerStreamVersionConflictRetryOptions = oe; exports.CompositeDecoder = U; exports.ConcurrencyError = _chunkCJZAVRMTcjs.l; exports.DeciderCommandHandler = wr; exports.DeciderSpecification = ho; exports.DefaultDecoder = g; exports.EmmettError = _chunkCJZAVRMTcjs.k; exports.ExpectedVersionConflictError = D; exports.GlobalStreamCaughtUpType = F; exports.IllegalStateError = _chunkCJZAVRMTcjs.n; exports.InMemoryEventStoreDefaultStreamVersion = x; exports.JSONParser = u; exports.JsonDecoder = A; exports.NO_CONCURRENCY_CHECK = O; exports.NoRetries = ne; exports.NotFoundError = _chunkCJZAVRMTcjs.o; exports.ObjectDecoder = I; exports.ParseError = q; exports.STREAM_DOES_NOT_EXIST = W; exports.STREAM_EXISTS = he; exports.StreamingCoordinator = re; exports.StringDecoder = k; exports.ValidationError = _chunkCJZAVRMTcjs.m; exports.ValidationErrors = _chunkCJZAVRMTcjs.d; exports.WrapEventStore = bo; exports.accept = ft; exports.argMatches = vo; exports.argValue = yo; exports.assertDeepEqual = Ge; exports.assertEqual = f; exports.assertExpectedVersionMatchesCurrent = _; exports.assertFails = so; exports.assertFalse = qe; exports.assertIsNotNull = uo; exports.assertIsNull = fo; exports.assertMatches = Te; exports.assertNotDeepEqual = lo; exports.assertNotEmptyString = _chunkCJZAVRMTcjs.g; exports.assertNotEqual = Ee; exports.assertOk = $; exports.assertPositiveNumber = _chunkCJZAVRMTcjs.h; exports.assertRejects = po; exports.assertThat = co; exports.assertThatArray = To; exports.assertThrows = mo; exports.assertThrowsAsync = io; exports.assertTrue = i; exports.assertUnsignedBigInt = _chunkCJZAVRMTcjs.i; exports.asyncProjections = je; exports.asyncRetry = V; exports.canCreateEventStoreSession = L; exports.caughtUpEventFrom = Ct; exports.collect = Jr; exports.command = ot; exports.complete = lt; exports.concatUint8Arrays = B; exports.deepEquals = p; exports.error = ut; exports.event = z; exports.formatDateToUtcYYYYMMDD = _chunkCJZAVRMTcjs.a; exports.getInMemoryEventStore = or; exports.getInMemoryMessageBus = Hr; exports.globalStreamCaughtUp = N; exports.ignore = ct; exports.inlineProjections = He; exports.isEquatable = Pe; exports.isErrorConstructor = _chunkCJZAVRMTcjs.j; exports.isExpectedVersionConflictError = Z; exports.isGlobalStreamCaughtUp = Q; exports.isNotInternalEvent = bt; exports.isNumber = _chunkCJZAVRMTcjs.e; exports.isPluginConfig = _chunkCJZAVRMTcjs.p; exports.isString = _chunkCJZAVRMTcjs.f; exports.isSubscriptionEvent = Rt; exports.isSubset = Se; exports.isValidYYYYMMDD = _chunkCJZAVRMTcjs.b; exports.matchesExpectedVersion = Ce; exports.merge = yr; exports.nulloSessionFactory = Y; exports.parseDateFromUtcYYYYMMDD = _chunkCJZAVRMTcjs.c; exports.projection = Fr; exports.projections = Nr; exports.publish = dt; exports.reply = it; exports.restream = Ln; exports.schedule = pt; exports.send = mt; exports.streamGenerators = fn; exports.streamTrackingGlobalPosition = ee; exports.streamTransformations = ve; exports.sum = ur; exports.verifyThat = So;
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/typing/command.ts","../src/typing/event.ts","../src/typing/workflow.ts","../src/eventStore/events/index.ts","../src/eventStore/expectedVersion.ts","../src/eventStore/inMemoryEventStore.ts","../../emmett-shims/src/index.ts","../src/eventStore/subscriptions/caughtUpTransformStream.ts","../src/eventStore/subscriptions/streamingCoordinator.ts","../src/streaming/transformations/notifyAboutNoActiveReaders.ts","../src/streaming/writers/writeToStream.ts","../src/utils/deepEquals.ts","../src/utils/iterators.ts","../src/utils/merge.ts","../src/utils/retry.ts","../src/commandHandling/handleCommand.ts","../src/commandHandling/handleCommandWithDecider.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","command","type","data","metadata","event","reply","message","send","publish","schedule","when","complete","ignore","reason","error","accept","GlobalStreamCaughtUpType","isGlobalStreamCaughtUp","caughtUpEventFrom","position","globalStreamCaughtUp","isSubscriptionEvent","isNotInternalEvent","STREAM_EXISTS","STREAM_DOES_NOT_EXIST","NO_CONCURRENCY_CHECK","matchesExpectedVersion","current","expected","defaultVersion","assertExpectedVersionMatchesCurrent","ExpectedVersionConflictError","_ExpectedVersionConflictError","ConcurrencyError","isExpectedVersionConflictError","streamsPolyfill","ReadableStream","WritableStream","TransformStream","isBun","streams","src_default","streamTrackingGlobalPosition","currentEvents","CaughtUpTransformStream","m","events","controller","globalPosition","value","notifyAboutNoActiveReadersStream","onNoActiveReaderCallback","options","NotifyAboutNoActiveReadersStream","uuid","interval","writeToStream","stream","items","writer","item","StreamingCoordinator","allEvents","listeners","listener","streamId","transformStream","InMemoryEventStoreDefaultStreamVersion","getInMemoryEventStore","streamingCoordinator","getAllEventsCount","s","p","c","streamName","evolve","initialState","read","result","currentStreamVersion","from","to","resultEvents","e","newEvents","index","positionOfLastEventInTheStream","deepEquals","left","right","isEquatable","val","keys1","keys2","key","sum","iterator","done","merge","array","where","onExisting","onNotFound","wasFound","NoRetries","asyncRetry","fn","opts","retry","bail","CommandHandlerStreamVersionConflictRetryOptions","fromCommandHandlerRetryOptions","retryOptions","CommandHandler","store","id","handle","handleOptions","withSession","aggregationResult","state","expectedStreamVersion","DeciderCommandHandler","decide","rest","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,wqCAA8J,IC0DjJA,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,CCpDO,IAAMG,EAAAA,CAAU,CACrBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAAAA,EAAAA,CAMO,CACL,IAAA,CAAAF,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CACF,CAAA,CAAA,CCVK,IAAMC,CAAAA,CAAQ,CACnBH,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAAAA,EAAAA,CAMO,CACL,IAAA,CAAAF,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CACF,CAAA,CAAA,CCLK,IAAME,EAAAA,CACXC,CAAAA,EAAAA,CAEO,CACL,IAAA,CAAM,OAAA,CACN,OAAA,CAAAA,CACF,CAAA,CAAA,CAGWC,EAAAA,gBACXD,CAAAA,EAAAA,CAEO,CACL,IAAA,CAAM,MAAA,CACN,OAAA,CAAAA,CACF,CAAA,CAAA,CAGWE,EAAAA,mBACXF,CAAAA,EAAAA,CAEO,CACL,IAAA,CAAM,SAAA,CACN,OAAA,CAAAA,CACF,CAAA,CAAA,CAGWG,EAAAA,oBAAW,CACtBH,CAAAA,CACAI,CAAAA,CAAAA,EAAAA,CAEO,CACL,IAAA,CAAM,UAAA,CACN,OAAA,CAAAJ,CAAAA,CACA,IAAA,CAAAI,CACF,CAAA,CAAA,CAGWC,EAAAA,oBAAW,CAAA,CAAA,EAAA,CAGf,CACL,IAAA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,CAEA,OAAA,CAAS,CAAA,CAAA,EAA0B,CACjC,IAAMG,CAAAA,CAAUZ,CAAAA,CAChB,OAAAA,CAAAA,CAAkB,CAAC,CAAA,CACZY,CACT,CACF,CACF,CAAA,CCpGO,IAAMC,EAAAA,CAWXC,CAAAA,EAC4BA,CAAAA,CAEjBC,EAAAA,6BAKXC,CAAAA,EAEAA,CAAAA,CAAY,GAAA,CAAKH,CAAAA,EAAAA,CAAgB,CAAE,IAAA,CAAM,QAAA,CAAU,UAAA,CAAAA,CAAW,CAAA,CAAE,CAAA,CAErDI,EAAAA,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,EAAAA,CACR,KAAA,CAAOE,EACT,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;ACiD1C;AAA0C;AAAA;AAY1C;AAA0C;AAAA;AAY1C;AAA0C;AAAA;AAsCP;AAA8C,UAAA;ACzDzF,OAAA","file":"/home/runner/work/emmett/emmett/src/packages/emmett/dist/index.cjs","sourcesContent":[null,"//import type { ReadableStream } from '@event-driven-io/emmett-shims';\nimport type { Event, ReadEvent, ReadEventMetadata } from '../typing';\n//import type { GlobalSubscriptionEvent } from './events';\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>>;\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 // streamEvents(): ReadableStream<\n // ReadEvent<Event, ReadEventMetadataType> | GlobalSubscriptionEvent\n // >;\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 streamExists: boolean;\n};\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 streamExists: boolean;\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 createdNewStream: boolean;\n};\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 {\n event,\n type Event,\n type EventDataOf,\n type ReadEvent,\n type ReadEventMetadataWithGlobalPosition,\n} from '../../typing';\n\nexport const GlobalStreamCaughtUpType = '__emt:GlobalStreamCaughtUp';\n\nexport type GlobalStreamCaughtUp = Event<\n '__emt:GlobalStreamCaughtUp',\n { globalPosition: bigint },\n { globalPosition: bigint }\n>;\n\nexport const isGlobalStreamCaughtUp = (\n event: Event,\n): event is GlobalStreamCaughtUp => event.type === GlobalStreamCaughtUpType;\n\nexport const caughtUpEventFrom =\n (position: bigint) =>\n (\n event: ReadEvent<Event, ReadEventMetadataWithGlobalPosition>,\n ): event is ReadEvent<\n GlobalStreamCaughtUp,\n ReadEventMetadataWithGlobalPosition\n > =>\n event.type === GlobalStreamCaughtUpType &&\n event.metadata?.globalPosition >= position;\n\nexport const globalStreamCaughtUp = (\n data: EventDataOf<GlobalStreamCaughtUp>,\n): GlobalStreamCaughtUp =>\n event<GlobalStreamCaughtUp>(GlobalStreamCaughtUpType, data, {\n globalPosition: data.globalPosition,\n });\n\nexport const isSubscriptionEvent = (\n event: Event,\n): event is GlobalSubscriptionEvent => isGlobalStreamCaughtUp(event);\n\nexport const isNotInternalEvent = (event: Event): boolean =>\n !isGlobalStreamCaughtUp(event);\n\nexport type GlobalSubscriptionEvent = GlobalStreamCaughtUp;\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 defaultVersion: StreamVersion,\n): boolean => {\n if (expected === NO_CONCURRENCY_CHECK) return true;\n\n if (expected == STREAM_DOES_NOT_EXIST) return current === defaultVersion;\n\n if (expected == STREAM_EXISTS) return current !== defaultVersion;\n\n return current === expected;\n};\n\nexport const assertExpectedVersionMatchesCurrent = <\n StreamVersion = DefaultStreamVersionType,\n>(\n current: StreamVersion,\n expected: ExpectedStreamVersion<StreamVersion> | undefined,\n defaultVersion: StreamVersion,\n): void => {\n expected ??= NO_CONCURRENCY_CHECK;\n\n if (!matchesExpectedVersion(current, expected, defaultVersion))\n throw new ExpectedVersionConflictError(current, expected);\n};\n\nexport class ExpectedVersionConflictError<\n VersionType = DefaultStreamVersionType,\n> extends ConcurrencyError {\n constructor(\n current: VersionType,\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\nexport const isExpectedVersionConflictError = (\n error: unknown,\n): error is ExpectedVersionConflictError =>\n error instanceof ExpectedVersionConflictError;\n","import { v4 as uuid } 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';\nimport { StreamingCoordinator } from './subscriptions';\n\nexport type EventHandler<E extends Event = Event> = (\n eventEnvelope: ReadEvent<E>,\n) => void;\n\nexport const InMemoryEventStoreDefaultStreamVersion = 0n;\n\nexport const getInMemoryEventStore = (): EventStore<\n DefaultStreamVersionType,\n ReadEventMetadataWithGlobalPosition\n> => {\n const streams = new Map<\n string,\n ReadEvent<Event, ReadEventMetadataWithGlobalPosition>[]\n >();\n const streamingCoordinator = StreamingCoordinator();\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>> {\n const { evolve, initialState, read } = options;\n\n const result = await this.readStream<EventType>(streamName, read);\n\n const events = result?.events ?? [];\n\n return {\n currentStreamVersion: BigInt(events.length),\n state: events.reduce(evolve, initialState()),\n streamExists: result.streamExists,\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\n ? BigInt(events.length)\n : InMemoryEventStoreDefaultStreamVersion;\n\n assertExpectedVersionMatchesCurrent(\n currentStreamVersion,\n options?.expectedStreamVersion,\n InMemoryEventStoreDefaultStreamVersion,\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 !== undefined && 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 currentStreamVersion,\n events: resultEvents,\n streamExists: events !== undefined && events.length > 0,\n };\n\n return Promise.resolve(result);\n },\n\n appendToStream: async <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\n ? BigInt(currentEvents.length)\n : InMemoryEventStoreDefaultStreamVersion;\n\n assertExpectedVersionMatchesCurrent(\n currentStreamVersion,\n options?.expectedStreamVersion,\n InMemoryEventStoreDefaultStreamVersion,\n );\n\n const newEvents: ReadEvent<\n EventType,\n ReadEventMetadataWithGlobalPosition\n >[] = events.map((event, index) => {\n return {\n ...event,\n metadata: {\n ...(event.metadata ?? {}),\n streamName,\n eventId: uuid(),\n streamPosition: BigInt(currentEvents.length + index + 1),\n globalPosition: BigInt(getAllEventsCount() + index + 1),\n },\n };\n });\n\n const positionOfLastEventInTheStream = BigInt(\n newEvents.slice(-1)[0]!.metadata.streamPosition,\n );\n\n streams.set(streamName, [...currentEvents, ...newEvents]);\n await streamingCoordinator.notify(newEvents);\n\n const result: AppendToStreamResult = {\n nextExpectedStreamVersion: positionOfLastEventInTheStream,\n createdNewStream:\n currentStreamVersion === InMemoryEventStoreDefaultStreamVersion,\n };\n\n return result;\n },\n\n //streamEvents: streamingCoordinator.stream,\n };\n};\n","import {\n ReadableStream,\n TransformStream,\n WritableStream,\n} from 'web-streams-polyfill';\n\nconst streamsPolyfill = { ReadableStream, WritableStream, TransformStream };\n\n// https://github.com/jsdom/jsdom/issues/1537#issuecomment-229405327\n\nconst isJsDom = (): boolean => {\n // @ts-expect-error global object check\n const globalWindow = window as { name: string };\n // @ts-expect-error global object check\n const globalNavigator = navigator as { userAgent: string };\n\n return (\n (typeof globalWindow !== 'undefined' && globalWindow.name === 'nodejs') ||\n (typeof globalNavigator !== 'undefined' &&\n 'userAgent' in globalNavigator &&\n typeof globalNavigator.userAgent === 'string' &&\n (globalNavigator.userAgent.includes('Node.js') ||\n globalNavigator.userAgent.includes('jsdom')))\n );\n};\n\nconst isDeno = (): boolean => {\n // @ts-expect-error global object check\n const globalDeno = Deno as { version: { deno: unknown } };\n\n return (\n typeof globalDeno !== 'undefined' &&\n typeof globalDeno.version !== 'undefined' &&\n typeof globalDeno.version.deno !== 'undefined'\n );\n};\n\nconst isBun =\n typeof process !== 'undefined' &&\n process.versions != null &&\n process.versions.bun != null;\n\nexport { isBrowser, isBun, isDeno, isJsDom, isNode, isWebWorker };\n\nlet streams: typeof streamsPolyfill;\n\nif (\n globalThis &&\n globalThis.WritableStream &&\n globalThis.ReadableStream &&\n globalThis.TransformStream\n) {\n streams = globalThis as typeof streamsPolyfill;\n} else {\n try {\n streams = (await import('node:stream/web')) as typeof streamsPolyfill;\n } catch {\n // Just falling back to the default polyfill\n streams = streamsPolyfill;\n }\n}\n\nexport default streams;\n\n// Use a type-only import/export to re-export all types\nexport type * from 'web-streams-polyfill';\n\nconst isBrowser = (): boolean => {\n // @ts-expect-error global object check\n const globalWindow = window as { document: unknown };\n\n return (\n typeof globalWindow !== 'undefined' &&\n typeof globalWindow.document !== 'undefined'\n );\n};\n\nconst isNode = (): boolean =>\n typeof process !== 'undefined' &&\n process.versions != null &&\n process.versions.node != null;\n\nconst isWebWorker = (): boolean => {\n // @ts-expect-error global object check\n const globalSelf = self as { constructor: { name: unknown } | undefined };\n\n return (\n typeof globalSelf === 'object' &&\n !!globalSelf.constructor &&\n globalSelf.constructor.name === 'DedicatedWorkerGlobalScope'\n );\n};\n","import streams from '@event-driven-io/emmett-shims';\nimport type {\n Event,\n ReadEvent,\n ReadEventMetadataWithGlobalPosition,\n} from '../../typing';\nimport { globalStreamCaughtUp, type GlobalSubscriptionEvent } from '../events';\n\nexport const streamTrackingGlobalPosition = (\n currentEvents: ReadEvent<Event, ReadEventMetadataWithGlobalPosition>[],\n) => new CaughtUpTransformStream(currentEvents);\n\nexport class CaughtUpTransformStream extends streams.TransformStream<\n ReadEvent<Event, ReadEventMetadataWithGlobalPosition>,\n | ReadEvent<Event, ReadEventMetadataWithGlobalPosition>\n | GlobalSubscriptionEvent\n> {\n private _currentPosition: bigint;\n private _logPosition: bigint;\n\n constructor(events: ReadEvent<Event, ReadEventMetadataWithGlobalPosition>[]) {\n super({\n start: (controller) => {\n let globalPosition = 0n;\n for (const event of events) {\n controller.enqueue(event);\n globalPosition = event.metadata.globalPosition;\n }\n controller.enqueue(globalStreamCaughtUp({ globalPosition }));\n },\n transform: (event, controller) => {\n this._currentPosition = event.metadata.globalPosition;\n controller.enqueue(event);\n\n if (this._currentPosition < this._logPosition) return;\n\n controller.enqueue(\n globalStreamCaughtUp({ globalPosition: this._currentPosition }),\n );\n },\n });\n\n this._currentPosition = this._logPosition =\n events.length > 0\n ? events[events.length - 1]!.metadata.globalPosition\n : 0n;\n }\n\n public set logPosition(value: bigint) {\n this._logPosition = value;\n }\n}\n","import { v4 as uuid } from 'uuid';\nimport { notifyAboutNoActiveReadersStream } from '../../streaming/transformations/notifyAboutNoActiveReaders';\nimport { writeToStream } from '../../streaming/writers';\nimport type {\n Event,\n ReadEvent,\n ReadEventMetadataWithGlobalPosition,\n} from '../../typing';\nimport {\n CaughtUpTransformStream,\n streamTrackingGlobalPosition,\n} from './caughtUpTransformStream';\n\nexport const StreamingCoordinator = () => {\n const allEvents: ReadEvent<Event, ReadEventMetadataWithGlobalPosition>[] = [];\n const listeners = new Map<string, CaughtUpTransformStream>();\n\n return {\n notify: async (\n events: ReadEvent<Event, ReadEventMetadataWithGlobalPosition>[],\n ) => {\n if (events.length === 0) return;\n\n allEvents.push(...events);\n\n for (const listener of listeners.values()) {\n listener.logPosition =\n events[events.length - 1]!.metadata.globalPosition;\n\n await writeToStream(listener, events);\n }\n },\n\n stream: () => {\n const streamId = uuid();\n const transformStream = streamTrackingGlobalPosition(allEvents);\n\n listeners.set(streamId, transformStream);\n return transformStream.readable.pipeThrough(\n notifyAboutNoActiveReadersStream(\n (stream) => {\n if (listeners.has(stream.streamId))\n listeners.delete(stream.streamId);\n },\n { streamId },\n ),\n );\n },\n };\n};\n","import streams from '@event-driven-io/emmett-shims';\nimport { v4 as uuid } from 'uuid';\n\nexport const notifyAboutNoActiveReadersStream = <Item>(\n onNoActiveReaderCallback: (\n stream: NotifyAboutNoActiveReadersStream<Item>,\n ) => void,\n options: { streamId?: string; intervalCheckInMs?: number } = {},\n) => new NotifyAboutNoActiveReadersStream(onNoActiveReaderCallback, options);\n\nexport class NotifyAboutNoActiveReadersStream<\n Item,\n> extends streams.TransformStream<Item, Item> {\n private checkInterval: NodeJS.Timeout | null = null;\n public readonly streamId: string;\n private _isStopped: boolean = false;\n public get hasActiveSubscribers() {\n return !this._isStopped;\n }\n\n constructor(\n private onNoActiveReaderCallback: (\n stream: NotifyAboutNoActiveReadersStream<Item>,\n ) => void,\n options: { streamId?: string; intervalCheckInMs?: number } = {},\n ) {\n super({\n cancel: (reason) => {\n console.log('Stream was canceled. Reason:', reason);\n this.stopChecking();\n },\n });\n this.streamId = options?.streamId ?? uuid();\n\n this.onNoActiveReaderCallback = onNoActiveReaderCallback;\n\n this.startChecking(options?.intervalCheckInMs ?? 20);\n }\n\n private startChecking(interval: number) {\n this.checkInterval = setInterval(() => {\n this.checkNoActiveReader();\n }, interval);\n }\n\n private stopChecking() {\n if (!this.checkInterval) return;\n\n clearInterval(this.checkInterval);\n this.checkInterval = null;\n this._isStopped = true;\n this.onNoActiveReaderCallback(this);\n }\n\n private checkNoActiveReader() {\n if (!this.readable.locked && !this._isStopped) {\n this.stopChecking();\n }\n }\n}\n","import type {\n ReadableStream,\n TransformStream,\n} from '@event-driven-io/emmett-shims';\nimport { noMoreWritingOn } from './noMoreWritingOn';\n\nexport const writeToStream = async <In, Out = In>(\n stream: TransformStream<In, Out>,\n items: In[],\n): Promise<boolean> => {\n if (stream.writable.locked) return false;\n\n const writer = stream.writable.getWriter();\n await writer.ready;\n\n if (!stream.readable.locked) return false;\n\n try {\n for (const item of items) {\n await writer.write(item);\n }\n } catch (error) {\n console.log(error);\n } finally {\n await writer.close();\n }\n return true;\n};\n\nexport const writeToStreamAndStop = async <In, Out>(\n stream: TransformStream<In, Out>,\n items: In[],\n): Promise<ReadableStream<Out>> => {\n await writeToStream(stream, items);\n return await noMoreWritingOn(stream);\n};\n","export const deepEquals = <T>(left: T, right: T): boolean => {\n if (isEquatable(left)) {\n return left.equals(right);\n }\n\n if (Array.isArray(left)) {\n return (\n Array.isArray(right) &&\n left.length === right.length &&\n left.every((val, index) => deepEquals(val, right[index]))\n );\n }\n\n if (\n typeof left !== 'object' ||\n typeof right !== 'object' ||\n left === null ||\n right === null\n ) {\n return left === right;\n }\n\n if (Array.isArray(right)) return false;\n\n const keys1 = Object.keys(left);\n const keys2 = Object.keys(right);\n\n if (\n keys1.length !== keys2.length ||\n !keys1.every((key) => keys2.includes(key))\n )\n return false;\n\n for (const key in left) {\n if (left[key] instanceof Function && right[key] instanceof Function)\n continue;\n\n const isEqual = deepEquals(left[key], right[key]);\n if (!isEqual) {\n return false;\n }\n }\n\n return true;\n};\n\nexport type Equatable<T> = { equals: (right: T) => boolean } & T;\n\nexport const isEquatable = <T>(left: T): left is Equatable<T> => {\n return (\n left &&\n typeof left === 'object' &&\n 'equals' in left &&\n typeof left['equals'] === 'function'\n );\n};\n","export const sum = (\n iterator: Iterator<number, number, number> | Iterator<number>,\n) => {\n let value,\n done: boolean | undefined,\n sum = 0;\n do {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n ({ value, done } = iterator.next());\n sum += value || 0;\n } while (!done);\n return sum;\n};\n","export const merge = <T>(\n array: T[],\n item: T,\n where: (current: T) => boolean,\n onExisting: (current: T) => T,\n onNotFound: () => T | undefined = () => undefined,\n) => {\n let wasFound = false;\n\n const result = array\n // merge the existing item if matches condition\n .map((p: T) => {\n if (!where(p)) return p;\n\n wasFound = true;\n return onExisting(p);\n })\n // filter out item if undefined was returned\n // for cases of removal\n .filter((p) => p !== undefined)\n // make TypeScript happy\n .map((p) => {\n if (!p) throw Error('That should not happen');\n\n return p;\n });\n\n // if item was not found and onNotFound action is defined\n // try to generate new item\n if (!wasFound) {\n const result = onNotFound();\n\n if (result !== undefined) return [...array, item];\n }\n\n return result;\n};\n","import retry from 'async-retry';\n\nexport type AsyncRetryOptions = retry.Options & {\n shouldRetryError?: (error: unknown) => boolean;\n};\n\nexport const NoRetries: AsyncRetryOptions = { retries: 0 };\n\nexport const asyncRetry = async <T>(\n fn: () => Promise<T>,\n opts?: AsyncRetryOptions,\n): Promise<T> => {\n if (opts === undefined || opts.retries === 0) return fn();\n\n return retry(\n async (bail) => {\n try {\n return await fn();\n } catch (error) {\n if (opts?.shouldRetryError && !opts.shouldRetryError(error)) {\n bail(error as Error);\n }\n throw error;\n }\n },\n opts ?? { retries: 0 },\n );\n};\n","import {\n canCreateEventStoreSession,\n isExpectedVersionConflictError,\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';\nimport { asyncRetry, NoRetries, type AsyncRetryOptions } from '../utils';\n\nexport const CommandHandlerStreamVersionConflictRetryOptions: AsyncRetryOptions =\n {\n retries: 3,\n minTimeout: 100,\n factor: 1.5,\n shouldRetryError: isExpectedVersionConflictError,\n };\n\nexport type CommandHandlerRetryOptions =\n | AsyncRetryOptions\n | { onVersionConflict: true | number | AsyncRetryOptions };\n\nconst fromCommandHandlerRetryOptions = (\n retryOptions: CommandHandlerRetryOptions | undefined,\n): AsyncRetryOptions => {\n if (retryOptions === undefined) return NoRetries;\n\n if ('onVersionConflict' in retryOptions) {\n if (typeof retryOptions.onVersionConflict === 'boolean')\n return CommandHandlerStreamVersionConflictRetryOptions;\n else if (typeof retryOptions.onVersionConflict === 'number')\n return {\n ...CommandHandlerStreamVersionConflictRetryOptions,\n retries: retryOptions.onVersionConflict,\n };\n else return retryOptions.onVersionConflict;\n }\n\n return retryOptions;\n};\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 type CommandHandlerOptions<State, StreamEvent extends Event> = {\n evolve: (state: State, event: StreamEvent) => State;\n initialState: () => State;\n mapToStreamId?: (id: string) => string;\n retry?: CommandHandlerRetryOptions;\n};\n\nexport type HandleOptions<\n StreamVersion,\n Store extends EventStore<StreamVersion>,\n> = Parameters<Store['appendToStream']>[2] &\n (\n | {\n expectedStreamVersion?: ExpectedStreamVersion<StreamVersion>;\n }\n | {\n retry?: CommandHandlerRetryOptions;\n }\n );\n\nexport const CommandHandler =\n <State, StreamEvent extends Event, StreamVersion = DefaultStreamVersionType>(\n options: CommandHandlerOptions<State, StreamEvent>,\n ) =>\n async <Store extends EventStore<StreamVersion>>(\n store: Store,\n id: string,\n handle: (\n state: State,\n ) =>\n | StreamEvent\n | StreamEvent[]\n | Promise<StreamEvent>\n | Promise<StreamEvent[]>,\n handleOptions?: HandleOptions<StreamVersion, EventStore<StreamVersion>>,\n ): Promise<CommandHandlerResult<State, StreamEvent, StreamVersion>> =>\n asyncRetry(\n async () => {\n const result = await withSession<\n Store,\n StreamVersion,\n CommandHandlerResult<State, StreamEvent, StreamVersion>\n >(store, async ({ eventStore }) => {\n const { evolve, initialState } = options;\n const mapToStreamId = options.mapToStreamId ?? ((id) => id);\n\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 handleOptions?.expectedStreamVersion ?? NO_CONCURRENCY_CHECK,\n },\n });\n\n // 2. Use the aggregate state\n const state = aggregationResult.state;\n const currentStreamVersion = aggregationResult.currentStreamVersion;\n\n // 3. Run business logic\n const result = await handle(state);\n\n const newEvents = Array.isArray(result) ? result : [result];\n\n if (newEvents.length === 0) {\n return {\n newEvents: [],\n newState: state,\n nextExpectedStreamVersion: currentStreamVersion,\n createdNewStream: false,\n };\n }\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 handleOptions?.expectedStreamVersion ??\n (aggregationResult.streamExists\n ? (currentStreamVersion as ExpectedStreamVersion<StreamVersion>)\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 ...handleOptions,\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 fromCommandHandlerRetryOptions(\n handleOptions && 'retry' in handleOptions\n ? handleOptions.retry\n : options.retry,\n ),\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 { DefaultStreamVersionType, EventStore } from '../eventStore';\nimport type { Command, Event } from '../typing';\nimport type { Decider } from '../typing/decider';\nimport {\n CommandHandler,\n type CommandHandlerOptions,\n type HandleOptions,\n} from './handleCommand';\n\n// #region command-handler\n\nexport type DeciderCommandHandlerOptions<\n State,\n CommandType extends Command,\n StreamEvent extends Event,\n> = CommandHandlerOptions<State, StreamEvent> &\n Decider<State, CommandType, StreamEvent>;\n\nexport const DeciderCommandHandler =\n <\n State,\n CommandType extends Command,\n StreamEvent extends Event,\n StreamVersion = DefaultStreamVersionType,\n >(\n options: DeciderCommandHandlerOptions<State, CommandType, StreamEvent>,\n ) =>\n async (\n eventStore: EventStore<StreamVersion>,\n id: string,\n command: CommandType,\n handleOptions?: HandleOptions<StreamVersion, EventStore<StreamVersion>>,\n ) => {\n const { decide, ...rest } = options;\n\n return CommandHandler<State, StreamEvent, StreamVersion>(rest)(\n eventStore,\n id,\n (state) => decide(command, state),\n handleOptions,\n );\n };\n// #endregion command-handler\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}\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};\n\nexport const assertRejects = async <T, TError extends Error = Error>(\n promise: Promise<T>,\n errorCheck?: ((error: TError) => boolean) | TError,\n) => {\n try {\n await promise;\n throw new AssertionError(\"Function didn't throw expected error\");\n } catch (error) {\n if (!errorCheck) return;\n\n if (errorCheck instanceof Error) assertDeepEqual(error, errorCheck);\n else assertTrue(errorCheck(error as TError));\n }\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, type ReadEventMetadata } from '../typing';\n\nexport type TestEventStream<EventType extends Event = Event> = [\n string,\n EventType[],\n];\n\nexport const WrapEventStore = <\n StreamVersion = DefaultStreamVersionType,\n ReadEventMetadataType extends ReadEventMetadata = ReadEventMetadata,\n>(\n eventStore: EventStore<StreamVersion, ReadEventMetadataType>,\n): EventStore<StreamVersion, ReadEventMetadataType> & {\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>> {\n return eventStore.aggregateStream(streamName, options);\n },\n\n readStream<EventType extends Event>(\n streamName: string,\n options?: ReadStreamOptions<StreamVersion>,\n ): Promise<\n ReadStreamResult<EventType, StreamVersion, ReadEventMetadataType>\n > {\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 // streamEvents: (): ReadableStream<\n // // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n // ReadEvent<Event, ReadEventMetadataType> | GlobalSubscriptionEvent\n // > => {\n // return eventStore.streamEvents();\n // },\n };\n};\n"]}