@mshindi-labs/google 0.0.0-stage → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +90 -2
  3. package/dist/chunk-JVP7HHFU.js +76 -0
  4. package/dist/chunk-JVP7HHFU.js.map +1 -0
  5. package/dist/chunk-KJPQ3DMR.cjs +76 -0
  6. package/dist/chunk-KJPQ3DMR.cjs.map +1 -0
  7. package/dist/chunk-RWT25QHA.js +190 -0
  8. package/dist/chunk-RWT25QHA.js.map +1 -0
  9. package/dist/chunk-SHDP4A3A.cjs +190 -0
  10. package/dist/chunk-SHDP4A3A.cjs.map +1 -0
  11. package/dist/chunk-SIDO26T7.js +949 -0
  12. package/dist/chunk-SIDO26T7.js.map +1 -0
  13. package/dist/chunk-V22QP2AM.cjs +49 -0
  14. package/dist/chunk-V22QP2AM.cjs.map +1 -0
  15. package/dist/chunk-VN5VWVCT.cjs +949 -0
  16. package/dist/chunk-VN5VWVCT.cjs.map +1 -0
  17. package/dist/chunk-Z7O6GO3C.js +49 -0
  18. package/dist/chunk-Z7O6GO3C.js.map +1 -0
  19. package/dist/core.cjs +289 -0
  20. package/dist/core.cjs.map +1 -0
  21. package/dist/core.d.cts +173 -0
  22. package/dist/core.d.ts +173 -0
  23. package/dist/core.js +289 -0
  24. package/dist/core.js.map +1 -0
  25. package/dist/create-google-CPGcK-3G.d.cts +107 -0
  26. package/dist/create-google-nP9f9jd9.d.ts +107 -0
  27. package/dist/events-BsWOMtza.d.cts +160 -0
  28. package/dist/events-BsWOMtza.d.ts +160 -0
  29. package/dist/gmail.cjs +489 -0
  30. package/dist/gmail.cjs.map +1 -0
  31. package/dist/gmail.d.cts +53 -0
  32. package/dist/gmail.d.ts +53 -0
  33. package/dist/gmail.js +489 -0
  34. package/dist/gmail.js.map +1 -0
  35. package/dist/key-provider-Cq_14Bh6.d.cts +53 -0
  36. package/dist/key-provider-Cq_14Bh6.d.ts +53 -0
  37. package/dist/postgres.cjs +455 -0
  38. package/dist/postgres.cjs.map +1 -0
  39. package/dist/postgres.d.cts +22 -0
  40. package/dist/postgres.d.ts +22 -0
  41. package/dist/postgres.js +455 -0
  42. package/dist/postgres.js.map +1 -0
  43. package/dist/static-key-provider-BhyRhY6-.d.ts +18 -0
  44. package/dist/static-key-provider-CPNt4YvF.d.cts +18 -0
  45. package/dist/testing.cjs +829 -0
  46. package/dist/testing.cjs.map +1 -0
  47. package/dist/testing.d.cts +147 -0
  48. package/dist/testing.d.ts +147 -0
  49. package/dist/testing.js +829 -0
  50. package/dist/testing.js.map +1 -0
  51. package/dist/transport-CVOgr9XP.d.cts +20 -0
  52. package/dist/transport-CVOgr9XP.d.ts +20 -0
  53. package/package.json +143 -4
package/dist/gmail.cjs ADDED
@@ -0,0 +1,489 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
4
+
5
+ var _chunkVN5VWVCTcjs = require('./chunk-VN5VWVCT.cjs');
6
+
7
+
8
+ var _chunkV22QP2AMcjs = require('./chunk-V22QP2AM.cjs');
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+ var _chunkSHDP4A3Acjs = require('./chunk-SHDP4A3A.cjs');
19
+
20
+ // src/gmail/mime.ts
21
+ var _crypto = require('crypto');
22
+ var MAX_ATTACHMENT_BYTES = 26214400;
23
+ function unwrap(mod) {
24
+ const m = mod;
25
+ return _nullishCoalesce(m.default, () => ( mod));
26
+ }
27
+ function toAddress(a) {
28
+ return a.name === null ? { address: a.address } : { name: a.name, address: a.address };
29
+ }
30
+ async function readLimited(stream, alreadyCounted) {
31
+ const chunks = [];
32
+ let total = alreadyCounted;
33
+ try {
34
+ for await (const chunk of stream) {
35
+ const buf = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
36
+ total += buf.length;
37
+ if (total > MAX_ATTACHMENT_BYTES) {
38
+ throw new (0, _chunkSHDP4A3Acjs.MessageTooLargeError)(total, MAX_ATTACHMENT_BYTES);
39
+ }
40
+ chunks.push(buf);
41
+ }
42
+ } catch (err) {
43
+ _optionalChain([stream, 'access', _ => _.destroy, 'optionalCall', _2 => _2()]);
44
+ throw err;
45
+ }
46
+ return { data: Buffer.concat(chunks), total };
47
+ }
48
+ async function buildMime(msg, from) {
49
+ try {
50
+ let total = 0;
51
+ for (const a of msg.attachments) {
52
+ if (Buffer.isBuffer(a.content)) total += a.content.length;
53
+ }
54
+ if (total > MAX_ATTACHMENT_BYTES) {
55
+ throw new (0, _chunkSHDP4A3Acjs.MessageTooLargeError)(total, MAX_ATTACHMENT_BYTES);
56
+ }
57
+ const htmlToText = msg.text === null && msg.html !== null ? unwrap(
58
+ await _chunkV22QP2AMcjs.loadPeer.call(void 0, "html-to-text", "html-to-text")
59
+ ) : null;
60
+ const MailComposer = unwrap(
61
+ await _chunkV22QP2AMcjs.loadPeer.call(void 0,
62
+ "nodemailer/lib/mail-composer/index.js",
63
+ "nodemailer"
64
+ )
65
+ );
66
+ const attachments = [];
67
+ for (const a of msg.attachments) {
68
+ let content;
69
+ if (Buffer.isBuffer(a.content)) {
70
+ content = a.content;
71
+ } else {
72
+ const read = await readLimited(a.content, total);
73
+ content = read.data;
74
+ total = read.total;
75
+ }
76
+ attachments.push({
77
+ filename: a.filename,
78
+ content,
79
+ ...a.contentType === null ? {} : { contentType: a.contentType }
80
+ });
81
+ }
82
+ let text = msg.text;
83
+ if (htmlToText !== null && msg.html !== null) {
84
+ text = htmlToText.convert(msg.html, { wordwrap: 78 });
85
+ }
86
+ const domain = from.address.split("@").pop();
87
+ const options = {
88
+ from: toAddress(from),
89
+ to: msg.to.map(toAddress),
90
+ cc: msg.cc.map(toAddress),
91
+ bcc: msg.bcc.map(toAddress),
92
+ subject: msg.subject,
93
+ messageId: `<${_crypto.randomUUID.call(void 0, )}@${domain}>`,
94
+ headers: msg.headers,
95
+ attachments
96
+ };
97
+ if (msg.replyTo) options.replyTo = toAddress(msg.replyTo);
98
+ if (msg.html !== null) options.html = msg.html;
99
+ if (text !== null) options.text = text;
100
+ if (msg.thread.inReplyTo !== null) options.inReplyTo = msg.thread.inReplyTo;
101
+ if (msg.thread.references.length > 0)
102
+ options.references = msg.thread.references;
103
+ const mail = new MailComposer(options).compile();
104
+ mail.keepBcc = true;
105
+ return mail.build();
106
+ } finally {
107
+ for (const a of msg.attachments) {
108
+ if (!Buffer.isBuffer(a.content)) {
109
+ _optionalChain([a, 'access', _3 => _3.content, 'access', _4 => _4.destroy, 'optionalCall', _5 => _5()]);
110
+ }
111
+ }
112
+ }
113
+ }
114
+
115
+ // src/gmail/retry.ts
116
+ var SendUnauthorizedSignal = class extends Error {
117
+ constructor() {
118
+ super("Google rejected the access token (401)");
119
+ this.name = "SendUnauthorizedSignal";
120
+ }
121
+ };
122
+ var PRE_SEND_CODES = /* @__PURE__ */ new Set(["ENOTFOUND", "EAI_AGAIN", "ECONNREFUSED"]);
123
+ var OUTCOME_UNKNOWN_CODES = /* @__PURE__ */ new Set([
124
+ "ECONNRESET",
125
+ "ETIMEDOUT",
126
+ "ESOCKETTIMEDOUT"
127
+ ]);
128
+ var RATE_REASONS = /* @__PURE__ */ new Set(["rateLimitExceeded", "userRateLimitExceeded"]);
129
+ var asErr = (err) => typeof err === "object" && err !== null ? err : {};
130
+ function readStatus(e) {
131
+ const s = _nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _6 => _6.response, 'optionalAccess', _7 => _7.status]), () => ( e.status)), () => ( e.code));
132
+ return typeof s === "number" ? s : null;
133
+ }
134
+ function readReason(e) {
135
+ const r = _nullishCoalesce(_optionalChain([e, 'access', _8 => _8.response, 'optionalAccess', _9 => _9.data, 'optionalAccess', _10 => _10.error, 'optionalAccess', _11 => _11.errors, 'optionalAccess', _12 => _12[0], 'optionalAccess', _13 => _13.reason]), () => ( _optionalChain([e, 'access', _14 => _14.errors, 'optionalAccess', _15 => _15[0], 'optionalAccess', _16 => _16.reason])));
136
+ return typeof r === "string" ? r : null;
137
+ }
138
+ function readNetCode(e) {
139
+ const c = _nullishCoalesce(e.code, () => ( _optionalChain([e, 'access', _17 => _17.cause, 'optionalAccess', _18 => _18.code])));
140
+ return typeof c === "string" ? c : null;
141
+ }
142
+ function readMessages(e) {
143
+ const a = typeof e.message === "string" ? e.message : "";
144
+ const b = _optionalChain([e, 'access', _19 => _19.response, 'optionalAccess', _20 => _20.data, 'optionalAccess', _21 => _21.error, 'optionalAccess', _22 => _22.message]);
145
+ return `${a} ${typeof b === "string" ? b : ""}`;
146
+ }
147
+ function readRetryAfterMs(e) {
148
+ const raw = _optionalChain([e, 'access', _23 => _23.response, 'optionalAccess', _24 => _24.headers, 'optionalAccess', _25 => _25["retry-after"]]);
149
+ const v = Array.isArray(raw) ? raw[0] : raw;
150
+ if (typeof v !== "string" && typeof v !== "number") return null;
151
+ const s = String(v).trim();
152
+ if (s === "") return null;
153
+ if (/^\d+(\.\d+)?$/.test(s)) return Math.round(Number(s) * 1e3);
154
+ const at = Date.parse(s);
155
+ return Number.isNaN(at) ? null : Math.max(0, at - Date.now());
156
+ }
157
+ function classifySendError(err) {
158
+ if (err instanceof _chunkSHDP4A3Acjs.GoogleLibError) return { kind: "fail", error: err };
159
+ const e = asErr(err);
160
+ const status = readStatus(e);
161
+ const reason = readReason(e);
162
+ const code = readNetCode(e);
163
+ const opts = { cause: err };
164
+ if (reason === "dailyLimitExceeded" || /sending limit/i.test(readMessages(e))) {
165
+ return {
166
+ kind: "fail",
167
+ error: new (0, _chunkSHDP4A3Acjs.DailyQuotaExceededError)(void 0, opts)
168
+ };
169
+ }
170
+ if (status === 429 || status === 403 && reason !== null && RATE_REASONS.has(reason)) {
171
+ return { kind: "retry", delayMs: readRetryAfterMs(e) };
172
+ }
173
+ if (status === 401) return { kind: "unauthorized" };
174
+ if (status === 400) {
175
+ return {
176
+ kind: "fail",
177
+ error: new (0, _chunkSHDP4A3Acjs.InvalidMessageError)("message", void 0, opts)
178
+ };
179
+ }
180
+ if (status !== null && status >= 500) {
181
+ return {
182
+ kind: "fail",
183
+ error: new (0, _chunkSHDP4A3Acjs.SendOutcomeUnknownError)(void 0, opts)
184
+ };
185
+ }
186
+ if (code !== null && (PRE_SEND_CODES.has(code) || code.startsWith("ERR_TLS_") || code.startsWith("CERT_"))) {
187
+ return { kind: "retry", delayMs: null };
188
+ }
189
+ if (code !== null && OUTCOME_UNKNOWN_CODES.has(code) || code === "ABORT_ERR" || e.name === "AbortError" || /socket hang up/i.test(readMessages(e))) {
190
+ return {
191
+ kind: "fail",
192
+ error: new (0, _chunkSHDP4A3Acjs.SendOutcomeUnknownError)(void 0, opts)
193
+ };
194
+ }
195
+ if (status !== null) {
196
+ return { kind: "fail", error: new (0, _chunkSHDP4A3Acjs.GoogleApiError)(status, reason, opts) };
197
+ }
198
+ return {
199
+ kind: "fail",
200
+ error: new (0, _chunkSHDP4A3Acjs.SendOutcomeUnknownError)(void 0, opts)
201
+ };
202
+ }
203
+ var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
204
+ async function withSendRetry(fn, opts = {}) {
205
+ const maxAttempts = _nullishCoalesce(opts.maxAttempts, () => ( 3));
206
+ const baseMs = _nullishCoalesce(opts.baseMs, () => ( 250));
207
+ const capMs = _nullishCoalesce(opts.capMs, () => ( 8e3));
208
+ const sleep = _nullishCoalesce(opts.sleep, () => ( defaultSleep));
209
+ const random = _nullishCoalesce(opts.random, () => ( Math.random));
210
+ for (let attempt = 0; ; attempt++) {
211
+ try {
212
+ return await fn();
213
+ } catch (err) {
214
+ const c = classifySendError(err);
215
+ if (c.kind === "fail") throw c.error;
216
+ if (c.kind === "unauthorized") throw new SendUnauthorizedSignal();
217
+ if (c.delayMs !== null && c.delayMs > capMs) {
218
+ throw new (0, _chunkSHDP4A3Acjs.RateLimitedError)(c.delayMs, { cause: err });
219
+ }
220
+ if (attempt + 1 >= maxAttempts) {
221
+ const e = asErr(err);
222
+ if (readStatus(e) !== null) {
223
+ throw new (0, _chunkSHDP4A3Acjs.RateLimitedError)(c.delayMs, { cause: err });
224
+ }
225
+ throw new (0, _chunkSHDP4A3Acjs.GoogleApiError)(0, readNetCode(e), { cause: err });
226
+ }
227
+ await sleep(
228
+ _nullishCoalesce(c.delayMs, () => ( random() * Math.min(capMs, baseMs * 2 ** attempt)))
229
+ );
230
+ }
231
+ }
232
+ }
233
+
234
+ // src/gmail/transport.ts
235
+ var _stream = require('stream');
236
+ var _googleauthlibrary = require('google-auth-library');
237
+ var UPLOAD_THRESHOLD_BYTES = 5242880;
238
+ function createGmailApiTransport() {
239
+ return {
240
+ async send({ accessToken, raw, threadId }) {
241
+ const mod = await _chunkV22QP2AMcjs.loadPeer.call(void 0, "@googleapis/gmail");
242
+ const { gmail } = mod.gmail ? mod : mod.default;
243
+ const auth = new (0, _googleauthlibrary.OAuth2Client)();
244
+ auth.setCredentials({ access_token: accessToken });
245
+ const api = gmail({ version: "v1", auth });
246
+ const thread = threadId === null ? {} : { threadId };
247
+ const { data } = raw.length <= UPLOAD_THRESHOLD_BYTES ? await api.users.messages.send({
248
+ userId: "me",
249
+ requestBody: { raw: raw.toString("base64url"), ...thread }
250
+ }) : await api.users.messages.send({
251
+ userId: "me",
252
+ requestBody: { ...thread },
253
+ media: { mimeType: "message/rfc822", body: _stream.Readable.from(raw) }
254
+ });
255
+ if (!_optionalChain([data, 'optionalAccess', _26 => _26.id])) throw new (0, _chunkSHDP4A3Acjs.SendOutcomeUnknownError)();
256
+ return {
257
+ messageId: data.id,
258
+ threadId: data.threadId || threadId || data.id
259
+ };
260
+ }
261
+ };
262
+ }
263
+
264
+ // src/gmail/validate.ts
265
+ var _path = require('path');
266
+ var LINE_BREAKS = /[\r\n\0]/;
267
+ var ADDRESS_FORBIDDEN = /[\s\u0000-\u001f\u007f-\u009f<>,;"()[\]\\]/;
268
+ var HEADER_NAME = /^X-[A-Za-z0-9-]+$/;
269
+ var CONTENT_TYPE = /^[A-Za-z0-9!#$&^_.+-]+\/[A-Za-z0-9!#$&^_.+-]+$/;
270
+ var MAX_ADDRESS = 254;
271
+ var MSG_ID = /^[\x21-\x7e]+$/;
272
+ var THREAD_ID = /^[A-Za-z0-9_-]+$/;
273
+ function fail(field) {
274
+ throw new (0, _chunkSHDP4A3Acjs.InvalidMessageError)(field);
275
+ }
276
+ function clean(value, field) {
277
+ if (typeof value !== "string" || LINE_BREAKS.test(value)) fail(field);
278
+ return value;
279
+ }
280
+ function matching(value, pattern, field) {
281
+ if (typeof value !== "string" || !pattern.test(value)) fail(field);
282
+ return value;
283
+ }
284
+ function parseAddress(raw, field) {
285
+ const v = clean(raw, field);
286
+ if (v.length > MAX_ADDRESS || ADDRESS_FORBIDDEN.test(v)) fail(field);
287
+ const parts = v.split("@");
288
+ if (parts.length !== 2) fail(field);
289
+ const [local, domain] = parts;
290
+ if (!local || !domain.includes(".")) fail(field);
291
+ if (domain.startsWith(".") || domain.endsWith(".") || domain.includes(".."))
292
+ fail(field);
293
+ return `${local}@${domain.toLowerCase()}`;
294
+ }
295
+ function parseMailAddress(a, path) {
296
+ if (typeof a === "string")
297
+ return { name: null, address: parseAddress(a, path) };
298
+ if (a === null || typeof a !== "object") fail(path);
299
+ const name = clean(a.name, `${path}.name`);
300
+ return {
301
+ name: name === "" ? null : name,
302
+ address: parseAddress(a.address, `${path}.address`)
303
+ };
304
+ }
305
+ function parseList(list, key) {
306
+ return (_nullishCoalesce(list, () => ( []))).map((a, i) => parseMailAddress(a, `${key}[${i}]`));
307
+ }
308
+ function normalizeExt(e) {
309
+ return e.trim().replace(/^\./, "").toLowerCase();
310
+ }
311
+ function cleanFilename(raw, path, blocked) {
312
+ clean(raw, path);
313
+ const base = _path.posix.basename(raw.replace(/\\/g, "/"));
314
+ let name = base.replace(/[\u0000-\u001f\u007f-\u009f]/g, "").trim();
315
+ if (name === "" || name === "." || name === "..") name = "attachment";
316
+ const effective = name.replace(/[.\s]+$/, "");
317
+ const dot = effective.lastIndexOf(".");
318
+ if (dot >= 0 && blocked.has(effective.slice(dot + 1).toLowerCase())) {
319
+ fail(path);
320
+ }
321
+ return name;
322
+ }
323
+ function validateSendInput(input, opts) {
324
+ const blocked = new Set(
325
+ opts.blockedExtensions.map(normalizeExt).filter((e) => e !== "")
326
+ );
327
+ const to = parseList(input.to, "to");
328
+ const cc = parseList(input.cc, "cc");
329
+ const bcc = parseList(input.bcc, "bcc");
330
+ if (to.length + cc.length + bcc.length === 0) fail("to");
331
+ const replyTo = input.replyTo === void 0 ? null : parseMailAddress(input.replyTo, "replyTo");
332
+ const subject = clean(input.subject, "subject");
333
+ if (!input.html && !input.text) fail("html");
334
+ const headers = {};
335
+ for (const [name, value] of Object.entries(_nullishCoalesce(input.headers, () => ( {})))) {
336
+ const field = `headers[${JSON.stringify(name).slice(0, 64)}]`;
337
+ if (!HEADER_NAME.test(name)) fail(field);
338
+ headers[name] = clean(value, field);
339
+ }
340
+ const attachments = (_nullishCoalesce(input.attachments, () => ( []))).map((a, i) => {
341
+ const p = `attachments[${i}]`;
342
+ const filename = cleanFilename(a.filename, `${p}.filename`, blocked);
343
+ let contentType = null;
344
+ if (a.contentType !== void 0) {
345
+ clean(a.contentType, `${p}.contentType`);
346
+ if (!CONTENT_TYPE.test(a.contentType)) fail(`${p}.contentType`);
347
+ contentType = a.contentType;
348
+ }
349
+ return { filename, content: a.content, contentType };
350
+ });
351
+ const t = _nullishCoalesce(input.thread, () => ( {}));
352
+ const thread = {
353
+ threadId: t.threadId === void 0 ? null : matching(t.threadId, THREAD_ID, "thread.threadId"),
354
+ inReplyTo: t.inReplyTo === void 0 ? null : matching(t.inReplyTo, MSG_ID, "thread.inReplyTo"),
355
+ references: (_nullishCoalesce(t.references, () => ( []))).map(
356
+ (r, i) => matching(r, MSG_ID, `thread.references[${i}]`)
357
+ )
358
+ };
359
+ return {
360
+ fromName: _chunkVN5VWVCTcjs.sanitizeDisplayName.call(void 0, _nullishCoalesce(input.fromName, () => ( null))),
361
+ to,
362
+ cc,
363
+ bcc,
364
+ replyTo,
365
+ subject,
366
+ html: input.html ? input.html : null,
367
+ text: input.text ? input.text : null,
368
+ attachments,
369
+ headers,
370
+ thread
371
+ };
372
+ }
373
+
374
+ // src/gmail/send.ts
375
+ function createGmail(google, opts = {}) {
376
+ const transport = _nullishCoalesce(opts.transport, () => ( createGmailApiTransport()));
377
+ const blocked = _nullishCoalesce(opts.blockedAttachmentExtensions, () => ( []));
378
+ return {
379
+ async send(input) {
380
+ const { store, tokens, emit, now, logger } = google[_chunkVN5VWVCTcjs.internals];
381
+ for (const field of ["tenantId", "connectionId", "actorId"]) {
382
+ if (typeof input[field] !== "string" || input[field] === "") {
383
+ throw new (0, _chunkSHDP4A3Acjs.InvalidMessageError)(field);
384
+ }
385
+ }
386
+ const { tenantId, connectionId, actorId } = input;
387
+ const msg = validateSendInput(input, { blockedExtensions: blocked });
388
+ const perCall = input.redactRecipients === void 0 ? void 0 : { redactRecipients: input.redactRecipients };
389
+ const addrs = {
390
+ to: msg.to.map((a) => a.address),
391
+ cc: msg.cc.map((a) => a.address),
392
+ bcc: msg.bcc.map((a) => a.address)
393
+ };
394
+ try {
395
+ const first = await tokens.getAccessToken(tenantId, connectionId);
396
+ const connection = first.connection;
397
+ _chunkVN5VWVCTcjs.assertServiceScopes.call(void 0, connection.scopes, ["gmail"], {
398
+ tenantId,
399
+ connectionId
400
+ });
401
+ const raw = await buildMime(msg, {
402
+ name: _nullishCoalesce(msg.fromName, () => ( connection.displayName)),
403
+ address: connection.email
404
+ });
405
+ const attempt = (accessToken) => withSendRetry(
406
+ () => transport.send({ accessToken, raw, threadId: msg.thread.threadId })
407
+ );
408
+ let sent;
409
+ try {
410
+ sent = await attempt(first.accessToken);
411
+ } catch (err) {
412
+ if (!(err instanceof SendUnauthorizedSignal)) throw err;
413
+ const fresh = await tokens.getAccessToken(tenantId, connectionId, {
414
+ forceRefresh: true
415
+ });
416
+ try {
417
+ sent = await attempt(fresh.accessToken);
418
+ } catch (err2) {
419
+ if (!(err2 instanceof SendUnauthorizedSignal)) throw err2;
420
+ await store.updateConnectionStatus(
421
+ tenantId,
422
+ connectionId,
423
+ "revoked",
424
+ "unauthorized"
425
+ );
426
+ tokens.evict(connectionId);
427
+ await emit({
428
+ type: "connection.revoked",
429
+ tenantId,
430
+ connectionId,
431
+ reason: "unauthorized",
432
+ at: now()
433
+ });
434
+ throw new (0, _chunkSHDP4A3Acjs.ConnectionRevokedError)("unauthorized", {
435
+ tenantId,
436
+ connectionId
437
+ });
438
+ }
439
+ }
440
+ try {
441
+ await store.touchConnection(tenantId, connectionId, now());
442
+ } catch (e2) {
443
+ try {
444
+ _optionalChain([logger, 'optionalAccess', _27 => _27.warn, 'call', _28 => _28("google touchConnection failed")]);
445
+ } catch (e3) {
446
+ }
447
+ }
448
+ await emit(
449
+ {
450
+ type: "message.sent",
451
+ tenantId,
452
+ actorId,
453
+ connectionId,
454
+ messageId: sent.messageId,
455
+ threadId: sent.threadId,
456
+ ...addrs,
457
+ subject: msg.subject,
458
+ attachmentCount: msg.attachments.length,
459
+ at: now()
460
+ },
461
+ perCall
462
+ );
463
+ return sent;
464
+ } catch (err) {
465
+ await emit(
466
+ {
467
+ type: "message.failed",
468
+ tenantId,
469
+ actorId,
470
+ connectionId,
471
+ errorCode: err instanceof _chunkSHDP4A3Acjs.GoogleLibError ? err.code : "unknown",
472
+ ...addrs,
473
+ subject: msg.subject,
474
+ at: now()
475
+ },
476
+ perCall
477
+ );
478
+ throw err;
479
+ }
480
+ }
481
+ };
482
+ }
483
+
484
+
485
+
486
+
487
+
488
+ exports.MAX_ATTACHMENT_BYTES = MAX_ATTACHMENT_BYTES; exports.UPLOAD_THRESHOLD_BYTES = UPLOAD_THRESHOLD_BYTES; exports.createGmail = createGmail; exports.createGmailApiTransport = createGmailApiTransport;
489
+ //# sourceMappingURL=gmail.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/google/google/dist/gmail.cjs","../src/gmail/mime.ts","../src/gmail/retry.ts","../src/gmail/transport.ts","../src/gmail/validate.ts","../src/gmail/send.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACnBA,gCAA2B;AAMpB,IAAM,qBAAA,EAAuB,QAAA;AAcpC,SAAS,MAAA,CAAU,GAAA,EAAiB;AAClC,EAAA,MAAM,EAAA,EAAI,GAAA;AACV,EAAA,wBAAQ,CAAA,CAAE,OAAA,UAAW,KAAA;AACvB;AAEA,SAAS,SAAA,CAAU,CAAA,EAAmC;AACpD,EAAA,OAAO,CAAA,CAAE,KAAA,IAAS,KAAA,EACd,EAAE,OAAA,EAAS,CAAA,CAAE,QAAQ,EAAA,EACrB,EAAE,IAAA,EAAM,CAAA,CAAE,IAAA,EAAM,OAAA,EAAS,CAAA,CAAE,QAAQ,CAAA;AACzC;AAGA,MAAA,SAAe,WAAA,CACb,MAAA,EACA,cAAA,EAC0C;AAC1C,EAAA,MAAM,OAAA,EAAmB,CAAC,CAAA;AAC1B,EAAA,IAAI,MAAA,EAAQ,cAAA;AACZ,EAAA,IAAI;AACF,IAAA,IAAA,MAAA,CAAA,MAAiB,MAAA,GAAS,MAAA,EAAQ;AAChC,MAAA,MAAM,IAAA,EACJ,OAAO,MAAA,IAAU,SAAA,EAAW,MAAA,CAAO,IAAA,CAAK,KAAK,EAAA,EAAK,KAAA;AACpD,MAAA,MAAA,GAAS,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AACF,QAAA;AACA,QAAA;AACF,MAAA;AACE,QAAA;AACE,UAAA;AAAA,YAAA;AACQ,YAAA;AACN,YAAA;AACA,YAAA;AACA,YAAA;AACsD,YAAA;AACnD,YAAA;AACU,YAAA;AAEf,UAAA;AACA,UAAA;AACF,QAAA;AACA,QAAA;AACF,MAAA;AACF,IAAA;AACF,EAAA;AACF;ALqVU;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/google/google/dist/gmail.cjs","sourcesContent":[null,"import { randomUUID } from \"node:crypto\";\nimport { MessageTooLargeError } from \"../core/errors.js\";\nimport { loadPeer } from \"../core/peer.js\";\nimport type { MailAddress, NormalizedMessage } from \"./validate.js\";\n\n/** Gmail's attachment limit: 25 MiB in total. */\nexport const MAX_ATTACHMENT_BYTES = 26_214_400;\n\ntype NodemailerAddress = { name?: string; address: string };\ntype MailComposerCtor = new (options: Record<string, unknown>) => {\n compile(): {\n keepBcc: boolean;\n build(): Promise<Buffer>;\n };\n};\ntype HtmlToText = {\n convert(html: string, options?: { wordwrap?: number | false }): string;\n};\n\n/** CommonJS peers surface as `{ default: module }` under ESM dynamic import. */\nfunction unwrap<T>(mod: unknown): T {\n const m = mod as { default?: unknown };\n return (m.default ?? mod) as T;\n}\n\nfunction toAddress(a: MailAddress): NodemailerAddress {\n return a.name === null\n ? { address: a.address }\n : { name: a.name, address: a.address };\n}\n\n/** Reads a stream into memory, destroying it as soon as the budget is blown. */\nasync function readLimited(\n stream: NodeJS.ReadableStream,\n alreadyCounted: number,\n): Promise<{ data: Buffer; total: number }> {\n const chunks: Buffer[] = [];\n let total = alreadyCounted;\n try {\n for await (const chunk of stream) {\n const buf =\n typeof chunk === \"string\" ? Buffer.from(chunk) : (chunk as Buffer);\n total += buf.length;\n if (total > MAX_ATTACHMENT_BYTES) {\n throw new MessageTooLargeError(total, MAX_ATTACHMENT_BYTES);\n }\n chunks.push(buf);\n }\n } catch (err) {\n (stream as { destroy?: () => void }).destroy?.();\n throw err;\n }\n return { data: Buffer.concat(chunks), total };\n}\n\n/**\n * Turns a validated message into the raw RFC 5322 bytes Gmail sends.\n * Throws MessageTooLargeError before building when attachments exceed 25 MiB.\n */\nexport async function buildMime(\n msg: NormalizedMessage,\n from: { name: string | null; address: string },\n): Promise<Buffer> {\n try {\n // Buffers first: cheap, and fails before any stream is touched.\n let total = 0;\n for (const a of msg.attachments) {\n if (Buffer.isBuffer(a.content)) total += a.content.length;\n }\n if (total > MAX_ATTACHMENT_BYTES) {\n throw new MessageTooLargeError(total, MAX_ATTACHMENT_BYTES);\n }\n\n // Peers load before any stream is read, so a missing peer fails fast.\n const htmlToText =\n msg.text === null && msg.html !== null\n ? unwrap<HtmlToText>(\n await loadPeer<unknown>(\"html-to-text\", \"html-to-text\"),\n )\n : null;\n const MailComposer = unwrap<MailComposerCtor>(\n await loadPeer<unknown>(\n \"nodemailer/lib/mail-composer/index.js\",\n \"nodemailer\",\n ),\n );\n\n const attachments: Record<string, unknown>[] = [];\n for (const a of msg.attachments) {\n let content: Buffer;\n if (Buffer.isBuffer(a.content)) {\n content = a.content;\n } else {\n const read = await readLimited(a.content, total);\n content = read.data;\n total = read.total;\n }\n attachments.push({\n filename: a.filename,\n content,\n ...(a.contentType === null ? {} : { contentType: a.contentType }),\n });\n }\n\n let text = msg.text;\n if (htmlToText !== null && msg.html !== null) {\n text = htmlToText.convert(msg.html, { wordwrap: 78 });\n }\n\n const domain = from.address.split(\"@\").pop() as string;\n const options: Record<string, unknown> = {\n from: toAddress(from),\n to: msg.to.map(toAddress),\n cc: msg.cc.map(toAddress),\n bcc: msg.bcc.map(toAddress),\n subject: msg.subject,\n messageId: `<${randomUUID()}@${domain}>`,\n headers: msg.headers,\n attachments,\n };\n if (msg.replyTo) options.replyTo = toAddress(msg.replyTo);\n if (msg.html !== null) options.html = msg.html;\n if (text !== null) options.text = text;\n if (msg.thread.inReplyTo !== null) options.inReplyTo = msg.thread.inReplyTo;\n if (msg.thread.references.length > 0)\n options.references = msg.thread.references;\n\n const mail = new MailComposer(options).compile();\n // Gmail's API routes on the raw Bcc header and strips it before delivery.\n mail.keepBcc = true;\n return mail.build();\n } finally {\n // Release any stream attachment we did not (fully) consume.\n for (const a of msg.attachments) {\n if (!Buffer.isBuffer(a.content)) {\n (a.content as { destroy?: () => void }).destroy?.();\n }\n }\n }\n}\n","import {\n DailyQuotaExceededError,\n GoogleApiError,\n GoogleLibError,\n InvalidMessageError,\n RateLimitedError,\n SendOutcomeUnknownError,\n} from \"../core/errors.js\";\n\nexport type SendErrorClass =\n | { kind: \"retry\"; delayMs: number | null }\n | { kind: \"unauthorized\" }\n | { kind: \"fail\"; error: GoogleLibError };\n\n/** Thrown by `withSendRetry` when Google answered 401; `send` refreshes and retries once. */\nexport class SendUnauthorizedSignal extends Error {\n constructor() {\n super(\"Google rejected the access token (401)\");\n this.name = \"SendUnauthorizedSignal\";\n }\n}\n\ntype ErrLike = {\n name?: unknown;\n message?: unknown;\n code?: unknown;\n status?: unknown;\n errors?: { reason?: unknown }[];\n cause?: { code?: unknown } | null;\n response?: {\n status?: unknown;\n headers?: Record<string, unknown>;\n data?: { error?: { message?: unknown; errors?: { reason?: unknown }[] } };\n };\n};\n\nconst PRE_SEND_CODES = new Set([\"ENOTFOUND\", \"EAI_AGAIN\", \"ECONNREFUSED\"]);\nconst OUTCOME_UNKNOWN_CODES = new Set([\n \"ECONNRESET\",\n \"ETIMEDOUT\",\n \"ESOCKETTIMEDOUT\",\n]);\nconst RATE_REASONS = new Set([\"rateLimitExceeded\", \"userRateLimitExceeded\"]);\n\nconst asErr = (err: unknown): ErrLike =>\n typeof err === \"object\" && err !== null ? (err as ErrLike) : {};\n\nfunction readStatus(e: ErrLike): number | null {\n const s = e.response?.status ?? e.status ?? e.code;\n return typeof s === \"number\" ? s : null;\n}\n\nfunction readReason(e: ErrLike): string | null {\n const r =\n e.response?.data?.error?.errors?.[0]?.reason ?? e.errors?.[0]?.reason;\n return typeof r === \"string\" ? r : null;\n}\n\nfunction readNetCode(e: ErrLike): string | null {\n const c = e.code ?? e.cause?.code;\n return typeof c === \"string\" ? c : null;\n}\n\nfunction readMessages(e: ErrLike): string {\n const a = typeof e.message === \"string\" ? e.message : \"\";\n const b = e.response?.data?.error?.message;\n return `${a} ${typeof b === \"string\" ? b : \"\"}`;\n}\n\nfunction readRetryAfterMs(e: ErrLike): number | null {\n const raw = e.response?.headers?.[\"retry-after\"];\n const v = Array.isArray(raw) ? raw[0] : raw;\n if (typeof v !== \"string\" && typeof v !== \"number\") return null;\n const s = String(v).trim();\n if (s === \"\") return null;\n if (/^\\d+(\\.\\d+)?$/.test(s)) return Math.round(Number(s) * 1000);\n const at = Date.parse(s);\n return Number.isNaN(at) ? null : Math.max(0, at - Date.now());\n}\n\nexport function classifySendError(err: unknown): SendErrorClass {\n if (err instanceof GoogleLibError) return { kind: \"fail\", error: err };\n const e = asErr(err);\n const status = readStatus(e);\n const reason = readReason(e);\n const code = readNetCode(e);\n const opts = { cause: err };\n\n if (\n reason === \"dailyLimitExceeded\" ||\n /sending limit/i.test(readMessages(e))\n ) {\n return {\n kind: \"fail\",\n error: new DailyQuotaExceededError(undefined, opts),\n };\n }\n if (\n status === 429 ||\n (status === 403 && reason !== null && RATE_REASONS.has(reason))\n ) {\n return { kind: \"retry\", delayMs: readRetryAfterMs(e) };\n }\n if (status === 401) return { kind: \"unauthorized\" };\n if (status === 400) {\n return {\n kind: \"fail\",\n error: new InvalidMessageError(\"message\", undefined, opts),\n };\n }\n if (status !== null && status >= 500) {\n return {\n kind: \"fail\",\n error: new SendOutcomeUnknownError(undefined, opts),\n };\n }\n if (\n code !== null &&\n (PRE_SEND_CODES.has(code) ||\n code.startsWith(\"ERR_TLS_\") ||\n code.startsWith(\"CERT_\"))\n ) {\n return { kind: \"retry\", delayMs: null };\n }\n if (\n (code !== null && OUTCOME_UNKNOWN_CODES.has(code)) ||\n code === \"ABORT_ERR\" ||\n e.name === \"AbortError\" ||\n /socket hang up/i.test(readMessages(e))\n ) {\n return {\n kind: \"fail\",\n error: new SendOutcomeUnknownError(undefined, opts),\n };\n }\n if (status !== null) {\n return { kind: \"fail\", error: new GoogleApiError(status, reason, opts) };\n }\n // No HTTP status and not provably pre-send: the request may have been written (I7).\n return {\n kind: \"fail\",\n error: new SendOutcomeUnknownError(undefined, opts),\n };\n}\n\nexport type RetryOptions = {\n maxAttempts?: number;\n baseMs?: number;\n capMs?: number;\n sleep?: (ms: number) => Promise<void>;\n random?: () => number;\n};\n\nconst defaultSleep = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Runs `fn`, retrying only errors that provably never reached Google's send\n * (pre-write network failures, rate limits). Anything ambiguous is not retried (I7).\n * 401 surfaces as `SendUnauthorizedSignal`.\n */\nexport async function withSendRetry<T>(\n fn: () => Promise<T>,\n opts: RetryOptions = {},\n): Promise<T> {\n const maxAttempts = opts.maxAttempts ?? 3;\n const baseMs = opts.baseMs ?? 250;\n const capMs = opts.capMs ?? 8000;\n const sleep = opts.sleep ?? defaultSleep;\n const random = opts.random ?? Math.random;\n\n for (let attempt = 0; ; attempt++) {\n try {\n return await fn();\n } catch (err) {\n const c = classifySendError(err);\n if (c.kind === \"fail\") throw c.error;\n if (c.kind === \"unauthorized\") throw new SendUnauthorizedSignal();\n if (c.delayMs !== null && c.delayMs > capMs) {\n throw new RateLimitedError(c.delayMs, { cause: err });\n }\n if (attempt + 1 >= maxAttempts) {\n const e = asErr(err);\n if (readStatus(e) !== null) {\n throw new RateLimitedError(c.delayMs, { cause: err });\n }\n throw new GoogleApiError(0, readNetCode(e), { cause: err });\n }\n await sleep(\n c.delayMs ?? random() * Math.min(capMs, baseMs * 2 ** attempt),\n );\n }\n }\n}\n","import { Readable } from \"node:stream\";\nimport { OAuth2Client } from \"google-auth-library\";\nimport { SendOutcomeUnknownError } from \"../core/errors.js\";\nimport { loadPeer } from \"../core/peer.js\";\n\n/** Raw messages above this size go through the media upload endpoint. */\nexport const UPLOAD_THRESHOLD_BYTES = 5_242_880;\n\nexport interface GmailTransport {\n send(p: {\n accessToken: string;\n raw: Buffer;\n threadId: string | null;\n }): Promise<{ messageId: string; threadId: string }>;\n}\n\ntype GmailModule = {\n gmail(opts: { version: \"v1\"; auth: unknown }): {\n users: {\n messages: {\n send(params: Record<string, unknown>): Promise<{\n data: { id?: string | null; threadId?: string | null };\n }>;\n };\n };\n };\n};\n\n/**\n * Sends through the Gmail API. Errors are thrown as-is (gaxios errors carry the\n * request config, including the bearer token); `send` classifies them and only\n * ever rethrows sanitized GoogleLibError instances.\n */\nexport function createGmailApiTransport(): GmailTransport {\n return {\n async send({ accessToken, raw, threadId }) {\n const mod = await loadPeer<\n Partial<GmailModule> & { default?: GmailModule }\n >(\"@googleapis/gmail\");\n const { gmail } = (mod.gmail ? mod : mod.default) as GmailModule;\n const auth = new OAuth2Client();\n auth.setCredentials({ access_token: accessToken });\n const api = gmail({ version: \"v1\", auth });\n const thread = threadId === null ? {} : { threadId };\n const { data } =\n raw.length <= UPLOAD_THRESHOLD_BYTES\n ? await api.users.messages.send({\n userId: \"me\",\n requestBody: { raw: raw.toString(\"base64url\"), ...thread },\n })\n : await api.users.messages.send({\n userId: \"me\",\n requestBody: { ...thread },\n media: { mimeType: \"message/rfc822\", body: Readable.from(raw) },\n });\n // Google answered 200: the message was sent, so never report a plain failure (I7).\n if (!data?.id) throw new SendOutcomeUnknownError();\n return {\n messageId: data.id,\n threadId: data.threadId || threadId || data.id,\n };\n },\n };\n}\n","import { posix } from \"node:path\";\nimport { sanitizeDisplayName } from \"../core/connections.js\";\nimport { InvalidMessageError } from \"../core/errors.js\";\n\nexport type Address = string | { name: string; address: string };\nexport type Attachment = {\n filename: string;\n content: Buffer | NodeJS.ReadableStream;\n contentType?: string;\n};\nexport type SendInput = {\n tenantId: string;\n connectionId: string;\n actorId: string;\n fromName?: string;\n to?: Address[];\n cc?: Address[];\n bcc?: Address[];\n replyTo?: Address;\n subject: string;\n html?: string;\n text?: string;\n attachments?: Attachment[];\n headers?: Record<string, string>;\n thread?: { threadId?: string; inReplyTo?: string; references?: string[] };\n redactRecipients?: boolean;\n};\nexport type MailAddress = { name: string | null; address: string };\nexport type NormalizedMessage = {\n fromName: string | null;\n to: MailAddress[];\n cc: MailAddress[];\n bcc: MailAddress[];\n replyTo: MailAddress | null;\n subject: string;\n html: string | null;\n text: string | null;\n attachments: {\n filename: string;\n content: Buffer | NodeJS.ReadableStream;\n contentType: string | null;\n }[];\n headers: Record<string, string>;\n thread: {\n threadId: string | null;\n inReplyTo: string | null;\n references: string[];\n };\n};\n\nconst LINE_BREAKS = /[\\r\\n\\0]/;\nconst ADDRESS_FORBIDDEN = /[\\s\\u0000-\\u001f\\u007f-\\u009f<>,;\"()[\\]\\\\]/;\nconst HEADER_NAME = /^X-[A-Za-z0-9-]+$/;\nconst CONTENT_TYPE = /^[A-Za-z0-9!#$&^_.+-]+\\/[A-Za-z0-9!#$&^_.+-]+$/;\nconst MAX_ADDRESS = 254;\nconst MSG_ID = /^[\\x21-\\x7e]+$/;\nconst THREAD_ID = /^[A-Za-z0-9_-]+$/;\n\nfunction fail(field: string): never {\n throw new InvalidMessageError(field);\n}\n\n/** Rejects CR, LF and NUL; returns the value unchanged. */\nfunction clean(value: unknown, field: string): string {\n if (typeof value !== \"string\" || LINE_BREAKS.test(value)) fail(field);\n return value;\n}\n\n/** Requires a string that fully matches `pattern`; returns it unchanged. */\nfunction matching(value: unknown, pattern: RegExp, field: string): string {\n if (typeof value !== \"string\" || !pattern.test(value)) fail(field);\n return value;\n}\n\nfunction parseAddress(raw: unknown, field: string): string {\n const v = clean(raw, field);\n if (v.length > MAX_ADDRESS || ADDRESS_FORBIDDEN.test(v)) fail(field);\n const parts = v.split(\"@\");\n if (parts.length !== 2) fail(field);\n const [local, domain] = parts as [string, string];\n if (!local || !domain.includes(\".\")) fail(field);\n if (domain.startsWith(\".\") || domain.endsWith(\".\") || domain.includes(\"..\"))\n fail(field);\n return `${local}@${domain.toLowerCase()}`;\n}\n\nfunction parseMailAddress(a: Address, path: string): MailAddress {\n if (typeof a === \"string\")\n return { name: null, address: parseAddress(a, path) };\n if (a === null || typeof a !== \"object\") fail(path);\n const name = clean(a.name, `${path}.name`);\n return {\n name: name === \"\" ? null : name,\n address: parseAddress(a.address, `${path}.address`),\n };\n}\n\nfunction parseList(list: Address[] | undefined, key: string): MailAddress[] {\n return (list ?? []).map((a, i) => parseMailAddress(a, `${key}[${i}]`));\n}\n\nfunction normalizeExt(e: string): string {\n return e.trim().replace(/^\\./, \"\").toLowerCase();\n}\n\nfunction cleanFilename(\n raw: string,\n path: string,\n blocked: Set<string>,\n): string {\n clean(raw, path);\n const base = posix.basename(raw.replace(/\\\\/g, \"/\"));\n // eslint-disable-next-line no-control-regex\n let name = base.replace(/[\\u0000-\\u001f\\u007f-\\u009f]/g, \"\").trim();\n if (name === \"\" || name === \".\" || name === \"..\") name = \"attachment\";\n // Windows drops trailing dots and spaces, so \"cv.exe.\" runs as \"cv.exe\".\n const effective = name.replace(/[.\\s]+$/, \"\");\n const dot = effective.lastIndexOf(\".\");\n if (dot >= 0 && blocked.has(effective.slice(dot + 1).toLowerCase())) {\n fail(path);\n }\n return name;\n}\n\nexport function validateSendInput(\n input: SendInput,\n opts: { blockedExtensions: string[] },\n): NormalizedMessage {\n const blocked = new Set(\n opts.blockedExtensions.map(normalizeExt).filter((e) => e !== \"\"),\n );\n\n const to = parseList(input.to, \"to\");\n const cc = parseList(input.cc, \"cc\");\n const bcc = parseList(input.bcc, \"bcc\");\n if (to.length + cc.length + bcc.length === 0) fail(\"to\");\n const replyTo =\n input.replyTo === undefined\n ? null\n : parseMailAddress(input.replyTo, \"replyTo\");\n\n const subject = clean(input.subject, \"subject\");\n if (!input.html && !input.text) fail(\"html\");\n\n const headers: Record<string, string> = {};\n for (const [name, value] of Object.entries(input.headers ?? {})) {\n // Caller-supplied name: JSON-escape (no raw CR/LF) and cap before it reaches the error.\n const field = `headers[${JSON.stringify(name).slice(0, 64)}]`;\n if (!HEADER_NAME.test(name)) fail(field);\n headers[name] = clean(value, field);\n }\n\n const attachments = (input.attachments ?? []).map((a, i) => {\n const p = `attachments[${i}]`;\n const filename = cleanFilename(a.filename, `${p}.filename`, blocked);\n let contentType: string | null = null;\n if (a.contentType !== undefined) {\n clean(a.contentType, `${p}.contentType`);\n if (!CONTENT_TYPE.test(a.contentType)) fail(`${p}.contentType`);\n contentType = a.contentType;\n }\n return { filename, content: a.content, contentType };\n });\n\n const t = input.thread ?? {};\n const thread = {\n threadId:\n t.threadId === undefined\n ? null\n : matching(t.threadId, THREAD_ID, \"thread.threadId\"),\n inReplyTo:\n t.inReplyTo === undefined\n ? null\n : matching(t.inReplyTo, MSG_ID, \"thread.inReplyTo\"),\n references: (t.references ?? []).map((r, i) =>\n matching(r, MSG_ID, `thread.references[${i}]`),\n ),\n };\n\n return {\n fromName: sanitizeDisplayName(input.fromName ?? null),\n to,\n cc,\n bcc,\n replyTo,\n subject,\n html: input.html ? input.html : null,\n text: input.text ? input.text : null,\n attachments,\n headers,\n thread,\n };\n}\n","import type { GoogleCore } from \"../core/create-google.js\";\nimport { internals } from \"../core/create-google.js\";\nimport {\n ConnectionRevokedError,\n GoogleLibError,\n InvalidMessageError,\n} from \"../core/errors.js\";\nimport { assertServiceScopes } from \"../core/scopes.js\";\nimport { buildMime } from \"./mime.js\";\nimport { SendUnauthorizedSignal, withSendRetry } from \"./retry.js\";\nimport { createGmailApiTransport } from \"./transport.js\";\nimport type { GmailTransport } from \"./transport.js\";\nimport { validateSendInput } from \"./validate.js\";\nimport type { SendInput } from \"./validate.js\";\n\nexport type GmailOptions = {\n blockedAttachmentExtensions?: string[];\n transport?: GmailTransport;\n};\n\nexport type SendResult = { messageId: string; threadId: string };\n\nexport function createGmail(\n google: GoogleCore,\n opts: GmailOptions = {},\n): { send(input: SendInput): Promise<SendResult> } {\n const transport = opts.transport ?? createGmailApiTransport();\n const blocked = opts.blockedAttachmentExtensions ?? [];\n\n return {\n async send(input) {\n const { store, tokens, emit, now, logger } = google[internals];\n for (const field of [\"tenantId\", \"connectionId\", \"actorId\"] as const) {\n if (typeof input[field] !== \"string\" || input[field] === \"\") {\n throw new InvalidMessageError(field);\n }\n }\n const { tenantId, connectionId, actorId } = input;\n const msg = validateSendInput(input, { blockedExtensions: blocked });\n const perCall =\n input.redactRecipients === undefined\n ? undefined\n : { redactRecipients: input.redactRecipients };\n const addrs = {\n to: msg.to.map((a) => a.address),\n cc: msg.cc.map((a) => a.address),\n bcc: msg.bcc.map((a) => a.address),\n };\n\n try {\n const first = await tokens.getAccessToken(tenantId, connectionId);\n const connection = first.connection;\n assertServiceScopes(connection.scopes, [\"gmail\"], {\n tenantId,\n connectionId,\n });\n const raw = await buildMime(msg, {\n name: msg.fromName ?? connection.displayName,\n address: connection.email,\n });\n const attempt = (accessToken: string) =>\n withSendRetry(() =>\n transport.send({ accessToken, raw, threadId: msg.thread.threadId }),\n );\n\n let sent: SendResult;\n try {\n sent = await attempt(first.accessToken);\n } catch (err) {\n if (!(err instanceof SendUnauthorizedSignal)) throw err;\n const fresh = await tokens.getAccessToken(tenantId, connectionId, {\n forceRefresh: true,\n });\n try {\n sent = await attempt(fresh.accessToken);\n } catch (err2) {\n if (!(err2 instanceof SendUnauthorizedSignal)) throw err2;\n await store.updateConnectionStatus(\n tenantId,\n connectionId,\n \"revoked\",\n \"unauthorized\",\n );\n tokens.evict(connectionId);\n await emit({\n type: \"connection.revoked\",\n tenantId,\n connectionId,\n reason: \"unauthorized\",\n at: now(),\n });\n throw new ConnectionRevokedError(\"unauthorized\", {\n tenantId,\n connectionId,\n });\n }\n }\n\n try {\n await store.touchConnection(tenantId, connectionId, now());\n } catch {\n try {\n logger?.warn(\"google touchConnection failed\");\n } catch {\n // logging must never break the caller\n }\n }\n await emit(\n {\n type: \"message.sent\",\n tenantId,\n actorId,\n connectionId,\n messageId: sent.messageId,\n threadId: sent.threadId,\n ...addrs,\n subject: msg.subject,\n attachmentCount: msg.attachments.length,\n at: now(),\n },\n perCall,\n );\n return sent;\n } catch (err) {\n await emit(\n {\n type: \"message.failed\",\n tenantId,\n actorId,\n connectionId,\n errorCode: err instanceof GoogleLibError ? err.code : \"unknown\",\n ...addrs,\n subject: msg.subject,\n at: now(),\n },\n perCall,\n );\n throw err;\n }\n },\n };\n}\n"]}
@@ -0,0 +1,53 @@
1
+ import { G as GoogleCore } from './create-google-CPGcK-3G.cjs';
2
+ import { G as GmailTransport } from './transport-CVOgr9XP.cjs';
3
+ export { U as UPLOAD_THRESHOLD_BYTES, c as createGmailApiTransport } from './transport-CVOgr9XP.cjs';
4
+ import './key-provider-Cq_14Bh6.cjs';
5
+ import './events-BsWOMtza.cjs';
6
+
7
+ type Address = string | {
8
+ name: string;
9
+ address: string;
10
+ };
11
+ type Attachment = {
12
+ filename: string;
13
+ content: Buffer | NodeJS.ReadableStream;
14
+ contentType?: string;
15
+ };
16
+ type SendInput = {
17
+ tenantId: string;
18
+ connectionId: string;
19
+ actorId: string;
20
+ fromName?: string;
21
+ to?: Address[];
22
+ cc?: Address[];
23
+ bcc?: Address[];
24
+ replyTo?: Address;
25
+ subject: string;
26
+ html?: string;
27
+ text?: string;
28
+ attachments?: Attachment[];
29
+ headers?: Record<string, string>;
30
+ thread?: {
31
+ threadId?: string;
32
+ inReplyTo?: string;
33
+ references?: string[];
34
+ };
35
+ redactRecipients?: boolean;
36
+ };
37
+
38
+ type GmailOptions = {
39
+ blockedAttachmentExtensions?: string[];
40
+ transport?: GmailTransport;
41
+ };
42
+ type SendResult = {
43
+ messageId: string;
44
+ threadId: string;
45
+ };
46
+ declare function createGmail(google: GoogleCore, opts?: GmailOptions): {
47
+ send(input: SendInput): Promise<SendResult>;
48
+ };
49
+
50
+ /** Gmail's attachment limit: 25 MiB in total. */
51
+ declare const MAX_ATTACHMENT_BYTES = 26214400;
52
+
53
+ export { type Address, type Attachment, type GmailOptions, GmailTransport, MAX_ATTACHMENT_BYTES, type SendInput, type SendResult, createGmail };
@@ -0,0 +1,53 @@
1
+ import { G as GoogleCore } from './create-google-nP9f9jd9.js';
2
+ import { G as GmailTransport } from './transport-CVOgr9XP.js';
3
+ export { U as UPLOAD_THRESHOLD_BYTES, c as createGmailApiTransport } from './transport-CVOgr9XP.js';
4
+ import './key-provider-Cq_14Bh6.js';
5
+ import './events-BsWOMtza.js';
6
+
7
+ type Address = string | {
8
+ name: string;
9
+ address: string;
10
+ };
11
+ type Attachment = {
12
+ filename: string;
13
+ content: Buffer | NodeJS.ReadableStream;
14
+ contentType?: string;
15
+ };
16
+ type SendInput = {
17
+ tenantId: string;
18
+ connectionId: string;
19
+ actorId: string;
20
+ fromName?: string;
21
+ to?: Address[];
22
+ cc?: Address[];
23
+ bcc?: Address[];
24
+ replyTo?: Address;
25
+ subject: string;
26
+ html?: string;
27
+ text?: string;
28
+ attachments?: Attachment[];
29
+ headers?: Record<string, string>;
30
+ thread?: {
31
+ threadId?: string;
32
+ inReplyTo?: string;
33
+ references?: string[];
34
+ };
35
+ redactRecipients?: boolean;
36
+ };
37
+
38
+ type GmailOptions = {
39
+ blockedAttachmentExtensions?: string[];
40
+ transport?: GmailTransport;
41
+ };
42
+ type SendResult = {
43
+ messageId: string;
44
+ threadId: string;
45
+ };
46
+ declare function createGmail(google: GoogleCore, opts?: GmailOptions): {
47
+ send(input: SendInput): Promise<SendResult>;
48
+ };
49
+
50
+ /** Gmail's attachment limit: 25 MiB in total. */
51
+ declare const MAX_ATTACHMENT_BYTES = 26214400;
52
+
53
+ export { type Address, type Attachment, type GmailOptions, GmailTransport, MAX_ATTACHMENT_BYTES, type SendInput, type SendResult, createGmail };