# CareStack EHR SDK

![Node.js](https://img.shields.io/badge/node-18.x-brightgreen)
[![NPM](https://img.shields.io/npm/v/carestack.svg)](https://www.npmjs.com/package/carestack)

A modern, reactive Node.js SDK for the **EHR platform**. This SDK simplifies integration with the API, providing type-safe, promise-based services for managing health records, appointments, ABHA/HPR workflows, and AI-powered features like document summarization and FHIR bundle generation.

Built with TypeScript and designed for asynchronous usage with `async/await`, it's ideal for building scalable healthcare applications.

---

## 📑 Table of Contents
- [Key Features](#-key-features)
- [Documentation](#-documentation)
- [Getting Started](#-getting-started)
- [Installation](#installation)
- [Credential Configuration](#-credential-configuration)
- [Quick Start](#-quick-start)
- [Services Overview](#services-overview)
- [Detailed Service Guide](#detailed-service-guide)
- [Building from Source](#️-building-from-source)
- [Running Tests](#-running-tests)
- [License](#-license)

## ✨ Key Features

This SDK supports a comprehensive suite of CareStack EHR functionalities:

- **Electronic Health Records (EHR)**: Secure and structured access to patient records.
- **ABHA (Ayushman Bharat Health Account)** workflows: Generate, verify, and manage ABHA numbers using official NDHM APIs.
- **HPR (Healthcare Professional Registry)** services: Professional identity creation and linking with ABHA.
- **HealthLake Resource Management**: Interact with FHIR-compliant resources such as **Patient**, **Practitioner**, **Organization**, and more.
- **Appointment Management**: Create, update, and retrieve patient appointment data.
- **FHIR Bundle Generation**: Generate structured clinical documents in FHIR format, ready for interoperability.
- **AI-powered Document Summarization**: Automatically summarize patient health documents using integrated AI services.

- **Comprehensive Resource Management:**  
  Full CRUD and search support for EHR resources such as `Patient`, `Appointment`, `Organization`, and `Practitioner`.

- **Workflow-Driven Services:**  
  Simplified step-by-step APIs for ABHA (Ayushman Bharat Health Account) and HPR (Healthcare Professional Registry) registration flows.

- **AI-Powered Document Processing:**
  - **Summarization:** Generate concise summaries from clinical documents.
  - **Entity Extraction:** Extract structured data (diagnoses, medications, etc.) from free text.
  - **FHIR Bundle Generation:** Convert raw documents or structured JSON into HL7 FHIR-compliant bundles.

- **Asynchronous & Promise-Based:**  
  All APIs are fully asynchronous using modern `Promise` and `async/await` patterns.

- **Validation & Security:**  
  DTO-based validation and built-in support for **RSA**/**JWE** encryption of sensitive information.
---

## 🚀 Getting Started

### Prerequisites

- Node.js v18 
- An active API key for the CareStack EHR platform

### Installation

Install via npm:

```javascript
npm install carestack
```

### 🔐 Credential Configuration
```javascript
const config = {
  apiUrl: 'your_api_url_here',
  apiKey: 'your_secret_api_key_here',
  hpridAuth: 'your-facility-hprid-auth-token' // Optional credential, mandatory for only organization related sdk services
};
```

### 🚀 Quick Start
```javascript
import { CareStack } from 'carestack';

const config = {
  apiUrl: 'your_api_url_here', 
  apiKey: 'your_secret_api_key_here'
};

const carestack = new CareStack(config);
const data = await carestack.patient.findById("632df79b-67bc-415e-91d7-aa70cd99a79e");
console.log(data);
```
---

## Services Overview

The SDK provides the following main services:

### Core EHR Services
| Service | Description | Key Operations |
|---------|-------------|----------------|
| **Patient** | Manage patient records and demographics | Create, Read, Update, Delete, Search |
| **Practitioner** | Handle healthcare provider information | CRUD operations, HPR integration |
| **Organization** | Manage healthcare facilities | Organization registry, master data |
| **Appointment** | Schedule and manage appointments | Booking, updates, availability |

### AI & Document Services
| Service | Description | Key Operations |
|---------|-------------|----------------|
| **AiService** | AI-powered document generation | Discharge summaries, Radiology Reports, Care Plans, FHIR bundles |
| **DocumentLinking** | Link health documents with care contexts | Multi-step workflow orchestration |
| **Encounter** | Healthcare encounter workflows | FHIR generation, discharge processing |

### Healthcare Identity Workflows 
| Service | Description | Key Operations |
|---------|-------------|----------------|
| **CreateABHA** | ABHA registration workflows | Multi-step OTP verification |
| **CreateHPR** | HPR registration processes | Professional registry enrollment |

---

## Detailed Service Guide

### Patient Resource Management
```javascript
import { CareStack } from 'carestack';

const config = {
  apiUrl: 'your_api_url_here', 
  apiKey: 'your_secret_api_key_here'
};

const carestack = new CareStack(config);

#### Creating the Patient Resource

    // Input:
    const data = await carestack.patient.create({
      idNumber: "123456789012",
      idType: PatientIdTypeEnum.AADHAAR,
      abhaAddress: "abha55578@example.com",
      patientType: PatientTypeEnum.REGULAR,
      firstName: "John",
      lastName: "Doe",
      birthDate: "1990-01-01",
      gender: 'male',
      mobileNumber: "+911234563291",
      emailId: "john@example.com",
      address: "123 Main St, Anytown, Anystate",
      pincode: "560001",
      state: StatesAndUnionTerritories.KARNATAKA,
      resourceType: "Patient"
    });
    console.log(data);

    // Expected Output:
    {
      message: 'Successfully created the Patient profile',
      type: 'Patient',
      resourceId: '791708f6-de6d-439e-bece-041e5d64e463',
      validationErrors: [],
      fhirProfileId: '',
      resource: {
        firstName: 'John',
        lastName: 'Doe',
        birthDate: '1990-01-01',
        gender: 'male',
        mobileNumber: '*********3291',
        emailId: 'john@example.com',
        address: '123 Main St, Anytown, Anystate, 12345',
        pincode: '560001',
        resourceType: 'Patient',
        // ... other fields
      }
    }

#### Updating the Patient Resource

    // Input:
    const updatedPatient = await carestack.patient.update({
      "resourceType": "Patient",
      "resourceId": "791708f6-de6d-439e-bece-041e5d64e463",
      "emailId": "VijayaLatha123@gmail.com",
      "mobileNumber": "+919182853291"
    });
    console.log(updatedPatient);

    // Expected Output:
    {
      message: 'Details Updated successfully',
      type: 'Patient',
      resource: {
        firstName: 'Vijaya',
        middleName: 'A',
        lastName: 'Doe',
        birthDate: '1980-01-01',
        gender: 'male',
        // ... other fields
      }
    }

#### Retrieving the Patient Resource by resource ID

    // Input:
    const patient = await carestack.patient.findById("123e4567-e89b-12d3-a456-426614174000");
    console.log(patient);

    // Expected Output:
    {
      type: 'Patient',
      message: 'Patient Found !!!',
      requestResource: {
          firstName: 'Sreenivasa',
          birthDate: '2025-07-23', 
          gender: 'male',
          mobileNumber: '*********0000',
          emailId: '',
          // ... other fields
      },
      totalNumberOfRecords: 1
    }

    // ... other methods
```

### Practitioner Resource Management
```javascript
import { CareStack } from 'carestack';

const config = {
  apiUrl: 'your_api_url_here', 
  apiKey: 'your_secret_api_key_here'
};

const carestack = new CareStack(config);

#### Creating the Practitioner Resource

    // Input:
    const createPractitioner = {
      registrationId: "1234567458",
      department: "urology",
      designation: "surgeon",
      status: "Active",
      joiningDate: "2023-05-15",
      staffType: "Full-Time",
      firstName: "Baipalli",
      middleName: "A",
      lastName: "Rama Rao",
      birthDate: "1980-12-25",
      gender: "male",
      mobileNumber: "+919182856790",
      emailId: "ramarao.baipalli@example.com",
      address: "123 Main Street, Cityville",
      pincode: "560001",
      state: "Karnataka",
      wantsToLinkWhatsapp: true,
      photo: "base64EncodedPhotoString",
      resourceType: "Practitioner"
    };

    const result = await carestack.practitioner.create(createPractitioner);
    console.log(result);

    // Expected Output:
    {
      message: "Successfully created the Practitioner profile",
      type: "Practitioner",
      resourceId: "43a0f739-0c54-4b9f-ab4b-08afbed0bf3c",
      validationErrors: [],
      fhirProfileId: "",
      resource: {
        firstName: "Baipalli",
        lastName: "Rama Rao",
        birthDate: "1980-12-25",
        registrationId: "1234567458",
        resourceId: "43a0f739-0c54-4b9f-ab4b-08afbed0bf3c",
        // ... other fields
      }
    }

#### Updating the Practitioner Resource

    // Input:
    const updatedData: UpdatePractitionerDTO = {
      registrationId: "PR12345",
      department: "Cardiology",
      designation: "Senior Surgeon",
      status: "Active",
      joiningDate: "2022-07-01",
      staffType: "Permanent",
      firstName: "Arjun",
      lastName: "Rao",
      birthDate: "1985-12-20",
      gender: "male",
      mobileNumber: "+911234567890",
      emailId: "arjun.rao@hospital.com",
      address: "123 Hospital Road",
      pincode: "500001",
      state: "Telanagana",
      resourceType: "practitioner"
    };

    const result = await carestack.practitioner.update(updatedData);
    console.log(result);

    // Expected Output:
    {
      message: 'Details Updated successfully',
      type: 'Practitioner',
      resource: {
        firstName: 'Vijaya',
        middleName: 'A',
        lastName: 'Doe',
        //...Other Details
      }
    }

#### Retrieving the Practitioner Resource by resource ID

    // Input:
    const practitioner = await carestack.practitioner.findById("767113fd-aaaf-492f-8226-347f804757b6");
    console.log(practitioner);

    // Expected Output:
    {
      type: 'Practitioner',
      message: 'Practitioner Found !!!',
      requestResource: {
        firstName: 'Nandamuri',
        lastName: 'Taraka Rama Rao',
        birthDate: '1980-12-25',
        registrationId: '1234567890',
        resourceId: '767113fd-aaaf-492f-8226-347f804757b6',
        gender: 'male',
        // ...other fields
      },
      totalNumberOfRecords: 1
    }

    // ... other methods
```

#### Organization Management
```javascript
import { CareStack } from 'carestack';

const config = {
  apiUrl: 'your_api_url_here', 
  apiKey: 'your_secret_api_key_here'
};

const carestack = new CareStack(config);

#### Creating the Organization 

    // Input:
    const response = await carestack.organization.register({
      basicInformation: {
          address: "123 Main Street, Hyderabad",
          state: "Telangana",
          pincode: "500001",
          contactNumber: "+919876543210"
        },
        // ... other organization fields
    });
    console.log(message);

    // Expected Output:
    "Facility added successfully. Your facility ID is IN6778"

#### Updating the Organization

    // Input:
    const response = await carestack.organization.update({
      id: "org-123",
      spocName: "Dr. Sneha",
      spocId: "spoc-001",
      consentManagerName: "Health Consent Inc.",
      consentManagerId: "cm-001"
    });

    // Expected Output:
    "Spoc and Consent Manager added Successfully"

    // ... other methods
```

### ABHA Registration Workflow
```javascript
#### Step 1: Register With Aadhaar

    // Input:
    const requestAadhaarOtpPayload = { aadhaar: '123456789012' };
    const aadhaarOtpResponse = await carestack.patient.abha.createAbha('RegisterWithAadhaar', requestAadhaarOtpPayload);

    // Expected Output:
    {
      "success": true,
      "message": "OTP sent successfully...",
      "response": {
        "txnId": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6"
      },
      "nextStep": "VerifyAadhaarOtp",
      "nextStepHint": "Please enter the OTP..."
    }

#### Step 2: Verify Aadhaar OTP

    // Input:
    const verifyAadhaarOtpPayload = {
      otp: '123456',
      txnId: 'a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6',
      mobile: '9876543210'
    };
    const aadhaarVerificationResponse = await carestack.patient.abha.createAbha('VerifyAadhaarOtp', verifyAadhaarOtpPayload);

    // Expected Output:
    {
      "success": true,
      "message": "Aadhaar OTP verified successfully.",
      "response": {
        "ABHAProfile": { "mobile": "9876543210", "...": "..." }
      },
      "nextStep": "GetAbhaAddressSuggestions",
      "nextStepHint": "Mobile number is already verified. Proceed to select ABHA address."
    }
    // ... Workflow continues with other steps
```


### HPR Registration Workflow

```javascript
import  {CareStack} from 'carestack';
const config = {
  apiUrl: 'your_api_url_here', 
  apiKey: 'your_secret_api_key_here'         
};
const carestack = new CareStack(config);

#### Step 1: Register With Aadhaar

    // Input:
    const requestAadhaarOtpPayload = { aadhaar: '123456789012' };
    const aadhaarOtpResponse = await carestack.practitioner.hpr.createHpr(HprSteps.RegisterWithAadhaar, requestAadhaarOtpPayload);

    // Expected Output:
    {
      "success": true,
      "message": "OTP sent successfully...",
      "response": {
        "txnId": "a1b2c3d4-e5f6-4a5b-8c9d-e1f2a3b4c5d6",
        "mobileNumber": "******3210"
      },
      "nextStep": "VerifyAadhaarOtp",
      "nextStepHint": "Enter txnId and OTP to verify mobile number."
    }

#### Step 2: Verify Aadhaar OTP

    // Input:
    const verifyAadhaarOtpPayload = {
      otp: '123456',
      txnId: 'a1b2c3d4-e5f6-4a5b-8c9d-e1f2a3b4c5d6'
    };
    const aadhaarVerificationResponse = await carestack.practitioner.hpr.createHpr(HprSteps.VerifyAadhaarOtp, verifyAadhaarOtpPayload);

    // Expected Output:
    {
      "success": true,
      "message": "Aadhaar OTP verified successfully.",
      "response": {
        "txnId": "a1b2c3d4-e5f6-4a5b-8c9d-e1f2a3b4c5d6",
        "name": "Dr. Priya Sharma",
        "gender": "F",
        "birthdate": "15-08-1990",
        "state": "Telangana",
        "district": "Hyderabad"
      },
      "nextStep": "CheckAccountExists",
      "nextStepHint": "Please provide txnId to check account existence."
    }

    // ...  Workflow continues with other steps
```

### Appointment Resource Management

```javascript
import  {CareStack} from 'carestack';
const config = {
  apiUrl: 'your_api_url_here', 
  apiKey: 'your_secret_api_key_here'         
};
const carestack = new CareStack(config);

#### Creating the Appointment Resource

    // Input:
    const appointment = {
      patientReference: "a8654878-4202-4b47-bcc4-868060a75254",
      practitionerReference: "3c7271bb-4212-4291-9f75-64d886d69893",
      appointmentStartDate: "2025-02-28T09:00:00Z",
      appointmentEndDate: "2025-02-28T10:00:00Z",
      appointmentPriority: "Emergency",
      organizationId: "org123",
      appointmentSlot: "slot123",
      reference: "ref123"
    };

    const result = await carestack.appointment.create(appointment);
    console.log(result);

    // Expected Output:
    {
      message: 'Successfully created the Appointment profile',
      type: 'Appointment',
      resourceId: '2d9f1cfb-3ab0-4697-907a-78431678df1e',
      validationErrors: [],
      fhirProfileId: '',
      resource: {
        reference: '2d9f1cfb-3ab0-4697-907a-78431678df1e',
        practitionerReference: '3c7271bb-4212-4291-9f75-64d886d69893',
        patientReference: 'a8654878-4202-4b47-bcc4-868060a75254',
        priority: 'Emergency',
        slot: '02:30 PM - 03:30 PM',
        start: '2025-02-28T09:00:00Z',
        end: '2025-02-28T10:00:00Z',
        organizationId: 'ACHALA_HEALTH_01'
      }
    }

#### Retrieving a Appointment Resource by resource ID

    // Input:
    const appointment = await carestack.appointment.findById("d7d79e4c-a3db-4505-877d-f853610b7c4a");
    console.log(appointment);

    // Expected Output:
    {
      type: 'Appointment',
      message: 'Appointment Found !!!',
      requestResource: {
        reference: 'd7d79e4c-a3db-4505-877d-f853610b7c4a',
        practitionerReference: '3c7271bb-4212-4291-9f75-64d886d69893',
        patientReference: 'a8654878-4202-4b47-bcc4-868060a75254',
        priority: 'Emergency',
        slot: '02:30 PM - 03:30 PM',
        start: '2025-02-28T09:00:00Z',
        end: '2025-02-28T10:00:00Z',
        organizationId: 'ACHALA_HEALTH_01'
      },
      totalNumberOfRecords: 1
    }

  // ... other Methods

```

### AI-Powered Discharge Summary and OpConsultation Generation from File URLs

```javascript
import  {CareStack} from 'carestack';
const config = {
  apiUrl: 'your_api_url_here', 
  apiKey: 'your_secret_api_key_here'        
};
const carestack = new CareStack(config);

#### Generating Discharge Summary from File URL

    // Input:
    const processDSDto = {
      files: [
        'https://example-bucket.s3.amazonaws.com/discharge1.pdf',
        'https://example-bucket.s3.amazonaws.com/discharge2.pdf'
      ],
      publicKey: '-----BEGIN PUBLIC KEY-----...'
    };
    const summary = await carestack.ai.generateDischargeSummary(processDSDto);
    console.log('Discharge Summary:', summary);

    // Expected Output:
    Discharge Summary : {
      "id": "1db63a9f-ac82-41fa-b50b-69a09c2c839e",
      "dischargeSummary": {
        "patientDetails": {
          "Name": "MR. ARUN KUMAR MITRA",
          "Age": "81 Years",
          "Gender": "MALE",
          "RegNo": "600174610"
          // ...other details
        }
      },
      "extractedData": {
        "Patient Details": {
          "Name": "MR. ARUN KUMAR MITRA",
          "Age": "81 Years",
          "Sex": "MALE",
          "Date of Birth": "08/08/1943"
          // ...other details
        }
      },
      "fhirBundle": {}
      "anomalies": { anomaliesDetected: false, ipNumbers: [], uhidNumbers: [] }
    }

#### Generating Discharge Summary from partial uploads (Daily / Incremental) and final triggering of Discharge Summary

    // Input:
    const processDSDto = {
      files: [
        'https://example-bucket.s3.amazonaws.com/discharge-day1.pdf'
      ],
      date: "2025-09-16T12:30:00Z"
    };

    // First partial upload (encounterId will be returned in response)
    const response1 = await carestack.ai.partialUploadForDischargeSummary(processDSDto);
    console.log('Partial Upload Response:', response1);

    // Second partial upload (must include encounterId from first response)
    const processDSDto2 = {
      files: [
        'https://example-bucket.s3.amazonaws.com/discharge-day2.pdf'
      ],
      encounterId: response1.id,  // reuse encounterId from initial upload
      date: "2025-09-17T12:30:00Z"
    };

    const response2 = await carestack.ai.partialUploadForDischargeSummary(processDSDto2);
    console.log('Partial Upload Response:', response2);

    // Expected Output:
    {
      id: "aece6ca4-2739-435d-b76c-d468738356cc",
      dischargeSummary: { },
      extractedData: { ... }
      "anomalies": { anomaliesDetected: false, ipNumbers: [], uhidNumbers: [] }
    }

    ### Final Discharge Summary Triggering

        // Input:
        const encounterId = "aece6ca4-2739-435d-b76c-d468738356cc";

        const finalSummary = await carestack.ai.triggerDischargeSummary(encounterId);
        console.log('Final Discharge Summary:', finalSummary);

        // Expected Output:
        {
          dischargeSummary: {
            patientDetails: {
              Name: "Mr. Rajulapudi Sravand",
              Age: "16 years 6 months",
              Gender: "Male",
              RegNo: "KHLB.4731638",
              ipNo: "2506132",
              admitDate: "2025-02-09",
              dateOfOperation: "2025-02-09",
              attendantDetails: "Not Available"
            },
            // ...other details
          },
          message: "Discharge for record aece6ca4-2739-435d-b76c-d468738356cc generated successfully"
        }


#### Generating OpConsultation from File URL

    // Input:
    const processDSDto = {
      files: [
        'https://example-bucket.s3.amazonaws.com/op-note1.pdf',
        'https://example-bucket.s3.amazonaws.com/op-note2.pdf'
      ],
      publicKey: '-----BEGIN PUBLIC KEY-----...'
    };
    const extractedText = await carestack.ai.extractOpCaseData(processDSDto);
    console.log('Extracted OP Case Data:', extractedText);

    // Expected Output:
    Extracted OP Case Data : {
      "id": "1db63a9f-ac82-41fa-b50b-69a09c2c839e",
      "extractedData": {
        "Patient Details": {
          "Name": "MR. ARUN KUMAR MITRA",
          "Age": "81 Years",
          "Sex": "MALE",
          "Date of Birth": "08/08/1943"
          // ...other details
        }
      },
      "fhirBundle": {}
    }

#### Generating CarePlan from File URL

    // Input:
    const carePlanDto = {
        "files": [
              "https://ai-features-test-ap-south-1.s3.amazonaws.com/careplan/dischargesummaries/case%20-%204.pdf"  // careplan
        ]
    }
    const data = await carestack.ai.generateCarePlan(carePlanDto)
    console.log('carePlanData:', data)

    // Expected Output:
    carePlanData:
    {
      "id": '72558f07-dd20-4076-a15c-f50a9c78ebb9',
      "carePlan": {
        "patientDetails": {
          "name": 'RUQSANA BEGUM',
          "age": '75Y(s) 6M(s) 30D(s)',
          "sex": 'Female',
          "uhid": 'MRKO2526015739',
          "visitId": 'IPKO2526005789',
          "address": 'TOLICHOWKI',
          "contactNumber": '8886131115'
        },
        // ...Other Details
      }
    }

#### Generating Fhir Bundle from Json Payload

    // Input:
    const extractedData = {
      "chiefComplaints": "Severe headache and nausea for the past 1 day",
      "physicalExamination": {
        "bloodPressure": { "value": "140/90", "unit": "mmHg" },
        "heartRate": { "value": "88", "unit": "bpm" },
        "respiratoryRate": { "value": "18", "unit": "breaths/min" },
        "temperature": { "value": "98.7", "unit": "°F" },
        "oxygenSaturation": { "value": "97", "unit": "%" },
        "height": { "value": "160", "unit": "cm" },
        "weight": { "value": "60", "unit": "kg" }
      },
      "conditions": ["Migraine (suspected)"],
      "medicalHistory": [
        { "condition": "Hypothyroidism diagnosed 3 years ago", "procedure": "None" }
      ],
      "familyHistory": [
        {
          "relation": "Sister",
          "healthNote": "Diagnosed with migraine at age 22",
          "condition": "Migraine"
        }
      ],
      "allergies": ["No known drug allergies"],
      "immunizations": ["Tetanus booster taken 2 years ago, Lot number: TET987, Expiry: 2026-06-30"],
      "investigations": {
        "observations": {
          "serumCreatinine": { "value": "1.1", "unit": "mg/dL" },
          "sodium": { "value": "138", "unit": "mmol/L" },
          "potassium": { "value": "4.2", "unit": "mmol/L" }
        },
        "status": "preliminary",
        "recordedDate": "2024-07-12"
      },
      "prescribedMedications": [
        "Sumatriptan 50 mg – once at onset – oral – for migraine",
        "Ondansetron 4 mg – as needed – oral – for nausea"
      ],
      "currentProcedures": [
        {
          "description": "Appendectomy surgery",
          "complications": "No postoperative complications"
        }
      ],
      "advisoryNotes": [
        "Avoid bright lights and loud noises",
        "Take rest in a dark, quiet room during episodes"
      ],
      "followUp": [
        "Review after MRI report – OP-87954 – In-person"
      ]
    };

    const dto = {
      extractedData: extractedData,
      enabledExtraction: true,
      caseType: "OPConsultation",
      patientDetails: {
        "firstName": "Ravi",
        "middleName": "Kumar",
        "lastName": "Sharma",
        "birthDate": "1980-05-20",
        // ... other patient details
      },
      practitionerDetails: [{
        "firstName": "Anita",
        "middleName": "S.",
        "lastName": "Verma",
        "birthDate": "1975-08-15",
        "gender": "female",
        "mobileNumber": "+919812345678",
        // ... other practitioner details
      }]
    };

    const response = await carestack.ai.generateFhirBundle(dto);
    console.log(response);

    // Expected Output:
    {
      resourceType: "Bundle",
      id: '7b3b5fef-7fd1-437b-940d-a55b64add446',
      meta: {
        lastUpdated: '2025-08-01T06:00:56.737721544Z',
        profile: [
          'https://nrces.in/ndhm/fhir/r4/StructureDefinition/DocumentBundle'
        ],
        security: [ [Object] ],
        versionId: '1'
      },
      identifier: {
        system: 'http://hip.in',
        value: '95328b17-adbf-49a0-b526-cd1ad8519e1c'
      },
      type: 'document',
      timestamp: '2025-08-01T06:00:56.308Z',
      entry: [
        {
          "resource": {
            "resourceType": "Patient",
            "name": [
              { "text": "John Doe" }
            ]
          }
        },
        // ... other entries
      ]
      // ... other entries
    }

```

### Generating a FHIR Bundle from Health Information Data

This method supports two modes of input:
1. **File-based**: Processes files provided in the `dto.caseSheets` array.
2. **JSON-based**: Processes JSON payload provided in `dto.payload`, which must match one of the supported HI types.

- In both cases, if the `enableExtraction` flag is set to false, document references will be mandatory.
- patientDetails and practitionerDetails are mandatory for case-2 (JSON-based processing), irrespective of the `enableExtraction` flag.
- PatinetDetails and PractitionerDetails are optional for case-1 (file-based processing) if enableExtraction is set to true. If easeExtraction is false, these details are mandatory.

#### Usage

```javascript
// Case 1: Generating FHIR bundle from a case sheets url/base64 string of Health Document file

const fileData = {
  caseType: "OPConsultation",
  enableExtraction: true,
  dto: {
    caseSheets: ["base64_string_or_file_url"]
  }
};
const bundle = await carestack.encounter.create(fileData);
console.log("FHIR bundle generated:", bundle);

// Expected Output:
FHIR bundle generated: {
  id: '7b3b5fef-7fd1-437b-940d-a55b64add446',
  meta: {
    lastUpdated: '2025-08-01T06:00:56.737721544Z',
    profile: [
      'https://nrces.in/ndhm/fhir/r4/StructureDefinition/DocumentBundle'
    ],
    security: [ [Object] ],
    versionId: '1'
  },
  identifier: {
    system: 'http://hip.in',
    value: '95328b17-adbf-49a0-b526-cd1ad8519e1c'
  },
  type: 'document',
  timestamp: '2025-08-01T06:00:56.308Z',
  entry: [
    {
      fullUrl: 'urn:uuid:43cb61d7-d59d-4935-b4ef-bd411f9e034c',
      resource: [Object]
    },
    {
      fullUrl: 'urn:uuid:37570edb-0a0d-4b6b-bc5f1ddb0853b',
      resource: [Object]
    },
    // ...Other Details
  ],
  resourceType: 'Bundle'
}

// Case 2: Generating FHIR bundle from a Health Information sections JSON payload

const rawData = {
  caseType: "OPConsultation",
  enableExtraction: true,
  patientDetails: {
    "firstName": "Ravi",
    "middleName": "Kumar",
    "lastName": "Sharma",
    "birthDate": "1980-05-20",
    // ... other patient details
  },
  practitionerDetails: [{
    "firstName": "Anita",
    "middleName": "S.",
    "lastName": "Verma",
    "birthDate": "1975-08-15",
    "gender": "female",
    "mobileNumber": "+919812345678",
    // ... other practitioner details
  }],
  dto: {
    payload: {
      "chiefComplaints": "Severe headache and nausea for the past 1 day",
      "physicalExamination": {
        "bloodPressure": { "value": "140/90", "unit": "mmHg" },
        "heartRate": { "value": "88", "unit": "bpm" },
        "respiratoryRate": { "value": "18", "unit": "breaths/min" },
        "temperature": { "value": "98.7", "unit": "°F" },
        "oxygenSaturation": { "value": "97", "unit": "%" },
        "height": { "value": "160", "unit": "cm" },
        "weight": { "value": "60", "unit": "kg" }
      },
      "conditions": ["Migraine (suspected)"],
      "medicalHistory": [
        { "condition": "Hypothyroidism diagnosed 3 years ago", "procedure": "None" }
      ],
      "familyHistory": [
        {
          "relation": "Sister",
          "healthNote": "Diagnosed with migraine at age 22",
          "condition": "Migraine"
        }
      ],
      "allergies": ["No known drug allergies"],
      "immunizations": ["Tetanus booster taken 2 years ago, Lot number: TET987, Expiry: 2026-06-30"],
      "investigations": {
        "observations": {
          "serumCreatinine": { "value": "1.1", "unit": "mg/dL" },
          "sodium": { "value": "138", "unit": "mmol/L" },
          "potassium": { "value": "4.2", "unit": "mmol/L" }
        },
        "status": "preliminary",
        "recordedDate": "2024-07-12"
      },
      // ... other fields
    }
  }
};

const bundle = await carestack.encounter.create(rawData);
console.log("FHIR bundle generated:", bundle);

// Expected Output:
FHIR bundle generated: {
  id: '7b3b5fef-7fd1-437b-940d-a55b64add446',
  meta: {
    lastUpdated: '2025-08-01T06:00:56.737721544Z',
    profile: [
      'https://nrces.in/ndhm/fhir/r4/StructureDefinition/DocumentBundle'
    ],
    security: [ [Object] ],
    versionId: '1'
  },
  identifier: {
    system: 'http://hip.in',
    value: '95328b17-adbf-49a0-b526-cd1ad8519e1c'
  },
  type: 'document',
  timestamp: '2025-08-01T06:00:56.308Z',
  entry: [
    {
      fullUrl: 'urn:uuid:43cb61d7-d59d-4935-b4ef-bd411f9e034c',
      resource: [Object]
    },
    {
      fullUrl: 'urn:uuid:37570edb-0a0d-4b6b-bc5e-c5f1ddb0853b',
      resource: [Object]
    },
    ...Other Details
  ],
  resourceType: 'Bundle'
}

```

### Linking the Health Document to ABHA

```javascript
import  {CareStack} from 'carestack';
const config = {
  apiUrl: 'your_api_url_here', 
  apiKey: 'your_secret_api_key_here'        
};
const carestack = new CareStack(config);

// Input:
const linkingData = {
  patientReference: "a8654878-4202-4b47-bcc4-868060a75254",
  practitionerReference: "3c7271bb-4212-4291-9f75-64d886d69893",
  patientAddress: "123 Main St, Springfield, IL",
  patientName: "John Doe",
  appointmentStartDate: "2025-02-28T09:00:00Z",
  appointmentEndDate: "2025-02-28T10:00:00Z",
  organizationId: "org123",
  appointmentReference: "3c832da8-9cfd-446b-be1c-4a8d01f39374",
  patientAbhaAddress: "sbx@sbx",
  hiType: "OPConsultation",
  mobileNumber: "+911234567890",
  healthRecords: [
    {
      rawFhir: false,
      fhirDocument: null,
      informationType: "OPConsultation",
      dto: {
        chiefComplaints: "Severe headache and nausea for the past 1 day",
        physicalExamination: {
          bloodPressure: { value: "140/90", unit: "mmHg" },
          heartRate: { value: "88", unit: "bpm" },
          respiratoryRate: { value: "18", unit: "breaths/min" },
          temperature: { value: "98.7", unit: "°F" },
          oxygenSaturation: { value: "97", unit: "%" },
          height: { value: "160", unit: "cm" },
          weight: { value: "60", unit: "kg" }
        },
        conditions: ["Migraine (suspected)"],
        //... other fields
      }
    }
  ]
};
const result = await linkHealthDocument.linkHealthDocument(linkingData);
console.log(result);

// Expected Output:
true

```
---
## 📚 Documentation

For a deep dive into all available services, methods, and DTOs, please refer to our complete SDK documentation:

👉 [View the Official Documentation](http://athenaabhabucket.s3-website.ap-south-1.amazonaws.com/)

---

## 🛠️ Building from Source

To build the SDK from the source code, use the following command
```bash
npm run build
```

## 🧪 Running Tests

To execute the unit tests for the SDK, run:

```bash
npm test
```

## 📄 License

This SDK is licensed under the **MIT License**. See the LICENSE file for more details.
