@sanoma-ai/connector-resend 0.0.0-stage → 0.1.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.
Files changed (67) hide show
  1. package/LICENSE +105 -0
  2. package/README.md +123 -2
  3. package/dist/connector.d.ts +36 -0
  4. package/dist/connector.js +36 -0
  5. package/dist/connector.js.map +1 -0
  6. package/dist/driver.d.ts +10 -0
  7. package/dist/driver.js +129 -0
  8. package/dist/driver.js.map +1 -0
  9. package/dist/fake.d.ts +18 -0
  10. package/dist/fake.js +32 -0
  11. package/dist/fake.js.map +1 -0
  12. package/dist/generated/client/client.gen.d.ts +2 -0
  13. package/dist/generated/client/client.gen.js +215 -0
  14. package/dist/generated/client/client.gen.js.map +1 -0
  15. package/dist/generated/client/index.d.ts +10 -0
  16. package/dist/generated/client/index.js +7 -0
  17. package/dist/generated/client/index.js.map +1 -0
  18. package/dist/generated/client/types.gen.d.ts +120 -0
  19. package/dist/generated/client/types.gen.js +3 -0
  20. package/dist/generated/client/types.gen.js.map +1 -0
  21. package/dist/generated/client/utils.gen.d.ts +37 -0
  22. package/dist/generated/client/utils.gen.js +227 -0
  23. package/dist/generated/client/utils.gen.js.map +1 -0
  24. package/dist/generated/client.gen.d.ts +12 -0
  25. package/dist/generated/client.gen.js +4 -0
  26. package/dist/generated/client.gen.js.map +1 -0
  27. package/dist/generated/core/auth.gen.d.ts +25 -0
  28. package/dist/generated/core/auth.gen.js +15 -0
  29. package/dist/generated/core/auth.gen.js.map +1 -0
  30. package/dist/generated/core/bodySerializer.gen.d.ts +25 -0
  31. package/dist/generated/core/bodySerializer.gen.js +58 -0
  32. package/dist/generated/core/bodySerializer.gen.js.map +1 -0
  33. package/dist/generated/core/params.gen.d.ts +43 -0
  34. package/dist/generated/core/params.gen.js +110 -0
  35. package/dist/generated/core/params.gen.js.map +1 -0
  36. package/dist/generated/core/pathSerializer.gen.d.ts +33 -0
  37. package/dist/generated/core/pathSerializer.gen.js +107 -0
  38. package/dist/generated/core/pathSerializer.gen.js.map +1 -0
  39. package/dist/generated/core/queryKeySerializer.gen.d.ts +18 -0
  40. package/dist/generated/core/queryKeySerializer.gen.js +93 -0
  41. package/dist/generated/core/queryKeySerializer.gen.js.map +1 -0
  42. package/dist/generated/core/serverSentEvents.gen.d.ts +71 -0
  43. package/dist/generated/core/serverSentEvents.gen.js +133 -0
  44. package/dist/generated/core/serverSentEvents.gen.js.map +1 -0
  45. package/dist/generated/core/types.gen.d.ts +83 -0
  46. package/dist/generated/core/types.gen.js +3 -0
  47. package/dist/generated/core/types.gen.js.map +1 -0
  48. package/dist/generated/core/utils.gen.d.ts +19 -0
  49. package/dist/generated/core/utils.gen.js +88 -0
  50. package/dist/generated/core/utils.gen.js.map +1 -0
  51. package/dist/generated/index.d.ts +2 -0
  52. package/dist/generated/index.js +3 -0
  53. package/dist/generated/index.js.map +1 -0
  54. package/dist/generated/sdk.gen.d.ts +27 -0
  55. package/dist/generated/sdk.gen.js +35 -0
  56. package/dist/generated/sdk.gen.js.map +1 -0
  57. package/dist/generated/types.gen.d.ts +192 -0
  58. package/dist/generated/types.gen.js +3 -0
  59. package/dist/generated/types.gen.js.map +1 -0
  60. package/dist/index.d.ts +39 -0
  61. package/dist/index.js +12 -0
  62. package/dist/index.js.map +1 -0
  63. package/dist/steps.d.ts +6 -0
  64. package/dist/steps.js +32 -0
  65. package/dist/steps.js.map +1 -0
  66. package/features/broadcast.feature +17 -0
  67. package/package.json +62 -3
package/LICENSE ADDED
@@ -0,0 +1,105 @@
1
+ # Functional Source License, Version 1.1, ALv2 Future License
2
+
3
+ ## Abbreviation
4
+
5
+ FSL-1.1-ALv2
6
+
7
+ ## Notice
8
+
9
+ Copyright 2026 Sanoma-AI
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly display
28
+ and redistribute the Software for any Permitted Purpose identified below.
29
+
30
+ ### Permitted Purpose
31
+
32
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
+ means making the Software available to others in a commercial product or
34
+ service that:
35
+
36
+ 1. substitutes for the Software;
37
+
38
+ 2. substitutes for any other product or service we offer using the Software
39
+ that exists as of the date we make the Software available; or
40
+
41
+ 3. offers the same or substantially similar functionality as the Software.
42
+
43
+ Permitted Purposes specifically include using the Software:
44
+
45
+ 1. for your internal use and access;
46
+
47
+ 2. for non-commercial education;
48
+
49
+ 3. for non-commercial research; and
50
+
51
+ 4. in connection with professional services that you provide to a licensee
52
+ using the Software in accordance with these Terms and Conditions.
53
+
54
+ ### Patents
55
+
56
+ To the extent your use for a Permitted Purpose would necessarily infringe our
57
+ patents, the license grant above includes a license under our patents. If you
58
+ make a claim against any party that the Software infringes or contributes to
59
+ the infringement of any patent, then your patent license to the Software ends
60
+ immediately.
61
+
62
+ ### Redistribution
63
+
64
+ The Terms and Conditions apply to all copies, modifications and derivatives of
65
+ the Software.
66
+
67
+ If you redistribute any copies, modifications or derivatives of the Software,
68
+ you must include a copy of or a link to these Terms and Conditions and not
69
+ remove any copyright notices provided in or with the Software.
70
+
71
+ ### Disclaimer
72
+
73
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
+
77
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
79
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
+
81
+ ### Trademarks
82
+
83
+ Except for displaying the License Details and identifying us as the origin of
84
+ the Software, you have no right under these Terms and Conditions to use our
85
+ trademarks, trade names, service marks or product names.
86
+
87
+ ## Grant of Future License
88
+
89
+ We hereby irrevocably grant you an additional license to use the Software under
90
+ the Apache License, Version 2.0 that is effective on the second anniversary of
91
+ the date we make the Software available. On or after that date, you may use the
92
+ Software under the Apache License, Version 2.0, in which case the following
93
+ will apply:
94
+
95
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
96
+ this file except in compliance with the License.
97
+
98
+ You may obtain a copy of the License at
99
+
100
+ http://www.apache.org/licenses/LICENSE-2.0
101
+
102
+ Unless required by applicable law or agreed to in writing, software distributed
103
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
+ specific language governing permissions and limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,124 @@
1
- # Temporary Holding Version
1
+ # @sanoma-ai/connector-resend
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [Resend Broadcasts API](https://resend.com/docs/api-reference/broadcasts) operations for [`@sanoma-ai/workflows`](https://www.npmjs.com/package/@sanoma-ai/workflows).
4
+
5
+ ## Usage
6
+
7
+ ```sh
8
+ npm install @sanoma-ai/connector-resend
9
+ ```
10
+
11
+ | Operation | Effect | What it does |
12
+ | ------------------------- | ------- | -------------------------------------------------------------------- |
13
+ | `resend.broadcast.create` | `write` | Create a broadcast to an audience. Nothing is sent. |
14
+ | `resend.broadcast.send` | `send` | Send a broadcast to every contact in its audience. Cannot be undone. |
15
+
16
+ ```ts
17
+ import { resend } from "@sanoma-ai/connector-resend";
18
+ import { defineWorkflow } from "@sanoma-ai/workflows";
19
+
20
+ defineWorkflow({
21
+ // ...
22
+ uses: [resend.broadcast.create, resend.broadcast.send],
23
+ run: async (ctx, input) => {
24
+ const email = await ctx.resend.broadcast.create({ audience: "newsletter", subject: input.title, html: input.body });
25
+ return ctx.resend.broadcast.send({ id: email.id });
26
+ },
27
+ });
28
+ ```
29
+
30
+ The logo the app shows beside these operations is Resend's lettermark from its [brand kit](https://resend.com/brand), black or white. It is there only to identify the service an operation calls.
31
+
32
+ ## Driver
33
+
34
+ `@sanoma-ai/connector-resend/driver` calls Resend. The `resend` connector the package root exports carries it, made once per resolved config, and its fake (`withSetup` from `@sanoma-ai/workflows`), so a config names the connector alone and workflows never import the driver (the lint refuses that):
35
+
36
+ ```ts
37
+ import { resend } from "@sanoma-ai/connector-resend";
38
+
39
+ export default defineConfig({ workflows, connectors: [resend], policy });
40
+ ```
41
+
42
+ `./driver` (`resendDriver`; `resendDriver({ timeoutMs })`, 15 s by default) and `./fake` (`fakeResend`) are internal entries, for tests.
43
+
44
+ `audience` is Resend's `segment_id` (Resend renamed audiences to segments). `from` comes from the input, else `RESEND_FROM` in the environment; Resend requires one. `send` returns `status: "queued"` when it sends: Resend replies with the id only and sends in the background.
45
+
46
+ The client is generated by [Hey API](https://heyapi.dev) from Resend's [OpenAPI spec](https://github.com/resend/resend-openapi), pinned to a commit and cut to the operations it calls in `openapi-ts.config.ts`: `pnpm run generate` rewrites `src/generated/`, which is never edited by hand.
47
+
48
+ ### Environment
49
+
50
+ It reads this on every call, never when the config loads:
51
+
52
+ | Variable | What it is |
53
+ | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
54
+ | `RESEND_API_KEY` | A Resend API key. |
55
+ | `RESEND_FROM` | Optional: the sender of a broadcast whose input has no `from`, such as `Acme <news@acme.example>`, on a domain verified in Resend. |
56
+
57
+ When the key is unset, a call fails, not retryable, naming it; so does a `create` with no sender from either place. The driver declares both in its `env` ([Credentials](https://www.npmjs.com/package/@sanoma-ai/workflows#credentials)): the worker starts without them, warning, and the app's connector page shows their status and lets you set them.
58
+
59
+ ### Idempotency
60
+
61
+ Resend documents `Idempotency-Key` for emails only, not broadcasts. The driver sends the call's key on both requests anyway, and names the broadcast after it so it traces to its run. A replayed `create` can leave a second draft, which sends nothing. `send` reads the broadcast first and sends only a `draft` or `scheduled` one, so a replayed `send` whose reply was lost sends nothing: it returns `queued` or `sent`, as Resend says the broadcast is, and fails for good on a `canceled` one. The read and the send are two requests, not one: two tries of one call running at once (a recovering worker re-running a call another worker still runs) could both read a draft and both send it, and Resend documents nothing that would stop the second.
62
+
63
+ ### Errors and retries
64
+
65
+ A 408, a 429 (except `daily_quota_exceeded` and `monthly_quota_exceeded`), a 409 `concurrent_idempotent_requests` (a request with the same key still in flight), a 5xx, a timeout (15 s; `timeoutMs` changes it) or no reply is retryable; any other 4xx is not. `status` and `vendorCode` (Resend's error `name`) are kept. Resend allows 10 requests per second per team.
66
+
67
+ ### Plan
68
+
69
+ Broadcasts are on the free Marketing plan (1,000 contacts, 3 segments, 3 domains), with no approval step documented. Sending to anyone but yourself needs a `from` on a domain you verified.
70
+
71
+ ### Testing the driver
72
+
73
+ `test/driver.test.ts` replays Resend's recorded replies (`test/fixtures`) with [`@sanoma-ai/testing/replay`](https://github.com/Sanoma-AI/sanoma/blob/main/packages/testing/README.md#replaying-a-vendors-api), which says what `SANOMA_LIVE` and `SANOMA_RECORD` do: `pnpm vitest run connectors/resend` needs no account. Live, they create broadcasts and send one to a test segment:
74
+
75
+ ```sh
76
+ SANOMA_LIVE=1 RESEND_API_KEY=re_... RESEND_TEST_AUDIENCE=<segment id> RESEND_TEST_FROM="Test <test@your-domain>" pnpm vitest run connectors/resend
77
+ ```
78
+
79
+ A recording loses ids, addresses, the sender's domain and keys. The error cases, and the broadcasts that are no longer drafts, only replay.
80
+
81
+ ## Steps and features
82
+
83
+ The connector carries steps for [scenarios](https://github.com/Sanoma-AI/sanoma/blob/main/packages/workflows/README.md#steps-a-connector-ships) (`resendSteps`, attached with `withSetup`), which a company's scenario can use beside the generic steps and other connectors' ones:
84
+
85
+ | Keyword | Step | What it does |
86
+ | ------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
87
+ | Given | `a Resend broadcast {string}` | Seeds a draft broadcast with that subject through `resend.broadcast.create`, named `broadcast` (`$broadcast.id`) |
88
+ | Given | `Resend fails to send once` | The next `resend.broadcast.send` fails (`failNext`) |
89
+ | Then | `the Resend broadcast {string} is sent` | The broadcast with that subject, seeded or created by the run, was sent |
90
+
91
+ `features/broadcast.feature` creates and sends a broadcast, with these steps and the generic ones for an operation's own test, on the fake and on Resend's recorded replies (`create-and-send.json`): `test/features.test.ts` runs them with [`describeFeatures`](https://github.com/Sanoma-AI/sanoma/blob/main/packages/testing/README.md#a-connectors-own-features). A scenario tagged `@fake-only` has no recording. The package ships `features/`.
92
+
93
+ ## Testing
94
+
95
+ `@sanoma-ai/connector-resend/fake` is an in-memory Resend that emails nobody, the fake the connector carries: each sandbox run makes one of its own. A test that reads or seeds one attaches it to the connector itself, then checks `state.broadcasts` and `calls`.
96
+
97
+ ```ts
98
+ import { withSetup } from "@sanoma-ai/workflows";
99
+ import { resend } from "@sanoma-ai/connector-resend";
100
+ import { fakeResend } from "@sanoma-ai/connector-resend/fake";
101
+
102
+ const fake = fakeResend();
103
+ const worker = await startWorker({
104
+ connectors: [withSetup(resend, { driver: () => fake.driver, fake: () => fake })],
105
+ /* ... */
106
+ });
107
+
108
+ // ...run a workflow, then:
109
+ Object.values(fake.state.broadcasts).map((b) => b.status); // ["sent"]
110
+ fake.calls.map((c) => c.op); // ["resend.broadcast.create", "resend.broadcast.send"]
111
+ ```
112
+
113
+ Like Resend, the fake refuses to send a broadcast twice, unless the second call repeats the first one's idempotency key: then it gets the first reply and nothing changes. To test what a workflow does when Resend misbehaves, set up the next call to an operation before the run makes it:
114
+
115
+ - `fake.failNext("resend.broadcast.send", err?)` throws `err` (default: a retryable `DriverError`).
116
+ - `fake.loseReply("resend.broadcast.send")` sends, then throws, as if the reply was lost.
117
+ - `fake.rateLimit("resend.broadcast.send")` throws a `DriverError` with status 429.
118
+ - `const release = fake.hold("resend.broadcast.send")` makes the call wait until `release()`.
119
+
120
+ `fake.reset()` empties it between tests. Pass `{ calls }` with one array to several fakes to see their calls in one order.
121
+
122
+ [`@sanoma-ai/testing`](https://github.com/Sanoma-AI/sanoma/blob/main/packages/testing/README.md) (in the sanoma repository, not published) has `startTestWorker` and `testDatabaseUrl` to run a test's worker with the fake on a database of its own.
123
+
124
+ License: FSL-1.1-ALv2.
@@ -0,0 +1,36 @@
1
+ import { z } from "zod";
2
+ /** Resend Broadcasts API: https://resend.com/docs/api-reference/broadcasts */
3
+ export declare const resendOps: import("@sanoma-ai/workflows").Connector<"resend", {
4
+ readonly broadcast: {
5
+ readonly create: {
6
+ readonly effect: "write";
7
+ readonly description: "Create a broadcast to an audience. Nothing is sent.";
8
+ readonly input: z.ZodObject<{
9
+ audience: z.ZodString;
10
+ from: z.ZodOptional<z.ZodString>;
11
+ subject: z.ZodString;
12
+ html: z.ZodString;
13
+ }, z.core.$strip>;
14
+ readonly output: z.ZodObject<{
15
+ id: z.ZodString;
16
+ }, z.core.$strip>;
17
+ };
18
+ readonly send: {
19
+ readonly effect: "send";
20
+ readonly description: "Send a broadcast to every contact in its audience. Cannot be undone.";
21
+ readonly phrases: {
22
+ readonly expect: "broadcast {id} is sent";
23
+ };
24
+ readonly input: z.ZodObject<{
25
+ id: z.ZodString;
26
+ }, z.core.$strip>;
27
+ readonly output: z.ZodObject<{
28
+ id: z.ZodString;
29
+ status: z.ZodEnum<{
30
+ queued: "queued";
31
+ sent: "sent";
32
+ }>;
33
+ }, z.core.$strip>;
34
+ };
35
+ };
36
+ }>;
@@ -0,0 +1,36 @@
1
+ import { defineConnector } from "@sanoma-ai/workflows";
2
+ import { z } from "zod";
3
+ /**
4
+ * Resend's lettermark, from https://resend.com/brand (resend-icon-black.svg, resend-icon-white.svg),
5
+ * in its official colours, its view box cropped to the mark.
6
+ */
7
+ const lettermark = (fill) => `<svg xmlns="http://www.w3.org/2000/svg" viewBox="450 450 900 900"><path fill="${fill}" d="M1000.46 450C1174.77 450 1278.43 553.669 1278.43 691.282C1278.43 828.896 1174.77 932.563 1000.46 932.563H912.382L1350 1350H1040.82L707.794 1033.48C683.944 1011.47 672.936 985.781 672.935 963.765C672.935 932.572 694.959 905.049 737.161 893.122L908.712 847.244C973.85 829.812 1018.81 779.353 1018.81 713.298C1018.8 632.567 952.745 585.78 871.095 585.78H450V450H1000.46Z"/></svg>`;
8
+ /** Resend Broadcasts API: https://resend.com/docs/api-reference/broadcasts */
9
+ export const resendOps = defineConnector("resend", {
10
+ broadcast: {
11
+ create: {
12
+ effect: "write",
13
+ description: "Create a broadcast to an audience. Nothing is sent.",
14
+ input: z.object({
15
+ audience: z.string().min(1),
16
+ from: z.string().optional(),
17
+ subject: z.string().min(1),
18
+ html: z.string(),
19
+ }),
20
+ output: z.object({ id: z.string() }),
21
+ },
22
+ send: {
23
+ effect: "send",
24
+ description: "Send a broadcast to every contact in its audience. Cannot be undone.",
25
+ phrases: { expect: "broadcast {id} is sent" },
26
+ input: z.object({ id: z.string() }),
27
+ output: z.object({ id: z.string(), status: z.enum(["queued", "sent"]) }),
28
+ },
29
+ },
30
+ }, {
31
+ title: "Resend",
32
+ logo: { svg: lettermark("black"), dark: lettermark("#FDFDFD") },
33
+ package: "@sanoma-ai/connector-resend",
34
+ homepage: "https://github.com/Sanoma-AI/sanoma/tree/main/connectors/resend#readme",
35
+ });
36
+ //# sourceMappingURL=connector.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connector.js","sourceRoot":"","sources":["../src/connector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;GAGG;AACH,MAAM,UAAU,GAAG,CAAC,IAAY,EAAE,EAAE,CAClC,iFAAiF,IAAI,+XAA+X,CAAC;AAEvd,8EAA8E;AAC9E,MAAM,CAAC,MA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 timeoutMs?: number;
4
+ }
5
+ /**
6
+ * Calls Resend's Broadcasts API with the key in `RESEND_API_KEY`, read on every call, as is
7
+ * `RESEND_FROM`, the sender of a broadcast whose input names none. The contract's `audience` is
8
+ * Resend's `segment_id`: Resend renamed audiences to segments.
9
+ */
10
+ export declare function resendDriver(options?: ResendDriverOptions): import("@sanoma-ai/workflows").Driver;
package/dist/driver.js ADDED
@@ -0,0 +1,129 @@
1
+ import { defineDriver, DriverError, retryableStatus } from "@sanoma-ai/workflows";
2
+ import { z } from "zod";
3
+ import { resendOps } from "./connector.js";
4
+ // Generated by `pnpm run generate` (openapi-ts.config.ts); never edited by hand.
5
+ import { client as generated } from "./generated/client.gen.js";
6
+ import { createClient } from "./generated/client/index.js";
7
+ import { broadcastsCreate, broadcastsGet, broadcastsSend } from "./generated/index.js";
8
+ /** The environment variables the driver reads, on every call. */
9
+ const env = z.object({
10
+ RESEND_API_KEY: z.string().describe("an API key"),
11
+ RESEND_FROM: z
12
+ .string()
13
+ .min(1)
14
+ .optional()
15
+ .describe("the sender of a broadcast whose input has no `from`, such as `Acme <news@acme.example>`, on a domain verified in Resend"),
16
+ });
17
+ /** Resend's error body. The spec declares none; the docs give `{ statusCode, name, message }`. */
18
+ const errorBody = z
19
+ .object({ name: z.string().optional().catch(undefined), message: z.string().optional().catch(undefined) })
20
+ .catch({});
21
+ /**
22
+ * The DriverError for a request that failed. The client hands its error interceptor what went
23
+ * wrong, the response once Resend answered, and the request once it was built.
24
+ */
25
+ function failure(op, timeoutMs) {
26
+ return (error, response, request) => {
27
+ if (!request) {
28
+ return new DriverError(`resend: ${op} could not build its request`, { retryable: false, cause: error });
29
+ }
30
+ if (!response) {
31
+ // No reply at all (the timeout, a dropped connection): the call may be tried again.
32
+ const timedOut = error instanceof Error && error.name === "TimeoutError";
33
+ return new DriverError(`resend: ${op} ${timedOut ? `timed out after ${timeoutMs} ms` : "got no reply"}`, {
34
+ retryable: true,
35
+ cause: error,
36
+ });
37
+ }
38
+ const { ok, status, statusText } = response;
39
+ // A body that could not be read (cut off, or the timeout fired while reading it) leaves the
40
+ // status to decide; a 2xx whose body is not JSON is no answer to retry.
41
+ const cutOff = error instanceof Error && !(error instanceof SyntaxError);
42
+ if (ok) {
43
+ return new DriverError(`resend: ${op} replied ${status} with ${cutOff ? "a body cut off" : "a body that is not JSON"}`, { retryable: cutOff, status, cause: error });
44
+ }
45
+ const { name, message } = cutOff ? {} : errorBody.parse(error);
46
+ // A daily or monthly quota does not lift in the seconds a retry waits; a 409
47
+ // `concurrent_idempotent_requests` is another request with this key still in flight.
48
+ const retryable = (retryableStatus(status) && !name?.endsWith("_quota_exceeded")) ||
49
+ (status === 409 && name === "concurrent_idempotent_requests");
50
+ return new DriverError(`resend: ${op} failed (${status}): ${message ?? statusText}`, {
51
+ retryable,
52
+ status,
53
+ ...(name === undefined ? {} : { vendorCode: name }),
54
+ });
55
+ };
56
+ }
57
+ /** The broadcast in a reply Resend accepted: the spec leaves its id optional, and a proxy may answer instead. */
58
+ function broadcastOf(op, reply) {
59
+ if (reply.data?.id)
60
+ return reply.data;
61
+ const { status } = reply.response;
62
+ throw new DriverError(`resend: ${op} replied ${status} without a broadcast id`, { retryable: false, status });
63
+ }
64
+ /**
65
+ * Calls Resend's Broadcasts API with the key in `RESEND_API_KEY`, read on every call, as is
66
+ * `RESEND_FROM`, the sender of a broadcast whose input names none. The contract's `audience` is
67
+ * Resend's `segment_id`: Resend renamed audiences to segments.
68
+ */
69
+ export function resendDriver(options = {}) {
70
+ const timeoutMs = options.timeoutMs ?? 15_000;
71
+ function client(op, call) {
72
+ const key = process.env.RESEND_API_KEY;
73
+ if (!key)
74
+ throw new DriverError("resend: RESEND_API_KEY is not set", { retryable: false });
75
+ // The generated client's config (the spec's server, throwOnError), with this call's key and headers.
76
+ const api = createClient({
77
+ ...generated.getConfig(),
78
+ auth: key,
79
+ // Resend documents Idempotency-Key for emails only; it is sent in case broadcasts honour it too.
80
+ headers: { "Idempotency-Key": call.idempotencyKey },
81
+ fetch: (input, init) => fetch(input, { ...init, signal: AbortSignal.timeout(timeoutMs) }),
82
+ });
83
+ api.interceptors.error.use(failure(op, timeoutMs));
84
+ return api;
85
+ }
86
+ return defineDriver(resendOps, {
87
+ broadcast: {
88
+ create: async (input, call) => {
89
+ const from = input.from ?? process.env.RESEND_FROM;
90
+ if (!from) {
91
+ throw new DriverError("resend: broadcast.create needs `from` in its input, or RESEND_FROM set", {
92
+ retryable: false,
93
+ });
94
+ }
95
+ const reply = await broadcastsCreate({
96
+ client: client("broadcast.create", call),
97
+ // `name` shows in Resend's dashboard only: it ties the broadcast to the call that made it.
98
+ body: {
99
+ segment_id: input.audience,
100
+ from,
101
+ subject: input.subject,
102
+ html: input.html,
103
+ name: call.idempotencyKey,
104
+ },
105
+ });
106
+ return { id: broadcastOf("broadcast.create", reply).id };
107
+ },
108
+ send: async ({ id }, call) => {
109
+ const api = client("broadcast.send", call);
110
+ // A replay of a send whose reply was lost must not send again: send only a broadcast that
111
+ // is still a draft or scheduled, and otherwise say where it is.
112
+ const { status } = broadcastOf("broadcast.send", await broadcastsGet({ client: api, path: { id } }));
113
+ if (status === "sent")
114
+ return { id, status: "sent" };
115
+ if (status === "queued")
116
+ return { id, status: "queued" };
117
+ if (status !== "draft" && status !== "scheduled") {
118
+ throw new DriverError(`resend: broadcast.send: broadcast ${id} is ${status ?? "of no status"}, not sendable`, {
119
+ retryable: false,
120
+ });
121
+ }
122
+ const reply = await broadcastsSend({ client: api, path: { id }, body: {} });
123
+ // Resend replies with the id only: it accepts the broadcast and sends it in the background.
124
+ return { id: broadcastOf("broadcast.send", reply).id, status: "queued" };
125
+ },
126
+ },
127
+ }, { env });
128
+ }
129
+ //# sourceMappingURL=driver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"driver.js","sourceRoot":"","sources":["../src/driver.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,eAAe,EAAoB,MAAM,sBAAsB,CAAC;AACp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AAE,MAAM,EAAE,MAAe,EAAE,CAAC;gBAC9D,IAAI,MAAM,KAAK,QAAQ;oBAAE,OAAO,EAAE,EAAE,EAAE,MAAM,EAAE,QAAiB,EAAE,CAAC;gBAClE,IAAI,MAAM,KAAK,OAAO,IAAI,MAAM,KAAK,WAAW,EAAE,CAAC;oBACjD,MAAM,IAAI,WAAW,CACnB,qCAAqC,EAAE,OAAO,MAAM,IAAI,cAAc,gBAAgB,EACtF;wBACE,SAAS,EAAE,KAAK;qBACjB,CACF,CAAC;gBACJ,CAAC;gBACD,MAAM,KAAK,GAAG,MAAM,cAAc,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC;gBAC5E,4FAA4F;gBAC5F,OAAO,EAAE,EAAE,EAAE,WAAW,CAAC,gBAAgB,EAAE,KAAK,CAAC,CAAC,EAAE,EAAE,MAAM,EAAE,QAAiB,EAAE,CAAC;YACpF,CAAC;SACF;KACF,EACD,EAAE,GAAG,EAAE,CACR,CAAC;AACJ,CAAC"}
package/dist/fake.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ import { type FakeOptions } from "@sanoma-ai/workflows/fake";
2
+ export interface FakeResendBroadcast {
3
+ id: string;
4
+ audience: string;
5
+ from?: string;
6
+ subject: string;
7
+ html: string;
8
+ status: "draft" | "sent";
9
+ }
10
+ export interface FakeResendState extends Record<string, unknown> {
11
+ seq: number;
12
+ broadcasts: Record<string, FakeResendBroadcast>;
13
+ }
14
+ /**
15
+ * An in-memory Resend for tests: broadcasts live in `state.broadcasts`, and nothing is
16
+ * emailed.
17
+ */
18
+ export declare function fakeResend(options?: FakeOptions): import("@sanoma-ai/workflows/fake").Fake<FakeResendState, "resend.broadcast.create" | "resend.broadcast.send">;
package/dist/fake.js ADDED
@@ -0,0 +1,32 @@
1
+ import { DriverError } from "@sanoma-ai/workflows";
2
+ import { defineFake } from "@sanoma-ai/workflows/fake";
3
+ import { resendOps } from "./connector.js";
4
+ /**
5
+ * An in-memory Resend for tests: broadcasts live in `state.broadcasts`, and nothing is
6
+ * emailed.
7
+ */
8
+ export function fakeResend(options = {}) {
9
+ return defineFake(resendOps, {
10
+ initial: () => ({ seq: 0, broadcasts: {} }),
11
+ ops: (state) => ({
12
+ broadcast: {
13
+ create: async (input) => {
14
+ const id = `bc_${String(++state.seq).padStart(4, "0")}`;
15
+ state.broadcasts[id] = { id, ...input, status: "draft" };
16
+ return { id };
17
+ },
18
+ send: async ({ id }) => {
19
+ const bc = state.broadcasts[id];
20
+ if (!bc)
21
+ throw new DriverError(`resend: no broadcast ${id}`, { retryable: false, status: 404 });
22
+ if (bc.status === "sent") {
23
+ throw new DriverError(`resend: broadcast ${id} was already sent`, { retryable: false, status: 422 });
24
+ }
25
+ bc.status = "sent";
26
+ return { id, status: "queued" };
27
+ },
28
+ },
29
+ }),
30
+ }, options);
31
+ }
32
+ //# sourceMappingURL=fake.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fake.js","sourceRoot":"","sources":["../src/fake.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnD,OAAO,EAAE,UAAU,EAAoB,MAAM,2BAA2B,CAAC;AACzE,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAgB3C;;;GAGG;AACH,MAAM,UAAU,UAAU,CAAC,OAAO,GAAgB,EAAE;IAClD,OAAO,UAAU,CACf,SAAS,EACT;QACE,OAAO,EAAE,GAAoB,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC;QAC5D,GAAG,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;YACf,SAAS,EAAE;gBACT,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE;oBACtB,MAAM,EAAE,GAAG,MAAM,MAAM,CAAC,EAAE,KAAK,CAAC,GAAG,C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