@astratra/native 0.1.0 → 0.3.0

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/src/index.d.ts CHANGED
@@ -280,3 +280,310 @@ export function createApiClient(options: {
280
280
  refreshPath?: string;
281
281
  onSessionExpired?: (cause: unknown) => void;
282
282
  }): ApiClient;
283
+
284
+ /* ───────────────────────────── Connectivity ──────────────────────────── */
285
+
286
+ /** What the OS reports, narrowed to what the rules read. NetInfo's state fits. */
287
+ export interface NetworkSnapshot {
288
+ isConnected?: boolean | null;
289
+ isInternetReachable?: boolean | null;
290
+ type?: string | null;
291
+ }
292
+
293
+ export type Reachability = 'online' | 'offline' | 'unknown';
294
+ export type ConnectionLink = 'wifi' | 'cellular' | 'none' | 'unknown';
295
+ export type TransportFailure = 'timeout' | 'unreachable';
296
+
297
+ export const TRANSPORT_BLACKOUT_MS: number;
298
+
299
+ /** Offline ONLY without any interface. The OS "no Internet" stays unknown. */
300
+ export function readReachability(snapshot: NetworkSnapshot | null | undefined): Reachability;
301
+ export function readConnectionLink(snapshot: NetworkSnapshot | null | undefined): ConnectionLink;
302
+ export function isDefinitelyOffline(snapshot: NetworkSnapshot | null | undefined): boolean;
303
+ export function worthAttempting(snapshot: NetworkSnapshot | null | undefined): boolean;
304
+ export function hasComeBack(previous: Reachability, next: Reachability): boolean;
305
+ export function shouldDeclareTransportDown(input: { reason: TransportFailure; reachability: Reachability }): boolean;
306
+
307
+ /** @react-native-community/netinfo's default export, narrowed. */
308
+ export interface NetInfoLike {
309
+ addEventListener(listener: (state: NetworkSnapshot) => void): (() => void) | { remove(): void };
310
+ fetch(): Promise<NetworkSnapshot>;
311
+ }
312
+
313
+ export interface ConnectivityMonitor {
314
+ start(): void;
315
+ stop(): void;
316
+ /** Re-reads the OS without emitting the comeback. Resolves worthAttempting. */
317
+ refresh(): Promise<boolean>;
318
+ setSnapshot(next: NetworkSnapshot | null | undefined): void;
319
+ getReachability(): Reachability;
320
+ getConnectionLink(): ConnectionLink;
321
+ isTransportDown(): boolean;
322
+ isOffline(): boolean;
323
+ shouldAttemptRequest(): boolean;
324
+ noteTransportFailure(reason?: TransportFailure): void;
325
+ noteTransportSuccess(): void;
326
+ setRecoveryProbe(probe: (() => Promise<unknown> | unknown) | null): void;
327
+ /** Shaped for useSyncExternalStore. */
328
+ subscribe(listener: () => void): () => void;
329
+ onComeback(listener: () => void): () => void;
330
+ }
331
+
332
+ export function createConnectivityMonitor(options?: {
333
+ netInfo?: NetInfoLike;
334
+ blackoutMs?: number;
335
+ now?: () => number;
336
+ }): ConnectivityMonitor;
337
+
338
+ /* ────────────────────────── Over-the-air updates ─────────────────────── */
339
+
340
+ export const UPDATE_CHECK_INTERVAL_MS: number;
341
+ export const UPDATE_APPLY_GRACE_MS: number;
342
+
343
+ export function shouldCheckForUpdate(
344
+ context: { enabled: boolean; online: boolean; lastCheckAt: number | null; now: number },
345
+ intervalMs?: number
346
+ ): boolean;
347
+
348
+ export function shouldApplyUpdate(context: {
349
+ downloaded: boolean;
350
+ stillInBackground: boolean;
351
+ pendingWrites: number;
352
+ }): boolean;
353
+
354
+ export function describeRelease(input: {
355
+ version?: string | null;
356
+ updateId?: string | null;
357
+ isEmbeddedLaunch: boolean;
358
+ }): string;
359
+
360
+ /** expo-updates' module namespace, narrowed to what the watcher uses. */
361
+ export interface UpdatesLike {
362
+ isEnabled: boolean;
363
+ isEmbeddedLaunch: boolean;
364
+ updateId?: string | null;
365
+ channel?: string | null;
366
+ runtimeVersion?: string | null;
367
+ checkForUpdateAsync(): Promise<{ isAvailable: boolean }>;
368
+ fetchUpdateAsync(): Promise<{ isNew: boolean }>;
369
+ reloadAsync(): Promise<void>;
370
+ }
371
+
372
+ /** React Native's AppState, narrowed. */
373
+ export interface AppStateLike {
374
+ currentState: string | null;
375
+ addEventListener(event: 'change', listener: (state: string) => void): { remove(): void } | void;
376
+ }
377
+
378
+ export interface BuildDescription {
379
+ updateId: string | null;
380
+ channel: string | null;
381
+ runtimeVersion: string | null;
382
+ isEmbeddedLaunch: boolean;
383
+ release: string;
384
+ }
385
+
386
+ export interface UpdateWatcher {
387
+ start(): void;
388
+ stop(): void;
389
+ /** Resolves true when a new update was downloaded by this call. */
390
+ check(now?: number): Promise<boolean>;
391
+ hasPendingUpdate(): boolean;
392
+ describeBuild(version?: string | null): BuildDescription;
393
+ }
394
+
395
+ export function createUpdateWatcher(options: {
396
+ updates: UpdatesLike;
397
+ appState: AppStateLike;
398
+ isOnline?: () => boolean;
399
+ pendingWrites?: () => number;
400
+ onError?: (error: unknown, context: { where: 'checkForUpdate' | 'reloadAsync' }) => void;
401
+ checkIntervalMs?: number;
402
+ graceMs?: number;
403
+ now?: () => number;
404
+ }): UpdateWatcher;
405
+
406
+ /* ────────────────────────────── Media cache ──────────────────────────── */
407
+
408
+ export const MEDIA_CACHE_MAX_FILES: number;
409
+ export const MEDIA_CACHE_MAX_BYTES: number;
410
+ export const MEDIA_CACHE_ABANDONED_MS: number;
411
+
412
+ /** [a-z0-9-] only. Every part that changes the bytes — a version included. */
413
+ export function contentKey(...parts: Array<string | number | null | undefined>): string;
414
+
415
+ export function extensionFor(
416
+ contentType: string | null | undefined,
417
+ types: Record<string, string>,
418
+ fallback: string
419
+ ): string;
420
+
421
+ export interface CachedFile {
422
+ name: string;
423
+ /** Bytes. */
424
+ size: number;
425
+ /** Milliseconds. */
426
+ modifiedAt: number;
427
+ }
428
+
429
+ export function planEviction(
430
+ files: CachedFile[],
431
+ options: {
432
+ extensions: string[];
433
+ maxFiles?: number;
434
+ maxBytes?: number;
435
+ abandonedAfterMs?: number;
436
+ now?: number;
437
+ }
438
+ ): string[];
439
+
440
+ /** expo-file-system/legacy's shape, narrowed. `modificationTime` in seconds. */
441
+ export interface FileSystemLike {
442
+ getInfoAsync(uri: string): Promise<{ exists: boolean; isDirectory?: boolean; size?: number; modificationTime?: number }>;
443
+ makeDirectoryAsync(uri: string, options?: { intermediates?: boolean }): Promise<void>;
444
+ moveAsync(options: { from: string; to: string }): Promise<void>;
445
+ deleteAsync(uri: string, options?: { idempotent?: boolean }): Promise<void>;
446
+ readDirectoryAsync(uri: string): Promise<string[]>;
447
+ }
448
+
449
+ export type MediaWriter = (tempUri: string) => Promise<unknown>;
450
+
451
+ export interface MediaCache {
452
+ readonly directory: string;
453
+ lookup(key: string): Promise<string | null>;
454
+ store(key: string, extension: string, write: MediaWriter): Promise<string>;
455
+ resolve(key: string, download: () => Promise<{ extension: string; write: MediaWriter }>): Promise<string>;
456
+ /** Resolves the names deleted. */
457
+ tidy(): Promise<string[]>;
458
+ }
459
+
460
+ export function createMediaCache(options: {
461
+ fs: FileSystemLike;
462
+ directory: string;
463
+ extensions: string[];
464
+ maxFiles?: number;
465
+ maxBytes?: number;
466
+ abandonedAfterMs?: number;
467
+ now?: () => number;
468
+ }): MediaCache;
469
+
470
+ /* ─────────────────────────────── Pictures ────────────────────────────── */
471
+
472
+ export const PICTURE_ADDRESS_MAX_LENGTH: number;
473
+ /** Largest inline picture accepted by default, decoded (10 MB). */
474
+ export const PICTURE_DATA_MAX_BYTES: number;
475
+ /** Inline types accepted by default (no SVG). */
476
+ export const PICTURE_DATA_TYPES: readonly string[];
477
+ export const PICTURE_EXTENSIONS: Readonly<Record<string, string>>;
478
+ export const PICTURE_FILE_EXTENSIONS: readonly string[];
479
+
480
+ export type PictureRefusal =
481
+ | 'empty'
482
+ | 'too_long'
483
+ | 'unsafe_characters'
484
+ | 'relative'
485
+ | 'scheme'
486
+ | 'userinfo'
487
+ | 'host'
488
+ | 'insecure'
489
+ | 'data_malformed'
490
+ | 'data_type'
491
+ | 'data_too_large';
492
+
493
+ export class PictureSourceError extends Error {
494
+ readonly code: 'refused' | 'http' | 'not_a_picture';
495
+ readonly reason: string | null;
496
+ readonly status: number | null;
497
+ constructor(code: 'refused' | 'http' | 'not_a_picture', reason?: string, status?: number);
498
+ }
499
+
500
+ export interface HttpAddress {
501
+ scheme: 'http' | 'https';
502
+ host: string;
503
+ /** null for the scheme's default port. */
504
+ port: number | null;
505
+ origin: string;
506
+ /** Path, query and fragment; '' when none. */
507
+ path: string;
508
+ }
509
+
510
+ /** Strict: no credentials, no backslash, no control character, ASCII host. */
511
+ export function parseHttpAddress(address: string): HttpAddress | null;
512
+ export function originOf(address: string): string | null;
513
+ /** Scheme, host and port compared whole — never a prefix or substring test. */
514
+ export function isSameOrigin(a: string, b: string): boolean;
515
+
516
+ export type DataAddressRead =
517
+ | { ok: true; mimeType: string; base64: boolean; payloadStart: number; bytes: number }
518
+ | { ok: false; reason: 'data_malformed' | 'data_type' | 'data_too_large' };
519
+ export function readDataAddress(address: string, options?: { types?: readonly string[]; maxBytes?: number }): DataAddressRead;
520
+ export function dataPayloadBase64(address: string, read: { base64: boolean; payloadStart: number }): string;
521
+ export function decodeBase64(text: string): Uint8Array;
522
+ export function encodeBase64(bytes: Uint8Array | ArrayLike<number>): string;
523
+ /** From the first bytes, never the name: PNG, JPEG, GIF, WebP, HEIC, AVIF, BMP. */
524
+ export function sniffPictureType(head: Uint8Array | ArrayLike<number>): { mimeType: string; extension: string } | null;
525
+ /** '' when neither the title nor the fallback leaves anything. */
526
+ export function pictureFileName(title: string, options?: { fallback?: string; maxLength?: number }): string;
527
+ /** expo-sharing's `UTI` for a picture file, from its extension; null when unknown. */
528
+ export function pictureUti(uri: string): string | null;
529
+
530
+ export type PictureKind =
531
+ | { kind: 'app'; url: string }
532
+ | { kind: 'outside'; url: string }
533
+ | { kind: 'data'; url: string; mimeType: string; bytes: number }
534
+ | { kind: 'refused'; reason: PictureRefusal };
535
+
536
+ /** What an image component takes: the token only on the app's own origin. */
537
+ export interface PictureSource {
538
+ uri: string;
539
+ headers?: Record<string, string>;
540
+ }
541
+
542
+ export type PictureQuery = Record<string, string | number | boolean | null | undefined>;
543
+
544
+ export interface PictureSources {
545
+ readonly appOrigin: string;
546
+ classify(address: string): PictureKind;
547
+ /** null for a refused address. */
548
+ resolve(address: string, options?: { query?: PictureQuery }): Promise<PictureSource | null>;
549
+ headersFor(url: string): Promise<Record<string, string>>;
550
+ /** null for a refused address; never contains the token. */
551
+ cacheKey(address: string, options?: { variant?: string; version?: string | number }): string | null;
552
+ }
553
+
554
+ export function createPictureSources(options: {
555
+ appUrl: string;
556
+ getToken?: () => string | null | undefined | Promise<string | null | undefined>;
557
+ authorize?: (token: string) => Record<string, string>;
558
+ allowHttpOutside?: boolean;
559
+ dataTypes?: readonly string[];
560
+ maxDataBytes?: number;
561
+ }): PictureSources;
562
+
563
+ /** expo-file-system/legacy's shape, as the picture files use it. */
564
+ export interface PictureFileSystemLike extends FileSystemLike {
565
+ copyAsync(options: { from: string; to: string }): Promise<void>;
566
+ downloadAsync(uri: string, fileUri: string, options?: { headers?: Record<string, string> }): Promise<{ status: number }>;
567
+ readAsStringAsync(uri: string, options: { encoding: 'base64'; position?: number; length?: number }): Promise<string>;
568
+ writeAsStringAsync(uri: string, contents: string, options: { encoding: 'base64' }): Promise<void>;
569
+ }
570
+
571
+ export interface PictureFiles {
572
+ readonly directory: string;
573
+ original(address: string, options?: { query?: PictureQuery; version?: string | number }): Promise<string>;
574
+ named(
575
+ address: string,
576
+ title: string,
577
+ options?: { fallback?: string; query?: PictureQuery; version?: string | number }
578
+ ): Promise<string>;
579
+ tidy(): Promise<string[]>;
580
+ }
581
+
582
+ export function createPictureFiles(options: {
583
+ sources: PictureSources;
584
+ fs: PictureFileSystemLike;
585
+ directory: string;
586
+ maxFiles?: number;
587
+ maxBytes?: number;
588
+ now?: () => number;
589
+ }): PictureFiles;
package/src/index.js CHANGED
@@ -8,5 +8,9 @@ module.exports = {
8
8
  ...require('./pushSettings'),
9
9
  ...require('./pushService'),
10
10
  ...require('./checkout'),
11
- ...require('./api')
11
+ ...require('./api'),
12
+ ...require('./connectivity'),
13
+ ...require('./updates'),
14
+ ...require('./mediaCache'),
15
+ ...require('./pictureSource')
12
16
  };
@@ -0,0 +1,262 @@
1
+ /**
2
+ * Media kept on the phone: fetched once, replayed from disk, bounded.
3
+ *
4
+ * The first version of this cache re-downloaded the WHOLE file on every play,
5
+ * and left each copy behind under a timestamped name that nothing ever read
6
+ * again: the cache directory grew without end. Something already played must
7
+ * replay from disk, instantly and without network, and the directory must stay
8
+ * bounded.
9
+ *
10
+ * Three pieces: a stable name for a piece of content (contentKey), the rule
11
+ * for what to throw away (planEviction), and the gestures on disk
12
+ * (createMediaCache). The file system is INJECTED — expo-file-system's legacy
13
+ * API fits as-is — so all three run in plain Node.
14
+ */
15
+
16
+ const MEDIA_CACHE_MAX_FILES = 40;
17
+ const MEDIA_CACHE_MAX_BYTES = 60 * 1024 * 1024;
18
+
19
+ /* A temporary file older than this is the remains of an interrupted download
20
+ (app killed, network lost): nobody will finish it. Younger, it may still be
21
+ being written — it is left alone. */
22
+ const MEDIA_CACHE_ABANDONED_MS = 5 * 60 * 1000;
23
+
24
+ const TEMP_SUFFIX = '.tmp';
25
+
26
+ /* cyrb53: a 53-bit pure-JS hash, stable across devices. Run twice with two
27
+ seeds (106 bits): two different contents landing on the same name would
28
+ serve the wrong media, and at that width it does not happen in practice.
29
+ A platform crypto digest would be asynchronous and native — it does not run
30
+ in Node, where this rule is tested. */
31
+ function cyrb53(text, seed) {
32
+ let h1 = 0xdeadbeef ^ seed;
33
+ let h2 = 0x41c6ce57 ^ seed;
34
+ for (let i = 0; i < text.length; i += 1) {
35
+ const code = text.charCodeAt(i);
36
+ h1 = Math.imul(h1 ^ code, 2654435761);
37
+ h2 = Math.imul(h2 ^ code, 1597334677);
38
+ }
39
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
40
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
41
+ return (2097152 * (h2 >>> 0) + (h1 >>> 0)).toString(36);
42
+ }
43
+
44
+ /**
45
+ * The file name of a piece of content: every part that changes the bytes.
46
+ *
47
+ * Put a version in the parts. When the server changes how it renders (a new
48
+ * voice, a new codec), files kept under the old key must stop being served,
49
+ * and bumping the version is how they do.
50
+ *
51
+ * The parts are encoded as a JSON array, never joined with a separator:
52
+ * ('a:b', 'c') and ('a', 'b:c') must not share a key.
53
+ *
54
+ * @param {...(string|number|null|undefined)} parts Null and undefined count
55
+ * as empty.
56
+ * @returns {string} [a-z0-9-] only — safe as a file name everywhere.
57
+ */
58
+ function contentKey(...parts) {
59
+ const source = JSON.stringify(parts.map((part) => (part === null || part === undefined ? '' : String(part))));
60
+ return `${cyrb53(source, 1)}-${cyrb53(source, 2)}`;
61
+ }
62
+
63
+ /**
64
+ * The extension to store a response under, from its Content-Type.
65
+ * @param {string|null|undefined} contentType
66
+ * @param {Record<string, string>} types Lowercase MIME type => extension.
67
+ * @param {string} fallback For anything unlisted — including a missing header.
68
+ */
69
+ function extensionFor(contentType, types, fallback) {
70
+ const type = String(contentType || '').split(';')[0].trim().toLowerCase();
71
+ const map = types || {};
72
+ return Object.prototype.hasOwnProperty.call(map, type) ? map[type] : fallback;
73
+ }
74
+
75
+ function isFinished(name, extensions) {
76
+ return extensions.some((extension) => name.endsWith(`.${extension}`));
77
+ }
78
+
79
+ /**
80
+ * Which files to delete, least recently written first.
81
+ *
82
+ * - a finished file survives while the directory stays under maxFiles AND
83
+ * maxBytes; past either, the oldest go;
84
+ * - the newest is NEVER deleted, even when too heavy on its own: it is the one
85
+ * being played;
86
+ * - anything that is not a finished file (a temporary) goes once abandoned,
87
+ * and does not count against the bounds.
88
+ *
89
+ * @param {Array<{name: string, size: number, modifiedAt: number}>} files
90
+ * `modifiedAt` in milliseconds.
91
+ * @param {object} options
92
+ * @param {string[]} options.extensions What a finished file ends with.
93
+ * @param {number} [options.maxFiles]
94
+ * @param {number} [options.maxBytes]
95
+ * @param {number} [options.abandonedAfterMs]
96
+ * @param {number} [options.now]
97
+ * @returns {string[]}
98
+ */
99
+ function planEviction(files, options = {}) {
100
+ const extensions = Array.isArray(options.extensions) ? options.extensions : [];
101
+ const maxFiles = Number.isFinite(options.maxFiles) ? options.maxFiles : MEDIA_CACHE_MAX_FILES;
102
+ const maxBytes = Number.isFinite(options.maxBytes) ? options.maxBytes : MEDIA_CACHE_MAX_BYTES;
103
+ const abandonedAfterMs = Number.isFinite(options.abandonedAfterMs) ? options.abandonedAfterMs : MEDIA_CACHE_ABANDONED_MS;
104
+ const now = Number.isFinite(options.now) ? options.now : Date.now();
105
+
106
+ const discard = [];
107
+ const finished = [];
108
+ for (const file of Array.isArray(files) ? files : []) {
109
+ if (!file || typeof file.name !== 'string') continue;
110
+ if (isFinished(file.name, extensions)) finished.push(file);
111
+ else if (now - file.modifiedAt > abandonedAfterMs) discard.push(file.name);
112
+ }
113
+ finished.sort((a, b) => b.modifiedAt - a.modifiedAt);
114
+ let bytes = 0;
115
+ finished.forEach((file, rank) => {
116
+ bytes += Math.max(0, Number(file.size) || 0);
117
+ if (rank === 0) return;
118
+ if (rank >= maxFiles || bytes > maxBytes) discard.push(file.name);
119
+ });
120
+ return discard;
121
+ }
122
+
123
+ /**
124
+ * The cache on disk.
125
+ *
126
+ * @param {object} options
127
+ * @param {object} options.fs expo-file-system/legacy's shape: getInfoAsync,
128
+ * makeDirectoryAsync, moveAsync, deleteAsync, readDirectoryAsync.
129
+ * getInfoAsync's `modificationTime` is in SECONDS, as Expo reports it.
130
+ * @param {string} options.directory A directory of its own — anything else
131
+ * found in it is treated as an abandoned temporary and deleted.
132
+ * @param {string[]} options.extensions Every extension a finished file may
133
+ * carry. A lookup tries each.
134
+ * @param {number} [options.maxFiles]
135
+ * @param {number} [options.maxBytes]
136
+ * @param {number} [options.abandonedAfterMs]
137
+ * @param {() => number} [options.now]
138
+ */
139
+ function createMediaCache(options = {}) {
140
+ const fs = options.fs;
141
+ if (!fs) throw new Error('createMediaCache: an fs adapter is required.');
142
+ if (!options.directory) throw new Error('createMediaCache: a directory is required.');
143
+ const extensions = Array.isArray(options.extensions) ? options.extensions.filter(Boolean) : [];
144
+ if (extensions.length === 0) throw new Error('createMediaCache: at least one extension is required.');
145
+ const directory = options.directory.endsWith('/') ? options.directory : `${options.directory}/`;
146
+ const now = typeof options.now === 'function' ? options.now : () => Date.now();
147
+ const bounds = {
148
+ extensions,
149
+ maxFiles: options.maxFiles,
150
+ maxBytes: options.maxBytes,
151
+ abandonedAfterMs: options.abandonedAfterMs
152
+ };
153
+
154
+ let tempCounter = 0;
155
+ let tidying = null;
156
+
157
+ /**
158
+ * The finished file for a key, or null.
159
+ *
160
+ * No "last used" date is refreshed on a hit: the legacy API cannot touch a
161
+ * file's date without rewriting it. Eviction therefore follows download
162
+ * order — a file replayed often eventually goes, and comes back on the next
163
+ * play.
164
+ */
165
+ async function lookup(key) {
166
+ for (const extension of extensions) {
167
+ const uri = `${directory}${key}.${extension}`;
168
+ const info = await fs.getInfoAsync(uri);
169
+ if (info && info.exists) return uri;
170
+ }
171
+ return null;
172
+ }
173
+
174
+ /**
175
+ * Write under a temporary name, THEN move: an interruption mid-write leaves
176
+ * a .tmp that eviction collects, never a truncated file taken for valid on
177
+ * the next play.
178
+ *
179
+ * @param {string} key
180
+ * @param {string} extension One of `extensions`.
181
+ * @param {(tempUri: string) => Promise<unknown>} write Puts the bytes at
182
+ * tempUri, however the caller's platform writes bytes.
183
+ * @returns {Promise<string>} The finished file's URI.
184
+ */
185
+ async function store(key, extension, write) {
186
+ if (!extensions.includes(extension)) {
187
+ throw new Error(`createMediaCache: extension "${extension}" is not one of this cache's extensions.`);
188
+ }
189
+ await fs.makeDirectoryAsync(directory, { intermediates: true });
190
+ const destination = `${directory}${key}.${extension}`;
191
+ tempCounter += 1;
192
+ const temporary = `${directory}${key}.${now()}-${tempCounter}${TEMP_SUFFIX}`;
193
+ try {
194
+ await write(temporary);
195
+ } catch (error) {
196
+ await fs.deleteAsync(temporary, { idempotent: true }).catch(() => undefined);
197
+ throw error;
198
+ }
199
+ try {
200
+ await fs.moveAsync({ from: temporary, to: destination });
201
+ } catch (error) {
202
+ /* Two taps on the same content: the other download already put the
203
+ finished file in place. Ours is useless, theirs is valid. */
204
+ await fs.deleteAsync(temporary, { idempotent: true });
205
+ const info = await fs.getInfoAsync(destination);
206
+ if (!info || !info.exists) throw error;
207
+ }
208
+ /* Tidying does not hold up playback: it runs on its own, and its failure
209
+ concerns nobody. */
210
+ void tidy().catch(() => undefined);
211
+ return destination;
212
+ }
213
+
214
+ /**
215
+ * The cached file, or a fresh download stored first.
216
+ * @param {string} key
217
+ * @param {() => Promise<{extension: string, write: (tempUri: string) => Promise<unknown>}>} download
218
+ */
219
+ async function resolve(key, download) {
220
+ const known = await lookup(key);
221
+ if (known) return known;
222
+ const { extension, write } = await download();
223
+ return store(key, extension, write);
224
+ }
225
+
226
+ /* One tidy at a time: two plays close together must not delete the same
227
+ files twice. */
228
+ function tidy() {
229
+ if (tidying) return tidying;
230
+ tidying = (async () => {
231
+ const info = await fs.getInfoAsync(directory);
232
+ if (!info || !info.exists) return [];
233
+ const names = await fs.readDirectoryAsync(directory);
234
+ const files = [];
235
+ for (const name of names) {
236
+ const entry = await fs.getInfoAsync(`${directory}${name}`);
237
+ if (!entry || !entry.exists || entry.isDirectory) continue;
238
+ files.push({ name, size: Number(entry.size) || 0, modifiedAt: (Number(entry.modificationTime) || 0) * 1000 });
239
+ }
240
+ const discard = planEviction(files, { ...bounds, now: now() });
241
+ for (const name of discard) {
242
+ await fs.deleteAsync(`${directory}${name}`, { idempotent: true });
243
+ }
244
+ return discard;
245
+ })().finally(() => {
246
+ tidying = null;
247
+ });
248
+ return tidying;
249
+ }
250
+
251
+ return { directory, lookup, store, resolve, tidy };
252
+ }
253
+
254
+ module.exports = {
255
+ MEDIA_CACHE_MAX_FILES,
256
+ MEDIA_CACHE_MAX_BYTES,
257
+ MEDIA_CACHE_ABANDONED_MS,
258
+ contentKey,
259
+ extensionFor,
260
+ planEviction,
261
+ createMediaCache
262
+ };