@opencoredev/email-sdk3.1.069.4 kB
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __hasOwnProp = Object.prototype.hasOwnProperty;
function __accessProp(key) {
return this[key];
}
var __toCommonJS = (from) => {
var entry = (__moduleCache ??= new WeakMap).get(from), desc;
if (entry)
return entry;
entry = __defProp({}, "__esModule", { value: true });
if (from && typeof from === "object" || typeof from === "function") {
for (var key of __getOwnPropNames(from))
if (!__hasOwnProp.call(entry, key))
__defProp(entry, key, {
get: __accessProp.bind(from, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
__moduleCache.set(from, entry);
return entry;
};
var __moduleCache;
var __returnValue = (v) => v;
function __exportSetter(name, newValue) {
this[name] = __returnValue.bind(null, newValue);
}
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, {
get: all[name],
enumerable: true,
configurable: true,
set: __exportSetter.bind(all, name)
});
};
// ../../../../../../../tmp/email-sdk-cjs-jSjbIi/index.ts
var exports_email_sdk_cjs_jSjbIi = {};
__export(exports_email_sdk_cjs_jSjbIi, {
isRetryableEmailError: () => import_errors10.isRetryableEmailError,
getTelemetryStatus: () => getTelemetryStatus,
disableTelemetry: () => disableTelemetry,
createEmailClient: () => createEmailClient,
SUPPORTED_MESSAGE_FIELDS: () => SUPPORTED_MESSAGE_FIELDS,
EmailValidationError: () => import_errors10.EmailValidationError,
EmailSdkError: () => import_errors10.EmailSdkError,
EmailRouteError: () => import_errors10.EmailRouteError,
EmailMiddlewareError: () => import_errors10.EmailMiddlewareError,
EmailAllRecipientsFailedError: () => import_errors10.EmailAllRecipientsFailedError,
EmailAdapterNotFoundError: () => import_errors10.EmailAdapterNotFoundError,
EmailAdapterError: () => import_errors10.EmailAdapterError,
EmailAbortError: () => import_errors10.EmailAbortError
});
module.exports = __toCommonJS(exports_email_sdk_cjs_jSjbIi);
// src/core/attempts.ts
var import_errors7 = require("./errors.cjs");
// src/utils.ts
var import_errors = require("./errors.cjs");
// src/internal/decode.ts
var FUNCTION_TAGS = new Set([
"[object Function]",
"[object AsyncFunction]",
"[object GeneratorFunction]",
"[object AsyncGeneratorFunction]"
]);
function tagOf(value) {
return Object.prototype.toString.call(value);
}
function isPrimitive(value) {
return Object(value) !== value;
}
function isStringMember(value) {
return isPrimitive(value) && tagOf(value) === "[object String]";
}
function isString(value) {
return isPrimitive(value) && tagOf(value) === "[object String]";
}
function isNumber(value) {
return isPrimitive(value) && tagOf(value) === "[object Number]";
}
function isFunctionMember(value) {
return FUNCTION_TAGS.has(tagOf(value));
}
function isObjectLike(value) {
return value !== null && value !== undefined && Object(value) === value;
}
function isJsonObject(value) {
return value !== undefined && value !== null && !Array.isArray(value) && Object(value) === value;
}
function jsonField(value, key) {
return isJsonObject(value) ? value[key] : undefined;
}
function jsonString(value, key) {
const field = jsonField(value, key);
return isJsonString(field) ? field : undefined;
}
function isJsonString(value) {
return isPrimitive(value) && tagOf(value) === "[object String]";
}
function parseJsonStrict(text) {
return JSON.parse(text);
}
function causeString(cause, key) {
if (!isObjectLike(cause)) {
return;
}
const fields = cause;
const field = fields[key];
return isString(field) ? field : undefined;
}
function causeNumber(cause, key) {
if (!isObjectLike(cause)) {
return;
}
const fields = cause;
const field = fields[key];
return isNumber(field) ? field : undefined;
}
// src/internal/address.ts
function scanMailbox(mailbox) {
let outside = "";
let angle;
let inAngle = false;
let quoted = false;
let inComment = false;
let inLiteral = false;
for (let index = 0;index < mailbox.length; index += 1) {
const character = mailbox.charAt(index);
if (inComment) {
if (character === "\\" || character === "(")
return;
if (character === ")")
inComment = false;
continue;
}
let kept = character;
if (quoted) {
if (character === "\\") {
index += 1;
kept += mailbox.charAt(index);
} else if (character === '"') {
quoted = false;
}
} else if (inLiteral) {
if (character === "]")
inLiteral = false;
} else if (character === "[") {
inLiteral = true;
} else if (character === "(") {
inComment = true;
kept = " ";
} else if (character === "," || character === ";" || character === ":") {
return;
} else if (character === '"') {
quoted = true;
} else if (character === "<" && angle === undefined) {
inAngle = true;
angle = "";
continue;
} else if (character === ">" && inAngle) {
inAngle = false;
continue;
}
if (inAngle)
angle += kept;
else
outside += kept;
}
if (quoted || inAngle || inComment || inLiteral)
return;
return { outside, angle };
}
var SCAN_STATE_CHARACTER = /[<(",;:[]/;
function mailboxAddress(address) {
if (!isStringMember(address))
return address.email;
if (!SCAN_STATE_CHARACTER.test(address))
return address.trim();
const scanned = scanMailbox(address);
if (!scanned)
return address.trim();
return (scanned.angle ?? scanned.outside).trim();
}
// src/utils.ts
function normalizeAdapterResult(adapter, result) {
return {
adapter: result.adapter || result.provider || adapter,
id: result.id ?? result.messageId,
accepted: result.accepted,
rejected: result.rejected,
raw: result.raw
};
}
function arrayify(value) {
if (value === undefined) {
return [];
}
return isList(value) ? [...value] : [value];
}
function isList(value) {
return Array.isArray(value);
}
function emailAddressOf(address) {
return mailboxAddress(address);
}
function isHeaderList(headers) {
return Array.isArray(headers);
}
function headersToArray(headers) {
if (!headers) {
return;
}
if (!isHeaderList(headers)) {
return Object.entries(headers).map(([name, value]) => ({
name,
value
}));
}
return [...headers];
}
function assertMessage(message) {
if (!message.from) {
throw new import_errors.EmailValidationError("Email message requires a from address.");
}
if (arrayify(message.to).length === 0) {
throw new import_errors.EmailValidationError("Email message requires at least one recipient.");
}
if (!message.subject) {
throw new import_errors.EmailValidationError("Email message requires a subject.");
}
if (!message.html && !message.text) {
throw new import_errors.EmailValidationError("Email message requires either html or text content.");
}
for (const attachment of message.attachments ?? []) {
const hasContent = attachment.content !== undefined;
const hasPath = isStringMember(attachment.path) && attachment.path.length > 0;
if (hasContent === hasPath) {
throw new import_errors.EmailValidationError(`Attachment "${attachment.filename}" requires exactly one of content or path.`);
}
}
if (message.sendAt !== undefined) {
toSendAtDate(message.sendAt);
}
}
var RFC_3339_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
function toSendAtDate(sendAt) {
if (isStringMember(sendAt) && !RFC_3339_TIMESTAMP.test(sendAt)) {
throw new import_errors.EmailValidationError(`Email message sendAt must be an RFC 3339 timestamp with Z or an explicit offset: "${sendAt}".`, { sendAt });
}
const date = sendAt instanceof Date ? sendAt : new Date(sendAt);
if (Number.isNaN(date.getTime())) {
throw new import_errors.EmailValidationError(`Email message sendAt is not a valid date: "${String(sendAt)}".`, { sendAt });
}
return date;
}
function toProviderError(provider, cause) {
if (cause instanceof import_errors.EmailAbortError || cause instanceof import_errors.EmailValidationError) {
return cause;
}
if (cause instanceof import_errors.EmailAdapterError) {
return cause;
}
if (cause instanceof import_errors.EmailSdkError) {
return new import_errors.EmailAdapterError(cause.message, {
adapter: provider,
retryable: cause.retryable,
delivery: "unknown",
cause
});
}
if (cause instanceof Error) {
return new import_errors.EmailAdapterError(cause.message, {
adapter: provider,
retryable: isRetryableRuntimeError(cause),
delivery: "unknown",
cause
});
}
return new import_errors.EmailAdapterError(`${provider} failed with an unknown error.`, {
adapter: provider,
retryable: false,
delivery: "unknown",
cause
});
}
function isRetryableRuntimeError(error) {
if (error.name === "AbortError") {
return false;
}
const code = causeString(error, "code");
if (code !== undefined && /^(ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|EPIPE)$/i.test(code)) {
return true;
}
return /fetch failed|failed to fetch|network|socket|timeout|timed out|connection reset/i.test(error.message);
}
var SUPPORTED_MESSAGE_FIELDS = {
resend: {
cc: true,
bcc: true,
replyTo: true,
headers: true,
attachments: true,
tags: true,
sendAt: true
},
postmark: {
cc: true,
bcc: true,
replyTo: true,
headers: true,
attachments: true,
tags: true,
metadata: true
},
sendgrid: {
cc: true,
bcc: true,
replyTo: true,
headers: true,
attachments: true,
tags: true,
metadata: true,
sendAt: true
},
cloudflare: { cc: true, bcc: true, replyTo: true, headers: true, attachments: true },
unosend: { cc: true, bcc: true, replyTo: true, headers: true, attachments: true, tags: true },
ses: { cc: true, bcc: true, replyTo: true, headers: true, attachments: true, tags: true },
mailgun: {
cc: true,
bcc: true,
replyTo: true,
headers: true,
attachments: true,
tags: true,
metadata: true,
sendAt: true
},
mailersend: {
cc: true,
bcc: true,
replyTo: true,
headers: true,
attachments: true,
tags: true,
sendAt: true
},
brevo: {
cc: true,
bcc: true,
replyTo: true,
headers: true,
attachments: true,
tags: true,
metadata: true,
sendAt: true
},
mailchimp: {
cc: true,
bcc: true,
headers: true,
attachments: true,
tags: true,
metadata: true,
sendAt: true
},
sparkpost: {
replyTo: true,
headers: true,
attachments: true,
tags: true,
metadata: true,
sendAt: true
},
iterable: { metadata: true },
loops: { attachments: true, metadata: true },
sequenzy: { replyTo: true, attachments: true, metadata: true },
jetemail: { cc: true, bcc: true, replyTo: true, headers: true, attachments: true },
lettermint: {
cc: true,
bcc: true,
replyTo: true,
headers: true,
attachments: true,
tags: true,
metadata: true
},
lettr: {
cc: true,
bcc: true,
replyTo: true,
headers: true,
attachments: true,
tags: true,
metadata: true,
sendAt: true
},
primitive: { attachments: true },
plunk: { replyTo: true, headers: true, attachments: true, metadata: true },
mailtrap: {
cc: true,
bcc: true,
replyTo: true,
headers: true,
attachments: true,
tags: true,
metadata: true
},
scaleway: { cc: true, bcc: true, replyTo: true, headers: true, attachments: true },
zeptomail: { cc: true, bcc: true, replyTo: true, attachments: true },
mailpace: { cc: true, bcc: true, replyTo: true },
smtp: { cc: true, bcc: true, replyTo: true, headers: true, attachments: true },
graph: { cc: true, bcc: true, replyTo: true, headers: true, attachments: true },
sendheron: {
cc: true,
bcc: true,
replyTo: true,
headers: true,
attachments: true,
sendAt: true
},
helo: {
cc: true,
bcc: true,
replyTo: true,
headers: true,
attachments: true,
tags: true,
metadata: true
}
};
var NATIVE_IDEMPOTENCY = new Set(["resend", "jetemail", "lettermint", "primitive", "sendheron", "helo"]);
var REPEATED_HEADERS = new Set(["mailgun", "postmark", "scaleway", "ses", "smtp", "graph"]);
var NATIVE_PERSONALIZED = new Set(["mailgun", "sendgrid"]);
var BUILT_IN_ADAPTER_CAPABILITIES = Object.fromEntries(Object.entries(SUPPORTED_MESSAGE_FIELDS).map(([name, fields]) => [
name,
{
repeatedHeaders: REPEATED_HEADERS.has(name),
idempotency: NATIVE_IDEMPOTENCY.has(name) ? "native" : name === "smtp" ? "message_id" : "none",
scheduling: "sendAt" in fields && fields.sendAt === true,
personalized: NATIVE_PERSONALIZED.has(name) ? "native" : "expanded"
}
]));
var BUILT_IN_ADAPTER_MARK = Symbol.for("@opencoredev/email-sdk/built-in-adapter");
for (const capabilities of Object.values(BUILT_IN_ADAPTER_CAPABILITIES)) {
Object.defineProperty(capabilities, BUILT_IN_ADAPTER_MARK, { value: true });
}
function isBuiltInAdapter(adapter) {
const capabilities = adapter?.capabilities;
return isObjectLike(capabilities) && Object.hasOwn(capabilities, BUILT_IN_ADAPTER_MARK);
}
var NO_HEADERS = [];
function headerList(headers) {
if (!headers)
return NO_HEADERS;
return isHeaderList(headers) ? headers : headersToArray(headers) ?? NO_HEADERS;
}
// src/core/failures.ts
var import_errors2 = require("./errors.cjs");
function normalizeAdapterFailure(adapter, cause) {
if (cause instanceof AttemptFailure)
return normalizeAdapterFailure(adapter, cause.error);
if (cause instanceof import_errors2.EmailAdapterError)
return cause;
const normalized = toProviderError(adapter, cause);
return normalized instanceof import_errors2.EmailAdapterError ? normalized : new import_errors2.EmailAdapterError(normalized.message, {
adapter,
retryable: normalized.retryable,
delivery: "unknown",
cause: normalized
});
}
function failureAttempt(cause) {
return cause instanceof AttemptFailure ? cause.attempt : 1;
}
function normalizeOwnedError(cause) {
if (cause instanceof import_errors2.EmailSdkError)
return cause;
return new import_errors2.EmailAdapterError(cause instanceof Error ? cause.message : "Email sending failed.", {
adapter: "unknown",
delivery: "unknown",
cause
});
}
function throwIfAborted(signal) {
if (signal?.aborted)
throw new import_errors2.EmailAbortError(signal.reason);
}
function isAbort(cause, signal) {
return signal?.aborted || cause instanceof Error && cause.name === "AbortError";
}
function sleep(delayMs, signal) {
if (delayMs <= 0) {
throwIfAborted(signal);
return Promise.resolve();
}
return new Promise((resolve, reject) => {
const timeout = setTimeout(done, delayMs);
const onAbort = () => {
clearTimeout(timeout);
signal?.removeEventListener("abort", onAbort);
reject(new import_errors2.EmailAbortError(signal?.reason));
};
function done() {
signal?.removeEventListener("abort", onAbort);
resolve();
}
signal?.addEventListener("abort", onAbort, { once: true });
});
}
// src/core/lifecycle.ts
var import_errors4 = require("./errors.cjs");
// src/core/routing.ts
var import_errors3 = require("./errors.cjs");
function validateCapabilities(adapter, message, operation) {
if (message.sendAt !== undefined && !adapter.capabilities.scheduling) {
throw new import_errors3.EmailValidationError(`${adapter.name} does not support scheduled email.`);
}
if (operation === "personalized" && adapter.capabilities.personalized === "unsupported") {
throw new import_errors3.EmailValidationError(`${adapter.name} does not support personalized email.`);
}
const headers = headerList(message.headers);
if (!adapter.capabilities.repeatedHeaders && headers.length > 1) {
const names = new Set;
for (const header of headers) {
const normalized = header.name.toLowerCase();
if (names.has(normalized)) {
throw new import_errors3.EmailValidationError(`${adapter.name} does not support repeated email header names: ${header.name}.`);
}
names.add(normalized);
}
}
}
function resolveRoute(defaultAdapter, clientFallback, sendOptions) {
const primary = sendOptions?.adapter ?? defaultAdapter;
const fallback = sendOptions?.fallback ?? clientFallback;
if (!fallback?.adapters?.length)
return { primary, fallback, names: [primary] };
return {
primary,
fallback,
names: [primary, ...fallback.adapters.filter((name) => name !== primary)]
};
}
function canFallback(error, fallback) {
return error.delivery === "not_sent" || fallback?.onUnknownDelivery === "continue";
}
function validateRetry(retry) {
if (retry?.maxAttempts !== undefined && (!Number.isInteger(retry.maxAttempts) || retry.maxAttempts < 1)) {
throw new import_errors3.EmailValidationError("retry.maxAttempts must be an integer greater than or equal to 1.");
}
}
function validateFallback(adapters, fallback) {
for (const name of fallback?.adapters ?? [])
requireAdapter(adapters, name);
}
function mergeSendOptions(base, override) {
if (!base)
return override;
if (!override)
return base;
return { ...base, ...override };
}
function requireAdapter(adapters, name) {
const adapter = adapters.get(name);
if (!adapter)
throw new import_errors3.EmailAdapterNotFoundError(name);
return adapter;
}
function addAdapter(adapters, adapter) {
if (adapters.has(adapter.name)) {
throw new import_errors3.EmailValidationError(`Duplicate email adapter "${adapter.name}".`);
}
adapters.set(adapter.name, adapter);
}
// src/core/lifecycle.ts
function createPluginContext(adapters, defaultAdapter) {
return {
adapters,
defaultAdapter,
addAdapter(adapter) {
addAdapter(adapters, adapter);
}
};
}
function resolvePluginAdapters(plugin, context) {
if (!plugin.adapters)
return [];
const adapters = Array.isArray(plugin.adapters) ? plugin.adapters : plugin.adapters(context);
if (!Array.isArray(adapters)) {
throw new import_errors4.EmailValidationError(`Email plugin "${plugin.id}" returned async adapters. createEmailClient requires synchronous plugin adapters.`);
}
return adapters;
}
function applyClientExtension(client, pluginId, extension) {
for (const key of Object.keys(extension)) {
if (Object.hasOwn(client, key)) {
throw new import_errors4.EmailValidationError(`Email plugin "${pluginId}" tried to extend the client with reserved key "${key}".`);
}
}
Object.assign(client, extension);
}
function applyBeforeSendMiddleware(middleware, event) {
if (middleware.length === 0)
return event;
return runBeforeSendMiddleware(middleware, event);
}
async function runBeforeSendMiddleware(middleware, event) {
let message = event.message;
let options = event.options;
for (const item of middleware) {
try {
const result = await item.beforeSend?.({ message, options });
if (result?.message)
message = result.message;
if (result?.options)
options = Object.assign({}, options, result.options);
} catch (error) {
throw new import_errors4.EmailMiddlewareError("before_send", error);
}
}
return { message, options };
}
function invokeAfterSendMiddleware(middleware, event) {
if (middleware.length === 0)
return;
return runAfterSendMiddleware(middleware, event);
}
async function runAfterSendMiddleware(middleware, event) {
for (const item of middleware) {
try {
await item.afterSend?.(event);
} catch (error) {
throw new import_errors4.EmailMiddlewareError("after_send", error);
}
}
}
function invokeErrorMiddleware(middleware, event) {
if (middleware.length === 0)
return;
return runErrorMiddleware(middleware, event);
}
async function runErrorMiddleware(middleware, event) {
for (const item of middleware) {
try {
await item.onError?.(event);
} catch (error) {
throw new import_errors4.EmailMiddlewareError("on_error", error);
}
}
}
async function invokeSendFailureLifecycle(middleware, hooks, event) {
await invokeErrorMiddleware(middleware, event);
await invokeHooks(hooks, "onError", event);
}
function invokeHooks(hooks, name, event) {
if (hooks.length === 0)
return;
return runHooks(hooks, name, event);
}
async function runHooks(hooks, name, event) {
for (const hook of hooks) {
try {
const handlers = hook;
await handlers[name]?.(event);
} catch {}
}
}
function hookEvent(adapter, message, attempt, metadata) {
return { adapter, message, attempt, metadata };
}
// src/telemetry.ts
var import_node_crypto = require("node:crypto");
var import_node_fs = require("node:fs");
var import_node_os = require("node:os");
var import_node_path = require("node:path");
var import_errors5 = require("./errors.cjs");
// src/version.ts
var SDK_VERSION = "3.1.0";
// src/telemetry.ts
var POSTHOG_HOST = "https://us.i.posthog.com";
var POSTHOG_PROJECT_KEY = "phc_D62r4m5ivBr6LPCBqjKHg8GL6QTxT57LTzKrmkg5hNZS";
var CAPTURE_TIMEOUT_MS = 3000;
var MAX_EXCEPTIONS_PER_PROCESS = 5;
var MAX_CAUSE_CHAIN = 3;
var MAX_STACK_FRAMES = 20;
var MAX_MESSAGE_LENGTH = 300;
var TELEMETRY_NOTICE = `@opencoredev/email-sdk collects opt-out usage telemetry using a stable installation identifier: adapter names, command names, success/failure counts, and redacted error reports. Email content, addresses, and credentials are never collected. Opt out with "email-sdk telemetry disable", EMAIL_SDK_TELEMETRY=0, or DO_NOT_TRACK=1. Details: https://github.com/opencoredev/email-sdk#telemetry`;
var KNOWN_ADAPTER_NAMES = new Set(Object.keys(SUPPORTED_MESSAGE_FIELDS));
function isBuiltInAdapterName(name) {
return KNOWN_ADAPTER_NAMES.has(name);
}
function normalizeAdapterName(name) {
if (!name) {
return "unknown";
}
return isBuiltInAdapterName(name) ? name : "custom";
}
function detectCiVendor(env) {
if (env.GITHUB_ACTIONS)
return "github_actions";
if (env.GITLAB_CI)
return "gitlab";
if (env.CIRCLECI)
return "circleci";
if (env.JENKINS_URL)
return "jenkins";
if (env.TRAVIS)
return "travis";
if (env.BUILDKITE)
return "buildkite";
if (env.CI === "true" || env.CI === "1")
return "generic";
return;
}
function detectHostingPlatform({
env,
hasDockerMarker
}) {
if (env.VERCEL)
return "vercel";
if (env.AWS_LAMBDA_FUNCTION_NAME)
return "aws_lambda";
if (env.K_SERVICE)
return "google_cloud_run";
if (env.RAILWAY_PROJECT_ID)
return "railway";
if (env.FLY_APP_NAME)
return "fly";
if (env.RENDER)
return "render";
if (env.KUBERNETES_SERVICE_HOST)
return "kubernetes";
return hasDockerMarker ? "docker" : undefined;
}
function hasDockerMarker() {
try {
return import_node_fs.existsSync("/.dockerenv");
} catch {
return false;
}
}
var disabledTelemetry = {
enabled: false,
capture: () => Promise.resolve(),
captureException: () => Promise.resolve(),
flush: () => Promise.resolve()
};
function createTelemetry(options = {}) {
const env = options.env ?? process.env;
const fetcher = options.fetch ?? fetch;
const notify = options.notify ?? ((message) => process.stderr.write(`${message}
`));
if (envOptOut(env))
return disabledTelemetry;
const configDir = resolveConfigDir(env, options.configDir);
const loaded = loadTelemetryState(configDir);
if (!loaded || loaded.state.disabled)
return disabledTelemetry;
const { state } = loaded;
let { installationIdSource } = loaded;
if (!state.noticeShown) {
notify(TELEMETRY_NOTICE);
const noticeSaved = loaded.mayWriteState && persistTelemetryState(configDir, { ...state, noticeShown: true });
if (noticeSaved && installationIdSource === "ephemeral") {
installationIdSource = "created";
}
}
const ciVendor = detectCiVendor(env);
const commonProperties = {
sdk_version: options.sdkVersion ?? SDK_VERSION,
node_version: process.versions.node,
platform: process.platform,
arch: process.arch,
ci: ciVendor !== undefined,
ci_vendor: ciVendor,
measurement_schema_version: 2,
capture_mode: options.fetch ? "injected" : env.NODE_ENV === "test" ? "test" : "runtime",
installation_id_source: installationIdSource,
hosting_platform: detectHostingPlatform({ env, hasDockerMarker: hasDockerMarker() })
};
const pending = new Set;
const seenErrorObjects = new WeakSet;
const seenErrorClasses = new Set;
let exceptionBudget = MAX_EXCEPTIONS_PER_PROCESS;
async function deliver(event, properties) {
if (disabledInCode)
return;
try {
const response = await fetcher(`${POSTHOG_HOST}/capture/`, {
method: "POST",
headers: { "Content-Type": "application/json" },
signal: captureTimeoutSignal(),
body: JSON.stringify({
api_key: POSTHOG_PROJECT_KEY,
event,
distinct_id: state.installationId,
timestamp: new Date().toISOString(),
properties: {
...commonProperties,
...properties,
$process_person_profile: false
}
})
});
await response.body?.cancel();
} catch {}
}
function enqueue(delivery) {
pending.add(delivery);
delivery.finally(() => pending.delete(delivery));
return delivery;
}
return {
get enabled() {
return !disabledInCode;
},
realProviderVolume: !options.fetch && env.NODE_ENV !== "test" && ciVendor === undefined,
capture(event, properties) {
return enqueue(deliver(event, properties));
},
captureException(cause, context) {
try {
const errorObject = isObjectLike(cause) ? cause : undefined;
if (errorObject && seenErrorObjects.has(errorObject)) {
return Promise.resolve();
}
const exceptionList = buildExceptionList(cause, context.handled);
const head = exceptionList[0];
if (!head) {
return Promise.resolve();
}
const errorCode = cause instanceof import_errors5.EmailSdkError ? cause.code : "unknown";
const fingerprint = exceptionFingerprint(exceptionList, errorCode, context);
if (seenErrorClasses.has(fingerprint) || exceptionBudget <= 0) {
return Promise.resolve();
}
if (errorObject) {
seenErrorObjects.add(errorObject);
}
seenErrorClasses.add(fingerprint);
exceptionBudget -= 1;
const properties = {
$exception_list: exceptionList,
$exception_level: "error",
$exception_fingerprint: fingerprint,
error_name: head.type,
error_code: errorCode,
source: context.source,
handled: context.handled,
adapter: context.adapter,
command: context.command
};
return enqueue(deliver("$exception", properties));
} catch {
return Promise.resolve();
}
},
async flush() {
await Promise.all(pending);
}
};
}
var sharedTelemetry;
var disabledInCode = false;
function getTelemetry() {
if (disabledInCode)
return disabledTelemetry;
sharedTelemetry ??= createTelemetry();
return sharedTelemetry;
}
function disableTelemetry() {
disabledInCode = true;
}
function getTelemetryStatus(options = {}) {
const env = options.env ?? process.env;
const configDir = resolveConfigDir(env, options.configDir);
const configPath = import_node_path.join(configDir, "telemetry.json");
const envReason = envOptOut(env);
if (envReason)
return { enabled: false, reason: envReason, configPath };
if (disabledInCode)
return { enabled: false, reason: "code", configPath };
const stored = readStoredState(configDir);
if (stored === "unreadable")
return { enabled: false, reason: "config-unreadable", configPath };
if (stored !== "missing" && stored.disabled)
return { enabled: false, reason: "config", configPath };
return { enabled: true, reason: "default", configPath };
}
var telemetrySource = "sdk";
function getTelemetrySource() {
return telemetrySource;
}
function envOptOut(env) {
const optOut = env.EMAIL_SDK_TELEMETRY?.toLowerCase();
if (optOut === "0" || optOut === "false" || optOut === "off") {
return "EMAIL_SDK_TELEMETRY";
}
const doNotTrack = env.DO_NOT_TRACK?.toLowerCase();
if (doNotTrack === "1" || doNotTrack === "true") {
return "DO_NOT_TRACK";
}
return env.NODE_ENV === "test" ? "NODE_ENV" : undefined;
}
function resolveConfigDir(env, configDir) {
return configDir ?? import_node_path.join(env.XDG_CONFIG_HOME ?? import_node_path.join(import_node_os.homedir(), ".config"), "email-sdk");
}
function buildExceptionList(cause, handled) {
const items = [];
const visited = new Set;
let current = cause;
while (current !== undefined && current !== null && items.length < MAX_CAUSE_CHAIN && !visited.has(current)) {
visited.add(current);
const currentError = current instanceof Error ? current : undefined;
const item = {
type: currentError ? sanitizeErrorName(currentError.name) : "Error",
value: redactErrorMessage(currentError ? currentError.message : String(current)),
mechanism: { handled, type: "generic", synthetic: !currentError }
};
const frames = currentError ? parseStackFrames(currentError.stack) : [];
if (frames.length > 0) {
item.stacktrace = { type: "raw", frames };
}
items.push(item);
current = currentError?.cause;
}
return items;
}
function exceptionFingerprint(exceptionList, errorCode, context) {
const head = exceptionList[0];
const root = exceptionList.at(-1);
const sdkFrame = exceptionList.toReversed().flatMap((item) => (item.stacktrace?.frames ?? []).filter((frame) => frame.in_app).toReversed()).at(0);
return [
head?.type ?? "Error",
errorCode,
context.adapter ?? context.command ?? "none",
root?.type ?? "Error",
sdkFrame ? `${stableModuleName(sdkFrame.filename)}#${stableFunctionName(sdkFrame.function)}` : root?.value.slice(0, 60) ?? ""
].join(":");
}
function stableModuleName(filename) {
return (filename.split("/").at(-1) ?? filename).replace(/\.[cm]?[jt]s$/, "");
}
function stableFunctionName(name) {
return name.replace(/^(?:async |new )?(?:Object\.)?/, "");
}
var STACK_LINE_PATTERN = /^\s*at (?:(.*?) \()?((?:file:\/\/)?[^()]+?):(\d+):(\d+)\)?\s*$/;
function parseStackFrames(stack) {
if (!isStringMember(stack)) {
return [];
}
const frames = [];
for (const line of stack.split(`
`)) {
const match = STACK_LINE_PATTERN.exec(line);
if (!match) {
continue;
}
const filename = sanitizeFrameFilename(match[2] ?? "");
frames.push({
platform: "node:javascript",
function: match[1]?.trim() || "<anonymous>",
filename,
lineno: Number(match[3]),
colno: Number(match[4]),
in_app: filename.includes("@opencoredev/email-sdk") || filename.includes("email-sdk/dist")
});
if (frames.length >= MAX_STACK_FRAMES) {
break;
}
}
return frames.reverse();
}
function sanitizeFrameFilename(raw) {
let filename = raw.startsWith("file://") ? raw.slice("file://".length) : raw;
filename = filename.replaceAll("\\", "/");
const nodeModulesIndex = filename.lastIndexOf("node_modules/");
if (nodeModulesIndex >= 0) {
return filename.slice(nodeModulesIndex);
}
if (filename.startsWith("node:")) {
return filename;
}
return filename.split("/").at(-1) || filename;
}
var SAFE_ERROR_NAMES = new Set([
"EmailSdkError",
"EmailAdapterError",
"EmailAdapterNotFoundError",
"EmailAllRecipientsFailedError",
"EmailRouteError",
"EmailMiddlewareError",
"EmailAbortError",
"EmailProviderError",
"EmailValidationError",
"EmailProviderNotFoundError",
"Error",
"TypeError",
"RangeError",
"SyntaxError",
"ReferenceError",
"EvalError",
"URIError",
"AggregateError",
"AbortError",
"TimeoutError",
"DOMException"
]);
function sanitizeErrorName(name) {
if (!isStringMember(name) || !name) {
return "Error";
}
return SAFE_ERROR_NAMES.has(name) ? name : redactErrorMessage(name);
}
var EMAIL_PATTERN = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
var URL_PATTERN = /(?<![a-z0-9+.-])[a-z][a-z0-9+.-]*:\/\/[^\s"'<>]+/gi;
var TOKEN_PATTERN = /(?<![A-Za-z0-9+/_=-])[A-Za-z0-9+/_=-]{24,}(?![A-Za-z0-9+/_=-])/g;
var HOME_DIR_PATTERN = /[/\\](?:Users|home)[/\\][^\s/\\]+/g;
var HOME_TAIL_PATTERN = /~[/\\][^\s"'`<>]+/g;
var HOSTNAME_PATTERN = /(?<![\w.@-])(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}(?::\d+)?(?![\w-])/gi;
var SOURCE_FILE_EXTENSION = /^(?:c?js|mjs|[cm]?ts|[jt]sx|json|map|node|wasm|txt|log|html|css|ya?ml|toml|lock|env)$/i;
function redactHostname(match) {
const labels = match.replace(/:\d+$/, "").split(".");
const last = labels.at(-1) ?? "";
if (SOURCE_FILE_EXTENSION.test(last) || labels.length === 2 && /[a-z][A-Z]/.test(last)) {
return match;
}
return "<host>";
}
var IPV4_PATTERN = /(?<![\w.])\d{1,3}(?:\.\d{1,3}){3}(?::\d+)?(?!\.?\d)/g;
var IPV6_PATTERN = /(?<![\w:])(?=[0-9a-f:]*[0-9a-f])(?:[0-9a-f]{0,4}:){2,7}[0-9a-f]{0,4}(?![\w:])/gi;
var KEY_VALUE_SECRET_PATTERN = /\b(password|passwd|pwd|pass|secret|token|api[_-]?key)=[^\s"'`]+/gi;
function redactErrorMessage(message) {
let redacted = message;
const home = import_node_os.homedir();
if (home && home !== "/") {
redacted = redacted.split(home).join("~");
}
redacted = redacted.replace(HOME_DIR_PATTERN, "~").replace(HOME_TAIL_PATTERN, "~<path-redacted>").replace(URL_PATTERN, "<url>").replace(EMAIL_PATTERN, "<email>").replace(HOSTNAME_PATTERN, redactHostname).replace(IPV4_PATTERN, "<ip>").replace(IPV6_PATTERN, "<ip>").replace(/"[^"]*"/g, '"<redacted>"').replace(/'[^']*'/g, "'<redacted>'").replace(/`[^`]*`/g, "`<redacted>`").replace(KEY_VALUE_SECRET_PATTERN, "$1=<redacted>").replace(TOKEN_PATTERN, "<token>");
return redacted.length > MAX_MESSAGE_LENGTH ? `${redacted.slice(0, MAX_MESSAGE_LENGTH)}…` : redacted;
}
function readStoredState(configDir) {
const path = import_node_path.join(configDir, "telemetry.json");
let contents;
try {
contents = import_node_fs.readFileSync(path, "utf8");
} catch (error) {
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
return "missing";
}
return "unreadable";
}
try {
const parsed = parseJsonStrict(contents);
const installationId = jsonString(parsed, "installationId") || jsonString(parsed, "anonymousId") || undefined;
if (installationId) {
return {
installationId,
noticeShown: jsonField(parsed, "noticeShown") === true,
disabled: jsonField(parsed, "disabled") === true
};
}
} catch {}
return "unreadable";
}
function loadTelemetryState(configDir) {
const stored = readStoredState(configDir);
if (stored === "unreadable")
return;
if (stored !== "missing") {
return { state: stored, installationIdSource: "stored", mayWriteState: true };
}
const state = { installationId: import_node_crypto.randomUUID(), noticeShown: false };
const written = createInitialStateFile(configDir, state);
if (written === "created")
return { state, installationIdSource: "created", mayWriteState: true };
if (written === "failed")
return { state, installationIdSource: "ephemeral", mayWriteState: true };
const winner = readStoredState(configDir);
if (winner === "unreadable")
return;
if (winner !== "missing") {
return { state: winner, installationIdSource: "stored", mayWriteState: true };
}
return { state, installationIdSource: "ephemeral", mayWriteState: false };
}
function createInitialStateFile(configDir, state) {
const path = import_node_path.join(configDir, "telemetry.json");
const contents = `${JSON.stringify(state, null, 2)}
`;
const temporary = `${path}.${import_node_crypto.randomUUID()}.tmp`;
try {
import_node_fs.mkdirSync(configDir, { recursive: true });
import_node_fs.writeFileSync(temporary, contents);
import_node_fs.linkSync(temporary, path);
return "created";
} catch (error) {
if (error instanceof Error && "code" in error && error.code === "EEXIST")
return "exists";
return createStateFileExclusively(path, contents);
} finally {
removeQuietly(temporary);
}
}
function createStateFileExclusively(path, contents) {
try {
import_node_fs.writeFileSync(path, contents, { flag: "wx" });
return "created";
} catch (error) {
return error instanceof Error && "code" in error && error.code === "EEXIST" ? "exists" : "failed";
}
}
function removeQuietly(path) {
try {
import_node_fs.rmSync(path, { force: true });
} catch {}
}
function persistTelemetryState(configDir, state) {
try {
writeStateFile(configDir, state);
return true;
} catch {
return false;
}
}
function writeStateFile(configDir, state) {
import_node_fs.mkdirSync(configDir, { recursive: true });
const link = import_node_path.join(configDir, "telemetry.json");
const path = import_node_fs.existsSync(link) ? import_node_fs.realpathSync(link) : link;
const temporary = `${path}.${import_node_crypto.randomUUID()}.tmp`;
try {
import_node_fs.writeFileSync(temporary, `${JSON.stringify(state, null, 2)}
`);
import_node_fs.renameSync(temporary, path);
} finally {
import_node_fs.rmSync(temporary, { force: true });
}
}
function captureTimeoutSignal() {
return isFunctionMember(AbortSignal.timeout) ? AbortSignal.timeout(CAPTURE_TIMEOUT_MS) : undefined;
}
// src/core/failure-kind.ts
var import_errors6 = require("./errors.cjs");
var MAX_CAUSE_DEPTH = 6;
var PROGRAMMING_ERROR_NAMES = new Set([
"TypeError",
"RangeError",
"ReferenceError",
"EvalError",
"URIError"
]);
var INVALID_HEADER_PATTERN = /invalid header (?:name|value)|^Header .* has invalid value|Cannot convert argument to a ByteString/i;
var NETWORK_CODE_PATTERN = /^(?:E(?:CONN\w*|HOSTUNREACH|NETUNREACH|NETDOWN|PIPE|AI_\w+|TIMEDOUT|NOTFOUND|ADDRNOTAVAIL|PROTO|SOCKET|DNS|TLS|PROXY|REQUIRETLS)|UND_ERR_\w+|ERR_(?:TLS|SSL|SOCKET)_\w+|CERT_\w+|UNABLE_TO_\w+|DEPTH_ZERO_SELF_SIGNED_CERT|SELF_SIGNED_CERT_IN_CHAIN|ConnectionRefused|ConnectionClosed|FailedToOpenSocket|Timeout)$/;
var NETWORK_MESSAGE_PATTERN = /fetch failed|failed to fetch|unable to connect|network ?(?:connection|error)|socket hang up|timed out|connection (?:reset|lost|closed|refused)/i;
var AUTH_CODES = new Set(["EAUTH", "ENOAUTH", "EOAUTH2"]);
var SMTP_AUTH_REPLIES = new Set([530, 534, 535, 538]);
function statusKind(status) {
if (status === 401 || status === 403)
return "auth";
if (status === 429)
return "rate_limited";
if (status >= 500)
return "provider_error";
return "rejected";
}
function causeChain(error) {
const chain = [];
let current = error;
while (isObjectLike(current) && chain.length < MAX_CAUSE_DEPTH && !chain.includes(current)) {
chain.push(current);
current = current instanceof Error ? current.cause : undefined;
}
return chain;
}
function chainStatus(chain) {
for (const link of chain) {
const status = causeNumber(link, "status");
if (status !== undefined)
return status;
}
return;
}
function attemptStatus(adapter, cause) {
try {
return chainStatus(causeChain(normalizeAdapterFailure(adapter, cause)));
} catch {
return;
}
}
function classifyAdapterFailure(error) {
try {
return classify(error);
} catch {
return "rejected";
}
}
function classifyAttemptFailure(adapter, cause) {
try {
return classify(normalizeAdapterFailure(adapter, cause));
} catch {
return "rejected";
}
}
function classify(error) {
const chain = causeChain(error);
if (chain.some((link) => link instanceof import_errors6.EmailMiddlewareError || link instanceof import_errors6.EmailValidationError || link instanceof import_errors6.EmailAbortError)) {
return "caller";
}
const status = chainStatus(chain);
if (status !== undefined)
return statusKind(status);
for (const link of chain) {
const code = causeString(link, "code");
const reply = causeNumber(link, "responseCode");
if (code !== undefined && AUTH_CODES.has(code) || reply !== undefined && SMTP_AUTH_REPLIES.has(reply)) {
return "auth";
}
if (code === "EMAXLIMIT")
return "rate_limited";
if (reply !== undefined && reply >= 400)
return "rejected";
if (code !== undefined && NETWORK_CODE_PATTERN.test(code))
return "network";
if (link instanceof Error && (link.name === "AbortError" || link.name === "TimeoutError")) {
return "network";
}
if (link instanceof Error && !(link instanceof import_errors6.EmailSdkError) && NETWORK_MESSAGE_PATTERN.test(link.message)) {
return "network";
}
}
const root = chain.at(-1);
if (root instanceof import_errors6.EmailSdkError || !(root instanceof Error))
return "rejected";
if (root.name === "SyntaxError")
return "provider_error";
if (root.name === "TypeError" && INVALID_HEADER_PATTERN.test(root.message))
return "caller";
return PROGRAMMING_ERROR_NAMES.has(root.name) ? "unexpected" : "rejected";
}
function sendFailures(error) {
if (error instanceof import_errors6.EmailRouteError || error instanceof import_errors6.EmailAllRecipientsFailedError) {
return error.failures;
}
return error instanceof import_errors6.EmailAdapterError ? [error] : [];
}
function classifySendFailure(error) {
const last = sendFailures(error).at(-1);
return last ? classifyAdapterFailure(last) : "caller";
}
function findSdkDefect(error, isSdkOwned) {
return sendFailures(error).find((failure) => {
try {
return isSdkOwned(failure) && classifyAdapterFailure(failure) === "unexpected";
} catch {
return false;
}
});
}
// src/core/send-telemetry.ts
function listLength(value) {
if (value === undefined)
return 0;
return Array.isArray(value) ? value.length : 1;
}
function recipientCount(message) {
return listLength(message.to) + listLength(message.cc) + listLength(message.bcc);
}
function messageFacts(message) {
return {
recipients: recipientCount(message),
has_attachments: (message.attachments?.length ?? 0) > 0,
used_recipient_variables: false,
used_send_at: message.sendAt !== undefined
};
}
function personalizedFacts(input) {
return {
recipients: input.recipients.length,
personalized_recipient_count: input.recipients.length,
has_attachments: (input.message.attachments?.length ?? 0) > 0,
used_recipient_variables: input.recipients.some((recipient) => Object.keys(recipient.variables).length > 0),
used_send_at: input.message.sendAt !== undefined
};
}
function captureSendTelemetry({
telemetry,
source,
startedAt,
facts,
adapter,
success,
messageCount,
errorCode,
failureKind,
deliveryPath = "single"
}) {
telemetry?.capture("email sent", {
...facts,
adapter: normalizeAdapterName(adapter),
delivery_path: deliveryPath,
success,
duration_ms: Date.now() - startedAt,
error_code: errorCode,
failure_kind: failureKind,
message_count: messageCount,
measurement_schema_version: 2,
measurement_scope: "logical_operation",
logical_operation_count: 1,
operation_success_count: Number(success),
operation_failure_count: Number(!success),
source
});
}
function captureSendFailure({ error, isSdkOwned, ...input }) {
captureSendTelemetry({
...input,
success: false,
errorCode: error.code,
failureKind: classifySendFailure(error)
});
const defect = input.telemetry ? findSdkDefect(error, isSdkOwned) : undefined;
if (defect) {
input.telemetry?.captureException(defect, {
source: input.source,
handled: true,
adapter: normalizeAdapterName(defect.adapter)
});
}
}
// src/core/attempts.ts
var defaultDelay = (attempt) => Math.min(100 * 2 ** (attempt - 1), 2000);
function acceptanceCounts(accepted, rejected, recipients, requireComplete) {
const valid = (count) => count === undefined || Number.isSafeInteger(count) && count >= 0 && count <= recipients;
if (!valid(accepted) || !valid(rejected) || accepted !== undefined && rejected !== undefined && (accepted + rejected > recipients || requireComplete && accepted + rejected !== recipients)) {
return { accepted: 0, rejected: 0, explicit: false };
}
return {
accepted: accepted ?? 0,
rejected: rejected ?? 0,
explicit: accepted !== undefined || rejected !== undefined
};
}
class AttemptFailure {
error;
attempt;
constructor(error, attempt) {
this.error = error;
this.attempt = attempt;
}
}
async function attemptAdapter(input) {
const maxAttempts = input.retry?.maxAttempts ?? 1;
const shouldRetry = input.retry?.shouldRetry ?? import_errors7.isRetryableEmailError;
const delayFor = input.retry?.delay ?? defaultDelay;
let earlierOutcomeUnknown = false;
for (let attempt = 1;attempt <= maxAttempts; attempt += 1) {
throwIfAborted(input.options?.signal);
const event = hookEvent(input.adapter.name, input.message, attempt, input.options?.metadata);
const beforeSend = invokeHooks(input.hooks, "beforeSend", event);
if (beforeSend)
await beforeSend;
let result;
try {
const adapterResult = await input.measureAttempt(input.adapter, input.path ?? "single", recipientCount(input.message), () => input.adapter.send(input.message, {
adapter: input.adapter.name,
operation: "send",
attempt,
signal: input.options?.signal,
idempotencyKey: input.options?.idempotencyKey,
metadata: input.options?.metadata
}));
throwIfAborted(input.options?.signal);
result = normalizeAdapterResult(input.adapter.name, adapterResult);
} catch (error) {
if (isAbort(error, input.options?.signal))
throw new import_errors7.EmailAbortError(error);
if (error instanceof import_errors7.EmailValidationError || error instanceof import_errors7.EmailMiddlewareError)
throw error;
const normalized = toProviderError(input.adapter.name, error);
if (!(normalized instanceof import_errors7.EmailAdapterError))
throw normalized;
const canRetry = attempt < maxAttempts && shouldRetry(normalized, attempt);
if (!canRetry) {
throw new AttemptFailure(earlierOutcomeUnknown ? withUnknownDelivery(normalized) : normalized, attempt);
}
if (normalized.delivery === "unknown")
earlierOutcomeUnknown = true;
const delayMs = Math.max(0, delayFor(attempt, normalized));
await invokeHooks(input.hooks, "onRetry", {
...event,
error: normalized,
nextAttempt: attempt + 1,
delayMs
});
await sleep(delayMs, input.options?.signal);
continue;
}
if (input.middleware.length > 0 || input.hooks.length > 0) {
const afterEvent = { ...event, response: result };
await invokeAfterSendMiddleware(input.middleware, afterEvent);
await invokeHooks(input.hooks, "afterSend", afterEvent);
}
return result;
}
throw new import_errors7.EmailAdapterError("Email retry loop exited unexpectedly.", {
adapter: input.adapter.name,
delivery: "unknown"
});
}
function withUnknownDelivery(error) {
if (error.delivery === "unknown")
return error;
return new import_errors7.EmailAdapterError(error.message, {
adapter: error.adapter,
status: error.status,
requestId: error.requestId,
retryable: error.retryable,
delivery: "unknown",
acceptedCount: error.acceptedCount,
rejectedCount: error.rejectedCount,
cause: error
});
}
// src/core/personalized.ts
var import_errors8 = require("./errors.cjs");
async function attemptNativePersonalized(adapter, input, hookMessage, sendOptions, clientRetry, hooks, middleware, measureAttempt) {
const maxAttempts = sendOptions?.retry?.maxAttempts ?? clientRetry?.maxAttempts ?? 1;
const retry = sendOptions?.retry ?? clientRetry;
let earlierOutcomeUnknown = false;
for (let attempt = 1;attempt <= maxAttempts; attempt += 1) {
throwIfAborted(sendOptions?.signal);
const event = hookEvent(adapter.name, hookMessage, attempt, sendOptions?.metadata);
await invokeHooks(hooks, "beforeSend", event);
try {
const result = await measureAttempt(adapter, "personalized_native", input.recipients.length, () => adapter.sendPersonalized(input, {
adapter: adapter.name,
operation: "personalized",
attempt,
signal: sendOptions?.signal,
idempotencyKey: sendOptions?.idempotencyKey,
metadata: sendOptions?.metadata
}));
throwIfAborted(sendOptions?.signal);
const normalized = normalizeAdapterResult(adapter.name, result);
const personalized = {
...normalized,
accepted: result.accepted,
rejected: result.rejected
};
if (personalized.accepted.length > 0) {
await invokeAfterSendMiddleware(middleware, { ...event, response: personalized });
await invokeHooks(hooks, "afterSend", { ...event, response: personalized });
return { ...personalized, failures: [] };
}
const failure = new import_errors8.EmailAdapterError(`${adapter.name} rejected every personalized recipient.`, {
adapter: adapter.name,
delivery: earlierOutcomeUnknown ? "unknown" : "not_sent"
});
await invokeSendFailureLifecycle(middleware, hooks, {
...event,
error: failure
});
return {
...personalized,
failures: [failure]
};
} catch (error) {
if (isAbort(error, sendOptions?.signal))
throw new import_errors8.EmailAbortError(error);
if (error instanceof import_errors8.EmailMiddlewareError || error instanceof import_errors8.EmailValidationError)
throw error;
const failure = normalizeAdapterFailure(adapter.name, error);
const canRetry = attempt < maxAttempts && (retry?.shouldRetry ?? import_errors8.isRetryableEmailError)(failure, attempt);
if (!canRetry) {
const finalFailure = earlierOutcomeUnknown ? withUnknownDelivery(failure) : failure;
await invokeSendFailureLifecycle(middleware, hooks, {
...event,
error: finalFailure
});
return { adapter: adapter.name, accepted: [], rejected: [], failures: [finalFailure] };
}
if (failure.delivery === "unknown")
earlierOutcomeUnknown = true;
const delayMs = Math.max(0, (retry?.delay ?? defaultDelay)(attempt, failure));
await invokeHooks(hooks, "onRetry", {
...event,
error: failure,
nextAttempt: attempt + 1,
delayMs
});
await sleep(delayMs, sendOptions?.signal);
}
}
return { adapter: adapter.name, accepted: [], rejected: [], failures: [] };
}
async function attemptExpandedPersonalized(adapter, expanded, sendOptions, clientRetry, hooks, middleware, measureAttempt) {
const accepted = [];
const rejected = [];
const failures = [];
let firstResult;
for (const { recipient, message } of expanded) {
const address = emailAddressOf(recipient.to);
try {
const result = await attemptAdapter({
adapter,
message,
options: {
...sendOptions,
fallback: undefined,
idempotencyKey: recipientIdempotencyKey(sendOptions?.idempotencyKey, address)
},
retry: sendOptions?.retry ?? clientRetry,
hooks,
middleware,
measureAttempt,
path: "personalized_expanded"
});
firstResult ??= result;
accepted.push(address);
} catch (error) {
if (error instanceof import_errors8.EmailAbortError || error instanceof import_errors8.EmailMiddlewareError || error instanceof import_errors8.EmailValidationError) {
throw error;
}
rejected.push(address);
const failure = normalizeAdapterFailure(adapter.name, error);
failures.push(failure);
await invokeSendFailureLifecycle(middleware, hooks, {
adapter: adapter.name,
message,
attempt: failureAttempt(error),
metadata: sendOptions?.metadata,
error: failure
});
}
}
return {
adapter: adapter.name,
id: firstResult?.id,
raw: firstResult?.raw,
accepted,
rejected,
failures
};
}
function validatePersonalizedInput(input) {
if (input.recipients.length === 0) {
throw new import_errors8.EmailValidationError("sendPersonalized requires at least one recipient.");
}
const recipients = new Set;
for (const recipient of input.recipients) {
const address = emailAddressOf(recipient.to).toLowerCase();
if (!address)
throw new import_errors8.EmailValidationError("Personalized recipients require an email address.");
if (recipients.has(address)) {
throw new import_errors8.EmailValidationError(`Personalized recipient "${address}" appears more than once.`);
}
recipients.add(address);
for (const key of Object.keys(recipient.variables)) {
if (!/^[\w-]+$/.test(key)) {
throw new import_errors8.EmailValidationError(`Personalized variable keys may only contain letters, numbers, underscores, and hyphens: "${key}".`);
}
}
}
}
function personalizedMiddlewareMessage(input) {
const to = input.recipients[0]?.to ?? "";
return { ...input.message, to };
}
function withPersonalizedMessage(input, message) {
const { to: _to, cc: _cc, bcc: _bcc, ...template } = message;
return {
message: template,
recipients: input.recipients
};
}
function expandPersonalizedMessage(input, to, variables) {
const render = (value) => value?.replace(/%recipient\.([\w-]+)%/g, (_match, key) => Object.hasOwn(variables, key) ? String(variables[key]) : `%recipient.${key}%`);
return {
...input.message,
to,
subject: render(input.message.subject) ?? input.message.subject,
html: render(input.message.html),
text: render(input.message.text)
};
}
function recipientIdempotencyKey(base, address) {
return base ? `${base}:${address}` : undefined;
}
// src/core.ts
var import_errors9 = require("./errors.cjs");
// src/testing.ts
var TEST_ADAPTER_SEND = Symbol.for("@opencoredev/email-sdk/test-adapter-send");
function isTestAdapter(adapter) {
return TEST_ADAPTER_SEND in adapter.send;
}
// src/core.ts
function createEmailClient(options) {
const adapters = new Map;
const pluginHooks = [];
const middleware = [];
const extensionPlugins = [];
for (const adapter of options.adapters ?? [])
addAdapter(adapters, adapter);
const requestedDefault = options.defaultAdapter ?? options.adapters?.[0]?.name ?? "";
const pluginIds = new Set;
for (const plugin of options.plugins ?? []) {
if (pluginIds.has(plugin.id)) {
throw new import_errors9.EmailValidationError(`Duplicate email plugin "${plugin.id}".`);
}
pluginIds.add(plugin.id);
const context = createPluginContext(adapters, requestedDefault);
for (const adapter of resolvePluginAdapters(plugin, context)) {
if (adapters.get(adapter.name) !== adapter)
context.addAdapter(adapter);
}
if (plugin.hooks)
pluginHooks.push(plugin.hooks);
middleware.push(...plugin.middleware ?? []);
if (plugin.extendClient)
extensionPlugins.push(plugin);
}
const defaultAdapter = options.defaultAdapter ?? adapters.keys().next().value;
if (!defaultAdapter) {
throw new import_errors9.EmailValidationError("createEmailClient requires at least one adapter.");
}
requireAdapter(adapters, defaultAdapter);
validateRetry(options.retry);
validateFallback(adapters, options.fallback);
const sharedTelemetry2 = options.telemetry === false ? undefined : getTelemetry();
const telemetry = sharedTelemetry2?.enabled ? sharedTelemetry2 : undefined;
const telemetrySource2 = getTelemetrySource();
const hooks = [...pluginHooks, ...options.hooks ? [options.hooks] : []];
const measureAttempt = (adapter, path, recipients, invoke) => {
if (!telemetry?.enabled)
return invoke();
return measureAttemptTelemetry(telemetry, adapter, path, recipients, invoke);
};
const measureAttemptTelemetry = async (telemetry2, adapter, path, recipients, invoke) => {
const startedAt = Date.now();
const adapterName = normalizeAdapterName(adapter.name);
const adapterKind = isTestAdapter(adapter) || adapter.name === "memory" ? "test" : ["custom", "unknown"].includes(adapterName) ? "custom" : "provider";
const provider = telemetry2.realProviderVolume === true && adapterKind !== "test";
let result;
let failure;
let resolved = false;
try {
const response = await invoke();
result = response;
resolved = true;
return response;
} catch (error) {
failure = error;
throw error;
} finally {
const adapterError = failure instanceof import_errors9.EmailAdapterError ? failure : undefined;
const counts = acceptanceCounts(result?.accepted?.length ?? adapterError?.acceptedCount, result?.rejected?.length ?? adapterError?.rejectedCount, recipients, adapterError !== undefined);
const { accepted, rejected } = counts;
const acceptedMessages = path === "personalized_native" ? accepted : Number(accepted > 0);
const inferred = resolved && result?.accepted === undefined && result?.rejected === undefined;
const acceptanceBasis = counts.explicit ? "explicit" : inferred ? "inferred_from_success" : "unknown";
const submittedRecipients = inferred ? recipients : accepted;
const submittedMessages = path === "personalized_native" ? submittedRecipients : Number(submittedRecipients > 0);
const notSent = adapterError?.delivery === "not_sent" && accepted === 0;
const unknownRecipients = notSent ? 0 : Math.max(0, recipients - accepted - rejected);
telemetry2.capture("email adapter attempted", {
failure_kind: resolved ? undefined : classifyAttemptFailure(adapter.name, failure),
http_status: resolved ? undefined : attemptStatus(adapter.name, failure),
measurement_schema_version: 2,
measurement_scope: "adapter_attempt",
adapter: adapterName,
adapter_kind: adapterKind,
delivery_path: path,
source: telemetrySource2,
duration_ms: Date.now() - startedAt,
adapter_attempt_count: 1,
adapter_resolved_count: Number(resolved),
adapter_failure_count: Number(!resolved),
not_sent_attempt_count: Number(notSent),
uncertain_attempt_count: Number(!resolved && !notSent),
attempted_message_count: path === "personalized_native" ? recipients : 1,
attempted_recipient_count: recipients,
not_sent_recipient_count: notSent ? recipients : 0,
accepted_message_count: acceptedMessages,
accepted_recipient_count: accepted,
rejected_recipient_count: rejected,
unknown_recipient_count: unknownRecipients,
provider_volume_eligible: provider,
provider_attempt_count: Number(provider),
provider_accepted_message_count: provider ? acceptedMessages : 0,
provider_accepted_recipient_count: provider ? accepted : 0,
acceptance_basis: acceptanceBasis,
provider_submitted_message_count: provider ? submittedMessages : 0,
provider_submitted_recipient_count: provider ? submittedRecipients : 0
});
}
};
const callerErrors = new WeakSet;
const callerOwned = (run) => {
try {
return run();
} catch (error) {
if (isObjectLike(error))
callerErrors.add(error);
throw error;
}
};
const callerRetry = (retry) => {
if (!retry)
return retry;
const { shouldRetry, delay } = retry;
return {
...retry,
shouldRetry: shouldRetry && ((error, attempt) => callerOwned(() => shouldRetry(error, attempt))),
delay: delay && ((attempt, error) => callerOwned(() => delay(attempt, error)))
};
};
const isSdkOwned = (failure) => {
if (isObjectLike(failure.cause) && callerErrors.has(failure.cause))
return false;
if (failure.adapter === "unknown" && !adapters.has("unknown"))
return true;
return isBuiltInAdapter(adapters.get(failure.adapter));
};
telemetry?.capture("client created", {
adapters: [...adapters.keys()].map(normalizeAdapterName),
adapter_count: adapters.size,
plugin_count: options.plugins?.length ?? 0,
default_adapter: normalizeAdapterName(defaultAdapter),
source: telemetrySource2
});
const markValidatorError = (adapter, cause) => {
if (!isBuiltInAdapter(adapter) && isObjectLike(cause))
callerErrors.add(cause);
throw cause;
};
const validateRoute = (message, route, operation, from = 0) => {
if (from === 0)
assertMessage(message);
for (let index = from;index < route.names.length; index += 1) {
const name = route.names[index] ?? route.primary;
const adapter = requireAdapter(adapters, name);
validateCapabilities(adapter, message, operation);
let pending;
try {
pending = adapter.validate?.(message, { adapter: name, operation });
} catch (error) {
return markValidatorError(adapter, error);
}
if (pending !== undefined) {
return Promise.resolve(pending).then(() => validateRoute(message, route, operation, index + 1), (cause) => markValidatorError(adapter, cause));
}
}
return;
};
const resolveCheckedRoute = (sendOptions) => {
validateRetry(sendOptions?.retry);
const route = resolveRoute(defaultAdapter, options.fallback, sendOptions);
validateFallback(adapters, route.fallback);
return route;
};
const validate = async (message, sendOptions) => {
const route = resolveCheckedRoute(sendOptions);
await validateRoute(message, route, "send");
return { adapter: route.primary, warnings: [] };
};
const send = async (message, sendOptions) => {
const startedAt = Date.now();
const facts = telemetry && messageFacts(message);
try {
throwIfAborted(sendOptions?.signal);
const preparing = applyBeforeSendMiddleware(middleware, {
message,
options: sendOptions
});
const prepared = preparing instanceof Promise ? await preparing : preparing;
const route = resolveCheckedRoute(prepared.options);
const validating = validateRoute(prepared.message, route, "send");
if (validating)
await validating;
const retry = callerRetry(prepared.options?.retry ?? options.retry);
const failures = [];
for (const [index, name] of route.names.entries()) {
const adapter = requireAdapter(adapters, name);
try {
const result = await attemptAdapter({
adapter,
message: prepared.message,
options: prepared.options,
retry,
hooks,
middleware,
measureAttempt
});
if (facts) {
captureSendTelemetry({
telemetry,
source: telemetrySource2,
startedAt,
facts,
adapter: result.adapter,
success: true,
messageCount: 1
});
}
return result;
} catch (error) {
if (error instanceof import_errors9.EmailAbortError || error instanceof import_errors9.EmailValidationError || error instanceof import_errors9.EmailMiddlewareError) {
throw error;
}
const failure = normalizeAdapterFailure(name, error);
failures.push(failure);
await invokeErrorMiddleware(middleware, {
adapter: name,
message: prepared.message,
attempt: failureAttempt(error),
metadata: prepared.options?.metadata,
error: failure
});
await invokeHooks(hooks, "onError", {
adapter: name,
message: prepared.message,
attempt: failureAttempt(error),
metadata: prepared.options?.metadata,
error: failure
});
const hasNext = index < route.names.length - 1;
if (!hasNext || !canFallback(failure, route.fallback))
break;
}
}
throw new import_errors9.EmailRouteError(failures);
} catch (error) {
const normalized = normalizeOwnedError(error);
if (facts) {
captureSendFailure({
telemetry,
source: telemetrySource2,
startedAt,
facts,
adapter: sendOptions?.adapter ?? defaultAdapter,
messageCount: 1,
error: normalized,
isSdkOwned
});
}
throw normalized;
}
};
const sendMany = async (items, sendOptions) => {
const startedAt = Date.now();
const results = [];
const usedAdapters = new Set;
let failed = 0;
let firstErrorCode;
for (const [index, item] of items.entries()) {
try {
const result = await send(item.message, mergeSendOptions(sendOptions, item.options));
if (telemetry)
usedAdapters.add(normalizeAdapterName(result.adapter));
results.push({ ok: true, index, result });
} catch (error) {
const normalized = normalizeOwnedError(error);
if (telemetry) {
const adapter2 = item.options?.adapter ?? sendOptions?.adapter ?? defaultAdapter;
usedAdapters.add(normalizeAdapterName(adapter2));
}
failed += 1;
firstErrorCode ??= normalized.code;
results.push({ ok: false, index, error: normalized });
}
}
if (!telemetry)
return results;
const adapter = usedAdapters.size === 0 ? normalizeAdapterName(sendOptions?.adapter ?? defaultAdapter) : usedAdapters.size === 1 ? [...usedAdapters][0] : "mixed";
telemetry.capture("email batch sent", {
message_count: items.length,
measurement_schema_version: 2,
measurement_scope: "batch_summary",
succeeded: items.length - failed,
failed,
recipients: items.reduce((total, item) => total + arrayify(item.message.to).length + arrayify(item.message.cc).length + arrayify(item.message.bcc).length, 0),
adapter,
success: failed === 0,
duration_ms: Date.now() - startedAt,
error_code: firstErrorCode,
source: telemetrySource2
});
return results;
};
const sendPersonalized = async (input, sendOptions) => {
const startedAt = Date.now();
const facts = telemetry && personalizedFacts(input);
let attemptedAdapter = sendOptions?.adapter ?? defaultAdapter;
let deliveryPath = "personalized";
try {
validatePersonalizedInput(input);
throwIfAborted(sendOptions?.signal);
const prepared = await applyBeforeSendMiddleware(middleware, {
message: personalizedMiddlewareMessage(input),
options: sendOptions
});
const preparedInput = withPersonalizedMessage(input, prepared.message);
const route = resolveRoute(defaultAdapter, options.fallback, prepared.options);
attemptedAdapter = route.primary;
validateFallback(adapters, route.fallback);
validateRetry(prepared.options?.retry);
const expanded = input.recipients.map((recipient) => ({
recipient,
message: expandPersonalizedMessage(preparedInput, recipient.to, recipient.variables)
}));
for (const { message } of expanded) {
await validateRoute(message, route, "personalized");
}
const routeFailures = [];
const attemptOptions = prepared.options && {
...prepared.options,
retry: callerRetry(prepared.options.retry)
};
const clientRetry = callerRetry(options.retry);
for (const [index, name] of route.names.entries()) {
const adapter = requireAdapter(adapters, name);
deliveryPath = adapter.sendPersonalized ? "personalized_native" : "personalized_expanded";
const result = adapter.sendPersonalized ? await attemptNativePersonalized(adapter, preparedInput, expanded[0].message, attemptOptions, clientRetry, hooks, middleware, measureAttempt) : await attemptExpandedPersonalized(adapter, expanded, attemptOptions, clientRetry, hooks, middleware, measureAttempt);
if (result.accepted.length > 0) {
if (facts) {
captureSendTelemetry({
telemetry,
source: telemetrySource2,
startedAt,
facts,
adapter: result.adapter,
success: true,
messageCount: facts.recipients,
deliveryPath
});
}
return result;
}
routeFailures.push(...result.failures);
const hasNext = index < route.names.length - 1;
const mayFallback = hasNext && result.failures.length > 0 && result.failures.every((failure) => canFallback(failure, route.fallback));
if (!mayFallback)
break;
}
throw new import_errors9.EmailAllRecipientsFailedError(routeFailures);
} catch (error) {
const normalized = normalizeOwnedError(error);
if (facts) {
captureSendFailure({
telemetry,
source: telemetrySource2,
startedAt,
facts,
adapter: attemptedAdapter,
messageCount: facts.recipients,
error: normalized,
isSdkOwned,
deliveryPath
});
}
throw normalized;
}
};
const client = {
adapters,
defaultAdapter,
validate(message, sendOptions) {
return validate(message, sendOptions);
},
send,
sendMany,
sendPersonalized,
adapter(name) {
return requireAdapter(adapters, name);
},
flush() {
return sharedTelemetry2?.flush() ?? Promise.resolve();
},
withAdapter(name) {
requireAdapter(adapters, name);
const routeOptions = (value) => ({
...value,
adapter: name
});
return {
validate(message, sendOptions) {
return validate(message, routeOptions(sendOptions));
},
send(message, sendOptions) {
return send(message, routeOptions(sendOptions));
},
sendMany(items, sendOptions) {
return sendMany(items, routeOptions(sendOptions));
},
sendPersonalized(input, sendOptions) {
return sendPersonalized(input, routeOptions(sendOptions));
}
};
}
};
for (const plugin of extensionPlugins) {
const extension = plugin.extendClient?.(createPluginContext(adapters, defaultAdapter));
if (extension)
applyClientExtension(client, plugin.id, extension);
}
return client;
}
// src/index.ts
var import_errors10 = require("./errors.cjs");
Shown as plain text from the published tarball, after apm checked it against the version's checksum. Nothing in it runs on this page.