• 简体中文
  • TypeScript SDK

    @a3s-lab/box 为 Node.js 20 或更高版本提供基于 Promise 的本地 API。它使用已安装的 A3S Box 运行时,不需要服务器 URL 或 API 密钥。

    安装

    npm install @a3s-lab/box

    启动应用前验证运行时:

    a3s-box --version
    a3s-box info

    创建 Sandbox

    下面是完整的 ESM TypeScript 程序:

    import { Sandbox } from '@a3s-lab/box';
    
    async function main(): Promise<void> {
      const sandbox = await Sandbox.create('node:22-alpine');
    
      try {
        const result = await sandbox.commands.run('node -e "console.log(6 * 7)"');
        console.log(result.stdout);
    
        await sandbox.files.write('/workspace/note.txt', 'hello');
        console.log(await sandbox.files.read('/workspace/note.txt'));
      } finally {
        await sandbox.kill();
      }
    }
    
    main().catch((error: unknown) => {
      console.error(error);
      process.exitCode = 1;
    });

    只要 Sandbox 生命周期超过单个表达式,就应在 finally 中清理。

    构建器式 CI/CD

    下面的完整程序从 ./ci/Dockerfile 构建镜像并执行测试:

    import { A3SBoxClient } from '@a3s-lab/box';
    
    async function main(): Promise<void> {
      const client = new A3SBoxClient();
      const image = await client
        .image('./ci')
        .dockerfile('Dockerfile')
        .tag('local/node-ci:latest')
        .buildArg('NODE_VERSION', '22')
        .build();
    
      const sandbox = await client
        .sandbox(image.reference)
        .cpus(4)
        .memoryMb(4096)
        .workdir('/workspace')
        .start();
    
      try {
        const result = await sandbox
          .script('npm ci\nnpm test\n')
          .interpreter('/bin/sh', '-se')
          .env('CI', 'true')
          .run();
    
        if (result.exitCode !== 0) {
          throw new Error(result.stderr);
        }
      } finally {
        await sandbox.kill();
      }
    }
    
    main().catch((error: unknown) => {
      console.error(error);
      process.exitCode = 1;
    });

    脚本内容通过标准输入进入客体解释器,不会插值到主机 shell。

    选择隔离

    MicroVM 是默认隔离。在经过认证的 Linux 主机上显式选择共享内核 Sandbox:

    import { Sandbox } from '@a3s-lab/box';
    
    async function main(): Promise<void> {
      const sandbox = await Sandbox.create('alpine:3.20', {
        isolation: 'sandbox',
        cpus: 2,
        memoryMb: 1024,
      });
    
      try {
        const result = await sandbox.commands.run('id');
        console.log(result.stdout);
      } finally {
        await sandbox.kill();
      }
    }
    
    main().catch((error: unknown) => {
      console.error(error);
      process.exitCode = 1;
    });

    命名桥接网络和静态端口发布仅适用于 MicroVM。支持的共享内核工作负载应使用带代际 围栏的回环转发。

    选择运行时

    仅当可执行文件不在 PATH 中时设置 A3S_BOX_BINARY,或在应用测试中注入类型化本地 运行时。SDK 与运行时交换结构化机器消息,不解析 CLI 表格。

    完整说明见 包指南npm 包