@midsummer-ai/sdk 0.1.0-staging.3428 → 0.1.0-staging.3434
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/auth-B7rCtXFQ.d.mts +36 -0
- package/{build-DQo-JrlN.d.mts → build-BhmOZmGQ.d.mts} +2 -27
- package/client.mjs +1 -1
- package/contract.mjs +2 -2
- package/database/build.d.mts +1 -1
- package/database/build.mjs +35 -2
- package/database/server.mjs +1 -1
- package/database/stand-in.d.mts +2 -1
- package/database/stand-in.mjs +2 -2
- package/email/client.d.mts +5 -4
- package/email/client.mjs +1 -1
- package/email/contract.d.mts +3 -1
- package/email/contract.mjs +111 -4
- package/email/index.d.mts +85 -16
- package/email/index.mjs +2 -2
- package/email/smtp.mjs +24 -8
- package/email/stand-in.d.mts +3 -0
- package/email/stand-in.mjs +17 -7
- package/email-IH5OllU2.mjs +337 -0
- package/errors-B1tO_wdm.mjs +28 -0
- package/flows/contract.d.mts +13 -0
- package/flows/contract.mjs +483 -0
- package/flows/index.d.mts +148 -0
- package/flows/index.mjs +347 -0
- package/index.mjs +2 -2
- package/{names-DfCBKupJ.mjs → names-Do0ot5Ha.mjs} +2 -28
- package/package.json +29 -1
- package/queues/contract.mjs +144 -1
- package/queues/index.d.mts +149 -5
- package/queues/index.mjs +56 -12
- package/queues/stand-in.mjs +333 -31
- package/queues/wire.mjs +302 -16
- package/s3.mjs +3 -2
- package/{server-EDRbF2u-.mjs → server-Drjni3-F.mjs} +4 -2
- package/socket.mjs +1 -1
- package/{src-BKrQAqJN.mjs → src-CkP59_Qu.mjs} +2 -1
- package/stand-in.mjs +2 -1
- package/storage/contract.d.mts +25 -0
- package/storage/contract.mjs +153 -0
- package/storage/files.d.mts +144 -0
- package/storage/files.mjs +513 -0
- package/wire.mjs +2 -1
- package/email-DXtpr7pT.mjs +0 -214
package/email/stand-in.mjs
CHANGED
|
@@ -1,19 +1,24 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { s as addressOf, t as EmailError } from "../email-IH5OllU2.mjs";
|
|
2
2
|
//#region src/email/stand-in.ts
|
|
3
3
|
/**
|
|
4
4
|
* Email's Stand-in: the Capability's behaviour in memory, for `midsummer dev` and tests. It sends
|
|
5
5
|
* nothing anywhere; what it would send is kept in `sent`. It passes the contract
|
|
6
|
-
* (`@midsummer-ai/sdk/email/contract`) except durability and
|
|
6
|
+
* (`@midsummer-ai/sdk/email/contract`) except durability, delivery and templates, which it fills
|
|
7
|
+
* from `templates` when given.
|
|
7
8
|
*
|
|
8
9
|
* const engine = standIn({ domains: ["mail.acme.dev"] })
|
|
9
10
|
* await email(engine).send({ from: "hi@mail.acme.dev", to: "ada@example.com", subject: "Hi", text: "Hello" })
|
|
10
11
|
* engine.sent // what was sent
|
|
11
12
|
*
|
|
12
|
-
* `domains` are the verified Sending domains; `suppressed` the addresses no longer sent to
|
|
13
|
+
* `domains` are the verified Sending domains; `suppressed` the addresses no longer sent to, and
|
|
14
|
+
* `optedOut` those that left a broadcast topic (`newsletter:ada@example.com`).
|
|
13
15
|
*/
|
|
14
16
|
function standIn(options) {
|
|
15
17
|
const domains = new Set(options.domains.map((name) => name.toLowerCase()));
|
|
16
18
|
const suppressed = new Set((options.suppressed ?? []).map(addressOf));
|
|
19
|
+
const optedOut = new Set(options.optedOut ?? []);
|
|
20
|
+
const templates = new Set(options.templates ?? []);
|
|
21
|
+
const clock = options.clock ?? Date.now;
|
|
17
22
|
const sent = [];
|
|
18
23
|
const byKey = /* @__PURE__ */ new Map();
|
|
19
24
|
let count = 0;
|
|
@@ -24,7 +29,8 @@ function standIn(options) {
|
|
|
24
29
|
},
|
|
25
30
|
async send(message) {
|
|
26
31
|
const from = addressOf(message.from);
|
|
27
|
-
if (!domains.has(from.slice(from.indexOf("@") + 1))) throw new EmailError("unverified", `${from} is not on a verified Sending domain`);
|
|
32
|
+
if (!message.test && !domains.has(from.slice(from.indexOf("@") + 1))) throw new EmailError("unverified", `${from} is not on a verified Sending domain`);
|
|
33
|
+
if (message.template !== void 0 && !templates.has(message.template)) throw new EmailError("invalid", `No template ${message.template}`);
|
|
28
34
|
const earlier = message.key !== void 0 ? byKey.get(message.key) : void 0;
|
|
29
35
|
if (earlier) return earlier;
|
|
30
36
|
const recipients = [...new Set([
|
|
@@ -32,11 +38,15 @@ function standIn(options) {
|
|
|
32
38
|
...message.cc ?? [],
|
|
33
39
|
...message.bcc ?? []
|
|
34
40
|
].map(addressOf))];
|
|
35
|
-
|
|
41
|
+
if (message.stream === "broadcast" && recipients.length !== 1) throw new EmailError("invalid", "A broadcast goes to one recipient");
|
|
42
|
+
const out = (address) => suppressed.has(address) || message.stream === "broadcast" && optedOut.has(`${message.topic}:${address}`);
|
|
43
|
+
const left = recipients.filter((address) => !out(address));
|
|
44
|
+
const later = message.sendAt !== void 0 && message.sendAt > clock();
|
|
36
45
|
const answer = {
|
|
37
46
|
id: `msg_${++count}`,
|
|
38
|
-
state: left.length ? "
|
|
39
|
-
suppressed: recipients.filter(
|
|
47
|
+
state: !left.length ? "suppressed" : later ? "queued" : "sent",
|
|
48
|
+
suppressed: recipients.filter(out),
|
|
49
|
+
...later ? { sendAt: message.sendAt } : {}
|
|
40
50
|
};
|
|
41
51
|
if (left.length) sent.push({
|
|
42
52
|
...message,
|
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
import { n as late, t as here } from "./here-CeqGJW21.mjs";
|
|
2
|
+
import { verifyEvent } from "./apps.mjs";
|
|
3
|
+
//#region src/email/client.ts
|
|
4
|
+
/**
|
|
5
|
+
* Email's wire: code holding an Email key sends through `client`, and the platform replies with
|
|
6
|
+
* `serveMessages`. One Message is one POST of JSON to `<origin>/email/messages` with
|
|
7
|
+
* `authorization: Bearer <the key's secret>`, files in base64; it returns the `SentMessage`, or
|
|
8
|
+
* `{ "error": { "code", "message" } }` with the code's status. A batch is a POST of a list of
|
|
9
|
+
* Messages to the same address, which returns a list of `BatchResult`, one for each in order.
|
|
10
|
+
*
|
|
11
|
+
* const mail = email(client("https://api.<site>", { key }))
|
|
12
|
+
*/
|
|
13
|
+
const MESSAGES_PATH = "/email/messages";
|
|
14
|
+
const STATUS = {
|
|
15
|
+
invalid: 400,
|
|
16
|
+
forbidden: 401,
|
|
17
|
+
unverified: 422,
|
|
18
|
+
unavailable: 503
|
|
19
|
+
};
|
|
20
|
+
/** The largest request the wire takes: one Message of 18 MB with its files in base64, and its words. */
|
|
21
|
+
const MAX_REQUEST = 26e6;
|
|
22
|
+
/** Email's engine at `origin` (the API's) for the Email key `key`. */
|
|
23
|
+
function client(origin, options) {
|
|
24
|
+
const url = `${origin.replace(/\/+$/, "")}${MESSAGES_PATH}`;
|
|
25
|
+
const fetcher = options.fetch ?? ((input, init) => fetch(input, init));
|
|
26
|
+
async function post(body) {
|
|
27
|
+
let response;
|
|
28
|
+
try {
|
|
29
|
+
response = await fetcher(url, {
|
|
30
|
+
method: "POST",
|
|
31
|
+
headers: {
|
|
32
|
+
authorization: `Bearer ${options.key}`,
|
|
33
|
+
"content-type": "application/json"
|
|
34
|
+
},
|
|
35
|
+
body: JSON.stringify(body)
|
|
36
|
+
});
|
|
37
|
+
} catch {
|
|
38
|
+
throw new EmailError("unavailable", "Email could not be reached");
|
|
39
|
+
}
|
|
40
|
+
const answer = await response.json().catch(() => void 0);
|
|
41
|
+
if (response.ok && answer !== void 0) return answer;
|
|
42
|
+
const code = answer?.error?.code;
|
|
43
|
+
throw new EmailError(code && code in STATUS ? code : "unavailable", answer?.error?.message ?? `Email answered ${response.status}`);
|
|
44
|
+
}
|
|
45
|
+
return {
|
|
46
|
+
async send(message) {
|
|
47
|
+
const sent = await post(message);
|
|
48
|
+
if (typeof sent.id !== "string") throw new EmailError("unavailable", "Email answered no Message");
|
|
49
|
+
return sent;
|
|
50
|
+
},
|
|
51
|
+
async batch(messages) {
|
|
52
|
+
const results = await post(messages);
|
|
53
|
+
if (!Array.isArray(results) || results.length !== messages.length) throw new EmailError("unavailable", "Email answered no batch");
|
|
54
|
+
return results;
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
/** Only what the wire promises of a Message sent, whatever more the platform answered. */
|
|
59
|
+
const promised = (sent) => ({
|
|
60
|
+
id: sent.id,
|
|
61
|
+
state: sent.state,
|
|
62
|
+
suppressed: sent.suppressed,
|
|
63
|
+
...sent.error !== void 0 ? { error: sent.error } : {},
|
|
64
|
+
...sent.sendAt !== void 0 ? { sendAt: sent.sendAt } : {}
|
|
65
|
+
});
|
|
66
|
+
/**
|
|
67
|
+
* The platform's side of the wire: checks the request again, as it comes from the network, and hands
|
|
68
|
+
* the key and the Message to `send`, or the key and a batch's Messages to `batch`, which throw an
|
|
69
|
+
* `EmailError` for a refusal of the whole; a batch returns each Message's own refusal in its list.
|
|
70
|
+
*/
|
|
71
|
+
function serveMessages(send, batch) {
|
|
72
|
+
const refuse = (code, message) => Response.json({ error: {
|
|
73
|
+
code,
|
|
74
|
+
message
|
|
75
|
+
} }, { status: STATUS[code] });
|
|
76
|
+
return async (request) => {
|
|
77
|
+
if (request.method !== "POST") return Response.json({ error: {
|
|
78
|
+
code: "invalid",
|
|
79
|
+
message: "Use POST."
|
|
80
|
+
} }, { status: 405 });
|
|
81
|
+
const key = /^Bearer (\S+)$/.exec(request.headers.get("authorization") ?? "")?.[1];
|
|
82
|
+
if (!key) return refuse("forbidden", "Send with an Email key: authorization: Bearer <key>.");
|
|
83
|
+
if (Number(request.headers.get("content-length") ?? 0) > MAX_REQUEST) return refuse("invalid", "A Message is at most 18 MB with its files.");
|
|
84
|
+
const text = await request.text();
|
|
85
|
+
if (text.length > MAX_REQUEST) return refuse("invalid", "A Message is at most 18 MB with its files.");
|
|
86
|
+
let body;
|
|
87
|
+
try {
|
|
88
|
+
body = JSON.parse(text);
|
|
89
|
+
} catch {
|
|
90
|
+
body = void 0;
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
if (Array.isArray(body)) {
|
|
94
|
+
if (!batch) return refuse("invalid", "This Email takes one Message at a time.");
|
|
95
|
+
if (!body.length || body.length > 100) return refuse("invalid", `A batch holds 1 to 100 Messages.`);
|
|
96
|
+
if (!body.every(isMessage)) return refuse("invalid", "Every item of a batch is a Message.");
|
|
97
|
+
const results = await email({
|
|
98
|
+
send: (message) => send(key, message),
|
|
99
|
+
batch: (messages) => batch(key, messages)
|
|
100
|
+
}).batch(body);
|
|
101
|
+
return Response.json(results.map((result) => "message" in result ? { message: promised(result.message) } : result));
|
|
102
|
+
}
|
|
103
|
+
if (!isMessage(body)) return refuse("invalid", "The body is not a Message.");
|
|
104
|
+
return Response.json(promised(await send(key, checkMessage(body))));
|
|
105
|
+
} catch (error) {
|
|
106
|
+
if (error instanceof EmailError) return refuse(error.code, error.message);
|
|
107
|
+
throw error;
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* What Midsummer hands a Deployment as `context.email`: sends from the Sending domains its
|
|
113
|
+
* Environment binds, with no key. A batch goes one Message at a time over it.
|
|
114
|
+
*
|
|
115
|
+
* await email(boundEmail(context.email)).send({ from: "Acme <hi@acme.dev>", to: ["ada@example.com"], subject: "Hi", text: "Hello" })
|
|
116
|
+
*/
|
|
117
|
+
function boundEmail(handle) {
|
|
118
|
+
return { async send(message) {
|
|
119
|
+
let answer;
|
|
120
|
+
try {
|
|
121
|
+
answer = await handle.send(message);
|
|
122
|
+
} catch {
|
|
123
|
+
throw new EmailError("unavailable", "Email could not be reached");
|
|
124
|
+
}
|
|
125
|
+
if ("id" in answer) return answer;
|
|
126
|
+
throw new EmailError(answer.error.code in STATUS ? answer.error.code : "unavailable", answer.error.message);
|
|
127
|
+
} };
|
|
128
|
+
}
|
|
129
|
+
/** The platform's side of a bound handle: the same checks as `serveMessages`, a refusal returned as data. */
|
|
130
|
+
function serveBound(send) {
|
|
131
|
+
return async (message) => {
|
|
132
|
+
if (!isMessage(message)) return { error: {
|
|
133
|
+
code: "invalid",
|
|
134
|
+
message: "The body is not a Message."
|
|
135
|
+
} };
|
|
136
|
+
try {
|
|
137
|
+
return promised(await send(checkMessage(message)));
|
|
138
|
+
} catch (error) {
|
|
139
|
+
if (error instanceof EmailError) return { error: {
|
|
140
|
+
code: error.code,
|
|
141
|
+
message: error.message
|
|
142
|
+
} };
|
|
143
|
+
throw error;
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
const strings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
148
|
+
const optional = (value) => value === void 0 || typeof value === "string";
|
|
149
|
+
const record = (value, of) => value === void 0 || typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every(of);
|
|
150
|
+
const file = (value) => {
|
|
151
|
+
if (typeof value !== "object" || value === null) return false;
|
|
152
|
+
const f = value;
|
|
153
|
+
return typeof f.filename === "string" && typeof f.content === "string" && optional(f.contentType) && optional(f.contentId);
|
|
154
|
+
};
|
|
155
|
+
/** Whether a value has a Message's shape, as it comes from the network; what it says is checked after. */
|
|
156
|
+
function isMessage(value) {
|
|
157
|
+
if (typeof value !== "object" || value === null) return false;
|
|
158
|
+
const m = value;
|
|
159
|
+
return typeof m.from === "string" && strings(m.to) && (m.cc === void 0 || strings(m.cc)) && (m.bcc === void 0 || strings(m.bcc)) && optional(m.subject) && optional(m.replyTo) && optional(m.text) && optional(m.html) && optional(m.key) && optional(m.template) && optional(m.topic) && optional(m.tag) && (m.attachments === void 0 || Array.isArray(m.attachments) && m.attachments.every(file)) && record(m.variables, (item) => typeof item === "string" || typeof item === "number") && record(m.metadata, (item) => typeof item === "string") && (m.sendAt === void 0 || typeof m.sendAt === "number") && (m.stream === void 0 || m.stream === "transactional" || m.stream === "broadcast") && (m.track === void 0 || record(m.track, (item) => typeof item === "boolean")) && (m.test === void 0 || typeof m.test === "boolean");
|
|
160
|
+
}
|
|
161
|
+
//#endregion
|
|
162
|
+
//#region src/email/index.ts
|
|
163
|
+
/**
|
|
164
|
+
* Email from a Project's code: Messages sent from the sending domains its environment binds.
|
|
165
|
+
*
|
|
166
|
+
* import { email } from "@midsummer-ai/sdk/email"
|
|
167
|
+
*
|
|
168
|
+
* const sent = await email().send({ from: "Acme <hi@mail.acme.dev>", to: "ada@example.com", subject: "Welcome", text: "Hello", key: "welcome-ada" })
|
|
169
|
+
* await email().send({ from: "billing@mail.acme.dev", to: "ada@example.com", template: "invoice-paid", variables: { name: "Ada", total: "$40" },
|
|
170
|
+
* attachments: [{ filename: "invoice.pdf", content: pdfBytes }], key: "invoice-1043" })
|
|
171
|
+
* await email().batch(people.map((person) => ({ from: "news@mail.acme.dev", to: person.email, template: "digest", variables: { name: person.name },
|
|
172
|
+
* stream: "broadcast", topic: "digest", key: `digest-2026-11-${person.id}` })))
|
|
173
|
+
*
|
|
174
|
+
* With no engine, `email()` sends from a deployment, in any framework, with nothing to connect.
|
|
175
|
+
* Otherwise `engine` is where Messages go: the Stand-in (`@midsummer-ai/sdk/email/stand-in`) in tests,
|
|
176
|
+
* or code outside Midsummer with an email key (`email(client(origin, { key }))` from
|
|
177
|
+
* `@midsummer-ai/sdk/email/client`). Every engine is held to the cases in `@midsummer-ai/sdk/email/contract`.
|
|
178
|
+
*
|
|
179
|
+
* Addresses, files and the Message's shape are checked here, before anything leaves the caller. Reuse
|
|
180
|
+
* a Message's `key` to retry while the original Message is retained for thirty days. After that
|
|
181
|
+
* Message is purged, the same key can send another Message. A suppressed recipient (one that bounced
|
|
182
|
+
* or complained, or left a broadcast's topic) is left out and named in `suppressed`; a Message with
|
|
183
|
+
* nobody left is `suppressed`. A Message with `sendAt` is `queued` until then. `test: true` sends to
|
|
184
|
+
* no one: each recipient's outcome is its address's (`bounce@…`, `soft-bounce@…`, `complaint@…`, else
|
|
185
|
+
* delivered), told to your webhooks as a real one would be. Every failure is an `EmailError`, whose
|
|
186
|
+
* `code` tells you which kind.
|
|
187
|
+
*
|
|
188
|
+
* Delivery events reach a Project's webhooks signed as Standard Webhooks says, as every webhook
|
|
189
|
+
* Midsummer sends is; `verifyWebhook` checks one with the endpoint's secret.
|
|
190
|
+
*/
|
|
191
|
+
var EmailError = class extends Error {
|
|
192
|
+
code;
|
|
193
|
+
constructor(code, message) {
|
|
194
|
+
super(message);
|
|
195
|
+
this.code = code;
|
|
196
|
+
this.name = "EmailError";
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
const ADDRESS = /^[^\s@<>()",;:]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/i;
|
|
200
|
+
/** The bare address of `Ada <ada@acme.dev>` or `ada@acme.dev`, lowercase; `invalid` when it is none. */
|
|
201
|
+
function addressOf(value) {
|
|
202
|
+
const bare = (/<([^<>]+)>\s*$/.exec(value)?.[1] ?? value).trim().toLowerCase();
|
|
203
|
+
if (!ADDRESS.test(bare) || bare.length > 254) throw new EmailError("invalid", `${value} is not an email address`);
|
|
204
|
+
return bare;
|
|
205
|
+
}
|
|
206
|
+
/** At most this many recipients, to, cc and bcc together. */
|
|
207
|
+
const MAX_RECIPIENTS = 50;
|
|
208
|
+
/** At most this many files a Message, each at most `MAX_ATTACHMENT_BYTES`, and the Message with them at most `MAX_MESSAGE_BYTES`. */
|
|
209
|
+
const MAX_ATTACHMENTS = 20;
|
|
210
|
+
const MAX_ATTACHMENT_BYTES = 10485760;
|
|
211
|
+
const MAX_MESSAGE_BYTES = 18874368;
|
|
212
|
+
/** At most this many Messages a batch. */
|
|
213
|
+
const MAX_BATCH = 100;
|
|
214
|
+
/** Files no Message carries, by their name's extension: programs and scripts. */
|
|
215
|
+
const REFUSED = /\.(ade|adp|apk|app|appx|appxbundle|bat|cab|chm|cmd|com|cpl|dll|dmg|exe|hta|ins|isp|jar|js|jse|lib|lnk|mde|msc|msi|msix|msixbundle|msp|mst|nsh|pif|ps1|reg|scr|sct|shb|sys|vb|vbe|vbs|vxd|wsc|wsf|wsh)$/i;
|
|
216
|
+
const encoder = new TextEncoder();
|
|
217
|
+
function toBase64(bytes) {
|
|
218
|
+
let text = "";
|
|
219
|
+
for (let at = 0; at < bytes.length; at += 32768) text += String.fromCharCode(...bytes.subarray(at, at + 32768));
|
|
220
|
+
return btoa(text);
|
|
221
|
+
}
|
|
222
|
+
/** How many bytes base64 holds. */
|
|
223
|
+
const decodedLength = (text) => {
|
|
224
|
+
const clean = text.replace(/\s+/g, "");
|
|
225
|
+
return Math.floor(clean.length * 3 / 4) - (clean.endsWith("==") ? 2 : clean.endsWith("=") ? 1 : 0);
|
|
226
|
+
};
|
|
227
|
+
/** A Message checked as the engine takes it; throws `EmailError("invalid")` saying what is wrong. */
|
|
228
|
+
function checkMessage(message) {
|
|
229
|
+
const to = typeof message.to === "string" ? [message.to] : [...message.to];
|
|
230
|
+
if (!to.length) throw new EmailError("invalid", "a Message needs someone to send to");
|
|
231
|
+
const all = [
|
|
232
|
+
message.from,
|
|
233
|
+
...to,
|
|
234
|
+
...message.cc ?? [],
|
|
235
|
+
...message.bcc ?? [],
|
|
236
|
+
...message.replyTo ? [message.replyTo] : []
|
|
237
|
+
];
|
|
238
|
+
all.forEach(addressOf);
|
|
239
|
+
if (all.length - 1 - (message.replyTo ? 1 : 0) > 50) throw new EmailError("invalid", `a Message goes to at most 50 recipients`);
|
|
240
|
+
if (message.template === void 0) {
|
|
241
|
+
if (!message.subject?.trim()) throw new EmailError("invalid", "a Message needs a subject");
|
|
242
|
+
if (message.text === void 0 && message.html === void 0) throw new EmailError("invalid", "a Message needs text or html");
|
|
243
|
+
} else if (message.subject !== void 0 || message.text !== void 0 || message.html !== void 0) throw new EmailError("invalid", "a Message from a template takes its subject, text and html from it");
|
|
244
|
+
const files = message.attachments ?? [];
|
|
245
|
+
if (files.length > 20) throw new EmailError("invalid", `a Message carries at most 20 files`);
|
|
246
|
+
let total = encoder.encode(`${message.subject ?? ""}${message.text ?? ""}${message.html ?? ""}`).length;
|
|
247
|
+
const attachments = files.map((file) => {
|
|
248
|
+
if (!file.filename.trim()) throw new EmailError("invalid", "every file needs a name");
|
|
249
|
+
if (REFUSED.test(file.filename.trim())) throw new EmailError("invalid", `${file.filename} is a program or script, which mail doesn't carry`);
|
|
250
|
+
const content = typeof file.content === "string" ? file.content : toBase64(file.content);
|
|
251
|
+
const size = typeof file.content === "string" ? decodedLength(file.content) : file.content.length;
|
|
252
|
+
if (size === 0) throw new EmailError("invalid", `${file.filename} is empty`);
|
|
253
|
+
if (size > 10485760) throw new EmailError("invalid", `${file.filename} is over 10 MB; send a link to it instead`);
|
|
254
|
+
total += size;
|
|
255
|
+
if (total > 18874368) throw new EmailError("invalid", "with its files the Message is over 18 MB");
|
|
256
|
+
return {
|
|
257
|
+
filename: file.filename,
|
|
258
|
+
content,
|
|
259
|
+
...file.contentType ? { contentType: file.contentType } : {},
|
|
260
|
+
...file.contentId ? { contentId: file.contentId } : {}
|
|
261
|
+
};
|
|
262
|
+
});
|
|
263
|
+
const sendAt = message.sendAt === void 0 ? void 0 : message.sendAt instanceof Date ? message.sendAt.getTime() : message.sendAt;
|
|
264
|
+
if (sendAt !== void 0 && !Number.isFinite(sendAt)) throw new EmailError("invalid", "sendAt is a time");
|
|
265
|
+
if (message.stream === "broadcast" && !message.topic) throw new EmailError("invalid", "a broadcast names its topic");
|
|
266
|
+
const { attachments: _files, sendAt: _sendAt, ...rest } = message;
|
|
267
|
+
return {
|
|
268
|
+
...rest,
|
|
269
|
+
to,
|
|
270
|
+
...attachments.length ? { attachments } : {},
|
|
271
|
+
...sendAt !== void 0 ? { sendAt } : {}
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
function email(given) {
|
|
275
|
+
const engine = given ?? late(() => {
|
|
276
|
+
const handle = here()?.email;
|
|
277
|
+
if (handle) return boundEmail(handle);
|
|
278
|
+
throw new EmailError("forbidden", "This code runs outside a deployment, so it sends with an email key: email(client(origin, { key })).");
|
|
279
|
+
});
|
|
280
|
+
return {
|
|
281
|
+
async send(message) {
|
|
282
|
+
return engine.send(checkMessage(message));
|
|
283
|
+
},
|
|
284
|
+
async batch(messages) {
|
|
285
|
+
if (!messages.length || messages.length > 100) throw new EmailError("invalid", `a batch holds 1 to 100 Messages`);
|
|
286
|
+
const checked = messages.map((message) => {
|
|
287
|
+
try {
|
|
288
|
+
if (message.attachments?.length) throw new EmailError("invalid", "a Message in a batch carries no files: send it on its own");
|
|
289
|
+
return checkMessage(message);
|
|
290
|
+
} catch (error) {
|
|
291
|
+
if (error instanceof EmailError) return error;
|
|
292
|
+
throw error;
|
|
293
|
+
}
|
|
294
|
+
});
|
|
295
|
+
const going = checked.filter((entry) => !(entry instanceof EmailError));
|
|
296
|
+
const answers = going.length ? engine.batch ? await engine.batch(going) : await sendEach(engine, going) : [];
|
|
297
|
+
let next = 0;
|
|
298
|
+
return checked.map((entry) => entry instanceof EmailError ? { error: {
|
|
299
|
+
code: entry.code,
|
|
300
|
+
message: entry.message
|
|
301
|
+
} } : answers[next++]);
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
/** A batch sent one Message at a time, at most eight at once, for an engine that takes one at a time. */
|
|
306
|
+
async function sendEach(engine, messages) {
|
|
307
|
+
const out = new Array(messages.length);
|
|
308
|
+
let next = 0;
|
|
309
|
+
await Promise.all(Array.from({ length: Math.min(8, messages.length) }, async () => {
|
|
310
|
+
for (let at = next++; at < messages.length; at = next++) try {
|
|
311
|
+
out[at] = { message: await engine.send(messages[at]) };
|
|
312
|
+
} catch (error) {
|
|
313
|
+
if (!(error instanceof EmailError)) throw error;
|
|
314
|
+
out[at] = { error: {
|
|
315
|
+
code: error.code,
|
|
316
|
+
message: error.message
|
|
317
|
+
} };
|
|
318
|
+
}
|
|
319
|
+
}));
|
|
320
|
+
return out;
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Whether a webhook delivery Midsummer sent is genuine: signed as Standard Webhooks says, as every
|
|
324
|
+
* webhook Midsummer sends is (email delivery events, Inbox rules' `email.received`, a Team's or an
|
|
325
|
+
* agent's endpoints, an installed app's events). Give the request's headers (`webhook-id`,
|
|
326
|
+
* `webhook-timestamp`, `webhook-signature`), the body exactly as it arrived, and the endpoint's
|
|
327
|
+
* secret (`whsec_…`, shown when it was made or rotated). A delivery older than five minutes, or
|
|
328
|
+
* ahead of the clock by as much, is refused. After a rotation both secrets sign for a day, and either
|
|
329
|
+
* passing is enough. Deliveries are at least once: drop a repeat by its `webhook-id`.
|
|
330
|
+
*
|
|
331
|
+
* if (!(await verifyWebhook(request.headers, body, process.env.MIDSUMMER_WEBHOOK_SECRET!))) return new Response(null, { status: 401 })
|
|
332
|
+
*/
|
|
333
|
+
function verifyWebhook(headers, body, secret, options = {}) {
|
|
334
|
+
return verifyEvent(headers, body, secret, options.now ?? Date.now());
|
|
335
|
+
}
|
|
336
|
+
//#endregion
|
|
337
|
+
export { MAX_MESSAGE_BYTES as a, checkMessage as c, MESSAGES_PATH as d, boundEmail as f, serveMessages as h, MAX_BATCH as i, email as l, serveBound as m, MAX_ATTACHMENTS as n, MAX_RECIPIENTS as o, client as p, MAX_ATTACHMENT_BYTES as r, addressOf as s, EmailError as t, verifyWebhook as u };
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
//#region src/errors.ts
|
|
2
|
+
const storageErrorCodes = [
|
|
3
|
+
"invalid",
|
|
4
|
+
"not_found",
|
|
5
|
+
"conflict",
|
|
6
|
+
"forbidden",
|
|
7
|
+
"quota",
|
|
8
|
+
"unavailable"
|
|
9
|
+
];
|
|
10
|
+
const storageErrorReasons = [
|
|
11
|
+
"range",
|
|
12
|
+
"upload",
|
|
13
|
+
"part",
|
|
14
|
+
"part-order",
|
|
15
|
+
"part-too-small"
|
|
16
|
+
];
|
|
17
|
+
var StorageError = class extends Error {
|
|
18
|
+
code;
|
|
19
|
+
reason;
|
|
20
|
+
constructor(code, why, reason) {
|
|
21
|
+
super(why);
|
|
22
|
+
this.code = code;
|
|
23
|
+
this.reason = reason;
|
|
24
|
+
this.name = "StorageError";
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
//#endregion
|
|
28
|
+
export { storageErrorCodes as n, storageErrorReasons as r, StorageError as t };
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { QueueEngine } from "../queues/index.mjs";
|
|
2
|
+
//#region src/flows/contract.d.ts
|
|
3
|
+
interface FlowCase {
|
|
4
|
+
/** A line of the specification. */
|
|
5
|
+
readonly name: string;
|
|
6
|
+
run(world: {
|
|
7
|
+
readonly engine: QueueEngine;
|
|
8
|
+
advance(ms: number): void;
|
|
9
|
+
}): Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
declare const flowsContract: ReadonlyArray<FlowCase>;
|
|
12
|
+
//#endregion
|
|
13
|
+
export { FlowCase, flowsContract };
|