diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 286ec67..5a969c3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,6 +23,8 @@ jobs: - run: bun audit --audit-level=high - run: bun run format:check - run: bun run typecheck + # kit/speed: the copied proto passes buf lint, and the generated code matches it. + - run: bunx buf lint && bun run generate && git diff --exit-code src/speed/gen - run: bun run test # The published files: built, loadable, and free of anything app-specific (scripts/check-package.ts). - run: bun run build diff --git a/CHANGELOG.md b/CHANGELOG.md index 973cfe7..7d791da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ All notable changes to `@jgb-solutions/kit`. Versions follow semver. - **Breaking:** `UiText` gains five strings, `shareOn` (with `{network}`), `shareByEmail`, `copyLink`, `linkCopied` and `shareMore`. The four shipped languages have them; an app that builds its own `UiText` object must add the five or it no longer type-checks. - **To know when adopting:** the patterns' rules are in `ui/patterns.css`, not in `core.css`: import both. Share buttons ship in one quiet style; a network's brand colour is the app's to set, through `--share-tone` on that button. - `kit/testing` (new): checks an app's browser tests run inside the page, so every app holds the same line. `checkTouchTargets` (every control has a 44 px touch area, no neighbour's touch area covers a button, no text under 12 px) and `adsAfterContent` (an ad never comes before the first block of content, or before the third search result). No dependency: pass them to your test runner's `page.evaluate`. +- `kit/speed` (new): typed clients for the Speed service, one per feature, starting with social cards. `createSocialCardsClient({ url, token, timeoutMs?, onFallback? })` speaks gRPC-Web over `fetch` (Connect-ES 2.3, protobuf-es 2.17), so it runs on Workers, Bun and Node: one call, no retries, a 1.5 s deadline, no redirects followed. `getCardOr(input, fallback)` never throws and never waits past the deadline: when Speed is slow, failing or not set up yet, it returns the app's own image or a colour, sized to the format, with `fromSpeed: false`. A circuit breaker per client skips Speed for 30 s after 3 failures in 30 s. `withFallback`, `CircuitBreaker` and `colorImage` are shared by every feature client. `getCard` throws a `SpeedError` with typed codes. `@connectrpc/connect`, `@connectrpc/connect-web` and `@bufbuild/protobuf` are new optional peer dependencies, needed only by this module. About 35 kB gzipped with them bundled, held by `check:size`. ## 0.9.0-beta.2 diff --git a/README.md b/README.md index e61a5b5..d395b50 100644 --- a/README.md +++ b/README.md @@ -587,6 +587,28 @@ function AccountButton() { - A menu, popover or tooltip works inside a `Dialog`: it draws above it, and Escape closes it before the dialog. - The page's global stylesheet starts with `@layer ui-sdk;`. Under a Content-Security-Policy, pages with a menu, popover or tooltip need `style-src-attr 'unsafe-inline'` and a ``: UI SDK positions popups with inline styles. The core components, dialogs and drawers included, need neither. +### `@jgb-solutions/kit/speed`: the clients for Speed (server-side) + +Typed clients for Speed, the service that does heavy work (drawing images) for an app's server, one per feature, over gRPC-Web on `fetch` (Connect-ES 2, protobuf-es 2): Cloudflare Workers, Bun and Node. Needs `@connectrpc/connect`, `@connectrpc/connect-web` and `@bufbuild/protobuf` (optional peers). The first feature is social cards, the share images for pages without one of their own: + +```ts +import { createSocialCardsClient } from '@jgb-solutions/kit/speed' + +const cards = createSocialCardsClient({ url: env.SPEED_URL, token: env.SPEED_TOKEN }) // once per isolate or process +const image = await cards.getCardOr( + { locale: 'en', page: { title: 'Animals', emoji: ['🐶', '🐱'] } }, + { url: 'https://example.com/share.png' }, +) +// { url, width, height, fromSpeed } +``` + +- **Speed never breaks a page.** `getCardOr` (and every feature's `…Or` call, built on `withFallback`) never throws and never waits past the deadline (1.5 s, no retries): when Speed is slow, failing or not set up yet (no `SPEED_URL`), it returns the app's own image (the logo on the brand colour is the recommended share image) or a colour, sized to the format. A circuit breaker skips Speed for 30 s after 3 failures in 30 s. `onFallback(reason)` counts them: `timeout`, `error`, `breaker-open`, `not-configured`. +- The same input always gives the same URL: cache it (KV, the Cache API or SQLite), but a fallback (`fromSpeed: false`) for 60 s at most. Prerendered pages ask while they are built. +- `getCard` is the call without the failover: `{ url, width, height, contentType, created, key }`, or a `SpeedError` with a `code`. +- `SPEED_TOKEN` is the app's key: server-side only. Mobile apps never call Speed; they ask their site, through its oRPC procedures. + +More in [docs/speed.md](docs/speed.md): the failover, Workers and Bun, caching, updating the API. + ## What goes in, and what never goes in **In:** generic plumbing that several apps need in the same shape, written once and tested: checking a signed token, parsing a header, a retry or rate-limit helper, a typed client for a public protocol. Every module: diff --git a/buf.gen.yaml b/buf.gen.yaml new file mode 100644 index 0000000..56aa1a7 --- /dev/null +++ b/buf.gen.yaml @@ -0,0 +1,11 @@ +# `bun run generate`: protoc-gen-es (protobuf-es 2) writes the messages and the service +# descriptor that Connect-ES 2 reads; no other plugin is needed since v2. +version: v2 +inputs: + - directory: proto +plugins: + - local: protoc-gen-es + out: src/speed/gen + opt: + - target=ts + - import_extension=js diff --git a/buf.yaml b/buf.yaml new file mode 100644 index 0000000..1779606 --- /dev/null +++ b/buf.yaml @@ -0,0 +1,8 @@ +# The Speed service's API, copied from its own repository (see proto/README.md). Lint only: +# breaking changes are decided there, not here. +version: v2 +modules: + - path: proto +lint: + use: + - STANDARD diff --git a/bun.lock b/bun.lock index a640863..752bac5 100644 --- a/bun.lock +++ b/bun.lock @@ -10,6 +10,11 @@ "devDependencies": { "@axe-core/playwright": "4.14.1", "@better-auth/passkey": "1.7.29", + "@bufbuild/buf": "1.76.0", + "@bufbuild/protobuf": "2.17.0", + "@bufbuild/protoc-gen-es": "2.17.0", + "@connectrpc/connect": "2.3.0", + "@connectrpc/connect-web": "2.3.0", "@orpc/server": "2.0.0-beta.53", "@playwright/test": "1.65.1", "@simplewebauthn/browser": "13.3.0", @@ -29,6 +34,9 @@ }, "peerDependencies": { "@better-auth/passkey": ">=1.7.22 <2", + "@bufbuild/protobuf": ">=2.17.0 <3", + "@connectrpc/connect": ">=2.3.0 <3", + "@connectrpc/connect-web": ">=2.3.0 <3", "@orpc/server": ">=2.0.0-beta.52 <3", "@ui-sdk/core": "0.1.0-beta.23", "@ui-sdk/react": "0.1.0-beta.23", @@ -40,6 +48,9 @@ }, "optionalPeers": [ "@better-auth/passkey", + "@bufbuild/protobuf", + "@connectrpc/connect", + "@connectrpc/connect-web", "@orpc/server", "@ui-sdk/core", "@ui-sdk/react", @@ -108,6 +119,32 @@ "@better-fetch/fetch": ["@better-fetch/fetch@1.3.3", "", {}, "sha512-U6SlDt/GUWtK2JAxS/NhdoYTEim+EL1G5byz2TUj83KjLZBUpYzb5SmX0aXaCnbGkAjFKnV/o/0+cyXMbEcqqg=="], + "@bufbuild/buf": ["@bufbuild/buf@1.76.0", "", { "optionalDependencies": { "@bufbuild/buf-darwin-arm64": "1.76.0", "@bufbuild/buf-darwin-x64": "1.76.0", "@bufbuild/buf-linux-aarch64": "1.76.0", "@bufbuild/buf-linux-armv7": "1.76.0", "@bufbuild/buf-linux-x64": "1.76.0", "@bufbuild/buf-win32-arm64": "1.76.0", "@bufbuild/buf-win32-x64": "1.76.0" }, "hasInstallScript": true, "bin": { "buf": "bin/buf", "protoc-gen-buf-lint": "bin/protoc-gen-buf-lint", "protoc-gen-buf-breaking": "bin/protoc-gen-buf-breaking" } }, "sha512-h0t2WASkOIRXFTBNbNYN1wCf9pTaaTjcm+0UC9HBSQ+5WizVFAb8BOHDX01Hh3q2EDtpX5TjZ9ENERU1N9btIg=="], + + "@bufbuild/buf-darwin-arm64": ["@bufbuild/buf-darwin-arm64@1.76.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-brlBzF0pMqwyMFsp53X5Csyn/rJgbbj68rmhwxPtRQYR4JAgI4brVw8B2a1L+jxj/433e4xQSCIpw+cWEE7n6w=="], + + "@bufbuild/buf-darwin-x64": ["@bufbuild/buf-darwin-x64@1.76.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-ydyskIrzjo+hnqzC/nLobqKMlJH18mWpZB959CPHKm6jrnBkKqDuEVnz1/S5uv930MX/eawCr6KXqeLD57n1Mg=="], + + "@bufbuild/buf-linux-aarch64": ["@bufbuild/buf-linux-aarch64@1.76.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-G+Qz/+fKdRAEW04Fgnh8sgam8yx1vQ3D50B0KL5yXP/nAwo19oBqHQGeZFbW+POlEpG0P9EMJ76Nt1Kwfu53Mw=="], + + "@bufbuild/buf-linux-armv7": ["@bufbuild/buf-linux-armv7@1.76.0", "", { "os": "linux", "cpu": "arm" }, "sha512-9y5ny80CN7nPNd7e3Mgj9xqmGhXVtZ4Qjvf+/bgdbA/k/cWU56xHYNIp5t88qABTxupk1hdanwtIr75VCBxPnw=="], + + "@bufbuild/buf-linux-x64": ["@bufbuild/buf-linux-x64@1.76.0", "", { "os": "linux", "cpu": "x64" }, "sha512-fXwFYldq++xZKn1tLOsHF8cq3OXecSCraaWnhJm8D7GJ6f85kZ6ibBuepA80tRb8bMZfyCBH+p3aSWHz5hOIwQ=="], + + "@bufbuild/buf-win32-arm64": ["@bufbuild/buf-win32-arm64@1.76.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-dKe/3wtEZ8njRgLgsHBEMgEaWN0Vc9N7bGC25MiT8R9bzpYEUKwMK2wz8lljCUdcHoPPOa+2ZnOB5XsG6/qczQ=="], + + "@bufbuild/buf-win32-x64": ["@bufbuild/buf-win32-x64@1.76.0", "", { "os": "win32", "cpu": "x64" }, "sha512-3VWgn8EkGaTOCMNo7eA/ZbHT4bRIDYbL0pAwdeUlv4gACu+eGLPMmoJZoBonWBQ7E529O/YtFZhXmzlNlrElTw=="], + + "@bufbuild/protobuf": ["@bufbuild/protobuf@2.17.0", "", {}, "sha512-hcPkSz6D7MiTU/5VBBhK+kxaYDoOdQ6yJRFJ3kS8Nydp+VZXfg1vrpABKPNod8bXMufsVCmiUJVIKFzCzta4uw=="], + + "@bufbuild/protoc-gen-es": ["@bufbuild/protoc-gen-es@2.17.0", "", { "dependencies": { "@bufbuild/protobuf": "2.17.0", "@bufbuild/protoplugin": "2.17.0" }, "bin": { "protoc-gen-es": "bin/protoc-gen-es" } }, "sha512-Uk8Hx145z76lDOEPhWChy53jtKITUnqG0vASuOiRybbZbBbx4oho9JDqt8QZsHemeTCNl6q4yy4Qpc2iV5outQ=="], + + "@bufbuild/protoplugin": ["@bufbuild/protoplugin@2.17.0", "", { "dependencies": { "@bufbuild/protobuf": "2.17.0", "@typescript/vfs": "^1.6.2", "typescript": "5.4.5" } }, "sha512-4ExU8AGygKkwIx3U8D5kyBOn9rcCM1qnj4wCP95RbP1CRe73QvVGHQ/lOp6IQiyvQMh9BGrYGht+ZDa8gwC2fg=="], + + "@connectrpc/connect": ["@connectrpc/connect@2.3.0", "", { "peerDependencies": { "@bufbuild/protobuf": "^2.7.0" } }, "sha512-rjAn8L9KbAZrkwiB8m1qzDsLs74hkYmwwM2iSWuxTPVOTRm/EZw31smKbQqPU50AXqJC5eKKpEnA6Uf/swQOgQ=="], + + "@connectrpc/connect-web": ["@connectrpc/connect-web@2.3.0", "", { "peerDependencies": { "@bufbuild/protobuf": "^2.7.0", "@connectrpc/connect": "2.3.0" } }, "sha512-JPXOiWaVsj+ZwaXOQjwvhc0ORnkl0a1w36Qyl3j1WTuak6/VYyuWGl1Aq8I60gQfQRjsjLLFGr64tO0sjwstcg=="], + "@hexagon/base64": ["@hexagon/base64@1.1.28", "", {}, "sha512-lhqDEAvWixy3bZ+UOYbPwUbBkwBq5C1LAJ/xPC8Oi+lL54oyakv/npbA0aU2hgCsx/1NUd4IBvV03+aUBWxerw=="], "@isaacs/ttlcache": ["@isaacs/ttlcache@1.4.1", "", {}, "sha512-RQgQ4uQ+pLbqXfOmieB91ejmLwvSgv9nLx6sT6sD83s7umBypgg+OIBOBbEUiJXrfpnp9j0mRhYYdzp9uqq3lA=="], @@ -228,6 +265,8 @@ "@types/yargs-parser": ["@types/yargs-parser@21.0.3", "", {}, "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ=="], + "@typescript/vfs": ["@typescript/vfs@1.6.6", "", { "dependencies": { "debug": "^4.4.3" }, "peerDependencies": { "typescript": "*" } }, "sha512-gXw0+tpchiQUjTcbnNIPnyLFIhbwJ7M1VaxLQ1vXhjQxtTBK3sdDLY1ih0jxCu1I5K3V0dDxq8CkVZtIMspC3A=="], + "@ui-sdk/core": ["@ui-sdk/core@0.1.0-beta.23", "", {}, "sha512-lf+hlu/5gijnjXsPL/VtTPTSzzoL18lSt4WJ9jfUg7xdU3QN4WH/AjXs/z6Vdp6+Ctg2gqpliAqidlJkYg8omg=="], "@ui-sdk/react": ["@ui-sdk/react@0.1.0-beta.23", "", { "peerDependencies": { "@types/react": ">=19.2.10", "@ui-sdk/core": "^0.1.0-beta.23", "react": ">=19", "react-dom": ">=19" }, "optionalPeers": ["@types/react"] }, "sha512-3ahRPFjaN5TgVV/lucbZ8mZ8G/vqmaEVPFS2EGAY0u5SsvvhW9BMTr5Mx5iiRcOvF5e/qd1WNmnj7wQs2o1ekQ=="], @@ -634,6 +673,8 @@ "@babel/helper-compilation-targets/semver": ["semver@6.3.2", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ=="], + "@bufbuild/protoplugin/typescript": ["typescript@5.4.5", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ=="], + "chalk/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], "chalk/supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="], diff --git a/docs/speed.md b/docs/speed.md new file mode 100644 index 0000000..f1f1569 --- /dev/null +++ b/docs/speed.md @@ -0,0 +1,179 @@ +# kit/speed: the clients for Speed + +Speed is a separate service that does work an app's server shouldn't do on each request, such as drawing +images. `@jgb-solutions/kit/speed` holds one typed client per feature, all with the same failover. The first +feature is **social cards**: the share images (og:image, twitter:image, Pinterest pins, stories) for pages +without an image of their own. + +The clients speak gRPC-Web over `fetch`, through [Connect-ES](https://connectrpc.com/docs/web/getting-started) +2 and messages generated by [protobuf-es](https://github.com/bufbuild/protobuf-es) 2, so the same code runs +on Cloudflare Workers, Bun and Node. Install the three optional peers next to the kit: + +```sh +bun add @connectrpc/connect @connectrpc/connect-web @bufbuild/protobuf +``` + +## Settings + +| Variable | What | +| ------------- | --------------------------------------------------------------------------------------- | +| `SPEED_URL` | Speed's base address, `https://…` (plain `http://` is accepted on localhost only). | +| `SPEED_TOKEN` | The app's key for Speed, sent as `authorization: Bearer …`. A secret, server-side only. | + +The token says which app is calling; Speed keeps each app's colours, logo and fonts, so a request carries +only the text. Keep the token in a Worker secret (`wrangler secret put SPEED_TOKEN`) or the server's +environment, never in code or in anything sent to a browser or a phone. + +**Not set yet?** Leave both out. The client still works: every `…Or` call returns its fallback at once, +without a call or an error (`onFallback` hears `not-configured`). So an app can ship before Speed is live, +and switches to Speed's images when the two variables appear. Settings that are set but unsafe (an address +that isn't HTTPS, a token with spaces or control characters) throw when the client is created. + +## The failover: Speed never breaks a page + +Every feature has a `…Or` call that returns an image whatever happens: + +```ts +{ url: string, width: number, height: number, fromSpeed: boolean } +``` + +- **Never throws, never waits past the deadline** (1500 ms by default, `timeoutMs` to change it; no retries). + When Speed is slow, answers with an error, or refuses the input, you get the fallback. +- **A circuit breaker per client.** After 3 failures within 30 s, the client stops calling Speed for 30 s + and returns the fallback at once, so a down Speed adds no time to page views. Then one trial call goes + through: a success closes the circuit, a failure opens it for another 30 s. Create the client once per + Worker isolate (at module level, or cached from `env`) or once per Bun process, so it remembers. +- **The fallback is yours:** an image of the app's own, or a hex colour. + - **Recommended for social cards: the site's logo on its brand colour**, as an image at the card's size + (the 1200×630 share image every project already has in `branding/`). It is sized to the format unless you + give `width` and `height`. + - **A colour** (`{ color: '#1f6feb' }`) becomes a tiny inline SVG of the format's size. Use it for images + inside your own pages; social networks don't read inline (`data:`) images, so og:image needs a URL. +- **Count them.** `onFallback(reason, error?)` hears each fallback: `timeout`, `error`, `breaker-open` or + `not-configured`. Its `error` is a `SpeedError`; log its `code` and `message`, never the token (the client + never puts it in either). + +```ts +import { createSocialCardsClient } from '@jgb-solutions/kit/speed' + +const cards = createSocialCardsClient({ + url: env.SPEED_URL, + token: env.SPEED_TOKEN, + onFallback: (reason) => fallbacks.add(1, { reason }), // your metrics +}) + +const image = await cards.getCardOr( + { locale: 'fr', format: 'link', page: { title: 'Animaux', emoji: ['🐶', '🐱'] } }, + { url: 'https://example.com/share.png' }, // the logo on the brand colour, 1200×630 +) +``` + +New feature clients reuse the same parts: `withFallback(call, fallback, { timeoutMs, breaker, onFallback })` +never throws and never waits past `timeoutMs`, whatever `call` does; `CircuitBreaker` and `colorImage` are +exported too. + +**Images inside the app's pages** (posters, avatars) that are missing in the browser fall back in the +component instead: kit/ui's `Avatar` and `Poster` draw the title's initials on a colour when there is no +picture or it fails to load. The failover here is +the server's, for images it asks Speed for. + +## Social cards + +```ts +const card = await cards.getCard({ + locale: 'fr', // en, fr, es or ht: the text is already in this language + format: 'link', // link 1200×630 (the default), square 1080×1080, portrait 1000×1500, story 1080×1920 + emoji: { emoji: '🐶', title: 'Chien', subtitle: 'Un ami fidèle', label: 'Animaux' }, + // or: page: { title: 'Animaux', subtitle: '…', emoji: ['🐶', '🐱'] } +}) +// { url: 'https://…/….png', width: 1200, height: 630, contentType: 'image/png', created: true, key: '…' } +``` + +- `getCard` is the call without the failover: it throws a `SpeedError` whose `code` is `timeout`, + `canceled`, `unauthenticated`, `forbidden`, `invalid_input`, `rate_limited`, `unavailable`, + `bad_response`, `not_configured` or `failed`. Pass `{ signal }` as its second argument to stop it sooner. + Pages should use `getCardOr`. +- **Same input, same URL.** Speed draws a card once and stores it; asking again returns the stored URL. +- **Checked answers.** A card whose address isn't HTTPS (or carries a user name or password), without a + size, or with a malformed `key` is refused as `bad_response`. `key` is an identifier: never use it as a + file path. The URL is a URL: escape it like any other value when you write it into HTML (the app's `seo()` + helper does). +- **No redirects.** The client never follows one, so the token never goes to another address. +- `CARD_SIZES` holds each format's size, for og:image:width and og:image:height. + +### Cache the URL + +The card's URL never changes for the same input, so ask Speed once per page and language, and keep the +answer. Key it by what the card shows (a hash of the input), not by the request. + +- **Cloudflare Workers:** KV (`get`, then `put` after a miss), or the Cache API for the page itself. +- **Bun on a server:** a small SQLite table (`card_key TEXT PRIMARY KEY, url TEXT, expires_at INTEGER`). +- **Never cache a fallback as the answer.** When `fromSpeed` is false, keep it for at most + `FALLBACK_TTL_SECONDS` (60), marked as a fallback, so Speed's card replaces it as soon as Speed is back. + +```ts +import { FALLBACK_TTL_SECONDS, type GetCardInput } from '@jgb-solutions/kit/speed' + +async function cardFor(env: Env, input: GetCardInput) { + // A hash keeps the key short (KV keys stop at 512 bytes) whatever the text. + const what = new TextEncoder().encode(JSON.stringify([input.locale, input.format ?? 'link', input.emoji ?? input.page])) + const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', what)) + const key = `card:${Array.from(hash, (byte) => byte.toString(16).padStart(2, '0')).join('')}` + const cached = await env.CARDS.get<{ url: string; width: number; height: number }>(key, 'json') + if (cached) return cached + const image = await cards.getCardOr(input, { url: 'https://example.com/share.png' }) + // Speed's card for good; a fallback for a minute only (KV's shortest expiry). + await env.CARDS.put(key, JSON.stringify(image), image.fromSpeed ? {} : { expirationTtl: FALLBACK_TTL_SECONDS }) + return image +} +``` + +### Prerendered pages + +A page that is prerendered asks for its card while it is built: the build runs with `SPEED_URL` and +`SPEED_TOKEN` in its environment and writes the URL into the page's tags. With the failover, a build never +fails because Speed is down; the next build picks the card up. + +### Mobile apps + +A mobile app never calls Speed and never holds `SPEED_TOKEN`. When it needs a card (to share a page, say), +it asks its own site, through the site's oRPC procedures, and the site calls Speed. + +## On a Worker + +```ts +import { createSocialCardsClient, type SocialCardsClient } from '@jgb-solutions/kit/speed' + +type Env = { SPEED_URL?: string; SPEED_TOKEN?: string } +let cards: SocialCardsClient | undefined // one per isolate, so its circuit breaker remembers + +export default { + async fetch(request, env) { + cards ??= createSocialCardsClient({ url: env.SPEED_URL, token: env.SPEED_TOKEN }) + const image = await cards.getCardOr({ locale: 'en', page: { title: 'Home' } }, { url: 'https://example.com/share.png' }) + // Put it in the page's tags through the app's own head helper, which escapes it. + return Response.json(image) + }, +} satisfies ExportedHandler +``` + +The client is about 35 kB gzipped (Connect-ES and protobuf-es included), counted in the Worker's size. +It works whatever the Worker's compatibility date: Connect asks fetch for `redirect: 'error'`, which Workers +refuse before 2026-12-22 unless the `fetch_redirect_error` flag is set, so the client sends `manual` and +refuses redirects itself. + +## On Bun + +```ts +import { createSocialCardsClient } from '@jgb-solutions/kit/speed' + +export const cards = createSocialCardsClient({ url: Bun.env.SPEED_URL, token: Bun.env.SPEED_TOKEN }) +``` + +Create it once at start-up and share it. + +## Updating the API + +The `.proto` files in `proto/` are copies of Speed's own (see `proto/README.md`). After copying a new +version, run `bun run generate` (buf, then protoc-gen-es) and commit `src/speed/gen/` with it. CI checks +that the two match. diff --git a/package.json b/package.json index faeaabe..9a27f4b 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,10 @@ "design-system", "accessible", "sign-in", - "react-native" + "react-native", + "grpc-web", + "connect-rpc", + "social-cards" ], "type": "module", "sideEffects": [ @@ -125,6 +128,10 @@ "types": "./dist/testing.d.ts", "import": "./dist/testing.js" }, + "./speed": { + "types": "./dist/speed.d.ts", + "import": "./dist/speed.js" + }, "./package.json": "./package.json" }, "engines": { @@ -154,7 +161,8 @@ "screenshots:account": "bun --bun playwright test e2e/account-screenshots.spec.ts", "screenshots:ui": "bun --bun playwright test e2e/ui-screenshots.spec.ts", "screenshots:overlays": "bun --bun playwright test e2e/overlays-screenshots.spec.ts", - "screenshots:showcase": "bun --bun playwright test e2e/showcase-screenshots.spec.ts" + "screenshots:showcase": "bun --bun playwright test e2e/showcase-screenshots.spec.ts", + "generate": "buf generate && bun fmt src/speed/gen" }, "dependencies": { "jose": "6.2.19" @@ -168,7 +176,10 @@ "react-native": ">=0.79 <1", "react-native-svg": ">=15 <16", "@ui-sdk/core": "0.1.0-beta.23", - "@ui-sdk/react": "0.1.0-beta.23" + "@ui-sdk/react": "0.1.0-beta.23", + "@bufbuild/protobuf": ">=2.17.0 <3", + "@connectrpc/connect": ">=2.3.0 <3", + "@connectrpc/connect-web": ">=2.3.0 <3" }, "peerDependenciesMeta": { "better-auth": { @@ -197,11 +208,25 @@ }, "@ui-sdk/react": { "optional": true + }, + "@bufbuild/protobuf": { + "optional": true + }, + "@connectrpc/connect": { + "optional": true + }, + "@connectrpc/connect-web": { + "optional": true } }, "devDependencies": { "@axe-core/playwright": "4.14.1", "@better-auth/passkey": "1.7.29", + "@bufbuild/buf": "1.76.0", + "@bufbuild/protobuf": "2.17.0", + "@bufbuild/protoc-gen-es": "2.17.0", + "@connectrpc/connect": "2.3.0", + "@connectrpc/connect-web": "2.3.0", "@orpc/server": "2.0.0-beta.53", "@playwright/test": "1.65.1", "@simplewebauthn/browser": "13.3.0", diff --git a/proto/README.md b/proto/README.md new file mode 100644 index 0000000..78a0c8a --- /dev/null +++ b/proto/README.md @@ -0,0 +1,6 @@ +# Speed's API, copied + +`speed/socialcards/v1/social_cards.proto` is a copy of the Speed service's own definition (package +`speed.socialcards.v1`), taken unchanged from the service's repository at commit `10648f9`. The service owns +it: changes are made there first, then copied here, and `bun run generate` rewrites `src/speed/gen/` from it +(buf and protobuf-es's `protoc-gen-es`). CI fails if the generated code no longer matches this file. diff --git a/proto/speed/socialcards/v1/social_cards.proto b/proto/speed/socialcards/v1/social_cards.proto new file mode 100644 index 0000000..85910f2 --- /dev/null +++ b/proto/speed/socialcards/v1/social_cards.proto @@ -0,0 +1,90 @@ +syntax = "proto3"; + +package speed.socialcards.v1; + +// Social cards: share images (og:image, twitter:image, Pinterest pins, stories) +// for pages that have no real image of their own. +// +// The calling app is not part of the request. The bearer token in the +// `authorization` header says which app is calling, and the app picks the look: +// its colours, logo and fonts live in Speed, never in the request. Every text +// field arrives already translated into `locale`. +// +// Cards are stored, not returned. The request's fields fully determine the +// card's storage key, so the same request always gives the same URL. When the +// card already exists Speed returns its URL without rendering; otherwise it +// renders the card, stores it, then returns the URL. +service SocialCardService { + // Returns the URL of the card for these parameters, making it first if needed. + rpc GetCard(GetCardRequest) returns (GetCardResponse); +} + +enum Locale { + LOCALE_UNSPECIFIED = 0; // treated as LOCALE_EN + LOCALE_EN = 1; + LOCALE_FR = 2; + LOCALE_ES = 3; + LOCALE_HT = 4; +} + +// The shape each network wants. Every card is a PNG: all networks accept PNG, +// while some link scrapers still refuse WebP. +enum CardFormat { + CARD_FORMAT_UNSPECIFIED = 0; // treated as CARD_FORMAT_LINK + // 1200x630: og:image and twitter:image (link previews everywhere). + CARD_FORMAT_LINK = 1; + // 1080x1080: square posts. + CARD_FORMAT_SQUARE = 2; + // 1000x1500: Pinterest pins. + CARD_FORMAT_PORTRAIT = 3; + // 1080x1920: stories and reels. + CARD_FORMAT_STORY = 4; +} + +message GetCardRequest { + Locale locale = 1; + CardFormat format = 2; + + // What the card shows. Typed templates only, never HTML or free-form markup. + oneof template { + EmojiCard emoji = 10; + PageCard page = 11; + } +} + +// A page about one emoji: the emoji drawn large beside its name. +message EmojiCard { + // One emoji, e.g. "😀", a flag or a ZWJ sequence. At most 16 code points, + // and only emoji Speed has artwork for. + string emoji = 1; + // Its name. 1 to 80 characters. + string title = 2; + // A short line under the name. Up to 160 characters. + string subtitle = 3; + // A small line above the name, e.g. its category. Up to 40 characters. + string label = 4; +} + +// Any other page (home, category, list): a title, a line and up to 4 emoji. +message PageCard { + // 1 to 80 characters. + string title = 1; + // Up to 160 characters. + string subtitle = 2; + // 0 to 4 emoji, each as in EmojiCard.emoji. + repeated string emoji = 3; +} + +message GetCardResponse { + // Public HTTPS URL of the stored card, on the bucket's own domain. + string url = 1; + // Pixel size of the card, for og:image:width and og:image:height. + uint32 width = 2; + uint32 height = 3; + // Always "image/png" for now. + string content_type = 4; + // True when this call rendered and stored the card; false when it already existed. + bool created = 5; + // The card's storage key: /socialcards///.png + string key = 6; +} diff --git a/scripts/check-package.ts b/scripts/check-package.ts index f1c2a97..260e26c 100644 --- a/scripts/check-package.ts +++ b/scripts/check-package.ts @@ -46,6 +46,8 @@ const IMPORTS: Record = { './ui/overlays': ['react', '@ui-sdk/react'], // Checks a test runner sends into the page: no import at all, so they stay self-contained. './testing': [], + // Speed's clients: Connect-ES over gRPC-Web, and the messages protobuf-es generates. + './speed': ['@connectrpc/connect', '@connectrpc/connect-web', '@bufbuild/protobuf'], } const OPTIONAL_PEERS = [ 'better-auth', @@ -57,6 +59,9 @@ const OPTIONAL_PEERS = [ 'react-native-svg', '@ui-sdk/core', '@ui-sdk/react', + '@bufbuild/protobuf', + '@connectrpc/connect', + '@connectrpc/connect-web', ] /** Modules that only load inside their platform: React Native's own code doesn't run in Bun, so they're checked by their imports alone. */ const NOT_LOADED_HERE = ['./account/native'] diff --git a/scripts/check-size.ts b/scripts/check-size.ts index b53e29d..76f906a 100644 --- a/scripts/check-size.ts +++ b/scripts/check-size.ts @@ -91,6 +91,14 @@ await cost( 'allowed', ) +// kit/speed runs on an app's server (a Worker counts its script size), with Connect-ES and protobuf-es bundled in. +const speed = JSON.stringify(resolve('dist/speed.js')) +await cost( + 'kit/speed: the social cards client', + `import { createSocialCardsClient } from ${speed}; globalThis.__keep = [createSocialCardsClient]`, + 40 * 1024, +) + const width = Math.max(...rows.map((row) => row.what.length)) console.log(`${'gzipped'.padEnd(width)} ${'size'.padStart(9)} ${'budget'.padStart(9)}`) for (const row of rows) { diff --git a/src/speed.test.ts b/src/speed.test.ts new file mode 100644 index 0000000..21cb91e --- /dev/null +++ b/src/speed.test.ts @@ -0,0 +1,390 @@ +import { describe, expect, test } from 'bun:test' +import { create, fromBinary, toBinary } from '@bufbuild/protobuf' +import { + CircuitBreaker, + colorImage, + createSocialCardsClient, + SpeedError, + withFallback, + type FallbackReason, + type SocialCard, + type SpeedErrorCode, +} from './speed' +import { + CardFormat, + GetCardRequestSchema, + GetCardResponseSchema, + Locale, + type GetCardRequest, +} from './speed/gen/speed/socialcards/v1/social_cards_pb.js' + +const URL_BASE = 'https://speed.example.com' +const TOKEN = 'test-token-not-a-secret' + +/** One gRPC-Web frame: a flag byte, the length (4 bytes, big-endian), then the bytes. */ +function frame(flag: number, bytes: Uint8Array): Uint8Array { + const out = new Uint8Array(5 + bytes.length) + out[0] = flag + new DataView(out.buffer).setUint32(1, bytes.length) + out.set(bytes, 5) + return out +} +const trailer = (status: number, message = '') => + frame(0x80, new TextEncoder().encode(`grpc-status: ${status}\r\ngrpc-message: ${encodeURIComponent(message)}\r\n`)) +const GRPC_WEB = { 'content-type': 'application/grpc-web+proto' } + +type Seen = { url: string; headers: Headers; redirect: RequestRedirect | undefined; request: GetCardRequest } + +/** A fake fetch that answers as Speed would, and records what it was sent. */ +function fakeSpeed(answer: (request: GetCardRequest) => Response | Promise) { + const seen: Seen[] = [] + const fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const body = new Uint8Array(init?.body as ArrayBuffer) + const request = fromBinary(GetCardRequestSchema, body.subarray(5)) + seen.push({ url: String(input), headers: new Headers(init?.headers), redirect: init?.redirect, request }) + return answer(request) + }) as typeof globalThis.fetch + return { fetch, seen } +} +const card = (fields: Partial = {}) => + new Response( + new Blob([ + frame( + 0, + toBinary( + GetCardResponseSchema, + create(GetCardResponseSchema, { + url: 'https://cards.example.com/app/socialcards/link/en/abc.png', + width: 1200, + height: 630, + contentType: 'image/png', + created: true, + key: 'app/socialcards/link/en/abc.png', + ...fields, + }), + ), + ), + trailer(0), + ]), + { headers: GRPC_WEB }, + ) +/** A trailers-only error, as gRPC servers send one. */ +const failure = (status: number, message: string) => + new Response(null, { headers: { ...GRPC_WEB, 'grpc-status': String(status), 'grpc-message': encodeURIComponent(message) } }) + +describe('createSocialCardsClient', () => { + test('sends the request to the GetCard method, with the Bearer token', async () => { + const speed = fakeSpeed(() => card()) + const cards = createSocialCardsClient({ url: `${URL_BASE}/`, token: TOKEN, fetch: speed.fetch }) + await cards.getCard({ locale: 'fr', format: 'story', emoji: { emoji: '😀', title: 'Visage souriant', label: 'Smileys' } }) + const [call] = speed.seen + expect(call?.url).toBe(`${URL_BASE}/speed.socialcards.v1.SocialCardService/GetCard`) + expect(call?.headers.get('authorization')).toBe(`Bearer ${TOKEN}`) + expect(call?.headers.get('grpc-timeout')).toBe('1500m') + expect(call?.request.locale).toBe(Locale.FR) + expect(call?.request.format).toBe(CardFormat.STORY) + expect(call?.request.template.case).toBe('emoji') + expect(call?.request.template.value).toMatchObject({ emoji: '😀', title: 'Visage souriant', subtitle: '', label: 'Smileys' }) + }) + + test('a page card, in the link shape when no format is given', async () => { + const speed = fakeSpeed(() => card()) + const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: speed.fetch, timeoutMs: 800 }) + await cards.getCard({ locale: 'ht', page: { title: 'Bèt', emoji: ['🐶', '🐱'] } }) + const [call] = speed.seen + expect(call?.headers.get('grpc-timeout')).toBe('800m') + expect(call?.request.format).toBe(CardFormat.LINK) + expect(call?.request.locale).toBe(Locale.HT) + expect(call?.request.template.case).toBe('page') + expect(call?.request.template.value).toMatchObject({ title: 'Bèt', subtitle: '', emoji: ['🐶', '🐱'] }) + }) + + test('maps the answer', async () => { + const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => card({ created: false })).fetch }) + expect(await cards.getCard({ locale: 'en', page: { title: 'Home' } })).toEqual({ + url: 'https://cards.example.com/app/socialcards/link/en/abc.png', + width: 1200, + height: 630, + contentType: 'image/png', + created: false, + key: 'app/socialcards/link/en/abc.png', + }) + }) + + test('an answer without an HTTPS address or a size is refused', async () => { + for (const fields of [{ url: 'javascript:alert(1)' }, { url: 'http://cards.example.com/a.png' }, { url: '' }, { width: 0 }]) { + const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => card(fields)).fetch }) + const error = await cards.getCard({ locale: 'en', page: { title: 'Home' } }).catch((e: unknown) => e) + expect(error).toBeInstanceOf(SpeedError) + expect((error as SpeedError).code).toBe('bad_response') + } + }) + + test('maps Speed errors to codes, and never puts the token in the message', async () => { + const cases: [number, SpeedErrorCode][] = [ + [16, 'unauthenticated'], + [7, 'forbidden'], + [3, 'invalid_input'], + [8, 'rate_limited'], + [14, 'unavailable'], + [13, 'failed'], + ] + for (const [status, code] of cases) { + const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => failure(status, 'no')).fetch }) + const error = await cards.getCard({ locale: 'en', page: { title: 'Home' } }).catch((e: unknown) => e) + expect(error).toBeInstanceOf(SpeedError) + expect((error as SpeedError).code).toBe(code) + expect((error as SpeedError).message).not.toContain(TOKEN) + } + }) + + test('an HTTP error or a network failure is a SpeedError too', async () => { + const down = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => new Response('', { status: 503 })).fetch }) + expect(((await down.getCard({ locale: 'en', page: { title: 'Home' } }).catch((e: unknown) => e)) as SpeedError).code).toBe( + 'unavailable', + ) + const offline = createSocialCardsClient({ + url: URL_BASE, + token: TOKEN, + fetch: (() => Promise.reject(new TypeError('fetch failed'))) as unknown as typeof globalThis.fetch, + }) + expect(await offline.getCard({ locale: 'en', page: { title: 'Home' } }).catch((e: unknown) => e)).toBeInstanceOf(SpeedError) + }) + + test('never follows a redirect, so the token stays with Speed', async () => { + const speed = fakeSpeed(() => new Response(null, { status: 302, headers: { location: 'https://elsewhere.example.com/' } })) + const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: speed.fetch }) + const error = await cards.getCard({ locale: 'en', page: { title: 'Home' } }).catch((e: unknown) => e) + expect((error as SpeedError).code).toBe('unavailable') + // 'manual', not Connect's 'error': Workers without the fetch_redirect_error flag refuse 'error' outright. + expect(speed.seen.map((call) => [call.url, call.redirect])).toEqual([ + [`${URL_BASE}/speed.socialcards.v1.SocialCardService/GetCard`, 'manual'], + ]) + }) + + test('gives up at the deadline, once (no retry)', async () => { + let calls = 0 + const hang = ((_input: RequestInfo | URL, init?: RequestInit) => { + calls++ + return new Promise((_, reject) => init?.signal?.addEventListener('abort', () => reject(init.signal?.reason))) + }) as typeof globalThis.fetch + const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: hang, timeoutMs: 30 }) + const started = performance.now() + const error = await cards.getCard({ locale: 'en', page: { title: 'Home' } }).catch((e: unknown) => e) + expect((error as SpeedError).code).toBe('timeout') + expect(performance.now() - started).toBeLessThan(1000) + expect(calls).toBe(1) + }) + + test('refuses unsafe settings before any call', () => { + const ok = { url: URL_BASE, token: TOKEN } + for (const url of [ + 'http://speed.example.com', + 'http://localhost.example.com', + 'ftp://speed.example.com', + 'not a url', + 'https://user:pw@speed.example.com', + 'https://speed.example.com/?a=1', + 'https://speed.example.com/#x', + ]) + expect(() => createSocialCardsClient({ ...ok, url })).toThrow(SpeedError) + for (const token of ['a b', 'a\r\nx-evil: 1', 'tokĀen']) expect(() => createSocialCardsClient({ ...ok, token })).toThrow(SpeedError) + expect(() => createSocialCardsClient({ ...ok, timeoutMs: 0 })).toThrow(SpeedError) + // Plain HTTP is allowed on the machine itself, for development. + expect(() => createSocialCardsClient({ ...ok, url: 'http://localhost:8080' })).not.toThrow() + expect(() => createSocialCardsClient({ ...ok, url: 'http://127.0.0.1:8080' })).not.toThrow() + }) + + test('an unsafe setting never shows the token', () => { + try { + createSocialCardsClient({ url: 'http://speed.example.com', token: TOKEN }) + } catch (error) { + expect(String(error)).not.toContain(TOKEN) + } + }) + + test('a malformed key or an address with a password is a bad response', async () => { + for (const fields of [{ key: '../../etc/passwd' }, { key: 'a b.png' }, { url: 'https://u:p@cards.example.com/a.png' }]) { + const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => card(fields)).fetch }) + expect(((await cards.getCard({ locale: 'en', page: { title: 'Home' } }).catch((e: unknown) => e)) as SpeedError).code).toBe( + 'bad_response', + ) + } + }) + + test('ends on time even with a fetch that ignores the abort signal', async () => { + const deaf = (() => new Promise(() => {})) as unknown as typeof globalThis.fetch + const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: deaf, timeoutMs: 30 }) + const started = performance.now() + expect(((await cards.getCard({ locale: 'en', page: { title: 'Home' } }).catch((e: unknown) => e)) as SpeedError).code).toBe('timeout') + expect(performance.now() - started).toBeLessThan(1000) + }) + + test("the caller's own signal cancels the call", async () => { + const hang = ((_: RequestInfo | URL, init?: RequestInit) => + new Promise((_, reject) => + init?.signal?.addEventListener('abort', () => reject(init.signal?.reason)), + )) as typeof globalThis.fetch + const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: hang }) + const controller = new AbortController() + const call = cards.getCard({ locale: 'en', page: { title: 'Home' } }, { signal: controller.signal }).catch((e: unknown) => e) + controller.abort() + expect(((await call) as SpeedError).code).toBe('canceled') + }) + + test('without SPEED_URL or SPEED_TOKEN, getCard says so', async () => { + for (const settings of [{}, { url: URL_BASE }, { token: TOKEN }, { url: '', token: '' }]) { + const cards = createSocialCardsClient(settings) + expect(((await cards.getCard({ locale: 'en', page: { title: 'Home' } }).catch((e: unknown) => e)) as SpeedError).code).toBe( + 'not_configured', + ) + } + }) +}) + +describe('getCardOr: the failover', () => { + const input = { locale: 'en', page: { title: 'Home' } } as const + const hang = ((_: RequestInfo | URL, init?: RequestInit) => + new Promise((_, reject) => + init?.signal?.addEventListener('abort', () => reject(init.signal?.reason)), + )) as typeof globalThis.fetch + + test("Speed's card, marked as from Speed", async () => { + const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => card()).fetch }) + expect(await cards.getCardOr(input, { url: 'https://example.com/og.png' })).toEqual({ + url: 'https://cards.example.com/app/socialcards/link/en/abc.png', + width: 1200, + height: 630, + fromSpeed: true, + }) + }) + + test("the app's image, sized to the format, on an error or a timeout; and why", async () => { + const reasons: FallbackReason[] = [] + const onFallback = (reason: FallbackReason) => reasons.push(reason) + const down = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => failure(14, 'down')).fetch, onFallback }) + expect(await down.getCardOr({ ...input, format: 'square' }, { url: 'https://example.com/logo-on-brand.png' })).toEqual({ + url: 'https://example.com/logo-on-brand.png', + width: 1080, + height: 1080, + fromSpeed: false, + }) + const slow = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: hang, timeoutMs: 20, onFallback }) + const started = performance.now() + expect((await slow.getCardOr(input, { url: 'https://example.com/og.png', width: 600, height: 315 })).width).toBe(600) + expect(performance.now() - started).toBeLessThan(1000) + expect(reasons).toEqual(['error', 'timeout']) + }) + + test('a colour becomes an inline image of the format', async () => { + const down = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => failure(13, 'oops')).fetch }) + const image = await down.getCardOr({ ...input, format: 'story' }, { color: '#1f6feb' }) + expect(image).toMatchObject({ width: 1080, height: 1920, fromSpeed: false }) + expect(decodeURIComponent(image.url)).toBe( + 'data:image/svg+xml,', + ) + }) + + test('not set up yet: the fallback at once, without a call', async () => { + const reasons: FallbackReason[] = [] + const cards = createSocialCardsClient({ url: undefined, token: undefined, onFallback: (reason) => reasons.push(reason) }) + expect((await cards.getCardOr(input, { url: '/og.png' })).url).toBe('/og.png') + expect(reasons).toEqual(['not-configured']) + }) + + test('never throws: a refused input, a throwing counter, a bad colour', async () => { + const cards = createSocialCardsClient({ + url: URL_BASE, + token: TOKEN, + fetch: fakeSpeed(() => card()).fetch, + onFallback: () => { + throw new Error('counter down') + }, + }) + // @ts-expect-error: a locale Speed doesn't have + expect((await cards.getCardOr({ locale: 'de', page: { title: 'Start' } }, { url: '/og.png' })).url).toBe('/og.png') + const down = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => failure(14, 'down')).fetch }) + expect((await down.getCardOr(input, { color: 'red"/>