Metadata-Version: 2.4
Name: trimlynk
Version: 1.1.0
Summary: Official Python SDK for the TrimLynk Developer API v1
Author: Vivek Gaur, Ashish Kumar Dwivedi, TrimLynk
Author-email: support@trimlynk.com
Maintainer: Vivek Gaur, Ashish Kumar Dwivedi
Maintainer-email: support@trimlynk.com
License-Expression: LicenseRef-Proprietary
Project-URL: Homepage, https://trimlynk.com
Project-URL: Documentation, https://trimlynk.com/developers/sdks
Project-URL: Developers Hub, https://trimlynk.com/developers
Project-URL: API Reference, https://trimlynk.com/api-docs
Project-URL: Webhooks Guide, https://trimlynk.com/developers/webhooks
Project-URL: PyPI Package, https://pypi.org/project/trimlynk/
Project-URL: Source Code, https://github.com/Anky9972/urlshortner
Project-URL: Bug Tracker, https://github.com/Anky9972/urlshortner/issues
Project-URL: Support, https://trimlynk.com/contact
Project-URL: Terms of Service, https://trimlynk.com/terms
Project-URL: Privacy Policy, https://trimlynk.com/privacy
Keywords: trimlynk,url-shortener,link-shortener,link-management,qr-code-generator,analytics,webhooks,webhook-tunneling,attribution,developer-api,fastapi,async,cli,pandas
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest>=8.4.0; extra == "dev"
Requires-Dist: pytest-cov>=5.0.0; extra == "dev"
Requires-Dist: pip-audit>=2.8.0; extra == "dev"
Provides-Extra: keyring
Requires-Dist: keyring>=25.0.0; extra == "keyring"
Provides-Extra: data
Requires-Dist: pandas>=2.0.0; extra == "data"
Dynamic: license-file

# TrimLynk Official Python SDK & CLI

The official Python client library and CLI for the **TrimLynk Developer API v1**.

TrimLynk is a modern, privacy-first URL shortening, link intelligence, and attribution platform. This SDK provides complete programmatic access to link creation, analytics telemetry, conversion funnel tracking, marketing campaigns, real-time webhook management, and zero-config local webhook tunneling.

[![Python Version](https://img.shields.io/badge/python-3.9+-blue.svg)](https://python.org)
[![PyPI version](https://img.shields.io/badge/pypi-1.1.0-brightgreen.svg)](https://pypi.org/project/trimlynk/)
[![License: Proprietary](https://img.shields.io/badge/license-Proprietary-red.svg)](https://trimlynk.com/terms)

---

### Official Platform & Documentation Links

| Resource | Official URL | Purpose |
| :--- | :--- | :--- |
| 🌐 **TrimLynk Platform** | [https://trimlynk.com](https://trimlynk.com) | Main dashboard, branded domains, and analytics |
| 📚 **SDK Documentation** | [https://trimlynk.com/developers/sdks](https://trimlynk.com/developers/sdks) | In-depth Python SDK & client library guides |
| 🚀 **Developers Hub** | [https://trimlynk.com/developers](https://trimlynk.com/developers) | API keys, telemetry, rate limits, and quickstarts |
| ⚡ **Webhooks & Events** | [https://trimlynk.com/developers/webhooks](https://trimlynk.com/developers/webhooks) | HMAC-SHA256 signature verification & event schema |
| 📖 **OpenAPI 3.1 Reference** | [https://trimlynk.com/api-docs](https://trimlynk.com/api-docs) | Interactive endpoint explorer & JSON spec |
| 📦 **PyPI Registry** | [https://pypi.org/project/trimlynk/](https://pypi.org/project/trimlynk/) | Official package release & installation |
| 🛡️ **Terms & Privacy** | [Terms of Service](https://trimlynk.com/terms) · [Privacy Policy](https://trimlynk.com/privacy) | Data protection & compliance policies |

---

## Highlights

* **Zero Mandatory Dependencies**: Implemented using the Python standard library. No bloated dependency trees or supply-chain vulnerabilities.
* **Native Async Support (`AsyncTrimLynk`)**: Native `async/await` client and `AsyncAutoPagingIterator` for FastAPI, asyncio bots, and async microservices.
* **CLI with Local Webhook Tunneling (`trimlynk webhooks listen`)**: Auto-detects local tunnels (ngrok) and streams/forwards events in real-time, just like `stripe listen`.
* **QR Code Exporter (`link.save_qr()`)**: Decode and save Base64 PNG/SVG/binary QR codes directly to disk with a single call.
* **Pandas / Data Science Export (`analytics.to_dataframe()`)**: Export analytics breakdowns (`devices`, `countries`, `referrers`) directly into Pandas DataFrames (`pip install trimlynk[data]`).
* **Stripe-Style Webhooks (`construct_event`)**: 1-line HMAC-SHA256 signature verification with typed `WebhookEvent` models (`event.is_click`, `event.revenue`, `event.url_id`).
* **Concurrent Batch Creation (`links.create_many()`)**: High-throughput multi-threaded and asynchronous batch creation.
* **Built-in UTM Campaign Engine**: Build query parameters automatically with `auto_decorate_utm=True`.
* **Forgiving Parameter Aliases**: Accepts `slug` for `custom_slug`, `link_id` for `url_id`, `revenue` for `event_value`, and native Python `date`/`datetime` objects.
* **Production-Grade Idempotency**: Safe mutations with `idempotency_key` on link, campaign, and webhook operations.

---

## Installation

```bash
# Standard zero-dependency installation
pip install trimlynk

# With optional Pandas data science export support
pip install trimlynk[data]

# With secure system credential keychain storage for the CLI
pip install trimlynk[keyring]
```

Installing the package automatically exposes both the Python SDK and the `trimlynk` CLI executable.

---

## Quickstart

### 1. Synchronous Client

```python
from trimlynk import TrimLynk

# 1. Initialize client (reads TRIMLYNK_API_KEY environment variable if omitted)
client = TrimLynk(api_key="tl_live_your_api_key_here")

# 2. Create a shortened link with UTM parameters
link = client.links.create(
    original_url="https://example.com/summer-promo",
    slug="summer-deal",
    title="Summer Promo 2026",
    tags=["summer", "promo"],
    utm_source="newsletter",
    utm_medium="email",
    utm_campaign="summer_launch",
    auto_decorate_utm=True,
)

print(f"Short URL: {link.short_url}")
print(f"QR Code URL: {link.qr_code}")

# 3. Export QR code image to disk
link.save_qr("assets/qr_code.png")
```

---

### 2. Asynchronous Client (`AsyncTrimLynk`)

Designed specifically for **FastAPI**, **Aiohttp**, Discord/Telegram bots, and asynchronous background tasks:

```python
import asyncio
from trimlynk import AsyncTrimLynk

async def main():
    async with AsyncTrimLynk(api_key="tl_live_xxx") as client:
        # Create a link asynchronously
        link = await client.links.create(
            original_url="https://example.com/product",
            slug="fast-deal",
        )
        print("Created:", link.short_url)

        # Batch create concurrently with bounded concurrency
        links = await client.links.create_many([
            {"original_url": "https://example.com/1", "slug": "item-1"},
            {"original_url": "https://example.com/2", "slug": "item-2"},
        ], concurrency=5)

        # Asynchronously stream through all links
        async for item in client.links.iter(limit=50):
            print(item.short_code, item.clicks)

asyncio.run(main())
```

---

## Features & Resources

### 1. QR Code Exporter
Save decoded Base64 PNG, SVG markup, or remote images directly to a local file:

```python
# Direct from Link object:
link = client.links.get("url_abc123")
path = link.save_qr("images/deal_qr.png")

# Or fetch and save in one step:
client.links.download_qr("url_abc123", "images/deal_qr.png")

# Async version:
await async_client.links.download_qr("url_abc123", "images/deal_qr.png")
```

---

### 2. Pandas / Data Science Export
Export telemetry breakdowns into Pandas DataFrames for Jupyter notebooks and BI pipelines:

```python
summary = client.analytics.get()

# Export specific breakdown
devices_df = summary.to_dataframe("devices")      # columns: ['device', 'clicks']
countries_df = summary.to_dataframe("countries")  # columns: ['country', 'clicks']
referrers_df = summary.to_dataframe("referrers")  # columns: ['referrer', 'clicks']

# Or export all tables into a dictionary:
dataframes = summary.to_dataframe("all")
print(dataframes["devices"].head())

# Export a paginated list of links directly:
links_df = client.links.list().to_dataframe()
```

---

### 3. Stripe-Style Webhook Ingestion & Verification
Verify HMAC-SHA256 signatures and deserialize events into typed `WebhookEvent` models:

```python
from fastapi import FastAPI, Request, HTTPException
from trimlynk import TrimLynk, SignatureVerificationError

app = FastAPI()
client = TrimLynk()

@app.post("/api/webhooks")
async def handle_webhook(request: Request):
    raw_payload = await request.body()
    signature_header = request.headers.get("x-trimlynk-signature")

    try:
        # 1-step verification and typed parsing
        event = client.webhooks.construct_event(
            raw_payload=raw_payload,
            signature_header=signature_header,
            secret="whsec_your_signing_secret",
            tolerance_seconds=300,
        )
    except SignatureVerificationError as e:
        raise HTTPException(status_code=400, detail=str(e))

    # Inspect event using convenient property helpers
    if event.is_click:
        print(f"Click on {event.short_url} from {event.channel}")
    elif event.is_conversion:
        print(f"Conversion {event.event_name} recorded! Revenue: ${event.revenue}")

    return {"status": "success"}
```

---

### 4. Conversions & Attribution Tracking

```python
# Record a customer conversion (supports revenue or event_value alias)
conv = client.conversions.create(
    link_id="url_abc123",
    event_name="checkout_completed",
    revenue=129.50,
    customer_email="buyer@example.com",
    order_id="ord_9981",
)

# Conversion funnel analytics (Click -> Lead -> Sale)
funnel = client.analytics.conversions(link_id="url_abc123")
print("Attributed Revenue:", funnel.revenue)
```

---

### 5. Automatic Pagination

Iterate seamlessly across thousands of records without manual cursor handling:

```python
# Sync iteration
for link in client.links.iter(limit=100, tag="promo"):
    print(link.short_url, link.clicks)

# Async iteration
async for webhook in async_client.webhooks.iter():
    print(webhook.url)
```

---

## Command Line Interface (CLI)

The `trimlynk` CLI is automatically installed with the package.

### Local Webhook Tunneling (`trimlynk webhooks listen`)
Stream incoming live webhooks to your local machine and forward to your local app (auto-discovers local ngrok):

```powershell
# 1. Listen and forward live events to your local server
trimlynk webhooks listen --forward-to http://localhost:8000/api/webhooks

# 2. Filter for specific event types
trimlynk webhooks listen --event click.created --event conversion.created

# 3. Explicit tunnel override
trimlynk webhooks listen --tunnel-url https://my-domain.ngrok-free.dev
```

### General CLI Commands

```powershell
# Authentication & Status
trimlynk auth login
trimlynk auth status

# Links Management
trimlynk links create https://example.com --slug deal26 --tag promo
trimlynk links list --limit 20
trimlynk links get deal26
trimlynk links update deal26 --title "Spring Sale"
trimlynk links delete deal26 --yes

# Analytics
trimlynk analytics summary
trimlynk analytics link deal26

# Webhooks CRUD
trimlynk webhooks list
trimlynk webhooks test <webhook_id>
trimlynk webhooks deliveries <webhook_id>
```

---

## Error Handling

The SDK maps all HTTP and network errors into a typed exception hierarchy:

```text
TrimLynkError
├── APIError
│   ├── InvalidRequestError       (HTTP 400)
│   ├── AuthenticationError       (HTTP 401)
│   ├── PermissionError           (HTTP 403)
│   ├── NotFoundError             (HTTP 404)
│   ├── ConflictError             (HTTP 409)
│   │   └── IdempotencyConflictError
│   ├── RateLimitError            (HTTP 429)
│   └── InternalServerError       (HTTP 500)
├── SignatureVerificationError
│   ├── SignatureExpiredError
│   ├── SignatureMismatchError
│   └── InvalidSignatureHeaderError
├── NetworkError
└── TimeoutError
```

---

## Documentation & Community Resources

* **Documentation Portal**: [https://trimlynk.com/developers/sdks](https://trimlynk.com/developers/sdks)
* **Webhooks Guide**: [https://trimlynk.com/developers/webhooks](https://trimlynk.com/developers/webhooks)
* **API Reference**: [https://trimlynk.com/api-docs](https://trimlynk.com/api-docs)
* **Source Repository**: [https://github.com/Anky9972/urlshortner](https://github.com/Anky9972/urlshortner)
* **Issue Tracker**: [https://github.com/Anky9972/urlshortner/issues](https://github.com/Anky9972/urlshortner/issues)
* **Customer Support**: [support@trimlynk.com](mailto:support@trimlynk.com) or [https://trimlynk.com/contact](https://trimlynk.com/contact)

---

## License

Proprietary License (All Rights Reserved). Licensed under the TrimLynk Software License Agreement. For complete terms of service and acceptable use policies, please visit [TrimLynk Terms of Service](https://trimlynk.com/terms) and [Privacy Policy](https://trimlynk.com/privacy).
