## Architecture

Understanding the Xtrem framework architecture is crucial for effective development. This section covers the structural foundation of Xtrem applications.

### Xtrem Package Structure

Xtrem packages follow a standardized directory structure that organizes different types of framework components. Understanding this structure is essential for navigating and building Xtrem applications.

### Standard Package Layout

```
@sage/xtrem-package-name/
├── package.json              # Package metadata and dependencies
├── index.ts                  # Main package entry point
├── routing.json              # Event routing configuration
├── tsconfig.json            # TypeScript configuration
├── tsconfig-artifacts.json  # TypeScript configuration for UI
├── eslint.config.mjs        # ESLint config
├── eslint-filename.config.mjs  # ESLint config for filenames
├── lib/                     # Source code directory
│   ├── index.ts             # Library entry point
│   ├── activities/          # Security activities and permissions
│   ├── classes/             # Business logic classes
│   ├── client-functions/    # Client-side utility functions
│   ├── data-types/          # Custom data type definitions
│   ├── enums/               # Enumeration definitions
│   ├── events/              # Event handlers and business rules
│   ├── functions/           # Server-side utility functions
│   ├── i18n/                # Internationalization resources
│   ├── interfaces/          # TypeScript interface definitions
│   ├── menu-items/          # Navigation menu structure
│   ├── node-extensions/     # Extensions to existing nodes
│   ├── nodes/               # Entity definitions (database models)
│   ├── page-extensions/     # Extensions to existing pages
│   ├── page-fragments/      # Reusable page components
│   ├── pages/               # User interface pages
│   ├── service-options/     # Feature toggles and options
│   ├── shared-functions/    # Common utility functions
│   ├── stickers/            # Package-level containers
│   ├── upgrades/            # Database migration scripts
│   ├── widgets/             # Dashboard and display widgets
│   └── workflow-steps/      # Business process automation steps
├── data/                    # Static data and configuration
│   └── layers/              # Environment-specific data layers
│       ├── demo/            # Demo environment data
│       ├── setup/           # Base setup data
│       └── test/            # Test environment data
├── sql/                     # Database schema definitions
├── test/                    # Test files
│   ├── cucumber/            # Functional tests (Gherkin)
│   └── mocha/               # Unit tests
└── api/                     # Generated API definitions
```

### Package.json Configuration

Xtrem packages use specific configuration in their `package.json`:

```json
{
    "name": "@sage/xtrem-show-case",
    "description": "Xtrem Show Case",
    "version": "59.0.1",
    "xtrem": {
        "hasListeners": true, // Package has event listeners
        "isMain": true, // Main application package
        "queue": "showcase" // Message queue for processing
    },
    "keywords": ["xtrem-application-package"],
    "main": "build/index.js",
    "files": ["build", "data", "sql", "routing.json"],
    "typings": "build/package-definition.d.ts",
    "devDependencies": {
        "@eslint/js": "^9.30.1",
        "@sage/eslint-config-xtrem": "^1.1.0",
        "@sage/eslint-plugin-xtrem": "workspace:*",
        "@sage/xtrem-cli": "workspace:*",
        "@sage/xtrem-cli-bundle-dev": "workspace:*",
        "@types/jest": "^29.5.0",
        "@types/node": "^20.10.5",
        "eslint": "^9.30.1",
        "jest": "^29.5.0",
        "ts-jest": "^29.1.0",
        "typescript": "^5.4.0"
    },
    "scripts": {
        "build": "xtrem compile",
        "build:api": "xtrem build --only-api-client",
        "build:binary": "xtrem compile --binary --prod",
        "build:cache": "turbo run build --concurrency=${XTREM_CONCURRENCY:=10}",
        "clean": "rm -rf build",
        "extract:demo:data": "xtrem layers --extract demo",
        "extract:qa:data": "xtrem layers --extract qa",
        "lint": "xtrem lint",
        "lint:filename": "eslint --no-config-lookup -c eslint-filename.config.mjs --report-unused-disable-directives-severity off \"**\"",
        "load:demo:data": "xtrem layers --load setup,demo",
        "load:qa:data": "xtrem layers --load setup,qa",
        "load:setup:data": "xtrem layers --load setup",
        "load:test:data": "xtrem layers --load setup,test",
        "qa:cucumber": "xtrem test test/cucumber/* --integration --noTimeout --layers=qa",
        "qa:cucumber:browser": "xtrem test test/cucumber/* --integration --browser --noTimeout --layers=qa",
        "sonarqube:scanner": "pnpm test:ci && pnpm dlx sonarqube-scanner && rm -rf coverage .nyc_output .scannerwork junit-report-*.xml",
        "start": "xtrem start",
        "test": "xtrem test --noTimeout --unit --graphql --layers=test",
        "test:ci": "xtrem test --noTimeout --unit --ci --layers=test",
        "test:graphql": "xtrem test --noTimeout --graphql --layers=test",
        "test:smoke": "xtrem test 'test/cucumber/smoke-test*.feature' --integration --layers=test",
        "test:smoke:ci": "xtrem test 'test/cucumber/smoke-test*.feature' --integration --layers=test --ci",
        "test:smoke:static": "xtrem test test/cucumber/smoke-test-static.feature --integration --layers=test",
        "test:smoke:static:ci": "xtrem test test/cucumber/smoke-test-static.feature --integration --layers=test --ci",
        "test:unit": "xtrem test --noTimeout --unit --layers=test",
        "xtrem": "xtrem"
    },
    "c8": {
        "cache": false,
        "all": true,
        "extension": [".ts", ".tsx"],
        "sourceMap": true,
        "instrument": true,
        "reporter": ["text-summary", "clover", "json", "lcov"],
        "include": ["lib/**/*.ts"],
        "exclude": ["test/**/*", "data/**/*"]
    }
}
```

### Package Entry Points

#### Main Index File (`index.ts`)

```typescript
export * from './lib/index';
```

#### Library Index File (`lib/index.ts`)

```typescript
import '@sage/xtrem-communication';
import '@sage/xtrem-customization';

import * as activities from './activities/_index';
import * as dataTypes from './data-types/_index';
import * as enums from './enums/_index';
import * as menuItems from './menu-items/_index';
import * as nodes from './nodes/_index';
import * as serviceOptions from './service-options/_index';

export { activities, enums, dataTypes, nodes, serviceOptions, menuItems };
```

### Directory Organization

#### Core Components

- **`nodes/`**: Entity definitions representing database tables and business objects
- **`pages/`**: User interface pages and forms
- **`activities/`**: Security permissions and authorization rules
- **`service-options/`**: Feature toggles and configuration options

#### Business Logic

- **`functions/`**: Server-side business logic and utilities
- **`classes/`**: Complex business objects and processors
- **`events/`**: Event handlers for entity lifecycle and business rules
- **`workflow-steps/`**: Automated business process components

#### Data and Configuration

- **`data-types/`**: Custom field types and validation rules
- **`enums/`**: Enumerated values and option lists
- **`interfaces/`**: TypeScript type definitions
- **`i18n/`**: Localization and translation resources

#### Extensions and Customization

- **`node-extensions/`**: Modifications to existing entities
- **`page-extensions/`**: Modifications to existing pages
- **`widgets/`**: Dashboard components and visualizations
- **`stickers/`**: Package-level containers and aggregators

#### Supporting Files

- **`menu-items/`**: Navigation structure definitions
- **`client-functions/`**: Browser-side utility functions
- **`shared-functions/`**: Common utilities used across components
- **`upgrades/`**: Database migration and upgrade scripts

### Index File Patterns

Each directory typically contains an `index.ts` file that exports all components, except for pages, page-extensions, widgets and stickers:

```typescript
// activities/index.ts
export * from './show-case-product';
export * from './show-case-provider';

// nodes/index.ts
export * from './show-case-product';
export * from './show-case-provider';
export * from './show-case-invoice';

// service-options/index.ts
export * from './show-case-discount-option';
export * from './show-case-experimental-option';
```

### Package Types

#### Application Packages

Complete business applications with full component sets:

```
@sage/xtrem-sales/          # Sales management application
@sage/xtrem-purchasing/     # Purchasing management application
@sage/xtrem-manufacturing/  # Manufacturing execution application
```

#### Platform Packages

Framework and infrastructure components:

```
@sage/xtrem-core/           # Core framework functionality
@sage/xtrem-ui/             # User interface framework
@sage/xtrem-system/         # System administration
```

#### Shared Packages

Common business entities and utilities:

```
@sage/xtrem-master-data/    # Common master data entities
@sage/xtrem-structure/      # Organizational structure
@sage/xtrem-workflow/       # Workflow engine components
```

#### Integration Packages

External system connections:

```
@sage/xtrem-x3-gateway/     # X3 ERP integration
@sage/xtrem-avalara-gateway/# Tax calculation integration
```

### Routing Configuration

The `routing.json` file defines event routing for the package:

```json
{
    "@sage/xtrem-system": [
        {
            "topic": "Company/asyncExport/start",
            "queue": "import-export",
            "sourceFileName": "company.ts"
        }
    ],
    "@sage/xtrem-show-case": [
        {
            "topic": "ShowCaseProduct/created",
            "queue": "showcase",
            "sourceFileName": "show-case-product-events.ts"
        }
    ]
}
```

### Best Practices

1. **Consistent Naming**: Use `kebab-case` for directories and files, `camelCase` for variable, constant and function names and `PascalCase` for class names.
2. **Index Files**: Always provide `index.ts` files for clean exports, except for UI components like page, page-extensions, widgets and stickers.
3. **Component Separation**: Keep different component types in dedicated directories
4. **Dependencies**: Minimize cross-package dependencies
5. **Documentation**: Include README files for complex packages
6. **Testing**: Organize tests parallel to source structure

Understanding this package structure helps developers navigate the Xtrem ecosystem effectively and maintain consistency across applications.
