@abraca/resend 2.90.0 → 2.91.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +6 -12
- package/src/bootstrap.ts +0 -153
- package/src/inbound-server.ts +0 -413
- package/src/index.ts +0 -128
- package/src/outbox-watcher.ts +0 -367
- package/src/render.ts +0 -112
- package/src/resend-client.ts +0 -50
- package/src/server.ts +0 -324
- package/src/utils.ts +0 -6
package/src/index.ts
DELETED
|
@@ -1,128 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
/**
|
|
3
|
-
* @abraca/resend — entry point.
|
|
4
|
-
*
|
|
5
|
-
* Environment variables:
|
|
6
|
-
* ABRA_URL (required) — Abracadabra server URL
|
|
7
|
-
* ABRA_SPACE_ID — Pin to a specific space (default: first visible)
|
|
8
|
-
* ABRA_KEY_FILE — Ed25519 seed path (default ~/.abracadabra/resend.key)
|
|
9
|
-
* ABRA_INVITE_CODE — Used only on first-run register
|
|
10
|
-
* ABRA_AGENT_NAME — Display name (default "Resend Bridge")
|
|
11
|
-
*
|
|
12
|
-
* RESEND_API_KEY (required) — Resend API key
|
|
13
|
-
* RESEND_FROM (required) — Default `from` address
|
|
14
|
-
* RESEND_INBOUND_ENABLED — "false" to skip the webhook server (default true)
|
|
15
|
-
* RESEND_INBOUND_PORT — Bind port for /inbound (default 0 = ephemeral)
|
|
16
|
-
* RESEND_INBOUND_HOST — Bind host (default 0.0.0.0)
|
|
17
|
-
* RESEND_INBOUND_SECRET — Required when inbound is enabled (Svix signing secret)
|
|
18
|
-
*/
|
|
19
|
-
import { bootstrap } from "./bootstrap.ts";
|
|
20
|
-
import { InboundServer } from "./inbound-server.ts";
|
|
21
|
-
import { OutboxWatcher } from "./outbox-watcher.ts";
|
|
22
|
-
import { ResendClient } from "./resend-client.ts";
|
|
23
|
-
import { AbracadabraResendServer } from "./server.ts";
|
|
24
|
-
|
|
25
|
-
function required(name: string): string {
|
|
26
|
-
const value = process.env[name];
|
|
27
|
-
if (!value || value.trim().length === 0) {
|
|
28
|
-
console.error(`[abracadabra-resend] Missing required env var: ${name}`);
|
|
29
|
-
process.exit(1);
|
|
30
|
-
}
|
|
31
|
-
return value;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
function boolEnv(name: string, fallback: boolean): boolean {
|
|
35
|
-
const v = process.env[name];
|
|
36
|
-
if (v === undefined) return fallback;
|
|
37
|
-
const norm = v.trim().toLowerCase();
|
|
38
|
-
if (["0", "false", "no", "off", ""].includes(norm)) return false;
|
|
39
|
-
return true;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
async function main(): Promise<void> {
|
|
43
|
-
const url = required("ABRA_URL");
|
|
44
|
-
const resendApiKey = required("RESEND_API_KEY");
|
|
45
|
-
const defaultFrom = required("RESEND_FROM");
|
|
46
|
-
|
|
47
|
-
const inboundEnabled = boolEnv("RESEND_INBOUND_ENABLED", true);
|
|
48
|
-
const inboundSecret = inboundEnabled
|
|
49
|
-
? required("RESEND_INBOUND_SECRET")
|
|
50
|
-
: process.env.RESEND_INBOUND_SECRET ?? "";
|
|
51
|
-
const inboundPort = process.env.RESEND_INBOUND_PORT
|
|
52
|
-
? Number(process.env.RESEND_INBOUND_PORT)
|
|
53
|
-
: 0;
|
|
54
|
-
const inboundHost = process.env.RESEND_INBOUND_HOST ?? "0.0.0.0";
|
|
55
|
-
|
|
56
|
-
const server = new AbracadabraResendServer({
|
|
57
|
-
url,
|
|
58
|
-
spaceId: process.env.ABRA_SPACE_ID,
|
|
59
|
-
keyFile: process.env.ABRA_KEY_FILE,
|
|
60
|
-
inviteCode: process.env.ABRA_INVITE_CODE,
|
|
61
|
-
agentName: process.env.ABRA_AGENT_NAME,
|
|
62
|
-
});
|
|
63
|
-
|
|
64
|
-
try {
|
|
65
|
-
await server.connect();
|
|
66
|
-
} catch (err: any) {
|
|
67
|
-
console.error(`[abracadabra-resend] Failed to connect: ${err?.message ?? err}`);
|
|
68
|
-
process.exit(1);
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
const boot = await bootstrap(server);
|
|
72
|
-
console.error(
|
|
73
|
-
`[abracadabra-resend] Bootstrapped Inbox=${boot.inboxId} Outbox=${boot.outboxId}`,
|
|
74
|
-
);
|
|
75
|
-
|
|
76
|
-
const sender = new ResendClient(resendApiKey);
|
|
77
|
-
const watcher = new OutboxWatcher({ server, sender, bootstrap: boot, defaultFrom });
|
|
78
|
-
watcher.start();
|
|
79
|
-
|
|
80
|
-
let inbound: InboundServer | null = null;
|
|
81
|
-
if (inboundEnabled) {
|
|
82
|
-
inbound = new InboundServer({
|
|
83
|
-
server,
|
|
84
|
-
bootstrap: boot,
|
|
85
|
-
secret: inboundSecret,
|
|
86
|
-
port: Number.isFinite(inboundPort) ? inboundPort : 0,
|
|
87
|
-
host: inboundHost,
|
|
88
|
-
});
|
|
89
|
-
try {
|
|
90
|
-
await inbound.start();
|
|
91
|
-
} catch (err: any) {
|
|
92
|
-
console.error(
|
|
93
|
-
`[abracadabra-resend] Inbound server failed to start: ${err?.message ?? err}`,
|
|
94
|
-
);
|
|
95
|
-
process.exit(1);
|
|
96
|
-
}
|
|
97
|
-
} else {
|
|
98
|
-
console.error(
|
|
99
|
-
"[abracadabra-resend] Inbound disabled (RESEND_INBOUND_ENABLED=false)",
|
|
100
|
-
);
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
console.error("[abracadabra-resend] Ready.");
|
|
104
|
-
|
|
105
|
-
const shutdown = async () => {
|
|
106
|
-
console.error("[abracadabra-resend] Shutting down...");
|
|
107
|
-
watcher.stop();
|
|
108
|
-
if (inbound) await inbound.stop();
|
|
109
|
-
await server.destroy();
|
|
110
|
-
process.exit(0);
|
|
111
|
-
};
|
|
112
|
-
process.on("SIGINT", shutdown);
|
|
113
|
-
process.on("SIGTERM", shutdown);
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
main().catch((err) => {
|
|
117
|
-
console.error("[abracadabra-resend] Fatal error:", err);
|
|
118
|
-
process.exit(1);
|
|
119
|
-
});
|
|
120
|
-
|
|
121
|
-
export { AbracadabraResendServer } from "./server.ts";
|
|
122
|
-
export { bootstrap } from "./bootstrap.ts";
|
|
123
|
-
export { InboundServer } from "./inbound-server.ts";
|
|
124
|
-
export { OutboxWatcher } from "./outbox-watcher.ts";
|
|
125
|
-
export { ResendClient } from "./resend-client.ts";
|
|
126
|
-
export type { ResendSender, SendResult } from "./resend-client.ts";
|
|
127
|
-
export { renderEmail, RenderError } from "./render.ts";
|
|
128
|
-
export type { EmailPayload } from "./render.ts";
|
package/src/outbox-watcher.ts
DELETED
|
@@ -1,367 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Outbox watcher. Observes the doc-tree map (deeply, so per-entry parentId
|
|
3
|
-
* updates surface) and dispatches any doc that lands under the "Ready" column.
|
|
4
|
-
*
|
|
5
|
-
* Dispatch flow per doc:
|
|
6
|
-
* render → resend.send → patch meta.resendId/sentAt → move to Sent
|
|
7
|
-
* On failure:
|
|
8
|
-
* patch meta.error/errorAt → move to Failed (left for human triage)
|
|
9
|
-
*
|
|
10
|
-
* Idempotency:
|
|
11
|
-
* - `meta.resendId` already set → skip (recovers from a restart that landed
|
|
12
|
-
* between Resend ack and the post-send move).
|
|
13
|
-
* - In-flight `Set<docId>` prevents the same observe burst from double-firing.
|
|
14
|
-
*/
|
|
15
|
-
import { patchEntry, toPlain } from "@abraca/dabra";
|
|
16
|
-
import type * as Y from "yjs";
|
|
17
|
-
import type { BootstrapResult } from "./bootstrap.ts";
|
|
18
|
-
import { renderEmail, RenderError } from "./render.ts";
|
|
19
|
-
import type { ResendSender } from "./resend-client.ts";
|
|
20
|
-
import type { AbracadabraResendServer } from "./server.ts";
|
|
21
|
-
|
|
22
|
-
export interface OutboxWatcherOptions {
|
|
23
|
-
server: AbracadabraResendServer;
|
|
24
|
-
sender: ResendSender;
|
|
25
|
-
bootstrap: BootstrapResult;
|
|
26
|
-
defaultFrom: string;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
interface EntryView {
|
|
30
|
-
id: string;
|
|
31
|
-
label: string;
|
|
32
|
-
parentId: string | null;
|
|
33
|
-
meta: Record<string, unknown>;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
function readEntry(treeMap: Y.Map<any>, id: string): EntryView | null {
|
|
37
|
-
const raw = treeMap.get(id);
|
|
38
|
-
if (!raw) return null;
|
|
39
|
-
const plain = toPlain(raw) as any;
|
|
40
|
-
if (!plain || typeof plain !== "object") return null;
|
|
41
|
-
return {
|
|
42
|
-
id,
|
|
43
|
-
label: typeof plain.label === "string" ? plain.label : "Untitled",
|
|
44
|
-
parentId: plain.parentId ?? null,
|
|
45
|
-
meta:
|
|
46
|
-
plain.meta && typeof plain.meta === "object"
|
|
47
|
-
? (plain.meta as Record<string, unknown>)
|
|
48
|
-
: {},
|
|
49
|
-
};
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export class OutboxWatcher {
|
|
53
|
-
private readonly server: AbracadabraResendServer;
|
|
54
|
-
private readonly sender: ResendSender;
|
|
55
|
-
private readonly bootstrap: BootstrapResult;
|
|
56
|
-
private readonly defaultFrom: string;
|
|
57
|
-
// Transient mid-dispatch guard ONLY: holds ids whose send is in flight RIGHT
|
|
58
|
-
// NOW, so a burst of observe events doesn't fire a second concurrent send
|
|
59
|
-
// before `meta.resendId` lands. Cleared the instant a dispatch settles — it
|
|
60
|
-
// is NEVER a durable "already sent" marker. The ONLY durable sent-state is
|
|
61
|
-
// `meta.resendId` on the document (set on success); a failed send is durably
|
|
62
|
-
// recorded by the move to the Failed column + `meta.error`. There is no
|
|
63
|
-
// in-memory "handled" set: a card re-queued into Ready (resendId cleared) is
|
|
64
|
-
// re-sent, and the bridge's view never diverges from the persisted tree.
|
|
65
|
-
private readonly inFlight = new Set<string>();
|
|
66
|
-
private observer: ((events: Y.YEvent<any>[]) => void) | null = null;
|
|
67
|
-
private treeMap: Y.Map<any> | null = null;
|
|
68
|
-
private rootDoc: Y.Doc | null = null;
|
|
69
|
-
private txHandler: ((tx: Y.Transaction) => void) | null = null;
|
|
70
|
-
private subdocsHandler:
|
|
71
|
-
| ((changes: {
|
|
72
|
-
added: Set<Y.Doc>;
|
|
73
|
-
removed: Set<Y.Doc>;
|
|
74
|
-
loaded: Set<Y.Doc>;
|
|
75
|
-
}) => void)
|
|
76
|
-
| null = null;
|
|
77
|
-
private updateHandler:
|
|
78
|
-
| ((update: Uint8Array, origin: unknown) => void)
|
|
79
|
-
| null = null;
|
|
80
|
-
private reconnectedHandler: (() => void) | null = null;
|
|
81
|
-
// The provider we attached `reconnected` to, kept so stop() can detach.
|
|
82
|
-
private reconnectProvider: { off(ev: string, cb: () => void): void } | null =
|
|
83
|
-
null;
|
|
84
|
-
// Per-subdoc afterTransaction handlers. Tracked so we (a) detach them on
|
|
85
|
-
// stop() and (b) never stack a second listener when the same subdoc reloads
|
|
86
|
-
// (the old code re-`on`'d every subdoc on every `subdocs` event — an
|
|
87
|
-
// unbounded listener leak that grew for the life of the daemon).
|
|
88
|
-
private readonly subdocHandlers = new Map<
|
|
89
|
-
Y.Doc,
|
|
90
|
-
(tx: Y.Transaction) => void
|
|
91
|
-
>();
|
|
92
|
-
|
|
93
|
-
constructor(opts: OutboxWatcherOptions) {
|
|
94
|
-
this.server = opts.server;
|
|
95
|
-
this.sender = opts.sender;
|
|
96
|
-
this.bootstrap = opts.bootstrap;
|
|
97
|
-
this.defaultFrom = opts.defaultFrom;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
start(): void {
|
|
101
|
-
const treeMap = this.server.getTreeMap();
|
|
102
|
-
if (!treeMap) {
|
|
103
|
-
throw new Error("OutboxWatcher.start: server is not connected");
|
|
104
|
-
}
|
|
105
|
-
this.treeMap = treeMap;
|
|
106
|
-
|
|
107
|
-
const rootDoc = this.server.rootDocument;
|
|
108
|
-
if (!rootDoc) {
|
|
109
|
-
throw new Error("OutboxWatcher.start: root doc not connected");
|
|
110
|
-
}
|
|
111
|
-
this.rootDoc = rootDoc;
|
|
112
|
-
|
|
113
|
-
// Initial scan — pick up anything already in Ready before we attached.
|
|
114
|
-
void this.scan("init");
|
|
115
|
-
|
|
116
|
-
// observeDeep on the tree map catches all the common edits (patchEntry
|
|
117
|
-
// mutating a nested Y.Map, treeMap.set replacing an entry).
|
|
118
|
-
const obs = (events: Y.YEvent<any>[]) => {
|
|
119
|
-
console.error(
|
|
120
|
-
`[abracadabra-resend] observeDeep fired (${events.length} events)`,
|
|
121
|
-
);
|
|
122
|
-
void this.scan("observeDeep");
|
|
123
|
-
};
|
|
124
|
-
treeMap.observeDeep(obs);
|
|
125
|
-
this.observer = obs;
|
|
126
|
-
|
|
127
|
-
// afterTransaction on the root Y.Doc fires for EVERY transaction applied
|
|
128
|
-
// to the doc — local writes and updates dispatched into this doc.
|
|
129
|
-
const onTx = (tx: Y.Transaction) => {
|
|
130
|
-
const changed: string[] = [];
|
|
131
|
-
for (const [type, events] of tx.changedParentTypes.entries()) {
|
|
132
|
-
const name = (type as any)._item ? (type as any)._item.parentSub : type.constructor.name;
|
|
133
|
-
const keys = events.flatMap((ev: any) => Array.from(ev.keysChanged ?? []));
|
|
134
|
-
changed.push(`${name ?? "type"}[${keys.join(",")}]`);
|
|
135
|
-
}
|
|
136
|
-
console.error(
|
|
137
|
-
`[abracadabra-resend] root afterTransaction (local=${tx.local}, origin=${String(tx.origin)}, changed=${changed.join(" | ") || "(none)"})`,
|
|
138
|
-
);
|
|
139
|
-
void this.scan("afterTransaction");
|
|
140
|
-
};
|
|
141
|
-
rootDoc.on("afterTransaction", onTx);
|
|
142
|
-
this.txHandler = onTx;
|
|
143
|
-
|
|
144
|
-
// Belt-and-suspenders: subdocs. abracadabra-rs may route some space-tree
|
|
145
|
-
// edits through subdoc payloads that don't fire transactions on the root
|
|
146
|
-
// doc directly. Watch every subdoc's transactions too — but dedup, so a
|
|
147
|
-
// subdoc that loads/unloads/reloads doesn't accumulate listeners.
|
|
148
|
-
const onSubdocs = (changes: {
|
|
149
|
-
added: Set<Y.Doc>;
|
|
150
|
-
removed: Set<Y.Doc>;
|
|
151
|
-
loaded: Set<Y.Doc>;
|
|
152
|
-
}) => {
|
|
153
|
-
console.error(
|
|
154
|
-
`[abracadabra-resend] subdocs: added=${changes.added.size} loaded=${changes.loaded.size} removed=${changes.removed.size}`,
|
|
155
|
-
);
|
|
156
|
-
for (const sub of changes.removed) {
|
|
157
|
-
const handler = this.subdocHandlers.get(sub);
|
|
158
|
-
if (handler) {
|
|
159
|
-
sub.off("afterTransaction", handler);
|
|
160
|
-
this.subdocHandlers.delete(sub);
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
for (const sub of [...changes.added, ...changes.loaded]) {
|
|
164
|
-
if (this.subdocHandlers.has(sub)) continue;
|
|
165
|
-
const handler = (tx: Y.Transaction) => {
|
|
166
|
-
console.error(
|
|
167
|
-
`[abracadabra-resend] subdoc afterTransaction (guid=${sub.guid}, local=${tx.local})`,
|
|
168
|
-
);
|
|
169
|
-
void this.scan("subdoc");
|
|
170
|
-
};
|
|
171
|
-
sub.on("afterTransaction", handler);
|
|
172
|
-
this.subdocHandlers.set(sub, handler);
|
|
173
|
-
}
|
|
174
|
-
};
|
|
175
|
-
rootDoc.on("subdocs", onSubdocs);
|
|
176
|
-
this.subdocsHandler = onSubdocs;
|
|
177
|
-
|
|
178
|
-
// Raw doc update — fires for every binary Yjs update applied to the doc,
|
|
179
|
-
// from any origin. If THIS doesn't fire when a remote writer changes
|
|
180
|
-
// state, the bridge's WS isn't delivering updates.
|
|
181
|
-
const onUpdate = (_update: Uint8Array, origin: unknown) => {
|
|
182
|
-
console.error(
|
|
183
|
-
`[abracadabra-resend] root update applied (origin=${String(origin)})`,
|
|
184
|
-
);
|
|
185
|
-
void this.scan("update");
|
|
186
|
-
};
|
|
187
|
-
rootDoc.on("update", onUpdate);
|
|
188
|
-
this.updateHandler = onUpdate;
|
|
189
|
-
|
|
190
|
-
// Re-scan whenever the provider's socket reconnects. The doc (and these
|
|
191
|
-
// observers) survive a reconnect untouched, and the post-reconnect sync
|
|
192
|
-
// re-fires them for anything that changed while we were offline — but an
|
|
193
|
-
// explicit, idempotent catch-up scan guarantees we don't sit on a Ready
|
|
194
|
-
// doc that landed during the outage.
|
|
195
|
-
const provider = this.server.rootProvider;
|
|
196
|
-
if (provider && typeof (provider as any).on === "function") {
|
|
197
|
-
const onReconnected = () => {
|
|
198
|
-
console.error("[abracadabra-resend] provider reconnected — re-scanning");
|
|
199
|
-
void this.scan("reconnected");
|
|
200
|
-
};
|
|
201
|
-
(provider as any).on("reconnected", onReconnected);
|
|
202
|
-
this.reconnectedHandler = onReconnected;
|
|
203
|
-
this.reconnectProvider = provider as any;
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
console.error(
|
|
207
|
-
`[abracadabra-resend] Outbox watcher attached (ready column ${this.bootstrap.columns.Ready})`,
|
|
208
|
-
);
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
stop(): void {
|
|
212
|
-
if (this.rootDoc && this.txHandler) {
|
|
213
|
-
this.rootDoc.off("afterTransaction", this.txHandler);
|
|
214
|
-
}
|
|
215
|
-
if (this.rootDoc && this.subdocsHandler) {
|
|
216
|
-
this.rootDoc.off("subdocs", this.subdocsHandler);
|
|
217
|
-
}
|
|
218
|
-
if (this.rootDoc && this.updateHandler) {
|
|
219
|
-
this.rootDoc.off("update", this.updateHandler);
|
|
220
|
-
}
|
|
221
|
-
for (const [sub, handler] of this.subdocHandlers) {
|
|
222
|
-
sub.off("afterTransaction", handler);
|
|
223
|
-
}
|
|
224
|
-
this.subdocHandlers.clear();
|
|
225
|
-
if (this.treeMap && this.observer) {
|
|
226
|
-
this.treeMap.unobserveDeep(this.observer);
|
|
227
|
-
}
|
|
228
|
-
if (this.reconnectProvider && this.reconnectedHandler) {
|
|
229
|
-
this.reconnectProvider.off("reconnected", this.reconnectedHandler);
|
|
230
|
-
}
|
|
231
|
-
this.txHandler = null;
|
|
232
|
-
this.subdocsHandler = null;
|
|
233
|
-
this.updateHandler = null;
|
|
234
|
-
this.reconnectedHandler = null;
|
|
235
|
-
this.reconnectProvider = null;
|
|
236
|
-
this.rootDoc = null;
|
|
237
|
-
this.observer = null;
|
|
238
|
-
this.treeMap = null;
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
private async scan(reason: string): Promise<void> {
|
|
242
|
-
const treeMap = this.treeMap;
|
|
243
|
-
if (!treeMap) return;
|
|
244
|
-
const readyColId = this.bootstrap.columns.Ready;
|
|
245
|
-
const outboxId = this.bootstrap.outboxId;
|
|
246
|
-
const columnIds = new Set(Object.values(this.bootstrap.columns));
|
|
247
|
-
const candidates: EntryView[] = [];
|
|
248
|
-
let inReadyCount = 0;
|
|
249
|
-
let totalEntries = 0;
|
|
250
|
-
// Dump every entry whose ancestor is Outbox so we can compare bridge
|
|
251
|
-
// view vs cou-sh view.
|
|
252
|
-
const outboxSubtree: Array<{ id: string; label: string; parentId: string | null; under: string }> = [];
|
|
253
|
-
treeMap.forEach((_raw: any, id: string) => {
|
|
254
|
-
totalEntries++;
|
|
255
|
-
const e = readEntry(treeMap, id);
|
|
256
|
-
if (!e) return;
|
|
257
|
-
// classify under outbox: direct child of Outbox, or grandchild via a column
|
|
258
|
-
if (e.parentId === outboxId || (e.parentId && columnIds.has(e.parentId))) {
|
|
259
|
-
outboxSubtree.push({
|
|
260
|
-
id,
|
|
261
|
-
label: e.label,
|
|
262
|
-
parentId: e.parentId,
|
|
263
|
-
under: e.parentId === outboxId ? "Outbox" :
|
|
264
|
-
e.parentId === this.bootstrap.columns.Draft ? "Draft" :
|
|
265
|
-
e.parentId === this.bootstrap.columns.Ready ? "Ready" :
|
|
266
|
-
e.parentId === this.bootstrap.columns.Sent ? "Sent" :
|
|
267
|
-
e.parentId === this.bootstrap.columns.Failed ? "Failed" : "?",
|
|
268
|
-
});
|
|
269
|
-
}
|
|
270
|
-
if (e.parentId !== readyColId) return;
|
|
271
|
-
inReadyCount++;
|
|
272
|
-
// Transient: a send for this id is already in flight in THIS process.
|
|
273
|
-
if (this.inFlight.has(id)) return;
|
|
274
|
-
// Durable: already sent (resendId persisted on the doc). Never re-send;
|
|
275
|
-
// just reconcile its column to Sent. This is the single source of truth
|
|
276
|
-
// for "done" — survives restarts, lives in document metadata.
|
|
277
|
-
if (typeof e.meta.resendId === "string" && e.meta.resendId.length > 0) {
|
|
278
|
-
this.moveTo(id, this.bootstrap.columns.Sent);
|
|
279
|
-
return;
|
|
280
|
-
}
|
|
281
|
-
candidates.push(e);
|
|
282
|
-
});
|
|
283
|
-
console.error(
|
|
284
|
-
`[abracadabra-resend] scan(${reason}): ${totalEntries} entries, ${inReadyCount} in Ready, ${candidates.length} to dispatch | Outbox subtree (${outboxSubtree.length}): ${outboxSubtree.map((e) => `${e.under}:"${e.label}"`).join(", ")}`,
|
|
285
|
-
);
|
|
286
|
-
|
|
287
|
-
for (const entry of candidates) {
|
|
288
|
-
this.inFlight.add(entry.id);
|
|
289
|
-
void this.dispatch(entry).finally(() => {
|
|
290
|
-
this.inFlight.delete(entry.id);
|
|
291
|
-
});
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
private async dispatch(entry: EntryView): Promise<void> {
|
|
296
|
-
const { id, label } = entry;
|
|
297
|
-
try {
|
|
298
|
-
const payload = await renderEmail(this.server, id, this.defaultFrom);
|
|
299
|
-
console.error(
|
|
300
|
-
`[abracadabra-resend] sending "${payload.subject}" → ${payload.to.join(", ")} (doc=${id})`,
|
|
301
|
-
);
|
|
302
|
-
const { id: resendId } = await this.sender.send(payload, {
|
|
303
|
-
"X-Abra-Doc-Id": id,
|
|
304
|
-
});
|
|
305
|
-
// Durable sent-marker: persisted on the doc, the only record of "sent".
|
|
306
|
-
this.patchMeta(id, { resendId, sentAt: Date.now(), error: null });
|
|
307
|
-
this.moveTo(id, this.bootstrap.columns.Sent);
|
|
308
|
-
console.error(
|
|
309
|
-
`[abracadabra-resend] sent "${payload.subject}" (resend=${resendId}, doc=${id})`,
|
|
310
|
-
);
|
|
311
|
-
} catch (err: any) {
|
|
312
|
-
// Durable failure record: meta.error + the move to the Failed column
|
|
313
|
-
// (below) — left for human triage. No in-memory marker.
|
|
314
|
-
const message =
|
|
315
|
-
err instanceof RenderError
|
|
316
|
-
? err.message
|
|
317
|
-
: err?.message
|
|
318
|
-
? String(err.message)
|
|
319
|
-
: String(err);
|
|
320
|
-
console.error(
|
|
321
|
-
`[abracadabra-resend] send failed for "${label}" (${id}): ${message}`,
|
|
322
|
-
);
|
|
323
|
-
this.patchMeta(id, { error: message, errorAt: Date.now() });
|
|
324
|
-
this.moveTo(id, this.bootstrap.columns.Failed);
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
private patchMeta(id: string, patch: Record<string, unknown>): void {
|
|
329
|
-
const treeMap = this.treeMap;
|
|
330
|
-
const rootDoc = this.server.rootDocument;
|
|
331
|
-
if (!treeMap || !rootDoc) return;
|
|
332
|
-
const current = readEntry(treeMap, id);
|
|
333
|
-
if (!current) return;
|
|
334
|
-
const nextMeta = { ...current.meta, ...patch };
|
|
335
|
-
for (const [k, v] of Object.entries(patch)) {
|
|
336
|
-
if (v === null) delete nextMeta[k];
|
|
337
|
-
}
|
|
338
|
-
rootDoc.transact(() => {
|
|
339
|
-
patchEntry(treeMap, id, {
|
|
340
|
-
meta: nextMeta,
|
|
341
|
-
updatedAt: Date.now(),
|
|
342
|
-
});
|
|
343
|
-
});
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
private moveTo(id: string, newParentId: string): void {
|
|
347
|
-
const treeMap = this.treeMap;
|
|
348
|
-
const rootDoc = this.server.rootDocument;
|
|
349
|
-
if (!treeMap || !rootDoc) return;
|
|
350
|
-
const now = Date.now();
|
|
351
|
-
rootDoc.transact(() => {
|
|
352
|
-
patchEntry(treeMap, id, {
|
|
353
|
-
parentId: newParentId,
|
|
354
|
-
order: now,
|
|
355
|
-
updatedAt: now,
|
|
356
|
-
});
|
|
357
|
-
});
|
|
358
|
-
// Best-effort registry reparent so REST/FTS sees the move too.
|
|
359
|
-
void this.server.client
|
|
360
|
-
.updateDocumentMeta(id, { parent_id: newParentId })
|
|
361
|
-
.catch((e) => {
|
|
362
|
-
console.error(
|
|
363
|
-
`[abracadabra-resend] REST reparent failed for ${id}: ${e?.message ?? e}`,
|
|
364
|
-
);
|
|
365
|
-
});
|
|
366
|
-
}
|
|
367
|
-
}
|
package/src/render.ts
DELETED
|
@@ -1,112 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Render an outbox document to an email-ready payload.
|
|
3
|
-
*
|
|
4
|
-
* Reads addressing from the doc's tree-entry `meta` (to/cc/bcc/subject/from/
|
|
5
|
-
* replyTo) and renders the body Y.XmlFragment via `@abraca/convert`'s
|
|
6
|
-
* `yjsToHtml` — which already emits a complete `<!DOCTYPE html>` doc with the
|
|
7
|
-
* doc label as `<h1>`, so the result is suitable as-is for Resend's `html`
|
|
8
|
-
* field.
|
|
9
|
-
*/
|
|
10
|
-
import { yjsToHtml } from "@abraca/convert";
|
|
11
|
-
import { toPlain } from "@abraca/dabra";
|
|
12
|
-
import type { AbracadabraResendServer } from "./server.ts";
|
|
13
|
-
|
|
14
|
-
export interface EmailPayload {
|
|
15
|
-
subject: string;
|
|
16
|
-
html: string;
|
|
17
|
-
to: string[];
|
|
18
|
-
cc?: string[];
|
|
19
|
-
bcc?: string[];
|
|
20
|
-
from?: string;
|
|
21
|
-
replyTo?: string;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
export class RenderError extends Error {
|
|
25
|
-
constructor(message: string) {
|
|
26
|
-
super(message);
|
|
27
|
-
this.name = "RenderError";
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
function asStringArray(value: unknown): string[] {
|
|
32
|
-
if (Array.isArray(value)) {
|
|
33
|
-
return value
|
|
34
|
-
.filter((v): v is string => typeof v === "string" && v.trim().length > 0)
|
|
35
|
-
.map((v) => v.trim());
|
|
36
|
-
}
|
|
37
|
-
if (typeof value === "string" && value.trim().length > 0) {
|
|
38
|
-
// Allow `to: "alice@x.com, bob@y.com"` as a convenience.
|
|
39
|
-
return value
|
|
40
|
-
.split(",")
|
|
41
|
-
.map((s) => s.trim())
|
|
42
|
-
.filter((s) => s.length > 0);
|
|
43
|
-
}
|
|
44
|
-
return [];
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
function asOptionalString(value: unknown): string | undefined {
|
|
48
|
-
return typeof value === "string" && value.trim().length > 0
|
|
49
|
-
? value.trim()
|
|
50
|
-
: undefined;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
interface OutboxEntry {
|
|
54
|
-
label: string;
|
|
55
|
-
meta: Record<string, unknown>;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
function readEntry(
|
|
59
|
-
server: AbracadabraResendServer,
|
|
60
|
-
docId: string,
|
|
61
|
-
): OutboxEntry | null {
|
|
62
|
-
const treeMap = server.getTreeMap();
|
|
63
|
-
if (!treeMap) return null;
|
|
64
|
-
const raw = treeMap.get(docId);
|
|
65
|
-
if (!raw) return null;
|
|
66
|
-
const plain = toPlain(raw) as any;
|
|
67
|
-
if (!plain || typeof plain !== "object") return null;
|
|
68
|
-
return {
|
|
69
|
-
label: typeof plain.label === "string" ? plain.label : "(no subject)",
|
|
70
|
-
meta:
|
|
71
|
-
plain.meta && typeof plain.meta === "object"
|
|
72
|
-
? (plain.meta as Record<string, unknown>)
|
|
73
|
-
: {},
|
|
74
|
-
};
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
export async function renderEmail(
|
|
78
|
-
server: AbracadabraResendServer,
|
|
79
|
-
docId: string,
|
|
80
|
-
defaultFrom: string,
|
|
81
|
-
): Promise<EmailPayload> {
|
|
82
|
-
const entry = readEntry(server, docId);
|
|
83
|
-
if (!entry) {
|
|
84
|
-
throw new RenderError(`Doc ${docId} has no tree entry.`);
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
const to = asStringArray(entry.meta.to);
|
|
88
|
-
if (to.length === 0) {
|
|
89
|
-
throw new RenderError(
|
|
90
|
-
`Doc ${docId} has no recipients — set meta.to (array of email addresses).`,
|
|
91
|
-
);
|
|
92
|
-
}
|
|
93
|
-
const cc = asStringArray(entry.meta.cc);
|
|
94
|
-
const bcc = asStringArray(entry.meta.bcc);
|
|
95
|
-
const from = asOptionalString(entry.meta.from) ?? defaultFrom;
|
|
96
|
-
const replyTo = asOptionalString(entry.meta.replyTo);
|
|
97
|
-
const subject = asOptionalString(entry.meta.subject) ?? entry.label;
|
|
98
|
-
|
|
99
|
-
const provider = await server.getChildProvider(docId);
|
|
100
|
-
const fragment = provider.document.getXmlFragment("default");
|
|
101
|
-
const html = yjsToHtml(fragment, subject);
|
|
102
|
-
|
|
103
|
-
return {
|
|
104
|
-
subject,
|
|
105
|
-
html,
|
|
106
|
-
to,
|
|
107
|
-
cc: cc.length ? cc : undefined,
|
|
108
|
-
bcc: bcc.length ? bcc : undefined,
|
|
109
|
-
from,
|
|
110
|
-
replyTo,
|
|
111
|
-
};
|
|
112
|
-
}
|
package/src/resend-client.ts
DELETED
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Thin wrapper around the official `resend` SDK. Kept separate so tests can
|
|
3
|
-
* substitute a fake without mocking the SDK directly.
|
|
4
|
-
*/
|
|
5
|
-
import { Resend } from "resend";
|
|
6
|
-
import type { EmailPayload } from "./render.ts";
|
|
7
|
-
|
|
8
|
-
export interface SendResult {
|
|
9
|
-
id: string;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export interface ResendSender {
|
|
13
|
-
send(payload: EmailPayload, headers?: Record<string, string>): Promise<SendResult>;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export class ResendClient implements ResendSender {
|
|
17
|
-
private readonly resend: Resend;
|
|
18
|
-
|
|
19
|
-
constructor(apiKey: string) {
|
|
20
|
-
this.resend = new Resend(apiKey);
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
async send(
|
|
24
|
-
payload: EmailPayload,
|
|
25
|
-
headers?: Record<string, string>,
|
|
26
|
-
): Promise<SendResult> {
|
|
27
|
-
if (!payload.from) {
|
|
28
|
-
throw new Error("ResendClient.send: payload.from is required");
|
|
29
|
-
}
|
|
30
|
-
const { data, error } = await this.resend.emails.send({
|
|
31
|
-
from: payload.from,
|
|
32
|
-
to: payload.to,
|
|
33
|
-
cc: payload.cc,
|
|
34
|
-
bcc: payload.bcc,
|
|
35
|
-
subject: payload.subject,
|
|
36
|
-
html: payload.html,
|
|
37
|
-
replyTo: payload.replyTo,
|
|
38
|
-
headers,
|
|
39
|
-
});
|
|
40
|
-
if (error) {
|
|
41
|
-
throw new Error(
|
|
42
|
-
`Resend rejected the message: ${error.message ?? JSON.stringify(error)}`,
|
|
43
|
-
);
|
|
44
|
-
}
|
|
45
|
-
if (!data?.id) {
|
|
46
|
-
throw new Error("Resend returned no id for the dispatched message");
|
|
47
|
-
}
|
|
48
|
-
return { id: data.id };
|
|
49
|
-
}
|
|
50
|
-
}
|