npm package: @giridharan_r/sdk
Description: Deepspot Embedded Analytics SDK — embed dashboards and reports in any website
Latest version: 1.2.7

# @giridharan_r/sdk — Deepspot Embedded Analytics SDK

Embed Deepspot dashboards and reports into **any website or framework** — React, Next.js, Vue, Angular, Svelte, or plain HTML — with a single import or script tag.

- **React & Vue components** — drop-in components with full TypeScript types
- **Next.js ready** — SSR-safe, works with App Router and Pages Router
- **No iframe** — renders directly in your page DOM
- **Self-contained bundle** — ApexCharts, html2canvas, jsPDF all included
- **Lazy loading** — only the active tab's SQL queries execute
- **Row-level security** — pass a `userId` to scope data per end-user

---

## Installation

```bash
npm install @giridharan_r/sdk
# or
pnpm add @giridharan_r/sdk
# or
yarn add @giridharan_r/sdk
```

---

## Quick Start by Framework

### React / Next.js (App Router)

```tsx
// Add 'use client' in your file (Next.js App Router)
'use client'
import { DeepspotDashboard } from '@giridharan_r/sdk/react'

export default function AnalyticsPage() {
  return (
    <DeepspotDashboard
      apiKey="sk_live_b74c55..."
      baseUrl="https://api.deepspot.ai"
      dashboardId="dashboard_123"
      embedLevel="dashboard"
      userId="user_456"
      theme="light"
      height="600px"
      onReady={() => console.log('Dashboard loaded')}
      onFilterChange={(filters) => console.log('Filters changed:', filters)}
      onError={(err) => console.error('Embed error:', err)}
    />
  )
}
```

### Next.js (Pages Router)

```tsx
import dynamic from 'next/dynamic'

// Disable SSR for the dashboard component
const DeepspotDashboard = dynamic(
  () => import('@giridharan_r/sdk/react').then(m => m.DeepspotDashboard),
  { ssr: false }
)

export default function Page() {
  return (
    <DeepspotDashboard
      apiKey={process.env.NEXT_PUBLIC_DEEPSPOT_API_KEY!}
      baseUrl={process.env.NEXT_PUBLIC_DEEPSPOT_BASE_URL!}
      dashboardId={process.env.NEXT_PUBLIC_DEEPSPOT_DASHBOARD_ID!}
      embedLevel="dashboard"
      userId="user_456"
      height="600px"
    />
  )
}
```

### Vue 3 / Nuxt

```vue
<script setup lang="ts">
import { DeepspotDashboard } from '@giridharan_r/sdk/vue'
</script>

<template>
  <DeepspotDashboard
    api-key="sk_live_b74c55..."
    base-url="https://api.deepspot.ai"
    dashboard-id="dashboard_123"
    embed-level="dashboard"
    :user-id="currentUser.id"
    theme="light"
    height="600px"
    @ready="onLoaded"
    @filter-change="onFiltersChanged"
    @error="onError"
  />
</template>
```

### Plain HTML (CDN)

```html
<!-- Load once in <head> -->
<script src="https://unpkg.com/@giridharan_r/sdk@1.2.4/dist/deepspot-sdk.js"></script>

<!-- Place where dashboard should appear -->
<deepspot-dashboard
  dashboard-id="dashboard_123"
  api-key="sk_live_b74c55..."
  base-url="https://api.deepspot.ai"
  user-id="user_456"
  embed-level="dashboard"
  theme="light"
  height="600px"
></deepspot-dashboard>
```

### Angular / Svelte / Vanilla JS

```typescript
import { DeepspotSDK } from '@giridharan_r/sdk'

const sdk = new DeepspotSDK({
  apiKey: 'sk_live_b74c55...',
  baseUrl: 'https://api.deepspot.ai'
})

const dash = await sdk.embedDashboard({
  dashboardId: 'dashboard_123',
  container: document.getElementById('analytics')!,
  userId: currentUser.id,
  theme: 'light',
  height: '600px',
})
```

---

## React Component Props

### `<DeepspotDashboard>`

| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `apiKey` | `string` | ✅ | — | `sk_live_...` key from Embed & Share page |
| `baseUrl` | `string` | ✅ | — | Your Deepspot backend URL |
| `dashboardId` | `string` | ✅ | — | Dashboard ID from Deepspot |
| `embedLevel` | `string` | No | `dashboard` | `dashboard` / `page` / `tab` / `report` |
| `userId` | `string` | No | `""` | End-user ID for row-level security |
| `tenantId` | `string` | No | — | Tenant ID for multi-tenant apps |
| `pageId` | `string` | No | first page | Starting page ID |
| `tabId` | `string` | No | first tab | Starting tab ID |
| `theme` | `string` | No | `light` | `light` or `dark` |
| `height` | `string` | No | `600px` | CSS height (e.g. `800px`, `100vh`) |
| `hideFilters` | `boolean` | No | `false` | Hide the filter bar |
| `hideExport` | `boolean` | No | `false` | Hide export buttons |
| `filters` | `object` | No | `{}` | Initial filter values |
| `className` | `string` | No | — | CSS class for the wrapper div |
| `style` | `CSSProperties` | No | — | Inline styles for the wrapper div |
| `loadingNode` | `ReactElement` | No | built-in spinner | Custom loading indicator |
| `onReady` | `() => void` | No | — | Fires when dashboard finishes loading |
| `onFilterChange` | `(filters) => void` | No | — | Fires when user changes a filter |
| `onTabSwitch` | `(pageId, tabId) => void` | No | — | Fires when user switches tab |
| `onError` | `(message) => void` | No | — | Fires on any load error |

### `<DeepspotReport>` (Single Component)

Same as above, but instead of `embedLevel/pageId/tabId` you pass:

| Prop | Type | Required | Description |
|---|---|---|---|
| `componentId` | `string` | ✅ | ID of the specific chart / table / KPI to embed |

---

## Vue Component Props

Same props as React but in kebab-case (`dashboard-id`, `api-key`, etc.).

Events emitted: `@ready`, `@filter-change`, `@tab-switch`, `@error`

---

## HTML Web Component Attributes

### `<deepspot-dashboard>`

| Attribute | Required | Default | Description |
|---|---|---|---|
| `dashboard-id` | ✅ | — | Dashboard ID |
| `api-key` | ✅ | — | `sk_live_...` key |
| `base-url` | ✅ | — | Backend URL |
| `user-id` | No | `""` | End-user ID |
| `embed-level` | No | `dashboard` | `dashboard` / `page` / `tab` / `report` |
| `page-id` | No | first page | Starting page |
| `tab-id` | No | first tab | Starting tab |
| `theme` | No | `light` | `light` or `dark` |
| `height` | No | `600px` | CSS height |
| `hide-filters` | No | `false` | Hide filter bar |
| `hide-export` | No | `false` | Hide export buttons |

### `<deepspot-report>`

| Attribute | Required | Description |
|---|---|---|
| `dashboard-id` | ✅ | Dashboard that owns this component |
| `component-id` | ✅ | ID of the specific component |
| `api-key` | ✅ | API key |
| `base-url` | ✅ | Backend URL |
| `user-id` | No | End-user ID |
| `theme` | No | `light` or `dark` |
| `height` | No | CSS height |

---

## JavaScript API (Programmatic Control)

```typescript
import { DeepspotSDK } from '@giridharan_r/sdk'

const sdk = new DeepspotSDK({
  apiKey: 'sk_live_b74c55...',
  baseUrl: 'https://api.deepspot.ai'
})

// Embed dashboard → returns EmbedInstance
const dash = await sdk.embedDashboard({
  dashboardId: 'dashboard_123',
  container: '#analytics-section',   // string selector or HTMLElement
  userId: currentUser.id,
  theme: 'dark',
  filters: { region: 'US' },
  onReady: () => console.log('ready'),
  onFilterChange: (f) => console.log(f),
})

// Embed single chart / KPI card
const report = await sdk.embedReport({
  dashboardId: 'dashboard_123',
  componentId: 'comp_revenue_chart',
  container: '#revenue-widget',
  userId: currentUser.id,
})

// Control the embed
dash.setFilter('region', 'EU')          // apply a filter → data re-fetches
dash.setFilters({ region: 'EU', year: '2024' })  // apply multiple at once
dash.goToPage('page_2')                 // switch page
dash.goToTab('page_2', 'tab_q1')        // switch to specific tab
dash.refresh()                          // force re-fetch current tab
dash.exportPDF()                        // download as PDF
dash.destroy()                          // remove from DOM and clean up
```

---

## Embed Levels

| Level | What renders | Navigation |
|---|---|---|
| `report` | 1 chart / table / KPI card | None |
| `tab` | All components on 1 tab | None |
| `page` | All tabs on 1 page | Tab switcher only |
| `dashboard` | Full dashboard, all pages | Page nav + Tab switcher |

All levels lazy-load — other tabs only run SQL when the user clicks them.

---

## Supported Component Types

| Type | Renders as |
|---|---|
| `bar` | Bar chart |
| `line` | Line chart |
| `area` | Area chart |
| `pie` | Pie chart |
| `donut` | Donut chart |
| `table` | HTML data table |
| `number-card` | KPI / metric card |
| `filter` | Dropdown / date-range / multi-select filter |
| `text` | Static text block |

---

## Environment Variables (Next.js)

```env
# .env.local
NEXT_PUBLIC_DEEPSPOT_API_KEY=sk_live_b74c55...
NEXT_PUBLIC_DEEPSPOT_BASE_URL=https://api.deepspot.ai
NEXT_PUBLIC_DEEPSPOT_DASHBOARD_ID=dashboard_123
NEXT_PUBLIC_DEEPSPOT_EMBED_LEVEL=dashboard
NEXT_PUBLIC_DEEPSPOT_THEME=light
NEXT_PUBLIC_DEEPSPOT_HEIGHT=600px
```

---

## Security

### Auth flow

```
Your website
  │  POST /embed-token  { apiKey, dashboardId, userId }
  ▼
Deepspot Backend → short-lived JWT (1 hour TTL)
  │
  │  GET /embed/:id/render  { x-embed-token: JWT }
  ▼
SQL executes server-side → pre-computed rows returned
(No SQL, no DB credentials ever reach the browser)
```

### Production best practice

Keep `apiKey` out of public HTML. Your backend exchanges it for a short-lived token:

```typescript
// YOUR backend endpoint (e.g. /api/embed-token)
const response = await fetch(`${DEEPSPOT_URL}/dashboard-builder/embed-token`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'x-deepspot-api-key': process.env.DEEPSPOT_API_KEY,  // server-side only
  },
  body: JSON.stringify({ dashboardId, embedType: 'dashboard', userId }),
})
const { data: { token } } = await response.json()
// Return token to your frontend (token expires in 1 hour)
```

---

## Get Your API Key

1. Open the Deepspot Dashboard Builder
2. Go to **Publish → Embed & Share**
3. Click **Generate Key**
4. Copy the `sk_live_...` key — it is scoped to that specific dashboard

---

## Building from Source

```bash
git clone https://github.com/Deepspot-AI/Gen-Ai-fe-client.git
cd Gen-Ai-fe-client/packages/deepspot-sdk

pnpm install

# Build main SDK bundle (UMD + ESM)
pnpm build:sdk

# Build React + Vue framework wrappers
pnpm build:frameworks

# Build everything
pnpm build

# Watch mode
pnpm dev
```

**Output:**
```
dist/
  deepspot-sdk.js        ← UMD  (CDN / <script> tag)
  deepspot-sdk.esm.js    ← ESM  (bundler / import)
  index.d.ts             ← TypeScript declarations
  react/
    index.mjs / .cjs / .d.ts
  vue/
    index.mjs / .cjs / .d.ts
```

---

## License

MIT