<!-- Calling JavaScript · Tin · https://tin.ad/docs/learn/js-interop/ · generated from the built page -->

[Learn](https://tin.ad/docs/learn/) · Real programs · 25 of 34

# Calling JavaScript

**Goal.** Call JavaScript with `import js` and `extern fn`, with data checked at the boundary.

Tin's standard library is small. When you need something it doesn't have, such as a date library, a file
format or a Node built-in, you call JavaScript. You don't write bindings: you declare the function with Tin types,
and Tin checks what comes back.

## A first extern

The examples in this chapter import this module, `shapes.mjs`, which sits next to them:

```tin
// The JavaScript side of the chapter's examples.
export function hypot(a, b) {
  return Math.hypot(a, b)
}

export function corners(sides, radius) {
  const points = []
  for (let i = 0; i < sides; i++) {
    const t = (2 * Math.PI * i) / sides
    points.push({ x: Math.round(radius * Math.cos(t) * 100) / 100, y: Math.round(radius * Math.sin(t) * 100) / 100 })
  }
  return points
}

export async function slowUpper(s) {
  await new Promise((r) => setTimeout(r, 5))
  return s.toUpperCase()
}

export function root(n) {
  if (n < 0) throw new Error(`no real square root of ${n}`)
  return Math.sqrt(n)
}

export function sides(name) {
  return { triangle: 3, square: 4 }[name] ?? 'many'
}
```

`import js "./shapes.mjs"` names the module. Each `extern fn` is a function it exports,
with the types you expect:

*hello-js.tin · tin run hello-js.tin*

```tin
import js "./shapes.mjs"

extern fn hypot(a: float, b: float): float

fn main() {
  print(hypot(3.0, 4.0))
}
```

<!-- output -->
```text
5.0
```

## Data crosses, checked

Arguments and results cross as plain data: numbers, strings, arrays and objects. An object becomes a Tin
struct if it has the right fields. An `async` function needs nothing special: Tin waits for it.

*data.tin · tin run data.tin*

```tin
import js "./shapes.mjs"

type Point = { x: float, y: float }

extern fn corners(sides: int, radius: float): Point[]   // JS returns objects; Tin checks the shape
extern fn slowUpper(s: string): string                  // an async JS function: just call it

fn main() {
  let square = corners(4, 1.0)
  print("{square.len} corners, first at ({square[0].x}, {square[0].y})")
  print(slowUpper("tin"))
}
```

<!-- output -->
```text
4 corners, first at (1.0, 0.0)
TIN
```

JavaScript has no types to promise anything, so Tin checks each result on the way in. A wrong one stops the
program at the boundary, instead of turning into a bug somewhere else:

*wrong-type.tin · tin run wrong-type.tin*

```tin
import js "./shapes.mjs"

extern fn sides(name: string): int

fn main() {
  print(sides("square"))
  print(sides("hexagon"))     // the JS returns the string "many"
}
```

<!-- output -->
```text
4
panic: sides: expected an integer, got "many"
```

## Node built-ins and packages

The spec can also be a Node built-in such as `"node:path"`, or a package installed next to your
program. A block says which module answers which externs. You need one when two modules export the same name.

*node.tin · tin run node.tin*

```tin
import js "node:path" {
  extern fn basename(path: string): string
  extern fn extname(path: string): string
}

fn main() {
  print(basename("/robots/arm/pose.tin"))
  print(extname("/robots/arm/pose.tin"))
}
```

<!-- output -->
```text
pose.tin
.tin
```

Externs are checked before the program starts. A function no module exports means the program never
runs:

*missing.tin · tin run missing.tin*

```tin
import js "./shapes.mjs"

extern fn area(radius: float): float

fn main() {
  print(area(1.0))
}
```

<!-- output -->
```text
tin: no imported module exports a function 'area' (imports: ./shapes.mjs)
```

## When JavaScript throws

Usually a JS exception stops the program. Declare the extern as returning `Result<T, string>`
and a throw becomes `Err(message)` instead, which you handle like any other error (chapter 7):

*throws.tin · tin run throws.tin*

```tin
import js "./shapes.mjs"

extern fn root(n: float): Result<float, string>   // a JS throw becomes Err(message)

fn main() {
  print(root(16.0))
  print(root(-4.0))
}
```

<!-- output -->
```text
Ok(4.0)
Err("no real square root of -4")
```

## JavaScript and agents

JavaScript can do anything on the machine, so the compiler treats an extern as the capability
`js`. A tool that a model may call freely is not allowed to reach one:

*tool.tin · tin check tool.tin*

```tin
import js "./shapes.mjs"

extern fn hypot(a: float, b: float): float

/// The length of a vector.
tool fn length(x: float, y: float): float => hypot(x, y)

agent Geometer { model: "mock", tools: [length] }

fn main() {
  print(Geometer("length 3 4"))
}
```

<!-- compiler output -->
```text
error: tool 'length' can call JavaScript (an extern fn), which can do anything on this machine, without anyone approving it
 --> tool.tin:6:1
  |
6 | tool fn length(x: float, y: float): float => hypot(x, y)
  | ^^^^^^^^^^^^^^
  = note: path: length → hypot
  = note: mark it `guarded tool fn length` so a person approves each call
  = fix: mark length as guarded
```

The fix is the one from chapter 18: make it `guarded`, so a person approves each call.

The examples in this chapter use files and Node, so they run with `tin run`, not in the
playground. How a web page hosts Tin is in chapter 28.

## Tasks

### Task 1: Ask the operating system

Using `node:os`, declare `platform()` and `cpus()`. `cpus()`
returns an array of objects with a `model` field. Print whether the machine has any CPUs.

**Solution

*task-1.solution.tin · tin run task-1.solution.tin*

```tin
import js "node:os" {
  extern fn platform(): string
  extern fn cpus(): Cpu[]
}

type Cpu = { model: string }

fn main() {
  let n = cpus().len
  print(if n > 0 { "this machine has CPUs" } else { "no CPUs?" })
  print(platform().len > 0)
}
```

<!-- output -->
```text
this machine has CPUs
true
```

The struct only needs the fields you use: Tin checks `model` and ignores the rest
of each object.

### Task 2: Let a model measure

Make the `Geometer` from [JavaScript and agents](#caps) compile, and run it with
`--yes`.

**Solution

*task-2.solution.tin · tin run task-2.solution.tin --yes*

```tin
import js "./shapes.mjs"

extern fn hypot(a: float, b: float): float

/// The length of a vector. Runs JavaScript, so a person approves each call.
guarded tool fn length(x: float, y: float): float => hypot(x, y)

agent Geometer { model: "mock", tools: [length] }

fn main() {
  print(Geometer("length 3 4"))
}
```

<!-- output -->
```text
mock: 5
```

## Recap

- `extern fn` declares a JavaScript function with Tin types.
- Data is checked as it crosses, in both directions.
- An exception in JavaScript becomes an error in Tin.

In the reference: [Files, modules and import js](https://tin.ad/docs/ref/language/#files) · [Capabilities](https://tin.ad/docs/ref/agents/#capabilities)
