npm package: @mailiam/client
Description: Official browser client for Mailiam - client-safe form submissions
Author: Mailiam
Latest version: 0.2.0

# @mailiam/client

Official browser client for [Mailiam](https://mailiam.io) - Client-safe form submissions.

## Installation

```bash
npm install @mailiam/client
```

## Quick Start

```typescript
import { MailiamClient } from '@mailiam/client';

const client = new MailiamClient({
  publicKey: 'mlm_pk_...' // Optional but recommended
});

// Submit a form
await client.submitForm('mycompany.com', {
  name: 'John Doe',
  email: 'john@example.com',
  message: 'Hello!'
});
```

## Features

- ✅ **Browser-Safe** - No server-side secrets exposed
- ✅ **TypeScript Support** - Full type safety
- ✅ **Lightweight** - Minimal bundle size
- ✅ **CORS-Friendly** - Works from any domain
- ✅ **Public Key Support** - Optional public keys for rate limit benefits

## Usage

### Get a Public Key (Optional)

```bash
# Install Mailiam CLI
npm install -g mailiam

# Create a public key (client-safe)
mailiam keys create --name "Website Forms" --type public --domain mycompany.com
```

### Submit to Domain-Based Form

```typescript
import { MailiamClient } from '@mailiam/client';

const client = new MailiamClient({
  publicKey: 'mlm_pk_...' // Optional
});

try {
  await client.submitForm('mycompany.com', {
    name: 'John Doe',
    email: 'john@example.com',
    message: 'Hello from the contact form!',
    // Any additional fields
    phone: '555-0123'
  });

  console.log('Form submitted successfully!');
} catch (error) {
  console.error('Submission failed:', error.message);
}
```

### Submit to Instant Form

```typescript
// Instant forms don't require authentication
await client.submitInstantForm('form_abc123', {
  name: 'Jane Doe',
  email: 'jane@example.com',
  message: 'Quick message'
});
```

### Vanilla JavaScript Example

```html
<!DOCTYPE html>
<html>
<body>
  <form id="contactForm">
    <input name="name" required>
    <input name="email" type="email" required>
    <textarea name="message" required></textarea>
    <button type="submit">Send</button>
  </form>

  <script type="module">
    import { MailiamClient } from 'https://esm.sh/@mailiam/client';

    const client = new MailiamClient();
    const form = document.getElementById('contactForm');

    form.addEventListener('submit', async (e) => {
      e.preventDefault();
      const formData = new FormData(form);
      const data = Object.fromEntries(formData.entries());

      try {
        await client.submitForm('mycompany.com', data);
        alert('Thanks for your message!');
        form.reset();
      } catch (error) {
        alert('Failed to send: ' + error.message);
      }
    });
  </script>
</body>
</html>
```

### React Example

```tsx
import { MailiamClient } from '@mailiam/client';
import { useState } from 'react';

const client = new MailiamClient({
  publicKey: process.env.NEXT_PUBLIC_MAILIAM_PUBLIC_KEY
});

export function ContactForm() {
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState('');

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setLoading(true);

    const formData = new FormData(e.currentTarget);
    const data = Object.fromEntries(formData.entries());

    try {
      await client.submitForm('mycompany.com', data);
      setMessage('Thanks! We\'ll be in touch.');
      e.currentTarget.reset();
    } catch (error) {
      setMessage('Failed to send. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input name="name" required />
      <input name="email" type="email" required />
      <textarea name="message" required />
      <button disabled={loading}>
        {loading ? 'Sending...' : 'Send'}
      </button>
      {message && <p>{message}</p>}
    </form>
  );
}
```

## Configuration Options

```typescript
const client = new MailiamClient({
  publicKey: 'mlm_pk_...', // Optional: Public API key
  baseUrl: 'https://api.mailiam.dev', // Optional: Custom API URL
  timeout: 30000 // Optional: Request timeout in ms (default: 30000)
});
```

## Error Handling

```typescript
import { MailiamClient, ValidationError, NetworkError, ApiError } from '@mailiam/client';

try {
  await client.submitForm('mycompany.com', data);
} catch (error) {
  if (error instanceof ValidationError) {
    // Invalid form data
  } else if (error instanceof NetworkError) {
    // Network/timeout error
  } else if (error instanceof ApiError) {
    // API error
    console.log('Status:', error.statusCode);
  }
}
```

## Public Keys vs No Authentication

- **Without a public key**: Forms still work! Anyone can submit to your domain-based or instant forms.
- **With a public key**: You get higher rate limits and better analytics.

Public keys are safe to expose in client-side code (`mlm_pk_*` prefix).

## Examples

See the [examples directory](../../examples) for more detailed examples:

- **Browser Form** - Vanilla HTML/JS contact form
- **React Form** - React component example

## Requirements

- Modern browser with fetch support
- Or Node.js 16+ (though @mailiam/node is recommended for server-side)

## License

MIT

## Support

- Documentation: https://mailiam.io/docs
- Issues: https://github.com/mailiam/mailiam/issues
- Email: team@mailiam.dev