@rewritetoday/sdk 1.0.1

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Rewrite
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,107 @@
1
+ <div align="center">
2
+
3
+ # Rewrite Node SDK
4
+
5
+ [`@rewritetoday/sdk`](https://docs.rewritetoday.com/en/sdks/node), the official Node.js/TypeScript SDK for the Rewrite API.
6
+
7
+ It wraps authentication, typed REST calls, and resource helpers on top of [`@rewritetoday/rest`](https://www.npmjs.com/package/@rewritetoday/rest) and [`@rewritetoday/types`](https://www.npmjs.com/package/@rewritetoday/types).
8
+
9
+ <img src="https://cdn.rewritetoday.com/assets/banners/node-sdk.png" width="100%" alt="Rewrite Banner"/>
10
+
11
+ ## Installation
12
+
13
+ Use your preferred package manager:
14
+
15
+ </div>
16
+
17
+ ```bash
18
+ bun add @rewritetoday/sdk
19
+ # Or
20
+ npm install @rewritetoday/sdk
21
+ # Or
22
+ pnpm add @rewritetoday/sdk
23
+ ```
24
+
25
+ <div align="center">
26
+
27
+ ## Setup
28
+
29
+ First, you need to create an API key in the [Rewrite Dashboard](https://dash.rewritetoday.com/api-keys) and use it in the constructor.
30
+
31
+ </div>
32
+
33
+ ```ts
34
+ import { Rewrite } from '@rewritetoday/sdk';
35
+
36
+ const rewrite = new Rewrite(process.env.REWRITE_API_KEY);
37
+ ```
38
+
39
+ <div align="center">
40
+
41
+ ## Create the client
42
+
43
+ You can pass the API key directly or use the full options object.
44
+
45
+ </div>
46
+
47
+ ```ts
48
+ import { Rewrite } from '@rewritetoday/sdk';
49
+
50
+ const rewrite = new Rewrite({
51
+ secret: 'rw_...',
52
+ rest: {
53
+ timeout: 10_000,
54
+ headers: {
55
+ 'User-Agent': 'StatusPage One (1.0.0)',
56
+ },
57
+ retry: {
58
+ max: 3,
59
+ delay(attempt) {
60
+ return attempt * 250;
61
+ },
62
+ },
63
+ },
64
+ });
65
+ ```
66
+
67
+ <div align="center">
68
+
69
+ ## Send your first message
70
+
71
+ </div>
72
+
73
+ ```ts
74
+ const { data, error } = await rewrite.messages.send({
75
+ to: '+551234567890',
76
+ content: 'Hey, Rewrite is here!',
77
+ });
78
+ ```
79
+
80
+ <div align="center">
81
+
82
+ You can view in our [documentation](https://docs.rewritetoday.com/api-reference/messages/send-a-message) everything in you can use when sending a message.
83
+
84
+ ## Error Handling
85
+
86
+ Requests run through `@rewritetoday/rest`. HTTP failures can throw `HTTPError`.
87
+
88
+ </div>
89
+
90
+ ```ts
91
+ import { HTTPError } from '@rewritetoday/rest';
92
+
93
+ try {
94
+ await rewrite.projects.get('invalid_id');
95
+ } catch (error) {
96
+ if (error instanceof HTTPError) {
97
+ console.error('HTTP Error:', error.status, error.method, error.url);
98
+ }
99
+ }
100
+ ```
101
+
102
+ <div align="center">
103
+
104
+ Made with 🤍 by the Rewrite team. <br/>
105
+ SMS the way it should be.
106
+
107
+ </div>
@@ -0,0 +1,33 @@
1
+ import { REST } from '@rewritetoday/rest';
2
+ import { APIKeyManager } from './resources/api-key';
3
+ import { LogManager } from './resources/logs';
4
+ import { MessageManager } from './resources/message';
5
+ import { OTPManager } from './resources/otp';
6
+ import { TemplateManager } from './resources/template';
7
+ import { WebhookManager } from './resources/webhook';
8
+ import type { RewriteOptions } from './types';
9
+ /**
10
+ * Main SDK client for the Rewrite API.
11
+ */
12
+ export declare class Rewrite {
13
+ /** Low-level REST client instance. */
14
+ readonly rest: REST;
15
+ /** Resolved API secret used for authentication. */
16
+ private readonly secret;
17
+ /** OTP resource client. */
18
+ readonly otp: OTPManager;
19
+ /** Webhook logs resource client. */
20
+ readonly logs: LogManager;
21
+ /** API key resource client. */
22
+ readonly apiKeys: APIKeyManager;
23
+ /** Messages resource client. */
24
+ readonly messages: MessageManager;
25
+ /** Webhook resource client. */
26
+ readonly webhooks: WebhookManager;
27
+ /** Template resource client. */
28
+ readonly templates: TemplateManager;
29
+ /**
30
+ * Creates a new Rewrite client instance.
31
+ */
32
+ constructor(options: RewriteOptions | string);
33
+ }
@@ -0,0 +1,10 @@
1
+ export * from '@rewritetoday/types';
2
+ export { Rewrite } from './client';
3
+ export { APIKeyManager } from './resources/api-key';
4
+ export { LogManager } from './resources/logs';
5
+ export { MessageManager } from './resources/message';
6
+ export { OTPManager } from './resources/otp';
7
+ export { TemplateManager } from './resources/template';
8
+ export { WebhookManager } from './resources/webhook';
9
+ export * from './types';
10
+ export { version } from './version';
package/dist/index.js ADDED
@@ -0,0 +1,483 @@
1
+ // node_modules/@rewritetoday/types/dist/v1/resources/apiKeys.js
2
+ var APIKeyScope;
3
+ (function(APIKeyScope2) {
4
+ APIKeyScope2["Wildcard"] = "*";
5
+ APIKeyScope2["ReadProject"] = "project:read";
6
+ APIKeyScope2["ReadAPIKeys"] = "project:api_keys:read";
7
+ APIKeyScope2["WriteProject"] = "project:write";
8
+ APIKeyScope2["ReadWebhooks"] = "project:webhooks:read";
9
+ APIKeyScope2["WriteTemplate"] = "project:templates:write";
10
+ APIKeyScope2["ReadTemplates"] = "project:templates:read";
11
+ APIKeyScope2["WriteWebhooks"] = "project:webhooks:write";
12
+ APIKeyScope2["WriteMessages"] = "message:write";
13
+ APIKeyScope2["ReadMessages"] = "message:read";
14
+ APIKeyScope2["ReadLogs"] = "project:logs:read";
15
+ })(APIKeyScope || (APIKeyScope = {}));
16
+ // node_modules/@rewritetoday/types/dist/v1/resources/logs.js
17
+ var WebhookDeliveryStatus;
18
+ (function(WebhookDeliveryStatus2) {
19
+ WebhookDeliveryStatus2["Success"] = "SUCCESS";
20
+ WebhookDeliveryStatus2["Failed"] = "FAILED";
21
+ })(WebhookDeliveryStatus || (WebhookDeliveryStatus = {}));
22
+ // node_modules/@rewritetoday/types/dist/v1/resources/message.js
23
+ var MessageEncoding;
24
+ (function(MessageEncoding2) {
25
+ MessageEncoding2["GMS7"] = "GMS7";
26
+ MessageEncoding2["UCS2"] = "UCS2";
27
+ })(MessageEncoding || (MessageEncoding = {}));
28
+ var MessageStatus;
29
+ (function(MessageStatus2) {
30
+ MessageStatus2["Sent"] = "SENT";
31
+ MessageStatus2["Queued"] = "QUEUED";
32
+ MessageStatus2["Failed"] = "FAILED";
33
+ MessageStatus2["Canceled"] = "CANCELED";
34
+ MessageStatus2["Scheduled"] = "SCHEDULED";
35
+ MessageStatus2["Delivered"] = "DELIVERED";
36
+ })(MessageStatus || (MessageStatus = {}));
37
+ var MessageType;
38
+ (function(MessageType2) {
39
+ MessageType2["SMS"] = "SMS";
40
+ MessageType2["OTP"] = "OTP";
41
+ })(MessageType || (MessageType = {}));
42
+ var MessageAnalysisReason;
43
+ (function(MessageAnalysisReason2) {
44
+ MessageAnalysisReason2["FitsSingleSegment"] = "fits";
45
+ MessageAnalysisReason2["SmartEncodingApplied"] = "smart";
46
+ MessageAnalysisReason2["ExceedsSingleSegmentLimit"] = "singleLimit";
47
+ MessageAnalysisReason2["ContainsNonGsm7Characters"] = "nonGsm7";
48
+ })(MessageAnalysisReason || (MessageAnalysisReason = {}));
49
+ var MessageAnalysisEncoding;
50
+ (function(MessageAnalysisEncoding2) {
51
+ MessageAnalysisEncoding2["GSM7"] = "gsm7";
52
+ MessageAnalysisEncoding2["UCS2"] = "ucs2";
53
+ })(MessageAnalysisEncoding || (MessageAnalysisEncoding = {}));
54
+ // node_modules/@rewritetoday/types/dist/v1/resources/webhooks.js
55
+ var WebhookEventType;
56
+ (function(WebhookEventType2) {
57
+ WebhookEventType2["SMSOTP"] = "sms.otp";
58
+ WebhookEventType2["MessageSent"] = "message.sent";
59
+ WebhookEventType2["MessageBatch"] = "message.batch";
60
+ WebhookEventType2["MessageQueued"] = "message.queued";
61
+ WebhookEventType2["MessageDelivered"] = "message.delivered";
62
+ WebhookEventType2["MessageScheduled"] = "message.scheduled";
63
+ WebhookEventType2["MessageFailed"] = "message.failed";
64
+ WebhookEventType2["MessageCanceled"] = "message.canceled";
65
+ })(WebhookEventType || (WebhookEventType = {}));
66
+ var WebhookStatus;
67
+ (function(WebhookStatus2) {
68
+ WebhookStatus2["Active"] = "ACTIVE";
69
+ WebhookStatus2["Inactive"] = "INACTIVE";
70
+ })(WebhookStatus || (WebhookStatus = {}));
71
+ // node_modules/@rewritetoday/types/dist/v1/utils.js
72
+ var createCursorQuery = ({ limit = 15, ...options } = {}) => {
73
+ return new URLSearchParams({ limit: limit.toString(), ...options });
74
+ };
75
+
76
+ // node_modules/@rewritetoday/types/dist/v1/routes.js
77
+ var API_BASE_URL = "https://api.rewritetoday.com";
78
+ var Routes = {
79
+ otp: {
80
+ send() {
81
+ return "/otp";
82
+ },
83
+ verify(id) {
84
+ return `/otp/${id}/verify`;
85
+ }
86
+ },
87
+ messages: {
88
+ send() {
89
+ return "/messages";
90
+ },
91
+ batch() {
92
+ return "/messages/batch";
93
+ },
94
+ list(options) {
95
+ return `/messages?${createCursorQuery(options)}`;
96
+ },
97
+ get(id) {
98
+ return `/messages/:${id}`;
99
+ },
100
+ cancel(id) {
101
+ return `/messages/${id}/cancel`;
102
+ }
103
+ },
104
+ webhooks: {
105
+ list(options) {
106
+ return `/webhooks?${createCursorQuery(options)}`;
107
+ },
108
+ create() {
109
+ return "/webhooks";
110
+ },
111
+ update(id) {
112
+ return `/webhooks/${id}`;
113
+ },
114
+ delete(id) {
115
+ return `/webhooks/${id}`;
116
+ },
117
+ get(id) {
118
+ return `/webhooks/${id}`;
119
+ },
120
+ logs(id, options) {
121
+ return `/webhooks/${id}/logs?${createCursorQuery(options)}`;
122
+ }
123
+ },
124
+ templates: {
125
+ list(options) {
126
+ return `/templates?${createCursorQuery(options)}`;
127
+ },
128
+ create() {
129
+ return "/templates";
130
+ },
131
+ update(id) {
132
+ return `/templates/${id}`;
133
+ },
134
+ delete(id) {
135
+ return `/templates/${id}`;
136
+ },
137
+ get(id) {
138
+ return `/templates/${id}`;
139
+ }
140
+ },
141
+ apiKeys: {
142
+ delete(id) {
143
+ return `/api-keys/${id}`;
144
+ }
145
+ },
146
+ logs: {
147
+ get(id) {
148
+ return `/logs/${id}`;
149
+ }
150
+ }
151
+ };
152
+ // node_modules/@rewritetoday/rest/dist/errors.js
153
+ class HTTPError extends Error {
154
+ message;
155
+ status;
156
+ url;
157
+ method;
158
+ constructor(message2, status, url, method) {
159
+ super(message2);
160
+ this.message = message2;
161
+ this.status = status;
162
+ this.url = url;
163
+ this.method = method;
164
+ this.name = `HTTPError(${status})`;
165
+ }
166
+ }
167
+
168
+ class RateLimitError extends HTTPError {
169
+ limit;
170
+ global;
171
+ retryAfter;
172
+ constructor(message2, url, method, context) {
173
+ super(message2, 429, url, method);
174
+ this.limit = context.limit;
175
+ this.global = context.isGlobal;
176
+ this.retryAfter = context.retryAfter;
177
+ this.name = "RateLimitError";
178
+ }
179
+ }
180
+
181
+ // node_modules/@rewritetoday/rest/dist/version.js
182
+ var version = "1.0.1";
183
+ var API_VERSION = "1";
184
+
185
+ // node_modules/@rewritetoday/rest/dist/utils.js
186
+ var DEFAULT_BASE_URL = "https://api.rewritetoday.com";
187
+ var API_PATH = `/v${API_VERSION}`;
188
+ var normalizeBaseURL = (baseURL) => {
189
+ let normalized = baseURL.endsWith("/") ? baseURL.slice(0, -1) : baseURL;
190
+ if (normalized.endsWith(API_PATH))
191
+ normalized = normalized.slice(0, -API_PATH.length);
192
+ return normalized;
193
+ };
194
+ var createURL = (route, query, baseURL = DEFAULT_BASE_URL) => {
195
+ const normalizedRoute = route.startsWith("/") ? route : `/${route}`;
196
+ const url = new URL(`${normalizeBaseURL(baseURL)}${API_PATH}${normalizedRoute}`);
197
+ if (query)
198
+ url.search = new URLSearchParams(query).toString();
199
+ return url.toString();
200
+ };
201
+ var FIVE_SECONDS_IN_MS = 5000;
202
+ var RETRYABLE_STATUS = [408, 425, 429, 500, 502, 503, 504];
203
+ var isRetryableStatus = (status) => RETRYABLE_STATUS.includes(status);
204
+ var BASE_DELAY_MS = 300;
205
+ var MAX_DELAY_MS = 1e4;
206
+ var backoff = (attempt) => {
207
+ const exp = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** attempt);
208
+ const jitter = Math.random() * exp * 0.3;
209
+ return Math.floor(exp + jitter);
210
+ };
211
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
212
+ var RATE_LIMIT_STATUS = 429;
213
+
214
+ // node_modules/@rewritetoday/rest/dist/client.js
215
+ var DEFAULT_RETRY_MAX = 3;
216
+
217
+ class REST {
218
+ options;
219
+ headers;
220
+ constructor(options) {
221
+ this.options = typeof options === "string" ? { auth: options } : { ...options };
222
+ this.headers = {
223
+ "Content-Type": "application/json",
224
+ "User-Agent": `@rewritetoday/rest (${version})`,
225
+ ...this.options.headers
226
+ };
227
+ this.setAuth(this.options.auth);
228
+ }
229
+ setAuth(authorization) {
230
+ if (typeof authorization !== "string" || !authorization.startsWith("rw_"))
231
+ throw new Error("Unknown or invalid API key.");
232
+ this.options.auth = authorization;
233
+ this.headers.Authorization = `Bearer ${authorization}`;
234
+ return this;
235
+ }
236
+ get(route, options) {
237
+ return this.request(route, { ...options, method: "GET" });
238
+ }
239
+ post(route, data, options) {
240
+ return this.request(route, { data, ...options, method: "POST" });
241
+ }
242
+ delete(route, options) {
243
+ return this.request(route, { ...options, method: "DELETE" });
244
+ }
245
+ put(route, data, options) {
246
+ return this.request(route, { data, ...options, method: "PUT" });
247
+ }
248
+ patch(route, data, options) {
249
+ return this.request(route, { data, ...options, method: "PATCH" });
250
+ }
251
+ async request(route, options, attempt = 0) {
252
+ const timeout = options.timeout ?? this.options.timeout ?? FIVE_SECONDS_IN_MS;
253
+ const response = await fetch(createURL(route, options.query, this.options.baseURL), {
254
+ method: options.method,
255
+ headers: { ...this.headers, ...options.headers },
256
+ signal: AbortSignal.timeout(timeout),
257
+ body: "data" in options ? JSON.stringify(options.data) : null
258
+ });
259
+ if (!response.ok)
260
+ return this.handleError({
261
+ route,
262
+ attempt,
263
+ options,
264
+ response,
265
+ method: options.method
266
+ });
267
+ return await response.json();
268
+ }
269
+ async handleError({ route, method, options, attempt, response }) {
270
+ if (!isRetryableStatus(response.status))
271
+ return await response.json();
272
+ const { onRateLimit, retry } = this.options;
273
+ const rateLimitContext = response.status === RATE_LIMIT_STATUS ? this.parseRateLimitContext(response) : null;
274
+ if (attempt >= (retry?.max ?? DEFAULT_RETRY_MAX))
275
+ throw this.buildRetryExceededError(response, method, rateLimitContext);
276
+ if (rateLimitContext)
277
+ await onRateLimit?.(rateLimitContext);
278
+ await retry?.onRetry?.({ route, attempt, options, response, method });
279
+ await sleep(rateLimitContext && rateLimitContext.retryAfter > 0 ? rateLimitContext.retryAfter : (retry?.delay ?? backoff)(attempt));
280
+ return this.request(route, options, attempt + 1);
281
+ }
282
+ buildRetryExceededError(response, method, rateLimitContext) {
283
+ if (rateLimitContext)
284
+ return new RateLimitError("Rate limit has not been reset yet", response.url, method, rateLimitContext);
285
+ return new HTTPError("Max retries reached", response.status, response.url, method);
286
+ }
287
+ parseRateLimitContext(response) {
288
+ const { headers } = response;
289
+ const xRateLimitRetryAfter = this.readNumberHeader(headers, "X-RateLimit-Retry-After");
290
+ const retryAfter = xRateLimitRetryAfter > 0 ? xRateLimitRetryAfter : this.parseRetryAfterHeader(headers.get("X-RateLimit-Retry-After"));
291
+ return {
292
+ retryAfter,
293
+ limit: this.readNumberHeader(headers, "X-RateLimit-Limit"),
294
+ isGlobal: headers.get("X-RateLimit-Global")?.toLowerCase() === "true"
295
+ };
296
+ }
297
+ readNumberHeader(headers, key) {
298
+ const value = headers.get(key);
299
+ if (!value)
300
+ return 0;
301
+ const parsed = Number(value);
302
+ return Number.isFinite(parsed) ? parsed : 0;
303
+ }
304
+ parseRetryAfterHeader(header) {
305
+ if (!header)
306
+ return 0;
307
+ const seconds = Number(header);
308
+ if (Number.isFinite(seconds))
309
+ return Math.max(0, Math.ceil(seconds * 1000));
310
+ const date = Date.parse(header);
311
+ return Number.isNaN(date) ? 0 : Math.max(0, date - Date.now());
312
+ }
313
+ }
314
+ // src/resources/base.ts
315
+ class BaseManager {
316
+ rest;
317
+ constructor(rest2) {
318
+ this.rest = rest2;
319
+ }
320
+ }
321
+
322
+ // src/resources/api-key.ts
323
+ class APIKeyManager extends BaseManager {
324
+ async delete(id) {
325
+ return await this.rest.delete(Routes.apiKeys.delete(id));
326
+ }
327
+ }
328
+
329
+ // src/resources/logs.ts
330
+ class LogManager extends BaseManager {
331
+ async list(id, options) {
332
+ return await this.rest.get(Routes.webhooks.logs(id, options));
333
+ }
334
+ async get(id) {
335
+ return await this.rest.get(Routes.logs.get(id));
336
+ }
337
+ }
338
+
339
+ // src/resources/message.ts
340
+ class MessageManager extends BaseManager {
341
+ async send({ idempotencyKey, ...body }) {
342
+ return await this.rest.post(Routes.messages.send(), body, {
343
+ headers: {
344
+ "Idempotency-Key": idempotencyKey ?? ""
345
+ }
346
+ });
347
+ }
348
+ async list(options) {
349
+ return await this.rest.get(Routes.messages.list(options));
350
+ }
351
+ async batch(body, { idempotencyKey }) {
352
+ return await this.rest.post(Routes.messages.batch(), body, {
353
+ headers: {
354
+ "Idempotency-Key": idempotencyKey ?? ""
355
+ }
356
+ });
357
+ }
358
+ async cancel(id) {
359
+ return await this.rest.post(Routes.messages.cancel(id));
360
+ }
361
+ async get(id) {
362
+ return await this.rest.get(Routes.messages.get(id));
363
+ }
364
+ }
365
+
366
+ // src/resources/otp.ts
367
+ class OTPManager extends BaseManager {
368
+ async send({ idempotencyKey, ...body }) {
369
+ return await this.rest.post(Routes.otp.send(), body, {
370
+ headers: {
371
+ "Idempotency-Key": idempotencyKey ?? ""
372
+ }
373
+ });
374
+ }
375
+ async verify({ id, ...body }) {
376
+ return await this.rest.post(Routes.otp.verify(id), body);
377
+ }
378
+ }
379
+
380
+ // src/resources/template.ts
381
+ class TemplateManager extends BaseManager {
382
+ async create(options) {
383
+ return await this.rest.post(Routes.templates.create(), options);
384
+ }
385
+ async update(id, options) {
386
+ return await this.rest.patch(Routes.templates.update(id), options);
387
+ }
388
+ async delete(id) {
389
+ return await this.rest.delete(Routes.templates.delete(id));
390
+ }
391
+ async list(options) {
392
+ return await this.rest.get(Routes.templates.list(options));
393
+ }
394
+ async get(id) {
395
+ return await this.rest.get(Routes.templates.get(id));
396
+ }
397
+ }
398
+
399
+ // src/resources/webhook.ts
400
+ import { createHmac, timingSafeEqual } from "node:crypto";
401
+ class WebhookManager extends BaseManager {
402
+ verify({
403
+ headers,
404
+ payload,
405
+ secret = process.env.REWRITE_WEBHOOK_SECRET
406
+ }) {
407
+ if (!secret)
408
+ throw new Error("Rewrite could not find a webhook secret to verify.");
409
+ const value = secret.startsWith("whsec_") ? secret.slice("whsec_".length) : secret;
410
+ const key = secret.startsWith("rw_whsec_") ? Buffer.from(secret) : /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}(?:==)?|[A-Za-z0-9+/]{3}=?)?$/.test(value) ? Buffer.from(value, "base64") : null;
411
+ const signature = headers["svix-signature"]?.split(",")[1];
412
+ if (!key || !headers["svix-id"] || !headers["svix-timestamp"] || !signature)
413
+ return false;
414
+ const expected = createHmac("sha256", key).update(`${headers["svix-id"]}.${headers["svix-timestamp"]}.${payload}`).digest("base64");
415
+ return signature.length === expected.length && timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
416
+ }
417
+ async create(options) {
418
+ return await this.rest.post(Routes.webhooks.create(), options);
419
+ }
420
+ async update(id, options) {
421
+ return await this.rest.patch(Routes.webhooks.update(id), options);
422
+ }
423
+ async delete(id) {
424
+ return await this.rest.delete(Routes.webhooks.delete(id));
425
+ }
426
+ async list(options) {
427
+ return await this.rest.get(Routes.webhooks.list(options));
428
+ }
429
+ async get(id) {
430
+ return await this.rest.get(Routes.webhooks.get(id));
431
+ }
432
+ }
433
+
434
+ // src/client.ts
435
+ class Rewrite {
436
+ rest;
437
+ secret;
438
+ otp;
439
+ logs;
440
+ apiKeys;
441
+ messages;
442
+ webhooks;
443
+ templates;
444
+ constructor(options) {
445
+ const resolved = typeof options === "string" ? { secret: options } : options;
446
+ if (typeof resolved.secret !== "string")
447
+ throw new Error("Expected a string for the secret");
448
+ this.secret = resolved.secret;
449
+ this.rest = new REST({
450
+ ...resolved.rest,
451
+ auth: this.secret
452
+ });
453
+ this.otp = new OTPManager(this.rest);
454
+ this.logs = new LogManager(this.rest);
455
+ this.apiKeys = new APIKeyManager(this.rest);
456
+ this.webhooks = new WebhookManager(this.rest);
457
+ this.messages = new MessageManager(this.rest);
458
+ this.templates = new TemplateManager(this.rest);
459
+ }
460
+ }
461
+ // src/version.ts
462
+ var version3 = "1.0.1";
463
+ export {
464
+ version3 as version,
465
+ WebhookStatus,
466
+ WebhookManager,
467
+ WebhookEventType,
468
+ WebhookDeliveryStatus,
469
+ TemplateManager,
470
+ Routes,
471
+ Rewrite,
472
+ OTPManager,
473
+ MessageType,
474
+ MessageStatus,
475
+ MessageManager,
476
+ MessageEncoding,
477
+ MessageAnalysisReason,
478
+ MessageAnalysisEncoding,
479
+ LogManager,
480
+ API_BASE_URL,
481
+ APIKeyScope,
482
+ APIKeyManager
483
+ };
@@ -0,0 +1,11 @@
1
+ import { type RESTDeleteAPIKeyData } from '@rewritetoday/types';
2
+ import { BaseManager } from './base';
3
+ /**
4
+ * API key resource operations.
5
+ */
6
+ export declare class APIKeyManager extends BaseManager {
7
+ /**
8
+ * Deletes an API key by id.
9
+ */
10
+ delete(id: string): Promise<RESTDeleteAPIKeyData>;
11
+ }
@@ -0,0 +1,12 @@
1
+ import type { REST } from '@rewritetoday/rest';
2
+ /**
3
+ * Shared base resource with access to the REST client.
4
+ */
5
+ export declare abstract class BaseManager {
6
+ /** REST client used by resource operations. */
7
+ readonly rest: REST;
8
+ /**
9
+ * Creates a base resource wrapper.
10
+ */
11
+ constructor(rest: REST);
12
+ }
@@ -0,0 +1,15 @@
1
+ import { type RESTGetListWebhookLogsData, type RESTGetListWebhookLogsQueryParams, type RESTGetWebhookLogData, type Snowflake } from '@rewritetoday/types';
2
+ import { BaseManager } from './base';
3
+ /**
4
+ * Webhook logs resource operations.
5
+ */
6
+ export declare class LogManager extends BaseManager {
7
+ /**
8
+ * Deletes an API key by id.
9
+ */
10
+ list(id: Snowflake, options?: RESTGetListWebhookLogsQueryParams): Promise<RESTGetListWebhookLogsData>;
11
+ /**
12
+ * Fetch for a single webhook log.
13
+ */
14
+ get(id: Snowflake): Promise<RESTGetWebhookLogData>;
15
+ }
@@ -0,0 +1,10 @@
1
+ import { type RESTGetListMessagesData, type RESTGetListMessagesQueryParams, type RESTGetMessageData, type RESTPostCancelMessageData, type RESTPostSendBatchMessagesBody, type RESTPostSendBatchMessagesData, type RESTPostSendMessageData } from '@rewritetoday/types';
2
+ import type { SendBatchMessageOptions, SendMessageOptions } from '../types/message';
3
+ import { BaseManager } from './base';
4
+ export declare class MessageManager extends BaseManager {
5
+ send({ idempotencyKey, ...body }: SendMessageOptions): Promise<RESTPostSendMessageData>;
6
+ list(options?: RESTGetListMessagesQueryParams): Promise<RESTGetListMessagesData>;
7
+ batch(body: RESTPostSendBatchMessagesBody, { idempotencyKey }: SendBatchMessageOptions): Promise<RESTPostSendBatchMessagesData>;
8
+ cancel(id: string): Promise<RESTPostCancelMessageData>;
9
+ get(id: string): Promise<RESTGetMessageData>;
10
+ }
@@ -0,0 +1,7 @@
1
+ import { type RESTPostSendOTPMessageData, type RESTPostVerifyOTPCodeData } from '@rewritetoday/types';
2
+ import type { SendOTPMessageOptions, VerifyOTPOptions } from '../types/otp';
3
+ import { BaseManager } from './base';
4
+ export declare class OTPManager extends BaseManager {
5
+ send({ idempotencyKey, ...body }: SendOTPMessageOptions): Promise<RESTPostSendOTPMessageData>;
6
+ verify({ id, ...body }: VerifyOTPOptions): Promise<RESTPostVerifyOTPCodeData>;
7
+ }
@@ -0,0 +1,27 @@
1
+ import { type RESTDeleteTemplateData, type RESTGetListTemplatesData, type RESTGetListTemplatesQueryParams, type RESTGetTemplateData, type RESTPostCreateTemplateBody, type RESTPostCreateTemplateData, type Snowflake } from '@rewritetoday/types';
2
+ import { BaseManager } from './base';
3
+ /**
4
+ * Template resource operations.
5
+ */
6
+ export declare class TemplateManager extends BaseManager {
7
+ /**
8
+ * Creates a template for a project.
9
+ */
10
+ create(options: RESTPostCreateTemplateBody): Promise<RESTPostCreateTemplateData>;
11
+ /**
12
+ * Updates a template by id.
13
+ */
14
+ update(id: Snowflake, options: RESTPostCreateTemplateBody): Promise<RESTPostCreateTemplateData>;
15
+ /**
16
+ * Deletes a template by id.
17
+ */
18
+ delete(id: Snowflake): Promise<RESTDeleteTemplateData>;
19
+ /**
20
+ * Lists templates for a project.
21
+ */
22
+ list(options?: RESTGetListTemplatesQueryParams): Promise<RESTGetListTemplatesData>;
23
+ /**
24
+ * Fetches a template by id.
25
+ */
26
+ get(id: Snowflake): Promise<RESTGetTemplateData>;
27
+ }
@@ -0,0 +1,29 @@
1
+ import { type RESTDeleteWebhookData, type RESTGetListWebhooksData, type RESTGetListWebhooksQueryParams, type RESTGetWebhookData, type RESTPatchUpdateWebhookBody, type RESTPatchUpdateWebhookData, type RESTPostCreateWebhookBody, type RESTPostCreateWebhookData, type Snowflake } from '@rewritetoday/types';
2
+ import type { VerifyWebhookOptions } from '../types/webhook';
3
+ import { BaseManager } from './base';
4
+ /**
5
+ * Webhook resource operations.
6
+ */
7
+ export declare class WebhookManager extends BaseManager {
8
+ verify({ headers, payload, secret, }: VerifyWebhookOptions): boolean;
9
+ /**
10
+ * Creates a webhook for a project.
11
+ */
12
+ create(options: RESTPostCreateWebhookBody): Promise<RESTPostCreateWebhookData>;
13
+ /**
14
+ * Updates a webhook by id.
15
+ */
16
+ update(id: Snowflake, options: RESTPatchUpdateWebhookBody): Promise<RESTPatchUpdateWebhookData>;
17
+ /**
18
+ * Deletes a webhook by id.
19
+ */
20
+ delete(id: Snowflake): Promise<RESTDeleteWebhookData>;
21
+ /**
22
+ * Lists webhooks for a project.
23
+ */
24
+ list(options?: RESTGetListWebhooksQueryParams): Promise<RESTGetListWebhooksData>;
25
+ /**
26
+ * Fetches a webhook by id.
27
+ */
28
+ get(id: Snowflake): Promise<RESTGetWebhookData>;
29
+ }
@@ -0,0 +1,13 @@
1
+ import type { RESTOptions } from '@rewritetoday/rest';
2
+ /**
3
+ * Options used to initialize the Rewrite client.
4
+ */
5
+ export interface RewriteOptions {
6
+ /** API secret used for authentication. */
7
+ secret: string;
8
+ /** Extra REST client options, excluding auth. */
9
+ rest?: Omit<RESTOptions, 'auth'>;
10
+ }
11
+ export * from './message';
12
+ export * from './otp';
13
+ export * from './webhook';
@@ -0,0 +1,10 @@
1
+ import type { RESTPostSendMessageBody } from '@rewritetoday/types';
2
+ /** Options to send when creating a new message. */
3
+ export type SendMessageOptions = RESTPostSendMessageBody & {
4
+ /** Idempotency key to use in "Idempotency-Key" header. */
5
+ idempotencyKey?: string;
6
+ };
7
+ export interface SendBatchMessageOptions {
8
+ /** Idempotency key to use in "Idempotency-Key" header. */
9
+ idempotencyKey?: string;
10
+ }
@@ -0,0 +1,11 @@
1
+ import type { RESTPostSendOTPMessageBody, RESTPostVerifyOTPCodeBody, Snowflake } from '@rewritetoday/types';
2
+ /** Options to send when creating a new OTP message. */
3
+ export interface SendOTPMessageOptions extends RESTPostSendOTPMessageBody {
4
+ /** Idempotency key to use in "Idempotency-Key" header. */
5
+ idempotencyKey?: string;
6
+ }
7
+ /** Options to send when verifing an OTP message. */
8
+ export interface VerifyOTPOptions extends RESTPostVerifyOTPCodeBody {
9
+ /** ID of the message. See {@link Snowflake}. */
10
+ id: Snowflake;
11
+ }
@@ -0,0 +1,9 @@
1
+ /** Options used the verify if a webhook came from Rewrite or not. */
2
+ export interface VerifyWebhookOptions {
3
+ /** Signing secret of the webhook. @default process.env.REWRITE_WEBHOOK_SECRET */
4
+ secret?: string;
5
+ /** Raw payload in string of the request. */
6
+ payload: string;
7
+ /** Headers of the request. */
8
+ headers: Record<string, string>;
9
+ }
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Current version of [@rewritetoday/sdk](https://www.npmjs.com/package/@rewritetoday/sdk).
3
+ */
4
+ export declare const version: "1.0.1";
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@rewritetoday/sdk",
3
+ "version": "1.0.1",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "git+https://github.com/rewritetoday/node.git"
7
+ },
8
+ "main": "./dist/index.js",
9
+ "module": "src/index.ts",
10
+ "devDependencies": {
11
+ "@biomejs/biome": "^2.4.8",
12
+ "@types/bun": "latest"
13
+ },
14
+ "peerDependencies": {
15
+ "typescript": "^5.9.3"
16
+ },
17
+ "description": "An ergonomic SDK to integrate with Rewrite in your workflow",
18
+ "engines": {
19
+ "node": ">=18",
20
+ "bun": ">=1.0.0"
21
+ },
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "maintainers": [
26
+ {
27
+ "name": "Almeida",
28
+ "url": "https://github.com/almeidazs"
29
+ }
30
+ ],
31
+ "private": false,
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "scripts": {
36
+ "test": "bun test",
37
+ "biome:check": "biome check --write .",
38
+ "build": "rm -rf dist && bun run scripts/version.ts && bun biome:check && bun build src/index.ts --outdir dist --target node && bun run types",
39
+ "types": "bunx tsc --emitDeclarationOnly",
40
+ "prepublishOnly": "bun run build"
41
+ },
42
+ "type": "module",
43
+ "types": "./dist/index.d.ts",
44
+ "dependencies": {
45
+ "@rewritetoday/rest": "^1.0.1",
46
+ "@rewritetoday/types": "^1.0.1"
47
+ }
48
+ }