@qafka/react-native-cms 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md ADDED
@@ -0,0 +1,510 @@
1
+ # AGENTS.md - `@qafka/react-native-cms`
2
+
3
+ Guide for coding agents working in a React Native app that uses the QafkaCMS runtime SDK. Every signature below was checked against the SDK source. Do not invent options that are not listed here.
4
+
5
+ ## Install
6
+
7
+ The package is published on npm (public, `UNLICENSED`).
8
+
9
+ ```sh
10
+ # in the app
11
+ npm install @qafka/react-native-cms # or pnpm add / yarn add
12
+ cd ios && pod install # or `npx expo prebuild` for Expo
13
+ ```
14
+
15
+ - Peer dependencies: `react >=18`, `react-native >=0.72`. No other JS dependencies.
16
+ - The SDK ships native modules (secure storage, device attestation, push). A rebuild of the native app is required after install; it does not run in Expo Go.
17
+ - Expo: `app.plugin.js` is the config plugin (App Attest + push: `aps-environment`, AppDelegate forwarding, notification permission). An app without push adds only the attestation part: `["@qafka/react-native-cms/expo-plugin/withQafkaCmsAttestation", { "appleEnvironment": "production" }]`. Bare RN: autolinking through `react-native.config.js` and the podspec.
18
+ - Updating: `npm install @qafka/react-native-cms@latest`, then rebuild the native app if the SDK's native code changed (the release notes say so).
19
+ - Testing an unreleased SDK change in an app: `pnpm build && yalc publish` in `packages/react-native` of the SDK repo, `yalc add @qafka/react-native-cms` in the app; `yalc remove --all` returns to the npm version.
20
+
21
+ ## Setup
22
+
23
+ ```tsx
24
+ import { createClient, QafkaCmsProvider } from '@qafka/react-native-cms';
25
+
26
+ const client = createClient({
27
+ apiUrl: 'https://api.example.com', // backend base URL, no /v1 suffix
28
+ projectId: '<project id (UUID)>', // from the dashboard (Settings → Apps); not a secret
29
+ });
30
+
31
+ export function Root() {
32
+ return (
33
+ <QafkaCmsProvider
34
+ client={client}
35
+ prefetch={[
36
+ { key: ['content', 'categories', {}], gate: true, ttl: '1h', persist: true,
37
+ fetch: (c) => c.content.list('categories') },
38
+ ]}
39
+ fallback={<Splash />}
40
+ >
41
+ <App />
42
+ </QafkaCmsProvider>
43
+ );
44
+ }
45
+ ```
46
+
47
+ `createClient(config: QafkaCmsConfig, deps?: QafkaCmsClientDeps)` returns a `QafkaCmsClient`. It throws `QafkaCMS: projectId is required (or a publishableKey qpk_…)` when neither is given, `publishableKey is required (qpk_…)` when a given `publishableKey` does not start with `qpk_`, and throws when no `apiUrl` can be resolved.
48
+
49
+ `QafkaCmsConfig`: `apiUrl?`, `projectId?` (project UUID; sent as `X-Project-Id`, also selects the dev config entry), `publishableKey?` (`qpk_…`; sent as `X-Project-Key`; optional when `projectId` is set, web and older setups), `projectSlug?`, `apiKey?` (explicit dev TEST key; wins over the dev config lookup), `devConfig?` (pass `__DEV__ ? require('./.qafkacms/qafkacms-runtime') : undefined`), `bootstrap?` (`{ i18n?, locales? }`, each `{ version, data }`, embeds translations for cold start), `configPollIntervalMs?` (config polling cadence, clamped to a 30 s floor, default 60 s), `externalTokenProvider?` and `externalProvider?` (external identity, see Auth), `anonymousAuth?` (`'manual'` default \| `'auto'`, type `AnonymousAuthMode`; see "Anonymous end-users"), `contentLiveDefault?` (see "Live content"), `contentVersionGate?` (`boolean | { maxAgeMs?: number }`, default off; see "Cache revalidation"), `appVersion?` (`string | null`, default the native app version; sent as `X-App-Version`, see "Content per app version"), `contentBundle?` (`ContentBundleOption`: `true` or `{ storage?, locale?, initial? }`, default off; see "Content bundle (offline snapshot)"), `cacheStorage?` (`CacheStorage`, a plain store such as `AsyncStorage`; default the SDK's secure store; see "Where cached data is stored").
50
+
51
+ `QafkaCmsClientDeps` is for tests and host injection (`fetch`, `storage`, `attestationNative`, `pushNative`, `platformOS`, `connectSse`, `appState`, `now`); apps normally omit it.
52
+
53
+ `QafkaCmsProvider` props (`QafkaCmsProviderProps`):
54
+
55
+ | Prop | Meaning |
56
+ |---|---|
57
+ | `client` | The `QafkaCmsClient` (required). |
58
+ | `prefetch?` | `readonly PrefetchResource[]`, warmed at boot. `PrefetchResource` is `{ key, fetch(client), ttl?, persist?, gate? }`. `gate: true` holds `ready` (and the `fallback`) until it settles; others are fire-and-forget. |
59
+ | `defaultTtl?` | Default freshness (`Duration`) for queries without their own `ttl`. |
60
+ | `onCacheError?` | `(error, key) => void` observer for fetch errors. |
61
+ | `fallback?` | Rendered while initializing (and gating prefetch). Omit to render children immediately. |
62
+ | `errorFallback?` | `ReactNode` or `(error, retry) => ReactNode`, rendered when init or a gating prefetch fails. |
63
+
64
+ `Duration` is a number of ms or a string such as `'500ms'`, `'30s'`, `'10m'`, `'1h'`, `'2d'` (`parseDuration` converts; malformed strings throw).
65
+
66
+ Lifecycle: `useQafkaCms()` returns `{ status: 'initializing' | 'ready' | 'error' (QafkaCmsStatus), error, retry, clearCache }`. `useQafkaCmsClient()` returns the `QafkaCmsClient`; `useQafkaCmsCache()` returns the shared `QueryCache`. All hooks throw outside a `QafkaCmsProvider`. `QafkaCmsContextValue` is the internal context shape.
67
+
68
+ ## Reading content
69
+
70
+ ```tsx
71
+ import { useContent, useContentItem } from '@qafka/react-native-cms';
72
+
73
+ const { data, isLoading, isFetching, error, refetch } = useContent('posts', {
74
+ filter: { status: { _eq: 'published' } },
75
+ sort: ['-created_at'],
76
+ expand: ['author'],
77
+ limit: 20,
78
+ });
79
+ // data: ListResult<ContentRecord> -> data?.docs
80
+
81
+ const { data: post } = useContentItem('posts', id, { expand: ['author'] });
82
+ ```
83
+
84
+ Signatures:
85
+
86
+ - `useContent<T = ContentRecord>(collection: string, params?: ListParams, options?: UseContentOptions): UseQueryResult<ListResult<T>>`
87
+ - `useContentItem<T = ContentRecord>(collection: string, id: string | null | undefined, params?: GetParams, options?: UseContentOptions): UseQueryResult<T>`. Disabled (no fetch) until `id` is truthy.
88
+ - `UseContentOptions` = `UseQueryOptions` + `live?: ContentLiveOption` (`true` or `{ mode?: ContentLiveMode ('auto' | 'sse' | 'poll'), also?: string[], pollIntervalMs?: number }`). `live` refreshes the query on server change signals (the collection must enable its change signal; otherwise one dev warning and plain TTL behavior). Absent = unchanged TTL behavior. App-wide default mode: `createClient({ contentLiveDefault })`. Debug: `client.contentChanges.status()` (`ContentChangesStatus`: `'sse' | 'polling' | 'idle'`); `client.contentChanges` is a `ContentChangesApi` (`watch(target: ContentWatchTarget, mode?, opts?: ContentWatchOptions)`, `status`, `reset`, `dispose`, `versions(collections)`; `ContentInvalidationTarget` = anything with `invalidateByPrefix`, e.g. the `QueryCache`).
89
+ - Imperative: `client.content.list<T>(collection, params?)`, `client.content.get<T>(collection, id, params?)` (also `create`, `update`, `delete`, see Writing).
90
+
91
+ `ListParams`:
92
+
93
+ | Field | Type | Notes |
94
+ |---|---|---|
95
+ | `filter` | `FilterNode` | Filter DSL below. |
96
+ | `limit` | `number` | Page size; backend clamps to 1..100. |
97
+ | `cursor` | `string` | Opaque `ListResult.nextCursor` from a previous call. |
98
+ | `page` | `number` | Page-based pagination (alternative to cursor). |
99
+ | `locale` | `string` | Overrides the active locale for this request. |
100
+ | `localeFallback` | `boolean` | Fall back to the default locale for missing translations. |
101
+ | `sort` | `string \| readonly string[]` | `['order', '-name']` or `'order,-name'`; `-` = descending. At most 3 keys. |
102
+ | `expand` | `string \| readonly string[]` | RELATION fields (single level) and sub-list (JOIN) fields to inline. |
103
+ | `withTitle` | `boolean` | `true` adds `_title` (display title) to every row. |
104
+
105
+ `GetParams`: `locale?`, `localeFallback?`, `expand?`, `withTitle?` (same meaning as above).
106
+
107
+ `ListResult<T>`: `{ docs: T[], nextCursor: string | null, hasMore: boolean, totalDocs?, totalPages?, page? }`. A row is a `ContentRecord` (`{ id: string } & Record<string, unknown>`); pass `T` for typed rows.
108
+
109
+ Sub-lists (JOIN fields): a collection can define a virtual "sub-list" field listing the child rows that point at a parent. It is only returned when named in `expand` (list, get, lookup); otherwise the key is absent. The value is a `JoinResult` (`JoinResult<T>`) = `{ docs: T[], totalDocs: number, hasMore: boolean }` (first page only), or `null` when the caller cannot read the child collection. Fetch further pages from the child collection, filtering on its relation field:
110
+
111
+ ```ts
112
+ const { data: parent } = useContentItem('parents', id, { expand: ['children'] });
113
+ const more = await content.list('child_collection', {
114
+ filter: { parent: { _eq: id } }, // the child's relation field -> parent id
115
+ sort: '-updated_at', // must equal the sub-list's sort (the JOIN's configured sort; default: the child collection's default sort, else -updated_at)
116
+ limit: 10, // same page size as the sub-list (pageSize, default 10)
117
+ page: 2,
118
+ });
119
+ ```
120
+
121
+ Display titles: pass `withTitle: true` (list, get and lookup params) and each row, including expanded related rows, carries `_title: string`, computed server-side from the collection's title settings. Show `_title` on list screens; do not re-implement title logic in the app. Without the param nothing changes.
122
+
123
+ Pagination and sorting rules:
124
+
125
+ - `sort` accepts at most 3 keys; `-` prefix means descending. Allowed keys: sortable field types plus `created_at`, `updated_at`, `id`.
126
+ - `sort` together with `cursor` returns 400. A sorted list must page with `page`, not `cursor`.
127
+ - Use `cursor` (`nextCursor`/`hasMore`) only for unsorted lists.
128
+ - `expand` inlines RELATION fields one level deep, and sub-list (JOIN) fields as a first page. Expanded rows obey the target collection's own read policy; hidden or draft rows are not returned.
129
+ - Params are part of the cache key: an expanded and a plain read, or two different `sort` values, are cached independently.
130
+ - Filter fields that are hidden by policy or private return 400.
131
+
132
+ Filter DSL (`FilterNode`): `{ field: { _eq: value } }`, combined with `{ _and: [...] }` / `{ _or: [...] }`. Operators (`FilterOp`, used in `FieldOps`): `_eq _neq _lt _lte _gt _gte _in _nin _null _nnull _contains _icontains _starts_with _istarts_with`. `_starts_with` is case-sensitive, `_istarts_with` case-insensitive; both pass a string. `_contains`, `_icontains`, `_starts_with` and `_istarts_with` work only on plain (non-localizable) text fields; on localizable fields, UUID system columns and non-text fields the API returns 400.
133
+
134
+ ```tsx
135
+ import { NOW, now, type FilterNode } from '@qafka/react-native-cms';
136
+
137
+ // Events whose end_date is between now and 7 days from now (ends within 7 days)
138
+ const endingSoon: FilterNode = {
139
+ _and: [{ end_date: { _gte: NOW } }, { end_date: { _lte: now('+7d') } }],
140
+ };
141
+ ```
142
+
143
+ - `CURRENT_USER` (`'$CURRENT_USER'`) is a dynamic value resolved server-side to the signed-in user's id: `{ owner: { _eq: CURRENT_USER } }`.
144
+ - `NOW` (`'$NOW'`) is the server's current time in UTC (server clock, not the device clock). Use it with `_eq _neq _lt _lte _gt _gte` on date fields; with other operators (e.g. `_in`, `_contains`) `$NOW` is not expanded; avoid it there (on date fields the server may reject the literal). `now()` returns `'$NOW'`; `now(offset)` returns a shifted value, `'$NOW(<offset>)'`. The offset is a signed count of at most 6 digits and a unit: `+7d`, `-1w`, `+2h`, `-30m` (units `m` minutes, `h` hours, `d` days, `w` weeks). Any other shape throws at build time, so a typo fails in the app, not on the server.
145
+
146
+ ### Query hooks, cache and options
147
+
148
+ - `useQuery<T>(key: QueryKey, fetcher: (client) => Promise<T>, options?: UseQueryOptions): UseQueryResult<T>` caches any call. `QueryKey` is a string or an array of JSON-serializable parts.
149
+ - `UseQueryOptions`: `ttl?: Duration | null`, `persist?: boolean`, `enabled?: boolean` (default true; false = no fetch, still serves cache), `gate?: string` (collection slug of the launch version gate; the content hooks set it themselves, see "Cache revalidation"; not the same as `PrefetchResource.gate`, which holds boot).
150
+ - `UseQueryResult<T>` extends `QueryState<T>`: `data`, `error`, `status` (`QueryStatus`: `'idle' | 'loading' | 'success' | 'error'`), `isLoading` (first load, no data), `isFetching` (any fetch in flight), `isStale`, `updatedAt`, plus `refetch()`. `QueryOptions` is the `ttl`/`persist` pair.
151
+ - Behaviour: in-flight dedupe, TTL freshness (no network while fresh), stale-while-revalidate, stale-on-error (old data stays when a refetch fails), race protection.
152
+ - Cache keys used by the content hooks: `useContent` -> `['content', collection, params]`; `useContentItem` -> `['content-item', collection, id, params]`. Note: the `['content', collection]` prefix does NOT cover item queries; invalidate `['content-item', collection]` too after writes.
153
+ - `persist: true` writes the entry with its timestamp to `client.cacheStorage`, so TTL survives restarts: the plain store passed as `createClient({ cacheStorage })`, otherwise the SDK's own secure native storage. Without `cacheStorage` use it only for small, rarely changing reference data (categories, config), never for large lists. See "Where cached data is stored".
154
+ - `QueryCache` (from `useQafkaCmsCache()`, constructed with `QueryCacheOptions`): `getSnapshot`, `subscribe`, `ensure`, `prefetch`, `refetch`, `refetchActive`, `invalidate`, `invalidateWhere`, `invalidateByPrefix`, `setData`, `clear`. `serializeKey` gives the stable string form of a key. `CacheStorage` and `createMemoryCacheStorage` are the persistence backend contract and an in-memory implementation (advanced / tests; the Provider wires `client.cacheStorage` for you).
155
+
156
+ ### Where cached data is stored
157
+
158
+ ```tsx
159
+ import AsyncStorage from '@react-native-async-storage/async-storage';
160
+
161
+ const client = createClient({ apiUrl, projectId, cacheStorage: AsyncStorage });
162
+ ```
163
+
164
+ - `cacheStorage?: CacheStorage` (opt-in): a plain key/value store (`getItem` / `setItem` / `removeItem` / `multiRemove`, all async). `AsyncStorage` fits as is; for MMKV wrap it like the content bundle example below. The SDK adds no dependency for it.
165
+ - With it, these go to that store: `persist: true` queries (and their key index), config-sync snapshots (`locales`, `i18n`, your own domains), the saved active locale, and the content bundle when `contentBundle` has no `storage` of its own. Session data stays in the SDK's secure storage (Keychain / EncryptedSharedPreferences, `client.storage`): refresh token, external / anonymous session markers, unlock tokens, attestation key, device id.
166
+ - Without it nothing changes: all of the above stays in the secure storage, which is meant for small data (keep `persist` to small reference data then); the content bundle without its own `storage` stays in memory.
167
+ - Switching an existing app to `cacheStorage` loses nothing: a cached entry, config snapshot or saved locale still in the secure storage is read from there the first time it is needed, moved to the plain store and removed from the secure one. Clearing the cache (login, logout, account switch) removes it from both.
168
+ - `client.cacheStorage` is the store in use (the plain store, or `client.storage` without `cacheStorage`); `client.storage` is always the secure storage.
169
+
170
+ ### Code-locked records (lookup)
171
+
172
+ A collection can hold records that are locked behind an access code. Locked rows come back in `list`/`get` as teasers: `id` + the teaser fields + `_locked: true` (`ContentRecord._locked?: true`), plus `_title` (built from the teaser fields only) when the read passes `withTitle: true`; other fields are absent.
173
+
174
+ ```tsx
175
+ import { useLookup } from '@qafka/react-native-cms';
176
+
177
+ const lookup = useLookup();
178
+ try {
179
+ const { data, unlockToken } = await lookup.mutate({ collection: 'shopping_malls', code: 'K7MX-Q4TP', expand: ['city'] });
180
+ } catch (e) {
181
+ // ProblemError: e.status 404 + e.raw.code 'LOOKUP_NOT_FOUND' (wrong code), 400 'LOOKUP_BAD_REQUEST', 429 'LOOKUP_RATE_LIMITED' (Retry-After)
182
+ }
183
+ ```
184
+
185
+ - `client.content.lookup<T>(collection, code, params?: GetParams): Promise<LookupResult<T>>` -> `POST /v1/end-user/lookup/:collection`; returns `{ data, unlockToken }`. The raw code is sent as typed (the server normalizes case, spaces and dashes).
186
+ - On success the token is stored in `UnlockTokenStore` (secure storage, one per collection+row, newest 20 kept, never expires) and sent as `X-Unlock-Token` on every later content request. Invalid or stale tokens are ignored by the server, so nothing needs pruning.
187
+ - With `QafkaCmsProvider`, all cached queries are invalidated after a successful lookup and after `clearUnlockTokens()`, so mounted screens refetch with the new token.
188
+ - `client.content.clearUnlockTokens(): Promise<void>` forgets all tokens (rows lock again). `client.content.onUnlockChange(listener)` subscribes to token changes.
189
+ - Stored tokens load during `initialize()` (or on the first `getRequestHeaders()` call); SDK requests made before hydration finishes do not carry them (`QafkaCmsProvider` bootstraps first). The SDK sends `X-Unlock-Token` only on content and lookup requests, never on auth, device, config-sync or SSE calls.
190
+ - Own HTTP client: `client.getRequestHeaders()` includes `X-Unlock-Token` when tokens are stored (see "Using your own HTTP client"). Call `content.lookup` through the SDK so the token is stored, and refetch your own queries on `client.content.onUnlockChange(listener)` (fires after a lookup and after `clearUnlockTokens()`).
191
+ - Content linked to a locked record is hidden by the server until that record is unlocked.
192
+
193
+ ## Writing content
194
+
195
+ ```tsx
196
+ import { useMutation } from '@qafka/react-native-cms';
197
+
198
+ const create = useMutation(
199
+ (client, vars: { title: string }) => client.content.create('posts', vars),
200
+ { invalidate: [['content', 'posts'], ['content-item', 'posts']] },
201
+ );
202
+ await create.mutate({ title: 'Hello' });
203
+ ```
204
+
205
+ - `useMutation<TVars = void, TResult = unknown>(mutationFn: (client, vars) => Promise<TResult>, options?: UseMutationOptions<TVars, TResult>): UseMutationResult<TVars, TResult>`.
206
+ - `UseMutationOptions`: `invalidate?: QueryKey[] | ((result, vars) => QueryKey[])` (prefix match, run on success), `onSuccess?(result, vars)`, `onError?(error, vars)`.
207
+ - `UseMutationResult`: `mutate(vars): Promise<TResult>` (rejects on error, also reflected in state), `isPending`, `error`, `data`, `reset()`.
208
+ - Client methods: `content.create<T>(collection, data)`, `content.update<T>(collection, id, data)`, `content.delete(collection, id)`. The backend needs an end-user token and a matching policy for each; otherwise it returns a `ProblemError` with status 401/403.
209
+ - Optimistic updates: `useQafkaCmsCache().setData(key, data)`.
210
+ - Errors from the backend are `ProblemError` (RFC 7807): `status`, `type?`, `title?`, `detail?`, `instance?`, `raw` (a `ProblemDetails`). Branch on `status`; the machine-readable reason is `raw.code` (see "Project identity and proof").
211
+
212
+ ## Project identity and proof
213
+
214
+ A mobile app ships no key. Every request carries `X-Project-Id` (the project id) plus a proof:
215
+
216
+ - Release build on a real device: `X-Session-Token`, the short-lived device attestation session (iOS App Attest, Android Key Attestation). The SDK attests in `initialize()` and refreshes the token itself.
217
+ - Dev build on a simulator/emulator (no attestation): the project's TEST API key as `x-api-key`. Either pass `devConfig`, or — no CLI needed — pass the key from an env var under `__DEV__` so a Release bundle drops it:
218
+ ```ts
219
+ createClient({ apiUrl, projectId, apiKey: __DEV__ ? process.env.EXPO_PUBLIC_QAFKA_TEST_KEY || undefined : undefined });
220
+ ```
221
+ Put `EXPO_PUBLIC_QAFKA_TEST_KEY=…` in `.env.local` (git-ignored) and restart Metro. Without a key the simulator's requests are rejected with `401 ATTESTATION_REQUIRED`. Create the TEST key in the dashboard (Settings → API Keys, type Test).
222
+ - The project id alone opens nothing (`401 ATTESTATION_REQUIRED`, even when attestation enforcement is off). The app identity must be registered in the dashboard under Settings → Apps: iOS team ID + bundle ID, Android package name + signing certificate SHA-256 hashes (debug and release). Otherwise attestation fails with `401 APP_NOT_REGISTERED`.
223
+ - With `publishableKey` set, `X-Project-Key` is sent as well; both must name the same project (attestation: `401 PROJECT_MISMATCH`; other requests: `400`).
224
+
225
+ Error codes (in `ProblemError.raw.code`): `PROJECT_REQUIRED`, `ATTESTATION_REQUIRED` (no or wrong proof), `ATTESTATION_SESSION_EXPIRED` (session lapsed; the SDK refreshes and retries once), `APP_NOT_REGISTERED`, `PROJECT_MISMATCH`, `DEVICE_NOT_TRUSTED` (Android with an unlocked bootloader or unverified boot), `ATTESTATION_REVOKED`, `ATTESTATION_STATUS_UNAVAILABLE` (503). The project codes (`PROJECT_REQUIRED`, `ATTESTATION_REQUIRED`, `APP_NOT_REGISTERED`, `PROJECT_MISMATCH`) never make the SDK regenerate the iOS attestation key; the last three codes come from the Android checks.
226
+
227
+ ### Using your own HTTP client
228
+
229
+ When the app keeps its own API client (or calls the QafkaCMS API outside the SDK), take the project + proof headers from the SDK instead of building them:
230
+
231
+ ```ts
232
+ const headers = await client.getRequestHeaders(); // X-Project-Id (+ X-Project-Key), X-Session-Token or x-api-key, X-Unlock-Token if any, X-App-Version
233
+ let res = await fetch(`${apiUrl}/v1/end-user/content/posts`, { headers });
234
+ if (res.status === 401 && (await res.clone().json()).code === 'ATTESTATION_SESSION_EXPIRED') {
235
+ // the attestation session lapsed: refresh once and send again
236
+ res = await fetch(`${apiUrl}/v1/end-user/content/posts`, { headers: await client.refreshRequestHeaders() });
237
+ }
238
+ ```
239
+
240
+ Retry only `ATTESTATION_SESSION_EXPIRED` (a validly signed session past its lifetime), once. The SDK's own requests already do this. Do not retry `ATTESTATION_REQUIRED` (no or wrong proof: e.g. a simulator without the TEST key, a token for another project) or the permanent codes — `APP_NOT_REGISTERED`, `PROJECT_MISMATCH`, `DEVICE_NOT_TRUSTED`, `ATTESTATION_REVOKED` — a new session cannot fix them; surface them (they mean a setup problem, a missing Apps registration, a wrong project id, or an untrusted device).
241
+
242
+ - `client.getRequestHeaders(opts?: { withUnlockTokens?: boolean }): Promise<Record<string, string>>` runs attestation and loads stored unlock tokens first if needed; works before `initialize()`. Adds `X-Unlock-Token` (comma-separated, newest 20) when `content.lookup` has unlocked records; pass `{ withUnlockTokens: false }` to leave it out. Adds `X-App-Version` when `client.appVersion` is set. The server reads it only on content and lookup routes. It does not include `Authorization` or `Content-Type`; add the end-user Bearer token (`await client.auth.getValidAccessToken()`) yourself.
243
+ - `client.refreshRequestHeaders(opts?)` forces a new attestation session and returns fresh headers. Use it for a single retry after `401 ATTESTATION_SESSION_EXPIRED`, not on every request or every 401.
244
+
245
+ ## Auth
246
+
247
+ ```tsx
248
+ import { useAuth, useQafkaCmsClient } from '@qafka/react-native-cms';
249
+
250
+ const client = useQafkaCmsClient();
251
+ await client.auth.login({ email, password });
252
+ await client.auth.logout();
253
+ const { isAuthenticated, userId, roles, isAnonymous } = useAuth();
254
+ ```
255
+
256
+ - `useAuth(): AuthState` = `{ isAuthenticated: boolean, userId: string | null, roles: string[], isAnonymous: boolean }`; reactive to login, refresh, logout and an anonymous upgrade. `isAnonymous` is true only for an anonymous end-user (see "Anonymous end-users"). `roles` are consumer-tier role ids for UI branching only; the backend enforces access.
257
+ - `client.auth` is an `AuthClient`: `register(RegisterInput)` -> `EndUser`; `login(LoginInput)` -> `AuthTokens`; `logout()`; `refresh()`; `getValidAccessToken()`; `requestMagicLink(email)` -> `{ ok }`; `methods()` -> `AuthMethods` (GET `/auth/methods`, no sign-in needed: `{ email, registration, magicLink, passwordReset, anonymous, providers: [{ key, displayName, nonce }] }`, use it to decide which sign-in buttons to show; cached for a minute), `requestPasswordReset(email)` -> `{ ok }`; `confirmPasswordReset(token, newPassword)` -> `{ ok }`; `handleMagicLinkCallback(urlOrFragment)` -> `AuthTokens | null`; `getClaims()` -> `AccessTokenClaims | null` (`anon?: boolean` is `true` only on anonymous tokens); `getRoles()`; `isAuthenticated()`; `getAuthState()`; `subscribe(listener)`; external identity (below): `signInWithExternalToken(token, opts?)`, `linkExternal(token, opts?)`, `unlinkExternal(opts?)`; `me()` -> `EndUser` (GET `/auth/me`, fills `linkedProviders?: string[]`; 401 `ACCOUNT_NOT_FOUND` / `ACCOUNT_DEACTIVATED`); `opts.nonce` / `upgrade({ method: 'external', nonce })` take the RAW nonce (send `sha256(raw)` hex to Apple AND Google, the raw value to us; a raw-equal claim is rejected; provider `nonce` must be `optional`/`required`, `required` only with `cms` session mode); anonymous end-users (below): `signInAnonymously()`, `isAnonymous()`, `upgrade(input)`, `getLastUpgradeOutcome()`, `deleteAccount()`.
258
+ - Types: `AuthMethod` = `'email' | 'magic_link'`; `EndUserAuthMethod` = `AuthMethod | 'oidc' | 'anonymous'` (`'anonymous'` was added with anonymous end-users: an exhaustive `switch` over `endUser.authMethod` needs a new case); `RegisterInput` = `{ email, password?, phone?, method }`; `LoginInput` = `{ email, password }`; `AuthTokens` = `{ accessToken, refreshToken, expiresIn }`; `RefreshResult` = `{ accessToken, expiresIn }`; `EndUser` = `{ id, email: string | null, phone, authMethod: EndUserAuthMethod, isActive, emailVerifiedAt }`.
259
+ - Password reset: `requestPasswordReset(email)` always resolves `{ ok: true }` (unknown, deactivated and external-only accounts look the same; show "e-mail sent" regardless). `confirmPasswordReset(token, newPassword)` sets the password from the e-mail link's `token` and does NOT sign in; call `login` afterwards. Both are anonymous. Needs the project's `passwordResetUrl` setting (dashboard) with a `{token}` placeholder (deep link such as `myapp://reset-password?token={token}`); your app parses `token` from the opened link. Cooldown: the same email gets at most 1 reset mail per 60 s and 10 per day (also for `requestMagicLink`; counted separately); a repeat still resolves `{ ok: true }` but sends no mail, so disable "resend" for 60 s. Errors (`error.raw.code`): 409 `PASSWORD_RESET_NOT_CONFIGURED` (request and confirm; clearing `passwordResetUrl` also kills already-issued links); 403 `EMAIL_AUTH_DISABLED` / `INTERNAL_AUTH_DISABLED`; 400 `INVALID_RESET_TOKEN` (unknown, expired, used, wrong kind or inactive account; one code for all). A password-policy violation is a 400 problem to show in the form (the same token can be retried).
260
+ - The Bearer token is attached to requests automatically and refreshed transparently; concurrent requests share one refresh.
261
+ - Login and logout reset the query cache automatically (no cross-user data leaks); mounted queries refetch with the new identity. Token refresh does not reset the cache. Manual reset: `useQafkaCms().clearCache()`.
262
+
263
+ ### External identity provider
264
+
265
+ When the project is configured with its own identity provider (dashboard: external auth), sign in with that provider's token instead of a CMS password:
266
+
267
+ ```ts
268
+ const client = createClient({ projectId, externalTokenProvider: async () => myAuth.getFreshToken() /* or null when logged out */ });
269
+ const { endUser, created } = await client.auth.signInWithExternalToken(idpToken); // ExternalSignInResult
270
+ await client.auth.linkExternal(idpToken); // signed-in member -> { endUser }
271
+ await client.auth.unlinkExternal(); // -> { endUser }
272
+
273
+ // Several providers (Apple, Google, your own IdP): name the provider by its key.
274
+ const client2 = createClient({ projectId, externalProvider: 'google' }); // client-wide default key
275
+ await client2.auth.signInWithExternalToken(googleIdToken); // sends provider: 'google'
276
+ await client2.auth.signInWithExternalToken(appleIdToken, { provider: 'apple' }); // per-call wins
277
+ await client2.auth.linkExternal(appleIdToken, { provider: 'apple' });
278
+ await client2.auth.unlinkExternal({ provider: 'apple' }); // only that provider's identity
279
+ ```
280
+
281
+ - `signInWithExternalToken(token, opts?: { provider?: string })` and `linkExternal(token, opts?: { provider?: string })`: `provider` is the project's `authConfig.externalProviders[].key`. Resolution order: per-call `opts.provider`, then `QafkaCmsConfig.externalProvider`, then nothing (the key is omitted from the request and the server routes: the only enabled provider, or the one matching the token's issuer). With several enabled providers (or an opaque `userinfo` provider) the server answers 400 `EXTERNAL_PROVIDER_REQUIRED` unless a key is sent, so send one. `unlinkExternal(opts?: { provider?: string })` only uses the per-call value (the config default is not applied): with it, only that provider's identity is removed, without it ALL external identities are.
282
+ - `endUser.email` may be `null`. The session depends on the provider's `sessionMode` (server setting): `external` (default) returns an access token only, renewed through `externalTokenProvider`; `cms` also returns a refresh token and the session is stored and refreshed exactly like `login` (no `externalTokenProvider` needed). The Apple and Google presets use `cms` because their ID tokens cannot be renewed silently; `cms` is recommended for them (the server does not enforce it). `jwks` providers need the app's own client ids as `audience` (mandatory for Apple/Google issuers and for `cms` providers that verify with `jwks`).
283
+ - `externalTokenProvider?: () => Promise<string | null>` (in `QafkaCmsConfig`) is called when the CMS access token expires and after an app restart, for `external`-mode sessions only; concurrent callers share one re-exchange, which reuses the provider key of the original sign-in. Returning `null` (or no provider) ends the session. `externalProvider?: string` (in `QafkaCmsConfig`) is the default provider key described above. Use `auth.getValidAccessToken()` to read the current CMS token.
284
+ - `logout()` on an `external`-mode session clears it locally (no `/logout` call) and never resumes silently; on a `cms`-mode session it behaves like a normal logout.
285
+ - Errors are `ProblemError`; the machine code is `error.raw.code`: 401 `INVALID_EXTERNAL_TOKEN` / `IDENTITY_DEACTIVATED` / `ACCOUNT_DEACTIVATED` (the member account itself is deactivated; a failed silent re-exchange with any of these three ends the external session); 400 `EXTERNAL_PROVIDER_REQUIRED`; 403 `EXTERNAL_AUTH_DISABLED` (also: the named `provider` is unknown or disabled) / `EXTERNAL_SIGNUP_DISABLED` / `INTERNAL_AUTH_DISABLED`; 409 `IDENTITY_IN_USE` / `ACCOUNT_EXISTS_LINK_REQUIRED` / `LAST_SIGN_IN_METHOD`; 502 `EXTERNAL_PROVIDER_UNAVAILABLE`.
286
+ - Already-issued CMS access tokens stay valid until `accessTokenTtlMinutes` after the identity is deactivated or the member logs out (access tokens are stateless).
287
+
288
+ ### Anonymous end-users
289
+
290
+ The project can let the app start without an account (dashboard: auth settings, anonymous; off by default). An anonymous end-user is a real member row with no e-mail or password, a normal stored session and an access token with `anon: true`. Later it is upgraded in place: the `userId` stays the same, so everything it created (owned rows, tier roles, inbox, push device) stays with it.
291
+
292
+ ```ts
293
+ const client = createClient({ apiUrl, projectId, anonymousAuth: 'manual' /* default */ });
294
+
295
+ const { userId, created } = await client.auth.signInAnonymously(); // AnonymousSignInResult
296
+ client.auth.isAnonymous(); // true
297
+ const { isAnonymous } = useAuth();
298
+
299
+ // later: keep the data, add a sign-in method
300
+ await client.auth.upgrade({ method: 'email', email, password }); // UpgradeResult
301
+ await client.auth.upgrade({ method: 'external', token: appleIdToken, provider: 'apple' });
302
+ await client.auth.upgrade({ method: 'magic_link', email }); // { ok: true }; finish in handleMagicLinkCallback
303
+ ```
304
+
305
+ - `manual` vs `auto`: with `'manual'` (default) the SDK never creates an anonymous user; call `signInAnonymously()` when the user first needs an identity (a write, a favourite, a purchase). Choose `'auto'` only when the app needs an identity on every install: `initialize()` (the Provider) creates one when no session is stored, and after `logout()`, `deleteAccount()` or a lost anonymous identity (below) a new one is created lazily on the next request that needs a token (never after a verification-pending upgrade, see `upgrade`). Every install then becomes a member row, so prefer `'manual'` for read-mostly apps. With `'auto'` a failed creation (e.g. anonymous auth disabled) does not fail `initialize()` and is not retried on every request; call `signInAnonymously()` to retry.
306
+ - `signInAnonymously(): Promise<AnonymousSignInResult>` -> `POST /v1/end-user/auth/anonymous` (no Bearer; the project + attestation proof headers like every SDK request: release builds need device attestation, simulators the dev TEST key). `AnonymousSignInResult` = `{ userId, isAnonymous, created, endUser }`. Idempotent: when any session exists (anonymous, registered or external) it returns that identity with `created: false` and `endUser: null`, without a request; concurrent calls share one request. Websites use the web SDK `@qafka/cms` instead (web key with the `auth` scope + Turnstile); a web key without those gets `403 ANONYMOUS_WEB_NOT_SUPPORTED`.
307
+ - `isAnonymous()` reads the `anon` claim of the current access token (false when signed out or registered). Policies: an anonymous user gets the PUBLIC policies plus the `ANONYMOUS_USER` ones, not the registered-member (`END_USER`) ones; grant anonymous writes per collection in the dashboard.
308
+ - `upgrade(input: UpgradeInput)` -> `POST /v1/end-user/auth/upgrade` with the anonymous Bearer. `UpgradeInput` is `{ method: 'email', email, password }`, `{ method: 'magic_link', email }` or `{ method: 'external', token, provider? }` (`provider` falls back to `QafkaCmsConfig.externalProvider`). `email`/`external` resolve `UpgradeResult` = `{ accessToken, refreshToken?, expiresIn, endUser, verificationRequired?, signedIn? }` (`signedIn` is always set by `upgrade()`); with `signedIn: true` the returned tokens replace the stored session; `refreshToken` is absent only for an external provider with `sessionMode: 'external'`, which then continues as an external session (needs `externalTokenProvider`). `magic_link` resolves `{ ok: true }` and changes nothing until the user opens the link; then `handleMagicLinkCallback(url)` stores the new session and `getLastUpgradeOutcome()` returns `UpgradeOutcome`: `'upgraded'` (same `userId`, data kept) or `'switched'` (the e-mail already had an account; the user is now signed in to that account and the anonymous data stays behind). It returns `null` when the last callback carried no upgrade result, and after logout.
309
+ - Email upgrade when the project requires e-mail verification: the server upgrades the account in place (same id, data kept) but revokes the anonymous sessions and issues no tokens. `upgrade()` then resolves `{ signedIn: false, verificationRequired: true, endUser, accessToken: '', expiresIn: 0 }` (no `refreshToken`), clears the local session and `useAuth()` turns signed out (`isAuthenticated: false`). Show "check your e-mail, then sign in"; after the user verifies, call `login({ email, password })` and the same `userId` comes back. Always branch on `signedIn`, not on `verificationRequired` alone (an older server could send `verificationRequired: true` together with tokens, and then the user is signed in). With `anonymousAuth: 'auto'` the SDK does NOT create a new anonymous user meanwhile (that user would be left behind at the login); lazy creation re-arms only after the next `logout()` / `deleteAccount()`. A cold start (`initialize()`) with no stored session still creates one in `'auto'`, so prefer finishing verification in the same app run.
310
+ - After an upgrade `useAuth()` keeps `userId` and flips `isAnonymous` to false. With `QafkaCmsProvider` the query cache is cleared and active queries refetch (the policy set changed), as on login. The push device stays bound to the same user.
311
+ - Conflicts (`ProblemError`, `raw.code`; the anonymous session is kept): 409 `ACCOUNT_EXISTS_SIGN_IN_REQUIRED` (the e-mail has an account: offer "sign in" -> `login`; the identity switches and the anonymous data is not carried over, so warn the user); 409 `ACCOUNT_EXISTS_LINK_REQUIRED` (external: the verified e-mail belongs to another member: sign in to that account, then `linkExternal`); 409 `IDENTITY_IN_USE` (external: the identity belongs to another member: `signInWithExternalToken` switches to it); 409 `NOT_ANONYMOUS` (the session is already registered: refresh your UI state). An e-mail that exists only as an external account answers 409 as well: offer the provider's sign-in. Magic link never reveals a conflict: it shows up as `'switched'`.
312
+ - Linking while anonymous: `linkExternal` needs a registered member; the server answers 409 `UPGRADE_REQUIRED` for an anonymous caller, and the SDK throws the same `ProblemError` (`status` 409, `raw.code` `'UPGRADE_REQUIRED'`) without a request when `isAnonymous()` is true. While `isAnonymous()`, call `auth.upgrade({ method: 'external', token, provider })` instead of `linkExternal`.
313
+ - Lost anonymous identity: when the refresh of an anonymous session answers 401 (the inactivity sweep deleted the user, it was deactivated, or the account was deleted on another device), the identity is gone for good. The SDK clears the local session without a server call, `useAuth()` turns signed out, and the call returns no token (`refresh()` rejects with the `ProblemError`). With `'auto'` the next request that needs a token creates a new anonymous user; with `'manual'` call `signInAnonymously()` when needed. This also works after a cold start (the SDK remembers that the stored session is anonymous). A 401 with an `ATTESTATION_*` code is not an identity loss and keeps the session. Registered sessions are unchanged: a failed refresh returns no token and keeps the stored session.
314
+ - Creation errors: 403 `ANONYMOUS_AUTH_DISABLED` (the project has it off), 403 `ANONYMOUS_WEB_NOT_SUPPORTED`, 429 `ANONYMOUS_RATE_LIMITED` (per-device daily limit; `Retry-After`), 403 `ANONYMOUS_LIMIT_REACHED` (project cap on active anonymous users), 401 `ATTESTATION_REQUIRED` (no proof).
315
+ - `logout()` while anonymous revokes the session and the anonymous data becomes unreachable for good (there is no way back to that user); the server deletes inactive anonymous users after the project's inactivity period (default 30 days). Upgrade first if the data matters.
316
+ - `deleteAccount(): Promise<void>` -> `DELETE /v1/end-user/auth/me` (Bearer) deletes the signed-in account, anonymous or registered (App Store account-deletion rule), then clears the local session. On an error the session is kept and the `ProblemError` is thrown. Content the user created: for a registered user it is kept without an owner; for an anonymous user it follows the project's anonymous cleanup setting (dashboard), the same as for the inactivity sweep.
317
+ - Logging in to another account while anonymous (`login`, `signInWithExternalToken`) is not an upgrade: the identity switches and the anonymous user is left for cleanup.
318
+
319
+ ## i18n and active language
320
+
321
+ ```tsx
322
+ import { useTranslation, useLocale } from '@qafka/react-native-cms';
323
+
324
+ const { t, locale, setLocale } = useTranslation();
325
+ t('greeting', { name: 'Ada' }); // {{name}} interpolation
326
+ const { availableLocales, defaultLocale } = useLocale();
327
+ ```
328
+
329
+ - `useTranslation(): UseTranslationResult` = `{ t(key, params?: TranslateParams), locale, setLocale(locale): Promise<void> }`. `t` falls back active -> default -> the key itself.
330
+ - `useLocale(): UseLocaleResult` = `{ locale, setLocale, availableLocales: string[], defaultLocale }`.
331
+ - The active locale is attached to every content request as `?locale=` (and `Accept-Language`); backend precedence is `?locale=` > `Accept-Language` > project default. A per-request `locale` param overrides it. Changing the locale invalidates the content cache.
332
+ - `client.language` is the `LanguageManager` (`LanguageManagerDeps` = `{ storage }`): `getLanguage()`, `setLanguage(locale)`, `getDefaultLocale()`, `getAvailableLocales()`, `t(key, params?)`, `subscribe(listener)`, `getRevision()`, `applyLocales(data)`, `applyI18n(data)`, `hydrate()`.
333
+ - Data shapes: `LocalesData` = `{ defaultLocale, locales: string[] }`; `I18nData` = `{ translations: Record<locale, Record<key, string>> }`; `TranslateParams` = `Record<string, string | number>`.
334
+ - Cold start without network: pass `bootstrap: { i18n, locales }` to `createClient` (files produced by the Qafka CLI `config pull`).
335
+
336
+ ## Push
337
+
338
+ ```tsx
339
+ import { usePush } from '@qafka/react-native-cms';
340
+
341
+ const { permission, deviceId, token, requestPermission } = usePush();
342
+ await requestPermission(); // shows the OS dialog; call it from a user action
343
+ ```
344
+
345
+ - `usePush(): UsePushResult` = `DeviceRegistrationState` (`permission: PushPermissionStatus`, `deviceId: string | null`, `token: string | null`) plus `requestPermission(): Promise<PushPermissionStatus>`.
346
+ - `PushPermissionStatus` = `'granted' | 'denied' | 'undetermined'`.
347
+ - The device is registered silently at boot (no prompt). `requestPermission()` prompts and registers the token. The device row is re-registered on auth change so it binds to the signed-in user.
348
+ - Low level: `client.deviceRegistration` is a `DeviceRegistrationManager` (`init`, `requestPermission`, `getDeviceState`, `subscribe`, `dispose`). Related types: `DeviceRegisterBody`, `NativePushApi`, `AndroidPushConfig` (Android FCM client config, delivered through the `push` config domain), `DeviceInfo`.
349
+
350
+ ## Live content (`live`)
351
+
352
+ Refresh a list or record while the screen is open when the server signals a change (QFK2-E76). Works out of the box on React Native.
353
+
354
+ ```tsx
355
+ const { data } = useContent('orders', params, { live: true }); // any change in the collection
356
+ const { data: order } = useContentItem('orders', id, undefined, { live: true }); // only this record
357
+ useContent('orders', { expand: ['customer'] }, { live: { also: ['customers'] } }); // expanded relations are not watched automatically
358
+ ```
359
+
360
+ - Prerequisite: the collection's change signal is on (admin: collection → Permissions → change signal switch; MCP: `apply_schema` with `changeSignal: 'on'`; refused on the `users` / `profiles` system collections). Off or not readable → one dev warning (`[QafkaCMS] live disabled for <c>: …`) and plain TTL behavior; nothing is thrown.
361
+ - Use it for screens that must update within seconds (chat-like list, order status). Ordinary screens keep the TTL cache; your own writes are refreshed by `useMutation` invalidation.
362
+ - The signal carries no data: the hook refetches with the user's own access. Only mounted queries refetch, with the server's jitter (`spreadMs`). Draft-only changes never signal.
363
+ - Transport: `mode: 'auto'` (default) and `'sse'` use one multiplexed SSE connection per client and fall back to polling (HTTP / network error, 3 immediate closes); `'poll'` polls only (`pollIntervalMs`, default 60 s, floor 30 s). App-wide default: `createClient({ contentLiveDefault: 'poll' })`. Closes / stops in the background, catches up on foreground. Over 20 collections / 50 records per connection the rest polls.
364
+ - Login / logout reconnects with the new identity. Debug: `client.contentChanges.status()` → `'sse' | 'polling' | 'idle'`.
365
+ - Raw HTTP contract and leak model: API repo `docs/integration/content-live.md`.
366
+
367
+ ## Cache revalidation (ETag, version gate)
368
+
369
+ When cached content goes stale (TTL over, `invalidate`, `refetch`), the SDK avoids downloading what has not changed (QFK2-E59).
370
+
371
+ - ETag, always on: `useContent` / `useContentItem` send the stored `ETag` as `If-None-Match`. A `304` means unchanged: the cached data (same object) is kept and its timestamp refreshed. Nothing to configure; works with every collection and with `expand`. An API without ETag support simply answers `200`.
372
+ - Version gate, opt-in: `createClient({ contentVersionGate: true })` (or `{ maxAgeMs }`; `true` = 24 h). Resolved value: `client.contentVersionGate` (`{ maxAgeMs }` or `null`).
373
+ - A stale entry first asks the collection version (`client.contentChanges.versions(collections)`, `GET /content-changes/version`). Unchanged since the data was fetched → served from cache with no data request at all (typical app launch with `persist: true`). Changed or unknown → normal conditional fetch.
374
+ - Only collections with the change signal on (`changeSignal: 'on'`, same switch as `live`), and only reads without `expand` (an expanded relation changes without bumping this collection's version). Other reads behave as before. A collection whose version request is refused (404) is ungated for the session.
375
+ - Version requests are batched (≤20 collections per call). The version is read before the data, so a change is never missed (worst case: one extra download).
376
+ - `maxAgeMs` bounds how long a version match may skip the download since the last real fetch (200 / 304): policy, schema and draft-only changes do not bump the version, so content is fully revalidated at least that often.
377
+ - `invalidate` / `refetch` and `live` signals skip the check and always fetch (conditionally). Login / logout clear the cache, stored versions included.
378
+
379
+ ## Content per app version
380
+
381
+ The SDK sends the app's version as `X-App-Version` on every request (QFK2-E59), so the server can leave out content this app version cannot show.
382
+
383
+ - Automatic on React Native: the default is the native app version (the SDK reads `getDeviceInfo().appVersion`: iOS `CFBundleShortVersionString`, Android `versionName`). Override it with `createClient({ appVersion })` (e.g. `appVersion: '2.4.0'`); `appVersion: null` sends none. Only a valid app version is sent: 1–4 numeric segments (`1`, `1.4`, `1.4.2`, `1.4.2.7`; `1.4` equals `1.4.0`). Anything else (`1.4.0-beta`, a build without the native module) sends no header, and the server treats the app as an unknown version. The resolved value is `client.appVersion` (`string | null`); `client.getRequestHeaders()` includes the header.
384
+ - Records: a collection can name a minimum and maximum app version field (text fields holding versions such as `1.4`; set in the dashboard or by the project's agent). A record whose minimum is above the app's version, or whose maximum is below it, is not returned to that app: not in lists, counts or expanded relations, and a 404 by id (`get`, `lookup`). An empty field means no limit.
385
+ - Blocks: a component type can carry `minAppVersion`. For an older app, blocks of that component are removed from dynamic-zone arrays and a component field holding one reads as `null` (nested components too). Render what you get; there is nothing to do in the app.
386
+ - Unknown version (no header, or an invalid one): set per collection (for blocks, per component type): `'show'` (the default; no filtering) or `'hide'` (records with a limit, and blocks with `minAppVersion`, are hidden).
387
+ - Writes: an old app that read a record with hidden blocks cannot update that dynamic-zone or component field: the server answers `409` with `raw.code` `APP_VERSION_BLOCKS_HIDDEN`, because the array it sends back would delete the blocks it never saw. In `content.update`, send only the fields you change (a body without that field is accepted). Writes never hide records.
388
+ - This is compatibility filtering, not a security boundary: the client sets the header. Protect data with policies.
389
+ - Relation to force update: force update makes users upgrade; this protects the users who have not upgraded yet. Typical use: publish new content with a minimum app version, and force-update only when an old version must go.
390
+ - Cache: persisted entries remember the app version they were fetched with. After an app update such an entry is still shown at once, but it counts as stale and skips the version gate, so it is revalidated for the new version (the ETag is kept: an unchanged answer is still a `304`). Nothing to configure; the Provider passes `client.appVersion` as `QueryCacheOptions.appVersion`.
391
+
392
+ ## Content bundle (offline snapshot)
393
+
394
+ An opt-in, read-only snapshot of chosen collections, downloaded as one file and kept on the device (QFK2-E59 T466). Screens read it with no network. Use it for games (levels, questions), offline catalogs, an in-mall store directory: data every user sees the same way.
395
+
396
+ ```tsx
397
+ import AsyncStorage from '@react-native-async-storage/async-storage';
398
+
399
+ const client = createClient({ apiUrl, projectId, contentBundle: { storage: AsyncStorage } });
400
+ // or: contentBundle: { storage: AsyncStorage, locale: 'tr', initial: require('./qafkacms/bundle.tr.json') }
401
+ // or: contentBundle: true (no storage: kept in `cacheStorage` when set, else in memory for the app session only)
402
+
403
+ function Stores() {
404
+ const { rows, version, isLoading, error } = useBundle<Store>('stores');
405
+ const { data: store } = useBundleItem<Store>('stores', selectedId);
406
+ // render rows; version is null until a bundle is held
407
+ }
408
+ ```
409
+
410
+ - Opt in per collection on the project side (admin: collection → Permissions → content bundle switch; MCP `apply_schema` with `bundle: true`), plus `createClient({ contentBundle })` in the app. Only regular collections the anonymous end-user can read (not `users` / `profiles`, not scoped). No collection opted in = no bundle; nothing else changes.
411
+ - Anonymous view only: the published rows an anonymous end-user may read (policies and code-locked teasers apply). No per-user data: a signed-in user gets the same bundle, and login / logout do not clear it. Per-user or private data stays on `useContent`.
412
+ - Built automatically (about 30 s after a change in a bundled collection, at most 5 min later) and by hand (admin "Build now", MCP `build_content_bundle`). Relations between bundled collections must resolve: a broken reference (a related row missing from the bundle, e.g. still a draft) fails the build and the previous bundle stays live, so the live bundle can lag behind the content until it is fixed. Relations are ids (no `expand`); join two bundled collections in the app.
413
+ - Limits: 20 MB uncompressed per file, one file per locale. Images and files are URLs, not embedded: showing them still needs the network (or your own image cache).
414
+ - `client.bundle` (`ContentBundleApi`, present only with `contentBundle`): `sync({ locale? })` → `ContentBundleSyncResult` (`{ version, changed }`), `ready()`, `version`, `locale`, `error`, `isLoading`, `revision`, `rows(collection)`, `get(collection, id)`, `subscribe(listener)`, `start()` (sync now + on foreground + on locale change; returns stop), `view` / `itemView` (the hooks' snapshots).
415
+ - `sync()` asks `GET /v1/end-user/content-bundle` for the published version (same headers as content requests). Only when it differs from the held bundle does it download the file from the short-lived signed URL: a CDN / storage host gets a plain GET with no SDK headers, an API path gets the SDK headers. The file is checked (`formatVersion` 1, the announced version) before it replaces the held one. Any failure (offline, expired URL, invalid file) keeps the previous bundle, sets `error` and rejects. Concurrent calls share one request. 404 `CONTENT_BUNDLE_NOT_FOUND` (no bundle published) → version `null` and the stored copy is removed.
416
+ - The Provider syncs at boot, whenever the app returns to the foreground and when the active locale changes; there is nothing to call. Without the Provider: `client.bundle.start()`, or `sync()` yourself.
417
+ - Storage: pass a plain key/value store as `contentBundle.storage` (type `CacheStorage`: `getItem` / `setItem` / `removeItem` / `multiRemove`, all async); without it the bundle uses `createClient({ cacheStorage })` when that is set. `AsyncStorage` fits as is; for MMKV wrap it: `{ getItem: async (k) => mmkv.getString(k) ?? null, setItem: async (k, v) => mmkv.set(k, v), removeItem: async (k) => mmkv.delete(k), multiRemove: async (ks) => ks.forEach((k) => mmkv.delete(k)) }`. Bundle files can be several MB (one key per locale): Android AsyncStorage has size limits per value and in total, so prefer MMKV or a file-backed adapter for big bundles. The SDK never writes the bundle to its secure storage (Keychain / EncryptedSharedPreferences, `client.storage`). Without `storage` (and without `cacheStorage`) the bundle lives in memory for the app session only (plus `initial`), with a dev warning: after a restart without network only `initial` is there until the next sync. A write that fails (storage full) keeps the new bundle in memory and warns.
418
+ - Offline: the last stored bundle keeps serving. `initial` (a `BundleFile`, e.g. downloaded at build time and shipped with the app) is shown until a newer version is stored, so a first launch without network has content.
419
+ - Locale: default the active locale (`setLocale` re-syncs that locale), else `contentBundle.locale`, or `sync({ locale })` (kept until the active locale changes). A locale without a file gets the project default; `client.bundle.locale` says which.
420
+ - App version filtering applied client-side with `client.appVersion`, by the rules of "Content per app version": rows outside their min / max range are left out, blocks of a component with a newer `minAppVersion` are removed from dynamic-zone arrays (nested too), an unknown version follows `'show'` / `'hide'`, and a component field holding such a component reads as `null` (repeatable too), exactly as from the API. The file names each collection's and component's composite fields (`componentFields`, `zoneFields`) for this; a bundle built by an older API lacks them, and then only dynamic-zone blocks (`__component`) are removed.
421
+ - `useContent` / `useContentItem` are unchanged and never read the bundle.
422
+ - Types: `UseBundleResult`, `UseBundleItemResult`, `ContentBundleConfig`, `ContentBundleOption`, `ContentBundleStatus`, `ContentBundleView`, `ContentBundleItemView`, `BundleFile` (`formatVersion`, `version`, `locale`, `collections` of `BundleCollection` = `{ rows, appVersion?: BundleCollectionAppVersion, componentFields?, zoneFields? }`, `components` of `BundleComponentInfo`; `componentFields` / `zoneFields` = `BundleFieldMeta`).
423
+
424
+ ## Config sync
425
+
426
+ ```ts
427
+ const theme = client.createConfigSync('theme', { primary: '#000' });
428
+ await theme.start();
429
+ const unsubscribe = theme.subscribe((data) => applyTheme(data));
430
+ theme.current(); // latest data
431
+ theme.stop();
432
+ ```
433
+
434
+ - `client.createConfigSync<T>(domain, buildTimeDefault: T, options?: { pollIntervalMs?, live?, buildTimeVersion? }): ConfigSyncClient<T>`.
435
+ - `ConfigSyncClient<T>`: `start()`, `stop()`, `current()`, `subscribe(listener)`. Snapshots are `ConfigSnapshot<T>` = `{ version, data }`.
436
+ - Default transport is polling (cheap version check first; downloads only when the version increases; pauses in background). `live: true` opens SSE and is only for domains needing sub-second push. Poll interval floor is 30 s.
437
+ - `locales`, `i18n` and (Android) `push` domains are managed by the SDK itself; do not create them again.
438
+ - SSE types for host injection: `ConnectSse`, `SseHandlers`, `SseConnection`; `AppStateProvider` is the foreground/background source (default: RN `AppState`).
439
+
440
+ ## Rules
441
+
442
+ - Never put a secret or service/API key in a release build. A mobile app needs no key (`projectId` is public); the TEST key lives only behind `__DEV__` (`devConfig` or an `apiKey` from an env var). Generate types with the MCP tool `generate_types` and commit the result.
443
+ - `QafkaCmsProvider` owns `client.initialize()` (token hydrate, attestation, language start). Do not call it again when using the Provider. Without React: `await client.initialize()` once yourself.
444
+ - Every SDK request carries `X-Project-Id` (and `X-Project-Key` when a `publishableKey` is set) plus the proof (session token or dev TEST key). Do not set these headers by hand; for your own client use `client.getRequestHeaders()`.
445
+ - `persist` is for small reference data only, unless `createClient({ cacheStorage })` gives the cache a plain store.
446
+ - Hooks must be called under `QafkaCmsProvider`.
447
+ - Reads without a session need a PUBLIC read policy on the collection; only published rows are returned (an anonymous end-user also gets the `ANONYMOUS_USER` policies).
448
+ - Use `useContent` / `useContentItem` for reads so params join the cache key; do not wrap `client.content.list` in a bare `useEffect`.
449
+
450
+ ## Ordered many-to-many (`RELATION_MANY`)
451
+
452
+ A `RELATION_MANY` field links a record to several records of another collection, in a fixed order.
453
+
454
+ - Read: by default the field is the ordered id array, typed `RelationManyValue` (`string[]`, `[]` when empty, never `null`). With `expand` it holds the ordered target objects (type them through the read generic, e.g. `ListResult<ContentRecord & { categories: Category[] }>`); targets the reader cannot see are dropped from the expanded list.
455
+ - Write (create/update body), typed `RelationManyWrite`: a full ordered array replaces the links (`{ categories: ['c1', 'c2'] }`); `{ connect: [...], disconnect: [...] }` changes them partially; `null` clears them. Semantics: a full array replaces the links in the given order; `connect` appends ids that are not yet linked to the end and keeps existing positions; `disconnect` removes ids and ignores ids that are not linked; the same id in both `connect` and `disconnect` is rejected with 400; `{}` changes nothing. With `withTitle` (`with_title`), expanded targets carry `_title`.
456
+ - Filter through a relation with a one-level dotted path: `{ 'categories.name': { _eq: 'Sports' } }` (also works for a plain `RELATION`, e.g. `'mall.name'`). Quantifiers (`QuantifierOps`): `_some` and `_none` take a filter on the target collection. `{ categories: { _some: { name: { _eq: 'Sports' } } } }` matches records with at least one matching target; the same under `_none` matches records with none. `{ categories: { _some: {} } }` means any visible linked target exists; `{ categories: { _none: {} } }` means none. `_some`/`_none` are valid only on `RELATION_MANY` fields (on any other field the API returns 400). They count only targets visible to the caller: `_some: {}` means at least one visible linked target, and `_none: {}` means no visible linked target, so records linked only to unreadable or draft targets match `_none: {}`. Direct comparison operators (`_eq`, `_in`, ...) on a `RELATION_MANY` field are rejected with 400.
457
+ - Sort by a related field (`sort: 'mall.name'`) works for `RELATION` only, not `RELATION_MANY`.
458
+ - The Qafka service endpoints (`/api/v1/service/*`) never return `RELATION_MANY` fields.
459
+ - Sharing a record with several users (set up in the dashboard / by the project's agent, nothing to do in the SDK): a `RELATION_MANY` field to the `users` collection (e.g. `shared_with`) plus a policy rowFilter `{ _or: [{ created_by: { _eq: '$CURRENT_USER' } }, { shared_with: { _some: { id: { _eq: '$CURRENT_USER' } } } }] }`. Then `content.list` / `get` / `update` / `delete` simply return or touch the records the signed-in user owns or that are shared with them; a record not shared with them is a 404 by id. To share, write the field like any `RELATION_MANY` (`{ shared_with: { connect: [userId] } }`), if the update policy lets this user change it.
460
+
461
+ ## Dependent relations (`constraint`)
462
+
463
+ A `RELATION` or `RELATION_MANY` field can carry a declarative `constraint: { targetField, equalsField }` in its config. It says: every record linked through this field must have `targetField` (a field of the target collection) equal to this record's `equalsField`. Example: on `stores`, field `floor` has `constraint: { targetField: 'mall', equalsField: 'mall' }`, so a store's `floor` must be a floor whose `mall` equals the store's own `mall`. The server enforces it; the SDK has no client-side check and needs no code for it.
464
+
465
+ - Enforcement: on create, the check runs whenever the saved record's constrained field is non-empty (including values from presets and column defaults), whether or not the body names it. On update, it runs when the body (or link writes) names the constrained field or its `equalsField`; updates that name neither are not checked. A `RELATION_MANY` is checked against its final link set. Version restore is checked too.
466
+ - Violation: HTTP 400; the whole write is rolled back. In the SDK, check `error.raw.code === 'RELATION_CONSTRAINT_VIOLATION'` and read the constrained field (e.g. `floor`) from `error.raw.errors[].field` (`ProblemError` has no top-level `errors`), so you can show the message next to that input. Fix it in the same save by changing or clearing the constrained field.
467
+ - Null is strict: if the record's `equalsField` is null, the constrained field must be null (`RELATION`) or `[]` (`RELATION_MANY`); a target whose `targetField` is null never matches. So set `equalsField` (e.g. `mall`) in the same request as the relation, and clear the relation when you clear `equalsField`.
468
+ - Comparison is exact equality: case-sensitive, no trimming, no normalization (for text-like fields `A@x` differs from `a@x`).
469
+ - Not enforced in v1: changes on the target side (moving a floor to another mall does not re-check its stores) and `ON DELETE` actions that change `equalsField` (`set_null`/`cascade`). Such a record gets a 400 the next time a save includes the constrained field or `equalsField`, so an unrelated full-object update can fail on it.
470
+ - Rule-driven writes do not return 400 to the SDK: a rule action that would violate the constraint fails and leaves the row unchanged.
471
+ - Reads, filters and sorting are unaffected. `constraint` is schema config, set from the admin panel or the MCP declarative schema (`config.constraint`); it is not a runtime SDK setting.
472
+
473
+ ## Color fields
474
+
475
+ `COLOR` field values are returned exactly as stored (the API does not normalize them). Shapes (`ColorValue`):
476
+
477
+ - Hex string: `#rgb`, `#rrggbb` or `#rrggbbaa` (`#RGB` / `#RRGGBBAA` also valid; any letter case, kept as written).
478
+ - `GradientValue`: `{ angle?, stops: [{ color, position? }] }`. A missing `angle` means 0. Angle convention is CSS: 0 = up (the top edge), measured clockwise (90 = right). `position` is optional, 0-100.
479
+ - `SchemedColor` (field config `schemes: true`): `{ light: ColorValue, dark?: ColorValue | null }`. Without `dark`, light is used in both schemes.
480
+
481
+ Helpers (exported from the package root, with the types `ColorValue`, `GradientValue`, `SchemedColor`):
482
+
483
+ - `resolveColor(value: unknown, scheme: 'light' | 'dark'): ColorValue | null` returns a plain hex or gradient as is (same value, not converted); for a `schemes` value it returns `dark ?? light` on 'dark' and `light` otherwise (an invalid `dark` falls back to `light`); invalid input returns `null`.
484
+ - `useResolvedColor(value: unknown): ColorValue | null` is `resolveColor` with the device scheme from React Native `useColorScheme` (unknown scheme = light); it re-resolves when the scheme changes.
485
+
486
+ ## Public exports
487
+
488
+ Everything exported from the package entry (`src/index.ts`), grouped.
489
+
490
+ Client: `createClient`, `QafkaCmsClient`, `QafkaCmsConfig`, `QafkaCmsClientDeps`, `getVersion`, `SDK_VERSION`.
491
+
492
+ Sub-clients: `AuthClient`, `ContentClient`, `ContentClientOptions` (`getLocale?`, `getLocaleFallback?`, `unlockTokens?`), `LookupResult`, `UnlockTokenStore`, `AttestationManager`, `DeviceRegistrationManager`, `DeviceRegistrationState`, `DeviceRegisterBody`, `NativePushApi`, `AndroidPushConfig`, `PushPermissionStatus`, `DeviceInfo`, `ConfigSyncClient`, `ProblemError`, `ProblemDetails`.
493
+
494
+ Content and filter types: `ContentRecord`, `GetParams`, `ListParams`, `ListResult`, `FilterNode`, `FieldOps`, `FilterOp`, `CURRENT_USER`, `NOW` (`'$NOW'`, server UTC time), `now` (`now(offset?)` builds `$NOW` or `$NOW(<offset>)`, offset `+7d`-style with units m h d w; throws on a malformed offset).
495
+
496
+ Auth types: `AuthMethod`, `EndUserAuthMethod`, `RegisterInput`, `EndUser`, `LoginInput`, `AuthTokens`, `RefreshResult`, `AuthState`, `AccessTokenClaims`, `ExternalSignInResult`, `AuthMethods`, `AuthClientOptions`, `AnonymousAuthMode`, `AnonymousSignInResult`, `UpgradeInput`, `UpgradeResult`, `UpgradeOutcome`.
497
+
498
+ Config-sync types: `ConfigSnapshot`, `ConnectSse`, `SseHandlers`, `SseConnection`, `AppStateProvider`.
499
+
500
+ Live content types: `ContentChangesApi`, `ContentChangesStatus`, `ContentLiveMode`, `ContentWatchTarget`, `ContentWatchOptions`, `ContentInvalidationTarget`.
501
+
502
+ Content bundle types: `ContentBundleApi`, `ContentBundleConfig`, `ContentBundleOption`, `ContentBundleSyncResult`, `ContentBundleStatus`, `ContentBundleView`, `ContentBundleItemView`, `BundleFile`, `BundleCollection`, `BundleCollectionAppVersion`, `BundleComponentInfo`, `BundleFieldMeta`.
503
+
504
+ React: `QafkaCmsProvider`, `QafkaCmsProviderProps`, `PrefetchResource`, `useQafkaCms`, `useQafkaCmsClient`, `useQafkaCmsCache`, `QafkaCmsContextValue`, `QafkaCmsStatus`, `useQuery`, `UseQueryOptions`, `UseQueryResult`, `useContent`, `useContentItem`, `UseContentOptions`, `ContentLiveOption`, `useBundle`, `useBundleItem`, `UseBundleResult`, `UseBundleItemResult`, `useLookup`, `UseLookupVars`, `useMutation`, `UseMutationOptions`, `UseMutationResult`, `useAuth`, `usePush`, `UsePushResult`, `useLocale`, `UseLocaleResult`, `useTranslation`, `UseTranslationResult`.
505
+
506
+ Color: `resolveColor`, `useResolvedColor`, `ColorValue`, `GradientValue`, `GradientStop`, `SchemedColor`, `HexColor`.
507
+
508
+ i18n: `LanguageManager`, `LanguageManagerDeps`, `LocalesData`, `I18nData`, `TranslateParams`.
509
+
510
+ Cache: `QueryCache`, `QueryCacheOptions`, `serializeKey`, `QueryKey`, `QueryState`, `QueryStatus`, `QueryOptions`, `createMemoryCacheStorage`, `CacheStorage`, `parseDuration`, `Duration`.