@devwithbobby/loops

中文文档
0.2.0发布于 2026/01/20Apache-2.0TypeScriptES Module近 30 天下载 2838

Convex component for integrating with Loops.so email marketing platform

原始使用文档
文档目录25 节
  1. Features
  2. Installation
  3. Quick Start
  4. 1. Install and Mount the Component
  5. 2. Set Up Environment Variables
  6. 3. Use the Component
  7. API Reference
  8. Contact Management
  9. Email Sending
  10. Monitoring & Analytics
  11. Rate Limiting
  12. Using the API Helper
  13. Security Best Practices
  14. Authentication Example
  15. Environment Variables
  16. Monitoring & Rate Limiting
  17. Development
  18. Local Development
  19. Building
  20. Testing
  21. Project Structure
  22. API Coverage
  23. Contributing
  24. License
  25. Resources

@devwithbobby/loops

npm version

A Convex component for integrating with Loops.so email marketing platform. Send transactional emails, manage contacts, trigger loops, and monitor email operations with built-in spam detection and rate limiting.

Features

  • Contact Management - Create, update, find, list, and delete contacts
  • Transactional Emails - Send one-off emails with templates
  • Events - Trigger email workflows based on events
  • Loops - Trigger automated email sequences
  • Monitoring - Track all email operations with spam detection
  • Rate Limiting - Built-in rate limiting queries for abuse prevention
  • Type-Safe - Full TypeScript support with Zod validation

Installation

npm install @devwithbobby/loops
# or
bun add @devwithbobby/loops

Quick Start

1. Install and Mount the Component

In your convex/convex.config.ts:

import loops from "@devwithbobby/loops/convex.config";
import { defineApp } from "convex/server";

const app = defineApp();
app.use(loops);

export default app;

2. Set Up Environment Variables

IMPORTANT: Set your Loops API key before using the component.

npx convex env set LOOPS_API_KEY "your-loops-api-key-here"

Or via Convex Dashboard:

  1. Go to Settings -> Environment Variables
  2. Add LOOPS_API_KEY with your Loops.so API key

Get your API key from Loops.so Dashboard.

3. Use the Component

In your convex/functions.ts (or any convex file):

import { Loops } from "@devwithbobby/loops";
import { components } from "./_generated/api";
import { action } from "./_generated/server";
import { v } from "convex/values";

// Initialize the Loops client
const loops = new Loops(components.loops);

// Export functions wrapped with auth (required in production)
export const addContact = action({
  args: {
    email: v.string(),
    firstName: v.optional(v.string()),
    lastName: v.optional(v.string()),
  },
  handler: async (ctx, args) => {
    // Add authentication check
    const identity = await ctx.auth.getUserIdentity();
    if (!identity) throw new Error("Unauthorized");

    return await loops.addContact(ctx, args);
  },
});

export const sendWelcomeEmail = action({
  args: {
    email: v.string(),
    name: v.string(),
  },
  handler: async (ctx, args) => {
    const identity = await ctx.auth.getUserIdentity();
    if (!identity) throw new Error("Unauthorized");

    // Send transactional email
    return await loops.sendTransactional(ctx, {
      transactionalId: "welcome-email-template-id",
      email: args.email,
      dataVariables: {
        name: args.name,
      },
    });
  },
});

API Reference

Contact Management

Add or Update Contact

await loops.addContact(ctx, {
  email: "[email protected]",
  firstName: "John",
  lastName: "Doe",
  userId: "user123",
  source: "webapp",
  subscribed: true,
  userGroup: "premium",
});

Update Contact

await loops.updateContact(ctx, "[email protected]", {
  firstName: "Jane",
  userGroup: "vip",
});

Find Contact

const contact = await loops.findContact(ctx, "[email protected]");

List Contacts

List contacts with pagination and optional filtering.

// Simple list with default limit (100)
const result = await loops.listContacts(ctx);

// List with filters and pagination
const result = await loops.listContacts(ctx, {
  userGroup: "premium",
  subscribed: true,
  limit: 20,
  offset: 0
});

console.log(result.contacts); // Array of contacts
console.log(result.total);    // Total count matching filters
console.log(result.hasMore);  // Boolean indicating if more pages exist

Delete Contact

await loops.deleteContact(ctx, "[email protected]");

Batch Create Contacts

await loops.batchCreateContacts(ctx, {
  contacts: [
    { email: "[email protected]", firstName: "John" },
    { email: "[email protected]", firstName: "Jane" },
  ],
});

Unsubscribe/Resubscribe

await loops.unsubscribeContact(ctx, "[email protected]");
await loops.resubscribeContact(ctx, "[email protected]");

Count Contacts

// Count all contacts
const total = await loops.countContacts(ctx, {});

// Count by filter
const premium = await loops.countContacts(ctx, {
  userGroup: "premium",
  subscribed: true,
});

Email Sending

Send Transactional Email

await loops.sendTransactional(ctx, {
  transactionalId: "template-id-from-loops",
  email: "[email protected]",
  dataVariables: {
    name: "John",
    orderId: "12345",
  },
});

Send Event (Triggers Workflows)

await loops.sendEvent(ctx, {
  email: "[email protected]",
  eventName: "purchase_completed",
  eventProperties: {
    product: "Premium Plan",
    amount: 99.99,
  },
});

Trigger Loop (Automated Sequence)

await loops.triggerLoop(ctx, {
  loopId: "loop-id-from-loops",
  email: "[email protected]",
  dataVariables: {
    onboardingStep: "welcome",
  },
});

Monitoring & Analytics

Get Email Statistics

const stats = await loops.getEmailStats(ctx, {
  timeWindowMs: 3600000, // Last hour
});

console.log(stats.totalOperations); // Total emails sent
console.log(stats.successfulOperations); // Successful sends
console.log(stats.failedOperations); // Failed sends
console.log(stats.operationsByType); // Breakdown by type
console.log(stats.uniqueRecipients); // Unique email addresses

Detect Spam Patterns

// Detect recipients with suspicious activity
const spamRecipients = await loops.detectRecipientSpam(ctx, {
  timeWindowMs: 3600000,
  maxEmailsPerRecipient: 10,
});

// Detect actors with suspicious activity
const spamActors = await loops.detectActorSpam(ctx, {
  timeWindowMs: 3600000,
  maxEmailsPerActor: 50,
});

// Detect rapid-fire patterns
const rapidFire = await loops.detectRapidFirePatterns(ctx, {
  timeWindowMs: 60000, // Last minute
  maxEmailsPerWindow: 5,
});

Rate Limiting

Check Rate Limits

// Check recipient rate limit
const recipientCheck = await loops.checkRecipientRateLimit(ctx, {
  email: "[email protected]",
  timeWindowMs: 3600000, // 1 hour
  maxEmails: 10,
});

if (!recipientCheck.allowed) {
  throw new Error(`Rate limit exceeded. Try again after ${recipientCheck.retryAfter}ms`);
}

// Check actor rate limit
const actorCheck = await loops.checkActorRateLimit(ctx, {
  actorId: "user123",
  timeWindowMs: 60000, // 1 minute
  maxEmails: 20,
});

// Check global rate limit
const globalCheck = await loops.checkGlobalRateLimit(ctx, {
  timeWindowMs: 60000,
  maxEmails: 1000,
});

Example: Rate-limited email sending

export const sendTransactionalWithRateLimit = action({
  args: {
    transactionalId: v.string(),
    email: v.string(),
    actorId: v.optional(v.string()),
  },
  handler: async (ctx, args) => {
    const identity = await ctx.auth.getUserIdentity();
    if (!identity) throw new Error("Unauthorized");

    const actorId = args.actorId ?? identity.subject;

    // Check rate limit before sending
    const rateLimitCheck = await loops.checkActorRateLimit(ctx, {
      actorId,
      timeWindowMs: 60000, // 1 minute
      maxEmails: 10,
    });

    if (!rateLimitCheck.allowed) {
      throw new Error(
        `Rate limit exceeded. Please try again after ${rateLimitCheck.retryAfter}ms.`
      );
    }

    // Send email
    return await loops.sendTransactional(ctx, {
      ...args,
      actorId,
    });
  },
});

Using the API Helper

The component also exports an api() helper for easier re-exporting:

import { Loops } from "@devwithbobby/loops";
import { components } from "./_generated/api";

const loops = new Loops(components.loops);

// Export all functions at once
export const {
  addContact,
  updateContact,
  sendTransactional,
  sendEvent,
  triggerLoop,
  countContacts,
  listContacts,
  // ... all other functions
} = loops.api();

Security Warning: The api() helper exports functions without authentication. Always wrap these functions with auth checks in production:

export const addContact = action({
  args: { email: v.string(), ... },
  handler: async (ctx, args) => {
    const identity = await ctx.auth.getUserIdentity();
    if (!identity) throw new Error("Unauthorized");

    return await loops.addContact(ctx, args);
  },
});

Security Best Practices

  1. Always add authentication - Wrap all functions with auth checks
  2. Use environment variables - Store API key in Convex environment variables (never hardcode)
  3. Implement rate limiting - Use the built-in rate limiting queries to prevent abuse
  4. Monitor for abuse - Use spam detection queries to identify suspicious patterns
  5. Sanitize errors - Don't expose sensitive error details to clients

Authentication Example

All functions should be wrapped with authentication:

export const addContact = action({
  args: { email: v.string(), ... },
  handler: async (ctx, args) => {
    // Add authentication check
    const identity = await ctx.auth.getUserIdentity();
    if (!identity) throw new Error("Unauthorized");
    
    // Add authorization checks if needed
    // if (!isAdmin(identity)) throw new Error("Forbidden");
    
    return await loops.addContact(ctx, args);
  },
});

Environment Variables

Set LOOPS_API_KEY in your Convex environment:

Via CLI:

npx convex env set LOOPS_API_KEY "your-api-key"

Via Dashboard:

  1. Go to your Convex Dashboard
  2. Navigate to Settings -> Environment Variables
  3. Add LOOPS_API_KEY with your Loops.so API key value

Get your API key from Loops.so Dashboard.

Never pass the API key directly in code or via function options in production. Always use environment variables.

Monitoring & Rate Limiting

The component automatically logs all email operations to the emailOperations table for monitoring. Use the built-in queries to:

  • Track email statistics - See total sends, success/failure rates, breakdowns by type
  • Detect spam patterns - Identify suspicious activity by recipient or actor
  • Enforce rate limits - Prevent abuse with recipient, actor, or global rate limits
  • Monitor for abuse - Detect rapid-fire patterns and unusual sending behavior

All monitoring queries are available through the Loops client - see the Monitoring & Analytics section above for usage examples.

Development

Local Development

To use this component in development with live reloading:

bun run dev:backend

This starts Convex dev with --live-component-sources enabled, allowing changes to be reflected immediately.

Building

npm run build

Testing

npm test

Project Structure

src/
  component/               # The Convex component
    convex.config.ts       # Component configuration
    schema.ts              # Database schema
    lib.ts                 # Component functions
    validators.ts          # Zod validators
    tables/                # Table definitions

  client/                  # Client library
    index.ts               # Loops client class
    types.ts               # TypeScript types

example/                   # Example app
  convex/
    example.ts             # Example usage

API Coverage

This component implements the following Loops.so API endpoints:

  • Create/Update Contact
  • Delete Contact
  • Find Contact
  • Batch Create Contacts
  • Unsubscribe/Resubscribe Contact
  • Count Contacts (custom implementation)
  • List Contacts (custom implementation)
  • Send Transactional Email
  • Send Event
  • Trigger Loop

Contributing

Contributions are welcome! Please open an issue or submit a pull request.

License

Apache-2.0

Resources

版本与发布记录

@devwithbobby/loops 共发布 21 个版本,首次发布于 2025/11/26;过去 12 个月发布了 21 个版本。

版本发布日期距今
0.2.0latest2026/01/209 个月前
0.1.192026/01/209 个月前
0.1.182026/01/129 个月前
0.1.172025/12/0311 个月前
0.1.162025/12/0311 个月前
0.1.152025/12/0311 个月前

关于 @devwithbobby/loops 的常见问题

@devwithbobby/loops 是什么?

Convex component for integrating with Loops.so email marketing platform

如何安装 @devwithbobby/loops?

在项目目录运行 npm install @devwithbobby/loops,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:convex(^1.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@devwithbobby/loops 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@devwithbobby/loops 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@devwithbobby/loops 可以商用吗?

@devwithbobby/loops 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@devwithbobby/loops 的下载量有多少?

根据 npm 官方下载统计,@devwithbobby/loops 在 2026/10/12 – 2026/11/10 这 30 天内被下载 2,838 次,日均约 95 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@devwithbobby/loops 还在维护吗?

最新版本 0.2.0 发布于 2026/01/20(9 个月前);至今共发布 21 个版本,其中过去 12 个月发布了 21 个;首次发布于 2025/11/26。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。