@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 +510 -0
- package/README.md +244 -2
- package/android/build.gradle +41 -0
- package/android/src/main/AndroidManifest.xml +2 -0
- package/android/src/main/java/com/qafkacms/QafkaCmsPackage.kt +21 -0
- package/android/src/main/java/com/qafkacms/attestation/QafkaCmsAttestationModule.kt +92 -0
- package/android/src/main/java/com/qafkacms/push/QafkaCmsPushModule.kt +162 -0
- package/android/src/main/java/com/qafkacms/storage/QafkaCmsStorageModule.kt +80 -0
- package/app.plugin.js +1 -0
- package/dist/index.d.ts +2373 -0
- package/dist/index.js +4468 -0
- package/dist/index.js.map +1 -0
- package/expo-plugin/apnsForwarding.js +48 -0
- package/expo-plugin/withQafkaCms.js +23 -0
- package/expo-plugin/withQafkaCmsAttestation.js +27 -0
- package/expo-plugin/withQafkaCmsPush.js +53 -0
- package/ios/QafkaCmsAttestation.m +25 -0
- package/ios/QafkaCmsAttestation.swift +128 -0
- package/ios/QafkaCmsPush.m +22 -0
- package/ios/QafkaCmsPush.swift +143 -0
- package/ios/QafkaCmsReactImports.h +2 -0
- package/ios/QafkaCmsStorage.m +26 -0
- package/ios/QafkaCmsStorage.swift +118 -0
- package/package.json +42 -4
- package/qafkacms.config.d.ts +9 -0
- package/qafkacms.config.js +13 -0
- package/react-native-qafkacms.podspec +20 -0
- package/react-native.config.js +17 -0
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,2373 @@
|
|
|
1
|
+
import { ReactNode } from 'react';
|
|
2
|
+
|
|
3
|
+
/** SDK version — surfaced in the `x-sdk-version` request header. */
|
|
4
|
+
declare const SDK_VERSION = "0.0.0";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Platform abstractions (QFK2-E73 §4). Everything the platform-neutral core
|
|
8
|
+
* (transport, auth, content, cache, config-sync, i18n) needs from its host is
|
|
9
|
+
* injected through these types, so the core never touches `react-native`,
|
|
10
|
+
* `__DEV__`, `XMLHttpRequest` or `process`. The React Native client wires the
|
|
11
|
+
* native implementations; a web / Node client wires browser or server ones.
|
|
12
|
+
*/
|
|
13
|
+
/** Minimal `fetch` the transport calls. `signal` and extra init fields are passed through untouched. */
|
|
14
|
+
type FetchLike = (url: string, init: {
|
|
15
|
+
method: string;
|
|
16
|
+
headers: Record<string, string>;
|
|
17
|
+
body?: string;
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
}) => Promise<Response>;
|
|
20
|
+
/** Async key-value store; structurally identical to the RN SDK's secure `QafkaCmsStorage`. */
|
|
21
|
+
interface KeyValueStorage {
|
|
22
|
+
getItem(key: string): Promise<string | null>;
|
|
23
|
+
setItem(key: string, value: string): Promise<void>;
|
|
24
|
+
removeItem(key: string): Promise<void>;
|
|
25
|
+
multiRemove(keys: string[]): Promise<void>;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* App foreground/background signal (E56). Injected so ConfigSyncClient stays
|
|
29
|
+
* RN-agnostic and unit-testable; the SDK wires the real React Native `AppState`.
|
|
30
|
+
*/
|
|
31
|
+
interface AppStateProvider {
|
|
32
|
+
isActive(): boolean;
|
|
33
|
+
subscribe(listener: (active: boolean) => void): () => void;
|
|
34
|
+
}
|
|
35
|
+
interface SseHandlers {
|
|
36
|
+
/**
|
|
37
|
+
* One parsed `data:` payload (JSON). Untyped on purpose (QFK2-E76 D7): one
|
|
38
|
+
* transport serves config version bumps and content change signals; each
|
|
39
|
+
* consumer validates the shape it expects and ignores the rest.
|
|
40
|
+
*/
|
|
41
|
+
onMessage: (event: unknown) => void;
|
|
42
|
+
onError: (err: unknown) => void;
|
|
43
|
+
onOpen?: () => void;
|
|
44
|
+
/**
|
|
45
|
+
* Stream ended cleanly (e.g. server revalidation closed it) — not an error;
|
|
46
|
+
* reconnect. `reason: 'recycle'` = the transport closed it itself to bound
|
|
47
|
+
* its buffer on a long stream: reconnect at once, not an "immediate close".
|
|
48
|
+
*/
|
|
49
|
+
onClose?: (info?: {
|
|
50
|
+
reason?: 'recycle';
|
|
51
|
+
}) => void;
|
|
52
|
+
}
|
|
53
|
+
interface SseConnection {
|
|
54
|
+
close(): void;
|
|
55
|
+
}
|
|
56
|
+
type ConnectSse = (url: string, headers: Record<string, string>, handlers: SseHandlers) => SseConnection;
|
|
57
|
+
/** What the transport tells a {@link ProofProvider} about the request it is building. */
|
|
58
|
+
interface ProofContext {
|
|
59
|
+
/** The request carries an end-user `Authorization: Bearer`. */
|
|
60
|
+
authenticated: boolean;
|
|
61
|
+
/**
|
|
62
|
+
* Include `X-Project-Key`. The transport sets it only on requests without a
|
|
63
|
+
* Bearer (E63 decision 14); `getRequestHeaders()` always sets it (the caller
|
|
64
|
+
* decides about Authorization).
|
|
65
|
+
*/
|
|
66
|
+
withProjectKey: boolean;
|
|
67
|
+
/** Per-request project slug override. */
|
|
68
|
+
projectSlug?: string;
|
|
69
|
+
/** HTTP method / end-user path (e.g. `POST` `/auth/register`); absent for non-request uses (SSE headers). */
|
|
70
|
+
method?: string;
|
|
71
|
+
path?: string;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Supplies the project-identity + client-proof headers of every request and
|
|
75
|
+
* recovers from a lapsed proof.
|
|
76
|
+
*
|
|
77
|
+
* RN: `AttestationProof` (device attestation session / dev key). Web:
|
|
78
|
+
* `PublishableKeyProof` (`X-Project-Key`, optional captcha). Node (later):
|
|
79
|
+
* a service-token proof.
|
|
80
|
+
*/
|
|
81
|
+
interface ProofProvider {
|
|
82
|
+
/** Project + proof headers for one request. */
|
|
83
|
+
headers(ctx: ProofContext): Promise<Record<string, string>>;
|
|
84
|
+
/**
|
|
85
|
+
* The backend demanded a new proof (429 `X-Token-Refresh-Required` or 401
|
|
86
|
+
* `ATTESTATION_SESSION_EXPIRED`), or the proof budget runs low. Returns the
|
|
87
|
+
* headers to overlay on the single retry, or `null` = no retry. Absent = the
|
|
88
|
+
* proof cannot be refreshed (no retry, no proactive refresh).
|
|
89
|
+
*/
|
|
90
|
+
refresh?(): Promise<Record<string, string> | null>;
|
|
91
|
+
/** First proof (RN: attestation). Run by the client's `initialize()`; must be safe to call repeatedly. */
|
|
92
|
+
initialize?(): Promise<void>;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* HTTP transport for the end-user API. Composes the three QafkaCMS trust axes
|
|
97
|
+
* onto every request and handles attestation session-token refresh.
|
|
98
|
+
*
|
|
99
|
+
* Trust axes (K1 in the spec):
|
|
100
|
+
* - `Authorization: Bearer <accessToken>` — end-user identity (E7 JWT)
|
|
101
|
+
* - `X-Session-Token: <sessionToken>` — device trust (E22 attestation)
|
|
102
|
+
* - `X-Project-Key: <qpk_…>` — publishable key (sent when no Bearer token)
|
|
103
|
+
* - `X-Project-Id: <uuid>` — project id (mobile; sent on every request)
|
|
104
|
+
* - `x-api-key: <test key>` — dev-bypass only
|
|
105
|
+
* - `X-Project-Slug: <slug>` — optional project label
|
|
106
|
+
*
|
|
107
|
+
* The project/proof headers (everything but the Bearer) come from a
|
|
108
|
+
* {@link ProofProvider} (QFK2-E73): `AttestationProof` on React Native,
|
|
109
|
+
* `PublishableKeyProof` on the web. Without an explicit `proof`, the legacy
|
|
110
|
+
* `getSessionToken` / `onRefreshRequired` / `getDevApiKey` deps are adapted
|
|
111
|
+
* into an `AttestationProof`.
|
|
112
|
+
*
|
|
113
|
+
* Refresh choreography is copied from Qafka's BackendService: a 429 with
|
|
114
|
+
* `X-Token-Refresh-Required` (or a 401 `ATTESTATION_SESSION_EXPIRED`) triggers
|
|
115
|
+
* a reactive `proof.refresh()` + single retry, while a low
|
|
116
|
+
* `X-Token-Budget-Remaining` triggers a proactive fire-and-forget refresh.
|
|
117
|
+
*/
|
|
118
|
+
type HttpMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';
|
|
119
|
+
interface HttpClientConfig {
|
|
120
|
+
apiUrl: string;
|
|
121
|
+
projectSlug?: string;
|
|
122
|
+
/** Project publishable key (`qpk_…`) — sent as `X-Project-Key` on requests without a Bearer token. */
|
|
123
|
+
publishableKey?: string;
|
|
124
|
+
/** Project id (UUID) — sent as `X-Project-Id` on every request. */
|
|
125
|
+
projectId?: string;
|
|
126
|
+
sdkVersion?: string;
|
|
127
|
+
/**
|
|
128
|
+
* Sent as `x-platform` (`ios` / `android` / `web` / `node`). The transport
|
|
129
|
+
* never asks the runtime: every client passes it (core: `PlatformAdapter.os`);
|
|
130
|
+
* when absent the header is omitted.
|
|
131
|
+
*/
|
|
132
|
+
platformOS?: string;
|
|
133
|
+
/**
|
|
134
|
+
* The app's version (QFK2-E59 V9), sent as `X-App-Version` on every request
|
|
135
|
+
* when it is a valid app version (`parseAppVersion`); otherwise omitted.
|
|
136
|
+
*/
|
|
137
|
+
appVersion?: string | null;
|
|
138
|
+
}
|
|
139
|
+
interface HttpClientDeps {
|
|
140
|
+
fetch: FetchLike;
|
|
141
|
+
/**
|
|
142
|
+
* Project + proof headers and proof refresh. When set, the legacy
|
|
143
|
+
* `getSessionToken` / `onRefreshRequired` / `getDevApiKey` deps (and the
|
|
144
|
+
* config's `projectId` / `publishableKey` / `projectSlug`) are not used for
|
|
145
|
+
* headers — the provider owns them.
|
|
146
|
+
*/
|
|
147
|
+
proof?: ProofProvider;
|
|
148
|
+
/** End-user access token (the getter may refresh it internally). */
|
|
149
|
+
getAccessToken?: () => Promise<string | null>;
|
|
150
|
+
/** Attestation session token. */
|
|
151
|
+
getSessionToken?: () => Promise<string | null>;
|
|
152
|
+
/** Force an attestation refresh; returns the new session token (or null). */
|
|
153
|
+
onRefreshRequired?: () => Promise<string | null>;
|
|
154
|
+
/** Active UI locale → sent as `Accept-Language` on every request (E55). */
|
|
155
|
+
getLocale?: () => string | null;
|
|
156
|
+
/** Dev-bypass API key → sent as `x-api-key` when non-null (never in release). */
|
|
157
|
+
getDevApiKey?: () => string | null;
|
|
158
|
+
/** Code-lookup unlock tokens → sent as `X-Unlock-Token` (comma-separated) when non-empty. */
|
|
159
|
+
getUnlockTokens?: () => string[];
|
|
160
|
+
}
|
|
161
|
+
interface RequestOptions {
|
|
162
|
+
body?: unknown;
|
|
163
|
+
query?: Record<string, string | number | boolean | undefined | null>;
|
|
164
|
+
/** Override the configured project slug for this request. */
|
|
165
|
+
projectSlug?: string;
|
|
166
|
+
/** Skip the Authorization header even if an access token exists. */
|
|
167
|
+
anonymous?: boolean;
|
|
168
|
+
/** Send `X-Unlock-Token` (content + lookup requests only; set by ContentClient). */
|
|
169
|
+
withUnlockTokens?: boolean;
|
|
170
|
+
}
|
|
171
|
+
/** Options of {@link HttpClient.requestConditional} (QFK2-E59 D3). */
|
|
172
|
+
interface ConditionalRequestOptions extends RequestOptions {
|
|
173
|
+
/** ETag of the copy the caller holds → `If-None-Match`; sent only when a non-empty string. */
|
|
174
|
+
ifNoneMatch?: string | null;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Result of {@link HttpClient.requestConditional}: `notModified` when the server
|
|
178
|
+
* answered 304 to our `If-None-Match`, otherwise the body and its `ETag`
|
|
179
|
+
* (`null` when absent or not exposed to the browser by CORS).
|
|
180
|
+
*/
|
|
181
|
+
type ConditionalResponse<T> = {
|
|
182
|
+
notModified: true;
|
|
183
|
+
} | {
|
|
184
|
+
notModified: false;
|
|
185
|
+
data: T;
|
|
186
|
+
etag: string | null;
|
|
187
|
+
};
|
|
188
|
+
declare class HttpClient {
|
|
189
|
+
private readonly config;
|
|
190
|
+
private readonly d;
|
|
191
|
+
private readonly proof;
|
|
192
|
+
/** The configured app version when valid (sent as `X-App-Version`), else `null`. */
|
|
193
|
+
readonly appVersion: string | null;
|
|
194
|
+
constructor(config: HttpClientConfig, deps: HttpClientDeps);
|
|
195
|
+
request<T = unknown>(method: HttpMethod, path: string, options?: RequestOptions): Promise<T>;
|
|
196
|
+
/**
|
|
197
|
+
* {@link request} with HTTP conditional-GET support (QFK2-E59 D3). Sends
|
|
198
|
+
* `If-None-Match` only when `options.ifNoneMatch` is a non-empty string; a
|
|
199
|
+
* 304 counts as "not modified" only then. A 304 to a request without it is
|
|
200
|
+
* an error, exactly as in {@link request}. Same headers, refresh and retry.
|
|
201
|
+
*/
|
|
202
|
+
requestConditional<T = unknown>(method: HttpMethod, path: string, options?: ConditionalRequestOptions): Promise<ConditionalResponse<T>>;
|
|
203
|
+
/** Build the URL + headers, send through the refresh path; status handling is the caller's. */
|
|
204
|
+
private send;
|
|
205
|
+
/**
|
|
206
|
+
* Exposed for clients that need the resolved security headers (e.g. SSE).
|
|
207
|
+
* `target` (method + end-user path) lets the proof provider scope
|
|
208
|
+
* request-specific headers (e.g. a captcha token on auth POSTs).
|
|
209
|
+
*/
|
|
210
|
+
securityHeaders(options?: RequestOptions, target?: {
|
|
211
|
+
method: string;
|
|
212
|
+
path: string;
|
|
213
|
+
}): Promise<Record<string, string>>;
|
|
214
|
+
/**
|
|
215
|
+
* Project + proof headers: `X-Project-Id`, `X-Project-Key` (when
|
|
216
|
+
* `withProjectKey`), `X-Project-Slug`, and `X-Session-Token` (release) or
|
|
217
|
+
* `x-api-key` (dev-bypass). {@link securityHeaders} sends the key only on
|
|
218
|
+
* requests without a Bearer; `getRequestHeaders()` (no Authorization, the
|
|
219
|
+
* caller decides) always does.
|
|
220
|
+
*/
|
|
221
|
+
projectProofHeaders(options: {
|
|
222
|
+
withProjectKey: boolean;
|
|
223
|
+
projectSlug?: string;
|
|
224
|
+
}): Promise<Record<string, string>>;
|
|
225
|
+
/** The proof provider (for `initialize()` / own-client header helpers). */
|
|
226
|
+
getProof(): ProofProvider;
|
|
227
|
+
private fetchWithRefresh;
|
|
228
|
+
private buildUrl;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** The SDK's storage surface — the platform-neutral {@link KeyValueStorage} under its RN-era name. */
|
|
232
|
+
interface QafkaCmsStorage extends KeyValueStorage {
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Holds the end-user session. The short-lived access token lives in memory
|
|
237
|
+
* only; the long-lived refresh token is persisted in secure storage so the
|
|
238
|
+
* session survives app restarts.
|
|
239
|
+
*
|
|
240
|
+
* Observable: `subscribe` is notified on every change (login / refresh / logout
|
|
241
|
+
* / hydrate) and `getVersion` bumps with each, so derived state (e.g. the
|
|
242
|
+
* `useAuth` snapshot) can be memoized without recomputing on every read.
|
|
243
|
+
*/
|
|
244
|
+
declare class TokenStore {
|
|
245
|
+
private readonly storage;
|
|
246
|
+
private readonly now;
|
|
247
|
+
private accessToken;
|
|
248
|
+
private accessExpiresAt;
|
|
249
|
+
private refreshToken;
|
|
250
|
+
private version;
|
|
251
|
+
private readonly listeners;
|
|
252
|
+
/**
|
|
253
|
+
* QFK2-E73 — how long a `REFRESH_TOKEN_ROTATED` answer waits for another
|
|
254
|
+
* tab's successor token (storage write or a cross-tab sync `adopt`) before
|
|
255
|
+
* the single retry.
|
|
256
|
+
*/
|
|
257
|
+
rotationWaitMs: number;
|
|
258
|
+
constructor(storage: Pick<QafkaCmsStorage, 'getItem' | 'setItem' | 'removeItem'>, now?: () => number);
|
|
259
|
+
/** Load the persisted refresh token (call once at SDK init). */
|
|
260
|
+
hydrate(): Promise<void>;
|
|
261
|
+
setTokens(tokens: {
|
|
262
|
+
accessToken: string;
|
|
263
|
+
refreshToken: string;
|
|
264
|
+
expiresIn: number;
|
|
265
|
+
}): Promise<void>;
|
|
266
|
+
/** External session: access token only. Drops any CMS refresh token (memory + storage); one notification. */
|
|
267
|
+
setExternalAccess(accessToken: string, expiresIn: number): Promise<void>;
|
|
268
|
+
/**
|
|
269
|
+
* QFK2-E73 — re-read the persisted refresh token (another tab/process may
|
|
270
|
+
* have rotated it in shared storage). Emits only when it changed.
|
|
271
|
+
*/
|
|
272
|
+
reload(): Promise<void>;
|
|
273
|
+
/**
|
|
274
|
+
* QFK2-E73 — take over a session state pushed by another tab (web
|
|
275
|
+
* BroadcastChannel sync): `null` = signed out there. Persists the refresh
|
|
276
|
+
* token like {@link setTokens}; one notification.
|
|
277
|
+
*/
|
|
278
|
+
adopt(state: {
|
|
279
|
+
accessToken: string | null;
|
|
280
|
+
accessExpiresAt: number;
|
|
281
|
+
refreshToken: string | null;
|
|
282
|
+
} | null): Promise<void>;
|
|
283
|
+
/**
|
|
284
|
+
* QFK2-E73 — resolve once the session moved past `staleRefreshToken`: the
|
|
285
|
+
* stored token changed (re-read first), or a valid access token arrived
|
|
286
|
+
* (another tab's sync), or the session ended. Gives up after
|
|
287
|
+
* {@link rotationWaitMs} (re-reading storage once more).
|
|
288
|
+
*/
|
|
289
|
+
waitForRotation(staleRefreshToken: string): Promise<void>;
|
|
290
|
+
setAccessToken(accessToken: string, expiresIn: number): void;
|
|
291
|
+
private applyAccess;
|
|
292
|
+
getAccessToken(): string | null;
|
|
293
|
+
/** Epoch ms when the access token expires (0 = none). */
|
|
294
|
+
getAccessExpiresAt(): number;
|
|
295
|
+
isAccessValid(marginMs?: number): boolean;
|
|
296
|
+
getRefreshToken(): string | null;
|
|
297
|
+
clear(): Promise<void>;
|
|
298
|
+
/** Observe auth-state changes. Returns an unsubscribe function. */
|
|
299
|
+
subscribe(listener: () => void): () => void;
|
|
300
|
+
/** Monotonic change counter — bumps on every mutation. */
|
|
301
|
+
getVersion(): number;
|
|
302
|
+
private emit;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* End-user access-token claims minted by the QafkaCMS backend (`jwt.ts`).
|
|
307
|
+
* Decoded client-side so the SDK can resolve the project without an extra round
|
|
308
|
+
* trip. The signature is NOT verified here — that is the backend's job; the SDK
|
|
309
|
+
* only reads claims it already trusts the transport to have authenticated.
|
|
310
|
+
*/
|
|
311
|
+
interface AccessTokenClaims {
|
|
312
|
+
sub: string;
|
|
313
|
+
projectId?: string;
|
|
314
|
+
schema?: string;
|
|
315
|
+
/**
|
|
316
|
+
* E54 — consumer-tier role ids the end-user holds (premium/special). Lets the
|
|
317
|
+
* app branch UI on tier (e.g. unlock premium screens); access itself is always
|
|
318
|
+
* enforced server-side. Absent on tokens minted before tiers existed.
|
|
319
|
+
*/
|
|
320
|
+
roles?: string[];
|
|
321
|
+
/**
|
|
322
|
+
* QFK2-T322 — `true` only on tokens of an anonymous end-user. Absent on
|
|
323
|
+
* registered (and older) tokens.
|
|
324
|
+
*/
|
|
325
|
+
anon?: boolean;
|
|
326
|
+
iat?: number;
|
|
327
|
+
exp?: number;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** Auth contracts — mirror `apps/qafkacms-api/src/end-user-auth`. */
|
|
331
|
+
type AuthMethod = 'email' | 'magic_link';
|
|
332
|
+
/**
|
|
333
|
+
* What `EndUser.authMethod` can hold: `oidc` = created through an external
|
|
334
|
+
* identity (E44); `anonymous` = an anonymous end-user (QFK2-T322) that has not
|
|
335
|
+
* been upgraded yet.
|
|
336
|
+
*/
|
|
337
|
+
type EndUserAuthMethod = AuthMethod | 'oidc' | 'anonymous';
|
|
338
|
+
interface RegisterInput {
|
|
339
|
+
email: string;
|
|
340
|
+
password?: string;
|
|
341
|
+
phone?: string;
|
|
342
|
+
method: AuthMethod;
|
|
343
|
+
}
|
|
344
|
+
interface EndUser {
|
|
345
|
+
id: string;
|
|
346
|
+
/** `null` for a member created through an external identity (E44). */
|
|
347
|
+
email: string | null;
|
|
348
|
+
phone: string | null;
|
|
349
|
+
authMethod: EndUserAuthMethod;
|
|
350
|
+
isActive: boolean;
|
|
351
|
+
emailVerifiedAt: string | null;
|
|
352
|
+
/** Provider keys linked to this member. Only `auth.me()` fills it. */
|
|
353
|
+
linkedProviders?: string[];
|
|
354
|
+
}
|
|
355
|
+
interface LoginInput {
|
|
356
|
+
email: string;
|
|
357
|
+
password: string;
|
|
358
|
+
}
|
|
359
|
+
/** `POST /login` and magic-link callback both yield this token triple. */
|
|
360
|
+
interface AuthTokens {
|
|
361
|
+
accessToken: string;
|
|
362
|
+
refreshToken: string;
|
|
363
|
+
expiresIn: number;
|
|
364
|
+
}
|
|
365
|
+
/** `POST /refresh` rotates only the access token. */
|
|
366
|
+
interface RefreshResult {
|
|
367
|
+
accessToken: string;
|
|
368
|
+
expiresIn: number;
|
|
369
|
+
}
|
|
370
|
+
/** Reactive snapshot of the end-user session, surfaced by `useAuth`. */
|
|
371
|
+
interface AuthState {
|
|
372
|
+
isAuthenticated: boolean;
|
|
373
|
+
/** `sub` claim of the current access token, or null (anonymous / undecodable). */
|
|
374
|
+
userId: string | null;
|
|
375
|
+
/** E54 consumer-tier role ids; empty when anonymous or untiered. */
|
|
376
|
+
roles: string[];
|
|
377
|
+
/**
|
|
378
|
+
* QFK2-T322 — true when the session belongs to an anonymous end-user (the
|
|
379
|
+
* access token carries `anon: true`). False when signed out, registered, or
|
|
380
|
+
* the access token is not loaded yet.
|
|
381
|
+
*/
|
|
382
|
+
isAnonymous: boolean;
|
|
383
|
+
}
|
|
384
|
+
/** Result of `auth.signInWithExternalToken` (E44). */
|
|
385
|
+
interface ExternalSignInResult {
|
|
386
|
+
endUser: EndUser;
|
|
387
|
+
/** True when the member was created by this sign-in. */
|
|
388
|
+
created: boolean;
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Result of `auth.methods()` (`GET /auth/methods`): which sign-in options the
|
|
392
|
+
* app should show. Only booleans and provider labels; no provider internals.
|
|
393
|
+
*/
|
|
394
|
+
interface AuthMethods {
|
|
395
|
+
/** E-mail + password sign-in. */
|
|
396
|
+
email: boolean;
|
|
397
|
+
/** Self-service registration. */
|
|
398
|
+
registration: boolean;
|
|
399
|
+
/** Magic-link sign-in (needs the project's magic-link redirect URL). */
|
|
400
|
+
magicLink: boolean;
|
|
401
|
+
/** Password-reset e-mail flow. */
|
|
402
|
+
passwordReset: boolean;
|
|
403
|
+
/** Anonymous (guest) accounts. */
|
|
404
|
+
anonymous: boolean;
|
|
405
|
+
/** Enabled external providers, to pass as `{ provider: key }`. */
|
|
406
|
+
providers: Array<{
|
|
407
|
+
key: string;
|
|
408
|
+
displayName: string;
|
|
409
|
+
nonce: 'off' | 'optional' | 'required';
|
|
410
|
+
}>;
|
|
411
|
+
}
|
|
412
|
+
/** Client option `anonymousAuth` (QFK2-T322): `'manual'` (default) or `'auto'`. */
|
|
413
|
+
type AnonymousAuthMode = 'manual' | 'auto';
|
|
414
|
+
/** Result of `auth.signInAnonymously()` (QFK2-T322). */
|
|
415
|
+
interface AnonymousSignInResult {
|
|
416
|
+
/** `sub` of the current access token (null when the session's access token is not loaded yet). */
|
|
417
|
+
userId: string | null;
|
|
418
|
+
/** True when the current session is anonymous. */
|
|
419
|
+
isAnonymous: boolean;
|
|
420
|
+
/** True when this call created a new anonymous end-user; false when an existing session was kept. */
|
|
421
|
+
created: boolean;
|
|
422
|
+
/** The new end-user record; `null` when an existing session was kept. */
|
|
423
|
+
endUser: EndUser | null;
|
|
424
|
+
}
|
|
425
|
+
/** `auth.upgrade` input (QFK2-T322): turns the anonymous end-user into an account, keeping its id. */
|
|
426
|
+
type UpgradeInput = {
|
|
427
|
+
method: 'email';
|
|
428
|
+
email: string;
|
|
429
|
+
password: string;
|
|
430
|
+
} | {
|
|
431
|
+
method: 'magic_link';
|
|
432
|
+
email: string;
|
|
433
|
+
} | {
|
|
434
|
+
method: 'external';
|
|
435
|
+
token: string;
|
|
436
|
+
provider?: string;
|
|
437
|
+
nonce?: string;
|
|
438
|
+
};
|
|
439
|
+
/**
|
|
440
|
+
* `auth.upgrade` result for the `email` and `external` methods.
|
|
441
|
+
*
|
|
442
|
+
* Two shapes, told apart by `signedIn`:
|
|
443
|
+
* - `signedIn: true` — the server issued tokens; they are the stored session now.
|
|
444
|
+
* - `signedIn: false` — email method in a project that requires e-mail
|
|
445
|
+
* verification: the account was upgraded in place (same id) but the server
|
|
446
|
+
* revoked the anonymous sessions and issued none. The SDK cleared the local
|
|
447
|
+
* session (signed out); the user verifies the e-mail, then calls `login`.
|
|
448
|
+
* `verificationRequired` is `true`, `accessToken` is `''`, `expiresIn` is `0`
|
|
449
|
+
* and `refreshToken` is absent.
|
|
450
|
+
*/
|
|
451
|
+
interface UpgradeResult {
|
|
452
|
+
/** `''` when `signedIn` is false. */
|
|
453
|
+
accessToken: string;
|
|
454
|
+
/** Absent for an external provider with `sessionMode: 'external'` (the session then renews via `externalTokenProvider`), and when `signedIn` is false. */
|
|
455
|
+
refreshToken?: string;
|
|
456
|
+
/** `0` when `signedIn` is false. */
|
|
457
|
+
expiresIn: number;
|
|
458
|
+
endUser: EndUser;
|
|
459
|
+
/** True when the e-mail still has to be verified (email method). */
|
|
460
|
+
verificationRequired?: boolean;
|
|
461
|
+
/** Whether a session was stored. Always set by `auth.upgrade()`; optional only for type compatibility. */
|
|
462
|
+
signedIn?: boolean;
|
|
463
|
+
}
|
|
464
|
+
/** Outcome of a magic-link upgrade, read from the confirm redirect (`upgrade=upgraded|switched`). */
|
|
465
|
+
type UpgradeOutcome = 'upgraded' | 'switched';
|
|
466
|
+
|
|
467
|
+
/** Options for external-identity sign-in (E44). */
|
|
468
|
+
interface AuthClientOptions {
|
|
469
|
+
/**
|
|
470
|
+
* Returns a fresh token from the host app's own identity provider, or `null`
|
|
471
|
+
* when that session is over. Called when the CMS access token expires and
|
|
472
|
+
* after an app restart.
|
|
473
|
+
*/
|
|
474
|
+
externalTokenProvider?: () => Promise<string | null>;
|
|
475
|
+
/** Where the external-session marker is persisted (secure storage). */
|
|
476
|
+
storage?: Pick<QafkaCmsStorage, 'getItem' | 'setItem' | 'removeItem'>;
|
|
477
|
+
/**
|
|
478
|
+
* Default external provider key (`authConfig.externalProviders[].key`) used by
|
|
479
|
+
* `signInWithExternalToken` / `linkExternal` / re-exchange when no per-call
|
|
480
|
+
* `provider` is given.
|
|
481
|
+
*/
|
|
482
|
+
externalProvider?: string;
|
|
483
|
+
/**
|
|
484
|
+
* QFK2-T322 — `'auto'` re-creates an anonymous end-user lazily after
|
|
485
|
+
* `logout()` / `deleteAccount()`: the next call that needs an access token
|
|
486
|
+
* (any SDK request, `getValidAccessToken()`) runs `signInAnonymously()`.
|
|
487
|
+
* The boot-time creation is done by `QafkaCmsClient.initialize()`. Default
|
|
488
|
+
* `'manual'`: the SDK never creates one on its own.
|
|
489
|
+
*/
|
|
490
|
+
anonymousAuth?: AnonymousAuthMode;
|
|
491
|
+
}
|
|
492
|
+
/**
|
|
493
|
+
* End-user authentication against `/v1/end-user/auth/*`. All calls are
|
|
494
|
+
* `anonymous` (no `Authorization` header) — identity is established by the
|
|
495
|
+
* payload, not by an existing session. The resulting tokens flow into the
|
|
496
|
+
* shared `TokenStore`, which the transport reads via `getValidAccessToken`.
|
|
497
|
+
*/
|
|
498
|
+
declare class AuthClient {
|
|
499
|
+
private readonly http;
|
|
500
|
+
private readonly store;
|
|
501
|
+
private readonly now;
|
|
502
|
+
private readonly options;
|
|
503
|
+
/** Shared in-flight refresh, so concurrent requests trigger a single `/refresh`. */
|
|
504
|
+
private refreshing;
|
|
505
|
+
private authStateCache;
|
|
506
|
+
private authStateVersion;
|
|
507
|
+
/** Shared in-flight anonymous sign-in (QFK2-T322). */
|
|
508
|
+
private anonymousSigningIn;
|
|
509
|
+
/** `anonymousAuth: 'auto'`: create an anonymous user on the next token need (set by logout/deleteAccount). */
|
|
510
|
+
private autoAnonymousArmed;
|
|
511
|
+
private lastUpgradeOutcome;
|
|
512
|
+
/** Mirror of the persisted anonymous-session marker; null = not read/written yet. */
|
|
513
|
+
private anonymousMarker;
|
|
514
|
+
constructor(http: HttpClient, store: TokenStore, now?: () => number, options?: AuthClientOptions);
|
|
515
|
+
register(input: RegisterInput): Promise<EndUser>;
|
|
516
|
+
login(input: LoginInput): Promise<AuthTokens>;
|
|
517
|
+
/**
|
|
518
|
+
* Sign in with a token from the customer's own identity provider (E44).
|
|
519
|
+
* For a `sessionMode: 'external'` provider the CMS issues an access token
|
|
520
|
+
* only; it is renewed through `externalTokenProvider`. For `'cms'` providers
|
|
521
|
+
* the response carries a refresh token and the session behaves exactly like
|
|
522
|
+
* a normal login (E72). `opts.provider` selects the provider by key.
|
|
523
|
+
*
|
|
524
|
+
* `opts.nonce` is the RAW nonce. Generate a random raw nonce, pass
|
|
525
|
+
* `sha256(raw)` (hex) to BOTH Apple's and Google's request and the **raw**
|
|
526
|
+
* value here (a token whose nonce claim equals the raw value is rejected).
|
|
527
|
+
* The provider must have `nonce`
|
|
528
|
+
* set to `optional` or `required`; `required` is meant for `cms` session mode
|
|
529
|
+
* (silent re-exchange through `externalTokenProvider` carries no nonce).
|
|
530
|
+
*/
|
|
531
|
+
signInWithExternalToken(token: string, opts?: {
|
|
532
|
+
provider?: string;
|
|
533
|
+
nonce?: string;
|
|
534
|
+
}): Promise<ExternalSignInResult>;
|
|
535
|
+
/** The signed-in member as the server sees it (Bearer session); `linkedProviders` is filled here. */
|
|
536
|
+
me(): Promise<EndUser>;
|
|
537
|
+
/** Attach an external identity to the signed-in member. `opts.nonce`: raw nonce; give the provider sha256(raw), see `signInWithExternalToken`. */
|
|
538
|
+
linkExternal(token: string, opts?: {
|
|
539
|
+
provider?: string;
|
|
540
|
+
nonce?: string;
|
|
541
|
+
}): Promise<{
|
|
542
|
+
endUser: EndUser;
|
|
543
|
+
}>;
|
|
544
|
+
/** Detach external identities from the signed-in member (all, or only `opts.provider`). */
|
|
545
|
+
unlinkExternal(opts?: {
|
|
546
|
+
provider?: string;
|
|
547
|
+
}): Promise<{
|
|
548
|
+
endUser: EndUser;
|
|
549
|
+
}>;
|
|
550
|
+
/**
|
|
551
|
+
* QFK2-T322 — sign in as a new anonymous end-user (`POST /auth/anonymous`,
|
|
552
|
+
* attestation proof required). Idempotent: when a session already exists
|
|
553
|
+
* (anonymous, registered or external) it returns the current identity
|
|
554
|
+
* without a request. Concurrent calls share one request.
|
|
555
|
+
*/
|
|
556
|
+
signInAnonymously(): Promise<AnonymousSignInResult>;
|
|
557
|
+
private runSignInAnonymously;
|
|
558
|
+
/** QFK2-T322 — true when the current access token carries `anon: true`. */
|
|
559
|
+
isAnonymous(): boolean;
|
|
560
|
+
/**
|
|
561
|
+
* QFK2-T322 — turn the signed-in anonymous end-user into an account, keeping
|
|
562
|
+
* its id (`POST /auth/upgrade`, Bearer = the anonymous access token).
|
|
563
|
+
* `email` and `external` replace the session with the returned tokens
|
|
564
|
+
* (`signedIn: true`); an email upgrade that needs verification comes back
|
|
565
|
+
* without tokens (`signedIn: false`) and leaves the client signed out;
|
|
566
|
+
* `magic_link` only sends the e-mail (finish with `handleMagicLinkCallback`,
|
|
567
|
+
* then read `getLastUpgradeOutcome()`). Conflicts are `ProblemError`s
|
|
568
|
+
* (`raw.code`: `ACCOUNT_EXISTS_SIGN_IN_REQUIRED`, `ACCOUNT_EXISTS_LINK_REQUIRED`,
|
|
569
|
+
* `IDENTITY_IN_USE`, `NOT_ANONYMOUS`); the anonymous session is kept then.
|
|
570
|
+
*/
|
|
571
|
+
upgrade(input: Extract<UpgradeInput, {
|
|
572
|
+
method: 'magic_link';
|
|
573
|
+
}>): Promise<{
|
|
574
|
+
ok: boolean;
|
|
575
|
+
}>;
|
|
576
|
+
upgrade(input: Extract<UpgradeInput, {
|
|
577
|
+
method: 'email' | 'external';
|
|
578
|
+
}>): Promise<UpgradeResult>;
|
|
579
|
+
upgrade(input: UpgradeInput): Promise<UpgradeResult | {
|
|
580
|
+
ok: boolean;
|
|
581
|
+
}>;
|
|
582
|
+
/** QFK2-T322 — outcome of the last magic-link callback that carried `upgrade=`; null otherwise. */
|
|
583
|
+
getLastUpgradeOutcome(): UpgradeOutcome | null;
|
|
584
|
+
/**
|
|
585
|
+
* QFK2-T322 — delete the signed-in end-user's account (`DELETE /auth/me`,
|
|
586
|
+
* anonymous or registered) and clear the local session. On an error the
|
|
587
|
+
* session is kept and the `ProblemError` is thrown.
|
|
588
|
+
*/
|
|
589
|
+
deleteAccount(): Promise<void>;
|
|
590
|
+
/** Which sign-in options the project offers (`GET /auth/methods`, anonymous; cache-friendly). */
|
|
591
|
+
methods(): Promise<AuthMethods>;
|
|
592
|
+
/** Request a password-reset e-mail. Always resolves `{ ok: true }` for existing/unknown addresses alike. */
|
|
593
|
+
requestPasswordReset(email: string): Promise<{
|
|
594
|
+
ok: boolean;
|
|
595
|
+
}>;
|
|
596
|
+
/** Set a new password with the token from the reset e-mail. Does not sign in. */
|
|
597
|
+
confirmPasswordReset(token: string, newPassword: string): Promise<{
|
|
598
|
+
ok: boolean;
|
|
599
|
+
}>;
|
|
600
|
+
private exchange;
|
|
601
|
+
/** Persist an exchange result: cms mode (refresh token) = normal login, else external session. */
|
|
602
|
+
private applyExchange;
|
|
603
|
+
private applySession;
|
|
604
|
+
/** Keep the persisted anonymous-session marker in line with the session (writes only on change). */
|
|
605
|
+
private syncAnonymousMarker;
|
|
606
|
+
/** Whether the stored session is anonymous: the token claim, else (cold start) the persisted marker. */
|
|
607
|
+
private storedSessionIsAnonymous;
|
|
608
|
+
private hasExternalSession;
|
|
609
|
+
private clearExternalMarker;
|
|
610
|
+
/** Re-exchange through the host's provider. Null = no session (and it is ended when the provider says so). */
|
|
611
|
+
private runExternalReExchange;
|
|
612
|
+
/**
|
|
613
|
+
* Returns a valid access token, refreshing transparently when it is near
|
|
614
|
+
* expiry. Returns null when there is no session (anonymous). This is the
|
|
615
|
+
* function wired into `HttpClient.getAccessToken`.
|
|
616
|
+
*/
|
|
617
|
+
getValidAccessToken(): Promise<string | null>;
|
|
618
|
+
/** `anonymousAuth: 'auto'` lazy creation; a failure disarms it until the next logout. */
|
|
619
|
+
private autoSignInAnonymously;
|
|
620
|
+
/**
|
|
621
|
+
* Local session end (no server call), shared by logout, deleteAccount, a lost
|
|
622
|
+
* anonymous identity and a verification-pending upgrade. `rearmAuto`: in
|
|
623
|
+
* `anonymousAuth: 'auto'` the next token need creates a new anonymous user.
|
|
624
|
+
*/
|
|
625
|
+
private endLocalSession;
|
|
626
|
+
/** Rotate the access token. De-duplicated: concurrent callers share one `/refresh`. */
|
|
627
|
+
refresh(): Promise<string | null>;
|
|
628
|
+
private runRefresh;
|
|
629
|
+
logout(): Promise<void>;
|
|
630
|
+
requestMagicLink(email: string): Promise<{
|
|
631
|
+
ok: boolean;
|
|
632
|
+
}>;
|
|
633
|
+
/**
|
|
634
|
+
* Ask the backend to (re)send the account's verification e-mail. Only sends
|
|
635
|
+
* when the project enabled verification e-mails; always resolves `{ ok: true }`
|
|
636
|
+
* (no account enumeration).
|
|
637
|
+
*/
|
|
638
|
+
requestEmailVerification(email: string): Promise<{
|
|
639
|
+
ok: boolean;
|
|
640
|
+
}>;
|
|
641
|
+
/**
|
|
642
|
+
* Parse the deep-link the backend redirects to after a magic-link confirm
|
|
643
|
+
* (`…#access_token=&refresh_token=&expires_in=`), store the tokens, and
|
|
644
|
+
* return them. Returns null when the URL carries no token fragment. An
|
|
645
|
+
* `upgrade=upgraded|switched` parameter (anonymous upgrade, QFK2-T322) is
|
|
646
|
+
* exposed through `getLastUpgradeOutcome()`.
|
|
647
|
+
*/
|
|
648
|
+
handleMagicLinkCallback(urlOrFragment: string): Promise<AuthTokens | null>;
|
|
649
|
+
/** Every CMS-token session replaces (and so ends) an external one. */
|
|
650
|
+
private storeCmsTokens;
|
|
651
|
+
/** Decode the current access token's claims (project id, subject, …). */
|
|
652
|
+
getClaims(): AccessTokenClaims | null;
|
|
653
|
+
/**
|
|
654
|
+
* E54 — consumer-tier role ids carried by the current token (premium/special).
|
|
655
|
+
* Empty when anonymous or untiered. Use it to branch UI on tier; the backend
|
|
656
|
+
* still enforces what each tier can actually read/write.
|
|
657
|
+
*/
|
|
658
|
+
getRoles(): string[];
|
|
659
|
+
isAuthenticated(): boolean;
|
|
660
|
+
/** Subscribe to auth-state changes (login / refresh / logout). Returns unsubscribe. */
|
|
661
|
+
subscribe(listener: () => void): () => void;
|
|
662
|
+
/**
|
|
663
|
+
* Reactive session snapshot for `useAuth`. Memoized on the store's version so
|
|
664
|
+
* the reference is stable between changes (safe for `useSyncExternalStore`).
|
|
665
|
+
*/
|
|
666
|
+
getAuthState(): AuthState;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/**
|
|
670
|
+
* Filter DSL — type-only mirror of the backend's `content/filter/filter.parser`.
|
|
671
|
+
* Kept local (not imported from `@qafka/cms-shared-types`) because that package
|
|
672
|
+
* pulls in Prisma + Zod at runtime, which must never enter the RN bundle. These
|
|
673
|
+
* are compile-time types only; no runtime code is duplicated.
|
|
674
|
+
*/
|
|
675
|
+
type FilterOp = '_eq' | '_neq' | '_lt' | '_lte' | '_gt' | '_gte' | '_in' | '_nin' | '_null' | '_nnull' | '_contains' | '_icontains' | '_starts_with' | '_istarts_with';
|
|
676
|
+
type FieldOps = {
|
|
677
|
+
[op in FilterOp]?: unknown;
|
|
678
|
+
};
|
|
679
|
+
/** Quantifiers over a relation field: `_some` / `_none` take a filter on the target collection (`{}` = any visible linked target). */
|
|
680
|
+
type QuantifierOps = {
|
|
681
|
+
_some?: FilterNode;
|
|
682
|
+
_none?: FilterNode;
|
|
683
|
+
};
|
|
684
|
+
type FilterNode = {
|
|
685
|
+
_and: FilterNode[];
|
|
686
|
+
} | {
|
|
687
|
+
_or: FilterNode[];
|
|
688
|
+
} | {
|
|
689
|
+
[field: string]: FieldOps | QuantifierOps;
|
|
690
|
+
};
|
|
691
|
+
/** Dynamic var resolved server-side to the authenticated user's id. */
|
|
692
|
+
declare const CURRENT_USER = "$CURRENT_USER";
|
|
693
|
+
/** Server-time "now" (UTC). Use with `_eq/_neq/_lt/_lte/_gt/_gte` on date fields. */
|
|
694
|
+
declare const NOW = "$NOW";
|
|
695
|
+
/**
|
|
696
|
+
* Builds a `$NOW` value, optionally shifted: `now()` → `'$NOW'`, `now('+7d')` → `'$NOW(+7d)'`.
|
|
697
|
+
* Offset units: `m` minutes, `h` hours, `d` days, `w` weeks. Throws on any other shape.
|
|
698
|
+
*/
|
|
699
|
+
declare function now(offset?: string): string;
|
|
700
|
+
|
|
701
|
+
/**
|
|
702
|
+
* A content row. The shape is collection-specific; `id` is always present.
|
|
703
|
+
* `_locked: true` marks a code-locked row that is not unlocked yet (QFK2-E78):
|
|
704
|
+
* only `id` + the collection's teaser fields are present; unlock via
|
|
705
|
+
* `content.lookup`. Absent on unlocked and non-locked rows.
|
|
706
|
+
* `_title` is the server-computed display title, present only when the read
|
|
707
|
+
* asked for `withTitle: true` (also on expanded related rows and on `_locked`
|
|
708
|
+
* teaser rows, where it is built from the teaser fields only) (QFK2-E84).
|
|
709
|
+
*/
|
|
710
|
+
type ContentRecord = {
|
|
711
|
+
id: string;
|
|
712
|
+
_locked?: true;
|
|
713
|
+
_title?: string;
|
|
714
|
+
} & Record<string, unknown>;
|
|
715
|
+
interface ListParams {
|
|
716
|
+
filter?: FilterNode;
|
|
717
|
+
/** Page size; the backend clamps to [1, 100]. */
|
|
718
|
+
limit?: number;
|
|
719
|
+
/** Opaque cursor from a previous `ListResult.nextCursor`. */
|
|
720
|
+
cursor?: string;
|
|
721
|
+
/** Page-based pagination (alternative to cursor). */
|
|
722
|
+
page?: number;
|
|
723
|
+
/** Override the ambient active locale for this request (E55). */
|
|
724
|
+
locale?: string;
|
|
725
|
+
/** Ask the backend to fall back to the default locale for missing translations. */
|
|
726
|
+
localeFallback?: boolean;
|
|
727
|
+
/**
|
|
728
|
+
* Sort keys, e.g. `['order', '-name']` or `'order,-name'`; `-` = descending.
|
|
729
|
+
* The backend allows at most 3 keys (sortable field types + `created_at`,
|
|
730
|
+
* `updated_at`, `id`). A sorted list pages with `page`, not `cursor`.
|
|
731
|
+
*/
|
|
732
|
+
sort?: string | readonly string[];
|
|
733
|
+
/** RELATION fields to inline (single level), e.g. `['city']`. */
|
|
734
|
+
expand?: string | readonly string[];
|
|
735
|
+
/** Ask the server for a display title: each row (and expanded row) gets `_title`. */
|
|
736
|
+
withTitle?: boolean;
|
|
737
|
+
}
|
|
738
|
+
/** Per-request options for single-record reads. */
|
|
739
|
+
interface GetParams {
|
|
740
|
+
locale?: string;
|
|
741
|
+
localeFallback?: boolean;
|
|
742
|
+
/** RELATION fields to inline (single level), e.g. `['city']`. */
|
|
743
|
+
expand?: string | readonly string[];
|
|
744
|
+
/** Ask the server for a display title: each row (and expanded row) gets `_title`. */
|
|
745
|
+
withTitle?: boolean;
|
|
746
|
+
}
|
|
747
|
+
/**
|
|
748
|
+
* Value of an expanded JOIN ("sub-list") field: the first page of child rows plus a total.
|
|
749
|
+
* `null` when the caller cannot read the child collection. Absent without `expand`.
|
|
750
|
+
*/
|
|
751
|
+
type JoinResult<T = ContentRecord> = {
|
|
752
|
+
docs: T[];
|
|
753
|
+
totalDocs: number;
|
|
754
|
+
hasMore: boolean;
|
|
755
|
+
};
|
|
756
|
+
/** RELATION_MANY read value: ordered target ids (`[]` when no links). With `expand` the field holds `T[]` instead (type it via the read generic). */
|
|
757
|
+
type RelationManyValue = string[];
|
|
758
|
+
/** RELATION_MANY write value: full ordered replace, partial `{ connect, disconnect }`, or `null` to clear. */
|
|
759
|
+
type RelationManyWrite = string[] | {
|
|
760
|
+
connect?: string[];
|
|
761
|
+
disconnect?: string[];
|
|
762
|
+
} | null;
|
|
763
|
+
interface ListResult<T = ContentRecord> {
|
|
764
|
+
docs: T[];
|
|
765
|
+
nextCursor: string | null;
|
|
766
|
+
hasMore: boolean;
|
|
767
|
+
totalDocs?: number;
|
|
768
|
+
totalPages?: number;
|
|
769
|
+
page?: number;
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/**
|
|
773
|
+
* Holds the unlock tokens returned by `content.lookup` (QFK2-E78). One token
|
|
774
|
+
* per (collection, id), newest 20 kept, persisted in secure storage. Tokens
|
|
775
|
+
* never expire and the server silently ignores stale ones, so nothing is ever
|
|
776
|
+
* pruned on failure. Observable: `subscribe` fires on add / clear.
|
|
777
|
+
*/
|
|
778
|
+
declare class UnlockTokenStore {
|
|
779
|
+
private readonly storage;
|
|
780
|
+
private entries;
|
|
781
|
+
/** Serializes storage writes so the last persisted snapshot equals the in-memory state. */
|
|
782
|
+
private writeChain;
|
|
783
|
+
private readonly listeners;
|
|
784
|
+
/** Memoized load: initialize(), getRequestHeaders(), add() and clear() share one read. */
|
|
785
|
+
private hydration;
|
|
786
|
+
constructor(storage: Pick<QafkaCmsStorage, "getItem" | "setItem" | "removeItem">);
|
|
787
|
+
/**
|
|
788
|
+
* Load persisted tokens. Idempotent: every caller awaits the same read, so it
|
|
789
|
+
* is safe from initialize() and from getRequestHeaders() before initialize().
|
|
790
|
+
* Corrupt storage → empty.
|
|
791
|
+
*/
|
|
792
|
+
hydrate(): Promise<void>;
|
|
793
|
+
private load;
|
|
794
|
+
/** Newest-last token list, as sent in `X-Unlock-Token`. */
|
|
795
|
+
tokens(): string[];
|
|
796
|
+
add(collection: string, id: string, token: string): Promise<void>;
|
|
797
|
+
clear(): Promise<void>;
|
|
798
|
+
subscribe(listener: () => void): () => void;
|
|
799
|
+
private enqueue;
|
|
800
|
+
private emit;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
/**
|
|
804
|
+
* Content CRUD against `/v1/end-user/content/:collection`. Access policy
|
|
805
|
+
* (PUBLIC vs END_USER), row scoping, and limit clamping are enforced
|
|
806
|
+
* server-side; the client just shapes requests and forwards the opaque cursor.
|
|
807
|
+
*
|
|
808
|
+
* Reads carry the active locale as an explicit `?locale=` query (E55): the
|
|
809
|
+
* ambient locale comes from {@link ContentClientOptions.getLocale}, and a
|
|
810
|
+
* per-request `params.locale` overrides it. The same locale also rides along as
|
|
811
|
+
* `Accept-Language` (HttpClient); the backend resolves query > header > default.
|
|
812
|
+
*/
|
|
813
|
+
interface ContentClientOptions {
|
|
814
|
+
/** Ambient active locale (typically `() => languageManager.getLanguage()`). */
|
|
815
|
+
getLocale?: () => string | null;
|
|
816
|
+
/** Ambient locale-fallback preference (default off). */
|
|
817
|
+
getLocaleFallback?: () => boolean;
|
|
818
|
+
/** Persisted code-lookup unlock tokens (QFK2-E78); `lookup` stores into it. */
|
|
819
|
+
unlockTokens?: UnlockTokenStore;
|
|
820
|
+
}
|
|
821
|
+
/** Result of {@link ContentClient.lookup}. */
|
|
822
|
+
interface LookupResult<T = ContentRecord> {
|
|
823
|
+
data: T;
|
|
824
|
+
unlockToken: string;
|
|
825
|
+
}
|
|
826
|
+
/** Options of {@link ContentClient.listConditional} / {@link ContentClient.getConditional} (QFK2-E59 D4). */
|
|
827
|
+
interface ConditionalReadOptions {
|
|
828
|
+
/** ETag of the copy the caller holds (`If-None-Match`); `null` / absent = unconditional. */
|
|
829
|
+
ifNoneMatch?: string | null;
|
|
830
|
+
}
|
|
831
|
+
declare class ContentClient {
|
|
832
|
+
private readonly http;
|
|
833
|
+
private readonly opts;
|
|
834
|
+
constructor(http: HttpClient, opts?: ContentClientOptions);
|
|
835
|
+
list<T = ContentRecord>(collection: string, params?: ListParams): Promise<ListResult<T>>;
|
|
836
|
+
get<T = ContentRecord>(collection: string, id: string, params?: GetParams): Promise<T>;
|
|
837
|
+
/**
|
|
838
|
+
* {@link list} as a conditional GET (QFK2-E59 D4): the identical request plus
|
|
839
|
+
* `If-None-Match` when `opts.ifNoneMatch` is set. Resolves
|
|
840
|
+
* `{ notModified: true }` on 304, otherwise the page and its ETag.
|
|
841
|
+
*/
|
|
842
|
+
listConditional<T = ContentRecord>(collection: string, params?: ListParams, opts?: ConditionalReadOptions): Promise<ConditionalResponse<ListResult<T>>>;
|
|
843
|
+
/** {@link get} as a conditional GET; see {@link listConditional}. */
|
|
844
|
+
getConditional<T = ContentRecord>(collection: string, id: string, params?: GetParams, opts?: ConditionalReadOptions): Promise<ConditionalResponse<T>>;
|
|
845
|
+
create<T = ContentRecord>(collection: string, data: Record<string, unknown>): Promise<T>;
|
|
846
|
+
update<T = ContentRecord>(collection: string, id: string, data: Record<string, unknown>): Promise<T>;
|
|
847
|
+
delete(collection: string, id: string): Promise<void>;
|
|
848
|
+
/**
|
|
849
|
+
* Unlock a code-locked record (QFK2-E78). Wrong/unknown codes reject with a
|
|
850
|
+
* `ProblemError` (404 `LOOKUP_NOT_FOUND`, 400 `LOOKUP_BAD_REQUEST`, 429
|
|
851
|
+
* `LOOKUP_RATE_LIMITED`). On success the token is persisted and sent on every
|
|
852
|
+
* later content request.
|
|
853
|
+
*/
|
|
854
|
+
lookup<T = ContentRecord>(collection: string, code: string, params?: GetParams): Promise<LookupResult<T>>;
|
|
855
|
+
/** Forget all stored unlock tokens (e.g. on sign-out); locked rows lock again. */
|
|
856
|
+
clearUnlockTokens(): Promise<void>;
|
|
857
|
+
/** Subscribe to unlock-token changes (lookup / clear). Returns unsubscribe. */
|
|
858
|
+
onUnlockChange(listener: () => void): () => void;
|
|
859
|
+
/** Request options of a list read (shared by {@link list} and {@link listConditional}). */
|
|
860
|
+
private listOptions;
|
|
861
|
+
/** Request options of a single-record read (shared by {@link get} and {@link getConditional}). */
|
|
862
|
+
private getOptions;
|
|
863
|
+
/** Explicit param wins over the ambient locale; both absent → omit the query. */
|
|
864
|
+
private resolveLocale;
|
|
865
|
+
/** Emit `locale_fallback=true` only when truthy; otherwise omit it. */
|
|
866
|
+
private resolveFallback;
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
interface ConfigSnapshot<T> {
|
|
870
|
+
version: number;
|
|
871
|
+
data: T;
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
interface ConfigSyncOptions<T> {
|
|
875
|
+
domain: string;
|
|
876
|
+
buildTimeDefault: T;
|
|
877
|
+
/**
|
|
878
|
+
* Version of the embedded `buildTimeDefault` (E58). Seeds the client's version
|
|
879
|
+
* so a fresh build supersedes an older cache, and a matching server version is
|
|
880
|
+
* not re-fetched. Omit (→ 0) when nothing is embedded.
|
|
881
|
+
*/
|
|
882
|
+
buildTimeVersion?: number;
|
|
883
|
+
apiUrl: string;
|
|
884
|
+
http: {
|
|
885
|
+
request: <R>(method: 'GET', path: string) => Promise<R>;
|
|
886
|
+
};
|
|
887
|
+
storage: Pick<QafkaCmsStorage, 'getItem' | 'setItem'>;
|
|
888
|
+
connectSse?: ConnectSse;
|
|
889
|
+
/** SSE request headers; a function is resolved (async) right before each connect. */
|
|
890
|
+
headers?: Record<string, string> | (() => Promise<Record<string, string>>);
|
|
891
|
+
pollIntervalMs?: number;
|
|
892
|
+
/** Foreground/background source — pauses polling in the background (E56). */
|
|
893
|
+
appState?: AppStateProvider;
|
|
894
|
+
/** Injectable RNG for poll and SSE-reconnect jitter (deterministic in tests). Default Math.random. */
|
|
895
|
+
random?: () => number;
|
|
896
|
+
}
|
|
897
|
+
type Listener<T> = (data: T) => void;
|
|
898
|
+
declare class ConfigSyncClient<T> {
|
|
899
|
+
private readonly opts;
|
|
900
|
+
private data;
|
|
901
|
+
private version;
|
|
902
|
+
private readonly listeners;
|
|
903
|
+
private stopped;
|
|
904
|
+
private appStateUnsub;
|
|
905
|
+
/** Polling fallback; this client drives pause/resume itself (SSE and polling share AppState). */
|
|
906
|
+
private readonly poller;
|
|
907
|
+
private readonly sse;
|
|
908
|
+
constructor(opts: ConfigSyncOptions<T>);
|
|
909
|
+
/** Latest known config (build-time default until `start()` resolves). */
|
|
910
|
+
current(): T;
|
|
911
|
+
subscribe(listener: Listener<T>): () => void;
|
|
912
|
+
start(): Promise<void>;
|
|
913
|
+
stop(): void;
|
|
914
|
+
/** Open the live channel: SSE if configured, otherwise polling. */
|
|
915
|
+
private beginSync;
|
|
916
|
+
/** Tear the live channel down without ending the client (background). */
|
|
917
|
+
private pauseSync;
|
|
918
|
+
private cacheKey;
|
|
919
|
+
private hydrateFromCache;
|
|
920
|
+
private fetchAndApply;
|
|
921
|
+
private emit;
|
|
922
|
+
/**
|
|
923
|
+
* One poll cycle: probe the cheap `/version` endpoint and only pull the full
|
|
924
|
+
* snapshot when the version actually advanced (E56). This keeps a 60s poll
|
|
925
|
+
* from re-downloading an unchanged KB-sized payload every tick.
|
|
926
|
+
*/
|
|
927
|
+
private pollOnce;
|
|
928
|
+
private startPolling;
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
/**
|
|
932
|
+
* SDK-side mirrors of the backend `locales` and `i18n` config-domain payloads
|
|
933
|
+
* (E10 `app-config/domains/schemas.ts`). Kept as plain types — the SDK treats
|
|
934
|
+
* config `data` opaquely; only the LanguageManager interprets these two shapes.
|
|
935
|
+
*/
|
|
936
|
+
/** `locales` domain — the project's supported language set. */
|
|
937
|
+
interface LocalesData {
|
|
938
|
+
defaultLocale: string;
|
|
939
|
+
locales: string[];
|
|
940
|
+
}
|
|
941
|
+
/** `i18n` domain — UI strings, locale-indexed (`{ tr: { key: value } }`). */
|
|
942
|
+
interface I18nData {
|
|
943
|
+
translations: Record<string, Record<string, string>>;
|
|
944
|
+
}
|
|
945
|
+
/** Interpolation values for `t(key, params)` — replaces `{{name}}` placeholders. */
|
|
946
|
+
type TranslateParams = Record<string, string | number>;
|
|
947
|
+
|
|
948
|
+
/**
|
|
949
|
+
* Active-language runtime for the SDK (E55). Holds the user's selected locale,
|
|
950
|
+
* the project's supported-locale set (`locales` domain), and the UI-string map
|
|
951
|
+
* (`i18n` domain), and resolves `t(key)` against them. Framework-agnostic: the
|
|
952
|
+
* React `useLocale`/`useTranslation` hooks subscribe to it via `useSyncExternalStore`.
|
|
953
|
+
*
|
|
954
|
+
* Modelled on Shopla's `react-native-firebase-translations` (active locale +
|
|
955
|
+
* persisted choice + reactive notify), but fed by QafkaCMS config-sync instead
|
|
956
|
+
* of Firebase — `applyLocales`/`applyI18n` are the seams the config-sync clients
|
|
957
|
+
* push into (see {@link QafkaCmsClient}).
|
|
958
|
+
*/
|
|
959
|
+
interface LanguageManagerDeps {
|
|
960
|
+
storage: Pick<QafkaCmsStorage, 'getItem' | 'setItem'>;
|
|
961
|
+
}
|
|
962
|
+
declare class LanguageManager {
|
|
963
|
+
private readonly deps;
|
|
964
|
+
/** null until the user picks (or `hydrate` restores) a locale; falls back to default. */
|
|
965
|
+
private locale;
|
|
966
|
+
private locales;
|
|
967
|
+
private i18n;
|
|
968
|
+
private readonly listeners;
|
|
969
|
+
/** Monotonic change counter — the `useSyncExternalStore` snapshot for the React hooks. */
|
|
970
|
+
private revision;
|
|
971
|
+
constructor(deps: LanguageManagerDeps);
|
|
972
|
+
/** Snapshot for `useSyncExternalStore`: bumps on every locale / data change. */
|
|
973
|
+
getRevision(): number;
|
|
974
|
+
/** The active locale, or the project default until one is chosen. */
|
|
975
|
+
getLanguage(): string;
|
|
976
|
+
getDefaultLocale(): string;
|
|
977
|
+
getAvailableLocales(): string[];
|
|
978
|
+
/** Switch the active locale: update state, persist, and notify subscribers. */
|
|
979
|
+
setLanguage(locale: string): Promise<void>;
|
|
980
|
+
/**
|
|
981
|
+
* Resolve a UI string. Lookup order: active locale → default locale → the key
|
|
982
|
+
* itself (so a missing translation degrades to a visible-but-stable token).
|
|
983
|
+
*/
|
|
984
|
+
t(key: string, params?: TranslateParams): string;
|
|
985
|
+
subscribe(listener: () => void): () => void;
|
|
986
|
+
/** Config-sync seam: the `locales` domain snapshot landed. */
|
|
987
|
+
applyLocales(data: LocalesData): void;
|
|
988
|
+
/** Config-sync seam: the `i18n` domain snapshot landed. */
|
|
989
|
+
applyI18n(data: I18nData): void;
|
|
990
|
+
/** Restore the persisted locale (call once at boot, after storage is ready). */
|
|
991
|
+
hydrate(): Promise<void>;
|
|
992
|
+
private emit;
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
/**
|
|
996
|
+
* Human-friendly cache durations. Accepts a raw millisecond number or a short
|
|
997
|
+
* suffixed string (`'500ms'`, `'30s'`, `'10m'`, `'1h'`, `'2d'`). Used for
|
|
998
|
+
* per-query TTL so callers can write `ttl: '1h'` instead of `3_600_000`.
|
|
999
|
+
*/
|
|
1000
|
+
type Duration = number | string;
|
|
1001
|
+
/**
|
|
1002
|
+
* Normalize a {@link Duration} to milliseconds. `null`/`undefined` → `null`
|
|
1003
|
+
* (meaning "no freshness window"). Throws on malformed strings so a typo fails
|
|
1004
|
+
* loud at call time rather than silently disabling the TTL.
|
|
1005
|
+
*/
|
|
1006
|
+
declare function parseDuration(value: Duration | null | undefined): number | null;
|
|
1007
|
+
|
|
1008
|
+
/**
|
|
1009
|
+
* A query key identifies a cache entry. Either an opaque string, or an array of
|
|
1010
|
+
* JSON-serializable parts (the common case — e.g. `['content', 'posts', { limit: 20 }]`).
|
|
1011
|
+
* Array keys are serialized deterministically so that object member order and
|
|
1012
|
+
* `undefined` members do not produce distinct cache entries.
|
|
1013
|
+
*/
|
|
1014
|
+
type QueryKey = string | readonly unknown[];
|
|
1015
|
+
/** Stable, order-independent serialization of a {@link QueryKey}. */
|
|
1016
|
+
declare function serializeKey(key: QueryKey): string;
|
|
1017
|
+
|
|
1018
|
+
/**
|
|
1019
|
+
* Plain key/value store for cached data: `persist: true` queries, config-sync
|
|
1020
|
+
* snapshots, the saved locale, the content bundle. Cached content can be large
|
|
1021
|
+
* and is not secret, so it does not belong in the Keychain /
|
|
1022
|
+
* EncryptedSharedPreferences. The host app injects one (AsyncStorage, MMKV, …);
|
|
1023
|
+
* the SDK ships no JS dependency for it (dependency policy).
|
|
1024
|
+
*
|
|
1025
|
+
* The surface mirrors AsyncStorage so it can be passed straight through:
|
|
1026
|
+
* React Native: `createClient({ …, cacheStorage: AsyncStorage })` (QFK2-T471;
|
|
1027
|
+
* without it the RN SDK keeps cached data in its secure store),
|
|
1028
|
+
* `contentBundle: { storage: AsyncStorage }` for the bundle alone.
|
|
1029
|
+
* Web: the session mode picks the store (`PlatformAdapter.cacheStorage`).
|
|
1030
|
+
*/
|
|
1031
|
+
interface CacheStorage {
|
|
1032
|
+
getItem(key: string): Promise<string | null>;
|
|
1033
|
+
setItem(key: string, value: string): Promise<void>;
|
|
1034
|
+
removeItem(key: string): Promise<void>;
|
|
1035
|
+
multiRemove(keys: string[]): Promise<void>;
|
|
1036
|
+
}
|
|
1037
|
+
/**
|
|
1038
|
+
* In-memory fallback used when no `cacheStorage` is configured. Persistence
|
|
1039
|
+
* becomes a no-op across restarts, but the cache API stays fully functional so
|
|
1040
|
+
* code paths do not branch on "is persistence available".
|
|
1041
|
+
*/
|
|
1042
|
+
declare function createMemoryCacheStorage(): CacheStorage;
|
|
1043
|
+
|
|
1044
|
+
type QueryStatus = 'idle' | 'loading' | 'success' | 'error';
|
|
1045
|
+
/**
|
|
1046
|
+
* The public, immutable view of a cache entry that hooks read via
|
|
1047
|
+
* `useSyncExternalStore`. A fresh frozen object is produced on every state
|
|
1048
|
+
* change; the reference is stable between changes so React can bail out.
|
|
1049
|
+
*/
|
|
1050
|
+
interface QueryState<T> {
|
|
1051
|
+
/** Latest data, or `undefined` until the first successful fetch / hydrate. */
|
|
1052
|
+
data: T | undefined;
|
|
1053
|
+
/** Last error. May be set while `data` is still present (stale-on-error). */
|
|
1054
|
+
error: Error | undefined;
|
|
1055
|
+
status: QueryStatus;
|
|
1056
|
+
/** Fetching with no data yet (first load). */
|
|
1057
|
+
isLoading: boolean;
|
|
1058
|
+
/** Any fetch in flight, including a background revalidate over stale data. */
|
|
1059
|
+
isFetching: boolean;
|
|
1060
|
+
/** Data is absent or older than its TTL. */
|
|
1061
|
+
isStale: boolean;
|
|
1062
|
+
/** Epoch ms of the last successful data, or `null`. */
|
|
1063
|
+
updatedAt: number | null;
|
|
1064
|
+
}
|
|
1065
|
+
/** Per-query behavior. */
|
|
1066
|
+
interface QueryOptions {
|
|
1067
|
+
/** Freshness window. While fresh, a mount returns cache without a network call. Default: always stale. */
|
|
1068
|
+
ttl?: Duration | null;
|
|
1069
|
+
/** Persist successful results to the configured `cacheStorage`. Default: false. */
|
|
1070
|
+
persist?: boolean;
|
|
1071
|
+
/**
|
|
1072
|
+
* Collection slug of the launch version gate (QFK2-E59 D8). Only used when
|
|
1073
|
+
* the cache has a `versionGate` (`createClient({ contentVersionGate })`):
|
|
1074
|
+
* the collection's version is read before each full fetch, and a stale
|
|
1075
|
+
* entry whose version is unchanged is served without a fetch. Only for
|
|
1076
|
+
* reads whose data depends on that collection alone (no `expand`).
|
|
1077
|
+
*/
|
|
1078
|
+
gate?: string;
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
/**
|
|
1082
|
+
* Conditional fetcher protocol of the {@link QueryCache} (QFK2-E59 D5).
|
|
1083
|
+
*
|
|
1084
|
+
* A query fetcher receives a {@link FetchContext} carrying the ETag of the data
|
|
1085
|
+
* the cache already holds. It may return plain data (today's behavior: no ETag
|
|
1086
|
+
* is kept) or a branded result built with {@link conditional}:
|
|
1087
|
+
*
|
|
1088
|
+
* - `conditional.notModified()` — the server answered 304: keep the cached data
|
|
1089
|
+
* (same object), refresh its timestamp, keep the ETag.
|
|
1090
|
+
* - `conditional.data(data, etag)` — a full response: store the data and its ETag.
|
|
1091
|
+
*
|
|
1092
|
+
* The brand is a symbol, so a plain value that happens to look like
|
|
1093
|
+
* `{ notModified: true }` is never mistaken for a conditional result.
|
|
1094
|
+
*/
|
|
1095
|
+
/** Argument every query fetcher receives. */
|
|
1096
|
+
interface FetchContext {
|
|
1097
|
+
/**
|
|
1098
|
+
* ETag of the cached data, or `null` when there is no data (first load,
|
|
1099
|
+
* after `setData` / `clear`) or the last result had none. Send it as
|
|
1100
|
+
* `If-None-Match` only when non-null.
|
|
1101
|
+
*/
|
|
1102
|
+
etag: string | null;
|
|
1103
|
+
}
|
|
1104
|
+
declare const BRAND: unique symbol;
|
|
1105
|
+
/** Branded fetcher result: see {@link conditional}. */
|
|
1106
|
+
type ConditionalResult<T> = {
|
|
1107
|
+
readonly [BRAND]: true;
|
|
1108
|
+
readonly notModified: true;
|
|
1109
|
+
} | {
|
|
1110
|
+
readonly [BRAND]: true;
|
|
1111
|
+
readonly notModified: false;
|
|
1112
|
+
readonly data: T;
|
|
1113
|
+
readonly etag: string | null;
|
|
1114
|
+
};
|
|
1115
|
+
/** A query fetcher: may ignore `ctx` and return plain data, or use it and return a {@link ConditionalResult}. */
|
|
1116
|
+
type QueryFetcher<T> = (ctx: FetchContext) => Promise<T | ConditionalResult<T>>;
|
|
1117
|
+
|
|
1118
|
+
/**
|
|
1119
|
+
* Launch version gate of the {@link QueryCache} (QFK2-E59 D7/D8): request
|
|
1120
|
+
* batching. Version questions arriving within {@link VERSION_GATE_BATCH_MS}
|
|
1121
|
+
* share one `check` call (de-duplicated, at most {@link VERSION_GATE_MAX_SLUGS}
|
|
1122
|
+
* slugs per call). The server answers a batch with one refused collection
|
|
1123
|
+
* (change signal off, unreadable, unknown) with a 404 for all of it, so a 404
|
|
1124
|
+
* batch is retried slug by slug; a slug that 404s alone is "no gate" for the
|
|
1125
|
+
* batcher's lifetime and never asked again.
|
|
1126
|
+
*/
|
|
1127
|
+
/** `QueryCacheOptions.versionGate`: how the cache reads collection versions. */
|
|
1128
|
+
interface VersionGateOptions {
|
|
1129
|
+
/** Current versions of `collections` (`client.contentChanges.versions`); rejects with a `status` on HTTP errors. */
|
|
1130
|
+
check: (collections: string[]) => Promise<Record<string, string>>;
|
|
1131
|
+
/** A version match skips the fetch only within this long of the last real (200/304) validation. */
|
|
1132
|
+
maxAgeMs: number;
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
interface QueryCacheOptions {
|
|
1136
|
+
/** Where to persist entries flagged `persist`. Omit → memory-only (no-op across restarts). */
|
|
1137
|
+
storage?: CacheStorage;
|
|
1138
|
+
/** Clock injection for tests. */
|
|
1139
|
+
now?: () => number;
|
|
1140
|
+
/** Default TTL applied to queries that do not specify one. */
|
|
1141
|
+
defaultTtl?: Duration | null;
|
|
1142
|
+
/** Observe fetch errors (logging/telemetry). */
|
|
1143
|
+
onError?: (error: Error, key: string) => void;
|
|
1144
|
+
/**
|
|
1145
|
+
* Launch version gate (QFK2-E59 D8). Entries with `QueryOptions.gate` read
|
|
1146
|
+
* their collection's version before each full fetch; a stale one reached
|
|
1147
|
+
* through `ensure` whose version is unchanged is refreshed without a fetch.
|
|
1148
|
+
* Omit → no gate (the default).
|
|
1149
|
+
*/
|
|
1150
|
+
versionGate?: VersionGateOptions;
|
|
1151
|
+
/**
|
|
1152
|
+
* The app version requests are sent with (QFK2-E59 V9; the Provider passes
|
|
1153
|
+
* `client.appVersion`). Persisted entries are tagged with it; an entry stored
|
|
1154
|
+
* under another app version (or with / without one) hydrates stale and
|
|
1155
|
+
* without its version-gate stamp, so it revalidates (ETag kept) while its
|
|
1156
|
+
* data is still shown. Invalid / omitted = none.
|
|
1157
|
+
*/
|
|
1158
|
+
appVersion?: string | null;
|
|
1159
|
+
}
|
|
1160
|
+
/** Options of {@link QueryCache.invalidate} / {@link QueryCache.invalidateByPrefix}. */
|
|
1161
|
+
interface InvalidateOptions {
|
|
1162
|
+
/**
|
|
1163
|
+
* Defer the refetch of a mounted entry by this many ms (QFK2-E76 D8: spread
|
|
1164
|
+
* a realtime signal's refetches). The entry is marked stale at once; one
|
|
1165
|
+
* pending timer per key, so repeated invalidations do not fetch twice.
|
|
1166
|
+
* Omitted / `0` = refetch now (the default).
|
|
1167
|
+
*/
|
|
1168
|
+
delayMs?: number;
|
|
1169
|
+
}
|
|
1170
|
+
/**
|
|
1171
|
+
* Framework-agnostic reactive query cache. The React layer binds to it through
|
|
1172
|
+
* `subscribe` / `getSnapshot` (`useSyncExternalStore`); nothing here imports
|
|
1173
|
+
* React. Behavior, per key: in-flight de-duplication, TTL freshness,
|
|
1174
|
+
* stale-while-revalidate, stale-on-error, race-safe results (epoch guard), and
|
|
1175
|
+
* opt-in persistence with the freshness timestamp.
|
|
1176
|
+
*/
|
|
1177
|
+
declare class QueryCache {
|
|
1178
|
+
private readonly entries;
|
|
1179
|
+
private readonly persistedKeys;
|
|
1180
|
+
/** Loads the persisted key index once (keys written in earlier sessions). */
|
|
1181
|
+
private indexLoad;
|
|
1182
|
+
/** Serialized index writes, so a slower earlier write cannot overwrite a newer one. */
|
|
1183
|
+
private indexWrite;
|
|
1184
|
+
/** Pending delayed refetches (one per serialized key). */
|
|
1185
|
+
private readonly delayed;
|
|
1186
|
+
private readonly storage?;
|
|
1187
|
+
private readonly now;
|
|
1188
|
+
private readonly defaultTtl;
|
|
1189
|
+
private readonly onError?;
|
|
1190
|
+
private warnedNoStorage;
|
|
1191
|
+
private readonly warn?;
|
|
1192
|
+
private readonly versions;
|
|
1193
|
+
private readonly gateMaxAgeMs;
|
|
1194
|
+
private readonly appVersion;
|
|
1195
|
+
/** Normalized form of {@link appVersion} (`1.4` = `1.4.0`); `'null'` when none. */
|
|
1196
|
+
private readonly appVersionKey;
|
|
1197
|
+
constructor(options?: QueryCacheOptions);
|
|
1198
|
+
/** Current immutable view for a key. Stable reference between changes. */
|
|
1199
|
+
getSnapshot<T>(key: QueryKey): QueryState<T>;
|
|
1200
|
+
/** Subscribe to changes for a key. Returns an unsubscribe function. */
|
|
1201
|
+
subscribe(key: QueryKey, listener: () => void): () => void;
|
|
1202
|
+
/**
|
|
1203
|
+
* Ensure data for `key` is loading or loaded. Hydrates from persistence
|
|
1204
|
+
* first, returns immediately if fresh, otherwise fetches (deduped). The
|
|
1205
|
+
* returned promise resolves once the work settles; data is read via state.
|
|
1206
|
+
*/
|
|
1207
|
+
ensure<T>(key: QueryKey, fetcher: QueryFetcher<T>, options?: QueryOptions): Promise<void>;
|
|
1208
|
+
/** Boot/warm-up prefetch — same semantics as {@link ensure}, no subscriber required. */
|
|
1209
|
+
prefetch<T>(key: QueryKey, fetcher: QueryFetcher<T>, options?: QueryOptions): Promise<void>;
|
|
1210
|
+
/** Force a refetch regardless of freshness (background revalidate over existing data). */
|
|
1211
|
+
refetch<T>(key: QueryKey, fetcher?: QueryFetcher<T>): Promise<void>;
|
|
1212
|
+
/**
|
|
1213
|
+
* Refetch every entry that currently has subscribers — used after an identity
|
|
1214
|
+
* change so mounted screens reload with the new session. Entries with no
|
|
1215
|
+
* listeners are left untouched (they refetch on their next mount).
|
|
1216
|
+
*/
|
|
1217
|
+
refetchActive(): void;
|
|
1218
|
+
/**
|
|
1219
|
+
* Mark a key stale and, if it has active subscribers, revalidate it — now, or
|
|
1220
|
+
* after `opts.delayMs`. An entry without subscribers is only marked stale.
|
|
1221
|
+
*/
|
|
1222
|
+
invalidate(key: QueryKey, opts?: InvalidateOptions): void;
|
|
1223
|
+
/** Invalidate every key whose serialized form matches `predicate`. */
|
|
1224
|
+
invalidateWhere(predicate: (key: string) => boolean): void;
|
|
1225
|
+
/**
|
|
1226
|
+
* Invalidate every key that has `prefix` as a leading segment (react-query
|
|
1227
|
+
* style). `invalidateByPrefix(['content', 'posts'])` refreshes every cached
|
|
1228
|
+
* `content.list('posts', …)` regardless of params; a string prefix matches
|
|
1229
|
+
* that exact key.
|
|
1230
|
+
*/
|
|
1231
|
+
invalidateByPrefix(prefix: QueryKey, opts?: InvalidateOptions): void;
|
|
1232
|
+
/**
|
|
1233
|
+
* Whether any entry matching `prefix` (same matching as
|
|
1234
|
+
* {@link invalidateByPrefix}) currently has subscribers, i.e. is on screen.
|
|
1235
|
+
*/
|
|
1236
|
+
hasActive(prefix: QueryKey): boolean;
|
|
1237
|
+
/**
|
|
1238
|
+
* Write data directly (optimistic update); cancels any in-flight fetch. The
|
|
1239
|
+
* ETag is dropped: the written data is not the server's representation.
|
|
1240
|
+
*/
|
|
1241
|
+
setData<T>(key: QueryKey, data: T): void;
|
|
1242
|
+
/**
|
|
1243
|
+
* Reset every entry to idle and drop persisted copies. Call on logout so a
|
|
1244
|
+
* previous user's visible set cannot leak. Does NOT auto-refetch — mounted
|
|
1245
|
+
* screens re-fetch on their next mount.
|
|
1246
|
+
*/
|
|
1247
|
+
clear(): Promise<void>;
|
|
1248
|
+
private getOrCreate;
|
|
1249
|
+
private applyOptions;
|
|
1250
|
+
private isStale;
|
|
1251
|
+
/**
|
|
1252
|
+
* Fetch (deduped). `gated` = reached through `ensure`: a version-gated entry
|
|
1253
|
+
* whose version is unchanged may skip the fetcher (QFK2-E59 D8). Forced
|
|
1254
|
+
* paths (`invalidate*`, `refetch*`) always fetch, still recording the version.
|
|
1255
|
+
*/
|
|
1256
|
+
private runFetch;
|
|
1257
|
+
/**
|
|
1258
|
+
* Store a fetcher result (QFK2-E59 D5). Branded `notModified` keeps the data
|
|
1259
|
+
* (same object) and ETag and only refreshes the timestamp; branded data
|
|
1260
|
+
* stores data + ETag; a plain value is today's behavior with no ETag.
|
|
1261
|
+
*/
|
|
1262
|
+
private applyResult;
|
|
1263
|
+
/** The entry's gate slug when the gate applies to it (configured, set, not refused). */
|
|
1264
|
+
private gateSlugOf;
|
|
1265
|
+
/** Data + stored version equal to `version`, within `maxAgeMs` of the last real validation. */
|
|
1266
|
+
private gateHolds;
|
|
1267
|
+
private invalidateEntry;
|
|
1268
|
+
private cancelDelayed;
|
|
1269
|
+
private maybeHydrate;
|
|
1270
|
+
private maybePersist;
|
|
1271
|
+
/** Read the persisted key index once into `persistedKeys`. */
|
|
1272
|
+
private loadIndex;
|
|
1273
|
+
/** Remember a persisted key in memory; true when it was not known yet. */
|
|
1274
|
+
private track;
|
|
1275
|
+
/** Write the stored key index (after merging the earlier-session index); serialized. */
|
|
1276
|
+
private writeIndex;
|
|
1277
|
+
private touch;
|
|
1278
|
+
/** Whether a persisted tag names this cache's app version (both absent counts as equal). */
|
|
1279
|
+
private sameAppVersion;
|
|
1280
|
+
private warnNoStorage;
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
/**
|
|
1284
|
+
* Transport of a live content watch (QFK2-E76 §9.1). `'auto'` and `'sse'`:
|
|
1285
|
+
* SSE when the platform has a transport, polling otherwise or after SSE keeps
|
|
1286
|
+
* failing (polling is always the fallback). `'poll'`: version polling only.
|
|
1287
|
+
*/
|
|
1288
|
+
type ContentLiveMode = 'auto' | 'sse' | 'poll';
|
|
1289
|
+
/** What the hub is doing right now (`client.contentChanges.status()`, debug only). */
|
|
1290
|
+
type ContentChangesStatus = 'sse' | 'polling' | 'idle';
|
|
1291
|
+
/** One live watch: a collection's lists + records, or one record (`id`), plus extra collections (`also`, §8.3). */
|
|
1292
|
+
interface ContentWatchTarget {
|
|
1293
|
+
collection: string;
|
|
1294
|
+
id?: string;
|
|
1295
|
+
/** Collections whose changes also refresh this target (e.g. an expanded relation). */
|
|
1296
|
+
also?: readonly string[];
|
|
1297
|
+
}
|
|
1298
|
+
/** Where a change signal lands: a `QueryCache` (or anything with its `invalidateByPrefix`). */
|
|
1299
|
+
interface ContentInvalidationTarget {
|
|
1300
|
+
invalidateByPrefix(prefix: QueryKey, opts?: InvalidateOptions): void;
|
|
1301
|
+
}
|
|
1302
|
+
interface ContentWatchOptions {
|
|
1303
|
+
/** The cache to invalidate on a change (the React hooks pass the Provider's cache). */
|
|
1304
|
+
cache?: ContentInvalidationTarget;
|
|
1305
|
+
/** Requested poll cadence while polling (default 60 s, floor 30 s; the smallest watcher wins). */
|
|
1306
|
+
pollIntervalMs?: number;
|
|
1307
|
+
}
|
|
1308
|
+
/** Public face of the hub on a client (`client.contentChanges`). Lazy: nothing runs until `watch`. */
|
|
1309
|
+
interface ContentChangesApi {
|
|
1310
|
+
/** Start watching; returns the unsubscribe. `mode` defaults to the client's `contentLiveDefault`. */
|
|
1311
|
+
watch(target: ContentWatchTarget, mode?: ContentLiveMode, opts?: ContentWatchOptions): () => void;
|
|
1312
|
+
status(): ContentChangesStatus;
|
|
1313
|
+
/** Identity changed: forget versions and reconnect with fresh headers. */
|
|
1314
|
+
reset(): void;
|
|
1315
|
+
/** Drop every watch and close the connection / poller. */
|
|
1316
|
+
dispose(): void;
|
|
1317
|
+
/**
|
|
1318
|
+
* Current version of each collection (QFK2-E59 D7): one
|
|
1319
|
+
* `GET /content-changes/version?collections=…` (≤20 per call, server limit).
|
|
1320
|
+
* Collections the answer lacks are omitted. Rejects with a `status` on HTTP
|
|
1321
|
+
* errors; one refused collection (change signal off, unreadable) 404s the
|
|
1322
|
+
* whole request. Needs no watch and opens no connection.
|
|
1323
|
+
*/
|
|
1324
|
+
versions(collections: readonly string[]): Promise<Record<string, string>>;
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
/**
|
|
1328
|
+
* Content bundle (QFK2-E59 T466): an offline snapshot of the collections the
|
|
1329
|
+
* project opted in, as the anonymous end-user sees them, one JSON file per
|
|
1330
|
+
* locale. The API announces the published version at
|
|
1331
|
+
* `GET /v1/end-user/content-bundle` and serves the file from a short-lived
|
|
1332
|
+
* signed URL; the SDK keeps the last file in its storage.
|
|
1333
|
+
*/
|
|
1334
|
+
/** A collection's app-version rule (T467), carried by the file; the SDK filters rows with it. */
|
|
1335
|
+
interface BundleCollectionAppVersion {
|
|
1336
|
+
/** Field holding the minimum app version of a row (text such as `1.4`). */
|
|
1337
|
+
minField?: string | null;
|
|
1338
|
+
/** Field holding the maximum app version of a row. */
|
|
1339
|
+
maxField?: string | null;
|
|
1340
|
+
/** Unknown client version: `'show'` (default) keeps every row, `'hide'` keeps only unrestricted rows. */
|
|
1341
|
+
unknown?: 'show' | 'hide' | null;
|
|
1342
|
+
}
|
|
1343
|
+
/**
|
|
1344
|
+
* Composite field metadata of a collection or component (added to format 1;
|
|
1345
|
+
* files of older APIs lack it). A COMPONENT value carries no `__component`,
|
|
1346
|
+
* so this map lets the SDK null a hidden component held by a COMPONENT field,
|
|
1347
|
+
* as the API does. Absent keys = no such field.
|
|
1348
|
+
*/
|
|
1349
|
+
interface BundleFieldMeta {
|
|
1350
|
+
/** COMPONENT fields: field slug → the component it holds (`repeatable`: an array of them). */
|
|
1351
|
+
componentFields?: Record<string, {
|
|
1352
|
+
componentId: string;
|
|
1353
|
+
repeatable?: boolean;
|
|
1354
|
+
}> | null;
|
|
1355
|
+
/** DYNAMIC_ZONE fields (blocks carry `__component`). */
|
|
1356
|
+
zoneFields?: string[] | null;
|
|
1357
|
+
}
|
|
1358
|
+
/** One collection of a {@link BundleFile}. */
|
|
1359
|
+
interface BundleCollection extends BundleFieldMeta {
|
|
1360
|
+
/** The rows (relations are ids; DYNAMIC_ZONE blocks carry `__component`). */
|
|
1361
|
+
rows: Array<Record<string, unknown>>;
|
|
1362
|
+
appVersion?: BundleCollectionAppVersion | null;
|
|
1363
|
+
}
|
|
1364
|
+
/**
|
|
1365
|
+
* A component type listed in the file: every one with a `minAppVersion`, and
|
|
1366
|
+
* the ones with composite fields of their own (their metadata lets nesting be walked).
|
|
1367
|
+
*/
|
|
1368
|
+
interface BundleComponentInfo extends BundleFieldMeta {
|
|
1369
|
+
slug?: string;
|
|
1370
|
+
minAppVersion?: string | null;
|
|
1371
|
+
appVersionUnknown?: 'show' | 'hide' | null;
|
|
1372
|
+
}
|
|
1373
|
+
/** The bundle file (format B5). `initial` (build-time embedded) has the same shape. */
|
|
1374
|
+
interface BundleFile {
|
|
1375
|
+
formatVersion: 1;
|
|
1376
|
+
projectId?: string;
|
|
1377
|
+
/** Bundle version (per project, increasing). */
|
|
1378
|
+
version: number;
|
|
1379
|
+
/** The locale the values are resolved for (`default` in a single-language project). */
|
|
1380
|
+
locale: string;
|
|
1381
|
+
generatedAt?: string;
|
|
1382
|
+
collections: Record<string, BundleCollection>;
|
|
1383
|
+
/** Component types (versioned ones and ones with composite fields), keyed by component id. */
|
|
1384
|
+
components?: Record<string, BundleComponentInfo>;
|
|
1385
|
+
}
|
|
1386
|
+
/** `createClient({ contentBundle: { … } })`. */
|
|
1387
|
+
interface ContentBundleConfig {
|
|
1388
|
+
/**
|
|
1389
|
+
* Plain key/value store the bundle file is persisted in (React Native: an
|
|
1390
|
+
* AsyncStorage / MMKV adapter with `getItem` / `setItem` / `removeItem` /
|
|
1391
|
+
* `multiRemove`). Default: the platform's plain cache storage (web: the
|
|
1392
|
+
* session / local storage of the session mode); none (React Native) = kept in
|
|
1393
|
+
* memory for the app session only, with a dev warning. `null` = memory only on
|
|
1394
|
+
* purpose. Never the SDK's secure store: bundle files go up to 20 MB.
|
|
1395
|
+
*/
|
|
1396
|
+
storage?: CacheStorage | null;
|
|
1397
|
+
/** Locale to sync. Default: the client's active locale (React Native), else the project default. */
|
|
1398
|
+
locale?: string;
|
|
1399
|
+
/** Build-time embedded bundle: used until a newer version is stored. */
|
|
1400
|
+
initial?: BundleFile;
|
|
1401
|
+
}
|
|
1402
|
+
/** `contentBundle` of the client config: `true` or a {@link ContentBundleConfig}. Default off. */
|
|
1403
|
+
type ContentBundleOption = boolean | ContentBundleConfig;
|
|
1404
|
+
/** Result of {@link ContentBundleApi.sync}. */
|
|
1405
|
+
interface ContentBundleSyncResult {
|
|
1406
|
+
/** The bundle version now held; `null` when the project has no bundle. */
|
|
1407
|
+
version: number | null;
|
|
1408
|
+
/** Whether the held bundle changed (downloaded, switched locale, or dropped). */
|
|
1409
|
+
changed: boolean;
|
|
1410
|
+
}
|
|
1411
|
+
/** State of the held bundle (the `useBundle` / `useBundleItem` result fields besides the data). */
|
|
1412
|
+
interface ContentBundleStatus {
|
|
1413
|
+
version: number | null;
|
|
1414
|
+
isLoading: boolean;
|
|
1415
|
+
error: Error | null;
|
|
1416
|
+
}
|
|
1417
|
+
/** {@link ContentBundleApi.view}: a collection's rows plus the status (what `useBundle` returns). */
|
|
1418
|
+
interface ContentBundleView<T> extends ContentBundleStatus {
|
|
1419
|
+
rows: T[];
|
|
1420
|
+
}
|
|
1421
|
+
/** {@link ContentBundleApi.itemView}: one row plus the status (what `useBundleItem` returns). */
|
|
1422
|
+
interface ContentBundleItemView<T> extends ContentBundleStatus {
|
|
1423
|
+
data: T | null;
|
|
1424
|
+
}
|
|
1425
|
+
/** `client.bundle` — present only when `contentBundle` is enabled. */
|
|
1426
|
+
interface ContentBundleApi {
|
|
1427
|
+
/** Version of the held bundle, `null` when none. */
|
|
1428
|
+
readonly version: number | null;
|
|
1429
|
+
/** Locale of the held bundle, `null` when none. */
|
|
1430
|
+
readonly locale: string | null;
|
|
1431
|
+
/** The last sync error (cleared by a successful sync); the held bundle stays usable. */
|
|
1432
|
+
readonly error: Error | null;
|
|
1433
|
+
/** No bundle held yet and the first hydrate / sync has not settled. */
|
|
1434
|
+
readonly isLoading: boolean;
|
|
1435
|
+
/** Bumps on every change (`useSyncExternalStore` snapshot). */
|
|
1436
|
+
readonly revision: number;
|
|
1437
|
+
/**
|
|
1438
|
+
* Ask the API for the published version; download, validate and persist the
|
|
1439
|
+
* file only when it differs from the held one. De-duplicated while running.
|
|
1440
|
+
* A `locale` is remembered for later syncs until the active locale changes.
|
|
1441
|
+
* Rejects on failure (network, invalid file); the held bundle is kept.
|
|
1442
|
+
*/
|
|
1443
|
+
sync(options?: {
|
|
1444
|
+
locale?: string;
|
|
1445
|
+
}): Promise<ContentBundleSyncResult>;
|
|
1446
|
+
/** Resolves once the persisted (or `initial`) bundle is loaded. */
|
|
1447
|
+
ready(): Promise<void>;
|
|
1448
|
+
/** The collection's rows, filtered for `client.appVersion` (rows and hidden blocks). `[]` when absent. */
|
|
1449
|
+
rows<T = Record<string, unknown>>(collection: string): T[];
|
|
1450
|
+
/** One row by `id` (filtered like {@link rows}), or `null`. */
|
|
1451
|
+
get<T = Record<string, unknown>>(collection: string, id: string): T | null;
|
|
1452
|
+
/** `{ rows, version, isLoading, error }`, the same object until the next change (React snapshot). */
|
|
1453
|
+
view<T = Record<string, unknown>>(collection: string): ContentBundleView<T>;
|
|
1454
|
+
/** `{ data, version, isLoading, error }`, the same object until the next change (React snapshot). */
|
|
1455
|
+
itemView<T = Record<string, unknown>>(collection: string, id: string | null | undefined): ContentBundleItemView<T>;
|
|
1456
|
+
/**
|
|
1457
|
+
* Called on every change (new bundle, loading or error state); the first
|
|
1458
|
+
* subscription also starts loading the persisted bundle. Returns the unsubscribe.
|
|
1459
|
+
*/
|
|
1460
|
+
subscribe(listener: () => void): () => void;
|
|
1461
|
+
/**
|
|
1462
|
+
* Sync now, on every return to the foreground and when the active locale
|
|
1463
|
+
* changes (the Provider calls it after boot). Returns the stop function.
|
|
1464
|
+
*/
|
|
1465
|
+
start(): () => void;
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
/** `contentVersionGate` of the client config: `true`, or a custom upper bound. */
|
|
1469
|
+
type ContentVersionGateOption = boolean | {
|
|
1470
|
+
maxAgeMs?: number;
|
|
1471
|
+
};
|
|
1472
|
+
/** Resolved launch version gate (`client.contentVersionGate`). */
|
|
1473
|
+
interface ContentVersionGate {
|
|
1474
|
+
/**
|
|
1475
|
+
* A version match skips a download only within this long of the last real
|
|
1476
|
+
* validation (a 200/304), since policy, schema and draft-only changes do not
|
|
1477
|
+
* bump the version.
|
|
1478
|
+
*/
|
|
1479
|
+
readonly maxAgeMs: number;
|
|
1480
|
+
}
|
|
1481
|
+
/**
|
|
1482
|
+
* The client surface the shared React layer (Provider + hooks) needs. Both the
|
|
1483
|
+
* RN `QafkaCmsClient` and a {@link CoreClient} satisfy it structurally.
|
|
1484
|
+
*/
|
|
1485
|
+
interface CoreClientLike {
|
|
1486
|
+
readonly auth: AuthClient;
|
|
1487
|
+
readonly content: ContentClient;
|
|
1488
|
+
/** Storage for `persist: true` queries when the client has no {@link cacheStorage}. */
|
|
1489
|
+
readonly storage: KeyValueStorage;
|
|
1490
|
+
/**
|
|
1491
|
+
* QFK2-T471 — the plain store for `persist: true` queries (wins over
|
|
1492
|
+
* {@link storage}). Absent = `storage`. The React Native client sets it to
|
|
1493
|
+
* `createClient({ cacheStorage })`, keeping `storage` its secure store. A
|
|
1494
|
+
* {@link CoreClient} sets it to its `storage` (`platform.cacheStorage ?? sessionStorage`).
|
|
1495
|
+
*/
|
|
1496
|
+
readonly cacheStorage?: KeyValueStorage;
|
|
1497
|
+
/** Present on the full tier; `useLocale` / `useTranslation` require it. */
|
|
1498
|
+
readonly language?: LanguageManager;
|
|
1499
|
+
/** Live content change signals (`live` on the content hooks). Absent = `live` is ignored. */
|
|
1500
|
+
readonly contentChanges?: ContentChangesApi;
|
|
1501
|
+
/** Launch version gate (QFK2-E59 D7); set → the Provider gates expand-less content reads. */
|
|
1502
|
+
readonly contentVersionGate?: ContentVersionGate | null;
|
|
1503
|
+
/** Resolved app version (QFK2-E59 V9); the Provider tags persisted cache entries with it. */
|
|
1504
|
+
readonly appVersion?: string | null;
|
|
1505
|
+
/** Content bundle (QFK2-E59 T466); present only when `contentBundle` is enabled. */
|
|
1506
|
+
readonly bundle?: ContentBundleApi;
|
|
1507
|
+
initialize(): Promise<void>;
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
/**
|
|
1511
|
+
* RFC 7807 Problem Details. The QafkaCMS API returns errors in this shape
|
|
1512
|
+
* (`ProblemDetailsFilter`), so the SDK surfaces a typed error rather than a
|
|
1513
|
+
* bare `Error`, letting callers branch on `status` / `type`.
|
|
1514
|
+
*/
|
|
1515
|
+
interface ProblemDetails {
|
|
1516
|
+
type?: string;
|
|
1517
|
+
title?: string;
|
|
1518
|
+
status?: number;
|
|
1519
|
+
detail?: string;
|
|
1520
|
+
instance?: string;
|
|
1521
|
+
[key: string]: unknown;
|
|
1522
|
+
}
|
|
1523
|
+
declare class ProblemError extends Error {
|
|
1524
|
+
readonly status: number;
|
|
1525
|
+
readonly type?: string;
|
|
1526
|
+
readonly title?: string;
|
|
1527
|
+
readonly detail?: string;
|
|
1528
|
+
readonly instance?: string;
|
|
1529
|
+
/** Machine-readable error code from the problem body (e.g. `EMAIL_NOT_VERIFIED`). */
|
|
1530
|
+
readonly code?: string;
|
|
1531
|
+
readonly raw: ProblemDetails;
|
|
1532
|
+
constructor(status: number, problem: ProblemDetails);
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
/**
|
|
1536
|
+
* Color value shapes stored by the QafkaCMS API (`COLOR` fields). Local mirror;
|
|
1537
|
+
* the API stores values exactly as written (no normalization).
|
|
1538
|
+
*/
|
|
1539
|
+
/** Hex color: `#rgb`, `#rrggbb` or `#rrggbbaa`, any letter case. */
|
|
1540
|
+
type HexColor = string;
|
|
1541
|
+
interface GradientStop {
|
|
1542
|
+
color: HexColor;
|
|
1543
|
+
/** 0-100. Optional. */
|
|
1544
|
+
position?: number;
|
|
1545
|
+
}
|
|
1546
|
+
/** Linear gradient. Missing `angle` = 0 (CSS: 0 = to top, clockwise). */
|
|
1547
|
+
interface GradientValue {
|
|
1548
|
+
angle?: number;
|
|
1549
|
+
stops: GradientStop[];
|
|
1550
|
+
}
|
|
1551
|
+
/** A solid hex color or a gradient. */
|
|
1552
|
+
type ColorValue = HexColor | GradientValue;
|
|
1553
|
+
/** Per-scheme color (field with `schemes: true`). `dark` falls back to `light`. */
|
|
1554
|
+
interface SchemedColor {
|
|
1555
|
+
light: ColorValue;
|
|
1556
|
+
dark?: ColorValue | null;
|
|
1557
|
+
}
|
|
1558
|
+
|
|
1559
|
+
/**
|
|
1560
|
+
* Resolves a stored color value for a scheme. Plain values (hex / gradient)
|
|
1561
|
+
* are returned as is; `{ light, dark? }` picks `dark ?? light` for 'dark',
|
|
1562
|
+
* otherwise `light`. Invalid input returns `null`.
|
|
1563
|
+
*/
|
|
1564
|
+
declare function resolveColor(value: unknown, scheme: 'light' | 'dark'): ColorValue | null;
|
|
1565
|
+
|
|
1566
|
+
/**
|
|
1567
|
+
* Native attestation contract — mirrors the iOS (App Attest / DeviceCheck) and
|
|
1568
|
+
* Android (Key Attestation / KeyStore) native modules. Adapted from Qafka's
|
|
1569
|
+
* `QafkaAttestation.ts`; the native binary is registered as `QafkaCmsAttestation`.
|
|
1570
|
+
*
|
|
1571
|
+
* The interface is tenant-agnostic (the challenge comes from the backend), which
|
|
1572
|
+
* is why Qafka's native code can be copied verbatim (QFK2-Q6 = A).
|
|
1573
|
+
*/
|
|
1574
|
+
interface NativeAttestationApi {
|
|
1575
|
+
/** Whether the native module is linked AND the device supports attestation. */
|
|
1576
|
+
isSupported(): Promise<boolean>;
|
|
1577
|
+
/** Whether the native module is registered at all (false → rebuild needed). */
|
|
1578
|
+
isAvailable(): boolean;
|
|
1579
|
+
generateKey(): Promise<string>;
|
|
1580
|
+
attestKey(keyId: string, challengeBase64: string): Promise<string>;
|
|
1581
|
+
generateAssertion(keyId: string, clientDataBase64: string): Promise<string>;
|
|
1582
|
+
generateKeyPair(alias: string, challengeBase64: string): Promise<void>;
|
|
1583
|
+
getAttestationCertChain(alias: string): Promise<string[]>;
|
|
1584
|
+
}
|
|
1585
|
+
|
|
1586
|
+
/**
|
|
1587
|
+
* Process-wide secure storage singleton. Resolves the native module once at
|
|
1588
|
+
* import; falls back to in-memory storage (with a dev warning) when the native
|
|
1589
|
+
* module is not linked.
|
|
1590
|
+
*/
|
|
1591
|
+
declare const storage: QafkaCmsStorage;
|
|
1592
|
+
|
|
1593
|
+
/**
|
|
1594
|
+
* Device attestation — iOS App Attest + Android Key Attestation.
|
|
1595
|
+
*
|
|
1596
|
+
* Adapted from Qafka's `AttestationManager.ts` (production-proven). The flow,
|
|
1597
|
+
* the stale-key self-heal heuristic, and the session-token refresh strategy are
|
|
1598
|
+
* copied verbatim (QFK2-Q6 = A); only the namespace, storage keys, the
|
|
1599
|
+
* `/v1/end-user/attest` endpoint, and the `X-Project-Slug` header differ.
|
|
1600
|
+
*
|
|
1601
|
+
* Native module, secure storage, fetch and the platform are injected so the
|
|
1602
|
+
* whole class is unit-testable without the React Native runtime.
|
|
1603
|
+
*/
|
|
1604
|
+
interface AttestationConfig {
|
|
1605
|
+
apiUrl: string;
|
|
1606
|
+
/** Resolves the backend project for the (pre-auth) attestation handshake. */
|
|
1607
|
+
projectSlug?: string;
|
|
1608
|
+
/** Project publishable key (`qpk_…`) — sent as `X-Project-Key` when set. */
|
|
1609
|
+
publishableKey?: string;
|
|
1610
|
+
/** Project id (UUID) — sent as `X-Project-Id` when set. */
|
|
1611
|
+
projectId?: string;
|
|
1612
|
+
/** Dev key (`__DEV__` only) — never present in release builds. */
|
|
1613
|
+
apiKey?: string | null;
|
|
1614
|
+
debug?: boolean;
|
|
1615
|
+
}
|
|
1616
|
+
interface AttestationDeps {
|
|
1617
|
+
native: NativeAttestationApi;
|
|
1618
|
+
storage: Pick<typeof storage, 'getItem' | 'setItem' | 'removeItem'>;
|
|
1619
|
+
fetch: (url: string, init: {
|
|
1620
|
+
method: string;
|
|
1621
|
+
headers: Record<string, string>;
|
|
1622
|
+
body: string;
|
|
1623
|
+
}) => Promise<Response>;
|
|
1624
|
+
platformOS: string;
|
|
1625
|
+
now: () => number;
|
|
1626
|
+
}
|
|
1627
|
+
declare class AttestationManager {
|
|
1628
|
+
private readonly config;
|
|
1629
|
+
private readonly d;
|
|
1630
|
+
private sessionToken;
|
|
1631
|
+
private keyId;
|
|
1632
|
+
/** The attestation/assertion in flight; concurrent callers share it. */
|
|
1633
|
+
private inflight;
|
|
1634
|
+
constructor(config: AttestationConfig, deps?: Partial<AttestationDeps>);
|
|
1635
|
+
initialize(): Promise<void>;
|
|
1636
|
+
/**
|
|
1637
|
+
* Run one attestation operation at a time. A second caller joins the one in
|
|
1638
|
+
* flight instead of starting its own: attesting a key twice makes Apple
|
|
1639
|
+
* refuse it and the stale-key path would mint an extra key.
|
|
1640
|
+
*/
|
|
1641
|
+
private exclusive;
|
|
1642
|
+
private doInitialize;
|
|
1643
|
+
/**
|
|
1644
|
+
* iOS start: an attested key is reused through an assertion (Apple allows a
|
|
1645
|
+
* single attestation per key); without one a new key is attested.
|
|
1646
|
+
*/
|
|
1647
|
+
private initializeIos;
|
|
1648
|
+
/**
|
|
1649
|
+
* Assertion with the stored key. Network, server (5xx) and project errors say
|
|
1650
|
+
* nothing about the key: keep it and propagate. Anything else (key unknown to
|
|
1651
|
+
* the server, key invalid on this device after a restore) starts a new key.
|
|
1652
|
+
*/
|
|
1653
|
+
private assertOrReattestIos;
|
|
1654
|
+
/**
|
|
1655
|
+
* Generate and attest a new key; it is stored only once the server accepted
|
|
1656
|
+
* it, so a failed attempt never leaves an unattested key behind.
|
|
1657
|
+
*/
|
|
1658
|
+
private attestNewIosKey;
|
|
1659
|
+
private performIosAttestation;
|
|
1660
|
+
private performIosAssertion;
|
|
1661
|
+
private performAndroidAttestation;
|
|
1662
|
+
getSessionToken(): Promise<string | null>;
|
|
1663
|
+
/** Called by the transport when the backend signals a refresh (429 / budget). */
|
|
1664
|
+
refresh(): Promise<string | null>;
|
|
1665
|
+
/**
|
|
1666
|
+
* Replace the session with a new one started after this call and return its
|
|
1667
|
+
* token. Unlike {@link refresh} it rejects on failure, so callers never keep a
|
|
1668
|
+
* stale token by accident. `null` only in dev-bypass (there is no session).
|
|
1669
|
+
*/
|
|
1670
|
+
forceRefresh(): Promise<string | null>;
|
|
1671
|
+
private refreshSession;
|
|
1672
|
+
isDevBypass(): boolean;
|
|
1673
|
+
reset(): Promise<void>;
|
|
1674
|
+
private setSession;
|
|
1675
|
+
private getHeaders;
|
|
1676
|
+
private requestChallenge;
|
|
1677
|
+
private submitAttestation;
|
|
1678
|
+
private base;
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
/**
|
|
1682
|
+
* Native push contract (E57) — collects the platform push token with **zero
|
|
1683
|
+
* host-app dependencies**:
|
|
1684
|
+
*
|
|
1685
|
+
* - iOS → raw APNs token via `UNUserNotificationCenter` +
|
|
1686
|
+
* `registerForRemoteNotifications`. No Firebase iOS SDK.
|
|
1687
|
+
* - Android → FCM token via a **secondary** `FirebaseApp` the SDK initializes
|
|
1688
|
+
* programmatically from the tenant's public client config (apiKey / appId /
|
|
1689
|
+
* senderId / projectId, delivered by config-sync). The host app's own
|
|
1690
|
+
* Firebase, if any, is untouched — we never claim the default app or its
|
|
1691
|
+
* `FirebaseMessagingService`, so we only *read* a token, never intercept
|
|
1692
|
+
* messages (out of scope for E57).
|
|
1693
|
+
*
|
|
1694
|
+
* Native module registered as `QafkaCmsPush`. Tenant-agnostic on iOS; on Android
|
|
1695
|
+
* the sender config is passed per call so the token is scoped to the right
|
|
1696
|
+
* project. Injected as `deps.native` so the manager is unit-testable without RN.
|
|
1697
|
+
*/
|
|
1698
|
+
/** Tenant Firebase Android *public* client config (never the secret service account). */
|
|
1699
|
+
interface AndroidPushConfig {
|
|
1700
|
+
apiKey: string;
|
|
1701
|
+
/** Firebase Android applicationId (mobilesdk_app_id), e.g. `1:123:android:abc`. */
|
|
1702
|
+
appId: string;
|
|
1703
|
+
/** FCM sender id (messagingSenderId / project number). */
|
|
1704
|
+
senderId: string;
|
|
1705
|
+
/** Firebase projectId. */
|
|
1706
|
+
projectId: string;
|
|
1707
|
+
}
|
|
1708
|
+
type PushPermissionStatus = 'granted' | 'denied' | 'undetermined';
|
|
1709
|
+
interface DeviceInfo {
|
|
1710
|
+
/** OS marketing version string, e.g. `iOS 17.4` / `Android 14`. */
|
|
1711
|
+
osVersion: string;
|
|
1712
|
+
/** Hardware model identifier, e.g. `iPhone15,3` / `Pixel 8`. */
|
|
1713
|
+
model: string;
|
|
1714
|
+
/** Manufacturer / brand, e.g. `Apple` / `Samsung`. */
|
|
1715
|
+
brand: string;
|
|
1716
|
+
}
|
|
1717
|
+
interface NativePushApi {
|
|
1718
|
+
/** Whether the native module is registered at all (false → rebuild needed). */
|
|
1719
|
+
isAvailable(): boolean;
|
|
1720
|
+
/** Current OS notification-permission state without prompting. */
|
|
1721
|
+
getPermissionStatus(): Promise<PushPermissionStatus>;
|
|
1722
|
+
/** Prompt the user for notification permission; resolves with the new state. */
|
|
1723
|
+
requestPermission(): Promise<PushPermissionStatus>;
|
|
1724
|
+
/**
|
|
1725
|
+
* Resolve the current push token. On Android the secondary FirebaseApp is
|
|
1726
|
+
* (re)initialized from `androidConfig`; on iOS the argument is ignored. Returns
|
|
1727
|
+
* null when permission is missing or the token cannot be obtained.
|
|
1728
|
+
*/
|
|
1729
|
+
getToken(androidConfig?: AndroidPushConfig): Promise<string | null>;
|
|
1730
|
+
/** Static device metadata for the device record. */
|
|
1731
|
+
getDeviceInfo(): Promise<DeviceInfo>;
|
|
1732
|
+
}
|
|
1733
|
+
|
|
1734
|
+
/**
|
|
1735
|
+
* Device registration (E57). Owns the device's identity on this install and
|
|
1736
|
+
* keeps the backend `Device` row in sync. Two-phase by design:
|
|
1737
|
+
*
|
|
1738
|
+
* 1. {@link init} (silent, no permission prompt) — ensure a stable `deviceId`,
|
|
1739
|
+
* capture metadata, and register the device with `token` omitted. Runs at
|
|
1740
|
+
* boot; the host shows no OS dialog. If permission was already granted in a
|
|
1741
|
+
* prior session, the token is (re)fetched here too — covering rotation.
|
|
1742
|
+
* 2. {@link requestPermission} (explicit user action) — prompt for notification
|
|
1743
|
+
* permission, then fetch the push token and patch the row.
|
|
1744
|
+
*
|
|
1745
|
+
* Ownership follows the request's identity: the transport attaches the bearer
|
|
1746
|
+
* when a session exists, so a logged-in re-register binds the row to that
|
|
1747
|
+
* end-user and a logged-out one clears it — hence we re-register on every auth
|
|
1748
|
+
* change. The class is fully injected (native, storage, transport, auth) so it
|
|
1749
|
+
* unit-tests without the React Native runtime.
|
|
1750
|
+
*/
|
|
1751
|
+
interface DeviceRegistrationState {
|
|
1752
|
+
permission: PushPermissionStatus;
|
|
1753
|
+
/** Stable client-generated id for this install (null until {@link init}). */
|
|
1754
|
+
deviceId: string | null;
|
|
1755
|
+
/** Current push token (null until permission is granted). */
|
|
1756
|
+
token: string | null;
|
|
1757
|
+
}
|
|
1758
|
+
interface DeviceRegisterBody {
|
|
1759
|
+
deviceId: string;
|
|
1760
|
+
platform: 'ios' | 'android';
|
|
1761
|
+
provider: 'apns' | 'fcm';
|
|
1762
|
+
/** Omitted in phase 1; the backend leaves an existing token untouched. */
|
|
1763
|
+
token?: string;
|
|
1764
|
+
osVersion?: string;
|
|
1765
|
+
model?: string;
|
|
1766
|
+
brand?: string;
|
|
1767
|
+
}
|
|
1768
|
+
interface DeviceRegistrationConfig {
|
|
1769
|
+
debug?: boolean;
|
|
1770
|
+
}
|
|
1771
|
+
interface DeviceRegistrationDeps {
|
|
1772
|
+
native: NativePushApi;
|
|
1773
|
+
storage: Pick<typeof storage, 'getItem' | 'setItem' | 'removeItem'>;
|
|
1774
|
+
/**
|
|
1775
|
+
* POST the device to `/v1/end-user/devices`. The transport attaches the three
|
|
1776
|
+
* trust axes (bearer if signed in, attestation session token, project slug).
|
|
1777
|
+
*/
|
|
1778
|
+
registerDevice: (body: DeviceRegisterBody) => Promise<unknown>;
|
|
1779
|
+
/**
|
|
1780
|
+
* Subscribe to auth changes (login / logout / refresh) to re-register so the
|
|
1781
|
+
* backend re-binds or clears `endUserId`. Returns an unsubscribe.
|
|
1782
|
+
*/
|
|
1783
|
+
subscribeAuth?: (listener: () => void) => () => void;
|
|
1784
|
+
/** Android FCM public client config from config-sync; iOS ignores it. */
|
|
1785
|
+
getAndroidPushConfig?: () => AndroidPushConfig | null;
|
|
1786
|
+
platformOS: string;
|
|
1787
|
+
/** Generate a stable device id (UUID v4). Injectable for deterministic tests. */
|
|
1788
|
+
generateDeviceId: () => string;
|
|
1789
|
+
}
|
|
1790
|
+
type RequiredDeps = Pick<DeviceRegistrationDeps, 'registerDevice'> & Partial<DeviceRegistrationDeps>;
|
|
1791
|
+
declare class DeviceRegistrationManager {
|
|
1792
|
+
private readonly config;
|
|
1793
|
+
private readonly d;
|
|
1794
|
+
private state;
|
|
1795
|
+
private readonly listeners;
|
|
1796
|
+
private unsubscribeAuth;
|
|
1797
|
+
private initialized;
|
|
1798
|
+
constructor(config: DeviceRegistrationConfig, deps: RequiredDeps);
|
|
1799
|
+
/** Phase 1 — silent metadata registration; idempotent across calls. */
|
|
1800
|
+
init(): Promise<void>;
|
|
1801
|
+
/** Phase 2 — prompt for permission, then collect + register the token. */
|
|
1802
|
+
requestPermission(): Promise<PushPermissionStatus>;
|
|
1803
|
+
getDeviceState(): DeviceRegistrationState;
|
|
1804
|
+
/** Observe device-state changes (for the `usePush` hook). Returns unsubscribe. */
|
|
1805
|
+
subscribe(listener: () => void): () => void;
|
|
1806
|
+
/** Detach the auth subscription. Call when tearing down the client. */
|
|
1807
|
+
dispose(): void;
|
|
1808
|
+
private platform;
|
|
1809
|
+
private provider;
|
|
1810
|
+
private ensureDeviceId;
|
|
1811
|
+
private fetchToken;
|
|
1812
|
+
private register;
|
|
1813
|
+
private setState;
|
|
1814
|
+
private warn;
|
|
1815
|
+
}
|
|
1816
|
+
|
|
1817
|
+
/**
|
|
1818
|
+
* Loads the dev-only runtime config bundled with the package
|
|
1819
|
+
* (`qafkacms.config.js`). Adapted from Qafka's `runtime-config-loader`.
|
|
1820
|
+
*
|
|
1821
|
+
* This is the FALLBACK source. The CLI no longer overwrites this package file
|
|
1822
|
+
* (node_modules gets wiped on install); it writes the real dev key to the
|
|
1823
|
+
* project root `.qafkacms/qafkacms-runtime.js`, which the consumer passes via
|
|
1824
|
+
* `config.devConfig` and `resolveRuntimeConfigSource` prefers. The shipped
|
|
1825
|
+
* placeholder only guarantees the `require` here never throws. In release builds
|
|
1826
|
+
* `__DEV__` dead-code-elimination strips the call site, so no dev key ships.
|
|
1827
|
+
*/
|
|
1828
|
+
interface RuntimeProjectEntry {
|
|
1829
|
+
/** The project's TEST API key, used by the SDK in dev builds. */
|
|
1830
|
+
developmentKey?: string;
|
|
1831
|
+
}
|
|
1832
|
+
interface RuntimeConfig {
|
|
1833
|
+
defaultProjectId?: string;
|
|
1834
|
+
apiUrl?: string;
|
|
1835
|
+
projects: Record<string, RuntimeProjectEntry>;
|
|
1836
|
+
}
|
|
1837
|
+
|
|
1838
|
+
/** Public configuration passed by the host app to `createClient`. */
|
|
1839
|
+
interface QafkaCmsConfig {
|
|
1840
|
+
/** Backend base URL (no `/v1/...` suffix). Optional in dev — resolved from the dev config. */
|
|
1841
|
+
apiUrl?: string;
|
|
1842
|
+
/**
|
|
1843
|
+
* Project publishable key (`qpk_…`). Optional when `projectId` is set. Sent as
|
|
1844
|
+
* `X-Project-Key` on anonymous requests.
|
|
1845
|
+
*/
|
|
1846
|
+
publishableKey?: string;
|
|
1847
|
+
/** Optional project label (`X-Project-Slug`). */
|
|
1848
|
+
projectSlug?: string;
|
|
1849
|
+
/**
|
|
1850
|
+
* The project's id (UUID) from the dashboard; identifies the project on mobile
|
|
1851
|
+
* (sent as `X-Project-Id`, with attestation proof), also selects the dev config.
|
|
1852
|
+
*/
|
|
1853
|
+
projectId?: string;
|
|
1854
|
+
/** Explicit dev API key override (rarely needed). */
|
|
1855
|
+
apiKey?: string | null;
|
|
1856
|
+
/**
|
|
1857
|
+
* Durable dev config the CLI writes to `<projectRoot>/.qafkacms/qafkacms-runtime.js`.
|
|
1858
|
+
* Wire it `__DEV__`-gated so Metro strips it from release bundles:
|
|
1859
|
+
* `devConfig: __DEV__ ? require('./.qafkacms/qafkacms-runtime') : undefined`
|
|
1860
|
+
* A package cannot reliably require a project-root file through Metro, so the
|
|
1861
|
+
* consumer passes it in. Takes precedence over the bundled placeholder.
|
|
1862
|
+
*/
|
|
1863
|
+
devConfig?: RuntimeConfig | null;
|
|
1864
|
+
/**
|
|
1865
|
+
* Build-time embedded config snapshots (E58). Lets the SDK-managed `locales`
|
|
1866
|
+
* and `i18n` domains paint real translations on a cold start (empty storage,
|
|
1867
|
+
* no network) instead of raw keys. Each carries its `version` so the runtime
|
|
1868
|
+
* supersedes it only when the server is newer. Produced (committed, not
|
|
1869
|
+
* gitignored) by `qafka cms config pull` and wired as e.g.
|
|
1870
|
+
* `bootstrap: { i18n: require('./qafkacms/i18n.json'), locales: require('./qafkacms/locales.json') }`
|
|
1871
|
+
*/
|
|
1872
|
+
bootstrap?: {
|
|
1873
|
+
i18n?: {
|
|
1874
|
+
version: number;
|
|
1875
|
+
data: I18nData;
|
|
1876
|
+
};
|
|
1877
|
+
locales?: {
|
|
1878
|
+
version: number;
|
|
1879
|
+
data: LocalesData;
|
|
1880
|
+
};
|
|
1881
|
+
};
|
|
1882
|
+
/**
|
|
1883
|
+
* Poll cadence (ms) for the SDK-managed config domains (`locales`, `i18n`).
|
|
1884
|
+
* One knob for everyone — individual `createConfigSync` calls can still
|
|
1885
|
+
* override. Clamped to a safe floor (`MIN_POLL_INTERVAL_MS`); a value below it
|
|
1886
|
+
* is raised, so apps cannot accidentally hammer the backend. Default ~60s.
|
|
1887
|
+
*/
|
|
1888
|
+
configPollIntervalMs?: number;
|
|
1889
|
+
/**
|
|
1890
|
+
* External identity provider (E44): returns a fresh token from your own auth
|
|
1891
|
+
* system, or `null` when that session is over. Called when the CMS access
|
|
1892
|
+
* token expires and after an app restart for sessions started with
|
|
1893
|
+
* `auth.signInWithExternalToken`.
|
|
1894
|
+
*/
|
|
1895
|
+
externalTokenProvider?: () => Promise<string | null>;
|
|
1896
|
+
/**
|
|
1897
|
+
* Default external provider key (`authConfig.externalProviders[].key`, E72)
|
|
1898
|
+
* sent as `provider` by `auth.signInWithExternalToken` / `linkExternal` when
|
|
1899
|
+
* the call passes none. A per-call `{ provider }` always wins. Leave unset to
|
|
1900
|
+
* let the server route (single enabled provider, or by token issuer).
|
|
1901
|
+
*/
|
|
1902
|
+
externalProvider?: string;
|
|
1903
|
+
/**
|
|
1904
|
+
* Anonymous end-users (QFK2-T322; the project must enable anonymous auth).
|
|
1905
|
+
* `'manual'` (default): the SDK never creates one; call
|
|
1906
|
+
* `auth.signInAnonymously()` yourself. `'auto'`: `initialize()` creates one
|
|
1907
|
+
* when no session is stored, and after `logout()` / `deleteAccount()` a new
|
|
1908
|
+
* one is created lazily on the next request that needs a token.
|
|
1909
|
+
*/
|
|
1910
|
+
anonymousAuth?: AnonymousAuthMode;
|
|
1911
|
+
/**
|
|
1912
|
+
* Transport of `live` content hooks that name no `mode` (QFK2-E76):
|
|
1913
|
+
* `'auto'` (default; SSE, polling as fallback), `'sse'` or `'poll'`.
|
|
1914
|
+
*/
|
|
1915
|
+
contentLiveDefault?: ContentLiveMode;
|
|
1916
|
+
/**
|
|
1917
|
+
* Launch version gate (QFK2-E59), opt-in. Stale cached `useContent` /
|
|
1918
|
+
* `useContentItem` reads of a collection with its change signal on (and no
|
|
1919
|
+
* `expand`) ask the collection version first and skip the download while it
|
|
1920
|
+
* is unchanged, at most `maxAgeMs` (default 24 h) since the last real
|
|
1921
|
+
* validation. `true` = 24 h. Default off.
|
|
1922
|
+
*/
|
|
1923
|
+
contentVersionGate?: ContentVersionGateOption;
|
|
1924
|
+
/**
|
|
1925
|
+
* The app version sent as `X-App-Version` (QFK2-E59): the server can hide
|
|
1926
|
+
* records and blocks the app is too old (or too new) for. Default: the
|
|
1927
|
+
* native app version (iOS `CFBundleShortVersionString`, Android
|
|
1928
|
+
* `versionName`). Override with a string; `null` sends none. Only a valid
|
|
1929
|
+
* app version (1–4 numeric segments, e.g. `1.4.2`) is sent.
|
|
1930
|
+
*/
|
|
1931
|
+
appVersion?: string | null;
|
|
1932
|
+
/**
|
|
1933
|
+
* Content bundle (QFK2-E59 T466), opt-in: `true` or `{ storage?, locale?, initial? }`
|
|
1934
|
+
* enables `client.bundle`, an offline snapshot of the collections the
|
|
1935
|
+
* project put in its bundle (admin: collection → "Add to content bundle").
|
|
1936
|
+
* `storage`: a plain key/value store (AsyncStorage / an MMKV adapter) the
|
|
1937
|
+
* file is persisted in; without it the bundle lives in memory for the app
|
|
1938
|
+
* session (never in the secure store). `locale` default: the active locale;
|
|
1939
|
+
* `initial`: a build-time embedded bundle file, used until a newer version is
|
|
1940
|
+
* stored. Default off.
|
|
1941
|
+
*/
|
|
1942
|
+
contentBundle?: ContentBundleOption;
|
|
1943
|
+
/**
|
|
1944
|
+
* Plain key/value store for cached data (QFK2-T471), opt-in: `AsyncStorage`
|
|
1945
|
+
* as is, or an MMKV adapter (`getItem` / `setItem` / `removeItem` /
|
|
1946
|
+
* `multiRemove`, all async). When set, `persist: true` queries, config-sync
|
|
1947
|
+
* snapshots, the saved locale and (without its own `storage`) the content
|
|
1948
|
+
* bundle are kept here instead of the SDK's secure store. Session data
|
|
1949
|
+
* (refresh token, unlock tokens, attestation, device id) stays in the secure
|
|
1950
|
+
* store. Existing secure copies move over the first time they are read, so
|
|
1951
|
+
* nothing is lost on the switch. Default: the secure store (keep persisted
|
|
1952
|
+
* data small then).
|
|
1953
|
+
*/
|
|
1954
|
+
cacheStorage?: CacheStorage;
|
|
1955
|
+
}
|
|
1956
|
+
/** Injectable dependencies — defaults wire the real RN runtime; tests override. */
|
|
1957
|
+
interface QafkaCmsClientDeps {
|
|
1958
|
+
fetch?: (url: string, init: {
|
|
1959
|
+
method: string;
|
|
1960
|
+
headers: Record<string, string>;
|
|
1961
|
+
body?: string;
|
|
1962
|
+
}) => Promise<Response>;
|
|
1963
|
+
storage?: QafkaCmsStorage;
|
|
1964
|
+
attestationNative?: NativeAttestationApi;
|
|
1965
|
+
/** Native push module (E57); defaults to the real `QafkaCmsPush` bridge. */
|
|
1966
|
+
pushNative?: NativePushApi;
|
|
1967
|
+
platformOS?: string;
|
|
1968
|
+
connectSse?: ConnectSse;
|
|
1969
|
+
/** Foreground/background source for config polling; defaults to RN AppState. */
|
|
1970
|
+
appState?: AppStateProvider;
|
|
1971
|
+
now?: () => number;
|
|
1972
|
+
}
|
|
1973
|
+
|
|
1974
|
+
/**
|
|
1975
|
+
* Top-level SDK client. Wires the five Foundation layers together and exposes
|
|
1976
|
+
* `auth`, `content`, `attestation` and a `createConfigSync` factory. Both trust
|
|
1977
|
+
* axes (end-user JWT + device attestation) are injected into the transport, so
|
|
1978
|
+
* every request carries whatever credentials are currently available.
|
|
1979
|
+
*
|
|
1980
|
+
* Construct via {@link createClient}; call {@link initialize} once at app boot.
|
|
1981
|
+
*/
|
|
1982
|
+
declare class QafkaCmsClient {
|
|
1983
|
+
readonly attestation: AttestationManager;
|
|
1984
|
+
readonly auth: AuthClient;
|
|
1985
|
+
readonly content: ContentClient;
|
|
1986
|
+
/**
|
|
1987
|
+
* Device registration (E57): native push-token collection + the backend
|
|
1988
|
+
* `Device` row. Phase 1 (metadata) runs automatically on {@link initialize};
|
|
1989
|
+
* the host calls `deviceRegistration.requestPermission()` (or the `usePush`
|
|
1990
|
+
* hook) to prompt for notifications and collect the token. Dependency-free on
|
|
1991
|
+
* the host: iOS uses raw APNs, Android a SDK-bundled secondary FirebaseApp.
|
|
1992
|
+
*/
|
|
1993
|
+
readonly deviceRegistration: DeviceRegistrationManager;
|
|
1994
|
+
/**
|
|
1995
|
+
* Active-language runtime (E55): holds the selected locale, the supported
|
|
1996
|
+
* locale set (`locales` domain) and UI strings (`i18n` domain), and resolves
|
|
1997
|
+
* `t(key)`. Fed by SDK-managed config-sync on {@link initialize}. The React
|
|
1998
|
+
* `useLocale`/`useTranslation` hooks subscribe to it.
|
|
1999
|
+
*/
|
|
2000
|
+
readonly language: LanguageManager;
|
|
2001
|
+
/**
|
|
2002
|
+
* Live content change signals (QFK2-E76): the hub behind `live` on
|
|
2003
|
+
* `useContent` / `useContentItem` — one multiplexed SSE stream (XHR) or
|
|
2004
|
+
* version polling per client. Nothing runs until something is watched.
|
|
2005
|
+
* `status()` → `'sse' | 'polling' | 'idle'` (debug).
|
|
2006
|
+
*/
|
|
2007
|
+
readonly contentChanges: ContentChangesApi;
|
|
2008
|
+
/**
|
|
2009
|
+
* Resolved `contentVersionGate` config (QFK2-E59): `{ maxAgeMs }`, or `null`
|
|
2010
|
+
* when off (the default). The provider gates expand-less content reads on it.
|
|
2011
|
+
*/
|
|
2012
|
+
readonly contentVersionGate: ContentVersionGate | null;
|
|
2013
|
+
/**
|
|
2014
|
+
* App version sent as `X-App-Version` (QFK2-E59): `config.appVersion`, else
|
|
2015
|
+
* the native app version; `null` when none / not a valid app version.
|
|
2016
|
+
*/
|
|
2017
|
+
readonly appVersion: string | null;
|
|
2018
|
+
/**
|
|
2019
|
+
* Content bundle (QFK2-E59 T466): the offline snapshot of the collections
|
|
2020
|
+
* the project put in its bundle — `sync()`, `rows(collection)`,
|
|
2021
|
+
* `get(collection, id)`, `subscribe`. Present only with `contentBundle`.
|
|
2022
|
+
* Persisted only in `contentBundle.storage`, else {@link cacheStorage} when
|
|
2023
|
+
* `createClient({ cacheStorage })` is set (a plain AsyncStorage / MMKV store),
|
|
2024
|
+
* never in the secure {@link storage}; without either it lives in memory for
|
|
2025
|
+
* the app session. The Provider syncs it at boot, on foreground and on
|
|
2026
|
+
* locale change.
|
|
2027
|
+
*/
|
|
2028
|
+
readonly bundle?: ContentBundleApi;
|
|
2029
|
+
/** Platform-neutral core (transport, auth, content, language, config-sync) — QFK2-E73. */
|
|
2030
|
+
private readonly core;
|
|
2031
|
+
private readonly proof;
|
|
2032
|
+
/**
|
|
2033
|
+
* Per-project public push client config (E57). Android only — the FCM sender
|
|
2034
|
+
* id / app id the SDK needs to mint a token from a secondary FirebaseApp. iOS
|
|
2035
|
+
* (raw APNs) needs nothing, so this is only started + read on Android.
|
|
2036
|
+
*/
|
|
2037
|
+
private readonly pushConfigSync;
|
|
2038
|
+
/**
|
|
2039
|
+
* The SDK's own native secure storage (iOS Keychain / Android
|
|
2040
|
+
* EncryptedSharedPreferences). Holds the session: refresh token, unlock
|
|
2041
|
+
* tokens, attestation key id, device id. Without `createClient({ cacheStorage })`
|
|
2042
|
+
* it also holds the cached data ({@link cacheStorage} is then this store):
|
|
2043
|
+
* keep persisted payloads small (reference data like categories) then.
|
|
2044
|
+
*/
|
|
2045
|
+
readonly storage: QafkaCmsStorage;
|
|
2046
|
+
/**
|
|
2047
|
+
* Where cached data lives (QFK2-T471): `persist: true` queries (the Provider
|
|
2048
|
+
* reads this), config-sync snapshots, the saved locale and, without its own
|
|
2049
|
+
* `contentBundle.storage`, the content bundle. With
|
|
2050
|
+
* `createClient({ cacheStorage })` it is that plain store, reading through to
|
|
2051
|
+
* the secure store once per key so copies an earlier SDK kept there move over;
|
|
2052
|
+
* otherwise it is {@link storage}.
|
|
2053
|
+
*/
|
|
2054
|
+
readonly cacheStorage: CacheStorage;
|
|
2055
|
+
private warnedNoProof;
|
|
2056
|
+
/**
|
|
2057
|
+
* Bundle files never belong in the secure store (up to 20 MB each). Pre-release
|
|
2058
|
+
* builds wrote them there: remove such leftovers (one read when none exist).
|
|
2059
|
+
*/
|
|
2060
|
+
private dropSecureBundleCopies;
|
|
2061
|
+
constructor(config: QafkaCmsConfig, deps?: QafkaCmsClientDeps);
|
|
2062
|
+
/**
|
|
2063
|
+
* Hydrate the persisted session, run device attestation, then start the
|
|
2064
|
+
* language runtime (restore the saved locale + start the locales/i18n
|
|
2065
|
+
* config-sync). Call once at boot.
|
|
2066
|
+
*/
|
|
2067
|
+
initialize(): Promise<void>;
|
|
2068
|
+
/**
|
|
2069
|
+
* Project + proof headers for calling the QafkaCMS API with your own HTTP
|
|
2070
|
+
* client: `X-Project-Id` and/or `X-Project-Key`, `X-Project-Slug` (if set), and
|
|
2071
|
+
* `X-Session-Token` (release) or `x-api-key` (dev-bypass), plus
|
|
2072
|
+
* `X-Unlock-Token` when `content.lookup` has unlocked records (QFK2-E78; pass
|
|
2073
|
+
* `{ withUnlockTokens: false }` to leave it out), and `X-App-Version` when
|
|
2074
|
+
* {@link appVersion} is set (QFK2-E59). Initialises device
|
|
2075
|
+
* attestation and loads the persisted unlock tokens first if that has not
|
|
2076
|
+
* happened yet. Contains no `Authorization` or `Content-Type` — add the
|
|
2077
|
+
* end-user token and body headers yourself.
|
|
2078
|
+
*/
|
|
2079
|
+
getRequestHeaders(options?: {
|
|
2080
|
+
withUnlockTokens?: boolean;
|
|
2081
|
+
}): Promise<Record<string, string>>;
|
|
2082
|
+
/**
|
|
2083
|
+
* Force a fresh attestation session, then return {@link getRequestHeaders}.
|
|
2084
|
+
* On the first-ever call the initial attestation already is fresh, so it
|
|
2085
|
+
* attests once; later calls replace the existing session.
|
|
2086
|
+
*/
|
|
2087
|
+
refreshRequestHeaders(options?: {
|
|
2088
|
+
withUnlockTokens?: boolean;
|
|
2089
|
+
}): Promise<Record<string, string>>;
|
|
2090
|
+
/**
|
|
2091
|
+
* Build a config-sync client for one customization domain (translations,
|
|
2092
|
+
* theme, navigation, …). Each shares the SDK's transport and storage.
|
|
2093
|
+
*
|
|
2094
|
+
* Transport defaults to **polling** — config rarely changes and a persistent
|
|
2095
|
+
* SSE per domain does not scale (one held connection per app per domain). Pass
|
|
2096
|
+
* `live: true` only for a domain that genuinely needs sub-second push (e.g. a
|
|
2097
|
+
* kill-switch flag); everything else polls (see E56).
|
|
2098
|
+
*/
|
|
2099
|
+
createConfigSync<T>(domain: string, buildTimeDefault: T, options?: {
|
|
2100
|
+
pollIntervalMs?: number;
|
|
2101
|
+
live?: boolean;
|
|
2102
|
+
buildTimeVersion?: number;
|
|
2103
|
+
}): ConfigSyncClient<T>;
|
|
2104
|
+
}
|
|
2105
|
+
/** Create a QafkaCMS SDK client. */
|
|
2106
|
+
declare function createClient(config: QafkaCmsConfig, deps?: QafkaCmsClientDeps): QafkaCmsClient;
|
|
2107
|
+
|
|
2108
|
+
/**
|
|
2109
|
+
* A resource the provider warms into the cache at boot. `gate: true` resources
|
|
2110
|
+
* block the provider from becoming `ready` (and, when a `fallback` is set, hold
|
|
2111
|
+
* the UI) until they settle; the rest are fire-and-forget.
|
|
2112
|
+
*/
|
|
2113
|
+
interface PrefetchResource$1<T = unknown, C extends CoreClientLike = CoreClientLike> {
|
|
2114
|
+
key: QueryKey;
|
|
2115
|
+
fetch: (client: C) => Promise<T>;
|
|
2116
|
+
/** Freshness window for the warmed entry (e.g. `'1h'`). */
|
|
2117
|
+
ttl?: Duration | null;
|
|
2118
|
+
/** Persist the warmed entry to `cacheStorage`. */
|
|
2119
|
+
persist?: boolean;
|
|
2120
|
+
/** Block `ready` until this resolves. Default: false (background warm-up). */
|
|
2121
|
+
gate?: boolean;
|
|
2122
|
+
}
|
|
2123
|
+
|
|
2124
|
+
interface QafkaCmsProviderProps$1<C extends CoreClientLike = CoreClientLike> {
|
|
2125
|
+
/** The SDK client. Create it with `createClient(...)` so dependency injection stays in the app's hands. */
|
|
2126
|
+
client: C;
|
|
2127
|
+
/** Resources to warm at boot. See {@link PrefetchResource}. */
|
|
2128
|
+
prefetch?: readonly PrefetchResource$1<unknown, C>[];
|
|
2129
|
+
/** Default freshness window for queries that do not set their own `ttl`. */
|
|
2130
|
+
defaultTtl?: Duration | null;
|
|
2131
|
+
/** Cache fetch-error observer (logging/telemetry). */
|
|
2132
|
+
onCacheError?: (error: Error, key: string) => void;
|
|
2133
|
+
/** Rendered while initializing (incl. gating prefetch). Omit to render children immediately. */
|
|
2134
|
+
fallback?: ReactNode;
|
|
2135
|
+
/** Rendered on init/gating-prefetch failure. Omit to render children (errors surface via hooks). */
|
|
2136
|
+
errorFallback?: ReactNode | ((error: Error, retry: () => void) => ReactNode);
|
|
2137
|
+
children?: ReactNode;
|
|
2138
|
+
}
|
|
2139
|
+
|
|
2140
|
+
/** Boot lifecycle phase owned by {@link QafkaCmsProvider}. */
|
|
2141
|
+
type QafkaCmsStatus = 'initializing' | 'ready' | 'error';
|
|
2142
|
+
interface QafkaCmsContextValue$1<C extends CoreClientLike = CoreClientLike> {
|
|
2143
|
+
/** The SDK client instance the app passed to the provider. */
|
|
2144
|
+
client: C;
|
|
2145
|
+
/** Shared reactive query cache backing the data hooks. */
|
|
2146
|
+
cache: QueryCache;
|
|
2147
|
+
status: QafkaCmsStatus;
|
|
2148
|
+
/** Set when `status === 'error'` (init or a gating prefetch failed). */
|
|
2149
|
+
error: Error | null;
|
|
2150
|
+
/** Re-run the boot sequence (initialize + gating prefetch). */
|
|
2151
|
+
retry: () => void;
|
|
2152
|
+
/** Drop all cached data + persisted copies. Call on logout. */
|
|
2153
|
+
clearCache: () => void;
|
|
2154
|
+
}
|
|
2155
|
+
/**
|
|
2156
|
+
* The shared reactive query cache — for manual invalidation, optimistic writes
|
|
2157
|
+
* (`setData`), prefetching, etc. Most apps use {@link useQuery}/`useMutation`
|
|
2158
|
+
* and never touch this directly.
|
|
2159
|
+
*/
|
|
2160
|
+
declare function useQafkaCmsCache(): QueryCache;
|
|
2161
|
+
|
|
2162
|
+
interface UseQueryOptions extends QueryOptions {
|
|
2163
|
+
/** When false the query does not fetch; it still serves whatever is cached. Default true. */
|
|
2164
|
+
enabled?: boolean;
|
|
2165
|
+
}
|
|
2166
|
+
interface UseQueryResult<T> extends QueryState<T> {
|
|
2167
|
+
/** Force a background refetch regardless of freshness. */
|
|
2168
|
+
refetch: () => Promise<void>;
|
|
2169
|
+
}
|
|
2170
|
+
|
|
2171
|
+
interface UseMutationOptions<TVars, TResult> {
|
|
2172
|
+
/**
|
|
2173
|
+
* Query keys to invalidate on success, **by prefix** (react-query style):
|
|
2174
|
+
* `[['content', 'posts']]` refreshes every cached `content.list('posts', …)`.
|
|
2175
|
+
* Pass a function to derive keys from the result/vars.
|
|
2176
|
+
*/
|
|
2177
|
+
invalidate?: QueryKey[] | ((result: TResult, vars: TVars) => QueryKey[]);
|
|
2178
|
+
onSuccess?: (result: TResult, vars: TVars) => void;
|
|
2179
|
+
onError?: (error: Error, vars: TVars) => void;
|
|
2180
|
+
}
|
|
2181
|
+
interface UseMutationResult<TVars, TResult> {
|
|
2182
|
+
/** Run the mutation. Resolves with the result, rejects on error (also reflected in state). */
|
|
2183
|
+
mutate: (vars: TVars) => Promise<TResult>;
|
|
2184
|
+
isPending: boolean;
|
|
2185
|
+
error: Error | undefined;
|
|
2186
|
+
data: TResult | undefined;
|
|
2187
|
+
reset: () => void;
|
|
2188
|
+
}
|
|
2189
|
+
|
|
2190
|
+
/**
|
|
2191
|
+
* `live` of the content hooks (QFK2-E76 §9.1). `true` = watch with the
|
|
2192
|
+
* client's `contentLiveDefault` (default `'auto'`: SSE when available,
|
|
2193
|
+
* polling otherwise). Off (absent / `false`) = plain TTL behavior.
|
|
2194
|
+
*/
|
|
2195
|
+
type ContentLiveOption = boolean | {
|
|
2196
|
+
mode?: ContentLiveMode;
|
|
2197
|
+
/** Other collections whose changes also refresh this query (e.g. an expanded relation). */
|
|
2198
|
+
also?: string[];
|
|
2199
|
+
/** Poll cadence while polling (default 60 s, floor 30 s). */
|
|
2200
|
+
pollIntervalMs?: number;
|
|
2201
|
+
};
|
|
2202
|
+
interface UseContentOptions extends Omit<UseQueryOptions, 'gate'> {
|
|
2203
|
+
/** Refresh on server change signals (the collection must enable its change signal). */
|
|
2204
|
+
live?: ContentLiveOption;
|
|
2205
|
+
}
|
|
2206
|
+
/**
|
|
2207
|
+
* Cached `content.list` for a collection. The cache key includes the params, so
|
|
2208
|
+
* different filters/pages are cached independently and shared across screens.
|
|
2209
|
+
* `options.live` also refreshes it on server change signals. Revalidation is a
|
|
2210
|
+
* conditional GET (QFK2-E59 D6): when the server answers 304 the cached data
|
|
2211
|
+
* (same object) is kept. With `contentVersionGate` on the client, an
|
|
2212
|
+
* expand-less read is version-gated (D8).
|
|
2213
|
+
*/
|
|
2214
|
+
declare function useContent<T = ContentRecord>(collection: string, params?: ListParams, options?: UseContentOptions): UseQueryResult<ListResult<T>>;
|
|
2215
|
+
/**
|
|
2216
|
+
* Cached `content.get` for a single record. Disabled (no fetch) until `id` is
|
|
2217
|
+
* truthy, so it is safe to call before the id is known. The cache key includes
|
|
2218
|
+
* the params, so an expanded and a plain read are cached independently.
|
|
2219
|
+
* `options.live` also refreshes it when this record changes. Revalidation is
|
|
2220
|
+
* conditional and version-gated, as in {@link useContent}.
|
|
2221
|
+
*/
|
|
2222
|
+
declare function useContentItem<T = ContentRecord>(collection: string, id: string | null | undefined, params?: GetParams, options?: UseContentOptions): UseQueryResult<T>;
|
|
2223
|
+
|
|
2224
|
+
/**
|
|
2225
|
+
* {@link useBundle}: `{ rows, version, isLoading, error }`. `version` is `null`
|
|
2226
|
+
* while no bundle is held (not synced yet, offline first run, none published);
|
|
2227
|
+
* `error` is the last sync error (the held rows stay available).
|
|
2228
|
+
*/
|
|
2229
|
+
interface UseBundleResult<T> extends ContentBundleView<T> {
|
|
2230
|
+
}
|
|
2231
|
+
/** {@link useBundleItem}: `{ data, version, isLoading, error }`; `data` is `null` when absent or hidden. */
|
|
2232
|
+
interface UseBundleItemResult<T> extends ContentBundleItemView<T> {
|
|
2233
|
+
}
|
|
2234
|
+
/**
|
|
2235
|
+
* Rows of one collection from the content bundle (QFK2-E59 T466): the offline
|
|
2236
|
+
* snapshot, filtered for `client.appVersion`. Re-renders when a new bundle
|
|
2237
|
+
* lands. Needs `createClient({ contentBundle })`; the Provider syncs it.
|
|
2238
|
+
*/
|
|
2239
|
+
declare function useBundle<T = ContentRecord>(collection: string): UseBundleResult<T>;
|
|
2240
|
+
/** One row of the content bundle by id (see {@link useBundle}). */
|
|
2241
|
+
declare function useBundleItem<T = ContentRecord>(collection: string, id: string | null | undefined): UseBundleItemResult<T>;
|
|
2242
|
+
|
|
2243
|
+
/** Variables for {@link useLookup}'s `mutate`. */
|
|
2244
|
+
interface UseLookupVars extends GetParams {
|
|
2245
|
+
collection: string;
|
|
2246
|
+
code: string;
|
|
2247
|
+
}
|
|
2248
|
+
/**
|
|
2249
|
+
* Unlock a code-locked record: `const l = useLookup(); await l.mutate({ collection, code })`.
|
|
2250
|
+
* Rejects with a `ProblemError` on a wrong code (404 `LOOKUP_NOT_FOUND`). Cached
|
|
2251
|
+
* queries revalidate automatically once the token is stored (Provider-wired).
|
|
2252
|
+
*/
|
|
2253
|
+
declare function useLookup<T = ContentRecord>(): UseMutationResult<UseLookupVars, LookupResult<T>>;
|
|
2254
|
+
|
|
2255
|
+
/**
|
|
2256
|
+
* Reactive end-user session: `{ isAuthenticated, userId, roles, isAnonymous }`.
|
|
2257
|
+
* Re-renders on login / token refresh / logout / anonymous upgrade. Backed by the SDK's `TokenStore` observable
|
|
2258
|
+
* (no polling). Branch UI on `roles` for tier-gated screens — the backend still
|
|
2259
|
+
* enforces what each tier can actually read/write.
|
|
2260
|
+
*/
|
|
2261
|
+
declare function useAuth(): AuthState;
|
|
2262
|
+
|
|
2263
|
+
interface UseLocaleResult {
|
|
2264
|
+
/** The active locale (the project default until one is chosen). */
|
|
2265
|
+
locale: string;
|
|
2266
|
+
/** Switch the active locale — persists + propagates app-wide. */
|
|
2267
|
+
setLocale: (locale: string) => Promise<void>;
|
|
2268
|
+
/** The project's supported locales (`locales` config domain). */
|
|
2269
|
+
availableLocales: string[];
|
|
2270
|
+
/** The project's default locale. */
|
|
2271
|
+
defaultLocale: string;
|
|
2272
|
+
}
|
|
2273
|
+
/**
|
|
2274
|
+
* Reactive access to the active language (E55). Re-renders whenever the locale,
|
|
2275
|
+
* the supported-locale set, or the UI strings change. Use this for a language
|
|
2276
|
+
* switcher; use {@link useTranslation} when you need `t()`.
|
|
2277
|
+
*/
|
|
2278
|
+
declare function useLocale(): UseLocaleResult;
|
|
2279
|
+
|
|
2280
|
+
interface UseTranslationResult {
|
|
2281
|
+
/** Resolve a UI string for the active locale (active → default → key fallback). */
|
|
2282
|
+
t: (key: string, params?: TranslateParams) => string;
|
|
2283
|
+
/** The active locale. */
|
|
2284
|
+
locale: string;
|
|
2285
|
+
/** Switch the active locale. */
|
|
2286
|
+
setLocale: (locale: string) => Promise<void>;
|
|
2287
|
+
}
|
|
2288
|
+
/**
|
|
2289
|
+
* Reactive translation hook (E55) — the SDK counterpart of Shopla's
|
|
2290
|
+
* `useTranslations`. `t()` resolves against the `i18n` config domain for the
|
|
2291
|
+
* active locale and re-renders when the locale or the strings change.
|
|
2292
|
+
*/
|
|
2293
|
+
declare function useTranslation(): UseTranslationResult;
|
|
2294
|
+
|
|
2295
|
+
/**
|
|
2296
|
+
* React Native view of the shared React layer (QFK2-E73 §4.3). The Provider and
|
|
2297
|
+
* hooks in `react/*` are generic over any `CoreClientLike`; the RN package
|
|
2298
|
+
* re-exports them narrowed to `QafkaCmsClient`, so the public signatures (and
|
|
2299
|
+
* AGENTS.md) stay exactly as before the core split.
|
|
2300
|
+
*/
|
|
2301
|
+
|
|
2302
|
+
/**
|
|
2303
|
+
* A resource the provider warms into the cache at boot. `gate: true` resources
|
|
2304
|
+
* block the provider from becoming `ready` (and, when a `fallback` is set, hold
|
|
2305
|
+
* the UI) until they settle; the rest are fire-and-forget.
|
|
2306
|
+
*/
|
|
2307
|
+
interface PrefetchResource<T = unknown> extends PrefetchResource$1<T, QafkaCmsClient> {
|
|
2308
|
+
}
|
|
2309
|
+
interface QafkaCmsContextValue extends QafkaCmsContextValue$1<QafkaCmsClient> {
|
|
2310
|
+
}
|
|
2311
|
+
interface QafkaCmsProviderProps extends Omit<QafkaCmsProviderProps$1<QafkaCmsClient>, 'prefetch'> {
|
|
2312
|
+
/** Resources to warm at boot. See {@link PrefetchResource}. */
|
|
2313
|
+
prefetch?: readonly PrefetchResource[];
|
|
2314
|
+
}
|
|
2315
|
+
/**
|
|
2316
|
+
* Shares the SDK client through context, owns the boot lifecycle (`initialize()`
|
|
2317
|
+
* + gating prefetch), and provides the reactive query cache the data hooks read.
|
|
2318
|
+
*
|
|
2319
|
+
* The client is created by the app and passed in; the provider does not build
|
|
2320
|
+
* it. Do not also call `client.initialize()` yourself — the provider owns it.
|
|
2321
|
+
*/
|
|
2322
|
+
declare const QafkaCmsProvider: (props: QafkaCmsProviderProps) => ReactNode;
|
|
2323
|
+
/** The SDK client instance. Throws when used outside a {@link QafkaCmsProvider}. */
|
|
2324
|
+
declare const useQafkaCmsClient: () => QafkaCmsClient;
|
|
2325
|
+
/** Boot lifecycle: `{ status, error, retry, clearCache }`. */
|
|
2326
|
+
declare const useQafkaCms: () => Pick<QafkaCmsContextValue, 'status' | 'error' | 'retry' | 'clearCache'>;
|
|
2327
|
+
/**
|
|
2328
|
+
* Subscribe a component to a cached query. Reads the shared cache via
|
|
2329
|
+
* `useSyncExternalStore` (so any consumer of the same key re-renders together)
|
|
2330
|
+
* and triggers a fetch on mount / key change through the cache, which handles
|
|
2331
|
+
* de-duplication, TTL, stale-while-revalidate, persistence and races.
|
|
2332
|
+
*/
|
|
2333
|
+
declare const useQuery: <T>(key: QueryKey, fetcher: (client: QafkaCmsClient) => Promise<T>, options?: UseQueryOptions) => UseQueryResult<T>;
|
|
2334
|
+
/**
|
|
2335
|
+
* Write helper with automatic, prefix-based cache invalidation. Pair it with
|
|
2336
|
+
* `useContent`/`useQuery`: after the mutation succeeds, the listed query keys
|
|
2337
|
+
* are invalidated, so any mounted screen showing that data revalidates and any
|
|
2338
|
+
* unmounted one refetches on next mount.
|
|
2339
|
+
*
|
|
2340
|
+
* const create = useMutation(
|
|
2341
|
+
* (c, vars: NewPost) => c.content.create('posts', vars),
|
|
2342
|
+
* { invalidate: [['content', 'posts']] },
|
|
2343
|
+
* );
|
|
2344
|
+
* await create.mutate({ title: 'Hello' });
|
|
2345
|
+
*
|
|
2346
|
+
* For optimistic updates, write through `useQafkaCmsCache().setData(...)`.
|
|
2347
|
+
*/
|
|
2348
|
+
declare const useMutation: <TVars = void, TResult = unknown>(mutationFn: (client: QafkaCmsClient, vars: TVars) => Promise<TResult>, options?: UseMutationOptions<TVars, TResult>) => UseMutationResult<TVars, TResult>;
|
|
2349
|
+
|
|
2350
|
+
interface UsePushResult extends DeviceRegistrationState {
|
|
2351
|
+
/**
|
|
2352
|
+
* Prompt for notification permission and, if granted, collect + register the
|
|
2353
|
+
* push token (phase 2). Safe to call from a button handler — this is where the
|
|
2354
|
+
* OS dialog appears, so the host controls *when* the user sees it. Resolves
|
|
2355
|
+
* with the resulting permission state.
|
|
2356
|
+
*/
|
|
2357
|
+
requestPermission: () => Promise<PushPermissionStatus>;
|
|
2358
|
+
}
|
|
2359
|
+
/**
|
|
2360
|
+
* Reactive push/device state: `{ permission, deviceId, token, requestPermission }`.
|
|
2361
|
+
* Re-renders when permission changes or the token is collected/rotated. The
|
|
2362
|
+
* device row is registered automatically at boot (phase 1, no prompt); call
|
|
2363
|
+
* `requestPermission()` to trigger the OS dialog and collect the token (phase 2).
|
|
2364
|
+
*/
|
|
2365
|
+
declare function usePush(): UsePushResult;
|
|
2366
|
+
|
|
2367
|
+
/** `resolveColor` using the device color scheme (unknown scheme = light). */
|
|
2368
|
+
declare function useResolvedColor(value: unknown): ColorValue | null;
|
|
2369
|
+
|
|
2370
|
+
/** Returns the running SDK version. */
|
|
2371
|
+
declare function getVersion(): string;
|
|
2372
|
+
|
|
2373
|
+
export { type AccessTokenClaims, type AndroidPushConfig, type AnonymousAuthMode, type AnonymousSignInResult, type AppStateProvider, AttestationManager, AuthClient, type AuthClientOptions, type AuthMethod, type AuthMethods, type AuthState, type AuthTokens, type BundleCollection, type BundleCollectionAppVersion, type BundleComponentInfo, type BundleFieldMeta, type BundleFile, CURRENT_USER, type CacheStorage, type ColorValue, type ConfigSnapshot, ConfigSyncClient, type ConnectSse, type ContentBundleApi, type ContentBundleConfig, type ContentBundleItemView, type ContentBundleOption, type ContentBundleStatus, type ContentBundleSyncResult, type ContentBundleView, type ContentChangesApi, type ContentChangesStatus, ContentClient, type ContentClientOptions, type ContentInvalidationTarget, type ContentLiveMode, type ContentLiveOption, type ContentRecord, type ContentWatchOptions, type ContentWatchTarget, type DeviceInfo, type DeviceRegisterBody, DeviceRegistrationManager, type DeviceRegistrationState, type Duration, type EndUser, type EndUserAuthMethod, type ExternalSignInResult, type FieldOps, type FilterNode, type FilterOp, type GetParams, type GradientStop, type GradientValue, type HexColor, type I18nData, type JoinResult, LanguageManager, type LanguageManagerDeps, type ListParams, type ListResult, type LocalesData, type LoginInput, type LookupResult, NOW, type NativePushApi, type PrefetchResource, type ProblemDetails, ProblemError, type PushPermissionStatus, QafkaCmsClient, type QafkaCmsClientDeps, type QafkaCmsConfig, type QafkaCmsContextValue, QafkaCmsProvider, type QafkaCmsProviderProps, type QafkaCmsStatus, type QuantifierOps, QueryCache, type QueryCacheOptions, type QueryKey, type QueryOptions, type QueryState, type QueryStatus, type RefreshResult, type RegisterInput, type RelationManyValue, type RelationManyWrite, SDK_VERSION, type SchemedColor, type SseConnection, type SseHandlers, type TranslateParams, UnlockTokenStore, type UpgradeInput, type UpgradeOutcome, type UpgradeResult, type UseBundleItemResult, type UseBundleResult, type UseContentOptions, type UseLocaleResult, type UseLookupVars, type UseMutationOptions, type UseMutationResult, type UsePushResult, type UseQueryOptions, type UseQueryResult, type UseTranslationResult, createClient, createMemoryCacheStorage, getVersion, now, parseDuration, resolveColor, serializeKey, useAuth, useBundle, useBundleItem, useContent, useContentItem, useLocale, useLookup, useMutation, usePush, useQafkaCms, useQafkaCmsCache, useQafkaCmsClient, useQuery, useResolvedColor, useTranslation };
|