@pithy-sh/email 0.1.1 → 0.1.3

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 (176) hide show
  1. package/dist/analytics.d.ts +19 -0
  2. package/dist/analytics.d.ts.map +1 -0
  3. package/dist/analytics.js +13 -0
  4. package/dist/audit/actions.d.ts +45 -0
  5. package/dist/audit/actions.d.ts.map +1 -0
  6. package/dist/audit/actions.js +45 -0
  7. package/dist/bounce/classify.d.ts +38 -0
  8. package/dist/bounce/classify.d.ts.map +1 -0
  9. package/dist/bounce/classify.js +46 -0
  10. package/dist/bounce/handler.d.ts +32 -0
  11. package/dist/bounce/handler.d.ts.map +1 -0
  12. package/dist/bounce/handler.js +81 -0
  13. package/dist/capability.d.ts +158 -0
  14. package/dist/capability.d.ts.map +1 -0
  15. package/dist/capability.js +255 -0
  16. package/dist/crypto/signingKey.d.ts +36 -0
  17. package/dist/crypto/signingKey.d.ts.map +1 -0
  18. package/dist/crypto/signingKey.js +36 -0
  19. package/dist/crypto/token.d.ts +47 -0
  20. package/dist/crypto/token.d.ts.map +1 -0
  21. package/dist/crypto/token.js +99 -0
  22. package/dist/data/emailEvent.d.ts +28 -0
  23. package/dist/data/emailEvent.d.ts.map +1 -0
  24. package/dist/data/emailEvent.js +22 -0
  25. package/dist/data/emailJob.d.ts +76 -0
  26. package/dist/data/emailJob.d.ts.map +1 -0
  27. package/dist/data/emailJob.js +62 -0
  28. package/dist/data/emailSuppression.d.ts +23 -0
  29. package/dist/data/emailSuppression.d.ts.map +1 -0
  30. package/dist/data/emailSuppression.js +21 -0
  31. package/dist/data/enums.d.ts +76 -0
  32. package/dist/data/enums.d.ts.map +1 -0
  33. package/dist/data/enums.js +65 -0
  34. package/dist/data/tables.d.ts +114 -0
  35. package/dist/data/tables.d.ts.map +1 -0
  36. package/dist/data/tables.js +30 -0
  37. package/dist/error/errors.d.ts +60 -0
  38. package/dist/error/errors.d.ts.map +1 -0
  39. package/dist/error/errors.js +82 -0
  40. package/dist/http/callbacks.d.ts +21 -0
  41. package/dist/http/callbacks.d.ts.map +1 -0
  42. package/dist/http/callbacks.js +110 -0
  43. package/dist/http/guards.d.ts +99 -0
  44. package/dist/http/guards.d.ts.map +1 -0
  45. package/dist/http/guards.js +144 -0
  46. package/dist/http/responses.d.ts +295 -0
  47. package/dist/http/responses.d.ts.map +1 -0
  48. package/dist/http/responses.js +115 -0
  49. package/dist/http/routes.d.ts +71 -0
  50. package/dist/http/routes.d.ts.map +1 -0
  51. package/dist/http/routes.js +292 -0
  52. package/dist/http/schemas.d.ts +90 -0
  53. package/dist/http/schemas.d.ts.map +1 -0
  54. package/dist/http/schemas.js +91 -0
  55. package/dist/http/view.d.ts +78 -0
  56. package/dist/http/view.d.ts.map +1 -0
  57. package/dist/http/view.js +130 -0
  58. package/dist/index.d.ts +46 -0
  59. package/dist/index.d.ts.map +1 -0
  60. package/dist/index.js +11 -0
  61. package/dist/jobs/read.d.ts +191 -0
  62. package/dist/jobs/read.d.ts.map +1 -0
  63. package/dist/jobs/read.js +143 -0
  64. package/dist/jobs/retry.d.ts +99 -0
  65. package/dist/jobs/retry.d.ts.map +1 -0
  66. package/dist/jobs/retry.js +67 -0
  67. package/dist/migrations/0001_init.d.ts +32 -0
  68. package/dist/migrations/0001_init.d.ts.map +1 -0
  69. package/dist/migrations/0001_init.js +60 -0
  70. package/dist/migrations/0001_suppressions.d.ts +10 -0
  71. package/dist/migrations/0001_suppressions.d.ts.map +1 -0
  72. package/dist/migrations/0001_suppressions.js +20 -0
  73. package/dist/provision/devDelivery.d.ts +32 -0
  74. package/dist/provision/devDelivery.d.ts.map +1 -0
  75. package/dist/provision/devDelivery.js +37 -0
  76. package/dist/provision/hostCatalogs.d.ts +10 -0
  77. package/dist/provision/hostCatalogs.d.ts.map +1 -0
  78. package/dist/provision/hostCatalogs.js +78 -0
  79. package/dist/provision/provisionEmail.d.ts +143 -0
  80. package/dist/provision/provisionEmail.d.ts.map +1 -0
  81. package/dist/provision/provisionEmail.js +118 -0
  82. package/dist/provision/resolveEmailConfig.d.ts +122 -0
  83. package/dist/provision/resolveEmailConfig.d.ts.map +1 -0
  84. package/dist/provision/resolveEmailConfig.js +124 -0
  85. package/dist/provision/settingsCheck.d.ts +40 -0
  86. package/dist/provision/settingsCheck.d.ts.map +1 -0
  87. package/dist/provision/settingsCheck.js +138 -0
  88. package/dist/send/batchIdentity.d.ts +42 -0
  89. package/dist/send/batchIdentity.d.ts.map +1 -0
  90. package/dist/send/batchIdentity.js +46 -0
  91. package/dist/send/enqueue.d.ts +216 -0
  92. package/dist/send/enqueue.d.ts.map +1 -0
  93. package/dist/send/enqueue.js +153 -0
  94. package/dist/send/errorMapping.d.ts +27 -0
  95. package/dist/send/errorMapping.d.ts.map +1 -0
  96. package/dist/send/errorMapping.js +52 -0
  97. package/dist/send/events.d.ts +15 -0
  98. package/dist/send/events.d.ts.map +1 -0
  99. package/dist/send/events.js +17 -0
  100. package/dist/send/fromComposition.d.ts +47 -0
  101. package/dist/send/fromComposition.d.ts.map +1 -0
  102. package/dist/send/fromComposition.js +53 -0
  103. package/dist/send/retryPolicy.d.ts +32 -0
  104. package/dist/send/retryPolicy.d.ts.map +1 -0
  105. package/dist/send/retryPolicy.js +39 -0
  106. package/dist/send/runSend.d.ts +106 -0
  107. package/dist/send/runSend.d.ts.map +1 -0
  108. package/dist/send/runSend.js +218 -0
  109. package/dist/send/sendAt.d.ts +6 -0
  110. package/dist/send/sendAt.d.ts.map +1 -0
  111. package/dist/send/sendAt.js +62 -0
  112. package/dist/send/sender.d.ts +42 -0
  113. package/dist/send/sender.d.ts.map +1 -0
  114. package/dist/send/sender.js +0 -0
  115. package/dist/send/senderBinding.d.ts +44 -0
  116. package/dist/send/senderBinding.d.ts.map +1 -0
  117. package/dist/send/senderBinding.js +21 -0
  118. package/dist/send/suppression.d.ts +93 -0
  119. package/dist/send/suppression.d.ts.map +1 -0
  120. package/dist/send/suppression.js +132 -0
  121. package/dist/templates/engine.d.ts +109 -0
  122. package/dist/templates/engine.d.ts.map +1 -0
  123. package/dist/templates/engine.js +258 -0
  124. package/dist/templates/messages.d.ts +94 -0
  125. package/dist/templates/messages.d.ts.map +1 -0
  126. package/dist/templates/messages.es.d.ts +29 -0
  127. package/dist/templates/messages.es.d.ts.map +1 -0
  128. package/dist/templates/messages.es.js +82 -0
  129. package/dist/templates/messages.js +266 -0
  130. package/dist/templates/partials.d.ts +5 -0
  131. package/dist/templates/partials.d.ts.map +1 -0
  132. package/dist/templates/partials.js +59 -0
  133. package/dist/templates/precompiled.generated.d.ts +266 -0
  134. package/dist/templates/precompiled.generated.d.ts.map +1 -0
  135. package/dist/templates/precompiled.generated.js +4039 -0
  136. package/dist/templates/registry.d.ts +118 -0
  137. package/dist/templates/registry.d.ts.map +1 -0
  138. package/dist/templates/registry.js +323 -0
  139. package/dist/templates/samples.d.ts +7 -0
  140. package/dist/templates/samples.d.ts.map +1 -0
  141. package/dist/templates/samples.js +98 -0
  142. package/dist/templates/severity.d.ts +40 -0
  143. package/dist/templates/severity.d.ts.map +1 -0
  144. package/dist/templates/severity.js +81 -0
  145. package/dist/templates/theme.d.ts +193 -0
  146. package/dist/templates/theme.d.ts.map +1 -0
  147. package/dist/templates/theme.js +168 -0
  148. package/dist/version.generated.d.ts +5 -0
  149. package/dist/version.generated.d.ts.map +1 -0
  150. package/dist/version.generated.js +7 -0
  151. package/dist/workflows/hostApp.d.ts +33 -0
  152. package/dist/workflows/hostApp.d.ts.map +1 -0
  153. package/dist/workflows/hostApp.js +19 -0
  154. package/dist/workflows/hostEnv.d.ts +129 -0
  155. package/dist/workflows/hostEnv.d.ts.map +1 -0
  156. package/dist/workflows/hostEnv.js +147 -0
  157. package/dist/workflows/instanceLiveness.d.ts +3 -0
  158. package/dist/workflows/instanceLiveness.d.ts.map +1 -0
  159. package/dist/workflows/instanceLiveness.js +37 -0
  160. package/dist/workflows/instances.d.ts +18 -0
  161. package/dist/workflows/instances.d.ts.map +1 -0
  162. package/dist/workflows/instances.js +0 -0
  163. package/dist/workflows/params.d.ts +23 -0
  164. package/dist/workflows/params.d.ts.map +1 -0
  165. package/dist/workflows/params.js +21 -0
  166. package/dist/workflows/scheduler.d.ts +82 -0
  167. package/dist/workflows/scheduler.d.ts.map +1 -0
  168. package/dist/workflows/scheduler.js +111 -0
  169. package/dist/workflows/sendBatch.d.ts +85 -0
  170. package/dist/workflows/sendBatch.d.ts.map +1 -0
  171. package/dist/workflows/sendBatch.js +50 -0
  172. package/dist/workflows/worker.d.ts +100 -0
  173. package/dist/workflows/worker.d.ts.map +1 -0
  174. package/dist/workflows/worker.js +117 -0
  175. package/package.json +22 -11
  176. package/src/version.generated.ts +1 -1
@@ -0,0 +1,52 @@
1
+ import { EmailRateLimitedError, EmailSendFailedError, EmailSuppressedError } from "../error/errors.js";
2
+ //#region src/send/errorMapping.ts
3
+ /** Codes the Email Service retries past — rate, daily quota, and transient delivery/server faults. */
4
+ const RETRYABLE = /* @__PURE__ */ new Set([
5
+ "E_RATE_LIMIT_EXCEEDED",
6
+ "E_DAILY_LIMIT_EXCEEDED",
7
+ "E_DELIVERY_FAILED",
8
+ "E_INTERNAL_SERVER_ERROR"
9
+ ]);
10
+ /** Rate/quota codes map to the dedicated 429 error so the cause reads clearly in logs. */
11
+ const RATE_LIMITED = /* @__PURE__ */ new Set(["E_RATE_LIMIT_EXCEEDED", "E_DAILY_LIMIT_EXCEEDED"]);
12
+ /** Read a thrown value's `.code`/`.message` without assuming its shape. */
13
+ function readError(err) {
14
+ if (err && typeof err === "object") return {
15
+ code: "code" in err && typeof err.code === "string" ? err.code : "E_UNKNOWN",
16
+ message: "message" in err && typeof err.message === "string" ? err.message : ""
17
+ };
18
+ return {
19
+ code: "E_UNKNOWN",
20
+ message: typeof err === "string" ? err : ""
21
+ };
22
+ }
23
+ /**
24
+ * Classify a send failure. `E_RECIPIENT_SUPPRESSED` is terminal and means the address must be
25
+ * suppressed locally too; rate/quota and transient delivery codes are retryable; everything else
26
+ * (validation, sender, content, headers) is terminal. An unknown code is treated as a transient
27
+ * failure so a momentary fault gets one bounded retry rather than failing the job outright.
28
+ */
29
+ function classifySendError(err) {
30
+ const { code, message } = readError(err);
31
+ const detail = `email send failed: ${code}${message ? ` — ${message}` : ""}`;
32
+ if (code === "E_RECIPIENT_SUPPRESSED") return {
33
+ code,
34
+ retryable: false,
35
+ suppressed: true,
36
+ error: new EmailSuppressedError({ detail }, { cause: err })
37
+ };
38
+ if (RATE_LIMITED.has(code)) return {
39
+ code,
40
+ retryable: true,
41
+ suppressed: false,
42
+ error: new EmailRateLimitedError({ detail }, { cause: err })
43
+ };
44
+ return {
45
+ code,
46
+ retryable: RETRYABLE.has(code) || code === "E_UNKNOWN",
47
+ suppressed: false,
48
+ error: new EmailSendFailedError({ detail }, { cause: err })
49
+ };
50
+ }
51
+ //#endregion
52
+ export { classifySendError };
@@ -0,0 +1,15 @@
1
+ import type { EmailEventType } from "../data/enums";
2
+ import type { EmailDatabase } from "../data/tables";
3
+ /** A per-recipient event to append to `pithy_email_events`. */
4
+ export interface EventInput {
5
+ jobId: string;
6
+ recipient: string;
7
+ type: EmailEventType;
8
+ linkLabel?: string | null;
9
+ linkUrl?: string | null;
10
+ campaignId?: string | null;
11
+ detail?: string | null;
12
+ }
13
+ /** Append one event row. The history/attribution log written by the send path, callbacks, and bounce handler. */
14
+ export declare function recordEvent(db: EmailDatabase, event: EventInput, now: Date): Promise<void>;
15
+ //# sourceMappingURL=events.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../../src/send/events.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAEpD,+DAA+D;AAC/D,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,cAAc,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACxB;AAED,iHAAiH;AACjH,wBAAsB,WAAW,CAAC,EAAE,EAAE,aAAa,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAchG"}
@@ -0,0 +1,17 @@
1
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
2
+ //#region src/send/events.ts
3
+ /** Append one event row. The history/attribution log written by the send path, callbacks, and bounce handler. */
4
+ async function recordEvent(db, event, now) {
5
+ await db.insertInto("pithyEmailEvents").values({
6
+ jobId: event.jobId,
7
+ recipient: event.recipient,
8
+ type: event.type,
9
+ linkLabel: event.linkLabel ?? null,
10
+ linkUrl: event.linkUrl ?? null,
11
+ campaignId: event.campaignId ?? null,
12
+ detail: event.detail ?? null,
13
+ createdAt: SQLiteDate.encode(now)
14
+ }).execute();
15
+ }
16
+ //#endregion
17
+ export { recordEvent };
@@ -0,0 +1,47 @@
1
+ import { type EmailCapability, type EmailEnqueueEnv } from "../capability";
2
+ import type { EnqueueInput, EnqueueResult } from "./enqueue";
3
+ /**
4
+ * Sending mail from a Workflow (pithy-sh/pithy#356).
5
+ *
6
+ * A route reaches `enqueue` through the `compose` hook, and should keep doing that — it is typed, it is
7
+ * explicit, and it does not depend on module load order. **A Workflow class has no such route.** The
8
+ * runtime constructs it with the worker `env` and nothing else, `enqueue` is a closure rather than a
9
+ * binding, and Workflow params are serialized so a closure cannot travel in one either. Until this
10
+ * existed, a durable job could not send mail without rebuilding the sending identity from `env` — the
11
+ * same from-address in a second place, free to drift from `pithy.config.ts` — which is exactly what this
12
+ * capability's own doc asks consumers not to do.
13
+ *
14
+ * So: one function, taking the env a Workflow already has, restating nothing.
15
+ *
16
+ * ```ts
17
+ * export class RotationWorkflow extends WorkflowEntrypoint<Env, RotationParams> {
18
+ * override async run(event: WorkflowEvent<RotationParams>, step: WorkflowStep) {
19
+ * await step.do("notify", async () => {
20
+ * await enqueueFromEnv(this.env, { to, template: "operationalNotice", payload });
21
+ * });
22
+ * }
23
+ * }
24
+ * ```
25
+ *
26
+ * The Workflow class must be exported from the same worker entrypoint that calls `createBackend` —
27
+ * which Cloudflare requires anyway — so the composition has already happened in this isolate by the time
28
+ * a step body runs. Where it has not, this raises a wiring fault naming what to compose rather than
29
+ * sending mail as some invented identity.
30
+ */
31
+ /**
32
+ * The composed email capability, or a raised wiring fault.
33
+ *
34
+ * Narrowed by `isEmailCapability`, the capability's own guard, so a capability composed under the name
35
+ * `email` but carrying no seams is caught here rather than at a call site whose `enqueue` is undefined.
36
+ */
37
+ export declare function composedEmail(): EmailCapability;
38
+ /**
39
+ * Enqueue an email from a worker env alone — the seam a Workflow step uses.
40
+ *
41
+ * Identical in every respect to `EmailCapability.enqueue`, because it *is* that function: the
42
+ * from-identity, the theme, the bindings and the automatic suppression check (pithy-sh/pithy#355) all
43
+ * come from the one composed capability. Nothing about a durable send differs from a request-time one
44
+ * except how the caller got here.
45
+ */
46
+ export declare function enqueueFromEnv(env: EmailEnqueueEnv, input: EnqueueInput): Promise<EnqueueResult>;
47
+ //# sourceMappingURL=fromComposition.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fromComposition.d.ts","sourceRoot":"","sources":["../../src/send/fromComposition.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,eAAe,EAAE,KAAK,eAAe,EAAqB,MAAM,eAAe,CAAC;AAC9F,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH;;;;;GAKG;AACH,wBAAgB,aAAa,IAAI,eAAe,CAE/C;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,eAAe,EAAE,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,aAAa,CAAC,CAEhG"}
@@ -0,0 +1,53 @@
1
+ import { isEmailCapability } from "../capability.js";
2
+ import { composedCapability } from "@pithy-sh/core/src/capability/composition";
3
+ //#region src/send/fromComposition.ts
4
+ /**
5
+ * Sending mail from a Workflow (pithy-sh/pithy#356).
6
+ *
7
+ * A route reaches `enqueue` through the `compose` hook, and should keep doing that — it is typed, it is
8
+ * explicit, and it does not depend on module load order. **A Workflow class has no such route.** The
9
+ * runtime constructs it with the worker `env` and nothing else, `enqueue` is a closure rather than a
10
+ * binding, and Workflow params are serialized so a closure cannot travel in one either. Until this
11
+ * existed, a durable job could not send mail without rebuilding the sending identity from `env` — the
12
+ * same from-address in a second place, free to drift from `pithy.config.ts` — which is exactly what this
13
+ * capability's own doc asks consumers not to do.
14
+ *
15
+ * So: one function, taking the env a Workflow already has, restating nothing.
16
+ *
17
+ * ```ts
18
+ * export class RotationWorkflow extends WorkflowEntrypoint<Env, RotationParams> {
19
+ * override async run(event: WorkflowEvent<RotationParams>, step: WorkflowStep) {
20
+ * await step.do("notify", async () => {
21
+ * await enqueueFromEnv(this.env, { to, template: "operationalNotice", payload });
22
+ * });
23
+ * }
24
+ * }
25
+ * ```
26
+ *
27
+ * The Workflow class must be exported from the same worker entrypoint that calls `createBackend` —
28
+ * which Cloudflare requires anyway — so the composition has already happened in this isolate by the time
29
+ * a step body runs. Where it has not, this raises a wiring fault naming what to compose rather than
30
+ * sending mail as some invented identity.
31
+ */
32
+ /**
33
+ * The composed email capability, or a raised wiring fault.
34
+ *
35
+ * Narrowed by `isEmailCapability`, the capability's own guard, so a capability composed under the name
36
+ * `email` but carrying no seams is caught here rather than at a call site whose `enqueue` is undefined.
37
+ */
38
+ function composedEmail() {
39
+ return composedCapability("email", isEmailCapability);
40
+ }
41
+ /**
42
+ * Enqueue an email from a worker env alone — the seam a Workflow step uses.
43
+ *
44
+ * Identical in every respect to `EmailCapability.enqueue`, because it *is* that function: the
45
+ * from-identity, the theme, the bindings and the automatic suppression check (pithy-sh/pithy#355) all
46
+ * come from the one composed capability. Nothing about a durable send differs from a request-time one
47
+ * except how the caller got here.
48
+ */
49
+ function enqueueFromEnv(env, input) {
50
+ return composedEmail().enqueue(env, input);
51
+ }
52
+ //#endregion
53
+ export { composedEmail, enqueueFromEnv };
@@ -0,0 +1,32 @@
1
+ import type { WorkflowRetryPolicy } from "@pithy-sh/core/src/workflow/faults";
2
+ /**
3
+ * **What a send retries, and what it refuses to.**
4
+ *
5
+ * Email already classified the *provider's* vocabulary — `errorMapping.ts` maps every `E_*` code the
6
+ * Email Service returns to retryable or terminal, and says why. This is the other half: the same
7
+ * decision in the form the durable step reads, covering the faults that never came from the binding at
8
+ * all (pithy-sh/pithy#338).
9
+ *
10
+ * ## Retryable
11
+ *
12
+ * - **`email/rate_limited`** — the per-second or daily quota. The next window is a different answer.
13
+ * - **`email/send_failed`** — raised by `runSend` **only** when `classifySendError` judged the code
14
+ * transient (`E_DELIVERY_FAILED`, `E_INTERNAL_SERVER_ERROR`, or an unknown code getting its one
15
+ * bounded retry). A validation, sender, or content code takes the terminal branch there and never
16
+ * reaches a throw, which is why this entry is not the hole it looks like — and `retryPolicy.test.ts`
17
+ * holds the two classifications to each other rather than trusting this sentence.
18
+ * - **A transient D1 fault** — the jobs, events and suppression tables. Classified in core.
19
+ *
20
+ * ## Terminal
21
+ *
22
+ * - **`core/not_found`** — the job row is gone. A send cannot invent the message it was asked to send,
23
+ * and a deleted row does not come back over a backoff.
24
+ * - **`email/template_not_found`, `email/invalid_payload`** — a render that cannot be attempted twice
25
+ * with a different result.
26
+ * - **Anything unclassified**, including a payload that will not parse.
27
+ *
28
+ * A suppressed recipient is neither: `runSend` records it and returns, because a person who asked not to
29
+ * be mailed is an outcome rather than a failure.
30
+ */
31
+ export declare const emailWorkflowRetry: WorkflowRetryPolicy;
32
+ //# sourceMappingURL=retryPolicy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retryPolicy.d.ts","sourceRoot":"","sources":["../../src/send/retryPolicy.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AAE9E;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,eAAO,MAAM,kBAAkB,EAAE,mBAOhC,CAAC"}
@@ -0,0 +1,39 @@
1
+ //#region src/send/retryPolicy.ts
2
+ /**
3
+ * **What a send retries, and what it refuses to.**
4
+ *
5
+ * Email already classified the *provider's* vocabulary — `errorMapping.ts` maps every `E_*` code the
6
+ * Email Service returns to retryable or terminal, and says why. This is the other half: the same
7
+ * decision in the form the durable step reads, covering the faults that never came from the binding at
8
+ * all (pithy-sh/pithy#338).
9
+ *
10
+ * ## Retryable
11
+ *
12
+ * - **`email/rate_limited`** — the per-second or daily quota. The next window is a different answer.
13
+ * - **`email/send_failed`** — raised by `runSend` **only** when `classifySendError` judged the code
14
+ * transient (`E_DELIVERY_FAILED`, `E_INTERNAL_SERVER_ERROR`, or an unknown code getting its one
15
+ * bounded retry). A validation, sender, or content code takes the terminal branch there and never
16
+ * reaches a throw, which is why this entry is not the hole it looks like — and `retryPolicy.test.ts`
17
+ * holds the two classifications to each other rather than trusting this sentence.
18
+ * - **A transient D1 fault** — the jobs, events and suppression tables. Classified in core.
19
+ *
20
+ * ## Terminal
21
+ *
22
+ * - **`core/not_found`** — the job row is gone. A send cannot invent the message it was asked to send,
23
+ * and a deleted row does not come back over a backoff.
24
+ * - **`email/template_not_found`, `email/invalid_payload`** — a render that cannot be attempted twice
25
+ * with a different result.
26
+ * - **Anything unclassified**, including a payload that will not parse.
27
+ *
28
+ * A suppressed recipient is neither: `runSend` records it and returns, because a person who asked not to
29
+ * be mailed is an outcome rather than a failure.
30
+ */
31
+ const emailWorkflowRetry = {
32
+ capability: "email",
33
+ retryable: {
34
+ "email/rate_limited": "The send was over a rate or daily quota; the next window admits it.",
35
+ "email/send_failed": "Only thrown for a code classifySendError judged transient — delivery, an upstream 5xx, or one bounded retry of an unknown code."
36
+ }
37
+ };
38
+ //#endregion
39
+ export { emailWorkflowRetry };
@@ -0,0 +1,106 @@
1
+ import type { EmailJobStatus, SuppressionReason } from "../data/enums";
2
+ import type { EmailDatabase, EmailSuppressionDatabase } from "../data/tables";
3
+ import { type EmailMessageLayers } from "../templates/messages";
4
+ import type { EmailTheme } from "../templates/theme";
5
+ import type { EmailSender } from "./sender";
6
+ /**
7
+ * Send one job — the body the send Workflow runs inside a durable step. Never called from a request
8
+ * handler. It loads the job, skips a suppressed recipient, renders (with tracking per the job's flags),
9
+ * sends through the binding, and records the outcome on the row plus an event. On a retryable failure
10
+ * it throws (the Workflow step retries with backoff) until `maxAttempts`, then marks the job failed.
11
+ *
12
+ * **Whether a suppression applies depends on the message.** The kind comes from the template, not from
13
+ * the job row and not from a caller, so a magic link is transactional by declaration and an unrelated
14
+ * unsubscribe cannot swallow it.
15
+ *
16
+ * **A delivered job's inputs are dropped here, and "delivered" is the only place they can be.** The
17
+ * payload of a magic link *is* the sign-in link, so a row that keeps it after the message is out is a
18
+ * second, permanent copy of a live credential in a table nobody thinks of as holding secrets — which is
19
+ * what made an adopter's digested invitation token worth nothing the moment it was mailed. The line is
20
+ * `sent`, and every other outcome keeps its payload on purpose: `failed` can be retried, `suppressed`
21
+ * can be unblocked, and a payload dropped before the last attempt is a message that cannot be resent —
22
+ * a worse failure than the one being fixed. `sent` is the one status a retry is *already* refused for,
23
+ * because the mail has gone to a real person, so nothing here can ever need those inputs again.
24
+ */
25
+ /** The current signing key plus the valid version set, for minting tracking/unsubscribe links. */
26
+ export interface SendSigning {
27
+ /** The current signing key value. */
28
+ key: string;
29
+ /** The current signing key version, recorded as the token `kid`. */
30
+ kid: string;
31
+ }
32
+ /** Everything a send needs that isn't on the job row. */
33
+ export interface SendDeps {
34
+ /** The per-environment jobs/events database. */
35
+ db: EmailDatabase;
36
+ /** The global, shared suppression database — checked before every send, fed by bounces/complaints. */
37
+ suppressionDb: EmailSuppressionDatabase;
38
+ sender: EmailSender;
39
+ theme: EmailTheme;
40
+ /**
41
+ * Where the words for a locale come from.
42
+ *
43
+ * The host that runs this is a standalone Worker — nothing composes capabilities inside it — so it
44
+ * cannot be handed a composed project's layers the way the app worker's enqueue is. It reads the
45
+ * catalogs off its own env instead (`EMAIL_MESSAGES`) and turns them into this. Absent walks the
46
+ * kit's English, which is what a project that never opted into a second language gets.
47
+ */
48
+ layersFor?: EmailMessageLayers;
49
+ /** The public base URL for callback links. */
50
+ baseUrl: string;
51
+ /** The signing key for tracking/unsubscribe links. Absent disables tracking (and blocks marketing sends). */
52
+ signing?: SendSigning;
53
+ /** How long a tracked link stays valid. */
54
+ linkTtlDays: number;
55
+ /** The most attempts before a retryable failure becomes terminal. */
56
+ maxAttempts: number;
57
+ /** This worker's environment name, stamped on each send (X-Pithy-Env) so the single inbound worker can route. */
58
+ environment?: string;
59
+ /**
60
+ * When this pass began — **stable across a Workflow resume** (pithy-sh/pithy#327).
61
+ *
62
+ * Everything that dates the work reads this: `sentAt`, the redaction stamp, the events, and how long a
63
+ * tracked link stays valid. A driver body re-executes from the top on a resume, so a clock read there
64
+ * answers with the resume — and a batch that backed off overnight dated its remaining jobs, and the
65
+ * expiry of every link in them, a day late. `runSendBatch` journals this in a step so a resume reads
66
+ * back the instant the batch began.
67
+ *
68
+ * A link minted on the resumed half expires from the pass, not from the mint. Two people in one batch
69
+ * are promised the same window; which attempt happened to render their message is not something they
70
+ * can see and not something their link should depend on.
71
+ */
72
+ passStartedAt: Date;
73
+ /**
74
+ * "This job is being worked on, now" — **read fresh on every call**, and never journaled.
75
+ *
76
+ * This is not a stamp with a tidier name. `updatedAt` is the scheduler's only evidence that a `sending`
77
+ * job is alive: `runScheduler` claims and re-drives anything in `sending` older than `stuckMs`, on the
78
+ * assumption its dispatch died. Freeze it and a batch that resumes past that window reports the job it
79
+ * is actively retrying as stranded, so the next tick starts a second send Workflow against it — and
80
+ * `runSend` short-circuits only a job already `sent`, so both attempts render and both call `send`. One
81
+ * person, two emails. A sweep journaled the single `now` this replaced and was reverted for exactly
82
+ * that.
83
+ *
84
+ * The suppression liveness read takes it too, because "is this address blocked *right now*" is a
85
+ * present-tense question and an hour-old answer to it is simply wrong.
86
+ */
87
+ heartbeatAt: () => Date;
88
+ }
89
+ /** The outcome of a send attempt. */
90
+ export interface SendOutcome {
91
+ jobId: string;
92
+ status: EmailJobStatus;
93
+ messageId?: string;
94
+ skipped?: boolean;
95
+ /**
96
+ * Why nothing was sent, when the recipient was on the suppression list.
97
+ *
98
+ * A skipped send has to be reported, not swallowed. Without this the caller sees an outcome that is
99
+ * not `failed` and the person sees an empty inbox, which is what made the whole class of bug invisible
100
+ * from both ends. "Suppressed" alone is not enough either — an operator deciding what to do next needs
101
+ * to know whether the address bounced, complained, or opted out.
102
+ */
103
+ suppressionReason?: SuppressionReason;
104
+ }
105
+ export declare function runSend(deps: SendDeps, jobId: string): Promise<SendOutcome>;
106
+ //# sourceMappingURL=runSend.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runSend.d.ts","sourceRoot":"","sources":["../../src/send/runSend.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACvE,OAAO,KAAK,EAAE,aAAa,EAAE,wBAAwB,EAAe,MAAM,gBAAgB,CAAC;AAE3F,OAAO,EAAE,KAAK,kBAAkB,EAAmC,MAAM,uBAAuB,CAAC;AACjG,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAGrD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAG5C;;;;;;;;;;;;;;;;;;GAkBG;AAEH,kGAAkG;AAClG,MAAM,WAAW,WAAW;IAC1B,qCAAqC;IACrC,GAAG,EAAE,MAAM,CAAC;IACZ,oEAAoE;IACpE,GAAG,EAAE,MAAM,CAAC;CACb;AAED,yDAAyD;AACzD,MAAM,WAAW,QAAQ;IACvB,gDAAgD;IAChD,EAAE,EAAE,aAAa,CAAC;IAClB,sGAAsG;IACtG,aAAa,EAAE,wBAAwB,CAAC;IACxC,MAAM,EAAE,WAAW,CAAC;IACpB,KAAK,EAAE,UAAU,CAAC;IAClB;;;;;;;OAOG;IACH,SAAS,CAAC,EAAE,kBAAkB,CAAC;IAC/B,8CAA8C;IAC9C,OAAO,EAAE,MAAM,CAAC;IAChB,6GAA6G;IAC7G,OAAO,CAAC,EAAE,WAAW,CAAC;IACtB,2CAA2C;IAC3C,WAAW,EAAE,MAAM,CAAC;IACpB,qEAAqE;IACrE,WAAW,EAAE,MAAM,CAAC;IACpB,iHAAiH;IACjH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;;;;;;;;OAYG;IACH,aAAa,EAAE,IAAI,CAAC;IACpB;;;;;;;;;;;;;OAaG;IACH,WAAW,EAAE,MAAM,IAAI,CAAC;CACzB;AAED,qCAAqC;AACrC,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,cAAc,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;;;;;;OAOG;IACH,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;CACvC;AAuBD,wBAAsB,OAAO,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAgLjF"}
@@ -0,0 +1,218 @@
1
+ import { EmailJob, SPENT_PAYLOAD } from "../data/emailJob.js";
2
+ import { recordEvent } from "./events.js";
3
+ import { blockingSuppression, suppress } from "./suppression.js";
4
+ import { emailTranslator, kitEmailLayers } from "../templates/messages.js";
5
+ import { redactsPayloadOnDelivery, renderEmail, templateKind } from "../templates/engine.js";
6
+ import { classifySendError } from "./errorMapping.js";
7
+ import { NotFoundError } from "@pithy-sh/core/src/error/pithyError";
8
+ import { normalizeAddress } from "@pithy-sh/core/src/address/address";
9
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
10
+ //#region src/send/runSend.ts
11
+ const DAY_MS = 864e5;
12
+ /**
13
+ * Patch a job row by id, always bumping `updatedAt` — **on the heartbeat clock, not the pass instant.**
14
+ *
15
+ * Every write this function makes is also a statement that the job is still being worked on, because
16
+ * `updatedAt` is what the scheduler's `sending` re-drive reads. That is why the bump is here rather than
17
+ * at each call site: a patch that did not say "still alive" would be a patch that invited a second send
18
+ * Workflow. See {@link SendDeps.heartbeatAt}.
19
+ */
20
+ async function patchJob(deps, jobId, patch) {
21
+ await deps.db.updateTable("pithyEmailJobs").set({
22
+ ...patch,
23
+ updatedAt: SQLiteDate.encode(deps.heartbeatAt())
24
+ }).where("id", "=", jobId).execute();
25
+ }
26
+ async function runSend(deps, jobId) {
27
+ const row = await deps.db.selectFrom("pithyEmailJobs").selectAll().where("id", "=", jobId).executeTakeFirst();
28
+ if (!row) throw new NotFoundError({ detail: `email job '${jobId}' not found` });
29
+ const job = EmailJob.parse(row);
30
+ if (job.status === "sent") return {
31
+ jobId,
32
+ status: "sent",
33
+ messageId: job.messageId ?? void 0
34
+ };
35
+ if (job.status === "canceled") return {
36
+ jobId,
37
+ status: "canceled",
38
+ skipped: true
39
+ };
40
+ const recipient = normalizeAddress(job.toAddress);
41
+ if (job.payloadRedactedAt) {
42
+ await patchJob(deps, jobId, {
43
+ status: "failed",
44
+ error: "payload dropped after delivery"
45
+ });
46
+ await recordEvent(deps.db, {
47
+ jobId,
48
+ recipient,
49
+ type: "failed",
50
+ detail: "payload already redacted"
51
+ }, deps.passStartedAt);
52
+ return {
53
+ jobId,
54
+ status: "failed"
55
+ };
56
+ }
57
+ const kind = templateKind(job.template);
58
+ const blocked = await blockingSuppression(deps.suppressionDb, recipient, deps.heartbeatAt(), kind);
59
+ if (blocked) {
60
+ await patchJob(deps, jobId, {
61
+ status: "suppressed",
62
+ error: `recipient suppressed: ${blocked}`
63
+ });
64
+ await recordEvent(deps.db, {
65
+ jobId,
66
+ recipient,
67
+ type: "suppressed",
68
+ detail: blocked
69
+ }, deps.passStartedAt);
70
+ return {
71
+ jobId,
72
+ status: "suppressed",
73
+ skipped: true,
74
+ suppressionReason: blocked
75
+ };
76
+ }
77
+ if (job.category === "marketing" && !deps.signing) {
78
+ await patchJob(deps, jobId, {
79
+ status: "failed",
80
+ error: "no signing key for marketing unsubscribe link"
81
+ });
82
+ await recordEvent(deps.db, {
83
+ jobId,
84
+ recipient,
85
+ type: "failed",
86
+ detail: "no signing key"
87
+ }, deps.passStartedAt);
88
+ return {
89
+ jobId,
90
+ status: "failed"
91
+ };
92
+ }
93
+ const tracking = deps.signing ? {
94
+ baseUrl: deps.baseUrl,
95
+ jobId,
96
+ recipient,
97
+ campaignId: job.campaignId ?? void 0,
98
+ key: deps.signing.key,
99
+ kid: deps.signing.kid,
100
+ expiresAt: new Date(deps.passStartedAt.getTime() + deps.linkTtlDays * DAY_MS),
101
+ openTracking: job.openTracking,
102
+ clickTracking: job.clickTracking
103
+ } : void 0;
104
+ const attempts = job.attempts + 1;
105
+ await patchJob(deps, jobId, {
106
+ status: "sending",
107
+ attempts
108
+ });
109
+ const rendered = await renderEmail(job.template, job.payload, deps.theme, tracking, emailTranslator(job.locale, deps.layersFor ?? kitEmailLayers));
110
+ const headers = { "X-Pithy-Job": jobId };
111
+ if (deps.environment) headers["X-Pithy-Env"] = deps.environment;
112
+ if (job.inReplyTo) headers["In-Reply-To"] = job.inReplyTo;
113
+ if (job.references) headers.References = job.references;
114
+ if (rendered.unsubscribeUrl) {
115
+ headers["List-Unsubscribe"] = `<${rendered.unsubscribeUrl}>`;
116
+ headers["List-Unsubscribe-Post"] = "List-Unsubscribe=One-Click";
117
+ }
118
+ const message = {
119
+ to: recipient,
120
+ from: {
121
+ email: job.fromAddress,
122
+ name: job.fromName
123
+ },
124
+ ...job.replyTo ? { replyTo: job.replyTo } : {},
125
+ subject: rendered.subject,
126
+ html: rendered.html,
127
+ text: rendered.text,
128
+ headers
129
+ };
130
+ try {
131
+ const result = await deps.sender.send(message);
132
+ const spent = redactsPayloadOnDelivery(job.template);
133
+ await patchJob(deps, jobId, {
134
+ status: "sent",
135
+ sentAt: SQLiteDate.encode(deps.passStartedAt),
136
+ messageId: result.messageId ?? null,
137
+ subject: rendered.subject,
138
+ error: null,
139
+ ...spent ? {
140
+ payload: SPENT_PAYLOAD,
141
+ payloadRedactedAt: SQLiteDate.encode(deps.passStartedAt)
142
+ } : {}
143
+ });
144
+ await recordEvent(deps.db, {
145
+ jobId,
146
+ recipient,
147
+ type: "sent",
148
+ campaignId: job.campaignId
149
+ }, deps.passStartedAt);
150
+ for (const bounced of result.permanentBounces ?? []) {
151
+ await suppress(deps.suppressionDb, {
152
+ email: bounced,
153
+ reason: "hard_bounce",
154
+ jobId,
155
+ environment: deps.environment,
156
+ detail: "permanent bounce on send"
157
+ }, deps.passStartedAt);
158
+ await recordEvent(deps.db, {
159
+ jobId,
160
+ recipient: normalizeAddress(bounced),
161
+ type: "bounce",
162
+ detail: "permanent bounce on send"
163
+ }, deps.passStartedAt);
164
+ }
165
+ return {
166
+ jobId,
167
+ status: "sent",
168
+ messageId: result.messageId
169
+ };
170
+ } catch (err) {
171
+ const classified = classifySendError(err);
172
+ if (classified.suppressed) {
173
+ await patchJob(deps, jobId, {
174
+ status: "suppressed",
175
+ error: classified.code,
176
+ bounceCode: classified.code
177
+ });
178
+ await suppress(deps.suppressionDb, {
179
+ email: recipient,
180
+ reason: "hard_bounce",
181
+ jobId,
182
+ environment: deps.environment,
183
+ detail: classified.code
184
+ }, deps.passStartedAt);
185
+ await recordEvent(deps.db, {
186
+ jobId,
187
+ recipient,
188
+ type: "suppressed",
189
+ detail: classified.code
190
+ }, deps.passStartedAt);
191
+ return {
192
+ jobId,
193
+ status: "suppressed",
194
+ skipped: true
195
+ };
196
+ }
197
+ if (classified.retryable && attempts < deps.maxAttempts) {
198
+ await patchJob(deps, jobId, { error: classified.code });
199
+ throw classified.error;
200
+ }
201
+ await patchJob(deps, jobId, {
202
+ status: "failed",
203
+ error: classified.code
204
+ });
205
+ await recordEvent(deps.db, {
206
+ jobId,
207
+ recipient,
208
+ type: "failed",
209
+ detail: classified.code
210
+ }, deps.passStartedAt);
211
+ return {
212
+ jobId,
213
+ status: "failed"
214
+ };
215
+ }
216
+ }
217
+ //#endregion
218
+ export { runSend };
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The next absolute instant when the wall clock reads `hour:minute` in `timezone`, at or after `now`.
3
+ * Computes the candidate for the zone-local date of `now`, advancing a day if it has already passed.
4
+ */
5
+ export declare function resolveTimezoneSendAt(localTime: string, timezone: string, now: Date): Date;
6
+ //# sourceMappingURL=sendAt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sendAt.d.ts","sourceRoot":"","sources":["../../src/send/sendAt.ts"],"names":[],"mappings":"AA4CA;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,GAAG,IAAI,CA4B1F"}