mailery 0.15.0 → 0.16.0

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/dist/index.cjs CHANGED
@@ -6180,13 +6180,13 @@ function createAdminRouter(mailer, opts = {}) {
6180
6180
  req.actor = getActor(req);
6181
6181
  next();
6182
6182
  });
6183
- router.use("/api", apiRouter(mailer, opts));
6183
+ router.use("/api", createAdminApiRouter(mailer, opts));
6184
6184
  router.get(/.*/, (_req, res) => {
6185
6185
  res.sendFile(path__default.default.join(spaDir, "index.html"));
6186
6186
  });
6187
6187
  return router;
6188
6188
  }
6189
- function apiRouter(mailer, opts = {}) {
6189
+ function createAdminApiRouter(mailer, opts = {}) {
6190
6190
  const r = express.Router();
6191
6191
  const c = mailer.collections;
6192
6192
  const varsSchema = mailer.config.varsAdapter ? varsJsonSchema(mailer.config.varsAdapter) : null;
@@ -6383,7 +6383,11 @@ function apiRouter(mailer, opts = {}) {
6383
6383
  asyncHandler(async (req, res) => {
6384
6384
  const before = await c.flows.findOne({ slug: req.params.slug });
6385
6385
  if (!before) return res.status(404).json({ error: "not_found" });
6386
- await c.flows.updateOne({ _id: before._id }, { $set: { enabled: true, updatedAt: /* @__PURE__ */ new Date() } });
6386
+ const now = /* @__PURE__ */ new Date();
6387
+ await c.flows.updateOne(
6388
+ { _id: before._id },
6389
+ { $set: { enabled: true, updatedAt: now, ...before.lastTriggerScanAt ? {} : { lastTriggerScanAt: now } } }
6390
+ );
6387
6391
  await mailer.audit({
6388
6392
  actor: req.actor,
6389
6393
  action: "flow.resume",
@@ -6964,6 +6968,7 @@ function apiRouter(mailer, opts = {}) {
6964
6968
  if (!Array.isArray(draftSteps) || draftSteps.length === 0) {
6965
6969
  return res.status(400).json({ error: "empty_flow", message: "flow has no steps to publish" });
6966
6970
  }
6971
+ const enable = req.body?.enable !== false;
6967
6972
  const nextVersion = (flow.version ?? 0) + 1;
6968
6973
  const now = /* @__PURE__ */ new Date();
6969
6974
  await c.flowVersions.insertOne({
@@ -6980,11 +6985,14 @@ function apiRouter(mailer, opts = {}) {
6980
6985
  $set: {
6981
6986
  steps: draftSteps,
6982
6987
  version: nextVersion,
6983
- enabled: true,
6988
+ enabled: enable ? true : flow.enabled,
6984
6989
  draft: null,
6985
6990
  publishedAt: now,
6986
6991
  publishedBy: req.actor,
6987
- updatedAt: now
6992
+ updatedAt: now,
6993
+ // First enable: stamp the trigger watermark so the scan does not
6994
+ // replay every event since the flow document was created.
6995
+ ...enable && !flow.lastTriggerScanAt ? { lastTriggerScanAt: now } : {}
6988
6996
  }
6989
6997
  }
6990
6998
  );
@@ -6992,9 +7000,9 @@ function apiRouter(mailer, opts = {}) {
6992
7000
  actor: req.actor,
6993
7001
  action: "flow.publish",
6994
7002
  resource: { collection: "mailer_flows", id: flow._id, slug: flow.slug },
6995
- diffSummary: `Published v${nextVersion}`
7003
+ diffSummary: `Published v${nextVersion}${enable ? "" : " (left disabled)"}`
6996
7004
  });
6997
- return res.json({ ok: true, version: nextVersion });
7005
+ return res.json({ ok: true, version: nextVersion, enabled: enable ? true : flow.enabled });
6998
7006
  })
6999
7007
  );
7000
7008
  r.delete(
@@ -7865,7 +7873,1345 @@ function wrap(logger, handler) {
7865
7873
  };
7866
7874
  }
7867
7875
 
7868
- // src/server/api/dmarc-inbound.ts
7876
+ // src/server/api/agent.ts
7877
+ init_vars();
7878
+
7879
+ // src/server/runner/arm.ts
7880
+ var FlowOperationError = class extends Error {
7881
+ constructor(code, message, status = 400) {
7882
+ super(message);
7883
+ this.code = code;
7884
+ this.status = status;
7885
+ this.name = "FlowOperationError";
7886
+ }
7887
+ code;
7888
+ status;
7889
+ };
7890
+ async function stampWatermarkIfNull(collections, flow, now = /* @__PURE__ */ new Date()) {
7891
+ if (flow.lastTriggerScanAt) return flow.lastTriggerScanAt;
7892
+ await collections.flows.updateOne(
7893
+ { _id: flow._id, lastTriggerScanAt: null },
7894
+ { $set: { lastTriggerScanAt: now, updatedAt: now } }
7895
+ );
7896
+ return now;
7897
+ }
7898
+ async function armFlow(mailer, slug, opts) {
7899
+ const c = mailer.collections;
7900
+ const flow = await c.flows.findOne({ slug });
7901
+ if (!flow) throw new FlowOperationError("not_found", `no flow with slug "${slug}"`, 404);
7902
+ if (!Array.isArray(flow.steps) || flow.steps.length === 0) {
7903
+ throw new FlowOperationError(
7904
+ "no_live_steps",
7905
+ `flow "${slug}" (v${flow.version}) has no published steps \u2014 publish it first; an empty flow completes every run instantly`,
7906
+ 409
7907
+ );
7908
+ }
7909
+ const eventName = flow.trigger?.eventName ?? null;
7910
+ const now = /* @__PURE__ */ new Date();
7911
+ const watermark = opts.since ?? now;
7912
+ if (flow.enabled) {
7913
+ return {
7914
+ slug,
7915
+ version: flow.version,
7916
+ armed: false,
7917
+ alreadyEnabled: true,
7918
+ watermark: flow.lastTriggerScanAt ?? null,
7919
+ eventName,
7920
+ skippedEvents: 0,
7921
+ pendingEvents: 0
7922
+ };
7923
+ }
7924
+ const previous = flow.lastTriggerScanAt ?? flow.createdAt;
7925
+ const overlapFrom = new Date(watermark.getTime() - SCAN_OVERLAP_MS);
7926
+ const [skippedEvents, pendingEvents] = eventName ? await Promise.all([
7927
+ c.events.countDocuments({ name: eventName, createdAt: { $gt: previous, $lte: overlapFrom } }),
7928
+ c.events.countDocuments({ name: eventName, createdAt: { $gt: overlapFrom } })
7929
+ ]) : [0, 0];
7930
+ const res = await c.flows.updateOne(
7931
+ { _id: flow._id, enabled: false },
7932
+ { $set: { enabled: true, lastTriggerScanAt: watermark, updatedAt: now } }
7933
+ );
7934
+ if (res.modifiedCount === 0) {
7935
+ const again = await c.flows.findOne({ _id: flow._id });
7936
+ return {
7937
+ slug,
7938
+ version: flow.version,
7939
+ armed: false,
7940
+ alreadyEnabled: !!again?.enabled,
7941
+ watermark: again?.lastTriggerScanAt ?? null,
7942
+ eventName,
7943
+ skippedEvents: 0,
7944
+ pendingEvents: 0
7945
+ };
7946
+ }
7947
+ await mailer.audit({
7948
+ actor: opts.actor,
7949
+ action: "flow.arm",
7950
+ resource: { collection: "mailer_flows", id: flow._id, slug },
7951
+ diffSummary: `Enabled v${flow.version} with lastTriggerScanAt=${watermark.toISOString()} (skipped ${skippedEvents} earlier ${eventName ?? "trigger"} event(s), ${pendingEvents} pending)`
7952
+ });
7953
+ return {
7954
+ slug,
7955
+ version: flow.version,
7956
+ armed: true,
7957
+ alreadyEnabled: false,
7958
+ watermark,
7959
+ eventName,
7960
+ skippedEvents,
7961
+ pendingEvents
7962
+ };
7963
+ }
7964
+ async function disarmFlow(mailer, slug, actor) {
7965
+ const c = mailer.collections;
7966
+ const flow = await c.flows.findOne({ slug });
7967
+ if (!flow) throw new FlowOperationError("not_found", `no flow with slug "${slug}"`, 404);
7968
+ if (!flow.enabled) return { slug, disarmed: false };
7969
+ await c.flows.updateOne({ _id: flow._id }, { $set: { enabled: false, updatedAt: /* @__PURE__ */ new Date() } });
7970
+ await mailer.audit({
7971
+ actor,
7972
+ action: "flow.pause",
7973
+ resource: { collection: "mailer_flows", id: flow._id, slug },
7974
+ diffSummary: "Disarmed (enabled: false); in-flight runs continue"
7975
+ });
7976
+ return { slug, disarmed: true };
7977
+ }
7978
+ function isCanaryGate(step) {
7979
+ const s = step;
7980
+ return !!s && s.type === "condition" && s.canaryGate === true;
7981
+ }
7982
+ function gateStep(tag) {
7983
+ return { type: "condition", test: { hasTag: tag }, ifFalse: "exit", canaryGate: true };
7984
+ }
7985
+ async function publishVersion(mailer, flow, steps, actor, summary) {
7986
+ const c = mailer.collections;
7987
+ const nextVersion = (flow.version ?? 0) + 1;
7988
+ const now = /* @__PURE__ */ new Date();
7989
+ await c.flowVersions.insertOne({
7990
+ flowId: flow._id,
7991
+ version: nextVersion,
7992
+ steps,
7993
+ trigger: flow.trigger,
7994
+ publishedAt: now,
7995
+ publishedBy: actor
7996
+ });
7997
+ await c.flows.updateOne(
7998
+ { _id: flow._id },
7999
+ { $set: { steps, version: nextVersion, draft: null, publishedAt: now, publishedBy: actor, updatedAt: now } }
8000
+ );
8001
+ await mailer.audit({
8002
+ actor,
8003
+ action: "flow.publish",
8004
+ resource: { collection: "mailer_flows", id: flow._id, slug: flow.slug },
8005
+ diffSummary: `Published v${nextVersion}: ${summary}`
8006
+ });
8007
+ return { version: nextVersion };
8008
+ }
8009
+ async function gateFlow(mailer, slug, opts) {
8010
+ const tag = String(opts.tag ?? "").trim();
8011
+ if (!tag) throw new FlowOperationError("tag_required", "a canary tag is required");
8012
+ const flow = await mailer.collections.flows.findOne({ slug });
8013
+ if (!flow) throw new FlowOperationError("not_found", `no flow with slug "${slug}"`, 404);
8014
+ const live = Array.isArray(flow.steps) ? flow.steps : [];
8015
+ if (live.length === 0) {
8016
+ throw new FlowOperationError("no_live_steps", `flow "${slug}" has no published steps to gate`, 409);
8017
+ }
8018
+ if (isCanaryGate(live[0])) {
8019
+ throw new FlowOperationError(
8020
+ "already_gated",
8021
+ `flow "${slug}" v${flow.version} is already gated on "${live[0].test.hasTag}" \u2014 ungate first`,
8022
+ 409
8023
+ );
8024
+ }
8025
+ await mailer.collections.flowVersions.updateOne(
8026
+ { flowId: flow._id, version: flow.version },
8027
+ {
8028
+ $setOnInsert: {
8029
+ flowId: flow._id,
8030
+ version: flow.version,
8031
+ steps: live,
8032
+ trigger: flow.trigger,
8033
+ publishedAt: flow.publishedAt ?? flow.updatedAt ?? /* @__PURE__ */ new Date(),
8034
+ publishedBy: flow.publishedBy ?? "unknown"
8035
+ }
8036
+ },
8037
+ { upsert: true }
8038
+ );
8039
+ const { version } = await publishVersion(
8040
+ mailer,
8041
+ flow,
8042
+ [gateStep(tag), ...live],
8043
+ opts.actor,
8044
+ `canary gate on tag "${tag}"`
8045
+ );
8046
+ return { slug, version, tag, enabled: flow.enabled };
8047
+ }
8048
+ async function ungateFlow(mailer, slug, opts) {
8049
+ const c = mailer.collections;
8050
+ const flow = await c.flows.findOne({ slug });
8051
+ if (!flow) throw new FlowOperationError("not_found", `no flow with slug "${slug}"`, 404);
8052
+ const live = Array.isArray(flow.steps) ? flow.steps : [];
8053
+ if (!isCanaryGate(live[0])) {
8054
+ throw new FlowOperationError("not_gated", `flow "${slug}" v${flow.version} is not gated`, 409);
8055
+ }
8056
+ const versions = await c.flowVersions.find({ flowId: flow._id }).sort({ version: -1 }).toArray();
8057
+ const clean = versions.find((v) => Array.isArray(v.steps) && v.steps.length > 0 && !isCanaryGate(v.steps[0]));
8058
+ if (!clean) {
8059
+ throw new FlowOperationError(
8060
+ "no_ungated_version",
8061
+ `flow "${slug}" has no ungated version in mailer_flow_versions to restore`,
8062
+ 409
8063
+ );
8064
+ }
8065
+ const { version } = await publishVersion(
8066
+ mailer,
8067
+ flow,
8068
+ clean.steps,
8069
+ opts.actor,
8070
+ `restored steps of v${clean.version} (canary gate removed)`
8071
+ );
8072
+ return { slug, version, restoredFrom: clean.version, enabled: flow.enabled };
8073
+ }
8074
+ var MAX_STEPS = 1e3;
8075
+ async function simulateFlow(flow, contact, ctx, opts = {}) {
8076
+ const enteredAt = opts.at ?? /* @__PURE__ */ new Date();
8077
+ const steps = opts.steps ?? flow.steps ?? [];
8078
+ const eventName = flow.trigger?.eventName ?? "simulated";
8079
+ const eventProperties = opts.eventProperties ?? {};
8080
+ const reasons = [];
8081
+ if (!flow.enabled) reasons.push("flow is disabled (enabled: false)");
8082
+ const sub = await ctx.collections.subscriptions.findOne({ externalId: contact.externalId });
8083
+ if (!sub) reasons.push("contact has no subscription row \u2014 the trigger scan requires one");
8084
+ else if (sub.status !== "subscribed") reasons.push(`subscription status is "${sub.status}", not "subscribed"`);
8085
+ if (flow.trigger?.once) {
8086
+ const existing = await ctx.collections.flowRuns.findOne(
8087
+ { externalId: contact.externalId, flowId: flow._id },
8088
+ { projection: { _id: 1, status: 1 } }
8089
+ );
8090
+ if (existing) reasons.push(`trigger.once is true and the contact already has a run (${existing.status})`);
8091
+ }
8092
+ if (steps.length === 0) reasons.push("flow has no live steps \u2014 a run would complete immediately");
8093
+ const run = {
8094
+ _id: new mongodb.ObjectId(),
8095
+ externalId: contact.externalId,
8096
+ flowId: flow._id,
8097
+ flowSlug: flow.slug,
8098
+ flowVersion: flow.version,
8099
+ emailAtEntry: contact.email,
8100
+ triggerEvent: { name: eventName, properties: eventProperties, occurredAt: enteredAt },
8101
+ triggerDedupeKey: null,
8102
+ enteredAt,
8103
+ status: "active",
8104
+ currentStepIndex: 0,
8105
+ currentBranchPath: [],
8106
+ nextActionAt: enteredAt,
8107
+ attemptsForCurrentStep: 0,
8108
+ history: [],
8109
+ exitedAt: null,
8110
+ exitReason: null,
8111
+ createdAt: enteredAt,
8112
+ updatedAt: enteredAt
8113
+ };
8114
+ const path3 = [];
8115
+ const sends = [];
8116
+ let list = steps;
8117
+ let index = 0;
8118
+ let branchPath = [];
8119
+ let t = enteredAt;
8120
+ let terminal = null;
8121
+ const record = (type, outcome, detail) => {
8122
+ path3.push({ at: t, stepIndex: index, branchPath: [...branchPath], type, outcome, ...detail ? { detail } : {} });
8123
+ };
8124
+ const predicateCtx = () => ({
8125
+ contact,
8126
+ run: { ...run, currentStepIndex: index, currentBranchPath: branchPath, nextActionAt: t },
8127
+ collections: ctx.collections,
8128
+ now: t,
8129
+ botFilter: ctx.config.botFilter
8130
+ });
8131
+ for (let guard = 0; guard < MAX_STEPS && !terminal; guard += 1) {
8132
+ const step = list[index];
8133
+ if (!step) {
8134
+ terminal = { kind: "completed", reason: "sequence_complete", at: t };
8135
+ break;
8136
+ }
8137
+ switch (step.type) {
8138
+ case "wait": {
8139
+ const ms = unitToMs2(step.value, step.unit);
8140
+ record("wait", "waited", { value: step.value, unit: step.unit, until: new Date(t.getTime() + ms) });
8141
+ t = new Date(t.getTime() + ms);
8142
+ index += 1;
8143
+ break;
8144
+ }
8145
+ case "condition": {
8146
+ const result = await evaluatePredicate(step.test, predicateCtx());
8147
+ if (result) {
8148
+ record("condition", "passed", { test: step.test, result });
8149
+ index += 1;
8150
+ } else if (step.ifFalse === "continue") {
8151
+ record("condition", "skipped_next", { test: step.test, result });
8152
+ index += 2;
8153
+ } else {
8154
+ record("condition", "exited", { test: step.test, result });
8155
+ terminal = { kind: "exited", reason: "condition_false", at: t };
8156
+ }
8157
+ break;
8158
+ }
8159
+ case "branch": {
8160
+ const result = await evaluatePredicate(step.test, predicateCtx());
8161
+ record("branch", result ? "branch_true" : "branch_false", { test: step.test, result });
8162
+ branchPath = [...branchPath, index, result ? "true" : "false", 0];
8163
+ list = result ? step.ifTrueSteps : step.ifFalseSteps;
8164
+ index = 0;
8165
+ break;
8166
+ }
8167
+ case "send": {
8168
+ let at = t;
8169
+ if (step.delivery) {
8170
+ at = computeDeliveryTime(t, step.delivery, contact.timezone);
8171
+ }
8172
+ if (at.getTime() > t.getTime() + 3e4) {
8173
+ record("send", "send_deferred", { templateSlug: step.templateSlug, delivery: step.delivery, until: at });
8174
+ t = at;
8175
+ }
8176
+ record("send", "send", { templateSlug: step.templateSlug });
8177
+ sends.push({ templateSlug: step.templateSlug, at: t, stepIndex: index, branchPath: [...branchPath] });
8178
+ index += 1;
8179
+ break;
8180
+ }
8181
+ case "tag":
8182
+ record("tag", "tagged", { addTags: step.addTags ?? [], removeTags: step.removeTags ?? [] });
8183
+ index += 1;
8184
+ break;
8185
+ case "fire_event":
8186
+ record("fire_event", "event_fired", { eventName: step.eventName });
8187
+ index += 1;
8188
+ break;
8189
+ case "webhook":
8190
+ record("webhook", "webhook", { url: step.url, method: step.method ?? "POST", note: "not called in simulation" });
8191
+ index += 1;
8192
+ break;
8193
+ case "exit":
8194
+ record("exit", "exited", { reason: step.reason ?? "exit_step" });
8195
+ terminal = { kind: "exited", reason: step.reason ?? "exit_step", at: t };
8196
+ break;
8197
+ }
8198
+ }
8199
+ if (!terminal) terminal = { kind: "truncated", reason: `stopped after ${MAX_STEPS} steps`, at: t };
8200
+ return {
8201
+ flow: { slug: flow.slug, version: flow.version, enabled: flow.enabled },
8202
+ contact: { externalId: contact.externalId, email: contact.email },
8203
+ enteredAt,
8204
+ wouldEnter: { ok: reasons.length === 0, reasons },
8205
+ path: path3,
8206
+ sends,
8207
+ terminal,
8208
+ durationMs: terminal.at.getTime() - enteredAt.getTime()
8209
+ };
8210
+ }
8211
+ function unitToMs2(value, unit) {
8212
+ const m = 6e4;
8213
+ switch (unit) {
8214
+ case "minutes":
8215
+ return value * m;
8216
+ case "hours":
8217
+ return value * 60 * m;
8218
+ case "days":
8219
+ return value * 24 * 60 * m;
8220
+ case "weeks":
8221
+ return value * 7 * 24 * 60 * m;
8222
+ }
8223
+ }
8224
+
8225
+ // src/server/api/agent.ts
8226
+ var VERSION = "0.16.0" ;
8227
+ var MIN_AGENT_TOKEN_LENGTH = 24;
8228
+ function createAgentRouter(mailer, opts) {
8229
+ if (!opts || !Array.isArray(opts.tokens) || opts.tokens.length === 0) {
8230
+ throw new Error("createAgentRouter: at least one bearer token is required \u2014 the agent API is never open");
8231
+ }
8232
+ for (const t of opts.tokens) {
8233
+ if (typeof t?.token !== "string" || t.token.length < MIN_AGENT_TOKEN_LENGTH) {
8234
+ throw new Error(
8235
+ `createAgentRouter: every token must be at least ${MIN_AGENT_TOKEN_LENGTH} characters (got ${t?.token?.length ?? 0})`
8236
+ );
8237
+ }
8238
+ if (typeof t.actor !== "string" || !t.actor.trim()) {
8239
+ throw new Error('createAgentRouter: every token needs an actor label, e.g. "agent:claude"');
8240
+ }
8241
+ }
8242
+ const logger = opts.logger ?? consoleRouteLogger;
8243
+ const isTestContact = testContactMatcher(opts.testContacts);
8244
+ const c = mailer.collections;
8245
+ const varsSchema = mailer.config.varsAdapter ? varsJsonSchema(mailer.config.varsAdapter) : null;
8246
+ const router = express.Router();
8247
+ router.use(express__default.default.json({ limit: "1mb" }));
8248
+ router.use(bearerAuth(opts.tokens));
8249
+ router.use("/api", createAdminApiRouter(mailer, { mailTesterClient: opts.mailTesterClient }));
8250
+ const actorOf = (req) => String(req.actor);
8251
+ function guardTestContact(res, contact) {
8252
+ if (!isTestContact) {
8253
+ res.status(403).json({
8254
+ error: "test_contacts_not_configured",
8255
+ message: "this route only acts on test contacts, and the router was constructed without a testContacts pattern"
8256
+ });
8257
+ return false;
8258
+ }
8259
+ if (!isTestContact(contact.email)) {
8260
+ res.status(403).json({
8261
+ error: "not_a_test_contact",
8262
+ message: `${contact.email} does not match the testContacts pattern`,
8263
+ externalId: contact.externalId
8264
+ });
8265
+ return false;
8266
+ }
8267
+ return true;
8268
+ }
8269
+ async function loadContact(res, externalId) {
8270
+ const contact = await mailer.adapter.getById(externalId);
8271
+ if (!contact) res.status(404).json({ error: "contact_not_found", externalId });
8272
+ return contact;
8273
+ }
8274
+ async function loadTemplate(res, slug) {
8275
+ const tpl = await c.templates.findOne({ slug });
8276
+ if (!tpl) res.status(404).json({ error: "template_not_found", slug });
8277
+ return tpl;
8278
+ }
8279
+ router.get("/", (req, res) => {
8280
+ res.json({
8281
+ service: "mailery-agent",
8282
+ version: VERSION,
8283
+ actor: actorOf(req),
8284
+ testContactsConfigured: !!isTestContact,
8285
+ docs: "https://jeffjassky.github.io/mailery/reference/agent-api",
8286
+ endpoints: ENDPOINTS
8287
+ });
8288
+ });
8289
+ router.post(
8290
+ "/templates/:slug/verify",
8291
+ wrap2(async (req, res) => {
8292
+ const tpl = await loadTemplate(res, String(req.params.slug));
8293
+ if (!tpl) return;
8294
+ const contact = await contactForRender(req, res);
8295
+ if (!contact) return;
8296
+ const report = await verifyTemplate(mailer, tpl, contact, {
8297
+ eventProperties: objectOrUndefined(req.body?.eventProperties),
8298
+ vars: objectOrUndefined(req.body?.vars),
8299
+ includeRendered: req.body?.includeRendered === true,
8300
+ varsSchema
8301
+ });
8302
+ res.status(200).json(report);
8303
+ })
8304
+ );
8305
+ router.post(
8306
+ "/templates/verify-all",
8307
+ wrap2(async (req, res) => {
8308
+ const slugs = Array.isArray(req.body?.slugs) ? req.body.slugs.map(String) : null;
8309
+ const contactIds = Array.isArray(req.body?.contactIds) ? req.body.contactIds.map(String) : [];
8310
+ if (contactIds.length === 0) {
8311
+ return res.status(400).json({ error: "validation_failed", message: "contactIds (non-empty array) is required" });
8312
+ }
8313
+ const templates = await c.templates.find(slugs ? { slug: { $in: slugs } } : {}).sort({ slug: 1 }).toArray();
8314
+ const contacts = [];
8315
+ for (const id of contactIds) {
8316
+ const found = await mailer.adapter.getById(id);
8317
+ if (!found) return res.status(404).json({ error: "contact_not_found", externalId: id });
8318
+ contacts.push(found);
8319
+ }
8320
+ const results = [];
8321
+ for (const tpl of templates) {
8322
+ for (const contact of contacts) {
8323
+ const report = await verifyTemplate(mailer, tpl, contact, {
8324
+ eventProperties: objectOrUndefined(req.body?.eventProperties),
8325
+ includeRendered: false,
8326
+ varsSchema
8327
+ });
8328
+ results.push({
8329
+ slug: tpl.slug,
8330
+ contactId: contact.externalId,
8331
+ ok: report.ok,
8332
+ failed: report.checks.filter((k) => k.status === "fail").map((k) => k.id),
8333
+ warned: report.checks.filter((k) => k.status === "warn").map((k) => k.id)
8334
+ });
8335
+ }
8336
+ }
8337
+ const failing = results.filter((r) => !r.ok);
8338
+ res.json({
8339
+ ok: failing.length === 0,
8340
+ templates: templates.length,
8341
+ contacts: contacts.length,
8342
+ verified: results.length,
8343
+ failing: failing.length,
8344
+ results
8345
+ });
8346
+ })
8347
+ );
8348
+ router.post(
8349
+ "/templates/:slug/render",
8350
+ wrap2(async (req, res) => {
8351
+ const tpl = await loadTemplate(res, String(req.params.slug));
8352
+ if (!tpl) return;
8353
+ const contact = await contactForRender(req, res);
8354
+ if (!contact) return;
8355
+ const out = await renderForContact(mailer, tpl, contact, {
8356
+ reason: "preview",
8357
+ eventProperties: objectOrUndefined(req.body?.eventProperties),
8358
+ vars: objectOrUndefined(req.body?.vars)
8359
+ });
8360
+ res.json({
8361
+ template: { slug: tpl.slug, kind: tpl.kind },
8362
+ contact: { externalId: contact.externalId, email: contact.email },
8363
+ subject: out.rendered.subject,
8364
+ preheader: out.rendered.preheader,
8365
+ fromName: out.rendered.fromName,
8366
+ fromEmail: out.rendered.fromEmail,
8367
+ replyTo: out.rendered.replyTo,
8368
+ html: out.rendered.html,
8369
+ plainText: out.rendered.plainText,
8370
+ resolvedVars: out.resolved,
8371
+ unsubscribeUrl: out.unsubscribeUrl
8372
+ });
8373
+ })
8374
+ );
8375
+ router.post(
8376
+ "/templates/:slug/send",
8377
+ wrap2(async (req, res) => {
8378
+ const tpl = await loadTemplate(res, String(req.params.slug));
8379
+ if (!tpl) return;
8380
+ const contactId = typeof req.body?.contactId === "string" ? req.body.contactId : "";
8381
+ if (!contactId) return res.status(400).json({ error: "validation_failed", message: "contactId is required" });
8382
+ const contact = await loadContact(res, contactId);
8383
+ if (!contact) return;
8384
+ if (!guardTestContact(res, contact)) return;
8385
+ if (!tpl.body?.html && !tpl.body?.mjml) {
8386
+ return res.status(409).json({ error: "not_published", message: "template has no published body" });
8387
+ }
8388
+ const dedupeKey = typeof req.body?.dedupeKey === "string" && req.body.dedupeKey ? String(req.body.dedupeKey) : `agent:${crypto2__default.default.randomUUID()}`;
8389
+ const { sendId } = await mailer.sendOneOff({
8390
+ templateSlug: tpl.slug,
8391
+ externalId: contact.externalId,
8392
+ dedupeKey,
8393
+ vars: objectOrUndefined(req.body?.vars)
8394
+ });
8395
+ const dispatchNow = req.body?.dispatch !== "queue";
8396
+ if (dispatchNow) {
8397
+ await dispatchSend(new mongodb.ObjectId(sendId), mailer.getRunnerContext());
8398
+ }
8399
+ const send = await c.sends.findOne({ _id: new mongodb.ObjectId(sendId) });
8400
+ await mailer.audit({
8401
+ actor: actorOf(req),
8402
+ action: "agent.send",
8403
+ resource: { collection: "mailer_sends", id: new mongodb.ObjectId(sendId), slug: tpl.slug },
8404
+ diffSummary: `to=${contact.email} dispatch=${dispatchNow ? "now" : "queue"} dedupeKey=${dedupeKey}`
8405
+ });
8406
+ res.status(201).json({ sendId, dedupeKey, dispatched: dispatchNow, send: send ? sendSummary(send) : null });
8407
+ })
8408
+ );
8409
+ router.get(
8410
+ "/sends/:id/wait",
8411
+ wrap2(async (req, res) => {
8412
+ const id = String(req.params.id);
8413
+ if (!mongodb.ObjectId.isValid(id)) return res.status(400).json({ error: "bad_id" });
8414
+ const target = String(req.query.status ?? "delivered");
8415
+ if (!WAIT_TARGETS.has(target)) {
8416
+ return res.status(400).json({ error: "validation_failed", message: `status must be one of ${[...WAIT_TARGETS].join(", ")}` });
8417
+ }
8418
+ const timeoutMs = Math.max(0, Math.min(Number(req.query.timeoutMs ?? 3e4) || 0, 55e3));
8419
+ const started = Date.now();
8420
+ let send = null;
8421
+ let reached = false;
8422
+ for (; ; ) {
8423
+ send = await c.sends.findOne({ _id: new mongodb.ObjectId(id) });
8424
+ if (!send) return res.status(404).json({ error: "not_found" });
8425
+ reached = waitTargetReached(send, target);
8426
+ if (reached || Date.now() - started >= timeoutMs) break;
8427
+ await sleep2(1e3);
8428
+ }
8429
+ const webhookEvents = send.providerMessageId ? await c.webhookEvents.find({ providerMessageId: send.providerMessageId }).sort({ receivedAt: 1 }).limit(100).toArray() : [];
8430
+ res.json({ reached, target, waitedMs: Date.now() - started, send: sendSummary(send), webhookEvents });
8431
+ })
8432
+ );
8433
+ router.post(
8434
+ "/sends/:id/dispatch",
8435
+ wrap2(async (req, res) => {
8436
+ const id = String(req.params.id);
8437
+ if (!mongodb.ObjectId.isValid(id)) return res.status(400).json({ error: "bad_id" });
8438
+ const send = await c.sends.findOne({ _id: new mongodb.ObjectId(id) });
8439
+ if (!send) return res.status(404).json({ error: "not_found" });
8440
+ const contact = await loadContact(res, send.externalId);
8441
+ if (!contact) return;
8442
+ if (!guardTestContact(res, contact)) return;
8443
+ await dispatchSend(send._id, mailer.getRunnerContext());
8444
+ const after = await c.sends.findOne({ _id: send._id });
8445
+ res.json({ send: after ? sendSummary(after) : null });
8446
+ })
8447
+ );
8448
+ router.post(
8449
+ "/flows/:slug/simulate",
8450
+ wrap2(async (req, res) => {
8451
+ const flow = await c.flows.findOne({ slug: String(req.params.slug) });
8452
+ if (!flow) return res.status(404).json({ error: "flow_not_found", slug: String(req.params.slug) });
8453
+ const contactId = typeof req.body?.contactId === "string" ? req.body.contactId : "";
8454
+ if (!contactId) return res.status(400).json({ error: "validation_failed", message: "contactId is required" });
8455
+ const contact = await loadContact(res, contactId);
8456
+ if (!contact) return;
8457
+ let at;
8458
+ if (req.body?.at) {
8459
+ at = new Date(String(req.body.at));
8460
+ if (Number.isNaN(at.getTime())) return res.status(400).json({ error: "validation_failed", message: "at must be an ISO date" });
8461
+ }
8462
+ let steps = void 0;
8463
+ if (req.body?.version !== void 0) {
8464
+ const v = Number(req.body.version);
8465
+ if (v !== flow.version) {
8466
+ const snap = await c.flowVersions.findOne({ flowId: flow._id, version: v });
8467
+ if (!snap) return res.status(404).json({ error: "version_not_found", version: v });
8468
+ steps = snap.steps;
8469
+ }
8470
+ }
8471
+ const result = await simulateFlow(flow, contact, mailer.getRunnerContext(), {
8472
+ at,
8473
+ eventProperties: objectOrUndefined(req.body?.eventProperties),
8474
+ steps
8475
+ });
8476
+ res.json(result);
8477
+ })
8478
+ );
8479
+ router.post(
8480
+ "/flows/:slug/arm",
8481
+ wrap2(async (req, res) => {
8482
+ if (req.body?.confirm !== true) {
8483
+ return res.status(400).json({
8484
+ error: "confirm_required",
8485
+ message: 'arming enables a flow for every future matching event; pass {"confirm": true}'
8486
+ });
8487
+ }
8488
+ let since;
8489
+ if (req.body?.since) {
8490
+ since = new Date(String(req.body.since));
8491
+ if (Number.isNaN(since.getTime())) return res.status(400).json({ error: "validation_failed", message: "since must be an ISO date" });
8492
+ }
8493
+ const result = await armFlow(mailer, String(req.params.slug), { actor: actorOf(req), since });
8494
+ res.json(result);
8495
+ })
8496
+ );
8497
+ router.post(
8498
+ "/flows/:slug/disarm",
8499
+ wrap2(async (req, res) => {
8500
+ res.json(await disarmFlow(mailer, String(req.params.slug), actorOf(req)));
8501
+ })
8502
+ );
8503
+ router.post(
8504
+ "/flows/:slug/gate",
8505
+ wrap2(async (req, res) => {
8506
+ const tag = typeof req.body?.tag === "string" ? req.body.tag : "";
8507
+ res.json(await gateFlow(mailer, String(req.params.slug), { tag, actor: actorOf(req) }));
8508
+ })
8509
+ );
8510
+ router.post(
8511
+ "/flows/:slug/ungate",
8512
+ wrap2(async (req, res) => {
8513
+ res.json(await ungateFlow(mailer, String(req.params.slug), { actor: actorOf(req) }));
8514
+ })
8515
+ );
8516
+ router.get(
8517
+ "/runs",
8518
+ wrap2(async (req, res) => {
8519
+ const filter = {};
8520
+ if (typeof req.query.externalId === "string") filter.externalId = req.query.externalId;
8521
+ if (typeof req.query.flowSlug === "string") filter.flowSlug = req.query.flowSlug;
8522
+ if (typeof req.query.status === "string") filter.status = req.query.status;
8523
+ const limit = Math.min(Math.max(Number(req.query.limit ?? 50) || 50, 1), 200);
8524
+ const runs = await c.flowRuns.find(filter).sort({ enteredAt: -1 }).limit(limit).toArray();
8525
+ res.json(runs.map(runSummary));
8526
+ })
8527
+ );
8528
+ router.get(
8529
+ "/runs/:id",
8530
+ wrap2(async (req, res) => {
8531
+ const id = String(req.params.id);
8532
+ if (!mongodb.ObjectId.isValid(id)) return res.status(400).json({ error: "bad_id" });
8533
+ const run = await c.flowRuns.findOne({ _id: new mongodb.ObjectId(id) });
8534
+ if (!run) return res.status(404).json({ error: "not_found" });
8535
+ const sends = await c.sends.find({ flowRunId: run._id }).sort({ queuedAt: 1 }).toArray();
8536
+ res.json({ run, sends: sends.map(sendSummary) });
8537
+ })
8538
+ );
8539
+ router.post(
8540
+ "/runs/:id/advance",
8541
+ wrap2(async (req, res) => {
8542
+ const id = String(req.params.id);
8543
+ if (!mongodb.ObjectId.isValid(id)) return res.status(400).json({ error: "bad_id" });
8544
+ const run = await c.flowRuns.findOne({ _id: new mongodb.ObjectId(id) });
8545
+ if (!run) return res.status(404).json({ error: "not_found" });
8546
+ const contact = await loadContact(res, run.externalId);
8547
+ if (!contact) return;
8548
+ if (!guardTestContact(res, contact)) return;
8549
+ if (run.status !== "active") {
8550
+ return res.status(409).json({ error: "run_not_active", status: run.status, exitReason: run.exitReason });
8551
+ }
8552
+ const steps = Math.min(Math.max(Number(req.body?.steps ?? 1) || 1, 1), 50);
8553
+ const dispatch = req.body?.dispatch !== false;
8554
+ const ctx = mailer.getRunnerContext();
8555
+ const startedAt = /* @__PURE__ */ new Date();
8556
+ const historyBefore = run.history.length;
8557
+ const actor = actorOf(req);
8558
+ for (let i = 0; i < steps; i += 1) {
8559
+ const advanced = await advanceOnce(run._id, ctx, actor, c);
8560
+ if (!advanced) break;
8561
+ }
8562
+ const after = await c.flowRuns.findOne({ _id: run._id });
8563
+ const newSends = await c.sends.find({ flowRunId: run._id, queuedAt: { $gte: startedAt } }).toArray();
8564
+ if (dispatch) {
8565
+ for (const s of newSends) {
8566
+ if (s.status === "queued") await dispatchSend(s._id, ctx);
8567
+ }
8568
+ }
8569
+ const sends = await c.sends.find({ flowRunId: run._id, queuedAt: { $gte: startedAt } }).toArray();
8570
+ await mailer.audit({
8571
+ actor,
8572
+ action: "agent.run.advance",
8573
+ resource: { collection: "mailer_flow_runs", id: run._id, slug: run.flowSlug },
8574
+ diffSummary: `advanced ${steps} step(s) for ${contact.email}; ${sends.length} send(s) created`
8575
+ });
8576
+ res.json({
8577
+ run: after ? runSummary(after) : null,
8578
+ historyAdded: after ? after.history.slice(historyBefore) : [],
8579
+ sends: sends.map(sendSummary)
8580
+ });
8581
+ })
8582
+ );
8583
+ router.post(
8584
+ "/runs/:id/cancel",
8585
+ wrap2(async (req, res) => {
8586
+ const id = String(req.params.id);
8587
+ if (!mongodb.ObjectId.isValid(id)) return res.status(400).json({ error: "bad_id" });
8588
+ const run = await c.flowRuns.findOne({ _id: new mongodb.ObjectId(id) });
8589
+ if (!run) return res.status(404).json({ error: "not_found" });
8590
+ if (run.status !== "active") return res.status(409).json({ error: "run_not_active", status: run.status });
8591
+ const actor = actorOf(req);
8592
+ await exitFlowRun(run, `aborted_by_host:${actor}`, mailer.getRunnerContext());
8593
+ const cancelled = await c.sends.updateMany(
8594
+ { flowRunId: run._id, status: "queued" },
8595
+ { $set: { status: "cancelled", errorMessage: `cancelled: aborted_by_host:${actor}`, updatedAt: /* @__PURE__ */ new Date() } }
8596
+ );
8597
+ await mailer.audit({
8598
+ actor,
8599
+ action: "agent.run.cancel",
8600
+ resource: { collection: "mailer_flow_runs", id: run._id, slug: run.flowSlug },
8601
+ diffSummary: `cancelled run for ${run.externalId}; ${cancelled.modifiedCount} queued send(s) cancelled`
8602
+ });
8603
+ const after = await c.flowRuns.findOne({ _id: run._id });
8604
+ res.json({ run: after ? runSummary(after) : null, cancelledSends: cancelled.modifiedCount });
8605
+ })
8606
+ );
8607
+ router.post(
8608
+ "/events",
8609
+ wrap2(async (req, res) => {
8610
+ const name = typeof req.body?.name === "string" ? req.body.name : "";
8611
+ const externalId = typeof req.body?.externalId === "string" ? req.body.externalId : "";
8612
+ if (!name || !externalId) {
8613
+ return res.status(400).json({ error: "validation_failed", message: "name and externalId are required" });
8614
+ }
8615
+ const contact = await loadContact(res, externalId);
8616
+ if (!contact) return;
8617
+ if (!guardTestContact(res, contact)) return;
8618
+ const dedupeKey = typeof req.body?.dedupeKey === "string" && req.body.dedupeKey ? req.body.dedupeKey : void 0;
8619
+ try {
8620
+ await mailer.fire(name, externalId, objectOrUndefined(req.body?.properties) ?? {}, dedupeKey);
8621
+ } catch (err) {
8622
+ return res.status(400).json({ error: "fire_failed", message: String(err?.message ?? err) });
8623
+ }
8624
+ const latest = await c.events.findOne({ externalId, name }, { sort: { createdAt: -1 } });
8625
+ await mailer.audit({
8626
+ actor: actorOf(req),
8627
+ action: "agent.event.fire",
8628
+ resource: { collection: "mailer_events", id: latest?._id },
8629
+ diffSummary: `${name} for ${contact.email}${dedupeKey ? ` key=${dedupeKey}` : ""}`
8630
+ });
8631
+ res.status(201).json({ ok: true, event: latest });
8632
+ })
8633
+ );
8634
+ router.get(
8635
+ "/contacts/by-email/:email",
8636
+ wrap2(async (req, res) => {
8637
+ const contact = await mailer.adapter.getByEmail(String(req.params.email).toLowerCase());
8638
+ if (!contact) return res.status(404).json({ error: "contact_not_found", email: req.params.email });
8639
+ res.json(await contactDetail(contact));
8640
+ })
8641
+ );
8642
+ router.get(
8643
+ "/contacts/:externalId",
8644
+ wrap2(async (req, res) => {
8645
+ const contact = await loadContact(res, String(req.params.externalId));
8646
+ if (!contact) return;
8647
+ res.json(await contactDetail(contact));
8648
+ })
8649
+ );
8650
+ router.get(
8651
+ "/contacts/:externalId/unsubscribe-url",
8652
+ wrap2(async (req, res) => {
8653
+ const contact = await loadContact(res, String(req.params.externalId));
8654
+ if (!contact) return;
8655
+ if (!guardTestContact(res, contact)) return;
8656
+ res.json({ contact: { externalId: contact.externalId, email: contact.email }, unsubscribeUrl: unsubscribeUrlFor(mailer, contact.email) });
8657
+ })
8658
+ );
8659
+ router.post(
8660
+ "/contacts/:externalId/subscribe",
8661
+ wrap2(async (req, res) => {
8662
+ const contact = await loadContact(res, String(req.params.externalId));
8663
+ if (!contact) return;
8664
+ if (!guardTestContact(res, contact)) return;
8665
+ await mailer.upsertSubscription({ externalId: contact.externalId, source: "agent" });
8666
+ const sub = await c.subscriptions.findOne({ externalId: contact.externalId });
8667
+ await mailer.audit({
8668
+ actor: actorOf(req),
8669
+ action: "agent.contact.subscribe",
8670
+ resource: { collection: "mailer_subscriptions", id: sub?._id },
8671
+ diffSummary: contact.email
8672
+ });
8673
+ res.json({ subscription: sub });
8674
+ })
8675
+ );
8676
+ router.post(
8677
+ "/contacts/:externalId/unsubscribe",
8678
+ wrap2(async (req, res) => {
8679
+ const contact = await loadContact(res, String(req.params.externalId));
8680
+ if (!contact) return;
8681
+ if (!guardTestContact(res, contact)) return;
8682
+ await mailer.unsubscribe(contact.email, { scope: "marketing", reason: "user_request", source: "agent" });
8683
+ const sub = await c.subscriptions.findOne({ externalId: contact.externalId });
8684
+ await mailer.audit({
8685
+ actor: actorOf(req),
8686
+ action: "agent.contact.unsubscribe",
8687
+ resource: { collection: "mailer_subscriptions", id: sub?._id },
8688
+ diffSummary: contact.email
8689
+ });
8690
+ res.json({ subscription: sub });
8691
+ })
8692
+ );
8693
+ router.post(
8694
+ "/contacts/:externalId/reset",
8695
+ wrap2(async (req, res) => {
8696
+ const contact = await loadContact(res, String(req.params.externalId));
8697
+ if (!contact) return;
8698
+ if (!guardTestContact(res, contact)) return;
8699
+ const b = req.body ?? {};
8700
+ const eventFilter = { externalId: contact.externalId };
8701
+ if (Array.isArray(b.events)) eventFilter.name = { $in: b.events.map(String) };
8702
+ const doRuns = b.runs !== false;
8703
+ const doSends = b.sends !== false;
8704
+ const doEvents = b.events !== false;
8705
+ const doSuppressions = b.suppressions !== false;
8706
+ const doSubscribe = b.subscribe !== false;
8707
+ const removed = { runs: 0, sends: 0, events: 0, suppressions: 0 };
8708
+ if (doRuns) removed.runs = (await c.flowRuns.deleteMany({ externalId: contact.externalId })).deletedCount;
8709
+ if (doSends) removed.sends = (await c.sends.deleteMany({ externalId: contact.externalId })).deletedCount;
8710
+ if (doEvents) removed.events = (await c.events.deleteMany(eventFilter)).deletedCount;
8711
+ if (doSuppressions) removed.suppressions = (await c.suppressions.deleteMany({ email: contact.email })).deletedCount;
8712
+ if (doSubscribe) await mailer.upsertSubscription({ externalId: contact.externalId, source: "agent-reset" });
8713
+ const subscription = await c.subscriptions.findOne({ externalId: contact.externalId });
8714
+ await mailer.audit({
8715
+ actor: actorOf(req),
8716
+ action: "agent.contact.reset",
8717
+ resource: { collection: "mailer_subscriptions", id: subscription?._id },
8718
+ diffSummary: `${contact.email}: removed ${removed.runs} run(s), ${removed.sends} send(s), ${removed.events} event(s), ${removed.suppressions} suppression(s)${doSubscribe ? "; resubscribed" : ""}`
8719
+ });
8720
+ res.json({ contact: { externalId: contact.externalId, email: contact.email }, removed, subscription });
8721
+ })
8722
+ );
8723
+ router.post(
8724
+ "/tick",
8725
+ wrap2(async (_req, res) => {
8726
+ const started = Date.now();
8727
+ await runTick(mailer.getRunnerContext());
8728
+ res.json({ ok: true, ms: Date.now() - started });
8729
+ })
8730
+ );
8731
+ router.get(
8732
+ "/webhooks/status",
8733
+ wrap2(async (_req, res) => {
8734
+ const dayAgo = new Date(Date.now() - 24 * 60 * 60 * 1e3);
8735
+ const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1e3);
8736
+ const [last, byType24h, total7d, unprocessed] = await Promise.all([
8737
+ c.webhookEvents.findOne({}, { sort: { receivedAt: -1 }, projection: { receivedAt: 1, provider: 1, normalizedType: 1 } }),
8738
+ c.webhookEvents.aggregate([{ $match: { receivedAt: { $gte: dayAgo } } }, { $group: { _id: "$normalizedType", n: { $sum: 1 } } }]).toArray(),
8739
+ c.webhookEvents.countDocuments({ receivedAt: { $gte: weekAgo } }),
8740
+ c.webhookEvents.countDocuments({ processed: false })
8741
+ ]);
8742
+ res.json({
8743
+ providers: Object.keys(mailer.providers),
8744
+ lastReceivedAt: last?.receivedAt ?? null,
8745
+ lastProvider: last?.provider ?? null,
8746
+ last24h: Object.fromEntries(byType24h.map((r) => [r._id, r.n])),
8747
+ last7d: total7d,
8748
+ unprocessed,
8749
+ ingestPath: `${mailer.config.publicUrl}/m/webhooks/<provider>`
8750
+ });
8751
+ })
8752
+ );
8753
+ router.get(
8754
+ "/status",
8755
+ wrap2(async (_req, res) => {
8756
+ const dayAgo = new Date(Date.now() - 24 * 60 * 60 * 1e3);
8757
+ const [flows, templates, subscribed, suppressions, activeRuns, sends24h, webhooks24h, lastWebhook, healthDocs, setup] = await Promise.all([
8758
+ c.flows.find({}, { projection: { slug: 1, enabled: 1, version: 1, lastTriggerScanAt: 1, steps: 1, trigger: 1 } }).sort({ slug: 1 }).toArray(),
8759
+ c.templates.find({}, { projection: { slug: 1, kind: 1, publishedAt: 1, "body.html": 1, fromEmail: 1 } }).sort({ slug: 1 }).toArray(),
8760
+ c.subscriptions.countDocuments({ status: "subscribed" }),
8761
+ c.suppressions.estimatedDocumentCount(),
8762
+ c.flowRuns.countDocuments({ status: "active" }),
8763
+ c.sends.aggregate([{ $match: { queuedAt: { $gte: dayAgo } } }, { $group: { _id: "$status", n: { $sum: 1 } } }]).toArray(),
8764
+ c.webhookEvents.countDocuments({ receivedAt: { $gte: dayAgo } }),
8765
+ c.webhookEvents.findOne({}, { sort: { receivedAt: -1 }, projection: { receivedAt: 1 } }),
8766
+ c.health.find({}).limit(500).toArray(),
8767
+ runSetupChecks(mailer)
8768
+ ]);
8769
+ const activeByFlow = await c.flowRuns.aggregate([{ $match: { status: "active" } }, { $group: { _id: "$flowSlug", n: { $sum: 1 } } }]).toArray();
8770
+ const activeMap = new Map(activeByFlow.map((r) => [r._id, r.n]));
8771
+ res.json({
8772
+ version: VERSION,
8773
+ now: /* @__PURE__ */ new Date(),
8774
+ testContactsConfigured: !!isTestContact,
8775
+ setup,
8776
+ health: { status: healthDocs.length ? effectiveOverallStatus(healthDocs) : null, aggregate: healthDocs.find((d) => d._id === HEALTH_AGG_ID) ?? null },
8777
+ flows: flows.map((f) => ({
8778
+ slug: f.slug,
8779
+ enabled: f.enabled,
8780
+ version: f.version,
8781
+ lastTriggerScanAt: f.lastTriggerScanAt ?? null,
8782
+ trigger: f.trigger,
8783
+ liveSteps: Array.isArray(f.steps) ? f.steps.length : 0,
8784
+ gated: Array.isArray(f.steps) && isCanaryGate(f.steps[0]) ? f.steps[0].test.hasTag : null,
8785
+ activeRuns: activeMap.get(f.slug) ?? 0
8786
+ })),
8787
+ templates: templates.map((t) => ({
8788
+ slug: t.slug,
8789
+ kind: t.kind,
8790
+ fromEmail: t.fromEmail,
8791
+ published: !!(t.body && t.body.html),
8792
+ publishedAt: t.publishedAt ?? null
8793
+ })),
8794
+ counts: {
8795
+ subscribed,
8796
+ suppressions,
8797
+ activeRuns,
8798
+ sendsLast24h: Object.fromEntries(sends24h.map((r) => [r._id, r.n])),
8799
+ webhookEventsLast24h: webhooks24h,
8800
+ lastWebhookAt: lastWebhook?.receivedAt ?? null
8801
+ }
8802
+ });
8803
+ })
8804
+ );
8805
+ router.use((req, res) => {
8806
+ res.status(404).json({ error: "not_found", message: `no agent route ${req.method} ${req.path}; GET / lists them` });
8807
+ });
8808
+ router.use((err, req, res, _next) => {
8809
+ if (err instanceof FlowOperationError) {
8810
+ return res.status(err.status).json({ error: err.code, message: err.message });
8811
+ }
8812
+ if (err?.name === "ZodError") {
8813
+ return res.status(400).json({ error: "validation_failed", issues: err.issues });
8814
+ }
8815
+ logger.error?.({ err: String(err?.message ?? err), path: req.path, method: req.method }, "mailery agent: request failed");
8816
+ if (res.headersSent) return;
8817
+ res.status(500).json({ error: "internal", message: String(err?.message ?? err) });
8818
+ });
8819
+ return router;
8820
+ async function contactForRender(req, res) {
8821
+ const contactId = typeof req.body?.contactId === "string" ? req.body.contactId : "";
8822
+ if (contactId) return loadContact(res, contactId);
8823
+ const sample = req.body?.sampleContact;
8824
+ if (sample && typeof sample === "object" && typeof sample.email === "string") {
8825
+ return {
8826
+ externalId: String(sample.externalId ?? "sample-contact"),
8827
+ email: sample.email,
8828
+ tags: Array.isArray(sample.tags) ? sample.tags.map(String) : [],
8829
+ fields: sample.fields && typeof sample.fields === "object" ? sample.fields : {},
8830
+ timezone: typeof sample.timezone === "string" ? sample.timezone : void 0
8831
+ };
8832
+ }
8833
+ res.status(400).json({ error: "validation_failed", message: "contactId (or a sampleContact with an email) is required" });
8834
+ return null;
8835
+ }
8836
+ async function contactDetail(contact) {
8837
+ const [subscription, recentEvents, recentSends, runs, suppressions] = await Promise.all([
8838
+ c.subscriptions.findOne({ externalId: contact.externalId }),
8839
+ c.events.find({ externalId: contact.externalId }).sort({ occurredAt: -1 }).limit(50).toArray(),
8840
+ c.sends.find({ externalId: contact.externalId }).sort({ queuedAt: -1 }).limit(50).toArray(),
8841
+ c.flowRuns.find({ externalId: contact.externalId }).sort({ enteredAt: -1 }).limit(50).toArray(),
8842
+ c.suppressions.find({ email: contact.email }).toArray()
8843
+ ]);
8844
+ return {
8845
+ contact,
8846
+ isTestContact: isTestContact ? isTestContact(contact.email) : null,
8847
+ subscription,
8848
+ suppressions,
8849
+ recentEvents,
8850
+ recentSends: recentSends.map(sendSummary),
8851
+ runs: runs.map(runSummary)
8852
+ };
8853
+ }
8854
+ }
8855
+ var PLACEHOLDER_RE = /\{\{[^{}]*\}\}|\{\{\{[^{}]*\}\}\}/g;
8856
+ var HREF_RE = /href\s*=\s*(?:"([^"]*)"|'([^']*)')/gi;
8857
+ var GMAIL_CLIP_BYTES = 102 * 1024;
8858
+ async function verifyTemplate(mailer, tpl, contact, opts = {}) {
8859
+ const checks = [];
8860
+ const push = (id, status, detail) => checks.push(detail === void 0 ? { id, status } : { id, status, detail });
8861
+ const base = {
8862
+ template: { slug: tpl.slug, kind: tpl.kind, name: tpl.name },
8863
+ contact: { externalId: contact.externalId, email: contact.email }
8864
+ };
8865
+ const finish = (rendered2, links2) => ({
8866
+ ok: checks.every((k) => k.status !== "fail"),
8867
+ ...base,
8868
+ checks,
8869
+ links: { total: links2.length, sample: links2.slice(0, 50) },
8870
+ rendered: rendered2 ? opts.includeRendered ? {
8871
+ subject: rendered2.subject,
8872
+ preheader: rendered2.preheader,
8873
+ html: rendered2.html,
8874
+ plainText: rendered2.plainText,
8875
+ fromEmail: rendered2.fromEmail,
8876
+ fromName: rendered2.fromName,
8877
+ replyTo: rendered2.replyTo
8878
+ } : {
8879
+ subject: rendered2.subject,
8880
+ preheader: rendered2.preheader,
8881
+ htmlBytes: Buffer.byteLength(rendered2.html, "utf8"),
8882
+ textLength: rendered2.plainText.trim().length,
8883
+ fromEmail: rendered2.fromEmail
8884
+ } : null
8885
+ });
8886
+ if (!tpl.body?.html && !tpl.body?.mjml) {
8887
+ push("published", "fail", "template has no published body (body.html and body.mjml are empty)");
8888
+ return finish(null, []);
8889
+ }
8890
+ push("published", "pass", { publishedAt: tpl.publishedAt ?? null });
8891
+ let out;
8892
+ try {
8893
+ out = await renderForContact(mailer, tpl, contact, {
8894
+ reason: "test",
8895
+ eventProperties: opts.eventProperties,
8896
+ vars: opts.vars
8897
+ });
8898
+ push("vars_resolved", "pass", { keys: Object.keys(out.resolved) });
8899
+ push("render", "pass");
8900
+ } catch (err) {
8901
+ const message = String(err?.message ?? err);
8902
+ push(message.startsWith("varsAdapter") ? "vars_resolved" : "render", "fail", message);
8903
+ return finish(null, []);
8904
+ }
8905
+ const { rendered, unsubscribeUrl } = out;
8906
+ const leftovers = /* @__PURE__ */ new Set();
8907
+ for (const part of [rendered.subject, rendered.preheader, rendered.html, rendered.plainText]) {
8908
+ for (const m of part.matchAll(PLACEHOLDER_RE)) leftovers.add(m[0]);
8909
+ }
8910
+ push("unresolved_placeholders", leftovers.size ? "fail" : "pass", leftovers.size ? { placeholders: [...leftovers] } : void 0);
8911
+ const referenced = referencedPaths(
8912
+ [tpl.subject, tpl.preheader, tpl.body.html, tpl.body.plainText, tpl.body.mjml ?? ""].join("\n"),
8913
+ Object.keys(mailer.config.handlebarsHelpers ?? {})
8914
+ );
8915
+ const missing = [];
8916
+ const empty = [];
8917
+ for (const path3 of referenced) {
8918
+ const value = lookupPath(out.context, path3);
8919
+ if (value === void 0) {
8920
+ const root = path3.split(".")[0];
8921
+ if (exports.RESERVED_VAR_KEYS.includes(root)) empty.push(path3);
8922
+ else missing.push(path3);
8923
+ } else if (value === null || value === "") {
8924
+ empty.push(path3);
8925
+ }
8926
+ }
8927
+ push("unknown_variables", missing.length ? "fail" : "pass", { referenced: referenced.length, missing });
8928
+ push("empty_variables", empty.length ? "warn" : "pass", { empty });
8929
+ const links = extractLinks(rendered.html);
8930
+ const invalid = links.filter((l) => !/^(https?:\/\/|mailto:|tel:)/i.test(l));
8931
+ push("links_absolute", invalid.length ? "fail" : "pass", { total: links.length, invalid });
8932
+ if (tpl.kind === "marketing") {
8933
+ push("unsubscribe_link", rendered.html.includes(unsubscribeUrl) ? "pass" : "fail", {
8934
+ hint: "a marketing template must reference {{unsubscribeUrl}} in its body"
8935
+ });
8936
+ if (mailer.config.senderAddress) {
8937
+ push("sender_address", rendered.html.includes(mailer.config.senderAddress) ? "pass" : "fail", {
8938
+ hint: "CAN-SPAM: reference {{senderAddress}} in the footer"
8939
+ });
8940
+ }
8941
+ }
8942
+ const text = rendered.plainText.trim();
8943
+ push("plain_text", text.length === 0 ? "fail" : text.length < 40 ? "warn" : "pass", { length: text.length });
8944
+ const subject = rendered.subject.trim();
8945
+ push("subject", subject.length === 0 ? "fail" : subject.length > 78 ? "warn" : "pass", { length: subject.length });
8946
+ if (mailer.config.senderDomains && Object.keys(mailer.config.senderDomains).length > 0) {
8947
+ const v = validateSenderDomain(rendered.fromEmail, tpl.kind, mailer.config.senderDomains);
8948
+ push("from_domain", v.ok ? "pass" : "fail", v.ok ? { fromEmail: rendered.fromEmail } : { fromEmail: rendered.fromEmail, code: v.code, reason: v.reason });
8949
+ }
8950
+ const bytes = Buffer.byteLength(rendered.html, "utf8");
8951
+ push("html_size", bytes > GMAIL_CLIP_BYTES ? "warn" : "pass", { bytes, clipAt: GMAIL_CLIP_BYTES });
8952
+ const lint = lintTemplate(
8953
+ {
8954
+ subject: tpl.subject,
8955
+ preheader: tpl.preheader,
8956
+ mjml: tpl.body.mjml ?? "",
8957
+ editorJson: tpl.body.editorJson ?? void 0,
8958
+ html: tpl.body.html,
8959
+ plainText: tpl.body.plainText,
8960
+ kind: tpl.kind,
8961
+ fromEmail: tpl.fromEmail
8962
+ },
8963
+ { senderDomains: mailer.config.senderDomains, varsJsonSchema: opts.varsSchema ?? null }
8964
+ );
8965
+ push("lint", lint.errors.length ? "fail" : lint.warnings.length ? "warn" : "pass", {
8966
+ errors: lint.errors.map((i) => ({ rule: i.rule, message: i.message })),
8967
+ warnings: lint.warnings.map((i) => i.rule)
8968
+ });
8969
+ return finish(rendered, links);
8970
+ }
8971
+ async function renderForContact(mailer, tpl, contact, opts) {
8972
+ let resolved;
8973
+ try {
8974
+ resolved = await resolveVars(mailer.config.varsAdapter, contact, {
8975
+ reason: opts.reason,
8976
+ templateSlug: tpl.slug,
8977
+ eventProperties: opts.eventProperties
8978
+ });
8979
+ } catch (err) {
8980
+ throw new Error(`varsAdapter.resolve threw: ${String(err?.message ?? err)}`);
8981
+ }
8982
+ const unsubscribeUrl = unsubscribeUrlFor(mailer, contact.email);
8983
+ const context = {
8984
+ ...resolved,
8985
+ contact,
8986
+ vars: opts.vars ?? {},
8987
+ event: opts.eventProperties ?? {},
8988
+ unsubscribeUrl,
8989
+ senderAddress: mailer.config.senderAddress
8990
+ };
8991
+ const rendered = await renderTemplate(tpl, context, { helpers: mailer.config.handlebarsHelpers });
8992
+ return { rendered, resolved, unsubscribeUrl, context };
8993
+ }
8994
+ function unsubscribeUrlFor(mailer, email) {
8995
+ const expiresAt = new Date(Date.now() + mailer.config.unsubscribeTokenLifetimeDays * 24 * 60 * 60 * 1e3);
8996
+ const token = signUnsubscribeToken({ email, scope: "marketing", expiresAt }, mailer.config.unsubscribeSecret);
8997
+ return `${mailer.config.publicUrl}/m/unsub/${token}`;
8998
+ }
8999
+ function extractLinks(html) {
9000
+ const out = [];
9001
+ for (const m of html.matchAll(HREF_RE)) {
9002
+ const href = (m[1] ?? m[2] ?? "").trim();
9003
+ if (!href || href.startsWith("#")) continue;
9004
+ out.push(href);
9005
+ }
9006
+ return out;
9007
+ }
9008
+ var BUILTIN_HELPERS = /* @__PURE__ */ new Set([
9009
+ "eq",
9010
+ "ne",
9011
+ "gt",
9012
+ "lt",
9013
+ "gte",
9014
+ "lte",
9015
+ "and",
9016
+ "or",
9017
+ "not",
9018
+ "formatDate",
9019
+ "formatNumber",
9020
+ "formatCurrency",
9021
+ "pluralize",
9022
+ "if",
9023
+ "unless",
9024
+ "each",
9025
+ "with",
9026
+ "else",
9027
+ "lookup",
9028
+ "log",
9029
+ "this",
9030
+ "true",
9031
+ "false",
9032
+ "null",
9033
+ "undefined"
9034
+ ]);
9035
+ var MUSTACHE_RE = /\{\{\{?([^{}]*)\}\}\}?/g;
9036
+ var BLOCK_SCOPE_RE = /\{\{#(each|with)\b[\s\S]*?\{\{\/\1\}\}/g;
9037
+ var HTML_COMMENT_RE = /<!--[\s\S]*?-->/g;
9038
+ var PATH_RE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/;
9039
+ function referencedPaths(source, helperNames = []) {
9040
+ const helpers = /* @__PURE__ */ new Set([...BUILTIN_HELPERS, ...helperNames]);
9041
+ const out = /* @__PURE__ */ new Set();
9042
+ const scanned = source.replace(HTML_COMMENT_RE, "").replace(BLOCK_SCOPE_RE, "");
9043
+ for (const m of scanned.matchAll(MUSTACHE_RE)) {
9044
+ let expr = (m[1] ?? "").trim();
9045
+ if (!expr || expr.startsWith("!")) continue;
9046
+ expr = expr.replace(/^[#/^]\s*/, "").replace(/^else\b\s*/, "");
9047
+ for (let tok of expr.split(/[\s()]+/)) {
9048
+ if (!tok) continue;
9049
+ const eq = tok.indexOf("=");
9050
+ if (eq > 0) tok = tok.slice(eq + 1);
9051
+ if (/^['"]/.test(tok) || /^-?\d/.test(tok)) continue;
9052
+ if (tok.startsWith("@") || tok.startsWith("../") || tok.startsWith("this.")) continue;
9053
+ if (helpers.has(tok) || !PATH_RE.test(tok)) continue;
9054
+ out.add(tok);
9055
+ }
9056
+ }
9057
+ return [...out];
9058
+ }
9059
+ function lookupPath(ctx, path3) {
9060
+ let cur = ctx;
9061
+ for (const part of path3.split(".")) {
9062
+ if (cur === null || typeof cur !== "object") return void 0;
9063
+ cur = cur[part];
9064
+ }
9065
+ return cur;
9066
+ }
9067
+ function testContactMatcher(spec) {
9068
+ if (!spec) return null;
9069
+ if (spec instanceof RegExp) return (email) => spec.test(email);
9070
+ if (typeof spec === "function") return (email) => !!spec(email);
9071
+ return null;
9072
+ }
9073
+ function bearerAuth(tokens) {
9074
+ const hashed = tokens.map((t) => ({ hash: crypto2__default.default.createHash("sha256").update(t.token).digest(), actor: t.actor }));
9075
+ return (req, res, next) => {
9076
+ const header = String(req.headers.authorization ?? "");
9077
+ const m = /^Bearer\s+(\S+)\s*$/i.exec(header);
9078
+ if (!m) {
9079
+ return res.status(401).json({ error: "unauthorized", message: "send Authorization: Bearer <token>" });
9080
+ }
9081
+ const presented = crypto2__default.default.createHash("sha256").update(m[1] ?? "").digest();
9082
+ const match = hashed.find((h) => crypto2__default.default.timingSafeEqual(h.hash, presented));
9083
+ if (!match) return res.status(401).json({ error: "unauthorized", message: "unknown token" });
9084
+ req.actor = match.actor;
9085
+ next();
9086
+ };
9087
+ }
9088
+ async function advanceOnce(runId, ctx, actor, c) {
9089
+ for (let hop = 0; hop < 10; hop += 1) {
9090
+ const run = await c.flowRuns.findOne({ _id: runId });
9091
+ if (!run || run.status !== "active") return false;
9092
+ if (run.nextActionAt && run.nextActionAt.getTime() > Date.now()) {
9093
+ await c.flowRuns.updateOne(
9094
+ { _id: runId, status: "active" },
9095
+ {
9096
+ $set: { nextActionAt: /* @__PURE__ */ new Date(), updatedAt: /* @__PURE__ */ new Date() },
9097
+ $push: {
9098
+ history: {
9099
+ stepIndex: Math.max(0, run.currentStepIndex - 1),
9100
+ action: "wait_completed",
9101
+ at: /* @__PURE__ */ new Date(),
9102
+ details: { forcedBy: actor, scheduledFor: run.nextActionAt }
9103
+ }
9104
+ }
9105
+ }
9106
+ );
9107
+ }
9108
+ const before = (await c.flowRuns.findOne({ _id: runId }))?.history.length ?? 0;
9109
+ await processOneRunStep(runId, ctx);
9110
+ const after = await c.flowRuns.findOne({ _id: runId });
9111
+ if (!after) return false;
9112
+ const last = after.history[after.history.length - 1];
9113
+ const progressed = after.history.length > before;
9114
+ if (progressed && last?.action === "wait_started" && after.status === "active") continue;
9115
+ return after.status === "active" && progressed;
9116
+ }
9117
+ return false;
9118
+ }
9119
+ var WAIT_TARGETS = /* @__PURE__ */ new Set(["sent", "delivered", "opened", "clicked", "terminal"]);
9120
+ function waitTargetReached(send, target) {
9121
+ switch (target) {
9122
+ case "sent":
9123
+ return send.status === "sent" || send.status === "delivered" || !!send.sentAt;
9124
+ case "delivered":
9125
+ return send.status === "delivered" || !!send.deliveredAt;
9126
+ case "opened":
9127
+ return !!send.openedAt;
9128
+ case "clicked":
9129
+ return !!send.firstClickAt;
9130
+ case "terminal":
9131
+ return ["delivered", "bounced", "failed", "suppressed", "cancelled", "complained"].includes(send.status);
9132
+ default:
9133
+ return false;
9134
+ }
9135
+ }
9136
+ function sendSummary(s) {
9137
+ return {
9138
+ id: String(s._id),
9139
+ templateSlug: s.templateSlug,
9140
+ externalId: s.externalId,
9141
+ email: s.emailAtSend,
9142
+ kind: s.kind,
9143
+ status: s.status,
9144
+ provider: s.provider,
9145
+ providerMessageId: s.providerMessageId,
9146
+ subject: s.subject,
9147
+ errorMessage: s.errorMessage,
9148
+ flowRunId: s.flowRunId ? String(s.flowRunId) : null,
9149
+ queuedAt: s.queuedAt,
9150
+ sentAt: s.sentAt,
9151
+ deliveredAt: s.deliveredAt,
9152
+ openedAt: s.openedAt,
9153
+ firstClickAt: s.firstClickAt,
9154
+ bounceType: s.bounceType
9155
+ };
9156
+ }
9157
+ function runSummary(r) {
9158
+ return {
9159
+ id: String(r._id),
9160
+ flowSlug: r.flowSlug,
9161
+ flowVersion: r.flowVersion,
9162
+ externalId: r.externalId,
9163
+ email: r.emailAtEntry,
9164
+ status: r.status,
9165
+ currentStepIndex: r.currentStepIndex,
9166
+ currentBranchPath: r.currentBranchPath,
9167
+ nextActionAt: r.nextActionAt,
9168
+ enteredAt: r.enteredAt,
9169
+ exitedAt: r.exitedAt,
9170
+ exitReason: r.exitReason,
9171
+ triggerEvent: r.triggerEvent ?? null,
9172
+ history: r.history
9173
+ };
9174
+ }
9175
+ function objectOrUndefined(v) {
9176
+ return v && typeof v === "object" && !Array.isArray(v) ? v : void 0;
9177
+ }
9178
+ function sleep2(ms) {
9179
+ return new Promise((r) => setTimeout(r, ms));
9180
+ }
9181
+ function wrap2(fn) {
9182
+ return (req, res, next) => {
9183
+ Promise.resolve(fn(req, res)).catch(next);
9184
+ };
9185
+ }
9186
+ var ENDPOINTS = [
9187
+ { method: "GET", path: "/", summary: "This listing, the package version and the actor behind the token." },
9188
+ { method: "*", path: "/api/*", summary: "The full admin JSON API (flows, templates, contacts, sends, health, setup-status, \u2026) with this token as the actor." },
9189
+ { method: "POST", path: "/templates/:slug/verify", summary: "Render the published template as a contact ({contactId} or {sampleContact}) and run named checks: placeholders, links, unsubscribe, sender address, plain text, subject, from domain, size, lint. {includeRendered: true} returns the HTML." },
9190
+ { method: "POST", path: "/templates/verify-all", summary: "Verify every template (or {slugs}) for each of {contactIds}; a matrix of pass/fail." },
9191
+ { method: "POST", path: "/templates/:slug/render", summary: "Render for a contact and return subject, preheader, HTML, plain text, resolved vars and the signed unsubscribe URL." },
9192
+ { method: "POST", path: "/templates/:slug/send", summary: 'A real send through the pipeline to a test contact ({contactId}); dispatched inline unless {dispatch: "queue"}. Returns the sendId.', testContactsOnly: true },
9193
+ { method: "GET", path: "/sends/:id/wait?status=delivered&timeoutMs=30000", summary: "Long-poll a send until it reaches sent | delivered | opened | clicked | terminal, with its webhook events." },
9194
+ { method: "POST", path: "/sends/:id/dispatch", summary: "Dispatch a queued send now (test contacts only).", testContactsOnly: true },
9195
+ { method: "POST", path: "/flows/:slug/simulate", summary: "Dry-run the flow for {contactId} from {at} with {eventProperties}: the path taken, every gate verdict, projected send times, where it ends. Writes nothing." },
9196
+ { method: "POST", path: "/flows/:slug/arm", summary: "Enable the flow for FUTURE events: stamps the trigger watermark ({since} or now) in the same write. Requires {confirm: true}." },
9197
+ { method: "POST", path: "/flows/:slug/disarm", summary: "Disable the flow (pause). In-flight runs continue." },
9198
+ { method: "POST", path: "/flows/:slug/gate", summary: "Publish a canary version whose first step exits anyone without {tag}." },
9199
+ { method: "POST", path: "/flows/:slug/ungate", summary: "Restore the newest ungated version." },
9200
+ { method: "GET", path: "/runs?externalId=&flowSlug=&status=&limit=", summary: "List flow runs." },
9201
+ { method: "GET", path: "/runs/:id", summary: "One run with its history and sends." },
9202
+ { method: "POST", path: "/runs/:id/advance", summary: "Walk a test contact's run forward now, skipping the wait in front of each of {steps} transitions; sends are dispatched inline.", testContactsOnly: true },
9203
+ { method: "POST", path: "/runs/:id/cancel", summary: "Exit an active run and cancel its queued sends." },
9204
+ { method: "POST", path: "/events", summary: "Fire {name} for a test contact {externalId} with {properties} and optional {dedupeKey}.", testContactsOnly: true },
9205
+ { method: "GET", path: "/contacts/:externalId", summary: "Contact with subscription, suppressions, recent events, sends and runs." },
9206
+ { method: "GET", path: "/contacts/by-email/:email", summary: "Same, looked up by email." },
9207
+ { method: "GET", path: "/contacts/:externalId/unsubscribe-url", summary: "A signed one-click unsubscribe URL for a test contact, to exercise POST /m/unsub/:token.", testContactsOnly: true },
9208
+ { method: "POST", path: "/contacts/:externalId/subscribe", summary: "Subscribe a test contact.", testContactsOnly: true },
9209
+ { method: "POST", path: "/contacts/:externalId/unsubscribe", summary: "Unsubscribe a test contact (marketing scope).", testContactsOnly: true },
9210
+ { method: "POST", path: "/contacts/:externalId/reset", summary: "Delete a test contact's runs, sends, events ({events: [names]} to narrow) and suppressions, then resubscribe. Each part can be turned off with false.", testContactsOnly: true },
9211
+ { method: "POST", path: "/tick", summary: "Run the runner tick now (trigger scan, sweeps, outbox, webhook backlog)." },
9212
+ { method: "GET", path: "/webhooks/status", summary: "Provider webhook ingest: last event received, counts by type (24h), unprocessed backlog." },
9213
+ { method: "GET", path: "/status", summary: "One document with setup checks, health, every flow (enabled, version, watermark, gate, active runs), every template, and 24h counts." }
9214
+ ];
7869
9215
  var ALLOWED_EXTENSIONS = [".zip", ".gz", ".xml"];
7870
9216
  var DEFAULT_PATH = "/inbound/dmarc";
7871
9217
  var DEFAULT_MAX_FILE_BYTES = 10 * 1024 * 1024;
@@ -8577,45 +9923,59 @@ var DEDUPE_POLICIES = [
8577
9923
  ];
8578
9924
 
8579
9925
  // src/server/index.ts
8580
- var VERSION = "0.15.0" ;
9926
+ var VERSION2 = "0.16.0" ;
8581
9927
 
8582
9928
  exports.DEDUPE_POLICIES = DEDUPE_POLICIES;
8583
9929
  exports.DEFAULT_BOT_UA_RE = DEFAULT_BOT_UA_RE;
8584
9930
  exports.FLOW_STEP_KINDS = FLOW_STEP_KINDS;
9931
+ exports.FlowOperationError = FlowOperationError;
9932
+ exports.MIN_AGENT_TOKEN_LENGTH = MIN_AGENT_TOKEN_LENGTH;
8585
9933
  exports.Mailer = Mailer;
8586
9934
  exports.NullProvider = NullProvider;
8587
9935
  exports.PREDICATE_KINDS = PREDICATE_KINDS;
8588
9936
  exports.SEGMENT_FILTER_KINDS = SEGMENT_FILTER_KINDS;
8589
9937
  exports.TRACKING_SIG_LENGTH = TRACKING_SIG_LENGTH;
8590
- exports.VERSION = VERSION;
9938
+ exports.VERSION = VERSION2;
8591
9939
  exports.applyTracking = applyTracking;
8592
9940
  exports.applyWebhookEvent = applyWebhookEvent;
9941
+ exports.armFlow = armFlow;
8593
9942
  exports.compileMailyTemplate = compileMailyTemplate;
8594
9943
  exports.compileTemplate = compileTemplate;
8595
9944
  exports.computeDeliveryTime = computeDeliveryTime;
9945
+ exports.createAdminApiRouter = createAdminApiRouter;
8596
9946
  exports.createAdminRouter = createAdminRouter;
9947
+ exports.createAgentRouter = createAgentRouter;
8597
9948
  exports.createPublicRouter = createPublicRouter;
8598
9949
  exports.defaultFlowStep = defaultFlowStep;
8599
9950
  exports.defaultPredicate = defaultPredicate;
8600
9951
  exports.defaultSegmentFilter = defaultSegmentFilter;
8601
9952
  exports.defineVars = defineVars;
8602
9953
  exports.derivePlaintext = derivePlaintext;
9954
+ exports.disarmFlow = disarmFlow;
8603
9955
  exports.dispatchSend = dispatchSend;
8604
9956
  exports.drainPendingUnsubscribes = drainPendingUnsubscribes;
8605
9957
  exports.ensureIndexes = ensureIndexes;
9958
+ exports.gateFlow = gateFlow;
8606
9959
  exports.getCollections = getCollections;
9960
+ exports.isCanaryGate = isCanaryGate;
8607
9961
  exports.predicateKind = predicateKind;
8608
9962
  exports.processNewlyFiredEventTriggers = processNewlyFiredEventTriggers;
8609
9963
  exports.processOneRunStep = processOneRunStep;
9964
+ exports.referencedPaths = referencedPaths;
9965
+ exports.renderForContact = renderForContact;
8610
9966
  exports.renderTemplate = renderTemplate;
8611
9967
  exports.runTick = runTick;
8612
9968
  exports.sendgridInboundParser = sendgridInboundParser;
8613
9969
  exports.sha256Hex = sha256Hex;
8614
9970
  exports.signTrackingToken = signTrackingToken;
8615
9971
  exports.signUnsubscribeToken = signUnsubscribeToken;
9972
+ exports.simulateFlow = simulateFlow;
9973
+ exports.stampWatermarkIfNull = stampWatermarkIfNull;
8616
9974
  exports.sweepStrandedFlowRuns = sweepStrandedFlowRuns;
9975
+ exports.ungateFlow = ungateFlow;
8617
9976
  exports.validateSenderDomain = validateSenderDomain;
8618
9977
  exports.varsJsonSchema = varsJsonSchema;
9978
+ exports.verifyTemplate = verifyTemplate;
8619
9979
  exports.verifyTrackingToken = verifyTrackingToken;
8620
9980
  exports.verifyUnsubscribeToken = verifyUnsubscribeToken;
8621
9981
  //# sourceMappingURL=index.cjs.map