# JavaScript of your own

`extern js` names a JavaScript file of the program's own and declares, with
types, the fns it exports; `extern script` puts another site's script in the
page's head. Everything else in a Mote program is checked by the compiler;
these two lines are where that stops. **They are a last resort**: kept small
on purpose, and meant to be used as little as possible. Back to the
[map](README.md).

**Reach for something else first.** In this order:

1. **A battery or the kit**: what Mote already has (`db`, `sql`, `net`,
   `fs`, `img`, `pdf`, `font`, `gl`, the kit's components) is checked
   end to end and works on every side.
2. **An extension** (`use "pkg:…"`,
   [../extensions/README.md](../extensions/README.md)): a
   service such as a payment or mail provider is reached by an extension
   written in Mote, with no dependency.
3. **The service's HTTP API**, from a `server fn` with `net.*`
   ([data.md](data.md#net)): nearly every service has one, and the
   secret stays on the back end.
4. **A program on the back end's machine** with `proc.run`
   ([back-end.md](back-end.md#other-programs)): a command-line tool, or a script beside
   the app.

**What `extern js` is for**, when none of those will do: a widget or SDK
that exists only as a script in the browser and has no HTTP API (a map, a
card form that must run in the page), or a small piece of glue to something
the browser has and the language truly lacks. It is not a way to bring in
npm packages, and it will not grow into one. `mote build`, `mote check` and
`mote check --access` list every `extern js` file (with its fns) and every
`extern script` as "outside what is checked", so a reviewer sees the edge at
a glance.

```text
extern js "./glue.js"
  fn confetti(count: number): none
  fn mapOf(el: element, opts: {lat: number, lng: number}): json
  fn later(words: string): {said: string, length: number}

state box: element? = none
state said = ""

action burst
  confetti(80)?

action show
  if box != none
    mapOf(box, {lat: 51.5, lng: -0.1})?
  let l = later("hello") else err => {said: err, length: 0}
  said = l.said

column gap=8 padding=16
  button "Burst" press=burst
  button "Map" press=show
  column ref=box height=300
  text said
```

```js
// glue.js, beside app.mote
export function confetti(count) { /* … */ }
export function mapOf(el, opts) {
  const map = new SomeMap(el, opts);
  el.addEventListener("mote:gone", () => map.destroy());
  return { zoom: map.zoom };
}
export async function later(words) {
  return { said: words.toUpperCase(), length: words.length };
}
```

## Mental model

- A fn under `extern js` is a plain `fn` whose body is the file's export of
  that name. It is typed like any other: a call is checked against the
  parameters, and what it gives has the declared type.
- **Every call can fail** (`else` or `?`, as for a call to the back end):
  the file's code may throw, and the file may not load. **Every call waits**:
  a promise the export returns is waited for, and the compiler waits for
  the call wherever it is, as it does for `net` (nothing says `async`).
- **What comes back is checked** against the declared type, in every build:
  a text where a `number` was declared is a failure that says so
  (`wrong(…), from glue.js, is to be a number; it is a text`), and a record's
  fields and a list's items are checked too. So the program never goes on
  with a value that is not what its type says. What the program *hands* the
  file has been checked by the compiler already.
- The file is loaded once, the first time one of its fns is called (an
  `import()` of it as a module), and kept for the life of the page.
- A fn is placed as a plain fn is: on the page where the page calls it, on
  the back end where a `server fn` does, in a worker where an `off fn` does
  and the file says `off`. Each place loads the file for itself.

## The forms

```text
extern js "./glue.js"                 a file of the program's own (.js or .mjs), from the file that names it
  fn name(a: T, b: U): R              one line for each export the program calls; every type said
extern js "./work.js" off             the file touches no page: its fns may also run in a worker
extern script "https://js.stripe.com/v3/"                         another site's script, in the head
extern script "https://…/x.js" integrity="sha384-…"               the same, refused by the browser if its bytes differ
```

The compiler reads the file and refuses a declared fn it does not export
(`export function name`, `export async function`, `export const name`,
`export class`, `export { a, b as name }` are all read; a file that says
`export * from …` is not checked, since its names are not known until it
runs).

### Types at the boundary

| Declared | What the file is handed | What it must give back |
|---|---|---|
| `string`, `number`, `bool` | a string, a number, a boolean | the same (a number is finite) |
| `bytes` | a `Uint8Array` | a `Uint8Array` |
| `T[]`, `T?`, `{a: T}`, a `shape` | an array, the value or `null`, an object | the same, item by item and field by field (a shape is checked as its fields) |
| `none` (the answer only) | | anything; it is dropped, and the call gives `none` |
| `element` | the DOM element a `ref=` holds | an element |
| `json` | the value as it is | anything, unchecked |
| `(x: T) => none` | a fn the file may call later (an action started, or a lambda) | not checked |

A **callback** is a parameter written as a fn type: hand it `w => heard(w)`,
a lambda that is nothing but a call of an action, and the action runs each
time the file calls it ([language.md](language.md#a-call-that-can-fail): a
`=>` may start an action that waits).

### An element, and when it goes

A parameter of type `element` is given the element itself (`state box:
element? = none`, `ref=box` on it: [events.md](events.md#the-element-itself)),
so a third-party widget can draw inside it. The page owns the element and
may take it away (an `if` turns false, a route changes, a row is removed).
When an element that was handed to a file leaves the page, it is sent a
`mote:gone` event: the file listens for it to clean up.

```js
export function chart(el, rows) {
  const c = new Chart(el, { data: rows });
  el.addEventListener("mote:gone", () => c.destroy(), { once: true });
}
```

Draw only inside the element you were given; what is outside it is the
page's, and the runtime redraws it as state changes.

### Where it runs

| Who calls it | Where the file runs | What the file may use |
|---|---|---|
| the page (an action, a handler, a fn the page calls) | the page | `document`, `window`, the element it was handed |
| an `off fn`, with `extern js "…" off` | a worker | no page: `fetch`, `crypto`, `WebAssembly`, its own code |
| a `server fn` (and what it calls) | the back end, in Bun | Bun and Node's modules, npm packages |

A file without `off` is the page's: an `off fn` that calls one of its fns is
refused (`H244`), and a heavy fn that calls one stays on the page with it.
A file reached only by `server fn`s is never shipped beside the page.

## What ships

| Build | The page loads | The back end loads |
|---|---|---|
| `mote build` | `assets/<name>.<hash>.js`, kept a year by the browser, in the service worker's list (so it is there offline) | `server/js/<name>.<hash>.js`, beside `server/main.js`, never served |
| `mote build --single` | the file inside the page, as a `data:` address | as `mote build` |
| `mote dev` | the file as it lies, beside the entry; a change to it reloads the page | the file as it lies |

Only the one file ships. A file that imports another of its own (`import
"./helpers.js"`) will not find it once built: bundle them into one file
first, or import by a whole address (`import x from "https://esm.sh/…"`),
which the browser fetches as it would any module.

**npm packages on the back end** are the program's own business, and
not something Mote helps with (a service's HTTP API, an extension or
`proc.run` comes first). The file
may `import { PDFDocument } from "pdf-lib"`: Bun finds the package from where
the file is. Under `mote dev` that is the file's own folder (a
`node_modules` beside the entry); in a build, `server/js/`, so install the
packages where the back end runs (`cd dist && bun add pdf-lib`, or a
`node_modules` beside `dist`). Mote downloads nothing and bundles nothing.

## Another site's script

`extern script "https://js.stripe.com/v3/"` writes `<script defer src=…>`
into the head, once however many files say it, in the order written. Deferred
scripts run in order before the page's own code, so by the time any `extern
js` fn is called, what the script defines (`window.Stripe`) is there; reach
it from your file:

```text
extern script "https://js.stripe.com/v3/"

extern js "./pay.js"
  fn mountCard(el: element, key: string): none
  fn pay(secret: string): {status: string}
```

```js
// pay.js
let stripe, card;
export function mountCard(el, key) {
  stripe = Stripe(key);
  card = stripe.elements().create("card");
  card.mount(el);
  el.addEventListener("mote:gone", () => card.destroy(), { once: true });
}
export async function pay(secret) {
  const r = await stripe.confirmCardPayment(secret, { payment_method: { card } });
  return { status: r.error ? r.error.message : r.paymentIntent.status };
}
```

The address is a whole `https://` one, written out. `integrity="sha384-…"`
(Subresource Integrity, as the site that serves the script publishes it)
makes the browser refuse the script if its bytes are not those; the tag is
then also `crossorigin=anonymous`. A script of another site is not in the
service worker's list: it is fetched from that site each time, so a page
opened offline runs without it (its fns' calls fail, which `else` settles).

**Content-Security-Policy.** The page's back end sends one rule only,
`frame-ancestors` (who may show the page in a frame: `MOTE_FRAME`,
[back-end.md](back-end.md#running-it)); it says nothing of scripts, so a
script by its address and an `extern js` file need nothing more. A proxy in
front that adds a `script-src` must allow the page's own inline module,
`'self'` for the files under `assets/`, and each `extern script` address.

## Security: the edge of what is checked

Inside a Mote program the compiler knows every name, every type and every
write; an `extern js` file is outside all of that. What the compiler does
check is the boundary: the types of what is handed over, and (at run time)
the types of what comes back. It does not and cannot check what the file
does: it may read and change the page, send data anywhere, keep state of
its own, or break the page. Treat the file as you would any dependency:

- Keep it small, and keep the program's logic in Mote: the file is glue to
  a library, not the place where the app is.
- On the page, the file runs with the page's privileges: what it is
  handed, and anything on the page, is the file's to read. Hand it only what
  it needs.
- On the back end, the file runs with the back end's: its settings, its
  files, its network. A `server fn` that calls it is still guarded by its
  own `requires`; the file is not.
- A script of another site is that site's code on your page. Give it
  `integrity=` where the site publishes a hash.

This is the supported way to reach what the browser has and Mote does not:
`window`, `document` and `navigator` are not names in Mote's own code
(`H020`), and `.constructor`, `.__proto__`, `.prototype` of any value,
`eval` and `Function` are refused (`H246`: from any value they reach
JavaScript's `Function`, and so the whole page, past every check). A key
worked out while the program runs (`w[k]`, with `k` the word
`"constructor"`) finds there only a stand-in that refuses: the page, its
workers and the back end begin by putting it where a fn's constructor was
([language.md](language.md#refused-with-the-fix-in-the-message)). Your own
file runs after that too: one that makes a fn from text through a fn's
`constructor` is refused the same way (`new Function(…)` itself is the
host's, and still there).

## Pitfalls

- **Declared types are promises the file keeps.** Declare `json` only for
  what is truly anything: a wrong declared type is a failure at the first
  call, which is better than a wrong value later.
- **`none` and missing fields.** A record whose field the file leaves out is
  given `undefined` there, which is not a text: declare it `string?`.
- **One call at a time is not promised.** Two actions may call into the file
  at once; a file that keeps state must allow for that.
- **The element may already be gone** when a slow call finishes: check
  `el.isConnected` in the file before drawing into it late.
- **A file that does not say `off` touches the page**, so it never moves to a
  worker; a long loop in it runs on the page's thread.

## In the source

| File | What |
|---|---|
| `compiler/src/js.rs` | The declarations' marks, the files checked and read for their exports, the types as the runtime checks them, what each side loads, what ships, `extern script`'s head. |
| `compiler/src/parse/js.rs` | `extern js` and its block, `extern script`. |
| `runtime/shared/js.mote` | Part `XJ`: the file loaded once, the export called and waited for, what it gives checked, `mote:gone`. |
| `runtime/page/js.mote` | Part `XJB`: where the page's files are found from. |
| `tests/externjs/`, `tests/externjs.real.mjs` | The browser run. |
