pulse-updates 1.0.14 → 1.0.16
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/lib/commonjs/config.js +364 -0
- package/lib/commonjs/config.js.map +1 -0
- package/lib/commonjs/index.js +12 -0
- package/lib/commonjs/index.js.map +1 -1
- package/lib/module/config.js +342 -0
- package/lib/module/config.js.map +1 -0
- package/lib/module/index.js +1 -0
- package/lib/module/index.js.map +1 -1
- package/lib/typescript/config.d.ts +124 -0
- package/lib/typescript/config.d.ts.map +1 -0
- package/lib/typescript/index.d.ts +1 -0
- package/lib/typescript/index.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/config.ts +410 -0
- package/src/index.ts +1 -0
package/src/config.ts
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pulse Config — the client half of the Firebase Remote Config replacement.
|
|
3
|
+
*
|
|
4
|
+
* Why this exists: from 2026-09-01 Firebase bills every Remote Config fetch above
|
|
5
|
+
* 100k/day and throttles projects that stay on the free plan. Worse than the bill is
|
|
6
|
+
* the failure mode — the Firebase SDK yields the type's zero value for a key it does
|
|
7
|
+
* not hold, so a throttled fetch reads as "every flag is false" and, for an ads
|
|
8
|
+
* config, quietly turns the revenue off.
|
|
9
|
+
*
|
|
10
|
+
* The shape here deliberately mirrors what the apps already do with Remote Config —
|
|
11
|
+
* defaults, fetch, activate, typed getters — so swapping the source is a change of
|
|
12
|
+
* adapter, not of every call site. Three things are different on purpose:
|
|
13
|
+
*
|
|
14
|
+
* 1. A missing key falls back to the registered default, never to false/0. That is
|
|
15
|
+
* the exact bug this replaces.
|
|
16
|
+
* 2. The last good values are persisted and reloaded at boot, so a failed fetch
|
|
17
|
+
* degrades to yesterday's config rather than to nothing.
|
|
18
|
+
* 3. Fetching is cheap (our server, no per-request price), so it happens on launch,
|
|
19
|
+
* on every return from foreground, and on a timer — with ETag, so an unchanged
|
|
20
|
+
* config costs a 304 with no body.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
export type ConfigValue = boolean | number | string | null | object;
|
|
24
|
+
|
|
25
|
+
export interface ConfigStorage {
|
|
26
|
+
getString(key: string): string | null | undefined;
|
|
27
|
+
set(key: string, value: string): void;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Everything the server may ever want to target on. Sent on every request even when
|
|
32
|
+
* no rule uses it yet: the client can only start sending a new field with a store
|
|
33
|
+
* build, so a contract that is incomplete today cannot be completed for months.
|
|
34
|
+
*/
|
|
35
|
+
export interface ConfigContext {
|
|
36
|
+
platform?: string;
|
|
37
|
+
appVersion?: string;
|
|
38
|
+
osVersion?: string;
|
|
39
|
+
language?: string;
|
|
40
|
+
deviceId?: string;
|
|
41
|
+
/** Free-form user attributes a rule can compare (registration date, plan, counters). */
|
|
42
|
+
userAttributes?: Record<string, string>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface ConfigOptions {
|
|
46
|
+
/** Full manifest-style URL, e.g. https://pulse.example.com/pulse/config/esound */
|
|
47
|
+
url: string;
|
|
48
|
+
/** Values used when the server has never been reached, or has no such key. */
|
|
49
|
+
defaults?: Record<string, ConfigValue>;
|
|
50
|
+
/** Persistence for the last good payload. Without it the cache is memory-only. */
|
|
51
|
+
storage?: ConfigStorage;
|
|
52
|
+
/** Read fresh on every request: the country or plan can change between launches. */
|
|
53
|
+
getContext?: () => ConfigContext;
|
|
54
|
+
/** Foreground poll interval. 0 disables polling (launch + resume still fetch). */
|
|
55
|
+
pollIntervalMs?: number;
|
|
56
|
+
/**
|
|
57
|
+
* Skip a fetch that lands within this window of the last successful one. 0 (the
|
|
58
|
+
* default) means never skip: unlike Firebase there is no per-request price, so the
|
|
59
|
+
* throttle exists only for callers who want it.
|
|
60
|
+
*/
|
|
61
|
+
minimumFetchIntervalMs?: number;
|
|
62
|
+
/**
|
|
63
|
+
* When false, a fetch stores the payload without applying it — call activateConfig()
|
|
64
|
+
* to swap it in. Mirrors Firebase's fetch/activate split, and matters here because
|
|
65
|
+
* the foreground poll would otherwise flip a flag under a user mid-session: an ad
|
|
66
|
+
* gate or a playback engine changing while a track plays is worse than being a few
|
|
67
|
+
* minutes stale. Default true, matching fetchAndActivate.
|
|
68
|
+
*/
|
|
69
|
+
activateOnFetch?: boolean;
|
|
70
|
+
/** Network timeout per request. */
|
|
71
|
+
timeoutMs?: number;
|
|
72
|
+
onError?: (error: unknown) => void;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
interface CachedPayload {
|
|
76
|
+
values: Record<string, ConfigValue>;
|
|
77
|
+
etag: string | null;
|
|
78
|
+
fetchedAt: number;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const STORAGE_KEY = 'pulse.config.v1';
|
|
82
|
+
const DEFAULT_POLL_MS = 5 * 60 * 1000;
|
|
83
|
+
const DEFAULT_TIMEOUT_MS = 10_000;
|
|
84
|
+
|
|
85
|
+
let options: ConfigOptions | null = null;
|
|
86
|
+
let defaults: Record<string, ConfigValue> = {};
|
|
87
|
+
let values: Record<string, ConfigValue> = {};
|
|
88
|
+
let etag: string | null = null;
|
|
89
|
+
let fetchedAt = 0;
|
|
90
|
+
let source: 'defaults' | 'cache' | 'remote' = 'defaults';
|
|
91
|
+
let pending: Record<string, ConfigValue> | null = null;
|
|
92
|
+
let inFlight: Promise<boolean> | null = null;
|
|
93
|
+
let pollTimer: ReturnType<typeof setInterval> | null = null;
|
|
94
|
+
const listeners = new Set<(values: Record<string, ConfigValue>) => void>();
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Registers defaults and reloads the last good payload from storage, synchronously,
|
|
98
|
+
* so the very first read at boot already has real values instead of a blank config
|
|
99
|
+
* while the network call is in flight.
|
|
100
|
+
*/
|
|
101
|
+
export function configureConfig(opts: ConfigOptions): void {
|
|
102
|
+
options = opts;
|
|
103
|
+
defaults = { ...(opts.defaults ?? {}) };
|
|
104
|
+
|
|
105
|
+
const cached = readCache(opts.storage);
|
|
106
|
+
if (cached) {
|
|
107
|
+
values = cached.values;
|
|
108
|
+
etag = cached.etag;
|
|
109
|
+
fetchedAt = cached.fetchedAt;
|
|
110
|
+
source = 'cache';
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Merge more defaults after configure (a late-loading module registering its own). */
|
|
115
|
+
export function setConfigDefaults(more: Record<string, ConfigValue>): void {
|
|
116
|
+
defaults = { ...defaults, ...more };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Fetch, and adopt the payload if it changed. Returns true when new values were
|
|
121
|
+
* applied — false for "nothing changed" (304) and false for a failure, which are
|
|
122
|
+
* deliberately indistinguishable to callers: in both cases the current values stand.
|
|
123
|
+
* Errors surface through onError instead of rejecting, because no caller should have
|
|
124
|
+
* to wrap a config refresh in a try/catch to keep the app running.
|
|
125
|
+
*/
|
|
126
|
+
export async function fetchConfig(): Promise<boolean> {
|
|
127
|
+
if (!options) return false;
|
|
128
|
+
// Collapse concurrent calls (launch + resume can land together) onto one request.
|
|
129
|
+
if (inFlight) return inFlight;
|
|
130
|
+
|
|
131
|
+
const minInterval = options.minimumFetchIntervalMs ?? 0;
|
|
132
|
+
if (minInterval > 0 && fetchedAt > 0 && Date.now() - fetchedAt < minInterval) {
|
|
133
|
+
return false;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
inFlight = (async () => {
|
|
137
|
+
const opts = options!;
|
|
138
|
+
const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
|
|
139
|
+
const timer = controller
|
|
140
|
+
? setTimeout(() => controller.abort(), opts.timeoutMs ?? DEFAULT_TIMEOUT_MS)
|
|
141
|
+
: null;
|
|
142
|
+
|
|
143
|
+
try {
|
|
144
|
+
const response = await fetch(opts.url, {
|
|
145
|
+
method: 'GET',
|
|
146
|
+
headers: buildHeaders(opts, etag),
|
|
147
|
+
signal: controller?.signal,
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
if (response.status === 304) return false;
|
|
151
|
+
if (!response.ok) throw new Error(`Pulse config HTTP ${response.status}`);
|
|
152
|
+
|
|
153
|
+
const payload = await response.json();
|
|
154
|
+
const nextValues = payload?.values;
|
|
155
|
+
// A payload without a values object is a broken response, not "no keys": adopting
|
|
156
|
+
// it would blank every flag at once.
|
|
157
|
+
if (!nextValues || typeof nextValues !== 'object' || Array.isArray(nextValues)) {
|
|
158
|
+
throw new Error('Pulse config: malformed payload');
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
etag = response.headers?.get?.('etag') ?? null;
|
|
162
|
+
fetchedAt = Date.now();
|
|
163
|
+
|
|
164
|
+
if (opts.activateOnFetch === false) {
|
|
165
|
+
pending = nextValues as Record<string, ConfigValue>;
|
|
166
|
+
return false;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
return applyValues(nextValues as Record<string, ConfigValue>, opts);
|
|
170
|
+
} catch (error) {
|
|
171
|
+
// A failed refresh must never clear what we have: the whole point of the cache
|
|
172
|
+
// is that an unreachable server degrades to the last good config.
|
|
173
|
+
opts.onError?.(error);
|
|
174
|
+
return false;
|
|
175
|
+
} finally {
|
|
176
|
+
if (timer) clearTimeout(timer);
|
|
177
|
+
inFlight = null;
|
|
178
|
+
}
|
|
179
|
+
})();
|
|
180
|
+
|
|
181
|
+
return inFlight;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Swap in the values from the last fetch made with activateOnFetch: false.
|
|
186
|
+
* Returns true when something actually changed.
|
|
187
|
+
*/
|
|
188
|
+
export function activateConfig(): boolean {
|
|
189
|
+
if (!pending || !options) return false;
|
|
190
|
+
const next = pending;
|
|
191
|
+
pending = null;
|
|
192
|
+
return applyValues(next, options);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Whether a fetched-but-not-yet-applied payload is waiting. */
|
|
196
|
+
export function hasPendingConfig(): boolean {
|
|
197
|
+
return pending !== null;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Fetch on launch, on every return to the foreground, and on a timer.
|
|
202
|
+
* Returns a function that stops both.
|
|
203
|
+
*/
|
|
204
|
+
export function startConfigAutoRefresh(appState?: {
|
|
205
|
+
addEventListener: (type: 'change', handler: (state: string) => void) => { remove: () => void };
|
|
206
|
+
}): () => void {
|
|
207
|
+
void fetchConfig();
|
|
208
|
+
|
|
209
|
+
const subscription = appState?.addEventListener('change', (state) => {
|
|
210
|
+
if (state === 'active') void fetchConfig();
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
const interval = options?.pollIntervalMs ?? DEFAULT_POLL_MS;
|
|
214
|
+
if (interval > 0) {
|
|
215
|
+
stopPolling();
|
|
216
|
+
pollTimer = setInterval(() => void fetchConfig(), interval);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
return () => {
|
|
220
|
+
subscription?.remove();
|
|
221
|
+
stopPolling();
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function applyValues(next: Record<string, ConfigValue>, opts: ConfigOptions): boolean {
|
|
226
|
+
const changed = !shallowEqual(values, next);
|
|
227
|
+
|
|
228
|
+
values = next;
|
|
229
|
+
source = 'remote';
|
|
230
|
+
writeCache(opts.storage, { values, etag, fetchedAt });
|
|
231
|
+
|
|
232
|
+
// Listeners drive re-renders and gate re-evaluation: firing them for an identical
|
|
233
|
+
// payload is pure churn, and the 200-with-same-content case is common enough
|
|
234
|
+
// (a proxy that drops the ETag) to be worth checking.
|
|
235
|
+
if (changed) notify();
|
|
236
|
+
return changed;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function shallowEqual(a: Record<string, ConfigValue>, b: Record<string, ConfigValue>): boolean {
|
|
240
|
+
const aKeys = Object.keys(a);
|
|
241
|
+
const bKeys = Object.keys(b);
|
|
242
|
+
if (aKeys.length !== bKeys.length) return false;
|
|
243
|
+
return aKeys.every((k) => {
|
|
244
|
+
const av = a[k];
|
|
245
|
+
const bv = b[k];
|
|
246
|
+
if (av !== null && bv !== null && typeof av === 'object' && typeof bv === 'object') {
|
|
247
|
+
return JSON.stringify(av) === JSON.stringify(bv);
|
|
248
|
+
}
|
|
249
|
+
return av === bv;
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function stopPolling(): void {
|
|
254
|
+
if (pollTimer) {
|
|
255
|
+
clearInterval(pollTimer);
|
|
256
|
+
pollTimer = null;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// ─── Reads ────────────────────────────────────────────────────────────────────
|
|
261
|
+
|
|
262
|
+
/** The served value, or the registered default. Never a type's zero value. */
|
|
263
|
+
export function getConfigValue(key: string): ConfigValue {
|
|
264
|
+
if (Object.prototype.hasOwnProperty.call(values, key) && values[key] !== null) {
|
|
265
|
+
return values[key] as ConfigValue;
|
|
266
|
+
}
|
|
267
|
+
const fallback = defaults[key];
|
|
268
|
+
return fallback === undefined ? null : fallback;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export function getConfigBoolean(key: string): boolean {
|
|
272
|
+
const value = getConfigValue(key);
|
|
273
|
+
if (typeof value === 'boolean') return value;
|
|
274
|
+
// A server that sends "true" as a string must not read as false.
|
|
275
|
+
if (typeof value === 'string') return value.toLowerCase() === 'true';
|
|
276
|
+
if (typeof value === 'number') return value !== 0;
|
|
277
|
+
return false;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export function getConfigNumber(key: string): number {
|
|
281
|
+
const value = getConfigValue(key);
|
|
282
|
+
if (typeof value === 'number') return value;
|
|
283
|
+
if (typeof value === 'string') {
|
|
284
|
+
const parsed = Number(value);
|
|
285
|
+
if (!Number.isNaN(parsed)) return parsed;
|
|
286
|
+
}
|
|
287
|
+
return 0;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export function getConfigString(key: string): string {
|
|
291
|
+
const value = getConfigValue(key);
|
|
292
|
+
if (typeof value === 'string') return value;
|
|
293
|
+
if (value === null || value === undefined) return '';
|
|
294
|
+
return String(value);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** Defaults first, then everything the server sent — what a caller would see key by key. */
|
|
298
|
+
export function getAllConfig(): Record<string, ConfigValue> {
|
|
299
|
+
return { ...defaults, ...values };
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Parsed object/array value, or the default. Null when neither is usable. */
|
|
303
|
+
export function getConfigJson<T = unknown>(key: string): T | null {
|
|
304
|
+
const value = getConfigValue(key);
|
|
305
|
+
if (value === null || value === undefined) return null;
|
|
306
|
+
if (typeof value === 'object') return value as T;
|
|
307
|
+
if (typeof value === 'string') {
|
|
308
|
+
try {
|
|
309
|
+
return JSON.parse(value) as T;
|
|
310
|
+
} catch {
|
|
311
|
+
return null;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return null;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Where this key's value came from — the answer to "why is this flag off?". */
|
|
318
|
+
export function getConfigSource(key: string): 'remote' | 'default' | 'missing' {
|
|
319
|
+
if (Object.prototype.hasOwnProperty.call(values, key) && values[key] !== null) return 'remote';
|
|
320
|
+
if (Object.prototype.hasOwnProperty.call(defaults, key)) return 'default';
|
|
321
|
+
return 'missing';
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
export function getConfigKeys(): string[] {
|
|
325
|
+
return Object.keys(getAllConfig()).sort();
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
export function onConfigChange(listener: (values: Record<string, ConfigValue>) => void): () => void {
|
|
329
|
+
listeners.add(listener);
|
|
330
|
+
return () => listeners.delete(listener);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** For diagnostics: where the current values came from and how old they are. */
|
|
334
|
+
export function getConfigInfo(): {
|
|
335
|
+
source: 'defaults' | 'cache' | 'remote';
|
|
336
|
+
fetchedAt: number;
|
|
337
|
+
etag: string | null;
|
|
338
|
+
keyCount: number;
|
|
339
|
+
} {
|
|
340
|
+
return { source, fetchedAt, etag, keyCount: Object.keys(getAllConfig()).length };
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Test seam: drops every piece of module state. */
|
|
344
|
+
export function resetConfigForTests(): void {
|
|
345
|
+
options = null;
|
|
346
|
+
defaults = {};
|
|
347
|
+
values = {};
|
|
348
|
+
etag = null;
|
|
349
|
+
fetchedAt = 0;
|
|
350
|
+
source = 'defaults';
|
|
351
|
+
inFlight = null;
|
|
352
|
+
pending = null;
|
|
353
|
+
listeners.clear();
|
|
354
|
+
stopPolling();
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// ─── Internals ────────────────────────────────────────────────────────────────
|
|
358
|
+
|
|
359
|
+
function buildHeaders(opts: ConfigOptions, currentEtag: string | null): Record<string, string> {
|
|
360
|
+
const ctx = opts.getContext?.() ?? {};
|
|
361
|
+
const headers: Record<string, string> = { Accept: 'application/json' };
|
|
362
|
+
|
|
363
|
+
if (ctx.platform) headers['X-Pulse-Platform'] = ctx.platform;
|
|
364
|
+
if (ctx.appVersion) headers['X-Pulse-App-Version'] = ctx.appVersion;
|
|
365
|
+
if (ctx.osVersion) headers['X-Pulse-Os-Version'] = ctx.osVersion;
|
|
366
|
+
if (ctx.language) headers['X-Pulse-Language'] = ctx.language;
|
|
367
|
+
if (ctx.deviceId) headers['Pulse-Device-Id'] = ctx.deviceId;
|
|
368
|
+
if (ctx.userAttributes && Object.keys(ctx.userAttributes).length > 0) {
|
|
369
|
+
headers['X-Pulse-User-Attributes'] = JSON.stringify(ctx.userAttributes);
|
|
370
|
+
}
|
|
371
|
+
// Country is deliberately absent: the server reads it from the edge, which a client
|
|
372
|
+
// header cannot spoof to opt into a targeted rollout.
|
|
373
|
+
|
|
374
|
+
if (currentEtag) headers['If-None-Match'] = currentEtag;
|
|
375
|
+
return headers;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function readCache(storage?: ConfigStorage): CachedPayload | null {
|
|
379
|
+
if (!storage) return null;
|
|
380
|
+
try {
|
|
381
|
+
const raw = storage.getString(STORAGE_KEY);
|
|
382
|
+
if (!raw) return null;
|
|
383
|
+
const parsed = JSON.parse(raw) as CachedPayload;
|
|
384
|
+
if (!parsed || typeof parsed !== 'object' || !parsed.values) return null;
|
|
385
|
+
return parsed;
|
|
386
|
+
} catch {
|
|
387
|
+
// A corrupt cache is not worth a crash at boot: fall back to defaults.
|
|
388
|
+
return null;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function writeCache(storage: ConfigStorage | undefined, payload: CachedPayload): void {
|
|
393
|
+
if (!storage) return;
|
|
394
|
+
try {
|
|
395
|
+
storage.set(STORAGE_KEY, JSON.stringify(payload));
|
|
396
|
+
} catch {
|
|
397
|
+
// Persistence is an optimisation; failing to write must not fail the fetch.
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function notify(): void {
|
|
402
|
+
const snapshot = getAllConfig();
|
|
403
|
+
listeners.forEach((listener) => {
|
|
404
|
+
try {
|
|
405
|
+
listener(snapshot);
|
|
406
|
+
} catch {
|
|
407
|
+
// One bad listener must not stop the others from being told.
|
|
408
|
+
}
|
|
409
|
+
});
|
|
410
|
+
}
|
package/src/index.ts
CHANGED