Production: consent, analytics, crash reports, translation and the scanner
@duolith/adapters holds what an app needs before it ships: a consent state that gates everything else, analytics with screen views and typed events, crash reports that say where the person was, translation with ICU messages and platform formatting, and duolith scan for npm dependencies. Each sends through a transport you choose, and runs with no provider at all. The runnable app is examples/production:
duolith dev examples/production --port 4350
duolith scan examples/production
Decisions: 0070 (the package and its hooks), 0071 (consent), 0072 (translation), 0073 (the scanner), 0074 (crash reports).
Start them once, in the root layout
// pages/_layout.duo
import { httpTransport, startAnalytics, startConsent, startCrashReporting, startTranslation } from "@duolith/adapters";
const consent = startConsent();
startTranslation({ fallback: "en" });
startCrashReporting({ transport: httpTransport("https://example.com/crashes"), consent, release: "1.4.0" });
startAnalytics({ transport: httpTransport("https://example.com/events"), consent });
Place the consent banner in the same layout (copy examples/production/components/ConsentBanner.duo into your components/).
Consent
| Call | Does |
|---|---|
startConsent({ categories?, version?, storage?, storageKey? }) | Categories default to necessary (always on), analytics (refused under Global Privacy Control) and crashes |
consent().decided | Whether the person has chosen: show the banner while it is false |
consent().granted("analytics") | Whether that category may be used now; views that read it follow it |
consent().choosable(name) | False for required categories and those Global Privacy Control refuses |
acceptAll(), refuseAll(), choose({ analytics: true }), reset() | Change and remember the choice on the device; reset asks again |
Nothing is recorded or sent for a category that is not granted. When the browser sends the Global Privacy Control signal, analytics stays refused even after "Accept all", and consent().globalPrivacyControl lets the banner say so. Raise version when the categories change, to ask again.
Analytics
import { startAnalytics, track } from "@duolith/adapters";
type Events = { "post.liked": { id: string }; "search.used": { results: number } };
const analytics = startAnalytics<Events>({ transport, consent });
analytics.track("post.liked", { id }); // typed by Events
track("post.liked", { id }); // the same, from any page
Screen views are recorded by themselves, from the router, by route pattern (/post/[id], never /post/7). Events wait in a batch that is sent when it holds 20, ten seconds after its first event (batchSize, flushAfter), and by navigator.sendBeacon the moment the page is hidden.
Crash reports
Uncaught errors and unhandled rejections are reported by themselves; report caught ones with captureError(error, { form: "profile" }) and add notes with addBreadcrumb("opened comments"). A report carries the screen in front (its route pattern and page; the path and parameters only with includePaths: true, since they can hold ids), the last 30 breadcrumbs (screens, actions by their name option, presses, notes), the release and the stack. A press is named by the element's data-crumb or aria-label, never by its text; give a button data-crumb="open profile" to name it in reports. Breadcrumbs are kept only while the crashes category is granted, and refusing it drops them, so nothing from before a yes is sent. Frames are mapped to the .duo file wherever a script on the app's own origin has a source map (new SourceMaps({ allowedOrigins }) adds others). At most ten reports a minute are made, and the reporter never throws: a failure in it or in the transport loses that report and nothing else.
Translation
Put one catalogue per locale in locales/, named by language tag:
// locales/en.json
{ "home": { "title": "Today", "posts": "{count, plural, =0 {No new posts} one {# new post} other {# new posts}}" } }
<text>{t("home.title")}</text>
<text>{t("home.posts", { count: posts.length })}</text>
Messages use ICU syntax: {name}, {count, plural, ...} (cases zero, one, two, few, many, other, =N; # is the number), {rank, selectordinal, ...}, {role, select, admin {...} other {...}}, {n, number} (percent, integer, currency:EUR), {d, date, short|medium|long|full}, {t, time, short}. Quote a brace as '{'.
The build fails when a locale lacks a key a page passes to t(), or a key another catalogue has (E0280), when a catalogue is not an object of messages (E0281), when a message does not parse (E0282), or when a file is not named after a locale (E0283).
The locale is the one chosen earlier on the device (translation().setLocale("ar")), else the person's preferred languages, else fallback. lang and dir are set on the document: in a right-to-left locale, rows, px-* padding and alignment flip; text-left, text-right, left-* and right-* stay where they are written.
Switching language. A settings screen lets the person choose with translation().setLocale(locale): it loads that catalogue, every t() on screen shows the new text, lang and dir follow, and the choice is remembered on the device for the next start. translation().locales lists the app's locales for the picker, and translation().locale is the one shown.
import { translation } from "@duolith/adapters";
const choose = (locale: string) => translation().setLocale(locale);
formatNumber(value, options?), formatDate(value, options?) and formatRelativeTime(value, now?) format with Intl in the current locale.
Moving text into catalogues
duolith locales works on the catalogues without a build (decision 0148):
duolith locales check # the build's catalogue checks, E0280 to E0283
duolith locales extract # a key for each untranslated text, in every catalogue
duolith locales extract --rewrite # and the markup changed to {t("key")}
extract reads the text in pages and components, both markup text and the attributes people read (label, placeholder, title, alt, ...). Each text gets a key named after its file, such as index.add_a_todo. Every catalogue gets each missing key, with the text as its value. With no catalogue yet, locales/en.json is made. Keys already there are never changed.
- Text around values is one message.
<text>Clear {completed} done</text>becomes the messageClear {completed} doneunderindex.clear_done, never two pieces, and is rewritten as{t("index.clear_done", { completed })}. A value that is not a plain name, such as{draft.trim()}, is passed by the variable it starts with ({ draft: draft.trim() }), else asvalue. - Any text is a valid message. An apostrophe is doubled and a brace quoted (
'{'), as the ICU syntax wants. - Keys never collide. A key cannot be a message and hold other keys too, so a text whose key would clash, such as
settings.profileonpages/settings.duobesidepages/settings/profile.duo, gets_2on the part that clashes. A key a page already passes tot()that cannot be added is refused (E0530), and nothing is written. - **
--rewritemakes the app translate.** It replaces each text with{t("index.add_a_todo")}, importstwhere the page does not, and keeps a formatted file formatted. When no page or component callsstartTranslation(), it adds the call to the root layout,pages/_layout.duo, making one if there is none: without itt()shows the keys.
Text built in an expression is not extracted; call t() there by hand. --json prints spec/schemas/cli/locales.schema.json. The refusals have codes: E0530, E0531, E0532 and E0539 (duolith explain).
Transports
| Transport | Sends |
|---|---|
consoleTransport({ label? }) | Prints each payload: for development |
httpTransport(url, { headers?, retryAfter?, mostWaiting? }) | Posts JSON; a beacon while the page is hidden, sent as text/plain so another origin needs no preflight (read the body as JSON); failures are dropped, never thrown. On a phone each payload waits in an outbox until it is delivered; mostWaiting is the most it keeps (100 by default), the oldest going first |
your own { send(payload, { leaving }) } | Anything else, such as a provider's SDK, kept in one folder |
A transport that sends to another origin needs that origin under connect-src in duolith.yaml, or the browser blocks every send (and, since a transport drops its failures, nothing says so but the browser's console). httpTransport("https://logs.example.com/ingest") written as text is checked when you build (E0551); an address read from environment() is not, so list it yourself:
security:
content-security-policy:
connect-src: [https://logs.example.com]
A provider's SDK usually needs its script, image or frame origins too; its documentation lists them. More in security.md.
The optimized web build
duolith build minifies every module and stylesheet, writes a copy of each with a hash of its contents in its name, links the pages to the copies through an import map, and adds its caching rules to _headers (decision 0107). Serve the hashed files with Cache-Control: public, max-age=31536000, immutable and the pages with no-cache: Netlify and Cloudflare Pages read _headers as it is; on another host, copy its rules into the host's configuration. _headers names each page by the addresses it is served at (/, /about, /about/ and /about/index.html), never with a /* rule (the Content-Security-Policy's /* rule, the file's first, sets no caching), because both hosts join the values of every rule that matches a file, and no-cache joined to a hashed file's immutable would cache nothing. An address served by the not-found page, such as a dynamic route's, gets the host's own default for HTML, which on both is to check again. A deploy then never mixes old and new code, and a returning visitor downloads only what changed. duolith build --no-optimize writes readable files under their own names only, for reading what the compiler made; browsers without import maps (before Safari 16.4) need it too.
A Content-Security-Policy
Every web build carries a strict Content-Security-Policy, in each page's <meta> tag and in _headers (decision 0150, security.md). The page's own inline scripts are allowed by their hashes, which the build works out itself, so nothing needs updating when they change:
| Script | When it is there |
|---|---|
| The module that starts the router | Always |
| The colour scheme, applied before the first paint | The theme follows the system |
| The platform look, picked before the first paint | The theme's web-look is user-agent |
globalThis.__duolith_environment = …, the DUOLITH_PUBLIC_* values | An environment file defines one |
| The import map | Always, unless --no-optimize |
A policy you serve yourself instead (with security: content-security-policy: off in duolith.yaml) must name the same hashes, or the browser blocks those scripts. The environment script matters most: blocked, environment() gets no values and each falls back to its default, with nothing but the browser's console saying why. On native none of this applies: the bundle sets the values in its first module.
On iOS and Android
The same imports work in a native build (duolith build --target native), with the shell in place of the browser (decision 0053):
- Consent, the chosen locale and anything waiting to be sent are kept in the shell's key-value storage, so they survive the app being closed.
httpTransportkeeps each payload in an outbox until a request for it succeeds. A report made just before the app is stopped in the background is sent on its next start. A phone has no beacons, soleavingonly means "send what is waiting now".- The outbox keeps at most 100 payloads and about half a megabyte of them, dropping the oldest. After a failed request it tries again by itself, waiting 30 seconds, then twice as long each time, to at most 15 minutes. Every transport to one address shares it, so a payload is never sent twice.
- Analytics batches and crash reports wait under their consent category. The outbox checks the category again when it sends, and drops what waits under it as soon as it is refused, so nothing goes out after
consent().refuseAll(), even on a later start. - Crash reports come from the shell's uncaught handler, which keeps only the script's own errors (Lynx's
isJSError, on both platforms). An error that stopped the app is reported on the next start, under the session and time of the run it happened in, and without the new run's screen and breadcrumbs. The kept crashes and the outbox stay out of Android's auto-backup. Frames are sent as they ran; map them with the bundle's source map (see Debugging). t()reads the catalogues the build put in the app and picks the phone's languages; nothing is fetched.- Where the phone's JavaScript engine has no
Intl, numbers, plurals, dates and relative times use a compact one with CLDR's data for each locale the app has a catalogue for, read from Node's ICU when the app is bundled. It writes what the platform'sIntlwrites. The exceptions are a zone other than UTC, which it writes as its offset (GMT+1), and an option it does not support (such asnotation: "compact"), which it reports once on the console and leaves out. Bundling fails for a locale it cannot write exactly, such as one with another calendar (decision 0053). - Presses are not named in breadcrumbs, and the direction comes from the phone's own setting, not from the locale
t()shows.
duolith scan
duolith scan # this project
duolith scan --json # for tools
Each package in dependencies (and theirs) gets a verdict, after its browser field has swapped out what the app's bundle leaves out. A file its react-native field swaps out ships only on the web, so its browser APIs do not count; a file its exports reach only under the node, node-addons, deno, bun or workerd conditions is never shipped, so nothing in it counts; and a regular expression after an if, while, for or with condition (if (ok) /x/.test(s)) is read as one. Minified imports (import{x}from"fs"), regular expressions and links inside the project are read as such. A missing package.json is said plainly, and one that is not valid JSON fails the command. works everywhere; web only (uses the DOM or another browser API, E0287); not fully checked (a script over 2 MB, or more than 4000 scripts, E0290); not supported (Node modules E0285, Node globals E0286, native addons E0288); or not installed (E0289). The command fails when a direct dependency is not fully checked, not supported or not installed. duolith explain <code> says what to do.
In --json each package is a module manifest (spec/schemas/module.schema.json), with targets saying whether it runs on the web, iOS and Android, and replaced listing what its browser field swapped.
Privacy declarations for the stores
duolith build writes two files into dist/privacy/ from what your pages start:
| File | For | Says |
|---|---|---|
PrivacyInfo.xcprivacy | The iOS privacy manifest | No tracking and no tracking domains; product interaction collected for analytics; crash data and other diagnostics for app functionality; UserDefaults (reason CA92.1) for what is kept on the device; the data types of the platform effects you import |
data-safety.json | Google Play's data safety form | The same data types in Play's words (App activity: App interactions; App info and performance: Crash logs, Diagnostics), whether each is optional (it is when you pass consent), not shared, the endpoints and whether they are all https:// |
Only what is started is declared, and each adapter on its own: data is optional only when every startAnalytics or startCrashReporting call passes consent, and crash data is declared linked to the person when crash reporting is started with includePaths: true. With your own transport the build cannot see where data goes, so data-safety.json leaves encryptedInTransit as null and a note asks you to answer it. An httpTransport to another host may be a third party's, so sharesData is then null with a note naming the host. Platform effects count as the analyzer reads your @duolith/effects imports: storage declares UserDefaults (CA92.1); secureStorage keeps values in the Keychain or Keystore, listed under keptSecurely (the Keychain needs no required reason); signIn declares an email address and a user id, linked and required, and keeps the user and its credentials in both; camera declares photos, push a device id and purchases the purchase history, each optional, and linked to the person when the app also uses signIn. If you add a user id to reports, pass identifying properties to track() or send to a tracking provider, change the declarations to match before you submit.