npm package: @kifiya/datasource-config-ui
Description: Data Source Configuration UI - A reusable React component library for managing data sources
Author: Kifiya
Latest version: 0.3.1

# @kifiya/datasource-config-ui

A reusable React micro-frontend component library for managing data source configurations. This package provides a complete UI for configuring data source types and their sources (database or API), designed to work with the [Data Source Service](https://github.com/kifiya/data-source-service).

## Features

- 📦 **Data Source Types Management** - Create, edit, and delete data source types with custom fields and parameters
- 🔌 **Multiple Source Support** - Configure database (PostgreSQL, MongoDB) and API sources
- 🔄 **Active Source Management** - Activate/deactivate sources per data source type
- 🎨 **Modern UI** - Built with Tailwind CSS and Radix UI primitives
- 🔧 **Direct API Communication** - Connects directly to the Data Source Service
- 🔑 **API Key Authentication** - Secure communication with X-API-Key header
- 📱 **Responsive Design** - Works on desktop and mobile
- 🎯 **TypeScript First** - Full TypeScript support with exported types

## Installation

```bash
npm install @kifiya/datasource-config-ui
# or
yarn add @kifiya/datasource-config-ui
# or
pnpm add @kifiya/datasource-config-ui
```

## Peer Dependencies

This package requires the following peer dependencies:

```bash
npm install react react-dom @tanstack/react-query tailwindcss
```

## Quick Start

### 1. Set up environment variables

Create a `.env.local` file in your project root:

```env
NEXT_PUBLIC_DATA_SOURCE_SERVICE_URL=http://localhost:8001
NEXT_PUBLIC_DATA_SOURCE_API_KEY=your-api-key-here
```

### 2. Wrap your app with the provider

```tsx
"use client";

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import {
  DataSourceProvider,
  DataSourcesPage,
} from "@kifiya/datasource-config-ui";

const queryClient = new QueryClient();

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <DataSourceProvider
        baseUrl={
          process.env.NEXT_PUBLIC_DATA_SOURCE_SERVICE_URL ||
          "http://localhost:8001"
        }
        apiKey={process.env.NEXT_PUBLIC_DATA_SOURCE_API_KEY}
      >
        <DataSourcesPage />
      </DataSourceProvider>
    </QueryClientProvider>
  );
}
```

### 3. Configure Tailwind CSS

Add the package to your Tailwind content paths:

```js
// tailwind.config.js
module.exports = {
  content: [
    // ... your paths
    "./node_modules/@kifiya/datasource-config-ui/dist/**/*.{js,mjs}",
  ],
  // ... rest of config
};
```

## Next.js Usage

For Next.js applications, use client-side rendering to avoid SSR issues with React Query:

```tsx
// app/data-sources/page.tsx
"use client";

import { useState, useEffect } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import {
  DataSourceProvider,
  DataSourcesPage,
} from "@kifiya/datasource-config-ui";

const queryClient = new QueryClient();

export default function DataSourcesPageWrapper() {
  const [isMounted, setIsMounted] = useState(false);

  useEffect(() => {
    setIsMounted(true);
  }, []);

  if (!isMounted) {
    return <div>Loading...</div>;
  }

  return (
    <QueryClientProvider client={queryClient}>
      <DataSourceProvider
        baseUrl={
          process.env.NEXT_PUBLIC_DATA_SOURCE_SERVICE_URL ||
          "http://localhost:8001"
        }
        apiKey={process.env.NEXT_PUBLIC_DATA_SOURCE_API_KEY}
      >
        <DataSourcesPage />
      </DataSourceProvider>
    </QueryClientProvider>
  );
}
```

## Components

### DataSourcesPage

The main page component that displays the complete data sources management UI.

```tsx
import { DataSourcesPage } from "@kifiya/datasource-config-ui";

<DataSourcesPage
  title="Data Sources" // Optional: custom title
  description="Configure your data sources" // Optional: custom description
  className="my-custom-class" // Optional: additional CSS classes
/>;
```

### Individual Components

You can also use individual components for custom layouts:

```tsx
import {
  DataSourceTypesTab,
  SourcesTab,
  AddDataSourceTypeDialog,
  AddSourceDialog,
  EditDataSourceTypeDialog,
  EditSourceDialog,
  DataSourceTypeDetailsDialog,
  SourceDetailsDialog,
} from "@kifiya/datasource-config-ui";
```

## Hooks

The package exports React Query hooks for data fetching:

```tsx
import {
  // Data Source Types
  useDataSourceTypes,
  useDataSourceType,
  useCreateDataSourceType,
  useUpdateDataSourceType,
  useDeleteDataSourceType,

  // Sources
  useSources,
  useSource,
  useSourcesByDataSourceType,
  useCreateSource,
  useUpdateSource,
  useDeleteSource,
  useActivateSource,
  useDeactivateSource,
  useTestSource,

  // Health
  useDataSourceHealth,
} from "@kifiya/datasource-config-ui";
```

## Provider Props

| Prop      | Type     | Required | Description                                                                          |
| --------- | -------- | -------- | ------------------------------------------------------------------------------------ |
| `baseUrl` | `string` | Yes      | Base URL of the Data Source Service (e.g., `http://localhost:8001`)                  |
| `apiKey`  | `string` | No       | API key for authenticating with the Data Source Service. Sent as `X-API-Key` header. |

## Data Source Service Requirements

This package communicates directly with the Data Source Service and expects the following:

### API Endpoints

| Method   | Endpoint                    | Description                    |
| -------- | --------------------------- | ------------------------------ |
| `GET`    | `/health`                   | Health check                   |
| `GET`    | `/data-source-types`        | List all data source types     |
| `POST`   | `/data-source-types`        | Create a data source type      |
| `GET`    | `/data-source-types/{name}` | Get a data source type by name |
| `PUT`    | `/data-source-types/{name}` | Update a data source type      |
| `DELETE` | `/data-source-types/{name}` | Delete a data source type      |
| `GET`    | `/sources`                  | List all sources               |
| `POST`   | `/sources`                  | Create a source                |
| `GET`    | `/sources/{id}`             | Get a source by ID             |
| `PUT`    | `/sources/{id}`             | Update a source                |
| `DELETE` | `/sources/{id}`             | Delete a source                |
| `POST`   | `/sources/{id}/activate`    | Activate a source              |
| `POST`   | `/sources/{id}/deactivate`  | Deactivate a source            |
| `POST`   | `/sources/test`             | Test a source configuration    |

### CORS Configuration

Since this package communicates directly from the browser, CORS must be configured on your Data Source Service:

```python
from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000"],  # Your frontend URL(s)
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],  # Must include X-API-Key
)
```

### API Key Authentication

If using API key authentication, ensure your middleware skips CORS preflight `OPTIONS` requests:

```python
class APIKeyAuthMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        # Skip authentication for CORS preflight requests
        if request.method == "OPTIONS":
            return await call_next(request)

        # ... rest of authentication logic
```

## TypeScript Support

Full TypeScript support with exported types:

```tsx
import type {
  // Data Source Types
  DataSourceType,
  DataSourceTypeCreate,
  DataSourceTypeUpdate,

  // Sources
  Source,
  SourceCreate,
  SourceUpdate,
  SourceType,

  // Field Mappings & Parameters
  FieldMapping,
  ParameterDefinition,
  ParameterType,

  // Health
  HealthStatus,

  // Configuration
  DataSourceConfig,
} from "@kifiya/datasource-config-ui";
```

## Environment Variables

| Variable                              | Description                    | Example                 |
| ------------------------------------- | ------------------------------ | ----------------------- |
| `NEXT_PUBLIC_DATA_SOURCE_SERVICE_URL` | URL of the Data Source Service | `http://localhost:8001` |
| `NEXT_PUBLIC_DATA_SOURCE_API_KEY`     | API key for authentication     | `dev-api-key-123`       |

## Security Considerations

⚠️ **Important**: This package sends the API key directly from the browser. Consider the following:

1. **Development**: Use a development-only API key
2. **Production**:
   - Use environment-specific API keys
   - Consider using a backend proxy for sensitive environments
   - Restrict CORS origins to your specific domains
   - Use short-lived or rotatable API keys

## License

MIT © [Kifiya](https://github.com/kifiya)