@pithy-sh/email 0.3.11 → 0.5.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.
Files changed (39) hide show
  1. package/dist/capability.d.ts.map +1 -1
  2. package/dist/capability.js +20 -1
  3. package/dist/crypto/signingKey.d.ts +4 -0
  4. package/dist/crypto/signingKey.d.ts.map +1 -1
  5. package/dist/crypto/signingKey.js +5 -1
  6. package/dist/http/callbacks.d.ts.map +1 -1
  7. package/dist/http/callbacks.js +26 -5
  8. package/dist/http/routes.d.ts +1 -1
  9. package/dist/http/routes.d.ts.map +1 -1
  10. package/dist/http/routes.js +42 -10
  11. package/dist/provision/provisionEmail.d.ts +16 -2
  12. package/dist/provision/provisionEmail.d.ts.map +1 -1
  13. package/dist/provision/provisionEmail.js +7 -2
  14. package/dist/provision/resolveEmailConfig.d.ts +7 -0
  15. package/dist/provision/resolveEmailConfig.d.ts.map +1 -1
  16. package/dist/provision/resolveEmailConfig.js +14 -1
  17. package/dist/provision/settingsCheck.d.ts.map +1 -1
  18. package/dist/provision/settingsCheck.js +44 -7
  19. package/dist/send/enqueue.d.ts +16 -0
  20. package/dist/send/enqueue.d.ts.map +1 -1
  21. package/dist/send/enqueue.js +14 -0
  22. package/dist/version.generated.d.ts +1 -1
  23. package/dist/version.generated.d.ts.map +1 -1
  24. package/dist/version.generated.js +1 -1
  25. package/dist/workflows/hostEnv.d.ts +41 -0
  26. package/dist/workflows/hostEnv.d.ts.map +1 -1
  27. package/dist/workflows/hostEnv.js +14 -7
  28. package/package.json +6 -6
  29. package/src/capability.ts +18 -1
  30. package/src/crypto/signingKey.ts +6 -0
  31. package/src/http/callbacks.ts +41 -12
  32. package/src/http/routes.ts +49 -11
  33. package/src/http/schemas.ts +1 -1
  34. package/src/provision/provisionEmail.ts +19 -5
  35. package/src/provision/resolveEmailConfig.ts +12 -0
  36. package/src/provision/settingsCheck.ts +48 -9
  37. package/src/send/enqueue.ts +28 -0
  38. package/src/version.generated.ts +1 -1
  39. package/src/workflows/hostEnv.ts +13 -6
@@ -1 +1 @@
1
- {"version":3,"file":"capability.d.ts","sourceRoot":"","sources":["../src/capability.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,KAAK,UAAU,EAAoB,MAAM,0CAA0C,CAAC;AAE7F,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACtE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EACL,KAAK,wBAAwB,EAM9B,MAAM,eAAe,CAAC;AAMvB,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAG1D,OAAO,EAAE,KAAK,YAAY,EAAE,KAAK,aAAa,EAAgB,MAAM,gBAAgB,CAAC;AACrF,OAAO,EAAE,KAAK,cAAc,EAAsB,MAAM,sBAAsB,CAAC;AAE/E,OAAO,EAAe,KAAK,UAAU,EAAgB,MAAM,mBAAmB,CAAC;AAI/E;;;;;;;;;;GAUG;AACH,MAAM,WAAW,eAAgB,SAAQ,cAAc;IACrD,EAAE,EAAE,UAAU,CAAC;IACf;;;;;;;OAOG;IACH,kBAAkB,CAAC,EAAE,UAAU,CAAC;CACjC;AAED;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,MAAM,CAAC;AAEzC,kGAAkG;AAClG,eAAO,MAAM,kCAAkC,MAAM,CAAC;AAEtD;;;;;;;GAOG;AACH,eAAO,MAAM,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiC8B,CAAC;AACvD,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,WAAW,CAAC,CAAC;AACvD,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,WAAW,CAAC,CAAC;AAE3D,2FAA2F;AAC3F,MAAM,WAAW,mBAAmB;IAClC,WAAW,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GAMG;AACH,wBAAgB,KAAK,CAAC,MAAM,EAAE,gBAAgB,GAAG,eAAe,CAoO/D;AAED,kFAAkF;AAClF,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,UAAU,GAAG,UAAU,IAAI,eAAe,CAEvF"}
@@ -19,6 +19,8 @@ import { PACKAGE_NAME, PACKAGE_VERSION } from "./version.generated.js";
19
19
  import { EmailScheduleParams, EmailSendParams } from "./workflows/params.js";
20
20
  import { z } from "zod";
21
21
  import { defineCapability } from "@pithy-sh/core/src/capability/capability";
22
+ import { pithyCommandOf } from "@pithy-sh/core/src/cli/command";
23
+ import { composedUsageMeter } from "@pithy-sh/core/src/entitlement/meter";
22
24
  import { InternalError } from "@pithy-sh/core/src/error/pithyError";
23
25
  //#region src/capability.ts
24
26
  /**
@@ -79,6 +81,12 @@ function email(config) {
79
81
  * capability's own config, and this is the only thing that knows it.
80
82
  */
81
83
  let supportedLocales = [];
84
+ /**
85
+ * The usage meter a composed provider exposes — `@pithy-sh/payments`, when it is composed — found in
86
+ * `compose` by core's structural predicate. Undefined with no provider, which is the email capability
87
+ * exactly as it always was: nothing is counted and nothing is refused.
88
+ */
89
+ let meter;
82
90
  const capability = defineCapability({
83
91
  name: "email",
84
92
  version: PACKAGE_VERSION,
@@ -113,6 +121,7 @@ function email(config) {
113
121
  * project sends what it always sent.
114
122
  */
115
123
  compose: ({ capabilities }) => {
124
+ meter = composedUsageMeter(capabilities);
116
125
  for (const composed of capabilities) {
117
126
  if (composed.name !== "i18n") continue;
118
127
  const candidate = composed.layersFor;
@@ -221,11 +230,20 @@ function email(config) {
221
230
  const binding = env.EMAIL_SUPPRESSIONS;
222
231
  if (!binding) throw new InternalError({
223
232
  message: "The suppression list is not available.",
224
- action: "Run `pithy add email` to provision it, or bind the EMAIL_SUPPRESSIONS D1 database.",
233
+ action: `Run \`${pithyCommandOf("add", {
234
+ args: ["email"],
235
+ flags: { "--with-prerequisites": true }
236
+ }, { runtime: true })}\` to provision it, or bind the EMAIL_SUPPRESSIONS D1 database.`,
225
237
  detail: "email.suppressions() was called with an env carrying no `EMAIL_SUPPRESSIONS` D1 binding."
226
238
  });
227
239
  return emailSuppressionDatabase(binding);
228
240
  };
241
+ /** The meter charge for one env, or undefined when no provider is composed. */
242
+ const chargeFor = (env) => {
243
+ const composed = meter;
244
+ if (composed === void 0) return void 0;
245
+ return (charge) => composed.charge(env, charge);
246
+ };
229
247
  const enqueue = (env, input) => enqueueEmail({
230
248
  db: emailDatabase(env.DB),
231
249
  fromAddress: resolved.fromAddress,
@@ -234,6 +252,7 @@ function email(config) {
234
252
  layersFor: (locale) => layersFor(locale),
235
253
  sender: emailSenderBinding(env),
236
254
  suppressionDb: env.EMAIL_SUPPRESSIONS ? emailSuppressionDatabase(env.EMAIL_SUPPRESSIONS) : void 0,
255
+ meter: chargeFor(env),
237
256
  now: /* @__PURE__ */ new Date(),
238
257
  newId: () => crypto.randomUUID()
239
258
  }, input);
@@ -33,6 +33,10 @@ export declare const emailSigningRegistry: {
33
33
  readonly rotation: {
34
34
  readonly kind: "local";
35
35
  };
36
+ readonly overlap: {
37
+ readonly days: 90;
38
+ readonly minimumDays: 90;
39
+ };
36
40
  };
37
41
  };
38
42
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"signingKey.d.ts","sourceRoot":"","sources":["../../src/crypto/signingKey.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAE1E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAG1E;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,2BAA2B,CAAC;AAE/D;;;;GAIG;AACH,eAAO,MAAM,8BAA8B,0BAA4C,CAAC;AAExF,gHAAgH;AAChH,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;CA+B/B,CAAC;AAEH;;;;GAIG;AACH,wBAAsB,kBAAkB,CACtC,GAAG,EAAE,eAAe,GACnB,OAAO,CAAC,eAAe,CAAC,CAAC,OAAO,oBAAoB,CAAC,CAAC,OAAO,sBAAsB,CAAC,CAAC,CAAC,CAGxF"}
1
+ {"version":3,"file":"signingKey.d.ts","sourceRoot":"","sources":["../../src/crypto/signingKey.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAE1E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAG1E;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,2BAA2B,CAAC;AAE/D;;;;GAIG;AACH,eAAO,MAAM,8BAA8B,0BAA4C,CAAC;AAExF,gHAAgH;AAChH,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;CAqC/B,CAAC;AAEH;;;;GAIG;AACH,wBAAsB,kBAAkB,CACtC,GAAG,EAAE,eAAe,GACnB,OAAO,CAAC,eAAe,CAAC,CAAC,OAAO,oBAAoB,CAAC,CAAC,OAAO,sBAAsB,CAAC,CAAC,CAAC,CAGxF"}
@@ -31,7 +31,11 @@ const emailSigningRegistry = defineSecretRegistry({ [EMAIL_LINK_SIGNING_KEY]: {
31
31
  encoding: "base64url"
32
32
  }
33
33
  },
34
- rotation: { kind: "local" }
34
+ rotation: { kind: "local" },
35
+ overlap: {
36
+ days: 90,
37
+ minimumDays: 90
38
+ }
35
39
  } });
36
40
  /**
37
41
  * Resolve the current signing key plus every still-valid prior version. The current version is the
@@ -1 +1 @@
1
- {"version":3,"file":"callbacks.d.ts","sourceRoot":"","sources":["../../src/http/callbacks.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAG7E,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAGjC,OAAO,EACL,KAAK,aAAa,EAClB,KAAK,wBAAwB,EAG9B,MAAM,gBAAgB,CAAC;AA4CxB,8DAA8D;AAC9D,MAAM,WAAW,WAAW;IAC1B,QAAQ,EAAE,MAA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AE,MAAM,CAAC,CAAC;CAClC;AAQD;;;;;;;GAOG;AACH,MAAM,WAAW,eAAe;IAC9B,4CAA4C;IAC5C,KAAK,EAAE,MAAM,CAAC;IACd,mEAAmE;IACnE,GAAG,EAAE,MAAM,CAAC;CACb;AAgBD,sFAAsF;AACtF,wBAAsB,WAAW,CAC/B,EAAE,EAAE,aAAa,EACjB,IAAI,EAAE,WAAW,EACjB,OAAO,EAAE,eAAe,EACxB,GAAG,EAAE,IAAI,GACR,OAAO,CAAC,QAAQ,CAAC,CAmBnB;AAED,uDAAuD;AACvD,wBAAsB,UAAU,CAC9B,EAAE,EAAE,aAAa,EACjB,IAAI,EAAE,WAAW,EACjB,OAAO,EAAE,eAAe,EACxB,GAAG,EAAE,IAAI,GACR,OAAO,CAAC,QAAQ,CAAC,CAgBnB;AAED;;;;;GAKG;AACH,wBAAsB,iBAAiB,CACrC,EAAE,EAAE,aAAa,EACjB,aAAa,EAAE,wBAAwB,EACvC,IAAI,EAAE,WAAW,EACjB,OAAO,EAAE,eAAe,EACxB,GAAG,EAAE,IAAI,EACT,MAAM,CAAC,EAAE,MAAM,EACf,WAAW,CAAC,EAAE,MAAM,GACnB,OAAO,CAAC,QAAQ,CAAC,CAuBnB;AAED,0GAA0G;AAC1G,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,GAAG,IAAI,CAsE/D"}
@@ -9,8 +9,8 @@ import { verifyToken } from "../crypto/token.js";
9
9
  import { CALLBACK_BASE } from "../templates/engine.js";
10
10
  import { CallbackTokenParam, UnsubscribeQuery } from "./schemas.js";
11
11
  import { normalizeAddress } from "@pithy-sh/core/src/address/address";
12
- import { zValidator } from "@hono/zod-validator";
13
- import { validationHook } from "@pithy-sh/core/src/http/validation";
12
+ import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
13
+ import { validate } from "@pithy-sh/core/src/http/validation";
14
14
  //#region src/http/callbacks.ts
15
15
  /** A 1×1 transparent PNG — the open-tracking pixel body. */
16
16
  const PIXEL = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg=="), (c) => c.charCodeAt(0));
@@ -97,21 +97,42 @@ function registerCallbacks(app) {
97
97
  keys: { versions: keys.versions }
98
98
  };
99
99
  };
100
- app.get(`${CALLBACK_BASE}/c/:token`, zValidator("param", CallbackTokenParam, validationHook), async (c) => {
100
+ app.get(`${CALLBACK_BASE}/c/:token`, describeRoute({
101
+ summary: "Record a click on a tracked link, then send the reader on to it.",
102
+ description: "Public: the HMAC signature on the token is the only gate. A forged, altered, or expired token answers `email/invalid_token` (400) before anything is recorded, and the destination is the http(s) URL signed into the token, never one from the request.",
103
+ verification: "public",
104
+ responses: { 302: { description: "A redirect to the link's destination, carried in `Location`." } }
105
+ }), validate("param", CallbackTokenParam), async (c) => {
101
106
  const { db, keys } = await setup(c.env);
102
107
  return handleClick(db, keys, {
103
108
  token: c.req.valid("param").token,
104
109
  url: c.req.url
105
110
  }, /* @__PURE__ */ new Date());
106
111
  });
107
- app.get(`${CALLBACK_BASE}/o/:token`, zValidator("param", CallbackTokenParam, validationHook), async (c) => {
112
+ app.get(`${CALLBACK_BASE}/o/:token`, describeRoute({
113
+ summary: "Record that an email was opened.",
114
+ description: "Public: the HMAC signature on the token is the only gate. The token may carry the `.png` suffix mail clients expect on an image URL.",
115
+ verification: "public",
116
+ responses: { 200: {
117
+ description: "A 1×1 transparent PNG, never cached.",
118
+ contentType: "image/png"
119
+ } }
120
+ }), validate("param", CallbackTokenParam), async (c) => {
108
121
  const { db, keys } = await setup(c.env);
109
122
  return handleOpen(db, keys, {
110
123
  token: c.req.valid("param").token,
111
124
  url: c.req.url
112
125
  }, /* @__PURE__ */ new Date());
113
126
  });
114
- app.on(["GET", "POST"], `${CALLBACK_BASE}/u/:token`, zValidator("param", CallbackTokenParam, validationHook), zValidator("query", UnsubscribeQuery, validationHook), async (c) => {
127
+ app.on(["GET", "POST"], `${CALLBACK_BASE}/u/:token`, describeRoute({
128
+ summary: "Unsubscribe the recipient from everything but the mail they ask for.",
129
+ description: "Public: the HMAC signature on the token is the only gate. Answers GET for the link in the message and POST for one-click unsubscribe. The address joins the suppression list shared by every environment.",
130
+ verification: "public",
131
+ responses: { 200: {
132
+ description: "A short HTML page confirming the opt-out.",
133
+ contentType: "text/html"
134
+ } }
135
+ }), validate("param", CallbackTokenParam), validate("query", UnsubscribeQuery), async (c) => {
115
136
  const env = c.env;
116
137
  const { db, suppressionDb, keys } = await setup(env);
117
138
  return handleUnsubscribe(db, suppressionDb, keys, {
@@ -49,7 +49,7 @@ export interface EmailRouteDeclaration {
49
49
  * Every management route, and how it is gated.
50
50
  *
51
51
  * Exported so a test can assert against the declaration rather than against a middleware count. A count
52
- * proves that *something* runs before the handler — a bare `zValidator` satisfies it — and cannot prove
52
+ * proves that *something* runs before the handler — a bare `validate` satisfies it — and cannot prove
53
53
  * *what*. `routeContract.test.ts` checks this list against the paths Hono actually registered, in both
54
54
  * directions, so a route added without an entry and an entry without a route both fail.
55
55
  */
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/http/routes.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAG7E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6CAA6C,CAAC;AAGrF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AACjF,OAAO,KAAK,EAAW,IAAI,EAAE,MAAM,MAAM,CAAC;AA+B1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,yGAAyG;AACzG,MAAM,WAAW,qBAAqB;IACpC,QAAQ,CAAC,MAAM,EAAE,KAAK,GAAG,MAAM,CAAC;IAChC,oEAAoE;IACpE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAA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H,QAAQ,EAAE,MAAM,CAAC;IACjB,4EAA4E;IAC5E,GAAG,CAAC,EAAE,MAAM,IAAI,CAAC;CAClB;AAiDD,yFAAyF;AACzF,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,uBAAuB,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,IAAI,CA+T5G"}
@@ -8,18 +8,20 @@ import { EmailAuditActions } from "../audit/actions.js";
8
8
  import { getJob, listJobs } from "../jobs/read.js";
9
9
  import { retryJob } from "../jobs/retry.js";
10
10
  import { emailSenderBinding } from "../send/senderBinding.js";
11
+ import { EmailJobResponse, EmailJobRetryResponse, EmailJobsResponse, EmailSuppressResponse, EmailSuppressionsResponse, EmailUnsuppressResponse } from "./responses.js";
11
12
  import { jobDetailView, jobListView, suppressionView } from "./view.js";
12
13
  import { ConflictError, InternalError, NotFoundError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
13
14
  import { normalizeAddress } from "@pithy-sh/core/src/address/address";
14
- import { zValidator } from "@hono/zod-validator";
15
- import { validationHook } from "@pithy-sh/core/src/http/validation";
15
+ import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
16
+ import { validate } from "@pithy-sh/core/src/http/validation";
16
17
  import { requireControlPlane } from "@pithy-sh/core/src/controlPlane/http/guard";
18
+ import { migrateStep } from "@pithy-sh/core/src/migrations/migrateStep";
17
19
  //#region src/http/routes.ts
18
20
  /**
19
21
  * Every management route, and how it is gated.
20
22
  *
21
23
  * Exported so a test can assert against the declaration rather than against a middleware count. A count
22
- * proves that *something* runs before the handler — a bare `zValidator` satisfies it — and cannot prove
24
+ * proves that *something* runs before the handler — a bare `validate` satisfies it — and cannot prove
23
25
  * *what*. `routeContract.test.ts` checks this list against the paths Hono actually registered, in both
24
26
  * directions, so a route added without an entry and an entry without a route both fail.
25
27
  */
@@ -72,7 +74,7 @@ function d1(c, binding) {
72
74
  const found = c.env[binding];
73
75
  if (!found) throw new InternalError({
74
76
  message: "Email is not fully configured on this Worker.",
75
- action: `Bind a D1 database named ${binding} in wrangler.jsonc, then run pithy migrate.`,
77
+ action: `Bind a D1 database named ${binding} in wrangler.jsonc, then ${migrateStep(c.env)}.`,
76
78
  detail: `the email management routes require a \`${binding}\` D1 binding; none was present on env`
77
79
  });
78
80
  return found;
@@ -105,7 +107,12 @@ function registerEmailAdminRoutes(options) {
105
107
  const base = options.basePath;
106
108
  const clock = options.now ?? (() => /* @__PURE__ */ new Date());
107
109
  return (app) => {
108
- app.get(`${base}/jobs`, requireControlPlane(EMAIL_JOBS_READ_SCOPE), zValidator("query", JobsQuery, validationHook), async (c) => {
110
+ app.get(`${base}/jobs`, describeRoute({
111
+ summary: "Page through the send log.",
112
+ verification: "control-plane",
113
+ scopes: [EMAIL_JOBS_READ_SCOPE],
114
+ responses: { 200: EmailJobsResponse }
115
+ }), requireControlPlane(EMAIL_JOBS_READ_SCOPE), validate("query", JobsQuery), async (c) => {
109
116
  const query = c.req.valid("query");
110
117
  const who = caller(c);
111
118
  const page = await listJobs(jobs(c), query);
@@ -128,7 +135,12 @@ function registerEmailAdminRoutes(options) {
128
135
  nextCursor: page.nextCursor
129
136
  });
130
137
  });
131
- app.get(`${base}/jobs/:id`, requireControlPlane(EMAIL_JOBS_READ_SCOPE), zValidator("param", JobIdParam, validationHook), async (c) => {
138
+ app.get(`${base}/jobs/:id`, describeRoute({
139
+ summary: "Read one email job in full, recipient included.",
140
+ verification: "control-plane",
141
+ scopes: [EMAIL_JOBS_READ_SCOPE],
142
+ responses: { 200: EmailJobResponse }
143
+ }), requireControlPlane(EMAIL_JOBS_READ_SCOPE), validate("param", JobIdParam), async (c) => {
132
144
  const { id } = c.req.valid("param");
133
145
  const who = caller(c);
134
146
  const job = await getJob(jobs(c), id);
@@ -152,7 +164,12 @@ function registerEmailAdminRoutes(options) {
152
164
  });
153
165
  return c.json({ job: jobDetailView(job) });
154
166
  });
155
- app.post(`${base}/jobs/:id/retry`, requireControlPlane(EMAIL_JOBS_RETRY_SCOPE), zValidator("param", JobIdParam, validationHook), async (c) => {
167
+ app.post(`${base}/jobs/:id/retry`, describeRoute({
168
+ summary: "Queue a job to send again.",
169
+ verification: "control-plane",
170
+ scopes: [EMAIL_JOBS_RETRY_SCOPE],
171
+ responses: { 200: EmailJobRetryResponse }
172
+ }), requireControlPlane(EMAIL_JOBS_RETRY_SCOPE), validate("param", JobIdParam), async (c) => {
156
173
  const { id } = c.req.valid("param");
157
174
  const who = caller(c);
158
175
  const now = clock();
@@ -184,7 +201,12 @@ function registerEmailAdminRoutes(options) {
184
201
  dispatched: result.dispatched
185
202
  });
186
203
  });
187
- app.get(`${base}/suppressions`, requireControlPlane(EMAIL_SUPPRESSIONS_READ_SCOPE), zValidator("query", SuppressionsQuery, validationHook), async (c) => {
204
+ app.get(`${base}/suppressions`, describeRoute({
205
+ summary: "Page through the suppression list, or look one address up.",
206
+ verification: "control-plane",
207
+ scopes: [EMAIL_SUPPRESSIONS_READ_SCOPE],
208
+ responses: { 200: EmailSuppressionsResponse }
209
+ }), requireControlPlane(EMAIL_SUPPRESSIONS_READ_SCOPE), validate("query", SuppressionsQuery), async (c) => {
188
210
  const query = c.req.valid("query");
189
211
  const who = caller(c);
190
212
  const now = clock();
@@ -209,7 +231,12 @@ function registerEmailAdminRoutes(options) {
209
231
  nextCursor: page.nextCursor
210
232
  });
211
233
  });
212
- app.post(`${base}/suppressions`, requireControlPlane(EMAIL_SUPPRESSIONS_WRITE_SCOPE), zValidator("json", SuppressRequest, validationHook), async (c) => {
234
+ app.post(`${base}/suppressions`, describeRoute({
235
+ summary: "Block an address by hand.",
236
+ verification: "control-plane",
237
+ scopes: [EMAIL_SUPPRESSIONS_WRITE_SCOPE],
238
+ responses: { 200: EmailSuppressResponse }
239
+ }), requireControlPlane(EMAIL_SUPPRESSIONS_WRITE_SCOPE), validate("json", SuppressRequest), async (c) => {
213
240
  const input = c.req.valid("json");
214
241
  const who = caller(c);
215
242
  const now = clock();
@@ -258,7 +285,12 @@ function registerEmailAdminRoutes(options) {
258
285
  });
259
286
  return c.json({ suppression: row ? suppressionView(row, now) : null }, 200);
260
287
  });
261
- app.post(`${base}/suppressions/remove`, requireControlPlane(EMAIL_SUPPRESSIONS_DELETE_SCOPE), zValidator("json", UnsuppressRequest, validationHook), async (c) => {
288
+ app.post(`${base}/suppressions/remove`, describeRoute({
289
+ summary: "Lift the block on an address.",
290
+ verification: "control-plane",
291
+ scopes: [EMAIL_SUPPRESSIONS_DELETE_SCOPE],
292
+ responses: { 200: EmailUnsuppressResponse }
293
+ }), requireControlPlane(EMAIL_SUPPRESSIONS_DELETE_SCOPE), validate("json", UnsuppressRequest), async (c) => {
262
294
  const input = c.req.valid("json");
263
295
  const who = caller(c);
264
296
  const email = normalizeAddress(input.email);
@@ -91,9 +91,13 @@ export interface EmailProvisioner {
91
91
  * Throws a clear, actionable error so provisioning fails fast and clean rather than mid-deploy.
92
92
  */
93
93
  preflight(): Promise<void>;
94
- /** Create (or reuse) the project's suppression D1; returns its id. Idempotent. Runs once, before any env. */
94
+ /**
95
+ * Create (or reuse) the project's suppression D1; returns its id, and whether this call created it. Idempotent.
96
+ * Runs once, before any env.
97
+ */
95
98
  ensureSuppressionDatabase(): Promise<{
96
99
  databaseId: string;
100
+ created: boolean;
97
101
  }>;
98
102
  /** Run the `email_0001_suppressions` migration against the suppression D1. Idempotent (applied ones skip). */
99
103
  migrateSuppression(databaseId: string): Promise<void>;
@@ -113,6 +117,8 @@ export interface EmailProvisioner {
113
117
  /** What provisioning produced. */
114
118
  export interface EmailProvisionResult {
115
119
  suppressionDatabaseId: string;
120
+ /** Whether this run created the suppression database, or found one an earlier run made. */
121
+ suppressionDatabaseCreated: boolean;
116
122
  environments: ManagedEnvironment[];
117
123
  /** Whether the inbound routing rule was created, already present, or skipped (not configured). */
118
124
  routing: {
@@ -147,6 +153,11 @@ export interface EmailDeprovisioner {
147
153
  * before it deletes the list they share (#591).
148
154
  */
149
155
  hasWorker(env: ManagedEnvironment): Promise<boolean>;
156
+ /**
157
+ * Delete the env's send and schedule Workflows, by `emailWorkflowNames`. Idempotent (a Workflow already gone is
158
+ * a no-op). Deleting the worker leaves them registered, so they go first (#789).
159
+ */
160
+ deleteWorkflows(env: ManagedEnvironment): Promise<void>;
150
161
  /** Delete the env's email worker. Idempotent (a missing worker is a no-op). */
151
162
  deleteWorker(env: ManagedEnvironment): Promise<void>;
152
163
  /**
@@ -178,7 +189,10 @@ export interface EmailDeprovisionOptions {
178
189
  * 2. With `deleteSuppression` only: refuse while any other declared environment still runs an email worker
179
190
  * (`assertSharedLeavesLast`). The list is one per project, and a staging teardown must not take production's.
180
191
  * 3. Count the list, and refuse unless the operator counted the same (`assertRetainedAgreed`, #588's guard).
181
- * 4. Delete the environment's worker (it binds the list), then — only when asked — the list.
192
+ * 4. Delete the environment's Workflows (#789), then its worker (it binds the list), then — only when asked — the list.
193
+ *
194
+ * It never deletes the environment's link-signing key. `pithy secrets provision` creates that entry and binds it
195
+ * into the app Worker, which is still deployed, and every link already sent is signed with it (#596).
182
196
  *
183
197
  * Idempotent end to end: a missing worker or database is a no-op.
184
198
  */
@@ -1 +1 @@
1
- {"version":3,"file":"provisionEmail.d.ts","sourceRoot":"","sources":["../../src/provision/provisionEmail.ts"],"names":[],"mappings":"AAGA,OAAO,EAAwB,KAAK,YAAY,EAAE,MAAM,wCAAwC,CAAC;AACjG,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,uCAAuC,CAAC;AAKlF,OAAO,EAEL,KAAK,iBAAiB,EAEtB,KAAK,kBAAkB,EAExB,MAAM,6BAA6B,CAAC;AAErC;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,4GAA4G;AAC5G,eAAO,MAAM,gBAAgB,UAAU,CAAC;AAExC,kGAAkG;AAClG,eAAO,MAAM,0BAA0B,uBAAuB,CAAC;AAW/D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CA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;OAGG;IACH,SAAS,CAAC,GAAG,EAAE,kBAAkB,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACrD;;;OAGG;IACH,eAAe,CAAC,GAAG,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACxD,+EAA+E;IAC/E,YAAY,CAAC,GAAG,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACrD;;;;;OAKG;IACH,yBAAyB,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC5C;AAED,+GAA+G;AAC/G,MAAM,WAAW,uBAAuB;IACtC,gGAAgG;IAChG,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,gBAAgB,CACpC,aAAa,EAAE,kBAAkB,EACjC,MAAM,EAAE,iBAAiB,EACzB,OAAO,GAAE,uBAA4B,GACpC,OAAO,CAAC;IAAE,GAAG,EAAE,kBAAkB,CAAA;CAAE,CAAC,CAiBtC"}
@@ -121,12 +121,13 @@ function emailWorkerName(project, env) {
121
121
  */
122
122
  async function provisionEmail(provisioner, environments) {
123
123
  await provisioner.preflight();
124
- const { databaseId } = await provisioner.ensureSuppressionDatabase();
124
+ const { databaseId, created } = await provisioner.ensureSuppressionDatabase();
125
125
  await provisioner.migrateSuppression(databaseId);
126
126
  const deployed = managedEnvironments(environments);
127
127
  for (const env of deployed) await provisioner.deployWorker(env, databaseId);
128
128
  return {
129
129
  suppressionDatabaseId: databaseId,
130
+ suppressionDatabaseCreated: created,
130
131
  environments: deployed,
131
132
  routing: deployed.length > 0 ? await provisioner.ensureRoutingRule() : {
132
133
  created: false,
@@ -145,7 +146,10 @@ async function provisionEmail(provisioner, environments) {
145
146
  * 2. With `deleteSuppression` only: refuse while any other declared environment still runs an email worker
146
147
  * (`assertSharedLeavesLast`). The list is one per project, and a staging teardown must not take production's.
147
148
  * 3. Count the list, and refuse unless the operator counted the same (`assertRetainedAgreed`, #588's guard).
148
- * 4. Delete the environment's worker (it binds the list), then — only when asked — the list.
149
+ * 4. Delete the environment's Workflows (#789), then its worker (it binds the list), then — only when asked — the list.
150
+ *
151
+ * It never deletes the environment's link-signing key. `pithy secrets provision` creates that entry and binds it
152
+ * into the app Worker, which is still deployed, and every link already sent is signed with it (#596).
149
153
  *
150
154
  * Idempotent end to end: a missing worker or database is a no-op.
151
155
  */
@@ -158,6 +162,7 @@ async function deprovisionEmail(deprovisioner, target, options = {}) {
158
162
  }]);
159
163
  assertRetainedAgreed(await deprovisioner.countSuppressionRetained(), options.destroyRetained, "anything was deleted");
160
164
  }
165
+ await deprovisioner.deleteWorkflows(env);
161
166
  await deprovisioner.deleteWorker(env);
162
167
  if (options.deleteSuppression) await deprovisioner.deleteSuppressionDatabase();
163
168
  return { env };
@@ -29,6 +29,13 @@ export interface EmailWorkerWranglerTemplate extends WorkflowHostTemplate {
29
29
  }
30
30
  /** The registry the host resolver derives its `workflows` array from, and the host's app dispatches on. */
31
31
  export declare const emailWorkflowRegistry: WorkflowRegistry;
32
+ /**
33
+ * The Workflows one environment's email worker is deployed with — `<project>-<env>-email-send` and
34
+ * `<project>-<env>-email-schedule`. Derived by the call {@link resolveEmailConfig} deploys with, so teardown
35
+ * deletes the names provision created and no others (#789). Deleting a Worker does not delete the Workflows
36
+ * registered against it.
37
+ */
38
+ export declare function emailWorkflowNames(project: string, env: ManagedEnvironment): string[];
32
39
  /**
33
40
  * The most one Cloudflare Worker variable holds. **Per variable, and that is the whole design.**
34
41
  *
@@ -1 +1 @@
1
- {"version":3,"file":"resolveEmailConfig.d.ts","sourceRoot":"","sources":["../../src/provision/resolveEmailConfig.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACtE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AAEzE,OAAO,KAAK,E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OAGG;IACH,WAAW,CAAC,EAAE,eAAe,CAAC;CAK/B;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,kBAAkB,CAChC,QAAQ,EAAE,2BAA2B,EACrC,MAAM,EAAE,iBAAiB,GACxB,2BAA2B,CAwD7B"}
@@ -34,6 +34,19 @@ const emailWorkflowRegistry = Object.fromEntries(Object.entries({
34
34
  }];
35
35
  }));
36
36
  /**
37
+ * The Workflows one environment's email worker is deployed with — `<project>-<env>-email-send` and
38
+ * `<project>-<env>-email-schedule`. Derived by the call {@link resolveEmailConfig} deploys with, so teardown
39
+ * deletes the names provision created and no others (#789). Deleting a Worker does not delete the Workflows
40
+ * registered against it.
41
+ */
42
+ function emailWorkflowNames(project, env) {
43
+ return hostWorkflowsFor(emailWorkflowRegistry, {
44
+ project,
45
+ capability: EMAIL_CAPABILITY,
46
+ env
47
+ }).workflows.map((workflow) => workflow.name);
48
+ }
49
+ /**
37
50
  * The most one Cloudflare Worker variable holds. **Per variable, and that is the whole design.**
38
51
  *
39
52
  * Cloudflare's documented limit is 5 KB per variable, on Free and Paid alike, and a Worker carries 64
@@ -131,4 +144,4 @@ function resolveEmailConfig(template, params) {
131
144
  });
132
145
  }
133
146
  //#endregion
134
- export { MAX_WORKER_VAR_BYTES, emailMessagesVars, emailWorkflowRegistry, resolveEmailConfig };
147
+ export { MAX_WORKER_VAR_BYTES, emailMessagesVars, emailWorkflowNames, emailWorkflowRegistry, resolveEmailConfig };
@@ -1 +1 @@
1
- {"version":3,"file":"settingsCheck.d.ts","sourceRoot":"","sources":["../../src/provision/settingsCheck.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,kBAAkB,EAInB,MAAM,wCAAwC,CAAC;AAMhD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAIrD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,uGAAuG;AACvG,MAAM,WAAW,kBAAkB;IACjC,qFAAqF;IACrF,WAAW,EAAE,MAAM,CAAC;IACpB,oEAAoE;IACpE,OAAO,EAAE,MAAM,CAAC;IAChB,iEAAiE;IACjE,KAAK,CAAC,EAAE,UAAU,CAAC;CACpB;AA2ND,wGAAwG;AACxG,wBAAgB,aAAa,CAAC,MAAM,EAAE,kBAAkB,GAAG,kBAAkB,CAK5E"}
1
+ {"version":3,"file":"settingsCheck.d.ts","sourceRoot":"","sources":["../../src/provision/settingsCheck.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,kBAAkB,EAInB,MAAM,wCAAwC,CAAC;AAOhD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAIrD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,uGAAuG;AACvG,MAAM,WAAW,kBAAkB;IACjC,qFAAqF;IACrF,WAAW,EAAE,MAAM,CAAC;IACpB,oEAAoE;IACpE,OAAO,EAAE,MAAM,CAAC;IAChB,iEAAiE;IACjE,KAAK,CAAC,EAAE,UAAU,CAAC;CACpB;AA6PD,wGAAwG;AACxG,wBAAgB,aAAa,CAAC,MAAM,EAAE,kBAAkB,GAAG,kBAAkB,CAS5E"}
@@ -1,8 +1,9 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { EMAIL_LINK_SIGNING_KEY, EMAIL_LINK_SIGNING_KEY_BINDING, emailSigningRegistry } from "../crypto/signingKey.js";
4
- import { emailHostEnv } from "../workflows/hostEnv.js";
4
+ import { EMAIL_PROVISION, emailHostEnv } from "../workflows/hostEnv.js";
5
5
  import { suppressionDatabaseName } from "./provisionEmail.js";
6
+ import { personDecision, pithyCommand, remedy, workerDirOf } from "@pithy-sh/core/src/cli/command";
6
7
  import { hostEnvFindings } from "@pithy-sh/core/src/capability/settings";
7
8
  import "@pithy-sh/core/src/naming/domains";
8
9
  import { environmentScope } from "@pithy-sh/core/src/naming/provisionScope";
@@ -54,13 +55,39 @@ function originOf(url) {
54
55
  * config object per Worker, so a `BASE_URL` that is not a URL is one edit however many environments a
55
56
  * project declares. Three lines about one key is how a report stops being read.
56
57
  */
57
- function localHostEnv(config) {
58
+ function localHostEnv(config, workerDirectory) {
58
59
  const candidate = {
59
60
  ...stubBindings(),
60
61
  BASE_URL: config.baseUrl,
61
62
  ...config.theme ? { EMAIL_THEME: JSON.stringify(config.theme) } : {}
62
63
  };
63
- return hostEnvFindings(checkHostEnv(emailHostEnv, candidate), null);
64
+ return hostEnvFindings(forWorker(checkHostEnv(emailHostEnv, candidate), workerDirectory), null);
65
+ }
66
+ /**
67
+ * **`pithy email provision` for the Worker this check ran for (#711).** It acts on one Worker, and in a project
68
+ * with several a bare one is refused `input/required`. Takes the Worker's `apps/` directory, which is what
69
+ * `--worker` takes and what that refusal lists. Not its `wrangler.jsonc` name: a scaffold deploys `apps/api` as
70
+ * `acme-api`.
71
+ */
72
+ function provisionCommand(workerDirectory) {
73
+ return pithyCommand("email provision", { flags: { "--worker": workerDirOf({ dir: workerDirectory }) } });
74
+ }
75
+ /**
76
+ * The host's own report, with its provisioning command named for this Worker by its `apps/` directory. The host
77
+ * writes the bare command into its log because it cannot know the Worker; a check that does know names it, in
78
+ * the action and the `fix` alike.
79
+ */
80
+ function forWorker(report, workerDirectory) {
81
+ return {
82
+ ...report,
83
+ problems: report.problems.map((problem) => problem.provider.command === EMAIL_PROVISION ? {
84
+ ...problem,
85
+ provider: {
86
+ ...problem.provider,
87
+ command: provisionCommand(workerDirectory)
88
+ }
89
+ } : problem)
90
+ };
64
91
  }
65
92
  /**
66
93
  * Whether a URL points at this machine — {@link LOCAL_ORIGIN} and every spelling of it, port or none.
@@ -141,7 +168,8 @@ async function accountFindings(config, context) {
141
168
  setting: "EMAIL_SUPPRESSIONS",
142
169
  environment: null,
143
170
  problem: `No D1 database named ${suppressions} exists on this account.`,
144
- action: "Run `pithy email provision`. Nothing is suppressed until it exists."
171
+ action: `Run \`${provisionCommand(context.workerDirectory)}\`. Nothing is suppressed until it exists.`,
172
+ fix: provisionCommand(context.workerDirectory)
145
173
  });
146
174
  for (const environment of context.environments) {
147
175
  if (environment.name === "dev") continue;
@@ -165,6 +193,8 @@ async function accountFindings(config, context) {
165
193
  * **What this sees:** a row under this registry name. A secret some other declaration moved off D1 has its
166
194
  * own check to write, or none; nothing here walks the vault for strays, because the vault cannot be listed.
167
195
  */
196
+ /** What creates a missing link-signing entry: a provision of every environment, production included (#711). */
197
+ const PROVISION_SECRETS = remedy("secrets provision");
168
198
  async function signingKeyFindings(context, environment) {
169
199
  const findings = [];
170
200
  const entry = environmentScope(context.project, environment).secretEntry(EMAIL_LINK_SIGNING_KEY, emailSigningRegistry[EMAIL_LINK_SIGNING_KEY].scope);
@@ -172,7 +202,8 @@ async function signingKeyFindings(context, environment) {
172
202
  setting: EMAIL_LINK_SIGNING_KEY,
173
203
  environment,
174
204
  problem: `The link-signing key has no Secrets Store entry in ${environment}, so no tracking or unsubscribe link can be signed.`,
175
- action: "Run `pithy secrets provision`."
205
+ action: PROVISION_SECRETS.say((command) => `Run \`${command}\`.`),
206
+ ...PROVISION_SECRETS.fix === void 0 ? {} : { fix: PROVISION_SECRETS.fix }
176
207
  });
177
208
  if (await context.account.vaultSecret({
178
209
  name: "email-link-signing-key",
@@ -181,7 +212,13 @@ async function signingKeyFindings(context, environment) {
181
212
  setting: EMAIL_LINK_SIGNING_KEY,
182
213
  environment,
183
214
  problem: `The link-signing key is still held in ${environment}'s D1 vault, where nothing reads it. Links signed with it before the move no longer verify.`,
184
- action: `Once the Secrets Store entry is bound and deployed, run \`pithy secrets rm ${EMAIL_LINK_SIGNING_KEY} --env ${environment} --backend d1\`. See docs/commands/secrets.md#moving-a-secret-off-d1.`
215
+ action: `Once the Secrets Store entry is bound and deployed, the D1 copy can go: ${personDecision("secrets rm", {
216
+ args: [EMAIL_LINK_SIGNING_KEY],
217
+ flags: {
218
+ "--env": environment,
219
+ "--backend": "d1"
220
+ }
221
+ })} See docs/commands/secrets.md#moving-a-secret-off-d1.`
185
222
  });
186
223
  return findings;
187
224
  }
@@ -189,7 +226,7 @@ async function signingKeyFindings(context, environment) {
189
226
  function emailSettings(config) {
190
227
  return {
191
228
  local: (context) => [
192
- ...localHostEnv(config),
229
+ ...localHostEnv(config, context.workerDirectory),
193
230
  ...localForAddress(config),
194
231
  ...localBaseUrlOrigin(config, context)
195
232
  ],
@@ -1,5 +1,6 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
+ import type { MeterCharge, MeterSubject } from "@pithy-sh/core/src/entitlement/meter";
3
4
  import type { EmailJobStatus, SendMode, SuppressionReason } from "../data/enums";
4
5
  import type { EmailDatabase, EmailSuppressionDatabase } from "../data/tables";
5
6
  import { type EmailMessageLayers } from "../templates/messages";
@@ -112,6 +113,16 @@ export interface EnqueueInput {
112
113
  inReplyTo?: string;
113
114
  /** The `References` chain, angle-bracketed and space-separated. Built by the caller from the parent. */
114
115
  references?: string;
116
+ /**
117
+ * Who this message is sent on behalf of, for the `emails` meter — the holder pair `@pithy-sh/payments`
118
+ * bills, `{ subjectType: "organization", subjectId }`.
119
+ *
120
+ * **Omit it and nothing is counted**, which is right for every message the kit sends on its own account: a
121
+ * magic link to somebody who has not signed up is not a tenant's usage. Name it on mail a customer's plan
122
+ * pays for — a campaign, a notification their workspace triggers — and, where the meter is enforced, an
123
+ * enqueue past the period's quota throws `payments/quota_exceeded` and writes no job.
124
+ */
125
+ subject?: MeterSubject;
115
126
  }
116
127
  /** Dependencies enqueue needs: the database, the from identity, optional send-Workflow binding, time, ids. */
117
128
  export interface EnqueueDeps {
@@ -139,6 +150,11 @@ export interface EnqueueDeps {
139
150
  * goes could not be consulted yet, which is strictly worse than queueing it.
140
151
  */
141
152
  suppressionDb?: EmailSuppressionDatabase;
153
+ /**
154
+ * Charge one email against the `emails` meter, or refuse — the composed provider's seam, closed over this
155
+ * request's env. Absent when no provider is composed, and then nothing is counted.
156
+ */
157
+ meter?: (charge: MeterCharge) => Promise<void>;
142
158
  now: Date;
143
159
  /** Generate a job id (a UUID in production). */
144
160
  newId: () => string;
@@ -1 +1 @@
1
- {"version":3,"file":"enqueue.d.ts","sourceRoot":"","sources":["../../src/send/enqueue.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACjF,OAAO,KAAK,EAAE,aAAa,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAG9E,OAAO,EAAE,KAAK,kBAAkB,EAAmC,MAAM,uBAAuB,CAAC;AACjG,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAMrD;;;;;;;;;;;;;;;;;;;GAmBG;AAEH;;;;;;;;;;GAUG;AACH,MAAM,WAAW,mBAAmB;IAClC,MAAM,CAAC,OAAO,EAAE;QAAE,EAAE,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE;YAAE,MAAM,EAAE,MAAM,EAAE,CAAA;SAAE,CAAA;KAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAClF;AAED,oDAAoD;AACpD,MAAM,WAAW,YAAY;IAC3B,6BAA6B;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,0CAA0C;IAC1C,QAAQ,EAAE,MAAM,CAAC;IACjB,qFAAqF;IACrF,OAAO,EAAE,OAAO,CAAC;IACjB,0CAA0C;IAC1C,IAAI,CAAC,EAAE,QAAQ,CAAC;IAChB,uDAAuD;IACvD,MAAM,CAAC,EAAE,IAAI,CAAC;IACd,qEAAqE;IACrE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,0DAA0D;IAC1D,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,kDAAkD;IAClD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;;;;;;;;OAYG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;;;;;;;;;;OAaG;IACH,WAAW,CAAC,EAAE,MA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
  * exist.
90
90
  */
91
91
  const batchId = sender ? (deps.newBatchId ?? mintBatchId)() : null;
92
+ /**
93
+ * Charge the `emails` meter **before the row exists**, so a refusal writes no job — and only for a message
94
+ * that is going to be sent. A withheld recipient costs the customer nothing, and a message the kit sends
95
+ * on nobody's account names no subject and is never counted.
96
+ *
97
+ * Before the insert rather than after it, and the cost is the right way round: an insert that fails after
98
+ * a charge over-counts by one, and over-counting briefly is recoverable where under-counting is not.
99
+ */
100
+ if (!blocked && input.subject !== void 0 && deps.meter !== void 0) await deps.meter({
101
+ subject: input.subject,
102
+ meter: "emails",
103
+ amount: 1,
104
+ now: deps.now
105
+ });
92
106
  const marketing = template.category === "marketing";
93
107
  const job = {
94
108
  id: deps.newId(),