# Another service, without a package

What a JavaScript program would `npm install` for (a payment service's SDK,
a mail client, an S3 client, a model's SDK) is, in Mote, a few fns of
ordinary Mote over the back end's own means: [`net.send`](data.md#netsend)
and [`net.stream`](data.md#netstream), [`secret`](back-end.md#secrets),
[`crypto`](data.md#crypto), a [`server route`](back-end.md#routes) for the
service's webhooks, and a [`job fn`](back-end.md#later-job-fn) for what must
not be lost. The [extensions](../extensions/README.md) that ship with Mote
are that, written out; this page is how to write one for a service that is
not there, so that `extern js` is the last resort. Back to the
[map](README.md).

## What you would npm install, and what to use

| npm | In Mote |
|---|---|
| `stripe` | [stripe](stripe.md): Checkout, the portal, plans kept from the code, subscriptions, usage, invoices, tax, saved cards, disputes, Connect, webhooks checked, done once and read fresh |
| `@paypal/paypal-server-sdk`, `@paypal/checkout-server-sdk` | [paypal](paypal.md): orders approved at PayPal and captured once, subscriptions, refunds, payouts, webhooks checked by PayPal's verify call |
| `@polar-sh/sdk` | [polar](polar.md): Polar as merchant of record: checkouts, subscriptions, benefits as what an account may do, refunds, Standard Webhooks |
| `@paddle/paddle-node-sdk` | [paddle](paddle.md): Paddle Billing as merchant of record: transactions and checkout links, subscriptions, signed webhooks |
| `resend`, `@sendgrid/mail`, `nodemailer` (to an API) | [mail](mail.md): Resend or Cloudflare Email Service behind one `mailSend`, a suppression list |
| `replicate` | [replicate](replicate.md): predictions waited for, streamed, or followed across restarts |
| `@aws-sdk/client-s3`, `@aws-sdk/s3-request-presigner` | [s3](s3.md): any S3-compatible store, SigV4 written out, presigned addresses |
| `@aws-sdk/client-sqs`, `-dynamodb`, `-lambda`, `-sns`, `-sesv2`, `-bedrock-runtime`, `-secrets-manager`, `-ssm`, `-eventbridge`, `@aws-sdk/credential-providers` | [aws](aws.md): each a file over one SigV4 core, a role's keys found as AWS's tools find them |
| `googleapis`, `@google-cloud/storage`, `@google-cloud/pubsub`, `@google-cloud/bigquery`, `firebase-admin` (messaging), `@google/genai`, `google-auth-library` | [gcloud](gcloud.md): a service account, the metadata server or a person's token, then each API |
| `@azure/storage-blob`, `@azure/communication-email` | [azure](azure.md) |
| `fast-xml-parser`, `xml2js`, `xmlbuilder2` | [`xml`](data.md#xml): `xml.parse`, `xml.find`, `xml.write`, `xml.of` |
| `apn`, `@parse/node-apn`, `http2` | `net.send(…, {http2: true})`; [gcloud](gcloud.md)'s `apns.mote` |
| `@anthropic-ai/sdk`, `openai`, `@google/genai`, `ai` (Vercel) | [ai](ai.md): Anthropic, OpenAI (Responses, Chat Completions), Gemini behind one surface; streams into the page or out of a route; tools and answers from the program's own types (`schema`); batches, files, pictures, speech; costs and budgets; `AiChat` |
| `@pinecone-database/pinecone`, `@qdrant/js-client-rest`, `langchain` (text splitters, vector stores), `cohere-ai` (rerank) | [ai](ai.md#retrieval): chunks (and Markdown by headings), a vector store in the program's own database, Pinecone, Qdrant, reranking |
| `twilio` | [twilio](twilio.md): texts, Verify, signed callbacks |
| `@modelcontextprotocol/sdk` (Streamable HTTP) | [mcp](mcp.md): the program as an MCP server (tools from typed fns, resources, prompts) and a client of others, their tools in the ai loop |
| `@slack/web-api`, `@slack/bolt` | [slack](slack.md): the Web API, Block Kit, events, commands and interactivity checked and done in jobs |
| `discord.js` (REST), `discord-interactions` | [discord](discord.md): messages, embeds, components, commands, the Interactions Endpoint (Ed25519) |
| `@notionhq/client`, `notion-to-md`, `@tryfabric/martian` | [notion](notion.md): data sources queried page by page, properties plain, pages made and changed, content as Markdown both ways |
| `@linear/sdk` | [linear](linear.md): issues and comments over GraphQL, the limit held, webhooks checked and done once |
| `@octokit/rest`, `@octokit/app`, `@octokit/webhooks`, `probot` | [github](github.md): REST page by page, GraphQL, a GitHub App's JWT and installation tokens, webhooks checked and done once |
| `graphql-request`, `@apollo/client` (on a server) | [graphql](graphql.md): a query, its variables, errors as failures, a connection by its cursor |
| `telegraf`, `node-telegram-bot-api`, `grammy` | [telegram](telegram.md): the Bot API, keyboards, files, updates by webhook or long polling, once |
| `airtable` | [airtable](airtable.md): records listed and written ten a request, the base's limit kept, webhooks checked and told once |
| `@slack/webhook`, Discord webhooks | [alert](alert.md) |
| `@sentry/node` | [sentry](sentry.md), fed by `server on failure` |
| hCaptcha / Turnstile verify helpers | [captcha](captcha.md) |
| `passport-google-oauth20`, `openid-client` | [google](google.md) |
| `passport-github2`, `@azure/msal-node`, `next-auth`, `@auth/core`, `arctic`, `simple-oauth2` | [oauth](oauth.md): GitHub, Microsoft, Apple, Discord, GitLab, LinkedIn, Slack, any issuer, a connection per customer; tokens kept and refreshed (`oauthToken`) |
| `otplib`, `speakeasy`, `qrcode` | [totp](second-factor.md#codes-from-an-app-totp) |
| `@simplewebauthn/server`, `@simplewebauthn/browser` | [passkey](second-factor.md#passkeys), and `passkey.create` / `passkey.get` in a page |
| `jsonwebtoken`, `jose` (issuing) , `unkey` (API keys) | [jwt](jwt.md): `auth.keyMake`, `auth.token`, `/.well-known/jwks.json`, `requires scope(…)` |
| `openapi-fetch`, `openapi-typescript`, `@openapitools/openapi-generator-cli` | [`api Name from "spec.json" only ["op", …]`](#a-service-with-an-openapi-file): typed fns and shapes made from the service's OpenAPI file as the program is built; `mote api expand` writes them out |
| `axios`, `node-fetch`, `got` | `net.send` (any status is an answer, `retries`, `form`, `multipart`, `auth`) |
| `p-retry`, `axios-retry` | `net.send(…, {retries: 3, idempotency: key})`, which honours `Retry-After` |
| `form-data`, `qs` | `net.send`'s `multipart:` and `form:`; `net.form(record)` |
| `eventsource`, `eventsource-parser` | `net.stream(…).event()` |
| `jsonwebtoken`, `jose` | `crypto.jwt.verify`, `crypto.jwt.sign`, `crypto.sign`, `crypto.verify`, `crypto.cert` ([data.md](data.md#signatures-with-a-key-pair)) |
| `cbor`, `cbor-x` | `cbor.decode`, `cbor.encode` ([data.md](data.md#cbor)) |
| `svix`, `standardwebhooks`, `@octokit/webhooks`, `@slack/bolt`'s verifier, `twilio.validateRequest` | [`webhook.check(req, scheme, secret)`](back-end.md#webhooks): Stripe's, Standard Webhooks', GitHub's, Slack's, Twilio's, Shopify's, Paddle's, Discord's and more, or a scheme of your own; `webhook.once(id)` for each event once |
| `zod`, `ajv`, `io-ts` (checking what came back) | [`check(value, Shape)`](data.md#check): typed, or a failure that says where; `{extra: "refuse"}` |
| `zod-to-json-schema` | [`schema(Shape)`](data.md#check) (or `schema(fn)`, its parameters), `{strict: true}` for a model's structured output |
| `busboy`, `multer`, `formidable` | [`req.form()`](back-end.md#routes) at a route: `{fields, files}`, each file capped |
| `node:dns` `resolveMx`, `resolveTxt`, … | [`net.lookup(host, "TXT")`](back-end.md#dns-records), typed by kind |
| `bottleneck`, `p-limit` (per host) | [`net.pace(host, {per, max})`](back-end.md#a-host-paced-and-a-breaker) |
| `opossum` (a circuit breaker) | [`net.breaker(host, {after, rest})`](back-end.md#a-host-paced-and-a-breaker), `net.health()` |
| `redlock`, `proper-lockfile` | [`lock(name)`](back-end.md#lockname-one-run-at-a-time) + a block |
| streaming a download to disk, `got.stream` | [`net.send(…, {to: {path, resume: true}})`](data.md#to-and-from-files); `body: {file, from, length}` to send one |
| `bullmq`, `agenda` | `job fn`, `retries=`, `unique`, `.in(ms, …)` |
| `node-cron` | `server every`, `server at "03:00"` |
| `execa`, `child_process` | `proc.run([…])`, `proc.start` ([back-end.md](back-end.md#other-programs)): a list, never a shell's line, and in the access report |
| `dotenv` | `env("KEY")`, `secret("KEY")`, and `.env.example` beside the build |
| `marked`, `markdown-it` (to HTML for mail) | `syntax.parse(text, "markdown")`; [mail](mail.md#markdown)'s `mailMarkdown` |
| `sharp` (resize) | `img` ([media.md](media.md#img)) |
| `archiver`, `jszip`, `zlib` | `zip` ([data.md](data.md#zip)) |
| `better-sqlite3` | `sql`, and models |
| `pg`, `postgres`, `@neondatabase/serverless` | [postgres](postgres.md): the wire protocol in Mote, on `tcp.open` |
| `ioredis`, `redis`, `@upstash/redis` | [redis](redis.md): RESP on `tcp.open`, or Upstash's REST |
| `net`, `tls` (a protocol of its own) | `tcp.open(host, port, {tls})`: `read(n)`, `readUntil`, `line`, `write`, `startTls` ([back-end.md](back-end.md#connections-of-its-own)) |
| `ws` (a client) | `ws.open(url, {headers, reconnect})`: `send`, `next(ms)`, `ping` ([back-end.md](back-end.md#a-websocket-from-the-back-end)) |
| `generic-pool` | `tcp.take(name, {size, idle})`, `c.give()` |

## The pattern

One file, its names beginning with the service's own; one fn that talks to
the service; typed shapes for what comes back; failures with a sentence and
a kind; a secret for the key; a route for the webhooks; a test.

```mote
// docs: whole
// Acme, a service with an HTTP API: an extension of forty lines.
wants fn acmeDone(job: AcmeJob): bool = true

shape AcmeJob
  id: string
  status: string
  result: string

fn acmeBase(): string = env("ACME_API") == "" ? "https://api.acme.example" : env("ACME_API")

// The one place that talks to Acme: the key as a bearer, tried again on 429 and 5xx with
// the same idempotency key, and its refusal as its own sentence with a kind.
fn acmeCall(method: string, path: string, body: json, key: string): json
  let a = net.send(method, `${acmeBase()}${path}`, {auth: {bearer: secret("ACME_KEY")}, body, idempotency: key == "" ? uid() : key, retries: 2, timeout: 30000}) else err => fail("Acme did not answer.", {kind: "offline"})?
  if a.ok return a.json
  let kind = a.status == 401 ? "auth" : a.status == 429 ? "limited" : a.status >= 500 ? "acme" : "invalid"
  fail(`Acme: ${a.json?.error?.message ?? a.status}`, {kind, data: {status: a.status}})?
  return none

// What Acme sends, held to the shape: typed, or a failure that says where it differs.
fn acmeStart(input: string, key: string): AcmeJob = check(acmeCall("POST", "/v1/jobs", {input}, key)?, AcmeJob)?

// Acme signs its webhooks: an HMAC-SHA256 of the body under the endpoint's secret, in hex.
// Each event is done once, by a job, however often Acme sends it.
server route POST "/acme/webhook"(req) requires anyone limit 600 per minute by ip
  let event = webhook.check(req, "hex", secret("ACME_WEBHOOK_SECRET"), {header: "acme-signature"})?
  webhook.once(`acme:${event.id}`)
    acmeHeard(check(event, AcmeJob)?)
  return {status: 200, json: {received: true}}

job fn acmeHeard(job: AcmeJob) retries=5
  acmeDone(job)?

server fn paint(input: string): string requires signedIn limit 10 per hour
  return acmeStart(input, "")?.id

test "acme: a job is begun with the key, and Acme's refusal is its words"
  given secret "ACME_KEY" is "acme-test-key"
  given net "https://api.acme.example/v1/jobs" answers {status: 200, json: {id: "j1", status: "queued", result: ""}}
  trusted
    expect acmeStart("a lamp", "lamp-1").id == "j1"
    expect sent(net)[0].headers["authorization"] == "Bearer acme-test-key"
    expect sent(net)[0].headers["idempotency-key"] == "lamp-1"

text "Acme"
```

What each line is for:

- **`secret("ACME_KEY")`**: the back end does not start without it, the log
  shows `[secret]`, and the compiler refuses to send it to a page.
- **One `acmeCall`**: the service's quirks (its auth, its version header, its
  error shape, a form in place of JSON) are in one fn, and the rest of the
  file is the service's nouns.
- **`idempotency`** where the service keeps a key (Stripe, Resend): a retry
  is then one thing at the service. Where it keeps none (Twilio's texts,
  Replicate's predictions), leave `retries` off a `POST` (the compiler says
  so, `H290`) and keep what was done in a row of your own.
- **`check(answer, Shape)`** where a field matters: what the service sent
  is held to the shape as it runs (`[3].amount: a number was wanted, and
  there is "12"`), instead of trusted, or turned into text field by field.
- **A kind on every failure**, so that a caller tells "the card was refused"
  from "the service is down" without reading words.
- **A webhook route checks the signature first** with
  [`webhook.check`](back-end.md#webhooks) (over the bytes sent, in constant
  time, a replay refused: a scheme for most services by name, or one of your
  own), does each event once with `webhook.once(id)`, answers at once, and
  hands the work to a `job fn`: see `extensions/stripe/webhooks.mote`.
- **`wants fn`** for what the program decides (what to do when a job is
  done, who may), with a default where one is safe.
- **Tests with `given net`**: what was sent is `sent(net)`; and a run
  against a stand-in that speaks the service's shape (`tests/svc_standin.mjs`
  in Mote's repository) for what needs a real HTTP server: streams, webhooks
  sent back, signatures checked by the other side.
- **Say what was checked against the real service**, and how to check the
  rest: a docs page with the settings, the calls, the kinds, and the steps
  with a test key.

## A service with an OpenAPI file

Many services publish an [OpenAPI](https://spec.openapis.org/oas/v3.1.0) 3
file of their API. For the long tail (a service you call for three or four
things) keep that file in the repository and say which operations you use:

```mote
api Calendly from "./specs/calendly.json" only ["listEvents", "getEvent"]
  base "https://api.calendly.com"
  auth bearer secret("CALENDLY_TOKEN")
  header "calendly-version" "2"

server fn upcoming(): CalendlyListEventsAnswer requires signedIn
  return calendlyListEvents({count: 20, status: "active"})?
```

As the program is built the file is read (never fetched), its `$ref`s are
followed, and what it describes is made into ordinary Mote, as though a file
of it were used:

- **a fn for each operation named** (every one, without `only`), named
  after the api and the operation's `operationId`: `calendlyGetEvent(uuid)`.
  It takes the path's parameters in the path's order, then the other
  required ones (query or header), then `body` if the operation takes one,
  then `options`, a record of the optional ones (`{}` for none). A cookie
  parameter is not sent (the fn says so);
- **only the shapes those reach**, each named after the api
  (`CalendlyEvent`; one written in place is named for where it is:
  `CalendlyListEventsAnswer`, `HarborSearchBoatsAnswerHitsItem`). A field
  that is not `required`, or is `nullable` (or `type: [… "null"]`), is
  `T?`; `allOf` is its parts' fields together; `oneOf` and `anyOf` of more
  than one kind are `json`; an `enum` is its type, its values said in a
  comment; a field whose name a shape cannot hold (`home-port`) is left out
  of the shape and is still in the value. A shape may name itself;
- **one fn every call goes through** (`calendlyCall`): the address
  (`CALENDLY_API` in the environment, else `base`, else the file's first
  server, its variables at their defaults), the query (a part that is
  `none` is left out), the headers, the body as JSON, a form
  (`application/x-www-form-urlencoded`) or parts (`multipart/form-data`:
  `{photo: {data, name, type}, caption}`), the `auth` line and every
  `header` line, `retries` on a `GET` (which honour `Retry-After`; a
  `POST` is not asked twice), and a refusal as a failure with the
  service's own words (where the file describes its error: `message`,
  `error.message`, `detail`, …) and a kind: `"auth"` (401), `"refused"`
  (403), `"missing"` (404), `"conflict"` (409), `"limited"` (429),
  `"invalid"` (another 4xx), the api's name in small letters (5xx),
  `"offline"` (no answer). `err.data` is `{status, body}`;
- **what comes back held to the type the file says**, as it runs
  ([`check(answer, Shape)`](data.md#check)): a field of the wrong type, or
  missing where the file says it is required, fails as `"invalid"` with
  where (`data[2].berths: a number was wanted, and there is "4"`), and
  fields the file does not name are kept.

The lines under it, each optional: `base` (an expression: the address),
`auth bearer <key>`, `auth basic <{user, password}>`, `auth header
"x-api-key" <key>`, `auth query "api_key" <key>`, and `header "name"
<value>` for one sent with every call (a version, say).

`mote api expand app.mote` prints what was made ([cli.md](cli.md#mote-api-expand)):
read it to see what a call takes, or write it to a file and go on by hand
when the generated client is a start and not the end (an extension of your
own, with the names and the checks you want). The fns are the back end's:
call them from a `server fn`, a job, a route.

Refused when compiled: a file that cannot be read, is not JSON, or is not
OpenAPI 3 (`H322`; a YAML file: write it out as JSON first, a Swagger 2 one:
convert it); an operation `only` names that the file has not (`H323`, with
the nearest); a `$ref` that points at nothing, or into another file
(`H324`); a line that is not one of the above (`H325`).

**What is not done** (write those calls by hand, beside the made ones):
an answer that may be `none` (`T?`) is typed and not checked (every other
answer is held to its type as it runs, with
[`check`](data.md#check): `berths: a number was wanted, and there is "4"`,
kind `"invalid"`, where the service and its file disagree); a query's list is
written as `net.form` writes one (`tags[0]=a`), not `tags=a&tags=b`; no
`style`/`explode` other than the plain ones; no `$ref` into another file;
YAML; callbacks, links and webhooks the file describes; security schemes
are not read from the file (say `auth`); a body only as JSON, a form or
parts; pagination is the caller's (the answer's `next` or `cursor`, given
again). Tested against a made-up service of a dozen operations
(`tests/openapi/harbor.json`) and a stand-in for it (`tests/all.sh
real_openapi`); no published service's file has been run here.

## When there is no HTTP API

A service that speaks a protocol of its own over TCP (a database, a cache, a broker, SMTP)
is [`tcp.open`](back-end.md#connections-of-its-own): the protocol written out in Mote, as
[postgres](postgres.md) and [redis](redis.md) are, with `bytes.buffer()` to build a message
and `read(n)`, `readUntil`, `line` to take one apart. One that streams over a WebSocket is
[`ws.open`](back-end.md#a-websocket-from-the-back-end).


A service whose only client is a program (a CLI, `ffmpeg`, `pdftotext`,
`git`) is [`proc.run`](back-end.md#other-programs): the command as a list,
`input` and output as bytes where they are bytes, a `timeout`, and every
program the back end may run listed by `mote check --access`. `extern js`
is for what is neither: a library that only exists as JavaScript, and is
worth what it costs (it is not checked, not typed, and goes where the
compiler cannot follow).
