# 🔌 ibl.ai API Client – TypeScript SDK Powered by OpenAPI

Welcome to the official API client for the **ibl.ai platform**, auto-generated from our OpenAPI schema and wrapped with love 💙.

This SDK allows you to easily communicate with the Ibl API from both frontend and backend environments. It supports:

- ✅ Native ESM usage via NPM
- ✅ UMD usage via CDN (e.g. S3 or CloudFront)
- ✅ Tree-shakable & type-safe
- ✅ Works with fetch, React, Redux RTK Query, and more

---

## 📦 Installation

### Option 1: Use via NPM (ESM)

Install the package from the registry:

```bash
npm install @iblai/ibl-api
```

### Option 2: Use via `script` tag (UMD)

If you're not using a bundler, you can load the SDK directly from S3/CDN:

```bash
<script src="https://cdn.iblai.com/ibl-api/1.0.0/index.umd.js"></script>

```

This exposes a global `IblApi` object you can use anywhere:

```bash
<script>
  IblApi.OpenAPI.BASE = 'https://api.iblai.com';
  IblApi.UserService.getCurrentUser().then(console.log);
</script>
```

## 🔧 Configuration

The SDK provides a flexible OpenAPI config object to set:

- Base URL
- Authorization token
- Custom headers

### Using NPM (ESM)

```ts
// src/lib/api.ts
import { OpenAPI } from "@iblai/ibl-api";

OpenAPI.BASE =
  process.env.REACT_APP_API_DM_URL || "https://base.manager.iblai.app";
OpenAPI.TOKEN = async () => {
  return localStorage.getItem("dm_token");
};
OpenAPI.HEADERS = {
  Authorization: `Token ${localStorage.getItem("dm_token")}`,
};
```

## Using UMD (CDN)

```html
<script>
  IblApi.OpenAPI.BASE = "https://base.manager.iblai.com";
  OpenAPI.HEADERS = {
    Authorization: `Token ${localStorage.getIte("dm_token")`,
  };
</script>
```

# 💡 Quick Examples

### 1. Fetch a User (ESM)

```ts
import { EngagementService } from "@iblai/ibl-api";

const courseCompletionPerCourse =
  await EngagementService.engagementOrgsCourseCompletionPerCourseRetrieve(
    "main"
  );
console.log(courseCompletionPerCourse);
```

### 2. Vanilla JS (CDN/UMD)

```html
<script>
  IblApi.EngagementService.engagementOrgsCourseCompletionPerCourseRetrieve(
    "main"
  ).then((courseCompletionPerCourse) => {
    console.log(courseCompletionPerCourse);
  });
</script>
```

# ⚛️ Usage in React

```tsx
import React, { useEffect, useState } from "react";
import { UserService, User } from "@iblai/ibl-api";

export const UserProfile = () => {
  const [courseCompletionPerCourse, setCourseCompletionPerCourse] =
    useState<CourseCompletionPerCourse | null>(null);

  useEffect(() => {
    EngagementService.engagementOrgsCourseCompletionPerCourseRetrieve().then(
      setCourseCompletionPerCourse
    );
  }, []);

  return <div></div>;
};
```

# 🧠 Using with Redux RTK Query

### Step 1: Create API Slice

```ts
// src/store/iblApiSlice.ts
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import { EngagementService } from "@iblai/ibl-api"; // Adjust the import based on your service

export const api = createApi({
  reducerPath: "iblApi",
  baseQuery: fetchBaseQuery({
    baseUrl: process.env.REACT_APP_IBL_DM_URL,
  }),
  endpoints: (builder) => ({
    engagementOrgsCourseCompletionPerCourseRetrieve: builder.query<any, void>({
      queryFn: async () => {
        try {
          const response =
            await EngagementService.engagementOrgsCourseCompletionPerCourseRetrieve(
              "main"
            );
          return { data: response };
        } catch (error) {
          return { error: error.message };
        }
      },
    }),
  }),
});

export const { useEngagementOrgsCourseCompletionPerCourseRetrieve } = api;
```

### Step 2: Use in Component

```ts
const Profile = () => {
  const { data, isLoading } =
    useEngagementOrgsCourseCompletionPerCourseRetrieve();

  if (isLoading) return <p>Loading...</p>;
  return <p>Hello, {data?.name}!</p>;
};
```

## ☁️ Deployment on Vercel

When using the NPM version on Vercel:

1. Set environment variable in your dashboard:

   REACT_APP_API_BASE_URL=https://base.manager.iblai.com

2. Reference it in your OpenAPI.ts config.

3. Don’t forget to trigger a redeploy after updating env vars.

## 🧪 Testing

You can mock service methods easily:

```ts
jest
  .spyOn(EngagementService, "engagementOrgsCourseCompletionPerCourseRetrieve")
  .mockResolvedValue({
    data: [],
  });
```

Or use MSW (Mock Service Worker) for integration testing.

# 🧰 Pro Tips

- 🔐 Use secure token storage (`axd_token` and `dm_token`)

- 🎯 Tree-shake only the services you need

# 📁 Directory Structure

If you inspect the package or generated source, you’ll find:

```bash
src/
  api-client/
    core/            # Internal helpers like fetch, configs
    models/          # Typed interfaces from OpenAPI
    services/        # Grouped endpoints (e.g., UserService)
    index.ts         # Exports everything
dist/
  index.cjs.js       # CommonJS
  index.esm.js       # ESM
  index.umd.js       # UMD (CDN-ready)
  types/
    index.d.ts       # Types
```

# 📚 Resources

- [Ibl Developer Docs](https://iblai.apidocumentation.com/reference)
