Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

2.2 KB
Raw Blame
/**
 * Native module loader for BoxLite Node.js SDK.
 *
 * This module centralizes native binding loading to avoid duplication
 * across simplebox.ts, interactivebox.ts, and index.ts.
 *
 * Uses the napi-generated loader (boxlite.js) which handles platform
 * detection automatically - tries local file first, then npm package.
 */

import type {
  ApiKeyCredentialConstructor,
  JsBoxliteConstructor,
  NativeBoxliteRestOptionsConstructor,
  NativeModule,
} from "./native-contracts.js";
import { wrapAgents, type NativeAgents } from "./agents.js";

// @ts-expect-error - Generated by napi build --js
import * as native from "../native/boxlite.js";

// The native runtime returns native Box instances, so adapt their namespace at
// the getter boundary while retaining the rest of the Box object unchanged.
const boxPrototype = (native as unknown as { JsBox: { prototype: object } })
  .JsBox.prototype;
const agentsGetter = Object.getOwnPropertyDescriptor(boxPrototype, "agents");
if (!agentsGetter?.get || !agentsGetter.configurable) {
  throw new Error("Native Box agents getter cannot be adapted");
}
const getAgents = agentsGetter.get;
Object.defineProperty(boxPrototype, "agents", {
  ...agentsGetter,
  get() {
    return wrapAgents(getAgents.call(this) as NativeAgents);
  },
});

/**
 * Get the native BoxLite module.
 *
 * The module is loaded via the napi-generated loader which handles
 * platform-specific binary selection automatically.
 */
export function getNativeModule(): NativeModule {
  return native as NativeModule;
}

/**
 * Get the JsBoxlite runtime class from the native module.
 */
export function getJsBoxlite(): JsBoxliteConstructor {
  return getNativeModule().JsBoxlite;
}

/**
 * Get the native ApiKeyCredential class from the native module.
 */
export function getApiKeyCredential(): ApiKeyCredentialConstructor {
  return getNativeModule().ApiKeyCredential;
}

/**
 * Get the native BoxliteRestOptions class from the native module.
 *
 * Internal — the public `BoxliteRestOptions` is the pure-TS class in
 * ./options; this is the binding twin consumed by `JsBoxlite.rest`.
 */
export function getNativeBoxliteRestOptions(): NativeBoxliteRestOptionsConstructor {
  return getNativeModule().JsBoxliteRestOptions;
}