Documentation

TypeDock — Mail Provider Plugin Specification (`provides: ["mail"]`)

Implement provides: ["mail"] to route outbound email through Brevo, Resend, Postmark, SendGrid, or Mailjet without recompiling Go.

TypeDock supports drop-in JavaScript plugins (executed in a 200ms goja sandbox) that replace or extend outbound email delivery (e.g. Brevo, Mailjet, Resend, Postmark, SendGrid) without recompiling Go.

Once a plugin declaring "provides": ["mail"] is enabled in Admin → Modules & Plugins:

  • All outbound mail calls (ctx.sendMail(...) from Form Block, Admin → Mail Settings → Send Test Email, etc.) are transparently routed to that plugin.
  • TypeDock's capability collision detector ensures at most one "mail" provider plugin is active at a time.
  • If the plugin is disabled, delivery automatically falls back to the SMTP / local sendmail settings in Admin → Mail Settings.

1. Directory & ZIP Structure

Place the plugin under plugins/<slug>/ or upload a .zip archive via Admin → Modules & Plugins → Install Drop-in Plugin (.zip):

mail-brevo/
├── plugin.json
└── plugin.js

plugin.json

{
  "slug": "mail-brevo",
  "name": "Brevo Mail",
  "version": "1.0.0",
  "description": "Send outbound emails via Brevo Transactional Email API v3",
  "entry": "plugin.js",
  "provides": ["mail"],
  "permissions": ["http", "admin"]
}

2. Capability Handler Contract ("mail")

Inside init(ctx) in plugin.js, register a handler for "mail" using ctx.registerCapability("mail", fn) (alias of ctx.registerCapabilityHandler):

Input payload

{
  action: "send",           // always "send"
  from_email: "[email protected]", // from Admin → Mail Settings (may be empty if overridden in plugin)
  from_name: "My Site",              // from Admin → Mail Settings / Site Name
  to: ["[email protected]"],         // non-empty array of validated recipient email addresses
  reply_to: "[email protected]",   // optional validated Reply-To address (or "")
  subject: "[My Site] Contact",      // email subject
  body: "Plain-text message body"    // UTF-8 plain-text body
}

Return Value

  • Success: { ok: true } (or any non-error object)
  • Failure: { ok: false, error: "human-readable error message" } (or throw new Error("..."))

3. Sandbox APIs Available to Mail Plugins

  • ctx.http().post(url, bodyString, headersObj) — SSRF-guarded outbound HTTPS POST (CPU timer pauses during Go network I/O; 10s HTTP timeout). Returns { status, ok, body, headers }.
  • ctx.getOption(key, defaultVal) / ctx.setOption(key, val) — persists plugin settings under site_options (plugin.<slug>.<key>).
  • ctx.base64Encode(str) / btoa(str) — Base64 encoding (useful for HTTP Basic Auth such as Mailjet).
  • ctx.registerAdminRoute(method, subPath, fn) — registers a settings page rendered inside Admin → Modules & Plugins → Configure.
  • ctx.log().info(msg) / warn(msg) / error(msg) — structured server logs.

4. Complete Example: Brevo (plugins/mail-brevo/plugin.js)

function esc(s) {
  return String(s || '')
    .replace(/&/g, '&amp;').replace(/</g, '&lt;')
    .replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

function init(ctx) {
  ctx.registerCapability('mail', function (payload) {
    var apiKey = String(ctx.getOption('api_key', '') || '').trim();
    if (!apiKey) {
      return { ok: false, error: 'Brevo API key is not configured in plugin settings' };
    }
    var fromEmail = String(ctx.getOption('from_email', '') || payload.from_email || '').trim();
    var fromName = String(ctx.getOption('from_name', '') || payload.from_name || 'TypeDock').trim();
    if (!fromEmail) {
      return { ok: false, error: 'From Email is required (configure in Brevo plugin or Mail Settings)' };
    }

    var toList = [];
    var rawTo = payload.to || [];
    for (var i = 0; i < rawTo.length; i++) {
      toList.push({ email: String(rawTo[i]) });
    }

    var reqBody = {
      sender: { email: fromEmail, name: fromName },
      to: toList,
      subject: String(payload.subject || '(No subject)'),
      textContent: String(payload.body || '')
    };
    if (payload.reply_to) {
      reqBody.replyTo = { email: String(payload.reply_to) };
    }

    var res = ctx.http().post(
      'https://api.brevo.com/v3/smtp/email',
      JSON.stringify(reqBody),
      {
        'api-key': apiKey,
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    );
    if (!res.ok) {
      return { ok: false, error: 'Brevo HTTP ' + res.status + ': ' + String(res.body || '').slice(0, 200) };
    }
    return { ok: true };
  });

  // Admin settings page (Configure button in Admin → Modules & Plugins)
  ctx.registerAdminRoute('GET', '/', function (req) {
    var hasKey = !!ctx.getOption('api_key', '');
    var fromEmail = ctx.getOption('from_email', '');
    var fromName = ctx.getOption('from_name', '');
    var saved = req.query.saved === '1' ? '<div style="padding:8px 12px;background:#dcfce7;color:#166534;border-radius:6px;margin-bottom:12px">Saved.</div>' : '';
    var html = '<!doctype html><html><body style="font-family:system-ui,sans-serif;padding:16px;max-width:600px">' +
      '<h2>Brevo Mail Settings</h2>' + saved +
      '<form method="post" action="' + esc(req.base_path + '/admin/plugins/mail-brevo/_frame/save') + '">' +
      '<p><label>API Key (xkeysib-...)<br><input type="password" name="api_key" placeholder="' + (hasKey ? 'Saved (leave blank to keep)' : 'xkeysib-...') + '" style="width:100%;padding:8px"></label></p>' +
      '<p><label>Override From Email (optional)<br><input type="email" name="from_email" value="' + esc(fromEmail) + '" style="width:100%;padding:8px"></label></p>' +
      '<p><label>Override From Name (optional)<br><input type="text" name="from_name" value="' + esc(fromName) + '" style="width:100%;padding:8px"></label></p>' +
      '<button type="submit" style="padding:8px 16px;background:#0f172a;color:#fff;border:0;border-radius:6px;cursor:pointer">Save</button>' +
      '</form></body></html>';
    return { status: 200, html: html };
  });

  ctx.registerAdminRoute('POST', '/save', function (req) {
    var key = String(req.form.api_key || '').trim();
    if (key) ctx.setOption('api_key', key);
    ctx.setOption('from_email', String(req.form.from_email || '').trim());
    ctx.setOption('from_name', String(req.form.from_name || '').trim());
    return { redirect: req.base_path + '/admin/plugins/mail-brevo/_frame/?saved=1' };
  });
}

5. Snippet for Mailjet (v3.1/send with Basic Auth)

var authHeader = 'Basic ' + ctx.base64Encode(apiKey + ':' + secretKey);
var res = ctx.http().post(
  'https://api.mailjet.com/v3.1/send',
  JSON.stringify({
    Messages: [{
      From: { Email: fromEmail, Name: fromName },
      To: toList.map(function (t) { return { Email: t.email }; }),
      Subject: payload.subject,
      TextPart: payload.body,
      Headers: payload.reply_to ? { 'Reply-To': payload.reply_to } : undefined
    }]
  }),
  {
    'Authorization': authHeader,
    'Content-Type': 'application/json'
  }
);