> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ferrum.thalamiq.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Packages

> Working with FHIR packages (IGs) and conformance resources.

## Implementation Features

| Feature                   | Support | Notes                                      |
| ------------------------- | ------- | ------------------------------------------ |
| **Package Installation**  | Full    | From registry or filesystem                |
| **Dependency Resolution** | Full    | Automatic dependency installation          |
| **Resource Filtering**    | Full    | Include/exclude specific resource types    |
| **Example Resources**     | Full    | Optional installation of example resources |
| **Package Tracking**      | Full    | Database tracking of installed packages    |
| **Internal Packages**     | Full    | Support for server-provided packages       |
| **Startup Installation**  | Full    | Automatic installation from config         |
| **Async Installation**    | Full    | Job queue for long-running installations   |
| **Package Listing**       | Full    | List installed packages and resources      |

## Package Sources

Ferrum supports packages from two sources:

### 1. Registry Packages

Packages from the official FHIR registry (registry.fhir.org):

* **Core FHIR packages**: `hl7.fhir.r4.core`, `hl7.fhir.r4b.core`, etc.
* **Extension packages**: `hl7.fhir.r4.extensions`
* **Terminology packages**: `hl7.fhir.r4.terminology`
* **Implementation Guides**: `hl7.fhir.us.core`, `hl7.fhir.uv.ips`, etc.

### 2. Internal Packages

Packages bundled with the server (from `fhir_packages/` directory):

* Server-specific OperationDefinitions
* Custom conformance resources
* Pre-configured profiles and extensions

## Package Installation

### Installation Methods

Packages can be installed via:

1. **Admin API** (recommended for runtime installation)
2. **\$install-package Operation** (FHIR-compliant)
3. **Startup Configuration** (automatic on server start)

### Admin API Installation

Install packages using the admin API:

```bash theme={null}
# Install US Core package
curl -X POST "http://localhost:8080/admin/packages/install" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "hl7.fhir.us.core",
    "version": "6.0.0",
    "includeDependencies": true,
    "includeExamples": false
  }'
```

Response:

```json theme={null}
{
  "jobId": "pkg-install-12345",
  "status": "accepted"
}
```

### Operation-Based Installation

Install packages using the FHIR `$install-package` operation:

```bash theme={null}
curl -X POST "http://localhost:8080/fhir/\$install-package" \
  -H "Content-Type: application/fhir+json" \
  -d '{
    "resourceType": "Parameters",
    "parameter": [
      {"name": "name", "valueString": "hl7.fhir.us.core"},
      {"name": "version", "valueString": "6.0.0"},
      {"name": "include-dependencies", "valueBoolean": true},
      {"name": "include-examples", "valueBoolean": false}
    ]
  }'
```

### Installation Options

| Option                 | Type      | Default  | Description                             |
| ---------------------- | --------- | -------- | --------------------------------------- |
| `name`                 | string    | required | Package name (e.g., `hl7.fhir.us.core`) |
| `version`              | string    | latest   | Package version (e.g., `6.0.0`)         |
| `includeDependencies`  | boolean   | `true`   | Install dependent packages              |
| `includeExamples`      | boolean   | `false`  | Include example resources               |
| `includeResourceTypes` | string\[] | all      | Only install specific resource types    |
| `excludeResourceTypes` | string\[] | none     | Exclude specific resource types         |

### Resource Type Filtering

Control which resources are installed:

```bash theme={null}
# Install only StructureDefinitions and ValueSets
curl -X POST "http://localhost:8080/admin/packages/install" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "hl7.fhir.us.core",
    "version": "6.0.0",
    "includeResourceTypes": ["StructureDefinition", "ValueSet"]
  }'

# Exclude example resources
curl -X POST "http://localhost:8080/admin/packages/install" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "hl7.fhir.us.core",
    "version": "6.0.0",
    "excludeResourceTypes": ["Patient", "Observation", "Encounter"]
  }'
```

## Package Management

### List Installed Packages

List all installed packages:

```bash theme={null}
# List all packages
curl "http://localhost:8080/admin/packages"

# Filter by status
curl "http://localhost:8080/admin/packages?status=loaded"

# Pagination
curl "http://localhost:8080/admin/packages?limit=10&offset=0"
```

Response:

```json theme={null}
{
  "packages": [
    {
      "id": 1,
      "name": "hl7.fhir.r4.core",
      "version": "4.0.1",
      "status": "loaded",
      "loadedAt": "2024-01-15T10:30:00Z",
      "resourceCount": 1234
    },
    {
      "id": 2,
      "name": "hl7.fhir.us.core",
      "version": "6.0.0",
      "status": "loading",
      "loadedAt": "2024-01-15T11:00:00Z",
      "resourceCount": 0
    }
  ],
  "total": 2,
  "limit": 100,
  "offset": 0
}
```

### Get Package Details

Get detailed information about a specific package:

```bash theme={null}
curl "http://localhost:8080/admin/packages/1"
```

Response:

```json theme={null}
{
  "id": 1,
  "name": "hl7.fhir.r4.core",
  "version": "4.0.1",
  "status": "loaded",
  "loadedAt": "2024-01-15T10:30:00Z",
  "resourceCount": 1234,
  "errorMessage": null
}
```

### List Package Resources

List all resources installed from a package:

```bash theme={null}
# List all resources
curl "http://localhost:8080/admin/packages/1/resources"

# Pagination
curl "http://localhost:8080/admin/packages/1/resources?limit=50&offset=0"
```

Response:

```json theme={null}
{
  "packageId": 1,
  "resources": [
    {
      "resourceType": "StructureDefinition",
      "id": "Patient",
      "url": "http://hl7.org/fhir/StructureDefinition/Patient",
      "version": "4.0.1"
    },
    {
      "resourceType": "ValueSet",
      "id": "administrative-gender",
      "url": "http://hl7.org/fhir/ValueSet/administrative-gender",
      "version": "4.0.1"
    }
  ],
  "total": 1234,
  "limit": 50,
  "offset": 0
}
```

## Configuration

### Startup Package Installation

Configure packages to install automatically at server startup:

```yaml theme={null}
fhir:
  version: "r4"
  
  # Default packages (core, extensions, terminology)
  default_packages:
    core: true
    extensions: true
    terminology: true
  
  # Custom packages to install
  packages:
    - name: "hl7.fhir.us.core"
      version: "6.0.0"
      install_examples: false
      filter:
        include_resource_types:
          - "StructureDefinition"
          - "ValueSet"
          - "SearchParameter"
    
    - name: "hl7.fhir.uv.ips"
      version: "1.0.0"
      install_examples: true
  
  # Registry configuration
  registry_url: "https://registry.fhir.org"  # Optional, defaults to official registry
  
  # Internal packages
  install_internal_packages: true
  internal_packages_dir: "./fhir_packages"  # Optional, defaults to ./fhir_packages
```

### Package Categories

Default packages are categorized:

* **Core**: Base FHIR specification (StructureDefinitions, etc.)
* **Extensions**: FHIR extensions
* **Terminology**: CodeSystems and ValueSets
* **Custom**: User-configured packages

## Installation Process

### Installation Flow

1. **Package Discovery**: Load package manifest from registry or filesystem
2. **Dependency Resolution**: Recursively load dependent packages
3. **Resource Collection**: Gather conformance resources (and optionally examples)
4. **Filtering**: Apply resource type filters
5. **Batch Processing**: Install resources using FHIR batch operations
6. **Indexing**: Index SearchParameters and other indexed resources
7. **Completion**: Update package status and resource counts

### Installation Status

Packages have the following statuses:

* **`loading`**: Installation in progress
* **`loaded`**: Successfully installed
* **`failed`**: Installation failed (check `errorMessage`)

### Duplicate Detection

Ferrum automatically detects if a package is already installed:

* Same `name` and `version` → Returns existing package ID
* Different version → Installs as new package
* Partial installation → Continues from where it left off

## Asynchronous Installation

Package installation runs asynchronously via the job queue:

```bash theme={null}
# 1. Submit installation request
curl -X POST "http://localhost:8080/admin/packages/install" \
  -H "Content-Type: application/json" \
  -d '{"name": "hl7.fhir.us.core", "version": "6.0.0"}'

# Response: {"jobId": "pkg-install-12345", "status": "accepted"}

# 2. Check installation status
curl "http://localhost:8080/admin/jobs/pkg-install-12345"

# 3. Monitor progress
# Job status updates as installation progresses
```

### Job Status

Package installation jobs provide progress updates:

```json theme={null}
{
  "id": "pkg-install-12345",
  "type": "install_package",
  "status": "running",
  "progress": {
    "current": 500,
    "total": 1000,
    "message": "Installing resources..."
  },
  "createdAt": "2024-01-15T10:00:00Z",
  "updatedAt": "2024-01-15T10:05:00Z"
}
```

## Package Resources

### Conformance Resources

Packages typically contain:

* **StructureDefinition**: Resource and data type definitions
* **ValueSet**: Code value sets
* **CodeSystem**: Code systems
* **SearchParameter**: Search parameter definitions
* **OperationDefinition**: Operation definitions
* **CapabilityStatement**: Server capabilities
* **CompartmentDefinition**: Compartment definitions
* **ImplementationGuide**: Implementation guide metadata

### Resource Installation

Resources are installed using FHIR batch operations:

* **PUT semantics**: Resources preserve their IDs
* **Version handling**: Resources are versioned per FHIR spec
* **Indexing**: SearchParameters are automatically indexed
* **Hooks**: Resource hooks process installed resources (e.g., CompartmentDefinition)

## Internal Packages

### Server-Provided Packages

Ferrum can include internal packages:

* Location: `fhir_packages/` directory (configurable)
* Format: Standard FHIR package structure
* Purpose: Server-specific OperationDefinitions, custom profiles

Example structure:

```
fhir_packages/
  Ferrum.fhir.server#1.0.0/
    package/
      package.json
      StructureDefinition-*.json
      OperationDefinition-*.json
```

### Internal Package Installation

Internal packages are installed automatically at startup (if enabled):

```yaml theme={null}
fhir:
  install_internal_packages: true
  internal_packages_dir: "./fhir_packages"
```

## Best Practices

### Package Selection

* **Start with core**: Always install core FHIR package first
* **Add incrementally**: Install packages as needed
* **Version pinning**: Pin specific versions for reproducibility
* **Filter resources**: Exclude unnecessary resource types to reduce storage

### Performance

* **Async installation**: Use async installation for large packages
* **Resource filtering**: Filter to only needed resource types
* **Skip examples**: Don't install examples unless needed for testing
* **Dependency management**: Let server handle dependencies automatically

### Maintenance

* **Monitor status**: Check package installation status regularly
* **Review resources**: List package resources to verify installation
* **Error handling**: Check `errorMessage` for failed installations
* **Cleanup**: Remove unused packages if needed

## Error Handling

### Common Errors

```bash theme={null}
# Package not found
curl -X POST "http://localhost:8080/admin/packages/install" \
  -d '{"name": "nonexistent.package"}'
# Returns: 400 Bad Request - Package not found in registry

# Invalid version
curl -X POST "http://localhost:8080/admin/packages/install" \
  -d '{"name": "hl7.fhir.us.core", "version": "999.0.0"}'
# Returns: 400 Bad Request - Version not found

# Invalid filter
curl -X POST "http://localhost:8080/admin/packages/install" \
  -d '{
    "name": "hl7.fhir.us.core",
    "includeResourceTypes": ["InvalidType"]
  }'
# Returns: 400 Bad Request - Invalid resource type filter
```

### Installation Failures

Failed installations include error details:

```json theme={null}
{
  "id": 2,
  "name": "hl7.fhir.us.core",
  "version": "6.0.0",
  "status": "failed",
  "errorMessage": "Failed to install 5 resources: Validation errors",
  "resourceCount": 100
}
```

## Limitations

* **No Package Removal**: Currently no API to remove installed packages
* **Version Conflicts**: Multiple versions of same package can coexist
* **Resource Updates**: Updating resources requires re-installing package
* **Registry Dependency**: Requires internet access for registry packages

## Related Documentation

* [Learn FHIR: Packages](/learn-fhir/packages)
* [FHIR Core: Packages](/fhir-core/fhir-packages)
* [Operations Documentation](/server/operations)
* [API reference: System operations](/api-reference/operations/system)
* [FHIR Package Specification](https://hl7.org/fhir/R4/package.html)
