# PERS Developer Resources

Essential tools, libraries, and resources for PERS API integration.

## Official Libraries

### **@explorins/pers-shared**

The official TypeScript library providing type-safe contracts and DTOs for PERS API integration.

> **📦 Package Size**: The npm package is 1.2 MB (includes full TypeScript definitions), but modern bundlers with tree-shaking typically include only 0.44-0.67 KB in your final bundle.


#### **Installation**

```bash
npm install @explorins/pers-shared
```

#### **Library Information**

- **Package Name**: `@explorins/pers-shared`
- **Registry**: [npmjs.org](https://www.npmjs.com/package/@explorins/pers-shared)
- **License**: MIT
- **Maintainer**: eXplorins Development Team


#### **What's Included**

- **DTOs**: Complete type definitions for all API request/response objects
- **Interfaces**: TypeScript contracts for authentication, users, campaigns, transactions
- **Types & Enums**: Authentication types, error codes, transaction statuses
- **Value Objects**: Immutable data structures like `Address`, `StructuredError`
- **Error Types**: TypeScript error interfaces and enums for type-safe error handling


#### **Usage Examples**

##### **Backend/Node.js Integration**

```typescript
import type { 
  UserDTO, 
  TransactionStatus,
  StructuredError,
  SessionAuthRequestDTO,
  SessionAuthContextResponseDTO 
} from '@explorins/pers-shared';

// Type-safe API requests
const authRequest: SessionAuthRequestDTO = {
  authToken: "external_provider_jwt_token"
};

// Structured error handling
try {
  const response = await fetch('/auth/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(authRequest)
  });
  
  if (!response.ok) {
    const error: StructuredError = await response.json();
    if (error.category === 'SECURITY') {
      console.error('Authentication failed:', error.message);
      // Handle authentication error with proper error code
    }
    return;
  }
  
  const ctx: SessionAuthContextResponseDTO = await response.json();
  console.log(`Authenticated user: ${ctx.user?.email}`);
} catch (error) {
  console.error('Network error:', error);
}

// Type-safe response handling
async function authenticateUser(token: string): Promise<SessionAuthContextResponseDTO> {
  const response = await fetch('/auth/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ authToken: token })
  });
  
  return response.json() as Promise<SessionAuthContextResponseDTO>;
}
```

##### **Frontend/Browser Integration**

```typescript
// Browser-optimized import for smaller bundle size
import { UserDTO, CampaignDTO, Address } from '@explorins/pers-shared/browser';
import type { SessionAuthRequestDTO, SessionAuthContextResponseDTO, UserTokenBalancesDTO } from '@explorins/pers-shared';

// Type-safe API client interface
interface PERSApiClient {
  authenticate(request: SessionAuthRequestDTO): Promise<SessionAuthContextResponseDTO>;
  getBalance(userId: string): Promise<UserTokenBalancesDTO>;
  getCampaigns(): Promise<CampaignDTO[]>;
}

// React component example
import React from 'react';

interface UserBalanceProps {
  userBalance: UserTokenBalancesDTO;
  email: string;
}

const UserBalance: React.FC<UserBalanceProps> = ({ userBalance, email }) => {
  return (
    <div>
      <h2>{email}</h2>
      <p>Wallet: {userBalance.walletAddress?.getValue()}</p>
      {userBalance.tokenBalances?.map(balance => (
        <div key={balance.tokenId}>
          {balance.tokenName}: {balance.balance}
        </div>
      ))}
    </div>
  );
};
```

##### **Vue.js Integration**

```vue
<template>
  <div>
    <h2 v-if="user">{{ user.email }}</h2>
    <div v-for="campaign in campaigns" :key="campaign.id">
      {{ campaign.name }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import type { UserDTO, CampaignDTO } from '@explorins/pers-shared/browser';

const user = ref<UserDTO | null>(null);
const campaigns = ref<CampaignDTO[]>([]);

onMounted(async () => {
  try {
    const userResponse = await fetch('/users/me');
    if (userResponse.ok) {
      user.value = await userResponse.json() as UserDTO;
    }
    
    const campaignsResponse = await fetch('/campaigns');
    if (campaignsResponse.ok) {
      campaigns.value = await campaignsResponse.json() as CampaignDTO[];
    }
  } catch (error) {
    console.error('API Error:', error);
  }
});
</script>
```

```typescript
// Type-safe API requests (Pseudo-code example)
const authRequest: SessionAuthRequestDTO = {
  authToken: "external_provider_jwt_token"
};

// Structured error handling using ErrorFactory
try {
  const ctx = await authenticate(authRequest);
  console.log(`Authenticated user: ${ctx.user.email}`);
} catch (error) {
  if (error === Errors.authenticationRequired()) {
    console.error('Authentication failed:', error.message);
    // Handle authentication error with proper error code
  }
}
```

- **Auto-completion**: All PERS types and interfaces
- **Error Detection**: TypeScript validation for API contracts
- **Quick Info**: Hover documentation for all DTOs
- **Go to Definition**: Navigate to type definitions


#### **WebStorm/IntelliJ**

Full TypeScript integration:

- **Smart Code Completion**: Context-aware suggestions
- **Refactoring Support**: Rename and restructure with confidence
- **Error Highlighting**: Real-time validation
- **Import Organization**: Auto-import management


### **Build Tool Integration**

#### **Webpack**

```javascript
// webpack.config.js - Tree shaking configuration
module.exports = {
  optimization: {
    usedExports: true,
    sideEffects: false // @explorins/pers-shared is side-effect free
  }
};
```

#### **Vite**

```javascript
// vite.config.js - Optimized for PERS library
import { defineConfig } from 'vite';

export default defineConfig({
  optimizeDeps: {
    include: ['@explorins/pers-shared']
  }
});
```

#### **Rollup**

```javascript
// rollup.config.js - Tree shaking optimization
export default {
  external: ['@explorins/pers-shared'],
  output: {
    format: 'es'
  }
};
```

## API Documentation

### **Interactive Documentation**

- **Swagger UI**: Available at `/swagger` when running PERS API server
- **OpenAPI Spec**: Complete API specification with examples
- **Postman Collection**: Ready-to-use API collection for testing


### **Code Examples Repository**

- **Integration Patterns**: Common use cases and implementations
- **Sample Applications**: Full working examples in different frameworks
- **Best Practices**: Recommended implementation approaches


## Community & Support

### **Official Channels**

- **Documentation**: Comprehensive API documentation and guides
- **API Status**: Real-time API status monitoring
- **Developer Portal**: Developer resources and community


### **Getting Help**

- **Technical Support**: Contact integration team for API assistance
- **Bug Reports**: Submit issues through official channels
- **Feature Requests**: Propose enhancements via developer portal


## Getting Started with Development

### **Quick Setup**

1. **Install the Library**

```bash
npm install @explorins/pers-shared
```
2. **Set Up TypeScript**

```json
{
  "compilerOptions": {
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true
  }
}
```
3. **Configure Your IDE**
  - Enable TypeScript language service
  - Install PERS-specific extensions (if available)
  - Set up auto-import preferences
4. **Start Building**

```typescript
import { UserDTO } from '@explorins/pers-shared';

// Your PERS integration starts here!
```


### **Next Steps**

- Review the [Authentication Guide](/5.authentication-guide) for API access setup
- Explore the [Platform Overview](/2.platform-overview) for architectural understanding
- Check the interactive API documentation for endpoint details
- Join the developer community for best practices and support


## Migration from Previous API Versions

### **V2 Performance Improvements**

PERS API V2 delivers substantial performance enhancements across all operations:

- **Faster Response Times**: Up to 3x improvement in API response speeds
- **Enhanced Scalability**: Optimized infrastructure handles higher concurrent loads
- **Reduced Latency**: Streamlined request processing with improved efficiency
- **Better Resource Usage**: Optimized memory and processing patterns


### **Breaking Changes in V2**

PERS API V2 introduces significant improvements but requires migration from previous versions:

#### **URL Structure Changes (Major Breaking Change)**

- **Plural Resource Names**: All endpoints now use plural naming conventions
  - `/campaign` → `/campaigns`
  - `/user` → `/users`
  - `/token` → `/tokens`
  - `/balance` → `/balances`
  - `/redemption` → `/redemptions`
- **RESTful Paths**: Role-agnostic URLs with decorator-based authorization
- **Nested Resources**: Improved resource relationships (e.g., `/campaign-claims`, `/campaign-triggers`)


#### **Enhanced API Patterns**

- **Unified Authentication**: Streamlined `/auth/token` endpoint for multiple flows
- **Structured Errors**: Enhanced error responses with correlation IDs and security filtering
- **Consistent DTOs**: Standardized data transfer objects across all endpoints


#### **Migration Steps**

1. **Update Packages**: Install latest `@explorins/pers-shared` for new types
2. **Update URLs**: Change all endpoint URLs to use plural resource names
3. **Review Authentication**: Verify authentication patterns work with new endpoints
4. **Error Handling**: Update error handling for new structured error format. See [Error Handling](/8.error-handling) for details.
5. **Testing**: Validate integration using testnet campaigns before production


#### **Performance Benefits**

Migrating to V2 provides immediate performance benefits with no additional configuration required. Applications typically see faster response times and improved reliability upon migration.

#### **Backward Compatibility**

Legacy endpoints remain functional during transition period. Contact support for migration timeline and assistance.

For detailed migration assistance, contact our integration team.

## Additional Resources

- **[features.pers.ninja](https://features.pers.ninja/)** — Interactive platform feature matrix: explore all features, packages, and stack architecture at a glance
- **[features.pers.ninja/features.html](https://features.pers.ninja/features.html)** — Detailed feature cards with capability highlights, competitive notes, and stack module breakdown