notifkit 0.1.15 → 0.1.17
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.
- package/dashboard/dist/assets/index-C-DJYu0_.css +1 -0
- package/dashboard/dist/assets/index-CzFZcEon.js +318 -0
- package/dashboard/dist/index.html +2 -2
- package/dist/{bootstrap-BOmT69OH.mjs → bootstrap-P63acBG9.mjs} +1 -1
- package/dist/{bulk-ZPiOJRx-.mjs → bulk-Beblt3ny.mjs} +1 -1
- package/dist/index.d.mts +84 -27
- package/dist/index.mjs +2 -2
- package/dist/{main-CTjaZ7ZD.mjs → main-BIahf4f9.mjs} +13 -15
- package/dist/{main-CCqcFDDe.mjs → main-C3XcLoCb.mjs} +21 -41
- package/dist/{main-g33jpia4.mjs → main-CktEylpL.mjs} +676 -582
- package/dist/{main-BdZvBgV7.mjs → main-DB0bUh2r.mjs} +22 -48
- package/dist/{main-JEXBLP2A.mjs → main-Dk92nti8.mjs} +8 -6
- package/dist/{main-C0m9-Eos.mjs → main-Lcbg7aEn.mjs} +183 -334
- package/dist/{main-C6S3EsJ3.mjs → main-NHUvynW2.mjs} +77 -64
- package/dist/{main-24J4U8yP.mjs → main-_I4b1cmP.mjs} +4 -4
- package/dist/schedule-or-dispatch-C5qfxQCv.mjs +52 -0
- package/dist/{src-9LXITcNi.mjs → src-BRatuWJS.mjs} +125 -95
- package/package.json +1 -1
- package/scripts/create-project.mjs +6 -2
- package/src/client.ts +3 -3
- package/src/config/index.ts +2 -1
- package/src/contracts/common.ts +2 -0
- package/src/contracts/envelope.ts +1 -1
- package/src/contracts/events/notification-created.ts +2 -0
- package/src/contracts/events/notification-delivered.ts +1 -1
- package/src/contracts/events/notification-failed.ts +1 -1
- package/src/contracts/events/notification-requested.ts +3 -2
- package/src/contracts/helpers.ts +1 -2
- package/src/contracts/index.ts +1 -0
- package/src/contracts/registry.ts +1 -0
- package/src/contracts/sdk.ts +8 -37
- package/src/db/schema.ts +8 -13
- package/src/idempotency/index.ts +6 -8
- package/src/metrics/index.ts +2 -0
- package/src/queue/index.ts +8 -0
- package/src/rate-limiter/api-rate-limiter.ts +208 -0
- package/src/rate-limiter/index.ts +3 -411
- package/src/rate-limiter/project-settings-cache.ts +99 -0
- package/src/rate-limiter/user-throttle.ts +100 -0
- package/src/redis/index.ts +10 -3
- package/src/repositories/admin-user.ts +83 -0
- package/src/repositories/contact.ts +359 -0
- package/src/repositories/index.ts +9 -1416
- package/src/repositories/preference.ts +35 -0
- package/src/repositories/project.ts +110 -0
- package/src/repositories/segment.ts +16 -0
- package/src/repositories/template.ts +72 -0
- package/src/repositories/types.ts +49 -0
- package/src/repositories/user.ts +644 -0
- package/src/repositories/workflow.ts +64 -0
- package/src/services/ai/main.ts +29 -71
- package/src/services/api/admin-static.ts +4 -1
- package/src/services/api/handlers/auth.ts +109 -0
- package/src/services/api/handlers/campaigns.ts +191 -0
- package/src/services/api/handlers/events.ts +99 -0
- package/src/services/api/handlers/notifications.ts +356 -0
- package/src/services/api/handlers/projects.ts +116 -0
- package/src/services/api/handlers/shared.ts +262 -0
- package/src/services/api/handlers/suppressions.ts +95 -0
- package/src/services/api/handlers/system.ts +314 -0
- package/src/services/api/handlers/templates.ts +97 -0
- package/src/services/api/handlers/unsubscribe.ts +215 -0
- package/src/services/api/handlers/users.ts +262 -0
- package/src/services/api/handlers/workflows.ts +150 -0
- package/src/services/api/handlers.ts +25 -2190
- package/src/services/api/health.ts +133 -0
- package/src/services/api/http.ts +12 -0
- package/src/services/api/main.ts +32 -322
- package/src/services/api/router.ts +1 -1
- package/src/services/api/webhooks.ts +172 -0
- package/src/services/delivery/main.ts +256 -498
- package/src/services/engine/main.ts +31 -247
- package/src/services/engine/quiet-hours.ts +151 -0
- package/src/services/engine/schedule-or-dispatch.ts +104 -0
- package/src/services/enricher/main.ts +9 -21
- package/src/services/events/main.ts +2 -2
- package/src/services/scheduler/main.ts +16 -25
- package/src/services/workflow/duration.ts +24 -0
- package/src/services/workflow/main.ts +6 -164
- package/src/services/workflow/timers.ts +157 -0
- package/src/shared/events.ts +3 -2
- package/src/templates/render.ts +1 -0
- package/src/workers/index.ts +34 -5
- package/src/workflows/sdk.ts +1 -0
- package/dashboard/dist/assets/index-ggpJKZqZ.js +0 -315
- 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-
|
|
9
|
-
<link rel="stylesheet" crossorigin href="./assets/index-
|
|
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 {
|
|
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-BRatuWJS.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) {
|
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.
|
|
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.
|
|
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"
|
|
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"
|
|
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"
|
|
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"
|
|
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"
|
|
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"
|
|
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"
|
|
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
|
-
*
|
|
3976
|
-
*
|
|
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
|
-
*
|
|
3990
|
-
*
|
|
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">;
|
|
@@ -4134,18 +4141,18 @@ declare class PendingMessageScanner {
|
|
|
4134
4141
|
private readonly consumer;
|
|
4135
4142
|
private readonly logger?;
|
|
4136
4143
|
constructor({ redis, stream, group, consumer, logger }: PendingMessageScannerOptions);
|
|
4144
|
+
/**
|
|
4145
|
+
* Resets a held entry's idle time so no scanner reclaims it while its
|
|
4146
|
+
* handler is still running. JUSTID leaves the delivery count alone.
|
|
4147
|
+
*/
|
|
4148
|
+
touch(id: string, stream: string): Promise<void>;
|
|
4137
4149
|
getPendingCount(): Promise<number>;
|
|
4138
4150
|
/** Pending entries for one stream, or across all of them when `stream` is omitted. */
|
|
4139
4151
|
getPendingEntries(limit?: number, stream?: StreamName): Promise<PendingEntry[]>;
|
|
4140
4152
|
autoclaim(minIdleMs: number, limit?: number): Promise<StreamMessage[]>;
|
|
4141
4153
|
}
|
|
4142
4154
|
//#endregion
|
|
4143
|
-
//#region src/rate-limiter/
|
|
4144
|
-
interface ThrottleResult {
|
|
4145
|
-
allowed: boolean;
|
|
4146
|
-
count: number;
|
|
4147
|
-
limit: number;
|
|
4148
|
-
}
|
|
4155
|
+
//#region src/rate-limiter/project-settings-cache.d.ts
|
|
4149
4156
|
/**
|
|
4150
4157
|
* Throttle overrides stored on the project row. `null` on either field means
|
|
4151
4158
|
* "no override" — fall back to the process-wide default.
|
|
@@ -4189,6 +4196,13 @@ declare class ProjectSettingsCache {
|
|
|
4189
4196
|
invalidate(projectId: string): void;
|
|
4190
4197
|
clear(): void;
|
|
4191
4198
|
}
|
|
4199
|
+
//#endregion
|
|
4200
|
+
//#region src/rate-limiter/user-throttle.d.ts
|
|
4201
|
+
interface ThrottleResult {
|
|
4202
|
+
allowed: boolean;
|
|
4203
|
+
count: number;
|
|
4204
|
+
limit: number;
|
|
4205
|
+
}
|
|
4192
4206
|
interface UserThrottleOptions {
|
|
4193
4207
|
redis: Redis;
|
|
4194
4208
|
maxPerHour?: number;
|
|
@@ -4221,6 +4235,8 @@ declare class UserThrottle {
|
|
|
4221
4235
|
*/
|
|
4222
4236
|
check(projectId: string, userId: string, priority?: string, options?: ThrottleCheckOptions): Promise<ThrottleResult>;
|
|
4223
4237
|
}
|
|
4238
|
+
//#endregion
|
|
4239
|
+
//#region src/rate-limiter/api-rate-limiter.d.ts
|
|
4224
4240
|
interface ApiRateLimiterOptions {
|
|
4225
4241
|
redis: Redis;
|
|
4226
4242
|
windowMs?: number;
|
|
@@ -4305,9 +4321,15 @@ declare const LUA_SCHEDULER_POLL = "\n local key = KEYS[1]\n local maxScore =
|
|
|
4305
4321
|
* address it counted stayed over its limit for good.
|
|
4306
4322
|
*/
|
|
4307
4323
|
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
|
-
/**
|
|
4324
|
+
/**
|
|
4325
|
+
* Two-phase idempotency lease acquisition. Checks sent/legacy, then attempts SET NX lock.
|
|
4326
|
+
* @deprecated Nothing calls the `acquireLease` command; removed in the next minor version.
|
|
4327
|
+
*/
|
|
4309
4328
|
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
|
-
/**
|
|
4329
|
+
/**
|
|
4330
|
+
* Two-phase idempotency completion marker. Atomically sets completed + legacy and deletes lock.
|
|
4331
|
+
* @deprecated Nothing calls the `markProcessed` command; removed in the next minor version.
|
|
4332
|
+
*/
|
|
4311
4333
|
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
4334
|
/**
|
|
4313
4335
|
* Registers pre-compiled custom commands on an ioredis instance.
|
|
@@ -4343,8 +4365,9 @@ declare class RedisClient {
|
|
|
4343
4365
|
healthCheck(): Promise<boolean>;
|
|
4344
4366
|
disconnect(): Promise<void>;
|
|
4345
4367
|
}
|
|
4368
|
+
declare function redactUrl(url: string): string;
|
|
4346
4369
|
//#endregion
|
|
4347
|
-
//#region src/repositories/
|
|
4370
|
+
//#region src/repositories/types.d.ts
|
|
4348
4371
|
interface UserProfile {
|
|
4349
4372
|
userId: string;
|
|
4350
4373
|
language?: string;
|
|
@@ -4371,7 +4394,9 @@ interface TemplateRecord {
|
|
|
4371
4394
|
/** Template-level AI prompts, merged with per-request ones by the engine. */
|
|
4372
4395
|
aiPrompts?: Record<string, string> | null;
|
|
4373
4396
|
}
|
|
4397
|
+
/** @deprecated Unused; removed in the next minor version. */
|
|
4374
4398
|
type DevicePlatform = "fcm" | "apns" | "web";
|
|
4399
|
+
/** @deprecated Unused; removed in the next minor version. */
|
|
4375
4400
|
interface DeviceToken {
|
|
4376
4401
|
id: string;
|
|
4377
4402
|
userId: string;
|
|
@@ -4384,10 +4409,14 @@ interface NotificationPreference {
|
|
|
4384
4409
|
eventType: string;
|
|
4385
4410
|
optedIn: boolean;
|
|
4386
4411
|
}
|
|
4412
|
+
//#endregion
|
|
4413
|
+
//#region src/repositories/user.d.ts
|
|
4387
4414
|
declare class UserRepository {
|
|
4388
4415
|
private readonly db;
|
|
4389
4416
|
private readonly recordCache;
|
|
4390
4417
|
constructor(db: Db);
|
|
4418
|
+
/** A repository that runs its queries inside `tx`. */
|
|
4419
|
+
withTx(tx: Db): UserRepository;
|
|
4391
4420
|
findById(projectId: string, userId: string): Promise<UserProfile | null>;
|
|
4392
4421
|
findRecordById(projectId: string, userId: string): Promise<UserRecord | null>;
|
|
4393
4422
|
findRecordsByIds(projectId: string, userIds: string[]): Promise<UserRecord[]>;
|
|
@@ -4428,16 +4457,23 @@ declare class UserRepository {
|
|
|
4428
4457
|
findUsersBySegment(projectId: string, segmentName: string): Promise<string[]>;
|
|
4429
4458
|
findUsersByTopic(projectId: string, topicName: string): Promise<string[]>;
|
|
4430
4459
|
}
|
|
4460
|
+
//#endregion
|
|
4461
|
+
//#region src/repositories/preference.d.ts
|
|
4462
|
+
/** @deprecated Unused; removed in the next minor version. */
|
|
4431
4463
|
declare class PreferenceRepository {
|
|
4432
4464
|
private readonly db;
|
|
4433
4465
|
constructor(db: Db);
|
|
4434
4466
|
isOptedIn(projectId: string, userId: string, eventType: string): Promise<boolean>;
|
|
4435
4467
|
findByUserId(projectId: string, userId: string): Promise<NotificationPreference[]>;
|
|
4436
4468
|
}
|
|
4469
|
+
//#endregion
|
|
4470
|
+
//#region src/repositories/contact.d.ts
|
|
4437
4471
|
declare class ContactRepository {
|
|
4438
4472
|
private readonly db;
|
|
4439
4473
|
private readonly activeContactsCache;
|
|
4440
4474
|
constructor(db: Db);
|
|
4475
|
+
/** A repository that runs its queries inside `tx`. */
|
|
4476
|
+
withTx(tx: Db): ContactRepository;
|
|
4441
4477
|
findByUserId(projectId: string, userId: string): Promise<UserContact[]>;
|
|
4442
4478
|
/** Resolve active addressable contacts for a batch without an N+1 query. */
|
|
4443
4479
|
findActiveByUserIds(projectId: string, userIds: string[]): Promise<Map<string, UserContact[]>>;
|
|
@@ -4456,6 +4492,8 @@ declare class ContactRepository {
|
|
|
4456
4492
|
deactivate(projectId: string, userId: string, channel: ContactChannel, target: string): Promise<boolean>;
|
|
4457
4493
|
delete(projectId: string, userId: string, channel: ContactChannel, target: string): Promise<boolean>;
|
|
4458
4494
|
}
|
|
4495
|
+
//#endregion
|
|
4496
|
+
//#region src/repositories/template.d.ts
|
|
4459
4497
|
declare class TemplateRepository {
|
|
4460
4498
|
private readonly db;
|
|
4461
4499
|
constructor(db: Db);
|
|
@@ -4464,6 +4502,8 @@ declare class TemplateRepository {
|
|
|
4464
4502
|
upsertMany(projectId: string, templateList: any[]): Promise<number>;
|
|
4465
4503
|
delete(projectId: string, id: string): Promise<boolean>;
|
|
4466
4504
|
}
|
|
4505
|
+
//#endregion
|
|
4506
|
+
//#region src/repositories/project.d.ts
|
|
4467
4507
|
declare class ProjectRepository {
|
|
4468
4508
|
private readonly db;
|
|
4469
4509
|
constructor(db: Db);
|
|
@@ -4488,6 +4528,8 @@ declare class ProjectRepository {
|
|
|
4488
4528
|
listApiKeys(projectId: string): Promise<any[]>;
|
|
4489
4529
|
deleteApiKey(projectId: string, keyId: string): Promise<boolean>;
|
|
4490
4530
|
}
|
|
4531
|
+
//#endregion
|
|
4532
|
+
//#region src/repositories/workflow.d.ts
|
|
4491
4533
|
declare class WorkflowRepository {
|
|
4492
4534
|
private readonly db;
|
|
4493
4535
|
constructor(db: Db);
|
|
@@ -4495,11 +4537,15 @@ declare class WorkflowRepository {
|
|
|
4495
4537
|
getInstance(projectId: string, instanceId: string): Promise<any | null>;
|
|
4496
4538
|
cancelInstance(projectId: string, instanceId: string): Promise<boolean>;
|
|
4497
4539
|
}
|
|
4540
|
+
//#endregion
|
|
4541
|
+
//#region src/repositories/segment.d.ts
|
|
4498
4542
|
declare class SegmentRepository {
|
|
4499
4543
|
private readonly db;
|
|
4500
4544
|
constructor(db: Db);
|
|
4501
4545
|
listSegments(projectId: string): Promise<string[]>;
|
|
4502
4546
|
}
|
|
4547
|
+
//#endregion
|
|
4548
|
+
//#region src/repositories/admin-user.d.ts
|
|
4503
4549
|
interface AdminUserRecord {
|
|
4504
4550
|
id: string;
|
|
4505
4551
|
email: string;
|
|
@@ -4520,7 +4566,9 @@ declare class AdminUserRepository {
|
|
|
4520
4566
|
passwordHash: string;
|
|
4521
4567
|
role?: string;
|
|
4522
4568
|
}): Promise<AdminUserRecord>;
|
|
4569
|
+
/** @deprecated Unused; removed in the next minor version. */
|
|
4523
4570
|
updatePassword(id: string, passwordHash: string): Promise<boolean>;
|
|
4571
|
+
/** @deprecated Unused; removed in the next minor version. */
|
|
4524
4572
|
list(): Promise<Omit<AdminUserRecord, "passwordHash">[]>;
|
|
4525
4573
|
count(): Promise<number>;
|
|
4526
4574
|
}
|
|
@@ -4717,6 +4765,14 @@ declare abstract class BaseWorker {
|
|
|
4717
4765
|
*/
|
|
4718
4766
|
processInline(event: StreamEvent): Promise<void>;
|
|
4719
4767
|
private processWithTracking;
|
|
4768
|
+
/**
|
|
4769
|
+
* Runs `process` while keeping the entry's idle time below the reclaim
|
|
4770
|
+
* threshold. Without this, a handler that outlasts `recoveryIntervalMs` (a
|
|
4771
|
+
* large segment fan-out) is reclaimed mid-run and started again elsewhere,
|
|
4772
|
+
* over and over, until it is dead-lettered while the first run still works.
|
|
4773
|
+
* If this process dies the touches stop, so the entry is reclaimed as before.
|
|
4774
|
+
*/
|
|
4775
|
+
private processHoldingLease;
|
|
4720
4776
|
/**
|
|
4721
4777
|
* `recoveryIntervalMs` is how long an entry must sit idle before it is
|
|
4722
4778
|
* claimed, not how often to look. Scanning only once per interval, timed from
|
|
@@ -4745,6 +4801,7 @@ declare class ValidationError extends AppError {
|
|
|
4745
4801
|
declare function escapeHtml(unsafe: string): string;
|
|
4746
4802
|
/** Strip CR/LF so an interpolated value cannot inject extra headers. */
|
|
4747
4803
|
declare function escapeHeader(unsafe: string): string;
|
|
4804
|
+
/** @deprecated Unused; templates render through renderWithTemplate. Removed in the next minor version. */
|
|
4748
4805
|
declare function interpolate(tmpl: string, variables: Record<string, unknown>, sanitize?: boolean): string;
|
|
4749
4806
|
/**
|
|
4750
4807
|
* How an interpolated value must be escaped, decided by the field it lands in.
|
|
@@ -5248,4 +5305,4 @@ declare class NotifkitServer extends EventEmitter {
|
|
|
5248
5305
|
stop(): Promise<void>;
|
|
5249
5306
|
}
|
|
5250
5307
|
//#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 };
|
|
5308
|
+
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
|
|
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-BRatuWJS.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,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { a as uniqueConsumerId, i as shutdownWorker, n as createStreamConsumer, r as createWorkerRuntime, t as createPriorityProducers } from "./bootstrap-
|
|
1
|
+
import { An as globalEmitter, D as ContactRepository, Dn as getPriorityBucket, E as TemplateRepository, On as normaliseTarget, Xt as CONSUMER_GROUPS, Yt as buildStreamEvent, c as BaseWorker, d as startHealthReporter, gn as readBaseConfig, k as UserRepository, lt as scheduledPayloads, mn as loadEnv, on as registry, tn as STREAMS, ut as suppressions } from "./src-BRatuWJS.mjs";
|
|
2
|
+
import { a as uniqueConsumerId, i as shutdownWorker, n as createStreamConsumer, r as createWorkerRuntime, t as createPriorityProducers } from "./bootstrap-P63acBG9.mjs";
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
4
|
import { and, asc, eq, gt, inArray, or, sql } from "drizzle-orm";
|
|
5
5
|
//#region src/services/scheduler/send-gate.ts
|
|
@@ -77,6 +77,9 @@ let worker;
|
|
|
77
77
|
let healthInterval = null;
|
|
78
78
|
let pollTimeout = null;
|
|
79
79
|
let isPolling = false;
|
|
80
|
+
/** Scheduled tasks are spread over 16 sorted sets by the last hex digit of the task id. */
|
|
81
|
+
const shardOf = (taskId) => parseInt(taskId.slice(-1), 16) || 0;
|
|
82
|
+
const zsetKey = (shard) => `notif:scheduled:zset:${shard}`;
|
|
80
83
|
var SchedulerWorker = class extends BaseWorker {
|
|
81
84
|
registry;
|
|
82
85
|
redisCli;
|
|
@@ -102,9 +105,8 @@ var SchedulerWorker = class extends BaseWorker {
|
|
|
102
105
|
enrichedEventId: scheduled.enrichedEventId,
|
|
103
106
|
traceId: event.metadata.traceId
|
|
104
107
|
});
|
|
105
|
-
const shard =
|
|
106
|
-
|
|
107
|
-
await this.redisCli.zadd(zsetKey, scheduledAt, taskData);
|
|
108
|
+
const shard = shardOf(scheduled.taskId);
|
|
109
|
+
await this.redisCli.zadd(zsetKey(shard), scheduledAt, taskData);
|
|
108
110
|
this.logger.debug({
|
|
109
111
|
taskId: scheduled.taskId,
|
|
110
112
|
scheduledAt: scheduled.scheduledAt,
|
|
@@ -124,7 +126,7 @@ async function executeSchedulerPoll(redis, outboundProducers, logger, db) {
|
|
|
124
126
|
const perShardLimit = 100;
|
|
125
127
|
const pipeline = redis.pipeline();
|
|
126
128
|
for (let i = 0; i < 16; i++) {
|
|
127
|
-
const shardKey =
|
|
129
|
+
const shardKey = zsetKey(i);
|
|
128
130
|
pipeline.schedulerPoll(shardKey, now, perShardLimit, visibilityTimeout);
|
|
129
131
|
}
|
|
130
132
|
const perShard = (await pipeline.exec())?.map((res) => res[0] ? [] : res[1] ?? []) ?? [];
|
|
@@ -161,14 +163,13 @@ async function executeSchedulerPoll(redis, outboundProducers, logger, db) {
|
|
|
161
163
|
for (let i = 0; i < parsedTasks.length; i++) {
|
|
162
164
|
const { taskStr, taskId, traceId } = parsedTasks[i];
|
|
163
165
|
if (released.has(taskId)) {
|
|
164
|
-
cleanupPipeline.zrem(
|
|
166
|
+
cleanupPipeline.zrem(zsetKey(shardOf(taskId)), taskStr);
|
|
165
167
|
continue;
|
|
166
168
|
}
|
|
167
169
|
const payload = payloadMap.get(taskId);
|
|
168
170
|
if (!payload) {
|
|
169
171
|
logger.warn({ taskId }, "scheduled payload not found in Postgres — skipping release");
|
|
170
|
-
|
|
171
|
-
cleanupPipeline.zrem(`notif:scheduled:zset:${shard}`, taskStr);
|
|
172
|
+
cleanupPipeline.zrem(zsetKey(shardOf(taskId)), taskStr);
|
|
172
173
|
continue;
|
|
173
174
|
}
|
|
174
175
|
const dispatchPayload = payload;
|
|
@@ -186,15 +187,13 @@ async function executeSchedulerPoll(redis, outboundProducers, logger, db) {
|
|
|
186
187
|
});
|
|
187
188
|
released.add(taskId);
|
|
188
189
|
dbCleanupIds.push(taskId);
|
|
189
|
-
|
|
190
|
-
cleanupPipeline.zrem(`notif:scheduled:zset:${shard}`, taskStr);
|
|
190
|
+
cleanupPipeline.zrem(zsetKey(shardOf(taskId)), taskStr);
|
|
191
191
|
continue;
|
|
192
192
|
}
|
|
193
193
|
batchedEvents[getPriorityBucket(dispatchPayload.priority)].push(buildStreamEvent("notification.dispatched", dispatchPayload, "scheduler", traceId));
|
|
194
194
|
released.add(taskId);
|
|
195
195
|
dbCleanupIds.push(taskId);
|
|
196
|
-
|
|
197
|
-
cleanupPipeline.zrem(`notif:scheduled:zset:${shard}`, taskStr);
|
|
196
|
+
cleanupPipeline.zrem(zsetKey(shardOf(taskId)), taskStr);
|
|
198
197
|
}
|
|
199
198
|
for (const p of Object.keys(batchedEvents)) if (batchedEvents[p].length > 0) await (outboundProducers[p] ?? outboundProducers["normal"]).publishBatch(batchedEvents[p]);
|
|
200
199
|
if (dbCleanupIds.length > 0) try {
|
|
@@ -247,8 +246,7 @@ async function rebuildScheduledQueue(redis, db, logger, pageSize = 1e3) {
|
|
|
247
246
|
taskId,
|
|
248
247
|
enrichedEventId: payload?.enrichedEventId
|
|
249
248
|
});
|
|
250
|
-
|
|
251
|
-
pipeline.zadd(`notif:scheduled:zset:${shard}`, "NX", Number.isNaN(sendAt) ? Date.now() : sendAt, member);
|
|
249
|
+
pipeline.zadd(zsetKey(shardOf(taskId)), "NX", Number.isNaN(sendAt) ? Date.now() : sendAt, member);
|
|
252
250
|
}
|
|
253
251
|
await pipeline.exec();
|
|
254
252
|
total += rows.length;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
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-BRatuWJS.mjs";
|
|
2
|
+
import { t as scheduleOrDispatch } from "./schedule-or-dispatch-C5qfxQCv.mjs";
|
|
3
|
+
import { a as uniqueConsumerId, i as shutdownWorker, n as createStreamConsumer, r as createWorkerRuntime, t as createPriorityProducers } from "./bootstrap-P63acBG9.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
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
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
|
|
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(
|
|
221
|
+
await subscriber.subscribe(PUBSUB_CHANNELS.TEMPLATE_INVALIDATED);
|
|
242
222
|
subscriber.on("message", (channel, message) => {
|
|
243
|
-
if (channel ===
|
|
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
|
}
|