arkos 2.0.0-next.26 → 2.0.0-next.28

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.
Files changed (35) hide show
  1. package/cli.js +1 -8
  2. package/dist/esm/components/arkos-gateway/arkos-gateway.js +9 -2
  3. package/dist/esm/components/arkos-gateway/arkos-gateway.js.map +1 -1
  4. package/dist/esm/components/arkos-gateway/socket-extensions.js +26 -18
  5. package/dist/esm/components/arkos-gateway/socket-extensions.js.map +1 -1
  6. package/dist/esm/components/arkos-gateway/types.js.map +1 -1
  7. package/dist/esm/modules/email/email.service.js +4 -2
  8. package/dist/esm/modules/email/email.service.js.map +1 -1
  9. package/dist/esm/utils/cli/build.js +2 -3
  10. package/dist/esm/utils/cli/build.js.map +1 -1
  11. package/dist/esm/utils/cli/dev.js +2 -4
  12. package/dist/esm/utils/cli/dev.js.map +1 -1
  13. package/dist/esm/utils/cli/export-auth-action.js +2 -3
  14. package/dist/esm/utils/cli/export-auth-action.js.map +1 -1
  15. package/dist/esm/utils/cli/index.js +13 -0
  16. package/dist/esm/utils/cli/index.js.map +1 -1
  17. package/dist/esm/utils/cli/prisma-generate.js +43 -2
  18. package/dist/esm/utils/cli/prisma-generate.js.map +1 -1
  19. package/dist/esm/utils/cli/start.js +2 -4
  20. package/dist/esm/utils/cli/start.js.map +1 -1
  21. package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
  22. package/dist/esm/utils/cli/utils/watermark-stamper.js +1 -1
  23. package/dist/esm/utils/cli/utils/watermark-stamper.js.map +1 -1
  24. package/dist/esm/utils/dotenv.helpers.js +3 -1
  25. package/dist/esm/utils/dotenv.helpers.js.map +1 -1
  26. package/dist/esm/utils/helpers/arkos-config.helpers.js +3 -2
  27. package/dist/esm/utils/helpers/arkos-config.helpers.js.map +1 -1
  28. package/dist/esm/utils/helpers/prisma.helpers.js +2 -2
  29. package/dist/esm/utils/helpers/prisma.helpers.js.map +1 -1
  30. package/dist/types/components/arkos-gateway/arkos-gateway.d.ts +4 -2
  31. package/dist/types/components/arkos-gateway/socket-extensions.d.ts +5 -4
  32. package/dist/types/components/arkos-gateway/types.d.ts +86 -0
  33. package/dist/types/modules/email/email.service.d.ts +2 -0
  34. package/dist/types/utils/dotenv.helpers.d.ts +1 -0
  35. package/package.json +2 -2
package/cli.js CHANGED
@@ -1,22 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  (async () => {
3
3
  const { join, dirname } = await import("path");
4
- const { existsSync, readFileSync } = await import("fs");
5
4
  const { spawn } = await import("child_process");
6
5
  const { fileURLToPath } = await import("node:url");
7
6
 
8
7
  const __filename = fileURLToPath(import.meta.url);
9
8
  const __dirname = dirname(__filename);
10
9
 
11
- const pkgPath = join(process.cwd(), "package.json");
12
- let useEsm = false;
13
- if (existsSync(pkgPath)) {
14
- const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
15
- useEsm = pkg.type === "module";
16
- }
17
10
  const entryPoint = join(
18
11
  __dirname,
19
- `dist/${useEsm ? "esm" : "cjs"}/utils/cli/index.js`
12
+ `dist/esm/utils/cli/index.js`
20
13
  );
21
14
  const args = [
22
15
  ...["--import", "tsx"],
@@ -8,7 +8,7 @@ import { loginRequiredError } from "../../modules/auth/utils/auth-error-objects.
8
8
  import errorPrettifier from "../../modules/base/utils/error-prettifier.js";
9
9
  import deepmerge from "../../utils/helpers/deepmerge.helper.js";
10
10
  import { defaultGatewayStore } from "./utils/memory-gateway-store.js";
11
- import { mountArkosSocketExtensions } from "./socket-extensions.js";
11
+ import { ArkosBroadcastOperatorImpl, mountArkosSocketExtensions } from "./socket-extensions.js";
12
12
  import { isAuthenticationEnabled, isUsingAuthentication, } from "../../utils/helpers/arkos-config.helpers.js";
13
13
  import ExitError from "../../utils/helpers/exit-error.js";
14
14
  import { getUserFileExtension } from "../../utils/helpers/fs.helpers.js";
@@ -19,10 +19,16 @@ export class IArkosGateway {
19
19
  pipes = [];
20
20
  gateways = [];
21
21
  hooks = [];
22
+ _nsp;
22
23
  constructor(config) {
23
24
  this.config = config;
24
25
  this.config.name = config.name ?? "web-socket";
25
26
  }
27
+ get nsp() {
28
+ if (!this._nsp)
29
+ throw new Error(`gateway.nsp accessed before register()`);
30
+ return new ArkosBroadcastOperatorImpl(this._nsp.sockets, this._nsp);
31
+ }
26
32
  use(...middlewareOrGateway) {
27
33
  for (const item of middlewareOrGateway) {
28
34
  if (item instanceof IArkosGateway) {
@@ -92,7 +98,7 @@ export class IArkosGateway {
92
98
  }
93
99
  register(io, options = {}) {
94
100
  if (io._arkosGatewayRegistered)
95
- throw new Error(`The method gateway.register() can only be called once per io server instance. Use gateway.use() to compose gateways, see https://www.arkosjs.com/docs/components/advanced-guides/web-sockets/setup.`);
101
+ throw new Error(`The method gateway.register() can only be called once per io server instance. Use gateway.use() to compose gateways, see https://www.arkosjs.com/docs/guides/web-sockets/setup.`);
96
102
  io._arkosGatewayRegistered = true;
97
103
  this._register(io, undefined, this.hooks || [], this.pipes || [], options);
98
104
  }
@@ -110,6 +116,7 @@ export class IArkosGateway {
110
116
  ? `${parentName.replace(/\/$/, "")}/${ownName.replace(/^\//, "")}`
111
117
  : (ownName ?? "");
112
118
  const ns = io.of(namespaceName);
119
+ this._nsp = ns;
113
120
  const resolvedAuth = this.config.authentication !== false &&
114
121
  parentConfig?.authentication !== false;
115
122
  const resolvedRateLimit = this.config.rateLimit ?? parentConfig?.rateLimit;
@@ -1 +1 @@
1
- {"version":3,"file":"arkos-gateway.js","sourceRoot":"","sources":["../../../../src/components/arkos-gateway/arkos-gateway.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACxE,OAAO,EAAE,cAAc,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAC/E,OAAO,EACL,wBAAwB,EACxB,oBAAoB,EACpB,qBAAqB,EACrB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AACzB,OAAO,eAAe,MAAM,6CAA6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EH,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAClC,KAAK,CAAC,SAAS,CACb,EAAE,EACF;gBACE,IAAI,EAAE,aAAa;gBACnB,cAAc,EAAE,YAAY;gBAC5B,SAAS,EAAE,iBAAiB;aAC7B,EACD,aAAa,EACb,cAAc,EACd,OAAO,CACR,CAAC;QACJ,CAAC;IACH,CAAC;CACF;AA6BD,SAAS,YAAY,CAAC,MAA0B;IAC9C,OAAO,IAAI,aAAa,CAAC,MAAM,CAAC,CAAC;AACnC,CAAC;AAED,eAAe,YAAY,CAAC","sourcesContent":["import {\n ArkosGatewayConfig,\n ArkosGatewayErrorHandler,\n ArkosGatewayEventConfig,\n ArkosGatewayEventEntry,\n ArkosGatewayHandler,\n ArkosGatewayHookHandler,\n ArkosGatewayHookType,\n ArkosGatewayPipe,\n ArkosGatewayConnectionHandler,\n ArkosSocket,\n ArkosGatewayRegisterOptions,\n} from \"./types\";\nimport { Validator } from \"../../types/validation/validator\";\nimport { Server } from \"socket.io\";\nimport { authActionService, authService } from \"../../exports/services\";\nimport { checkRateLimit, clearRateLimitForSocket } from \"./utils/rate-limiter\";\nimport {\n handleArkosGatewayErrors,\n runArkosGatewayPipes,\n handleGatewayEventLog,\n handleGatewayLifecycleLog,\n} from \"./utils/helpers\";\nimport authHookManager from \"../../modules/auth/utils/auth-hooks-manager\";\nimport { getArkosConfig } from \"../../server\";\nimport validationManager from \"../../types/validation/validation-manager\";\nimport { loginRequiredError } from \"../../modules/auth/utils/auth-error-objects\";\nimport errorPrettifier from \"../../modules/base/utils/error-prettifier\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { defaultGatewayStore } from \"./utils/memory-gateway-store\";\nimport { mountArkosSocketExtensions } from \"./socket-extensions\";\nimport {\n isAuthenticationEnabled,\n isUsingAuthentication,\n} from \"../../utils/helpers/arkos-config.helpers\";\nimport ExitError from \"../../utils/helpers/exit-error\";\nimport { getUserFileExtension } from \"../../utils/helpers/fs.helpers\";\nimport {\n BadRequestError,\n TooManyRequestsError,\n} from \"../../modules/error-handler/utils/errors\";\n\nexport class IArkosGateway {\n private config: ArkosGatewayConfig;\n private events: ArkosGatewayEventEntry[] = [];\n private pipes: ArkosGatewayPipe[] = [];\n private gateways: IArkosGateway[] = [];\n private hooks: {\n type: ArkosGatewayHookType;\n handler: ArkosGatewayHookHandler;\n }[] = [];\n\n constructor(config: ArkosGatewayConfig) {\n this.config = config;\n this.config.name = config.name ?? \"web-socket\";\n }\n\n /**\n * Register a Socket.io connection-level middleware — runs before a socket\n * is accepted into this gateway's namespace. Also accepts a child\n * `ArkosGateway` which will inherit this gateway's name as prefix along\n * with its auth, rateLimit, and pipes.\n *\n * @example\n * chatGateway.use((socket, next) => {\n * console.log(\"incoming connection\", socket.id)\n * })\n *\n * // nested gateway\n * chatGateway.use(notificationsGateway)\n */\n use(...middlewareOrGateway: Array<ArkosGatewayPipe | IArkosGateway>): this {\n for (const item of middlewareOrGateway) {\n if (item instanceof IArkosGateway) {\n this.gateways.push(item);\n } else if (typeof item === \"function\") {\n this.pipes.push(item as ArkosGatewayPipe);\n } else {\n throw new Error(\n `Invalid value for gateway.use() — expected an ArkosGateway instance or a middleware function but received \"${typeof item}\".`\n );\n }\n }\n return this;\n }\n\n /**\n * Register a pipe — middleware that runs before event handlers.\n *\n * When called with a function only, the pipe runs before every event\n * handler in this gateway and drills down to child gateways.\n *\n * When called with an event config object, the pipe runs only for that\n * specific event.\n *\n * @example\n * // runs before every event in this gateway\n * chatGateway.pipe((socket, data) => {\n * })\n *\n * // runs only before \"send_message\"\n * chatGateway.pipe({ event: \"send_message\" }, (socket, data) => {\n * })\n */\n pipe(fn: ArkosGatewayPipe): this;\n pipe<TSchema extends Validator = any>(\n eventConfig: { event: string },\n fn: ArkosGatewayPipe\n ): this;\n pipe<TSchema extends Validator = any>(\n fnOrConfig: ArkosGatewayPipe | ArkosGatewayEventConfig<TSchema>,\n fn?: ArkosGatewayPipe\n ): this {\n if (typeof fnOrConfig === \"function\") {\n this.pipes.push(fnOrConfig);\n } else if (fnOrConfig && typeof fnOrConfig === \"object\" && fn) {\n const entry = this.events.find(\n (e) => e.config.event === fnOrConfig.event\n );\n if (entry) {\n entry.pipes = entry.pipes ?? [];\n entry.pipes.push(fn);\n } else {\n this.events.push({\n config: { event: fnOrConfig.event, _pipeOnly: true } as any,\n handler: null as any,\n pipes: [fn],\n });\n }\n } else {\n throw new Error(\n `Invalid arguments for gateway.pipe() — pass a middleware function, or an event config object followed by a middleware function.`\n );\n }\n return this;\n }\n\n /**\n * Register an event handler.\n *\n * @example\n * chatGateway.on(\n * { event: \"send_message\", validation: MessageSchema, ack: true },\n * (socket, data, ack) => {\n * socket.to(data.room).emit(\"receive_message\", data)\n * ack?.({ status: \"ok\" })\n * }\n * )\n */\n on<TSchema extends Validator = any>(\n eventConfig: ArkosGatewayEventConfig<TSchema>,\n handler: ArkosGatewayHandler\n ): this {\n if (eventConfig.disabled) return this;\n\n if (eventConfig.authorization && this.config.authentication === false) {\n throw new Error(\n `Event \"${eventConfig.event}\" on \"${this.config.name}\" gateway defines authorization rules ` +\n `but the gateway has authentication: false. Enable authentication on the gateway to use per-event authentication.`\n );\n }\n\n const deferred = this.events.find(\n (e) => (e.config as any)._pipeOnly && e.config.event === eventConfig.event\n );\n\n const entry: ArkosGatewayEventEntry = {\n config: eventConfig,\n handler,\n pipes: [...this.pipes, ...(deferred?.pipes ?? [])],\n };\n\n if (deferred) {\n const idx = this.events.indexOf(deferred);\n this.events.splice(idx, 1, entry);\n } else {\n this.events.push(entry);\n }\n\n if (typeof eventConfig?.authorization == \"object\")\n // To reuse later on\n (eventConfig.authorization as any)._authAction = authActionService.add(\n eventConfig.authorization!.action,\n eventConfig.authorization!.resource,\n {\n [eventConfig.authorization!.action]: eventConfig.authorization?.rule,\n }\n );\n\n return this;\n }\n\n /**\n * Register a lifecycle hook.\n *\n * - `\"connection\"` — called after a socket successfully connects and passes authentication.\n * - `\"disconnect\"` — called when a socket disconnects.\n * - `\"error\"` — called when an error is thrown inside any event handler.\n * If not registered, Arkos emits a default `\"error\"` event to the socket.\n *\n * @example\n * chatGateway.hook(\"connection\", (socket) => {\n * console.log(\"connected\", socket.user.id)\n * })\n *\n * chatGateway.hook(\"error\", (err, socket) => {\n * socket.emit(\"error\", { message: err.message })\n * })\n */\n hook(type: \"connection\", handler: ArkosGatewayConnectionHandler): this;\n hook(type: \"disconnect\", handler: ArkosGatewayConnectionHandler): this;\n hook(type: \"error\", handler: ArkosGatewayErrorHandler): this;\n hook(\n type: ArkosGatewayHookType,\n handler: ArkosGatewayConnectionHandler | ArkosGatewayErrorHandler\n ): this {\n this.hooks.push({ type, handler });\n return this;\n }\n\n /**\n * Wire this gateway into a Socket.io `Server` instance.\n * Registers the namespace, auth middleware, rate limiting, pipes,\n * and all event handlers — then recurses into child gateways.\n *\n * @example\n * const io = new Server(server)\n * chatGateway.register(io)\n */\n register(io: Server, options: ArkosGatewayRegisterOptions = {}): void {\n if ((io as any)._arkosGatewayRegistered)\n throw new Error(\n `The method gateway.register() can only be called once per io server instance. Use gateway.use() to compose gateways, see https://www.arkosjs.com/docs/components/advanced-guides/web-sockets/setup.`\n );\n (io as any)._arkosGatewayRegistered = true;\n this._register(io, undefined, this.hooks || [], this.pipes || [], options);\n }\n\n private _register(\n io: Server,\n parentConfig?: ArkosGatewayConfig,\n inheritedHooks: {\n type: ArkosGatewayHookType;\n handler: ArkosGatewayHookHandler;\n }[] = [],\n inheritedPipes: ArkosGatewayPipe[] = [],\n options: ArkosGatewayRegisterOptions = {}\n ): void {\n options.store = options.store ?? defaultGatewayStore;\n const { store } = options;\n\n const parentName = parentConfig?.name;\n const ownName = this.config.name;\n this.config = deepmerge(parentConfig || {}, this.config, {\n arrayMerge: (_, sourceArray) => sourceArray,\n });\n this.config.name = ownName;\n const localConfig = this.config;\n\n const namespaceName = parentName\n ? `${parentName.replace(/\\/$/, \"\")}/${ownName.replace(/^\\//, \"\")}`\n : (ownName ?? \"\");\n\n const ns = io.of(namespaceName);\n\n const resolvedAuth =\n this.config.authentication !== false &&\n parentConfig?.authentication !== false;\n\n const resolvedRateLimit = this.config.rateLimit ?? parentConfig?.rateLimit;\n const resolvedHooks = [...inheritedHooks, ...this.hooks];\n\n const connectHandlers = resolvedHooks\n .filter((h) => h.type === \"connection\")\n .map((h) => h.handler as ArkosGatewayConnectionHandler);\n\n const disconnectHandlers = resolvedHooks\n .filter((h) => h.type === \"disconnect\")\n .map((h) => h.handler as ArkosGatewayConnectionHandler);\n\n const errorHandlers = resolvedHooks\n .filter((h) => h.type === \"error\")\n .map((h) => h.handler as ArkosGatewayErrorHandler);\n\n if (resolvedAuth && isAuthenticationEnabled()) {\n ns.use(async (socket: any, next) => {\n socket = socket as ArkosSocket;\n const startTime = new Date().getTime();\n try {\n await authHookManager.runAuthenticate(\n {\n context: socket,\n done: (err?: any) => {\n if (err) throw err;\n next();\n },\n },\n async (socket) => {\n const user = await authService.getAuthenticatedUser(socket);\n if (!user) throw loginRequiredError;\n return user;\n },\n \"currentUser\"\n );\n } catch (err: any) {\n handleArkosGatewayErrors(err, socket, errorHandlers, {\n startTime,\n namespace: this.config.name,\n event: \"authentication\",\n });\n next(err);\n }\n });\n } else if (\n (this.config.authentication || parentConfig?.authentication) &&\n !isUsingAuthentication()\n )\n throw ExitError(\n `Trying to authenticate gateway ${this.config.name ? `${this.config.name}` : \"\"} without choosing an authentication mode under arkos.config.${getUserFileExtension()}.\n\nFor further help see https://www.arkosjs.com/docs/core-concepts/authentication/setup.`\n );\n\n ns.on(\"connection\", async (s) => {\n const socket = s as ArkosSocket;\n socket.locals = {};\n\n socket._arkos = { store, gatewayConfig: localConfig };\n mountArkosSocketExtensions(socket);\n\n handleGatewayLifecycleLog(this.config.name, \"connected\", socket.id);\n const connectionStartTime = new Date().getTime();\n\n if (socket.currentUser?.id)\n socket.join(`arkos::user:${socket.currentUser.id}`);\n\n try {\n for (const handler of connectHandlers) await handler(socket);\n } catch (err: any) {\n handleArkosGatewayErrors(err, socket, [], {\n startTime: connectionStartTime,\n namespace: this.config.name,\n event: \"connection\",\n });\n return;\n }\n\n socket.on(\"disconnect\", async () => {\n handleGatewayLifecycleLog(this.config.name, \"disconnected\", socket.id);\n\n await clearRateLimitForSocket(socket.id, store);\n try {\n for (const handler of disconnectHandlers) await handler(socket);\n } catch (err) {\n handleArkosGatewayErrors(err, socket, [], {\n startTime: connectionStartTime,\n namespace: this.config.name,\n event: \"disconnection\",\n });\n }\n });\n\n for (const entry of this.events) {\n if ((entry.config as any)._pipeOnly || !entry.handler) continue;\n\n const { config: eventConfig, handler, pipes: eventPipes = [] } = entry;\n\n if (\n (this.config.authentication || parentConfig?.authentication) &&\n !isUsingAuthentication()\n )\n throw ExitError(\n `Trying to use authorization gateway.on(\"${eventConfig.event}\") without choosing an authentication mode under arkos.config.${getUserFileExtension()}.\n\nFor further help see https://www.arkosjs.com/docs/core-concepts/authentication/setup.`\n );\n\n socket.on(eventConfig.event, async (...args: any[]) => {\n socket.locals = {};\n const startTime = new Date().getTime();\n let data = args[0];\n\n const ack =\n typeof args[args.length - 1] === \"function\"\n ? args[args.length - 1]\n : undefined;\n\n let ackCalled = false;\n const wrappedAck = ack\n ? (...response: any) => {\n ackCalled = true;\n ack(...response);\n }\n : undefined;\n\n function resolveDedup() {\n if (\n eventConfig.dedup === false ||\n localConfig.dedup === false ||\n parentConfig?.dedup === false\n )\n return null;\n\n return {\n enabled: true,\n ttl: 3600,\n ...parentConfig?.dedup,\n ...localConfig?.dedup,\n ...eventConfig?.dedup,\n };\n }\n\n const dedupOpt = resolveDedup();\n\n try {\n const meta = data?._meta || {};\n const resolvedMaxAge =\n eventConfig.maxAge ?? localConfig.maxAge ?? parentConfig?.maxAge;\n\n if (resolvedMaxAge && !meta.timestamp)\n throw new BadRequestError(\n \"Missing _meta.timestamp for maxAge deduplication\"\n );\n\n if (meta.timestamp !== undefined) {\n const timestamp = new Date(meta.timestamp);\n\n if (isNaN(timestamp.getTime())) {\n throw new BadRequestError(\n \"Invalid data._meta.timestamp\",\n \"InvalidTimestamp\"\n );\n }\n\n const age = Date.now() - timestamp.getTime();\n\n if (age + 1000 < 0)\n throw new BadRequestError(\n \"Timestamp is in the future\",\n \"FutureTimestamp\"\n );\n\n if (resolvedMaxAge && age > resolvedMaxAge) {\n throw new BadRequestError(\"Message is too old\", \"StaleMessage\");\n }\n }\n\n if (dedupOpt && dedupOpt?.enabled !== false) {\n if (!meta?.mid)\n throw new BadRequestError(\n \"Missing data._meta.mid in your payload for deduplication\",\n \"MissingDedupMessageId\",\n { data }\n );\n\n if (typeof meta.mid !== \"string\" || meta.mid.trim() === \"\")\n throw new BadRequestError(\n \"Invalid data._meta.mid, it must be a non-empty string\",\n \"InvalidMessageId\"\n );\n\n const key = `arkos::dedup:${eventConfig.event}:${meta.mid}`;\n const ttl = dedupOpt?.ttl ?? 3600;\n\n const acquired = await store.setIfNotExists(key, ttl);\n\n if (acquired === false)\n return wrappedAck?.({\n success: true,\n duplicate: true,\n });\n\n const { _meta, ...payload } = data;\n data = payload;\n\n socket.meta = meta;\n }\n\n const rateLimitOptions = eventConfig.rateLimit ?? resolvedRateLimit;\n if (rateLimitOptions !== false) {\n const { allowed, retryAfter } = await checkRateLimit(\n socket.id,\n eventConfig.event,\n rateLimitOptions || {},\n options.store!\n );\n if (!allowed) {\n throw new TooManyRequestsError(undefined, undefined, {\n retryAfter,\n });\n }\n }\n\n if (\n typeof eventConfig.authorization === \"object\" &&\n resolvedAuth &&\n isAuthenticationEnabled()\n ) {\n await authHookManager.runAuthorize(\n { context: socket, done: () => {} },\n (eventConfig?.authorization as any)?._authAction,\n \"currentUser\"\n );\n }\n\n if (eventConfig.validation) {\n const arkosConfig = getArkosConfig();\n const {\n validationFn,\n isValidValidator,\n validatorName,\n validatorNameType,\n } = validationManager;\n\n if (!isValidValidator(eventConfig.validation))\n throw new Error(\n `Your validation resolver is set to ${arkosConfig.validation!.resolver}, ` +\n `please provide a valid ${validatorName} in order to use { validation: ${validatorNameType} } ` +\n `under event handler \"${eventConfig.event}\" in \"${this.config.name}\" gateway.`\n );\n\n const shouldValidate = validationManager.shouldValidate(\n eventConfig.validation,\n data\n );\n\n if (shouldValidate === \"prohibit\")\n throw new BadRequestError(\n \"Event data is not allowed for this event.\",\n \"EventDataNotAllowed\",\n { data }\n );\n else if (shouldValidate === \"passthrough\") data = data;\n else {\n try {\n data = await (validationFn as any)(\n eventConfig.validation,\n data\n );\n } catch (err: any) {\n const { validationConfig } = validationManager;\n\n const resolver = validationConfig?.resolver;\n const isZod = validationConfig?.resolver === \"zod\";\n\n const prettifiedError = errorPrettifier.prettify(\n resolver as any,\n err\n );\n const error = prettifiedError[0];\n\n throw new BadRequestError(\n error.message,\n `InvalidData`,\n isZod ? err.format() : err\n );\n }\n }\n }\n\n socket.data = data;\n\n await runArkosGatewayPipes(\n [...inheritedPipes, ...eventPipes],\n socket,\n data\n );\n\n await handler(socket, data, wrappedAck);\n\n handleGatewayEventLog(\n this.config.name,\n eventConfig.event,\n 200,\n startTime\n );\n\n if (eventConfig.ack && ack && !ackCalled) {\n ack({ success: true });\n }\n } catch (err: any) {\n handleArkosGatewayErrors(\n err,\n socket,\n errorHandlers,\n {\n startTime,\n namespace: this.config.name,\n event: eventConfig.event,\n },\n ack\n );\n }\n });\n }\n });\n\n for (const child of this.gateways) {\n child._register(\n io,\n {\n name: namespaceName,\n authentication: resolvedAuth,\n rateLimit: resolvedRateLimit,\n },\n resolvedHooks,\n inheritedPipes,\n options\n );\n }\n }\n}\n\n/**\n * Creates an Arkos WebSocket Gateway backed by Socket.io.\n *\n * Handles authentication, validation, rate limiting, pipes,\n * error handling, and nested gateways — all declaratively.\n * Enhances every connected socket with `socket.user()`, `socket.peer()`,\n * `socket.retry()`, and automatic `_meta` injection on outgoing emits.\n *\n * @example\n * ```ts\n * const chatGateway = ArkosGateway({\n * name: \"chat\",\n * authentication: true,\n * rateLimit: { windowMs: 60_000, max: 200 },\n * })\n *\n * chatGateway.on(\n * { event: \"send_message\", validation: MessageSchema, ack: true },\n * (socket, data, ack) => {\n * socket.to(data.room).emit(\"receive_message\", data)\n * ack?.({ status: \"ok\" })\n * }\n * )\n * ```\n * @since 1.7.0-canary.18\n * @see {@link https://www.arkosjs.com/docs/core-concepts/components/gateways}\n */\nfunction ArkosGateway(config: ArkosGatewayConfig) {\n return new IArkosGateway(config);\n}\n\nexport default ArkosGateway;\n"]}
1
+ {"version":3,"file":"arkos-gateway.js","sourceRoot":"","sources":["../../../../src/components/arkos-gateway/arkos-gateway.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACxE,OAAO,EAAE,cAAc,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAC/E,OAAO,EACL,wBAAwB,EACxB,oBAAoB,EACpB,qBAAqB,EACrB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AACzB,OAAO,eAAe,MAAM,6CAA6C,CAAC;AAC1E,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,iBAAiB,MAAM,2CAA2C,CAAC;AAC1E,OAAO,EAAE,kBAAkB,EAAE,MAAM,6CAA6C,CAAC;AACjF,OAAO,eAAe,MAAM,2CAA2C,CAAC;AACxE,OAAO,SAAS,MAAM,sCAAsC,CAAC;AAC7D,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EAAE,0BAA0B,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AAC7F,OAAO,EACL,uBAAuB,EACvB,qBAAqB,GACtB,MAAM,0CAA0C,CAAC;AAClD,OAAO,SAAS,MAAM,gCAAgC,CAAC;AACvD,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EACL,eAAe,EACf,oBAAoB,GACrB,MAAM,0CAA0C,CAAC;AAElD,MAAM,OAAO,aAAa;IAChB,MAAM,CAAqB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M,CAAC,CAAC;AACnC,CAAC;AAED,eAAe,YAAY,CAAC","sourcesContent":["import {\n ArkosGatewayConfig,\n ArkosGatewayErrorHandler,\n ArkosGatewayEventConfig,\n ArkosGatewayEventEntry,\n ArkosGatewayHandler,\n ArkosGatewayHookHandler,\n ArkosGatewayHookType,\n ArkosGatewayPipe,\n ArkosGatewayConnectionHandler,\n ArkosSocket,\n ArkosGatewayRegisterOptions,\n ArkosBroadcastOperator,\n ArkosEmitTarget,\n} from \"./types\";\nimport { Validator } from \"../../types/validation/validator\";\nimport { BroadcastOperator, Namespace, Server } from \"socket.io\";\nimport { authActionService, authService } from \"../../exports/services\";\nimport { checkRateLimit, clearRateLimitForSocket } from \"./utils/rate-limiter\";\nimport {\n handleArkosGatewayErrors,\n runArkosGatewayPipes,\n handleGatewayEventLog,\n handleGatewayLifecycleLog,\n} from \"./utils/helpers\";\nimport authHookManager from \"../../modules/auth/utils/auth-hooks-manager\";\nimport { getArkosConfig } from \"../../server\";\nimport validationManager from \"../../types/validation/validation-manager\";\nimport { loginRequiredError } from \"../../modules/auth/utils/auth-error-objects\";\nimport errorPrettifier from \"../../modules/base/utils/error-prettifier\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { defaultGatewayStore } from \"./utils/memory-gateway-store\";\nimport { ArkosBroadcastOperatorImpl, mountArkosSocketExtensions } from \"./socket-extensions\";\nimport {\n isAuthenticationEnabled,\n isUsingAuthentication,\n} from \"../../utils/helpers/arkos-config.helpers\";\nimport ExitError from \"../../utils/helpers/exit-error\";\nimport { getUserFileExtension } from \"../../utils/helpers/fs.helpers\";\nimport {\n BadRequestError,\n TooManyRequestsError,\n} from \"../../modules/error-handler/utils/errors\";\n\nexport class IArkosGateway {\n private config: ArkosGatewayConfig;\n private events: ArkosGatewayEventEntry[] = [];\n private pipes: ArkosGatewayPipe[] = [];\n private gateways: IArkosGateway[] = [];\n private hooks: {\n type: ArkosGatewayHookType;\n handler: ArkosGatewayHookHandler;\n }[] = [];\n private _nsp!: Namespace\n\n constructor(config: ArkosGatewayConfig) {\n this.config = config;\n this.config.name = config.name ?? \"web-socket\";\n }\n\n get nsp(): Omit<Namespace, keyof ArkosEmitTarget | keyof BroadcastOperator<any, any>> & ArkosBroadcastOperator {\n if (!this._nsp) throw new Error(`gateway.nsp accessed before register()`);\n return new ArkosBroadcastOperatorImpl(this._nsp.sockets, this._nsp) as any;\n }\n\n /**\n * Register a Socket.io connection-level middleware — runs before a socket\n * is accepted into this gateway's namespace. Also accepts a child\n * `ArkosGateway` which will inherit this gateway's name as prefix along\n * with its auth, rateLimit, and pipes.\n *\n * @example\n * chatGateway.use((socket, next) => {\n * console.log(\"incoming connection\", socket.id)\n * })\n *\n * // nested gateway\n * chatGateway.use(notificationsGateway)\n */\n use(...middlewareOrGateway: Array<ArkosGatewayPipe | IArkosGateway>): this {\n for (const item of middlewareOrGateway) {\n if (item instanceof IArkosGateway) {\n this.gateways.push(item);\n } else if (typeof item === \"function\") {\n this.pipes.push(item as ArkosGatewayPipe);\n } else {\n throw new Error(\n `Invalid value for gateway.use() — expected an ArkosGateway instance or a middleware function but received \"${typeof item}\".`\n );\n }\n }\n return this;\n }\n\n /**\n * Register a pipe — middleware that runs before event handlers.\n *\n * When called with a function only, the pipe runs before every event\n * handler in this gateway and drills down to child gateways.\n *\n * When called with an event config object, the pipe runs only for that\n * specific event.\n *\n * @example\n * // runs before every event in this gateway\n * chatGateway.pipe((socket, data) => {\n * })\n *\n * // runs only before \"send_message\"\n * chatGateway.pipe({ event: \"send_message\" }, (socket, data) => {\n * })\n */\n pipe(fn: ArkosGatewayPipe): this;\n pipe<TSchema extends Validator = any>(\n eventConfig: { event: string },\n fn: ArkosGatewayPipe\n ): this;\n pipe<TSchema extends Validator = any>(\n fnOrConfig: ArkosGatewayPipe | ArkosGatewayEventConfig<TSchema>,\n fn?: ArkosGatewayPipe\n ): this {\n if (typeof fnOrConfig === \"function\") {\n this.pipes.push(fnOrConfig);\n } else if (fnOrConfig && typeof fnOrConfig === \"object\" && fn) {\n const entry = this.events.find(\n (e) => e.config.event === fnOrConfig.event\n );\n if (entry) {\n entry.pipes = entry.pipes ?? [];\n entry.pipes.push(fn);\n } else {\n this.events.push({\n config: { event: fnOrConfig.event, _pipeOnly: true } as any,\n handler: null as any,\n pipes: [fn],\n });\n }\n } else {\n throw new Error(\n `Invalid arguments for gateway.pipe() — pass a middleware function, or an event config object followed by a middleware function.`\n );\n }\n return this;\n }\n\n /**\n * Register an event handler.\n *\n * @example\n * chatGateway.on(\n * { event: \"send_message\", validation: MessageSchema, ack: true },\n * (socket, data, ack) => {\n * socket.to(data.room).emit(\"receive_message\", data)\n * ack?.({ status: \"ok\" })\n * }\n * )\n */\n on<TSchema extends Validator = any>(\n eventConfig: ArkosGatewayEventConfig<TSchema>,\n handler: ArkosGatewayHandler\n ): this {\n if (eventConfig.disabled) return this;\n\n if (eventConfig.authorization && this.config.authentication === false) {\n throw new Error(\n `Event \"${eventConfig.event}\" on \"${this.config.name}\" gateway defines authorization rules ` +\n `but the gateway has authentication: false. Enable authentication on the gateway to use per-event authentication.`\n );\n }\n\n const deferred = this.events.find(\n (e) => (e.config as any)._pipeOnly && e.config.event === eventConfig.event\n );\n\n const entry: ArkosGatewayEventEntry = {\n config: eventConfig,\n handler,\n pipes: [...this.pipes, ...(deferred?.pipes ?? [])],\n };\n\n if (deferred) {\n const idx = this.events.indexOf(deferred);\n this.events.splice(idx, 1, entry);\n } else {\n this.events.push(entry);\n }\n\n if (typeof eventConfig?.authorization == \"object\")\n // To reuse later on\n (eventConfig.authorization as any)._authAction = authActionService.add(\n eventConfig.authorization!.action,\n eventConfig.authorization!.resource,\n {\n [eventConfig.authorization!.action]: eventConfig.authorization?.rule,\n }\n );\n\n return this;\n }\n\n /**\n * Register a lifecycle hook.\n *\n * - `\"connection\"` — called after a socket successfully connects and passes authentication.\n * - `\"disconnect\"` — called when a socket disconnects.\n * - `\"error\"` — called when an error is thrown inside any event handler.\n * If not registered, Arkos emits a default `\"error\"` event to the socket.\n *\n * @example\n * chatGateway.hook(\"connection\", (socket) => {\n * console.log(\"connected\", socket.user.id)\n * })\n *\n * chatGateway.hook(\"error\", (err, socket) => {\n * socket.emit(\"error\", { message: err.message })\n * })\n */\n hook(type: \"connection\", handler: ArkosGatewayConnectionHandler): this;\n hook(type: \"disconnect\", handler: ArkosGatewayConnectionHandler): this;\n hook(type: \"error\", handler: ArkosGatewayErrorHandler): this;\n hook(\n type: ArkosGatewayHookType,\n handler: ArkosGatewayConnectionHandler | ArkosGatewayErrorHandler\n ): this {\n this.hooks.push({ type, handler });\n return this;\n }\n\n /**\n * Wire this gateway into a Socket.io `Server` instance.\n * Registers the namespace, auth middleware, rate limiting, pipes,\n * and all event handlers — then recurses into child gateways.\n *\n * @example\n * const io = new Server(server)\n * chatGateway.register(io)\n */\n register(io: Server, options: ArkosGatewayRegisterOptions = {}): void {\n if ((io as any)._arkosGatewayRegistered)\n throw new Error(\n `The method gateway.register() can only be called once per io server instance. Use gateway.use() to compose gateways, see https://www.arkosjs.com/docs/guides/web-sockets/setup.`\n );\n (io as any)._arkosGatewayRegistered = true;\n this._register(io, undefined, this.hooks || [], this.pipes || [], options);\n }\n\n private _register(\n io: Server,\n parentConfig?: ArkosGatewayConfig,\n inheritedHooks: {\n type: ArkosGatewayHookType;\n handler: ArkosGatewayHookHandler;\n }[] = [],\n inheritedPipes: ArkosGatewayPipe[] = [],\n options: ArkosGatewayRegisterOptions = {}\n ): void {\n options.store = options.store ?? defaultGatewayStore;\n const { store } = options;\n\n const parentName = parentConfig?.name;\n const ownName = this.config.name;\n this.config = deepmerge(parentConfig || {}, this.config, {\n arrayMerge: (_, sourceArray) => sourceArray,\n });\n this.config.name = ownName;\n const localConfig = this.config;\n\n const namespaceName = parentName\n ? `${parentName.replace(/\\/$/, \"\")}/${ownName.replace(/^\\//, \"\")}`\n : (ownName ?? \"\");\n\n const ns = io.of(namespaceName);\n this._nsp = ns;\n\n const resolvedAuth =\n this.config.authentication !== false &&\n parentConfig?.authentication !== false;\n\n const resolvedRateLimit = this.config.rateLimit ?? parentConfig?.rateLimit;\n const resolvedHooks = [...inheritedHooks, ...this.hooks];\n\n const connectHandlers = resolvedHooks\n .filter((h) => h.type === \"connection\")\n .map((h) => h.handler as ArkosGatewayConnectionHandler);\n\n const disconnectHandlers = resolvedHooks\n .filter((h) => h.type === \"disconnect\")\n .map((h) => h.handler as ArkosGatewayConnectionHandler);\n\n const errorHandlers = resolvedHooks\n .filter((h) => h.type === \"error\")\n .map((h) => h.handler as ArkosGatewayErrorHandler);\n\n if (resolvedAuth && isAuthenticationEnabled()) {\n ns.use(async (socket: any, next) => {\n socket = socket as ArkosSocket;\n const startTime = new Date().getTime();\n try {\n await authHookManager.runAuthenticate(\n {\n context: socket,\n done: (err?: any) => {\n if (err) throw err;\n next();\n },\n },\n async (socket) => {\n const user = await authService.getAuthenticatedUser(socket);\n if (!user) throw loginRequiredError;\n return user;\n },\n \"currentUser\"\n );\n } catch (err: any) {\n handleArkosGatewayErrors(err, socket, errorHandlers, {\n startTime,\n namespace: this.config.name,\n event: \"authentication\",\n });\n next(err);\n }\n });\n } else if (\n (this.config.authentication || parentConfig?.authentication) &&\n !isUsingAuthentication()\n )\n throw ExitError(\n `Trying to authenticate gateway ${this.config.name ? `${this.config.name}` : \"\"} without choosing an authentication mode under arkos.config.${getUserFileExtension()}.\n\nFor further help see https://www.arkosjs.com/docs/core-concepts/authentication/setup.`\n );\n\n ns.on(\"connection\", async (s) => {\n const socket = s as ArkosSocket;\n socket.locals = {};\n\n socket._arkos = { store, gatewayConfig: localConfig };\n mountArkosSocketExtensions(socket);\n\n handleGatewayLifecycleLog(this.config.name, \"connected\", socket.id);\n const connectionStartTime = new Date().getTime();\n\n if (socket.currentUser?.id)\n socket.join(`arkos::user:${socket.currentUser.id}`);\n\n try {\n for (const handler of connectHandlers) await handler(socket);\n } catch (err: any) {\n handleArkosGatewayErrors(err, socket, [], {\n startTime: connectionStartTime,\n namespace: this.config.name,\n event: \"connection\",\n });\n return;\n }\n\n socket.on(\"disconnect\", async () => {\n handleGatewayLifecycleLog(this.config.name, \"disconnected\", socket.id);\n\n await clearRateLimitForSocket(socket.id, store);\n try {\n for (const handler of disconnectHandlers) await handler(socket);\n } catch (err) {\n handleArkosGatewayErrors(err, socket, [], {\n startTime: connectionStartTime,\n namespace: this.config.name,\n event: \"disconnection\",\n });\n }\n });\n\n for (const entry of this.events) {\n if ((entry.config as any)._pipeOnly || !entry.handler) continue;\n\n const { config: eventConfig, handler, pipes: eventPipes = [] } = entry;\n\n if (\n (this.config.authentication || parentConfig?.authentication) &&\n !isUsingAuthentication()\n )\n throw ExitError(\n `Trying to use authorization gateway.on(\"${eventConfig.event}\") without choosing an authentication mode under arkos.config.${getUserFileExtension()}.\n\nFor further help see https://www.arkosjs.com/docs/core-concepts/authentication/setup.`\n );\n\n socket.on(eventConfig.event, async (...args: any[]) => {\n socket.locals = {};\n const startTime = new Date().getTime();\n let data = args[0];\n\n const ack =\n typeof args[args.length - 1] === \"function\"\n ? args[args.length - 1]\n : undefined;\n\n let ackCalled = false;\n const wrappedAck = ack\n ? (...response: any) => {\n ackCalled = true;\n ack(...response);\n }\n : undefined;\n\n function resolveDedup() {\n if (\n eventConfig.dedup === false ||\n localConfig.dedup === false ||\n parentConfig?.dedup === false\n )\n return null;\n\n return {\n enabled: true,\n ttl: 3600,\n ...parentConfig?.dedup,\n ...localConfig?.dedup,\n ...eventConfig?.dedup,\n };\n }\n\n const dedupOpt = resolveDedup();\n\n try {\n const meta = data?._meta || {};\n const resolvedMaxAge =\n eventConfig.maxAge ?? localConfig.maxAge ?? parentConfig?.maxAge;\n\n if (resolvedMaxAge && !meta.timestamp)\n throw new BadRequestError(\n \"Missing _meta.timestamp for maxAge deduplication\"\n );\n\n if (meta.timestamp !== undefined) {\n const timestamp = new Date(meta.timestamp);\n\n if (isNaN(timestamp.getTime())) {\n throw new BadRequestError(\n \"Invalid data._meta.timestamp\",\n \"InvalidTimestamp\"\n );\n }\n\n const age = Date.now() - timestamp.getTime();\n\n if (age + 1000 < 0)\n throw new BadRequestError(\n \"Timestamp is in the future\",\n \"FutureTimestamp\"\n );\n\n if (resolvedMaxAge && age > resolvedMaxAge) {\n throw new BadRequestError(\"Message is too old\", \"StaleMessage\");\n }\n }\n\n if (dedupOpt && dedupOpt?.enabled !== false) {\n if (!meta?.mid)\n throw new BadRequestError(\n \"Missing data._meta.mid in your payload for deduplication\",\n \"MissingDedupMessageId\",\n { data }\n );\n\n if (typeof meta.mid !== \"string\" || meta.mid.trim() === \"\")\n throw new BadRequestError(\n \"Invalid data._meta.mid, it must be a non-empty string\",\n \"InvalidMessageId\"\n );\n\n const key = `arkos::dedup:${eventConfig.event}:${meta.mid}`;\n const ttl = dedupOpt?.ttl ?? 3600;\n\n const acquired = await store.setIfNotExists(key, ttl);\n\n if (acquired === false)\n return wrappedAck?.({\n success: true,\n duplicate: true,\n });\n\n const { _meta, ...payload } = data;\n data = payload;\n\n socket.meta = meta;\n }\n\n const rateLimitOptions = eventConfig.rateLimit ?? resolvedRateLimit;\n if (rateLimitOptions !== false) {\n const { allowed, retryAfter } = await checkRateLimit(\n socket.id,\n eventConfig.event,\n rateLimitOptions || {},\n options.store!\n );\n if (!allowed) {\n throw new TooManyRequestsError(undefined, undefined, {\n retryAfter,\n });\n }\n }\n\n if (\n typeof eventConfig.authorization === \"object\" &&\n resolvedAuth &&\n isAuthenticationEnabled()\n ) {\n await authHookManager.runAuthorize(\n { context: socket, done: () => { } },\n (eventConfig?.authorization as any)?._authAction,\n \"currentUser\"\n );\n }\n\n if (eventConfig.validation) {\n const arkosConfig = getArkosConfig();\n const {\n validationFn,\n isValidValidator,\n validatorName,\n validatorNameType,\n } = validationManager;\n\n if (!isValidValidator(eventConfig.validation))\n throw new Error(\n `Your validation resolver is set to ${arkosConfig.validation!.resolver}, ` +\n `please provide a valid ${validatorName} in order to use { validation: ${validatorNameType} } ` +\n `under event handler \"${eventConfig.event}\" in \"${this.config.name}\" gateway.`\n );\n\n const shouldValidate = validationManager.shouldValidate(\n eventConfig.validation,\n data\n );\n\n if (shouldValidate === \"prohibit\")\n throw new BadRequestError(\n \"Event data is not allowed for this event.\",\n \"EventDataNotAllowed\",\n { data }\n );\n else if (shouldValidate === \"passthrough\") data = data;\n else {\n try {\n data = await (validationFn as any)(\n eventConfig.validation,\n data\n );\n } catch (err: any) {\n const { validationConfig } = validationManager;\n\n const resolver = validationConfig?.resolver;\n const isZod = validationConfig?.resolver === \"zod\";\n\n const prettifiedError = errorPrettifier.prettify(\n resolver as any,\n err\n );\n const error = prettifiedError[0];\n\n throw new BadRequestError(\n error.message,\n `InvalidData`,\n isZod ? err.format() : err\n );\n }\n }\n }\n\n socket.data = data;\n\n await runArkosGatewayPipes(\n [...inheritedPipes, ...eventPipes],\n socket,\n data\n );\n\n await handler(socket, data, wrappedAck);\n\n handleGatewayEventLog(\n this.config.name,\n eventConfig.event,\n 200,\n startTime\n );\n\n if (eventConfig.ack && ack && !ackCalled) {\n ack({ success: true });\n }\n } catch (err: any) {\n handleArkosGatewayErrors(\n err,\n socket,\n errorHandlers,\n {\n startTime,\n namespace: this.config.name,\n event: eventConfig.event,\n },\n ack\n );\n }\n });\n }\n });\n\n for (const child of this.gateways) {\n child._register(\n io,\n {\n name: namespaceName,\n authentication: resolvedAuth,\n rateLimit: resolvedRateLimit,\n },\n resolvedHooks,\n inheritedPipes,\n options\n );\n }\n }\n}\n\n/**\n * Creates an Arkos WebSocket Gateway backed by Socket.io.\n *\n * Handles authentication, validation, rate limiting, pipes,\n * error handling, and nested gateways — all declaratively.\n * Enhances every connected socket with `socket.user()`, `socket.peer()`,\n * `socket.retry()`, and automatic `_meta` injection on outgoing emits.\n *\n * @example\n * ```ts\n * const chatGateway = ArkosGateway({\n * name: \"chat\",\n * authentication: true,\n * rateLimit: { windowMs: 60_000, max: 200 },\n * })\n *\n * chatGateway.on(\n * { event: \"send_message\", validation: MessageSchema, ack: true },\n * (socket, data, ack) => {\n * socket.to(data.room).emit(\"receive_message\", data)\n * ack?.({ status: \"ok\" })\n * }\n * )\n * ```\n * @since 1.7.0-canary.18\n * @see {@link https://www.arkosjs.com/docs/core-concepts/components/gateways}\n */\nfunction ArkosGateway(config: ArkosGatewayConfig) {\n return new IArkosGateway(config);\n}\n\nexport default ArkosGateway;\n"]}
@@ -5,10 +5,10 @@ function injectMeta(data) {
5
5
  _meta: { mid: uuidv7(), timestamp: Date.now() },
6
6
  };
7
7
  }
8
- function resolveUserSocketIds(socket, userId) {
8
+ function resolveUserSocketIds(sockets, userId) {
9
9
  const ids = Array.isArray(userId) ? userId : [userId];
10
10
  const result = [];
11
- for (const [id, s] of socket.nsp.sockets) {
11
+ for (const [id, s] of sockets) {
12
12
  for (const uid of ids) {
13
13
  if (s.rooms.has(`arkos::user:${uid}`)) {
14
14
  result.push(id);
@@ -19,10 +19,10 @@ function resolveUserSocketIds(socket, userId) {
19
19
  return result;
20
20
  }
21
21
  export class ArkosBroadcastOperatorImpl {
22
- socket;
22
+ sockets;
23
23
  operator;
24
- constructor(socket, operator) {
25
- this.socket = socket;
24
+ constructor(sockets, operator) {
25
+ this.sockets = sockets;
26
26
  this.operator = operator;
27
27
  const instance = Object.create(operator);
28
28
  instance.emit = this.emit.bind(this);
@@ -37,6 +37,9 @@ export class ArkosBroadcastOperatorImpl {
37
37
  });
38
38
  return instance;
39
39
  }
40
+ user(userId) {
41
+ return applyUserTarget(this.sockets, this.operator)(userId);
42
+ }
40
43
  async users() {
41
44
  const sockets = await this.operator.fetchSockets();
42
45
  const userIds = new Set();
@@ -52,29 +55,31 @@ export class ArkosBroadcastOperatorImpl {
52
55
  }
53
56
  except(room) {
54
57
  if (typeof room === "string" || Array.isArray(room)) {
55
- return new ArkosBroadcastOperatorImpl(this.socket, this.operator.except(room));
58
+ return new ArkosBroadcastOperatorImpl(this.sockets, this.operator.except(room));
56
59
  }
57
- const socketIds = resolveUserSocketIds(this.socket, room.user);
60
+ const socketIds = resolveUserSocketIds(this.sockets, room.user);
58
61
  let op = this.operator;
59
62
  for (const id of socketIds)
60
63
  op = op.except(id);
61
- return new ArkosBroadcastOperatorImpl(this.socket, op);
64
+ return new ArkosBroadcastOperatorImpl(this.sockets, op);
62
65
  }
63
66
  emit(event, ...args) {
64
67
  const [data, ...rest] = args;
65
68
  return this.operator.emit(event, injectMeta(data), ...rest);
66
69
  }
67
70
  get volatile() {
68
- return new ArkosBroadcastOperatorImpl(this.socket, this.operator.volatile);
71
+ return new ArkosBroadcastOperatorImpl(this.sockets, this.operator.volatile);
69
72
  }
70
73
  compress(value) {
71
- return new ArkosBroadcastOperatorImpl(this.socket, this.operator.compress(value));
74
+ return new ArkosBroadcastOperatorImpl(this.sockets, this.operator.compress(value));
72
75
  }
73
76
  timeout(ms) {
74
- return new ArkosBroadcastOperatorImpl(this.socket, this.operator.timeout(ms));
77
+ return new ArkosBroadcastOperatorImpl(this.sockets, this.operator.timeout(ms));
75
78
  }
76
79
  async emitWithAck(event, ...args) {
77
80
  const [data, ...rest] = args;
81
+ if (!this.operator?.emitWithAck)
82
+ throw Error("emitWithAck is not supported on this target — call .timeout(ms) first if targeting a Namespace.");
78
83
  return this.operator.emitWithAck(event, injectMeta(data), ...rest);
79
84
  }
80
85
  }
@@ -127,7 +132,7 @@ export function mountArkosSocketExtensions(socket) {
127
132
  return originalEmitWithAck(event, injectMeta(data), ...rest);
128
133
  };
129
134
  socket.to = function (room) {
130
- return new ArkosBroadcastOperatorImpl(socket, originalTo(room));
135
+ return new ArkosBroadcastOperatorImpl(socket.nsp.sockets, originalTo(room));
131
136
  };
132
137
  socket.timeout = function (ms) {
133
138
  const timedSocket = originalTimeout(ms);
@@ -142,12 +147,18 @@ export function mountArkosSocketExtensions(socket) {
142
147
  Object.defineProperty(socket, "broadcast", {
143
148
  get() {
144
149
  const operator = broadcastDescriptor.get.call(socket);
145
- return new ArkosBroadcastOperatorImpl(socket, operator);
150
+ return new ArkosBroadcastOperatorImpl(socket.nsp.sockets, operator);
146
151
  },
147
152
  configurable: true,
148
153
  });
149
- socket.user = function (userId) {
150
- const target = new ArkosBroadcastOperatorImpl(socket, socket.nsp.to(`arkos::user:${userId}`));
154
+ socket.user = applyUserTarget(socket.nsp.sockets, socket.nsp);
155
+ socket.retry = function (times, baseDelay = 1000, multiplier = 2) {
156
+ return new ArkosRetryTargetImpl(socket, times, baseDelay, multiplier);
157
+ };
158
+ }
159
+ function applyUserTarget(sockets, operator) {
160
+ return (userId) => {
161
+ const target = new ArkosBroadcastOperatorImpl(sockets, operator.to(`arkos::user:${userId}`));
151
162
  target.activeRooms = async () => {
152
163
  const sockets = await target.fetchSockets();
153
164
  const roomsSet = new Set();
@@ -161,8 +172,5 @@ export function mountArkosSocketExtensions(socket) {
161
172
  };
162
173
  return target;
163
174
  };
164
- socket.retry = function (times, baseDelay = 1000, multiplier = 2) {
165
- return new ArkosRetryTargetImpl(socket, times, baseDelay, multiplier);
166
- };
167
175
  }
168
176
  //# sourceMappingURL=socket-extensions.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"socket-extensions.js","sourceRoot":"","sources":["../../../../src/components/arkos-gateway/socket-extensions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAShC,SAAS,UAAU,CACjB,IAAO;IAEP,OAAO;QACL,GAAI,IAAY;QAChB,KAAK,EAAE,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE;KAChD,CAAC;AACJ,CAAC;AAED,SAAS,oBAAoB,CAC3B,MAAmB,EACnB,MAAyB;IAEzB,MAAM,GAAG,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;IACtD,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,KAAK,MAAM,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC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AAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YACxD,OAAO,IAAI,0BAA0B,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAC1D,CAAC;QACD,YAAY,EAAE,IAAI;KACnB,CAAC,CAAC;IAEH,MAAM,CAAC,IAAI,GAAG,UAAU,MAAc;QACpC,MAAM,MAAM,GAAG,IAAI,0BAA0B,CAC3C,MAAM,EACN,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,eAAe,MAAM,EAAE,CAAC,CACb,CAAC;QAE5B,MAAM,CAAC,WAAW,GAAG,KAAK,IAAI,EAAE;YAC9B,MAAM,OAAO,GAAG,MACd,MACD,CAAC,YAAY,EAAE,CAAC;YACjB,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAU,CAAC;YACnC,KAAK,MAAM,CAAC,IAAI,OAAgB,EAAE,CAAC;gBACjC,KAAK,MAAM,IAAI,IAAI,CAAC,CAAC,KAAK,EAAE,CAAC;oBAC3B,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC;wBAAE,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;gBAC3D,CAAC;YACH,CAAC;YACD,OAAO,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAC9B,CAAC,CAAC;QAEF,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IACF,MAAM,CAAC,KAAK,GAAG,UACb,KAAa,EACb,YAAoB,IAAI,EACxB,aAAqB,CAAC;QAEtB,OAAO,IAAI,oBAAoB,CAAC,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,UAAU,CAAC,CAAC;IACxE,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { uuidv7 } from \"uuidv7\";\nimport {\n ArkosBroadcastOperator,\n ArkosRetryTarget,\n ArkosSocket,\n ArkosUserTarget,\n} from \"./types\";\nimport { BroadcastOperator } from \"socket.io\";\n\nfunction injectMeta<T>(\n data: T\n): T & { _meta: { mid: string; timestamp: number } } {\n return {\n ...(data as any),\n _meta: { mid: uuidv7(), timestamp: Date.now() },\n };\n}\n\nfunction resolveUserSocketIds(\n socket: ArkosSocket,\n userId: string | string[]\n): string[] {\n const ids = Array.isArray(userId) ? userId : [userId];\n const result: string[] = [];\n for (const [id, s] of socket.nsp.sockets) {\n for (const uid of ids) {\n if (s.rooms.has(`arkos::user:${uid}`)) {\n result.push(id);\n break;\n }\n }\n }\n return result;\n}\n\nexport class ArkosBroadcastOperatorImpl {\n constructor(\n private readonly socket: ArkosSocket,\n private readonly operator: BroadcastOperator<any, any>\n ) {\n const instance = Object.create(operator) as this;\n instance.emit = this.emit.bind(this);\n instance.emitWithAck = this.emitWithAck.bind(this);\n instance.except = this.except.bind(this);\n instance.compress = this.compress.bind(this);\n instance.timeout = this.timeout.bind(this);\n instance.users = this.users.bind(this);\n Object.defineProperty(instance, \"volatile\", {\n get: () => this.volatile,\n configurable: true,\n });\n return instance;\n }\n\n /**\n * Returns all unique user IDs currently in the target room(s).\n * Uses the internal `arkos::user:` room convention to map sockets to users.\n *\n * @example\n * const users = await socket.to(\"room-123\").users()\n * console.log(users) // ['user-1', 'user-2']\n */\n async users(): Promise<string[]> {\n const sockets = await this.operator.fetchSockets();\n const userIds = new Set<string>();\n for (const s of sockets) {\n for (const room of s.rooms) {\n if (room.startsWith(\"arkos::user:\")) {\n userIds.add(room.slice(\"arkos::user:\".length));\n break; // each socket has at most one user room\n }\n }\n }\n return Array.from(userIds);\n }\n\n /**\n * Excludes sockets from the broadcast.\n * Accepts a room name, socket ID, array of rooms/IDs, or `{ user: string | string[] }`\n * to exclude all sockets belonging to one or more users.\n *\n * @example\n * socket.to(\"room-101\").except(\"room-102\").emit(\"foo\", data)\n * socket.broadcast.except({ user: userId }).emit(\"foo\", data)\n * socket.broadcast.except({ user: [id1, id2] }).emit(\"foo\", data)\n */\n except(room: string | string[] | { user: string | string[] }) {\n if (typeof room === \"string\" || Array.isArray(room)) {\n return new ArkosBroadcastOperatorImpl(\n this.socket,\n this.operator.except(room)\n );\n }\n const socketIds = resolveUserSocketIds(this.socket, room.user);\n let op = this.operator;\n for (const id of socketIds) op = op.except(id);\n return new ArkosBroadcastOperatorImpl(this.socket, op);\n }\n\n /**\n * Emits an event to the target. `_meta` (`mid` + `timestamp`) is injected automatically.\n *\n * @example\n * socket.to(\"room-101\").emit(\"message\", { text: \"hello\" })\n * socket.broadcast.emit(\"announcement\", data)\n */\n emit(event: string, ...args: any[]): boolean {\n const [data, ...rest] = args;\n return this.operator.emit(event, injectMeta(data), ...rest);\n }\n\n /**\n * Sets the volatile flag — the event may be dropped if the client is not ready.\n * Useful for high-frequency non-critical events like cursor positions or typing indicators.\n *\n * @example\n * socket.to(\"room-101\").volatile.emit(\"cursor\", position)\n */\n get volatile() {\n return new ArkosBroadcastOperatorImpl(this.socket, this.operator.volatile);\n }\n\n /**\n * Sets the compress flag for the next emission.\n *\n * @example\n * socket.broadcast.compress(false).emit(\"ping\", data)\n */\n compress(value: boolean) {\n return new ArkosBroadcastOperatorImpl(\n this.socket,\n this.operator.compress(value)\n );\n }\n\n /**\n * Sets a timeout in milliseconds for `emitWithAck`.\n * Rejects the promise if no client acknowledges within the given delay.\n *\n * @example\n * socket.to(\"room-101\").timeout(3000).emitWithAck(\"confirm\", data)\n */\n timeout(ms: number) {\n return new ArkosBroadcastOperatorImpl(\n this.socket,\n this.operator.timeout(ms)\n );\n }\n\n /**\n * Emits an event and waits for acknowledgements from all matched clients.\n * `_meta` is injected automatically. Use `.timeout(ms)` to avoid hanging indefinitely.\n *\n * @example\n * const responses = await socket.to(\"room-101\").timeout(3000).emitWithAck(\"confirm\", data)\n */\n async emitWithAck(event: string, ...args: any[]): Promise<any[]> {\n const [data, ...rest] = args;\n return this.operator.emitWithAck(event, injectMeta(data), ...rest);\n }\n}\n\nclass ArkosRetryTargetImpl implements ArkosRetryTarget {\n private timeoutMs?: number;\n\n constructor(\n private readonly socket: ArkosSocket,\n private readonly maxRetries: number,\n private readonly baseDelay: number,\n private readonly multiplier: number\n ) {}\n\n /**\n * Sets a timeout in milliseconds applied on each `emitWithAck` attempt.\n *\n * @example\n * socket.retry(3).timeout(5000).emitWithAck(\"event\", data)\n */\n timeout(ms: number) {\n this.timeoutMs = ms;\n return this;\n }\n\n /**\n * Emits with ack and exponential backoff retry. `_meta` is injected automatically.\n * Each attempt respects the `.timeout(ms)` if set.\n *\n * @example\n * const ack = await socket.retry(3).timeout(5000).emitWithAck(\"confirm\", data)\n */\n async emitWithAck(event: string, data: any, ...rest: any[]): Promise<any> {\n const patched = injectMeta(data);\n return this.attemptEmitWithAck(event, patched, rest, 0);\n }\n\n private async attemptEmitWithAck(\n event: string,\n data: any,\n rest: any[],\n attempt: number\n ): Promise<any> {\n try {\n const s = this.timeoutMs\n ? this.socket.timeout(this.timeoutMs)\n : this.socket;\n return await s.emitWithAck(event, data, ...rest);\n } catch (err) {\n if (attempt < this.maxRetries) {\n const delay = Math.pow(this.multiplier, attempt) * this.baseDelay;\n await new Promise((r) => setTimeout(r, delay));\n return this.attemptEmitWithAck(event, data, rest, attempt + 1);\n }\n throw err;\n }\n }\n}\n\n/**\n * Mounts Arkos socket extensions and patches emit methods for automatic `_meta` injection.\n * Called once by the gateway at connection time, right after injecting `_arkos`.\n *\n * Patches: `emit`, `emitWithAck`, `to()`, `timeout()`, `broadcast`\n * Mounts: `user()`, `peer()`, `retry()`\n *\n * @internal\n * @since 1.7.0-canary.29\n */\nexport function mountArkosSocketExtensions(socket: ArkosSocket): void {\n const originalEmit = socket.emit.bind(socket);\n const originalEmitWithAck = socket.emitWithAck.bind(socket);\n const originalTo = socket.to.bind(socket);\n const originalTimeout = socket.timeout.bind(socket);\n\n socket.emit = function (event: string, data?: any, ...rest: any[]) {\n return originalEmit(event, injectMeta(data), ...rest);\n };\n\n socket.emitWithAck = function (event: string, data?: any, ...rest: any[]) {\n return originalEmitWithAck(event, injectMeta(data), ...rest);\n };\n\n socket.to = function (room: string | string[]) {\n return new ArkosBroadcastOperatorImpl(\n socket,\n originalTo(room)\n ) as any as ArkosBroadcastOperator;\n };\n\n socket.timeout = function (ms: number) {\n const timedSocket = originalTimeout(ms);\n const originalTimedEmitWithAck = timedSocket.emitWithAck.bind(timedSocket);\n timedSocket.emitWithAck = function (\n event: string,\n data?: any,\n ...rest: any[]\n ) {\n const result = originalTimedEmitWithAck(event, injectMeta(data), ...rest);\n return result;\n };\n return timedSocket;\n };\n\n const broadcastDescriptor = Object.getOwnPropertyDescriptor(\n Object.getPrototypeOf(socket),\n \"broadcast\"\n );\n\n Object.defineProperty(socket, \"broadcast\", {\n get() {\n const operator = broadcastDescriptor!.get!.call(socket);\n return new ArkosBroadcastOperatorImpl(socket, operator);\n },\n configurable: true,\n });\n\n socket.user = function (userId: string): ArkosUserTarget {\n const target = new ArkosBroadcastOperatorImpl(\n socket,\n socket.nsp.to(`arkos::user:${userId}`)\n ) as any as ArkosUserTarget;\n\n target.activeRooms = async () => {\n const sockets = await (\n target as unknown as ArkosBroadcastOperator\n ).fetchSockets();\n const roomsSet = new Set<string>();\n for (const s of sockets as any[]) {\n for (const room of s.rooms) {\n if (!room.startsWith(\"arkos::user:\")) roomsSet.add(room);\n }\n }\n return Array.from(roomsSet);\n };\n\n return target;\n };\n socket.retry = function (\n times: number,\n baseDelay: number = 1000,\n multiplier: number = 2\n ): ArkosRetryTarget {\n return new ArkosRetryTargetImpl(socket, times, baseDelay, multiplier);\n };\n}\n"]}
1
+ {"version":3,"file":"socket-extensions.js","sourceRoot":"","sources":["../../../../src/components/arkos-gateway/socket-extensions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAUhC,SAAS,UAAU,CACjB,IAAO;IAEP,OAAO;QACL,GAAI,IAAY;QAChB,KAAK,EAAE,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE;KAChD,CAAC;AACJ,CAAC;AAED,SAAS,oBAAoB,CAC3B,OAA4B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;YAC9B,MAAM,OAAO,GAAG,MACd,MACD,CAAC,YAAY,EAAE,CAAC;YACjB,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAU,CAAC;YACnC,KAAK,MAAM,CAAC,IAAI,OAAgB,EAAE,CAAC;gBACjC,KAAK,MAAM,IAAI,IAAI,CAAC,CAAC,KAAK,EAAE,CAAC;oBAC3B,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC;wBAAE,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;gBAC3D,CAAC;YACH,CAAC;YACD,OAAO,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAC9B,CAAC,CAAC;QAEF,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AAEJ,CAAC","sourcesContent":["import { uuidv7 } from \"uuidv7\";\nimport {\n ArkosBroadcastOperator,\n ArkosEmitTarget,\n ArkosRetryTarget,\n ArkosSocket,\n ArkosUserTarget,\n} from \"./types\";\nimport { Socket } from \"socket.io\";\n\nfunction injectMeta<T>(\n data: T\n): T & { _meta: { mid: string; timestamp: number } } {\n return {\n ...(data as any),\n _meta: { mid: uuidv7(), timestamp: Date.now() },\n };\n}\n\nfunction resolveUserSocketIds(\n sockets: Map<string, Socket>,\n userId: string | string[]\n): string[] {\n const ids = Array.isArray(userId) ? userId : [userId];\n\n const result: string[] = [];\n for (const [id, s] of sockets) {\n for (const uid of ids) {\n if (s.rooms.has(`arkos::user:${uid}`)) {\n result.push(id);\n break;\n }\n }\n }\n return result;\n}\n\nexport class ArkosBroadcastOperatorImpl {\n constructor(\n private readonly sockets: Map<string, Socket>,\n private readonly operator: ArkosEmitTarget\n ) {\n const instance = Object.create(operator) as this;\n instance.emit = this.emit.bind(this);\n instance.emitWithAck = this.emitWithAck.bind(this);\n instance.except = this.except.bind(this);\n instance.compress = this.compress.bind(this);\n instance.timeout = this.timeout.bind(this);\n instance.users = this.users.bind(this);\n Object.defineProperty(instance, \"volatile\", {\n get: () => this.volatile,\n configurable: true,\n });\n return instance;\n }\n\n user(userId: string) {\n return applyUserTarget(this.sockets, this.operator)(userId)\n }\n\n /**\n * Returns all unique user IDs currently in the target room(s).\n * Uses the internal `arkos::user:` room convention to map sockets to users.\n *\n * @example\n * const users = await socket.to(\"room-123\").users()\n * console.log(users) // ['user-1', 'user-2']\n */\n async users(): Promise<string[]> {\n const sockets = await this.operator.fetchSockets();\n const userIds = new Set<string>();\n for (const s of sockets) {\n for (const room of s.rooms) {\n if (room.startsWith(\"arkos::user:\")) {\n userIds.add(room.slice(\"arkos::user:\".length));\n break; // each socket has at most one user room\n }\n }\n }\n return Array.from(userIds);\n }\n\n /**\n * Excludes sockets from the broadcast.\n * Accepts a room name, socket ID, array of rooms/IDs, or `{ user: string | string[] }`\n * to exclude all sockets belonging to one or more users.\n *\n * @example\n * socket.to(\"room-101\").except(\"room-102\").emit(\"foo\", data)\n * socket.broadcast.except({ user: userId }).emit(\"foo\", data)\n * socket.broadcast.except({ user: [id1, id2] }).emit(\"foo\", data)\n */\n except(room: string | string[] | { user: string | string[] }) {\n if (typeof room === \"string\" || Array.isArray(room)) {\n return new ArkosBroadcastOperatorImpl(\n this.sockets,\n this.operator.except(room)\n );\n }\n const socketIds = resolveUserSocketIds(this.sockets, room.user);\n let op = this.operator;\n for (const id of socketIds) op = op.except(id);\n return new ArkosBroadcastOperatorImpl(this.sockets, op);\n }\n\n /**\n * Emits an event to the target. `_meta` (`mid` + `timestamp`) is injected automatically.\n *\n * @example\n * socket.to(\"room-101\").emit(\"message\", { text: \"hello\" })\n * socket.broadcast.emit(\"announcement\", data)\n */\n emit(event: string, ...args: any[]): boolean {\n const [data, ...rest] = args;\n return this.operator.emit(event, injectMeta(data), ...rest);\n }\n\n /**\n * Sets the volatile flag — the event may be dropped if the client is not ready.\n * Useful for high-frequency non-critical events like cursor positions or typing indicators.\n *\n * @example\n * socket.to(\"room-101\").volatile.emit(\"cursor\", position)\n */\n get volatile() {\n return new ArkosBroadcastOperatorImpl(this.sockets, this.operator.volatile);\n }\n\n /**\n * Sets the compress flag for the next emission.\n *\n * @example\n * socket.broadcast.compress(false).emit(\"ping\", data)\n */\n compress(value: boolean) {\n return new ArkosBroadcastOperatorImpl(\n this.sockets,\n this.operator.compress(value)\n );\n }\n\n /**\n * Sets a timeout in milliseconds for `emitWithAck`.\n * Rejects the promise if no client acknowledges within the given delay.\n *\n * @example\n * socket.to(\"room-101\").timeout(3000).emitWithAck(\"confirm\", data)\n */\n timeout(ms: number) {\n return new ArkosBroadcastOperatorImpl(\n this.sockets,\n this.operator.timeout(ms)\n );\n }\n\n /**\n * Emits an event and waits for acknowledgements from all matched clients.\n * `_meta` is injected automatically. Use `.timeout(ms)` to avoid hanging indefinitely.\n *\n * @example\n * const responses = await socket.to(\"room-101\").timeout(3000).emitWithAck(\"confirm\", data)\n */\n async emitWithAck(event: string, ...args: any[]): Promise<any[]> {\n const [data, ...rest] = args;\n if (!this.operator?.emitWithAck)\n throw Error(\"emitWithAck is not supported on this target — call .timeout(ms) first if targeting a Namespace.\")\n\n return this.operator.emitWithAck!(event, injectMeta(data), ...rest);\n\n }\n}\n\nclass ArkosRetryTargetImpl implements ArkosRetryTarget {\n private timeoutMs?: number;\n\n constructor(\n private readonly socket: ArkosSocket,\n private readonly maxRetries: number,\n private readonly baseDelay: number,\n private readonly multiplier: number\n ) { }\n\n /**\n * Sets a timeout in milliseconds applied on each `emitWithAck` attempt.\n *\n * @example\n * socket.retry(3).timeout(5000).emitWithAck(\"event\", data)\n */\n timeout(ms: number) {\n this.timeoutMs = ms;\n return this;\n }\n\n /**\n * Emits with ack and exponential backoff retry. `_meta` is injected automatically.\n * Each attempt respects the `.timeout(ms)` if set.\n *\n * @example\n * const ack = await socket.retry(3).timeout(5000).emitWithAck(\"confirm\", data)\n */\n async emitWithAck(event: string, data: any, ...rest: any[]): Promise<any> {\n const patched = injectMeta(data);\n return this.attemptEmitWithAck(event, patched, rest, 0);\n }\n\n private async attemptEmitWithAck(\n event: string,\n data: any,\n rest: any[],\n attempt: number\n ): Promise<any> {\n try {\n const s = this.timeoutMs\n ? this.socket.timeout(this.timeoutMs)\n : this.socket;\n return await s.emitWithAck(event, data, ...rest);\n } catch (err) {\n if (attempt < this.maxRetries) {\n const delay = Math.pow(this.multiplier, attempt) * this.baseDelay;\n await new Promise((r) => setTimeout(r, delay));\n return this.attemptEmitWithAck(event, data, rest, attempt + 1);\n }\n throw err;\n }\n }\n}\n\n/**\n * Mounts Arkos socket extensions and patches emit methods for automatic `_meta` injection.\n * Called once by the gateway at connection time, right after injecting `_arkos`.\n *\n * Patches: `emit`, `emitWithAck`, `to()`, `timeout()`, `broadcast`\n * Mounts: `user()`, `peer()`, `retry()`\n *\n * @internal\n * @since 1.7.0-canary.29\n */\nexport function mountArkosSocketExtensions(socket: ArkosSocket): void {\n const originalEmit = socket.emit.bind(socket);\n const originalEmitWithAck = socket.emitWithAck.bind(socket);\n const originalTo = socket.to.bind(socket);\n const originalTimeout = socket.timeout.bind(socket);\n\n socket.emit = function(event: string, data?: any, ...rest: any[]) {\n return originalEmit(event, injectMeta(data), ...rest);\n };\n\n socket.emitWithAck = function(event: string, data?: any, ...rest: any[]) {\n return originalEmitWithAck(event, injectMeta(data), ...rest);\n };\n\n socket.to = function(room: string | string[]) {\n return new ArkosBroadcastOperatorImpl(\n socket.nsp.sockets,\n originalTo(room)\n ) as any as ArkosBroadcastOperator;\n };\n\n socket.timeout = function(ms: number) {\n const timedSocket = originalTimeout(ms);\n const originalTimedEmitWithAck = timedSocket.emitWithAck.bind(timedSocket);\n timedSocket.emitWithAck = function(\n event: string,\n data?: any,\n ...rest: any[]\n ) {\n const result = originalTimedEmitWithAck(event, injectMeta(data), ...rest);\n return result;\n };\n return timedSocket;\n };\n\n const broadcastDescriptor = Object.getOwnPropertyDescriptor(\n Object.getPrototypeOf(socket),\n \"broadcast\"\n );\n\n Object.defineProperty(socket, \"broadcast\", {\n get() {\n const operator = broadcastDescriptor!.get!.call(socket);\n return new ArkosBroadcastOperatorImpl(socket.nsp.sockets, operator);\n },\n configurable: true,\n });\n\n socket.user = applyUserTarget(socket.nsp.sockets, socket.nsp)\n\n\n socket.retry = function(\n times: number,\n baseDelay: number = 1000,\n multiplier: number = 2\n ): ArkosRetryTarget {\n return new ArkosRetryTargetImpl(socket, times, baseDelay, multiplier);\n };\n}\n\nfunction applyUserTarget(sockets: Map<string, Socket>, operator: { to: Function }) {\n return (userId: string): ArkosUserTarget => {\n const target = new ArkosBroadcastOperatorImpl(\n sockets,\n operator.to(`arkos::user:${userId}`)\n ) as any as ArkosUserTarget;\n\n target.activeRooms = async () => {\n const sockets = await (\n target as unknown as ArkosBroadcastOperator\n ).fetchSockets();\n const roomsSet = new Set<string>();\n for (const s of sockets as any[]) {\n for (const room of s.rooms) {\n if (!room.startsWith(\"arkos::user:\")) roomsSet.add(room);\n }\n }\n return Array.from(roomsSet);\n };\n\n return target;\n };\n\n}\n\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/components/arkos-gateway/types.ts"],"names":[],"mappings":"AA8dA,MAAM,OAAO,sBAAsB;CAAG","sourcesContent":["import { BroadcastOperator, Socket } from \"socket.io\";\nimport { User } from \"../../types\";\nimport { DefaultEventsMap } from \"socket.io\";\nimport { Validator } from \"../../types/validation/validator\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport { DetailedAccessControlRule } from \"../../types/auth\";\n///@ts-ignore\nimport {\n AllButLast,\n DecorateAcknowledgements,\n DecorateAcknowledgementsWithMultipleResponses,\n EventNames,\n EventNamesWithAck,\n EventNamesWithError,\n EventParams,\n FirstNonErrorArg,\n Last,\n ///@ts-ignore\n} from \"socket.io/dist/typed-events\";\n\nexport interface EventsMap {\n [event: string]: any;\n}\n\nexport interface ArkosSocket<\n ListenEvents extends EventsMap = DefaultEventsMap,\n EmitEvents extends EventsMap = ListenEvents,\n ServerSideEvents extends EventsMap = DefaultEventsMap,\n SocketData extends Validator = any,\n SocketLocals extends Record<string, any> = Record<string, any>,\n> extends Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData> {\n /**\n * Populated by Arkos after successful authentication on connection.\n * Available in all event handlers when `authentication: true` on the gateway.\n */\n currentUser?: User;\n\n /**\n * Populated by Arkos after successful validation.\n * Typed to the event's validation schema when using TypeScript.\n */\n data: SocketData;\n\n /** User access token. */\n accessToken?: string;\n\n /**\n * Metadata from the incoming message, extracted from `_meta` by Arkos.\n *\n * - `mid`: Unique message ID used for deduplication.\n * - `timestamp`: When the message was sent by the client.\n */\n meta?: {\n mid?: string;\n timestamp?: string | number | Date;\n };\n\n /**\n * Per-event local storage, scoped to the current event pipeline.\n * Use to pass data between pipes and the event handler — like Express's `res.locals`.\n * Reset automatically on each event.\n *\n * @example\n * chatGateway.pipe((socket, data) => {\n * socket.locals.enriched = enrichUser(socket.currentUser)\n * })\n *\n * chatGateway.on({ event: \"send_message\" }, (socket, data) => {\n * console.log(socket.locals.enriched)\n * })\n */\n locals?: SocketLocals;\n\n /**\n * Internal Arkos context injected by the gateway at connection time.\n *\n * @internal\n */\n _arkos: {\n store: ArkosGatewayStore;\n gatewayConfig: ArkosGatewayConfig;\n };\n\n /**\n * Targets all active socket connections of a user by their user ID.\n * Uses the internal `arkos::user:{userId}` room convention.\n *\n * Supports emit, management, and exclusion operations across all of the\n * user's active connections.\n *\n * @example\n * socket.user(userId).emit(\"notification\", data)\n * socket.user(userId).except({ user: otherUserId }).emit(\"sync\", data)\n * const sockets = await socket.user(userId).fetchSockets()\n * const online = await socket.user(userId).isOnline()\n *\n * @since 1.7.0-canary.29\n */\n user(userId: string): ArkosUserTarget;\n\n /**\n * Wraps the next `emit` or `emitWithAck` with exponential backoff retry logic.\n * Chain `.timeout(ms)` before `.emitWithAck()` as usual.\n *\n * @example\n * socket.retry(3).emit(\"event\", data)\n * socket.retry(3).timeout(5000).emitWithAck(\"event\", data)\n *\n * @since 1.7.0-canary.29\n */\n retry(\n times: number,\n initialDelay?: number,\n multiplier?: number\n ): ArkosRetryTarget;\n\n /**\n * Emits an event to this client.\n * Arkos automatically injects `_meta` (`mid` + `timestamp`) into every outgoing payload\n * for client-side deduplication and freshness checks.\n *\n * @example\n * socket.emit(\"message\", { text: \"hello\" })\n * socket.emit(\"notification\", { title: \"New order\" })\n */\n emit<Ev extends EventNames<EmitEvents>>(\n ev: Ev,\n ...args: EventParams<EmitEvents, Ev>\n ): true;\n\n /**\n * Emits an event and waits for an acknowledgement from the client.\n * Arkos injects `_meta` automatically. Use `.timeout(ms)` to avoid hanging indefinitely.\n *\n * @example\n * const response = await socket.timeout(5000).emitWithAck(\"confirm\", data)\n */\n emitWithAck<Ev extends EventNamesWithAck<EmitEvents>>(\n ev: Ev,\n ...args: AllButLast<EventParams<EmitEvents, Ev>>\n ): Promise<FirstNonErrorArg<Last<EventParams<EmitEvents, Ev>>>>;\n\n /**\n * Targets a room when broadcasting — excludes the sender.\n * Returns an {@link ArkosBroadcastOperator} with enhanced `.except({ user })` support\n * and automatic `_meta` injection on every `.emit()`.\n *\n * @example\n * socket.to(\"room-101\").emit(\"message\", data)\n * socket.to(\"room-101\").except({ user: userId }).emit(\"message\", data)\n * socket.to(\"room-101\").volatile.emit(\"typing\", data)\n * await socket.to(\"room-101\").timeout(3000).emitWithAck(\"confirm\", data)\n *\n * @since 1.7.0-canary.29\n */\n to(\n room: string | string[]\n ): ArkosBroadcastOperator<\n DecorateAcknowledgementsWithMultipleResponses<EmitEvents>,\n SocketData\n > &\n BroadcastOperator<EmitEvents, SocketData>;\n /**\n * Broadcasts to all connected clients except the sender.\n * Returns an {@link ArkosBroadcastOperator} with enhanced `.except({ user })` support\n * and automatic `_meta` injection on every `.emit()`.\n *\n * @example\n * socket.broadcast.emit(\"announcement\", data)\n * socket.broadcast.except({ user: userId }).emit(\"announcement\", data)\n * socket.broadcast.volatile.emit(\"ping\", data)\n *\n * @since 1.7.0-canary.29\n */\n get broadcast(): ArkosBroadcastOperator<\n DecorateAcknowledgementsWithMultipleResponses<EmitEvents>,\n SocketData\n > &\n BroadcastOperator<EmitEvents, SocketData>;\n}\n\n/**\n * Enhanced broadcast/room target returned by `socket.to()` and `socket.broadcast`.\n * Extends the native `BroadcastOperator` with `{ user }` exclusion support\n * and automatic `_meta` injection on emit.\n *\n * @since 1.7.0-canary.29\n */\nexport interface ArkosBroadcastOperator<\n EmitEvents extends EventsMap = DefaultEventsMap,\n SocketData extends Validator = any,\n> extends BroadcastOperator<EmitEvents, SocketData> {\n /**\n * Exclude sockets from the broadcast.\n * Accepts a room name, socket ID, or `{ user: string | string[] }` to exclude\n * all sockets belonging to one or more users.\n *\n * @example\n * socket.to(\"room-101\").except(\"room-102\").emit(\"foo\", data)\n * socket.broadcast.except({ user: userId }).emit(\"foo\", data)\n * socket.broadcast.except({ user: [userId1, userId2] }).emit(\"foo\", data)\n */\n except(\n room: string | string[] | { user: string | string[] }\n ): ArkosBroadcastOperator<EmitEvents, SocketData>;\n\n /**\n * Emits to all clients,`_meta` is injected automatically.\n *\n * @example\n * // the “foo” event will be broadcast to all connected clients\n * io.emit(\"foo\", \"bar\");\n *\n * // the “foo” event will be broadcast to all connected clients in the “room-101” room\n * io.to(\"room-101\").emit(\"foo\", \"bar\");\n *\n * // with an acknowledgement expected from all connected clients\n * io.timeout(1000).emit(\"some-event\", (err, responses) => {\n * if (err) {\n * // some clients did not acknowledge the event in the given delay\n * } else {\n * console.log(responses); // one response per client\n * }\n * });\n *\n * @return Always true\n */\n emit<Ev extends EventNames<EmitEvents>>(\n ev: Ev,\n ...args: EventParams<EmitEvents, Ev>\n ): true;\n\n /** Chain volatile flag — event may be lost if client is not ready. */\n get volatile(): ArkosBroadcastOperator<EmitEvents, SocketData>;\n\n /** Chain compress flag. */\n compress(value: boolean): ArkosBroadcastOperator<EmitEvents, SocketData>;\n\n /** Chain timeout for `emitWithAck`. */\n timeout(\n ms: number\n ): ArkosBroadcastOperator<DecorateAcknowledgements<EmitEvents>, SocketData>;\n\n /**\n * Emits an event and waits for an acknowledgement from all clients.\n * `_meta` is injected automatically\n * @example\n * try {\n * const responses = await io.timeout(1000).emitWithAck(\"some-event\");\n * console.log(responses); // one response per client\n * } catch (e) {\n * // some clients did not acknowledge the event in the given delay\n * }\n *\n * @return a Promise that will be fulfilled when all clients have acknowledged the event\n */\n emitWithAck<Ev extends EventNamesWithError<EmitEvents>>(\n ev: Ev,\n ...args: AllButLast<EventParams<EmitEvents, Ev>>\n ): Promise<FirstNonErrorArg<Last<EventParams<EmitEvents, Ev>>>>;\n /**\n * Returns all unique user IDs currently in the target room(s).\n *\n * @example\n * const users = await socket.to(\"room-123\").users()\n */\n users(): Promise<string[]>;\n}\n\n/**\n * Returned by `socket.retry(n)`. Wraps `emit` and `emitWithAck`\n * with exponential backoff. Chain `.timeout(ms)` before `.emitWithAck()` as usual.\n *\n * @since 1.7.0-canary.29\n */\nexport interface ArkosRetryTarget {\n /** Emit with ack and retry. `_meta` is injected automatically. */\n emitWithAck(event: string, data: any, ...rest: any[]): Promise<any>;\n\n /**\n * Chain a timeout before `emitWithAck`.\n *\n * @example\n * socket.retry(3).timeout(5000).emitWithAck(\"event\", data)\n */\n timeout(ms: number): ArkosRetryTarget;\n}\n\n/**\n * Returned by `socket.user(userId)`.\n * Targets all active socket connections of a user.\n *\n * @since 1.7.0-canary.29\n */\nexport interface ArkosUserTarget extends ArkosBroadcastOperator {\n /**\n * Returns all active rooms for this user.\n *\n * @example\n * const rooms = await socket.user(userId).activeRooms()\n * console.log(rooms.length) // number of active tabs/connections\n */\n activeRooms(): Promise<string[]>;\n}\n\nexport type ArkosGatewayPipe = (\n socket: ArkosSocket,\n data: any\n) => void | Promise<void>;\n\nexport type ArkosGatewayEventConfig<TSchema extends Validator = any> = {\n /** The Socket.io event name to listen for. */\n event: string;\n\n /** Zod schema or class-validator DTO to validate the incoming event payload. */\n validation?: TSchema;\n\n /** Per-event rate limiting. Overrides gateway-level `rateLimit` for this event. */\n rateLimit?: Partial<RateLimitOptions> | false;\n\n /**\n * Authorization configuration.\n *\n * @remarks Gateway `authentication` must NOT be `false` or this throws at registration time.\n */\n authorization?: {\n resource: string;\n action: string;\n rule?: DetailedAccessControlRule | string[] | \"*\";\n };\n\n /**\n * When `true`, Arkos automatically calls `ack({ success: true })` after the handler\n * finishes, unless the handler already called ack manually.\n */\n ack?: boolean;\n\n /** Disables this event handler without removing it. */\n disabled?: boolean;\n\n /**\n * Maximum age in milliseconds for incoming messages.\n * Requires `data._meta.timestamp`. Events older than this are rejected.\n */\n maxAge?: number;\n\n /** Per-event deduplication. Overrides gateway-level `dedup`. */\n dedup?:\n | {\n /** @default true */\n enabled?: boolean;\n /** Time-to-live in seconds for the dedup key. @default 3600 */\n ttl?: number;\n }\n | false;\n};\n\nexport type ArkosGatewayAckFn = (response: any) => void;\n\nexport type ArkosGatewayHandler<TData = any> = (\n socket: ArkosSocket,\n data: TData,\n ack?: ArkosGatewayAckFn\n) => void | Promise<void>;\n\nexport type ArkosGatewayEventEntry = {\n config: ArkosGatewayEventConfig;\n handler: ArkosGatewayHandler;\n pipes: ArkosGatewayPipe[];\n};\n\nexport type ArkosGatewayConnectionHandler = (\n socket: ArkosSocket\n) => void | Promise<void>;\n\nexport type ArkosGatewayHookHandler =\n | ArkosGatewayConnectionHandler\n | ArkosGatewayErrorHandler;\n\nexport type ArkosGatewayErrorHandler = (\n error: any,\n socket: ArkosSocket\n) => void | Promise<void>;\n\nexport type ArkosGatewayHookType = \"connection\" | \"disconnect\" | \"error\";\n\nexport type ArkosGatewayConfig = {\n /**\n * Socket.io namespace for this gateway.\n *\n * @example\n * name: \"/chat\"\n */\n name: string;\n\n /**\n * When `true`, Arkos runs auth middleware on connection and populates `socket.currentUser`.\n * Unauthenticated sockets are rejected.\n *\n * @default false\n */\n authentication?: boolean;\n\n /** Gateway-level rate limiting, applied per socket. Can be overridden per event. */\n rateLimit?: Partial<RateLimitOptions>;\n\n /**\n * Gateway-level deduplication. Drills down to child gateways and can be overridden\n * per child or per event listener.\n */\n dedup?:\n | {\n /** @default true */\n enabled?: boolean;\n /** @default 3600 */\n ttl?: number;\n }\n | false;\n\n /**\n * Maximum age in milliseconds for incoming messages.\n * Can be overridden per event via `maxAge` in `gateway.on()`.\n */\n maxAge?: number;\n};\n\n/**\n * Options for `gateway.register()`.\n * Passed once at the root — applies to all child gateways.\n */\nexport type ArkosGatewayRegisterOptions = {\n /**\n * Unified store for rate limiting and deduplication.\n * Defaults to an in-memory store — zero config for single-instance deployments.\n * For distributed deployments plug in a Redis-backed store.\n *\n * @example\n * store: new RedisArkosStore(redis)\n */\n store?: ArkosGatewayStore;\n};\n\n/**\n * Unified store interface for rate limiting and deduplication.\n * Implement this to plug in Redis, Valkey, or any distributed store.\n *\n * @example\n * class RedisArkosStore implements ArkosGatewayStore {\n * async increment(key, windowMs) { ... }\n * async clear(prefix) { ... }\n * async has(key) { ... }\n * async set(key, ttl) { ... }\n * async setIfNotExists(key, ttl) { ... }\n * }\n */\nexport interface ArkosGatewayStore {\n /** Increment a rate limit counter. Key format: `arkos::rl:{socketId}:{event}` */\n increment(\n key: string,\n windowMs: number\n ): Promise<{ count: number; resetAt: number }>;\n\n /** Clear all rate limit entries matching a prefix. Key format: `arkos::rl:{socketId}` */\n clear(prefix: string): Promise<void>;\n\n /** Check if a dedup key exists. */\n has(key: string): Promise<boolean>;\n\n /** Store a dedup key with TTL in seconds. */\n set(key: string, ttl: number): Promise<void>;\n\n /**\n * Atomically store a dedup key only if it does not already exist.\n * Returns `true` if created (process the message), `false` if duplicate (skip).\n */\n setIfNotExists(key: string, ttl: number): Promise<boolean>;\n}\n\nexport class ArkosGatewayController {}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/components/arkos-gateway/types.ts"],"names":[],"mappings":"AA4jBA,MAAM,OAAO,sBAAsB;CAAI","sourcesContent":["import { BroadcastOperator, Socket } from \"socket.io\";\nimport { User } from \"../../types\";\nimport { DefaultEventsMap } from \"socket.io\";\nimport { Validator } from \"../../types/validation/validator\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport { DetailedAccessControlRule } from \"../../types/auth\";\n///@ts-ignore\nimport {\n AllButLast,\n DecorateAcknowledgements,\n DecorateAcknowledgementsWithMultipleResponses,\n EventNames,\n EventNamesWithAck,\n EventNamesWithError,\n EventParams,\n FirstNonErrorArg,\n Last,\n ///@ts-ignore\n} from \"socket.io/dist/typed-events\";\n\nexport interface EventsMap {\n [event: string]: any;\n}\n\nexport interface ArkosSocket<\n ListenEvents extends EventsMap = DefaultEventsMap,\n EmitEvents extends EventsMap = ListenEvents,\n ServerSideEvents extends EventsMap = DefaultEventsMap,\n SocketData extends Validator = any,\n SocketLocals extends Record<string, any> = Record<string, any>,\n> extends Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData> {\n /**\n * Populated by Arkos after successful authentication on connection.\n * Available in all event handlers when `authentication: true` on the gateway.\n */\n currentUser?: User;\n\n /**\n * Populated by Arkos after successful validation.\n * Typed to the event's validation schema when using TypeScript.\n */\n data: SocketData;\n\n /** User access token. */\n accessToken?: string;\n\n /**\n * Metadata from the incoming message, extracted from `_meta` by Arkos.\n *\n * - `mid`: Unique message ID used for deduplication.\n * - `timestamp`: When the message was sent by the client.\n */\n meta?: {\n mid?: string;\n timestamp?: string | number | Date;\n };\n\n /**\n * Per-event local storage, scoped to the current event pipeline.\n * Use to pass data between pipes and the event handler — like Express's `res.locals`.\n * Reset automatically on each event.\n *\n * @example\n * chatGateway.pipe((socket, data) => {\n * socket.locals.enriched = enrichUser(socket.currentUser)\n * })\n *\n * chatGateway.on({ event: \"send_message\" }, (socket, data) => {\n * console.log(socket.locals.enriched)\n * })\n */\n locals?: SocketLocals;\n\n /**\n * Internal Arkos context injected by the gateway at connection time.\n *\n * @internal\n */\n _arkos: {\n store: ArkosGatewayStore;\n gatewayConfig: ArkosGatewayConfig;\n };\n\n /**\n * Targets all active socket connections of a user by their user ID.\n * Uses the internal `arkos::user:{userId}` room convention.\n *\n * Supports emit, management, and exclusion operations across all of the\n * user's active connections.\n *\n * @example\n * socket.user(userId).emit(\"notification\", data)\n * socket.user(userId).except({ user: otherUserId }).emit(\"sync\", data)\n * const sockets = await socket.user(userId).fetchSockets()\n * const online = await socket.user(userId).isOnline()\n *\n * @since 1.7.0-canary.29\n */\n user(userId: string): ArkosUserTarget;\n\n /**\n * Wraps the next `emit` or `emitWithAck` with exponential backoff retry logic.\n * Chain `.timeout(ms)` before `.emitWithAck()` as usual.\n *\n * @example\n * socket.retry(3).emit(\"event\", data)\n * socket.retry(3).timeout(5000).emitWithAck(\"event\", data)\n *\n * @since 1.7.0-canary.29\n */\n retry(\n times: number,\n initialDelay?: number,\n multiplier?: number\n ): ArkosRetryTarget;\n\n /**\n * Emits an event to this client.\n * Arkos automatically injects `_meta` (`mid` + `timestamp`) into every outgoing payload\n * for client-side deduplication and freshness checks.\n *\n * @example\n * socket.emit(\"message\", { text: \"hello\" })\n * socket.emit(\"notification\", { title: \"New order\" })\n */\n emit<Ev extends EventNames<EmitEvents>>(\n ev: Ev,\n ...args: EventParams<EmitEvents, Ev>\n ): true;\n\n /**\n * Emits an event and waits for an acknowledgement from the client.\n * Arkos injects `_meta` automatically. Use `.timeout(ms)` to avoid hanging indefinitely.\n *\n * @example\n * const response = await socket.timeout(5000).emitWithAck(\"confirm\", data)\n */\n emitWithAck<Ev extends EventNamesWithAck<EmitEvents>>(\n ev: Ev,\n ...args: AllButLast<EventParams<EmitEvents, Ev>>\n ): Promise<FirstNonErrorArg<Last<EventParams<EmitEvents, Ev>>>>;\n\n /**\n * Targets a room when broadcasting — excludes the sender.\n * Returns an {@link ArkosBroadcastOperator} with enhanced `.except({ user })` support\n * and automatic `_meta` injection on every `.emit()`.\n *\n * @example\n * socket.to(\"room-101\").emit(\"message\", data)\n * socket.to(\"room-101\").except({ user: userId }).emit(\"message\", data)\n * socket.to(\"room-101\").volatile.emit(\"typing\", data)\n * await socket.to(\"room-101\").timeout(3000).emitWithAck(\"confirm\", data)\n *\n * @since 1.7.0-canary.29\n */\n to(\n room: string | string[]\n ): ArkosBroadcastOperator<\n DecorateAcknowledgementsWithMultipleResponses<EmitEvents>,\n SocketData\n > &\n BroadcastOperator<EmitEvents, SocketData>;\n /**\n * Broadcasts to all connected clients except the sender.\n * Returns an {@link ArkosBroadcastOperator} with enhanced `.except({ user })` support\n * and automatic `_meta` injection on every `.emit()`.\n *\n * @example\n * socket.broadcast.emit(\"announcement\", data)\n * socket.broadcast.except({ user: userId }).emit(\"announcement\", data)\n * socket.broadcast.volatile.emit(\"ping\", data)\n *\n * @since 1.7.0-canary.29\n */\n get broadcast(): ArkosBroadcastOperator<\n DecorateAcknowledgementsWithMultipleResponses<EmitEvents>,\n SocketData\n > &\n BroadcastOperator<EmitEvents, SocketData>;\n}\n\n/**\n * Enhanced broadcast/room target returned by `socket.to()` and `socket.broadcast`.\n * Extends the native `BroadcastOperator` with `{ user }` exclusion support\n * and automatic `_meta` injection on emit.\n *\n * @since 1.7.0-canary.29\n */\nexport interface ArkosBroadcastOperator<\n EmitEvents extends EventsMap = DefaultEventsMap,\n SocketData extends Validator = any,\n> extends BroadcastOperator<EmitEvents, SocketData> {\n /**\n * Exclude sockets from the broadcast.\n * Accepts a room name, socket ID, or `{ user: string | string[] }` to exclude\n * all sockets belonging to one or more users.\n *\n * @example\n * socket.to(\"room-101\").except(\"room-102\").emit(\"foo\", data)\n * socket.broadcast.except({ user: userId }).emit(\"foo\", data)\n * socket.broadcast.except({ user: [userId1, userId2] }).emit(\"foo\", data)\n */\n except(\n room: string | string[] | { user: string | string[] }\n ): ArkosBroadcastOperator<EmitEvents, SocketData>;\n\n /**\n * Emits to all clients,`_meta` is injected automatically.\n *\n * @example\n * // the “foo” event will be broadcast to all connected clients\n * io.emit(\"foo\", \"bar\");\n *\n * // the “foo” event will be broadcast to all connected clients in the “room-101” room\n * io.to(\"room-101\").emit(\"foo\", \"bar\");\n *\n * // with an acknowledgement expected from all connected clients\n * io.timeout(1000).emit(\"some-event\", (err, responses) => {\n * if (err) {\n * // some clients did not acknowledge the event in the given delay\n * } else {\n * console.log(responses); // one response per client\n * }\n * });\n *\n * @return Always true\n */\n emit<Ev extends EventNames<EmitEvents>>(\n ev: Ev,\n ...args: EventParams<EmitEvents, Ev>\n ): true;\n\n /** Chain volatile flag — event may be lost if client is not ready. */\n get volatile(): ArkosBroadcastOperator<EmitEvents, SocketData>;\n\n /** Chain compress flag. */\n compress(value: boolean): ArkosBroadcastOperator<EmitEvents, SocketData>;\n\n /** Chain timeout for `emitWithAck`. */\n timeout(\n ms: number\n ): ArkosBroadcastOperator<DecorateAcknowledgements<EmitEvents>, SocketData>;\n\n /**\n * Emits an event and waits for an acknowledgement from all clients.\n * `_meta` is injected automatically\n * @example\n * try {\n * const responses = await io.timeout(1000).emitWithAck(\"some-event\");\n * console.log(responses); // one response per client\n * } catch (e) {\n * // some clients did not acknowledge the event in the given delay\n * }\n *\n * @return a Promise that will be fulfilled when all clients have acknowledged the event\n */\n emitWithAck<Ev extends EventNamesWithError<EmitEvents>>(\n ev: Ev,\n ...args: AllButLast<EventParams<EmitEvents, Ev>>\n ): Promise<FirstNonErrorArg<Last<EventParams<EmitEvents, Ev>>>>;\n\n /**\n * Targets all active socket connections of a user by their user ID.\n * Uses the internal `arkos::user:{userId}` room convention.\n *\n * Supports emit, management, and exclusion operations across all of the\n * user's active connections.\n *\n * @example\n * socket.user(userId).emit(\"notification\", data)\n * socket.user(userId).except({ user: otherUserId }).emit(\"sync\", data)\n * const sockets = await socket.user(userId).fetchSockets()\n * const online = await socket.user(userId).isOnline()\n *\n * @since 1.7.0-canary.29\n */\n user(userId: string): ArkosUserTarget;\n /**\n * Returns all unique user IDs currently in the target room(s).\n *\n * @example\n * const users = await socket.to(\"room-123\").users()\n */\n users(): Promise<string[]>;\n}\n\n/**\n * Returned by `socket.retry(n)`. Wraps `emit` and `emitWithAck`\n * with exponential backoff. Chain `.timeout(ms)` before `.emitWithAck()` as usual.\n *\n * @since 1.7.0-canary.29\n */\nexport interface ArkosRetryTarget {\n /** Emit with ack and retry. `_meta` is injected automatically. */\n emitWithAck(event: string, data: any, ...rest: any[]): Promise<any>;\n\n /**\n * Chain a timeout before `emitWithAck`.\n *\n * @example\n * socket.retry(3).timeout(5000).emitWithAck(\"event\", data)\n */\n timeout(ms: number): ArkosRetryTarget;\n}\n\n/**\n * Returned by `socket.user(userId)`.\n * Targets all active socket connections of a user.\n *\n * @since 1.7.0-canary.29\n */\nexport interface ArkosUserTarget extends ArkosBroadcastOperator {\n /**\n * Returns all active rooms for this user.\n *\n * @example\n * const rooms = await socket.user(userId).activeRooms()\n * console.log(rooms.length) // number of active tabs/connections\n */\n activeRooms(): Promise<string[]>;\n}\n\nexport type ArkosGatewayPipe = (\n socket: ArkosSocket,\n data: any\n) => void | Promise<void>;\n\nexport type ArkosGatewayEventConfig<TSchema extends Validator = any> = {\n /** The Socket.io event name to listen for. */\n event: string;\n\n /** Zod schema or class-validator DTO to validate the incoming event payload. */\n validation?: TSchema;\n\n /** Per-event rate limiting. Overrides gateway-level `rateLimit` for this event. */\n rateLimit?: Partial<RateLimitOptions> | false;\n\n /**\n * Authorization configuration.\n *\n * @remarks Gateway `authentication` must NOT be `false` or this throws at registration time.\n */\n authorization?: {\n resource: string;\n action: string;\n rule?: DetailedAccessControlRule | string[] | \"*\";\n };\n\n /**\n * When `true`, Arkos automatically calls `ack({ success: true })` after the handler\n * finishes, unless the handler already called ack manually.\n */\n ack?: boolean;\n\n /** Disables this event handler without removing it. */\n disabled?: boolean;\n\n /**\n * Maximum age in milliseconds for incoming messages.\n * Requires `data._meta.timestamp`. Events older than this are rejected.\n */\n maxAge?: number;\n\n /** Per-event deduplication. Overrides gateway-level `dedup`. */\n dedup?:\n | {\n /** @default true */\n enabled?: boolean;\n /** Time-to-live in seconds for the dedup key. @default 3600 */\n ttl?: number;\n }\n | false;\n};\n\nexport type ArkosGatewayAckFn = (response: any) => void;\n\nexport type ArkosGatewayHandler<TData = any> = (\n socket: ArkosSocket,\n data: TData,\n ack?: ArkosGatewayAckFn\n) => void | Promise<void>;\n\nexport type ArkosGatewayEventEntry = {\n config: ArkosGatewayEventConfig;\n handler: ArkosGatewayHandler;\n pipes: ArkosGatewayPipe[];\n};\n\nexport type ArkosGatewayConnectionHandler = (\n socket: ArkosSocket\n) => void | Promise<void>;\n\nexport type ArkosGatewayHookHandler =\n | ArkosGatewayConnectionHandler\n | ArkosGatewayErrorHandler;\n\nexport type ArkosGatewayErrorHandler = (\n error: any,\n socket: ArkosSocket\n) => void | Promise<void>;\n\nexport type ArkosGatewayHookType = \"connection\" | \"disconnect\" | \"error\";\n\nexport type ArkosGatewayConfig = {\n /**\n * Socket.io namespace for this gateway.\n *\n * @example\n * name: \"/chat\"\n */\n name: string;\n\n /**\n * When `true`, Arkos runs auth middleware on connection and populates `socket.currentUser`.\n * Unauthenticated sockets are rejected.\n *\n * @default false\n */\n authentication?: boolean;\n\n /** Gateway-level rate limiting, applied per socket. Can be overridden per event. */\n rateLimit?: Partial<RateLimitOptions>;\n\n /**\n * Gateway-level deduplication. Drills down to child gateways and can be overridden\n * per child or per event listener.\n */\n dedup?:\n | {\n /** @default true */\n enabled?: boolean;\n /** @default 3600 */\n ttl?: number;\n }\n | false;\n\n /**\n * Maximum age in milliseconds for incoming messages.\n * Can be overridden per event via `maxAge` in `gateway.on()`.\n */\n maxAge?: number;\n};\n\n/**\n * Options for `gateway.register()`.\n * Passed once at the root — applies to all child gateways.\n */\nexport type ArkosGatewayRegisterOptions = {\n /**\n * Unified store for rate limiting and deduplication.\n * Defaults to an in-memory store — zero config for single-instance deployments.\n * For distributed deployments plug in a Redis-backed store.\n *\n * @example\n * store: new RedisArkosStore(redis)\n */\n store?: ArkosGatewayStore;\n};\n\n/**\n * Unified store interface for rate limiting and deduplication.\n * Implement this to plug in Redis, Valkey, or any distributed store.\n *\n * @example\n * class RedisArkosStore implements ArkosGatewayStore {\n * async increment(key, windowMs) { ... }\n * async clear(prefix) { ... }\n * async has(key) { ... }\n * async set(key, ttl) { ... }\n * async setIfNotExists(key, ttl) { ... }\n * }\n */\nexport interface ArkosGatewayStore {\n /** Increment a rate limit counter. Key format: `arkos::rl:{socketId}:{event}` */\n increment(\n key: string,\n windowMs: number\n ): Promise<{ count: number; resetAt: number }>;\n\n /** Clear all rate limit entries matching a prefix. Key format: `arkos::rl:{socketId}` */\n clear(prefix: string): Promise<void>;\n\n /** Check if a dedup key exists. */\n has(key: string): Promise<boolean>;\n\n /** Store a dedup key with TTL in seconds. */\n set(key: string, ttl: number): Promise<void>;\n\n /**\n * Atomically store a dedup key only if it does not already exist.\n * Returns `true` if created (process the message), `false` if duplicate (skip).\n */\n setIfNotExists(key: string, ttl: number): Promise<boolean>;\n}\n\n/**\n * Minimal broadcast/emit contract that {@link ArkosBroadcastOperatorImpl} wraps.\n * Deliberately narrower than socket.io's `BroadcastOperator` — only the methods\n * Arkos actually calls, so both a `BroadcastOperator` (from `socket.to()`) and a\n * raw `Namespace` (from `gateway.nsp`) satisfy it structurally.\n *\n * @since 1.7.1-canary.3\n */\nexport interface ArkosEmitTarget<EmitEvents extends EventsMap = DefaultEventsMap> {\n /**\n * Emits an event to the target. `_meta` (`mid` + `timestamp`) is injected automatically.\n *\n * @example\n * socket.to(\"room-101\").emit(\"message\", { text: \"hello\" })\n * socket.broadcast.emit(\"announcement\", data)\n */\n emit(event: string, ...args: any[]): boolean;\n\n /**\n * Emits an event and waits for an acknowledgement from all matched clients.\n * `_meta` is injected automatically.\n *\n * Optional — not every target supports ack collection directly (e.g. a raw\n * `Namespace` requires `.timeout(ms)` first). Throws at runtime if called on\n * a target that doesn't implement it natively.\n *\n * @example\n * const responses = await socket.to(\"room-101\").timeout(3000).emitWithAck(\"confirm\", data)\n */\n emitWithAck?(event: string, ...args: any[]): Promise<any>;\n\n /**\n * Excludes sockets from the broadcast.\n * Accepts a room name, socket ID, or array of rooms/IDs.\n * For `{ user }` exclusion, see {@link ArkosBroadcastOperatorImpl.except}.\n *\n * @example\n * socket.to(\"room-101\").except(\"room-102\").emit(\"foo\", data)\n */\n except(room: string | string[]): ArkosEmitTarget<EmitEvents>;\n\n /**\n * Sets the compress flag for the next emission.\n *\n * @example\n * socket.broadcast.compress(false).emit(\"ping\", data)\n */\n compress(value: boolean): ArkosEmitTarget<EmitEvents>;\n\n /**\n * Sets a timeout in milliseconds for `emitWithAck`.\n * Rejects the promise if no client acknowledges within the given delay.\n *\n * @example\n * socket.to(\"room-101\").timeout(3000).emitWithAck(\"confirm\", data)\n */\n timeout(ms: number): ArkosEmitTarget\n\n /**\n * Returns all sockets currently matched by this target.\n *\n * @example\n * const sockets = await socket.to(\"room-101\").fetchSockets()\n */\n fetchSockets(): Promise<any[]>;\n\n to(room: string | string[]): ArkosEmitTarget\n\n /**\n * Sets the volatile flag — the event may be dropped if the client is not ready.\n * Useful for high-frequency non-critical events like cursor positions or typing indicators.\n *\n * @example\n * socket.to(\"room-101\").volatile.emit(\"cursor\", position)\n */\n readonly volatile: ArkosEmitTarget<EmitEvents>;\n}\nexport class ArkosGatewayController { }\n"]}
@@ -44,6 +44,8 @@ export class EmailService {
44
44
  }
45
45
  : undefined,
46
46
  name,
47
+ user,
48
+ pass
47
49
  };
48
50
  }
49
51
  getTransporter(customConfig) {
@@ -52,7 +54,7 @@ export class EmailService {
52
54
  return nodemailer.createTransport(config);
53
55
  }
54
56
  if (!this.transporter) {
55
- const { name, ...config } = this.getEmailConfig() || {};
57
+ const { name, user, pass, ...config } = this.getEmailConfig() || {};
56
58
  this.transporter = nodemailer.createTransport(config);
57
59
  }
58
60
  return this.transporter;
@@ -62,7 +64,7 @@ export class EmailService {
62
64
  const transporter = connectionOptions
63
65
  ? this.getTransporter(connectionOptions)
64
66
  : this.getTransporter();
65
- const fromAddress = options.from || connectionOptions?.auth?.user || config.auth?.user;
67
+ const fromAddress = options.from || connectionOptions?.auth?.user || config.auth?.user || config?.user;
66
68
  if (connectionOptions || !skipVerification) {
67
69
  const isConnected = await this.verifyConnection(transporter);
68
70
  if (!isConnected)
@@ -1 +1 @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K,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,gCAAgC,EAAE,KAAK,CAAC,CAAC;YACvD,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAMM,YAAY,CAAC,MAA6B;QAC/C,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC;QAC3B,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;IAC1B,CAAC;IAOM,MAAM,CAAC,MAAM,CAAC,MAA6B;QAChD,OAAO,IAAI,YAAY,CAAC,MAAM,CAAC,CAAC;IAClC,CAAC;CACF;AAED,MAAM,YAAY,GAAG,IAAI,YAAY,EAAE,CAAC;AAExC,eAAe,YAAY,CAAC","sourcesContent":["import nodemailer, { SendMailOptions, Transporter } from \"nodemailer\";\nimport { convert } from \"html-to-text\";\nimport { getArkosConfig } from \"../../server\";\nimport AppError from \"../error-handler/utils/app-error\";\n\n/**\n * Defines the options for sending an email.\n */\nexport type EmailOptions = {\n subject: string;\n} & SendMailOptions;\n\n/**\n * Defines the authentication options for SMTP.\n */\nexport type SMTPAuthOptions = {\n user: string;\n pass: string;\n};\n\n/**\n * Defines the connection options for SMTP server.\n */\nexport type SMTPConnectionOptions = {\n host?: string;\n port?: number;\n secure?: boolean;\n auth?: SMTPAuthOptions;\n name?: string;\n};\n\n/**\n * A service class to handle email-related tasks, including sending emails.\n *\n * See the api reference [www.arkosjs.com/docs/reference/the-email-service-class](https://www.arkosjs.com/docs/reference/the-email-service-class)\n */\nexport class EmailService {\n transporter: Transporter | null = null;\n private customConfig: SMTPConnectionOptions | null = null;\n\n /**\n * Creates an instance of the EmailService class.\n *\n * @param {SMTPConnectionOptions} [config] - Optional custom SMTP configuration.\n * If provided, these settings will be used instead of the Arkos config.\n */\n constructor(config?: SMTPConnectionOptions) {\n if (config) {\n this.customConfig = config;\n }\n }\n\n /**\n * Gets the email configuration from multiple sources with priority:\n * 1. Constructor customConfig\n * 2. ArkosConfig\n * 3. Environment variables\n * @returns Configuration object with host, port, and auth details\n * @throws AppError if required email configuration is not set\n */\n private getEmailConfig(): SMTPConnectionOptions {\n if (this.customConfig) {\n return this.customConfig;\n }\n\n const { email: emailConfigs } = getArkosConfig();\n const host = emailConfigs?.host || process.env.EMAIL_HOST;\n const port =\n emailConfigs?.port ||\n (process.env.EMAIL_PORT ? parseInt(process.env.EMAIL_PORT) : undefined);\n const secure =\n emailConfigs?.secure !== undefined\n ? emailConfigs.secure\n : process.env.EMAIL_SECURE\n ? process.env.EMAIL_SECURE === \"true\"\n : undefined;\n const user = emailConfigs?.auth?.user || process.env.EMAIL_USER;\n const pass = emailConfigs?.auth?.pass || process.env.EMAIL_PASSWORD;\n const name = emailConfigs?.name || process.env.EMAIL_NAME;\n\n if (!host) {\n throw new AppError(\n \"You are trying to use emailService without setting email configurations. \" +\n \"Please configure either arkosConfig.email or environment variables (EMAIL_HOST)\",\n 500,\n {\n docs: \"Read more about emailService at https://www.arkosjs.com/docs/guides/email-service\",\n }\n );\n }\n\n return {\n ...emailConfigs,\n host,\n port: port || 465,\n secure: secure !== undefined ? secure : true,\n auth:\n user && pass\n ? {\n user,\n pass,\n }\n : undefined,\n name,\n };\n }\n\n /**\n * Gets or creates a transporter using the email configuration\n * @param customConfig Optional override connection settings (takes full priority if provided)\n * @returns A configured nodemailer transporter\n */\n private getTransporter(customConfig?: SMTPConnectionOptions): Transporter {\n if (customConfig) {\n const { name, ...config } = customConfig;\n return nodemailer.createTransport(config);\n }\n\n if (!this.transporter) {\n const { name, ...config } = this.getEmailConfig() || {};\n this.transporter = nodemailer.createTransport(config);\n }\n return this.transporter;\n }\n\n /**\n * Sends an email with the provided options.\n * Can use either the default configuration or custom connection options.\n *\n * @param {EmailOptions} options - The options for the email to be sent.\n * @param {SMTPConnectionOptions} [connectionOptions] - Optional custom connection settings.\n * @param {boolean} [skipVerification=false] - Whether to skip connection verification.\n * @returns {Promise<{ success: boolean; messageId?: string } & Record<string, any>>} Result with message ID on success.\n */\n public async send(\n options: EmailOptions & SendMailOptions,\n connectionOptions?: SMTPConnectionOptions,\n skipVerification: boolean = true\n ): Promise<{ success: boolean; messageId?: string } & Record<string, any>> {\n const config = this.getEmailConfig();\n const transporter = connectionOptions\n ? this.getTransporter(connectionOptions)\n : this.getTransporter();\n\n const fromAddress =\n options.from || connectionOptions?.auth?.user || config.auth?.user;\n\n if (connectionOptions || !skipVerification) {\n const isConnected = await this.verifyConnection(transporter);\n if (!isConnected) throw new Error(\"Failed to connect to email server\");\n }\n\n const info = await transporter.sendMail({\n ...options,\n from: fromAddress\n ? config.name\n ? `${config.name}<${fromAddress}>`\n : fromAddress\n : undefined,\n text:\n options?.text ||\n (typeof options.html === \"string\" && options.html\n ? convert(options.html as string)\n : undefined),\n });\n\n return { success: true, ...info };\n }\n\n /**\n * Verifies the connection to the email server.\n * @param {Transporter} [transporterToVerify] - Optional transporter to verify.\n * @returns {Promise<boolean>} A promise that resolves to true if connection is valid.\n */\n public async verifyConnection(\n transporterToVerify?: Transporter\n ): Promise<boolean> {\n try {\n const transporter = transporterToVerify || this.getTransporter();\n await transporter.verify();\n return true;\n } catch (error) {\n console.error(\"Email Server Connection Failed\", error);\n return false;\n }\n }\n\n /**\n * Updates the custom configuration for this email service instance.\n * @param {SMTPConnectionOptions} config - The new connection options.\n */\n public updateConfig(config: SMTPConnectionOptions): void {\n this.customConfig = config;\n this.transporter = null; // Reset transporter so it will be recreated with new config\n }\n\n /**\n * Creates a new instance of EmailService with custom configuration.\n * @param {SMTPConnectionOptions} config - The connection options for the new instance.\n * @returns {EmailService} A new EmailService instance.\n */\n public static create(config: SMTPConnectionOptions): EmailService {\n return new EmailService(config);\n }\n}\n\nconst emailService = new EmailService();\n\nexport default emailService;\n"]}
1
+ {"version":3,"file":"email.service.js","sourceRoot":"","sources":["../../../../src/modules/email/email.service.ts"],"names":[],"mappings":"AAAA,OAAO,UAA4C,MAAM,YAAY,CAAC;AACtE,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,cAAc,EA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CAAC;IAMM,YAAY,CAAC,MAA6B;QAC/C,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC;QAC3B,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;IAC1B,CAAC;IAOM,MAAM,CAAC,MAAM,CAAC,MAA6B;QAChD,OAAO,IAAI,YAAY,CAAC,MAAM,CAAC,CAAC;IAClC,CAAC;CACF;AAED,MAAM,YAAY,GAAG,IAAI,YAAY,EAAE,CAAC;AAExC,eAAe,YAAY,CAAC","sourcesContent":["import nodemailer, { SendMailOptions, Transporter } from \"nodemailer\";\nimport { convert } from \"html-to-text\";\nimport { getArkosConfig } from \"../../server\";\nimport AppError from \"../error-handler/utils/app-error\";\n\n/**\n * Defines the options for sending an email.\n */\nexport type EmailOptions = {\n subject: string;\n} & SendMailOptions;\n\n/**\n * Defines the authentication options for SMTP.\n */\nexport type SMTPAuthOptions = {\n user: string;\n pass: string;\n};\n\n/**\n * Defines the connection options for SMTP server.\n */\nexport type SMTPConnectionOptions = {\n host?: string;\n port?: number;\n secure?: boolean;\n auth?: SMTPAuthOptions;\n name?: string;\n user?: string;\n pass?: string;\n};\n\n/**\n * A service class to handle email-related tasks, including sending emails.\n *\n * See the api reference [www.arkosjs.com/docs/reference/the-email-service-class](https://www.arkosjs.com/docs/reference/the-email-service-class)\n */\nexport class EmailService {\n transporter: Transporter | null = null;\n private customConfig: SMTPConnectionOptions | null = null;\n\n /**\n * Creates an instance of the EmailService class.\n *\n * @param {SMTPConnectionOptions} [config] - Optional custom SMTP configuration.\n * If provided, these settings will be used instead of the Arkos config.\n */\n constructor(config?: SMTPConnectionOptions) {\n if (config) {\n this.customConfig = config;\n }\n }\n\n /**\n * Gets the email configuration from multiple sources with priority:\n * 1. Constructor customConfig\n * 2. ArkosConfig\n * 3. Environment variables\n * @returns Configuration object with host, port, and auth details\n * @throws AppError if required email configuration is not set\n */\n private getEmailConfig(): SMTPConnectionOptions {\n if (this.customConfig) {\n return this.customConfig;\n }\n\n const { email: emailConfigs } = getArkosConfig();\n const host = emailConfigs?.host || process.env.EMAIL_HOST;\n const port =\n emailConfigs?.port ||\n (process.env.EMAIL_PORT ? parseInt(process.env.EMAIL_PORT) : undefined);\n const secure =\n emailConfigs?.secure !== undefined\n ? emailConfigs.secure\n : process.env.EMAIL_SECURE\n ? process.env.EMAIL_SECURE === \"true\"\n : undefined;\n const user = emailConfigs?.auth?.user || process.env.EMAIL_USER;\n const pass = emailConfigs?.auth?.pass || process.env.EMAIL_PASSWORD;\n const name = emailConfigs?.name || process.env.EMAIL_NAME;\n\n if (!host) {\n throw new AppError(\n \"You are trying to use emailService without setting email configurations. \" +\n \"Please configure either arkosConfig.email or environment variables (EMAIL_HOST)\",\n 500,\n {\n docs: \"Read more about emailService at https://www.arkosjs.com/docs/guides/email-service\",\n }\n );\n }\n\n return {\n ...emailConfigs,\n host,\n port: port || 465,\n secure: secure !== undefined ? secure : true,\n auth:\n user && pass\n ? {\n user,\n pass,\n }\n : undefined,\n name,\n user,\n pass\n };\n }\n\n /**\n * Gets or creates a transporter using the email configuration\n * @param customConfig Optional override connection settings (takes full priority if provided)\n * @returns A configured nodemailer transporter\n */\n private getTransporter(customConfig?: SMTPConnectionOptions): Transporter {\n if (customConfig) {\n const { name, ...config } = customConfig;\n return nodemailer.createTransport(config);\n }\n\n if (!this.transporter) {\n const { name, user, pass, ...config } = this.getEmailConfig() || {};\n this.transporter = nodemailer.createTransport(config);\n }\n return this.transporter;\n }\n\n /**\n * Sends an email with the provided options.\n * Can use either the default configuration or custom connection options.\n *\n * @param {EmailOptions} options - The options for the email to be sent.\n * @param {SMTPConnectionOptions} [connectionOptions] - Optional custom connection settings.\n * @param {boolean} [skipVerification=false] - Whether to skip connection verification.\n * @returns {Promise<{ success: boolean; messageId?: string } & Record<string, any>>} Result with message ID on success.\n */\n public async send(\n options: EmailOptions & SendMailOptions,\n connectionOptions?: SMTPConnectionOptions,\n skipVerification: boolean = true\n ): Promise<{ success: boolean; messageId?: string } & Record<string, any>> {\n const config = this.getEmailConfig();\n const transporter = connectionOptions\n ? this.getTransporter(connectionOptions)\n : this.getTransporter();\n\n const fromAddress =\n options.from || connectionOptions?.auth?.user || config.auth?.user || config?.user;\n\n if (connectionOptions || !skipVerification) {\n const isConnected = await this.verifyConnection(transporter);\n if (!isConnected) throw new Error(\"Failed to connect to email server\");\n }\n\n const info = await transporter.sendMail({\n ...options,\n from: fromAddress\n ? config.name\n ? `${config.name}<${fromAddress}>`\n : fromAddress\n : undefined,\n text:\n options?.text ||\n (typeof options.html === \"string\" && options.html\n ? convert(options.html as string)\n : undefined),\n });\n\n return { success: true, ...info };\n }\n\n /**\n * Verifies the connection to the email server.\n * @param {Transporter} [transporterToVerify] - Optional transporter to verify.\n * @returns {Promise<boolean>} A promise that resolves to true if connection is valid.\n */\n public async verifyConnection(\n transporterToVerify?: Transporter\n ): Promise<boolean> {\n try {\n const transporter = transporterToVerify || this.getTransporter();\n await transporter.verify();\n return true;\n } catch (error) {\n console.error(\"Email Server Connection Failed\", error);\n return false;\n }\n }\n\n /**\n * Updates the custom configuration for this email service instance.\n * @param {SMTPConnectionOptions} config - The new connection options.\n */\n public updateConfig(config: SMTPConnectionOptions): void {\n this.customConfig = config;\n this.transporter = null; // Reset transporter so it will be recreated with new config\n }\n\n /**\n * Creates a new instance of EmailService with custom configuration.\n * @param {SMTPConnectionOptions} config - The connection options for the new instance.\n * @returns {EmailService} A new EmailService instance.\n */\n public static create(config: SMTPConnectionOptions): EmailService {\n return new EmailService(config);\n }\n}\n\nconst emailService = new EmailService();\n\nexport default emailService;\n"]}