notifkit 0.1.15 → 0.1.16

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 (85) hide show
  1. package/dashboard/dist/assets/index-C-DJYu0_.css +1 -0
  2. package/dashboard/dist/assets/index-CzFZcEon.js +318 -0
  3. package/dashboard/dist/index.html +2 -2
  4. package/dist/{bootstrap-BOmT69OH.mjs → bootstrap-BMDRPjgp.mjs} +1 -1
  5. package/dist/{bulk-ZPiOJRx-.mjs → bulk-CJ5QXiPa.mjs} +1 -1
  6. package/dist/index.d.mts +71 -27
  7. package/dist/index.mjs +2 -2
  8. package/dist/{main-CCqcFDDe.mjs → main-6_bXQBDH.mjs} +21 -41
  9. package/dist/{main-BdZvBgV7.mjs → main-8nP3qmCT.mjs} +22 -48
  10. package/dist/{main-C0m9-Eos.mjs → main-B82bsFoy.mjs} +183 -334
  11. package/dist/{main-CTjaZ7ZD.mjs → main-CpaHF1Zw.mjs} +13 -15
  12. package/dist/{main-JEXBLP2A.mjs → main-DULD8-th.mjs} +8 -6
  13. package/dist/{main-C6S3EsJ3.mjs → main-ZW5RaiOK.mjs} +77 -64
  14. package/dist/{main-g33jpia4.mjs → main-g1KEcXXp.mjs} +676 -582
  15. package/dist/{main-24J4U8yP.mjs → main-mGIT8jv4.mjs} +4 -4
  16. package/dist/schedule-or-dispatch-Cd7GLfc3.mjs +52 -0
  17. package/dist/{src-9LXITcNi.mjs → src-BE_EUpZ6.mjs} +93 -93
  18. package/package.json +1 -1
  19. package/scripts/create-project.mjs +6 -2
  20. package/src/client.ts +3 -3
  21. package/src/config/index.ts +1 -0
  22. package/src/contracts/common.ts +2 -0
  23. package/src/contracts/envelope.ts +1 -1
  24. package/src/contracts/events/notification-created.ts +2 -0
  25. package/src/contracts/events/notification-delivered.ts +1 -1
  26. package/src/contracts/events/notification-failed.ts +1 -1
  27. package/src/contracts/events/notification-requested.ts +3 -2
  28. package/src/contracts/helpers.ts +1 -2
  29. package/src/contracts/index.ts +1 -0
  30. package/src/contracts/registry.ts +1 -0
  31. package/src/contracts/sdk.ts +8 -37
  32. package/src/db/schema.ts +8 -13
  33. package/src/idempotency/index.ts +6 -8
  34. package/src/metrics/index.ts +2 -0
  35. package/src/rate-limiter/api-rate-limiter.ts +208 -0
  36. package/src/rate-limiter/index.ts +3 -411
  37. package/src/rate-limiter/project-settings-cache.ts +99 -0
  38. package/src/rate-limiter/user-throttle.ts +100 -0
  39. package/src/redis/index.ts +10 -3
  40. package/src/repositories/admin-user.ts +83 -0
  41. package/src/repositories/contact.ts +359 -0
  42. package/src/repositories/index.ts +9 -1416
  43. package/src/repositories/preference.ts +35 -0
  44. package/src/repositories/project.ts +110 -0
  45. package/src/repositories/segment.ts +16 -0
  46. package/src/repositories/template.ts +72 -0
  47. package/src/repositories/types.ts +49 -0
  48. package/src/repositories/user.ts +644 -0
  49. package/src/repositories/workflow.ts +64 -0
  50. package/src/services/ai/main.ts +29 -71
  51. package/src/services/api/admin-static.ts +4 -1
  52. package/src/services/api/handlers/auth.ts +109 -0
  53. package/src/services/api/handlers/campaigns.ts +191 -0
  54. package/src/services/api/handlers/events.ts +99 -0
  55. package/src/services/api/handlers/notifications.ts +356 -0
  56. package/src/services/api/handlers/projects.ts +116 -0
  57. package/src/services/api/handlers/shared.ts +262 -0
  58. package/src/services/api/handlers/suppressions.ts +95 -0
  59. package/src/services/api/handlers/system.ts +314 -0
  60. package/src/services/api/handlers/templates.ts +97 -0
  61. package/src/services/api/handlers/unsubscribe.ts +215 -0
  62. package/src/services/api/handlers/users.ts +262 -0
  63. package/src/services/api/handlers/workflows.ts +150 -0
  64. package/src/services/api/handlers.ts +25 -2190
  65. package/src/services/api/health.ts +133 -0
  66. package/src/services/api/http.ts +12 -0
  67. package/src/services/api/main.ts +32 -322
  68. package/src/services/api/router.ts +1 -1
  69. package/src/services/api/webhooks.ts +172 -0
  70. package/src/services/delivery/main.ts +256 -498
  71. package/src/services/engine/main.ts +31 -247
  72. package/src/services/engine/quiet-hours.ts +151 -0
  73. package/src/services/engine/schedule-or-dispatch.ts +104 -0
  74. package/src/services/enricher/main.ts +9 -21
  75. package/src/services/events/main.ts +2 -2
  76. package/src/services/scheduler/main.ts +16 -25
  77. package/src/services/workflow/duration.ts +24 -0
  78. package/src/services/workflow/main.ts +6 -164
  79. package/src/services/workflow/timers.ts +157 -0
  80. package/src/shared/events.ts +3 -2
  81. package/src/templates/render.ts +1 -0
  82. package/src/workers/index.ts +7 -4
  83. package/src/workflows/sdk.ts +1 -0
  84. package/dashboard/dist/assets/index-ggpJKZqZ.js +0 -315
  85. package/dashboard/dist/assets/index-s-SXGIwv.css +0 -1
@@ -5,8 +5,8 @@
5
5
  <link rel="icon" type="image/svg+xml" href="./favicon.svg" />
6
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
7
  <title>Notifkit Observability & Admin</title>
8
- <script type="module" crossorigin src="./assets/index-ggpJKZqZ.js"></script>
9
- <link rel="stylesheet" crossorigin href="./assets/index-s-SXGIwv.css">
8
+ <script type="module" crossorigin src="./assets/index-CzFZcEon.js"></script>
9
+ <link rel="stylesheet" crossorigin href="./assets/index-C-DJYu0_.css">
10
10
  </head>
11
11
  <body class="h-screen bg-background text-foreground antialiased overflow-hidden">
12
12
  <div id="root" class="h-full w-full"></div>
@@ -1,4 +1,4 @@
1
- import { $ as createDatabase, G as PendingMessageScanner, K as StreamConsumer, X as createLogger, en as STREAMS, q as StreamProducer, z as RedisClient } from "./src-9LXITcNi.mjs";
1
+ import { J as StreamProducer, K as PendingMessageScanner, Z as createLogger, et as createDatabase, q as StreamConsumer, tn as STREAMS, z as RedisClient } from "./src-BE_EUpZ6.mjs";
2
2
  //#region src/workers/bootstrap.ts
3
3
  /** Logger, shared Redis connection and Postgres pool for one service. */
4
4
  function createWorkerRuntime(config, name, loggerName = name) {
@@ -1,4 +1,4 @@
1
- import { at as messageLogs, it as deliveryOutbox } from "./src-9LXITcNi.mjs";
1
+ import { at as deliveryOutbox, ot as messageLogs } from "./src-BE_EUpZ6.mjs";
2
2
  import { sql } from "drizzle-orm";
3
3
  //#region src/db/bulk.ts
4
4
  function rawClient(db) {
package/dist/index.d.mts CHANGED
@@ -50,6 +50,7 @@ declare const baseConfigSchema: z.ZodObject<{
50
50
  type BaseConfig = z.infer<typeof baseConfigSchema>;
51
51
  declare function setGlobalConfig(config: BaseConfig): void;
52
52
  declare function readBaseConfig(data?: NodeJS.ProcessEnv): BaseConfig;
53
+ /** @deprecated Unused; removed in the next minor version. */
53
54
  interface RateLimitConfig {
54
55
  limit: number;
55
56
  windowSeconds: number;
@@ -91,6 +92,7 @@ declare const NotificationPrioritySchema: z.ZodEnum<{
91
92
  critical: "critical";
92
93
  }>;
93
94
  type NotificationPriority = z.infer<typeof NotificationPrioritySchema>;
95
+ /** @deprecated Unused; removed in the next minor version. */
94
96
  declare const NotificationStatusSchema: z.ZodEnum<{
95
97
  pending: "pending";
96
98
  failed: "failed";
@@ -100,6 +102,7 @@ declare const NotificationStatusSchema: z.ZodEnum<{
100
102
  bounced: "bounced";
101
103
  suppressed: "suppressed";
102
104
  }>;
105
+ /** @deprecated Unused; removed in the next minor version. */
103
106
  type NotificationStatus = z.infer<typeof NotificationStatusSchema>;
104
107
  //#endregion
105
108
  //#region src/contracts/metadata.d.ts
@@ -116,10 +119,11 @@ type EventMetadata = z.infer<typeof EventMetadataSchema>;
116
119
  /**
117
120
  * A high-level notification request as issued by the SDK's `notify()` call.
118
121
  *
119
- * Unlike `notification.created` (which targets a single resolved recipient),
122
+ * Unlike `notification.enriched` (which targets a single resolved address),
120
123
  * this event carries the *unresolved* target — a user id, a segment, or a
121
124
  * topic. A downstream resolver stage fans it out into one
122
- * `notification.created` per matching recipient, applying preference filters.
125
+ * `notification.enriched` per matching address and channel, applying
126
+ * preference filters.
123
127
  */
124
128
  declare const NotificationTargetSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
125
129
  type: z.ZodLiteral<"user">;
@@ -173,6 +177,7 @@ declare const NotificationRequestedPayloadSchema: z.ZodObject<{
173
177
  type NotificationRequestedPayload = z.infer<typeof NotificationRequestedPayloadSchema>;
174
178
  //#endregion
175
179
  //#region src/contracts/events/notification-created.d.ts
180
+ /** @deprecated Nothing publishes `notification.created`; removed in the next minor version. */
176
181
  declare const NotificationCreatedPayloadSchema: z.ZodObject<{
177
182
  projectId: z.ZodString;
178
183
  recipientId: z.ZodString;
@@ -198,6 +203,7 @@ declare const NotificationCreatedPayloadSchema: z.ZodObject<{
198
203
  scheduledAt: z.ZodOptional<z.ZodString>;
199
204
  idempotencyKey: z.ZodOptional<z.ZodString>;
200
205
  }, z.core.$strip>;
206
+ /** @deprecated Nothing publishes `notification.created`; removed in the next minor version. */
201
207
  type NotificationCreatedPayload = z.infer<typeof NotificationCreatedPayloadSchema>;
202
208
  //#endregion
203
209
  //#region src/contracts/events/notification-enriched.d.ts
@@ -588,6 +594,7 @@ type NotificationAiPendingPayload = z.infer<typeof NotificationAiPendingPayloadS
588
594
  */
589
595
  interface EventPayloadMap {
590
596
  "notification.requested": NotificationRequestedPayload;
597
+ /** @deprecated Nothing publishes `notification.created`; removed in the next minor version. */
591
598
  "notification.created": NotificationCreatedPayload;
592
599
  "notification.enriched": NotificationEnrichedPayload;
593
600
  "notification.scheduled": NotificationScheduledPayload;
@@ -1722,7 +1729,7 @@ declare function createLogger({ name, level, pretty, context }: LoggerOptions):
1722
1729
  declare namespace schema_d_exports {
1723
1730
  export { adminUsers, apiKeyRoleEnum, channelEnum, contactTopicPreferences, deliveryOutbox, messageLogs, projectApiKeys, projects, quietHours, scheduledPayloads, suppressions, templates, userChannelPreferences, userContacts, userSegments, userTopicPreferences, users, workflowDefinitions, workflowInstances, workflowStatusEnum, workflowSteps, workflowWaiters };
1724
1731
  }
1725
- declare const channelEnum: import("drizzle-orm/pg-core").PgEnum<["email", "sms", "push", "webhook", "in-app", "telegram", "discord", "whatsapp", "slack"]>;
1732
+ declare const channelEnum: import("drizzle-orm/pg-core").PgEnum<["email" | "sms" | "push" | "webhook" | "in-app" | "telegram" | "discord" | "whatsapp" | "slack", ...("email" | "sms" | "push" | "webhook" | "in-app" | "telegram" | "discord" | "whatsapp" | "slack")[]]>;
1726
1733
  declare const projects: import("drizzle-orm/pg-core").PgTableWithColumns<{
1727
1734
  name: "projects";
1728
1735
  schema: undefined;
@@ -2148,7 +2155,7 @@ declare const userContacts: import("drizzle-orm/pg-core").PgTableWithColumns<{
2148
2155
  isPrimaryKey: false;
2149
2156
  isAutoincrement: false;
2150
2157
  hasRuntimeDefault: false;
2151
- enumValues: ["email", "sms", "push", "webhook", "in-app", "telegram", "discord", "whatsapp", "slack"];
2158
+ enumValues: ["email" | "sms" | "push" | "webhook" | "in-app" | "telegram" | "discord" | "whatsapp" | "slack", ...("email" | "sms" | "push" | "webhook" | "in-app" | "telegram" | "discord" | "whatsapp" | "slack")[]];
2152
2159
  baseColumn: never;
2153
2160
  identity: undefined;
2154
2161
  generated: undefined;
@@ -2274,7 +2281,7 @@ declare const userChannelPreferences: import("drizzle-orm/pg-core").PgTableWithC
2274
2281
  isPrimaryKey: false;
2275
2282
  isAutoincrement: false;
2276
2283
  hasRuntimeDefault: false;
2277
- enumValues: ["email", "sms", "push", "webhook", "in-app", "telegram", "discord", "whatsapp", "slack"];
2284
+ enumValues: ["email" | "sms" | "push" | "webhook" | "in-app" | "telegram" | "discord" | "whatsapp" | "slack", ...("email" | "sms" | "push" | "webhook" | "in-app" | "telegram" | "discord" | "whatsapp" | "slack")[]];
2278
2285
  baseColumn: never;
2279
2286
  identity: undefined;
2280
2287
  generated: undefined;
@@ -2597,7 +2604,7 @@ declare const templates: import("drizzle-orm/pg-core").PgTableWithColumns<{
2597
2604
  isPrimaryKey: false;
2598
2605
  isAutoincrement: false;
2599
2606
  hasRuntimeDefault: false;
2600
- enumValues: ["email", "sms", "push", "webhook", "in-app", "telegram", "discord", "whatsapp", "slack"];
2607
+ enumValues: ["email" | "sms" | "push" | "webhook" | "in-app" | "telegram" | "discord" | "whatsapp" | "slack", ...("email" | "sms" | "push" | "webhook" | "in-app" | "telegram" | "discord" | "whatsapp" | "slack")[]];
2601
2608
  baseColumn: never;
2602
2609
  identity: undefined;
2603
2610
  generated: undefined;
@@ -2823,7 +2830,7 @@ declare const messageLogs: import("drizzle-orm/pg-core").PgTableWithColumns<{
2823
2830
  isPrimaryKey: false;
2824
2831
  isAutoincrement: false;
2825
2832
  hasRuntimeDefault: false;
2826
- enumValues: ["email", "sms", "push", "webhook", "in-app", "telegram", "discord", "whatsapp", "slack"];
2833
+ enumValues: ["email" | "sms" | "push" | "webhook" | "in-app" | "telegram" | "discord" | "whatsapp" | "slack", ...("email" | "sms" | "push" | "webhook" | "in-app" | "telegram" | "discord" | "whatsapp" | "slack")[]];
2827
2834
  baseColumn: never;
2828
2835
  identity: undefined;
2829
2836
  generated: undefined;
@@ -2998,7 +3005,7 @@ declare const suppressions: import("drizzle-orm/pg-core").PgTableWithColumns<{
2998
3005
  isPrimaryKey: false;
2999
3006
  isAutoincrement: false;
3000
3007
  hasRuntimeDefault: false;
3001
- enumValues: ["email", "sms", "push", "webhook", "in-app", "telegram", "discord", "whatsapp", "slack"];
3008
+ enumValues: ["email" | "sms" | "push" | "webhook" | "in-app" | "telegram" | "discord" | "whatsapp" | "slack", ...("email" | "sms" | "push" | "webhook" | "in-app" | "telegram" | "discord" | "whatsapp" | "slack")[]];
3002
3009
  baseColumn: never;
3003
3010
  identity: undefined;
3004
3011
  generated: undefined;
@@ -3632,7 +3639,7 @@ declare const deliveryOutbox: import("drizzle-orm/pg-core").PgTableWithColumns<{
3632
3639
  isPrimaryKey: false;
3633
3640
  isAutoincrement: false;
3634
3641
  hasRuntimeDefault: false;
3635
- enumValues: ["email", "sms", "push", "webhook", "in-app", "telegram", "discord", "whatsapp", "slack"];
3642
+ enumValues: ["email" | "sms" | "push" | "webhook" | "in-app" | "telegram" | "discord" | "whatsapp" | "slack", ...("email" | "sms" | "push" | "webhook" | "in-app" | "telegram" | "discord" | "whatsapp" | "slack")[]];
3636
3643
  baseColumn: never;
3637
3644
  identity: undefined;
3638
3645
  generated: undefined;
@@ -3972,10 +3979,8 @@ interface IdempotencyOptions {
3972
3979
  }
3973
3980
  type LeaseResult = "acquired" | "locked" | "completed";
3974
3981
  /**
3975
- * Two-phase SETNX-based idempotency guard.
3976
- * Supports:
3977
- * - Phase 1 (:lock): Short lease acquired at the start of message processing.
3978
- * - Phase 2 (:sent): Long-lived completion marker recorded when processing succeeds.
3982
+ * SET NX-based idempotency guard.
3983
+ * One key per id: `L` while leased, `1` once processed.
3979
3984
  */
3980
3985
  declare class IdempotencyGuard {
3981
3986
  private readonly redis;
@@ -3983,13 +3988,13 @@ declare class IdempotencyGuard {
3983
3988
  private readonly ttlSeconds;
3984
3989
  constructor({ redis, keyPrefix, ttlSeconds }: IdempotencyOptions);
3985
3990
  private key;
3991
+ /** @deprecated Nothing writes `:lock` keys any more; read only for markers from older versions. Remove in the next minor. */
3986
3992
  private lockKey;
3993
+ /** @deprecated Nothing writes `:sent` keys any more; read only for markers from older versions. Remove in the next minor. */
3987
3994
  private completedKey;
3988
3995
  /**
3989
- * Two-phase lease acquisition.
3990
- * Atomically checks existing state and acquires lock if available.
3991
- * - Happy path (new message): single native SET NX command storing "L" (lock lease).
3992
- * - If already present: checks if "S" (sent/completed) or "L" (locked by another worker).
3996
+ * Leases the id with SET NX. One key per id: `L` while leased, `1` once processed.
3997
+ * Returns "completed" if already processed, "locked" if another worker holds the lease.
3993
3998
  */
3994
3999
  acquireLease(id: string, lockTtlSeconds?: number): Promise<LeaseResult>;
3995
4000
  /** Atomically mark id as processed. Returns true on first call; false if already seen. */
@@ -4007,8 +4012,10 @@ declare const metrics: {
4007
4012
  messagesProcessed: promClient.Counter<"worker" | "status">;
4008
4013
  deliverySuccess: promClient.Counter<"channel">;
4009
4014
  deliveryFailed: promClient.Counter<"channel" | "reason">;
4015
+ /** @deprecated Never set, so it always reads 0. Removed in the next minor version. */
4010
4016
  workerActiveTasks: promClient.Gauge<"worker">;
4011
4017
  queueSize: promClient.Gauge<"stream">;
4018
+ /** @deprecated Never set, so it always reads 0. Removed in the next minor version. */
4012
4019
  pendingAcks: promClient.Gauge<"group">;
4013
4020
  };
4014
4021
  declare function getMetricsRegistry(): promClient.Registry<"text/plain; version=0.0.4; charset=utf-8">;
@@ -4140,12 +4147,7 @@ declare class PendingMessageScanner {
4140
4147
  autoclaim(minIdleMs: number, limit?: number): Promise<StreamMessage[]>;
4141
4148
  }
4142
4149
  //#endregion
4143
- //#region src/rate-limiter/index.d.ts
4144
- interface ThrottleResult {
4145
- allowed: boolean;
4146
- count: number;
4147
- limit: number;
4148
- }
4150
+ //#region src/rate-limiter/project-settings-cache.d.ts
4149
4151
  /**
4150
4152
  * Throttle overrides stored on the project row. `null` on either field means
4151
4153
  * "no override" — fall back to the process-wide default.
@@ -4189,6 +4191,13 @@ declare class ProjectSettingsCache {
4189
4191
  invalidate(projectId: string): void;
4190
4192
  clear(): void;
4191
4193
  }
4194
+ //#endregion
4195
+ //#region src/rate-limiter/user-throttle.d.ts
4196
+ interface ThrottleResult {
4197
+ allowed: boolean;
4198
+ count: number;
4199
+ limit: number;
4200
+ }
4192
4201
  interface UserThrottleOptions {
4193
4202
  redis: Redis;
4194
4203
  maxPerHour?: number;
@@ -4221,6 +4230,8 @@ declare class UserThrottle {
4221
4230
  */
4222
4231
  check(projectId: string, userId: string, priority?: string, options?: ThrottleCheckOptions): Promise<ThrottleResult>;
4223
4232
  }
4233
+ //#endregion
4234
+ //#region src/rate-limiter/api-rate-limiter.d.ts
4224
4235
  interface ApiRateLimiterOptions {
4225
4236
  redis: Redis;
4226
4237
  windowMs?: number;
@@ -4305,9 +4316,15 @@ declare const LUA_SCHEDULER_POLL = "\n local key = KEYS[1]\n local maxScore =
4305
4316
  * address it counted stayed over its limit for good.
4306
4317
  */
4307
4318
  declare const LUA_COUNT_REQUEST = "\n local count = redis.call('INCR', KEYS[1])\n if redis.call('TTL', KEYS[1]) < 0 then\n redis.call('EXPIRE', KEYS[1], ARGV[1])\n end\n return count\n";
4308
- /** Two-phase idempotency lease acquisition. Checks sent/legacy, then attempts SET NX lock. */
4319
+ /**
4320
+ * Two-phase idempotency lease acquisition. Checks sent/legacy, then attempts SET NX lock.
4321
+ * @deprecated Nothing calls the `acquireLease` command; removed in the next minor version.
4322
+ */
4309
4323
  declare const LUA_ACQUIRE_LEASE = "\n if redis.call('EXISTS', KEYS[1]) == 1 or redis.call('EXISTS', KEYS[3]) == 1 then\n return 'completed'\n end\n local lockAcquired = redis.call('SET', KEYS[2], '1', 'EX', ARGV[1], 'NX')\n if lockAcquired then\n return 'acquired'\n end\n if redis.call('EXISTS', KEYS[1]) == 1 or redis.call('EXISTS', KEYS[3]) == 1 then\n return 'completed'\n end\n return 'locked'\n";
4310
- /** Two-phase idempotency completion marker. Atomically sets completed + legacy and deletes lock. */
4324
+ /**
4325
+ * Two-phase idempotency completion marker. Atomically sets completed + legacy and deletes lock.
4326
+ * @deprecated Nothing calls the `markProcessed` command; removed in the next minor version.
4327
+ */
4311
4328
  declare const LUA_MARK_PROCESSED = "\n redis.call('SET', KEYS[1], '1', 'EX', ARGV[1])\n redis.call('SET', KEYS[2], '1', 'EX', ARGV[1])\n redis.call('DEL', KEYS[3])\n return 1\n";
4312
4329
  /**
4313
4330
  * Registers pre-compiled custom commands on an ioredis instance.
@@ -4343,8 +4360,9 @@ declare class RedisClient {
4343
4360
  healthCheck(): Promise<boolean>;
4344
4361
  disconnect(): Promise<void>;
4345
4362
  }
4363
+ declare function redactUrl(url: string): string;
4346
4364
  //#endregion
4347
- //#region src/repositories/index.d.ts
4365
+ //#region src/repositories/types.d.ts
4348
4366
  interface UserProfile {
4349
4367
  userId: string;
4350
4368
  language?: string;
@@ -4371,7 +4389,9 @@ interface TemplateRecord {
4371
4389
  /** Template-level AI prompts, merged with per-request ones by the engine. */
4372
4390
  aiPrompts?: Record<string, string> | null;
4373
4391
  }
4392
+ /** @deprecated Unused; removed in the next minor version. */
4374
4393
  type DevicePlatform = "fcm" | "apns" | "web";
4394
+ /** @deprecated Unused; removed in the next minor version. */
4375
4395
  interface DeviceToken {
4376
4396
  id: string;
4377
4397
  userId: string;
@@ -4384,10 +4404,14 @@ interface NotificationPreference {
4384
4404
  eventType: string;
4385
4405
  optedIn: boolean;
4386
4406
  }
4407
+ //#endregion
4408
+ //#region src/repositories/user.d.ts
4387
4409
  declare class UserRepository {
4388
4410
  private readonly db;
4389
4411
  private readonly recordCache;
4390
4412
  constructor(db: Db);
4413
+ /** A repository that runs its queries inside `tx`. */
4414
+ withTx(tx: Db): UserRepository;
4391
4415
  findById(projectId: string, userId: string): Promise<UserProfile | null>;
4392
4416
  findRecordById(projectId: string, userId: string): Promise<UserRecord | null>;
4393
4417
  findRecordsByIds(projectId: string, userIds: string[]): Promise<UserRecord[]>;
@@ -4428,16 +4452,23 @@ declare class UserRepository {
4428
4452
  findUsersBySegment(projectId: string, segmentName: string): Promise<string[]>;
4429
4453
  findUsersByTopic(projectId: string, topicName: string): Promise<string[]>;
4430
4454
  }
4455
+ //#endregion
4456
+ //#region src/repositories/preference.d.ts
4457
+ /** @deprecated Unused; removed in the next minor version. */
4431
4458
  declare class PreferenceRepository {
4432
4459
  private readonly db;
4433
4460
  constructor(db: Db);
4434
4461
  isOptedIn(projectId: string, userId: string, eventType: string): Promise<boolean>;
4435
4462
  findByUserId(projectId: string, userId: string): Promise<NotificationPreference[]>;
4436
4463
  }
4464
+ //#endregion
4465
+ //#region src/repositories/contact.d.ts
4437
4466
  declare class ContactRepository {
4438
4467
  private readonly db;
4439
4468
  private readonly activeContactsCache;
4440
4469
  constructor(db: Db);
4470
+ /** A repository that runs its queries inside `tx`. */
4471
+ withTx(tx: Db): ContactRepository;
4441
4472
  findByUserId(projectId: string, userId: string): Promise<UserContact[]>;
4442
4473
  /** Resolve active addressable contacts for a batch without an N+1 query. */
4443
4474
  findActiveByUserIds(projectId: string, userIds: string[]): Promise<Map<string, UserContact[]>>;
@@ -4456,6 +4487,8 @@ declare class ContactRepository {
4456
4487
  deactivate(projectId: string, userId: string, channel: ContactChannel, target: string): Promise<boolean>;
4457
4488
  delete(projectId: string, userId: string, channel: ContactChannel, target: string): Promise<boolean>;
4458
4489
  }
4490
+ //#endregion
4491
+ //#region src/repositories/template.d.ts
4459
4492
  declare class TemplateRepository {
4460
4493
  private readonly db;
4461
4494
  constructor(db: Db);
@@ -4464,6 +4497,8 @@ declare class TemplateRepository {
4464
4497
  upsertMany(projectId: string, templateList: any[]): Promise<number>;
4465
4498
  delete(projectId: string, id: string): Promise<boolean>;
4466
4499
  }
4500
+ //#endregion
4501
+ //#region src/repositories/project.d.ts
4467
4502
  declare class ProjectRepository {
4468
4503
  private readonly db;
4469
4504
  constructor(db: Db);
@@ -4488,6 +4523,8 @@ declare class ProjectRepository {
4488
4523
  listApiKeys(projectId: string): Promise<any[]>;
4489
4524
  deleteApiKey(projectId: string, keyId: string): Promise<boolean>;
4490
4525
  }
4526
+ //#endregion
4527
+ //#region src/repositories/workflow.d.ts
4491
4528
  declare class WorkflowRepository {
4492
4529
  private readonly db;
4493
4530
  constructor(db: Db);
@@ -4495,11 +4532,15 @@ declare class WorkflowRepository {
4495
4532
  getInstance(projectId: string, instanceId: string): Promise<any | null>;
4496
4533
  cancelInstance(projectId: string, instanceId: string): Promise<boolean>;
4497
4534
  }
4535
+ //#endregion
4536
+ //#region src/repositories/segment.d.ts
4498
4537
  declare class SegmentRepository {
4499
4538
  private readonly db;
4500
4539
  constructor(db: Db);
4501
4540
  listSegments(projectId: string): Promise<string[]>;
4502
4541
  }
4542
+ //#endregion
4543
+ //#region src/repositories/admin-user.d.ts
4503
4544
  interface AdminUserRecord {
4504
4545
  id: string;
4505
4546
  email: string;
@@ -4520,7 +4561,9 @@ declare class AdminUserRepository {
4520
4561
  passwordHash: string;
4521
4562
  role?: string;
4522
4563
  }): Promise<AdminUserRecord>;
4564
+ /** @deprecated Unused; removed in the next minor version. */
4523
4565
  updatePassword(id: string, passwordHash: string): Promise<boolean>;
4566
+ /** @deprecated Unused; removed in the next minor version. */
4524
4567
  list(): Promise<Omit<AdminUserRecord, "passwordHash">[]>;
4525
4568
  count(): Promise<number>;
4526
4569
  }
@@ -4745,6 +4788,7 @@ declare class ValidationError extends AppError {
4745
4788
  declare function escapeHtml(unsafe: string): string;
4746
4789
  /** Strip CR/LF so an interpolated value cannot inject extra headers. */
4747
4790
  declare function escapeHeader(unsafe: string): string;
4791
+ /** @deprecated Unused; templates render through renderWithTemplate. Removed in the next minor version. */
4748
4792
  declare function interpolate(tmpl: string, variables: Record<string, unknown>, sanitize?: boolean): string;
4749
4793
  /**
4750
4794
  * How an interpolated value must be escaped, decided by the field it lands in.
@@ -5248,4 +5292,4 @@ declare class NotifkitServer extends EventEmitter {
5248
5292
  stop(): Promise<void>;
5249
5293
  }
5250
5294
  //#endregion
5251
- export { AI_DEFAULTS, AddContactInput, AddContactSchema, AddUserInput, AddUserSchema, AdminUserRecord, AdminUserRepository, AiConfig, ApiRateLimiter, ApiRateLimiterOptions, AppError, AsyncSemaphore, BaseConfig, BaseWorker, BatchAddContactsInput, BatchAddContactsSchema, BatchItem, BatchProcessor, CONSUMER_GROUPS, CircuitBreaker, CircuitBreakerOptions, ConsumerGroup, ContactChannel, ContactChannelSchema, ContactRepository, CreateWorkflowInput, CreateWorkflowSchema, CreatedProjectKeyRecord, DLQMessageRecord, DataLoader, DataLoaderOptions, DatabaseClients, DatabaseOptions, Db, DeliveryOptions, DeliveryOptionsSchema, DeliveryResult, DevicePlatform, DeviceToken, DispatchedTaskPayload, ENRICHED_STREAMS, EscapeMode, EventEnvelope, EventEnvelopeSchema, EventMetadata, EventMetadataSchema, EventPayloadMap, EventRegistry, INBOUND_STREAMS, IdempotencyGuard, IdempotencyOptions, IngestEventInput, IngestEventSchema, InlineUser, InlineUserSchema, KnownEventType, LRUCache, LUA_ACQUIRE_LEASE, LUA_COUNT_REQUEST, LUA_LEASE_API_RATE_LIMIT, LUA_MARK_PROCESSED, LUA_RELEASE_LOCK, LUA_RENEW_LOCK, LUA_SCHEDULER_POLL, LUA_USER_THROTTLE, LeaseResult, LockHeldError, LogLevel, Logger, LoggerOptions, MigrationOptions, NonRetryableError, NotificationAiPendingPayload, NotificationAiPendingPayloadSchema, NotificationCanceledPayload, NotificationCanceledPayloadSchema, NotificationChannel, NotificationChannelSchema, NotificationCreatedPayload, NotificationCreatedPayloadSchema, NotificationDeliveredPayload, NotificationDeliveredPayloadSchema, NotificationDispatchedPayload, NotificationDispatchedPayloadSchema, NotificationEnrichedPayload, NotificationEnrichedPayloadSchema, NotificationFailedPayload, NotificationFailedPayloadSchema, NotificationLogRecord, NotificationPreference, NotificationPriority, NotificationPrioritySchema, NotificationRequestedPayload, NotificationRequestedPayloadSchema, NotificationScheduledPayload, NotificationScheduledPayloadSchema, NotificationSkippedPayload, NotificationSkippedPayloadSchema, NotificationStatus, NotificationStatusSchema, NotificationTarget, NotificationTargetSchema, NotifkitClient, NotifkitClientOptions, NotifkitOptions, NotifkitServer, NotifyRequestInput, NotifyRequestSchema, OUTBOUND_STREAMS, PUBSUB_CHANNELS, ParseResult, PendingEntry, PendingMessageScanner, PendingMessageScannerOptions, PreferenceRepository, Preferences, PreferencesSchema, ProcessResult, ProjectKeyRecord, ProjectRecord, ProjectRepository, ProjectSettingsCache, ProjectSettingsCacheOptions, ProjectThrottleSettings, PubSubChannel, QuietHours, QuietHoursSchema, RateLimitConfig, RecipientProfile, RecipientProfileSchema, Redis, RedisClient, RedisClientOptions, type RedisOptions, RenderedContent, RenderedContentSchema, STREAMS, SegmentRepository, Sql, StreamConsumer, StreamConsumerOptions, StreamEvent, StreamEventMetadata, StreamEventMetadataSchema, StreamEventSchema, StreamMessage, StreamName, StreamProducer, StreamProducerOptions, SuppressionRecord, SuspendExecutionError, SyncTemplatesInput, SyncTemplatesSchema, SystemHealthRecord, SystemMetricsRecord, TemplateCache, TemplateInput, TemplateRecord, TemplateRecordResponse, TemplateRepository, TemplateSchema, ThrottleCheckOptions, ThrottleResult, Transport, TriggerWorkflowInput, TriggerWorkflowSchema, TypedEventEnvelope, UnsubscribeClaim, UnsubscribeHeaderOptions, UpdateProjectInput, UpdateProjectSchema, UpdateUserInput, UpdateUserSchema, UserContact, UserContactInput, UserContactInputSchema, UserContactResponse, UserDetailResponse, UserProfile, UserProfileResponse, UserRecord, UserRepository, UserResponse, UserThrottle, UserThrottleOptions, ValidationError, WebhookEvent, WorkerHealth, WorkerOptions, WorkerState, WorkflowContext, WorkflowDefinitionRecord, WorkflowEvent, WorkflowInstanceRecord, WorkflowNotifyInput, WorkflowNotifyPayloadSchema, WorkflowNotifyResult, WorkflowRepository, WorkflowStepContext, WorkflowStepDef, WorkflowStepRecord, WorkflowStepSchema, WorkflowWaiterRecord, assertTablesInSchema, baseConfigSchema, buildStepNotifyPayload, buildStreamEvent, buildUnsubscribeHeaders, calculateTokenBatchSize, createDatabase, createLogger, escapeHeader, escapeHtml, generateId, getAiConfig, getMetricsRegistry, getPriorityBucket, globalEmitter, interpolate, loadEnv, metrics, migrateDatabase, normaliseTarget, notifkitTableNames, parseConfig, qualifyMigrationSql, readBaseConfig, registerCustomCommands, registerTransport, registry, renderWithTemplate, resolveStepTarget, runMigrations, setAiConfig, setGlobalConfig, signUnsubscribeToken, sleep, startHealthReporter, transportRegistry, verifyUnsubscribeToken, workflow, workflowRegistry };
5295
+ export { AI_DEFAULTS, AddContactInput, AddContactSchema, AddUserInput, AddUserSchema, AdminUserRecord, AdminUserRepository, AiConfig, ApiRateLimiter, ApiRateLimiterOptions, AppError, AsyncSemaphore, BaseConfig, BaseWorker, BatchAddContactsInput, BatchAddContactsSchema, BatchItem, BatchProcessor, CONSUMER_GROUPS, CircuitBreaker, CircuitBreakerOptions, ConsumerGroup, ContactChannel, ContactChannelSchema, ContactRepository, CreateWorkflowInput, CreateWorkflowSchema, CreatedProjectKeyRecord, DLQMessageRecord, DataLoader, DataLoaderOptions, DatabaseClients, DatabaseOptions, Db, DeliveryOptions, DeliveryOptionsSchema, DeliveryResult, DevicePlatform, DeviceToken, DispatchedTaskPayload, ENRICHED_STREAMS, EscapeMode, EventEnvelope, EventEnvelopeSchema, EventMetadata, EventMetadataSchema, EventPayloadMap, EventRegistry, INBOUND_STREAMS, IdempotencyGuard, IdempotencyOptions, IngestEventInput, IngestEventSchema, InlineUser, InlineUserSchema, KnownEventType, LRUCache, LUA_ACQUIRE_LEASE, LUA_COUNT_REQUEST, LUA_LEASE_API_RATE_LIMIT, LUA_MARK_PROCESSED, LUA_RELEASE_LOCK, LUA_RENEW_LOCK, LUA_SCHEDULER_POLL, LUA_USER_THROTTLE, LeaseResult, LockHeldError, LogLevel, Logger, LoggerOptions, MigrationOptions, NonRetryableError, NotificationAiPendingPayload, NotificationAiPendingPayloadSchema, NotificationCanceledPayload, NotificationCanceledPayloadSchema, NotificationChannel, NotificationChannelSchema, NotificationCreatedPayload, NotificationCreatedPayloadSchema, NotificationDeliveredPayload, NotificationDeliveredPayloadSchema, NotificationDispatchedPayload, NotificationDispatchedPayloadSchema, NotificationEnrichedPayload, NotificationEnrichedPayloadSchema, NotificationFailedPayload, NotificationFailedPayloadSchema, NotificationLogRecord, NotificationPreference, NotificationPriority, NotificationPrioritySchema, NotificationRequestedPayload, NotificationRequestedPayloadSchema, NotificationScheduledPayload, NotificationScheduledPayloadSchema, NotificationSkippedPayload, NotificationSkippedPayloadSchema, NotificationStatus, NotificationStatusSchema, NotificationTarget, NotificationTargetSchema, NotifkitClient, NotifkitClientOptions, NotifkitOptions, NotifkitServer, NotifyRequestInput, NotifyRequestSchema, OUTBOUND_STREAMS, PUBSUB_CHANNELS, ParseResult, PendingEntry, PendingMessageScanner, PendingMessageScannerOptions, PreferenceRepository, Preferences, PreferencesSchema, ProcessResult, ProjectKeyRecord, ProjectRecord, ProjectRepository, ProjectSettingsCache, ProjectSettingsCacheOptions, ProjectThrottleSettings, PubSubChannel, QuietHours, QuietHoursSchema, RateLimitConfig, RecipientProfile, RecipientProfileSchema, Redis, RedisClient, RedisClientOptions, type RedisOptions, RenderedContent, RenderedContentSchema, STREAMS, SegmentRepository, Sql, StreamConsumer, StreamConsumerOptions, StreamEvent, StreamEventMetadata, StreamEventMetadataSchema, StreamEventSchema, StreamMessage, StreamName, StreamProducer, StreamProducerOptions, SuppressionRecord, SuspendExecutionError, SyncTemplatesInput, SyncTemplatesSchema, SystemHealthRecord, SystemMetricsRecord, TemplateCache, TemplateInput, TemplateRecord, TemplateRecordResponse, TemplateRepository, TemplateSchema, ThrottleCheckOptions, ThrottleResult, Transport, TriggerWorkflowInput, TriggerWorkflowSchema, TypedEventEnvelope, UnsubscribeClaim, UnsubscribeHeaderOptions, UpdateProjectInput, UpdateProjectSchema, UpdateUserInput, UpdateUserSchema, UserContact, UserContactInput, UserContactInputSchema, UserContactResponse, UserDetailResponse, UserProfile, UserProfileResponse, UserRecord, UserRepository, UserResponse, UserThrottle, UserThrottleOptions, ValidationError, WebhookEvent, WorkerHealth, WorkerOptions, WorkerState, WorkflowContext, WorkflowDefinitionRecord, WorkflowEvent, WorkflowInstanceRecord, WorkflowNotifyInput, WorkflowNotifyPayloadSchema, WorkflowNotifyResult, WorkflowRepository, WorkflowStepContext, WorkflowStepDef, WorkflowStepRecord, WorkflowStepSchema, WorkflowWaiterRecord, assertTablesInSchema, baseConfigSchema, buildStepNotifyPayload, buildStreamEvent, buildUnsubscribeHeaders, calculateTokenBatchSize, createDatabase, createLogger, escapeHeader, escapeHtml, generateId, getAiConfig, getMetricsRegistry, getPriorityBucket, globalEmitter, interpolate, loadEnv, metrics, migrateDatabase, normaliseTarget, notifkitTableNames, parseConfig, qualifyMigrationSql, readBaseConfig, redactUrl, registerCustomCommands, registerTransport, registry, renderWithTemplate, resolveStepTarget, runMigrations, setAiConfig, setGlobalConfig, signUnsubscribeToken, sleep, startHealthReporter, transportRegistry, verifyUnsubscribeToken, workflow, workflowRegistry };
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { $ as createDatabase, $t as PUBSUB_CHANNELS, A as LUA_ACQUIRE_LEASE, At as AddContactSchema, B as registerCustomCommands, Bt as SyncTemplatesSchema, C as ContactRepository, Cn as CircuitBreaker, Ct as RenderedContentSchema, D as TemplateRepository, Dn as normaliseTarget, Dt as NotificationCreatedPayloadSchema, E as SegmentRepository, En as getPriorityBucket, Et as RecipientProfileSchema, F as LUA_RENEW_LOCK, Ft as IngestEventSchema, G as PendingMessageScanner, Gt as UserContactInputSchema, H as ProjectSettingsCache, Ht as TriggerWorkflowSchema, I as LUA_SCHEDULER_POLL, It as InlineUserSchema, J as getMetricsRegistry, Jt as buildStreamEvent, K as StreamConsumer, Kt as WorkflowNotifyPayloadSchema, L as LUA_USER_THROTTLE, Lt as NotifyRequestSchema, M as LUA_LEASE_API_RATE_LIMIT, Mt as BatchAddContactsSchema, N as LUA_MARK_PROCESSED, Nt as ContactChannelSchema, O as UserRepository, On as LRUCache, Ot as NotificationRequestedPayloadSchema, P as LUA_RELEASE_LOCK, Pt as CreateWorkflowSchema, Q as assertTablesInSchema, Qt as OUTBOUND_STREAMS, R as Redis, Rt as PreferencesSchema, S as AdminUserRepository, Sn as DataLoader, St as NotificationDispatchedPayloadSchema, T as ProjectRepository, Tn as AsyncSemaphore, Tt as NotificationEnrichedPayloadSchema, U as UserThrottle, Ut as UpdateProjectSchema, V as ApiRateLimiter, Vt as TemplateSchema, W as calculateTokenBatchSize, Wt as UpdateUserSchema, X as createLogger, Xt as ENRICHED_STREAMS, Y as metrics, Yt as CONSUMER_GROUPS, Z as IdempotencyGuard, Zt as INBOUND_STREAMS, _ as TemplateCache, _n as setGlobalConfig, _t as NotificationCanceledPayloadSchema, a as SuspendExecutionError, an as registry, b as interpolate, bn as generateId, bt as NotificationDeliveredPayloadSchema, c as BaseWorker, cn as NotificationPrioritySchema, d as startHealthReporter, dn as baseConfigSchema, en as STREAMS, et as migrateDatabase, f as buildUnsubscribeHeaders, fn as getAiConfig, g as transportRegistry, gn as setAiConfig, gt as NotificationAiPendingPayloadSchema, h as registerTransport, hn as readBaseConfig, i as workflowRegistry, in as EventRegistry, j as LUA_COUNT_REQUEST, jt as AddUserSchema, k as WorkflowRepository, kn as globalEmitter, kt as NotificationTargetSchema, l as LockHeldError, ln as NotificationStatusSchema, m as verifyUnsubscribeToken, mn as parseConfig, n as NotifkitClient, nn as StreamEventMetadataSchema, nt as qualifyMigrationSql, o as buildStepNotifyPayload, on as EventMetadataSchema, p as signUnsubscribeToken, pn as loadEnv, q as StreamProducer, qt as WorkflowStepSchema, r as workflow, rn as StreamEventSchema, rt as runMigrations, s as resolveStepTarget, sn as NotificationChannelSchema, t as NotifkitServer, tn as EventEnvelopeSchema, tt as notifkitTableNames, u as NonRetryableError, un as AI_DEFAULTS, v as escapeHeader, vn as AppError, vt as NotificationSkippedPayloadSchema, w as PreferenceRepository, wn as BatchProcessor, wt as NotificationScheduledPayloadSchema, x as renderWithTemplate, xn as sleep, xt as DeliveryOptionsSchema, y as escapeHtml, yn as ValidationError, yt as NotificationFailedPayloadSchema, z as RedisClient, zt as QuietHoursSchema } from "./src-9LXITcNi.mjs";
2
- export { AI_DEFAULTS, AddContactSchema, AddUserSchema, AdminUserRepository, ApiRateLimiter, 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_ACQUIRE_LEASE, LUA_COUNT_REQUEST, LUA_LEASE_API_RATE_LIMIT, LUA_MARK_PROCESSED, LUA_RELEASE_LOCK, LUA_RENEW_LOCK, LUA_SCHEDULER_POLL, LUA_USER_THROTTLE, LockHeldError, 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, assertTablesInSchema, baseConfigSchema, buildStepNotifyPayload, buildStreamEvent, buildUnsubscribeHeaders, calculateTokenBatchSize, createDatabase, createLogger, escapeHeader, escapeHtml, generateId, getAiConfig, getMetricsRegistry, getPriorityBucket, globalEmitter, interpolate, loadEnv, metrics, migrateDatabase, normaliseTarget, notifkitTableNames, parseConfig, qualifyMigrationSql, readBaseConfig, registerCustomCommands, registerTransport, registry, renderWithTemplate, resolveStepTarget, runMigrations, setAiConfig, setGlobalConfig, signUnsubscribeToken, sleep, startHealthReporter, transportRegistry, verifyUnsubscribeToken, workflow, workflowRegistry };
1
+ import { $ as assertTablesInSchema, $t as OUTBOUND_STREAMS, A as LUA_ACQUIRE_LEASE, An as globalEmitter, At as NotificationTargetSchema, B as redactUrl, Bt as QuietHoursSchema, C as SegmentRepository, Cn as DataLoader, Ct as NotificationDispatchedPayloadSchema, D as ContactRepository, Dn as getPriorityBucket, Dt as RecipientProfileSchema, E as TemplateRepository, En as AsyncSemaphore, Et as NotificationEnrichedPayloadSchema, F as LUA_RENEW_LOCK, Ft as CreateWorkflowSchema, G as ProjectSettingsCache, Gt as UpdateUserSchema, H as ApiRateLimiter, Ht as TemplateSchema, I as LUA_SCHEDULER_POLL, It as IngestEventSchema, J as StreamProducer, Jt as WorkflowStepSchema, K as PendingMessageScanner, Kt as UserContactInputSchema, L as LUA_USER_THROTTLE, Lt as InlineUserSchema, M as LUA_LEASE_API_RATE_LIMIT, Mt as AddUserSchema, N as LUA_MARK_PROCESSED, Nt as BatchAddContactsSchema, O as PreferenceRepository, On as normaliseTarget, Ot as NotificationCreatedPayloadSchema, P as LUA_RELEASE_LOCK, Pt as ContactChannelSchema, Q as IdempotencyGuard, Qt as INBOUND_STREAMS, R as Redis, Rt as NotifyRequestSchema, S as AdminUserRepository, Sn as sleep, St as DeliveryOptionsSchema, T as ProjectRepository, Tn as BatchProcessor, Tt as NotificationScheduledPayloadSchema, U as calculateTokenBatchSize, Ut as TriggerWorkflowSchema, V as registerCustomCommands, Vt as SyncTemplatesSchema, W as UserThrottle, Wt as UpdateProjectSchema, X as metrics, Xt as CONSUMER_GROUPS, Y as getMetricsRegistry, Yt as buildStreamEvent, Z as createLogger, Zt as ENRICHED_STREAMS, _ as TemplateCache, _n as setAiConfig, _t as NotificationAiPendingPayloadSchema, a as SuspendExecutionError, an as EventRegistry, b as interpolate, bn as ValidationError, bt as NotificationFailedPayloadSchema, c as BaseWorker, cn as NotificationChannelSchema, d as startHealthReporter, dn as AI_DEFAULTS, en as PUBSUB_CHANNELS, et as createDatabase, f as buildUnsubscribeHeaders, fn as baseConfigSchema, g as transportRegistry, gn as readBaseConfig, h as registerTransport, hn as parseConfig, i as workflowRegistry, in as StreamEventSchema, it as runMigrations, j as LUA_COUNT_REQUEST, jt as AddContactSchema, k as UserRepository, kn as LRUCache, kt as NotificationRequestedPayloadSchema, l as LockHeldError, ln as NotificationPrioritySchema, m as verifyUnsubscribeToken, mn as loadEnv, n as NotifkitClient, nn as EventEnvelopeSchema, nt as notifkitTableNames, o as buildStepNotifyPayload, on as registry, p as signUnsubscribeToken, pn as getAiConfig, q as StreamConsumer, qt as WorkflowNotifyPayloadSchema, r as workflow, rn as StreamEventMetadataSchema, rt as qualifyMigrationSql, s as resolveStepTarget, sn as EventMetadataSchema, t as NotifkitServer, tn as STREAMS, tt as migrateDatabase, u as NonRetryableError, un as NotificationStatusSchema, v as escapeHeader, vn as setGlobalConfig, vt as NotificationCanceledPayloadSchema, w as WorkflowRepository, wn as CircuitBreaker, wt as RenderedContentSchema, x as renderWithTemplate, xn as generateId, xt as NotificationDeliveredPayloadSchema, y as escapeHtml, yn as AppError, yt as NotificationSkippedPayloadSchema, z as RedisClient, zt as PreferencesSchema } from "./src-BE_EUpZ6.mjs";
2
+ export { AI_DEFAULTS, AddContactSchema, AddUserSchema, AdminUserRepository, ApiRateLimiter, 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_ACQUIRE_LEASE, LUA_COUNT_REQUEST, LUA_LEASE_API_RATE_LIMIT, LUA_MARK_PROCESSED, LUA_RELEASE_LOCK, LUA_RENEW_LOCK, LUA_SCHEDULER_POLL, LUA_USER_THROTTLE, LockHeldError, 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, assertTablesInSchema, baseConfigSchema, buildStepNotifyPayload, buildStreamEvent, buildUnsubscribeHeaders, calculateTokenBatchSize, createDatabase, createLogger, escapeHeader, escapeHtml, generateId, getAiConfig, getMetricsRegistry, getPriorityBucket, globalEmitter, interpolate, loadEnv, metrics, migrateDatabase, normaliseTarget, notifkitTableNames, parseConfig, qualifyMigrationSql, readBaseConfig, redactUrl, registerCustomCommands, registerTransport, registry, renderWithTemplate, resolveStepTarget, runMigrations, setAiConfig, setGlobalConfig, signUnsubscribeToken, sleep, startHealthReporter, transportRegistry, verifyUnsubscribeToken, workflow, workflowRegistry };
@@ -1,5 +1,6 @@
1
- import { D as TemplateRepository, En as getPriorityBucket, Jt as buildStreamEvent, Yt as CONSUMER_GROUPS, Z as IdempotencyGuard, _ as TemplateCache, an as registry, c as BaseWorker, ct as scheduledPayloads, d as startHealthReporter, en as STREAMS, fn as getAiConfig, hn as readBaseConfig, kn as globalEmitter, pn as loadEnv, q as StreamProducer, un as AI_DEFAULTS, x as renderWithTemplate } from "./src-9LXITcNi.mjs";
2
- import { a as uniqueConsumerId, i as shutdownWorker, n as createStreamConsumer, r as createWorkerRuntime, t as createPriorityProducers } from "./bootstrap-BOmT69OH.mjs";
1
+ import { An as globalEmitter, B as redactUrl, E as TemplateRepository, J as StreamProducer, Q as IdempotencyGuard, Xt as CONSUMER_GROUPS, _ as TemplateCache, c as BaseWorker, d as startHealthReporter, dn as AI_DEFAULTS, en as PUBSUB_CHANNELS, gn as readBaseConfig, mn as loadEnv, on as registry, pn as getAiConfig, tn as STREAMS, x as renderWithTemplate } from "./src-BE_EUpZ6.mjs";
2
+ import { t as scheduleOrDispatch } from "./schedule-or-dispatch-Cd7GLfc3.mjs";
3
+ import { a as uniqueConsumerId, i as shutdownWorker, n as createStreamConsumer, r as createWorkerRuntime, t as createPriorityProducers } from "./bootstrap-BMDRPjgp.mjs";
3
4
  import { generateText } from "ai";
4
5
  //#region src/services/ai/main.ts
5
6
  loadEnv();
@@ -39,7 +40,6 @@ function isRetryableAiError(err) {
39
40
  var AiWorker = class extends BaseWorker {
40
41
  registry;
41
42
  idempotency;
42
- redisCli;
43
43
  generateAiContent;
44
44
  templateCache;
45
45
  scheduledProducer;
@@ -49,7 +49,6 @@ var AiWorker = class extends BaseWorker {
49
49
  super(options);
50
50
  this.registry = options.registry;
51
51
  this.idempotency = options.idempotency;
52
- this.redisCli = options.redis;
53
52
  this.generateAiContent = options.generateAiContent;
54
53
  this.templateCache = options.templateCache;
55
54
  this.scheduledProducer = options.scheduledProducer;
@@ -125,39 +124,20 @@ var AiWorker = class extends BaseWorker {
125
124
  campaignId: pending.campaignId,
126
125
  workflowInstanceId: pending.workflowInstanceId
127
126
  };
128
- const envelope = buildStreamEvent("notification.dispatched", taskPayload, "ai-worker", event.metadata.traceId);
129
- const now = Date.now();
130
- if ((pending.scheduledAt ? new Date(pending.scheduledAt).getTime() : now) > now) {
131
- await this.db.insert(scheduledPayloads).values({
132
- taskId,
133
- payload: {
134
- ...taskPayload,
135
- scheduledAt: pending.scheduledAt
136
- }
137
- }).onConflictDoNothing();
138
- const scheduledEnvelope = buildStreamEvent("notification.scheduled", {
139
- projectId: pending.projectId,
140
- enrichedEventId: pending.enrichedEventId,
141
- taskId,
142
- scheduledAt: pending.scheduledAt
143
- }, "ai-worker", event.metadata.traceId);
144
- await this.scheduledProducer.publish(scheduledEnvelope);
145
- this.logger.info({
146
- messageId: message.id,
147
- taskId,
148
- scheduledAt: pending.scheduledAt,
149
- traceId: event.metadata.traceId
150
- }, "task scheduled and payload cached after AI generation");
151
- } else {
152
- const p = getPriorityBucket(pending.priority);
153
- await (this.outboundProducers[p] ?? this.outboundProducers["normal"]).publish(envelope);
154
- this.logger.info({
155
- messageId: message.id,
156
- taskId,
157
- recipientId: pending.recipientId,
158
- traceId: event.metadata.traceId
159
- }, "task dispatched after AI generation");
160
- }
127
+ await scheduleOrDispatch({
128
+ db: this.db,
129
+ scheduledProducer: this.scheduledProducer,
130
+ outboundProducers: this.outboundProducers,
131
+ logger: this.logger
132
+ }, taskPayload, {
133
+ source: "ai-worker",
134
+ scheduledAt: pending.scheduledAt,
135
+ messageId: message.id,
136
+ traceId: event.metadata.traceId,
137
+ logLevel: "info",
138
+ scheduledMessage: "task scheduled and payload cached after AI generation",
139
+ dispatchedMessage: "task dispatched after AI generation"
140
+ });
161
141
  await this.idempotency.markProcessed?.(idempotencyKey);
162
142
  } catch (err) {
163
143
  await this.idempotency.unmark(idempotencyKey);
@@ -201,7 +181,7 @@ async function startAiWorker() {
201
181
  async function generateAiContent(prompt, vars) {
202
182
  const aiConfig = getAiConfig();
203
183
  const interpolated = prompt.replace(/\{\{(\w+)\}\}/g, (_, k) => String(vars[k] ?? ""));
204
- if (!aiConfig || !aiConfig.aiModel) {
184
+ if (!aiConfig.aiModel) {
205
185
  logger.warn("AI worker called but no AI model was provided to NotifkitServer");
206
186
  return `[AI Disabled] ${interpolated}`;
207
187
  }
@@ -238,9 +218,9 @@ async function startAiWorker() {
238
218
  db
239
219
  });
240
220
  subscriber = redis.native.duplicate({ enableAutoPipelining: false });
241
- await subscriber.subscribe("template.invalidated");
221
+ await subscriber.subscribe(PUBSUB_CHANNELS.TEMPLATE_INVALIDATED);
242
222
  subscriber.on("message", (channel, message) => {
243
- if (channel === "template.invalidated") {
223
+ if (channel === PUBSUB_CHANNELS.TEMPLATE_INVALIDATED) {
244
224
  templateCache.invalidateKey(message);
245
225
  logger.info({ cacheKey: message }, "invalidated template cache");
246
226
  }
@@ -248,7 +228,7 @@ async function startAiWorker() {
248
228
  healthInterval = startHealthReporter("ai", worker, redis, logger);
249
229
  logger.info({
250
230
  env: config.NODE_ENV,
251
- redis: config.REDIS_URL
231
+ redis: redactUrl(config.REDIS_URL)
252
232
  }, "ai starting");
253
233
  await worker.start();
254
234
  }