@webreflection/barcode 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Andrea Giammarchi - @webreflection
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,228 @@
1
- # Temporary Holding Version
1
+ # @webreflection/barcode
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <sup>**Social Media Photo by [Risto Kokkonen](https://unsplash.com/@risto_kokkonen) on [Unsplash](https://unsplash.com/)**</sup>
4
+
5
+ WebGPU-accelerated barcode and QR scanning for the web, with encoding
6
+ (rendering) for all 17 supported symbologies. Native JS + a Rust/WASM
7
+ core — clean-room implementations, MIT throughout.
8
+
9
+ **[Live demos →](https://webreflection.github.io/barcode/)** —
10
+ [camera scan](https://webreflection.github.io/barcode/scan.html),
11
+ [your own video / mount](https://webreflection.github.io/barcode/live.html),
12
+ [still image](https://webreflection.github.io/barcode/still.html),
13
+ [render playground](https://webreflection.github.io/barcode/render.html),
14
+ [worker API](https://webreflection.github.io/barcode/worker.html),
15
+ [self-test](https://webreflection.github.io/barcode/test.html) and
16
+ [transports](https://webreflection.github.io/barcode/contract-test.html).
17
+
18
+ ```js
19
+ import barcode from '@webreflection/barcode';
20
+ import '@webreflection/barcode/css'; // optional: the default scan UI
21
+
22
+ const { scan, render } = barcode();
23
+
24
+ // scan: one code per call — resolves with { symbology, text, raw, position, score }
25
+ // or undefined (graceful end: abort, or the latency expired)
26
+ const code = await scan(); // default UI: viewfinder + ✕
27
+ if (code) {
28
+ const svg = await render(code); // SVGSVGElement, styleable
29
+ document.body.append(svg);
30
+ }
31
+ ```
32
+
33
+ ## Three entries, one package
34
+
35
+ | import | context | default export |
36
+ | --- | --- | --- |
37
+ | `@webreflection/barcode` | auto | on a page: `barcode(options)` → `{ scan, render, worker }`; in a worker: the bootstrap promise |
38
+ | `@webreflection/barcode/main` | main thread | `barcode(options)` (always) |
39
+ | `@webreflection/barcode/worker` | worker | bootstrap promise (always) |
40
+
41
+ The auto entry detects the context before importing anything DOM-ish:
42
+ a worker only evaluates `worker.js`, so main-thread code never runs
43
+ there. In a worker the default is a **non-blocking promise**: the
44
+ message listener is installed synchronously; the promise resolves when
45
+ the page hands over its port.
46
+
47
+ It uses top-level await (the branch must be chosen before the default
48
+ export exists). Browsers support that; a bundler targeting below ES2022
49
+ (Vite's default `build.target`) should either raise the target to
50
+ `es2022` or import the explicit `/main` / `/worker` entry, which needs no
51
+ top-level await.
52
+
53
+ ```js
54
+ // a worker that wants the SDK alongside its own protocol
55
+ import bootstrap from '@webreflection/barcode';
56
+ const { decode, encode } = await bootstrap;
57
+
58
+ // a page, explicit entry (precise types; no runtime branching)
59
+ import barcode from '@webreflection/barcode/main';
60
+ ```
61
+
62
+ The worker script is strict-once: it binds the first port-carrying
63
+ message and never again. Port-less messages pass through untouched, so
64
+ an embedder can keep its own protocol on the same worker.
65
+
66
+ ## Symbologies
67
+
68
+ * **2D**: `qrcode`, `microqr`, `aztec`, `datamatrix`, `pdf417`
69
+ * **1D**: `upca`, `ean13`, `ean8`, `upce`, `code39`, `code93`,
70
+ `code128`, `itf`, `codabar`, `databar`, `databarltd`, `databarstk`
71
+
72
+ Session option `type` filters what decodes: `'qr'` (QR + Micro QR),
73
+ `'barcode'` (the 1D set), an exact name, or an array of names.
74
+
75
+ ## The session
76
+
77
+ One `barcode(options)` per page/SPA. It returns `{ scan, render, worker }`
78
+ and boots instantly — the worker spawns, the handshake crosses, and wasm
79
+ warms up before your first scan. The session owns its worker for its
80
+ whole lifetime: **abort never terminates it**. Handing the same worker
81
+ to a second session throws (`duplicated worker`).
82
+
83
+ ```js
84
+ const { scan } = barcode({
85
+ type: 'barcode', // decode filter (session default)
86
+ accuracy: 'high', // 'low' | 'auto' (default) | 'high'
87
+ worker: './my-worker.js', // optional transport — see below
88
+ });
89
+ ```
90
+
91
+ ### scan(options) → Promise&lt;Code | undefined&gt;
92
+
93
+ `Code` is `{ symbology, text, raw, position, score }` — most-centered
94
+ result first, larger symbol as tiebreak. `raw` holds the exact payload
95
+ bytes; `text` is their display form. The promise resolves **once**: a
96
+ real error (camera denied, broken pipeline) rejects; a graceful end
97
+ resolves `undefined` and never throws.
98
+
99
+ Exactly one mode per call:
100
+
101
+ ```js
102
+ await scan(); // { into: document.body } — the default UI
103
+ await scan({ into: '#modal' }); // the default UI mounted there
104
+ await scan({ video, signal }); // your <video>, your AbortController
105
+ await scan({ image }); // still: canvas | ImageBitmap |
106
+ // HTMLImageElement | SVG | Blob/File
107
+ ```
108
+
109
+ Camera knobs: `crop` (`'square'` default — what you frame is what
110
+ decodes; `'full'` opts out), `zoom`, `torch`. `latency` overrides the
111
+ per-mode law (500ms live, 5000ms still). `type`/`accuracy`/`lens` have
112
+ per-scan overrides.
113
+
114
+ ### render(result, opts) → Promise&lt;SVGSVGElement | null&gt;
115
+
116
+ Turns a scan result — or any `{ symbology, text }` / `{ symbology, raw }`
117
+ — into an SVG. It **re-encodes from the payload**, so the artwork is a
118
+ fresh, standards-compliant symbol, not a pixel copy; `scan(render(code))`
119
+ yields the same value.
120
+
121
+ | option | applies to | default | meaning |
122
+ | --- | --- | --- | --- |
123
+ | `module` | all | `4` | pixels per module (the SVG is sized by its viewBox; scale with CSS) |
124
+ | `height` | 1D | `30 × module` | bar height |
125
+ | `ec` | QR | `"M"` | error correction: `"L"`, `"M"`, `"Q"` or `"H"` |
126
+ | `mask` | QR | `2` | mask pattern 0–7 |
127
+ | `version` | QR | smallest that fits | version 1–40; pads the symbol to that size |
128
+ | `level` | PDF417 | encoder default | error correction level 0–8 |
129
+ | `columns` | PDF417 | auto | data columns 1–30 |
130
+ | `rows`, `cols` | Data Matrix | smallest square | ECC200 size in modules **including borders** (e.g. `12` / `36` for a DMRE) |
131
+
132
+ Every option is optional and keeps the historical default; options that
133
+ do not apply to the symbology are ignored. Out-of-range values throw a
134
+ `TypeError` before anything reaches the worker.
135
+
136
+ ```js
137
+ await render(code, { ec: "H", version: 7 }); // larger QR, more redundancy
138
+ await render(code, { rows: 12, cols: 36 }); // rectangular Data Matrix
139
+ ```
140
+
141
+ Style via CSS custom properties — set them on the SVG (it carries class
142
+ `barcode-svg`) or any ancestor:
143
+
144
+ ```css
145
+ .barcode-svg { --barcode-ink: #123; --barcode-paper: #fff; }
146
+ ```
147
+
148
+ ## Transports
149
+
150
+ `worker` accepts a string/URL (spawns a dedicated module Worker), or an
151
+ already-created `Worker` used as-is. Either way `Barcode.worker` is the
152
+ live Worker instance. The handshake is deterministic: the page sends a
153
+ port-less `barcode:ping`, the worker answers `barcode:ready`, then the
154
+ MessagePort crosses. Ports posted before the worker is bound are safe.
155
+
156
+ `@webreflection/barcode/worker` is the script the session loads. It can
157
+ also be imported on top of your own worker (its default export is the
158
+ bootstrap promise).
159
+
160
+ With a bundler, the default `barcode()` just works when it understands
161
+ `new URL("./worker.js", import.meta.url)` / `new URL("./wasm.wasm", ...)`
162
+ (Vite, Rollup, webpack 5 asset modules): the emitted worker and wasm are
163
+ linked automatically. For an unbundled `dist/` (CDN, import map, static
164
+ folder) they sit beside `main.js` and resolve the same way. A bundler that
165
+ does neither can pass an explicit worker URL, optionally with
166
+ `?wasm=<url>` pointing at the wasm asset it copied.
167
+
168
+ ## Published payload
169
+
170
+ The npm package is `README.md`, `LICENSE` and `dist/`:
171
+
172
+ ```
173
+ dist/
174
+ index.js thread-aware default entry
175
+ main.js main-thread SDK (scan/render/camera/dialog)
176
+ worker.js bound worker (binarizer + wasm decode/encode)
177
+ wasm.wasm the binary (resolved next to worker.js)
178
+ css.css optional default-UI stylesheet
179
+ *.d.ts consumer types
180
+ README.md
181
+ LICENSE
182
+ ```
183
+
184
+ Serve the folder from any origin (import map, CDN, unpacked localhost);
185
+ `wasm.wasm` resolves relatively to `worker.js`. The module never touches
186
+ `window`; the auto entry avoids loading main-thread code in a worker.
187
+
188
+ ## Development
189
+
190
+ ```sh
191
+ # from the repo root, one command builds types + wasm + dist/
192
+ npm run build
193
+
194
+ # the deployable demo (static folder, relative URLs, shared wasm)
195
+ npm run build:demo
196
+ npm run serve:demo # http://<lan-ip>:8124
197
+ npm run serve:iphone # https on :8443 (mkcert) + trust notes
198
+
199
+ # the public GitHub Pages site (landing + one demo per API surface)
200
+ npm run build:docs # → docs/
201
+ npm run serve:docs # http://<lan-ip>:8128
202
+ npm run serve:docs:iphone # https on :8443 for a real iPhone
203
+ ```
204
+
205
+ The repo tests run on Playwright in CI (Chromium + WebKit, fake camera)
206
+ and keep the CDP tools for real phones:
207
+
208
+ ```sh
209
+ npm test # chromium + webkit + iphone profile
210
+ npm --prefix packages/web run test:ci # headless chromium + webkit
211
+ npm --prefix packages/web run test:ci:chromium # what CI runs per push
212
+ npm --prefix packages/web run test:ci:webkit # Safari engine (nightly)
213
+ npm --prefix packages/web run test:webkit # Safari engine locally
214
+ npm --prefix packages/web run test:iphone # WebKit + iPhone descriptor only
215
+ npm --prefix packages/web run test:phone # Android over adb (real camera)
216
+ npm --prefix packages/web run test:field # local real-photo corpus
217
+ ```
218
+
219
+ A real iPhone can be tested manually with `serve:iphone`: the camera needs
220
+ a secure origin, so the script generates a LAN HTTPS certificate with
221
+ `mkcert` and prints how to trust its CA once on the device. The
222
+ `iphone` Playwright project (WebKit + iPhone 15 Pro descriptor) is the
223
+ automated engine proxy — it exercises the same UI and fake-camera suite
224
+ without a device.
225
+
226
+ ## License
227
+
228
+ [MIT](./LICENSE)
package/dist/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Andrea Giammarchi - @webreflection
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/README.md ADDED
@@ -0,0 +1,228 @@
1
+ # @webreflection/barcode
2
+
3
+ <sup>**Social Media Photo by [Risto Kokkonen](https://unsplash.com/@risto_kokkonen) on [Unsplash](https://unsplash.com/)**</sup>
4
+
5
+ WebGPU-accelerated barcode and QR scanning for the web, with encoding
6
+ (rendering) for all 17 supported symbologies. Native JS + a Rust/WASM
7
+ core — clean-room implementations, MIT throughout.
8
+
9
+ **[Live demos →](https://webreflection.github.io/barcode/)** —
10
+ [camera scan](https://webreflection.github.io/barcode/scan.html),
11
+ [your own video / mount](https://webreflection.github.io/barcode/live.html),
12
+ [still image](https://webreflection.github.io/barcode/still.html),
13
+ [render playground](https://webreflection.github.io/barcode/render.html),
14
+ [worker API](https://webreflection.github.io/barcode/worker.html),
15
+ [self-test](https://webreflection.github.io/barcode/test.html) and
16
+ [transports](https://webreflection.github.io/barcode/contract-test.html).
17
+
18
+ ```js
19
+ import barcode from '@webreflection/barcode';
20
+ import '@webreflection/barcode/css'; // optional: the default scan UI
21
+
22
+ const { scan, render } = barcode();
23
+
24
+ // scan: one code per call — resolves with { symbology, text, raw, position, score }
25
+ // or undefined (graceful end: abort, or the latency expired)
26
+ const code = await scan(); // default UI: viewfinder + ✕
27
+ if (code) {
28
+ const svg = await render(code); // SVGSVGElement, styleable
29
+ document.body.append(svg);
30
+ }
31
+ ```
32
+
33
+ ## Three entries, one package
34
+
35
+ | import | context | default export |
36
+ | --- | --- | --- |
37
+ | `@webreflection/barcode` | auto | on a page: `barcode(options)` → `{ scan, render, worker }`; in a worker: the bootstrap promise |
38
+ | `@webreflection/barcode/main` | main thread | `barcode(options)` (always) |
39
+ | `@webreflection/barcode/worker` | worker | bootstrap promise (always) |
40
+
41
+ The auto entry detects the context before importing anything DOM-ish:
42
+ a worker only evaluates `worker.js`, so main-thread code never runs
43
+ there. In a worker the default is a **non-blocking promise**: the
44
+ message listener is installed synchronously; the promise resolves when
45
+ the page hands over its port.
46
+
47
+ It uses top-level await (the branch must be chosen before the default
48
+ export exists). Browsers support that; a bundler targeting below ES2022
49
+ (Vite's default `build.target`) should either raise the target to
50
+ `es2022` or import the explicit `/main` / `/worker` entry, which needs no
51
+ top-level await.
52
+
53
+ ```js
54
+ // a worker that wants the SDK alongside its own protocol
55
+ import bootstrap from '@webreflection/barcode';
56
+ const { decode, encode } = await bootstrap;
57
+
58
+ // a page, explicit entry (precise types; no runtime branching)
59
+ import barcode from '@webreflection/barcode/main';
60
+ ```
61
+
62
+ The worker script is strict-once: it binds the first port-carrying
63
+ message and never again. Port-less messages pass through untouched, so
64
+ an embedder can keep its own protocol on the same worker.
65
+
66
+ ## Symbologies
67
+
68
+ * **2D**: `qrcode`, `microqr`, `aztec`, `datamatrix`, `pdf417`
69
+ * **1D**: `upca`, `ean13`, `ean8`, `upce`, `code39`, `code93`,
70
+ `code128`, `itf`, `codabar`, `databar`, `databarltd`, `databarstk`
71
+
72
+ Session option `type` filters what decodes: `'qr'` (QR + Micro QR),
73
+ `'barcode'` (the 1D set), an exact name, or an array of names.
74
+
75
+ ## The session
76
+
77
+ One `barcode(options)` per page/SPA. It returns `{ scan, render, worker }`
78
+ and boots instantly — the worker spawns, the handshake crosses, and wasm
79
+ warms up before your first scan. The session owns its worker for its
80
+ whole lifetime: **abort never terminates it**. Handing the same worker
81
+ to a second session throws (`duplicated worker`).
82
+
83
+ ```js
84
+ const { scan } = barcode({
85
+ type: 'barcode', // decode filter (session default)
86
+ accuracy: 'high', // 'low' | 'auto' (default) | 'high'
87
+ worker: './my-worker.js', // optional transport — see below
88
+ });
89
+ ```
90
+
91
+ ### scan(options) → Promise&lt;Code | undefined&gt;
92
+
93
+ `Code` is `{ symbology, text, raw, position, score }` — most-centered
94
+ result first, larger symbol as tiebreak. `raw` holds the exact payload
95
+ bytes; `text` is their display form. The promise resolves **once**: a
96
+ real error (camera denied, broken pipeline) rejects; a graceful end
97
+ resolves `undefined` and never throws.
98
+
99
+ Exactly one mode per call:
100
+
101
+ ```js
102
+ await scan(); // { into: document.body } — the default UI
103
+ await scan({ into: '#modal' }); // the default UI mounted there
104
+ await scan({ video, signal }); // your <video>, your AbortController
105
+ await scan({ image }); // still: canvas | ImageBitmap |
106
+ // HTMLImageElement | SVG | Blob/File
107
+ ```
108
+
109
+ Camera knobs: `crop` (`'square'` default — what you frame is what
110
+ decodes; `'full'` opts out), `zoom`, `torch`. `latency` overrides the
111
+ per-mode law (500ms live, 5000ms still). `type`/`accuracy`/`lens` have
112
+ per-scan overrides.
113
+
114
+ ### render(result, opts) → Promise&lt;SVGSVGElement | null&gt;
115
+
116
+ Turns a scan result — or any `{ symbology, text }` / `{ symbology, raw }`
117
+ — into an SVG. It **re-encodes from the payload**, so the artwork is a
118
+ fresh, standards-compliant symbol, not a pixel copy; `scan(render(code))`
119
+ yields the same value.
120
+
121
+ | option | applies to | default | meaning |
122
+ | --- | --- | --- | --- |
123
+ | `module` | all | `4` | pixels per module (the SVG is sized by its viewBox; scale with CSS) |
124
+ | `height` | 1D | `30 × module` | bar height |
125
+ | `ec` | QR | `"M"` | error correction: `"L"`, `"M"`, `"Q"` or `"H"` |
126
+ | `mask` | QR | `2` | mask pattern 0–7 |
127
+ | `version` | QR | smallest that fits | version 1–40; pads the symbol to that size |
128
+ | `level` | PDF417 | encoder default | error correction level 0–8 |
129
+ | `columns` | PDF417 | auto | data columns 1–30 |
130
+ | `rows`, `cols` | Data Matrix | smallest square | ECC200 size in modules **including borders** (e.g. `12` / `36` for a DMRE) |
131
+
132
+ Every option is optional and keeps the historical default; options that
133
+ do not apply to the symbology are ignored. Out-of-range values throw a
134
+ `TypeError` before anything reaches the worker.
135
+
136
+ ```js
137
+ await render(code, { ec: "H", version: 7 }); // larger QR, more redundancy
138
+ await render(code, { rows: 12, cols: 36 }); // rectangular Data Matrix
139
+ ```
140
+
141
+ Style via CSS custom properties — set them on the SVG (it carries class
142
+ `barcode-svg`) or any ancestor:
143
+
144
+ ```css
145
+ .barcode-svg { --barcode-ink: #123; --barcode-paper: #fff; }
146
+ ```
147
+
148
+ ## Transports
149
+
150
+ `worker` accepts a string/URL (spawns a dedicated module Worker), or an
151
+ already-created `Worker` used as-is. Either way `Barcode.worker` is the
152
+ live Worker instance. The handshake is deterministic: the page sends a
153
+ port-less `barcode:ping`, the worker answers `barcode:ready`, then the
154
+ MessagePort crosses. Ports posted before the worker is bound are safe.
155
+
156
+ `@webreflection/barcode/worker` is the script the session loads. It can
157
+ also be imported on top of your own worker (its default export is the
158
+ bootstrap promise).
159
+
160
+ With a bundler, the default `barcode()` just works when it understands
161
+ `new URL("./worker.js", import.meta.url)` / `new URL("./wasm.wasm", ...)`
162
+ (Vite, Rollup, webpack 5 asset modules): the emitted worker and wasm are
163
+ linked automatically. For an unbundled `dist/` (CDN, import map, static
164
+ folder) they sit beside `main.js` and resolve the same way. A bundler that
165
+ does neither can pass an explicit worker URL, optionally with
166
+ `?wasm=<url>` pointing at the wasm asset it copied.
167
+
168
+ ## Published payload
169
+
170
+ The npm package is `README.md`, `LICENSE` and `dist/`:
171
+
172
+ ```
173
+ dist/
174
+ index.js thread-aware default entry
175
+ main.js main-thread SDK (scan/render/camera/dialog)
176
+ worker.js bound worker (binarizer + wasm decode/encode)
177
+ wasm.wasm the binary (resolved next to worker.js)
178
+ css.css optional default-UI stylesheet
179
+ *.d.ts consumer types
180
+ README.md
181
+ LICENSE
182
+ ```
183
+
184
+ Serve the folder from any origin (import map, CDN, unpacked localhost);
185
+ `wasm.wasm` resolves relatively to `worker.js`. The module never touches
186
+ `window`; the auto entry avoids loading main-thread code in a worker.
187
+
188
+ ## Development
189
+
190
+ ```sh
191
+ # from the repo root, one command builds types + wasm + dist/
192
+ npm run build
193
+
194
+ # the deployable demo (static folder, relative URLs, shared wasm)
195
+ npm run build:demo
196
+ npm run serve:demo # http://<lan-ip>:8124
197
+ npm run serve:iphone # https on :8443 (mkcert) + trust notes
198
+
199
+ # the public GitHub Pages site (landing + one demo per API surface)
200
+ npm run build:docs # → docs/
201
+ npm run serve:docs # http://<lan-ip>:8128
202
+ npm run serve:docs:iphone # https on :8443 for a real iPhone
203
+ ```
204
+
205
+ The repo tests run on Playwright in CI (Chromium + WebKit, fake camera)
206
+ and keep the CDP tools for real phones:
207
+
208
+ ```sh
209
+ npm test # chromium + webkit + iphone profile
210
+ npm --prefix packages/web run test:ci # headless chromium + webkit
211
+ npm --prefix packages/web run test:ci:chromium # what CI runs per push
212
+ npm --prefix packages/web run test:ci:webkit # Safari engine (nightly)
213
+ npm --prefix packages/web run test:webkit # Safari engine locally
214
+ npm --prefix packages/web run test:iphone # WebKit + iPhone descriptor only
215
+ npm --prefix packages/web run test:phone # Android over adb (real camera)
216
+ npm --prefix packages/web run test:field # local real-photo corpus
217
+ ```
218
+
219
+ A real iPhone can be tested manually with `serve:iphone`: the camera needs
220
+ a secure origin, so the script generates a LAN HTTPS certificate with
221
+ `mkcert` and prints how to trust its CA once on the device. The
222
+ `iphone` Playwright project (WebKit + iPhone 15 Pro descriptor) is the
223
+ automated engine proxy — it exercises the same UI and fake-camera suite
224
+ without a device.
225
+
226
+ ## License
227
+
228
+ [MIT](./LICENSE)
package/dist/css.css ADDED
@@ -0,0 +1,121 @@
1
+ /* barcode-web default UI — link it next to the module:
2
+ *
3
+ * <link rel="stylesheet" href="node_modules/barcode-web/css.css">
4
+ *
5
+ * Every color, radius and text value reads a --barcode-ui-* custom
6
+ * property with a fallback, so themes are pure CSS on the consumer
7
+ * side — nothing here needs touching.
8
+ */
9
+ dialog.barcode-ui {
10
+ position: fixed; inset: 0;
11
+ /* border-box: with the UA's content-box, the 16px padding lands
12
+ OUTSIDE the declared 100vw/100dvh and the ✕ ends up off-screen */
13
+ box-sizing: border-box;
14
+ width: 100vw; height: 100dvh; max-width: none; max-height: none;
15
+ margin: 0; border: 0; padding: 16px;
16
+ display: none;
17
+ flex-direction: column; align-items: center; justify-content: center;
18
+ gap: 14px;
19
+ background: var(--barcode-ui-backdrop, rgba(8, 10, 12, .82));
20
+ color-scheme: dark;
21
+ }
22
+ dialog.barcode-ui[open] { display: flex; }
23
+ dialog.barcode-ui::backdrop {
24
+ background: var(--barcode-ui-backdrop, rgba(8, 10, 12, .82));
25
+ }
26
+ .barcode-ui-stage {
27
+ position: relative;
28
+ width: min(86vw, 86dvh, 440px);
29
+ aspect-ratio: 1;
30
+ border-radius: var(--barcode-ui-radius, 28px);
31
+ overflow: hidden;
32
+ background: #000;
33
+ box-shadow: 0 0 0 1px rgba(255, 255, 255, .08);
34
+ }
35
+ .barcode-ui-stage video {
36
+ display: block; width: 100%; height: 100%;
37
+ object-fit: cover;
38
+ }
39
+ .barcode-ui-corners i {
40
+ position: absolute;
41
+ width: 34px; height: 34px;
42
+ border: 0 solid var(--barcode-ui-bracket, #fff);
43
+ opacity: .92;
44
+ }
45
+ .barcode-ui-corners i:nth-of-type(1) {
46
+ top: 14px; left: 14px;
47
+ border-top-width: 4px; border-left-width: 4px;
48
+ border-top-left-radius: 14px;
49
+ }
50
+ .barcode-ui-corners i:nth-of-type(2) {
51
+ top: 14px; right: 14px;
52
+ border-top-width: 4px; border-right-width: 4px;
53
+ border-top-right-radius: 14px;
54
+ }
55
+ .barcode-ui-corners i:nth-of-type(3) {
56
+ bottom: 14px; left: 14px;
57
+ border-bottom-width: 4px; border-left-width: 4px;
58
+ border-bottom-left-radius: 14px;
59
+ }
60
+ .barcode-ui-corners i:nth-of-type(4) {
61
+ bottom: 14px; right: 14px;
62
+ border-bottom-width: 4px; border-right-width: 4px;
63
+ border-bottom-right-radius: 14px;
64
+ }
65
+ .barcode-ui-line {
66
+ position: absolute; left: 12%; right: 12%; top: 50%;
67
+ height: 2px; border-radius: 2px; transform: translateY(-50%);
68
+ background: linear-gradient(90deg, transparent, var(--barcode-ui-bracket, #fff), transparent);
69
+ opacity: .7;
70
+ }
71
+ /* Read feedback: 0% hunting, 50% one read (confirmation pending),
72
+ 100% confirmed — then the dialog plays its 300ms exit and closes. */
73
+ .barcode-ui-progress {
74
+ position: absolute; left: 14px; right: 14px; bottom: 14px;
75
+ height: 4px; border-radius: 2px;
76
+ background: var(--barcode-ui-track, rgba(255, 255, 255, .22));
77
+ overflow: hidden;
78
+ }
79
+ .barcode-ui-progress i {
80
+ display: block; height: 100%; width: 0;
81
+ border-radius: 2px;
82
+ background: var(--barcode-ui-accent, #ffd60a);
83
+ transition: width .18s ease-out;
84
+ }
85
+ dialog.barcode-ui.barcode-ui-done {
86
+ animation: barcode-ui-exit .3s ease-in forwards;
87
+ }
88
+ dialog.barcode-ui.barcode-ui-done::backdrop {
89
+ animation: barcode-ui-exit .3s ease-in forwards;
90
+ }
91
+ @keyframes barcode-ui-exit {
92
+ to { opacity: 0; transform: scale(.96); }
93
+ }
94
+ dialog.barcode-ui.barcode-ui-done::backdrop {
95
+ background: var(--barcode-ui-backdrop, rgba(8, 10, 12, .82));
96
+ }
97
+ .barcode-ui-hint {
98
+ margin: 0;
99
+ font: 500 14px/1.4 system-ui, sans-serif;
100
+ color: var(--barcode-ui-text, rgba(255, 255, 255, .85));
101
+ }
102
+ .barcode-ui-close, .barcode-ui-torch {
103
+ border: 0; border-radius: 50%;
104
+ width: 44px; height: 44px; padding: 0;
105
+ background: rgba(0, 0, 0, .45); color: #fff;
106
+ font: 18px/1 system-ui, sans-serif;
107
+ display: grid; place-items: center;
108
+ cursor: pointer;
109
+ -webkit-tap-highlight-color: transparent;
110
+ }
111
+ .barcode-ui-close {
112
+ position: absolute;
113
+ top: max(14px, env(safe-area-inset-top));
114
+ right: max(14px, env(safe-area-inset-right));
115
+ }
116
+ .barcode-ui-torch { font-size: 20px; }
117
+ .barcode-ui-torch svg { display: block; }
118
+ .barcode-ui-torch.on {
119
+ background: var(--barcode-ui-accent, #ffd60a);
120
+ color: #111;
121
+ }
@@ -0,0 +1,24 @@
1
+ // Types for the thread-aware default entry (`@webreflection/barcode`).
2
+ //
3
+ // The runtime default depends on where the module is imported:
4
+ // - main thread → the barcode() session factory (see ./main.d.ts)
5
+ // - worker → the bootstrap promise (see ./worker.d.ts)
6
+ //
7
+ // TypeScript cannot see the runtime context, so the honest type is the
8
+ // union. Import '@webreflection/barcode/main' or
9
+ // '@webreflection/barcode/worker' for a precise type.
10
+
11
+ declare const entry:
12
+ | typeof import("./main.js").default
13
+ | Promise<unknown>;
14
+
15
+ export default entry;
16
+
17
+ // Type-only: no runtime named exports exist on this entry.
18
+ export type {
19
+ Barcode,
20
+ BarcodeOptions,
21
+ Code,
22
+ RenderOptions,
23
+ ScanOptions,
24
+ } from "./main.js";
package/dist/index.js ADDED
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Thread-aware default entry — the `@webreflection/barcode` specifier.
3
+ *
4
+ * One import works in both contexts:
5
+ *
6
+ * // main thread: the default is barcode(options) → { scan, render, worker }
7
+ * import barcode from '@webreflection/barcode';
8
+ * const { scan, render } = barcode();
9
+ *
10
+ * // dedicated/shared worker: the default is the bootstrap promise
11
+ * // (non-blocking by design — the listener is installed synchronously;
12
+ * // the promise resolves when the main thread hands over its port)
13
+ * import bootstrap from '@webreflection/barcode';
14
+ *
15
+ * The detection runs BEFORE anything DOM-ish is imported: on a worker we
16
+ * only load `worker.js`, so the SDK never evaluates main-thread code there.
17
+ * `WorkerGlobalScope` is exposed in dedicated/shared/service workers and
18
+ * undefined on the main thread, so this never touches `window`.
19
+ *
20
+ * Use the explicit entries when a static import is preferable:
21
+ * '@webreflection/barcode/main' main thread only
22
+ * '@webreflection/barcode/worker' worker only
23
+ */
24
+ const inWorker = typeof WorkerGlobalScope !== "undefined";
25
+
26
+ const { default: entry } = inWorker
27
+ ? await import("./worker.js")
28
+ : await import("./main.js");
29
+
30
+ export default entry;
package/dist/main.d.ts ADDED
@@ -0,0 +1,116 @@
1
+ // Public API types for barcode-web's main entry (api/main.js).
2
+ // The contract: one barcode() per page/SPA/session, returning
3
+ // { scan, render, worker }. Hand-authored against the frozen contract —
4
+ // the implementation is plain JS with JSDoc, so this file is the
5
+ // consumer-facing truth. Keep it in sync with api/README.md.
6
+
7
+ export interface Code {
8
+ /** Lowercase canonical name on render input ("code128"); decode
9
+ * results carry the wasm's title-cased name ("Code128"). */
10
+ symbology: string;
11
+ text: string;
12
+ /** Exact payload bytes. `text` is a display string — binary payloads
13
+ * (QR byte mode, Aztec, DataMatrix, PDF417) survive only here, where
14
+ * they are mapped to `text` Latin-1-style (byte → U+0000..U+00FF). */
15
+ raw: Uint8Array;
16
+ /** The four corner points, in mask coordinates. */
17
+ position: Array<{ x: number; y: number }>;
18
+ /** Centering rank: 1 = dead center, 0 = frame corner. */
19
+ score?: number;
20
+ }
21
+
22
+ export interface BarcodeOptions {
23
+ /**
24
+ * Where the pipeline lives. A string/URL spawns a dedicated module
25
+ * Worker instantly; an already-created Worker is used as-is. Either
26
+ * way `Barcode.worker` is the live Worker instance. The session owns
27
+ * the worker for its whole lifetime — abort never terminates it;
28
+ * handing the same worker to a second session throws ('duplicated
29
+ * worker').
30
+ * @default new URL('./worker.js', import.meta.url)
31
+ */
32
+ worker?: string | URL | Worker;
33
+ /** Session-wide symbology default: 'qr' | 'barcode' | exact name(s). */
34
+ type?: string | string[];
35
+ /** Session-wide accuracy default: 'low' | 'auto' (default) | 'high'. */
36
+ accuracy?: 'low' | 'auto' | 'high';
37
+ /** Camera lens hint for live scans. */
38
+ lens?: 'ultrawide' | 'wide' | 'default';
39
+ }
40
+
41
+ export interface ScanOptions {
42
+ /** Exactly one of into / video / image may be set (a TypeError is
43
+ * thrown otherwise). Default: { into: document.body } — the default
44
+ * UI with its own ✕ that aborts the scan. */
45
+ into?: string | Node;
46
+ /** Bring your own <video> (chain your own signal to stop early). */
47
+ video?: HTMLVideoElement;
48
+ /** Still scan: canvas, ImageBitmap, HTMLImageElement, SVG, Blob/File. */
49
+ image?: CanvasImageSource | Blob | OffscreenCanvas;
50
+ /** Graceful stop → the promise resolves undefined (never throws). */
51
+ signal?: AbortSignal;
52
+ /** Escape hatch over the mode defaults (500ms live, 5000ms still). */
53
+ latency?: number;
54
+ /** Per-scan override of the session type/accuracy/lens. */
55
+ type?: string | string[];
56
+ accuracy?: 'low' | 'auto' | 'high';
57
+ lens?: 'ultrawide' | 'wide' | 'default';
58
+ /** Live framing: 'square' (default — what you frame is what decodes)
59
+ * or 'full' (the explicit opt-out). */
60
+ crop?: 'square' | 'full';
61
+ /** Initial camera zoom factor. */
62
+ zoom?: number;
63
+ /** Initial torch state (the default UI also carries a toggle). */
64
+ torch?: boolean;
65
+ }
66
+
67
+ /** Layout for render(): every field is optional and keeps its default. */
68
+ export interface RenderOptions {
69
+ /** Module (dot/bar) size in px. @default 4 */
70
+ module?: number;
71
+ /** 1D bar height in px. @default 30 * module */
72
+ height?: number;
73
+ /** QR error correction level. @default "M" */
74
+ ec?: "L" | "M" | "Q" | "H";
75
+ /** QR mask pattern 0..7. @default 2 */
76
+ mask?: number;
77
+ /** QR version 1..40; pads the symbol to that size. @default smallest that fits */
78
+ version?: number;
79
+ /** PDF417 error correction level 0..8. @default encoder default */
80
+ level?: number;
81
+ /** PDF417 data columns 1..30. @default auto */
82
+ columns?: number;
83
+ /** Data Matrix ECC200 size in modules INCLUDING borders, e.g. 12 for a 12×36 DMRE. @default smallest square */
84
+ rows?: number;
85
+ /** Data Matrix ECC200 columns; provide together with `rows`. @default smallest square */
86
+ cols?: number;
87
+ }
88
+
89
+ export interface Barcode {
90
+ /**
91
+ * One complete scan. Resolves ONCE with the best code (most centered
92
+ * first, larger symbol as tiebreak) or `undefined` — abort, still
93
+ * latency expired, or a graceful end. Real errors (camera denied,
94
+ * broken pipeline) reject. One scan at a time per session.
95
+ */
96
+ scan(options?: ScanOptions): Promise<Code | undefined>;
97
+ /**
98
+ * Render a scan result (or a bare { symbology, text }) as an
99
+ * SVGSVGElement, styleable via --barcode-ink / --barcode-paper.
100
+ * `undefined`/empty → null. Stateless: safe to fire N times in
101
+ * parallel.
102
+ */
103
+ render(
104
+ result:
105
+ | { symbology: string; text?: string; raw?: Uint8Array }
106
+ | null
107
+ | undefined,
108
+ opts?: RenderOptions,
109
+ ): Promise<SVGSVGElement | null>;
110
+ /** The live Worker instance — the one spawned from the string/URL
111
+ * option, or the caller's own, verbatim. */
112
+ worker: Worker;
113
+ }
114
+
115
+ declare function barcode(options?: BarcodeOptions): Barcode;
116
+ export default barcode;
package/dist/main.js ADDED
@@ -0,0 +1 @@
1
+ function je(){var t,e,r=new this((n,s)=>{t=n,e=s});return{resolve:t,reject:e,promise:r}}var xe=(Promise.withResolvers??je).bind(Promise);var ke=(t=0)=>{let e=new Int32Array([t]);return()=>e[0]++};var Ee=(t=(e=>e))=>{let e=new Map,r=ke();return[()=>{let n;do n=t(r());while(e.has(n));let s=xe();return e.set(n,s),[n,s.promise]},(n,s,i)=>{let a=e.get(n);a&&(e.delete(n),i?a.reject(i):a.resolve(s))}]};function Me(t){this._=t}for(let t of Reflect.ownKeys(Reflect))typeof t=="string"&&(Me.prototype[t]=function(e,r){if(t!=="get"||r!=="then")return(this._[t]??Reflect[t]).apply(this._,arguments)});var Te=(function(t,e){return new Proxy(t,new Me(e))});var Q=class extends Map{put(t,e){return this.set(t,e),e}};var{create:Ne,freeze:ce}=Object,xt=ce([]),G=ce(Ne(null)),kt=ce({});var{defineProperty:$e}=Object,[Be,Ue]=Ee(),Z=Symbol(),Ge=(t,e)=>{let r=t.postMessage.bind(t),n=new Q,s=new Te(G,{get:(a,o)=>o===Z?(c=>(i=c,s)):n.get(o)??n.put(o,(...c)=>{try{let[l,u]=Be();return r([!0,l,o,c],i),u}finally{i=G}})}),i=G;return $e(e,Z,{configurable:!1,set(a){i=a}}),t.onmessage=async({data:[a,o,c,l]})=>{if(a)try{let u=await e[c](...l);r([!a,o,u,null],i)}catch(u){r([!a,o,null,u])}finally{i=G}else Ue(o,c,l)},s},Ce=Ge;var Re=()=>document.createRange();var{entries:Ze}=Object,Le=(t,e=globalThis.document)=>{let r="",n={},s=Re();for(let[i,a]of Ze(t))n[i]=o=>(r!==i&&(r=i,s.selectNodeContents(a)),s.createContextualFragment(o));return n};var Se=Le({html:document.createElement("template"),svg:document.createElementNS("http://www.w3.org/2000/svg","svg")},document),Ot=Se.html,Y=Se.svg;async function Ve(){(await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:"environment"}}})).getTracks().forEach(e=>e.stop())}async function Ie(){return(await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind==="videoinput")}async function X(){let t=await Ie();if(t.some(r=>!r.deviceId)){try{await Ve()}catch{}t=await Ie()}let e=[];for(let r of t){if(!r.deviceId)continue;let n=r.label.toLowerCase();/front|frontkamera|kamera vorne|vorwärts|selfie|facetime|前|前置/.test(n)||e.push({deviceId:r.deviceId,label:r.label,groupId:r.groupId,kind:Ke(n)})}return e}function Ke(t){return/ultra|ultrawide|0[.,]5x|0[.,]5\b/.test(t)?"ultrawide":/tele|zoom|2x|3x|5x/.test(t)?"tele":/wide|haupt|main|back|rück/.test(t)?"wide":"unknown"}async function le(t={}){let{idealWidth:e=1920,idealHeight:r=1080}=t,n={width:{ideal:e},height:{ideal:r}};if(t.deviceId)n.deviceId={exact:t.deviceId};else if(t.lens&&t.lens!=="default"){let a=await X(),o=t.lens==="ultrawide"?"ultrawide":"wide",c=a.find(l=>l.kind===o)??(t.lens==="wide"?a.find(l=>l.kind==="unknown"):void 0);c?n.deviceId={exact:c.deviceId}:n.facingMode={ideal:"environment"}}else n.facingMode={ideal:"environment"};let s=await navigator.mediaDevices.getUserMedia({video:n,audio:!1}),i=s.getVideoTracks()[0];if(i&&typeof i.applyConstraints=="function"){let a=i.getCapabilities?.()??{},o=[];if(t.zoom!=null&&a.zoom){let c=Math.min(Math.max(t.zoom,a.zoom.min),a.zoom.max);o.push({zoom:c})}if(t.torch!=null&&a.torch&&o.push({torch:t.torch}),o.length)try{await i.applyConstraints({advanced:o})}catch{for(let c of o)try{await i.applyConstraints({advanced:[c]})}catch{}}}return s}function S(t){return t.getCapabilities?.()??{}}async function J(t,e){let r=S(t);if(!r.zoom)return null;let n=Math.min(r.zoom.max,Math.max(r.zoom.min,e));return await t.applyConstraints({advanced:[{zoom:n}]}),n}function ee(t){return t.getSettings().zoom??null}async function ue(t,e){return S(t).torch?(await t.applyConstraints({advanced:[{torch:e}]}),!0):!1}async function ze(t,e){let r=S(t);if(!r.focusDistance)return!1;let n=r.focusDistance,s=Math.min(n.max,Math.max(n.min,e));try{return await t.applyConstraints({advanced:[{focusMode:"manual",focusDistance:s}]}),!0}catch{return!1}}async function Ae(t){let e=S(t);if(!e.focusMode||!e.focusMode.includes("continuous"))return!1;try{return await t.applyConstraints({advanced:[{focusMode:"continuous"}]}),!0}catch{return!1}}async function de(t){let e=S(t),r=t.getSettings(),n=r.focusDistance??null;await new Promise(a=>setTimeout(a,150));let i=t.getSettings().focusDistance??null;return{mode:r.focusMode??null,distance:n,range:e.focusDistance?{min:e.focusDistance.min,max:e.focusDistance.max}:null,changing:n!==null&&i!==null&&Math.abs(i-n)>.005}}async function me(t){let e=performance.now()+2e3,r=null;for(;performance.now()<e;){let s=t.getSettings().focusDistance??null;if(r!==null&&s!==null&&Math.abs(s-r)<.005&&r!==0)return;r=s,await new Promise(i=>setTimeout(i,150))}}var Qe={qrcode:"qrcode",microqr:"microqr",microqrcode:"microqr",datamatrix:"datamatrix",aztec:"aztec",pdf417:"pdf417",ean13:"ean13",ean8:"ean8",upca:"upca",upce:"upce",code39:"code39",code93:"code93",code128:"code128",itf:"itf",codabar:"codabar",databar:"databar",databarltd:"databarltd",databarstacked:"databarstk",databarstk:"databarstk"},Ye=new Set(["QRCode","QRCode Micro","Data Matrix","DataMatrix","Aztec","PDF417"]),Oe=.4,_e=1200,Xe=1200,Je=5e3,et=2e3,tt=1e3,rt=3e3,te=class{#e;#n=null;#r=!1;#g=!1;#y=!1;#v=0;#m=0;#f=0;#l=0;#b=0;#T=0;#i=null;#C=!1;#h=!1;#R=null;#L=0;#u=0;#p=0;#w=0;#s=null;#x="init";#d=[];#o=new Map;#k=0;#E=0;#a=null;#c=null;constructor(e){if(this.#e={maxFps:30,adaptiveZoom:!0,suggestAfterMs:3e3,accuracy:"auto",budget:500,...e},this.#e.formats!=null){if(!Array.isArray(this.#e.formats)||this.#e.formats.some(r=>typeof r!="string"))throw new Error("formats must be an array of symbology name strings");this.#e.formats=this.#e.formats.map(r=>r.trim().toLowerCase())}}get capabilities(){return{binarizer:this.#x,symbologies:[...this.#d],formats:this.#e.formats??null}}get binarizerKind(){return this.#x}async start(){if(this.#r)return;let e=this.#e.video;if(this.#n=await le({lens:this.#e.lens,...this.#e.camera}),e.srcObject=this.#n,e.muted=!0,e.playsInline=!0,await e.play(),!this.#e.decode){if(this.#e.worker===!1)throw new Error("The scanner requires the pipeline worker (worker: false is not supported).");if(!this.#i){let r="./pipeline-worker.js",n=this.#e.pipelineWorker;this.#i=n instanceof Worker?n:new Worker(new URL(n??r,import.meta.url),{type:"module"});try{await this.#D()}catch(s){throw this.#n.getTracks().forEach(i=>i.stop()),this.#n=null,this.#i=null,s}}}this.#r=!0,this.#v=performance.now(),this.#T=performance.now(),this.#l=0,this.#b=0,this.#y||(this.#y=!0,this.#M())}async#M(){if(!this.#r){this.#y=!1;return}let e=this.#e.video;if("requestVideoFrameCallback"in e?e.requestVideoFrameCallback(()=>void this.#M()):setTimeout(()=>void this.#M(),33),this.#g){this.#E++;return}if(e.videoWidth===0)return;let r=1e3/this.#e.maxFps;if(performance.now()-this.#v<r){this.#E++;return}this.#g=!0;let n=performance.now();try{let s=this.#e.decode?await this.#F(e):await this.#P(e);if(s.error)throw new Error(s.error);let i=s.results,a=performance.now()-n;this.#H(i,s);let o=this.#W(i,a>(this.#e.budget??500),s.partial===!0);this.#q(i,o,s);let c=null;s.mask&&(c={width:s.frameW,height:s.frameH,data:new Uint8Array(s.mask),bytesPerRow:s.bytesPerRow},await this.#e.onFrame?.(c)),i.length&&(this.#l=performance.now()),this.#k=0,o.length&&this.#e.onResults?.(o),this.#e.adaptiveZoom&&c&&this.#_(i,c),this.#e.adaptiveZoom&&c&&this.#O(i,c),this.#A(s,i.length>0),this.#z();let l=performance.now()-n;this.#f=this.#f===0?1e3/l:.9*this.#f+.1*(1e3/l),this.#e.onStats?.({fps:this.#f,frameMs:l,frameW:c?.width??0,frameH:c?.height??0,zoom:ee(this.#t()),dropped:this.#E})}catch(s){console.error("frame failed:",s),++this.#k>=3&&(this.#o.clear(),this.#e.onError?.(s),this.stop())}finally{this.#v=performance.now(),this.#g=!1}}#z(){let e=this.#e.suggestAfterMs;if(!e||!this.#e.onHint)return;let r=performance.now();if(r-this.#b<1e4)return;let n=this.#l||this.#T;r-n<e||(this.#b=r,(async()=>{let s=await de(this.#t()),a=this.#t().getSettings().deviceId??"",c=(await X()).filter(l=>l.deviceId!==a).map(l=>({deviceId:l.deviceId,label:l.label,kind:l.kind,focusDistance:null}));this.#e.onHint?.({reason:"no-decode",elapsedMs:r-n,cameras:{cameras:c,currentDeviceId:a},focus:s})})())}async#A(e,r){if(this.#e.autoTorch===!1||this.#C||!this.#r)return;let n=this.#t();if(!S(n).torch)return;let i=performance.now();if(i-this.#L<tt)return;let a=e?.qrPresence,o=null;typeof a=="number"?(a===1?(this.#u||(this.#u=i),o=i-this.#u>=Xe?!0:null):this.#u=0,a===0?(this.#p||(this.#p=i),this.#h&&i-this.#p>=et&&(o=!1)):this.#p=0):r?(this.#w=0,o=!1):(this.#w||(this.#w=i),o=i-this.#w>=Je?!0:null),r&&(this.#u=0),!(o==null||o===this.#h)&&(this.#L=i,this.#h=o,await this.#S(n,o))}get torchApplied(){return this.#R}async#S(e,r){let n=await ue(e,r);return n&&(this.#R=r),n}async overrideTorch(e){return this.#C=!0,this.#h=!1,this.#r?this.#S(this.#t(),e):!1}async#O(e,r){if(e.length||this.#e.camera?.zoom!=null)return;let n=performance.now();if(n-this.#m<_e||!this.#l||n-this.#l<rt)return;let s=this.#t(),i=S(s);if(!i.zoom)return;let a=i.zoom;(ee(s)??a.min)<=a.min*1.02||(this.#m=n,await J(s,a.min))}async#_(e,r){if(!e.length||this.#e.camera?.zoom!=null)return;let n=performance.now();if(n-this.#m<_e)return;let s=this.#t(),i=S(s);if(!i.zoom)return;let a=0;for(let x of e){let d=x.position.map(m=>m.x),f=x.position.map(m=>m.y);a=Math.max(a,Math.max(...d)-Math.min(...d),Math.max(...f)-Math.min(...f))}let o=a/r.width;if(o>=Oe)return;let c=i.zoom,l=ee(s)??c.min,u=Math.min(c.max,l*(Oe/o));u<=l*1.05||(this.#m=n,await J(s,u))}#W(e,r,n=!1){if(n)return[];let s=o=>o.symbology+"\0"+o.text;if(r&&e.length===0)return this.#o.clear(),[];let i=new Map(e.map(o=>[s(o),o]));for(let o of this.#o.keys())i.has(o)||this.#o.delete(o);for(let o of i.keys())this.#o.set(o,(this.#o.get(o)??0)+1);let a=e.find(o=>(this.#o.get(s(o))??0)>=2);return a?[a]:[]}#H(e,r){let n=this.#c;if(!n||!e.length)return;let s=r.frameW??0,i=r.frameH??0;if(!s||!i)return;let a=n.w<=s?1:n.w/s,o=n.h<=i?1:n.h/i;for(let c of e)c.position?.length&&(c.position=c.position.map(l=>({x:n.x+l.x*a,y:n.y+l.y*o})))}#q(e,r,n){if(r.length){this.#a=null;return}if(this.#a||!e.length)return;let s=e[0];if(!s||!Ye.has(String(s.symbology)))return;let i=this.#e.video,a=i.videoWidth,o=i.videoHeight,c=n.frameW??0,l=n.frameH??0;if(!a||!o||!c||!l||!s.position?.length)return;let u=this.#e.crop==="square",x=u?Math.min(a,o):0,d=u?(a-x)/2:0,f=u?(o-x)/2:0,m=u?x:a,W=u?x:o,v=m/c,I=W/l,$=s.position.map(A=>A.x*v+d),H=s.position.map(A=>A.y*I+f),h=Math.min(...$),b=Math.min(...H),p=Math.max(...$)-h,g=Math.max(...H)-b;if(!(p>0&&g>0))return;let k=Math.max(16,p*.25),z=Math.max(16,g*.25);if(h=Math.max(0,Math.round(h-k)),b=Math.max(0,Math.round(b-z)),p=Math.min(a-h,Math.round(p+2*k)),g=Math.min(o-b,Math.round(g+2*z)),p<32||g<16)return;let q=String(s.symbology).toLowerCase().replace(/[^a-z0-9]/g,"");this.#a={x:h,y:b,w:p,h:g,format:Qe[q]??null,frames:5}}#I(e){this.#c=null;let r=this.#a;if(r&&r.frames>0)return r.frames-=1,this.#c=r,r.frames===0&&(this.#a=null),createImageBitmap(e,r.x,r.y,r.w,r.h);if(this.#e.crop!=="square")return createImageBitmap(e);let n=Math.min(e.videoWidth,e.videoHeight);return n?createImageBitmap(e,(e.videoWidth-n)/2,(e.videoHeight-n)/2,n,n):createImageBitmap(e)}async#F(e){let r=await this.#I(e);try{let n=this.#c,s=await this.#e.decode(r,n?.format?[n.format]:this.#e.formats,this.#e.accuracy);if(s?.error)throw new Error(s.error);return{results:s?.results??[],qrPresence:s?.qrPresence,partial:s?.partial===!0}}finally{r.close?.()}}#D(){let e=this.#i,{promise:r,resolve:n,reject:s}=Promise.withResolvers(),i=setTimeout(()=>s(new Error("worker init timeout")),8e3);return e.addEventListener("message",a=>{let o=a.data;if(o?.type==="ready"){clearTimeout(i),this.#x=o.kind??"unknown",this.#d=Array.isArray(o.symbologies)?o.symbologies:[];let c=this.#e.formats;if(c?.length&&this.#d.length){let l=c.filter(u=>!this.#d.includes(u));if(l.length){s(new Error(`unknown symbology ${l.join(", ")} \u2014 supported: ${this.#d.join(", ")}`));return}}n(void 0)}else if(o?.type==="error")clearTimeout(i),s(new Error(o.message));else if(o?.type==="frameResult"){let c=this.#s;c&&(clearTimeout(c.timer),this.#s=null,c.resolve(o))}}),e.addEventListener("error",a=>{clearTimeout(i),s(new Error(a.message??"worker error"))}),e.postMessage({type:"init",opts:{...this.#e.binarizer??{},accuracy:this.#e.accuracy}}),r}#P(e){if(this.#s)return Promise.reject(new Error("frame already in flight"));let r=this.#i,{promise:n,resolve:s,reject:i}=Promise.withResolvers(),a={promise:n,resolve:s,reject:i,timer:0};return a.timer=setTimeout(()=>{this.#s=null,i(new Error("worker decode timeout"))},5e3),this.#s=a,this.#I(e).then(o=>{let c=this.#c;return r.postMessage({type:"frame",bitmap:o,opts:{...this.#e.binarizer??{},formats:c?.format?[c.format]:this.#e.formats}},[o]),n},o=>{throw clearTimeout(a.timer),this.#s=null,o})}#t(){let e=this.#n?.getVideoTracks()[0];if(!e)throw new Error("Scanner not started.");return e}hasTorch(){return this.#r?S(this.#t()).torch===!0:!1}async setTorch(e){return this.#r?ue(this.#t(),e):!1}async zoomTo(e){let r=this.#r?await J(this.#t(),e):null;return r!==null&&this.#r&&await me(this.#t()),r}async setLens(e){this.#e.lens=e,this.#r&&(this.#n?.getTracks().forEach(r=>r.stop()),this.#n=await le({lens:e,...this.#e.camera}),this.#e.video.srcObject=this.#n,await this.#e.video.play(),await me(this.#t()))}async setFocusDistance(e){return this.#r?ze(this.#t(),e):!1}async setFocusContinuous(){return this.#r?Ae(this.#t()):!1}async focusInfo(){return de(this.#t())}async lenses(){return X()}async suspend(){if(this.#r=!1,this.#n?.getTracks().forEach(e=>e.stop()),this.#n=null,this.#e.video.srcObject=null,this.#s){clearTimeout(this.#s.timer);let e=this.#s;this.#s=null,e.reject(new Error("scanner stopped"))}this.#o.clear(),this.#a=null,this.#c=null,this.#k=0}async stop(){await this.suspend(),this.#i?.terminate(),this.#i=null}};var{replace:nt}="";var st=/[&<>'"]/g,ot={"&":"&amp;","<":"&lt;",">":"&gt;","'":"&#39;",'"':"&quot;"},it=t=>ot[t],We=t=>nt.call(t,st,it);var at={M:0,L:1,H:2,Q:3},N=(t,e,r,n)=>{if(!Number.isInteger(e)||e<r||e>n)throw new TypeError(`render: ${t} must be an integer ${r}..${n}`);return e};function fe(t={}){let e=-1;if(t.ec!=null){let s=String(t.ec).trim().toUpperCase(),i=at[s];if(i==null)throw new TypeError('render: ec must be "L", "M", "Q" or "H"');e=i}let r=t.rows!=null,n=t.cols!=null;if(r!==n)throw new TypeError("render: rows and cols must be provided together");return{ec:e,mask:t.mask==null?-1:N("mask",t.mask,0,7),version:t.version==null?0:N("version",t.version,1,40),level:t.level==null?-1:N("level",t.level,0,8),columns:t.columns==null?0:N("columns",t.columns,1,30),rows:r?N("rows",t.rows??0,1,144):0,cols:n?N("cols",t.cols??0,1,144):0}}var $t=Promise.resolve();function He({width:t,height:e,bytesPerRow:r,data:n},s){let i=(d,f)=>n[f*r+(d>>3)]>>(d&7)&1,a=(d,f,m)=>{for(let[W,v]of d)l+=`<rect x="${W}" y="${f}" width="${v}" height="${m-f}" fill="var(--barcode-ink, #000)"/>`},o=null,c=0,l="";for(let d=0;d<e;d++){let f=[],m=-1;for(let v=0;v<t;v++)i(v,d)?m<0&&(m=v):m>=0&&(f.push([m,v-m]),m=-1);m>=0&&f.push([m,t-m]),!!o&&o.length===f.length&&o.every(([v,I],$)=>{let H=f[$];return H[0]===v&&H[1]===I})||(o&&a(o,c,d),c=d),o=f}o&&a(o,c,e);let u=We(s),x=`<svg xmlns="http://www.w3.org/2000/svg" class="barcode-svg" viewBox="0 0 ${t} ${e}" width="${t}" height="${e}" role="img" aria-label="${u}"><rect width="${t}" height="${e}" fill="var(--barcode-paper, #fff)"/>${l}</svg>`;return Y(x).firstChild}var qe=new WeakSet,ct={qr:["qrcode","microqr"],barcode:["upca","ean13","ean8","upce","code39","code93","code128","itf","codabar","databar","databarltd","databarstk"]},Fe=t=>t==null?void 0:(Array.isArray(t)?t:[t]).flatMap(r=>{let n=String(r).trim().toLowerCase();return ct[n]??[n]}),lt=t=>new Promise((e,r)=>{let n=new Image;n.onload=()=>e(n),n.onerror=()=>r(new TypeError("image failed to load")),n.src=t}),De=(t,e,r)=>{let n=document.createElement("canvas");return n.width=e,n.height=r,n.getContext("2d")?.drawImage(t,0,0),createImageBitmap(n)},ut=async t=>{if(t instanceof HTMLCanvasElement||t instanceof Blob||t instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)return createImageBitmap(t);if(t instanceof HTMLImageElement)return t.complete||await t.decode(),De(t,t.naturalWidth,t.naturalHeight);if(typeof SVGSVGElement<"u"&&t instanceof SVGSVGElement){let e=new XMLSerializer().serializeToString(t),r=URL.createObjectURL(new Blob([e],{type:"image/svg+xml"}));try{let n=await lt(r);return De(n,n.naturalWidth,n.naturalHeight)}finally{URL.revokeObjectURL(r)}}throw new TypeError("scan: unsupported image input")},he,pe;he=new URL("./worker.js",import.meta.url),pe=new URL("./wasm.wasm",import.meta.url).href,he.hash="wasm="+encodeURIComponent(pe);var Qt=(t={})=>{let e=t.worker!=null,{worker:r=he??new URL("./worker.js",import.meta.url),type:n,accuracy:s,lens:i}=t,a;if(typeof r=="string"||r instanceof URL)a=new Worker(r,{type:"module"});else if(r instanceof Worker)a=r;else throw new TypeError("barcode: worker must be a string, a URL, or a Worker");if(qe.has(a))throw new Error("duplicated worker");qe.add(a);let{port1:o,port2:c}=new MessageChannel,l=Ce(o,{}),u=!1,x=()=>{u||a.postMessage({type:"barcode:ping",wasm:e?null:pe})},d=h=>{h.data?.type==="barcode:ready"&&(u||(u=!0,a.removeEventListener("message",d),clearInterval(f),a.postMessage(null,{transfer:[c]})))};a.addEventListener("message",d),x();let f=setInterval(x,250);setTimeout(()=>{u||(u=!0,a.removeEventListener("message",d),clearInterval(f),a.postMessage(null,{transfer:[c]}))},1e4);let m=n,W=s,v=i,I=!1;return{scan:(h={into:document.body})=>{let{into:b,video:p,image:g,signal:k,latency:z,lens:q=v,crop:A,zoom:re,torch:Pe,type:we=m,accuracy:ge=W??"auto"}=h,{promise:B,resolve:V,reject:O}=Promise.withResolvers(),F=!1,T=(R,L)=>{F||(F=!0,I=!1,R(L))};if(I)return T(O,new Error("scan: another scan is already in progress")),B;if(k&&(typeof k!="object"||typeof k.addEventListener!="function"))throw new TypeError("scan: signal must be an AbortSignal (pass controller.signal)");if(+(g!=null)+ +(p!=null)+ +(b!=null)>1)return T(O,new TypeError("scan: pick one of into, video, image")),B;I=!0;let D=new AbortController,ne=()=>{D.signal.aborted||D.abort()};return D.signal.addEventListener("abort",()=>T(V,void 0),{once:!0}),k&&(k.aborted?ne():k.addEventListener("abort",ne,{once:!0})),F?B:g!=null?((async()=>{let R=await ut(g);if(F){R.close?.();return}l[Z]({transfer:[R]});let L=await l.decode({bitmap:R,formats:Fe(we),still:!0,accuracy:ge,latency:z??5e3});F||(L?.type==="error"?T(O,new Error(L.message)):T(V,L?.codes?.[0]))})().catch(R=>T(O,R)),B):((async()=>{let L=b!=null?b:document.body,ye=p??null,E=null,se=null,K=null,P,oe=()=>{D.signal.removeEventListener("abort",ie);try{P?.stop()}catch{}E?.remove(),E=null},ie=()=>oe();if(D.signal.addEventListener("abort",ie,{once:!0}),!p){let w=typeof L=="string"?document.querySelector(L):L;if(!w)throw new TypeError(`scan: no element matches ${JSON.stringify(L)}`);E=w.appendChild(document.createElement("dialog")),E.className="barcode-ui";let C=Object.assign(document.createElement("video"),{autoplay:!0,playsInline:!0,muted:!0}),M=E.appendChild(document.createElement("div"));M.className="barcode-ui-stage",ye=M.appendChild(C);let _=M.appendChild(document.createElement("div"));_.className="barcode-ui-corners",_.setAttribute("aria-hidden","true");for(let be=0;be<4;be++)_.appendChild(document.createElement("i"));let y=M.appendChild(document.createElement("div"));y.className="barcode-ui-line",y.setAttribute("aria-hidden","true");let j=M.appendChild(document.createElement("div"));j.className="barcode-ui-progress",j.setAttribute("aria-hidden","true"),K=j.appendChild(document.createElement("i"));let ae=E.appendChild(document.createElement("p"));ae.className="barcode-ui-hint",ae.textContent="Center the code in the frame";let ve=Object.assign(document.createElement("button"),{type:"button",className:"barcode-ui-torch","aria-label":"Toggle torch",hidden:!0});ve.append(Y('<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><path d="M13 2 4.5 13.5h5L10 22l9-12h-5.5L13 2z" fill="currentColor"/></svg>')),se=E.appendChild(ve);let U=E.appendChild(document.createElement("button"));U.type="button",U.className="barcode-ui-close",U.textContent="\u2715",U.setAttribute("aria-label","Stop scanning"),U.addEventListener("click",ne,{once:!0}),E.showModal()}P=new te({video:ye,budget:z??500,formats:Fe(we),accuracy:ge,lens:q??void 0,crop:A??"square",camera:{zoom:re,torch:Pe},onResults:w=>{let C=w[0];try{P?.stop()}catch{}D.signal.removeEventListener("abort",ie);let M=E,_=K;if(!M){T(V,C);return}_.style.width="100%",M.classList.add("barcode-ui-done");let y=!1,j=()=>{y||(y=!0,M.remove(),T(V,C))};M.addEventListener("animationend",j,{once:!0}),setTimeout(j,320)},onError:w=>{oe(),T(O,w)},decode:async(w,C,M)=>{let _=l[Z];_?.({transfer:[w]});let y=await l.decode({bitmap:w,formats:C,still:!1,accuracy:M});return E&&K&&!F&&y?.type==="result"&&y.codes.length&&!E.classList.contains("barcode-ui-done")&&(K.style.width="50%"),y?.type==="error"?{results:[],error:y.message}:{results:y.codes??[],qrPresence:y.qrPresence,partial:y.partial===!0,frameW:y.frameW,frameH:y.frameH}}});try{if(await P.start(),!p&&se&&P.hasTorch()){let w=se;w.hidden=!1;let C=!1;w.addEventListener("click",()=>{C=!C,P.overrideTorch(C),w.classList.toggle("on",C)})}}catch(w){oe(),T(O,w)}})().catch(R=>T(O,R)),B)},render:async(h,b={})=>{let p=h?.raw instanceof Uint8Array&&h.raw.length?h.raw:null,g=typeof h?.text=="string"?h.text:"";if(!h||!p&&!g)return null;let k=String(h.symbology??"").trim().toLowerCase(),z=fe(b),q=b.module??4,A=p&&(dt.has(k)||!g),re=await l.encode({symbology:k,text:g,raw:A?p:null,module:q,height:b.height??30*q,...z});return He(re,g||`binary: ${p?.length??0} bytes`)},worker:a}},dt=new Set(["qrcode","microqr","datamatrix","aztec","pdf417"]);export{Qt as default};
package/dist/wasm.wasm ADDED
Binary file
@@ -0,0 +1,18 @@
1
+ // Types for the worker entry (`@webreflection/barcode/worker`, dist/worker.js).
2
+ //
3
+ // Spawn it —
4
+ // new Worker('<url-to>/worker.js', { type: 'module' })
5
+ // — or point barcode({ worker }) at it, or import the auto entry
6
+ // (`@webreflection/barcode`) inside a worker. The default export is the
7
+ // bootstrap promise; the module installs its listener synchronously and
8
+ // resolves after the main thread's ping/ready handshake.
9
+ //
10
+ // The first port-carrying 'message' event binds the protocol, exactly
11
+ // once. Port-less messages pass through untouched, so an embedder can
12
+ // keep its own protocol on the same worker.
13
+
14
+ declare const bootstrap: Promise<{
15
+ decode: (msg: unknown) => Promise<unknown>;
16
+ encode: (msg: unknown) => Promise<unknown>;
17
+ }>;
18
+ export default bootstrap;
package/dist/worker.js ADDED
@@ -0,0 +1,84 @@
1
+ function ce(){var e,t,r=new this((n,o)=>{e=n,t=o});return{resolve:e,reject:t,promise:r}}var wt=(Promise.withResolvers??ce).bind(Promise);var mt=(e=0)=>{let t=new Int32Array([e]);return()=>t[0]++};var bt=(e=(t=>t))=>{let t=new Map,r=mt();return[()=>{let n;do n=e(r());while(t.has(n));let o=wt();return t.set(n,o),[n,o.promise]},(n,o,s)=>{let i=t.get(n);i&&(t.delete(n),s?i.reject(s):i.resolve(o))}]};function yt(e){this._=e}for(let e of Reflect.ownKeys(Reflect))typeof e=="string"&&(yt.prototype[e]=function(t,r){if(e!=="get"||r!=="then")return(this._[e]??Reflect[e]).apply(this._,arguments)});var xt=(function(e,t){return new Proxy(e,new yt(t))});var K=class extends Map{put(e,t){return this.set(e,t),t}};var{create:ue,freeze:tt}=Object,Qe=tt([]),F=tt(ue(null)),Ze=tt({});var{defineProperty:de}=Object,[le,fe]=bt(),$=Symbol(),he=(e,t)=>{let r=e.postMessage.bind(e),n=new K,o=new xt(F,{get:(i,a)=>a===$?(c=>(s=c,o)):n.get(a)??n.put(a,(...c)=>{try{let[u,h]=le();return r([!0,u,a,c],s),h}finally{s=F}})}),s=F;return de(t,$,{configurable:!1,set(i){s=i}}),e.onmessage=async({data:[i,a,c,u]})=>{if(i)try{let h=await t[c](...u);r([!i,a,h,null],s)}catch(h){r([!i,a,null,h])}finally{s=F}else fe(a,c,u)},o},Mt=he;var et=null,vt=[],St=e=>{let t=e.ports?.[0];if(t){e.stopImmediatePropagation(),removeEventListener("message",St),et=t;for(let r of vt.splice(0))r(t)}};addEventListener("message",St);addEventListener("message",e=>{e.data?.type==="barcode:ping"&&(typeof e.data.wasm=="string"&&(globalThis.__barcodeWasm=e.data.wasm),postMessage({type:"barcode:ready",wasm:e.data.wasm??null}))});var It=()=>et?Promise.resolve(et):new Promise(e=>vt.push(e));var At=`struct Uniforms {
2
+ dstW: u32,
3
+ dstH: u32,
4
+ srcW: u32,
5
+ srcH: u32,
6
+ };
7
+ @group(0) @binding(0) var srcTex: texture_2d<f32>;
8
+ @group(0) @binding(1) var srcSamp: sampler;
9
+ @group(0) @binding(2) var<uniform> u: Uniforms;
10
+ @group(0) @binding(3) var<storage, read_write> outLuma: array<f32>;
11
+ @compute @workgroup_size(8, 8)
12
+ fn main(@builtin(global_invocation_id) gid: vec3u) {
13
+ if (gid.x >= u.dstW || gid.y >= u.dstH) { return; }
14
+ if (gid.x >= u.srcW || gid.y >= u.srcH) {
15
+ outLuma[gid.y * u.dstW + gid.x] = 1.0;
16
+ return;
17
+ }
18
+ let uv = select(
19
+ (vec2f(gid.xy) + 0.5) / vec2f(f32(u.dstW), f32(u.dstH)),
20
+ (vec2f(gid.xy) + 0.5) / vec2f(f32(u.srcW), f32(u.srcH)),
21
+ u.dstW >= u.srcW && u.dstH >= u.srcH,
22
+ );
23
+ let c = textureSampleLevel(srcTex, srcSamp, uv, 0.0);
24
+ outLuma[gid.y * u.dstW + gid.x] = dot(c.rgb, vec3f(0.299, 0.587, 0.114));
25
+ }`;var Et=`struct Uniforms {
26
+ width: u32,
27
+ height: u32,
28
+ radius: i32,
29
+ axis: u32,
30
+ };
31
+ @group(0) @binding(0) var<uniform> u: Uniforms;
32
+ @group(0) @binding(1) var<storage, read> input: array<f32>;
33
+ @group(0) @binding(2) var<storage, read_write> output: array<f32>;
34
+ @compute @workgroup_size(8, 8)
35
+ fn main(@builtin(global_invocation_id) gid: vec3u) {
36
+ if (gid.x >= u.width || gid.y >= u.height) { return; }
37
+ var sum = 0.0;
38
+ var count = 0u;
39
+ for (var d = -u.radius; d <= u.radius; d = d + 1) {
40
+ var sx = gid.x;
41
+ var sy = gid.y;
42
+ if (u.axis == 0u) {
43
+ let x = i32(gid.x) + d;
44
+ if (x < 0 || x >= i32(u.width)) { continue; }
45
+ sx = u32(x);
46
+ } else {
47
+ let y = i32(gid.y) + d;
48
+ if (y < 0 || y >= i32(u.height)) { continue; }
49
+ sy = u32(y);
50
+ }
51
+ sum = sum + input[sy * u.width + sx];
52
+ count = count + 1u;
53
+ }
54
+ output[gid.y * u.width + gid.x] = sum / f32(count);
55
+ }`;var Ut=`struct Uniforms {
56
+ width: u32,
57
+ height: u32,
58
+ thresholdNum: u32,
59
+ thresholdDen: u32,
60
+ floorNum: u32,
61
+ floorDen: u32,
62
+ gw: u32,
63
+ gh: u32,
64
+ };
65
+ @group(0) @binding(0) var<uniform> u: Uniforms;
66
+ @group(0) @binding(1) var<storage, read> luma: array<f32>;
67
+ @group(0) @binding(2) var<storage, read> mean: array<f32>;
68
+ @group(0) @binding(3) var<storage, read_write> mask: array<atomic<u32>>;
69
+ @group(0) @binding(4) var<storage, read> globalMean: array<f32>;
70
+ @compute @workgroup_size(8, 8)
71
+ fn main(@builtin(global_invocation_id) gid: vec3u) {
72
+ if (gid.x >= u.width || gid.y >= u.height) { return; }
73
+ let idx = gid.y * u.width + gid.x;
74
+ let local = f32(u.thresholdNum) / f32(u.thresholdDen);
75
+ let floor_ = f32(u.floorNum) / f32(u.floorDen);
76
+ let gx = min(u.gw - 1u, gid.x * u.gw / u.width);
77
+ let gy = min(u.gh - 1u, gid.y * u.gh / u.height);
78
+ let gMean = globalMean[gy * u.gw + gx];
79
+ let gFloor = gMean * floor_;
80
+ let isInk = luma[idx] < mean[idx] * local || (luma[idx] < gFloor && luma[idx] <= mean[idx] + 8.0 / 255.0);
81
+ if (isInk) {
82
+ atomicOr(&mask[idx >> 5u], 1u << (idx & 31u));
83
+ }
84
+ }`;var E={luma:0,blurH:256,blurV:512,binarize:768,lumaSmall:1024,globalH:1280,globalV:1536},we=7,S=64,J=class e{#t;#e;#o;#i;#n;#r;#u;#c;#s;#d=0;#l=0;#f=0;#h=0;#a=null;constructor(t,r){this.#t=t,this.#e=r.maxSize,this.#o=r.windowDivisor,this.#i=r.threshold;let n=t;n.addEventListener?.("uncapturederror",s=>{console.error("[WebGPU]",s.error?.message??s)}),this.#c=n.createSampler({magFilter:"linear",minFilter:"linear"});let o=s=>n.createShaderModule({code:s});this.#n=n.createComputePipeline({layout:"auto",compute:{module:o(At),entryPoint:"main"}}),this.#r=n.createComputePipeline({layout:"auto",compute:{module:o(Et),entryPoint:"main"}}),this.#u=n.createComputePipeline({layout:"auto",compute:{module:o(Ut),entryPoint:"main"}})}static async create(t={}){if(!("gpu"in navigator)||!navigator.gpu)throw new Error("WebGPU unavailable. The SDK requires a WebGPU-capable browser (iOS 26+, Chrome 113+, Firefox 141+).");let r=await navigator.gpu.requestAdapter();if(!r)throw new Error("No suitable GPU adapter.");let n=await r.requestDevice();return new e(n,{maxSize:t.maxSize??1152,windowDivisor:t.windowDivisor??8,threshold:t.threshold??.85})}#g(t,r){let n=Math.min(1,this.#e/Math.max(t,r));if(n>=1){let s=i=>Math.min(this.#e,Math.max(32,Math.ceil(i/32)*32));return{w:s(t),h:s(r)}}let o=s=>Math.max(32,Math.floor(s*n/32)*32);return{w:o(t),h:o(r)}}#_(t,r){let n=this.#t,o=t*r,s=Math.ceil(o/32)*4,i=this.#a;i&&(i.uniform.destroy(),i.luma.destroy(),i.blurA.destroy(),i.blurB.destroy(),i.small.destroy(),i.smallScratch.destroy(),i.smallGlobal.destroy(),i.mask.destroy(),i.staging.destroy());let a=S*S*4;this.#a={uniform:n.createBuffer({size:256*we,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),luma:n.createBuffer({size:o*4,usage:GPUBufferUsage.STORAGE}),blurA:n.createBuffer({size:o*4,usage:GPUBufferUsage.STORAGE}),blurB:n.createBuffer({size:o*4,usage:GPUBufferUsage.STORAGE}),small:n.createBuffer({size:a,usage:GPUBufferUsage.STORAGE}),smallScratch:n.createBuffer({size:a,usage:GPUBufferUsage.STORAGE}),smallGlobal:n.createBuffer({size:a,usage:GPUBufferUsage.STORAGE}),mask:n.createBuffer({size:s,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}),staging:n.createBuffer({size:s,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST})},this.#d=t,this.#h=r}setThreshold(t){this.#i=t}async process(t){let r=t.videoWidth??t.width,n=t.videoHeight??t.height;if(!r||!n)throw new Error("Frame not ready.");let{w:o,h:s}=this.#g(r,n);(o!==this.#d||s!==this.#h||r!==this.#l||n!==this.#f)&&(this.#s?.destroy(),this.#s=this.#t.createTexture({size:[r,n],format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT}),this.#l=r,this.#f=n,this.#_(o,s));let i=this.#a,a=this.#s;if(!i||!a)throw new Error("Unreachable: buffers missing.");let c=this.#t,u=Math.max(1,Math.floor(Math.min(o,s)/(2*this.#o))),h=c.queue;h.writeBuffer(i.uniform,E.luma,new Uint32Array([o,s,r,n])),h.writeBuffer(i.uniform,E.blurH,new Uint32Array([o,s,u,0])),h.writeBuffer(i.uniform,E.blurV,new Uint32Array([o,s,u,1])),h.writeBuffer(i.uniform,E.binarize,new Uint32Array([o,s,Math.round(this.#i*1e3),1e3,500,1e3,S,S])),h.writeBuffer(i.uniform,E.lumaSmall,new Uint32Array([S,S])),h.writeBuffer(i.uniform,E.globalH,new Uint32Array([S,S,S,0])),h.writeBuffer(i.uniform,E.globalV,new Uint32Array([S,S,S,1])),c.queue.copyExternalImageToTexture({source:t},{texture:a},[r,n]);let w=c.createCommandEncoder(),g=Math.ceil(o*s/32)*4;w.clearBuffer(i.mask,0,g);let _=(d,m=16)=>({buffer:i.uniform,offset:d,size:m}),l=(d,m,y=o,x=s)=>{let b=w.beginComputePass();b.setPipeline(d),b.setBindGroup(0,c.createBindGroup({layout:d.getBindGroupLayout(0),entries:m})),b.dispatchWorkgroups(Math.ceil(y/8),Math.ceil(x/8)),b.end()};l(this.#n,[{binding:0,resource:a.createView()},{binding:1,resource:this.#c},{binding:2,resource:_(E.luma)},{binding:3,resource:{buffer:i.luma}}]),l(this.#r,[{binding:0,resource:_(E.blurH)},{binding:1,resource:{buffer:i.luma}},{binding:2,resource:{buffer:i.blurA}}]),l(this.#r,[{binding:0,resource:_(E.blurV)},{binding:1,resource:{buffer:i.blurA}},{binding:2,resource:{buffer:i.blurB}}]),l(this.#n,[{binding:0,resource:a.createView()},{binding:1,resource:this.#c},{binding:2,resource:_(E.lumaSmall)},{binding:3,resource:{buffer:i.small}}],S,S),l(this.#r,[{binding:0,resource:_(E.globalH)},{binding:1,resource:{buffer:i.small}},{binding:2,resource:{buffer:i.smallScratch}}],S,S),l(this.#r,[{binding:0,resource:_(E.globalV)},{binding:1,resource:{buffer:i.smallScratch}},{binding:2,resource:{buffer:i.smallGlobal}}],S,S),l(this.#u,[{binding:0,resource:_(E.binarize,32)},{binding:1,resource:{buffer:i.luma}},{binding:2,resource:{buffer:i.blurB}},{binding:3,resource:{buffer:i.mask}},{binding:4,resource:{buffer:i.smallGlobal}}]),w.copyBufferToBuffer(i.mask,0,i.staging,0,g),c.queue.submit([w.finish()]),await i.staging.mapAsync(GPUMapMode.READ);let f=new Uint8Array(i.staging.getMappedRange().slice(0));return i.staging.unmap(),{width:o,height:s,data:f,bytesPerRow:o/8}}destroy(){this.#s?.destroy();let t=this.#a;t&&(t.luma.destroy(),t.blurA.destroy(),t.blurB.destroy(),t.small.destroy(),t.smallScratch.destroy(),t.smallGlobal.destroy(),t.mask.destroy(),t.staging.destroy(),t.uniform.destroy()),this.#t.destroy()}};var Q=class{#t;#e;#o;#i;#n;constructor(t){this.#o=t.maxSize,this.#i=t.windowDivisor,this.#n=t.threshold,this.#t=typeof document>"u"?new OffscreenCanvas(1,1):document.createElement("canvas"),this.#e=this.#t.getContext("2d",{willReadFrequently:!0})}setThreshold(t){this.#n=t}#r(t,r){let n=Math.min(1,this.#o/Math.max(t,r));if(n>=1){let s=i=>Math.min(this.#o,Math.max(32,Math.ceil(i/32)*32));return{w:s(t),h:s(r)}}let o=s=>Math.max(32,Math.floor(s*n/32)*32);return{w:o(t),h:o(r)}}async process(t){let r=t.videoWidth??t.width,n=t.videoHeight??t.height;if(!r||!n)throw new Error("Frame not ready.");let{w:o,h:s}=this.#r(r,n);(o!==this.#t.width||s!==this.#t.height)&&(this.#t.width=o,this.#t.height=s),o>=r&&s>=n?(this.#e.fillStyle="#fff",this.#e.fillRect(0,0,o,s),this.#e.drawImage(t,0,0)):this.#e.drawImage(t,0,0,o,s);let i=this.#e.getImageData(0,0,o,s).data,a=new Float32Array(o*s);for(let f=0;f<o*s;f++)a[f]=(.299*(i[f*4]??0)+.587*(i[f*4+1]??0)+.114*(i[f*4+2]??0))/255;let c=new Float64Array((o+1)*(s+1));for(let f=0;f<s;f++)for(let d=0;d<o;d++)c[(f+1)*(o+1)+d+1]=(a[f*o+d]??0)+(c[f*(o+1)+d+1]??0)+(c[(f+1)*(o+1)+d]??0)-(c[f*(o+1)+d]??0);let u=Math.max(1,Math.floor(Math.min(o,s)/(2*this.#i))),h=Math.ceil(o/8/4)*4,w=new Uint8Array(h*s),g=this.#n,_=0;for(let f=0;f<o*s;f++)_+=a[f]??0;let l=.5*(_/(o*s));for(let f=0;f<s;f++){let d=Math.max(0,f-u),m=Math.min(s-1,f+u),y=f*h;for(let x=0;x<o;x++){let b=Math.max(0,x-u),v=Math.min(o-1,x+u),R=(m-d+1)*(v-b+1),k=(c[(m+1)*(o+1)+v+1]??0)-(c[d*(o+1)+v+1]??0)-(c[(m+1)*(o+1)+b]??0)+(c[d*(o+1)+b]??0),L=a[f*o+x]??0,D=k/R;if(L<g*D||L<l&&L<=D+8/255){let C=y+(x>>3);w[C]=(w[C]??0)|1<<(x&7)}}}return{width:o,height:s,data:w,bytesPerRow:h}}destroy(){}};async function nt(e={}){let t={maxSize:e.maxSize??1056,windowDivisor:e.windowDivisor??20,threshold:e.threshold??.92};if("gpu"in navigator&&navigator.gpu)try{let n=await J.create(t);return{process:o=>n.process(o),destroy:()=>n.destroy(),kind:"gpu",setThreshold:o=>n.setThreshold(o)}}catch(n){if(e.requireGpu)throw n;console.warn("GPU binarizer unavailable, falling back to CPU:",n)}else if(e.requireGpu)throw new Error("GPU binarizer required but WebGPU is unavailable in this context.");let r=new Q(t);return{process:n=>r.process(n),destroy:()=>r.destroy(),kind:"cpu",setThreshold:n=>r.setThreshold(n)}}var W=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Tt.unregister(this),t}free(){let t=this.__destroy_into_raw();p.__wbg_barcodescanner_free(t,0)}decode(t,r,n){try{let a=p.__wbindgen_add_to_stack_pointer(-16),c=q(n,p.__wbindgen_export),u=A;p.barcodescanner_decode(a,this.__wbg_ptr,t,r,c,u);var o=M().getInt32(a+0,!0),s=M().getInt32(a+4,!0),i=M().getInt32(a+8,!0);if(i)throw I(s);return I(o)}finally{p.__wbindgen_add_to_stack_pointer(16)}}decode_filtered(t,r,n,o){try{let c=p.__wbindgen_add_to_stack_pointer(-16),u=q(n,p.__wbindgen_export),h=A,w=Rt(o,p.__wbindgen_export),g=A;p.barcodescanner_decode_filtered(c,this.__wbg_ptr,t,r,u,h,w,g);var s=M().getInt32(c+0,!0),i=M().getInt32(c+4,!0),a=M().getInt32(c+8,!0);if(a)throw I(i);return I(s)}finally{p.__wbindgen_add_to_stack_pointer(16)}}decode_filtered_still(t,r,n,o,s){try{let u=p.__wbindgen_add_to_stack_pointer(-16),h=q(n,p.__wbindgen_export),w=A,g=Rt(o,p.__wbindgen_export),_=A;p.barcodescanner_decode_filtered_still(u,this.__wbg_ptr,t,r,h,w,g,_,s);var i=M().getInt32(u+0,!0),a=M().getInt32(u+4,!0),c=M().getInt32(u+8,!0);if(c)throw I(a);return I(i)}finally{p.__wbindgen_add_to_stack_pointer(16)}}decode_still(t,r,n,o){try{let c=p.__wbindgen_add_to_stack_pointer(-16),u=q(n,p.__wbindgen_export),h=A;p.barcodescanner_decode_still(c,this.__wbg_ptr,t,r,u,h,o);var s=M().getInt32(c+0,!0),i=M().getInt32(c+4,!0),a=M().getInt32(c+8,!0);if(a)throw I(i);return I(s)}finally{p.__wbindgen_add_to_stack_pointer(16)}}constructor(){let t=p.barcodescanner_new();return this.__wbg_ptr=t,Tt.register(this,this.__wbg_ptr,this),this}qr_presence(){return p.barcodescanner_qr_presence(this.__wbg_ptr)}};Symbol.dispose&&(W.prototype[Symbol.dispose]=W.prototype.free);function Lt(e,t,r,n,o,s,i,a,c,u,h){try{let l=p.__wbindgen_add_to_stack_pointer(-16),f=X(e,p.__wbindgen_export,p.__wbindgen_export2),d=A,m=X(t,p.__wbindgen_export,p.__wbindgen_export2),y=A;p.encode_fixture_opts(l,f,d,m,y,r,n,o,s,i,a,c,u,h);var w=M().getInt32(l+0,!0),g=M().getInt32(l+4,!0),_=M().getInt32(l+8,!0);if(_)throw I(g);return I(w)}finally{p.__wbindgen_add_to_stack_pointer(16)}}function Pt(e,t,r,n,o,s,i,a,c,u,h){try{let l=p.__wbindgen_add_to_stack_pointer(-16),f=X(e,p.__wbindgen_export,p.__wbindgen_export2),d=A,m=q(t,p.__wbindgen_export),y=A;p.encode_fixture_raw_opts(l,f,d,m,y,r,n,o,s,i,a,c,u,h);var w=M().getInt32(l+0,!0),g=M().getInt32(l+4,!0),_=M().getInt32(l+8,!0);if(_)throw I(g);return I(w)}finally{p.__wbindgen_add_to_stack_pointer(16)}}function me(){return{__proto__:null,"./barcode_wasm_bg.js":{__proto__:null,__wbg_Error_30c8987f7c2ed4e2:function(t,r){let n=Error(rt(t,r));return B(n)},__wbg_String_8564e559799eccda:function(t,r){let n=String(G(r)),o=X(n,p.__wbindgen_export,p.__wbindgen_export2),s=A;M().setInt32(t+4,s,!0),M().setInt32(t+0,o,!0)},__wbg___wbindgen_string_get_0380ccaa2f57f0d9:function(t,r){let n=G(r),o=typeof n=="string"?n:void 0;var s=ye(o)?0:X(o,p.__wbindgen_export,p.__wbindgen_export2),i=A;M().setInt32(t+4,i,!0),M().setInt32(t+0,s,!0)},__wbg___wbindgen_throw_41e9ee4f547fc59a:function(t,r){throw new Error(rt(t,r))},__wbg_new_617a8cdb8bb1130e:function(){let t=new Object;return B(t)},__wbg_new_ee2291f50781bf1d:function(){let t=new Array;return B(t)},__wbg_now_aa4ccb83129e9e55:function(){return Date.now()},__wbg_set_6be42768c690e380:function(t,r,n){G(t)[I(r)]=I(n)},__wbg_set_bea140a88be9b277:function(t,r,n){G(t)[r>>>0]=I(n)},__wbindgen_generic_0000000000000001:function(t){return B(t)},__wbindgen_generic_0000000000000002:function(t,r){let n=rt(t,r);return B(n)},__wbindgen_generic_0000000000000003:function(t){let r=BigInt.asUintN(64,t);return B(r)},__wbindgen_object_clone_ref:function(t){let r=G(t);return B(r)},__wbindgen_object_drop_ref:function(t){I(t)}}}}var Tt=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>p.__wbg_barcodescanner_free(e,1));function B(e){j===P.length&&P.push(P.length+1);let t=j;return j=P[t],P[t]=e,t}function be(e){e<1028||(P[e]=j,j=e)}var O=null;function M(){return(O===null||O.buffer.detached===!0||O.buffer.detached===void 0&&O.buffer!==p.memory.buffer)&&(O=new DataView(p.memory.buffer)),O}function rt(e,t){return Me(e>>>0,t)}var N=null;function H(){return(N===null||N.byteLength===0)&&(N=new Uint8Array(p.memory.buffer)),N}function G(e){return P[e]}var P=new Array(1024).fill(void 0);P.push(void 0,null,!0,!1);var j=P.length;function ye(e){return e==null}function q(e,t){let r=t(e.length*1,1)>>>0;return H().set(e,r/1),A=e.length,r}function Rt(e,t){let r=t(e.length*4,4)>>>0,n=M();for(let o=0;o<e.length;o++)n.setUint32(r+4*o,B(e[o]),!0);return A=e.length,r}function X(e,t,r){if(r===void 0){let a=V.encode(e),c=t(a.length,1)>>>0;return H().subarray(c,c+a.length).set(a),A=a.length,c}let n=e.length,o=t(n,1)>>>0,s=H(),i=0;for(;i<n;i++){let a=e.charCodeAt(i);if(a>127)break;s[o+i]=a}if(i!==n){i!==0&&(e=e.slice(i)),o=r(o,n,n=i+e.length*3,1)>>>0;let a=H().subarray(o+i,o+n),c=V.encodeInto(e,a);i+=c.written,o=r(o,n,i,1)>>>0}return A=i,o}function I(e){let t=G(e);return be(e),t}var Z=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});Z.decode();var xe=2146435072,ot=0;function Me(e,t){return ot+=t,ot>=xe&&(Z=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),Z.decode(),ot=t),Z.decode(H().subarray(e,e+t))}var V=new TextEncoder;"encodeInto"in V||(V.encodeInto=function(e,t){let r=V.encode(e);return t.set(r),{read:e.length,written:r.length}});var A=0,ve,Se,p;function Ie(e,t){return Se=e,p=e.exports,ve=t,O=null,N=null,p}async function Ae(e,t){if(typeof Response=="function"&&e instanceof Response){if(!e.ok)throw new Error(`failed to fetch Wasm: ${e.status} ${e.statusText} fetching '${e.url}'`);if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(o){if(r(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",o);else throw o}let n=await e.arrayBuffer();return await WebAssembly.instantiate(n,t)}else{let n=await WebAssembly.instantiate(e,t);return n instanceof WebAssembly.Instance?{instance:n,module:e}:n}function r(n){switch(n){case"basic":case"cors":case"default":return!0}return!1}}async function kt(e){if(p!==void 0)return p;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0&&(e=new URL("barcode_wasm_bg.wasm",import.meta.url));let t=me();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));let{instance:r,module:n}=await Ae(await e,t);return Ie(r,n)}var Dt=new URL("wasm.wasm",import.meta.url).href;var Ee=()=>{try{let t=new URL(import.meta.url),r=t.searchParams.get("wasm");if(r)return r;let n=t.hash.replace(/^#/,"");if(n.startsWith("wasm=")){let o=decodeURIComponent(n.slice(5));if(o)return o}}catch{}let e=globalThis.__barcodeWasm;return typeof e=="string"?e:Dt},it=null;function Bt(){return it||(it=(async()=>(await kt(Ee()),new W))()),it}function z(e,t,r,n={}){let o=n.still===!0,s=n.latency??5e3;return(r?.length?o?e.decode_filtered_still(t.width,t.height,t.data,r,s):e.decode_filtered(t.width,t.height,t.data,r):o?e.decode_still(t.width,t.height,t.data,s):e.decode(t.width,t.height,t.data)).map(a=>({text:a.text,raw:a.raw instanceof Uint8Array?a.raw:Uint8Array.from(a.raw??[]),symbology:a.symbology,position:[0,1,2,3].map(c=>({x:a.quad[c*2]??0,y:a.quad[c*2+1]??0}))}))}var Ue=e=>{let t=e;return{w:Number(t.width??t.videoWidth??0),h:Number(t.height??t.videoHeight??0)}};async function Ct(e,t){let{w:r,h:n}=Ue(e);if(!r||!n)throw new TypeError("rotateDrawable: source has no dimensions");let o=t*Math.PI/180,s=Math.ceil(Math.abs(r*Math.cos(o))+Math.abs(n*Math.sin(o))),i=Math.ceil(Math.abs(r*Math.sin(o))+Math.abs(n*Math.cos(o))),a=typeof OffscreenCanvas<"u"?new OffscreenCanvas(s,i):Object.assign(document.createElement("canvas"),{width:s,height:i}),c=a.getContext("2d");if(!c)throw new TypeError("rotateDrawable: no 2d context");return c.fillStyle="#fff",c.fillRect(0,0,s,i),c.imageSmoothingEnabled=!0,c.imageSmoothingQuality="high",c.translate(s/2,i/2),c.rotate(o),c.drawImage(e,-r/2,-n/2,r,n),{canvas:a,width:s,height:i,map:(h,w,g)=>{let _=s/h,l=i/w,f=Math.cos(-o),d=Math.sin(-o);return g.map(({x:m,y})=>{let x=m*_-s/2,b=y*l-i/2;return{x:f*x-d*b+r/2,y:d*x+f*b+n/2}})}}}var st=(e,t,r)=>(e.data[r*e.bytesPerRow+(t>>3)]??0)>>(t&7)&1,Te=(e,t,r)=>{let n=new Uint8Array(e.length),o=[];for(let s=0;s<e.length;s++){if(!e[s]||n[s])continue;let i=[],a=[s];for(n[s]=1;a.length;){let c=a.pop();i.push(c);let u=c%t,h=c/t|0;for(let w=-1;w<=1;w++)for(let g=-1;g<=1;g++){if(!g&&!w)continue;let _=u+g,l=h+w;if(_<0||l<0||_>=t||l>=r)continue;let f=l*t+_;e[f]&&!n[f]&&(n[f]=1,a.push(f))}}o.push(i)}return o},Re=(e,t,r,n,o)=>{let s=Math.max(2,Math.round(Math.min(n-t,o-r)/24)),i=0,a=0;for(let c=r;c<o;c+=s)for(let u=t;u<n;u+=s)a++,i+=st(e,u,c);return a?i/a:0};function Ot(e,t,r,n=4){if(!(e.width>0&&e.height>0&&t>0&&r>0))return[];let o=Math.ceil(e.width/24),s=Math.ceil(e.height/24),i=new Uint8Array(o*s);for(let g=0;g<s;g++){let _=g*24,l=Math.min(e.height,_+24);for(let f=0;f<o;f++){let d=f*24,m=Math.min(e.width,d+24),y=0,x=0;for(let b=_;b<l;b+=3)for(let v=d;v<m;v+=3)x++,y+=st(e,v,b);x&&y/x>=.045&&(i[g*o+f]=1)}}let a=t<=e.width?1:t/e.width,c=r<=e.height?1:r/e.height,u=[],h=e.width*e.height;for(let g of Te(i,o,s)){let _=o,l=s,f=0,d=0;for(let U of g){let T=U%o,pt=U/o|0;_=Math.min(_,T),l=Math.min(l,pt),f=Math.max(f,T),d=Math.max(d,pt)}let m=_*24,y=l*24,x=Math.min(e.width,(f+1)*24),b=Math.min(e.height,(d+1)*24),v=x-m,R=b-y;if(v<8||R<8||v*R>.72*h)continue;let k=Re(e,m,y,x,b);if(k<.045)continue;let L=x,D=b,C=m,Y=y;for(let U=y;U<b;U++)for(let T=m;T<x;T++)st(e,T,U)&&(T<L&&(L=T),T>C&&(C=T),U<D&&(D=U),U>Y&&(Y=U));if(C<L||Y<D)continue;let se=g.length/((f-_+1)*(d-l+1)),ae=k*(.55+.45*se)*(1+Math.log10(1+v*R)/8),ct=(C-L+1)*a,ut=(Y-D+1)*c,dt=Math.max(8,Math.round(ct*.12)),lt=Math.max(8,Math.round(ut*.12)),ft=Math.max(0,Math.round(L*a)-dt),ht=Math.max(0,Math.round(D*c)-lt),gt=Math.min(t-ft,Math.round(ct)+2*dt),_t=Math.min(r-ht,Math.round(ut)+2*lt);gt<8||_t<8||u.push({x:ft,y:ht,w:gt,h:_t,score:ae})}u.sort((g,_)=>_.score-g.score);let w=[];for(let g of u)if(w.some(l=>{let f=Math.max(0,Math.min(g.x+g.w,l.x+l.w)-Math.max(g.x,l.x)),d=Math.max(0,Math.min(g.y+g.h,l.y+l.h)-Math.max(g.y,l.y));return f*d>.6*Math.min(g.w*g.h,l.w*l.h)})||w.push(g),w.length>=n)break;return w}var Le=e=>{let t=e;return{w:Number(t.width??t.videoWidth??0),h:Number(t.height??t.videoHeight??0)}};async function zt(e,t){let{w:r,h:n}=Le(e);if(!r||!n)throw new TypeError("cropDrawable: source has no dimensions");let o=Math.max(0,Math.min(r-1,Math.round(t.x))),s=Math.max(0,Math.min(n-1,Math.round(t.y))),i=Math.max(1,Math.min(r-o,Math.round(t.w))),a=Math.max(1,Math.min(n-s,Math.round(t.h))),c=typeof OffscreenCanvas<"u"?new OffscreenCanvas(i,a):Object.assign(document.createElement("canvas"),{width:i,height:a}),u=c.getContext("2d");if(!u)throw new TypeError("cropDrawable: no 2d context");return u.drawImage(e,o,s,i,a,0,0,i,a),{canvas:c,width:i,height:a,x:o,y:s,map:(h,w,g)=>{let _=i<=h?1:i/h,l=a<=w?1:a/w;return g.map(({x:f,y:d})=>({x:o+f*_,y:s+d*l}))}}}var Pe=["qrcode","microqr","aztec","databarstk"],ke=["qrcode","microqr","upca","datamatrix","aztec","pdf417","ean13","ean8","upce","code39","code93","code128","itf","codabar","databar","databarltd","databarstk"],Gt=new Set(["datamatrix","pdf417"]),De=["upca","ean13","ean8","upce","code39","code93","code128","itf","codabar","databar","databarltd"],Be=new Set(["qrcode","microqr","datamatrix","aztec","pdf417","databarstk"]),Ce=e=>e.toLowerCase().replace(/[^a-z0-9]/g,""),Wt=e=>Be.has(Ce(e)),Ft=e=>{if(!e?.length)return!0;let t=e.map(n=>n.trim().toLowerCase());return t.some(n=>Gt.has(n))&&t.some(n=>!Gt.has(n))},Nt=(e,t=!1)=>(e?.length?e:ke).filter(r=>{let n=r.trim().toLowerCase();return Pe.includes(n)||t&&De.includes(n)}),qt=-1/0,Ht=e=>e-qt>=250,jt=e=>{qt=e};var at=2112,Oe=nt({maxSize:1056,windowDivisor:20,threshold:.92}),ze=null,Ge=()=>ze??=nt({maxSize:at,windowDivisor:20,threshold:.92}),ie=Bt(),We=ie,Vt=!1,Xt=[],Yt=new Set(["datamatrix","aztec","pdf417"]),Kt=0,$t=new Set(["upca","ean13","ean8","upce","code39","code93","code128","itf","codabar","databar","databarltd"]),Jt=e=>e==null?[...$t]:e.filter(t=>$t.has(String(t).toLowerCase())),Fe=(e,t,r)=>{let n=t/2,o=r/2,s=Math.hypot(t,r)/2||1,i=a=>{let c=0;for(let u=0;u<a.length;u++){let h=a[u]??{x:0,y:0},w=a[(u+1)%a.length]??h;c+=h.x*w.y-w.x*h.y}return Math.abs(c)/2};for(let a of e){let c=0,u=0;for(let w of a.position)c+=w.x,u+=w.y;let h=Math.hypot(c/a.position.length-n,u/a.position.length-o)/s;a.score=Math.max(0,Math.min(1,1-h))}return e.sort((a,c)=>(c.score??0)-(a.score??0)||i(c.position)-i(a.position))},Ne=250,Qt=-1/0,Zt=0,te=(e,t,r,n,o,s)=>{if(!e.length)return e;let i=o<=n.width?1:n.width/o,a=s<=n.height?1:n.height/s;for(let c of e){if(!c.position?.length)continue;let u=t.map(r.width,r.height,c.position);c.position=u.map(h=>({x:h.x*i,y:h.y*a}))}return e},ee=async(e,t,r,n,o,s,i,a)=>{let c=r.width,u=r.height;if(!c||!u)return[];let h=Ot(n,c,u,i);if(!h.length)return[];t.setThreshold?.(.92);for(let w of h){let g=a-performance.now();if(g<=0)break;let _=await zt(r,w),l=await t.process(_.canvas),f=s.still===!0?{still:!0,latency:Math.max(250,Math.min(s.latency??5e3,g))}:s,d=z(e,l,o,f);if(d.length)return te(d,_,l,n,c,u);let m=a-performance.now();if(m<=0)break;let y=f.still===!0?{...f,latency:Math.max(250,Math.min(f.latency??5e3,m))}:f,x=l.data.map(v=>~v),b=z(e,{...l,data:x},o,y);if(b.length)return te(b,_,l,n,c,u)}return[]},ne={async decode(e){let t=!0;try{let{bitmap:r,formats:n,still:o,accuracy:s,latency:i}=e??{};if(!r)throw new Error("decode: missing bitmap");let a=n;if(o!==!0&&Ft(n)&&(t=Ht(performance.now()),!t)){if(a=Nt(n,!Vt),a.length){let d=new Set(a);for(let m of Xt){let y=String(m).toLowerCase().replace(/[^a-z0-9]/g,"");y&&!d.has(y)&&(d.add(y),a.push(y))}}if(!a.length)return{type:"result",codes:[],decodeMs:0}}let c=await(o===!0?Ge():Oe),u=await ie,h=performance.now(),w=r;if(o===!0){let d=Math.max(r.width,r.height);if(d>at){let m=at/d,y=Math.max(1,Math.round(r.width*m)),x=Math.max(1,Math.round(r.height*m)),b=new OffscreenCanvas(y,x),v=b.getContext("2d");v&&(v.imageSmoothingEnabled=!0,v.imageSmoothingQuality="high",v.drawImage(r,0,0,y,x),w=b)}}let g=await c.process(w),_={still:o,latency:i},l=[],f=!1;if(o===!0&&typeof c.setThreshold=="function"){let d=Jt(a);if(d.length){let m=s==="low"?[.92]:[.92,.82,.7];for(let y of m){let x=g;y!==.92&&(c.setThreshold(y),x=await c.process(r));let b=z(u,x,d,_);if(b.length){l=b,f=!0;break}}c.setThreshold(.92)}}if(o===!0&&!f){let d=Jt(a);if(d.length){let m=await ee(u,c,r,g,d,_,2,Math.min(performance.now()+900,h+(i??5e3)));m.length&&(l=m,f=!0)}}if(!f){l=z(u,g,a,_);let d=performance.now()-h;if((s==="high"||s==="auto"&&l.length===0&&d<(o?2500:220))&&typeof c.setThreshold=="function"){c.setThreshold(.82);let y=await c.process(r);c.setThreshold(.92);let x=new Set(l.map(b=>b.symbology+"\0"+b.text));l=l.concat(z(u,y,a,_).filter(b=>!x.has(b.symbology+"\0"+b.text)))}}if(l.length===0&&(o===!0||n!=null)){let d=a==null?[...Yt]:a.filter(x=>Yt.has(String(x).toLowerCase())),m=performance.now(),y=o===!0||d.length>0&&m-Kt>=500;if(d.length>0&&y){Kt=m,c.setThreshold(.92);for(let x of[45,-45]){let b=await Ct(r,x),v=await c.process(b.canvas),R=z(u,v,d,_);if(R.length){for(let k of R)k.position?.length&&(k.position=b.map(v.width,v.height,k.position));l=R;break}}}}if(l.length===0){let d=performance.now();if(o===!0||d<=Zt||d-Qt>=Ne){Qt=d;let m=o===!0?h+(i??5e3):d+120,y=await ee(u,c,r,g,a,_,o===!0?4:2,m);y.length&&(l=y,Zt=d+600)}}return t&&(Vt=l.some(d=>Wt(d.symbology))),Xt=l.map(d=>d.symbology),{type:"result",codes:Fe(l,g.width,g.height),decodeMs:Math.round(performance.now()-h),frameW:g.width,frameH:g.height,partial:!t,qrPresence:!a?.length||a.some(m=>m==="qr"||m==="qrcode")?u.qr_presence():void 0}}catch(r){return console.error("decode failed:",r),{type:"error",message:String(r instanceof Error?r.message:r)}}finally{t&&jt(performance.now()),e?.bitmap?.close?.()}},async encode(e){await We;let t=e.module??4,r=e.height??30*t,n=e.ec??-1,o=e.mask??-1,s=e.version??0,i=e.level??-1,a=e.columns??0,c=e.rows??0,u=e.cols??0,h=e.raw instanceof Uint8Array&&e.raw.length?Pt(e.symbology,e.raw,t,r,n,o,s,i,a,c,u):Lt(e.symbology,e.text??"",t,r,n,o,s,i,a,c,u),w=h.data instanceof Uint8Array?h.data:Uint8Array.from(h.data);return this[$]={transfer:[w.buffer]},{width:h.width,height:h.height,bytesPerRow:h.bytesPerRow,data:w}}},re=Promise.resolve(),oe=e=>function(t){let r=re.then(()=>e.call(this,t));return re=r.then(()=>{},()=>{}),r},qe=()=>({decode:oe(ne.decode),encode:oe(ne.encode)}),Cn=It().then(e=>Mt(e,qe()));export{Cn as default};
package/package.json CHANGED
@@ -1,6 +1,96 @@
1
1
  {
2
2
  "name": "@webreflection/barcode",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "WebGPU-accelerated barcode and QR scanning for the web: clean-room Rust/WASM decoders, native JS with JSDoc types, one static dist folder.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Andrea Giammarchi <andrea.giammarchi@gmail.com> (https://github.com/WebReflection)",
8
+ "homepage": "https://webreflection.github.io/barcode/",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/WebReflection/barcode.git"
12
+ },
13
+ "keywords": [
14
+ "barcode",
15
+ "qrcode",
16
+ "qr",
17
+ "datamatrix",
18
+ "aztec",
19
+ "pdf417",
20
+ "ean13",
21
+ "code128",
22
+ "webgpu",
23
+ "wasm",
24
+ "scanner",
25
+ "camera"
26
+ ],
27
+ "main": "./dist/index.js",
28
+ "types": "./dist/index.d.ts",
29
+ "files": [
30
+ "./dist",
31
+ "./README.md",
32
+ "./LICENSE"
33
+ ],
34
+ "exports": {
35
+ ".": {
36
+ "types": "./dist/index.d.ts",
37
+ "default": "./dist/index.js"
38
+ },
39
+ "./index": {
40
+ "types": "./dist/index.d.ts",
41
+ "default": "./dist/index.js"
42
+ },
43
+ "./main": {
44
+ "types": "./dist/main.d.ts",
45
+ "default": "./dist/main.js"
46
+ },
47
+ "./worker": {
48
+ "types": "./dist/worker.d.ts",
49
+ "default": "./dist/worker.js"
50
+ },
51
+ "./css": "./dist/css.css",
52
+ "./wasm": "./dist/wasm.wasm",
53
+ "./package.json": "./package.json"
54
+ },
55
+ "scripts": {
56
+ "dev": "vite",
57
+ "build": "node tools/build.mjs",
58
+ "build:demo": "node tools/build.mjs --demo",
59
+ "demo": "node tools/build.mjs --demo",
60
+ "check": "node node_modules/typescript/bin/tsc --noEmit",
61
+ "types": "node node_modules/typescript/bin/tsc -p tsconfig.types.json",
62
+ "wasm": "wasm-pack build ../../crates/barcode-wasm --target web --out-dir ../../packages/web/src/wasm/pkg",
63
+ "artifacts": "node tools/build-artifacts.mjs",
64
+ "test": "node tools/e2e/playwright.mjs",
65
+ "test:ci": "node tools/e2e/playwright.mjs --ci",
66
+ "test:phone": "node tools/e2e/fakecam.mjs --all --port 9222",
67
+ "test:field": "node tools/e2e/field.mjs --port 9225",
68
+ "test:field:live": "node tools/e2e/field.mjs --port 9225 --mode live",
69
+ "serve:demo": "node tools/serve-demo.mjs",
70
+ "serve:iphone": "node tools/serve-demo.mjs --https",
71
+ "preview": "vite preview",
72
+ "test:iphone": "node tools/e2e/playwright.mjs --browser iphone",
73
+ "test:webkit": "node tools/e2e/playwright.mjs --browser webkit",
74
+ "prepublishOnly": "npm run build",
75
+ "build:docs": "node tools/build-docs.mjs",
76
+ "serve:docs": "node tools/serve-demo.mjs --docs",
77
+ "serve:docs:iphone": "node tools/serve-demo.mjs --docs --https",
78
+ "test:ci:chromium": "node tools/e2e/playwright.mjs --ci --browser chromium",
79
+ "test:ci:webkit": "node tools/e2e/playwright.mjs --ci --browser webkit"
80
+ },
81
+ "devDependencies": {
82
+ "@webgpu/types": "^0.1.64",
83
+ "playwright": "^1.65.1",
84
+ "typescript": "^5.6.0",
85
+ "vite": "^6.0.0",
86
+ "vite-plugin-singlefile": "^2.3.3"
87
+ },
88
+ "dependencies": {
89
+ "@webreflection/bindings": "^0.3.0",
90
+ "@webreflection/utils": "^0.4.20",
91
+ "html-escaper": "^3.0.3"
92
+ },
93
+ "engines": {
94
+ "node": ">=24"
95
+ }
96
+ }