posthog-node 5.70.0 → 5.72.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.
@@ -33,8 +33,10 @@ __webpack_require__.d(__webpack_exports__, {
33
33
  EmailSender: ()=>EmailSender
34
34
  });
35
35
  const core_namespaceObject = require("@posthog/core");
36
+ const external_attachments_js_namespaceObject = require("./attachments.js");
36
37
  const external_errors_js_namespaceObject = require("./errors.js");
37
38
  const SEND_PATH = '/api/projects/@current/messaging/send/email/';
39
+ const UPLOADS_PATH = '/api/projects/@current/messaging/attachments/uploads/';
38
40
  const STATUS_PATH = '/api/projects/@current/messaging/emails/{messageId}/';
39
41
  const PREFERENCES_PATH = '/api/projects/@current/messaging/preferences/';
40
42
  const US_APP_HOST = 'https://us.posthog.com';
@@ -66,6 +68,11 @@ const CODE_FIELDS = {
66
68
  from: true,
67
69
  replyTo: true,
68
70
  captureEngagement: true,
71
+ cc: true,
72
+ bcc: true,
73
+ attachments: true,
74
+ sensitive: true,
75
+ tracking: true,
69
76
  html: true,
70
77
  text: true,
71
78
  react: true
@@ -112,7 +119,13 @@ class EmailSender {
112
119
  refuseSecondArgument(unexpected);
113
120
  const prepared = prepareSend(options, this.config.maxRetries);
114
121
  const { appHost, secretKey } = this.connect('no email was sent', 'Sending email needs secretKey, a project secret API key with the transactional_email:write scope.');
115
- const body = void 0 === prepared.react ? prepared.body : await withRenderedReact(prepared.body, prepared.react, this.config.requestTimeoutMs);
122
+ const content = void 0 === prepared.react ? prepared.content : await withRenderedReact(prepared.content, prepared.react, this.config.requestTimeoutMs);
123
+ if (void 0 !== prepared.react) (0, external_attachments_js_namespaceObject.refuseRenderedMessageOverLimit)(prepared.files, content);
124
+ const attachments = await this.uploadAttachments(prepared, appHost, secretKey);
125
+ const body = (0, core_namespaceObject.safeJsonStringify)({
126
+ ...content,
127
+ ...unlessEmpty('attachments', attachments)
128
+ });
116
129
  const headers = this.headers(secretKey, {
117
130
  'Content-Type': 'application/json',
118
131
  'Idempotency-Key': prepared.idempotencyKey
@@ -148,6 +161,69 @@ class EmailSender {
148
161
  };
149
162
  }
150
163
  }
164
+ async uploadAttachments({ files, maxRetries }, appHost, secretKey) {
165
+ if (0 === files.length) return [];
166
+ const hashed = await (0, external_attachments_js_namespaceObject.hashedFiles)(files);
167
+ const distinct = new Map();
168
+ for (const file of hashed)if (!distinct.has(file.sha256)) distinct.set(file.sha256, file);
169
+ const requested = [
170
+ ...distinct.values()
171
+ ];
172
+ const body = (0, core_namespaceObject.safeJsonStringify)({
173
+ files: requested.map(({ sha256, bytes })=>({
174
+ sha256,
175
+ size: bytes.byteLength
176
+ }))
177
+ });
178
+ const headers = this.headers(secretKey, {
179
+ 'Content-Type': 'application/json'
180
+ });
181
+ const uploads = await this.withRetries(maxRetries, async ()=>parseUploadsReply(await this.request(appHost + UPLOADS_PATH, 'POST', headers, body), requested));
182
+ const unencrypted = isPlainHttp(appHost) ? void 0 : uploads.find(({ url })=>!isHttps(url));
183
+ if (unencrypted) throw new external_errors_js_namespaceObject.EmailError({
184
+ code: 'api_error',
185
+ message: `PostHog named an upload URL for ${unencrypted.field} that isn't https, so the file would travel unencrypted. No email was sent.`,
186
+ field: unencrypted.field,
187
+ fix: "Make your PostHog's file storage URL use https. For local development over plain HTTP, set appHost to your http app host."
188
+ });
189
+ for (const upload of uploads)await this.withRetries(maxRetries, ()=>this.uploadFile(upload));
190
+ return hashed.map(external_attachments_js_namespaceObject.attachmentReference);
191
+ }
192
+ async uploadFile({ url, headers, bytes, field }) {
193
+ let reply;
194
+ try {
195
+ reply = await this.request(url, 'PUT', headers, bytes, 'manual');
196
+ } catch (cause) {
197
+ if (cause instanceof Error && 'AbortError' === cause.name) throw new external_errors_js_namespaceObject.EmailError({
198
+ code: 'network_error',
199
+ message: `The upload of ${field} timed out after ${this.config.requestTimeoutMs}ms, so no email was sent.`,
200
+ fix: 'Raise emailRequestTimeoutMs on the client, or send smaller files.',
201
+ field,
202
+ cause
203
+ });
204
+ throw new external_errors_js_namespaceObject.EmailError({
205
+ code: 'network_error',
206
+ message: `The upload of ${field} didn't reach PostHog's file storage, so no email was sent.`,
207
+ field,
208
+ cause
209
+ });
210
+ }
211
+ if (reply.status >= 300 && reply.status < 400) throw new external_errors_js_namespaceObject.EmailError({
212
+ code: 'attachment_upload_failed',
213
+ message: `PostHog's file storage redirected the upload of ${field} elsewhere. The SDK uploads only to the URL PostHog signed, so no email was sent.`,
214
+ statusCode: reply.status,
215
+ fix: "Make your PostHog's file storage URL point straight at the storage, over https.",
216
+ field
217
+ });
218
+ if (reply.status < 200 || reply.status >= 300) throw new external_errors_js_namespaceObject.EmailError({
219
+ code: 'attachment_upload_failed',
220
+ message: `PostHog's file storage refused the upload of ${field}, so no email was sent. ${storageAnswer(reply)}`,
221
+ statusCode: reply.status,
222
+ fix: 'Send the email again. Each send asks for new upload URLs.',
223
+ field,
224
+ retryAfterMs: reply.retryAfterMs
225
+ });
226
+ }
151
227
  async setPreferencesUntracked(options) {
152
228
  try {
153
229
  const body = preparePreferences(options);
@@ -218,7 +294,7 @@ class EmailSender {
218
294
  await new Promise((resolve)=>setTimeout(resolve, delayMs));
219
295
  }
220
296
  }
221
- async request(url, method, headers, body) {
297
+ async request(url, method, headers, body, redirect) {
222
298
  const controller = new AbortController();
223
299
  const timeoutMs = this.config.requestTimeoutMs;
224
300
  let timer;
@@ -236,6 +312,9 @@ class EmailSender {
236
312
  ...void 0 === body ? {} : {
237
313
  body
238
314
  },
315
+ ...redirect ? {
316
+ redirect
317
+ } : {},
239
318
  signal: controller.signal
240
319
  }));
241
320
  fetchPromise.then((lateResponse)=>{
@@ -257,13 +336,13 @@ class EmailSender {
257
336
  if (response.status >= 200 && response.status < 300) throw error;
258
337
  return {
259
338
  status: response.status,
260
- payload: null,
339
+ text: '',
261
340
  retryAfterMs: readRetryAfter(response)
262
341
  };
263
342
  }
264
343
  return {
265
344
  status: response.status,
266
- payload: parseJson(text),
345
+ text,
267
346
  retryAfterMs: readRetryAfter(response)
268
347
  };
269
348
  } finally{
@@ -283,19 +362,23 @@ function prepareSend(options, defaultMaxRetries) {
283
362
  const { to, distinctId, idempotencyKey, maxRetries } = send;
284
363
  if ('string' != typeof to || !to.trim()) throw invalid('invalid_recipient', 'to must be one email address as a nonempty string.', 'to');
285
364
  if (void 0 !== distinctId && ('string' != typeof distinctId || !distinctId)) throw invalid('invalid_distinct_id', 'distinctId must be a nonempty string.', 'distinctId');
286
- const content = contentOf(send, distinctId);
365
+ const { content, files } = contentOf(send, distinctId);
287
366
  if (void 0 !== idempotencyKey && ('string' != typeof idempotencyKey || !IDEMPOTENCY_KEY_PATTERN.test(idempotencyKey))) throw invalid('invalid_idempotency_key', 'idempotencyKey must be 1 to 255 visible ASCII characters without spaces.', 'idempotencyKey');
288
367
  if (void 0 !== maxRetries && !isRetryCount(maxRetries)) throw invalid('invalid_max_retries', 'maxRetries must be a nonnegative integer.', 'maxRetries');
289
368
  return {
290
- body: (0, core_namespaceObject.safeJsonStringify)({
369
+ content: snapshotOf({
291
370
  ...content,
292
371
  to
293
372
  }),
373
+ files,
294
374
  react: isReactElement(send.react) ? send.react : void 0,
295
375
  idempotencyKey: idempotencyKey ?? globalThis.crypto.randomUUID(),
296
376
  maxRetries: isRetryCount(maxRetries) ? maxRetries : defaultMaxRetries
297
377
  };
298
378
  }
379
+ function snapshotOf(content) {
380
+ return JSON.parse((0, core_namespaceObject.safeJsonStringify)(content));
381
+ }
299
382
  function preparePreferences(options) {
300
383
  const fallback = {};
301
384
  const { to, allMarketing, topics } = options ?? fallback;
@@ -322,7 +405,10 @@ function contentOf(send, distinctId) {
322
405
  code: 'invalid_form',
323
406
  message: 'Send either templateId, or templateKey with subject and html, text or react.'
324
407
  });
325
- return void 0 === send.templateKey ? templateContent(send, distinctId) : codeContent(send, distinctId);
408
+ return void 0 === send.templateKey ? {
409
+ content: templateContent(send, distinctId),
410
+ files: []
411
+ } : codeContent(send, distinctId);
326
412
  }
327
413
  function templateContent(send, distinctId) {
328
414
  const { templateId, templateData } = send;
@@ -338,7 +424,7 @@ function templateContent(send, distinctId) {
338
424
  };
339
425
  }
340
426
  function codeContent(send, distinctId) {
341
- const { templateKey, subject, html, text, react, from, replyTo, captureEngagement } = send;
427
+ const { templateKey, subject, html, text, react } = send;
342
428
  if ('string' != typeof templateKey || !TEMPLATE_KEY_PATTERN.test(templateKey)) throw invalid('invalid_template_key', 'templateKey can only have letters, digits, hyphens (-) and underscores (_), at most 400.', 'templateKey');
343
429
  refuseFieldsOutside(send, CODE_FORM, TEMPLATE_FORM);
344
430
  if ('string' != typeof subject) throw invalid('invalid_form', 'A send with templateKey needs a subject.', 'subject');
@@ -346,30 +432,59 @@ function codeContent(send, distinctId) {
346
432
  if (void 0 !== text && 'string' != typeof text) throw invalid('invalid_form', 'text must be a string.', 'text');
347
433
  if (void 0 !== react) checkReactContent(react, html);
348
434
  else if (void 0 === html && void 0 === text) throw invalid('invalid_form', 'A send with templateKey needs html, text or react.', 'html');
349
- const sendsReplyTo = void 0 !== replyTo && !(Array.isArray(replyTo) && 0 === replyTo.length);
435
+ const files = void 0 === send.attachments ? [] : (0, external_attachments_js_namespaceObject.attachmentFiles)(send.attachments, {
436
+ html,
437
+ text,
438
+ subject
439
+ });
350
440
  return {
351
- template_key: templateKey,
352
- subject,
353
- ...void 0 !== html && {
354
- html
355
- },
356
- ...void 0 !== text && {
357
- text
441
+ content: {
442
+ template_key: templateKey,
443
+ subject,
444
+ ...void 0 !== html && {
445
+ html
446
+ },
447
+ ...void 0 !== text && {
448
+ text
449
+ },
450
+ ...codeFormFields(send),
451
+ ...void 0 !== distinctId && {
452
+ distinct_id: distinctId
453
+ }
358
454
  },
455
+ files
456
+ };
457
+ }
458
+ function codeFormFields(send) {
459
+ const { from, replyTo, cc, bcc, captureEngagement, sensitive, tracking } = send;
460
+ return {
359
461
  ...void 0 !== from && {
360
462
  from
361
463
  },
362
- ...sendsReplyTo && {
363
- reply_to: 'string' == typeof replyTo ? [
364
- replyTo
365
- ] : replyTo
464
+ ...void 0 !== replyTo && unlessEmpty('reply_to', addressList(replyTo)),
465
+ ...void 0 !== cc && unlessEmpty('cc', addressList(cc)),
466
+ ...void 0 !== bcc && unlessEmpty('bcc', addressList(bcc)),
467
+ ...void 0 !== captureEngagement && {
468
+ capture_engagement: captureEngagement
366
469
  },
367
- capture_engagement: captureEngagement ?? true,
368
- ...void 0 !== distinctId && {
369
- distinct_id: distinctId
470
+ ...void 0 !== sensitive && {
471
+ sensitive
472
+ },
473
+ ...void 0 !== tracking && {
474
+ tracking
370
475
  }
371
476
  };
372
477
  }
478
+ function unlessEmpty(field, list) {
479
+ return Array.isArray(list) && 0 === list.length ? {} : {
480
+ [field]: list
481
+ };
482
+ }
483
+ function addressList(addresses) {
484
+ return 'string' == typeof addresses ? [
485
+ addresses
486
+ ] : addresses;
487
+ }
373
488
  function checkReactContent(react, html) {
374
489
  if (!isReactElement(react)) throw invalid('invalid_form', 'react must be a React element, such as <WelcomeEmail />.', 'react');
375
490
  if (void 0 !== html) throw new external_errors_js_namespaceObject.EmailError({
@@ -386,18 +501,17 @@ const REACT_18_AND_19_ELEMENT_MARKERS = [
386
501
  function isReactElement(value) {
387
502
  return 'object' == typeof value && null !== value && '$$typeof' in value && REACT_18_AND_19_ELEMENT_MARKERS.includes(value.$$typeof) && 'type' in value && 'props' in value;
388
503
  }
389
- async function withRenderedReact(body, react, timeoutMs) {
504
+ async function withRenderedReact(content, react, timeoutMs) {
390
505
  const { render, toPlainText } = await loadReactRenderer();
391
- const fields = JSON.parse(body);
392
506
  try {
393
507
  const html = await settleWithin(render(react), timeoutMs, 'Rendering the react element');
394
- return (0, core_namespaceObject.safeJsonStringify)({
395
- ...fields,
508
+ return {
509
+ ...content,
396
510
  html,
397
- ...void 0 === fields.text && {
511
+ ...void 0 === content.text && {
398
512
  text: toPlainText(html)
399
513
  }
400
- });
514
+ };
401
515
  } catch (cause) {
402
516
  throw new external_errors_js_namespaceObject.EmailError({
403
517
  code: 'react_render_failed',
@@ -460,6 +574,12 @@ function invalid(code, message, field) {
460
574
  field
461
575
  });
462
576
  }
577
+ function isHttps(url) {
578
+ return url.toLowerCase().startsWith('https://');
579
+ }
580
+ function isPlainHttp(url) {
581
+ return url.toLowerCase().startsWith('http://');
582
+ }
463
583
  function resolveAppHost(host, appHost) {
464
584
  const explicit = 'string' == typeof appHost ? (0, core_namespaceObject.removeTrailingSlash)(appHost.trim()) : '';
465
585
  if (explicit) return CLOUD_APP_HOSTS[explicit] ?? explicit;
@@ -485,8 +605,8 @@ function emails_text(value) {
485
605
  function replyFields(payload) {
486
606
  return null === payload || 'object' != typeof payload || Array.isArray(payload) ? {} : payload;
487
607
  }
488
- function parseSendReply({ status, payload, retryAfterMs }) {
489
- const fields = replyFields(payload);
608
+ function parseSendReply({ status, text: body, retryAfterMs }) {
609
+ const fields = replyFields(parseJson(body));
490
610
  if (status >= 200 && status < 300) {
491
611
  const id = emails_text(fields.message_id);
492
612
  if (!id) throw new external_errors_js_namespaceObject.EmailError({
@@ -510,8 +630,8 @@ function parseSendReply({ status, payload, retryAfterMs }) {
510
630
  }
511
631
  throw replyError(fields, status, retryAfterMs);
512
632
  }
513
- function parseStatusReply({ status, payload, retryAfterMs }) {
514
- const fields = replyFields(payload);
633
+ function parseStatusReply({ status, text: body, retryAfterMs }) {
634
+ const fields = replyFields(parseJson(body));
515
635
  if (status < 200 || status >= 300) throw replyError(fields, status, retryAfterMs);
516
636
  const id = emails_text(fields.id);
517
637
  const deliveryStatus = emails_text(fields.status);
@@ -530,8 +650,53 @@ function parseStatusReply({ status, payload, retryAfterMs }) {
530
650
  reason: emails_text(fields.reason) ?? null
531
651
  };
532
652
  }
533
- function parsePreferencesReply({ status, payload, retryAfterMs }) {
534
- const fields = replyFields(payload);
653
+ function parseUploadsReply({ status, text: body, retryAfterMs }, requested) {
654
+ const fields = replyFields(parseJson(body));
655
+ if (404 === status) throw replyError({
656
+ code: 'not_found',
657
+ ...fields,
658
+ attr: emails_text(fields.attr) ?? 'attachments'
659
+ }, status, retryAfterMs);
660
+ if (status < 200 || status >= 300) throw replyError({
661
+ ...fields,
662
+ attr: callerField(emails_text(fields.attr), requested)
663
+ }, status, retryAfterMs);
664
+ const answers = Array.isArray(fields.files) ? fields.files.map(replyFields) : [];
665
+ const uploads = [];
666
+ for (const { sha256, bytes, field } of requested){
667
+ const answer = answers.find((file)=>file.sha256 === sha256);
668
+ if (answer?.status === 'present') continue;
669
+ const url = emails_text(answer?.url);
670
+ if (answer?.status !== 'upload' || !url || !isStringRecord(answer.headers)) throw new external_errors_js_namespaceObject.EmailError({
671
+ code: 'api_error',
672
+ message: 'PostHog answered without telling where to upload every file.',
673
+ statusCode: status
674
+ });
675
+ uploads.push({
676
+ url,
677
+ headers: answer.headers,
678
+ bytes,
679
+ field
680
+ });
681
+ }
682
+ return uploads;
683
+ }
684
+ function callerField(attr, requested) {
685
+ const file = void 0 === attr ? null : /^files(?:__(\d+))?(?:__|$)/.exec(attr);
686
+ if (!file) return attr;
687
+ return void 0 === file[1] ? 'attachments' : requested[Number(file[1])]?.field ?? 'attachments';
688
+ }
689
+ function isStringRecord(value) {
690
+ return null !== value && 'object' == typeof value && !Array.isArray(value) && Object.values(value).every((item)=>'string' == typeof item);
691
+ }
692
+ function storageAnswer({ status, text: body }) {
693
+ const code = /<Code>([^<]{1,100})<\/Code>/.exec(body)?.[1];
694
+ const message = /<Message>([^<]{1,300})<\/Message>/.exec(body)?.[1];
695
+ const answer = `It answered HTTP ${status}${code ? ` ${code}` : ''}${message ? `: ${message}` : ''}`;
696
+ return answer.endsWith('.') ? answer : `${answer}.`;
697
+ }
698
+ function parsePreferencesReply({ status, text: body, retryAfterMs }) {
699
+ const fields = replyFields(parseJson(body));
535
700
  if (status < 200 || status >= 300) throw replyError(fields, status, retryAfterMs);
536
701
  const to = emails_text(fields.identifier);
537
702
  const allMarketing = fields.all_marketing;
@@ -568,8 +733,9 @@ function asEmailError(error, message) {
568
733
  }
569
734
  function isRetryable(error) {
570
735
  if (void 0 === error.statusCode) return 'network_error' === error.code;
736
+ if ('attachment_upload_failed' === error.code) return 429 === error.statusCode || error.statusCode >= 500;
571
737
  if (409 === error.statusCode) return 'idempotency_key_in_flight' === error.code;
572
- if (429 === error.statusCode) return 'quota_limited' !== error.code;
738
+ if (429 === error.statusCode) return 'quota_limited' !== error.code && 'upload_quota_exceeded' !== error.code;
573
739
  return 503 === error.statusCode;
574
740
  }
575
741
  function retryDelayMs(error, attempt, maxRetries) {