@octane-xplat/barcode-scanner 0.0.0-nightly.g1b95ef7

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/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # @octane-xplat/barcode-scanner
2
+
3
+ [Documentation](https://octane-xplat.goddardai.org/package-barcode-scanner).
4
+
5
+ [API reference](https://octane-xplat.goddardai.org/api-barcode-scanner).
package/package.json ADDED
@@ -0,0 +1,93 @@
1
+ {
2
+ "name": "@octane-xplat/barcode-scanner",
3
+ "version": "0.0.0-nightly.g1b95ef7",
4
+ "description": "Barcode and QR scanning for Octane xplat — ML Kit camera preview + still decode on iOS/Android, Vision still decode on macOS, BarcodeDetector on web",
5
+ "keywords": [
6
+ "android",
7
+ "cross-platform",
8
+ "nativescript",
9
+ "octane",
10
+ "xplat",
11
+ "barcode",
12
+ "qr",
13
+ "scanner",
14
+ "mlkit"
15
+ ],
16
+ "homepage": "https://github.com/octane-xplat/octane-xplat/tree/main/packages/barcode-scanner",
17
+ "license": "MIT",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "https://github.com/octane-xplat/octane-xplat",
21
+ "directory": "packages/barcode-scanner"
22
+ },
23
+ "files": [
24
+ "src",
25
+ "platforms",
26
+ "types",
27
+ "!src/**/*.test.*",
28
+ "!src/**/*.spec.*"
29
+ ],
30
+ "type": "module",
31
+ "exports": {
32
+ ".": {
33
+ "types": "./types/generated/index.d.ts",
34
+ "macos": "./src/index.macos.ts",
35
+ "web": "./src/index.web.ts",
36
+ "native": "./src/index.ts",
37
+ "default": "./src/index.ts"
38
+ },
39
+ "./*": {
40
+ "types": "./types/generated/*.d.ts",
41
+ "default": "./src/*"
42
+ },
43
+ "./*.ts": {
44
+ "types": "./types/generated/*.d.ts",
45
+ "default": "./src/*.ts"
46
+ }
47
+ },
48
+ "publishConfig": {
49
+ "access": "public"
50
+ },
51
+ "scripts": {
52
+ "typegen": "tsrx-typegen --target octane",
53
+ "prepack": "bun run typegen && tsrx-typegen --pack-check",
54
+ "pack:check": "tsrx-typegen --pack-check",
55
+ "test": "node --test tests/*.test.ts",
56
+ "typecheck": "node ../../scripts/typecheck.ts"
57
+ },
58
+ "devDependencies": {
59
+ "@octane-xplat/nativescript-octane": "0.0.0-nightly.g1b95ef7",
60
+ "@nativescript/core": "9.1.3",
61
+ "@nativescript/types": "9.1.4",
62
+ "octane": "0.23.2",
63
+ "tsrx-typegen": "0.6.2",
64
+ "typescript": "7.1.0-dev.20261121.1",
65
+ "@tsrx/content-mapper": "0.1.2"
66
+ },
67
+ "peerDependencies": {
68
+ "@octane-xplat/nativescript-octane": "0.0.0-nightly.g1b95ef7",
69
+ "@nativescript/core": ">=9.1.0 <10",
70
+ "octane": ">=0.6.3 <1"
71
+ },
72
+ "peerDependenciesMeta": {
73
+ "@octane-xplat/nativescript-octane": {
74
+ "optional": true
75
+ },
76
+ "@nativescript/core": {
77
+ "optional": true
78
+ }
79
+ },
80
+ "nativescript": {
81
+ "platforms": {
82
+ "android": "9.1.0",
83
+ "ios": "9.1.0"
84
+ }
85
+ },
86
+ "dependencies": {
87
+ "@octane-xplat/lib": "0.0.0-nightly.g1b95ef7",
88
+ "@nativescript/mlkit-barcode-scanning": "3.0.4",
89
+ "@nativescript/mlkit-core": "3.0.4",
90
+ "@octane-xplat/jsx": "0.0.0-nightly.g1b95ef7",
91
+ "@octane-xplat/platform": "0.0.0-nightly.g1b95ef7"
92
+ }
93
+ }
@@ -0,0 +1,3 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <uses-permission android:name="android.permission.CAMERA" />
3
+ </manifest>
@@ -0,0 +1,8 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>NSCameraUsageDescription</key>
6
+ <string>Camera access is required to scan codes.</string>
7
+ </dict>
8
+ </plist>
@@ -0,0 +1,15 @@
1
+ /** @jsxImportSource @octane-xplat/jsx */
2
+ // Live barcode scanner — AppKit stub. Still-image decoding works through
3
+ // barcodeScanner.scanImage (Vision); live camera scanning needs an
4
+ // AVCaptureVideoDataOutput frame path the camera leaf does not expose yet
5
+ // (decision #140). Renders nothing and reports once via onError.
6
+ import { useEffect } from 'octane'
7
+ import type { BarcodeScannerProps } from './props'
8
+
9
+ export function BarcodeScanner(props: BarcodeScannerProps): unknown @{
10
+ useEffect(() => {
11
+ props.onError?.({ message: 'unsupported: live barcode scanning is not wired on macOS' })
12
+ }, [])
13
+
14
+ <masonview style={props.style} className={props.className} />
15
+ }
@@ -0,0 +1,105 @@
1
+ /** @jsxImportSource @octane-xplat/jsx */
2
+ import { applyEscapeProps } from '@octane-xplat/lib/escape-props'
3
+ import { useImperativeHandle, useCallback, useEffect, useRef } from 'octane'
4
+ import { registerElement } from '@octane-xplat/nativescript-octane'
5
+ import { CameraPosition, DetectionType, MLKitView } from '@nativescript/mlkit-core'
6
+ import type { BarcodeScannerHandle, BarcodeScannerProps } from './props'
7
+ import { fromNativeFormat, toNativeFormats } from './format-map'
8
+
9
+ registerElement('xplatbarcodescanner', MLKitView)
10
+
11
+ /** Live barcode/QR scanner — ML Kit's camera preview with `detectionType:
12
+ * barcode`. Decoding only; photo capture stays in @octane-xplat/camera. */
13
+ export function BarcodeScanner(props: BarcodeScannerProps): unknown @{
14
+ const host = useRef<MLKitView | null>(null)
15
+
16
+ const bindHost = useCallback((v: MLKitView | null) => {
17
+ host.current = v
18
+ }, [])
19
+
20
+ useImperativeHandle(
21
+ props.ref,
22
+ (): BarcodeScannerHandle => ({
23
+ setPaused: (paused) => {
24
+ if (host.current) {
25
+ host.current.pause = paused
26
+ }
27
+ },
28
+ toggleCamera: () => host.current?.toggleCamera(),
29
+ native: host.current?.nativeViewProtected ?? host.current,
30
+ }),
31
+ [],
32
+ )
33
+
34
+ // Mount wiring — listeners before any prop assignment.
35
+ useEffect(() => {
36
+ const v = host.current
37
+
38
+ if (!v) {
39
+ return
40
+ }
41
+
42
+ v.detectionType = DetectionType.Barcode
43
+ v.on(MLKitView.detectionEvent, (e: any) => {
44
+ const data = e?.data ?? e?.data?.data ?? e
45
+ const list = Array.isArray(data) ? data : [data]
46
+
47
+ for (const item of list) {
48
+ if (!item) {
49
+ continue
50
+ }
51
+
52
+ const bounds = item.bounds
53
+
54
+ props.onCodeScanned?.({
55
+ type: fromNativeFormat(item.format),
56
+ data: String(item.rawValue ?? item.displayValue ?? ''),
57
+ bounds: bounds
58
+ ? {
59
+ x: bounds.origin?.x ?? bounds.x ?? 0,
60
+ y: bounds.origin?.y ?? bounds.y ?? 0,
61
+ width: bounds.size?.width ?? bounds.width ?? 0,
62
+ height: bounds.size?.height ?? bounds.height ?? 0,
63
+ }
64
+ : undefined,
65
+ })
66
+ }
67
+ })
68
+
69
+ applyEscapeProps(v, props)
70
+ }, [])
71
+
72
+ useEffect(() => {
73
+ const v = host.current
74
+
75
+ if (v) {
76
+ v.barcodeFormats = toNativeFormats(props.formats)
77
+ }
78
+ }, [JSON.stringify(props.formats)])
79
+
80
+ useEffect(() => {
81
+ const v = host.current
82
+
83
+ if (v) {
84
+ v.cameraPosition = props.facing === 'front' ? CameraPosition.FRONT : CameraPosition.BACK
85
+ }
86
+ }, [props.facing])
87
+
88
+ useEffect(() => {
89
+ const v = host.current
90
+
91
+ if (v) {
92
+ v.pause = props.paused ?? false
93
+ }
94
+ }, [props.paused])
95
+
96
+ useEffect(() => {
97
+ const v = host.current
98
+
99
+ if (v) {
100
+ v.torchOn = props.torch ?? false
101
+ }
102
+ }, [props.torch])
103
+
104
+ <xplatbarcodescanner ref={bindHost} style={props.style} className={props.className} />
105
+ }
@@ -0,0 +1,135 @@
1
+ /** @jsxImportSource @octane-xplat/jsx/dom */
2
+ import { useImperativeHandle, useEffect, useRef } from 'octane'
3
+ import type { BarcodeScannerHandle, BarcodeScannerProps } from './props'
4
+ import { fromDetectorFormat, toDetectorFormats } from './format-map.web'
5
+ import type { JSX } from 'octane/jsx-runtime'
6
+
7
+ /** Live barcode/QR scanner — getUserMedia + the BarcodeDetector API
8
+ * (Chromium/Safari 18.4+; Firefox lacks the detector). Polling runs on
9
+ * requestVideoFrameCallback where available, else a 250ms interval. */
10
+ export function BarcodeScanner(props: BarcodeScannerProps): JSX.Element @{
11
+ const video = useRef<HTMLVideoElement | null>(null)
12
+ const latest = useRef(props)
13
+
14
+ latest.current = props
15
+
16
+ const handle = (v: HTMLVideoElement | null): BarcodeScannerHandle => ({
17
+ setPaused: () => {},
18
+ toggleCamera: () => {},
19
+ native: v,
20
+ })
21
+
22
+ useImperativeHandle(props.ref, () => handle(video.current), [])
23
+
24
+ useEffect(() => {
25
+ const Detector = (globalThis as any).BarcodeDetector
26
+ const mediaDevices = (globalThis as any).navigator?.mediaDevices
27
+
28
+ if (!Detector || typeof mediaDevices?.getUserMedia !== 'function') {
29
+ props.onError?.({ message: 'unsupported: BarcodeDetector/getUserMedia is not available' })
30
+ return
31
+ }
32
+
33
+ const el = video.current
34
+
35
+ if (!el) {
36
+ return
37
+ }
38
+
39
+ let detector: any
40
+
41
+ try {
42
+ detector = new Detector({ formats: toDetectorFormats(props.formats) })
43
+ } catch {
44
+ detector = new Detector()
45
+ }
46
+
47
+ let stream: MediaStream | null = null
48
+ let timer: any = null
49
+ let cancelled = false
50
+ const pausedRef = { current: false }
51
+
52
+ const poll = async () => {
53
+ if (cancelled || !el || pausedRef.current) {
54
+ return
55
+ }
56
+
57
+ try {
58
+ const codes = await detector.detect(el)
59
+
60
+ for (const code of codes ?? []) {
61
+ const box = code.boundingBox
62
+
63
+ latest.current.onCodeScanned?.({
64
+ type: fromDetectorFormat(code.format),
65
+ data: String(code.rawValue ?? ''),
66
+ bounds: box ? { x: box.x, y: box.y, width: box.width, height: box.height } : undefined,
67
+ })
68
+ }
69
+ } catch {
70
+ // A transient frame failure ends detection for this tick only.
71
+ }
72
+
73
+ schedule()
74
+ }
75
+
76
+ const schedule = () => {
77
+ if (cancelled) {
78
+ return
79
+ }
80
+
81
+ const rvfc = (el as any).requestVideoFrameCallback
82
+
83
+ if (typeof rvfc === 'function') {
84
+ rvfc.call(el, () => poll())
85
+ } else {
86
+ timer = setTimeout(poll, 250)
87
+ }
88
+ }
89
+
90
+ // props.paused is read through latest in the poll loop.
91
+ Object.defineProperty(pausedRef, 'current', {
92
+ get: () => latest.current.paused ?? false,
93
+ })
94
+
95
+ mediaDevices
96
+ .getUserMedia({
97
+ video: { facingMode: props.facing === 'front' ? 'user' : 'environment' },
98
+ audio: false,
99
+ })
100
+ .then((s: MediaStream) => {
101
+ if (cancelled) {
102
+ s.getTracks().forEach((t) => t.stop())
103
+ return
104
+ }
105
+
106
+ stream = s
107
+ el.srcObject = s
108
+ el.play().catch(() => {})
109
+ schedule()
110
+ })
111
+ .catch((e: any) => {
112
+ latest.current.onError?.({ message: e?.message ?? 'camera unavailable' })
113
+ })
114
+
115
+ return () => {
116
+ cancelled = true
117
+ if (timer) {
118
+ clearTimeout(timer)
119
+ }
120
+
121
+ stream?.getTracks().forEach((t) => t.stop())
122
+ el.srcObject = null
123
+ }
124
+ }, [props.facing, JSON.stringify(props.formats)])
125
+
126
+ <video
127
+ ref={(el: HTMLVideoElement | null) => {
128
+ video.current = el
129
+ }}
130
+ muted
131
+ playsInline
132
+ style={props.style}
133
+ className={props.className}
134
+ />
135
+ }
@@ -0,0 +1,13 @@
1
+ /** @jsxImportSource @octane-xplat/jsx */
2
+ // Live barcode scanner — Windows leaf. No ML Kit camera path exists on
3
+ // Windows; renders an empty host and reports once via onError.
4
+ import { useEffect } from 'octane'
5
+ import type { BarcodeScannerProps } from './props'
6
+
7
+ export function BarcodeScanner(props: BarcodeScannerProps): unknown @{
8
+ useEffect(() => {
9
+ props.onError?.({ message: 'unsupported: live barcode scanning is not available on windows' })
10
+ }, [])
11
+
12
+ <masonview style={props.style} className={props.className} />
13
+ }
@@ -0,0 +1,62 @@
1
+ import { Application } from '@nativescript/core'
2
+ import type { PermissionStatus } from '@octane-xplat/platform'
3
+ import { android } from '@octane-xplat/platform/android'
4
+ import type { PermissionResult } from './types'
5
+
6
+ let scanRequestCode = 7723
7
+
8
+ // Non-prompting authorization read for the dispatcher's getPermissions.
9
+ // Android can't distinguish never-asked from denied without the rationale
10
+ // hook — report undetermined and let request resolve it.
11
+ export function cameraPermissionStatus(): PermissionStatus {
12
+ const activity = Application.android.foregroundActivity ?? Application.android.startActivity
13
+
14
+ return activity?.checkSelfPermission?.('android.permission.CAMERA') ===
15
+ android.content.pm.PackageManager.PERMISSION_GRANTED
16
+ ? 'granted'
17
+ : 'undetermined'
18
+ }
19
+
20
+ export async function ensureCameraPermission(): Promise<PermissionResult> {
21
+ try {
22
+ const perm = 'android.permission.CAMERA'
23
+ const activity = Application.android.foregroundActivity ?? Application.android.startActivity
24
+
25
+ if (
26
+ activity?.checkSelfPermission?.(perm) === android.content.pm.PackageManager.PERMISSION_GRANTED
27
+ ) {
28
+ return 'granted'
29
+ }
30
+
31
+ if (!activity) {
32
+ return 'denied'
33
+ }
34
+
35
+ return await new Promise<PermissionResult>((resolve) => {
36
+ const requestCode = scanRequestCode++
37
+ const event = Application.android.activityRequestPermissionsEvent
38
+ const onResult = (args: any) => {
39
+ if (args.requestCode !== requestCode) {
40
+ return
41
+ }
42
+
43
+ Application.android.off(event, onResult)
44
+ resolve(
45
+ args.grantResults?.[0] === android.content.pm.PackageManager.PERMISSION_GRANTED
46
+ ? 'granted'
47
+ : 'denied',
48
+ )
49
+ }
50
+
51
+ Application.android.on(event, onResult)
52
+ try {
53
+ activity.requestPermissions([perm], requestCode)
54
+ } catch {
55
+ Application.android.off(event, onResult)
56
+ resolve('denied')
57
+ }
58
+ })
59
+ } catch {
60
+ return 'denied'
61
+ }
62
+ }
@@ -0,0 +1,45 @@
1
+ import type { PermissionStatus } from '@octane-xplat/platform'
2
+ import type { PermissionResult } from './types'
3
+
4
+ // Non-prompting authorization read for the dispatcher's getPermissions.
5
+ export function cameraPermissionStatus(): PermissionStatus {
6
+ const av = (globalThis as any).AVCaptureDevice
7
+
8
+ if (typeof av?.authorizationStatusForMediaType !== 'function') {
9
+ return 'unsupported'
10
+ }
11
+
12
+ // AVCaptureDevice authorization: 0=notDetermined 1=restricted 2=denied 3=authorized
13
+ const status = av.authorizationStatusForMediaType((globalThis as any).AVMediaTypeVideo)
14
+
15
+ return status === 3 ? 'granted' : status === 0 ? 'undetermined' : 'denied'
16
+ }
17
+
18
+ export async function ensureCameraPermission(): Promise<PermissionResult> {
19
+ try {
20
+ const av = (globalThis as any).AVCaptureDevice
21
+ const video = (globalThis as any).AVMediaTypeVideo
22
+ // 0=notDetermined 1=restricted 2=denied 3=authorized
23
+ const status = av?.authorizationStatusForMediaType?.(video)
24
+
25
+ if (status === 3) {
26
+ return 'granted'
27
+ }
28
+
29
+ if (status === 1 || status === 2) {
30
+ return 'denied'
31
+ }
32
+
33
+ if (typeof av?.requestAccessForMediaTypeCompletionHandler !== 'function') {
34
+ return 'unsupported'
35
+ }
36
+
37
+ return await new Promise<PermissionResult>((resolve) => {
38
+ av.requestAccessForMediaTypeCompletionHandler(video, (granted: boolean) =>
39
+ resolve(granted ? 'granted' : 'denied'),
40
+ )
41
+ })
42
+ } catch {
43
+ return 'denied'
44
+ }
45
+ }
@@ -0,0 +1,2 @@
1
+ // Linux's system webview runs the shared web implementation.
2
+ export { barcodeScanner } from './barcode-scanner.web'
@@ -0,0 +1,178 @@
1
+ // Barcode scanner — macOS leaf. Still images decode through Vision's
2
+ // VNDetectBarcodesRequest; live camera scanning is not available on macOS,
3
+ // so ensure() reports 'unsupported'.
4
+ import {
5
+ CGImageGetHeight,
6
+ CGImageGetWidth,
7
+ NSImage,
8
+ NSURL,
9
+ VNDetectBarcodesRequest,
10
+ VNImageRequestHandler,
11
+ } from '@octane-xplat/platform/macos'
12
+
13
+ import type { BarcodeFormat, BarcodeScannerService, PermissionResult, ScannedCode } from './types'
14
+
15
+ // String literals, not the bound constants — the generated metadata targets
16
+ // macOS 11 and omits VNBarcodeSymbologyCodabar.
17
+ const VISION_PREFIX = 'VNBarcodeSymbology'
18
+ const SYMBOLOGIES: Record<BarcodeFormat, readonly string[]> = {
19
+ qr: ['QR'],
20
+ ean13: ['EAN13'],
21
+ ean8: ['EAN8'],
22
+ upc_a: ['EAN13'],
23
+ upc_e: ['UPCE'],
24
+ code128: ['Code128'],
25
+ code39: ['Code39', 'Code39Checksum', 'Code39FullASCII', 'Code39FullASCIIChecksum'],
26
+ code93: ['Code93', 'Code93i'],
27
+ codabar: ['Codabar'],
28
+ itf: ['I2of5', 'I2of5Checksum', 'ITF14'],
29
+ datamatrix: ['DataMatrix'],
30
+ pdf417: ['PDF417'],
31
+ aztec: ['Aztec'],
32
+ }
33
+
34
+ // Vision → our vocabulary. EAN13 resolves to ean13; UPC-A is an EAN-13 with
35
+ // a leading 0 and is rewritten on the payload (see below).
36
+ const FORMATS: Record<string, string> = {}
37
+
38
+ for (const [format, names] of Object.entries(SYMBOLOGIES)) {
39
+ for (const name of names) {
40
+ FORMATS[VISION_PREFIX + name] ??= format
41
+ }
42
+ }
43
+
44
+ /** The deduplicated, prefixed union for the requested formats — every entry
45
+ * when `formats` is missing or empty, so results stay inside our vocabulary. */
46
+ function symbologiesFor(formats?: BarcodeFormat[]): string[] {
47
+ const wanted = formats?.length ? formats : (Object.keys(SYMBOLOGIES) as BarcodeFormat[])
48
+ const out = new Set<string>()
49
+
50
+ for (const format of wanted) {
51
+ for (const name of SYMBOLOGIES[format] ?? []) {
52
+ out.add(VISION_PREFIX + name)
53
+ }
54
+ }
55
+
56
+ return [...out]
57
+ }
58
+
59
+ /** request.results may be a JS array or an NSArray — count/objectAtIndex. */
60
+ function observations(results: any): any[] {
61
+ if (!results) {
62
+ return []
63
+ }
64
+
65
+ if (Array.isArray(results)) {
66
+ return results
67
+ }
68
+
69
+ const out: any[] = []
70
+
71
+ for (let i = 0, count = Number(results.count ?? 0); i < count; i++) {
72
+ out.push(results.objectAtIndex(i))
73
+ }
74
+
75
+ return out
76
+ }
77
+
78
+ /** Headless barcode service — permission + still-image decode. See BarcodeScannerService. */
79
+ export const barcodeScanner: BarcodeScannerService = {
80
+ supported: true,
81
+ ensure: async (): Promise<PermissionResult> => 'unsupported',
82
+ scanImage: async (image: unknown, formats?: BarcodeFormat[]): Promise<ScannedCode[]> => {
83
+ let source: any
84
+
85
+ if (typeof image === 'string' || (image != null && typeof (image as any).uri === 'string')) {
86
+ const input = typeof image === 'string' ? image : (image as any).uri
87
+
88
+ if (/^file:/i.test(input)) {
89
+ source = NSImage.alloc().initWithContentsOfURL(NSURL.URLWithString(input))
90
+ } else if (/^[a-z][a-z0-9+.-]*:/i.test(input)) {
91
+ throw new Error(
92
+ 'barcodeScanner.scanImage: macOS decodes local files; download remote images first',
93
+ )
94
+ } else {
95
+ source = NSImage.alloc().initWithContentsOfURL(NSURL.fileURLWithPath(input))
96
+ }
97
+ } else if (
98
+ image != null &&
99
+ typeof (image as any).CGImageForProposedRectContextHints === 'function'
100
+ ) {
101
+ source = image
102
+ } else {
103
+ throw new Error(
104
+ 'barcodeScanner.scanImage: expected a file path, file URL, {uri} ref, or NSImage',
105
+ )
106
+ }
107
+
108
+ const cg = source?.CGImageForProposedRectContextHints?.(null, null, null)
109
+
110
+ if (!cg) {
111
+ throw new Error('barcodeScanner.scanImage: could not read the image')
112
+ }
113
+
114
+ const request = VNDetectBarcodesRequest.alloc().init()
115
+
116
+ request.symbologies = symbologiesFor(formats)
117
+
118
+ const handler = VNImageRequestHandler.alloc().initWithCGImageOptions(cg, {})
119
+
120
+ if (!handler.performRequestsError([request], null)) {
121
+ throw new Error('barcodeScanner.scanImage: Vision could not process the image')
122
+ }
123
+
124
+ // Vision reports UPC-A as EAN-13 with a leading 0.
125
+ const wantsUpcA = !formats?.length || formats.includes('upc_a')
126
+ const wantsEan13 = !formats?.length || formats.includes('ean13')
127
+ const W = Number(CGImageGetWidth(cg))
128
+ const H = Number(CGImageGetHeight(cg))
129
+ const codes: ScannedCode[] = []
130
+
131
+ for (const observation of observations(request.results)) {
132
+ const symbology = String(observation?.symbology ?? '')
133
+ let type =
134
+ FORMATS[symbology] ??
135
+ (symbology.startsWith(VISION_PREFIX) ? symbology.slice(VISION_PREFIX.length) : symbology)
136
+
137
+ let data = String(observation?.payloadStringValue ?? '')
138
+
139
+ if (type === 'ean13') {
140
+ if (data.length === 13 && data.startsWith('0') && wantsUpcA) {
141
+ type = 'upc_a'
142
+ data = data.slice(1)
143
+ } else if (!wantsEan13) {
144
+ continue
145
+ }
146
+ }
147
+
148
+ const code: ScannedCode = { type, data }
149
+ const box = observation?.boundingBox
150
+
151
+ if (box) {
152
+ const ox = Number(box.origin?.x)
153
+ const oy = Number(box.origin?.y)
154
+ const width = Number(box.size?.width)
155
+ const height = Number(box.size?.height)
156
+
157
+ if (
158
+ Number.isFinite(ox) &&
159
+ Number.isFinite(oy) &&
160
+ Number.isFinite(width) &&
161
+ Number.isFinite(height)
162
+ ) {
163
+ // Vision bounds are normalized with a bottom-left origin.
164
+ code.bounds = {
165
+ x: ox * W,
166
+ y: (1 - oy - height) * H,
167
+ width: width * W,
168
+ height: height * H,
169
+ }
170
+ }
171
+ }
172
+
173
+ codes.push(code)
174
+ }
175
+
176
+ return codes
177
+ },
178
+ }
@@ -0,0 +1,80 @@
1
+ // Barcode scanner — native service leaf. Live scanning is the <BarcodeScanner>
2
+ // component (mlkit-core's MLKitView); this file owns the camera permission
3
+ // ensure (platform primitives, media's pattern) and headless still decode.
4
+ import { ImageSource } from '@nativescript/core'
5
+ import { DetectionType, detectWithStillImage } from '@nativescript/mlkit-core'
6
+ import type { BarcodeFormat, BarcodeScannerService, ScannedCode } from './types'
7
+ import { cameraPermissionStatus, ensureCameraPermission } from './barcode-permission'
8
+ import type { PermissionStatus } from '@octane-xplat/platform'
9
+ import { fromNativeFormat, toNativeFormats } from './format-map'
10
+
11
+ async function toImageSource(image: unknown): Promise<any> {
12
+ if (image instanceof ImageSource) {
13
+ return image
14
+ }
15
+
16
+ if (typeof image === 'string') {
17
+ return ImageSource.fromFile(image)
18
+ }
19
+
20
+ if (
21
+ typeof image === 'object' &&
22
+ image !== null &&
23
+ 'uri' in image &&
24
+ typeof image.uri === 'string'
25
+ ) {
26
+ return ImageSource.fromFile(image.uri)
27
+ }
28
+
29
+ throw new Error('barcodeScanner.scanImage: expected an ImageSource, file path, or {uri} ref')
30
+ }
31
+
32
+ /** Headless barcode service — permission + still-image decode. See BarcodeScannerService. */
33
+ export const barcodeScanner: BarcodeScannerService = {
34
+ supported: true,
35
+
36
+ ensure: ensureCameraPermission,
37
+
38
+ async scanImage(image: unknown, formats?: BarcodeFormat[]): Promise<ScannedCode[]> {
39
+ const source = await toImageSource(image)
40
+ const result = await detectWithStillImage(source, {
41
+ detectorType: DetectionType.Barcode,
42
+ barcodeScanning: { barcodeFormat: toNativeFormats(formats) as [any] },
43
+ })
44
+
45
+ const list = Array.isArray(result) ? result : Object.values(result ?? {})
46
+
47
+ return list
48
+ .flat()
49
+ .filter((item: any) => item && (item.rawValue !== undefined || item.format !== undefined))
50
+ .map((item: any) => ({
51
+ type: fromNativeFormat(item.format),
52
+ data: String(item.rawValue ?? item.displayValue ?? ''),
53
+ bounds: item.bounds
54
+ ? {
55
+ x: item.bounds.origin?.x ?? item.bounds.x ?? 0,
56
+ y: item.bounds.origin?.y ?? item.bounds.y ?? 0,
57
+ width: item.bounds.size?.width ?? item.bounds.width ?? 0,
58
+ height: item.bounds.size?.height ?? item.bounds.height ?? 0,
59
+ }
60
+ : undefined,
61
+ }))
62
+ },
63
+ }
64
+
65
+ // Scanning needs camera access — register the kind this leaf owns for the
66
+ // platform dispatcher. media registers the same 'camera' kind with the
67
+ // availability-aware owner, so claim it only as a fallback: media's owner
68
+ // wins whenever it is installed regardless of module evaluation order.
69
+ const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
70
+
71
+ const toResponse = (status: PermissionStatus) => ({
72
+ status,
73
+ granted: status === 'granted',
74
+ canAskAgain: status === 'granted' || status === 'undetermined',
75
+ })
76
+
77
+ permissionOwners.camera ??= {
78
+ getPermissions: async () => toResponse(cameraPermissionStatus()),
79
+ requestPermissions: async () => toResponse(await barcodeScanner.ensure()),
80
+ }
@@ -0,0 +1,77 @@
1
+ // Barcode scanner — web service leaf over the BarcodeDetector API. Live
2
+ // scanning is <BarcodeScanner> (getUserMedia + detector poll); this owns
3
+ // still-image decode and the availability flag.
4
+ import type { BarcodeFormat, BarcodeScannerService, PermissionResult, ScannedCode } from './types'
5
+ import { fromDetectorFormat, toDetectorFormats } from './format-map.web'
6
+
7
+ const detector = () => {
8
+ const Detector = (globalThis as any).BarcodeDetector
9
+
10
+ return typeof Detector === 'function' ? Detector : null
11
+ }
12
+
13
+ async function toImageSource(image: unknown): Promise<any> {
14
+ if (typeof image === 'string') {
15
+ const response = await fetch(image)
16
+
17
+ return createImageBitmap(await response.blob())
18
+ }
19
+
20
+ return image
21
+ }
22
+
23
+ /** Headless barcode service — permission + still-image decode. See BarcodeScannerService. */
24
+ export const barcodeScanner: BarcodeScannerService = {
25
+ supported: detector() !== null,
26
+
27
+ ensure(): Promise<PermissionResult> {
28
+ return Promise.resolve(detector() ? 'granted' : 'unsupported')
29
+ },
30
+
31
+ async scanImage(image: unknown, formats?: BarcodeFormat[]): Promise<ScannedCode[]> {
32
+ const Detector = detector()
33
+
34
+ if (!Detector) {
35
+ throw new Error('unsupported: BarcodeDetector is not available')
36
+ }
37
+
38
+ let d: any
39
+
40
+ try {
41
+ d = new Detector({ formats: toDetectorFormats(formats) })
42
+ } catch {
43
+ d = new Detector()
44
+ }
45
+
46
+ const source = await toImageSource(image)
47
+ const codes = await d.detect(source)
48
+
49
+ return (codes ?? []).map((code: any) => ({
50
+ type: fromDetectorFormat(code.format),
51
+ data: String(code.rawValue ?? ''),
52
+ bounds: code.boundingBox
53
+ ? {
54
+ x: code.boundingBox.x,
55
+ y: code.boundingBox.y,
56
+ width: code.boundingBox.width,
57
+ height: code.boundingBox.height,
58
+ }
59
+ : undefined,
60
+ }))
61
+ },
62
+ }
63
+
64
+ const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
65
+
66
+ const toResponse = (status: PermissionResult) => ({
67
+ status,
68
+ granted: status === 'granted',
69
+ canAskAgain: status === 'granted',
70
+ })
71
+
72
+ // BarcodeDetector presence is the only check — ensure() never prompts here.
73
+ // media registers the same 'camera' kind, so claim it only as a fallback.
74
+ permissionOwners.camera ??= {
75
+ getPermissions: async () => toResponse(await barcodeScanner.ensure()),
76
+ requestPermissions: async () => toResponse(await barcodeScanner.ensure()),
77
+ }
@@ -0,0 +1,24 @@
1
+ // Windows leaf — no ML Kit/BarcodeDetector backend; report unsupported.
2
+ import type { BarcodeScannerService, PermissionResult } from './types'
3
+
4
+ /** Headless barcode service — permission + still-image decode. See BarcodeScannerService. */
5
+ export const barcodeScanner: BarcodeScannerService = {
6
+ supported: false,
7
+ ensure: async (): Promise<PermissionResult> => 'unsupported',
8
+ scanImage: () =>
9
+ Promise.reject(new Error('unsupported: barcode scanning is not available on windows')),
10
+ }
11
+
12
+ const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
13
+
14
+ const toResponse = (status: PermissionResult) => ({
15
+ status,
16
+ granted: status === 'granted',
17
+ canAskAgain: status === 'granted',
18
+ })
19
+
20
+ // media registers the same 'camera' kind, so claim it only as a fallback.
21
+ permissionOwners.camera ??= {
22
+ getPermissions: async () => toResponse(await barcodeScanner.ensure()),
23
+ requestPermissions: async () => toResponse(await barcodeScanner.ensure()),
24
+ }
@@ -0,0 +1,31 @@
1
+ // Shared BarcodeFormat ↔ native-vocabulary mapping.
2
+ import { BarcodeFormats } from '@nativescript/mlkit-core'
3
+ import type { BarcodeFormat } from './types'
4
+
5
+ const TO_MLKIT: Record<BarcodeFormat, BarcodeFormats> = {
6
+ qr: BarcodeFormats.QR_CODE,
7
+ ean13: BarcodeFormats.EAN_13,
8
+ ean8: BarcodeFormats.EAN_8,
9
+ upc_a: BarcodeFormats.UPC_A,
10
+ upc_e: BarcodeFormats.UPC_E,
11
+ code128: BarcodeFormats.CODE_128,
12
+ code39: BarcodeFormats.CODE_39,
13
+ code93: BarcodeFormats.CODE_93,
14
+ codabar: BarcodeFormats.CODABAR,
15
+ itf: BarcodeFormats.ITF,
16
+ datamatrix: BarcodeFormats.DATA_MATRIX,
17
+ pdf417: BarcodeFormats.PDF417,
18
+ aztec: BarcodeFormats.AZTEC,
19
+ }
20
+
21
+ const FROM_MLKIT: Record<string, string> = Object.fromEntries(
22
+ Object.entries(TO_MLKIT).map(([ours, theirs]) => [String(theirs), ours]),
23
+ )
24
+
25
+ export function toNativeFormats(formats?: BarcodeFormat[]): BarcodeFormats[] {
26
+ return formats?.length ? formats.map((f) => TO_MLKIT[f]) : [BarcodeFormats.ALL]
27
+ }
28
+
29
+ export function fromNativeFormat(format: unknown): string {
30
+ return FROM_MLKIT[String(format)] ?? String(format ?? 'unknown')
31
+ }
@@ -0,0 +1,30 @@
1
+ // Shared BarcodeFormat ↔ web BarcodeDetector-vocabulary mapping.
2
+ import type { BarcodeFormat } from './types'
3
+
4
+ const TO_DETECTOR: Record<BarcodeFormat, string> = {
5
+ qr: 'qr_code',
6
+ ean13: 'ean_13',
7
+ ean8: 'ean_8',
8
+ upc_a: 'upc_a',
9
+ upc_e: 'upc_e',
10
+ code128: 'code_128',
11
+ code39: 'code_39',
12
+ code93: 'code_93',
13
+ codabar: 'codabar',
14
+ itf: 'itf',
15
+ datamatrix: 'data_matrix',
16
+ pdf417: 'pdf417',
17
+ aztec: 'aztec',
18
+ }
19
+
20
+ const FROM_DETECTOR: Record<string, string> = Object.fromEntries(
21
+ Object.entries(TO_DETECTOR).map(([ours, theirs]) => [theirs, ours]),
22
+ )
23
+
24
+ export function toDetectorFormats(formats?: BarcodeFormat[]): string[] | undefined {
25
+ return formats?.length ? formats.map((f) => TO_DETECTOR[f]) : undefined
26
+ }
27
+
28
+ export function fromDetectorFormat(format: unknown): string {
29
+ return FROM_DETECTOR[String(format)] ?? String(format ?? 'unknown')
30
+ }
@@ -0,0 +1,4 @@
1
+ export * from './types'
2
+ export * from './props'
3
+ export { barcodeScanner } from './barcode-scanner.macos'
4
+ export { BarcodeScanner } from './BarcodeScanner.macos.tsrx'
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from './types'
2
+ export * from './props'
3
+ export { barcodeScanner } from './barcode-scanner'
4
+ export { BarcodeScanner } from './BarcodeScanner.tsrx'
@@ -0,0 +1,4 @@
1
+ export * from './types'
2
+ export * from './props'
3
+ export { barcodeScanner } from './barcode-scanner.web'
4
+ export { BarcodeScanner } from './BarcodeScanner.web.tsrx'
@@ -0,0 +1,7 @@
1
+ import type { Attributes } from '@octane-xplat/jsx/intrinsics'
2
+
3
+ declare module '@octane-xplat/jsx/intrinsics' {
4
+ interface NativeElements<TElement> {
5
+ xplatbarcodescanner: Attributes<TElement>
6
+ }
7
+ }
package/src/props.ts ADDED
@@ -0,0 +1,43 @@
1
+ import type { Octane } from 'octane/jsx-runtime'
2
+ import type { BarcodeFormat, ScannedCode } from './types'
3
+
4
+ /** Imperative handle exposed through the BarcodeScanner `ref`. */
5
+ export interface BarcodeScannerHandle {
6
+ /** Pause/resume preview processing (not the camera feed itself). */
7
+ setPaused(paused: boolean): void
8
+ /** Switch between the front and back cameras while scanning. */
9
+ toggleCamera(): void
10
+ /** The underlying MLKitView on native, the <video> element on web. */
11
+ native: unknown
12
+ }
13
+
14
+ /** Live barcode/QR scanning view — ML Kit on native, BarcodeDetector on web.
15
+ * Decoding only: photo capture stays in `@octane-xplat/camera`, gallery
16
+ * picking in `@octane-xplat/media`. */
17
+ export interface BarcodeScannerProps {
18
+ /** Class list applied to the preview element. */
19
+ className?: any
20
+ /** Inline style applied to the preview element (string CSS or object). */
21
+ style?: any
22
+ /** Restrict decoded symbologies — all supported formats by default. */
23
+ formats?: BarcodeFormat[]
24
+ /** Fires for each detected code (the OS may deliver batches). */
25
+ onCodeScanned?: (e: { type: string; data: string; bounds?: ScannedCode['bounds'] }) => void
26
+ /** Freeze detection; preview keeps running. Default false. */
27
+ paused?: boolean
28
+ /** Illuminate the camera torch while scanning. Default false. */
29
+ torch?: boolean
30
+ /** 'back' | 'front'. Default 'back'. */
31
+ facing?: 'back' | 'front'
32
+ /** Detector/preview failures (permission is requested separately via the
33
+ * `barcodeScanner` service, not surfaced here). */
34
+ onError?: (e: { message: string }) => void
35
+ /** Imperative handle — see BarcodeScannerHandle. */
36
+ ref?: Octane.Ref<BarcodeScannerHandle>
37
+ /** Platform escape hatches, applied after the shared props. */
38
+ ios?: Record<string, any>
39
+ /** Platform escape hatch — same bag contract as `ios`. */
40
+ android?: Record<string, any>
41
+ /** Platform escape hatch — same bag contract as `ios`. */
42
+ web?: Record<string, any>
43
+ }
package/src/types.ts ADDED
@@ -0,0 +1,44 @@
1
+ /** Result of ensure(): 'unsupported' means the platform has no camera/permission path. */
2
+ export type PermissionResult = 'granted' | 'denied' | 'unsupported'
3
+
4
+ /** Code symbologies — expo-camera spellings; each platform maps them onto
5
+ * its own detector vocabulary (ML Kit BarcodeFormats / BarcodeDetector). */
6
+ export type BarcodeFormat =
7
+ | 'qr'
8
+ | 'ean13'
9
+ | 'ean8'
10
+ | 'upc_a'
11
+ | 'upc_e'
12
+ | 'code128'
13
+ | 'code39'
14
+ | 'code93'
15
+ | 'codabar'
16
+ | 'itf'
17
+ | 'datamatrix'
18
+ | 'pdf417'
19
+ | 'aztec'
20
+
21
+ /** One decoded barcode/QR value. */
22
+ export interface ScannedCode {
23
+ /** The symbology, in our BarcodeFormat spelling. */
24
+ type: string
25
+ /** Decoded payload. */
26
+ data: string
27
+ /** Corner points / bounding rect where the detector reports it. */
28
+ bounds?: { x: number; y: number; width: number; height: number }
29
+ }
30
+
31
+ /** Headless decode + permission service — the scanning view is
32
+ * `<BarcodeScanner>` from the same package. */
33
+ export interface BarcodeScannerService {
34
+ /** Synchronous fast check — a detector backend exists on this platform. */
35
+ readonly supported: boolean
36
+ /** Ensure camera permission for live scanning. */
37
+ ensure(): Promise<PermissionResult>
38
+ /** Decode codes from a still image (platform image ref: a path or
39
+ * ImageSource on native, Blob/HTMLImageElement/data URL on web).
40
+ * Returns [] when the detector finds nothing. */
41
+ scanImage(image: unknown, formats?: BarcodeFormat[]): Promise<ScannedCode[]>
42
+ }
43
+
44
+ export declare const barcodeScanner: BarcodeScannerService
@@ -0,0 +1,13 @@
1
+ {
2
+ "version": 1,
3
+ "files": [
4
+ "BarcodeScanner.d.ts",
5
+ "barcode-permission.android.d.ts",
6
+ "barcode-permission.ios.d.ts",
7
+ "barcode-scanner.d.ts",
8
+ "format-map.d.ts",
9
+ "index.d.ts",
10
+ "props.d.ts",
11
+ "types.d.ts"
12
+ ]
13
+ }
@@ -0,0 +1,4 @@
1
+ import type { BarcodeScannerProps } from './props.js';
2
+ /** Live barcode/QR scanner — ML Kit's camera preview with `detectionType:
3
+ * barcode`. Decoding only; photo capture stays in @octane-xplat/camera. */
4
+ export declare function BarcodeScanner(props: BarcodeScannerProps): unknown;
@@ -0,0 +1,4 @@
1
+ import type { PermissionStatus } from '@octane-xplat/platform';
2
+ import type { PermissionResult } from './types.js';
3
+ export declare function cameraPermissionStatus(): PermissionStatus;
4
+ export declare function ensureCameraPermission(): Promise<PermissionResult>;
@@ -0,0 +1,4 @@
1
+ import type { PermissionStatus } from '@octane-xplat/platform';
2
+ import type { PermissionResult } from './types.js';
3
+ export declare function cameraPermissionStatus(): PermissionStatus;
4
+ export declare function ensureCameraPermission(): Promise<PermissionResult>;
@@ -0,0 +1,3 @@
1
+ import type { BarcodeScannerService } from './types.js';
2
+ /** Headless barcode service — permission + still-image decode. See BarcodeScannerService. */
3
+ export declare const barcodeScanner: BarcodeScannerService;
@@ -0,0 +1,4 @@
1
+ import { BarcodeFormats } from '@nativescript/mlkit-core';
2
+ import type { BarcodeFormat } from './types.js';
3
+ export declare function toNativeFormats(formats?: BarcodeFormat[]): BarcodeFormats[];
4
+ export declare function fromNativeFormat(format: unknown): string;
@@ -0,0 +1,4 @@
1
+ export * from './types.js';
2
+ export * from './props.js';
3
+ export { barcodeScanner } from './barcode-scanner.js';
4
+ export { BarcodeScanner } from './BarcodeScanner.js';
@@ -0,0 +1,47 @@
1
+ import type { Octane } from 'octane/jsx-runtime';
2
+ import type { BarcodeFormat, ScannedCode } from './types.js';
3
+ /** Imperative handle exposed through the BarcodeScanner `ref`. */
4
+ export interface BarcodeScannerHandle {
5
+ /** Pause/resume preview processing (not the camera feed itself). */
6
+ setPaused(paused: boolean): void;
7
+ /** Switch between the front and back cameras while scanning. */
8
+ toggleCamera(): void;
9
+ /** The underlying MLKitView on native, the <video> element on web. */
10
+ native: unknown;
11
+ }
12
+ /** Live barcode/QR scanning view — ML Kit on native, BarcodeDetector on web.
13
+ * Decoding only: photo capture stays in `@octane-xplat/camera`, gallery
14
+ * picking in `@octane-xplat/media`. */
15
+ export interface BarcodeScannerProps {
16
+ /** Class list applied to the preview element. */
17
+ className?: any;
18
+ /** Inline style applied to the preview element (string CSS or object). */
19
+ style?: any;
20
+ /** Restrict decoded symbologies — all supported formats by default. */
21
+ formats?: BarcodeFormat[];
22
+ /** Fires for each detected code (the OS may deliver batches). */
23
+ onCodeScanned?: (e: {
24
+ type: string;
25
+ data: string;
26
+ bounds?: ScannedCode['bounds'];
27
+ }) => void;
28
+ /** Freeze detection; preview keeps running. Default false. */
29
+ paused?: boolean;
30
+ /** Illuminate the camera torch while scanning. Default false. */
31
+ torch?: boolean;
32
+ /** 'back' | 'front'. Default 'back'. */
33
+ facing?: 'back' | 'front';
34
+ /** Detector/preview failures (permission is requested separately via the
35
+ * `barcodeScanner` service, not surfaced here). */
36
+ onError?: (e: {
37
+ message: string;
38
+ }) => void;
39
+ /** Imperative handle — see BarcodeScannerHandle. */
40
+ ref?: Octane.Ref<BarcodeScannerHandle>;
41
+ /** Platform escape hatches, applied after the shared props. */
42
+ ios?: Record<string, any>;
43
+ /** Platform escape hatch — same bag contract as `ios`. */
44
+ android?: Record<string, any>;
45
+ /** Platform escape hatch — same bag contract as `ios`. */
46
+ web?: Record<string, any>;
47
+ }
@@ -0,0 +1,32 @@
1
+ /** Result of ensure(): 'unsupported' means the platform has no camera/permission path. */
2
+ export type PermissionResult = 'granted' | 'denied' | 'unsupported';
3
+ /** Code symbologies — expo-camera spellings; each platform maps them onto
4
+ * its own detector vocabulary (ML Kit BarcodeFormats / BarcodeDetector). */
5
+ export type BarcodeFormat = 'qr' | 'ean13' | 'ean8' | 'upc_a' | 'upc_e' | 'code128' | 'code39' | 'code93' | 'codabar' | 'itf' | 'datamatrix' | 'pdf417' | 'aztec';
6
+ /** One decoded barcode/QR value. */
7
+ export interface ScannedCode {
8
+ /** The symbology, in our BarcodeFormat spelling. */
9
+ type: string;
10
+ /** Decoded payload. */
11
+ data: string;
12
+ /** Corner points / bounding rect where the detector reports it. */
13
+ bounds?: {
14
+ x: number;
15
+ y: number;
16
+ width: number;
17
+ height: number;
18
+ };
19
+ }
20
+ /** Headless decode + permission service — the scanning view is
21
+ * `<BarcodeScanner>` from the same package. */
22
+ export interface BarcodeScannerService {
23
+ /** Synchronous fast check — a detector backend exists on this platform. */
24
+ readonly supported: boolean;
25
+ /** Ensure camera permission for live scanning. */
26
+ ensure(): Promise<PermissionResult>;
27
+ /** Decode codes from a still image (platform image ref: a path or
28
+ * ImageSource on native, Blob/HTMLImageElement/data URL on web).
29
+ * Returns [] when the detector finds nothing. */
30
+ scanImage(image: unknown, formats?: BarcodeFormat[]): Promise<ScannedCode[]>;
31
+ }
32
+ export declare const barcodeScanner: BarcodeScannerService;