Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

4.2 KB
Raw Blame
#!/usr/bin/env node
// SPDX-License-Identifier: FSL-1.1-MIT
// Copyright (c) 2026 Cua AI, Inc.

/**
 * Generate the Swift binding of the Cua Spaces app export
 * (`libs/cua/crates/cua-spaces-ffi`, UniFFI namespace `cua_spaces_ffi`) into
 * this package, and fail rather than rot when it drifts (`--check`).
 *
 * The library also carries the MIT cua SDK (`cua_sdk`); its binding is the
 * `CuaSDK` module of `libs/cua/swift`, generated by
 * `libs/cua/scripts/generate-uniffi-bindings.mjs`. This binding refers to the
 * SDK's types (`Cua`, `Space`, `HostStatus`, ...), so it imports `CuaSDK`.
 *
 * Usage: node generate-bindings.mjs [--check] [--skip-build]
 */

import { spawnSync } from "node:child_process"
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { dirname, join, resolve } from "node:path"
import { fileURLToPath } from "node:url"

const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..")
const cuaRoot = resolve(packageRoot, "..", "cua")
const check = process.argv.includes("--check")
const skipBuild = process.argv.includes("--skip-build")
const CRATE = "cua_spaces_ffi"
const HEADER = "// SPDX-License-Identifier: FSL-1.1-MIT\n// Copyright (c) 2026 Cua AI, Inc.\n\n"

function run(command, args, cwd) {
  const result = spawnSync(command, args, { cwd, stdio: "inherit" })
  if (result.error) throw result.error
  if (result.status !== 0) throw new Error(`${command} exited with status ${result.status}`)
}

function normalize(source) {
  const out = source
    .replaceAll("\r\n", "\n")
    .split("\n")
    .map((line) => line.replace(/[ \t]+$/u, ""))
    .join("\n")
  return out.endsWith("\n") ? out : `${out}\n`
}

const library = (() => {
  const file =
    process.platform === "darwin"
      ? "libcua_spaces_ffi.dylib"
      : process.platform === "win32"
        ? "cua_spaces_ffi.dll"
        : "libcua_spaces_ffi.so"
  const target = process.env.CARGO_TARGET_DIR ? resolve(process.env.CARGO_TARGET_DIR) : join(cuaRoot, "target")
  return join(target, "release", file)
})()

const temporary = mkdtempSync(join(tmpdir(), "cua-spaces-ffi-"))
try {
  if (!skipBuild) run("cargo", ["build", "--locked", "--release", "-p", "cua-spaces-ffi"], cuaRoot)
  if (!existsSync(library)) throw new Error(`missing ${library}; run cargo build --release -p cua-spaces-ffi`)
  run(
    "cargo",
    ["run", "--locked", "-q", "-p", "cua-bindgen", "--", "generate", library, "--crate", CRATE,
      "--language", "swift", "--out-dir", temporary, "--no-format"],
    cuaRoot,
  )
  let swift = normalize(readFileSync(join(temporary, "CuaSpacesFFI.swift"), "utf8"))
  // The SDK's records and objects this binding passes through.
  const needle = "import Foundation\n"
  if (!swift.includes(needle)) throw new Error("expected `import Foundation` in the generated binding")
  swift = swift.replace(needle, `${needle}import CuaSDK\n`)
  // Foundation has a \`Host\` too: name the SDK's.
  swift = swift
    .split("\n")
    .map((line) => (/^\s*(\/\/|\*|\/\*)/.test(line) ? line : line.replace(/(?<![\w.])Host(?![\w])/g, "CuaSDK.Host")))
    .join("\n")
  const files = {
    "Sources/CuaSpacesFFI/CuaSpacesFFI.swift": HEADER + swift,
    "Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h": HEADER + normalize(readFileSync(join(temporary, "cua_spaces_ffiFFI.h"), "utf8")),
    "Sources/cua_spaces_ffiFFI/module.modulemap": normalize(
      readFileSync(join(temporary, "cua_spaces_ffiFFI.modulemap"), "utf8").replace(
        'header "cua_spaces_ffiFFI.h"',
        'header "include/cua_spaces_ffiFFI.h"',
      ),
    ),
  }
  const stale = []
  for (const [path, contents] of Object.entries(files)) {
    const destination = join(packageRoot, path)
    if (check) {
      if (!existsSync(destination) || readFileSync(destination, "utf8") !== contents) stale.push(path)
      continue
    }
    mkdirSync(dirname(destination), { recursive: true })
    writeFileSync(destination, contents)
  }
  if (stale.length) throw new Error(`stale Cua Spaces app binding: ${stale.join(", ")}`)
  console.log(check ? "The Cua Spaces app binding is up to date." : "Generated the Cua Spaces app binding.")
} finally {
  rmSync(temporary, { recursive: true, force: true })
}