# Modules

## Overview

The `@antelopejs/interface-core/modules` module provides lifecycle events and management functions for AntelopeJS modules. Modules transition through a defined lifecycle, and each transition emits an event that other modules can observe.

## Import

```ts
import {
  Events,
  ListModules,
  GetModuleInfo,
  LoadModule,
  StartModule,
  StopModule,
  DestroyModule,
  ReloadModule,
} from "@antelopejs/interface-core/modules";
```

## Module lifecycle

A module moves through these states:

```
loaded -> constructed -> active -> constructed -> loaded
                                   (stopped)     (destroyed)
```

| State         | Description                                    |
| ------------- | ---------------------------------------------- |
| `loaded`      | Module code is loaded but no instance exists   |
| `constructed` | Module instance is created but not started     |
| `active`      | Module is fully started and providing services |
| `unknown`     | Module status cannot be determined             |

## Module execution context

`RunWithModuleContext` propagates module ownership and provider routing through synchronous and asynchronous work:

```ts
import { RunWithModuleContext } from "@antelopejs/interface-core/modules";

await RunWithModuleContext(
  {
    module: "search-provider",
    owner: "search-provider#42",
    provider: "search-provider",
    providerRoutes: routes,
  },
  () => constructModule(),
);
```

`module` remains the stable public module ID. `owner` identifies one lifecycle generation and should be unique when old and replacement instances can overlap. Providers capture this full context when attaching callbacks. `GetModuleContext` returns the active context and throws `ModuleContextInvalidatedError` after its owner is destroyed.

## Lifecycle events

The `Events` namespace exposes four `EventProxy` instances that fire during module lifecycle transitions.

### `Events.ModuleConstructed`

Fires after a module instance is created, before the module is started.

```ts
import { Events } from "@antelopejs/interface-core/modules";

Events.ModuleConstructed.register((moduleId: string) => {
  console.log(`Module constructed: ${moduleId}`);
});
```

### `Events.ModuleStarted`

Fires after a module has been started and is fully operational.

```ts
Events.ModuleStarted.register((moduleId: string) => {
  console.log(`Module started: ${moduleId}`);
});
```

### `Events.ModuleStopped`

Fires after a module has been stopped. The module instance still exists but is no longer active.

```ts
Events.ModuleStopped.register((moduleId: string) => {
  console.log(`Module stopped: ${moduleId}`);
});
```

### `Events.ModuleDestroyed`

Fires after a module instance has been destroyed and all its resources have been released. The system uses this event internally to clean up proxy attachments and event handlers associated with the destroyed module.

```ts
Events.ModuleDestroyed.register((moduleId: string) => {
  console.log(`Module destroyed: ${moduleId}`);
});
```

The event signature remains the module ID. When emitted inside `RunWithModuleContext`, cleanup targets that context's `owner`; without an explicit owner it retains the module-level behavior used by earlier releases.

## Management functions

These functions are declared as `InterfaceFunction` proxies. They are available once the core runtime provides their implementation.

### `ListModules`

Returns the identifiers of all loaded modules.

```ts
const modules = await ListModules();
// ["auth-module", "database-module", "api-module"]
```

### `GetModuleInfo`

Returns detailed information about a specific module, including its configuration, status, and file system path.

```ts
import type { ModuleInfo } from "@antelopejs/interface-core/modules";

const info: ModuleInfo = await GetModuleInfo("auth-module");
// info.status -> "active"
// info.localPath -> "/path/to/auth-module"
// info.source -> { type: "package", ... }
```

### `LoadModule`

Loads a new module with the given configuration. Set `autostart` to `true` to automatically start the module after loading.

```ts
import type { ModuleDefinition } from "@antelopejs/interface-core/modules";

const definition: ModuleDefinition = {
  source: { type: "package", package: "@my/module", version: "1.0.0" },
  config: { key: "value" },
};

await LoadModule("my-module", definition, true);
```

### `StartModule`

Starts a loaded but inactive module.

```ts
await StartModule("my-module");
```

### `StopModule`

Stops an active module. The module instance remains but stops providing services.

```ts
await StopModule("my-module");
```

### `DestroyModule`

Destroys a stopped module instance. The module code remains loaded.

```ts
await DestroyModule("my-module");
```

### `ReloadModule`

Stops, destroys, unloads, and reloads a module from its source. This is useful for applying updates without restarting the application.

```ts
await ReloadModule("my-module");
```

## `ModuleDefinition`

The configuration object for defining a module.

| Property          | Type                             | Description                                       |
| ----------------- | -------------------------------- | ------------------------------------------------- |
| `source`          | `{ type: string } & Record<...>` | Source location and loading mechanism             |
| `config`          | `unknown`                        | Optional configuration data for the module        |
| `importOverrides` | `Record<string, string[]>`       | Optional mapping of import paths to alternatives  |
| `disabledExports` | `string[]`                       | Optional list of exports to hide from this module |

## `ModuleInfo`

Extends `ModuleDefinition` with runtime information.

| Property    | Type     | Description                              |
| ----------- | -------- | ---------------------------------------- |
| `status`    | `string` | Current lifecycle state of the module    |
| `localPath` | `string` | File system path where the module exists |

## Next steps

- [Logging](./6.logging.md) - Structured logging with channels and levels
- [Configuration](./7.configuration.md) - Project configuration types
