@technomoron/mail-magic-client 1.0.33 → 1.0.35

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/CHANGES CHANGED
@@ -1,6 +1,19 @@
1
1
  CHANGES
2
2
  =======
3
3
 
4
+ Version 1.0.35 (2026-03-05)
5
+
6
+ - fix(client): check response `content-type` header in `postFormData` before calling `response.json()`; extract shared `parseJsonResponse` helper used by both `request()` and `postFormData()`.
7
+ - (Changes generated/assisted by Claude Code (profile: anthropic-claude-opus-4-6/high).)
8
+
9
+ Version 1.0.34 (2026-03-04)
10
+
11
+ - chore(dist): remove generated `dist/mail-magic-client.js` artifact from package tree.
12
+ - test(integration): guard integration test teardown/setup usage so `beforeAll` failures do not trigger secondary `ctx.cleanup()` crashes.
13
+ - fix(client): check response `content-type` header before calling `response.json()` to avoid obscure parse errors from non-JSON responses (e.g. HTML proxy error pages).
14
+ - (Changes generated/assisted by Codex (profile: chatgpt-5.3-codex/medium).)
15
+ - (Changes generated/assisted by Claude Code (profile: anthropic-claude-opus-4-6/high).)
16
+
4
17
  Version 1.0.33 (2026-02-22)
5
18
 
6
19
  - chore(release): add package-level `release:check` script and wire `release` to shared publish script.
@@ -77,6 +77,7 @@ declare class TemplateClient {
77
77
  private baseURL;
78
78
  private apiKey;
79
79
  constructor(baseURL: string, apiKey: string);
80
+ private parseJsonResponse;
80
81
  request<T>(method: 'GET' | 'POST' | 'PUT' | 'DELETE', command: string, body?: RequestBody): Promise<T>;
81
82
  get<T>(command: string): Promise<T>;
82
83
  post<T>(command: string, body: RequestBody): Promise<T>;
@@ -15,6 +15,21 @@ class TemplateClient {
15
15
  throw new Error('Apikey/api-url required');
16
16
  }
17
17
  }
18
+ async parseJsonResponse(response) {
19
+ const contentType = response.headers.get('content-type') || '';
20
+ if (!contentType.includes('application/json')) {
21
+ const text = await response.text();
22
+ throw new Error(`FETCH FAILED: ${response.status} unexpected content-type "${contentType}" - ${text.slice(0, 200)}`);
23
+ }
24
+ const j = await response.json();
25
+ if (response.ok) {
26
+ return j;
27
+ }
28
+ if (j && j.message) {
29
+ throw new Error(`FETCH FAILED: ${response.status} ${j.message}`);
30
+ }
31
+ throw new Error(`FETCH FAILED: ${response.status} ${response.statusText}`);
32
+ }
18
33
  async request(method, command, body) {
19
34
  const url = `${this.baseURL}${command}`;
20
35
  const headers = {
@@ -31,16 +46,7 @@ class TemplateClient {
31
46
  options.body = JSON.stringify(body);
32
47
  }
33
48
  const response = await fetch(url, options);
34
- const j = await response.json();
35
- if (response.ok) {
36
- return j;
37
- }
38
- if (j && j.message) {
39
- throw new Error(`FETCH FAILED: ${response.status} ${j.message}`);
40
- }
41
- else {
42
- throw new Error(`FETCH FAILED: ${response.status} ${response.statusText}`);
43
- }
49
+ return this.parseJsonResponse(response);
44
50
  }
45
51
  async get(command) {
46
52
  return this.request('GET', command);
@@ -139,14 +145,7 @@ class TemplateClient {
139
145
  },
140
146
  body: formData
141
147
  });
142
- const j = await response.json();
143
- if (response.ok) {
144
- return j;
145
- }
146
- if (j && j.message) {
147
- throw new Error(`FETCH FAILED: ${response.status} ${j.message}`);
148
- }
149
- throw new Error(`FETCH FAILED: ${response.status} ${response.statusText}`);
148
+ return this.parseJsonResponse(response);
150
149
  }
151
150
  async storeTemplate(td) {
152
151
  // Backward-compatible alias for transactional template storage.
@@ -10,6 +10,21 @@ class TemplateClient {
10
10
  throw new Error('Apikey/api-url required');
11
11
  }
12
12
  }
13
+ async parseJsonResponse(response) {
14
+ const contentType = response.headers.get('content-type') || '';
15
+ if (!contentType.includes('application/json')) {
16
+ const text = await response.text();
17
+ throw new Error(`FETCH FAILED: ${response.status} unexpected content-type "${contentType}" - ${text.slice(0, 200)}`);
18
+ }
19
+ const j = await response.json();
20
+ if (response.ok) {
21
+ return j;
22
+ }
23
+ if (j && j.message) {
24
+ throw new Error(`FETCH FAILED: ${response.status} ${j.message}`);
25
+ }
26
+ throw new Error(`FETCH FAILED: ${response.status} ${response.statusText}`);
27
+ }
13
28
  async request(method, command, body) {
14
29
  const url = `${this.baseURL}${command}`;
15
30
  const headers = {
@@ -26,16 +41,7 @@ class TemplateClient {
26
41
  options.body = JSON.stringify(body);
27
42
  }
28
43
  const response = await fetch(url, options);
29
- const j = await response.json();
30
- if (response.ok) {
31
- return j;
32
- }
33
- if (j && j.message) {
34
- throw new Error(`FETCH FAILED: ${response.status} ${j.message}`);
35
- }
36
- else {
37
- throw new Error(`FETCH FAILED: ${response.status} ${response.statusText}`);
38
- }
44
+ return this.parseJsonResponse(response);
39
45
  }
40
46
  async get(command) {
41
47
  return this.request('GET', command);
@@ -134,14 +140,7 @@ class TemplateClient {
134
140
  },
135
141
  body: formData
136
142
  });
137
- const j = await response.json();
138
- if (response.ok) {
139
- return j;
140
- }
141
- if (j && j.message) {
142
- throw new Error(`FETCH FAILED: ${response.status} ${j.message}`);
143
- }
144
- throw new Error(`FETCH FAILED: ${response.status} ${response.statusText}`);
143
+ return this.parseJsonResponse(response);
145
144
  }
146
145
  async storeTemplate(td) {
147
146
  // Backward-compatible alias for transactional template storage.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@technomoron/mail-magic-client",
3
- "version": "1.0.33",
3
+ "version": "1.0.35",
4
4
  "description": "Client library for mail-magic",
5
5
  "main": "dist/cjs/mail-magic-client.js",
6
6
  "types": "dist/cjs/mail-magic-client.d.ts",
@@ -1,325 +0,0 @@
1
- 'use strict';
2
- var __importDefault =
3
- (this && this.__importDefault) ||
4
- function (mod) {
5
- return mod && mod.__esModule ? mod : { default: mod };
6
- };
7
- Object.defineProperty(exports, '__esModule', { value: true });
8
- const fs_1 = __importDefault(require('fs'));
9
- const path_1 = __importDefault(require('path'));
10
- const email_addresses_1 = __importDefault(require('email-addresses'));
11
- const nunjucks_1 = __importDefault(require('nunjucks'));
12
- class templateClient {
13
- constructor(baseURL, apiKey) {
14
- this.baseURL = baseURL;
15
- this.apiKey = apiKey;
16
- if (!apiKey || !baseURL) {
17
- throw new Error('Apikey/api-url required');
18
- }
19
- }
20
- async request(method, command, body) {
21
- const url = `${this.baseURL}${command}`;
22
- const headers = {
23
- Accept: 'application/json',
24
- Authorization: `Bearer apikey-${this.apiKey}`
25
- };
26
- const options = {
27
- method,
28
- headers
29
- };
30
- // Avoid GET bodies (they're non-standard and can break under some proxies).
31
- if (method !== 'GET' && body !== undefined) {
32
- headers['Content-Type'] = 'application/json';
33
- options.body = JSON.stringify(body);
34
- }
35
- const response = await fetch(url, options);
36
- const j = await response.json();
37
- if (response.ok) {
38
- return j;
39
- }
40
- if (j && j.message) {
41
- throw new Error(`FETCH FAILED: ${response.status} ${j.message}`);
42
- } else {
43
- throw new Error(`FETCH FAILED: ${response.status} ${response.statusText}`);
44
- }
45
- }
46
- async get(command) {
47
- return this.request('GET', command);
48
- }
49
- async post(command, body) {
50
- return this.request('POST', command, body);
51
- }
52
- async put(command, body) {
53
- return this.request('PUT', command, body);
54
- }
55
- async delete(command, body) {
56
- return this.request('DELETE', command, body);
57
- }
58
- validateEmails(list) {
59
- const valid = [],
60
- invalid = [];
61
- const emails = list
62
- .split(',')
63
- .map((email) => email.trim())
64
- .filter((email) => email !== '');
65
- emails.forEach((email) => {
66
- const parsed = email_addresses_1.default.parseOneAddress(email);
67
- if (parsed && parsed.address) {
68
- valid.push(parsed.address);
69
- } else {
70
- invalid.push(email);
71
- }
72
- });
73
- return { valid, invalid };
74
- }
75
- validateTemplate(template) {
76
- try {
77
- const env = new nunjucks_1.default.Environment(null, { autoescape: true });
78
- const compiled = nunjucks_1.default.compile(template, env);
79
- compiled.render({});
80
- } catch (error) {
81
- const message = error instanceof Error ? error.message : String(error);
82
- // Syntax validation should not require local template loaders.
83
- if (/template not found|no loader|unable to find template/i.test(message)) {
84
- return;
85
- }
86
- if (error instanceof Error) {
87
- throw new Error(`Template validation failed: ${error.message}`);
88
- } else {
89
- throw new Error('Template validation failed with an unknown error');
90
- }
91
- }
92
- }
93
- validateSender(sender) {
94
- const exp = /^[^<>]+<[^<>]+@[^<>]+\.[^<>]+>$/;
95
- if (!exp.test(sender)) {
96
- throw new Error('Invalid sender format. Expected "Name <email@example.com>"');
97
- }
98
- }
99
- createAttachmentPayload(attachments) {
100
- const formData = new FormData();
101
- const usedFields = [];
102
- for (const attachment of attachments) {
103
- if (!attachment?.path) {
104
- throw new Error('Attachment path is required');
105
- }
106
- const raw = fs_1.default.readFileSync(attachment.path);
107
- const filename = attachment.filename || path_1.default.basename(attachment.path);
108
- const blob = new Blob([raw], attachment.contentType ? { type: attachment.contentType } : undefined);
109
- const field = attachment.field || 'attachment';
110
- formData.append(field, blob, filename);
111
- usedFields.push(field);
112
- }
113
- return { formData, usedFields };
114
- }
115
- appendFields(formData, fields) {
116
- for (const [key, value] of Object.entries(fields)) {
117
- if (value === undefined || value === null) {
118
- continue;
119
- }
120
- if (typeof value === 'string') {
121
- formData.append(key, value);
122
- } else if (typeof value === 'number' || typeof value === 'boolean') {
123
- formData.append(key, String(value));
124
- } else {
125
- formData.append(key, JSON.stringify(value));
126
- }
127
- }
128
- }
129
- async postFormData(command, formData) {
130
- const url = `${this.baseURL}${command}`;
131
- const response = await fetch(url, {
132
- method: 'POST',
133
- headers: {
134
- Authorization: `Bearer apikey-${this.apiKey}`
135
- },
136
- body: formData
137
- });
138
- const j = await response.json();
139
- if (response.ok) {
140
- return j;
141
- }
142
- if (j && j.message) {
143
- throw new Error(`FETCH FAILED: ${response.status} ${j.message}`);
144
- }
145
- throw new Error(`FETCH FAILED: ${response.status} ${response.statusText}`);
146
- }
147
- async storeTemplate(td) {
148
- // Backward-compatible alias for transactional template storage.
149
- return this.storeTxTemplate(td);
150
- }
151
- async sendTemplate(std) {
152
- if (!std.name || !std.rcpt) {
153
- throw new Error('Invalid request body; name/rcpt required');
154
- }
155
- return this.sendTxMessage(std);
156
- }
157
- async storeTxTemplate(td) {
158
- if (!td.template) {
159
- throw new Error('No template data provided');
160
- }
161
- this.validateTemplate(td.template);
162
- if (td.sender) {
163
- this.validateSender(td.sender);
164
- }
165
- return this.post('/api/v1/tx/template', td);
166
- }
167
- async sendTxMessage(std) {
168
- if (!std.name || !std.rcpt) {
169
- throw new Error('Invalid request body; name/rcpt required');
170
- }
171
- const { invalid } = this.validateEmails(std.rcpt);
172
- if (invalid.length > 0) {
173
- throw new Error('Invalid email address(es): ' + invalid.join(','));
174
- }
175
- const body = {
176
- name: std.name,
177
- rcpt: std.rcpt,
178
- domain: std.domain || '',
179
- locale: std.locale || '',
180
- vars: std.vars || {},
181
- replyTo: std.replyTo,
182
- headers: std.headers
183
- };
184
- if (std.attachments && std.attachments.length > 0) {
185
- if (std.headers) {
186
- throw new Error('Headers are not supported with attachment uploads');
187
- }
188
- const { formData } = this.createAttachmentPayload(std.attachments);
189
- this.appendFields(formData, {
190
- name: std.name,
191
- rcpt: std.rcpt,
192
- domain: std.domain || '',
193
- locale: std.locale || '',
194
- vars: JSON.stringify(std.vars || {}),
195
- replyTo: std.replyTo
196
- });
197
- return this.postFormData('/api/v1/tx/message', formData);
198
- }
199
- return this.post('/api/v1/tx/message', body);
200
- }
201
- async storeFormTemplate(data) {
202
- if (!data.template) {
203
- throw new Error('No template data provided');
204
- }
205
- if (!data.idname) {
206
- throw new Error('Missing form identifier');
207
- }
208
- if (!data.sender) {
209
- throw new Error('Missing sender address');
210
- }
211
- if (!data.recipient) {
212
- throw new Error('Missing recipient address');
213
- }
214
- this.validateTemplate(data.template);
215
- this.validateSender(data.sender);
216
- return this.post('/api/v1/form/template', data);
217
- }
218
- async storeFormRecipient(data) {
219
- if (!data.domain) {
220
- throw new Error('Missing domain');
221
- }
222
- if (!data.idname) {
223
- throw new Error('Missing recipient identifier');
224
- }
225
- if (!data.email) {
226
- throw new Error('Missing recipient email');
227
- }
228
- const parsed = email_addresses_1.default.parseOneAddress(data.email);
229
- if (!parsed || !parsed.address) {
230
- throw new Error('Invalid recipient email address');
231
- }
232
- return this.post('/api/v1/form/recipient', data);
233
- }
234
- async sendFormMessage(data) {
235
- if (!data._mm_form_key) {
236
- throw new Error('Invalid request body; _mm_form_key required');
237
- }
238
- const fields = data.fields || {};
239
- const baseFields = {
240
- _mm_form_key: data._mm_form_key,
241
- _mm_locale: data._mm_locale,
242
- _mm_recipients: data._mm_recipients,
243
- ...fields
244
- };
245
- if (data.attachments && data.attachments.length > 0) {
246
- const normalized = data.attachments.map((attachment, idx) => {
247
- const field = attachment.field || `_mm_file${idx + 1}`;
248
- if (!field.startsWith('_mm_file')) {
249
- throw new Error('Form attachments must use multipart field names starting with _mm_file');
250
- }
251
- return { ...attachment, field };
252
- });
253
- const { formData } = this.createAttachmentPayload(normalized);
254
- this.appendFields(formData, {
255
- _mm_form_key: data._mm_form_key,
256
- _mm_locale: data._mm_locale,
257
- _mm_recipients: data._mm_recipients
258
- });
259
- this.appendFields(formData, fields);
260
- return this.postFormData('/api/v1/form/message', formData);
261
- }
262
- return this.post('/api/v1/form/message', baseFields);
263
- }
264
- async uploadAssets(data) {
265
- if (!data.domain) {
266
- throw new Error('domain is required');
267
- }
268
- if (!data.files || data.files.length === 0) {
269
- throw new Error('At least one asset file is required');
270
- }
271
- if (data.templateType && !data.template) {
272
- throw new Error('template is required when templateType is provided');
273
- }
274
- if (data.template && !data.templateType) {
275
- throw new Error('templateType is required when template is provided');
276
- }
277
- const attachments = data.files.map((input) => {
278
- if (typeof input === 'string') {
279
- return { path: input, field: 'asset' };
280
- }
281
- return { ...input, field: input.field || 'asset' };
282
- });
283
- const { formData } = this.createAttachmentPayload(attachments);
284
- this.appendFields(formData, {
285
- domain: data.domain,
286
- templateType: data.templateType,
287
- template: data.template,
288
- locale: data.locale,
289
- path: data.path
290
- });
291
- return this.postFormData('/api/v1/assets', formData);
292
- }
293
- async getSwaggerSpec() {
294
- return this.get('/api/swagger');
295
- }
296
- async fetchPublicAsset(domain, assetPath, viaApiBase = false) {
297
- if (!domain) {
298
- throw new Error('domain is required');
299
- }
300
- if (!assetPath) {
301
- throw new Error('assetPath is required');
302
- }
303
- const cleanedPath = assetPath
304
- .split('/')
305
- .filter(Boolean)
306
- .map((segment) => encodeURIComponent(segment))
307
- .join('/');
308
- if (!cleanedPath) {
309
- throw new Error('assetPath is required');
310
- }
311
- const prefix = viaApiBase ? '/api/asset' : '/asset';
312
- const url = `${this.baseURL}${prefix}/${encodeURIComponent(domain)}/${cleanedPath}`;
313
- const response = await fetch(url, {
314
- method: 'GET',
315
- headers: {
316
- Accept: '*/*'
317
- }
318
- });
319
- if (!response.ok) {
320
- throw new Error(`FETCH FAILED: ${response.status} ${response.statusText}`);
321
- }
322
- return response.arrayBuffer();
323
- }
324
- }
325
- exports.default = templateClient;