Skip to content

Cookbook

Return nothing from onNotify() when previous is null. If the card needs something on the first run (the latest messages, say), fetch it in run() anyway; just don’t notify.

When an input changes what is watched (a different URL, feed or mailbox), the previous state belongs to something else. Keep the watched thing in the state and start over when it differs, as rss-new-entry.js does:

const previous = ctx.previous && ctx.previous.url === url ? ctx.previous : null;

The store keeps data between runs that doesn’t belong on the card. It’s saved only when the run succeeds.

// Remember the price when the item started watching, so "±10 %" means something.
const baseline = ctx.store.get("baseline") ?? price;
ctx.store.set("baseline", baseline);

For “have I seen this?” lists, cap them: ctx.store.set("seen", ids.slice(0, 500)).

The app delivers the same (type, dedupeKey) once per cooldown (six hours unless you set cooldown). Put in the key what makes the event unique:

Event Key
A new comment, release or message its id: `comment-${id}`
A count went up the count: `count-${count}`
Crossed a threshold the zone and when it was entered: `below-${zoneSince}`
A daily condition the day: `below-${ctx.now.toISOString().slice(0, 10)}`

Without a key, the title and body are the key.

const history = ctx.store.get("history") ?? [];
ctx.store.set("history", [...history, value].slice(-48));

and in summary(): { type: "sparkline", values: ctx.store.get("history") ?? [] }. The store is read-only there, which is all summary() needs.

Notify once, not once per thing:

if (fresh.length === 1) return { type: "new", title: fresh[0].title, dedupeKey: `id-${fresh[0].id}` };
return { type: "new", title: `${fresh.length} new entries`, body: fresh.slice(0, 3).map((e) => `• ${e.title}`).join("\n"), dedupeKey: `ids-${fresh[0].id}` };

Keep the new things (a few are enough) in the state so onNotify() can see them.

Follow the API’s cursor, but stop early: a run may make 100 requests and must finish within its timeout.

let url = `https://api.example.com/items?per_page=100`;
const items = [];
for (let page = 0; url && page < 10; page++) {
const res = await ctx.http.get(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
items.push(...res.json());
url = res.headers["link"]?.match(/<([^>]+)>;\s*rel="next"/)?.[1];
}

Often you don’t need every page: ask for the newest first and stop at the first thing you have already seen.

The message of a thrown error is what the user sees on the card. Say what went wrong and what to do:

if (res.status === 401) throw new Error("The API key was rejected. Check it in the item's settings.");

Implement validate(ctx) to check credentials: it runs when the user taps Test Run in the item’s settings, and should throw the same kind of message.

For flaky APIs, retry once politely: await ctx.sleep("2s"). Don’t retry forever; the app retries failed items later with a backoff.

Declare API keys and passwords as type: "secret". They live in the Keychain and reach the script only in ctx.inputs. The app masks them in logs, errors, summaries and notifications, and removes them from saved state. Read them from ctx.inputs on every run; never copy them into state.

Save a round trip’s body with conditional requests:

const cache = ctx.store.get("cache") ?? {};
const res = await ctx.http.get(url, { headers: cache.etag ? { "If-None-Match": cache.etag } : {} });
if (res.status === 304 && ctx.previous) return ctx.previous;
ctx.store.set("cache", { etag: res.headers["etag"] ?? null });

APIs that want an HMAC signature:

const timestamp = String(ctx.now.getTime());
const signature = ctx.crypto.hmac("sha256", ctx.inputs.secret, `${timestamp}GET/api/v1/balance`, { encoding: "base64" });

When the key is itself base64 (Kraken, for example), pass { keyEncoding: "base64" }. Chain signatures with keyEncoding: "hex"; see crypto for AWS Signature V4 and ES256 JWTs.

const rss = ctx.xml.parse(res.text());
for (const item of rss.findAll("channel/item")) {
const title = item.textOf("title");
const link = item.textOf("link");
}

Atom uses feed/entry with <link href="…">; rss-new-entry.js handles RSS 2.0, RSS 1.0 and Atom.

const res = await ctx.http.get(url, { headers: { Accept: "text/html" } });
const doc = ctx.html.parse(res.text());
const price = doc.querySelector(".product .price")?.text;
const stock = doc.querySelector('td:contains("Availability") + td')?.text;
const inStock = doc.querySelector("button.add-to-cart:not([disabled])") !== null;

res.text() reads the body as UTF-8. For pages in another charset, ask for responseType: "base64" and decode with ctx.encoding.decode; web-page-watch.js finds the charset in the Content-Type header or the page’s <meta charset>, and also tells a missing element apart from a captcha or bot check.

ctx.net opens TCP and TLS sockets. The host needs its port in permissions.hosts ("imap.example.com:993"). A typical line-based conversation:

const socket = await ctx.net.connect({ host, port: 993 });
const greeting = await socket.readLine();
await socket.write("a1 CAPABILITY\r\n");
for (let line; (line = await socket.readLine()) !== null && !line.startsWith("a1 "); ) { /* … */ }
await socket.close();

imap-inbox.js is a complete client: login, STATUS, UID SEARCH, literals, and decoding encoded mail headers with ctx.encoding.decode.

Use ctx.now rather than new Date(): fixtures control it, so tests are repeatable. Store dates as ISO strings (ctx.now.toISOString()), and give them to the card as { date, style }.