@yaks/resend 0.0.0-stage → 0.2.36

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 (59) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +96 -2
  3. package/_dist/api.d.ts +2 -0
  4. package/_dist/api.d.ts.map +1 -0
  5. package/_dist/box-queue.d.ts +30 -0
  6. package/_dist/box-queue.d.ts.map +1 -0
  7. package/_dist/box-wire.d.ts +35 -0
  8. package/_dist/box-wire.d.ts.map +1 -0
  9. package/_dist/domains.d.ts +55 -0
  10. package/_dist/domains.d.ts.map +1 -0
  11. package/_dist/graph.d.ts +8 -0
  12. package/_dist/graph.d.ts.map +1 -0
  13. package/_dist/mod.d.ts +5 -0
  14. package/_dist/mod.d.ts.map +1 -0
  15. package/_dist/options.d.ts +19 -0
  16. package/_dist/options.d.ts.map +1 -0
  17. package/_dist/receive.d.ts +45 -0
  18. package/_dist/receive.d.ts.map +1 -0
  19. package/_dist/routes.d.ts +8 -0
  20. package/_dist/routes.d.ts.map +1 -0
  21. package/_dist/sender.d.ts +19 -0
  22. package/_dist/sender.d.ts.map +1 -0
  23. package/_dist/service.d.ts +10 -0
  24. package/_dist/service.d.ts.map +1 -0
  25. package/api.js +19 -0
  26. package/api.js.map +1 -0
  27. package/api.ts +27 -0
  28. package/box-queue.js +161 -0
  29. package/box-queue.js.map +1 -0
  30. package/box-queue.ts +188 -0
  31. package/box-wire.js +18 -0
  32. package/box-wire.js.map +1 -0
  33. package/box-wire.ts +57 -0
  34. package/deno.json +1 -0
  35. package/domains.js +226 -0
  36. package/domains.js.map +1 -0
  37. package/domains.ts +300 -0
  38. package/graph.js +31 -0
  39. package/graph.js.map +1 -0
  40. package/graph.ts +54 -0
  41. package/mod.js +5 -0
  42. package/mod.js.map +1 -0
  43. package/mod.ts +5 -0
  44. package/options.js +19 -0
  45. package/options.js.map +1 -0
  46. package/options.ts +48 -0
  47. package/package.json +54 -4
  48. package/receive.js +206 -0
  49. package/receive.js.map +1 -0
  50. package/receive.ts +266 -0
  51. package/routes.js +43 -0
  52. package/routes.js.map +1 -0
  53. package/routes.ts +45 -0
  54. package/sender.js +101 -0
  55. package/sender.js.map +1 -0
  56. package/sender.ts +124 -0
  57. package/service.js +102 -0
  58. package/service.js.map +1 -0
  59. package/service.ts +107 -0
package/sender.js ADDED
@@ -0,0 +1,101 @@
1
+ // Resend at the same Sender boundary as the other transports. A sending-only
2
+ // key suffices: no account management or read credential leaves with a letter.
3
+ // The API's `id` is not the RFC Message-ID, so it never becomes a thread id.
4
+ import { Undeliverable, Unsent } from "@yaks/host/senders";
5
+ import { root, said as error } from "./api.js";
6
+ let payload = (m, tags)=>({
7
+ tags: Object.entries({
8
+ ...tags,
9
+ ...m.id ? {
10
+ yak_letter: m.id
11
+ } : {}
12
+ }).map(([name, value])=>({
13
+ name,
14
+ value
15
+ })),
16
+ from: m.name ? `${m.name} <${m.from}>` : m.from,
17
+ to: [
18
+ m.to
19
+ ].flat(),
20
+ ...m.cc ? {
21
+ cc: [
22
+ m.cc
23
+ ]
24
+ } : {},
25
+ reply_to: m.replyAddress ?? m.from,
26
+ subject: m.subject,
27
+ text: m.text,
28
+ html: m.html || (m.text ? '' : '<div></div>'),
29
+ ...m.replyTo ? {
30
+ headers: {
31
+ 'In-Reply-To': `<${m.replyTo}>`,
32
+ References: `<${m.replyTo}>`
33
+ }
34
+ } : {}
35
+ });
36
+ // Whether Resend's message is about the letter's readers: it names the `to`
37
+ // or `cc` field, or one of their addresses.
38
+ let naming = (message, m)=>/`(to|cc)`/.test(message) || [
39
+ m.to,
40
+ m.cc ?? []
41
+ ].flat().some((a)=>!!a && message.toLowerCase().includes(a.toLowerCase()));
42
+ /** Resend's sending API. Only a refusal known to precede acceptance retries
43
+ * (a dropped connection, a 429, a refused key), and a refusal of the letter's
44
+ * recipient is {@link Undeliverable};
45
+ * an uncertain response never causes another send or another provider to send.
46
+ * Resend exposes the RFC Message-ID through webhooks and retrieval, rather
47
+ * than its send response. An accepted letter therefore has an empty receipt. */ export let resend = ({ token, base, fetch: call, tags = {} })=>({
48
+ send: async (m)=>{
49
+ let response = await (call ?? fetch)(`${root(base)}/emails`, {
50
+ method: 'POST',
51
+ headers: {
52
+ authorization: `Bearer ${token}`,
53
+ 'content-type': 'application/json'
54
+ },
55
+ body: JSON.stringify(payload(m, tags))
56
+ }).catch((error)=>{
57
+ if (/\(Connect\)/.test(String(error))) {
58
+ throw new Unsent(`not sent: ${String(error)}`);
59
+ }
60
+ throw error;
61
+ });
62
+ if (response.status == 429) {
63
+ let seconds = Number(response.headers.get('retry-after'));
64
+ throw new Unsent('Resend has not accepted the letter (HTTP 429)', seconds > 0 ? seconds * 1000 : 1000);
65
+ }
66
+ let said = await error(response);
67
+ // A refused key (401, 403: unknown, revoked, or not allowed this from
68
+ // domain) is refused before the letter is taken, and a repaired key
69
+ // cures it, so the letter waits rather than bounces. Its answer speaks
70
+ // of the key and the domain, never the letter.
71
+ if (response.status == 401 || response.status == 403) {
72
+ throw new Unsent(`Resend refused the key (HTTP ${response.status})` + (said.message ? `: ${said.message.slice(0, 200)}` : ''));
73
+ }
74
+ // A validation refusal that names a reader, such as one at example.com,
75
+ // which Resend never sends to, is the letter's own bounce. Its answer is
76
+ // about an address the letter already carries.
77
+ if ((response.status == 400 || response.status == 422) && naming(said.message, m)) {
78
+ throw new Undeliverable(`Resend refused the recipient (HTTP ${response.status}): ` + said.message.slice(0, 200));
79
+ }
80
+ if (!response.ok) {
81
+ // Provider bodies can echo a private letter or credential. Keep neither
82
+ // in the failure that callers record in the graph; the error's name,
83
+ // Resend's code for it, is neither.
84
+ throw new Error(`Resend send failed (HTTP ${response.status}` + (said.name ? ` ${said.name}` : '') + ')');
85
+ }
86
+ let answer = await response.json();
87
+ if (!answer || typeof answer != 'object' || !('id' in answer) || typeof answer.id != 'string' || !answer.id) {
88
+ throw new Error('Resend accepted no email id');
89
+ }
90
+ return {};
91
+ }
92
+ });
93
+ /** Build from host configuration, leaving missing credentials waiting. */ export let configured = (options)=>options.token ? {
94
+ sender: resend({
95
+ ...options,
96
+ token: options.token
97
+ })
98
+ } : {
99
+ waiting: 'waiting for credentials: a resend sender needs `token`'
100
+ };
101
+ //# sourceMappingURL=sender.js.map
package/sender.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sender.js","sources":["./sender.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,+EAA+E;AAC/E,6EAA6E;AAC7E,SAAS,aAAa,EAAE,MAAM,kCAAuC;AAErE,SAAqB,IAAI,EAAE,QAAQ,KAAK,mBAAkB;AAU1D,IAAI,UAAU,CAAC,GAAY,OAAiC,CAAC;IAC3D,MAAM,OAAO,OAAO,CAAC;MAAE,GAAG,IAAI;MAAE,GAAI,EAAE,EAAE,GAAG;QAAE,YAAY,EAAE,EAAE;MAAC,IAAI,CAAC,CAAC;IAAE,GAAG,GAAG,CAAC,CAC3E,CAAC,MAAM,MAAM,GACV,CAAC;QAAE;QAAM;MAAM,CAAC;IACrB,MAAM,EAAE,IAAI,GAAG,GAAG,EAAE,IAAI,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC,CAAC,GAAG,EAAE,IAAI;IAC/C,IAAI;MAAC,EAAE,EAAE;KAAC,CAAC,IAAI;IACf,GAAI,EAAE,EAAE,GAAG;MAAE,IAAI;QAAC,EAAE,EAAE;OAAC;IAAC,IAAI,CAAC,CAAC;IAC9B,UAAU,EAAE,YAAY,IAAI,EAAE,IAAI;IAClC,SAAS,EAAE,OAAO;IAClB,MAAM,EAAE,IAAI;IACZ,MAAM,EAAE,IAAI,IAAI,CAAC,EAAE,IAAI,GAAG,KAAK,aAAa;IAC5C,GAAI,EAAE,OAAO,GACT;MACA,SAAS;QACP,eAAe,CAAC,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC,CAAC;QAC/B,YAAY,CAAC,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC,CAAC;MAC9B;IACF,IACE,CAAC,CAAC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MAAM,GAAG,EAAE;MAE5D;MACA,wEAAwE;MACxE,yEAAyE;MACzE,+CAA+C;MAC/C,IACE,CAAC,SAAS,MAAM,IAAI,OAAO,SAAS,MAAM,IAAI,GAAG,KACjD,OAAO,KAAK,OAAO,EAAE,IACrB;QACA,MAAM,IAAI,cACR,CAAC,mCAAmC,EAAE,SAAS,MAAM,CAAC,GAAG,CAAC,GACxD,KAAK,OAAO,CAAC,KAAK,CAAC,GAAG;MAE5B;MACA,IAAI,CAAC,SAAS,EAAE,EAAE;QAChB,wEAAwE;QACxE,qEAAqE;QACrE,oCAAoC;QACpC,MAAM,IAAI,MACR,CAAC,yBAAyB,EAAE,SAAS,MAAM,EAAE,GAC3C,CAAC,KAAK,IAAI,GAAG,CAAC,CAAC,EAAE,KAAK,IAAI,EAAE,GAAG,EAAE,IAAI;MAE3C;MACA,IAAI,SAAkB,MAAM,SAAS,IAAI;MACzC,IACE,CAAC,UAAU,OAAO,UAAU,YAAY,CAAC,CAAC,QAAQ,MAAM,KACxD,OAAO,OAAO,EAAE,IAAI,YAAY,CAAC,OAAO,EAAE,EAC1C;QACA,MAAM,IAAI,MAAM;MAClB;MACA,OAAO,CAAC;IACV;EACF,CAAC,EAAC;AAEF,wEAAwE,GACxE,OAAO,IAAI,aAAa,CACtB,UAEA,QAAQ,KAAK,GACT;IAAE,QAAQ,OAAO;MAAE,GAAG,OAAO;MAAE,OAAO,QAAQ,KAAK;IAAC;EAAG,IACvD;IAAE,SAAS;EAAyD,EAAC"}
package/sender.ts ADDED
@@ -0,0 +1,124 @@
1
+ // Resend at the same Sender boundary as the other transports. A sending-only
2
+ // key suffices: no account management or read credential leaves with a letter.
3
+ // The API's `id` is not the RFC Message-ID, so it never becomes a thread id.
4
+ import { Undeliverable, Unsent } from '@yaks/host/senders'
5
+ import type { Message, Sender } from '@yaks/host/senders'
6
+ import { type Fetch, root, said as error } from './api.js'
7
+
8
+ /** Credentials and the HTTP boundary, supplied by the host. */
9
+ export type Resend = {
10
+ token: string
11
+ base?: string
12
+ fetch?: Fetch
13
+ tags?: Record<string, string>
14
+ }
15
+
16
+ let payload = (m: Message, tags: Record<string, string>) => ({
17
+ tags: Object.entries({ ...tags, ...(m.id ? { yak_letter: m.id } : {}) }).map((
18
+ [name, value],
19
+ ) => ({ name, value })),
20
+ from: m.name ? `${m.name} <${m.from}>` : m.from,
21
+ to: [m.to].flat(),
22
+ ...(m.cc ? { cc: [m.cc] } : {}),
23
+ reply_to: m.replyAddress ?? m.from,
24
+ subject: m.subject,
25
+ text: m.text,
26
+ html: m.html || (m.text ? '' : '<div></div>'),
27
+ ...(m.replyTo
28
+ ? {
29
+ headers: {
30
+ 'In-Reply-To': `<${m.replyTo}>`,
31
+ References: `<${m.replyTo}>`,
32
+ },
33
+ }
34
+ : {}),
35
+ })
36
+
37
+ // Whether Resend's message is about the letter's readers: it names the `to`
38
+ // or `cc` field, or one of their addresses.
39
+ let naming = (message: string, m: Message) =>
40
+ /`(to|cc)`/.test(message) ||
41
+ [m.to, m.cc ?? []].flat().some((a) =>
42
+ !!a && message.toLowerCase().includes(a.toLowerCase())
43
+ )
44
+
45
+ /** Resend's sending API. Only a refusal known to precede acceptance retries
46
+ * (a dropped connection, a 429, a refused key), and a refusal of the letter's
47
+ * recipient is {@link Undeliverable};
48
+ * an uncertain response never causes another send or another provider to send.
49
+ * Resend exposes the RFC Message-ID through webhooks and retrieval, rather
50
+ * than its send response. An accepted letter therefore has an empty receipt. */
51
+ export let resend = (
52
+ { token, base, fetch: call, tags = {} }: Resend,
53
+ ): Sender => ({
54
+ send: async (m) => {
55
+ let response = await (call ?? fetch)(`${root(base)}/emails`, {
56
+ method: 'POST',
57
+ headers: {
58
+ authorization: `Bearer ${token}`,
59
+ 'content-type': 'application/json',
60
+ },
61
+ body: JSON.stringify(payload(m, tags)),
62
+ }).catch((error) => {
63
+ if (/\(Connect\)/.test(String(error))) {
64
+ throw new Unsent(`not sent: ${String(error)}`)
65
+ }
66
+ throw error
67
+ })
68
+ if (response.status == 429) {
69
+ let seconds = Number(response.headers.get('retry-after'))
70
+ throw new Unsent(
71
+ 'Resend has not accepted the letter (HTTP 429)',
72
+ seconds > 0 ? seconds * 1000 : 1000,
73
+ )
74
+ }
75
+ let said = await error(response)
76
+ // A refused key (401, 403: unknown, revoked, or not allowed this from
77
+ // domain) is refused before the letter is taken, and a repaired key
78
+ // cures it, so the letter waits rather than bounces. Its answer speaks
79
+ // of the key and the domain, never the letter.
80
+ if (response.status == 401 || response.status == 403) {
81
+ throw new Unsent(
82
+ `Resend refused the key (HTTP ${response.status})` +
83
+ (said.message ? `: ${said.message.slice(0, 200)}` : ''),
84
+ )
85
+ }
86
+ // A validation refusal that names a reader, such as one at example.com,
87
+ // which Resend never sends to, is the letter's own bounce. Its answer is
88
+ // about an address the letter already carries.
89
+ if (
90
+ (response.status == 400 || response.status == 422) &&
91
+ naming(said.message, m)
92
+ ) {
93
+ throw new Undeliverable(
94
+ `Resend refused the recipient (HTTP ${response.status}): ` +
95
+ said.message.slice(0, 200),
96
+ )
97
+ }
98
+ if (!response.ok) {
99
+ // Provider bodies can echo a private letter or credential. Keep neither
100
+ // in the failure that callers record in the graph; the error's name,
101
+ // Resend's code for it, is neither.
102
+ throw new Error(
103
+ `Resend send failed (HTTP ${response.status}` +
104
+ (said.name ? ` ${said.name}` : '') + ')',
105
+ )
106
+ }
107
+ let answer: unknown = await response.json()
108
+ if (
109
+ !answer || typeof answer != 'object' || !('id' in answer) ||
110
+ typeof answer.id != 'string' || !answer.id
111
+ ) {
112
+ throw new Error('Resend accepted no email id')
113
+ }
114
+ return {}
115
+ },
116
+ })
117
+
118
+ /** Build from host configuration, leaving missing credentials waiting. */
119
+ export let configured = (
120
+ options: Partial<Resend>,
121
+ ): { sender?: Sender; waiting?: string } =>
122
+ options.token
123
+ ? { sender: resend({ ...options, token: options.token }) }
124
+ : { waiting: 'waiting for credentials: a resend sender needs `token`' }
package/service.js ADDED
@@ -0,0 +1,102 @@
1
+ import { sleep } from "@yaks/fp";
2
+ import { path, ticket } from "./box-wire.js";
3
+ import { domains, sendingKeys } from "./domains.js";
4
+ import { retrieved } from "./receive.js";
5
+ export let service = async (host, options = {}, signal = AbortSignal.abort())=>{
6
+ if (!options.box?.url) return;
7
+ let url = new URL(path, options.box.url);
8
+ if (url.protocol !== 'https:') throw new Error('Resend box needs HTTPS');
9
+ let once = signal.aborted;
10
+ let call = async (method, cursor, body = '')=>{
11
+ let at = new URL(url);
12
+ if (cursor) at.searchParams.set('cursor', cursor);
13
+ let secret = options.box?.secret;
14
+ if (!secret) throw new Error('Resend box signing secret is unavailable');
15
+ let response = await fetch(at, {
16
+ method,
17
+ headers: {
18
+ authorization: 'Bearer ' + await ticket(secret, method, body),
19
+ 'content-type': 'application/json'
20
+ },
21
+ ...body ? {
22
+ body
23
+ } : {},
24
+ redirect: 'manual',
25
+ signal: AbortSignal.timeout(20_000)
26
+ });
27
+ if (!response.ok) {
28
+ throw new Error(`Resend box endpoint returned HTTP ${response.status}`);
29
+ }
30
+ return response;
31
+ };
32
+ let pass = async (cursor)=>{
33
+ let response = await call('GET', cursor);
34
+ let page = await response.json();
35
+ if (!page.jobs.length) return page.cursor;
36
+ let token = options.box?.token;
37
+ if (!token) throw new Error('The box Resend credential is unavailable');
38
+ let provider = {
39
+ token,
40
+ fetch: bounded
41
+ };
42
+ let domain = domains(provider);
43
+ if (!host.vault) throw new Error('Resend box needs a local vault');
44
+ let keys = sendingKeys(provider, host.vault);
45
+ for (let { id, job, sender } of page.jobs){
46
+ if (!once && signal.aborted) return;
47
+ try {
48
+ let result;
49
+ if (job.op === 'receive') {
50
+ result = {
51
+ incoming: await retrieved(provider, job.email)
52
+ };
53
+ } else {
54
+ let got = job.op === 'setup' ? await domain.setup(job.name) : job.op === 'read' ? await domain.read(job.name) : await domain.remove(job.name).then(()=>null);
55
+ result = {
56
+ domain: got ?? null
57
+ };
58
+ if (job.op === 'remove') await keys.remove(job.name);
59
+ if (sender && got?.records.length && got.records.every((r)=>r.arrived)) {
60
+ result.token = await keys.pending(job.name);
61
+ }
62
+ }
63
+ let accepted = await call('POST', undefined, JSON.stringify({
64
+ id,
65
+ result
66
+ }));
67
+ await accepted.body?.cancel();
68
+ if ('name' in job && 'token' in result) {
69
+ await keys.acknowledged(job.name);
70
+ }
71
+ } catch (error) {
72
+ await host.report?.(error, {
73
+ tags: {
74
+ step: 'Resend box',
75
+ verb: job.op
76
+ }
77
+ });
78
+ }
79
+ }
80
+ return page.cursor;
81
+ };
82
+ let cursor;
83
+ do {
84
+ try {
85
+ cursor = await pass(cursor);
86
+ } catch (error) {
87
+ await host.report?.(error, {
88
+ tags: {
89
+ step: 'Resend box polling'
90
+ }
91
+ });
92
+ cursor = undefined;
93
+ }
94
+ if (!once) await sleep(cursor ? 1000 : 15_000, signal);
95
+ }while (!signal.aborted)
96
+ };
97
+ let bounded = (input, init)=>fetch(input, {
98
+ ...init,
99
+ redirect: 'manual',
100
+ signal: AbortSignal.timeout(15_000)
101
+ });
102
+ //# sourceMappingURL=service.js.map
package/service.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service.js","sources":["./service.ts"],"names":[],"mappings":"AAAA,SAAS,KAAK,wBAA6B;AAE3C,SAAS,IAAI,EAAe,MAAM,wBAAkC;AACpE,SAAS,OAAO,EAAE,WAAW,uBAAsB;AACnD,SAAS,SAAS,uBAAsB;AAMxC,OAAO,IAAI,UAAU,OACnB,MACA,UAAmB,CAAC,CAAC,EACrB,SAAsB,YAAY,KAAK,EAAE;EAEzC,IAAI,CAAC,QAAQ,GAAG,EAAE,KAAK;EACvB,IAAI,MAAM,IAAI,IAAI,MAAM,QAAQ,GAAG,CAAC,GAAG;EACvC,IAAI,IAAI,QAAQ,KAAK,UAAU,MAAM,IAAI,MAAM;EAC/C,IAAI,OAAO,OAAO,OAAO;EAEzB,IAAI,OAAO,OAAO,QAAgB,QAAiB,OAAO,EAAE;IAC1D,IAAI,KAAK,IAAI,IAAI;IACjB,IAAI,QAAQ,GAAG,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,OAAO,IAAI,CAAC,IAAI,IAAI,IAC1B,MAAM,OAAO,MAAM,CAAC,IAAI,IAAI,EAAE,IAAI,CAAC,IAAM;UAC7C,SAAS;YAAE,QAAQ,OAAO;UAAK;UAC/B,IAAI,IAAI,EAAE,KAAK,UAAU,MAAM,KAAK,MAAM,CAAC,IAAI,IAAI;UACnD,IACE,UAAU,KAAK,QAAQ,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC,IAAM,EAAE,OAAO,GACnE;YACA,OAAO,KAAK,GAAG,MAAM,KAAK,OAAO,CAAC,IAAI,IAAI;UAC5C;QACF;QACA,IAAI,WAAW,MAAM,KACnB,QACA,WACA,KAAK,SAAS,CAAC;UAAE;UAAI;QAAO;QAE9B,MAAM,SAAS,IAAI,EAAE;QACrB,IAAI,UAAU,OAAO,WAAW,QAAQ;UACtC,MAAM,KAAK,YAAY,CAAC,IAAI,IAAI;QAClC;MACF,EAAE,OAAO,OAAO;QACd,MAAM,KAAK,MAAM,GAAG,OAAO;UACzB,MAAM;YAAE,MAAM;YAAc,MAAM,IAAI,EAAE;UAAC;QAC3C;MACF;IACF;IACA,OAAO,KAAK,MAAM;EACpB;EAEA,IAAI;EACJ,GAAG;IACD,IAAI;MACF,SAAS,MAAM,KAAK;IACtB,EAAE,OAAO,OAAO;MACd,MAAM,KAAK,MAAM,GAAG,OAAO;QAAE,MAAM;UAAE,MAAM;QAAqB;MAAE;MAClE,SAAS;IACX;IACA,IAAI,CAAC,MAAM,MAAM,MAAM,SAAS,OAAO,QAAQ;EACjD,QAAS,CAAC,OAAO,OAAO,CAAC;AAC3B,EAAC;AAED,IAAI,UAAwB,CAAC,OAAO,OAClC,MAAM,OAAO;IACX,GAAG,IAAI;IACP,UAAU;IACV,QAAQ,YAAY,OAAO,CAAC;EAC9B"}
package/service.ts ADDED
@@ -0,0 +1,107 @@
1
+ import { sleep } from '@yaks/fp'
2
+ import type { Host } from 'jsr:@yaks/host@0.2.36'
3
+ import { path, type Result, ticket, type Work } from './box-wire.js'
4
+ import { domains, sendingKeys } from './domains.js'
5
+ import { retrieved } from './receive.js'
6
+
7
+ type Options = {
8
+ box?: { url?: string; secret?: string; token?: string }
9
+ }
10
+
11
+ export let service = async (
12
+ host: Host,
13
+ options: Options = {},
14
+ signal: AbortSignal = AbortSignal.abort(),
15
+ ): Promise<void> => {
16
+ if (!options.box?.url) return
17
+ let url = new URL(path, options.box.url)
18
+ if (url.protocol !== 'https:') throw new Error('Resend box needs HTTPS')
19
+ let once = signal.aborted
20
+
21
+ let call = async (method: string, cursor?: string, body = '') => {
22
+ let at = new URL(url)
23
+ if (cursor) at.searchParams.set('cursor', cursor)
24
+ let secret = options.box?.secret
25
+ if (!secret) throw new Error('Resend box signing secret is unavailable')
26
+ let response = await fetch(at, {
27
+ method,
28
+ headers: {
29
+ authorization: 'Bearer ' + await ticket(secret, method, body),
30
+ 'content-type': 'application/json',
31
+ },
32
+ ...body ? { body } : {},
33
+ redirect: 'manual',
34
+ signal: AbortSignal.timeout(20_000),
35
+ })
36
+ if (!response.ok) {
37
+ throw new Error(`Resend box endpoint returned HTTP ${response.status}`)
38
+ }
39
+ return response
40
+ }
41
+
42
+ let pass = async (cursor?: string) => {
43
+ let response = await call('GET', cursor)
44
+ let page = await response.json() as { jobs: Work[]; cursor?: string }
45
+ if (!page.jobs.length) return page.cursor
46
+ let token = options.box?.token
47
+ if (!token) throw new Error('The box Resend credential is unavailable')
48
+ let provider = { token, fetch: bounded }
49
+ let domain = domains(provider)
50
+ if (!host.vault) throw new Error('Resend box needs a local vault')
51
+ let keys = sendingKeys(provider, host.vault)
52
+ for (let { id, job, sender } of page.jobs) {
53
+ if (!once && signal.aborted) return
54
+ try {
55
+ let result: Result
56
+ if (job.op === 'receive') {
57
+ result = { incoming: await retrieved(provider, job.email) }
58
+ } else {
59
+ let got = job.op === 'setup'
60
+ ? await domain.setup(job.name)
61
+ : job.op === 'read'
62
+ ? await domain.read(job.name)
63
+ : await domain.remove(job.name).then(() => null)
64
+ result = { domain: got ?? null }
65
+ if (job.op === 'remove') await keys.remove(job.name)
66
+ if (
67
+ sender && got?.records.length && got.records.every((r) => r.arrived)
68
+ ) {
69
+ result.token = await keys.pending(job.name)
70
+ }
71
+ }
72
+ let accepted = await call(
73
+ 'POST',
74
+ undefined,
75
+ JSON.stringify({ id, result }),
76
+ )
77
+ await accepted.body?.cancel()
78
+ if ('name' in job && 'token' in result) {
79
+ await keys.acknowledged(job.name)
80
+ }
81
+ } catch (error) {
82
+ await host.report?.(error, {
83
+ tags: { step: 'Resend box', verb: job.op },
84
+ })
85
+ }
86
+ }
87
+ return page.cursor
88
+ }
89
+
90
+ let cursor: string | undefined
91
+ do {
92
+ try {
93
+ cursor = await pass(cursor)
94
+ } catch (error) {
95
+ await host.report?.(error, { tags: { step: 'Resend box polling' } })
96
+ cursor = undefined
97
+ }
98
+ if (!once) await sleep(cursor ? 1000 : 15_000, signal)
99
+ } while (!signal.aborted)
100
+ }
101
+
102
+ let bounded: typeof fetch = (input, init) =>
103
+ fetch(input, {
104
+ ...init,
105
+ redirect: 'manual',
106
+ signal: AbortSignal.timeout(15_000),
107
+ })