notifkit 0.1.5 → 0.1.7

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 (29) hide show
  1. package/README.md +5 -17
  2. package/dist/index.d.mts +3012 -550
  3. package/dist/index.d.mts.map +1 -1
  4. package/dist/index.mjs +2 -2
  5. package/dist/{main-DeNFQ-UL.mjs → main-Bgi2wWck.mjs} +2 -2
  6. package/dist/{main-DeNFQ-UL.mjs.map → main-Bgi2wWck.mjs.map} +1 -1
  7. package/dist/{main-40zwq6b0.mjs → main-CFSukWm8.mjs} +73 -39
  8. package/dist/main-CFSukWm8.mjs.map +1 -0
  9. package/dist/{main-DmCPcxOc.mjs → main-CRPxM-O3.mjs} +2 -2
  10. package/dist/{main-DmCPcxOc.mjs.map → main-CRPxM-O3.mjs.map} +1 -1
  11. package/dist/{main-BFre2-HQ.mjs → main-CjbVdUqa.mjs} +2 -2
  12. package/dist/{main-BFre2-HQ.mjs.map → main-CjbVdUqa.mjs.map} +1 -1
  13. package/dist/{main-BNJtzY61.mjs → main-D6SG3Isk.mjs} +2 -2
  14. package/dist/{main-BNJtzY61.mjs.map → main-D6SG3Isk.mjs.map} +1 -1
  15. package/dist/{main-DvgJSm11.mjs → main-DFMHcN_d.mjs} +2 -2
  16. package/dist/{main-DvgJSm11.mjs.map → main-DFMHcN_d.mjs.map} +1 -1
  17. package/dist/{main-BOPMYqsW.mjs → main-Yorxzw0Z.mjs} +2 -2
  18. package/dist/{main-BOPMYqsW.mjs.map → main-Yorxzw0Z.mjs.map} +1 -1
  19. package/dist/{main-CiigNpsP.mjs → main-pFAfCkVX.mjs} +2 -2
  20. package/dist/{main-CiigNpsP.mjs.map → main-pFAfCkVX.mjs.map} +1 -1
  21. package/dist/{src-vG79L-8m.mjs → src-CPMwsUCJ.mjs} +70 -41
  22. package/dist/src-CPMwsUCJ.mjs.map +1 -0
  23. package/package.json +1 -1
  24. package/src/client.ts +111 -40
  25. package/src/config/index.ts +5 -1
  26. package/src/contracts/sdk.ts +143 -3
  27. package/src/services/api/handlers.ts +94 -30
  28. package/dist/main-40zwq6b0.mjs.map +0 -1
  29. package/dist/src-vG79L-8m.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/config/index.ts","../src/contracts/common.ts","../src/contracts/metadata.ts","../src/contracts/events/notification-requested.ts","../src/contracts/events/notification-created.ts","../src/contracts/events/notification-enriched.ts","../src/contracts/events/notification-scheduled.ts","../src/contracts/events/notification-dispatched.ts","../src/contracts/events/notification-delivered.ts","../src/contracts/events/notification-failed.ts","../src/contracts/events/notification-skipped.ts","../src/contracts/events/notification-canceled.ts","../src/contracts/events/notification-ai-pending.ts","../src/contracts/registry.ts","../src/contracts/envelope.ts","../src/contracts/streams.ts","../src/contracts/helpers.ts","../src/contracts/sdk.ts","../src/db/schema.ts","../src/db/index.ts","../src/idempotency/index.ts","../src/logger/index.ts","../src/metrics/index.ts","../src/queue/index.ts","../src/rate-limiter/index.ts","../src/redis/index.ts","../src/repositories/index.ts","../src/shared/events.ts","../src/shared/cache.ts","../src/shared/utils.ts","../src/shared/semaphore.ts","../src/shared/batch-processor.ts","../src/shared/circuit-breaker.ts","../src/shared/dataloader.ts","../src/workers/health.ts","../src/workers/index.ts","../src/shared/index.ts","../src/templates/render.ts","../src/templates/cache.ts","../src/templates/index.ts","../src/transport/index.ts","../src/unsubscribe/index.ts","../src/workflows/sdk.ts","../src/workflows/registry.ts","../src/client.ts","../src/server.ts"],"mappings":";;;;;;;;;iBAOgB,QAAQ;iBAKR,YAAY,gBAAgB,YAC1C,QAAQ,SACR,gBACC,EAAE,OAAO;cAkBC,kBAAgB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA6BjB,aAAa,EAAE,aAAa;iBAIxB,gBAAgB,QAAQ;iBAIxB,eAAe,OAAM,OAAO,aAA2B;UAOtD;EACf;EACA;;UAGe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BAAkB,iBAAiB,iBAAiB;;EAUpD,sBAAsB,iBAAiB;IAAU;IAAgB;;;EAKjE,mBAAmB,iBAAiB;IAAU;;;EAK9C,wBAAwB;IAAU;;;EAOlC,QAAQ,aAAa;;EAKrB,eAAe,aAAa;;EAK5B,mBAAmB,aAAa;;EAKhC,sBACJ,YACA,aAAa,sBACZ;IAAU;IAAY;;;EAOnB,iBAAiB;IAAU;;;EAK3B,YAAY,aAAa;;EAOzB,mBAAmB;;EAKnB,oBAAoB;;EAKpB,kBAAkB;IAAU;;;EAK5B,iBAAiB,aAAa;IAAU;IAAkB;;;EAK1D,iBAAiB,aAAa;IAAU;;;;;UClZ/B;EACf;EACA;EACA;EACA;EACA;EACA;EAGA,YAAY;EACZ;EACA,UAAU;EACV;EACA;IACE;;EAEF;IACE;;;cAIS,uBAAuB;UAC1B;UACA;UACA;UACA;UACA;UACA;UACA;UACA;EAEI,YAAA,SAAS;EA4Bf,SAAK;EAiJL,QAAI"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/config/index.ts","../src/contracts/common.ts","../src/contracts/metadata.ts","../src/contracts/events/notification-requested.ts","../src/contracts/events/notification-created.ts","../src/contracts/events/notification-enriched.ts","../src/contracts/events/notification-scheduled.ts","../src/contracts/events/notification-dispatched.ts","../src/contracts/events/notification-delivered.ts","../src/contracts/events/notification-failed.ts","../src/contracts/events/notification-skipped.ts","../src/contracts/events/notification-canceled.ts","../src/contracts/events/notification-ai-pending.ts","../src/contracts/registry.ts","../src/contracts/envelope.ts","../src/contracts/streams.ts","../src/contracts/helpers.ts","../src/contracts/sdk.ts","../src/db/schema.ts","../src/db/index.ts","../src/idempotency/index.ts","../src/logger/index.ts","../src/metrics/index.ts","../src/queue/index.ts","../src/rate-limiter/index.ts","../src/redis/index.ts","../src/repositories/index.ts","../src/shared/events.ts","../src/shared/cache.ts","../src/shared/utils.ts","../src/shared/semaphore.ts","../src/shared/batch-processor.ts","../src/shared/circuit-breaker.ts","../src/shared/dataloader.ts","../src/workers/health.ts","../src/workers/index.ts","../src/shared/index.ts","../src/templates/render.ts","../src/templates/cache.ts","../src/templates/index.ts","../src/transport/index.ts","../src/unsubscribe/index.ts","../src/workflows/sdk.ts","../src/workflows/registry.ts","../src/client.ts","../src/server.ts"],"mappings":";;;;;;;;;iBAOgB,QAAQ;iBAKR,YAAY,gBAAgB,YAC1C,QAAQ,SACR,gBACC,EAAE,OAAO;cAkBC,kBAAgB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAiCjB,aAAa,EAAE,aAAa;iBAIxB,gBAAgB,QAAQ;iBAIxB,eAAe,OAAM,OAAO,aAA2B;UAOtD;EACf;EACA;;UAGe;EACf,UAAU;;EAEV;;EAEA;;EAEA;;cAGW;;;;;iBAQG,YAAY,QAAQ;iBAIpB,eAAe;;;cC1GlB,2BAAyB,EAAA;KAW1B,sBAAsB,EAAE,aAAa;cAEpC,4BAA0B,EAAA;KAC3B,uBAAuB,EAAE,aAAa;cAErC,0BAAwB,EAAA;KASzB,qBAAqB,EAAE,aAAa;;;cCzBnC,qBAAmB,EAAA;;;;;;;;;;;;;;;;;;;KAOpB,gBAAgB,EAAE,aAAa;;;;;;;;;;;cCE9B,0BAAwB,EAAA,+BAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAKzB,qBAAqB,EAAE,aAAa;cAEnC,oCAAkC,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAiBnC,+BAA+B,EAAE,aAAa;;;cChC7C,kCAAgC,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAUjC,6BAA6B,EAAE,aAAa;;;cCV3C,wBAAsB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAy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1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
- import { $ as childLogger, $t as PUBSUB_CHANNELS, A as ProjectSettingsCache, At as NotificationRequestedPayloadSchema, B as LUA_RELEASE_LOCK, Bt as QuietHoursSchema, C as ProjectRepository, Ct as DeliveryOptionsSchema, D as WorkflowRepository, Dt as NotificationEnrichedPayloadSchema, E as UserRepository, Et as NotificationScheduledPayloadSchema, F as sleep, Ft as CreateWorkflowSchema, G as normaliseTarget, Gt as UpdateUserSchema, H as LUA_SCHEDULER_CLAIM, Ht as TemplateSchema, I as DataLoader, It as IngestEventSchema, J as PendingMessageScanner, Jt as buildStreamEvent, K as LRUCache, Kt as WorkflowNotifyPayloadSchema, L as CircuitBreaker, Lt as InlineUserSchema, M as AppError, Mt as AddContactSchema, N as ValidationError, Nt as AddUserSchema, O as Redis, Ot as RecipientProfileSchema, P as generateId, Pt as ContactChannelSchema, Q as metrics, Qt as OUTBOUND_STREAMS, R as BatchProcessor, Rt as NotifyRequestSchema, S as PreferenceRepository, St as NotificationDeliveredPayloadSchema, T as TemplateRepository, Tt as RenderedContentSchema, U as LUA_SCHEDULER_POLL, Ut as TriggerWorkflowSchema, V as LUA_RENEW_LOCK, Vt as SyncTemplatesSchema, W as getPriorityBucket, Wt as UpdateProjectSchema, X as StreamProducer, Xt as ENRICHED_STREAMS, Y as StreamConsumer, Yt as CONSUMER_GROUPS, Z as getMetricsRegistry, Zt as INBOUND_STREAMS, _ as escapeHeader, _n as setGlobalConfig, a as SuspendExecutionError, an as registry, at as runMigrations, b as renderWithTemplate, bt as NotificationSkippedPayloadSchema, c as BaseWorker, cn as NotificationPrioritySchema, d as buildUnsubscribeHeaders, dn as baseConfigSchema, en as STREAMS, et as createLogger, f as signUnsubscribeToken, fn as getAiConfig, g as TemplateCache, gn as setAiConfig, h as templateRegistry, hn as readBaseConfig, i as workflowRegistry, in as EventRegistry, it as createDatabase, j as UserThrottle, jt as NotificationTargetSchema, k as RedisClient, kt as NotificationCreatedPayloadSchema, l as NonRetryableError, ln as NotificationStatusSchema, m as renderTemplate, mn as parseConfig, n as NotifkitClient, nn as StreamEventMetadataSchema, nt as withRequestId, o as buildStepNotifyPayload, on as EventMetadataSchema, p as verifyUnsubscribeToken, pn as loadEnv, q as globalEmitter, qt as WorkflowStepSchema, r as workflow, rn as StreamEventSchema, rt as IdempotencyGuard, s as resolveStepTarget, sn as NotificationChannelSchema, t as NotifkitServer, tn as EventEnvelopeSchema, tt as withContext, u as startHealthReporter, un as AI_DEFAULTS, v as escapeHtml, vt as NotificationAiPendingPayloadSchema, w as SegmentRepository, wt as NotificationDispatchedPayloadSchema, x as ContactRepository, xt as NotificationFailedPayloadSchema, y as interpolate, yt as NotificationCanceledPayloadSchema, z as AsyncSemaphore, zt as PreferencesSchema } from "./src-vG79L-8m.mjs";
2
+ import { $ as childLogger, $t as INBOUND_STREAMS, A as ProjectSettingsCache, At as NotificationRequestedPayloadSchema, B as LUA_RELEASE_LOCK, Bt as PreferencesSchema, C as ProjectRepository, Ct as DeliveryOptionsSchema, D as WorkflowRepository, Dt as NotificationEnrichedPayloadSchema, E as UserRepository, Et as NotificationScheduledPayloadSchema, F as sleep, Ft as ContactChannelSchema, G as normaliseTarget, Gt as UpdateProjectSchema, H as LUA_SCHEDULER_CLAIM, Ht as SyncTemplatesSchema, I as DataLoader, It as CreateWorkflowSchema, J as PendingMessageScanner, Jt as WorkflowNotifyPayloadSchema, K as LRUCache, Kt as UpdateUserSchema, L as CircuitBreaker, Lt as IngestEventSchema, M as AppError, Mt as AddContactSchema, N as ValidationError, Nt as AddUserSchema, O as Redis, Ot as RecipientProfileSchema, P as generateId, Pt as BatchAddContactsSchema, Q as metrics, Qt as ENRICHED_STREAMS, R as BatchProcessor, Rt as InlineUserSchema, S as PreferenceRepository, St as NotificationDeliveredPayloadSchema, T as TemplateRepository, Tt as RenderedContentSchema, U as LUA_SCHEDULER_POLL, Ut as TemplateSchema, V as LUA_RENEW_LOCK, Vt as QuietHoursSchema, W as getPriorityBucket, Wt as TriggerWorkflowSchema, X as StreamProducer, Xt as buildStreamEvent, Y as StreamConsumer, Yt as WorkflowStepSchema, Z as getMetricsRegistry, Zt as CONSUMER_GROUPS, _ as escapeHeader, _n as readBaseConfig, a as SuspendExecutionError, an as StreamEventSchema, at as runMigrations, b as renderWithTemplate, bt as NotificationSkippedPayloadSchema, c as BaseWorker, cn as EventMetadataSchema, d as buildUnsubscribeHeaders, dn as NotificationStatusSchema, en as OUTBOUND_STREAMS, et as createLogger, f as signUnsubscribeToken, fn as AI_DEFAULTS, g as TemplateCache, gn as parseConfig, h as templateRegistry, hn as loadEnv, i as workflowRegistry, in as StreamEventMetadataSchema, it as createDatabase, j as UserThrottle, jt as NotificationTargetSchema, k as RedisClient, kt as NotificationCreatedPayloadSchema, l as NonRetryableError, ln as NotificationChannelSchema, m as renderTemplate, mn as getAiConfig, n as NotifkitClient, nn as STREAMS, nt as withRequestId, o as buildStepNotifyPayload, on as EventRegistry, p as verifyUnsubscribeToken, pn as baseConfigSchema, q as globalEmitter, qt as UserContactInputSchema, r as workflow, rn as EventEnvelopeSchema, rt as IdempotencyGuard, s as resolveStepTarget, sn as registry, t as NotifkitServer, tn as PUBSUB_CHANNELS, tt as withContext, u as startHealthReporter, un as NotificationPrioritySchema, v as escapeHtml, vn as setAiConfig, vt as NotificationAiPendingPayloadSchema, w as SegmentRepository, wt as NotificationDispatchedPayloadSchema, x as ContactRepository, xt as NotificationFailedPayloadSchema, y as interpolate, yn as setGlobalConfig, yt as NotificationCanceledPayloadSchema, z as AsyncSemaphore, zt as NotifyRequestSchema } from "./src-CPMwsUCJ.mjs";
3
3
  //#region src/transport/index.ts
4
4
  var transport_exports = /* @__PURE__ */ __exportAll({
5
5
  registerTransport: () => registerTransport,
@@ -33,6 +33,6 @@ function registerTransport(transport, priority = 0) {
33
33
  transportRegistry.register(transport, priority);
34
34
  }
35
35
  //#endregion
36
- export { AI_DEFAULTS, AddContactSchema, AddUserSchema, AppError, AsyncSemaphore, BaseWorker, BatchProcessor, CONSUMER_GROUPS, CircuitBreaker, ContactChannelSchema, ContactRepository, CreateWorkflowSchema, DataLoader, DeliveryOptionsSchema, ENRICHED_STREAMS, EventEnvelopeSchema, EventMetadataSchema, EventRegistry, INBOUND_STREAMS, IdempotencyGuard, IngestEventSchema, InlineUserSchema, LRUCache, LUA_RELEASE_LOCK, LUA_RENEW_LOCK, LUA_SCHEDULER_CLAIM, LUA_SCHEDULER_POLL, NonRetryableError, NotificationAiPendingPayloadSchema, NotificationCanceledPayloadSchema, NotificationChannelSchema, NotificationCreatedPayloadSchema, NotificationDeliveredPayloadSchema, NotificationDispatchedPayloadSchema, NotificationEnrichedPayloadSchema, NotificationFailedPayloadSchema, NotificationPrioritySchema, NotificationRequestedPayloadSchema, NotificationScheduledPayloadSchema, NotificationSkippedPayloadSchema, NotificationStatusSchema, NotificationTargetSchema, NotifkitClient, NotifkitServer, NotifyRequestSchema, OUTBOUND_STREAMS, PUBSUB_CHANNELS, PendingMessageScanner, PreferenceRepository, PreferencesSchema, ProjectRepository, ProjectSettingsCache, QuietHoursSchema, RecipientProfileSchema, Redis, RedisClient, RenderedContentSchema, STREAMS, SegmentRepository, StreamConsumer, StreamEventMetadataSchema, StreamEventSchema, StreamProducer, SuspendExecutionError, SyncTemplatesSchema, TemplateCache, TemplateRepository, TemplateSchema, TriggerWorkflowSchema, UpdateProjectSchema, UpdateUserSchema, UserRepository, UserThrottle, ValidationError, WorkflowNotifyPayloadSchema, WorkflowRepository, WorkflowStepSchema, baseConfigSchema, buildStepNotifyPayload, buildStreamEvent, buildUnsubscribeHeaders, childLogger, createDatabase, createLogger, escapeHeader, escapeHtml, generateId, getAiConfig, getMetricsRegistry, getPriorityBucket, globalEmitter, interpolate, loadEnv, metrics, normaliseTarget, parseConfig, readBaseConfig, registerTransport, registry, renderTemplate, renderWithTemplate, resolveStepTarget, runMigrations, setAiConfig, setGlobalConfig, signUnsubscribeToken, sleep, startHealthReporter, transport_exports as t, templateRegistry, transportRegistry, verifyUnsubscribeToken, withContext, withRequestId, workflow, workflowRegistry };
36
+ export { AI_DEFAULTS, AddContactSchema, AddUserSchema, AppError, AsyncSemaphore, BaseWorker, BatchAddContactsSchema, BatchProcessor, CONSUMER_GROUPS, CircuitBreaker, ContactChannelSchema, ContactRepository, CreateWorkflowSchema, DataLoader, DeliveryOptionsSchema, ENRICHED_STREAMS, EventEnvelopeSchema, EventMetadataSchema, EventRegistry, INBOUND_STREAMS, IdempotencyGuard, IngestEventSchema, InlineUserSchema, LRUCache, LUA_RELEASE_LOCK, LUA_RENEW_LOCK, LUA_SCHEDULER_CLAIM, LUA_SCHEDULER_POLL, NonRetryableError, NotificationAiPendingPayloadSchema, NotificationCanceledPayloadSchema, NotificationChannelSchema, NotificationCreatedPayloadSchema, NotificationDeliveredPayloadSchema, NotificationDispatchedPayloadSchema, NotificationEnrichedPayloadSchema, NotificationFailedPayloadSchema, NotificationPrioritySchema, NotificationRequestedPayloadSchema, NotificationScheduledPayloadSchema, NotificationSkippedPayloadSchema, NotificationStatusSchema, NotificationTargetSchema, NotifkitClient, NotifkitServer, NotifyRequestSchema, OUTBOUND_STREAMS, PUBSUB_CHANNELS, PendingMessageScanner, PreferenceRepository, PreferencesSchema, ProjectRepository, ProjectSettingsCache, QuietHoursSchema, RecipientProfileSchema, Redis, RedisClient, RenderedContentSchema, STREAMS, SegmentRepository, StreamConsumer, StreamEventMetadataSchema, StreamEventSchema, StreamProducer, SuspendExecutionError, SyncTemplatesSchema, TemplateCache, TemplateRepository, TemplateSchema, TriggerWorkflowSchema, UpdateProjectSchema, UpdateUserSchema, UserContactInputSchema, UserRepository, UserThrottle, ValidationError, WorkflowNotifyPayloadSchema, WorkflowRepository, WorkflowStepSchema, baseConfigSchema, buildStepNotifyPayload, buildStreamEvent, buildUnsubscribeHeaders, childLogger, createDatabase, createLogger, escapeHeader, escapeHtml, generateId, getAiConfig, getMetricsRegistry, getPriorityBucket, globalEmitter, interpolate, loadEnv, metrics, normaliseTarget, parseConfig, readBaseConfig, registerTransport, registry, renderTemplate, renderWithTemplate, resolveStepTarget, runMigrations, setAiConfig, setGlobalConfig, signUnsubscribeToken, sleep, startHealthReporter, transport_exports as t, templateRegistry, transportRegistry, verifyUnsubscribeToken, withContext, withRequestId, workflow, workflowRegistry };
37
37
 
38
38
  //# sourceMappingURL=index.mjs.map
@@ -1,4 +1,4 @@
1
- import { E as UserRepository, J as PendingMessageScanner, Jt as buildStreamEvent, S as PreferenceRepository, T as TemplateRepository, W as getPriorityBucket, X as StreamProducer, Y as StreamConsumer, Yt as CONSUMER_GROUPS, Zt as INBOUND_STREAMS, an as registry, c as BaseWorker, en as STREAMS, et as createLogger, g as TemplateCache, hn as readBaseConfig, it as createDatabase, k as RedisClient, pn as loadEnv, rt as IdempotencyGuard, u as startHealthReporter, x as ContactRepository } from "./src-vG79L-8m.mjs";
1
+ import { $t as INBOUND_STREAMS, E as UserRepository, J as PendingMessageScanner, S as PreferenceRepository, T as TemplateRepository, W as getPriorityBucket, X as StreamProducer, Xt as buildStreamEvent, Y as StreamConsumer, Zt as CONSUMER_GROUPS, _n as readBaseConfig, c as BaseWorker, et as createLogger, g as TemplateCache, hn as loadEnv, it as createDatabase, k as RedisClient, nn as STREAMS, rt as IdempotencyGuard, sn as registry, u as startHealthReporter, x as ContactRepository } from "./src-CPMwsUCJ.mjs";
2
2
  //#region src/services/enricher/main.ts
3
3
  loadEnv();
4
4
  const config = readBaseConfig();
@@ -430,4 +430,4 @@ async function stopEnricherWorker() {
430
430
  //#endregion
431
431
  export { startEnricherWorker, stopEnricherWorker };
432
432
 
433
- //# sourceMappingURL=main-DeNFQ-UL.mjs.map
433
+ //# sourceMappingURL=main-Bgi2wWck.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"main-DeNFQ-UL.mjs","names":[],"sources":["../src/services/enricher/main.ts"],"sourcesContent":["import { loadEnv, readBaseConfig } from \"@/index.js\";\nimport { createLogger } from \"@/index.js\";\nimport { RedisClient } from \"@/index.js\";\nimport {\n StreamConsumer,\n PendingMessageScanner,\n StreamProducer,\n type StreamMessage,\n} from \"@/index.js\";\nimport { BaseWorker } from \"@/index.js\";\nimport {\n STREAMS,\n INBOUND_STREAMS,\n CONSUMER_GROUPS,\n registry,\n buildStreamEvent,\n type NotificationCreatedPayload,\n type NotificationEnrichedPayload,\n} from \"@/index.js\";\nimport { type StreamName } from \"@/contracts/streams.js\";\nimport { IdempotencyGuard } from \"@/index.js\";\nimport { createDatabase } from \"@/db/index.js\";\nimport {\n UserRepository,\n PreferenceRepository,\n TemplateRepository,\n ContactRepository,\n} from \"@/index.js\";\nimport { TemplateCache } from \"@/templates/index.js\";\nimport { getPriorityBucket, type WorkerOptions } from \"@/shared/index.js\";\nimport { startHealthReporter } from \"@/workers/index.js\";\n\n// ─── Bootstrap ─────────────────────────────────────────────────────────────\n\nloadEnv();\nconst config = readBaseConfig();\n\nlet logger: ReturnType<typeof createLogger>;\nlet redis: RedisClient;\nlet sql: any;\nlet db: any;\n\nlet consumer: StreamConsumer;\nlet pendingScanner: PendingMessageScanner;\nlet worker: BaseWorker;\nlet healthInterval: NodeJS.Timeout | null = null;\n\nexport interface EnricherWorkerOptions extends WorkerOptions {\n producers: any;\n idempotency: any;\n userRepo: any;\n prefRepo: any;\n contactRepo: any;\n templateCache: TemplateCache;\n}\n\nexport class EnricherWorker extends BaseWorker {\n private readonly producers: any;\n private readonly idempotency: any;\n private readonly userRepo: any;\n private readonly prefRepo: any;\n private readonly contactRepo: any;\n private readonly templateCache: TemplateCache;\n\n private userBatch: {\n projectId: string;\n userId: string;\n resolve: (p: any) => void;\n reject: (e: any) => void;\n }[] = [];\n private batchTimer: NodeJS.Timeout | null = null;\n private eventBuffer: {\n producer: any;\n event: any;\n resolve: () => void;\n reject: (e: any) => void;\n }[] = [];\n private flushTimer: NodeJS.Timeout | null = null;\n\n private contactBatch: {\n projectId: string;\n userIds: string[];\n resolve: (c: Map<string, any[]>) => void;\n reject: (e: any) => void;\n }[] = [];\n private contactBatchTimer: NodeJS.Timeout | null = null;\n\n private async loadContacts(projectId: string, userIds: string[]): Promise<Map<string, any[]>> {\n return new Promise((resolve, reject) => {\n this.contactBatch.push({ projectId, userIds, resolve, reject });\n if (this.contactBatch.length >= 500) {\n if (this.contactBatchTimer) clearTimeout(this.contactBatchTimer);\n void this.flushContactBatch();\n } else if (!this.contactBatchTimer) {\n this.contactBatchTimer = setTimeout(() => void this.flushContactBatch(), 10);\n }\n });\n }\n\n private async flushContactBatch(): Promise<void> {\n const batch = this.contactBatch;\n this.contactBatch = [];\n this.contactBatchTimer = null;\n if (batch.length === 0) return;\n\n try {\n const byProject = new Map<string, typeof batch>();\n for (const b of batch) {\n if (!byProject.has(b.projectId)) byProject.set(b.projectId, []);\n byProject.get(b.projectId)!.push(b);\n }\n\n for (const [projectId, items] of byProject) {\n const userIds = Array.from(new Set(items.flatMap((i) => i.userIds)));\n const contactsMap = await this.contactRepo.findActiveByUserIds(projectId, userIds);\n for (const item of items) {\n item.resolve(contactsMap);\n }\n }\n } catch (err) {\n for (const b of batch) b.reject(err);\n }\n }\n\n constructor(options: EnricherWorkerOptions) {\n super(options);\n this.producers = options.producers;\n this.idempotency = options.idempotency;\n this.userRepo = options.userRepo;\n this.prefRepo = options.prefRepo;\n this.contactRepo = options.contactRepo;\n this.templateCache = options.templateCache;\n\n this.flushTimer = setInterval(() => void this.flushWorkerBuffers(), 100);\n }\n\n override async stop(): Promise<void> {\n if (this.batchTimer) {\n clearTimeout(this.batchTimer);\n this.batchTimer = null;\n }\n if (this.flushTimer) {\n clearInterval(this.flushTimer);\n this.flushTimer = null;\n }\n if (this.contactBatchTimer) {\n clearTimeout(this.contactBatchTimer);\n this.contactBatchTimer = null;\n }\n await this.flushContactBatch();\n await this.flushUserBatch();\n await this.flushWorkerBuffers();\n await super.stop();\n }\n\n private async flushWorkerBuffers(): Promise<void> {\n if (this.eventBuffer.length === 0) return;\n const events = this.eventBuffer;\n this.eventBuffer = [];\n\n try {\n const byProducer = new Map<any, typeof events>();\n for (const e of events) {\n if (!byProducer.has(e.producer)) byProducer.set(e.producer, []);\n byProducer.get(e.producer)!.push(e);\n }\n for (const [producer, batch] of byProducer) {\n await producer.publishBatch(batch.map((b) => b.event));\n for (const b of batch) b.resolve();\n }\n } catch (err: any) {\n this.logger.error({ err }, \"failed to flush events in EnricherWorker\");\n for (const e of events) e.reject(err);\n }\n }\n\n private async loadUser(projectId: string, userId: string): Promise<any> {\n return new Promise((resolve, reject) => {\n this.userBatch.push({ projectId, userId, resolve, reject });\n if (this.userBatch.length >= 500) {\n if (this.batchTimer) clearTimeout(this.batchTimer);\n void this.flushUserBatch();\n } else if (!this.batchTimer) {\n this.batchTimer = setTimeout(() => {\n void this.flushUserBatch();\n }, 10);\n }\n });\n }\n\n private async flushUserBatch() {\n const batch = this.userBatch;\n this.userBatch = [];\n this.batchTimer = null;\n\n const byProject = new Map<string, typeof batch>();\n for (const b of batch) {\n if (!byProject.has(b.projectId)) byProject.set(b.projectId, []);\n byProject.get(b.projectId)!.push(b);\n }\n\n for (const [projectId, reqs] of byProject.entries()) {\n try {\n const uniqueIds = Array.from(new Set(reqs.map((r) => r.userId)));\n const profiles = await this.userRepo.findRecordsByIds(projectId, uniqueIds);\n const profileMap = new Map(profiles.map((p: any) => [p.userId, p]));\n\n for (const req of reqs) {\n req.resolve(profileMap.get(req.userId) || null);\n }\n } catch (err) {\n for (const req of reqs) req.reject(err);\n }\n }\n }\n\n async process(message: StreamMessage): Promise<void> {\n const { event } = message;\n const publishPromises: Promise<void>[] = [];\n\n let isRequested = true;\n const requestedResult = registry.safeParsePayload(\"notification.requested\", event.payload);\n let createdResult: any = null;\n if (!requestedResult.success) {\n createdResult = registry.safeParsePayload(\"notification.created\", event.payload);\n isRequested = false;\n }\n\n if (!isRequested && (!createdResult || !createdResult.success)) {\n const issues = createdResult\n ? createdResult.error.issues\n : (requestedResult as any).error.issues;\n this.logger.warn({ messageId: message.id, issues }, \"invalid payload — skipping\");\n return;\n }\n\n // Handle legacy notification.created\n if (!isRequested) {\n const raw = createdResult.data as NotificationCreatedPayload;\n const dedupeId = `${raw.projectId}:${raw.idempotencyKey ?? event.id}`;\n if (!(await this.idempotency.checkAndMark(dedupeId, 60))) return;\n try {\n const profile = await this.userRepo.findRecordById(raw.projectId, raw.recipientId);\n if (!profile) return;\n\n const prefs = await this.prefRepo.findByUserId(raw.projectId, raw.recipientId);\n const optedOutTypes = new Set(\n prefs.filter((p: any) => !p.optedIn).map((p: any) => p.eventType),\n );\n\n const enrichedPayload: NotificationEnrichedPayload = {\n projectId: raw.projectId,\n rawEventId: event.id,\n recipientId: raw.recipientId,\n channel: raw.channel,\n priority: raw.priority,\n templateId: raw.templateId,\n templateVariables: raw.payload,\n recipient: {\n id: profile.userId,\n email: profile.email ?? undefined,\n locale: profile.language ?? \"en\",\n timezone: profile.timezone ?? \"UTC\",\n preferences: {\n optedOut:\n optedOutTypes.has(event.type) || profile.preferences.topics?.[event.type] === false,\n channels: Object.entries(profile.preferences.channels ?? {})\n .filter(([_, enabled]) => !enabled)\n .map(([channel]) => channel as any),\n quietHours: profile.preferences.quietHours,\n },\n },\n // No campaignId: this is the legacy `notification.created` path,\n // which predates campaigns and carries no label to attribute to.\n scheduledAt: raw.scheduledAt,\n };\n\n const p = getPriorityBucket(raw.priority);\n const producer = this.producers[p] ?? this.producers[\"normal\"]!;\n\n publishPromises.push(\n new Promise((resolve, reject) => {\n this.eventBuffer.push({\n producer,\n event: buildStreamEvent(\n \"notification.enriched\",\n enrichedPayload as Record<string, unknown>,\n \"enricher\",\n event.metadata.traceId,\n ),\n resolve,\n reject,\n });\n }),\n );\n this.logger.info(\n { messageId: message.id, eventId: event.id, recipientId: raw.recipientId },\n \"event enriched\",\n );\n } catch (err) {\n throw err;\n }\n await Promise.all(publishPromises).catch(async (err) => {\n await this.idempotency.unmark(dedupeId).catch(() => {});\n throw err;\n });\n await this.idempotency.markProcessed(dedupeId);\n return;\n }\n\n // Handle new notification.requested\n const raw = (requestedResult as any).data;\n const dedupeId = `${raw.projectId}:${raw.idempotencyKey ?? event.id}`;\n if (!(await this.idempotency.checkAndMark(dedupeId, 60))) return;\n try {\n let userIds: string[] = [];\n if (raw.target.type === \"user\") {\n userIds = [raw.target.userId];\n } else if (raw.target.type === \"segment\") {\n userIds = await this.userRepo.findUsersBySegment(raw.projectId, raw.target.segment);\n this.logger.info(\n { segment: raw.target.segment, count: userIds.length },\n \"Resolved segment\",\n );\n } else if (raw.target.type === \"topic\") {\n userIds = await this.userRepo.findUsersByTopic(raw.projectId, raw.target.topic);\n this.logger.info({ topic: raw.target.topic, count: userIds.length }, \"Resolved topic\");\n } else {\n this.logger.warn({ target: raw.target }, \"Segment/topic resolution not fully implemented\");\n // Stub: maybe resolve later\n }\n\n const maxUsers = readBaseConfig().SEGMENT_MAX_USERS;\n if (userIds.length > maxUsers) {\n this.logger.error(\n { count: userIds.length, max: maxUsers, projectId: raw.projectId, eventId: event.id },\n \"Segment fan-out exceeds maximum allowed limit\",\n );\n const p = getPriorityBucket(raw.priority ?? \"normal\");\n const producer = this.producers[p] ?? this.producers.normal;\n await producer.publish(\n buildStreamEvent(\n \"notification.failed\",\n {\n projectId: raw.projectId,\n rawEventId: event.id,\n error: `Segment fan-out of ${userIds.length} exceeds limit of ${maxUsers}`,\n },\n \"enricher\",\n event.metadata.traceId,\n ),\n );\n return;\n }\n\n // Topic opt-outs are keyed on the TEMPLATE's topics, not the envelope type.\n // `event.type` here is \"notification.requested\", which no user ever sets a\n // preference against, so keying on it silently disabled every opt-out.\n const template = raw.templateId\n ? await this.templateCache.getCachedTemplate(raw.projectId, raw.templateId)\n : null;\n const topics: string[] = template?.topics ?? [];\n\n const channels =\n raw.channels && raw.channels.length > 0 ? raw.channels : ([\"email\"] as any[]);\n const isFallback = (raw as any).fallback === true;\n\n // If fallback is true, we only emit the first channel, and pass the rest in fallbackChain.\n // If fallback is false, we emit all channels concurrently.\n const channelsToProcess = isFallback ? [channels[0]] : channels;\n const fallbackChain = isFallback ? channels.slice(1) : undefined;\n\n const chunkArray = <T>(arr: T[], size: number) =>\n Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>\n arr.slice(i * size, i * size + size),\n );\n\n const chunks = chunkArray(userIds, 500);\n\n for (const chunk of chunks) {\n const profiles = (\n await Promise.all(chunk.map((id) => this.loadUser(raw.projectId, id)))\n ).filter(Boolean);\n const contactsByUser = await this.loadContacts(\n raw.projectId,\n profiles.map((profile: any) => profile.userId),\n );\n\n const batchedEvents: Record<\n \"critical\" | \"high\" | \"normal\" | \"low\",\n Omit<any, \"id\" | \"timestamp\">[]\n > = {\n critical: [],\n high: [],\n normal: [],\n low: [],\n };\n\n for (const profile of profiles) {\n for (const channel of channelsToProcess) {\n const contacts = contactsByUser.get(profile.userId) ?? [];\n const channelContacts = contacts.filter((contact: any) => contact.channel === channel);\n // Push resolves its active tokens at send time so token invalidation\n // remains current. Other channels need one task per address.\n const destinations =\n channel === \"push\" ? [undefined] : channelContacts.map((c: any) => c.target);\n if (destinations.length === 0) {\n this.logger.info(\n { recipientId: profile.userId, channel },\n \"no active contact for channel\",\n );\n continue;\n }\n for (const destination of destinations) {\n const enrichedPayload: NotificationEnrichedPayload = {\n projectId: raw.projectId,\n rawEventId: event.id,\n recipientId: profile.userId,\n channel: channel,\n priority: \"normal\",\n templateId: raw.templateId,\n templateVariables: raw.data,\n aiPrompts: raw.aiPrompts,\n recipient: {\n id: profile.userId,\n email:\n channel === \"email\"\n ? (destination ?? profile.email ?? undefined)\n : (profile.email ?? undefined),\n phone: channel === \"sms\" || channel === \"whatsapp\" ? destination : undefined,\n webhook: channel === \"webhook\" ? destination : undefined,\n telegram: channel === \"telegram\" ? destination : undefined,\n discord: channel === \"discord\" ? destination : undefined,\n slack: channel === \"slack\" ? destination : undefined,\n locale: profile.language ?? \"en\",\n timezone: profile.timezone ?? \"UTC\",\n preferences: {\n // Opted out if the user disabled ANY topic this template carries.\n optedOut: topics.some((t) => profile.preferences.topics?.[t] === false),\n channels: Object.entries(profile.preferences.channels ?? {})\n .filter(([_, enabled]) => !enabled)\n .map(([channel]) => channel as any),\n quietHours: profile.preferences.quietHours,\n },\n },\n scheduledAt: raw.scheduledAt,\n fallbackChain: fallbackChain?.length ? fallbackChain : undefined,\n campaignId: raw.campaignId,\n };\n\n const msgPriority = raw.priority ?? \"normal\";\n const p = getPriorityBucket(msgPriority);\n\n enrichedPayload.priority = msgPriority;\n\n batchedEvents[p].push(\n buildStreamEvent(\n \"notification.enriched\",\n enrichedPayload as Record<string, unknown>,\n \"enricher\",\n event.metadata.traceId,\n ),\n );\n }\n }\n }\n\n for (const p of [\"critical\", \"normal\", \"low\"] as const) {\n if (batchedEvents[p].length > 0) {\n const producer = this.producers[p] ?? this.producers.normal;\n for (const ev of batchedEvents[p]) {\n publishPromises.push(\n new Promise((resolve, reject) => {\n this.eventBuffer.push({ producer, event: ev, resolve, reject });\n }),\n );\n }\n }\n }\n }\n\n this.logger.info(\n {\n messageId: message.id,\n eventId: event.id,\n target: raw.target.type,\n traceId: event.metadata.traceId,\n },\n \"event enriched\",\n );\n } catch (err) {\n throw err;\n }\n\n await Promise.all(publishPromises).catch(async (err) => {\n await this.idempotency.unmark(dedupeId).catch(() => {});\n throw err;\n });\n\n await this.idempotency.markProcessed(dedupeId);\n }\n}\n\nexport async function startEnricherWorker() {\n logger = createLogger({ name: \"enricher\", level: config.LOG_LEVEL });\n redis = new RedisClient({ url: config.REDIS_URL, name: \"enricher\", logger });\n const dbData = createDatabase({ url: config.DATABASE_URL, applicationName: \"enricher\", logger });\n sql = dbData.sql;\n db = dbData.db;\n consumer = new StreamConsumer({\n redis: redis.native,\n stream: INBOUND_STREAMS as unknown as StreamName[],\n group: CONSUMER_GROUPS.ENRICHER,\n consumer: `enricher-${process.pid}`,\n dlqStream: STREAMS.DEAD_LETTER,\n batchSize: config.WORKER_CONCURRENCY,\n logger,\n });\n\n pendingScanner = new PendingMessageScanner({\n redis: redis.native,\n stream: INBOUND_STREAMS as unknown as StreamName[],\n group: CONSUMER_GROUPS.ENRICHER,\n consumer: `enricher-${process.pid}`,\n logger,\n });\n\n const producers = {\n critical: new StreamProducer({\n redis: redis.native,\n stream: STREAMS.ENRICHED_CRITICAL,\n logger,\n }),\n normal: new StreamProducer({ redis: redis.native, stream: STREAMS.ENRICHED_NORMAL, logger }),\n low: new StreamProducer({ redis: redis.native, stream: STREAMS.ENRICHED_LOW, logger }),\n };\n\n const idempotency = new IdempotencyGuard({\n redis: redis.native,\n keyPrefix: \"notif:processed:enricher\",\n ttlSeconds: 86_400,\n });\n\n const userRepo = new UserRepository(db);\n const prefRepo = new PreferenceRepository(db);\n const contactRepo = new ContactRepository(db);\n const templateCache = new TemplateCache(new TemplateRepository(db));\n\n // ─── Stage 1: Context Enricher ──────────────────────────────────────────────\n //\n // Pipeline:\n // 1. Parse payload as notification.created\n // 2. Idempotency check — drop if already processed\n // 3. Load user profile (language, timezone) from DB\n // 4. Load all stored preferences for this user\n // 5. Publish notification.enriched to ENRICHED stream\n\n // 5. Publish notification.enriched to ENRICHED stream\n\n worker = new EnricherWorker({\n consumer,\n pendingScanner,\n logger,\n maxRetriesBeforeDlq: 5,\n concurrency: config.WORKER_CONCURRENCY,\n producers,\n idempotency,\n userRepo,\n prefRepo,\n contactRepo,\n templateCache,\n });\n\n // ─── Health check interval ──────────────────────────────────────────────────\n\n healthInterval = startHealthReporter(\"enricher\", worker, redis, logger);\n\n logger.info({ env: config.NODE_ENV }, \"enricher starting\");\n await worker.start();\n}\n\n// ─── Shutdown ──────────────────────────────────────────────────────────────\n\nexport async function stopEnricherWorker(): Promise<void> {\n logger?.info(\"shutdown initiated\");\n if (healthInterval) {\n clearInterval(healthInterval);\n healthInterval = null;\n }\n if (worker) await worker.stop();\n if (sql) await sql.end();\n if (redis) await redis.disconnect();\n logger?.info(\"enricher stopped\");\n}\n"],"mappings":";;AAkCA,QAAQ;AACR,MAAM,SAAS,eAAe;AAE9B,IAAI;AACJ,IAAI;AACJ,IAAI;A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AM,OAAO,KAAK;CAC9B,IAAI,KAAK,MAAM,IAAI,IAAI;CACvB,IAAI,OAAO,MAAM,MAAM,WAAW;CAClC,QAAQ,KAAK,kBAAkB;AACjC"}
1
+ {"version":3,"file":"main-Bgi2wWck.mjs","names":[],"sources":["../src/services/enricher/main.ts"],"sourcesContent":["import { loadEnv, readBaseConfig } from \"@/index.js\";\nimport { createLogger } from \"@/index.js\";\nimport { RedisClient } from \"@/index.js\";\nimport {\n StreamConsumer,\n PendingMessageScanner,\n StreamProducer,\n type StreamMessage,\n} from \"@/index.js\";\nimport { BaseWorker } from \"@/index.js\";\nimport {\n STREAMS,\n INBOUND_STREAMS,\n CONSUMER_GROUPS,\n registry,\n buildStreamEvent,\n type NotificationCreatedPayload,\n type NotificationEnrichedPayload,\n} from \"@/index.js\";\nimport { type StreamName } from \"@/contracts/streams.js\";\nimport { IdempotencyGuard } from \"@/index.js\";\nimport { createDatabase } from \"@/db/index.js\";\nimport {\n UserRepository,\n PreferenceRepository,\n TemplateRepository,\n ContactRepository,\n} from \"@/index.js\";\nimport { TemplateCache } from \"@/templates/index.js\";\nimport { getPriorityBucket, type WorkerOptions } from \"@/shared/index.js\";\nimport { startHealthReporter } from \"@/workers/index.js\";\n\n// ─── Bootstrap ─────────────────────────────────────────────────────────────\n\nloadEnv();\nconst config = readBaseConfig();\n\nlet logger: ReturnType<typeof createLogger>;\nlet redis: RedisClient;\nlet sql: any;\nlet db: any;\n\nlet consumer: StreamConsumer;\nlet pendingScanner: PendingMessageScanner;\nlet worker: BaseWorker;\nlet healthInterval: NodeJS.Timeout | null = null;\n\nexport interface EnricherWorkerOptions extends WorkerOptions {\n producers: any;\n idempotency: any;\n userRepo: any;\n prefRepo: any;\n contactRepo: any;\n templateCache: TemplateCache;\n}\n\nexport class EnricherWorker extends BaseWorker {\n private readonly producers: any;\n private readonly idempotency: any;\n private readonly userRepo: any;\n private readonly prefRepo: any;\n private readonly contactRepo: any;\n private readonly templateCache: TemplateCache;\n\n private userBatch: {\n projectId: string;\n userId: string;\n resolve: (p: any) => void;\n reject: (e: any) => void;\n }[] = [];\n private batchTimer: NodeJS.Timeout | null = null;\n private eventBuffer: {\n producer: any;\n event: any;\n resolve: () => void;\n reject: (e: any) => void;\n }[] = [];\n private flushTimer: NodeJS.Timeout | null = null;\n\n private contactBatch: {\n projectId: string;\n userIds: string[];\n resolve: (c: Map<string, any[]>) => void;\n reject: (e: any) => void;\n }[] = [];\n private contactBatchTimer: NodeJS.Timeout | null = null;\n\n private async loadContacts(projectId: string, userIds: string[]): Promise<Map<string, any[]>> {\n return new Promise((resolve, reject) => {\n this.contactBatch.push({ projectId, userIds, resolve, reject });\n if (this.contactBatch.length >= 500) {\n if (this.contactBatchTimer) clearTimeout(this.contactBatchTimer);\n void this.flushContactBatch();\n } else if (!this.contactBatchTimer) {\n this.contactBatchTimer = setTimeout(() => void this.flushContactBatch(), 10);\n }\n });\n }\n\n private async flushContactBatch(): Promise<void> {\n const batch = this.contactBatch;\n this.contactBatch = [];\n this.contactBatchTimer = null;\n if (batch.length === 0) return;\n\n try {\n const byProject = new Map<string, typeof batch>();\n for (const b of batch) {\n if (!byProject.has(b.projectId)) byProject.set(b.projectId, []);\n byProject.get(b.projectId)!.push(b);\n }\n\n for (const [projectId, items] of byProject) {\n const userIds = Array.from(new Set(items.flatMap((i) => i.userIds)));\n const contactsMap = await this.contactRepo.findActiveByUserIds(projectId, userIds);\n for (const item of items) {\n item.resolve(contactsMap);\n }\n }\n } catch (err) {\n for (const b of batch) b.reject(err);\n }\n }\n\n constructor(options: EnricherWorkerOptions) {\n super(options);\n this.producers = options.producers;\n this.idempotency = options.idempotency;\n this.userRepo = options.userRepo;\n this.prefRepo = options.prefRepo;\n this.contactRepo = options.contactRepo;\n this.templateCache = options.templateCache;\n\n this.flushTimer = setInterval(() => void this.flushWorkerBuffers(), 100);\n }\n\n override async stop(): Promise<void> {\n if (this.batchTimer) {\n clearTimeout(this.batchTimer);\n this.batchTimer = null;\n }\n if (this.flushTimer) {\n clearInterval(this.flushTimer);\n this.flushTimer = null;\n }\n if (this.contactBatchTimer) {\n clearTimeout(this.contactBatchTimer);\n this.contactBatchTimer = null;\n }\n await this.flushContactBatch();\n await this.flushUserBatch();\n await this.flushWorkerBuffers();\n await super.stop();\n }\n\n private async flushWorkerBuffers(): Promise<void> {\n if (this.eventBuffer.length === 0) return;\n const events = this.eventBuffer;\n this.eventBuffer = [];\n\n try {\n const byProducer = new Map<any, typeof events>();\n for (const e of events) {\n if (!byProducer.has(e.producer)) byProducer.set(e.producer, []);\n byProducer.get(e.producer)!.push(e);\n }\n for (const [producer, batch] of byProducer) {\n await producer.publishBatch(batch.map((b) => b.event));\n for (const b of batch) b.resolve();\n }\n } catch (err: any) {\n this.logger.error({ err }, \"failed to flush events in EnricherWorker\");\n for (const e of events) e.reject(err);\n }\n }\n\n private async loadUser(projectId: string, userId: string): Promise<any> {\n return new Promise((resolve, reject) => {\n this.userBatch.push({ projectId, userId, resolve, reject });\n if (this.userBatch.length >= 500) {\n if (this.batchTimer) clearTimeout(this.batchTimer);\n void this.flushUserBatch();\n } else if (!this.batchTimer) {\n this.batchTimer = setTimeout(() => {\n void this.flushUserBatch();\n }, 10);\n }\n });\n }\n\n private async flushUserBatch() {\n const batch = this.userBatch;\n this.userBatch = [];\n this.batchTimer = null;\n\n const byProject = new Map<string, typeof batch>();\n for (const b of batch) {\n if (!byProject.has(b.projectId)) byProject.set(b.projectId, []);\n byProject.get(b.projectId)!.push(b);\n }\n\n for (const [projectId, reqs] of byProject.entries()) {\n try {\n const uniqueIds = Array.from(new Set(reqs.map((r) => r.userId)));\n const profiles = await this.userRepo.findRecordsByIds(projectId, uniqueIds);\n const profileMap = new Map(profiles.map((p: any) => [p.userId, p]));\n\n for (const req of reqs) {\n req.resolve(profileMap.get(req.userId) || null);\n }\n } catch (err) {\n for (const req of reqs) req.reject(err);\n }\n }\n }\n\n async process(message: StreamMessage): Promise<void> {\n const { event } = message;\n const publishPromises: Promise<void>[] = [];\n\n let isRequested = true;\n const requestedResult = registry.safeParsePayload(\"notification.requested\", event.payload);\n let createdResult: any = null;\n if (!requestedResult.success) {\n createdResult = registry.safeParsePayload(\"notification.created\", event.payload);\n isRequested = false;\n }\n\n if (!isRequested && (!createdResult || !createdResult.success)) {\n const issues = createdResult\n ? createdResult.error.issues\n : (requestedResult as any).error.issues;\n this.logger.warn({ messageId: message.id, issues }, \"invalid payload — skipping\");\n return;\n }\n\n // Handle legacy notification.created\n if (!isRequested) {\n const raw = createdResult.data as NotificationCreatedPayload;\n const dedupeId = `${raw.projectId}:${raw.idempotencyKey ?? event.id}`;\n if (!(await this.idempotency.checkAndMark(dedupeId, 60))) return;\n try {\n const profile = await this.userRepo.findRecordById(raw.projectId, raw.recipientId);\n if (!profile) return;\n\n const prefs = await this.prefRepo.findByUserId(raw.projectId, raw.recipientId);\n const optedOutTypes = new Set(\n prefs.filter((p: any) => !p.optedIn).map((p: any) => p.eventType),\n );\n\n const enrichedPayload: NotificationEnrichedPayload = {\n projectId: raw.projectId,\n rawEventId: event.id,\n recipientId: raw.recipientId,\n channel: raw.channel,\n priority: raw.priority,\n templateId: raw.templateId,\n templateVariables: raw.payload,\n recipient: {\n id: profile.userId,\n email: profile.email ?? undefined,\n locale: profile.language ?? \"en\",\n timezone: profile.timezone ?? \"UTC\",\n preferences: {\n optedOut:\n optedOutTypes.has(event.type) || profile.preferences.topics?.[event.type] === false,\n channels: Object.entries(profile.preferences.channels ?? {})\n .filter(([_, enabled]) => !enabled)\n .map(([channel]) => channel as any),\n quietHours: profile.preferences.quietHours,\n },\n },\n // No campaignId: this is the legacy `notification.created` path,\n // which predates campaigns and carries no label to attribute to.\n scheduledAt: raw.scheduledAt,\n };\n\n const p = getPriorityBucket(raw.priority);\n const producer = this.producers[p] ?? this.producers[\"normal\"]!;\n\n publishPromises.push(\n new Promise((resolve, reject) => {\n this.eventBuffer.push({\n producer,\n event: buildStreamEvent(\n \"notification.enriched\",\n enrichedPayload as Record<string, unknown>,\n \"enricher\",\n event.metadata.traceId,\n ),\n resolve,\n reject,\n });\n }),\n );\n this.logger.info(\n { messageId: message.id, eventId: event.id, recipientId: raw.recipientId },\n \"event enriched\",\n );\n } catch (err) {\n throw err;\n }\n await Promise.all(publishPromises).catch(async (err) => {\n await this.idempotency.unmark(dedupeId).catch(() => {});\n throw err;\n });\n await this.idempotency.markProcessed(dedupeId);\n return;\n }\n\n // Handle new notification.requested\n const raw = (requestedResult as any).data;\n const dedupeId = `${raw.projectId}:${raw.idempotencyKey ?? event.id}`;\n if (!(await this.idempotency.checkAndMark(dedupeId, 60))) return;\n try {\n let userIds: string[] = [];\n if (raw.target.type === \"user\") {\n userIds = [raw.target.userId];\n } else if (raw.target.type === \"segment\") {\n userIds = await this.userRepo.findUsersBySegment(raw.projectId, raw.target.segment);\n this.logger.info(\n { segment: raw.target.segment, count: userIds.length },\n \"Resolved segment\",\n );\n } else if (raw.target.type === \"topic\") {\n userIds = await this.userRepo.findUsersByTopic(raw.projectId, raw.target.topic);\n this.logger.info({ topic: raw.target.topic, count: userIds.length }, \"Resolved topic\");\n } else {\n this.logger.warn({ target: raw.target }, \"Segment/topic resolution not fully implemented\");\n // Stub: maybe resolve later\n }\n\n const maxUsers = readBaseConfig().SEGMENT_MAX_USERS;\n if (userIds.length > maxUsers) {\n this.logger.error(\n { count: userIds.length, max: maxUsers, projectId: raw.projectId, eventId: event.id },\n \"Segment fan-out exceeds maximum allowed limit\",\n );\n const p = getPriorityBucket(raw.priority ?? \"normal\");\n const producer = this.producers[p] ?? this.producers.normal;\n await producer.publish(\n buildStreamEvent(\n \"notification.failed\",\n {\n projectId: raw.projectId,\n rawEventId: event.id,\n error: `Segment fan-out of ${userIds.length} exceeds limit of ${maxUsers}`,\n },\n \"enricher\",\n event.metadata.traceId,\n ),\n );\n return;\n }\n\n // Topic opt-outs are keyed on the TEMPLATE's topics, not the envelope type.\n // `event.type` here is \"notification.requested\", which no user ever sets a\n // preference against, so keying on it silently disabled every opt-out.\n const template = raw.templateId\n ? await this.templateCache.getCachedTemplate(raw.projectId, raw.templateId)\n : null;\n const topics: string[] = template?.topics ?? [];\n\n const channels =\n raw.channels && raw.channels.length > 0 ? raw.channels : ([\"email\"] as any[]);\n const isFallback = (raw as any).fallback === true;\n\n // If fallback is true, we only emit the first channel, and pass the rest in fallbackChain.\n // If fallback is false, we emit all channels concurrently.\n const channelsToProcess = isFallback ? [channels[0]] : channels;\n const fallbackChain = isFallback ? channels.slice(1) : undefined;\n\n const chunkArray = <T>(arr: T[], size: number) =>\n Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>\n arr.slice(i * size, i * size + size),\n );\n\n const chunks = chunkArray(userIds, 500);\n\n for (const chunk of chunks) {\n const profiles = (\n await Promise.all(chunk.map((id) => this.loadUser(raw.projectId, id)))\n ).filter(Boolean);\n const contactsByUser = await this.loadContacts(\n raw.projectId,\n profiles.map((profile: any) => profile.userId),\n );\n\n const batchedEvents: Record<\n \"critical\" | \"high\" | \"normal\" | \"low\",\n Omit<any, \"id\" | \"timestamp\">[]\n > = {\n critical: [],\n high: [],\n normal: [],\n low: [],\n };\n\n for (const profile of profiles) {\n for (const channel of channelsToProcess) {\n const contacts = contactsByUser.get(profile.userId) ?? [];\n const channelContacts = contacts.filter((contact: any) => contact.channel === channel);\n // Push resolves its active tokens at send time so token invalidation\n // remains current. Other channels need one task per address.\n const destinations =\n channel === \"push\" ? [undefined] : channelContacts.map((c: any) => c.target);\n if (destinations.length === 0) {\n this.logger.info(\n { recipientId: profile.userId, channel },\n \"no active contact for channel\",\n );\n continue;\n }\n for (const destination of destinations) {\n const enrichedPayload: NotificationEnrichedPayload = {\n projectId: raw.projectId,\n rawEventId: event.id,\n recipientId: profile.userId,\n channel: channel,\n priority: \"normal\",\n templateId: raw.templateId,\n templateVariables: raw.data,\n aiPrompts: raw.aiPrompts,\n recipient: {\n id: profile.userId,\n email:\n channel === \"email\"\n ? (destination ?? profile.email ?? undefined)\n : (profile.email ?? undefined),\n phone: channel === \"sms\" || channel === \"whatsapp\" ? destination : undefined,\n webhook: channel === \"webhook\" ? destination : undefined,\n telegram: channel === \"telegram\" ? destination : undefined,\n discord: channel === \"discord\" ? destination : undefined,\n slack: channel === \"slack\" ? destination : undefined,\n locale: profile.language ?? \"en\",\n timezone: profile.timezone ?? \"UTC\",\n preferences: {\n // Opted out if the user disabled ANY topic this template carries.\n optedOut: topics.some((t) => profile.preferences.topics?.[t] === false),\n channels: Object.entries(profile.preferences.channels ?? {})\n .filter(([_, enabled]) => !enabled)\n .map(([channel]) => channel as any),\n quietHours: profile.preferences.quietHours,\n },\n },\n scheduledAt: raw.scheduledAt,\n fallbackChain: fallbackChain?.length ? fallbackChain : undefined,\n campaignId: raw.campaignId,\n };\n\n const msgPriority = raw.priority ?? \"normal\";\n const p = getPriorityBucket(msgPriority);\n\n enrichedPayload.priority = msgPriority;\n\n batchedEvents[p].push(\n buildStreamEvent(\n \"notification.enriched\",\n enrichedPayload as Record<string, unknown>,\n \"enricher\",\n event.metadata.traceId,\n ),\n );\n }\n }\n }\n\n for (const p of [\"critical\", \"normal\", \"low\"] as const) {\n if (batchedEvents[p].length > 0) {\n const producer = this.producers[p] ?? this.producers.normal;\n for (const ev of batchedEvents[p]) {\n publishPromises.push(\n new Promise((resolve, reject) => {\n this.eventBuffer.push({ producer, event: ev, resolve, reject });\n }),\n );\n }\n }\n }\n }\n\n this.logger.info(\n {\n messageId: message.id,\n eventId: event.id,\n target: raw.target.type,\n traceId: event.metadata.traceId,\n },\n \"event enriched\",\n );\n } catch (err) {\n throw err;\n }\n\n await Promise.all(publishPromises).catch(async (err) => {\n await this.idempotency.unmark(dedupeId).catch(() => {});\n throw err;\n });\n\n await this.idempotency.markProcessed(dedupeId);\n }\n}\n\nexport async function startEnricherWorker() {\n logger = createLogger({ name: \"enricher\", level: config.LOG_LEVEL });\n redis = new RedisClient({ url: config.REDIS_URL, name: \"enricher\", logger });\n const dbData = createDatabase({ url: config.DATABASE_URL, applicationName: \"enricher\", logger });\n sql = dbData.sql;\n db = dbData.db;\n consumer = new StreamConsumer({\n redis: redis.native,\n stream: INBOUND_STREAMS as unknown as StreamName[],\n group: CONSUMER_GROUPS.ENRICHER,\n consumer: `enricher-${process.pid}`,\n dlqStream: STREAMS.DEAD_LETTER,\n batchSize: config.WORKER_CONCURRENCY,\n logger,\n });\n\n pendingScanner = new PendingMessageScanner({\n redis: redis.native,\n stream: INBOUND_STREAMS as unknown as StreamName[],\n group: CONSUMER_GROUPS.ENRICHER,\n consumer: `enricher-${process.pid}`,\n logger,\n });\n\n const producers = {\n critical: new StreamProducer({\n redis: redis.native,\n stream: STREAMS.ENRICHED_CRITICAL,\n logger,\n }),\n normal: new StreamProducer({ redis: redis.native, stream: STREAMS.ENRICHED_NORMAL, logger }),\n low: new StreamProducer({ redis: redis.native, stream: STREAMS.ENRICHED_LOW, logger }),\n };\n\n const idempotency = new IdempotencyGuard({\n redis: redis.native,\n keyPrefix: \"notif:processed:enricher\",\n ttlSeconds: 86_400,\n });\n\n const userRepo = new UserRepository(db);\n const prefRepo = new PreferenceRepository(db);\n const contactRepo = new ContactRepository(db);\n const templateCache = new TemplateCache(new TemplateRepository(db));\n\n // ─── Stage 1: Context Enricher ──────────────────────────────────────────────\n //\n // Pipeline:\n // 1. Parse payload as notification.created\n // 2. Idempotency check — drop if already processed\n // 3. Load user profile (language, timezone) from DB\n // 4. Load all stored preferences for this user\n // 5. Publish notification.enriched to ENRICHED stream\n\n // 5. Publish notification.enriched to ENRICHED stream\n\n worker = new EnricherWorker({\n consumer,\n pendingScanner,\n logger,\n maxRetriesBeforeDlq: 5,\n concurrency: config.WORKER_CONCURRENCY,\n producers,\n idempotency,\n userRepo,\n prefRepo,\n contactRepo,\n templateCache,\n });\n\n // ─── Health check interval ──────────────────────────────────────────────────\n\n healthInterval = startHealthReporter(\"enricher\", worker, redis, logger);\n\n logger.info({ env: config.NODE_ENV }, \"enricher starting\");\n await worker.start();\n}\n\n// ─── Shutdown ──────────────────────────────────────────────────────────────\n\nexport async function stopEnricherWorker(): Promise<void> {\n logger?.info(\"shutdown initiated\");\n if (healthInterval) {\n clearInterval(healthInterval);\n healthInterval = null;\n }\n if (worker) await worker.stop();\n if (sql) await sql.end();\n if (redis) await redis.disconnect();\n logger?.info(\"enricher stopped\");\n}\n"],"mappings":";;AAkCA,QAAQ;AACR,MAAM,SAAS,eAAe;AAE9B,IAAI;AACJ,IAAI;AACJ,IAAI;AACJ,IAAI;AAEJ,IAAI;AACJ,IAAI;AACJ,IAAI;AACJ,IAAI,iBAAwC;AAW5C,IAAa,iBAAb,cAAoC,WAAW;CAC7C;CACA;CACA;CACA;CACA;CACA;CAEA,YAKM,CAAC;CACP,aAA4C;CAC5C,cAKM,CAAC;CACP,aAA4C;CAE5C,eAKM,CAAC;CACP,oBAAmD;CAEnD,MAAc,aAAa,WAAmB,SAAgD;EAC5F,OAAO,IAAI,SAAS,SAAS,WAAW;GACtC,KAAK,aAAa,KAAK;IAAE;IAAW;IAAS;IAAS;GAAO,CAAC;GAC9D,IAAI,KAAK,aAAa,UAAU,KAAK;IACnC,IAAI,KAAK,mBAAmB,aAAa,KAAK,iBAAiB;IAC/D,KAAU,kBAAkB;GAC9B,OAAO,IAAI,CAAC,KAAK,mBACf,KAAK,oBAAoB,iBAAiB,KAAK,KAAK,kBAAkB,GAAG,EAAE;EAE/E,CAAC;CACH;CAEA,MAAc,oBAAmC;EAC/C,MAAM,QAAQ,KAAK;EACnB,KAAK,eAAe,CAAC;EACrB,KAAK,oBAAoB;EACzB,IAAI,MAAM,WAAW,GAAG;EAExB,IAAI;GACF,MAAM,4BAAY,IAAI,IAA0B;GAChD,KAAK,MAAM,KAAK,OAAO;IACrB,IAAI,CAAC,UAAU,IAAI,EAAE,SAAS,GAAG,UAAU,IAAI,EAAE,WAAW,CAAC,CAAC;IAC9D,UAAU,IAAI,EAAE,SAAS,CAAC,CAAE,KAAK,CAAC;GACpC;GAEA,KAAK,MAAM,CAAC,WAAW,UAAU,WAAW;IA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,CAAC;CAID,iBAAiB,oBAAoB,YAAY,QAAQ,OAAO,MAAM;CAEtE,OAAO,KAAK,EAAE,KAAK,OAAO,SAAS,GAAG,mBAAmB;CACzD,MAAM,OAAO,MAAM;AACrB;AAIA,eAAsB,qBAAoC;CACxD,QAAQ,KAAK,oBAAoB;CACjC,IAAI,gBAAgB;EAClB,cAAc,cAAc;EAC5B,iBAAiB;CACnB;CACA,IAAI,QAAQ,MAAM,OAAO,KAAK;CAC9B,IAAI,KAAK,MAAM,IAAI,IAAI;CACvB,IAAI,OAAO,MAAM,MAAM,WAAW;CAClC,QAAQ,KAAK,kBAAkB;AACjC"}
@@ -1,4 +1,4 @@
1
- import { $t as PUBSUB_CHANNELS, C as ProjectRepository, D as WorkflowRepository, E as UserRepository, Ft as CreateWorkflowSchema, G as normaliseTarget, Gt as UpdateUserSchema, Jt as buildStreamEvent, K as LRUCache, Mt as AddContactSchema, Nt as AddUserSchema, Pt as ContactChannelSchema, Q as metrics, Rt as NotifyRequestSchema, T as TemplateRepository, Ut as TriggerWorkflowSchema, Vt as SyncTemplatesSchema, W as getPriorityBucket, X as StreamProducer, Z as getMetricsRegistry, ct as projectApiKeys, dt as suppressions, en as STREAMS, et as createLogger, ft as userTopicPreferences, hn as readBaseConfig, it as createDatabase, k as RedisClient, lt as projects, mt as workflowDefinitions, p as verifyUnsubscribeToken, pn as loadEnv, pt as users, q as globalEmitter, st as messageLogs, ut as scheduledPayloads, w as SegmentRepository, x as ContactRepository, zt as PreferencesSchema } from "./src-vG79L-8m.mjs";
1
+ import { Bt as PreferencesSchema, C as ProjectRepository, D as WorkflowRepository, E as UserRepository, Ft as ContactChannelSchema, G as normaliseTarget, Ht as SyncTemplatesSchema, It as CreateWorkflowSchema, K as LRUCache, Kt as UpdateUserSchema, Nt as AddUserSchema, Pt as BatchAddContactsSchema, Q as metrics, T as TemplateRepository, W as getPriorityBucket, Wt as TriggerWorkflowSchema, X as StreamProducer, Xt as buildStreamEvent, Z as getMetricsRegistry, _n as readBaseConfig, ct as projectApiKeys, dt as suppressions, et as createLogger, ft as userTopicPreferences, hn as loadEnv, it as createDatabase, k as RedisClient, lt as projects, mt as workflowDefinitions, nn as STREAMS, p as verifyUnsubscribeToken, pt as users, q as globalEmitter, st as messageLogs, tn as PUBSUB_CHANNELS, ut as scheduledPayloads, w as SegmentRepository, x as ContactRepository, zt as NotifyRequestSchema } from "./src-CPMwsUCJ.mjs";
2
2
  import { z } from "zod";
3
3
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
4
4
  import { and, desc, eq, gte, inArray, isNotNull, like, lt, lte, or, sql } from "drizzle-orm";
@@ -127,39 +127,50 @@ const IngestEventSchema = z.object({
127
127
  name: z.string().min(1),
128
128
  properties: z.record(z.string(), z.unknown())
129
129
  });
130
- /** Map an inline user's contact arrays into (channel, target) pairs. */
130
+ /** Map an inline or user input's contacts and legacy arrays into resolved contact records. */
131
131
  function contactsOf(user) {
132
- return [
133
- ...(user.email ?? []).map((target) => ({
134
- channel: "email",
135
- target
136
- })),
137
- ...(user.phone ?? []).map((target) => ({
138
- channel: "sms",
139
- target
140
- })),
141
- ...(user.pushToken ?? []).map((target) => ({
142
- channel: "push",
143
- target
144
- }))
145
- ];
132
+ const list = [];
133
+ if (user.contacts && Array.isArray(user.contacts)) for (const c of user.contacts) list.push({
134
+ channel: c.channel,
135
+ target: c.target,
136
+ label: c.label,
137
+ isPrimary: c.isPrimary,
138
+ enabled: c.enabled,
139
+ preferences: c.preferences
140
+ });
141
+ if (user.email) for (const target of user.email) list.push({
142
+ channel: "email",
143
+ target
144
+ });
145
+ if (user.phone) for (const target of user.phone) list.push({
146
+ channel: "sms",
147
+ target
148
+ });
149
+ if (user.pushToken) for (const target of user.pushToken) list.push({
150
+ channel: "push",
151
+ target
152
+ });
153
+ return list;
146
154
  }
147
155
  /** Persist user records + their contacts in bulk. Shared by addUser and inline notify. */
148
156
  async function persistUsers(deps, users, projectId) {
149
- const usersList = users.map((u) => ({
150
- userId: u.id,
151
- language: u.language ?? "en",
152
- timezone: u.timezone ?? "UTC",
153
- email: u.email?.[0] ?? null,
154
- segments: u.segments ?? [],
155
- preferences: u.preferences ?? {}
156
- }));
157
+ const usersList = users.map((u) => {
158
+ const primaryEmail = u.email?.[0] ?? u.contacts?.find((c) => c.channel === "email")?.target ?? null;
159
+ return {
160
+ userId: u.id,
161
+ language: u.language ?? "en",
162
+ timezone: u.timezone ?? "UTC",
163
+ email: primaryEmail,
164
+ segments: u.segments ?? [],
165
+ preferences: u.preferences ?? {}
166
+ };
167
+ });
157
168
  const contactsList = [];
158
169
  for (const u of users) for (const c of contactsOf(u)) contactsList.push({
159
170
  userId: u.id,
160
171
  channel: c.channel,
161
172
  target: c.target,
162
- preferences: {}
173
+ preferences: c.preferences ?? {}
163
174
  });
164
175
  await deps.db.transaction(async (tx) => {
165
176
  const txUserRepo = deps.userRepo.constructor.name === "Object" ? deps.userRepo : new deps.userRepo.constructor(tx);
@@ -204,7 +215,7 @@ function createHandlers(deps) {
204
215
  if (!await deps.userRepo.updatePartial(ctx.projectId, userId, {
205
216
  language: patch.language,
206
217
  timezone: patch.timezone,
207
- email: patch.email?.[0],
218
+ email: patch.email?.[0] ?? patch.contacts?.find((c) => c.channel === "email")?.target,
208
219
  segments: patch.segments,
209
220
  preferences: patch.preferences
210
221
  })) return sendJson(res, 404, {
@@ -214,7 +225,8 @@ function createHandlers(deps) {
214
225
  for (const c of contactsOf({
215
226
  id: userId,
216
227
  ...patch
217
- })) await deps.contactRepo.upsert(ctx.projectId, userId, c.channel, c.target);
228
+ })) if (c.preferences) await deps.contactRepo.upsert(ctx.projectId, userId, c.channel, c.target, c.preferences);
229
+ else await deps.contactRepo.upsert(ctx.projectId, userId, c.channel, c.target);
218
230
  logger.info({ userId }, "user updated");
219
231
  sendJson(res, 200, { id: userId });
220
232
  }
@@ -229,22 +241,44 @@ function createHandlers(deps) {
229
241
  }
230
242
  async function addContact(req, res, ctx) {
231
243
  const userId = ctx.params.id;
232
- const parsed = AddContactSchema.safeParse(await readJsonBody(req));
244
+ const body = await readJsonBody(req);
245
+ const parsed = BatchAddContactsSchema.safeParse(body);
233
246
  if (!parsed.success) return sendValidationError(res, parsed.error);
234
247
  if (!await deps.userRepo.findById(ctx.projectId, userId)) return sendJson(res, 404, {
235
248
  error: "user_not_found",
236
249
  id: userId
237
250
  });
238
- await deps.contactRepo.upsert(ctx.projectId, userId, parsed.data.channel, parsed.data.target, parsed.data.preferences ?? {});
239
- logger.info({
240
- userId,
241
- channel: parsed.data.channel
242
- }, "contact added");
243
- sendJson(res, 201, {
244
- userId,
245
- channel: parsed.data.channel,
246
- target: parsed.data.target
247
- });
251
+ if (Array.isArray(parsed.data)) {
252
+ const contactsList = parsed.data.map((c) => ({
253
+ userId,
254
+ channel: c.channel,
255
+ target: c.target,
256
+ preferences: c.preferences ?? {}
257
+ }));
258
+ await deps.contactRepo.upsertMany(ctx.projectId, contactsList);
259
+ logger.info({
260
+ userId,
261
+ count: contactsList.length
262
+ }, "contacts batch added");
263
+ sendJson(res, 201, {
264
+ userId,
265
+ contacts: contactsList.map((c) => ({
266
+ channel: c.channel,
267
+ target: c.target
268
+ }))
269
+ });
270
+ } else {
271
+ await deps.contactRepo.upsert(ctx.projectId, userId, parsed.data.channel, parsed.data.target, parsed.data.preferences ?? {});
272
+ logger.info({
273
+ userId,
274
+ channel: parsed.data.channel
275
+ }, "contact added");
276
+ sendJson(res, 201, {
277
+ userId,
278
+ channel: parsed.data.channel,
279
+ target: parsed.data.target
280
+ });
281
+ }
248
282
  }
249
283
  async function deleteContact(_req, res, ctx) {
250
284
  const userId = ctx.params.id;
@@ -1695,4 +1729,4 @@ async function stopApiServer() {
1695
1729
  //#endregion
1696
1730
  export { startApiServer, stopApiServer };
1697
1731
 
1698
- //# sourceMappingURL=main-40zwq6b0.mjs.map
1732
+ //# sourceMappingURL=main-CFSukWm8.mjs.map