npm package: @meucontrole.ai/plugin-sdk
Description: SDK para desenvolvimento de plugins MeuControle
Latest version: 0.0.1

# @meucontrole.ai/plugin-sdk

The official **TypeScript SDK** for developing plugins for the **MeuControle** platform.

This SDK provides all the necessary type definitions, React hooks, and utility functions to build powerful integrations that interact seamlessly with the MeuControle ecosystem (Orders, Menu, Customers, etc.).

## 📦 Installation

Install the SDK and all required dependencies:

```bash
npm install @meucontrole.ai/plugin-sdk react react-dom
npm install -D typescript vite @vitejs/plugin-react @types/node @types/react
```

## 🚀 Quick Start: Creating a Plugin

### 1. Initialize Your Project

Create a new directory for your plugin and initialize it:

```bash
mkdir my-plugin
cd my-plugin
npm init -y
```

### 2. Install Dependencies

```bash
npm install @meucontrole.ai/plugin-sdk react react-dom
npm install -D typescript vite @vitejs/plugin-react @types/node @types/react
```

### 3. Configure package.json

Update your `package.json`:

```json
{
  "name": "my-awesome-plugin",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "build": "tsc && vite build"
  },
  "dependencies": {
    "@meucontrole.ai/plugin-sdk": "^1.0.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@types/node": "^24.0.0",
    "@types/react": "^18.2.0",
    "@vitejs/plugin-react": "^5.0.0",
    "typescript": "^5.0.0",
    "vite": "^7.0.0"
  }
}
```

### 4. Create tsconfig.json

```json
{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}
```

### 5. Create tsconfig.node.json

```json
{
  "compilerOptions": {
    "composite": true,
    "skipLibCheck": true,
    "module": "ESNext",
    "moduleResolution": "bundler",
    "allowSyntheticDefaultImports": true
  },
  "include": ["vite.config.ts"]
}
```

### 6. Create vite.config.ts

```typescript
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';

export default defineConfig({
  plugins: [react()],
  build: {
    lib: {
      entry: path.resolve(__dirname, 'src/index.tsx'),
      name: 'Plugin',
      fileName: () => 'plugin.js',
      formats: ['iife']
    },
    rollupOptions: {
      external: ['react', 'react-dom', '@meucontrole.ai/plugin-sdk'],
      output: {
        globals: {
          react: 'window.MeuControleSDK.React',
          'react-dom': 'window.MeuControleSDK.ReactDOM',
          '@meucontrole.ai/plugin-sdk': 'window.MeuControleSDK'
        }
      }
    },
    emptyOutDir: true,
    outDir: 'dist',
    minify: 'esbuild'
  },
  define: {
    'process.env.NODE_ENV': '"production"'
  }
});
```

### 7. Create Your Plugin (src/index.tsx)

```tsx
import { Plugin, PluginManager, useNotifications } from '@meucontrole.ai/plugin-sdk';

const MyPlugin: Plugin = {
  manifest: {
    id: 'com.yourcompany.pluginname',
    name: 'My Awesome Plugin',
    version: '1.0.0',
    description: 'A brief description of what this plugin does.',
    author: 'Your Name',
    sdkVersion: '1.0.0',
    permissions: ['orders:read', 'notifications:send'],
    icon: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='
  },

  onActivate: async (context) => {
    console.log('Plugin activated!', context);
  },

  slots: {
    dashboardWidget: () => {
      const { showSuccess } = useNotifications();
      
      return (
        <div className="p-4 bg-white rounded-lg shadow">
          <h3 className="font-bold text-lg mb-2">Hello from Plugin!</h3>
          <p className="text-gray-600 mb-4">
            This component is written in TSX and compiled to JS.
          </p>
          <button
            className="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600"
            onClick={() => showSuccess('It works perfectly!')}
          >
            Test Notification
          </button>
        </div>
      );
    }
  }
};

// Register the plugin with the platform
PluginManager.register(MyPlugin);

export default MyPlugin;
```

### 8. Build Your Plugin

```bash
npm run build
```

This will generate `dist/plugin.js` — your bundled plugin ready for upload.

## 📚 API Reference

### Hooks

The SDK exposes several hooks to interact with the platform data:

#### `useOrders()`
Access and manage orders.

```tsx
const { orders, isLoading, error, refetch, getOrder, updateStatus } = useOrders();
```

#### `useMenu()`
Read and update the product catalog.

```tsx
const { categories, isLoading, error, refetch, getCategory, getItemsByCategory } = useMenu();
```

#### `useMerchant()`
Get information about the current store/merchant.

```tsx
const { merchant, user, isLoading, isOpen, toggleOpen } = useMerchant();
```

#### `useNotifications()`
Display toast notifications.

```tsx
const { showSuccess, showError, showWarning, showInfo } = useNotifications();

showSuccess('Operation completed!');
showError('Something went wrong', { duration: 5000 });
```

#### `useStorage()`
Persist simple data locally for the plugin.

```tsx
const { get, set, remove, clear } = useStorage();

set('myKey', { foo: 'bar' });
const data = get<MyType>('myKey');
```

#### `useEvents()`
Subscribe to real-time events.

```tsx
const { subscribe, emit } = useEvents();

useEffect(() => {
  const unsubscribe = subscribe('order:created', (event) => {
    console.log('New order:', event.payload.order);
  });
  
  return unsubscribe;
}, []);
```

### UI Slots

You can inject your components into specific parts of the MeuControle interface:

*   **`dashboardWidget`**: Adds a card to the main dashboard.
*   **`orderTab`**: Adds a custom tab in the Order Details modal.
*   **`orderActions`**: Adds buttons to the Order Actions bar.
*   **`menuWidget`**: Adds content to the Menu management screen.
*   **`sidebarItem`**: Adds a new item to the main navigation sidebar.
*   **`integrationApp`**: Configures the plugin to appear in the App Marketplace.

### Types

All TypeScript types are fully exported:

```tsx
import type { 
  Plugin, 
  PluginManifest, 
  Order, 
  OrderStatus, 
  Customer,
  MenuItem,
  Money 
} from '@meucontrole.ai/plugin-sdk';
```

## 🛠️ Building & Deployment

### Build Process

The build process compiles your TypeScript code and bundles it with Vite:

1.  **TypeScript Compilation**: `tsc` validates types and generates declarations
2.  **Bundling**: Vite bundles your code into a single `plugin.js` file
3.  **External Dependencies**: React and the SDK are marked as external and mapped to global variables

### Upload to Platform

1.  Build your plugin: `npm run build`
2.  Locate the artifact: `dist/plugin.js`
3.  Go to the **MeuControle Developer Portal**
4.  Create a new Plugin or select an existing one
5.  Upload the `dist/plugin.js` file
6.  The platform will validate the manifest and permissions

## 🔍 Troubleshooting

### "Cannot find module '@meucontrole.ai/plugin-sdk'"

Make sure you've installed all dependencies:
```bash
npm install @meucontrole.ai/plugin-sdk react react-dom
```

### TypeScript errors with React types

Install the React type definitions:
```bash
npm install -D @types/react
```

### Build fails with "Cannot find module 'path'"

Install Node.js type definitions:
```bash
npm install -D @types/node
```

## 📄 License

MIT © MeuControle