// src/index.ts

// Node.js compatibility: provide DOM stubs before any browser class evaluates.
// Must be the first import so it runs before browser element class definitions.
import './_node-compat';

// Core (Headless Components)
export { MatrixActor } from './core/MatrixActor';
export type { ActorStatusSnapshotV1 } from './core/MatrixActor';
export { WorkstreamActor } from './core/WorkstreamActor';
export { RootActor } from './core/RootActor';
export { LispDispatchStrategy } from './core/lisp';
export type { IMessageMeta, MessageMeta } from './core/actor/IMessageMeta';
export type { ILispEnvironment } from './engine/core/ILispEnvironment';
export type { ILispSecurityContextLike } from './engine/core/ILispSecurityContextLike';
export {
  DEVELOPER_CONTEXT,
  SANDBOX_CONTEXT,
} from './core/security/LispSecurityContext';
export type { ILispSecurityContext } from './core/security/LispSecurityContext';
export type { Position } from './core/composite/Position';
export type { IAddChildOptions, IDynamicComponentDefinition } from './core/composite';
export {
  COMPONENT_RUNTIME_METADATA,
} from './core/composite/IComponentRuntimeMetadata';
export type {
  IComponentRuntimeMetadata,
  ComponentRegistrationSource,
  ComponentSourceKind,
  ComponentVersionSource,
} from './core/composite/IComponentRuntimeMetadata';
export { MockRuntime } from './core/MockRuntime';
export { HeadlessComponentRegistry } from './core/ComponentRegistry';
export type {
  IComponentRegistry,
  ComponentConstructor as HeadlessComponentConstructor,
  ComponentLoader,
} from './core/IComponentRegistry';
// Descriptor types from core (IMatrixRuntime interface is in engine/core/IMatrixContext.ts)
export type { IChildDescriptor } from './engine/core/IChildDescriptor';
export type { IComponentDescriptor } from './engine/core/IComponentDescriptor';
export { Supervisor, DEFAULT_SUPERVISION_POLICY } from './core/Supervision';
export { CheatDetector } from './core/CheatDetector';
export type {
  ISupervisionError,
  SupervisionAction,
  BuiltinStrategy,
  SupervisionFn,
  SupervisionStrategy,
  IRestartLimits,
  ISupervisionPolicy,
} from './core/Supervision';
export {
  TARGET_KEY_SEPARATOR,
  canonicalTargetKey,
  isTargetRef,
  normalizeAuthorityRoot,
  normalizeLogicalMount,
} from './core/identity/TargetRef';
export type { TargetArtifactKind, TargetRef } from './core/identity/TargetRef';
export type {
  AppRouteServedBy,
  AppRouteSource,
  AppRouteTargetSource,
  IAppRouteView,
} from './app-route/AppRouteView';

// Framework (Browser Components)
export { MatrixActorHtmlElement } from './framework/MatrixActorHtmlElement';
// TODO: MatrixActorMixin — not yet implemented
// export { MatrixActorMixin, MX } from './framework/mixin';
// export type { IMatrixProtocol, IMatrixActorStatics, IMxOracleSnapshot } from './framework/mixin';
export { isTerminalPhase } from './framework/ActivityFrame';
export type { ActivityFrame, ActivityPhase } from './framework/ActivityFrame';
export { buildCodeRef, createEmptyManifest, addManifestEntry, removeManifestEntry } from './framework/PageManifest';
export type { PageManifest, PageManifestEntry } from './framework/PageManifest';
export { ACTIVITY_SINK_KEY, CompoundActivitySink } from './framework/IActivitySink';
export type { IActivitySink } from './framework/IActivitySink';
export { RECORD_STORE_KEY } from './framework/InteractionRecord';
export type {
  InteractionRecord,
  RecordKind,
  RecordPhase,
  RecordChannel,
} from './framework/InteractionRecord';
export type {
  IRecordStore,
  RecordFilter,
  RetentionPolicy,
} from './framework/IRecordStore';
export { RECORD_STORE_PROVIDER_KEY } from './core/IRecordStoreProvider';
export type { IRecordStoreProvider } from './core/IRecordStoreProvider';
export { ShellEffectBackend } from './core/membrane/ShellEffectBackend';
export type { ShellDelegate } from './core/membrane/ShellEffectBackend';
export {
  MxContract,
  MxInterface,
  MxProxy,
  MxService,
  MxMiddlewares,
  defineComponents,
  MxTopicTag,
} from './framework/primitive-elements.js';

// Engine: Core
export type { IMatrixContext } from './engine/core/IMatrixContext';
export type { IComponentRegistryLike } from './engine/core/IComponentRegistryLike';
export type { IMatrixRuntime } from './engine/core/IMatrixRuntime';
export type { MatrixContextOptions } from './engine/core/MatrixContext';
export { MatrixContext } from './engine/core/MatrixContext';
export { ACTOR_SERVICES, ActorServices } from './engine/core/ActorServices';
export { SCOPED_INTENT_RESOLVER, ScopedIntentResolver } from './engine/core/ScopedIntentResolver';
export type { IntentScope, WellKnownServiceBinding } from './engine/core/ScopedIntentResolver';
export { Lifecycle } from './engine/core/Lifecycle';
export { Ports, parentToChild, childPorts, sendTo } from './engine/core/Ports';
export {
  PlatformAuthContract,
  PlatformCapabilitiesContract,
  UserAgentsContract,
  UserDevicesContract,
  UserRegistryContract,
  UserRuntimesContract,
} from './contracts/WellKnownServiceContracts';
export { WELL_KNOWN_SERVICE_BINDINGS } from './contracts/WellKnownServiceBindings';

// Engine: Messaging
export { TopicRouter } from './engine/messaging/TopicRouter';
export { SubscriptionBag } from './engine/messaging/SubscriptionBag';
export type { Unsub } from './engine/messaging/SubscriptionBag';
export type { MxEnvelope } from './engine/messaging/MxEnvelope';

// Engine: Reflection
export type {
  IInterfaceDescriptor,
  IMethodSpec,
  IParamSpec,
  IReturnSpec,
  Scalar,
} from './engine/reflection/IInterfaceDescriptor';
export type { IContractDescriptor as MatrixContractDescriptor } from './engine/reflection/IContractDescriptor';
export { GraphBuilder } from './engine/reflection/GraphBuilder';

// Engine: Remoting
export { RequestReply, requestReply } from './engine/remoting/RequestReply';
export type { IRrRequestOptions } from './engine/remoting/RequestReply';
export { ACTOR_CALL_CLIENT, ActorCallClient } from './engine/remoting/ActorCallClient';
export type { ActorCallOptions } from './engine/remoting/ActorCallClient';
export { RUNTIME_ADDRESS_CONTEXT } from './engine/remoting/RuntimeAddressContext';
export type { RuntimeAddressContext } from './engine/remoting/RuntimeAddressContext';
export { RequestReplyBinder, bindRR } from './engine/remoting/RequestReplyBinder';
export { RemoteProxy, proxyMount } from './engine/remoting/RemoteProxy';
export type {
  ITransportAdapter,
  ITransportAdapter as TransportAdapter,
} from './engine/remoting/ITransportAdapter';

export {
  TransportRegistry,
  getDefaultTransportRegistry,
  resetDefaultTransportRegistry,
} from './engine/remoting/TransportRegistry';
export type { ITransportRegistry } from './engine/remoting/ITransportRegistry';
export { wrapTransport } from './engine/remoting/TransportMiddleware';
export type { ITransportMiddleware } from './engine/remoting/TransportMiddleware';

// Engine: Utils
export { NameUtils, toHandlerCase } from './engine/utils/NameUtils';

// Runtime — Component Factory (Vision 45 §5)
export { createFromSchema } from './runtime/ComponentFactory';
export type { ICreateResult, ICreateOptions } from './runtime/ComponentFactory';
export { SchemaEvaluator } from './runtime/SchemaEvaluator';
export type { ISchemaEvalResult, ISchemaEvalOptions } from './runtime/SchemaEvaluator';

// Runtime
export { MatrixRuntime } from './runtime/MatrixRuntime';
export { ShellElementRegistry } from './runtime/ComponentRegistry';
export { HeadlessHost } from './runtime/HeadlessHost';
export { ConsoleLogger, NullLogger } from './runtime/ConsoleLogger';
export type { IRuntimeHost } from './runtime/IRuntimeHost';
export type { IRuntimeConfig } from './runtime/IRuntimeConfig';
export type { IRuntimeStats } from './runtime/IRuntimeStats';
export type { IRuntimeEvent, RuntimeEventType, RuntimeEventListener } from './runtime/IRuntimeEvent';
export type { IRuntimeLogger } from './runtime/IRuntimeLogger';
export type { IRuntimeComponent } from './runtime/IRuntimeComponent';
export type { IComponentRegistration } from './runtime/IComponentRegistration';
export {
  platformServiceTarget,
  requireSelectedAuthorityRoot,
  userAuthorityTarget,
} from './runtime/MatrixAuthorityContext';
export type {
  MatrixAuthorityContext,
  MatrixAuthorityTarget,
} from './runtime/MatrixAuthorityContext';
export type { IHostDocument } from './runtime/IHostDocument';
export type { IHostElement } from './runtime/IHostElement';
export type { IHostShadowRoot } from './runtime/IHostShadowRoot';
export type { IHostCustomElementRegistry } from './runtime/IHostCustomElementRegistry';
export {
  deepMergeConfig,
  resolveConfiguredPackageConfig,
} from './runtime/PackageConfigResolver';
export type {
  DeepPartial,
  IPackageConfigContract,
  IPackageConfigProviderDeclaration,
  IPackageConfigResolutionOptions,
  IResolveConfiguredPackageConfigParams,
} from './runtime/PackageConfigResolver';

// Services
export { ServiceRegistry } from './services/ServiceRegistry';
export type { IServiceMeta } from './services/ServiceRegistry';

// Transports
export { InMemoryBroker } from './transport/InMemoryBroker';
export { InMemoryTransport } from './transport/InMemoryTransport';
export type { InMemoryTransportOptions } from './transport/InMemoryTransport';
export { NatsTransport } from './transport/NatsTransport';
export type { INatsTransportOptions } from './transport/NatsTransport';
export { createTransport } from './transport/createTransport';
export type { ICreateTransportConfig } from './transport/createTransport';
export { TransportProxy } from './transport/TransportProxy';
export { WireCodecTransport } from './transport/WireCodecTransport';
// Adapter to bridge @open-matrix/federation Transport to ITransportAdapter
export { FederationTransportAdapter, wrapFederationTransport } from './transport/FederationTransportAdapter';

// Middleware (retry is transport-based, not bus-based)
export { withRetry, createRetryingRR } from './middleware/retry';
export type { IRetryOptions } from './middleware/retry';
export { withCircuitBreaker, createCircuitBreaker, CircuitBreaker, CircuitOpenError } from './middleware/circuitBreaker';
export type { ICircuitBreakerOptions, CircuitState, ICircuitStats } from './middleware/circuitBreaker';

// Flow / orchestration
export { FlowBuilder } from './flow/FlowBuilder';
export { FlowEngine } from './flow/FlowEngine';
export { createFlowContext, FlowContext } from './flow/FlowContext';
export type { IFlowContextData } from './flow/FlowContext';
export type { IFlowPlan } from './flow/FlowPlan';
export { cloneFlowPlan } from './flow/FlowPlan';
export type {
  AnyStage as FlowStage,
  ILocalMapStage,
  ILocalFilterStage,
  IRemoteRRStage,
  IRemoteSinkStage,
} from './flow/FlowTypes';

// Topology / runtime control
export type {
  IRuntimeRef,
  ITopologyComponentSpec,
  ITopologyPlan,
} from './topology/TopologyTypes';
export { TopologyBuilder } from './topology/TopologyBuilder';
export { TopologyDeployer } from './topology/TopologyDeployer';
export type {
  IRuntimeControl,
  ISpawnComponentOptions,
  ISpawnResult,
} from './runtime/RuntimeControl';
export { LocalRuntimeControl } from './runtime/LocalRuntimeControl';
export { RemoteRuntimeControl } from './runtime/RemoteRuntimeControl';

// QueryPad
export { QueryPad } from './querypad/QueryPad';

// LISP-on-Protocol
export {
  Interpreter,
  EvalContext,
  parseSExpr,
  parseSExprSingle,
  parseForEval,
  toSExpr,
  prettySExpr,
  SCHEME_EXAMPLES,
  METACIRCULAR_EVAL,
  getMetacircularEval,
  PARALLELIZABLE_OPS,
  canAtomize,
  allArgsAreAtoms,
  // Primitives
  allPrimitives,
  primitiveMap,
  buildPrimitiveMap,
  isPrimitive,
  getPrimitive,
  primitivesByCategory,
  wrapInDo,
  parseSchemeExample,
  // LISP Components
  LispEval,
  SchemeEval,
  BootstrapNode,
  // VLM Components
  VLMRouter,
  VLMJoinCoordinator,
  VLMAtomizer,
  VLMBootstrapNode,
  VLMEntryPoint,
  getVLMNamespace,
} from './lisp';
export type {
  SExpr,
  ILambdaClosure,
  IMacroDef,
  IStream,
  IStreamOperator,
  ITravelingMessage,
  IVLMTrace,
  IJoinInfo,
  IVLMTravelingMessage,
  IAtomizedMessage,
  IRemoteCallHandler,
  IInterpreterOptions,
  IPrimitiveDefinition,
  PrimitiveHandler,
  INodeInfo,
  IJoinState,
  VLMEventType,
  IVLMEvent,
} from './lisp';

// Serialization (5-Representation Parity)
export {
  serialize,
  parse,
  toHtml,
  fromHtml,
  toFluent,
  toSExpr as componentToSExpr,
  fromSExpr as componentFromSExpr,
  toTopics,
  toJson,
  toJsonSchema,
  getTopicsArray,
  getSubscriptionMap,
  getPublicationMap,
  Serializable,
} from './serialization';
export type {
  SerializationFormat,
  ISerializable,
  IComponentSchema,
  IMethodSchema,
  IEventSchema,
  IParamSchema,
  ISerializationOptions,
  IParseResult,
} from './serialization';

// Browser Runtime
export { BrowserDomStrategy } from './runtime/BrowserDomStrategy';
// MatrixDSLHost and BootstrapOptions moved to @open-matrix/browser-host
// during the core package split.
// Import from '@open-matrix/browser-host/host' instead.

// Remoting — ComponentProxy
export { ComponentProxy, createProxy } from './engine/remoting/ComponentProxy';

// Flow Viewers
export { ViewTypeRegistry } from './flow/viewers/ViewTypeRegistry';
export type { ActorViewProfile, ViewTypeRegistration, ViewMatchRule } from './flow/viewers/ViewTypeRegistry';
export { DataViewer, DataViewerShell } from './flow/viewers/DataViewer';
export { TreeViewer, TreeViewerShell } from './flow/viewers/TreeViewer';
export { TableViewer, TableViewerShell } from './flow/viewers/TableViewer';
export { ErrorViewer, ErrorViewerShell } from './flow/viewers/ErrorViewer';
export { CommandResultViewer, CommandResultViewerShell } from './flow/viewers/CommandResultViewer';

// Security
export { SecurityRealm } from './core/security/SecurityRealm';
export { DEFAULT_SECURITY_POLICY } from './core/security/defaults';
export { TopicClaimRegistry } from './core/security/TopicClaimRegistry';
export type { ITopicClaim, IClaimResult, IClaimQuery } from './core/security/ITopicClaim';
export type { MessageDirection, ISecurityRealm } from './core/security/ISecurityRealm';
export type { ICapabilityToken, CapabilityRight } from './core/security/ICapabilityToken';

// Discovery — namespace-scoped runtime presence helpers.
//
// Contract types (placement / service-registry / runtime-presence) moved
// out of @open-matrix/core to @open-matrix/contracts in Phase 2 of
// core-decontamination. Consumers must import contract types directly
// from @open-matrix/contracts/{placement,service-registry,runtime-presence};
// the runtime helpers below remain in core pending Phase 3.
export {
  publishRuntimePresence,
  runtimePresenceTopic,
  subscribeRuntimePresence,
} from './discovery/RuntimePresence';
export type {
  RuntimePresenceHandler,
  RuntimePresenceSource,
} from './discovery/RuntimePresence';
export {
  RUNTIME_DIRECTORY_MOUNT,
  countRuntimeDirectory,
  listRuntimeDirectory,
} from './discovery/RuntimeDirectory';
export type {
  IRuntimeDirectoryReadOptions,
  RuntimeDirectoryEntry,
  RuntimeDirectoryListResult,
  RuntimeDirectoryLoadedPackage,
  RuntimeDirectoryWebapp,
} from './discovery/RuntimeDirectory';
