@sendery/sdk 0.1.3 → 0.1.5

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/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.5
4
+
5
+ - Register and list event definitions with readable data fields and recipient roles for the visual trigger builder.
6
+
7
+ - Add application events, stable-key retries, event status lookup, and object-data deletion. Framework integrations use the project client.
8
+
9
+ ## 0.1.4
10
+
11
+ - Optionally pin sends to a published template version.
12
+
3
13
  ## 0.1.3
4
14
 
5
15
  - See the GitHub release notes for this version.
package/README.md CHANGED
@@ -16,7 +16,7 @@ npm install @sendery/sdk
16
16
 
17
17
  ## Set up
18
18
 
19
- Publish a `welcome` template with `name` and `action_url` variables, and create a [project API key](https://sendery.co/en/docs/authentication). Store it as `SENDERY_API_KEY` on your server. Use the SDK only on the server.
19
+ Choose a published template and create a [project API key](https://sendery.co/en/docs/authentication). Store the key as `SENDERY_API_KEY` on your server.
20
20
 
21
21
  ```bash
22
22
  export SENDERY_API_KEY="your_project_api_key"
@@ -24,6 +24,8 @@ export SENDERY_API_KEY="your_project_api_key"
24
24
 
25
25
  ## Send an email
26
26
 
27
+ Replace `your-template` with your published template’s key and `data` with its variables.
28
+
27
29
  The response contains the accepted email’s `id` and `status`.
28
30
 
29
31
  ```javascript
@@ -35,18 +37,30 @@ if (!apiKey) throw new Error('Set SENDERY_API_KEY on your server.');
35
37
  const sendery = new Sendery(apiKey);
36
38
  const receipt = await sendery.send({
37
39
  to: 'alex@example.com',
38
- template: 'welcome',
40
+ template: 'your-template',
39
41
  data: { name: 'Alex', action_url: 'https://example.com/start' },
40
42
  });
41
43
 
42
44
  console.log(receipt.id);
43
45
  ```
44
46
 
47
+ ## Send a specific version
48
+
49
+ Choose a [published template version](https://sendery.co/en/docs/send-email#section-5) to keep sending it after newer versions are published. By default, Sendery uses the latest version.
50
+
51
+ ```javascript
52
+ const receipt = await sendery.prepare({
53
+ to: 'alex@example.com',
54
+ template: 'your-template',
55
+ data: { name: 'Alex', action_url: 'https://example.com/start' },
56
+ }).version(3).send();
57
+ ```
58
+
45
59
  ## Attachments
46
60
 
47
61
  Use `attachment()` to create an attachment from file bytes. The helper handles base64 encoding.
48
62
 
49
- Send up to 10 files totaling 5 MB. See the [attachment reference](https://sendery.co/en/docs/send-email#section-5) for supported formats and limits.
63
+ Send up to 10 files totaling 5 MB. See the [attachment reference](https://sendery.co/en/docs/send-email#section-6) for supported formats and limits.
50
64
 
51
65
  ```javascript
52
66
  import { Sendery, attachment } from '@sendery/sdk';
@@ -57,10 +71,10 @@ const file = await readFile('/path/document.pdf');
57
71
 
58
72
  await sendery.prepare({
59
73
  to: 'alex@example.com',
60
- template: 'welcome',
74
+ template: 'your-template',
61
75
  data: { name: 'Alex', action_url: 'https://example.com/start' },
62
76
  attachments: [attachment('document.pdf', file, 'application/pdf')],
63
- }, 'welcome-attachment-123').retry().send();
77
+ }, 'your-idempotency-key').retry().send();
64
78
  ```
65
79
 
66
80
  In Next.js and Nuxt, use this in server-side routes or actions.
@@ -76,14 +90,14 @@ console.log(message.status);
76
90
 
77
91
  ## Retry a send
78
92
 
79
- Use a key such as `welcome-123` for one email, and [keep the payload unchanged on retries](https://sendery.co/en/docs/idempotency). `retry(3)` allows up to three additional attempts for temporary failures; `send()` alone makes one attempt.
93
+ Use `retry(3)` for up to three extra attempts after temporary failures. Keep the same [idempotency key and email data](https://sendery.co/en/docs/idempotency) on every attempt.
80
94
 
81
95
  ```javascript
82
96
  const email = sendery.prepare({
83
97
  to: 'alex@example.com',
84
- template: 'welcome',
98
+ template: 'your-template',
85
99
  data: { name: 'Alex', action_url: 'https://example.com/start' },
86
- }, 'welcome-123');
100
+ }, 'your-idempotency-key');
87
101
 
88
102
  const receipt = await email.retry(3).send();
89
103
  ```
@@ -113,8 +127,24 @@ Follow the server setup for [Next.js](https://sendery.co/en/docs/next) or [Nuxt]
113
127
 
114
128
  ## More
115
129
 
116
- See [idempotency and retries](https://sendery.co/en/docs/idempotency) for retry conditions, delays, and reusing a key across attempts.
130
+ Learn how to [retry emails without duplicate sends](https://sendery.co/en/docs/idempotency).
117
131
 
118
132
  ## License
119
133
 
120
134
  [MIT](LICENSE).
135
+
136
+ ## Events and triggers
137
+
138
+ Send events such as account signups or orders from your app. Your team can use them to automate emails in Sendery, choosing the content, recipients, and timing. Available on all plans.
139
+
140
+ Start with [Connecting your application](https://sendery.co/en/docs/connect-events) to define the data Sendery can expect, then [send events](https://sendery.co/en/docs/send-events) as they happen.
141
+
142
+ ```typescript
143
+ const receipt = await sendery.event({
144
+ name: "account.created",
145
+ object: { type: "account", id: "842" },
146
+ data: { email: "alex@example.com", name: "Alex" },
147
+ }).retry().send();
148
+ ```
149
+
150
+ Retries reuse the same event data and idempotency key. To retry across jobs or process restarts, supply and persist your own key. A successful response confirms that Sendery accepted the event. [Learn what you can automate with triggers](https://sendery.co/en/docs/build-trigger).
package/dist/index.d.ts CHANGED
@@ -1,3 +1,34 @@
1
+ export interface EventField {
2
+ label: string;
3
+ path: string;
4
+ type: "text" | "number" | "boolean" | "email" | "url" | "date" | "rows";
5
+ required?: boolean;
6
+ /** Use synthetic examples, never customer information. */
7
+ example?: string | number | boolean | Record<string, string | number | boolean>[];
8
+ }
9
+ export interface EventDefinition {
10
+ label: string;
11
+ object: {
12
+ type: string;
13
+ label: string;
14
+ };
15
+ fields: Record<string, EventField>;
16
+ recipients: Record<string, {
17
+ label: string;
18
+ email: string;
19
+ name?: string;
20
+ locale?: string;
21
+ }>;
22
+ }
23
+ export interface EventType extends EventDefinition {
24
+ name: string;
25
+ verified: boolean;
26
+ last_received_at: string | null;
27
+ }
28
+ export interface EventTypeReceipt {
29
+ name: string;
30
+ verified: boolean;
31
+ }
1
32
  export type Variables = Record<string, string | number | boolean | Record<string, string | number | boolean>[]>;
2
33
  export interface Attachment {
3
34
  filename: string;
@@ -11,6 +42,7 @@ export interface SendEmailInput {
11
42
  template: string;
12
43
  data: Variables;
13
44
  locale?: string;
45
+ version?: number;
14
46
  attachments?: Attachment[];
15
47
  }
16
48
  export interface SendReceipt {
@@ -28,14 +60,50 @@ export declare class SenderyError extends Error {
28
60
  constructor(status: number, code?: string, errors?: Record<string, string[]>, retryAfter?: number);
29
61
  get retryable(): boolean;
30
62
  }
31
- export declare class PendingEmail {
63
+ export interface EventInput {
64
+ name: string;
65
+ object: {
66
+ type: string;
67
+ id: string;
68
+ };
69
+ correlation_id?: string;
70
+ data: Record<string, unknown>;
71
+ }
72
+ export interface EventReceipt extends SendReceipt {
73
+ name?: string;
74
+ received_at?: string;
75
+ matched_triggers?: number;
76
+ environment?: "sandbox" | "live";
77
+ runs?: {
78
+ id: string;
79
+ trigger_id: number;
80
+ status: string;
81
+ due_at: string | null;
82
+ error_code: string | null;
83
+ actions: {
84
+ position: number;
85
+ type: string;
86
+ status: string;
87
+ email_id: string | null;
88
+ }[];
89
+ }[];
90
+ }
91
+ declare class PendingRequest<T extends SendReceipt> {
32
92
  readonly idempotencyKey: string;
33
- private readonly body;
34
- private readonly client;
93
+ protected body: string;
35
94
  private retries;
36
- constructor(client: Sendery, input: SendEmailInput, key: string);
95
+ private client;
96
+ private endpoint;
97
+ constructor(client: Sendery, input: unknown, key: string, endpoint: string);
37
98
  retry(retries?: number): this;
38
- send(): Promise<SendReceipt>;
99
+ send(): Promise<T>;
100
+ }
101
+ export declare class PendingEvent extends PendingRequest<EventReceipt> {
102
+ constructor(client: Sendery, input: EventInput, key: string);
103
+ }
104
+ export declare class PendingEmail extends PendingRequest<SendReceipt> {
105
+ constructor(client: Sendery, input: SendEmailInput, key: string);
106
+ version(version: number): this;
39
107
  }
40
108
  export declare class Sendery {
41
109
  private apiKey;
@@ -43,6 +111,12 @@ export declare class Sendery {
43
111
  constructor(apiKey: string, baseUrl?: string);
44
112
  prepare(input: SendEmailInput, idempotencyKey?: string): PendingEmail;
45
113
  send(input: SendEmailInput, idempotencyKey?: string): Promise<SendReceipt>;
114
+ defineEvent(name: string, definition: EventDefinition): Promise<EventTypeReceipt>;
115
+ getEventTypes(): Promise<EventType[]>;
116
+ event(input: EventInput, idempotencyKey?: string): PendingEvent;
117
+ getEvent(id: string): Promise<EventReceipt>;
118
+ forgetObject(type: string, id: string): Promise<SendReceipt>;
46
119
  get(id: string): Promise<SendReceipt>;
47
- request(method: string, path: string, body?: string, key?: string): Promise<SendReceipt>;
120
+ request<T = SendReceipt>(method: string, path: string, body?: string, key?: string): Promise<T>;
48
121
  }
122
+ export {};
package/dist/index.js CHANGED
@@ -24,31 +24,19 @@ export class SenderyError extends Error {
24
24
  (this.status === 429 && this.code === "rate_limited"));
25
25
  }
26
26
  }
27
- export class PendingEmail {
27
+ class PendingRequest {
28
28
  idempotencyKey;
29
29
  body;
30
- client;
31
30
  retries = 0;
32
- constructor(client, input, key) {
31
+ client;
32
+ endpoint;
33
+ constructor(client, input, key, endpoint) {
33
34
  if (!/^[a-zA-Z0-9_.:-]{1,128}$/.test(key))
34
35
  throw new Error("Invalid idempotency key.");
35
- const files = input.attachments ?? [];
36
- const size = files.reduce((sum, file) => {
37
- if (!file.content.length || file.content.length > 6990508 || (file.content.length % 4 !== 0 || /[^A-Za-z0-9+/]/.test(file.content.replace(/={1,2}$/, ""))))
38
- throw new Error("Provide standard base64 attachment content.");
39
- return sum + (file.content.length / 4) * 3 - (file.content.endsWith("==") ? 2 : file.content.endsWith("=") ? 1 : 0);
40
- }, 0);
41
- if (files.length > 10 || size > 5 * 1024 * 1024)
42
- throw new Error("Use at most 10 attachments, up to 5 MB combined.");
43
- this.client = client;
44
36
  this.idempotencyKey = key;
45
- this.body = JSON.stringify({
46
- to: input.to,
47
- template: input.template,
48
- data: input.data,
49
- ...(input.locale ? { locale: input.locale } : {}),
50
- ...(files.length ? { attachments: files } : {}),
51
- });
37
+ this.client = client;
38
+ this.endpoint = endpoint;
39
+ this.body = JSON.stringify(input);
52
40
  }
53
41
  retry(retries = 3) {
54
42
  if (!Number.isInteger(retries) || retries < 0 || retries > 5)
@@ -59,7 +47,7 @@ export class PendingEmail {
59
47
  async send() {
60
48
  for (let attempt = 0;; attempt++) {
61
49
  try {
62
- return await this.client.request("POST", "/api/v1/emails", this.body, this.idempotencyKey);
50
+ return await this.client.request("POST", this.endpoint, this.body, this.idempotencyKey);
63
51
  }
64
52
  catch (error) {
65
53
  if (!(error instanceof SenderyError) ||
@@ -75,6 +63,47 @@ export class PendingEmail {
75
63
  }
76
64
  }
77
65
  }
66
+ export class PendingEvent extends PendingRequest {
67
+ constructor(client, input, key) {
68
+ super(client, input, key, "/api/v1/events");
69
+ }
70
+ }
71
+ export class PendingEmail extends PendingRequest {
72
+ constructor(client, input, key) {
73
+ const files = input.attachments ?? [];
74
+ const size = files.reduce((sum, file) => {
75
+ if (!file.content.length ||
76
+ file.content.length > 6990508 ||
77
+ file.content.length % 4 !== 0 ||
78
+ /[^A-Za-z0-9+/]/.test(file.content.replace(/={1,2}$/, "")))
79
+ throw new Error("Provide standard base64 attachment content.");
80
+ return (sum +
81
+ (file.content.length / 4) * 3 -
82
+ (file.content.endsWith("==")
83
+ ? 2
84
+ : file.content.endsWith("=")
85
+ ? 1
86
+ : 0));
87
+ }, 0);
88
+ if (files.length > 10 || size > 5 * 1024 * 1024)
89
+ throw new Error("Use at most 10 attachments, up to 5 MB combined.");
90
+ super(client, {
91
+ to: input.to,
92
+ template: input.template,
93
+ data: input.data,
94
+ ...(input.locale ? { locale: input.locale } : {}),
95
+ ...(files.length ? { attachments: files } : {}),
96
+ }, key, "/api/v1/emails");
97
+ if (input.version !== undefined)
98
+ this.version(input.version);
99
+ }
100
+ version(version) {
101
+ if (!Number.isSafeInteger(version) || version < 1)
102
+ throw new Error("Version must be a positive integer.");
103
+ this.body = JSON.stringify({ ...JSON.parse(this.body), version });
104
+ return this;
105
+ }
106
+ }
78
107
  export class Sendery {
79
108
  apiKey;
80
109
  baseUrl;
@@ -100,6 +129,21 @@ export class Sendery {
100
129
  send(input, idempotencyKey) {
101
130
  return this.prepare(input, idempotencyKey).send();
102
131
  }
132
+ defineEvent(name, definition) {
133
+ return this.request("PUT", `/api/v1/event-types/${encodeURIComponent(name)}`, JSON.stringify(definition));
134
+ }
135
+ async getEventTypes() {
136
+ return (await this.request("GET", "/api/v1/event-types")).events;
137
+ }
138
+ event(input, idempotencyKey = crypto.randomUUID()) {
139
+ return new PendingEvent(this, input, idempotencyKey);
140
+ }
141
+ getEvent(id) {
142
+ return this.request("GET", `/api/v1/events/${encodeURIComponent(id)}`);
143
+ }
144
+ forgetObject(type, id) {
145
+ return this.request("DELETE", "/api/v1/event-objects", JSON.stringify({ type, id }));
146
+ }
103
147
  get(id) {
104
148
  return this.request("GET", `/api/v1/emails/${encodeURIComponent(id)}`);
105
149
  }
@@ -137,7 +181,14 @@ export class Sendery {
137
181
  ? Math.max(0, seconds)
138
182
  : undefined);
139
183
  }
140
- if (typeof data.id !== "string" || typeof data.status !== "string")
184
+ const valid = path === "/api/v1/event-types"
185
+ ? Array.isArray(data.events)
186
+ : path.startsWith("/api/v1/event-types/")
187
+ ? typeof data.name === "string" &&
188
+ typeof data.verified === "boolean"
189
+ : typeof data.id === "string" &&
190
+ typeof data.status === "string";
191
+ if (!valid)
141
192
  throw new SenderyError(0, "invalid_response");
142
193
  return data;
143
194
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sendery/sdk",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "type": "module",
5
5
  "description": "Server-side Sendery template email SDK for JavaScript and TypeScript",
6
6
  "license": "MIT",