Skip to content
← Public packages

@cameronpak/box

Full Box Public API v1 client: lifecycle, prompts, files, commands, snapshots, environments, webhooks, desktop, hosting, and account.

src/run-code.ts

50 lines · 1.3 KB · TypeScript
import { failure, success, type Result } from './client.ts'
import runCommand from './run-command.ts'
import writeFile from './write-file.ts'
import type { CommandResult } from './types.ts'

export type RunCodeInput = {
	boxId: string
	/** Path to write the source to, relative to the box work directory. */
	path: string
	/** Source text to write before running. */
	content: string
	/** Command that runs the written file, for example "node script.js". */
	command: string
	cwd?: string
	/** 1 to 600 seconds. Defaults to 30. */
	timeoutSeconds?: number
}

export type RunCodeOutput = {
	path: string
	bytesWritten: number
	command: CommandResult
}

/**
 * Write a source file into a box and run it in one call.
 * Use this for one-off scripts; use writeFile plus runCommand for multi-file work.
 */
export default async function runCode(input: RunCodeInput): Promise<Result<RunCodeOutput>> {
	const written = await writeFile({
		boxId: input.boxId,
		path: input.path,
		content: input.content,
	})
	if (!written.ok) return failure<RunCodeOutput>(written.error)

	const ran = await runCommand({
		boxId: input.boxId,
		command: input.command,
		cwd: input.cwd,
		timeoutSeconds: input.timeoutSeconds,
	})
	if (!ran.ok) return failure<RunCodeOutput>(ran.error)

	return success({
		path: written.data.path,
		bytesWritten: written.data.size,
		command: ran.data,
	})
}