mailery 0.15.0 → 0.16.1

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