tapirscan 1.0.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 (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +241 -0
  3. package/THIRD_PARTY_NOTICES.md +656 -0
  4. package/dist/detail-20260914/continuity.d.mts +2 -0
  5. package/dist/detail-20260914/continuity.mjs +62 -0
  6. package/dist/detail-20260914/detail-proposals-rich.d.mts +13 -0
  7. package/dist/detail-20260914/detail-proposals-rich.mjs +53 -0
  8. package/dist/detail-20260914/direct-recovery.d.mts +28 -0
  9. package/dist/detail-20260914/direct-recovery.mjs +139 -0
  10. package/dist/detail-20260914/host.d.mts +40 -0
  11. package/dist/detail-20260914/host.mjs +280 -0
  12. package/dist/detail-20260914/scanner.d.mts +12 -0
  13. package/dist/detail-20260914/scanner.mjs +64 -0
  14. package/dist/detail-20260914/source-evidence.d.mts +10 -0
  15. package/dist/detail-20260914/source-evidence.mjs +94 -0
  16. package/dist/detail-canvas.d.ts +35 -0
  17. package/dist/detail-canvas.js +73 -0
  18. package/dist/detail.d.ts +19 -0
  19. package/dist/detail.js +87 -0
  20. package/dist/host.d.ts +112 -0
  21. package/dist/host.js +184 -0
  22. package/dist/host64.d.ts +112 -0
  23. package/dist/host64.js +184 -0
  24. package/dist/index.d.ts +92 -0
  25. package/dist/index.js +199 -0
  26. package/dist/multiformat/formats.d.ts +26 -0
  27. package/dist/multiformat/formats.js +59 -0
  28. package/dist/multiformat/geometry.d.ts +32 -0
  29. package/dist/multiformat/geometry.js +122 -0
  30. package/dist/multiformat/pixels.d.ts +3 -0
  31. package/dist/multiformat/pixels.js +36 -0
  32. package/dist/multiformat/scanner.d.ts +51 -0
  33. package/dist/multiformat/scanner.js +258 -0
  34. package/dist/multiformat-host.d.ts +121 -0
  35. package/dist/multiformat-host.js +207 -0
  36. package/dist/policy.d.ts +12 -0
  37. package/dist/policy.js +12 -0
  38. package/package.json +52 -0
  39. package/wasm/high-release-20260915.wasm +0 -0
  40. package/wasm/low-release-20260915.wasm +0 -0
  41. package/wasm/medium-release-20260915.wasm +0 -0
  42. package/wasm/multiformat.json +6 -0
  43. package/wasm/multiformat.wasm +0 -0
  44. package/wasm/very-high-release-20260915.wasm +0 -0
package/dist/host.js ADDED
@@ -0,0 +1,184 @@
1
+ /** Explicit indices reject sparse arrays; nonfinite numeric geometry reaches Rust. */
2
+ export function isQuadShape(value) {
3
+ if (!Array.isArray(value) || value.length !== 4)
4
+ return false;
5
+ for (let i = 0; i < 4; i++) {
6
+ if (!Object.hasOwn(value, i))
7
+ return false;
8
+ const point = value[i];
9
+ if (!Array.isArray(point) || point.length !== 2)
10
+ return false;
11
+ for (let j = 0; j < 2; j++)
12
+ if (!Object.hasOwn(point, j) || typeof point[j] !== 'number')
13
+ return false;
14
+ }
15
+ return true;
16
+ }
17
+ export class ScannerError extends Error {
18
+ code;
19
+ constructor(code, message) { super(message); this.name = 'ScannerError'; this.code = code; }
20
+ }
21
+ function integer(value, min, max, name) {
22
+ if (!Number.isSafeInteger(value) || value < min || value > max)
23
+ throw new ScannerError('invalid_input', `Invalid ${name}`);
24
+ return value;
25
+ }
26
+ function status(code) {
27
+ if (code !== 0)
28
+ throw new ScannerError(`core_${code}`, `Independent scanner rejected operation (${code})`);
29
+ }
30
+ function parseFrame(text, count) {
31
+ const v = JSON.parse(text);
32
+ if (!v || typeof v !== 'object')
33
+ throw new ScannerError('invalid_output', 'Expected frame object');
34
+ const f = v;
35
+ if (!Array.isArray(f.candidates) || f.candidates.length !== count || !Array.isArray(f.barcodes) || typeof f.unfinished !== 'boolean' || !f.reconciliation)
36
+ throw new ScannerError('invalid_output', 'Invalid frame shape');
37
+ for (let i = 0; i < f.candidates.length; i++) {
38
+ const c = f.candidates[i];
39
+ if (c.candidate_index !== i || !Array.isArray(c.coverage) || c.coverage.length !== 4 || !Array.isArray(c.observations) || !Array.isArray(c.detections) || typeof c.error !== 'boolean')
40
+ throw new ScannerError('invalid_output', 'Invalid candidate shape');
41
+ }
42
+ for (const b of f.barcodes)
43
+ if (!/^\d{13}$/.test(b.text) || !Array.isArray(b.polygon) || b.polygon.length !== 4 || !Array.isArray(b.candidate_indices) || b.candidate_indices.some(i => !Number.isInteger(i) || i < 0 || i >= count))
44
+ throw new ScannerError('invalid_output', 'Invalid barcode shape');
45
+ return f;
46
+ }
47
+ /** Validate before asynchronous work; returned bytes are owned by the caller. */
48
+ export function snapshotImage(image) {
49
+ if (!image || typeof image !== 'object')
50
+ throw new ScannerError('invalid_input', 'Invalid image');
51
+ const width = integer(image.width, 1, 0xffffffff, 'width'), height = integer(image.height, 1, 0xffffffff, 'height');
52
+ if (![1, 3, 4].includes(image.channels) || !(image.data instanceof Uint8Array))
53
+ throw new ScannerError('invalid_input', 'Invalid image buffer/channels');
54
+ const stride = integer(image.stride, width * image.channels, 0xffffffff, 'stride');
55
+ const required = integer((height - 1) * stride + width * image.channels, 1, 128 * 1024 * 1024, 'image length');
56
+ if (image.data.byteLength < required)
57
+ throw new ScannerError('invalid_input', 'Image buffer is too short');
58
+ return { data: new Uint8Array(image.data.subarray(0, required)), width, height, channels: image.channels, stride };
59
+ }
60
+ export function snapshotPolicy(policy) {
61
+ if (!policy || typeof policy !== 'object')
62
+ throw new ScannerError('invalid_input', 'Invalid policy');
63
+ const copy = { ...policy };
64
+ for (const key of ['transitionCleanup', 'sourceIdentity', 'interiorNormalization', 'guardBias', 'allowSingleRow'])
65
+ if (copy[key] !== undefined && typeof copy[key] !== 'boolean')
66
+ throw new ScannerError('invalid_input', `Invalid ${key}`);
67
+ integer(copy.maxRetryPathsPerCandidate ?? 512, 0, 4096, 'candidate budget');
68
+ integer(copy.maxRetryPathsPerFrame ?? 8192, 0, 65536, 'frame budget');
69
+ integer(copy.maxAssociationChecks ?? 200000, 0, 2000000, 'comparison budget');
70
+ integer(copy.maxAssociationPixels ?? 2000000, 0, 16000000, 'pixel budget');
71
+ integer(copy.maxResults ?? 1024, 1, 4096, 'result budget');
72
+ return copy;
73
+ }
74
+ /** Uncalibrated support ordering; ties preserve spatial output order. */
75
+ export function rankBarcodes(barcodes) {
76
+ return [...barcodes].sort((a, b) => b.support - a.support);
77
+ }
78
+ export class IndependentScanner {
79
+ #exports;
80
+ #handle;
81
+ constructor(exports) {
82
+ this.#exports = exports;
83
+ if (exports.regions_version() !== 1)
84
+ throw new ScannerError('abi_version', 'Unsupported scanner ABI');
85
+ this.#handle = exports.regions_new();
86
+ if (!this.#handle)
87
+ throw new ScannerError('capacity', 'Scanner handle capacity exhausted');
88
+ }
89
+ static async create(bytes) {
90
+ const module = await WebAssembly.compile(bytes);
91
+ const instance = await WebAssembly.instantiate(module, {});
92
+ const exports = instance.exports;
93
+ for (const name of ['regions_localize', 'regions_version', 'regions_new', 'regions_destroy', 'regions_prepare', 'regions_input_ptr', 'regions_input_len', 'regions_quads_ptr', 'regions_output_ptr', 'regions_output_len', 'regions_scan']) {
94
+ if (typeof instance.exports[name] !== 'function')
95
+ throw new ScannerError('abi_shape', `Missing ${name}`);
96
+ }
97
+ if (!(exports.memory instanceof WebAssembly.Memory))
98
+ throw new ScannerError('abi_shape', 'Missing memory');
99
+ return new IndependentScanner(exports);
100
+ }
101
+ /** All supplied regions receive the cheap pass; successful reads do not end scanning. */
102
+ scan(image, quads, policy = {}) {
103
+ return this.#scan(image, quads, policy, false);
104
+ }
105
+ /** Synchronous transaction: upload once, localize, decode the same owned pixels. */
106
+ scanLocalized(image, policy = {}, fitLimit = 8, fullFrame = false) {
107
+ const start = performance.now();
108
+ if (!this.#handle)
109
+ throw new ScannerError('disposed', 'Scanner is disposed');
110
+ if (!image || typeof image !== 'object')
111
+ throw new ScannerError('invalid_input', 'Invalid image');
112
+ const width = integer(image.width, 3, 0xffffffff, 'width'), height = integer(image.height, 3, 0xffffffff, 'height');
113
+ if (![1, 3, 4].includes(image.channels) || !(image.data instanceof Uint8Array))
114
+ throw new ScannerError('invalid_input', 'Invalid image buffer/channels');
115
+ const stride = integer(image.stride, width * image.channels, 0xffffffff, 'stride');
116
+ const required = integer((height - 1) * stride + width * image.channels, 1, 128 * 1024 * 1024, 'image length');
117
+ if (image.data.byteLength < required)
118
+ throw new ScannerError('invalid_input', 'Image buffer is too short');
119
+ integer(fitLimit, 0, 8, 'shear limit');
120
+ const e = this.#exports, id = this.#handle;
121
+ status(e.regions_prepare(id, width, height, image.channels, stride));
122
+ if (e.regions_input_len(id) !== required)
123
+ throw new ScannerError('abi_shape', 'Input allocation mismatch');
124
+ new Uint8Array(e.memory.buffer, e.regions_input_ptr(id), required).set(image.data.subarray(0, required));
125
+ status(e.regions_localize(id, fitLimit));
126
+ const localization = JSON.parse(new TextDecoder().decode(new Uint8Array(e.memory.buffer, e.regions_output_ptr(id), e.regions_output_len(id))));
127
+ if (!Array.isArray(localization.proposals) || localization.proposals.length > 32 || localization.proposals.some((p) => !isQuadShape(p.polygon)))
128
+ throw new ScannerError('abi_shape', 'Invalid localization');
129
+ const searchWindows = fullFrame ? [{ kind: 'full_frame_search', polygon: [[0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]], candidateIndex: localization.proposals.length }] : [];
130
+ const localizationMs = performance.now() - start, decodeStart = performance.now();
131
+ const scan = this.#scan(image, [...localization.proposals.map((p) => p.polygon), ...searchWindows.map(p => p.polygon)], policy, true);
132
+ return { localization, searchWindows, scan, localizationMs, decodingMs: performance.now() - decodeStart, scanMs: performance.now() - start };
133
+ }
134
+ #scan(image, quads, policy, prepared) {
135
+ const start = performance.now();
136
+ if (!this.#handle)
137
+ throw new ScannerError('disposed', 'Scanner is disposed');
138
+ if (!image || typeof image !== 'object' || !Array.isArray(quads) || !policy || typeof policy !== 'object')
139
+ throw new ScannerError('invalid_input', 'Invalid scan arguments');
140
+ for (const key of ['transitionCleanup', 'sourceIdentity', 'interiorNormalization', 'guardBias', 'allowSingleRow'])
141
+ if (policy[key] !== undefined && typeof policy[key] !== 'boolean')
142
+ throw new ScannerError('invalid_input', `Invalid ${key}`);
143
+ const e = this.#exports, id = this.#handle;
144
+ const width = integer(image.width, 1, 0xffffffff, 'width'), height = integer(image.height, 1, 0xffffffff, 'height');
145
+ if (![1, 3, 4].includes(image.channels) || !(image.data instanceof Uint8Array))
146
+ throw new ScannerError('invalid_input', 'Invalid image buffer/channels');
147
+ const stride = integer(image.stride, width * image.channels, 0xffffffff, 'stride');
148
+ const required = integer((height - 1) * stride + width * image.channels, 1, 128 * 1024 * 1024, 'image length');
149
+ if (image.data.byteLength < required)
150
+ throw new ScannerError('invalid_input', 'Image buffer is too short');
151
+ integer(quads.length, 0, 64, 'candidate count');
152
+ for (const q of quads)
153
+ if (!isQuadShape(q))
154
+ throw new ScannerError('invalid_input', 'Invalid quad shape');
155
+ const perCandidate = integer(policy.maxRetryPathsPerCandidate ?? 512, 0, 4096, 'candidate budget');
156
+ const perFrame = integer(policy.maxRetryPathsPerFrame ?? 8192, 0, 65536, 'frame budget');
157
+ const checks = integer(policy.maxAssociationChecks ?? 200000, 0, 2000000, 'comparison budget');
158
+ const pixels = integer(policy.maxAssociationPixels ?? 2000000, 0, 16000000, 'pixel budget');
159
+ const results = integer(policy.maxResults ?? 1024, 1, 4096, 'result budget');
160
+ const flags = (policy.transitionCleanup ? 1 : 0) | (policy.sourceIdentity ? 2 : 0) | (policy.interiorNormalization ? 4 : 0) | (policy.guardBias ? 8 : 0) | (policy.allowSingleRow ? 16 : 0);
161
+ if (!prepared) {
162
+ status(e.regions_prepare(id, width, height, image.channels, stride));
163
+ if (e.regions_input_len(id) !== required)
164
+ throw new ScannerError('abi_shape', 'Input allocation mismatch');
165
+ new Uint8Array(e.memory.buffer, e.regions_input_ptr(id), required).set(image.data.subarray(0, required));
166
+ }
167
+ const coordinates = new Float64Array(e.memory.buffer, e.regions_quads_ptr(id), 512);
168
+ quads.forEach((q, i) => q.forEach((p, j) => { coordinates[i * 8 + j * 2] = p[0]; coordinates[i * 8 + j * 2 + 1] = p[1]; }));
169
+ status(e.regions_scan(id, quads.length, flags, perCandidate, perFrame, checks, pixels, results));
170
+ // Scan can grow memory. Never reuse the earlier input/coordinate views.
171
+ const output = new Uint8Array(e.memory.buffer, e.regions_output_ptr(id), e.regions_output_len(id)).slice();
172
+ const frame = parseFrame(new TextDecoder().decode(output), quads.length);
173
+ return { ...frame, candidateTimingsAvailable: false, elapsedMs: performance.now() - start };
174
+ }
175
+ /** Separate convenience; it never changes find-all work or suppresses frame evidence. */
176
+ best(result) {
177
+ return rankBarcodes(result.barcodes)[0];
178
+ }
179
+ dispose() { if (this.#handle) {
180
+ const id = this.#handle;
181
+ this.#handle = 0;
182
+ status(this.#exports.regions_destroy(id));
183
+ } }
184
+ }
@@ -0,0 +1,112 @@
1
+ /** Independent EAN-13 supplied-region scanner. Experimental; no localizer or
2
+ * reference decoder is imported. All result confidence remains uncalibrated. */
3
+ export type Point = readonly [number, number];
4
+ export type Quad = readonly [Point, Point, Point, Point];
5
+ export interface Image {
6
+ data: Uint8Array;
7
+ width: number;
8
+ height: number;
9
+ channels: 1 | 3 | 4;
10
+ stride: number;
11
+ }
12
+ export interface Policy {
13
+ transitionCleanup?: boolean;
14
+ sourceIdentity?: boolean;
15
+ interiorNormalization?: boolean;
16
+ guardBias?: boolean;
17
+ /** Experimental: accept one full-quiet scanline; increases false-read risk. Default false. */
18
+ allowSingleRow?: boolean;
19
+ maxRetryPathsPerCandidate?: number;
20
+ maxRetryPathsPerFrame?: number;
21
+ maxAssociationChecks?: number;
22
+ maxAssociationPixels?: number;
23
+ maxResults?: number;
24
+ }
25
+ export interface Detection {
26
+ text: string;
27
+ polygon: Quad;
28
+ support: number;
29
+ axis: number;
30
+ }
31
+ export interface Barcode extends Detection {
32
+ candidate_indices: number[];
33
+ }
34
+ export interface Observation {
35
+ text: string;
36
+ axis: number;
37
+ fraction: number;
38
+ left: number;
39
+ right: number;
40
+ cost: number;
41
+ gap: number;
42
+ }
43
+ export interface Candidate {
44
+ candidate_index: number;
45
+ coverage: readonly (readonly [number | null, number | null])[];
46
+ error: boolean;
47
+ error_detail: 'invalid_geometry' | 'sampling_error' | null;
48
+ unfinished: boolean;
49
+ ms: number;
50
+ work: Record<string, number>;
51
+ detections: Detection[];
52
+ observations: Observation[];
53
+ }
54
+ export interface ScanFrame {
55
+ unfinished: boolean;
56
+ candidates: Candidate[];
57
+ barcodes: Barcode[];
58
+ reconciliation: {
59
+ comparisons: number;
60
+ merged: number;
61
+ ambiguous: number;
62
+ conflicting: number;
63
+ pending_observations: number;
64
+ truncated: boolean;
65
+ source_pairs: number;
66
+ source_matches: number;
67
+ source_pixels: number;
68
+ source_capped: number;
69
+ pending_coverage_checks: number;
70
+ pending_quarantined: number;
71
+ };
72
+ }
73
+ export interface ScanResult extends ScanFrame {
74
+ /** This WASM build has no internal clock. Candidate ms values are unavailable zeros. */
75
+ candidateTimingsAvailable: false;
76
+ /** Actual host wall time, including validation, preparation/copies, decode and JSON parsing. */
77
+ elapsedMs: number;
78
+ }
79
+ /** Explicit indices reject sparse arrays; nonfinite numeric geometry reaches Rust. */
80
+ export declare function isQuadShape(value: unknown): value is Quad;
81
+ export declare class ScannerError extends Error {
82
+ readonly code: string;
83
+ constructor(code: string, message: string);
84
+ }
85
+ /** Validate before asynchronous work; returned bytes are owned by the caller. */
86
+ export declare function snapshotImage(image: Image): Image;
87
+ export declare function snapshotPolicy(policy: Policy): Policy;
88
+ /** Uncalibrated support ordering; ties preserve spatial output order. */
89
+ export declare function rankBarcodes(barcodes: readonly Barcode[]): Barcode[];
90
+ export declare class IndependentScanner {
91
+ #private;
92
+ private constructor();
93
+ static create(bytes: BufferSource): Promise<IndependentScanner>;
94
+ /** All supplied regions receive the cheap pass; successful reads do not end scanning. */
95
+ scan(image: Image, quads: readonly Quad[], policy?: Policy): ScanResult;
96
+ /** Synchronous transaction: upload once, localize, decode the same owned pixels. */
97
+ scanLocalized(image: Image, policy?: Policy, fitLimit?: number, fullFrame?: boolean): {
98
+ localization: any;
99
+ searchWindows: {
100
+ kind: string;
101
+ polygon: number[][];
102
+ candidateIndex: any;
103
+ }[];
104
+ scan: ScanResult;
105
+ localizationMs: number;
106
+ decodingMs: number;
107
+ scanMs: number;
108
+ };
109
+ /** Separate convenience; it never changes find-all work or suppresses frame evidence. */
110
+ best(result: ScanFrame): Barcode | undefined;
111
+ dispose(): void;
112
+ }
package/dist/host64.js ADDED
@@ -0,0 +1,184 @@
1
+ /** Explicit indices reject sparse arrays; nonfinite numeric geometry reaches Rust. */
2
+ export function isQuadShape(value) {
3
+ if (!Array.isArray(value) || value.length !== 4)
4
+ return false;
5
+ for (let i = 0; i < 4; i++) {
6
+ if (!Object.hasOwn(value, i))
7
+ return false;
8
+ const point = value[i];
9
+ if (!Array.isArray(point) || point.length !== 2)
10
+ return false;
11
+ for (let j = 0; j < 2; j++)
12
+ if (!Object.hasOwn(point, j) || typeof point[j] !== 'number')
13
+ return false;
14
+ }
15
+ return true;
16
+ }
17
+ export class ScannerError extends Error {
18
+ code;
19
+ constructor(code, message) { super(message); this.name = 'ScannerError'; this.code = code; }
20
+ }
21
+ function integer(value, min, max, name) {
22
+ if (!Number.isSafeInteger(value) || value < min || value > max)
23
+ throw new ScannerError('invalid_input', `Invalid ${name}`);
24
+ return value;
25
+ }
26
+ function status(code) {
27
+ if (code !== 0)
28
+ throw new ScannerError(`core_${code}`, `Independent scanner rejected operation (${code})`);
29
+ }
30
+ function parseFrame(text, count) {
31
+ const v = JSON.parse(text);
32
+ if (!v || typeof v !== 'object')
33
+ throw new ScannerError('invalid_output', 'Expected frame object');
34
+ const f = v;
35
+ if (!Array.isArray(f.candidates) || f.candidates.length !== count || !Array.isArray(f.barcodes) || typeof f.unfinished !== 'boolean' || !f.reconciliation)
36
+ throw new ScannerError('invalid_output', 'Invalid frame shape');
37
+ for (let i = 0; i < f.candidates.length; i++) {
38
+ const c = f.candidates[i];
39
+ if (c.candidate_index !== i || !Array.isArray(c.coverage) || c.coverage.length !== 4 || !Array.isArray(c.observations) || !Array.isArray(c.detections) || typeof c.error !== 'boolean')
40
+ throw new ScannerError('invalid_output', 'Invalid candidate shape');
41
+ }
42
+ for (const b of f.barcodes)
43
+ if (!/^\d{13}$/.test(b.text) || !Array.isArray(b.polygon) || b.polygon.length !== 4 || !Array.isArray(b.candidate_indices) || b.candidate_indices.some(i => !Number.isInteger(i) || i < 0 || i >= count))
44
+ throw new ScannerError('invalid_output', 'Invalid barcode shape');
45
+ return f;
46
+ }
47
+ /** Validate before asynchronous work; returned bytes are owned by the caller. */
48
+ export function snapshotImage(image) {
49
+ if (!image || typeof image !== 'object')
50
+ throw new ScannerError('invalid_input', 'Invalid image');
51
+ const width = integer(image.width, 1, 0xffffffff, 'width'), height = integer(image.height, 1, 0xffffffff, 'height');
52
+ if (![1, 3, 4].includes(image.channels) || !(image.data instanceof Uint8Array))
53
+ throw new ScannerError('invalid_input', 'Invalid image buffer/channels');
54
+ const stride = integer(image.stride, width * image.channels, 0xffffffff, 'stride');
55
+ const required = integer((height - 1) * stride + width * image.channels, 1, 128 * 1024 * 1024, 'image length');
56
+ if (image.data.byteLength < required)
57
+ throw new ScannerError('invalid_input', 'Image buffer is too short');
58
+ return { data: new Uint8Array(image.data.subarray(0, required)), width, height, channels: image.channels, stride };
59
+ }
60
+ export function snapshotPolicy(policy) {
61
+ if (!policy || typeof policy !== 'object')
62
+ throw new ScannerError('invalid_input', 'Invalid policy');
63
+ const copy = { ...policy };
64
+ for (const key of ['transitionCleanup', 'sourceIdentity', 'interiorNormalization', 'guardBias', 'allowSingleRow'])
65
+ if (copy[key] !== undefined && typeof copy[key] !== 'boolean')
66
+ throw new ScannerError('invalid_input', `Invalid ${key}`);
67
+ integer(copy.maxRetryPathsPerCandidate ?? 512, 0, 4096, 'candidate budget');
68
+ integer(copy.maxRetryPathsPerFrame ?? 8192, 0, 65536, 'frame budget');
69
+ integer(copy.maxAssociationChecks ?? 200000, 0, 2000000, 'comparison budget');
70
+ integer(copy.maxAssociationPixels ?? 2000000, 0, 16000000, 'pixel budget');
71
+ integer(copy.maxResults ?? 1024, 1, 4096, 'result budget');
72
+ return copy;
73
+ }
74
+ /** Uncalibrated support ordering; ties preserve spatial output order. */
75
+ export function rankBarcodes(barcodes) {
76
+ return [...barcodes].sort((a, b) => b.support - a.support);
77
+ }
78
+ export class IndependentScanner {
79
+ #exports;
80
+ #handle;
81
+ constructor(exports) {
82
+ this.#exports = exports;
83
+ if (exports.regions_version() !== 1)
84
+ throw new ScannerError('abi_version', 'Unsupported scanner ABI');
85
+ this.#handle = exports.regions_new();
86
+ if (!this.#handle)
87
+ throw new ScannerError('capacity', 'Scanner handle capacity exhausted');
88
+ }
89
+ static async create(bytes) {
90
+ const module = await WebAssembly.compile(bytes);
91
+ const instance = await WebAssembly.instantiate(module, {});
92
+ const exports = instance.exports;
93
+ for (const name of ['regions_localize', 'regions_version', 'regions_new', 'regions_destroy', 'regions_prepare', 'regions_input_ptr', 'regions_input_len', 'regions_quads_ptr', 'regions_output_ptr', 'regions_output_len', 'regions_scan']) {
94
+ if (typeof instance.exports[name] !== 'function')
95
+ throw new ScannerError('abi_shape', `Missing ${name}`);
96
+ }
97
+ if (!(exports.memory instanceof WebAssembly.Memory))
98
+ throw new ScannerError('abi_shape', 'Missing memory');
99
+ return new IndependentScanner(exports);
100
+ }
101
+ /** All supplied regions receive the cheap pass; successful reads do not end scanning. */
102
+ scan(image, quads, policy = {}) {
103
+ return this.#scan(image, quads, policy, false);
104
+ }
105
+ /** Synchronous transaction: upload once, localize, decode the same owned pixels. */
106
+ scanLocalized(image, policy = {}, fitLimit = 8, fullFrame = false) {
107
+ const start = performance.now();
108
+ if (!this.#handle)
109
+ throw new ScannerError('disposed', 'Scanner is disposed');
110
+ if (!image || typeof image !== 'object')
111
+ throw new ScannerError('invalid_input', 'Invalid image');
112
+ const width = integer(image.width, 3, 0xffffffff, 'width'), height = integer(image.height, 3, 0xffffffff, 'height');
113
+ if (![1, 3, 4].includes(image.channels) || !(image.data instanceof Uint8Array))
114
+ throw new ScannerError('invalid_input', 'Invalid image buffer/channels');
115
+ const stride = integer(image.stride, width * image.channels, 0xffffffff, 'stride');
116
+ const required = integer((height - 1) * stride + width * image.channels, 1, 128 * 1024 * 1024, 'image length');
117
+ if (image.data.byteLength < required)
118
+ throw new ScannerError('invalid_input', 'Image buffer is too short');
119
+ integer(fitLimit, 0, 8, 'shear limit');
120
+ const e = this.#exports, id = this.#handle;
121
+ status(e.regions_prepare(id, width, height, image.channels, stride));
122
+ if (e.regions_input_len(id) !== required)
123
+ throw new ScannerError('abi_shape', 'Input allocation mismatch');
124
+ new Uint8Array(e.memory.buffer, e.regions_input_ptr(id), required).set(image.data.subarray(0, required));
125
+ status(e.regions_localize(id, fitLimit));
126
+ const localization = JSON.parse(new TextDecoder().decode(new Uint8Array(e.memory.buffer, e.regions_output_ptr(id), e.regions_output_len(id))));
127
+ if (!Array.isArray(localization.proposals) || localization.proposals.length > (fullFrame ? 63 : 64) || localization.proposals.some((p) => !isQuadShape(p.polygon)))
128
+ throw new ScannerError('abi_shape', 'Invalid localization');
129
+ const searchWindows = fullFrame ? [{ kind: 'full_frame_search', polygon: [[0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]], candidateIndex: localization.proposals.length }] : [];
130
+ const localizationMs = performance.now() - start, decodeStart = performance.now();
131
+ const scan = this.#scan(image, [...localization.proposals.map((p) => p.polygon), ...searchWindows.map(p => p.polygon)], policy, true);
132
+ return { localization, searchWindows, scan, localizationMs, decodingMs: performance.now() - decodeStart, scanMs: performance.now() - start };
133
+ }
134
+ #scan(image, quads, policy, prepared) {
135
+ const start = performance.now();
136
+ if (!this.#handle)
137
+ throw new ScannerError('disposed', 'Scanner is disposed');
138
+ if (!image || typeof image !== 'object' || !Array.isArray(quads) || !policy || typeof policy !== 'object')
139
+ throw new ScannerError('invalid_input', 'Invalid scan arguments');
140
+ for (const key of ['transitionCleanup', 'sourceIdentity', 'interiorNormalization', 'guardBias', 'allowSingleRow'])
141
+ if (policy[key] !== undefined && typeof policy[key] !== 'boolean')
142
+ throw new ScannerError('invalid_input', `Invalid ${key}`);
143
+ const e = this.#exports, id = this.#handle;
144
+ const width = integer(image.width, 1, 0xffffffff, 'width'), height = integer(image.height, 1, 0xffffffff, 'height');
145
+ if (![1, 3, 4].includes(image.channels) || !(image.data instanceof Uint8Array))
146
+ throw new ScannerError('invalid_input', 'Invalid image buffer/channels');
147
+ const stride = integer(image.stride, width * image.channels, 0xffffffff, 'stride');
148
+ const required = integer((height - 1) * stride + width * image.channels, 1, 128 * 1024 * 1024, 'image length');
149
+ if (image.data.byteLength < required)
150
+ throw new ScannerError('invalid_input', 'Image buffer is too short');
151
+ integer(quads.length, 0, 64, 'candidate count');
152
+ for (const q of quads)
153
+ if (!isQuadShape(q))
154
+ throw new ScannerError('invalid_input', 'Invalid quad shape');
155
+ const perCandidate = integer(policy.maxRetryPathsPerCandidate ?? 512, 0, 4096, 'candidate budget');
156
+ const perFrame = integer(policy.maxRetryPathsPerFrame ?? 8192, 0, 65536, 'frame budget');
157
+ const checks = integer(policy.maxAssociationChecks ?? 200000, 0, 2000000, 'comparison budget');
158
+ const pixels = integer(policy.maxAssociationPixels ?? 2000000, 0, 16000000, 'pixel budget');
159
+ const results = integer(policy.maxResults ?? 1024, 1, 4096, 'result budget');
160
+ const flags = (policy.transitionCleanup ? 1 : 0) | (policy.sourceIdentity ? 2 : 0) | (policy.interiorNormalization ? 4 : 0) | (policy.guardBias ? 8 : 0) | (policy.allowSingleRow ? 16 : 0);
161
+ if (!prepared) {
162
+ status(e.regions_prepare(id, width, height, image.channels, stride));
163
+ if (e.regions_input_len(id) !== required)
164
+ throw new ScannerError('abi_shape', 'Input allocation mismatch');
165
+ new Uint8Array(e.memory.buffer, e.regions_input_ptr(id), required).set(image.data.subarray(0, required));
166
+ }
167
+ const coordinates = new Float64Array(e.memory.buffer, e.regions_quads_ptr(id), 512);
168
+ quads.forEach((q, i) => q.forEach((p, j) => { coordinates[i * 8 + j * 2] = p[0]; coordinates[i * 8 + j * 2 + 1] = p[1]; }));
169
+ status(e.regions_scan(id, quads.length, flags, perCandidate, perFrame, checks, pixels, results));
170
+ // Scan can grow memory. Never reuse the earlier input/coordinate views.
171
+ const output = new Uint8Array(e.memory.buffer, e.regions_output_ptr(id), e.regions_output_len(id)).slice();
172
+ const frame = parseFrame(new TextDecoder().decode(output), quads.length);
173
+ return { ...frame, candidateTimingsAvailable: false, elapsedMs: performance.now() - start };
174
+ }
175
+ /** Separate convenience; it never changes find-all work or suppresses frame evidence. */
176
+ best(result) {
177
+ return rankBarcodes(result.barcodes)[0];
178
+ }
179
+ dispose() { if (this.#handle) {
180
+ const id = this.#handle;
181
+ this.#handle = 0;
182
+ status(this.#exports.regions_destroy(id));
183
+ } }
184
+ }
@@ -0,0 +1,92 @@
1
+ import type { Recovery, DetailRegion } from "./detail-20260914/scanner.mjs";
2
+ import { type Barcode as FormatBarcode } from "./multiformat/scanner.js";
3
+ import { type Format, type FormatSelection } from "./multiformat/formats.js";
4
+ export { formatBits, linearFormats, matrixFormats, retailFormats } from "./multiformat/formats.js";
5
+ export type { Format, FormatSelection } from "./multiformat/formats.js";
6
+ import { type Image, type ScanFrame, type Quad } from "./host.js";
7
+ export type { Image, Quad } from "./host.js";
8
+ export { ScannerError } from "./host.js";
9
+ export type DiagnosticBarcode = FormatBarcode | (ScanFrame["barcodes"][number] & {
10
+ format: "EAN13";
11
+ });
12
+ export type Mode = "low" | "medium" | "high" | "very-high";
13
+ export interface ScanOptions {
14
+ multiple?: boolean;
15
+ debug?: boolean;
16
+ /** Compatibility alias; use debug. Decoded polygons are always returned. */
17
+ includeRegions?: boolean;
18
+ }
19
+ export interface Diagnostics {
20
+ schemaVersion: 2;
21
+ mode: Mode;
22
+ multiple: boolean;
23
+ elapsedMs: number;
24
+ localizationLimited: boolean;
25
+ scan: {
26
+ barcodes: DiagnosticBarcode[];
27
+ unfinished: boolean;
28
+ regions?: FormatBarcode[];
29
+ } & Partial<Omit<ScanFrame, "barcodes" | "unfinished">>;
30
+ localization?: {
31
+ proposals: {
32
+ polygon: Quad;
33
+ score: number;
34
+ text: string;
35
+ }[];
36
+ omitted: number;
37
+ workLimited: boolean;
38
+ trace?: Record<string, number>;
39
+ };
40
+ recovery?: Recovery;
41
+ detailRegions?: DetailRegion[];
42
+ searchWindows?: {
43
+ kind: string;
44
+ polygon: number[][];
45
+ candidateIndex: number;
46
+ }[];
47
+ }
48
+ export interface Barcode {
49
+ text: string;
50
+ format: Format | "Unknown";
51
+ polygon: Quad;
52
+ rect: {
53
+ left: number;
54
+ top: number;
55
+ width: number;
56
+ height: number;
57
+ };
58
+ }
59
+ export interface ScanResult {
60
+ barcodes: Barcode[];
61
+ values: string[];
62
+ best: Barcode | undefined;
63
+ image: {
64
+ width: number;
65
+ height: number;
66
+ };
67
+ mode: Mode;
68
+ elapsedMs: number;
69
+ unfinished: boolean;
70
+ debug?: Diagnostics;
71
+ }
72
+ export interface ScannerOptions {
73
+ mode?: Mode;
74
+ formats?: FormatSelection;
75
+ loadWasm?: (url: URL) => Promise<ArrayBuffer>;
76
+ }
77
+ export type PixelImage = Image | Pick<ImageData, "data" | "width" | "height">;
78
+ /** Mode selects a compiled implementation. Create another instance to switch. */
79
+ export declare class Scanner {
80
+ private readonly host;
81
+ readonly mode: Mode;
82
+ private readonly additional?;
83
+ private readonly formats;
84
+ private constructor();
85
+ static create(options?: ScannerOptions): Promise<Scanner>;
86
+ scan(inputImage: PixelImage, options?: ScanOptions): ScanResult;
87
+ /** Convenience alias for result.best. */
88
+ best(result: ScanResult): Barcode | undefined;
89
+ dispose(): void;
90
+ }
91
+ /** Scan one image with automatic cleanup. Reuse Scanner for a stream of images. */
92
+ export declare function scan(image: PixelImage, options?: ScannerOptions & ScanOptions): Promise<ScanResult>;