scandit-react-native-datacapture-core 8.6.1 → 8.7.0-beta.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/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import { CORE_PROXY_TYPE_NAMES, registerCoreProxies, loadCoreDefaults, setCoreDefaultsLoader, BaseDataCaptureView, DataCaptureContext, TorchState, CameraPosition, Camera, FrameSourceState } from './core.js';
2
- export { AimerViewfinder, Anchor, Brush, CameraSettings, CameraSwitchControl, ClusteringMode, Color, ContextStatus, DataCaptureContextSettings, Direction, Expiration, Feedback, FocusGestureStrategy, FocusRange, FontFamily, FrameDataSettings, FrameDataSettingsBuilder, ImageBuffer, ImageFrameSource, LaserlineViewfinder, LicenseInfo, LogoStyle, MacroMode, MarginsWithUnit, MeasureUnit, NoViewfinder, NoneLocationSelection, NumberWithUnit, OpenSourceSoftwareLicenseInfo, Orientation, PinchToZoom, Point, PointWithUnit, Quadrilateral, RadiusLocationSelection, Rect, RectWithUnit, RectangularLocationSelection, RectangularViewfinder, RectangularViewfinderAnimation, RectangularViewfinderLineStyle, RectangularViewfinderStyle, ScanIntention, ScanditIcon, ScanditIconBuilder, ScanditIconShape, ScanditIconType, SelectionMode, SequenceFrameSource, Size, SizeWithAspect, SizeWithUnit, SizeWithUnitAndAspect, SizingMode, Sound, SwipeToZoom, TapToFocus, TextAlignment, TorchSwitchControl, Vibration, VibrationType, VideoResolution, WaveFormVibration, ZoomSwitchControl, ZoomSwitchOrientation } from './core.js';
1
+ import { CORE_PROXY_TYPE_NAMES, registerCoreProxies, FactoryMaker, loadCoreDefaults, setCoreDefaultsLoader, buildStaticCoreDefaultsJson, getCoreDefaults, BaseDataCaptureView, DataCaptureContext, TorchState, CameraPosition, Camera, FrameSourceState } from './core.js';
2
+ export { AimerViewfinder, Anchor, Brush, CameraSettings, CameraSwitchControl, ClusteringMode, Color, ColorFillOverlay, ContextStatus, DEFAULT_CATEGORIES, DataCaptureContextSettings, Direction, Expiration, Feedback, FocusGestureStrategy, FocusRange, FontFamily, FrameDataSettings, FrameDataSettingsBuilder, ImageBuffer, ImageFrameSource, LaserlineViewfinder, LicenseInfo, LogCategory, LogLevel, LogoStyle, MacroMode, MarginsWithUnit, MeasureUnit, NoViewfinder, NoneLocationSelection, NumberWithUnit, OpenSourceSoftwareLicenseInfo, Orientation, PinchToZoom, Point, PointWithUnit, Quadrilateral, RadiusLocationSelection, Rect, RectWithUnit, RectangularLocationSelection, RectangularViewfinder, RectangularViewfinderAnimation, RectangularViewfinderLineStyle, RectangularViewfinderStyle, ScanIntention, ScanditIcon, ScanditIconBuilder, ScanditIconShape, ScanditIconType, ScanditLogger, SelectionMode, SequenceFrameSource, Size, SizeWithAspect, SizeWithUnit, SizeWithUnitAndAspect, SizingMode, Sound, SwipeToZoom, TapToFocus, TextAlignment, TorchSwitchControl, Vibration, VibrationType, VideoResolution, WaveFormVibration, ZoomSwitchControl, ZoomSwitchOrientation } from './core.js';
3
3
  import { NativeEventEmitter, Platform, NativeModules, TurboModuleRegistry, findNodeHandle, requireNativeComponent, AppState, PermissionsAndroid } from 'react-native';
4
- import React, { useState, useEffect, useCallback, useMemo, createContext, useContext, useRef, useLayoutEffect } from 'react';
4
+ import React, { useState, useEffect, useCallback, useMemo, useRef, createContext, useContext, useLayoutEffect } from 'react';
5
5
 
6
6
  class RNNativeCaller {
7
7
  nativeModule;
@@ -109,39 +109,91 @@ function getNativeModule(name) {
109
109
  }
110
110
  throw new Error(`Module ${name} not found. Ensure the native module is properly linked.`);
111
111
  }
112
- function getModuleDefaults(name) {
112
+ /**
113
+ * Returns the dynamic residual exposed by native as `DynamicDefaults` (device id, SDK version,
114
+ * probed camera positions, localized accessibility labels, ...). Every supported version of the
115
+ * native side exposes it, so there is no legacy full-`Defaults`-blob fallback anymore
116
+ * (SDC-32175/SDC-32178).
117
+ */
118
+ function getModuleDynamicDefaults(name) {
113
119
  const mod = getNativeModule(name);
114
- // Constants are automatically merged by React Native
115
- const defaults = mod.Defaults;
116
- if (defaults) {
117
- // Our modules will always be returned by Defaults property, the legacy
118
- // code is there just to ensure compatibility with older versions of React Native.
119
- return defaults;
120
- }
121
- // Fallback: Try getConstants() directly
120
+ const dynamicDefaults = mod.DynamicDefaults;
121
+ if (dynamicDefaults) {
122
+ return dynamicDefaults;
123
+ }
122
124
  if (typeof mod.getConstants === 'function') {
123
125
  const constants = mod.getConstants();
124
- if (constants?.Defaults) {
125
- return constants.Defaults;
126
+ if (constants?.DynamicDefaults) {
127
+ return constants.DynamicDefaults;
126
128
  }
127
129
  }
128
- throw new Error(`Could not load Defaults from module ${name}`);
130
+ throw new Error(`Could not load DynamicDefaults from module ${name}`);
129
131
  }
130
132
 
133
+ // RN has no plugin-init gate: user code constructs Camera.default (etc.) immediately at import
134
+ // time, so the dynamic residual (device id, SDK version, probed camera positions, localized
135
+ // accessibility label) must be read synchronously here, not via an async round-trip.
131
136
  function initCoreDefaults() {
132
- // Use helper to get defaults with fallback logic
133
- const defaults = getModuleDefaults('ScanditDataCaptureCore');
134
- loadCoreDefaults(defaults);
137
+ const platform = Platform.OS === 'ios' ? 'ios' : 'android';
138
+ // Merge raw JSON into raw JSON, then let loadCoreDefaults produce the typed object — never
139
+ // merge into the already-parsed one. Merging into parsed values happens to work while the
140
+ // residual is strings/arrays, but the first dynamic key that parsing converts (a Color, Brush
141
+ // or PointWithUnit) would land as raw JSON inside a typed object and fail silently at the
142
+ // consumer, far from here.
143
+ const merged = buildStaticCoreDefaultsJson(platform);
144
+ deepMerge(merged, getModuleDynamicDefaults('ScanditDataCaptureCore'));
145
+ // bindInstanceIfNotExists would no-op on a second load, so drop the binding first.
146
+ FactoryMaker.instances.delete('CoreDefaults');
147
+ loadCoreDefaults(merged);
148
+ }
149
+ // Keys whose assignment would mutate the prototype chain instead of setting a data property.
150
+ // The payload comes from our own native code, but JSON.parse can produce an own "__proto__" key
151
+ // and Object.keys lists it, so the bracket assignment below is guarded.
152
+ const UNSAFE_MERGE_KEYS = ['__proto__', 'constructor', 'prototype'];
153
+ function deepMerge(target, source) {
154
+ for (const key of Object.keys(source)) {
155
+ if (UNSAFE_MERGE_KEYS.includes(key)) {
156
+ continue;
157
+ }
158
+ const sourceValue = source[key];
159
+ const targetValue = target[key];
160
+ // Both sides must be plain objects to recurse: an array on either side is replaced wholesale,
161
+ // never merged key-by-key (which would leave numeric-index pollution behind).
162
+ if (sourceValue &&
163
+ targetValue &&
164
+ typeof sourceValue === 'object' &&
165
+ typeof targetValue === 'object' &&
166
+ !Array.isArray(sourceValue) &&
167
+ !Array.isArray(targetValue)) {
168
+ // Copy-on-write: buildStatic*DefaultsJson hands out REFERENCES to module-level generated
169
+ // constants, so recursing straight into targetValue would write the dynamic value into the
170
+ // generated constant and corrupt it process-wide for every later caller. Descend into a
171
+ // shallow copy instead.
172
+ const branch = { ...targetValue };
173
+ target[key] = branch;
174
+ deepMerge(branch, sourceValue);
175
+ }
176
+ else {
177
+ target[key] = sourceValue;
178
+ }
179
+ }
135
180
  }
136
181
  setCoreDefaultsLoader(initCoreDefaults);
137
182
 
138
- const NativeModule = getNativeModule('ScanditDataCaptureCore');
139
183
  class DataCaptureVersion {
140
184
  static get pluginVersion() {
141
- return '8.6.1';
185
+ return '8.7.0-beta.1';
142
186
  }
187
+ /**
188
+ * Version of the native SDK the plugin is running against.
189
+ *
190
+ * Read from the Core defaults singleton, which `initCoreDefaults()` populates from the native
191
+ * `DynamicDefaults` payload at import time. This used to read a flat `NativeModule.Version`
192
+ * constant, which native stopped exposing when the residual moved under `DynamicDefaults`
193
+ * (SDC-32175 / SDC-32178) — so it had been returning undefined.
194
+ */
143
195
  static get sdkVersion() {
144
- return NativeModule.Version;
196
+ return getCoreDefaults().Version ?? '';
145
197
  }
146
198
  }
147
199
 
@@ -277,11 +329,15 @@ class DataCaptureView extends React.Component {
277
329
  // starvable by a blocked JS interaction queue (e.g. a looping animation with
278
330
  // `useNativeDriver: false`), which previously left the preview never created.
279
331
  // See SDC-32208. `onLayout` can fire repeatedly, so create exactly once.
332
+ // SDC-33139: kick off creation BEFORE forwarding onLayout, since a caller
333
+ // may call a view method (e.g. show()) from its own onLayout. Base-view
334
+ // methods already gate on creation completing, so only the kickoff order
335
+ // matters here.
280
336
  onNativeViewLayout = (event) => {
337
+ this.tryCreateDataCaptureView();
281
338
  // Forward to a caller-supplied onLayout so our internal handler doesn't
282
339
  // swallow it (render() overrides the spread `onLayout` with this one).
283
340
  this.props.onLayout?.(event);
284
- this.tryCreateDataCaptureView();
285
341
  };
286
342
  // Attempt to create the native view exactly once. Returns true once creation
287
343
  // has been kicked off, false if the native tag is not available yet (so a
@@ -326,7 +382,7 @@ const RNTDataCaptureView = requireNativeComponent('RNTDataCaptureView');
326
382
  * ```tsx
327
383
  * const isForeground = useIsForeground();
328
384
  * const isFocused = useIsFocused(); // from @react-navigation/native
329
- * <BarcodeCaptureView isActive={isFocused && isForeground} ... />
385
+ * <BarcodeCaptureAioView isActive={isFocused && isForeground} ... />
330
386
  * ```
331
387
  */
332
388
  function useIsForeground() {
@@ -374,7 +430,7 @@ async function requestAndroidPermission() {
374
430
  * On iOS this hook returns `permissionStatus: 'not-determined'` initially and
375
431
  * optimistically flips to `'granted'` after `requestPermission()` is called.
376
432
  * It cannot detect denials after-the-fact; consumers should treat the iOS camera-start
377
- * flow as the authoritative signal (surfaced via `<BarcodeCaptureView onError={...} />`).
433
+ * flow as the authoritative signal (surfaced via `<BarcodeCaptureAioView onError={...} />`).
378
434
  *
379
435
  * ```tsx
380
436
  * const { hasPermission, requestPermission } = useCameraPermission();
@@ -411,7 +467,7 @@ function useCameraPermission() {
411
467
  }
412
468
  // iOS: we can't drive the prompt from JS. Flip optimistically to 'granted';
413
469
  // the native camera access triggers the iOS dialog automatically, and denial
414
- // surfaces as a camera-start failure (hook into `BarcodeCaptureView.onError`).
470
+ // surfaces as a camera-start failure (hook into `BarcodeCaptureAioView.onError`).
415
471
  setStatus('granted');
416
472
  return true;
417
473
  }, []);
@@ -447,6 +503,121 @@ function useScanditContext(licenseKey, options) {
447
503
  return context;
448
504
  }
449
505
 
506
+ /**
507
+ * Render an unknown thrown value as a string worth logging.
508
+ *
509
+ * Exists because `console.warn('...', err)` loses the only part that matters.
510
+ * `Error.message` and `Error.stack` are **non-enumerable**, so any log sink that
511
+ * JSON-serializes its arguments — the DebugApp's on-device console tee, among
512
+ * others — writes `{}` for a plain `Error`, or, for a React Native native
513
+ * rejection, just `{"code":"-1","nativeStackIOS":[…]}` with the message gone.
514
+ *
515
+ * That is not hypothetical. During the SDC-33115 B4 rapid-swap run the device
516
+ * showed `Unable to switch the camera to on` on screen while the captured log
517
+ * held only the code and a native stack, because LogBox reads `err.message`
518
+ * directly and the file sink had already dropped it. Interpolating first makes
519
+ * the two agree.
520
+ */
521
+ function describeError(err) {
522
+ if (err instanceof Error) {
523
+ // The stack normally already opens with `Error: <message>`, so prefixing the
524
+ // message again would just duplicate it.
525
+ const head = err.stack?.includes(err.message) ? err.stack : `${err.message}\n${err.stack ?? ''}`;
526
+ // Anything the thrower hung off the Error stays. React Native's native
527
+ // rejections arrive as real `Error`s carrying enumerable `code` and
528
+ // `nativeStackIOS`, and that native stack is often the only thing that
529
+ // identifies the failing native call — dropping it to keep the message
530
+ // would just move the erasure rather than end it. (It did, briefly: the
531
+ // first cut of this function returned message + stack only, and threw away
532
+ // the `AbstractCamera::resetContext` frames that diagnosed SDC-33115's F14.)
533
+ const extras = ownEnumerableProps(err);
534
+ return extras === undefined ? head : `${head}\n${extras}`;
535
+ }
536
+ // React Native rejects native promises with a plain object carrying `code` /
537
+ // `message` rather than a real Error, so pull those out before falling back
538
+ // to `String(err)` (which would render `[object Object]`).
539
+ if (err !== null && typeof err === 'object') {
540
+ const bag = err;
541
+ const message = typeof bag.message === 'string' ? bag.message : undefined;
542
+ // Only stringify a primitive `code`. Coercing an object here would print
543
+ // `[object Object]` — the same uselessness this function exists to prevent.
544
+ const code = typeof bag.code === 'string' || typeof bag.code === 'number' || typeof bag.code === 'boolean'
545
+ ? String(bag.code)
546
+ : undefined;
547
+ if (message !== undefined || code !== undefined) {
548
+ const parts = [message, code === undefined ? undefined : `(code ${code})`].filter(Boolean);
549
+ return `${parts.join(' ')}\n${safeJson(err)}`;
550
+ }
551
+ return safeJson(err);
552
+ }
553
+ return String(err);
554
+ }
555
+ /**
556
+ * Serialize an Error's own enumerable properties — the payload a thrower
557
+ * attached, which `message`/`stack` alone do not cover. Returns `undefined` when
558
+ * there is nothing extra, so the caller can skip a trailing empty line.
559
+ */
560
+ function ownEnumerableProps(err) {
561
+ const extras = {};
562
+ for (const key of Object.keys(err)) {
563
+ if (key === 'message' || key === 'stack')
564
+ continue;
565
+ extras[key] = err[key];
566
+ }
567
+ return Object.keys(extras).length === 0 ? undefined : safeJson(extras);
568
+ }
569
+ function safeJson(value) {
570
+ try {
571
+ return JSON.stringify(value) ?? String(value);
572
+ }
573
+ catch {
574
+ return String(value);
575
+ }
576
+ }
577
+
578
+ function isSerializable(v) {
579
+ return typeof v === 'object' && v !== null && typeof v.toJson === 'function';
580
+ }
581
+ function signature(v) {
582
+ try {
583
+ return JSON.stringify(isSerializable(v) ? v.toJson() : v) ?? '';
584
+ }
585
+ catch {
586
+ // Cyclic / un-serializable values fall through to `''` so the caller sees
587
+ // a "changed" signature and uses the new value. Better safe than wrong.
588
+ return '';
589
+ }
590
+ }
591
+ /**
592
+ * Returns a referentially-stable copy of `value` as long as the structural
593
+ * content stays the same. Lets consumers pass inline SDK class instances
594
+ * (`new Brush(...)`, `new TorchSwitchControl()`) or plain options objects
595
+ * without memoizing — the effect deps array sees the same reference until
596
+ * the underlying content actually changes.
597
+ *
598
+ * SDK classes that extend `DefaultSerializeable` are compared via their
599
+ * `toJson()` output (which respects `@ignoreFromSerialization`), so private
600
+ * back-refs like `view` don't cause spurious diffs. Plain objects and arrays
601
+ * are compared via direct `JSON.stringify`.
602
+ *
603
+ * ```tsx
604
+ * function MyView({ brush }: { brush?: Brush | null }) {
605
+ * const stableBrush = useStableProp(brush);
606
+ * useEffect(() => {
607
+ * if (stableBrush) overlay.brush = stableBrush;
608
+ * }, [stableBrush]);
609
+ * }
610
+ * ```
611
+ */
612
+ function useStableProp(value) {
613
+ const ref = useRef(null);
614
+ const sig = signature(value);
615
+ if (ref.current && ref.current.sig === sig)
616
+ return ref.current.value;
617
+ ref.current = { value, sig };
618
+ return value;
619
+ }
620
+
450
621
  const DEFAULT_TORCH = TorchState.Off;
451
622
  const DEFAULT_POSITION = CameraPosition.WorldFacing;
452
623
  function createCameraOwner(context, cameraFactory = position => Camera.atPosition(position), onError) {
@@ -455,6 +626,12 @@ function createCameraOwner(context, cameraFactory = position => Camera.atPositio
455
626
  let createdPosition = null;
456
627
  let position = DEFAULT_POSITION;
457
628
  let desiredTorch = DEFAULT_TORCH;
629
+ let desiredSettings = null;
630
+ // What the provider last applied to its OWN camera (native state latch).
631
+ // Transitions must be idempotent: while an exclusive owner drives camera 0,
632
+ // a redundant Off+setFrameSource(null) on the *released* provider camera
633
+ // races the exclusive view's On and can win, leaving a black preview
634
+ // (SDC-32484 iOS). Only transition on actual native state changes.
458
635
  let applied = 'off';
459
636
  // True only after a FULLY successful acquire (both native calls confirmed).
460
637
  // Lets the apply pass skip re-issuing setFrameSource/switchOn when nothing
@@ -468,7 +645,7 @@ function createCameraOwner(context, cameraFactory = position => Camera.atPositio
468
645
  let chain = Promise.resolve();
469
646
  const enqueue = (op) => {
470
647
  chain = chain.then(op).catch(err => {
471
- console.warn('ScanditProvider: camera operation failed', err);
648
+ console.warn(`ScanditProvider: camera operation failed: ${describeError(err)}`);
472
649
  onError?.(err);
473
650
  });
474
651
  return chain;
@@ -484,30 +661,59 @@ function createCameraOwner(context, cameraFactory = position => Camera.atPositio
484
661
  camera.desiredTorchState = desiredTorch;
485
662
  return;
486
663
  }
664
+ // Probe before releasing. The factory opens no native session, so asking
665
+ // first costs nothing and a position the device lacks leaves the running
666
+ // camera untouched instead of stranding the caller with a dead preview.
667
+ let nextCamera = camera;
487
668
  if (camera === null || createdPosition !== position) {
488
- // `Camera.atPosition` returns null when the position is unavailable on
489
- // the device. Don't crash the chain — warn and leave the camera off; a
490
- // later position change can retry.
491
- camera = cameraFactory(position);
492
- if (camera === null) {
669
+ nextCamera = cameraFactory(position);
670
+ if (nextCamera === null) {
493
671
  console.warn('ScanditProvider: no camera available at position', position);
672
+ // Never latch a position the device does not have: every later acquire
673
+ // would take this same early return, so a standby-resume would find no
674
+ // camera to reopen and the preview would stay dead (SDC-33131).
675
+ if (createdPosition !== null)
676
+ position = createdPosition;
494
677
  return;
495
678
  }
496
- createdPosition = position;
497
679
  }
498
- camera.desiredTorchState = desiredTorch;
499
- // Mark before the awaits: a partial failure leaves applied='on' so a
500
- // later release fully unwinds the half-attached camera.
501
- applied = 'on';
502
- acquireSucceeded = false;
680
+ // Non-null by construction: a null `camera` forces the branch above, which
681
+ // either returns or assigns.
682
+ const target = nextCamera;
503
683
  try {
504
- await context.setFrameSource(camera);
505
- await camera.switchToDesiredState(FrameSourceState.On);
684
+ if (target !== camera) {
685
+ // Android refuses to configure the new camera while the old one still
686
+ // holds its capture session ("Unsupported set of inputs/outputs
687
+ // provided" — SDC-33131), and that constraint applies to setFrameSource
688
+ // and switchToDesiredState, both of which are still ahead of us here.
689
+ // Inside the try so a rejected teardown costs one retry rather than
690
+ // aborting with the frame source already detached.
691
+ await releaseSharedCamera();
692
+ camera = target;
693
+ createdPosition = position;
694
+ }
695
+ target.desiredTorchState = desiredTorch;
696
+ // Mark before the awaits: a partial failure leaves applied='on' so a
697
+ // later release fully unwinds the half-attached camera.
698
+ applied = 'on';
699
+ acquireSucceeded = false;
700
+ if (desiredSettings !== null)
701
+ await target.applySettings(desiredSettings);
702
+ await context.setFrameSource(target);
703
+ await target.switchToDesiredState(FrameSourceState.On);
506
704
  acquireSucceeded = true;
705
+ console.debug(`[cameraOwner] camera -> On (position=${position})`);
507
706
  }
508
707
  catch (err) {
708
+ // Report every failure. A superseded switch-on looks like a candidate for
709
+ // silencing — it recovers, and under rapid swapping it is common — but the
710
+ // native call really did fail, and a layer that decides on the caller's
711
+ // behalf which failures are worth mentioning is how a system ends up
712
+ // looking healthier than it is. SDC-33115 F14 is a real native race
713
+ // (`AbstractCamera::resetContext` cancelling an in-flight ~700ms switch);
714
+ // it is characterised and ticketed, not hidden here.
509
715
  if (retriesLeft > 0) {
510
- console.warn('ScanditProvider: switching the camera on failed, retrying once', err);
716
+ console.warn(`ScanditProvider: switching the camera on failed, retrying once: ${describeError(err)}`);
511
717
  await acquireSharedCamera(retriesLeft - 1);
512
718
  return;
513
719
  }
@@ -526,6 +732,7 @@ function createCameraOwner(context, cameraFactory = position => Camera.atPositio
526
732
  applied = 'standby';
527
733
  acquireSucceeded = false;
528
734
  await camera.switchToDesiredState(FrameSourceState.Standby);
735
+ console.debug('[cameraOwner] camera -> Standby (no owner)');
529
736
  };
530
737
  /** Hard release: full Off + frame source detached. Required when the device
531
738
  * must be free immediately - an exclusive (own-camera) owner taking camera 0,
@@ -534,10 +741,21 @@ function createCameraOwner(context, cameraFactory = position => Camera.atPositio
534
741
  const releaseSharedCamera = async () => {
535
742
  if (camera === null || applied === 'off')
536
743
  return;
744
+ const before = applied;
537
745
  applied = 'off';
538
746
  acquireSucceeded = false;
539
- await camera.switchToDesiredState(FrameSourceState.Off);
540
- await context.setFrameSource(null);
747
+ try {
748
+ await camera.switchToDesiredState(FrameSourceState.Off);
749
+ await context.setFrameSource(null);
750
+ }
751
+ catch (err) {
752
+ // Put the latch back, or the retry's release returns on its first line
753
+ // and the next camera is attached while this one still holds its session
754
+ // — the Android failure the release exists to prevent (SDC-33131).
755
+ applied = before;
756
+ throw err;
757
+ }
758
+ console.debug('[cameraOwner] camera -> Off, frame source detached');
541
759
  };
542
760
  const releaseManagedCamera = releaseSharedCamera;
543
761
  /** Apply the state the CURRENT owner implies. Called at op-run time so a
@@ -545,6 +763,14 @@ function createCameraOwner(context, cameraFactory = position => Camera.atPositio
545
763
  const applyOwnerState = async () => {
546
764
  if (disposed)
547
765
  return;
766
+ // Do NOT add an `if (applyScheduled) return` short-circuit here. It looks
767
+ // like a free extension of the coalescing `scheduleApply` already does, and
768
+ // it measures WORSE on device: over an identical 10x shared<->exclusive
769
+ // deep-link loop on an iPhone SE it took bridge errors from 0.67 to 1.0 per
770
+ // crossing and halved how often the camera reached `On` (SDC-33115 F14,
771
+ // A/B recorded in the ticket log). Deferring the transition appears to move
772
+ // it into a worse window rather than avoiding the collision. Measure before
773
+ // reintroducing it.
548
774
  if (owner === null) {
549
775
  await standbySharedCamera();
550
776
  }
@@ -628,9 +854,25 @@ function createCameraOwner(context, cameraFactory = position => Camera.atPositio
628
854
  const whenGranted = (claim) => {
629
855
  return enqueue(() => Promise.resolve());
630
856
  };
857
+ const inspect = () => ({
858
+ ownerMode: owner === null ? null : owner.mode,
859
+ applied,
860
+ acquireSucceeded,
861
+ pendingSteps: pendingSteps.length,
862
+ });
863
+ // Read `owner` here, not via `inspect()`: that is diagnostic-only by contract
864
+ // and its read can be stale.
865
+ const warnIfExclusive = (prop) => {
866
+ if (owner !== null && owner.mode === 'exclusive') {
867
+ console.warn(`ScanditProvider: \`${prop}\` has no visible effect while a view owns the camera ` +
868
+ 'exclusively (SparkScanAioView). Set SparkScanViewSettings.defaultTorchState / ' +
869
+ 'defaultCameraPosition instead.');
870
+ }
871
+ };
631
872
  return {
632
873
  setTorch(next) {
633
874
  return enqueue(() => {
875
+ warnIfExclusive('torchState');
634
876
  desiredTorch = next;
635
877
  if (camera !== null)
636
878
  camera.desiredTorchState = next;
@@ -639,10 +881,18 @@ function createCameraOwner(context, cameraFactory = position => Camera.atPositio
639
881
  },
640
882
  setPosition(next) {
641
883
  return enqueue(async () => {
884
+ warnIfExclusive('cameraPosition');
642
885
  position = next;
643
886
  await applyOwnerState();
644
887
  });
645
888
  },
889
+ setCameraSettings(next) {
890
+ return enqueue(async () => {
891
+ desiredSettings = next;
892
+ if (camera !== null && next !== null)
893
+ await camera.applySettings(next);
894
+ });
895
+ },
646
896
  idle() {
647
897
  return chain.then(() => undefined, () => undefined);
648
898
  },
@@ -664,12 +914,15 @@ function createCameraOwner(context, cameraFactory = position => Camera.atPositio
664
914
  updateClaim,
665
915
  removeClaim,
666
916
  whenGranted,
917
+ // ─── Diagnostics ────────────────────────────────────────────────────────
918
+ inspect,
667
919
  };
668
920
  }
669
921
  const ScanditInternalContext = createContext(null);
670
922
  /** Reflects a provider's camera-related props onto the singleton camera. */
671
923
  function useApplyCameraProps(owner, props) {
672
924
  const { frameSourceState, torchState, cameraPosition } = props;
925
+ const cameraSettings = useStableProp(props.cameraSettings);
673
926
  useEffect(() => {
674
927
  if (cameraPosition !== undefined)
675
928
  void owner.setPosition(cameraPosition);
@@ -678,6 +931,10 @@ function useApplyCameraProps(owner, props) {
678
931
  if (torchState !== undefined)
679
932
  void owner.setTorch(torchState);
680
933
  }, [owner, torchState]);
934
+ useEffect(() => {
935
+ if (cameraSettings !== undefined)
936
+ void owner.setCameraSettings(cameraSettings);
937
+ }, [owner, cameraSettings]);
681
938
  // The camera is ownership-driven: it is only turned on when a view (or an
682
939
  // explicit `frameSourceState={On}`) claims it.
683
940
  // - undefined → do nothing (let views drive the camera).
@@ -698,7 +955,7 @@ function useApplyCameraProps(owner, props) {
698
955
  * - **Root** (no parent `<ScanditProvider>` above): creates the context + camera,
699
956
  * disposes them on unmount.
700
957
  * - **Nested**: applies its own `frameSourceState` / `torchState` / `cameraPosition`
701
- * props to the same singleton camera. Last writer wins; values are not reverted
958
+ * / `cameraSettings` props to the same singleton camera. Last writer wins; values are not reverted
702
959
  * when a nested provider unmounts.
703
960
  *
704
961
  * The camera is ownership-driven: exactly one view owns it at a time (last
@@ -717,7 +974,7 @@ function useApplyCameraProps(owner, props) {
717
974
  * frameSourceState={isFocused ? FrameSourceState.On : FrameSourceState.Off}
718
975
  * torchState={torch}
719
976
  * cameraPosition={position}>
720
- * <BarcodeCaptureView state="enabled" ... />
977
+ * <BarcodeCaptureAioView navigation={navigation} ... />
721
978
  * </ScanditProvider>
722
979
  * ```
723
980
  */
@@ -731,14 +988,14 @@ function ScanditProvider(props) {
731
988
  }
732
989
  return React.createElement(RootScanditProvider, { ...props, licenseKey: props.licenseKey });
733
990
  }
734
- function NestedScanditProvider({ parent, frameSourceState, torchState, cameraPosition, licenseKey, settings, options, children, }) {
991
+ function NestedScanditProvider({ parent, frameSourceState, torchState, cameraPosition, cameraSettings, licenseKey, settings, options, children, }) {
735
992
  if (licenseKey || settings || options) {
736
993
  console.warn('ScanditProvider: licenseKey/settings/options are ignored on nested providers.');
737
994
  }
738
- useApplyCameraProps(parent.owner, { frameSourceState, torchState, cameraPosition });
995
+ useApplyCameraProps(parent.owner, { frameSourceState, torchState, cameraPosition, cameraSettings });
739
996
  return React.createElement(ScanditInternalContext.Provider, { value: parent }, children);
740
997
  }
741
- function RootScanditProvider({ licenseKey, options, settings, frameSourceState, torchState, cameraPosition, onError, children, }) {
998
+ function RootScanditProvider({ licenseKey, options, settings, frameSourceState, torchState, cameraPosition, cameraSettings, onError, children, }) {
742
999
  const context = useMemo(() => DataCaptureContext.initialize(licenseKey, options ?? null, settings ?? null),
743
1000
  // The context is a singleton keyed on licenseKey.
744
1001
  // eslint-disable-next-line react-hooks/exhaustive-deps
@@ -757,6 +1014,7 @@ function RootScanditProvider({ licenseKey, options, settings, frameSourceState,
757
1014
  frameSourceState,
758
1015
  torchState: torchState ?? DEFAULT_TORCH,
759
1016
  cameraPosition: cameraPosition ?? DEFAULT_POSITION,
1017
+ cameraSettings,
760
1018
  });
761
1019
  // Dispose context + camera on unmount. Chained onto the owner's chain so
762
1020
  // any in-flight operation finishes first.
@@ -782,49 +1040,6 @@ function useDataCaptureContextInternal() {
782
1040
  return useScanditInternal().context;
783
1041
  }
784
1042
 
785
- function isSerializable(v) {
786
- return typeof v === 'object' && v !== null && typeof v.toJson === 'function';
787
- }
788
- function signature(v) {
789
- try {
790
- return JSON.stringify(isSerializable(v) ? v.toJson() : v) ?? '';
791
- }
792
- catch {
793
- // Cyclic / un-serializable values fall through to `''` so the caller sees
794
- // a "changed" signature and uses the new value. Better safe than wrong.
795
- return '';
796
- }
797
- }
798
- /**
799
- * Returns a referentially-stable copy of `value` as long as the structural
800
- * content stays the same. Lets consumers pass inline SDK class instances
801
- * (`new Brush(...)`, `new TorchSwitchControl()`) or plain options objects
802
- * without memoizing — the effect deps array sees the same reference until
803
- * the underlying content actually changes.
804
- *
805
- * SDK classes that extend `DefaultSerializeable` are compared via their
806
- * `toJson()` output (which respects `@ignoreFromSerialization`), so private
807
- * back-refs like `view` don't cause spurious diffs. Plain objects and arrays
808
- * are compared via direct `JSON.stringify`.
809
- *
810
- * ```tsx
811
- * function MyView({ brush }: { brush?: Brush | null }) {
812
- * const stableBrush = useStableProp(brush);
813
- * useEffect(() => {
814
- * if (stableBrush) overlay.brush = stableBrush;
815
- * }, [stableBrush]);
816
- * }
817
- * ```
818
- */
819
- function useStableProp(value) {
820
- const ref = useRef(null);
821
- const sig = signature(value);
822
- if (ref.current && ref.current.sig === sig)
823
- return ref.current.value;
824
- ref.current = { value, sig };
825
- return value;
826
- }
827
-
828
1043
  /**
829
1044
  * Mirrors a fixed set of prop values onto a live native-view instance via
830
1045
  * direct property assignment.
@@ -1070,7 +1285,8 @@ function useMode(options) {
1070
1285
  // later lifecycle op.
1071
1286
  const enqueue = useCallback((op) => {
1072
1287
  opChainRef.current = opChainRef.current.then(op).catch(err => {
1073
- console.warn('[useMode] lifecycle operation failed', err);
1288
+ // Interpolated, not passed as an object — see `describeError`.
1289
+ console.warn(`[useMode] lifecycle operation failed: ${describeError(err)}`);
1074
1290
  });
1075
1291
  return opChainRef.current;
1076
1292
  }, []);
@@ -1507,8 +1723,54 @@ function useCameraClaim({ mode, active, nativeViewRef }) {
1507
1723
  }), [owner]);
1508
1724
  }
1509
1725
 
1726
+ /**
1727
+ * The `attach` body shared by every AIO view that owns its own native view.
1728
+ *
1729
+ * It exists because getting this wrong is invisible. The natural shape —
1730
+ * `new Promise(resolve => { void whenReady().then(async () => { … resolve() }) })`
1731
+ * — has no rejection path, so anything thrown past `whenReady()` leaves the
1732
+ * returned promise neither resolved nor rejected. `useMode` serializes lifecycle
1733
+ * work on a single op chain, so an attach that never settles blocks *every*
1734
+ * later op behind it: `setEnabled` never runs, the unmount `detach()` never
1735
+ * runs, the camera claim never activates and the provider camera parks in
1736
+ * Standby. The user gets a black view with no error, no crash, and no recovery
1737
+ * even by navigating away and back.
1738
+ *
1739
+ * That is not hypothetical: it shipped in `SparkScanAioView`, where a colour
1740
+ * default typed `Color` but holding a hex string made `toJSON()` throw inside
1741
+ * `createNativeView` (SDC-33115). `BarcodeCountAioView` and `BarcodeArAioView`
1742
+ * carried the same shape with the same reachable throw sites and were working
1743
+ * only by luck. Routing all three through here means a fourth view cannot
1744
+ * reintroduce the bug by writing the obvious thing.
1745
+ *
1746
+ * Gating on layout rather than `InteractionManager.runAfterInteractions` is
1747
+ * deliberate: that queue can be starved by a blocked JS interaction, which
1748
+ * leaves the preview never created (SDC-32208).
1749
+ */
1750
+ function attachNativeViewWhenReady({ tag, node, whenReady, createNativeView, }) {
1751
+ return new Promise((resolve, reject) => {
1752
+ if (!node)
1753
+ return resolve();
1754
+ void whenReady()
1755
+ .then(async () => {
1756
+ const nodeId = findNodeHandle(node);
1757
+ if (nodeId == null)
1758
+ return resolve();
1759
+ await createNativeView(nodeId);
1760
+ resolve();
1761
+ })
1762
+ .catch((err) => {
1763
+ // Interpolated, not passed as an object — see `describeError`.
1764
+ console.warn(`[useMode:${tag}] attach failed: ${describeError(err)}`);
1765
+ reject(err instanceof Error ? err : new Error(String(err)));
1766
+ });
1767
+ });
1768
+ }
1769
+
1510
1770
  var index = /*#__PURE__*/Object.freeze({
1511
1771
  __proto__: null,
1772
+ attachNativeViewWhenReady: attachNativeViewWhenReady,
1773
+ describeError: describeError,
1512
1774
  useCameraClaim: useCameraClaim,
1513
1775
  useDataCaptureContextInternal: useDataCaptureContextInternal,
1514
1776
  useLifecycleHook: useLifecycleHook,
@@ -1525,5 +1787,5 @@ var index = /*#__PURE__*/Object.freeze({
1525
1787
  initCoreDefaults();
1526
1788
  initCoreProxy();
1527
1789
 
1528
- export { Camera, CameraPosition, DataCaptureContext, DataCaptureVersion, DataCaptureView, FrameSourceState, RNNativeCaller, ScanditProvider, TorchState, index as _internal, createRNNativeCaller, getModuleDefaults, getNativeModule, initCoreDefaults, initCoreProxy, useCameraPermission, useIsForeground, useScanditContext };
1790
+ export { Camera, CameraPosition, DataCaptureContext, DataCaptureVersion, DataCaptureView, FrameSourceState, RNNativeCaller, ScanditProvider, TorchState, index as _internal, createRNNativeCaller, getModuleDynamicDefaults, getNativeModule, initCoreDefaults, initCoreProxy, useCameraPermission, useIsForeground, useScanditContext };
1529
1791
  //# sourceMappingURL=index.js.map