@chipmobilesdk/rn-camera 0.2.0 → 0.2.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.
@@ -1,518 +1,516 @@
1
- /**
2
- * Camera controller — the object consuming apps actually drive.
3
- *
4
- * It owns observable state and orchestrates the three ports (engine,
5
- * permissions, artifact store). All I/O lives here; the decisions live in
6
- * `sessionMachine` and `captureController`, which stay pure so they can be
7
- * tested without a camera.
8
- */
9
-
10
- import {
11
- type CameraPermissionState,
12
- type CameraPosition,
13
- type CameraState,
14
- type CapabilityProfile,
15
- type CapturedImage,
16
- type CaptureRequest,
17
- type FlashMode,
18
- type StartOptions,
19
- } from '../config/types';
20
- import { CameraError, isCameraError } from '../diagnostics/errors';
21
- import { silentLogger, type CameraLogger } from '../diagnostics/logger';
22
- import type { CameraEngine } from '../native/cameraEngine';
23
- import type { PermissionPort } from '../permissions/permissionPort';
24
- import type { ArtifactStore } from '../storage/artifactStore';
25
- import { EMPTY_CAPABILITIES, assertSupported, supportsTorch } from './capabilities';
26
- import {
27
- SingleFlight,
28
- assertCaptureAllowed,
29
- finalizeResult,
30
- type CaptureContext,
31
- } from './captureController';
32
- import { canStart, initialSession, sessionReducer, type SessionSnapshot } from './sessionMachine';
33
-
34
- /** 24 hours (FR-029). */
35
- export const DEFAULT_TEMPORARY_TTL_MS = 24 * 60 * 60 * 1000;
36
-
37
- export type AppStatus = 'active' | 'background';
38
-
39
- export interface CameraControllerOptions {
40
- readonly engine?: CameraEngine;
41
- readonly permissions?: PermissionPort;
42
- readonly store?: ArtifactStore;
43
- readonly logger?: CameraLogger;
44
- readonly temporaryTtlMs?: number;
45
- /**
46
- * App foreground/background source. Defaults to React Native `AppState`.
47
- * Injectable so lifecycle rules are testable without an app (FR-015).
48
- */
49
- readonly subscribeToAppState?: (listener: (status: AppStatus) => void) => () => void;
50
- /**
51
- * Set false to skip the sweep that runs when the controller is first used
52
- * (tests). Defaults to true.
53
- */
54
- readonly sweepOnInit?: boolean;
55
- }
56
-
57
- export interface CameraController {
58
- readonly state: CameraState;
59
- subscribe(listener: (state: CameraState) => void): () => void;
60
-
61
- getPermission(): Promise<CameraPermissionState>;
62
- requestPermission(): Promise<CameraPermissionState>;
63
-
64
- start(options?: StartOptions): Promise<void>;
65
- pause(): Promise<void>;
66
- resume(): Promise<void>;
67
- stop(): Promise<void>;
68
-
69
- capture(request?: CaptureRequest): Promise<CapturedImage>;
70
- cleanup(image: CapturedImage | string): Promise<void>;
71
-
72
- getCapabilities(): Promise<CapabilityProfile>;
73
- setFlashMode(mode: FlashMode): void;
74
- setTorch(enabled: boolean): Promise<void>;
75
-
76
- /** Marks the preview surface mounted, enabling foreground auto-restart. */
77
- setSurfaceMounted(mounted: boolean): void;
78
- /**
79
- * Releases ports, listeners, and the camera. Safe to call twice. Afterwards
80
- * `start`, `resume`, `capture` and the permission and capability reads reject
81
- * with `notReady`; `stop`, `pause` and `cleanup` stay safe no-ops so teardown
82
- * code never has to check.
83
- */
84
- dispose(): Promise<void>;
85
- }
86
-
87
- function defaultAppStateSubscribe(listener: (status: AppStatus) => void): () => void {
88
- // Lazy require so importing the package outside React Native (for example in
89
- // a Node-based test runner) does not pull in the RN runtime.
90
- const { AppState } = require('react-native');
91
- const subscription = AppState.addEventListener('change', (next: string) => {
92
- listener(next === 'active' ? 'active' : 'background');
93
- });
94
- return () => subscription.remove();
95
- }
96
-
97
- export function createCameraController(
98
- options: CameraControllerOptions = {},
99
- ): CameraController {
100
- if (!options.engine || !options.permissions) {
101
- throw new CameraError(
102
- 'unsupportedCapability',
103
- 'createCameraController requires `engine` and `permissions` ports. Use the ' +
104
- 'default adapters, or createTestCamera() in tests.',
105
- );
106
- }
107
-
108
- // Bound after the guard so the closures below see non-optional ports.
109
- const engine: CameraEngine = options.engine;
110
- const permissions: PermissionPort = options.permissions;
111
- const store = options.store;
112
- const logger = options.logger ?? silentLogger;
113
- const ttlMs = options.temporaryTtlMs ?? DEFAULT_TEMPORARY_TTL_MS;
114
-
115
- let session: SessionSnapshot = initialSession;
116
- let permission: CameraPermissionState = 'undetermined';
117
- let capabilities: CapabilityProfile | null = null;
118
- let cameraPosition: CameraPosition = 'back';
119
- let flashMode: FlashMode = 'off';
120
- let torchEnabled = false;
121
- let surfaceMounted = false;
122
- let disposed = false;
123
- let appStatus: AppStatus = 'active';
124
- // Set only when backgrounding cut a running session short. Foregrounding
125
- // used to restart from any idle or stopped session, so a camera the user had
126
- // stopped — or never started, or no longer had permission for — came back on
127
- // with the app.
128
- let resumeOnForeground = false;
129
- let releasing: Promise<void> | null = null;
130
- let warnedUnmanaged = false;
131
- let detach: (() => void) | null = null;
132
-
133
- const capture = new SingleFlight();
134
- const listeners = new Set<(state: CameraState) => void>();
135
-
136
- function snapshot(): CameraState {
137
- return {
138
- session: session.status,
139
- permission,
140
- capabilities,
141
- cameraPosition,
142
- flashMode,
143
- torchEnabled,
144
- capturing: capture.busy,
145
- error: session.error
146
- ? {
147
- code: session.error.code,
148
- recoverable: session.error.recoverable,
149
- message: session.error.message,
150
- }
151
- : null,
152
- };
153
- }
154
-
155
- let current = snapshot();
156
-
157
- function emit(): void {
158
- current = snapshot();
159
- for (const listener of listeners) {
160
- // One throwing subscriber must not starve the others, nor unwind into
161
- // the transition that emitted — that left the controller half-updated.
162
- try {
163
- listener(current);
164
- } catch {
165
- logger.log({ type: 'session', code: 'listener-threw' });
166
- }
167
- }
168
- }
169
-
170
- function dispatch(event: Parameters<typeof sessionReducer>[1]): void {
171
- const next = sessionReducer(session, event);
172
- if (next !== session) {
173
- session = next;
174
- logger.log({
175
- type: 'session',
176
- code: session.status,
177
- recoverable: session.error?.recoverable,
178
- });
179
- emit();
180
- }
181
- }
182
-
183
- /** Torch must never survive leaving the active state (FR-034b). */
184
- async function forceTorchOff(): Promise<void> {
185
- if (!torchEnabled) {
186
- return;
187
- }
188
- torchEnabled = false;
189
- try {
190
- await engine.setTorch(false);
191
- } catch {
192
- // Torch-off is best effort; the session is going away regardless.
193
- }
194
- emit();
195
- }
196
-
197
- async function releaseCamera(): Promise<void> {
198
- await forceTorchOff();
199
- // Nothing to release. Going through STOP/STOPPED here turned an idle
200
- // controller into `stopped` on every preview unmount.
201
- if (session.status === 'idle' || session.status === 'stopped') {
202
- return;
203
- }
204
- dispatch({ type: 'STOP' });
205
- try {
206
- await engine.stop();
207
- dispatch({ type: 'STOPPED' });
208
- } catch (error) {
209
- dispatch({ type: 'FAIL', code: isCameraError(error) ? error.code : 'captureFailed' });
210
- }
211
- }
212
-
213
- async function startEngine(startOptions: StartOptions = {}): Promise<void> {
214
- try {
215
- await engine.start({ cameraPosition: startOptions.cameraPosition ?? cameraPosition });
216
- dispatch({ type: 'STARTED' });
217
- } catch (error) {
218
- dispatch({ type: 'FAIL', code: isCameraError(error) ? error.code : 'cameraUnavailable' });
219
- }
220
- }
221
-
222
- function resumeAfterForeground(): void {
223
- if (disposed || appStatus !== 'active' || !resumeOnForeground) {
224
- return;
225
- }
226
- resumeOnForeground = false;
227
- if (!surfaceMounted || permission !== 'granted') {
228
- return;
229
- }
230
- dispatch({ type: 'FOREGROUND', surfaceMounted });
231
- if (session.status === 'starting') {
232
- startEngine().catch(() => undefined);
233
- }
234
- }
235
-
236
- function onAppState(status: AppStatus): void {
237
- appStatus = status;
238
- if (status === 'background') {
239
- resumeOnForeground ||= session.status === 'active' || session.status === 'starting';
240
- dispatch({ type: 'BACKGROUND' });
241
- releasing = releaseCamera().catch(() => undefined);
242
- } else {
243
- // Wait for a release still in flight, or the restart lands on a
244
- // `stopping` session and is dropped.
245
- (releasing ?? Promise.resolve()).then(resumeAfterForeground).catch(() => undefined);
246
- }
247
- }
248
-
249
- /**
250
- * Subscribes to permission and app-state changes and runs the sweep, on first
251
- * use rather than at construction. React may build a controller during a
252
- * render it then throws away (StrictMode does so on purpose); construction
253
- * that subscribed leaked a listener pair every time.
254
- */
255
- function attach(): void {
256
- if (detach || disposed) {
257
- return;
258
- }
259
- const unsubscribePermission = permissions.subscribe(next => {
260
- permission = next;
261
- logger.log({ type: 'permission', code: next });
262
- emit();
263
- // A revocation while running must tear the session down, not leave a
264
- // frozen preview on screen (FR-007).
265
- if (next !== 'granted') {
266
- resumeOnForeground = false;
267
- if (session.status !== 'idle' && session.status !== 'stopped') {
268
- releaseCamera().catch(() => undefined);
269
- }
270
- }
271
- });
272
- const unsubscribeAppState = (options.subscribeToAppState ?? defaultAppStateSubscribe)(
273
- onAppState,
274
- );
275
- detach = () => {
276
- unsubscribePermission();
277
- unsubscribeAppState();
278
- };
279
-
280
- // FR-029: sweep our own temp directory once, asynchronously, so it can
281
- // never add latency to the capture path or the preview start.
282
- if (store && options.sweepOnInit !== false) {
283
- store
284
- .sweep(ttlMs)
285
- .then(removed => {
286
- if (removed > 0) {
287
- logger.log({ type: 'cleanup', code: `swept:${removed}` });
288
- }
289
- })
290
- .catch(() => {
291
- // A failed sweep must never block startup.
292
- });
293
- }
294
- }
295
-
296
- /** Entry guard for operations that need a live controller. */
297
- function live(operation: string): void {
298
- if (disposed) {
299
- throw new CameraError('notReady', `${operation}() called on a disposed camera controller`);
300
- }
301
- attach();
302
- }
303
-
304
- /**
305
- * Puts a package-temporary capture under the store so `cleanup()` and the
306
- * sweep can reach it. Never throws: the capture itself succeeded, and a file
307
- * the store cannot manage is still a usable photo.
308
- */
309
- async function manage(image: CapturedImage): Promise<CapturedImage> {
310
- if (image.ownership !== 'packageTemporary') {
311
- return image;
312
- }
313
- if (store?.adopt) {
314
- try {
315
- return { ...image, uri: await store.adopt(image.uri) };
316
- } catch {
317
- logger.log({ type: 'cleanup', code: 'adopt-failed' });
318
- return image;
319
- }
320
- }
321
- if (!store?.owns(image.uri) && !warnedUnmanaged) {
322
- warnedUnmanaged = true;
323
- logger.log({ type: 'cleanup', code: store ? 'unmanaged:store-cannot-adopt' : 'unmanaged:no-store' });
324
- }
325
- return image;
326
- }
327
-
328
- const controller: CameraController = {
329
- get state() {
330
- return current;
331
- },
332
-
333
- subscribe(listener) {
334
- if (disposed) {
335
- return () => undefined;
336
- }
337
- attach();
338
- listeners.add(listener);
339
- return () => {
340
- listeners.delete(listener);
341
- };
342
- },
343
-
344
- async getPermission() {
345
- live('getPermission');
346
- permission = await permissions.getStatus();
347
- emit();
348
- return permission;
349
- },
350
-
351
- async requestPermission() {
352
- live('requestPermission');
353
- permission = 'requesting';
354
- emit();
355
- permission = await permissions.request();
356
- emit();
357
- return permission;
358
- },
359
-
360
- async start(startOptions: StartOptions = {}) {
361
- live('start');
362
- if (permission !== 'granted') {
363
- dispatch({ type: 'FAIL', code: 'permissionDenied' });
364
- throw new CameraError('permissionDenied', 'Camera permission is not granted');
365
- }
366
- if (!canStart(session.status)) {
367
- throw new CameraError('sessionConflict', `Session already ${session.status}`);
368
- }
369
- if (startOptions.cameraPosition) {
370
- cameraPosition = startOptions.cameraPosition;
371
- }
372
- dispatch({ type: 'START' });
373
- await startEngine(startOptions);
374
- if (session.error) {
375
- throw session.error;
376
- }
377
- },
378
-
379
- async pause() {
380
- if (disposed) {
381
- return;
382
- }
383
- await forceTorchOff();
384
- dispatch({ type: 'PAUSE' });
385
- },
386
-
387
- async resume() {
388
- live('resume');
389
- dispatch({ type: 'RESUME' });
390
- if (session.status === 'starting') {
391
- await startEngine();
392
- }
393
- },
394
-
395
- async stop() {
396
- // An explicit stop is the user's decision; foregrounding must not undo it.
397
- resumeOnForeground = false;
398
- if (disposed) {
399
- return;
400
- }
401
- await releaseCamera();
402
- },
403
-
404
- async capture(request: CaptureRequest = {}) {
405
- live('capture');
406
- const context: CaptureContext = {
407
- engine,
408
- sessionStatus: session.status,
409
- permissionGranted: permission === 'granted',
410
- capabilities,
411
- cameraPosition,
412
- flashMode,
413
- };
414
- // Guards run before the single-flight slot is taken so a rejected
415
- // request cannot block a subsequent legal one.
416
- assertCaptureAllowed(context, request);
417
-
418
- try {
419
- const result = await capture.run(async () => {
420
- emit();
421
- const raw = await engine.capture({
422
- ...request,
423
- flashMode: request.flashMode ?? flashMode,
424
- cameraPosition: request.cameraPosition ?? cameraPosition,
425
- });
426
- return manage(finalizeResult(raw, request, context));
427
- });
428
- logger.log({ type: 'capture', code: 'succeeded' });
429
- return result;
430
- } catch (error) {
431
- // The contract promises a CameraError; a raw native error carries
432
- // no code to branch on and its message may hold a file path.
433
- const failure = isCameraError(error)
434
- ? error
435
- : new CameraError('captureFailed', 'The camera failed to capture a photo');
436
- logger.log({ type: 'capture', code: failure.code, recoverable: failure.recoverable });
437
- throw failure;
438
- } finally {
439
- // Without this a failed capture left `capturing: true` published
440
- // until some unrelated change emitted again.
441
- emit();
442
- }
443
- },
444
-
445
- async cleanup(image: CapturedImage | string) {
446
- const uri = typeof image === 'string' ? image : image.uri;
447
- if (!store) {
448
- return;
449
- }
450
- // Refuse anything we did not create rather than deleting an arbitrary
451
- // path, which also covers every appOwned artifact (FR-026b, FR-028).
452
- if (!store.owns(uri)) {
453
- logger.log({ type: 'cleanup', code: 'refused-not-owned' });
454
- return;
455
- }
456
- await store.remove(uri);
457
- logger.log({ type: 'cleanup', code: 'removed' });
458
- },
459
-
460
- async getCapabilities() {
461
- live('getCapabilities');
462
- try {
463
- capabilities = await engine.getCapabilities();
464
- } catch {
465
- capabilities = EMPTY_CAPABILITIES;
466
- }
467
- logger.log({
468
- type: 'capability',
469
- code: capabilities.hasCameraHardware ? 'available' : 'no-hardware',
470
- });
471
- emit();
472
- return capabilities;
473
- },
474
-
475
- setFlashMode(mode: FlashMode) {
476
- assertSupported(
477
- mode === 'off' || capabilities?.hasFlash === true,
478
- `flash mode "${mode}"`,
479
- );
480
- flashMode = mode;
481
- emit();
482
- },
483
-
484
- async setTorch(enabled: boolean) {
485
- if (disposed && !enabled) {
486
- return;
487
- }
488
- live('setTorch');
489
- if (enabled) {
490
- assertSupported(supportsTorch(capabilities), 'torch');
491
- }
492
- await engine.setTorch(enabled);
493
- torchEnabled = enabled;
494
- emit();
495
- },
496
-
497
- setSurfaceMounted(mounted: boolean) {
498
- if (disposed) {
499
- return;
500
- }
501
- surfaceMounted = mounted;
502
- },
503
-
504
- async dispose() {
505
- if (disposed) {
506
- return;
507
- }
508
- disposed = true;
509
- resumeOnForeground = false;
510
- detach?.();
511
- detach = null;
512
- await releaseCamera();
513
- listeners.clear();
514
- },
515
- };
516
-
517
- return controller;
518
- }
1
+ /**
2
+ * Camera controller — the object consuming apps actually drive.
3
+ *
4
+ * It owns observable state and orchestrates the three ports (engine,
5
+ * permissions, artifact store). All I/O lives here; the decisions live in
6
+ * `sessionMachine` and `captureController`, which stay pure so they can be
7
+ * tested without a camera.
8
+ */
9
+
10
+ import {
11
+ type CameraPermissionState,
12
+ type CameraPosition,
13
+ type CameraState,
14
+ type CapabilityProfile,
15
+ type CapturedImage,
16
+ type CaptureRequest,
17
+ type FlashMode,
18
+ type StartOptions,
19
+ } from '../config/types';
20
+ import { CameraError, isCameraError } from '../diagnostics/errors';
21
+ import { silentLogger, type CameraLogger } from '../diagnostics/logger';
22
+ import type { CameraEngine } from '../native/cameraEngine';
23
+ import type { PermissionPort } from '../permissions/permissionPort';
24
+ import type { ArtifactStore } from '../storage/artifactStore';
25
+ import { EMPTY_CAPABILITIES, assertSupported, supportsTorch } from './capabilities';
26
+ import {
27
+ SingleFlight,
28
+ assertCaptureAllowed,
29
+ finalizeResult,
30
+ type CaptureContext,
31
+ } from './captureController';
32
+ import { canStart, initialSession, sessionReducer, type SessionSnapshot } from './sessionMachine';
33
+
34
+ /** 24 hours (FR-029). */
35
+ export const DEFAULT_TEMPORARY_TTL_MS = 24 * 60 * 60 * 1000;
36
+
37
+ export type AppStatus = 'active' | 'background';
38
+
39
+ export interface CameraControllerOptions {
40
+ readonly engine?: CameraEngine;
41
+ readonly permissions?: PermissionPort;
42
+ readonly store?: ArtifactStore;
43
+ readonly logger?: CameraLogger;
44
+ readonly temporaryTtlMs?: number;
45
+ /**
46
+ * App foreground/background source. Defaults to React Native `AppState`.
47
+ * Injectable so lifecycle rules are testable without an app (FR-015).
48
+ */
49
+ readonly subscribeToAppState?: (listener: (status: AppStatus) => void) => () => void;
50
+ /**
51
+ * Set false to skip the sweep that runs when the controller is first used
52
+ * (tests). Defaults to true.
53
+ */
54
+ readonly sweepOnInit?: boolean;
55
+ }
56
+
57
+ export interface CameraController {
58
+ readonly state: CameraState;
59
+ subscribe(listener: (state: CameraState) => void): () => void;
60
+
61
+ getPermission(): Promise<CameraPermissionState>;
62
+ requestPermission(): Promise<CameraPermissionState>;
63
+
64
+ start(options?: StartOptions): Promise<void>;
65
+ pause(): Promise<void>;
66
+ resume(): Promise<void>;
67
+ stop(): Promise<void>;
68
+
69
+ capture(request?: CaptureRequest): Promise<CapturedImage>;
70
+ cleanup(image: CapturedImage | string): Promise<void>;
71
+
72
+ getCapabilities(): Promise<CapabilityProfile>;
73
+ setFlashMode(mode: FlashMode): void;
74
+ setTorch(enabled: boolean): Promise<void>;
75
+
76
+ /** Marks the preview surface mounted, enabling foreground auto-restart. */
77
+ setSurfaceMounted(mounted: boolean): void;
78
+ /**
79
+ * Releases ports, listeners, and the camera. Safe to call twice. Afterwards
80
+ * `start`, `resume`, `capture` and the permission and capability reads reject
81
+ * with `notReady`; `stop`, `pause` and `cleanup` stay safe no-ops so teardown
82
+ * code never has to check.
83
+ */
84
+ dispose(): Promise<void>;
85
+ }
86
+
87
+ function defaultAppStateSubscribe(listener: (status: AppStatus) => void): () => void {
88
+ // Lazy require so importing the package outside React Native (for example in
89
+ // a Node-based test runner) does not pull in the RN runtime.
90
+ const { AppState } = require('react-native');
91
+ const subscription = AppState.addEventListener('change', (next: string) => {
92
+ listener(next === 'active' ? 'active' : 'background');
93
+ });
94
+ return () => subscription.remove();
95
+ }
96
+
97
+ export function createCameraController(options: CameraControllerOptions = {}): CameraController {
98
+ if (!options.engine || !options.permissions) {
99
+ throw new CameraError(
100
+ 'unsupportedCapability',
101
+ 'createCameraController requires `engine` and `permissions` ports. Use the ' +
102
+ 'default adapters, or createTestCamera() in tests.',
103
+ );
104
+ }
105
+
106
+ // Bound after the guard so the closures below see non-optional ports.
107
+ const engine: CameraEngine = options.engine;
108
+ const permissions: PermissionPort = options.permissions;
109
+ const store = options.store;
110
+ const logger = options.logger ?? silentLogger;
111
+ const ttlMs = options.temporaryTtlMs ?? DEFAULT_TEMPORARY_TTL_MS;
112
+
113
+ let session: SessionSnapshot = initialSession;
114
+ let permission: CameraPermissionState = 'undetermined';
115
+ let capabilities: CapabilityProfile | null = null;
116
+ let cameraPosition: CameraPosition = 'back';
117
+ let flashMode: FlashMode = 'off';
118
+ let torchEnabled = false;
119
+ let surfaceMounted = false;
120
+ let disposed = false;
121
+ let appStatus: AppStatus = 'active';
122
+ // Set only when backgrounding cut a running session short. Foregrounding
123
+ // used to restart from any idle or stopped session, so a camera the user had
124
+ // stopped — or never started, or no longer had permission for — came back on
125
+ // with the app.
126
+ let resumeOnForeground = false;
127
+ let releasing: Promise<void> | null = null;
128
+ let warnedUnmanaged = false;
129
+ let detach: (() => void) | null = null;
130
+
131
+ const capture = new SingleFlight();
132
+ const listeners = new Set<(state: CameraState) => void>();
133
+
134
+ function snapshot(): CameraState {
135
+ return {
136
+ session: session.status,
137
+ permission,
138
+ capabilities,
139
+ cameraPosition,
140
+ flashMode,
141
+ torchEnabled,
142
+ capturing: capture.busy,
143
+ error: session.error
144
+ ? {
145
+ code: session.error.code,
146
+ recoverable: session.error.recoverable,
147
+ message: session.error.message,
148
+ }
149
+ : null,
150
+ };
151
+ }
152
+
153
+ let current = snapshot();
154
+
155
+ function emit(): void {
156
+ current = snapshot();
157
+ for (const listener of listeners) {
158
+ // One throwing subscriber must not starve the others, nor unwind into
159
+ // the transition that emitted — that left the controller half-updated.
160
+ try {
161
+ listener(current);
162
+ } catch {
163
+ logger.log({ type: 'session', code: 'listener-threw' });
164
+ }
165
+ }
166
+ }
167
+
168
+ function dispatch(event: Parameters<typeof sessionReducer>[1]): void {
169
+ const next = sessionReducer(session, event);
170
+ if (next !== session) {
171
+ session = next;
172
+ logger.log({
173
+ type: 'session',
174
+ code: session.status,
175
+ recoverable: session.error?.recoverable,
176
+ });
177
+ emit();
178
+ }
179
+ }
180
+
181
+ /** Torch must never survive leaving the active state (FR-034b). */
182
+ async function forceTorchOff(): Promise<void> {
183
+ if (!torchEnabled) {
184
+ return;
185
+ }
186
+ torchEnabled = false;
187
+ try {
188
+ await engine.setTorch(false);
189
+ } catch {
190
+ // Torch-off is best effort; the session is going away regardless.
191
+ }
192
+ emit();
193
+ }
194
+
195
+ async function releaseCamera(): Promise<void> {
196
+ await forceTorchOff();
197
+ // Nothing to release. Going through STOP/STOPPED here turned an idle
198
+ // controller into `stopped` on every preview unmount.
199
+ if (session.status === 'idle' || session.status === 'stopped') {
200
+ return;
201
+ }
202
+ dispatch({ type: 'STOP' });
203
+ try {
204
+ await engine.stop();
205
+ dispatch({ type: 'STOPPED' });
206
+ } catch (error) {
207
+ dispatch({ type: 'FAIL', code: isCameraError(error) ? error.code : 'captureFailed' });
208
+ }
209
+ }
210
+
211
+ async function startEngine(startOptions: StartOptions = {}): Promise<void> {
212
+ try {
213
+ await engine.start({ cameraPosition: startOptions.cameraPosition ?? cameraPosition });
214
+ dispatch({ type: 'STARTED' });
215
+ } catch (error) {
216
+ dispatch({ type: 'FAIL', code: isCameraError(error) ? error.code : 'cameraUnavailable' });
217
+ }
218
+ }
219
+
220
+ function resumeAfterForeground(): void {
221
+ if (disposed || appStatus !== 'active' || !resumeOnForeground) {
222
+ return;
223
+ }
224
+ resumeOnForeground = false;
225
+ if (!surfaceMounted || permission !== 'granted') {
226
+ return;
227
+ }
228
+ dispatch({ type: 'FOREGROUND', surfaceMounted });
229
+ if (session.status === 'starting') {
230
+ startEngine().catch(() => undefined);
231
+ }
232
+ }
233
+
234
+ function onAppState(status: AppStatus): void {
235
+ appStatus = status;
236
+ if (status === 'background') {
237
+ resumeOnForeground ||= session.status === 'active' || session.status === 'starting';
238
+ dispatch({ type: 'BACKGROUND' });
239
+ releasing = releaseCamera().catch(() => undefined);
240
+ } else {
241
+ // Wait for a release still in flight, or the restart lands on a
242
+ // `stopping` session and is dropped.
243
+ (releasing ?? Promise.resolve()).then(resumeAfterForeground).catch(() => undefined);
244
+ }
245
+ }
246
+
247
+ /**
248
+ * Subscribes to permission and app-state changes and runs the sweep, on first
249
+ * use rather than at construction. React may build a controller during a
250
+ * render it then throws away (StrictMode does so on purpose); construction
251
+ * that subscribed leaked a listener pair every time.
252
+ */
253
+ function attach(): void {
254
+ if (detach || disposed) {
255
+ return;
256
+ }
257
+ const unsubscribePermission = permissions.subscribe(next => {
258
+ permission = next;
259
+ logger.log({ type: 'permission', code: next });
260
+ emit();
261
+ // A revocation while running must tear the session down, not leave a
262
+ // frozen preview on screen (FR-007).
263
+ if (next !== 'granted') {
264
+ resumeOnForeground = false;
265
+ if (session.status !== 'idle' && session.status !== 'stopped') {
266
+ releaseCamera().catch(() => undefined);
267
+ }
268
+ }
269
+ });
270
+ const unsubscribeAppState = (options.subscribeToAppState ?? defaultAppStateSubscribe)(
271
+ onAppState,
272
+ );
273
+ detach = () => {
274
+ unsubscribePermission();
275
+ unsubscribeAppState();
276
+ };
277
+
278
+ // FR-029: sweep our own temp directory once, asynchronously, so it can
279
+ // never add latency to the capture path or the preview start.
280
+ if (store && options.sweepOnInit !== false) {
281
+ store
282
+ .sweep(ttlMs)
283
+ .then(removed => {
284
+ if (removed > 0) {
285
+ logger.log({ type: 'cleanup', code: `swept:${removed}` });
286
+ }
287
+ })
288
+ .catch(() => {
289
+ // A failed sweep must never block startup.
290
+ });
291
+ }
292
+ }
293
+
294
+ /** Entry guard for operations that need a live controller. */
295
+ function live(operation: string): void {
296
+ if (disposed) {
297
+ throw new CameraError('notReady', `${operation}() called on a disposed camera controller`);
298
+ }
299
+ attach();
300
+ }
301
+
302
+ /**
303
+ * Puts a package-temporary capture under the store so `cleanup()` and the
304
+ * sweep can reach it. Never throws: the capture itself succeeded, and a file
305
+ * the store cannot manage is still a usable photo.
306
+ */
307
+ async function manage(image: CapturedImage): Promise<CapturedImage> {
308
+ if (image.ownership !== 'packageTemporary') {
309
+ return image;
310
+ }
311
+ if (store?.adopt) {
312
+ try {
313
+ return { ...image, uri: await store.adopt(image.uri) };
314
+ } catch {
315
+ logger.log({ type: 'cleanup', code: 'adopt-failed' });
316
+ return image;
317
+ }
318
+ }
319
+ if (!store?.owns(image.uri) && !warnedUnmanaged) {
320
+ warnedUnmanaged = true;
321
+ logger.log({
322
+ type: 'cleanup',
323
+ code: store ? 'unmanaged:store-cannot-adopt' : 'unmanaged:no-store',
324
+ });
325
+ }
326
+ return image;
327
+ }
328
+
329
+ const controller: CameraController = {
330
+ get state() {
331
+ return current;
332
+ },
333
+
334
+ subscribe(listener) {
335
+ if (disposed) {
336
+ return () => undefined;
337
+ }
338
+ attach();
339
+ listeners.add(listener);
340
+ return () => {
341
+ listeners.delete(listener);
342
+ };
343
+ },
344
+
345
+ async getPermission() {
346
+ live('getPermission');
347
+ permission = await permissions.getStatus();
348
+ emit();
349
+ return permission;
350
+ },
351
+
352
+ async requestPermission() {
353
+ live('requestPermission');
354
+ permission = 'requesting';
355
+ emit();
356
+ permission = await permissions.request();
357
+ emit();
358
+ return permission;
359
+ },
360
+
361
+ async start(startOptions: StartOptions = {}) {
362
+ live('start');
363
+ if (permission !== 'granted') {
364
+ dispatch({ type: 'FAIL', code: 'permissionDenied' });
365
+ throw new CameraError('permissionDenied', 'Camera permission is not granted');
366
+ }
367
+ if (!canStart(session.status)) {
368
+ throw new CameraError('sessionConflict', `Session already ${session.status}`);
369
+ }
370
+ if (startOptions.cameraPosition) {
371
+ cameraPosition = startOptions.cameraPosition;
372
+ }
373
+ dispatch({ type: 'START' });
374
+ await startEngine(startOptions);
375
+ if (session.error) {
376
+ throw session.error;
377
+ }
378
+ },
379
+
380
+ async pause() {
381
+ if (disposed) {
382
+ return;
383
+ }
384
+ await forceTorchOff();
385
+ dispatch({ type: 'PAUSE' });
386
+ },
387
+
388
+ async resume() {
389
+ live('resume');
390
+ dispatch({ type: 'RESUME' });
391
+ if (session.status === 'starting') {
392
+ await startEngine();
393
+ }
394
+ },
395
+
396
+ async stop() {
397
+ // An explicit stop is the user's decision; foregrounding must not undo it.
398
+ resumeOnForeground = false;
399
+ if (disposed) {
400
+ return;
401
+ }
402
+ await releaseCamera();
403
+ },
404
+
405
+ async capture(request: CaptureRequest = {}) {
406
+ live('capture');
407
+ const context: CaptureContext = {
408
+ engine,
409
+ sessionStatus: session.status,
410
+ permissionGranted: permission === 'granted',
411
+ capabilities,
412
+ cameraPosition,
413
+ flashMode,
414
+ };
415
+ // Guards run before the single-flight slot is taken so a rejected
416
+ // request cannot block a subsequent legal one.
417
+ assertCaptureAllowed(context, request);
418
+
419
+ try {
420
+ const result = await capture.run(async () => {
421
+ emit();
422
+ const raw = await engine.capture({
423
+ ...request,
424
+ flashMode: request.flashMode ?? flashMode,
425
+ cameraPosition: request.cameraPosition ?? cameraPosition,
426
+ });
427
+ return manage(finalizeResult(raw, request, context));
428
+ });
429
+ logger.log({ type: 'capture', code: 'succeeded' });
430
+ return result;
431
+ } catch (error) {
432
+ // The contract promises a CameraError; a raw native error carries
433
+ // no code to branch on and its message may hold a file path.
434
+ const failure = isCameraError(error)
435
+ ? error
436
+ : new CameraError('captureFailed', 'The camera failed to capture a photo');
437
+ logger.log({ type: 'capture', code: failure.code, recoverable: failure.recoverable });
438
+ throw failure;
439
+ } finally {
440
+ // Without this a failed capture left `capturing: true` published
441
+ // until some unrelated change emitted again.
442
+ emit();
443
+ }
444
+ },
445
+
446
+ async cleanup(image: CapturedImage | string) {
447
+ const uri = typeof image === 'string' ? image : image.uri;
448
+ if (!store) {
449
+ return;
450
+ }
451
+ // Refuse anything we did not create rather than deleting an arbitrary
452
+ // path, which also covers every appOwned artifact (FR-026b, FR-028).
453
+ if (!store.owns(uri)) {
454
+ logger.log({ type: 'cleanup', code: 'refused-not-owned' });
455
+ return;
456
+ }
457
+ await store.remove(uri);
458
+ logger.log({ type: 'cleanup', code: 'removed' });
459
+ },
460
+
461
+ async getCapabilities() {
462
+ live('getCapabilities');
463
+ try {
464
+ capabilities = await engine.getCapabilities();
465
+ } catch {
466
+ capabilities = EMPTY_CAPABILITIES;
467
+ }
468
+ logger.log({
469
+ type: 'capability',
470
+ code: capabilities.hasCameraHardware ? 'available' : 'no-hardware',
471
+ });
472
+ emit();
473
+ return capabilities;
474
+ },
475
+
476
+ setFlashMode(mode: FlashMode) {
477
+ assertSupported(mode === 'off' || capabilities?.hasFlash === true, `flash mode "${mode}"`);
478
+ flashMode = mode;
479
+ emit();
480
+ },
481
+
482
+ async setTorch(enabled: boolean) {
483
+ if (disposed && !enabled) {
484
+ return;
485
+ }
486
+ live('setTorch');
487
+ if (enabled) {
488
+ assertSupported(supportsTorch(capabilities), 'torch');
489
+ }
490
+ await engine.setTorch(enabled);
491
+ torchEnabled = enabled;
492
+ emit();
493
+ },
494
+
495
+ setSurfaceMounted(mounted: boolean) {
496
+ if (disposed) {
497
+ return;
498
+ }
499
+ surfaceMounted = mounted;
500
+ },
501
+
502
+ async dispose() {
503
+ if (disposed) {
504
+ return;
505
+ }
506
+ disposed = true;
507
+ resumeOnForeground = false;
508
+ detach?.();
509
+ detach = null;
510
+ await releaseCamera();
511
+ listeners.clear();
512
+ },
513
+ };
514
+
515
+ return controller;
516
+ }