@tallyui/pos 3.18.0 → 3.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/dist/index.d.ts +3202 -1721
  2. package/dist/index.js +3871 -677
  3. package/package.json +6 -6
  4. package/src/customer-display/display-client.ts +341 -0
  5. package/src/customer-display/index.ts +20 -0
  6. package/src/customer-display/sale-display.ts +115 -0
  7. package/src/customer-display/snapshot-fallback.ts +138 -0
  8. package/src/customer-display/till-display-service.ts +304 -0
  9. package/src/customer-display/till-pairing.ts +177 -0
  10. package/src/customer-display/use-display-client.ts +25 -0
  11. package/src/customer-display/use-sale-display.ts +28 -0
  12. package/src/customer-display/use-till-pairing.ts +35 -0
  13. package/src/customer-display/webrtc/index.ts +5 -0
  14. package/src/customer-display/webrtc/peer-link.ts +222 -0
  15. package/src/index.ts +36 -10
  16. package/src/order/index.ts +2 -1
  17. package/src/order/order-builder.ts +104 -16
  18. package/src/order/types.ts +10 -4
  19. package/src/payment-driver/index.ts +1 -1
  20. package/src/payment-driver/registry.ts +23 -0
  21. package/src/pos-order/__fixtures__/order-create-v8.json +117 -0
  22. package/src/pos-order/command.ts +27 -9
  23. package/src/pos-order/finalize.ts +30 -2
  24. package/src/pos-order/schema.ts +16 -5
  25. package/src/pos-order/types.ts +7 -4
  26. package/src/receipt/reprint.ts +3 -10
  27. package/src/receipt/woo-gross.ts +16 -0
  28. package/src/receipt-template/index.ts +8 -0
  29. package/src/receipt-template/render-store-template.ts +51 -0
  30. package/src/receipt-template/wcpos/build.ts +320 -0
  31. package/src/receipt-template/wcpos/context.ts +29 -0
  32. package/src/receipt-template/wcpos/format.ts +153 -0
  33. package/src/receipt-template/wcpos/from-orders.ts +203 -0
  34. package/src/receipt-template/wcpos/index.ts +11 -0
  35. package/src/receipt-template/wcpos/money.ts +42 -0
  36. package/src/receipt-template/wcpos/types.ts +350 -0
  37. package/src/register/expected.ts +60 -0
  38. package/src/register/index.ts +2 -2
  39. package/src/register/use-register-session.ts +8 -4
  40. package/src/sale/discount-codes.ts +7 -2
  41. package/src/sale/index.ts +9 -2
  42. package/src/sale/order-filters-query.ts +59 -0
  43. package/src/sale/store-priced-discount-codes.ts +52 -0
  44. package/src/sale/use-sale.ts +157 -16
  45. package/src/sale/variant-match.ts +44 -0
  46. package/src/scanner/camera-scan.ts +113 -0
  47. package/src/scanner/capabilities.ts +22 -0
  48. package/src/scanner/chooser-cancel.ts +8 -0
  49. package/src/scanner/device-identity.ts +84 -0
  50. package/src/scanner/device-scanner.ts +62 -0
  51. package/src/scanner/hid-pos-decoder.ts +60 -0
  52. package/src/scanner/hid-scanner.ts +171 -0
  53. package/src/scanner/index.ts +27 -0
  54. package/src/scanner/scan-dedup.ts +48 -0
  55. package/src/scanner/scan-events.ts +75 -0
  56. package/src/scanner/scan-hub-context.tsx +124 -0
  57. package/src/scanner/scan-session.ts +4 -0
  58. package/src/scanner/scanner-profiles.ts +96 -0
  59. package/src/scanner/serial-line-decoder.ts +58 -0
  60. package/src/scanner/serial-scanner.ts +227 -0
  61. package/src/scanner/use-barcode-scanner.ts +23 -5
  62. package/src/scanner/use-camera-scan.ts +57 -0
  63. package/src/scanner/wedge-detector.ts +28 -6
  64. package/src/store-settings/use-store-settings.ts +23 -5
  65. package/src/tax/index.ts +6 -0
  66. package/src/tax/location-rates.ts +46 -0
  67. package/src/tax/sale-tax-contexts.ts +40 -0
  68. package/src/tax/tax-context.ts +37 -0
  69. package/src/tax/tax-derivation.ts +99 -0
  70. package/src/tax/tax-provider.tsx +4 -31
@@ -0,0 +1,113 @@
1
+ // Ported from WCPOS v2 packages/core/src/screens/main/pos/products (scanner-viewfinder.web.tsx, decode-loop.ts).
2
+ /** The symbologies a camera scanner looks for, in TallyUI's (and expo-camera's) names. */
3
+ export const CAMERA_BARCODE_TYPES = ['ean13', 'ean8', 'upc_a', 'upc_e', 'code128', 'qr'] as const;
4
+ /** The same symbologies in BarcodeDetector's format names. */
5
+ export const DETECTOR_FORMATS = ['ean_13', 'ean_8', 'upc_a', 'upc_e', 'code_128', 'qr_code'] as const;
6
+
7
+ const DETECTOR_TO_SYMBOLOGY: Record<string, string> = {
8
+ ean_13: 'ean13', ean_8: 'ean8', upc_a: 'upc_a', upc_e: 'upc_e', code_128: 'code128', qr_code: 'qr',
9
+ };
10
+
11
+ /** BarcodeDetector format → TallyUI symbology (v2 WEB_TO_EXPO_TYPE). Unknown formats map to undefined. */
12
+ export function detectorFormatToSymbology(format: string): string | undefined {
13
+ return Object.prototype.hasOwnProperty.call(DETECTOR_TO_SYMBOLOGY, format) ? DETECTOR_TO_SYMBOLOGY[format] : undefined;
14
+ }
15
+
16
+ export interface DetectedBarcode { rawValue: string; format: string }
17
+ /** The structural part of BarcodeDetector the loop uses (the native API and v2's ponyfill both fit). */
18
+ export interface CameraDecoder { detect(source: unknown): Promise<DetectedBarcode[]> }
19
+
20
+ type DetectorClass = new (options: { formats: string[] }) => CameraDecoder;
21
+
22
+ /** The browser's BarcodeDetector for DETECTOR_FORMATS, or undefined when the global is missing. Never throws. */
23
+ export function nativeBarcodeDetector(): CameraDecoder | undefined {
24
+ try {
25
+ const Detector = (globalThis as { BarcodeDetector?: DetectorClass }).BarcodeDetector;
26
+ if (typeof Detector !== 'function') return undefined;
27
+ const detector = new Detector({ formats: [...DETECTOR_FORMATS] });
28
+ return { detect: (source) => detector.detect(source) };
29
+ } catch {
30
+ return undefined;
31
+ }
32
+ }
33
+
34
+ export type ViewfinderStatus = 'initializing' | 'scanning' | 'camera-denied' | 'camera-unavailable' | 'decoder-error';
35
+ export const DEFAULT_DECODE_INTERVAL_MS = 200;
36
+ /** Consecutive decoder rejections before the scanner reports 'decoder-error'. */
37
+ export const DECODER_ERROR_THRESHOLD = 5;
38
+
39
+ export interface DecodeLoopOptions {
40
+ decoder: CameraDecoder;
41
+ /** The <video> element on web. */
42
+ source: unknown;
43
+ onDetected: (code: string, symbology?: string) => void;
44
+ onStatus: (status: 'scanning' | 'decoder-error') => void;
45
+ intervalMs?: number;
46
+ /** Default setTimeout. */
47
+ setTimer?: (fn: () => void, ms: number) => unknown;
48
+ /** Default clearTimeout. */
49
+ clearTimer?: (handle: unknown) => void;
50
+ }
51
+
52
+ /** Decode every intervalMs: one detect in flight at a time; each result goes to onDetected; DECODER_ERROR_THRESHOLD
53
+ * consecutive rejections report 'decoder-error'; any success clears the count and reports 'scanning' again. stop()
54
+ * ends it, and no callback fires after stop. */
55
+ export function startDecodeLoop(options: DecodeLoopOptions): { stop(): void } {
56
+ const intervalMs = options.intervalMs ?? DEFAULT_DECODE_INTERVAL_MS;
57
+ const setTimer = options.setTimer ?? ((fn: () => void, ms: number) => globalThis.setTimeout(fn, ms));
58
+ const clearTimer = options.clearTimer
59
+ ?? ((handle: unknown) => globalThis.clearTimeout(handle as ReturnType<typeof setTimeout>));
60
+ let stopped = false;
61
+ let handle: unknown;
62
+ let failures = 0;
63
+ let failing = false;
64
+
65
+ const schedule = () => {
66
+ if (!stopped) handle = setTimer(tick, intervalMs);
67
+ };
68
+ // The next detect is scheduled only once this one settles, so a slow decoder never has two in flight.
69
+ function tick() {
70
+ handle = undefined;
71
+ Promise.resolve()
72
+ .then(() => options.decoder.detect(options.source))
73
+ .then((results) => {
74
+ if (stopped) return;
75
+ failures = 0;
76
+ if (failing) {
77
+ failing = false;
78
+ options.onStatus('scanning');
79
+ }
80
+ for (const { rawValue, format } of results) {
81
+ if (stopped) return;
82
+ if (rawValue) options.onDetected(rawValue, detectorFormatToSymbology(format));
83
+ }
84
+ }, () => {
85
+ if (stopped) return;
86
+ failures += 1;
87
+ if (failures === DECODER_ERROR_THRESHOLD) {
88
+ failing = true;
89
+ options.onStatus('decoder-error');
90
+ }
91
+ })
92
+ .finally(schedule);
93
+ }
94
+
95
+ schedule();
96
+ return {
97
+ stop: () => {
98
+ stopped = true;
99
+ if (handle !== undefined) clearTimer(handle);
100
+ handle = undefined;
101
+ },
102
+ };
103
+ }
104
+
105
+ /** getUserMedia error → status: NotAllowedError → 'camera-denied', anything else → 'camera-unavailable'. */
106
+ export function cameraErrorStatus(error: unknown): 'camera-denied' | 'camera-unavailable' {
107
+ return (error as { name?: unknown } | null)?.name === 'NotAllowedError' ? 'camera-denied' : 'camera-unavailable';
108
+ }
109
+
110
+ export const CAMERA_CONSTRAINTS: MediaStreamConstraints = {
111
+ video: { facingMode: { ideal: 'environment' }, width: { ideal: 1280 }, height: { ideal: 720 } },
112
+ audio: false,
113
+ };
@@ -0,0 +1,22 @@
1
+ // Ported from WCPOS v2 packages/scanner/src/capabilities.ts (monorepo 85ecbd43f).
2
+ /** Feature detection for the direct-connection transports. Web Serial and
3
+ * WebHID exist on Chromium desktop; elsewhere these functions return false. */
4
+
5
+ interface NavigatorLike {
6
+ serial?: unknown;
7
+ hid?: unknown;
8
+ userAgent?: string;
9
+ }
10
+
11
+ function nav(navLike?: NavigatorLike): NavigatorLike | undefined {
12
+ if (navLike) return navLike;
13
+ return typeof navigator !== 'undefined' ? (navigator as NavigatorLike) : undefined;
14
+ }
15
+
16
+ export function isWebSerialSupported(navLike?: NavigatorLike): boolean {
17
+ return !!nav(navLike)?.serial;
18
+ }
19
+
20
+ export function isWebHidSupported(navLike?: NavigatorLike): boolean {
21
+ return !!nav(navLike)?.hid;
22
+ }
@@ -0,0 +1,8 @@
1
+ // Ported from WCPOS v2 packages/core/src/screens/main/pos/products/chooser-cancel.ts (monorepo 85ecbd43f).
2
+ /** WCPOS v2 treats `NotFoundError` and `AbortError` from the serial or HID
3
+ * chooser as the cashier closing it without picking a device. That is a
4
+ * cancel, not a scanner fault. */
5
+ export function isChooserCancel(error: unknown): boolean {
6
+ const name = (error as { name?: unknown } | null)?.name;
7
+ return name === 'NotFoundError' || name === 'AbortError';
8
+ }
@@ -0,0 +1,84 @@
1
+ // Ported from WCPOS v2 packages/scanner/src/device-identity.ts (monorepo 85ecbd43f).
2
+ /** One canonical identity for a registered scanner. The key is composed here,
3
+ * once, and every consumer compares strings. It is also the scanner-profile
4
+ * primary key, so the database enforces one profile per device.
5
+ *
6
+ * Known ceiling: a key identifies a model or service, not a unit. Two identical
7
+ * USB scanners on one till share a vid:pid and therefore one profile. A USB
8
+ * serial number is optional and absent on most retail scanners, so keying on it
9
+ * would mint a different key depending on whether the platform reported it. */
10
+
11
+ export type ScannerConnectionType = 'keyboard' | 'usb-serial' | 'bluetooth-spp' | 'bluetooth-le' | 'hid-pos';
12
+
13
+ /** The identifying facts each lane can observe. A discriminated union, so it
14
+ * is a type error to build a Bluetooth key out of USB ids. */
15
+ export type ScannerIdentity =
16
+ | { connectionType: 'keyboard'; vendorId: number; productId: number; deviceName: string }
17
+ | { connectionType: 'usb-serial'; vendorId: number; productId: number }
18
+ | { connectionType: 'hid-pos'; vendorId: number; productId: number }
19
+ | { connectionType: 'bluetooth-spp'; serviceUuid: string }
20
+ | { connectionType: 'bluetooth-le'; peripheralId: string };
21
+
22
+ /** Primary-key ceiling. The only unbounded input is an Android device name. */
23
+ export const SCANNER_DEVICE_KEY_MAX_LENGTH = 128;
24
+
25
+ const DEVICE_NAME_KEY_MAX_LENGTH = 64;
26
+
27
+ const CANONICAL_UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
28
+
29
+ /** Lowercase + trim. Bluetooth UUIDs from the platform and from a merchant
30
+ * typing one into settings disagree about case; comparing them raw is how the
31
+ * same scanner ends up registered twice. */
32
+ export function normalizeUuid(value: string): string {
33
+ return value.trim().toLowerCase();
34
+ }
35
+
36
+ /** True for a full 128-bit UUID in canonical 8-4-4-4-12 form, after normalizing. */
37
+ export function isCanonicalUuid(value: string): boolean {
38
+ return CANONICAL_UUID_PATTERN.test(normalizeUuid(value));
39
+ }
40
+
41
+ /** Device names are display data with vendor padding and inconsistent case.
42
+ * Fold them hard for key purposes; the profile keeps the raw name for the UI. */
43
+ function foldDeviceName(deviceName: string): string {
44
+ return deviceName.trim().toLowerCase().replace(/\s+/g, ' ').slice(0, DEVICE_NAME_KEY_MAX_LENGTH);
45
+ }
46
+
47
+ /** Compose the canonical key. The connection type is part of the key so the
48
+ * same scanner registered over two transports stays two profiles: they
49
+ * reconnect differently and the merchant should see both. */
50
+ export function scannerDeviceKey(identity: ScannerIdentity): string {
51
+ switch (identity.connectionType) {
52
+ case 'keyboard':
53
+ // vid:pid alone is too coarse here: on Android the built-in virtual
54
+ // keyboard and a paired scanner can both report 0:0, so the folded name
55
+ // is what keeps them apart.
56
+ return `keyboard:${identity.vendorId}:${identity.productId}:${foldDeviceName(identity.deviceName)}`;
57
+ case 'usb-serial':
58
+ return `usb-serial:${identity.vendorId}:${identity.productId}`;
59
+ case 'hid-pos':
60
+ return `hid-pos:${identity.vendorId}:${identity.productId}`;
61
+ case 'bluetooth-spp':
62
+ return `bluetooth-spp:${normalizeUuid(identity.serviceUuid)}`;
63
+ case 'bluetooth-le':
64
+ return `bluetooth-le:${normalizeUuid(identity.peripheralId)}`;
65
+ }
66
+ }
67
+
68
+ /** Which transport the merchant is looking at, derived from the connection
69
+ * type so there is one authority for the mapping. `hid-pos` is `unknown`:
70
+ * WebHID reports no bus, so claiming "USB" would show a guess as a fact. */
71
+ export type ScannerTransport = 'usb' | 'bluetooth' | 'unknown';
72
+
73
+ export function scannerTransport(connectionType: ScannerConnectionType): ScannerTransport {
74
+ switch (connectionType) {
75
+ case 'usb-serial':
76
+ return 'usb';
77
+ case 'bluetooth-spp':
78
+ case 'bluetooth-le':
79
+ return 'bluetooth';
80
+ case 'keyboard':
81
+ case 'hid-pos':
82
+ return 'unknown';
83
+ }
84
+ }
@@ -0,0 +1,62 @@
1
+ /** Types and helpers shared by the framework-agnostic device-scanner controllers (Web Serial, WebHID). A controller
2
+ * takes its dependencies as arguments, so a host binds it to its own state. */
3
+ import type { ScannerConnectionType } from './device-identity';
4
+ import { readScannerProfiles, saveScannerProfile, type ScannerProfile, type ScannerProfileCollection } from './scanner-profiles';
5
+
6
+ /** What the controller needs from profile storage. The RxDB collection adapts to it with
7
+ * scannerProfileStore(); tests and the browser proof pass an in-memory one. */
8
+ export interface ScannerProfileStore {
9
+ read: (types: readonly ScannerConnectionType[]) => Promise<ScannerProfile[]>;
10
+ save: (profile: ScannerProfile) => Promise<void>;
11
+ }
12
+
13
+ export function scannerProfileStore(collection: ScannerProfileCollection): ScannerProfileStore {
14
+ return {
15
+ read: (types) => readScannerProfiles(collection, types),
16
+ save: (profile) => saveScannerProfile(collection, profile),
17
+ };
18
+ }
19
+
20
+ export interface DeviceScannerSettings { prefix: string; suffix: string; minChars: number }
21
+ export interface DeviceScannerState { connected: boolean; connectedDeviceKey: string | null }
22
+ export type DeviceScannerErrorPhase = 'connect' | 'reopen';
23
+ /** cancelled is isChooserCancel(error): the cashier closed the chooser. */
24
+ export type DeviceScannerErrorHandler = (error: unknown, info: { phase: DeviceScannerErrorPhase; cancelled: boolean }) => void;
25
+
26
+ /** A tiny observable state cell: get, set (notifies only on change, by value), subscribe (returns unsubscribe). */
27
+ export interface DeviceScannerStateCell {
28
+ get: () => DeviceScannerState;
29
+ set: (next: DeviceScannerState) => void;
30
+ subscribe: (listener: (state: DeviceScannerState) => void) => () => void;
31
+ }
32
+
33
+ export function createDeviceScannerStateCell(): DeviceScannerStateCell {
34
+ let state: DeviceScannerState = { connected: false, connectedDeviceKey: null };
35
+ const listeners = new Set<(state: DeviceScannerState) => void>();
36
+ return {
37
+ get: () => state,
38
+ set: (next) => {
39
+ if (next.connected === state.connected && next.connectedDeviceKey === state.connectedDeviceKey) return;
40
+ state = { connected: next.connected, connectedDeviceKey: next.connectedDeviceKey };
41
+ for (const listener of [...listeners]) listener(state);
42
+ },
43
+ subscribe: (listener) => {
44
+ listeners.add(listener);
45
+ return () => void listeners.delete(listener);
46
+ },
47
+ };
48
+ }
49
+
50
+ /** The controller surface part 5's hook binds to, shared by the serial and HID controllers. */
51
+ export interface DeviceScanner {
52
+ readonly available: boolean;
53
+ /** Opens the browser chooser: call it inside a user gesture. Never rejects; failures go to onError. */
54
+ connect: () => Promise<void>;
55
+ /** Silently reopens the one granted device that matches a saved profile. Never rejects; failures go to onError. */
56
+ reopenSaved: () => Promise<void>;
57
+ disconnect: () => Promise<void>;
58
+ /** disconnect, and every later call is a no-op (host teardown). */
59
+ dispose: () => Promise<void>;
60
+ getState: () => DeviceScannerState;
61
+ subscribe: (listener: (state: DeviceScannerState) => void) => () => void;
62
+ }
@@ -0,0 +1,60 @@
1
+ // Ported from WCPOS v2 packages/scanner/src/hid-pos-decoder.ts (monorepo 85ecbd43f).
2
+ /** Decodes a HID Point-of-Sale (USB-IF usage page 0x8C) barcode input report,
3
+ * shaped as:
4
+ *
5
+ * [reportId?] [length] [data … (length ASCII bytes)] [symbologyId?]
6
+ *
7
+ * a one-byte length prefix, the decoded barcode as ASCII, then an optional
8
+ * trailing symbology identifier. The whole barcode arrives in one report.
9
+ *
10
+ * Vendor variations exist (report-ID presence, symbology encoding, multi-report
11
+ * long barcodes). `hasReportId` covers the common one; anything more exotic is
12
+ * left for on-device tuning rather than guessed at here. */
13
+
14
+ export interface HidPosDecodeOptions {
15
+ /** The device's report descriptor prefixes each report with a report ID. */
16
+ hasReportId?: boolean;
17
+ }
18
+
19
+ export interface HidPosResult {
20
+ code: string;
21
+ symbology?: string;
22
+ }
23
+
24
+ // Common HID POS symbology identifiers → retail symbology strings. Unknown ids
25
+ // are left undefined.
26
+ const SYMBOLOGY_BY_ID: Record<number, string> = {
27
+ 0x02: 'code128',
28
+ 0x03: 'code39',
29
+ 0x0a: 'ean13',
30
+ 0x0b: 'ean8',
31
+ 0x0c: 'upc_a',
32
+ 0x0d: 'upc_e',
33
+ 0x11: 'qr',
34
+ 0x13: 'pdf417',
35
+ 0x15: 'datamatrix',
36
+ };
37
+
38
+ function toBytes(report: number[] | Uint8Array): number[] {
39
+ return Array.from(report);
40
+ }
41
+
42
+ export function decodeHidPosReport(report: number[] | Uint8Array, options: HidPosDecodeOptions = {}): HidPosResult | null {
43
+ let bytes = toBytes(report);
44
+ if (options.hasReportId) bytes = bytes.slice(1);
45
+ if (bytes.length < 2) return null;
46
+
47
+ const length = bytes[0];
48
+ if (length <= 0 || length > bytes.length - 1) return null;
49
+
50
+ const dataBytes = bytes.slice(1, 1 + length);
51
+ // Decoded data must be printable ASCII; a report of zeros or control bytes is
52
+ // a keep-alive or non-barcode report, not a scan.
53
+ if (!dataBytes.every((byte) => byte >= 0x20 && byte <= 0x7e)) return null;
54
+ const code = String.fromCharCode(...dataBytes);
55
+
56
+ const symbologyId = bytes[1 + length];
57
+ const symbology = symbologyId !== undefined ? SYMBOLOGY_BY_ID[symbologyId] : undefined;
58
+
59
+ return symbology ? { code, symbology } : { code };
60
+ }
@@ -0,0 +1,171 @@
1
+ // Ported from WCPOS v2 packages/core/src/screens/main/pos/products/use-hid-scan.web.ts (monorepo 85ecbd43f), as a framework-agnostic controller.
2
+ /** WebHID (USB HID POS, usage page 0x8C) barcode source. Each input report carries a complete decoded barcode;
3
+ * decode it, dedup via the scan session, and emit `hid-pos` ScanEvents. */
4
+ import { isChooserCancel } from './chooser-cancel';
5
+ import { scannerDeviceKey } from './device-identity';
6
+ import { createDeviceScannerStateCell, type DeviceScanner, type DeviceScannerErrorHandler, type DeviceScannerSettings,
7
+ type ScannerProfileStore } from './device-scanner';
8
+ import { decodeHidPosReport } from './hid-pos-decoder';
9
+ import type { ScanEvent } from './scan-events';
10
+ import { createScanSession } from './scan-session';
11
+
12
+ /** USB HID Point-of-Sale usage page: the structured barcode-scanner mode. */
13
+ export const HID_POS_USAGE_PAGE = 0x8c;
14
+
15
+ // Minimal WebHID typings (not in the TS DOM lib).
16
+ export interface HidInputReportEventLike { data: DataView; reportId: number }
17
+ export interface HidDeviceLike {
18
+ productName?: string;
19
+ vendorId: number;
20
+ productId: number;
21
+ collections?: { usagePage?: number }[];
22
+ open: () => Promise<void>;
23
+ close: () => Promise<void>;
24
+ addEventListener: (type: 'inputreport', listener: (event: HidInputReportEventLike) => void) => void;
25
+ removeEventListener: (type: 'inputreport', listener: (event: HidInputReportEventLike) => void) => void;
26
+ }
27
+ export interface HidLike {
28
+ requestDevice: (options: { filters: { usagePage?: number }[] }) => Promise<HidDeviceLike[]>;
29
+ getDevices: () => Promise<HidDeviceLike[]>;
30
+ }
31
+
32
+ export interface HidScannerOptions {
33
+ /** navigator.hid, or undefined where WebHID is absent (then available is false and every call is a no-op). */
34
+ hid: HidLike | undefined;
35
+ profiles: ScannerProfileStore;
36
+ /** prefix and suffix are unused by HID-POS (a report is already one framed code); minChars is the gate. */
37
+ getSettings: () => DeviceScannerSettings;
38
+ emit: (event: ScanEvent) => void;
39
+ onError?: DeviceScannerErrorHandler;
40
+ now?: () => number;
41
+ }
42
+
43
+ const DISCONNECTED = { connected: false, connectedDeviceKey: null } as const;
44
+
45
+ const hidDeviceKey = (device: HidDeviceLike) =>
46
+ scannerDeviceKey({ connectionType: 'hid-pos', vendorId: device.vendorId, productId: device.productId });
47
+
48
+ function dataViewToBytes(view: DataView): number[] {
49
+ const bytes: number[] = [];
50
+ for (let i = 0; i < view.byteLength; i += 1) bytes.push(view.getUint8(i));
51
+ return bytes;
52
+ }
53
+
54
+ export function createHidScanner(options: HidScannerOptions): DeviceScanner {
55
+ const { hid, profiles, getSettings, emit, onError } = options;
56
+ const now = options.now ?? Date.now;
57
+ const state = createDeviceScannerStateCell();
58
+
59
+ let activeDevice: HidDeviceLike | null = null;
60
+ let activeListener: ((event: HidInputReportEventLike) => void) | null = null;
61
+ let attachRequest = 0;
62
+ let lifecycleQueue: Promise<void> = Promise.resolve();
63
+ let disposed = false;
64
+ let disposing: Promise<void> | null = null;
65
+
66
+ const session = createScanSession({
67
+ onAccept: (code, symbology) => {
68
+ if (code.length < getSettings().minChars) return;
69
+ emit({ code, ...(symbology !== undefined ? { symbology } : {}), source: { kind: 'hid-pos' }, timestamp: now() });
70
+ },
71
+ });
72
+
73
+ const teardown = async () => {
74
+ const device = activeDevice;
75
+ const listener = activeListener;
76
+ activeDevice = null;
77
+ activeListener = null;
78
+ state.set(DISCONNECTED);
79
+ if (!device) return;
80
+ // Remove the listener before closing, so a report racing the close is never delivered.
81
+ if (listener) device.removeEventListener('inputreport', listener);
82
+ await device.close().catch(() => undefined);
83
+ };
84
+
85
+ const isStale = (request: number) => disposed || request !== attachRequest;
86
+
87
+ const attachDevice = async (device: HidDeviceLike, save: boolean) => {
88
+ const request = ++attachRequest;
89
+ let attached = false;
90
+ const pending = lifecycleQueue.then(async () => {
91
+ if (isStale(request)) return;
92
+ await teardown();
93
+ if (isStale(request)) return;
94
+ await device.open();
95
+ if (isStale(request)) {
96
+ await device.close().catch(() => undefined);
97
+ return;
98
+ }
99
+ const listener = (event: HidInputReportEventLike) => {
100
+ // WebHID delivers event.data as the report body *without* the report id (it is carried separately as
101
+ // event.reportId), so decode it directly: prepending it would read a report id of zero as the length.
102
+ const decoded = decodeHidPosReport(dataViewToBytes(event.data));
103
+ if (decoded) session.offer(decoded.code, decoded.symbology);
104
+ };
105
+ device.addEventListener('inputreport', listener);
106
+ activeDevice = device;
107
+ activeListener = listener;
108
+ session.reset();
109
+ state.set({ connected: true, connectedDeviceKey: hidDeviceKey(device) });
110
+ attached = true;
111
+ });
112
+ lifecycleQueue = pending.catch(() => undefined);
113
+ await pending;
114
+ if (!attached || !save) return;
115
+ // Upsert on the canonical key: re-connecting an already-registered scanner refreshes it instead of adding a
116
+ // second row. An absent product name stays empty rather than an invented English label.
117
+ await profiles.save({
118
+ deviceKey: hidDeviceKey(device), name: '', connectionType: 'hid-pos', deviceName: device.productName || '',
119
+ vendorId: device.vendorId, productId: device.productId, createdAt: new Date(now()).toISOString(),
120
+ });
121
+ };
122
+
123
+ const connect = async () => {
124
+ if (!hid || disposed) return;
125
+ try {
126
+ const devices = await hid.requestDevice({ filters: [{ usagePage: HID_POS_USAGE_PAGE }] });
127
+ if (devices[0]) await attachDevice(devices[0], true);
128
+ } catch (error) {
129
+ // Closing the browser's device chooser is a cancel, not a fault.
130
+ onError?.(error, { phase: 'connect', cancelled: isChooserCancel(error) });
131
+ }
132
+ };
133
+
134
+ // Silently re-open an already-granted HID device matching a saved hid-pos profile (the browser remembers granted
135
+ // devices across reloads). An HID key always carries vendor and product, so the first match is taken.
136
+ const reopenSaved = async () => {
137
+ if (!hid || disposed) return;
138
+ try {
139
+ const [devices, saved] = await Promise.all([hid.getDevices(), profiles.read(['hid-pos'])]);
140
+ if (disposed) return;
141
+ const savedKeys = new Set(saved.map((profile) => profile.deviceKey));
142
+ const match = devices.find((device) => savedKeys.has(hidDeviceKey(device)));
143
+ if (match) await attachDevice(match, false);
144
+ } catch (error) {
145
+ // A silent best-effort reopen (another tab may hold the device).
146
+ onError?.(error, { phase: 'reopen', cancelled: false });
147
+ }
148
+ };
149
+
150
+ const queueTeardown = async () => {
151
+ attachRequest += 1;
152
+ const pending = lifecycleQueue.then(teardown);
153
+ lifecycleQueue = pending.catch(() => undefined);
154
+ await pending;
155
+ state.set(DISCONNECTED);
156
+ };
157
+
158
+ return {
159
+ available: !!hid, connect, reopenSaved,
160
+ disconnect: () => (disposed ? Promise.resolve() : queueTeardown()),
161
+ dispose: () => {
162
+ if (!disposing) {
163
+ // Release the device and its listener on host teardown (logout, unmount).
164
+ disposed = true;
165
+ disposing = queueTeardown();
166
+ }
167
+ return disposing;
168
+ },
169
+ getState: state.get, subscribe: state.subscribe,
170
+ };
171
+ }
@@ -4,3 +4,30 @@ export { DEFAULT_COOLDOWN_MS, normalizeRetailCode, hasValidRetailCheckDigit, ret
4
4
  export type { ScanRejectReason, ScanOfferResult, ScanSessionOptions, ScanSession } from './scan-session';
5
5
  export { useBarcodeScanner } from './use-barcode-scanner';
6
6
  export type { UseBarcodeScannerOptions } from './use-barcode-scanner';
7
+ export { SCANNER_DEVICE_KEY_MAX_LENGTH, normalizeUuid, isCanonicalUuid, scannerDeviceKey, scannerTransport } from './device-identity';
8
+ export type { ScannerConnectionType, ScannerIdentity, ScannerTransport } from './device-identity';
9
+ export { createSerialLineDecoder } from './serial-line-decoder';
10
+ export type { SerialLineDecoderOptions, SerialLineDecoder } from './serial-line-decoder';
11
+ export { decodeHidPosReport } from './hid-pos-decoder';
12
+ export type { HidPosDecodeOptions, HidPosResult } from './hid-pos-decoder';
13
+ export { isWebSerialSupported, isWebHidSupported } from './capabilities';
14
+ export { isChooserCancel } from './chooser-cancel';
15
+ export { SCANNER_PROFILES_COLLECTION, scannerProfileSchema, scannerProfileCollection, addScannerProfileCollection, scannerProfiles$, readScannerProfiles, saveScannerProfile, removeScannerProfile } from './scanner-profiles';
16
+ export type { ScannerProfile, ScannerProfileCollection } from './scanner-profiles';
17
+ export type { WedgeScanMeta } from './wedge-detector';
18
+ export { createScanHub, createScanBus, inertScanHub } from './scan-events';
19
+ export type { ScanSourceKind, ScanSource, ScanEvent, ScanBus, ScanHub } from './scan-events';
20
+ export { dedupeScans, SCAN_DEDUP_WINDOW_MS } from './scan-dedup';
21
+ export { scanTimeOf } from './scan-dedup';
22
+ export { scannerProfileStore, createDeviceScannerStateCell } from './device-scanner';
23
+ export type { ScannerProfileStore, DeviceScannerSettings, DeviceScannerState, DeviceScannerErrorPhase, DeviceScannerErrorHandler, DeviceScannerStateCell, DeviceScanner } from './device-scanner';
24
+ export { createSerialScanner, serialPortIdentity, DEFAULT_SERIAL_BAUD_RATE, STANDARD_SPP_SERVICE_CLASS_ID } from './serial-scanner';
25
+ export type { SerialPortInfoLike, SerialPortLike, SerialLike, SerialScannerOptions } from './serial-scanner';
26
+ export { createHidScanner, HID_POS_USAGE_PAGE } from './hid-scanner';
27
+ export type { HidInputReportEventLike, HidDeviceLike, HidLike, HidScannerOptions } from './hid-scanner';
28
+ export { ScanHubProvider, useScanHub, useDeviceScanControls, inertDeviceScanControls } from './scan-hub-context';
29
+ export type { DeviceScanControl, DeviceScanControls, ScanHubProviderProps } from './scan-hub-context';
30
+ export { CAMERA_BARCODE_TYPES, DETECTOR_FORMATS, detectorFormatToSymbology, nativeBarcodeDetector, DEFAULT_DECODE_INTERVAL_MS, DECODER_ERROR_THRESHOLD, startDecodeLoop, cameraErrorStatus, CAMERA_CONSTRAINTS } from './camera-scan';
31
+ export type { DetectedBarcode, CameraDecoder, ViewfinderStatus, DecodeLoopOptions } from './camera-scan';
32
+ export { useCameraScan } from './use-camera-scan';
33
+ export type { UseCameraScanOptions, CameraScan } from './use-camera-scan';
@@ -0,0 +1,48 @@
1
+ // Ported from WCPOS v2 packages/scanner/src/scan-dedup.ts (monorepo 85ecbd43f).
2
+ import { defer, type MonoTypeOperatorFunction, type Observable } from 'rxjs';
3
+ import { filter } from 'rxjs/operators';
4
+
5
+ import type { ScanEvent, ScanSourceKind } from './scan-events';
6
+
7
+ /** One physical scan can reach the POS through two sources: the keyboard wedge
8
+ * AND a direct HID-POS or serial connection to the same dongle. The 500 ms
9
+ * window is measured from the physical scan, independent of code length or
10
+ * scanner speed. Only a repeat from a DIFFERENT source is dropped: the same
11
+ * source repeating a code is a real second scan (two identical items), and each
12
+ * source's own handling decides those. */
13
+ export const SCAN_DEDUP_WINDOW_MS = 500;
14
+
15
+ // A scanner sending UPC-A as EAN-13 reports `0` plus 12 digits through the wedge, while
16
+ // scan-session's normalizeRetailCode reports the bare 12 — the same printed code.
17
+ const dedupKey = (code: string) => (/^0\d{12}$/.test(code) ? code.slice(1) : code);
18
+
19
+ export function dedupeScans(
20
+ windowMs = SCAN_DEDUP_WINDOW_MS,
21
+ scanTime: (event: ScanEvent) => number = () => Date.now(),
22
+ ): MonoTypeOperatorFunction<ScanEvent> {
23
+ return (source$: Observable<ScanEvent>) =>
24
+ defer(() => {
25
+ const lastPassed = new Map<string, { t: number; kind: ScanSourceKind }>();
26
+ return source$.pipe(
27
+ filter((event) => {
28
+ const t = scanTime(event);
29
+ for (const [code, passed] of lastPassed) {
30
+ if (Math.abs(t - passed.t) >= windowMs) lastPassed.delete(code);
31
+ }
32
+ const key = dedupKey(event.code);
33
+ const prev = lastPassed.get(key);
34
+ const crossSource = prev !== undefined && prev.kind !== event.source.kind;
35
+ if (crossSource && Math.abs(t - prev.t) < windowMs) return false;
36
+ lastPassed.set(key, { t, kind: event.source.kind });
37
+ return true;
38
+ }),
39
+ );
40
+ });
41
+ }
42
+
43
+ /** A wedge copy is timed from its burst's first key (the physical scan); every other source is
44
+ * timed at receipt, because sources stamp on different clocks. Pass it to dedupeScans.
45
+ * Ported from WCPOS v2 use-barcode-detection.ts (monorepo 85ecbd43f, #2263). */
46
+ export function scanTimeOf(event: ScanEvent): number {
47
+ return event.source.kind === 'wedge' ? event.timestamp : Date.now();
48
+ }