@pithy-sh/email 0.1.2 → 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.
- package/dist/analytics.d.ts +19 -0
- package/dist/analytics.d.ts.map +1 -0
- package/dist/analytics.js +13 -0
- package/dist/audit/actions.d.ts +45 -0
- package/dist/audit/actions.d.ts.map +1 -0
- package/dist/audit/actions.js +45 -0
- package/dist/bounce/classify.d.ts +38 -0
- package/dist/bounce/classify.d.ts.map +1 -0
- package/dist/bounce/classify.js +46 -0
- package/dist/bounce/handler.d.ts +32 -0
- package/dist/bounce/handler.d.ts.map +1 -0
- package/dist/bounce/handler.js +81 -0
- package/dist/capability.d.ts +158 -0
- package/dist/capability.d.ts.map +1 -0
- package/dist/capability.js +255 -0
- package/dist/crypto/signingKey.d.ts +36 -0
- package/dist/crypto/signingKey.d.ts.map +1 -0
- package/dist/crypto/signingKey.js +36 -0
- package/dist/crypto/token.d.ts +47 -0
- package/dist/crypto/token.d.ts.map +1 -0
- package/dist/crypto/token.js +99 -0
- package/dist/data/emailEvent.d.ts +28 -0
- package/dist/data/emailEvent.d.ts.map +1 -0
- package/dist/data/emailEvent.js +22 -0
- package/dist/data/emailJob.d.ts +76 -0
- package/dist/data/emailJob.d.ts.map +1 -0
- package/dist/data/emailJob.js +62 -0
- package/dist/data/emailSuppression.d.ts +23 -0
- package/dist/data/emailSuppression.d.ts.map +1 -0
- package/dist/data/emailSuppression.js +21 -0
- package/dist/data/enums.d.ts +76 -0
- package/dist/data/enums.d.ts.map +1 -0
- package/dist/data/enums.js +65 -0
- package/dist/data/tables.d.ts +114 -0
- package/dist/data/tables.d.ts.map +1 -0
- package/dist/data/tables.js +30 -0
- package/dist/error/errors.d.ts +60 -0
- package/dist/error/errors.d.ts.map +1 -0
- package/dist/error/errors.js +82 -0
- package/dist/http/callbacks.d.ts +21 -0
- package/dist/http/callbacks.d.ts.map +1 -0
- package/dist/http/callbacks.js +110 -0
- package/dist/http/guards.d.ts +99 -0
- package/dist/http/guards.d.ts.map +1 -0
- package/dist/http/guards.js +144 -0
- package/dist/http/responses.d.ts +295 -0
- package/dist/http/responses.d.ts.map +1 -0
- package/dist/http/responses.js +115 -0
- package/dist/http/routes.d.ts +71 -0
- package/dist/http/routes.d.ts.map +1 -0
- package/dist/http/routes.js +292 -0
- package/dist/http/schemas.d.ts +90 -0
- package/dist/http/schemas.d.ts.map +1 -0
- package/dist/http/schemas.js +91 -0
- package/dist/http/view.d.ts +78 -0
- package/dist/http/view.d.ts.map +1 -0
- package/dist/http/view.js +130 -0
- package/dist/index.d.ts +46 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +11 -0
- package/dist/jobs/read.d.ts +191 -0
- package/dist/jobs/read.d.ts.map +1 -0
- package/dist/jobs/read.js +143 -0
- package/dist/jobs/retry.d.ts +99 -0
- package/dist/jobs/retry.d.ts.map +1 -0
- package/dist/jobs/retry.js +67 -0
- package/dist/migrations/0001_init.d.ts +32 -0
- package/dist/migrations/0001_init.d.ts.map +1 -0
- package/dist/migrations/0001_init.js +60 -0
- package/dist/migrations/0001_suppressions.d.ts +10 -0
- package/dist/migrations/0001_suppressions.d.ts.map +1 -0
- package/dist/migrations/0001_suppressions.js +20 -0
- package/dist/provision/devDelivery.d.ts +32 -0
- package/dist/provision/devDelivery.d.ts.map +1 -0
- package/dist/provision/devDelivery.js +37 -0
- package/dist/provision/hostCatalogs.d.ts +10 -0
- package/dist/provision/hostCatalogs.d.ts.map +1 -0
- package/dist/provision/hostCatalogs.js +78 -0
- package/dist/provision/provisionEmail.d.ts +143 -0
- package/dist/provision/provisionEmail.d.ts.map +1 -0
- package/dist/provision/provisionEmail.js +118 -0
- package/dist/provision/resolveEmailConfig.d.ts +122 -0
- package/dist/provision/resolveEmailConfig.d.ts.map +1 -0
- package/dist/provision/resolveEmailConfig.js +124 -0
- package/dist/provision/settingsCheck.d.ts +40 -0
- package/dist/provision/settingsCheck.d.ts.map +1 -0
- package/dist/provision/settingsCheck.js +138 -0
- package/dist/send/batchIdentity.d.ts +42 -0
- package/dist/send/batchIdentity.d.ts.map +1 -0
- package/dist/send/batchIdentity.js +46 -0
- package/dist/send/enqueue.d.ts +216 -0
- package/dist/send/enqueue.d.ts.map +1 -0
- package/dist/send/enqueue.js +153 -0
- package/dist/send/errorMapping.d.ts +27 -0
- package/dist/send/errorMapping.d.ts.map +1 -0
- package/dist/send/errorMapping.js +52 -0
- package/dist/send/events.d.ts +15 -0
- package/dist/send/events.d.ts.map +1 -0
- package/dist/send/events.js +17 -0
- package/dist/send/fromComposition.d.ts +47 -0
- package/dist/send/fromComposition.d.ts.map +1 -0
- package/dist/send/fromComposition.js +53 -0
- package/dist/send/retryPolicy.d.ts +32 -0
- package/dist/send/retryPolicy.d.ts.map +1 -0
- package/dist/send/retryPolicy.js +39 -0
- package/dist/send/runSend.d.ts +106 -0
- package/dist/send/runSend.d.ts.map +1 -0
- package/dist/send/runSend.js +218 -0
- package/dist/send/sendAt.d.ts +6 -0
- package/dist/send/sendAt.d.ts.map +1 -0
- package/dist/send/sendAt.js +62 -0
- package/dist/send/sender.d.ts +42 -0
- package/dist/send/sender.d.ts.map +1 -0
- package/dist/send/sender.js +0 -0
- package/dist/send/senderBinding.d.ts +44 -0
- package/dist/send/senderBinding.d.ts.map +1 -0
- package/dist/send/senderBinding.js +21 -0
- package/dist/send/suppression.d.ts +93 -0
- package/dist/send/suppression.d.ts.map +1 -0
- package/dist/send/suppression.js +132 -0
- package/dist/templates/engine.d.ts +109 -0
- package/dist/templates/engine.d.ts.map +1 -0
- package/dist/templates/engine.js +258 -0
- package/dist/templates/messages.d.ts +94 -0
- package/dist/templates/messages.d.ts.map +1 -0
- package/dist/templates/messages.es.d.ts +29 -0
- package/dist/templates/messages.es.d.ts.map +1 -0
- package/dist/templates/messages.es.js +82 -0
- package/dist/templates/messages.js +266 -0
- package/dist/templates/partials.d.ts +5 -0
- package/dist/templates/partials.d.ts.map +1 -0
- package/dist/templates/partials.js +59 -0
- package/dist/templates/precompiled.generated.d.ts +266 -0
- package/dist/templates/precompiled.generated.d.ts.map +1 -0
- package/dist/templates/precompiled.generated.js +4039 -0
- package/dist/templates/registry.d.ts +118 -0
- package/dist/templates/registry.d.ts.map +1 -0
- package/dist/templates/registry.js +323 -0
- package/dist/templates/samples.d.ts +7 -0
- package/dist/templates/samples.d.ts.map +1 -0
- package/dist/templates/samples.js +98 -0
- package/dist/templates/severity.d.ts +40 -0
- package/dist/templates/severity.d.ts.map +1 -0
- package/dist/templates/severity.js +81 -0
- package/dist/templates/theme.d.ts +193 -0
- package/dist/templates/theme.d.ts.map +1 -0
- package/dist/templates/theme.js +168 -0
- package/dist/version.generated.d.ts +5 -0
- package/dist/version.generated.d.ts.map +1 -0
- package/dist/version.generated.js +7 -0
- package/dist/workflows/hostApp.d.ts +33 -0
- package/dist/workflows/hostApp.d.ts.map +1 -0
- package/dist/workflows/hostApp.js +19 -0
- package/dist/workflows/hostEnv.d.ts +129 -0
- package/dist/workflows/hostEnv.d.ts.map +1 -0
- package/dist/workflows/hostEnv.js +147 -0
- package/dist/workflows/instanceLiveness.d.ts +3 -0
- package/dist/workflows/instanceLiveness.d.ts.map +1 -0
- package/dist/workflows/instanceLiveness.js +37 -0
- package/dist/workflows/instances.d.ts +18 -0
- package/dist/workflows/instances.d.ts.map +1 -0
- package/dist/workflows/instances.js +0 -0
- package/dist/workflows/params.d.ts +23 -0
- package/dist/workflows/params.d.ts.map +1 -0
- package/dist/workflows/params.js +21 -0
- package/dist/workflows/scheduler.d.ts +82 -0
- package/dist/workflows/scheduler.d.ts.map +1 -0
- package/dist/workflows/scheduler.js +111 -0
- package/dist/workflows/sendBatch.d.ts +85 -0
- package/dist/workflows/sendBatch.d.ts.map +1 -0
- package/dist/workflows/sendBatch.js +50 -0
- package/dist/workflows/worker.d.ts +100 -0
- package/dist/workflows/worker.d.ts.map +1 -0
- package/dist/workflows/worker.js +117 -0
- package/package.json +22 -11
- package/src/version.generated.ts +1 -1
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { EmailJob } from "../data/emailJob.js";
|
|
2
|
+
import { InternalError } from "@pithy-sh/core/src/error/pithyError";
|
|
3
|
+
import { normalizeAddress } from "@pithy-sh/core/src/address/address";
|
|
4
|
+
import { decodeCursor, pageLimit, toPage } from "@pithy-sh/core/src/data/cursor";
|
|
5
|
+
//#region src/jobs/read.ts
|
|
6
|
+
/**
|
|
7
|
+
* A cursor this table can actually resume from.
|
|
8
|
+
*
|
|
9
|
+
* `PageCursor.sort` is a union because Better Auth stores ISO text where Pithy's own tables store
|
|
10
|
+
* ms-epoch numbers, and comparing a string against an integer column in SQLite silently orders by
|
|
11
|
+
* something nobody meant. Jobs store a number, so anything else is treated exactly as a malformed
|
|
12
|
+
* cursor is: undefined, and the caller gets a first page.
|
|
13
|
+
*/
|
|
14
|
+
function jobCursor(raw) {
|
|
15
|
+
const cursor = decodeCursor(raw);
|
|
16
|
+
if (!cursor || typeof cursor.sort !== "number") return void 0;
|
|
17
|
+
return {
|
|
18
|
+
sort: cursor.sort,
|
|
19
|
+
id: String(cursor.id)
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
/** One page of jobs, newest first, optionally filtered to one status. */
|
|
23
|
+
async function listJobs(db, filter) {
|
|
24
|
+
const limit = pageLimit(filter.limit);
|
|
25
|
+
const after = jobCursor(filter.cursor);
|
|
26
|
+
let query = db.selectFrom("pithyEmailJobs").selectAll().orderBy("createdAt", "desc").orderBy("id", "desc").limit(limit + 1);
|
|
27
|
+
if (filter.status) query = query.where("status", "=", filter.status);
|
|
28
|
+
if (after) query = query.where((eb) => eb.or([eb("createdAt", "<", after.sort), eb.and([eb("createdAt", "=", after.sort), eb("id", "<", after.id)])]));
|
|
29
|
+
const jobs = (await query.execute()).map((row) => EmailJob.parse(row));
|
|
30
|
+
return toPage(jobs, limit, (job) => ({
|
|
31
|
+
sort: job.createdAt.getTime(),
|
|
32
|
+
id: job.id
|
|
33
|
+
}));
|
|
34
|
+
}
|
|
35
|
+
/** One job by id, or undefined. The caller decides what a miss means. */
|
|
36
|
+
async function getJob(db, jobId) {
|
|
37
|
+
const row = await db.selectFrom("pithyEmailJobs").selectAll().where("id", "=", jobId).executeTakeFirst();
|
|
38
|
+
return row ? EmailJob.parse(row) : void 0;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* ## `sentSince` — has this message already gone out
|
|
42
|
+
*
|
|
43
|
+
* The narrow read, for the caller deciding whether to send. A transactional notice that must not repeat,
|
|
44
|
+
* and must be *corrected* if the thing it announced stops being true, cannot be decided from a flag of
|
|
45
|
+
* the caller's own: a `cancellationNoticeSentAt` column is a second answer to a question this table
|
|
46
|
+
* already holds the first of, and the two disagree the first time a send fails after the flag is
|
|
47
|
+
* written. `pithy_email_jobs` is the record; this is the read over it, so nobody has to define its shape
|
|
48
|
+
* a second time in their own repository.
|
|
49
|
+
*
|
|
50
|
+
* ## Two axes, because a template is not always one message
|
|
51
|
+
*
|
|
52
|
+
* It was `(to, template)` alone, and that could not finish its only intended consumer (pithy-sh/pithy#382).
|
|
53
|
+
* Six account notices ride one `operationalNotice` to the same addresses, so the template id does not
|
|
54
|
+
* separate them; `correlation` is the enqueue-side discriminator that does. See {@link SentSubject} for
|
|
55
|
+
* why the two are a union and not three optional fields.
|
|
56
|
+
*
|
|
57
|
+
* **The direction of the failure is why this was worth a column.** The dashboard uses the answer
|
|
58
|
+
* *positively*: the correction letter goes out only when the letter it corrects already did. An
|
|
59
|
+
* under-report there sends nothing at all — it withholds the correction from somebody holding a letter
|
|
60
|
+
* that has stopped being true. That is silence, to the one person owed the message, and silence is the
|
|
61
|
+
* failure nobody finds in production.
|
|
62
|
+
*
|
|
63
|
+
* ## Four columns, and every other one is a deliberate no
|
|
64
|
+
*
|
|
65
|
+
* `SentSummary` is `EmailJob.pick(…)`, so the columns it carries are the columns it selects and a
|
|
66
|
+
* projection cannot leak one it never loaded. What is not on it:
|
|
67
|
+
*
|
|
68
|
+
* - **`toAddress`.** The caller passed the address in; handing it back means a read answering a question
|
|
69
|
+
* about one person returns a copy of them in every row, and any log of the result is an address list.
|
|
70
|
+
* - **`payload`.** The sign-in link and the OTP. `view.ts` argues this at length and the argument is the
|
|
71
|
+
* same here, except that this reader is reachable from ordinary application code rather than only from
|
|
72
|
+
* a scoped credential, which makes it stronger rather than weaker.
|
|
73
|
+
* - **`subject`.** Rendered content, and the temptation is specific: it is the only per-row string that
|
|
74
|
+
* distinguishes two messages sharing a template, so a caller needing that discrimination would match
|
|
75
|
+
* on it. That match breaks on a copy edit, silently, in the direction of sending again. Discriminating
|
|
76
|
+
* two notices was the enqueue side's problem and now has an enqueue-side answer — `correlation`
|
|
77
|
+
* (#382) — rather than a rendered string exported to be string-matched.
|
|
78
|
+
* - **`messageId`, `error`, `bounceCode`.** The provider's own words. A provider error routinely embeds
|
|
79
|
+
* the recipient, which is why the list view carries `failed` rather than the text.
|
|
80
|
+
*
|
|
81
|
+
* `status` rather than a boolean, because the statuses are the answer: a `failed` or `suppressed` row is
|
|
82
|
+
* an email nobody read, and a reader that collapsed the log to "yes" would treat it as one they did.
|
|
83
|
+
*
|
|
84
|
+
* ## Bounded, and it says when the bound bit
|
|
85
|
+
*
|
|
86
|
+
* The log is append-only and unbounded by nature, so the read is capped — and a cap that silently
|
|
87
|
+
* truncates is the failure mode, not the bound. `truncated` says the cap was reached, the same word
|
|
88
|
+
* `@pithy-sh/auth`'s bounded sub-lists use. A caller counting rows must read it; a caller asking only
|
|
89
|
+
* "did anything go out" may ignore it, because a truncated page is still a non-empty one.
|
|
90
|
+
*/
|
|
91
|
+
/**
|
|
92
|
+
* One job as the send-decision reader sees it: the handle, the outcome, and the two instants.
|
|
93
|
+
*
|
|
94
|
+
* Derived from `EmailJob` with `.pick()` rather than restated, so the codecs and the field descriptions
|
|
95
|
+
* come from the one table definition and a column added to the row does not silently appear here.
|
|
96
|
+
* Re-described because `.pick()` builds a new schema and the top-level description does not follow it.
|
|
97
|
+
*/
|
|
98
|
+
const SentSummary = EmailJob.pick({
|
|
99
|
+
id: true,
|
|
100
|
+
status: true,
|
|
101
|
+
createdAt: true,
|
|
102
|
+
sentAt: true
|
|
103
|
+
}).describe("One previously enqueued message, as the caller deciding whether to send another one sees it. No recipient, no subject, no payload, no provider text — the id is the handle into the full record for anyone holding the scope to read it.");
|
|
104
|
+
/**
|
|
105
|
+
* Every job matching one subject since an instant, newest first.
|
|
106
|
+
*
|
|
107
|
+
* The subject is `(to, template)`, or a `correlation`, or both — see {@link SentSubject}. Neither is not
|
|
108
|
+
* a subject, and the type will not build one.
|
|
109
|
+
*
|
|
110
|
+
* **A row that will not parse throws.** It is tempting to skip it and carry on, and it is wrong here in
|
|
111
|
+
* a way it is not on a listing: this reader's answer decides whether a message goes out. A skipped row
|
|
112
|
+
* is reported as an email that never went, which means a duplicate send — or, where the caller is
|
|
113
|
+
* looking for who to send a *correction* to, a correction withheld from exactly the person owed one.
|
|
114
|
+
* Both failures are silent and neither is recoverable after the fact, so a row this schema cannot read
|
|
115
|
+
* stops the decision instead of quietly biasing it.
|
|
116
|
+
*/
|
|
117
|
+
async function sentSince(db, filter) {
|
|
118
|
+
const limit = pageLimit(filter.limit);
|
|
119
|
+
let query = db.selectFrom("pithyEmailJobs").select([
|
|
120
|
+
"id",
|
|
121
|
+
"status",
|
|
122
|
+
"createdAt",
|
|
123
|
+
"sentAt"
|
|
124
|
+
]).where("createdAt", ">=", filter.since.getTime()).orderBy("createdAt", "desc").orderBy("id", "desc").limit(limit + 1);
|
|
125
|
+
if (filter.to !== void 0) query = query.where("recipientKey", "=", normalizeAddress(filter.to));
|
|
126
|
+
if (filter.template !== void 0) query = query.where("template", "=", filter.template);
|
|
127
|
+
if (filter.correlation !== void 0) query = query.where("correlation", "=", filter.correlation);
|
|
128
|
+
const rows = await query.execute();
|
|
129
|
+
return {
|
|
130
|
+
items: rows.slice(0, limit).map((row) => {
|
|
131
|
+
const parsed = SentSummary.safeParse(row);
|
|
132
|
+
if (!parsed.success) throw new InternalError({
|
|
133
|
+
message: "The send log could not be read.",
|
|
134
|
+
action: "Inspect pithy_email_jobs for a row this deployment's schema cannot decode.",
|
|
135
|
+
detail: `pithy_email_jobs row '${String(row.id)}' does not satisfy EmailJob: ${parsed.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.code}`).join("; ")}`
|
|
136
|
+
});
|
|
137
|
+
return parsed.data;
|
|
138
|
+
}),
|
|
139
|
+
truncated: rows.length > limit
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
//#endregion
|
|
143
|
+
export { SentSummary, getJob, listJobs, sentSince };
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { EmailJob } from "../data/emailJob";
|
|
2
|
+
import type { EmailDatabase, EmailSuppressionDatabase } from "../data/tables";
|
|
3
|
+
import type { SendWorkflowBinding } from "../send/enqueue";
|
|
4
|
+
/**
|
|
5
|
+
* Putting a failed job back in the queue — the body behind `POST /email/jobs/:id/retry`.
|
|
6
|
+
*
|
|
7
|
+
* ## A handler never sends
|
|
8
|
+
*
|
|
9
|
+
* `runSend` is Workflow-only and is never called from here. A retry does what `enqueueEmail` does: it
|
|
10
|
+
* puts the row back into a sendable state and dispatches the send Workflow. That keeps the one place
|
|
11
|
+
* that talks to the Email Service inside a durable step with retries and history, which is the whole
|
|
12
|
+
* reason email is a job table rather than a function call.
|
|
13
|
+
*
|
|
14
|
+
* A failed dispatch is safe and deliberately swallowed. The row is `pending` before the Workflow is
|
|
15
|
+
* started, so the every-minute scheduler's safety net re-drives it on the next tick — the same contract
|
|
16
|
+
* `enqueueEmail` relies on. Losing the dispatch costs a minute; failing the request after the row was
|
|
17
|
+
* already reset would tell an operator nothing happened when something did.
|
|
18
|
+
*
|
|
19
|
+
* ## Only a `failed` job may be retried
|
|
20
|
+
*
|
|
21
|
+
* Every other state is refused with `core/conflict`, and each refusal is a different thing going wrong:
|
|
22
|
+
*
|
|
23
|
+
* - `sent` — already delivered. Retrying is a duplicate email to a real person. It is also the one
|
|
24
|
+
* state whose inputs are gone: a transactional job's payload is dropped when the message goes out,
|
|
25
|
+
* which is safe precisely because this refusal is what makes `sent` terminal.
|
|
26
|
+
* - `pending` / `scheduled` / `sending` — still in flight. Resetting it races the scheduler, and
|
|
27
|
+
* `sending` in particular is a job a Workflow is holding right now.
|
|
28
|
+
* - `suppressed` — the address is on the block list. Retrying is the one send this capability must
|
|
29
|
+
* never make.
|
|
30
|
+
* - `bounced` — the recipient's server said permanently no, and the bounce handler only sets this
|
|
31
|
+
* state while suppressing the address, so a retry is the previous case wearing a different label.
|
|
32
|
+
* - `canceled` — somebody withdrew it. Reviving a withdrawal is a separate decision, not a retry, and
|
|
33
|
+
* it should have to be made somewhere it is named.
|
|
34
|
+
*
|
|
35
|
+
* ## The attempt budget is reset, and it has to be
|
|
36
|
+
*
|
|
37
|
+
* `runSend` gives up when `attempts >= maxAttempts`. A job that failed did so having spent its budget,
|
|
38
|
+
* so a retry that left `attempts` alone would take one retryable error to fail terminally again — the
|
|
39
|
+
* button would appear to work and change nothing. `attempts` returns to zero; `error` does not, because
|
|
40
|
+
* it is the record of what went wrong last time and a successful send clears it anyway.
|
|
41
|
+
*
|
|
42
|
+
* ## The batch id is re-minted, and the old one must not survive
|
|
43
|
+
*
|
|
44
|
+
* A `failed` row still names the batch that failed it (pithy-sh/pithy#342), and that id is about to
|
|
45
|
+
* become wrong in both directions at once. `batchId` means *the instance coming for this row* — see
|
|
46
|
+
* `send/batchIdentity.ts` — and after a retry the instance coming for it is the one this function
|
|
47
|
+
* starts, not the one that gave up on it.
|
|
48
|
+
*
|
|
49
|
+
* Leaving the old id there is not a stale label. It hands the scheduler's veto the wrong Workflow to ask
|
|
50
|
+
* about, and a failure inside a batch is exactly the case where that Workflow is *still running*: a
|
|
51
|
+
* batch of fifty that failed job seven walks on to job fifty. So the tick that should re-drive the retry
|
|
52
|
+
* asks about the batch that abandoned it, is told "alive", and holds — the operator's click sends
|
|
53
|
+
* nothing for as long as the old batch runs. Then the old batch ends, the same row reads as stranded,
|
|
54
|
+
* and the tick starts a second Workflow behind the one this function already started. Held when it
|
|
55
|
+
* should send, then sent twice: one wrong id, both failures.
|
|
56
|
+
*
|
|
57
|
+
* So a retry mints its own, writes it in the same statement that makes the row queryable again, and
|
|
58
|
+
* creates the instance under it. Null when there is no binding to dispatch on, because then nothing is
|
|
59
|
+
* coming for the row and the scheduler should claim it on the next tick — and the row is `undispatched`
|
|
60
|
+
* rather than `pending` there, for the reason the write itself states.
|
|
61
|
+
*/
|
|
62
|
+
/** What a retry needs: both databases, the send Workflow binding, and the clock. */
|
|
63
|
+
export interface RetryDeps {
|
|
64
|
+
/** The per-environment jobs database. */
|
|
65
|
+
db: EmailDatabase;
|
|
66
|
+
/** The global suppression database — checked before the row is touched. */
|
|
67
|
+
suppressionDb: EmailSuppressionDatabase;
|
|
68
|
+
/**
|
|
69
|
+
* The send Workflow binding. Optional so a Worker that somehow lacks it still resets the row and
|
|
70
|
+
* leaves the scheduler to re-drive, rather than failing an operator's click outright.
|
|
71
|
+
*/
|
|
72
|
+
sender?: SendWorkflowBinding;
|
|
73
|
+
now: Date;
|
|
74
|
+
/**
|
|
75
|
+
* Mint the id of the batch this retry dispatches — **the send Workflow instance's id**
|
|
76
|
+
* (pithy-sh/pithy#342). Defaults to {@link mintBatchId}; injected only so a test can name it.
|
|
77
|
+
*/
|
|
78
|
+
newBatchId?: () => string;
|
|
79
|
+
}
|
|
80
|
+
/** What a retry did. */
|
|
81
|
+
export interface RetryResult {
|
|
82
|
+
/** The job that was re-queued. */
|
|
83
|
+
job: EmailJob;
|
|
84
|
+
/**
|
|
85
|
+
* Whether the send Workflow actually started. False means the scheduler will pick the row up within
|
|
86
|
+
* the minute — the mail is not lost, it is merely not immediate.
|
|
87
|
+
*/
|
|
88
|
+
dispatched: boolean;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Re-queue one failed job.
|
|
92
|
+
*
|
|
93
|
+
* Reads before it writes: the job must exist, be `failed`, and its recipient must not have been
|
|
94
|
+
* suppressed in the meantime. That last check is not redundant with `runSend`'s — `runSend` would mark
|
|
95
|
+
* the row `suppressed` and skip, which reports to the operator as a successful retry that silently sent
|
|
96
|
+
* nothing. Refusing here says what actually happened.
|
|
97
|
+
*/
|
|
98
|
+
export declare function retryJob(deps: RetryDeps, jobId: string): Promise<RetryResult>;
|
|
99
|
+
//# sourceMappingURL=retry.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"retry.d.ts","sourceRoot":"","sources":["../../src/jobs/retry.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,KAAK,EAAE,aAAa,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAG9E,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAK3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyDG;AAEH,oFAAoF;AACpF,MAAM,WAAW,SAAS;IACxB,yCAAyC;IACzC,EAAE,EAAE,aAAa,CAAC;IAClB,2EAA2E;IAC3E,aAAa,EAAE,wBAAwB,CAAC;IACxC;;;OAGG;IACH,MAAM,CAAC,EAAE,mBAAmB,CAAC;IAC7B,GAAG,EAAE,IAAI,CAAC;IACV;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,MAAM,CAAC;CAC3B;AAED,wBAAwB;AACxB,MAAM,WAAW,WAAW;IAC1B,kCAAkC;IAClC,GAAG,EAAE,QAAQ,CAAC;IACd;;;OAGG;IACH,UAAU,EAAE,OAAO,CAAC;CACrB;AAED;;;;;;;GAOG;AACH,wBAAsB,QAAQ,CAAC,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAqGnF"}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { blockingSuppression } from "../send/suppression.js";
|
|
2
|
+
import { EmailSuppressedError } from "../error/errors.js";
|
|
3
|
+
import { templateKind } from "../templates/engine.js";
|
|
4
|
+
import { getJob } from "./read.js";
|
|
5
|
+
import { mintBatchId } from "../send/batchIdentity.js";
|
|
6
|
+
import { ConflictError, NotFoundError } from "@pithy-sh/core/src/error/pithyError";
|
|
7
|
+
import { normalizeAddress } from "@pithy-sh/core/src/address/address";
|
|
8
|
+
import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
|
|
9
|
+
//#region src/jobs/retry.ts
|
|
10
|
+
/**
|
|
11
|
+
* Re-queue one failed job.
|
|
12
|
+
*
|
|
13
|
+
* Reads before it writes: the job must exist, be `failed`, and its recipient must not have been
|
|
14
|
+
* suppressed in the meantime. That last check is not redundant with `runSend`'s — `runSend` would mark
|
|
15
|
+
* the row `suppressed` and skip, which reports to the operator as a successful retry that silently sent
|
|
16
|
+
* nothing. Refusing here says what actually happened.
|
|
17
|
+
*/
|
|
18
|
+
async function retryJob(deps, jobId) {
|
|
19
|
+
const existing = await getJob(deps.db, jobId);
|
|
20
|
+
if (!existing) throw new NotFoundError({
|
|
21
|
+
message: "No such email job.",
|
|
22
|
+
action: "Check the job id against the send log.",
|
|
23
|
+
detail: `email job '${jobId}' not found`
|
|
24
|
+
});
|
|
25
|
+
if (existing.status !== "failed") throw new ConflictError({
|
|
26
|
+
message: `Only a failed job can be retried. This one is ${existing.status}.`,
|
|
27
|
+
action: "Retry a job whose status is failed.",
|
|
28
|
+
detail: `email job '${jobId}' is ${existing.status}`
|
|
29
|
+
});
|
|
30
|
+
const recipient = normalizeAddress(existing.toAddress);
|
|
31
|
+
const blocked = await blockingSuppression(deps.suppressionDb, recipient, deps.now, templateKind(existing.template));
|
|
32
|
+
if (blocked) throw new EmailSuppressedError({
|
|
33
|
+
message: `That recipient is on the suppression list (${blocked}), so this job cannot be retried.`,
|
|
34
|
+
action: "Remove the address from the suppression list first, if that is what you mean to do.",
|
|
35
|
+
detail: `recipient of email job '${jobId}' is suppressed: ${blocked}`
|
|
36
|
+
});
|
|
37
|
+
const batchId = deps.sender ? (deps.newBatchId ?? mintBatchId)() : null;
|
|
38
|
+
if (((await deps.db.updateTable("pithyEmailJobs").set({
|
|
39
|
+
batchId,
|
|
40
|
+
status: deps.sender ? "pending" : "undispatched",
|
|
41
|
+
sendAt: SQLiteDate.encode(deps.now),
|
|
42
|
+
attempts: 0,
|
|
43
|
+
updatedAt: SQLiteDate.encode(deps.now),
|
|
44
|
+
createdAt: SQLiteDate.encode(deps.now)
|
|
45
|
+
}).where("id", "=", jobId).where("status", "=", "failed").executeTakeFirst()).numUpdatedRows ?? 0n) === 0n) {
|
|
46
|
+
const current = await getJob(deps.db, jobId);
|
|
47
|
+
throw new ConflictError({
|
|
48
|
+
message: `Only a failed job can be retried. This one is ${current?.status ?? "no longer there"}.`,
|
|
49
|
+
action: "Reload the send log — somebody may have retried it already.",
|
|
50
|
+
detail: `email job '${jobId}' left the failed state between the read and the write`
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
let dispatched = false;
|
|
54
|
+
if (deps.sender && batchId) try {
|
|
55
|
+
await deps.sender.create({
|
|
56
|
+
id: batchId,
|
|
57
|
+
params: { jobIds: [jobId] }
|
|
58
|
+
});
|
|
59
|
+
dispatched = true;
|
|
60
|
+
} catch {}
|
|
61
|
+
return {
|
|
62
|
+
job: await getJob(deps.db, jobId) ?? existing,
|
|
63
|
+
dispatched
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
//#endregion
|
|
67
|
+
export { retryJob };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { Migration } from "kysely/migration";
|
|
2
|
+
/**
|
|
3
|
+
* Create the per-environment email tables in the app database: `pithy_email_jobs` and
|
|
4
|
+
* `pithy_email_events`. Both carry the `pithy_email_` prefix so they never clash with an adopter's own
|
|
5
|
+
* tables. (Suppression lives in its own durable database — see `0001_suppressions.ts`.)
|
|
6
|
+
*
|
|
7
|
+
* Identifiers are declared in **camelCase**: the runner installs `CamelCasePlugin`, which snake-cases
|
|
8
|
+
* every identifier in the emitted DDL (CLAUDE.md §Data layer). `down` is the tested inverse — indexes
|
|
9
|
+
* then tables, in reverse creation order (D1 has no transactional DDL).
|
|
10
|
+
*
|
|
11
|
+
* **This is the capability's whole schema for this database, in one migration, and that is the rule
|
|
12
|
+
* while nothing is published.** CONTRIBUTING.md §Migrations states it and
|
|
13
|
+
* `packages/cli/src/migrations/oneMigration.test.ts` enforces it: a chain buys exactly one thing —
|
|
14
|
+
* walking a database that already holds rows from an old shape to a new one — and there is no such
|
|
15
|
+
* database, so a `0002` would be a step from a shape that never ran to a shape that never shipped.
|
|
16
|
+
*
|
|
17
|
+
* **Amended in place on 2026-08-23** for `locale` (pithy-sh/pithy#441), and **on 2026-08-16** for
|
|
18
|
+
* `correlation` (pithy-sh/pithy#382). The condition was re-checked on each occasion rather than
|
|
19
|
+
* assumed, because CONTRIBUTING.md asks a later reader to check it:
|
|
20
|
+
*
|
|
21
|
+
* - `@pithy-sh/email` is at `0.0.0` and `npm view @pithy-sh/email version` is a 404. Nothing has been
|
|
22
|
+
* released, so no `0200_email_0001_init` has run anywhere a chain would be replayed against.
|
|
23
|
+
* - The only adopter is `pithy-sh/dashboard`, and `GET /accounts/602df2e6ce74e98b4c7ac5e90a3af5c8/d1/database`
|
|
24
|
+
* — the account `apps/board/pithy.config.ts` pins, not whatever wrangler is logged in to — returns an
|
|
25
|
+
* **empty list**. There is no deployed D1 at all, so none holds a `pithy_email_jobs` row.
|
|
26
|
+
*
|
|
27
|
+
* **The moment either stops being true this file is history, and the chain is append-only.** A version
|
|
28
|
+
* cut, or one database on that account, and the next column is a `0002`. Nothing about a tidy `0001`
|
|
29
|
+
* tells a reader which side of that line they are on — re-run the two checks, do not infer them.
|
|
30
|
+
*/
|
|
31
|
+
export declare const email_0001_init: Migration;
|
|
32
|
+
//# sourceMappingURL=0001_init.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"0001_init.d.ts","sourceRoot":"","sources":["../../src/migrations/0001_init.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAElD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,eAAO,MAAM,eAAe,EAAE,SA0I7B,CAAC"}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
//#region src/migrations/0001_init.ts
|
|
2
|
+
/**
|
|
3
|
+
* Create the per-environment email tables in the app database: `pithy_email_jobs` and
|
|
4
|
+
* `pithy_email_events`. Both carry the `pithy_email_` prefix so they never clash with an adopter's own
|
|
5
|
+
* tables. (Suppression lives in its own durable database — see `0001_suppressions.ts`.)
|
|
6
|
+
*
|
|
7
|
+
* Identifiers are declared in **camelCase**: the runner installs `CamelCasePlugin`, which snake-cases
|
|
8
|
+
* every identifier in the emitted DDL (CLAUDE.md §Data layer). `down` is the tested inverse — indexes
|
|
9
|
+
* then tables, in reverse creation order (D1 has no transactional DDL).
|
|
10
|
+
*
|
|
11
|
+
* **This is the capability's whole schema for this database, in one migration, and that is the rule
|
|
12
|
+
* while nothing is published.** CONTRIBUTING.md §Migrations states it and
|
|
13
|
+
* `packages/cli/src/migrations/oneMigration.test.ts` enforces it: a chain buys exactly one thing —
|
|
14
|
+
* walking a database that already holds rows from an old shape to a new one — and there is no such
|
|
15
|
+
* database, so a `0002` would be a step from a shape that never ran to a shape that never shipped.
|
|
16
|
+
*
|
|
17
|
+
* **Amended in place on 2026-08-23** for `locale` (pithy-sh/pithy#441), and **on 2026-08-16** for
|
|
18
|
+
* `correlation` (pithy-sh/pithy#382). The condition was re-checked on each occasion rather than
|
|
19
|
+
* assumed, because CONTRIBUTING.md asks a later reader to check it:
|
|
20
|
+
*
|
|
21
|
+
* - `@pithy-sh/email` is at `0.0.0` and `npm view @pithy-sh/email version` is a 404. Nothing has been
|
|
22
|
+
* released, so no `0200_email_0001_init` has run anywhere a chain would be replayed against.
|
|
23
|
+
* - The only adopter is `pithy-sh/dashboard`, and `GET /accounts/602df2e6ce74e98b4c7ac5e90a3af5c8/d1/database`
|
|
24
|
+
* — the account `apps/board/pithy.config.ts` pins, not whatever wrangler is logged in to — returns an
|
|
25
|
+
* **empty list**. There is no deployed D1 at all, so none holds a `pithy_email_jobs` row.
|
|
26
|
+
*
|
|
27
|
+
* **The moment either stops being true this file is history, and the chain is append-only.** A version
|
|
28
|
+
* cut, or one database on that account, and the next column is a `0002`. Nothing about a tidy `0001`
|
|
29
|
+
* tells a reader which side of that line they are on — re-run the two checks, do not infer them.
|
|
30
|
+
*/
|
|
31
|
+
const email_0001_init = {
|
|
32
|
+
up: async (db) => {
|
|
33
|
+
await db.schema.createTable("pithyEmailJobs").addColumn("id", "text", (c) => c.primaryKey()).addColumn("toAddress", "text", (c) => c.notNull()).addColumn("recipientKey", "text", (c) => c.notNull()).addColumn("fromAddress", "text", (c) => c.notNull()).addColumn("fromName", "text", (c) => c.notNull()).addColumn("subject", "text", (c) => c.notNull()).addColumn("template", "text", (c) => c.notNull()).addColumn("category", "text", (c) => c.notNull()).addColumn("payload", "text", (c) => c.notNull()).addColumn("payloadRedactedAt", "integer").addColumn("status", "text", (c) => c.notNull()).addColumn("mode", "text", (c) => c.notNull()).addColumn("attempts", "integer", (c) => c.notNull().defaultTo(0)).addColumn("batchId", "text").addColumn("sendAt", "integer", (c) => c.notNull()).addColumn("timezone", "text").addColumn("localTime", "text").addColumn("campaignId", "text").addColumn("locale", "text").addColumn("correlation", "text").addColumn("openTracking", "integer", (c) => c.notNull().defaultTo(0)).addColumn("clickTracking", "integer", (c) => c.notNull().defaultTo(0)).addColumn("messageId", "text").addColumn("error", "text").addColumn("bounceCode", "text").addColumn("bounceType", "text").addColumn("replyTo", "text").addColumn("inReplyTo", "text").addColumn("references", "text").addColumn("createdAt", "integer", (c) => c.notNull()).addColumn("updatedAt", "integer", (c) => c.notNull()).addColumn("sentAt", "integer").execute();
|
|
34
|
+
await db.schema.createIndex("pithyEmailJobsDueIdx").on("pithyEmailJobs").columns(["status", "sendAt"]).execute();
|
|
35
|
+
await db.schema.createIndex("pithyEmailJobsMessageIdIdx").on("pithyEmailJobs").column("messageId").execute();
|
|
36
|
+
await db.schema.createTable("pithyEmailEvents").addColumn("id", "integer", (c) => c.primaryKey().autoIncrement()).addColumn("jobId", "text", (c) => c.notNull()).addColumn("recipient", "text", (c) => c.notNull()).addColumn("type", "text", (c) => c.notNull()).addColumn("linkLabel", "text").addColumn("linkUrl", "text").addColumn("campaignId", "text").addColumn("detail", "text").addColumn("createdAt", "integer", (c) => c.notNull()).execute();
|
|
37
|
+
await db.schema.createIndex("pithyEmailEventsJobIdIdx").on("pithyEmailEvents").column("jobId").execute();
|
|
38
|
+
await db.schema.createIndex("pithyEmailJobsStatusCreatedIdx").on("pithyEmailJobs").columns(["status", "createdAt"]).execute();
|
|
39
|
+
await db.schema.createIndex("pithyEmailJobsCreatedIdx").on("pithyEmailJobs").column("createdAt").execute();
|
|
40
|
+
await db.schema.createIndex("pithyEmailJobsRecipientTemplateIdx").on("pithyEmailJobs").columns([
|
|
41
|
+
"recipientKey",
|
|
42
|
+
"template",
|
|
43
|
+
"createdAt"
|
|
44
|
+
]).execute();
|
|
45
|
+
await db.schema.createIndex("pithyEmailJobsCorrelationIdx").on("pithyEmailJobs").columns(["correlation", "createdAt"]).execute();
|
|
46
|
+
},
|
|
47
|
+
down: async (db) => {
|
|
48
|
+
await db.schema.dropIndex("pithyEmailJobsCorrelationIdx").execute();
|
|
49
|
+
await db.schema.dropIndex("pithyEmailJobsRecipientTemplateIdx").execute();
|
|
50
|
+
await db.schema.dropIndex("pithyEmailJobsCreatedIdx").execute();
|
|
51
|
+
await db.schema.dropIndex("pithyEmailJobsStatusCreatedIdx").execute();
|
|
52
|
+
await db.schema.dropIndex("pithyEmailEventsJobIdIdx").execute();
|
|
53
|
+
await db.schema.dropTable("pithyEmailEvents").execute();
|
|
54
|
+
await db.schema.dropIndex("pithyEmailJobsMessageIdIdx").execute();
|
|
55
|
+
await db.schema.dropIndex("pithyEmailJobsDueIdx").execute();
|
|
56
|
+
await db.schema.dropTable("pithyEmailJobs").execute();
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
//#endregion
|
|
60
|
+
export { email_0001_init };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Migration } from "kysely/migration";
|
|
2
|
+
/**
|
|
3
|
+
* Create the global suppression table in the dedicated, durable `EMAIL_SUPPRESSIONS` database —
|
|
4
|
+
* distinct from the per-environment app `DB`, because an address that hard-bounced, complained, or
|
|
5
|
+
* unsubscribed must never be emailed from *any* environment. Mirrors the shared-DB pattern of
|
|
6
|
+
* `@pithy-sh/secrets`. The single inbound bounce worker and the unsubscribe callbacks write it; every
|
|
7
|
+
* environment's send path reads it.
|
|
8
|
+
*/
|
|
9
|
+
export declare const email_0001_suppressions: Migration;
|
|
10
|
+
//# sourceMappingURL=0001_suppressions.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"0001_suppressions.d.ts","sourceRoot":"","sources":["../../src/migrations/0001_suppressions.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAElD;;;;;;GAMG;AACH,eAAO,MAAM,uBAAuB,EAAE,SA0BrC,CAAC"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
//#region src/migrations/0001_suppressions.ts
|
|
2
|
+
/**
|
|
3
|
+
* Create the global suppression table in the dedicated, durable `EMAIL_SUPPRESSIONS` database —
|
|
4
|
+
* distinct from the per-environment app `DB`, because an address that hard-bounced, complained, or
|
|
5
|
+
* unsubscribed must never be emailed from *any* environment. Mirrors the shared-DB pattern of
|
|
6
|
+
* `@pithy-sh/secrets`. The single inbound bounce worker and the unsubscribe callbacks write it; every
|
|
7
|
+
* environment's send path reads it.
|
|
8
|
+
*/
|
|
9
|
+
const email_0001_suppressions = {
|
|
10
|
+
up: async (db) => {
|
|
11
|
+
await db.schema.createTable("pithyEmailSuppressions").addColumn("id", "integer", (c) => c.primaryKey().autoIncrement()).addColumn("email", "text", (c) => c.notNull().unique()).addColumn("reason", "text", (c) => c.notNull()).addColumn("jobId", "text").addColumn("environment", "text").addColumn("detail", "text").addColumn("createdAt", "integer", (c) => c.notNull()).addColumn("expiresAt", "integer").execute();
|
|
12
|
+
await db.schema.createIndex("pithyEmailSuppressionsCreatedIdx").on("pithyEmailSuppressions").column("createdAt").execute();
|
|
13
|
+
},
|
|
14
|
+
down: async (db) => {
|
|
15
|
+
await db.schema.dropIndex("pithyEmailSuppressionsCreatedIdx").execute();
|
|
16
|
+
await db.schema.dropTable("pithyEmailSuppressions").execute();
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
//#endregion
|
|
20
|
+
export { email_0001_suppressions };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/**
|
|
3
|
+
* How mail leaves the email host worker when that worker is running on a developer's machine.
|
|
4
|
+
*
|
|
5
|
+
* The point of the local loop is a magic link that **arrives** (pithy-sh/pithy#410). Until now it
|
|
6
|
+
* could not: `pithy dev` never ran the email host at all, so a sign-in wrote a row that said
|
|
7
|
+
* `pending` and a screen that said "check your inbox". With the host in the dev set, one flag decides
|
|
8
|
+
* what its `send_email` binding does — and the default is the one that ends the loop.
|
|
9
|
+
*
|
|
10
|
+
* Both settings run the Worker locally. Neither is a transport of ours: `wrangler dev` implements the
|
|
11
|
+
* binding either way, and there is no REST or SMTP sender in this kit (that stays out of scope until
|
|
12
|
+
* a context with no binding at all needs one).
|
|
13
|
+
*/
|
|
14
|
+
/** What the host's `send_email` binding does under `pithy dev`. */
|
|
15
|
+
export declare const DevMailDelivery: z.ZodEnum<{
|
|
16
|
+
remote: "remote";
|
|
17
|
+
simulator: "simulator";
|
|
18
|
+
}>;
|
|
19
|
+
export type DevMailDelivery = z.infer<typeof DevMailDelivery>;
|
|
20
|
+
/**
|
|
21
|
+
* Which bindings the resolved host config must mark `remote: true`, for one environment.
|
|
22
|
+
*
|
|
23
|
+
* The committed template no longer hardcodes the flag, because a hardcoded `true` cannot be turned
|
|
24
|
+
* off: `resolveWorkflowHost` only ever *adds* `remote`, so a template that already carried it left no
|
|
25
|
+
* way to select the simulator. The decision moved here, where the capability's config can reach it.
|
|
26
|
+
*
|
|
27
|
+
* Outside `dev` the answer is always `remote: true`. A deployed Worker ignores the flag entirely —
|
|
28
|
+
* it is a `wrangler dev` instruction — so the resolved config for `staging` and `prod` is byte-
|
|
29
|
+
* identical whatever an adopter chose for their laptop.
|
|
30
|
+
*/
|
|
31
|
+
export declare function emailRemoteBindings(env: string, delivery: DevMailDelivery): readonly string[];
|
|
32
|
+
//# sourceMappingURL=devDelivery.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"devDelivery.d.ts","sourceRoot":"","sources":["../../src/provision/devDelivery.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;;;;;;;;GAWG;AAEH,mEAAmE;AACnE,eAAO,MAAM,eAAe;;;EAIzB,CAAC;AACJ,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,eAAe,CAAC,CAAC;AAQ9D;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,eAAe,GAAG,SAAS,MAAM,EAAE,CAG7F"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
//#region src/provision/devDelivery.ts
|
|
3
|
+
/**
|
|
4
|
+
* How mail leaves the email host worker when that worker is running on a developer's machine.
|
|
5
|
+
*
|
|
6
|
+
* The point of the local loop is a magic link that **arrives** (pithy-sh/pithy#410). Until now it
|
|
7
|
+
* could not: `pithy dev` never ran the email host at all, so a sign-in wrote a row that said
|
|
8
|
+
* `pending` and a screen that said "check your inbox". With the host in the dev set, one flag decides
|
|
9
|
+
* what its `send_email` binding does — and the default is the one that ends the loop.
|
|
10
|
+
*
|
|
11
|
+
* Both settings run the Worker locally. Neither is a transport of ours: `wrangler dev` implements the
|
|
12
|
+
* binding either way, and there is no REST or SMTP sender in this kit (that stays out of scope until
|
|
13
|
+
* a context with no binding at all needs one).
|
|
14
|
+
*/
|
|
15
|
+
/** What the host's `send_email` binding does under `pithy dev`. */
|
|
16
|
+
const DevMailDelivery = z.enum(["remote", "simulator"]).describe("How email is delivered when the host worker runs under `pithy dev`. **`remote` is the default, and it sends real mail from the developer's machine** — `remote: true` on the `send_email` binding runs the Worker locally and delivers through Cloudflare Email Service, so the message lands in a real inbox with the same DKIM and the same delivery logs as production. It needs a Cloudflare login `wrangler dev` can use and a sending domain already onboarded onto Email Service. `simulator` sends nothing: `wrangler dev` logs the sender, recipient and subject and writes the rendered HTML and text bodies to disk, which is what an offline machine and CI want. Choose `simulator` deliberately — the cost of `remote` is that a test sign-in really does reach whatever address it was given.");
|
|
17
|
+
/** The local environment. The only one this flag governs; every other one deploys and delivers for real. */
|
|
18
|
+
const DEV_ENVIRONMENT = "dev";
|
|
19
|
+
/** The `send_email` binding name the committed host template declares. */
|
|
20
|
+
const SEND_BINDING = "EMAIL";
|
|
21
|
+
/**
|
|
22
|
+
* Which bindings the resolved host config must mark `remote: true`, for one environment.
|
|
23
|
+
*
|
|
24
|
+
* The committed template no longer hardcodes the flag, because a hardcoded `true` cannot be turned
|
|
25
|
+
* off: `resolveWorkflowHost` only ever *adds* `remote`, so a template that already carried it left no
|
|
26
|
+
* way to select the simulator. The decision moved here, where the capability's config can reach it.
|
|
27
|
+
*
|
|
28
|
+
* Outside `dev` the answer is always `remote: true`. A deployed Worker ignores the flag entirely —
|
|
29
|
+
* it is a `wrangler dev` instruction — so the resolved config for `staging` and `prod` is byte-
|
|
30
|
+
* identical whatever an adopter chose for their laptop.
|
|
31
|
+
*/
|
|
32
|
+
function emailRemoteBindings(env, delivery) {
|
|
33
|
+
if (env === DEV_ENVIRONMENT && delivery === "simulator") return [];
|
|
34
|
+
return [SEND_BINDING];
|
|
35
|
+
}
|
|
36
|
+
//#endregion
|
|
37
|
+
export { DevMailDelivery, emailRemoteBindings };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { LocaleCatalogs } from "@pithy-sh/core/src/i18n/catalog";
|
|
2
|
+
import { type EmailMessageLayers } from "../templates/messages";
|
|
3
|
+
/**
|
|
4
|
+
* Flatten a composed project's layers into the `EMAIL_MESSAGES` var's value, one catalog per locale.
|
|
5
|
+
*
|
|
6
|
+
* `locales` is the project's `supportedLocales`; a project that composed no i18n capability passes
|
|
7
|
+
* none, gets `{}`, and deploys a host with no var at all — which is the same English it always sent.
|
|
8
|
+
*/
|
|
9
|
+
export declare function emailHostCatalogs(locales: readonly string[], layersFor: EmailMessageLayers): LocaleCatalogs;
|
|
10
|
+
//# sourceMappingURL=hostCatalogs.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hostCatalogs.d.ts","sourceRoot":"","sources":["../../src/provision/hostCatalogs.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,cAAc,EAAkB,MAAM,iCAAiC,CAAC;AACtF,OAAO,EAAkB,KAAK,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AA6DhF;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,EAAE,SAAS,EAAE,kBAAkB,GAAG,cAAc,CAkC3G"}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { EMAIL_MESSAGES } from "../templates/messages.js";
|
|
2
|
+
import { KitErrorPayload } from "@pithy-sh/core/src/error/payload";
|
|
3
|
+
//#region src/provision/hostCatalogs.ts
|
|
4
|
+
/**
|
|
5
|
+
* The catalogs the prebuilt email host worker is deployed with — the provision-time half of
|
|
6
|
+
* `catalogLayers`.
|
|
7
|
+
*
|
|
8
|
+
* ## Why the host needs data where the app worker needs a seam
|
|
9
|
+
*
|
|
10
|
+
* An app worker composes capabilities, so `@pithy-sh/email`'s enqueue reaches a composed project's
|
|
11
|
+
* `layersFor` through the `compose` hook and renders a subject in whatever language the project
|
|
12
|
+
* speaks. The host worker composes nothing: `pithy email provision` deploys it from a committed
|
|
13
|
+
* template, and no `pithy.config.ts` of the adopter's is ever evaluated inside it. So the layers
|
|
14
|
+
* cannot travel as a function; they travel as one JSON var, and this is what flattens them.
|
|
15
|
+
*
|
|
16
|
+
* Nothing wrote that var before pithy-sh/pithy#441's remediation, which made the whole translated-body
|
|
17
|
+
* path dead in any real deployment: the send Workflow rendered the kit's English whatever tag was on
|
|
18
|
+
* the row, and — because `runSend` overwrites the stored subject with its own fresh render — discarded
|
|
19
|
+
* the translated subject the app worker had computed at enqueue as well. Two Workers, one message, and
|
|
20
|
+
* they disagreed about its language.
|
|
21
|
+
*
|
|
22
|
+
* ## What is dropped, and why dropping it changes nothing
|
|
23
|
+
*
|
|
24
|
+
* **Only `email/` keys.** The host renders email templates and nothing else, so a screen's copy or an
|
|
25
|
+
* error's translation in this var is weight against a hard 5 KB ceiling (see `resolveEmailConfig`) for
|
|
26
|
+
* a key no template will ever ask for.
|
|
27
|
+
*
|
|
28
|
+
* **And only keys that say something the host does not already have.** `catalogLayers` ends every
|
|
29
|
+
* lookup at `EMAIL_MESSAGES` — this package's own copy, in every language it is written in, bundled
|
|
30
|
+
* into the host — so a key whose merged value is byte-identical to what the host already resolves for
|
|
31
|
+
* that locale renders the same string whether it is in the var or not. Leaving it out is invisible in
|
|
32
|
+
* the rendered mail, and it is what makes adding a language cost no configuration at all: a project
|
|
33
|
+
* on the kit's own locales that overrode nothing deploys no catalog variable.
|
|
34
|
+
*
|
|
35
|
+
* An adopter who overrode a sentence is unaffected, including one who overrode a translation back to
|
|
36
|
+
* the English wording: the comparison is against the locale's own bundled value, which is not that.
|
|
37
|
+
*/
|
|
38
|
+
/** The domain every key this capability renders lives under — `composeMessages` enforces it too. */
|
|
39
|
+
const EMAIL_KEY_PREFIX = "email/";
|
|
40
|
+
/**
|
|
41
|
+
* The `email/*` keys that are **error codes**, not template copy.
|
|
42
|
+
*
|
|
43
|
+
* The prefix alone is not the rule the doc below states. `email/send_failed` and its five siblings are
|
|
44
|
+
* catalog keys under this capability's domain because for an error the key *is* the code — but no
|
|
45
|
+
* template ever asks for one, and the host is the Worker that renders templates. A client translates
|
|
46
|
+
* an error from a catalog it already holds; the send Workflow never renders one.
|
|
47
|
+
*
|
|
48
|
+
* Worth the derivation rather than a list: it is 416 bytes of a 5120-byte ceiling that a real project
|
|
49
|
+
* already fills to 69%, so it is roughly 8% of the room a second locale would need. Read off
|
|
50
|
+
* `KitErrorPayload` so a seventh `email/*` code drops out on its own.
|
|
51
|
+
*/
|
|
52
|
+
const EMAIL_ERROR_CODES = new Set(KitErrorPayload.options.map((member) => member.shape.code.value).filter((code) => code.startsWith(EMAIL_KEY_PREFIX)));
|
|
53
|
+
/** Whether a key is copy this host will actually render. */
|
|
54
|
+
function rendersOnTheHost(key) {
|
|
55
|
+
return key.startsWith(EMAIL_KEY_PREFIX) && !EMAIL_ERROR_CODES.has(key);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Flatten a composed project's layers into the `EMAIL_MESSAGES` var's value, one catalog per locale.
|
|
59
|
+
*
|
|
60
|
+
* `locales` is the project's `supportedLocales`; a project that composed no i18n capability passes
|
|
61
|
+
* none, gets `{}`, and deploys a host with no var at all — which is the same English it always sent.
|
|
62
|
+
*/
|
|
63
|
+
function emailHostCatalogs(locales, layersFor) {
|
|
64
|
+
const catalogs = {};
|
|
65
|
+
for (const locale of locales) {
|
|
66
|
+
const merged = {};
|
|
67
|
+
for (const layer of [...layersFor(locale)].reverse()) for (const [key, value] of Object.entries(layer ?? {})) if (rendersOnTheHost(key)) merged[key] = value;
|
|
68
|
+
const bundled = {
|
|
69
|
+
...EMAIL_MESSAGES.en ?? {},
|
|
70
|
+
...EMAIL_MESSAGES[locale] ?? {}
|
|
71
|
+
};
|
|
72
|
+
for (const [key, value] of Object.entries(merged)) if (bundled[key] === value) delete merged[key];
|
|
73
|
+
if (Object.keys(merged).length > 0) catalogs[locale] = merged;
|
|
74
|
+
}
|
|
75
|
+
return catalogs;
|
|
76
|
+
}
|
|
77
|
+
//#endregion
|
|
78
|
+
export { emailHostCatalogs };
|