New:Microsoft Teams Notifications Are Now Available in Socket.Learn more
Get Started

@fluojs/notifications

Package Overview
Dependencies
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@fluojs/notifications

Channel-agnostic notification orchestration with optional queue and lifecycle event seams for Fluo.

latest
Source
npmnpm
Version
2.0.0
Version published
Maintainers
1
Created
Source

@fluojs/notifications

English 한국어

Node.js support is >=24.0.0 <27. See Node.js support and migration before upgrading.

Channel-agnostic notification orchestration for fluo. It freezes the shared contract for notification channels, provides explicit module registration with familiar dynamic-module ergonomics, and exposes optional queue-backed delivery and lifecycle event publication seams.

Table of Contents

Installation

npm install @fluojs/notifications

When to Use

  • When you want one shared dispatch contract for multiple notification channels without coupling sibling packages to each other.
  • When application code should depend on NotificationsService instead of provider-specific SDKs or transport details.
  • When bulk delivery may need to be offloaded to a queue, but direct in-process dispatch should still remain available.
  • When notification lifecycle events (requested, queued, delivered, failed) should be observable through an event publication seam.

Quick Start

1. Register the foundation module

Register notifications with NotificationsModule.forRoot(...) or NotificationsModule.forRootAsync(...) by passing explicit NotificationChannel values in channels.

import { Module } from '@fluojs/core';
import {
  NotificationsModule,
  type NotificationChannel,
} from '@fluojs/notifications';

const emailChannel: NotificationChannel = {
  channel: 'email',
  async send(notification) {
    console.log('sending email', notification.subject, notification.payload);

    return {
      externalId: 'email-123',
      metadata: { provider: 'demo-email' },
    };
  },
};

@Module({
  imports: [
    NotificationsModule.forRoot({
      channels: [emailChannel],
    }),
  ],
})
export class AppModule {}

2. Inject NotificationsService

import { Inject } from '@fluojs/core';
import { NotificationsService } from '@fluojs/notifications';

@Inject(NotificationsService)
export class WelcomeService {
  constructor(private readonly notifications: NotificationsService) {}

  async sendWelcomeEmail(userId: string, email: string) {
    await this.notifications.dispatch({
      channel: 'email',
      recipients: [email],
      subject: 'Welcome to fluo',
      payload: {
        template: 'welcome-email',
        userId,
      },
    });
  }
}

NotificationsModule.forRoot(...) and NotificationsModule.forRootAsync(...) export NotificationsService, NOTIFICATIONS, and NOTIFICATION_CHANNELS as global providers by default. Set global: false when these providers should stay visible only to the module that imports the notifications module. Application services should declare dependencies with fluo's class-level @Inject(...) decorator so the standard-decorator DI container can resolve the service without parameter decorators.

Migration boundary: channel registration is value-based, not metadata-based. Do not rely on NestJS provider discovery, @Injectable() metadata, or emitDecoratorMetadata to register channels. Build NotificationChannel objects in application code or return them from NotificationsModule.forRootAsync({ inject, useFactory, global? }), then pass them through the channels option.

Common Patterns

Queue-backed bulk delivery

Use the optional queue seam when many notifications should be deferred to background workers. The queue adapter is an application-owned integration; @fluojs/notifications only calls the abstract adapter contract.

NotificationsModule.forRoot({
  channels: [emailChannel],
  queue: {
    adapter: {
      async enqueue(job, context) {
        return queue.enqueue(job);
      },
      async enqueueMany(jobs, context) {
        return Promise.all(jobs.map((job) => queue.enqueue(job)));
      },
    },
    bulkThreshold: 50,
  },
});

Behavioral contract notes:

  • bulkThreshold defaults to 10 when omitted. Explicit values must be finite positive integers; invalid values cause module options resolution to throw NotificationsConfigurationError before notification service providers can be constructed.
  • Bulk queue delegation starts when the notification count reaches bulkThreshold, and dispatchMany(..., { queue: true }) explicitly forces queue-backed delivery even when the batch is below that threshold.
  • dispatch() stays direct by default even when a queue adapter is configured. Use dispatch(..., { queue: true }) to opt one single notification into queue-backed delivery.
  • Use dispatch(..., { queue: false }) to force direct delivery even when a queue adapter exists.
  • Queue-backed delivery is opt-in for single dispatch and threshold-driven for dispatchMany(...) unless the caller explicitly passes { queue: true }.
  • NotificationsQueueContext is the optional second argument of enqueue(...) and enqueueMany(...). It carries the exact caller-owned AbortSignal from dispatch; existing one-argument adapters remain valid.
  • Before every queue handoff, the service checks the signal and then passes that same live signal to the adapter. A pre-aborted queued dispatch emits requested then failed when lifecycle events are enabled, but never calls enqueue(...) or enqueueMany(...). A signal that aborts after an adapter accepts a job cannot revoke that accepted queue job.
  • Queue adapters own queue-specific cancellation policy and must remove any abort listeners when their enqueue operation settles. If an adapter rejects because the signal aborts, native bulk dispatch rejects and publishes failed for every requested job; sequential fallback never hands subsequent jobs to the queue. With continueOnError: true, earlier accepted jobs remain in results and aborted current/remaining jobs appear in failures.
  • Queue adapters must resolve every enqueue() result and every enqueueMany() result entry with a non-empty string identifier. Native enqueueMany() must return a dense array whose own data-property entries exactly match the admitted job count; accessor-backed entries, sparse arrays, and length drift are rejected. The service rejects malformed values with NotificationQueueResultIntegrityError; it never fabricates a queued delivery id from the notification envelope.
  • Queue jobs preserve caller-provided notification.id as the authoritative idempotency key. Otherwise, they derive a deterministic fallback id from a runtime-neutral serialization that orders object keys by locale-independent code-unit order and uses a wider 64-bit digest. Queue adapters should pass this value to backing queues that support deduplication. The generated fallback key is deterministic for equivalent supported inputs, including cyclic opaque payloads, but it is not a durable cross-release identity contract; set notification.id when callers need stable identity across application or package upgrades.
  • dispatchMany(..., { continueOnError: true }) collects failures instead of throwing on the first failed direct delivery or sequential queue fallback enqueue.
  • When queue enqueue fails, the service emits deterministic notification.dispatch.failed lifecycle events before rethrowing the enqueue error to the caller. Queued bulk dispatch also publishes a terminal queued or failed event for every notification that already emitted requested, including queue-missing, channel-resolution, and provider/adapter failure paths.
  • If enqueueMany(...) is unavailable, bulk queue delivery falls back to enqueueing each job individually in input order. With continueOnError: true, successful enqueues remain visible in results while failed enqueues are returned in failures; without it, the first enqueue failure is rethrown after the remaining requested fallback jobs receive failed lifecycle events.
  • The foundation package does not assume or import a concrete queue implementation, create queue clients/workers, or close/drain application-owned queue resources.

Lifecycle publication through an event publisher

Publish caller-visible lifecycle events without coupling the foundation package to @fluojs/event-bus directly. The event publisher is also application-owned; the foundation package does not create, import, close, or drain a concrete event bus.

NotificationsModule.forRoot({
  channels: [emailChannel],
  events: {
    publishLifecycleEvents: true,
    publisher: {
      async publish(event) {
        await eventBus.publish(event);
      },
    },
  },
});

Published event names:

  • notification.dispatch.requested
  • notification.dispatch.queued
  • notification.dispatch.delivered
  • notification.dispatch.failed

If events.publisher is configured, lifecycle event publication defaults to on unless publishLifecycleEvents: false is set. The service snapshots every non-empty dispatchMany(...) batch at admission before its first lifecycle publication, and snapshots a single dispatch(...) envelope at admission for channel resolution, queue jobs, generated identity, and provider delivery. It then publishes a separate immutable lifecycle event snapshot. Lifecycle snapshots never expose native mutable built-ins: ArrayBuffer stores byte length and bytes, while ArrayBufferView values additionally preserve byte offset and view kind; Map and Set become ordered entry/value data, Date stores epoch milliseconds (null for an invalid date), URL stores href, URLSearchParams stores its query string, and RegExp stores source, flags, and lastIndex. Publishers must treat lifecycle events as observation-only and must not mutate them to influence delivery. Channel deliveries that omit externalId receive a deterministic fallback delivery id so dispatch results remain stable for callers without relying on time or random data. Generated fallback ids use the same locale-independent key ordering and 64-bit runtime-neutral digest as queue job ids, while caller-provided notification.id remains authoritative. They are keys for the current envelope shape, not a documented full-payload hash contract; set notification.id when callers need durable identity across releases. Channel resolution failures publish requested and then failed events before throwing NotificationChannelNotFoundError; treat those failures as permanent configuration errors. Queue enqueue and provider delivery failures also publish failed events, but callers should classify their retry behavior from the underlying adapter/provider error. Publication failures for success-path lifecycle events remain best-effort so a delivered notification is not converted into an application failure. Publication failures for notification.dispatch.failed are caller-visible as AggregateError values that include both the original dispatch error and the publisher error so failed-event guarantees are not silently weakened.

Lifecycle built-in representations

InterfaceImmutable fields
NotificationSnapshotArrayBufferkind: 'ArrayBuffer', byteLength, bytes
NotificationSnapshotArrayBufferViewkind: 'ArrayBufferView', byteOffset, byteLength, bytes, view
NotificationSnapshotDatekind: 'Date', epochMilliseconds: number | null
NotificationSnapshotMap<TKey, TValue>kind: 'Map', entries
NotificationSnapshotRegExpkind: 'RegExp', source, flags, lastIndex
NotificationSnapshotSet<TValue>kind: 'Set', values
NotificationSnapshotUrlkind: 'URL', href
NotificationSnapshotUrlSearchParamskind: 'URLSearchParams', query

Intentional limitations

The foundation package intentionally does not:

  • ship built-in email, Slack, or Discord implementations
  • inspect process.env directly
  • depend on @fluojs/queue or @fluojs/event-bus concrete runtime types
  • create, import, close, or drain concrete queue or event-bus resources; queue adapters and event publishers are application-owned integrations
  • encode provider-specific payload semantics into the shared contract

These limitations are part of the package contract so leaf packages can evolve independently while sharing one stable orchestration layer.

Public API Overview

Core

  • NotificationsModule.forRoot(options) / NotificationsModule.forRootAsync(options)
  • NotificationsService
  • NotificationsService.createPlatformStatusSnapshot()
  • Notifications
  • NOTIFICATIONS
  • NOTIFICATION_CHANNELS

Contracts

  • NotificationDispatchRequest
  • NotificationDispatchOptions
  • NotificationDispatchManyOptions
  • NotificationDispatchResult
  • NotificationDispatchBatchResult
  • NotificationDispatchFailure
  • NotificationDispatchStatus
  • NotificationChannel
  • NotificationChannelContext
  • NotificationChannelDelivery
  • NotificationPayload
  • NotificationSnapshot
  • NotificationSnapshotDate
  • NotificationSnapshotMap<TKey, TValue>
  • NotificationSnapshotRegExp
  • NotificationSnapshotSet<TValue>
  • NotificationSnapshotUrl
  • NotificationSnapshotUrlSearchParams
  • NotificationSnapshotArrayBuffer
  • NotificationSnapshotArrayBufferView
  • NotificationsQueueAdapter
  • NotificationsQueueContext
  • NotificationsQueueJob
  • NotificationsQueueOptions
  • NotificationsModuleOptions
  • NotificationsAsyncModuleOptions
  • NotificationsEventsOptions
  • NotificationsEventPublisher
  • NotificationLifecycleEvent
  • NotificationLifecycleEventName

Status and errors

  • createNotificationsPlatformStatusSnapshot(...)
  • NotificationsOperationMode
  • NotificationsPlatformStatusSnapshot
  • NotificationsStatusAdapterInput
  • NotificationsStatusDetails
  • NotificationsConfigurationError
  • NotificationChannelNotFoundError
  • NotificationQueueNotConfiguredError
  • NotificationQueueResultIntegrityError

Status snapshots include readiness, health, ownership, and a details object for platform diagnostics. operationMode, dependencies, bulkQueueThreshold, queueConfigured, eventPublisherConfigured, and eventPublicationEnabled live under details; they are not top-level snapshot fields. eventPublisherConfigured records publisher wiring, while eventPublicationEnabled records whether that publisher emits lifecycle events. When a queue adapter is configured, details.dependencies includes notifications.queue-adapter; when lifecycle events are enabled through an event publisher, it includes notifications.event-publisher. A configured publisher with publishLifecycleEvents: false remains visible as configured but does not add an active dependency, event-backed operation mode, or external ownership. Active optional integrations mark ownership.externallyManaged: true while the foundation package still reports ownsResources: false because it does not create, close, or drain concrete queue or event-bus resources.

  • @fluojs/queue: Recommended when bulk notification delivery should run in the background.
  • @fluojs/event-bus: Recommended when notification lifecycle events should be published to the wider app.
  • @fluojs/config: Recommended for passing provider configuration into forRootAsync() without direct environment access.

Example Sources

  • packages/notifications/src/module.test.ts: Module registration, async wiring, queue seam, and tolerant bulk dispatch examples.
  • packages/notifications/src/public-surface.test.ts: Public contract verification for root exports and TypeScript-only types.
  • packages/notifications/src/status.test.ts: Health/readiness contract examples.

Keywords

fluo

FAQs

Package last updated on 07 Sep 2026

Related posts