Api Reference

Ecosistema completo para organización y gestión de contenido con interfaces espaciales

@libs-core/action-registry - API Reference

Complete API documentation for all public interfaces, classes, and types.


Table of Contents

  1. Core Services
  2. Interfaces & Types
  3. Decorators
  4. Built-in Actions
  5. Utilities

Core Services

ActionRegistryService

Central registry for managing action metadata and lifecycle.

Properties

// Computed Signals
readonly availableActions: Signal<ActionMetadata[]>
readonly registryState: Signal<ActionRegistryState>
readonly executionState: Signal<ActionExecutionState>
readonly getActionsByType: Signal<Map<string, ActionMetadata[]>>
readonly getActionsByModule: Signal<Map<string, ActionMetadata[]>>

// Observables
readonly actionRegistered$: Observable<ActionRegisteredEvent>

Methods

register(config: ActionRegistrationConfig): void

Registers a new action in the system.

Parameters:

Throws: Error if action ID already exists and overwrite is false

Example:

actionRegistry.register({
  id: 'myModule.myAction',
  actionClass: MyAction,
  metadata: {
    name: 'My Action',
    description: 'Does something useful',
    type: 'service',
    permissions: ['myModule.execute'],
    tags: ['custom'],
    isAsync: true,
    timeout: 5000,
    retryable: false,
    maxRetries: 0
  }
});

registerMany(configs: ActionRegistrationConfig[]): void

Registers multiple actions.

unregister(actionId: string): boolean

Removes an action from the registry. Returns true if action existed.

getActionMetadata(actionId: string): ActionMetadata | undefined

Retrieves metadata for a specific action.

hasAction(actionId: string): boolean

Checks if an action is registered.

searchByTags(tags: string[]): ActionMetadata[]

Finds actions matching any of the provided tags.

searchByText(query: string): ActionMetadata[]

Searches actions by name, description, or tags.

getExecutableActions(userPermissions: string[]): ActionMetadata[]

Returns actions the user can execute based on permissions.

updateExecutionStats(actionId: string, success: boolean): void

Updates execution statistics.

setExecutionState(state: ActionExecutionState): void

Sets the current execution state.

clear(): void

Removes all registered actions and resets statistics.

exportActions(): ActionMetadata[]

Exports all registered action metadata.

importActions(actions: ActionMetadata[]): void

Imports action metadata (useful for testing/migration).

getDetailedStats(): object

Returns detailed statistics including counts by type and module.


ActionHandlerService

Executes registered actions with resilience and state management.

Properties

readonly hasActiveExecutions: Signal<boolean>

Methods

execute(actionId: string, parameters?: ActionParams, context?: ActionContext): Observable<ActionResult>

Executes a single action.

Parameters:

Returns: Observable emitting ActionResult

Example:

actionHandler.execute('core.navigate', { route: '/dashboard' })
  .subscribe({
    next: (result) => console.log('Success:', result.data),
    error: (err) => console.error('Error:', err)
  });

executeBatch(requests: ActionBatchRequest[]): Observable<ActionBatchResult>

Executes multiple actions in parallel.

Returns: ActionBatchResult with aggregated results

Example:

actionHandler.executeBatch([
  { actionId: 'action1', parameters: { id: 1 } },
  { actionId: 'action2', parameters: { id: 2 } }
]).subscribe(result => {
  console.log(`${result.successful}/${result.total} succeeded`);
});

executeSequence(requests: ActionBatchRequest[]): Observable<ActionResult[]>

Executes actions sequentially, stopping on first failure.

executeTransaction(requests: ActionTransactionRequest[]): Observable<ActionTransactionResult>

Executes actions as a transaction with rollback support.

Example:

actionHandler.executeTransaction([
  {
    actionId: 'create-order',
    parameters: { order },
    rollback: (result) => this.deleteOrder(result.data.id)
  },
  {
    actionId: 'charge-payment',
    parameters: { payment },
    rollback: (result) => this.refundPayment(result.data.id)
  }
]).subscribe(result => {
  if (result.success) {
    console.log('Transaction completed');
  } else {
    console.log('Transaction rolled back');
  }
});

cancelExecution(actionId: string): boolean

Cancels an active execution.

cancelAllExecutions(): void

Cancels all active executions.

getActiveExecutions(): Record<string, ActionExecutionState>

Returns all currently executing actions.


CircuitBreakerService

Provides circuit breaker protection for action execution.

Properties

readonly circuitCount: Signal<number>

Methods

execute(actionId: string, fn: () => Observable, config?: Partial): Observable

Executes a function with circuit breaker protection.

Parameters:

Example:

circuitBreaker.execute(
  'external-api-call',
  () => this.http.get(url),
  {
    failureThreshold: 5,
    resetTimeout: 60000,
    successThreshold: 2
  }
).subscribe(data => console.log(data));

getMetrics(actionId: string): CircuitBreakerMetrics | null

Returns metrics for a specific circuit.

getAllMetrics(): Record<string, CircuitBreakerMetrics>

Returns metrics for all circuits.

reset(actionId: string): void

Manually resets a circuit to closed state.

remove(actionId: string): void

Removes a circuit breaker.


ActionStateService

Manages execution state and history.

Properties

readonly executionHistory: Signal<ExecutionRecord[]>
readonly activeExecutions: Signal<Map<string, ExecutionInfo>>
readonly stateChanged$: Observable<ActionStateResetEvent>

Methods

recordExecution(record: ExecutionRecord): void

Records an execution in history.

getExecutionHistory(actionId?: string): ExecutionRecord[]

Retrieves execution history, optionally filtered by action ID.

clearHistory(): void

Clears all execution history.


ActionDiscoveryService

Discovers actions from modules using contracts.

Methods

discoverModuleActions(moduleContract: ModuleActionContract): Observable

Discovers actions from a single module.

discoverAllModules(modules: ModuleActionContract[]): Observable<ActionDiscoveryResult[]>

Discovers actions from multiple modules.

registerDiscoveredActions(result: ActionDiscoveryResult): void

Registers all discovered actions.

validateContract(contract: any): boolean

Validates that an object implements ModuleActionContract.


Interfaces & Types

Core Types

ActionExecutionState

type ActionExecutionState = 'idle' | 'executing' | 'success' | 'error';

ActionType

type ActionType = 'component' | 'service' | 'http' | 'custom';

ActionParams

type ActionParams = Record<string, any>;

ActionMetadata

Complete metadata for a registered action.

interface ActionMetadata {
  id: string;
  name: string;
  description: string;
  type: ActionType;
  actionClass: Type<any>;
  permissions: string[];
  tags: string[];
  parameters?: ActionParameterMetadata[];
  isAsync: boolean;
  timeout: number;
  retryable: boolean;
  maxRetries: number;
  moduleId?: string;
  registeredAt: Date;
}

ActionContext

Execution context passed to actions.

interface ActionContext {
  executionId: string;
  timestamp: Date;
  userId?: string;
  metadata: Record<string, any>;
  toJSON(): Record<string, any>;
}

ExecutionContext (Implementation):

class ExecutionContext implements ActionContext {
  public readonly executionId: string;
  public readonly timestamp: Date;
  public userId?: string;
  public metadata: Record<string, any>;

  constructor(userId?: string, metadata?: Record<string, any>) {
    this.executionId = crypto.randomUUID();
    this.timestamp = new Date();
    this.userId = userId;
    this.metadata = metadata || {};
  }

  toJSON(): Record<string, any> {
    return {
      executionId: this.executionId,
      timestamp: this.timestamp.toISOString(),
      userId: this.userId,
      metadata: this.metadata
    };
  }
}

ExecutionContextBuilder:

class ExecutionContextBuilder {
  private userId?: string;
  private metadata: Record<string, any> = {};

  withUserId(userId: string): this {
    this.userId = userId;
    return this;
  }

  withMetadata(key: string, value: any): this {
    this.metadata[key] = value;
    return this;
  }

  build(): ExecutionContext {
    return new ExecutionContext(this.userId, this.metadata);
  }
}

ActionResult

Result of action execution.

interface ActionResult<T = any> {
  success: boolean;
  data?: T;
  error?: Error;
  executedAt: Date;
  actionId: string;
  executionTime?: number;
}

ExecutableAction

Interface all actions must implement.

interface ExecutableAction<T = any> {
  execute(params: ActionParams, context: ActionContext): Observable<T>;
  validate?(params: ActionParams): Observable<boolean>;
  cleanup?(): void | Observable<void>;
}

ModuleActionContract

Contract for module integration.

interface ModuleActionContract {
  getModuleInfo(): ModuleInfo;
  discoverActions(): Observable<ActionDiscoveryResult>;
  getPublicActions(): Observable<ModuleActionConfig[]>;
  canExecuteAction(actionId: string, context: ActionContext): Observable<boolean>;
  executeAction(actionId: string, params: ActionParams, context: ActionContext): Observable<ActionResult>;
  initialize(): Observable<void>;
  cleanup(): Observable<void>;
  healthCheck(): Observable<ModuleHealthStatus>;
}

BaseModuleActionContract (Abstract implementation):

Provides default implementations for common methods.


CircuitBreakerConfig

Configuration for circuit breakers.

interface CircuitBreakerConfig {
  failureThreshold: number;    // Default: 5
  resetTimeout: number;         // Default: 60000ms
  successThreshold: number;     // Default: 2
  name?: string;
}

CircuitBreakerMetrics

Metrics for a circuit breaker.

interface CircuitBreakerMetrics {
  totalCalls: number;
  successfulCalls: number;
  failedCalls: number;
  rejectedCalls: number;
  state: CircuitState;
  lastStateChangeAt: Date;
  successRate: number;
}

Decorators

@PublicAction

Marks an action class as publicly discoverable.

function PublicAction(metadata: PublicActionMetadata): ClassDecorator

interface PublicActionMetadata {
  id: string;
  name: string;
  description: string;
  permissions?: string[];
  tags?: string[];
  config?: Record<string, any>;
}

Example:

@PublicAction({
  id: 'send-email',
  name: 'Send Email',
  description: 'Sends an email notification',
  permissions: ['email.send'],
  tags: ['communication', 'notification']
})
@Injectable({ providedIn: 'root' })
export class SendEmailAction implements ExecutableAction<boolean> {
  execute(params, context): Observable<boolean> {
    // Implementation
  }
}

@ModuleContract

Marks a class as a module contract.

function ModuleContract(moduleInfo: ModuleInfo): ClassDecorator

interface ModuleInfo {
  id: string;
  name: string;
  version: string;
  description: string;
  author?: string;
  tags: string[];
  dependencies: string[];
}

Example:

@ModuleContract({
  id: 'payment-module',
  name: 'Payment Module',
  version: '1.0.0',
  description: 'Handles payment processing',
  tags: ['payment', 'finance'],
  dependencies: []
})
@Injectable()
export class PaymentModuleContract extends BaseModuleActionContract {
  protected moduleInfo = {...};
  // Implementation
}

Built-in Actions

Navigation Actions

NavigateAction

NavigateBackAction

NavigateForwardAction

NavigateExternalAction

ReloadPageAction

NavigateReplaceAction

GetCurrentRouteAction

UI Actions

See examples.md for detailed UI action examples.

Form Actions

See examples.md for detailed form action examples.

Data Actions

See examples.md for detailed data action examples.


Utilities

ActionValidator

Provides validation utilities for actions.

class ActionValidator {
  static validateParams(params: ActionParams, schema: any): ValidationResult
  static validatePermissions(required: string[], userPerms: string[]): boolean
}

PermissionCheckerService

Checks user permissions for actions.

class PermissionCheckerService {
  checkPermission(
    actionId: string,
    userContext: UserPermissionContext
  ): Observable<PermissionCheckResult>

  checkMultiple(
    actionIds: string[],
    userContext: UserPermissionContext
  ): Observable<Map<string, PermissionCheckResult>>
}

ModuleContractUtils

Utilities for working with module contracts.

class ModuleContractUtils {
  static validateContract(contract: any): boolean
  static getPublicActionMetadata(actionClass: Type<any>): PublicActionMetadata | null
  static getModuleInfo(moduleClass: Type<any>): ModuleInfo | null
  static isPublicAction(actionClass: Type<any>): boolean
  static createFullActionId(moduleId: string, actionId: string): string
  static parseActionId(fullActionId: string): { moduleId: string; actionId: string }
}

Constants

CORE_ACTIONS

Array of all built-in action classes.

const CORE_ACTIONS = [
  ...NAVIGATION_ACTIONS,
  ...UI_ACTIONS,
  ...FORM_ACTIONS,
  ...DATA_ACTIONS
] as const;

CORE_ACTION_CONFIGS

Array of registration configurations for all built-in actions.

const CORE_ACTION_CONFIGS = [
  ...NAVIGATION_ACTION_CONFIGS,
  ...UI_ACTION_CONFIGS,
  ...FORM_ACTION_CONFIGS,
  ...DATA_ACTION_CONFIGS
] as const;

Events

ActionRegisteredEvent

Emitted when an action is registered.

class ActionRegisteredEvent extends DomainEvent<ActionMetadata> {
  public readonly eventName = 'action:registered';
  constructor(public readonly metadata: ActionMetadata)
}

ActionExecutedEvent

Emitted when an action executes successfully.

class ActionExecutedEvent extends DomainEvent {
  public readonly eventName = 'action:executed';
  constructor(public readonly payload: {
    actionId: string;
    executionId: string;
    result: ActionResult;
    duration: number;
  })
}

ActionExecutionFailedEvent

Emitted when an action execution fails.

class ActionExecutionFailedEvent extends DomainEvent {
  public readonly eventName = 'action:executionFailed';
  constructor(public readonly payload: {
    actionId: string;
    executionId: string;
    error: string;
    duration: number;
  })
}

API Version: 1.0.0 Last Updated: 2025-10-14 Status: Complete