qr-core 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.
- package/LICENSE +21 -0
- package/README.md +126 -0
- package/dist/bench/bench.d.ts +1 -0
- package/dist/bench/bench.js +38 -0
- package/dist/src/api/index.d.ts +9 -0
- package/dist/src/api/index.js +224 -0
- package/dist/src/core/bit-buffer.d.ts +11 -0
- package/dist/src/core/bit-buffer.js +53 -0
- package/dist/src/core/error.d.ts +8 -0
- package/dist/src/core/error.js +16 -0
- package/dist/src/core/gf.d.ts +4 -0
- package/dist/src/core/gf.js +52 -0
- package/dist/src/core/rs.d.ts +1 -0
- package/dist/src/core/rs.js +60 -0
- package/dist/src/encoding/bitstream.d.ts +7 -0
- package/dist/src/encoding/bitstream.js +68 -0
- package/dist/src/encoding/encoders.d.ts +13 -0
- package/dist/src/encoding/encoders.js +54 -0
- package/dist/src/encoding/interleave.d.ts +5 -0
- package/dist/src/encoding/interleave.js +49 -0
- package/dist/src/encoding/segmentation.d.ts +12 -0
- package/dist/src/encoding/segmentation.js +43 -0
- package/dist/src/index.d.ts +3 -0
- package/dist/src/index.js +3 -0
- package/dist/src/layout/patterns.d.ts +12 -0
- package/dist/src/layout/patterns.js +120 -0
- package/dist/src/mapping/zigzag.d.ts +5 -0
- package/dist/src/mapping/zigzag.js +28 -0
- package/dist/src/mask/patterns.d.ts +6 -0
- package/dist/src/mask/patterns.js +13 -0
- package/dist/src/mask/penalty.d.ts +5 -0
- package/dist/src/mask/penalty.js +173 -0
- package/dist/src/mask/selection.d.ts +12 -0
- package/dist/src/mask/selection.js +178 -0
- package/dist/src/matrix/bit-matrix.d.ts +46 -0
- package/dist/src/matrix/bit-matrix.js +139 -0
- package/dist/src/spec/bch.d.ts +11 -0
- package/dist/src/spec/bch.js +30 -0
- package/dist/src/spec/constants.d.ts +40 -0
- package/dist/src/spec/constants.js +37 -0
- package/dist/src/spec/tables.d.ts +20 -0
- package/dist/src/spec/tables.js +1099 -0
- package/dist/src/strategies/index.d.ts +3 -0
- package/dist/src/strategies/index.js +3 -0
- package/dist/src/strategies/mask.d.ts +16 -0
- package/dist/src/strategies/mask.js +9 -0
- package/dist/src/strategies/segmentation.d.ts +12 -0
- package/dist/src/strategies/segmentation.js +41 -0
- package/dist/src/strategies/version.d.ts +12 -0
- package/dist/src/strategies/version.js +22 -0
- package/dist/src/types/index.d.ts +51 -0
- package/dist/src/types/index.js +1 -0
- package/dist/tests/golden/golden.test.d.ts +1 -0
- package/dist/tests/golden/golden.test.js +26 -0
- package/dist/tests/unit/api.test.d.ts +1 -0
- package/dist/tests/unit/api.test.js +35 -0
- package/dist/tests/unit/bit-matrix.test.d.ts +1 -0
- package/dist/tests/unit/bit-matrix.test.js +46 -0
- package/dist/tests/unit/core.test.d.ts +1 -0
- package/dist/tests/unit/core.test.js +88 -0
- package/dist/tests/unit/encoding.test.d.ts +1 -0
- package/dist/tests/unit/encoding.test.js +63 -0
- package/dist/tests/unit/layout.test.d.ts +1 -0
- package/dist/tests/unit/layout.test.js +62 -0
- package/dist/tests/unit/masking.test.d.ts +1 -0
- package/dist/tests/unit/masking.test.js +31 -0
- package/package.json +45 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 QR Core Contributors
|
|
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
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# qr-core
|
|
2
|
+
|
|
3
|
+
Deterministic, zero-dependency QR Code Model 2 encoder for TypeScript/JavaScript. Outputs a binary module matrix and metadata only (no rendering), aligned with the project RFC.
|
|
4
|
+
|
|
5
|
+
## Highlights
|
|
6
|
+
|
|
7
|
+
- **Deterministic output**: Same input + same options ⇒ identical version, mask, and matrix.
|
|
8
|
+
- **Strict typing**: TypeScript 5.x, strict mode.
|
|
9
|
+
- **RFC-aligned**: Numeric, alphanumeric, and byte modes; versions 1–40; ECC L/M/Q/H.
|
|
10
|
+
- **Read‑only matrix**: Consumers cannot mutate the QR matrix.
|
|
11
|
+
- **Zero dependencies**: Small, portable, runtime-agnostic.
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install qr-core
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Quick Start
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import { encode } from "qr-core";
|
|
23
|
+
|
|
24
|
+
const qr = encode("HELLO WORLD");
|
|
25
|
+
console.log(qr.version, qr.mask, qr.size);
|
|
26
|
+
console.log(qr.matrix.get(0, 0));
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Usage
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
import { encode, encodeSafe } from "qr-core";
|
|
33
|
+
|
|
34
|
+
// Basic
|
|
35
|
+
const qr = encode("https://example.com");
|
|
36
|
+
|
|
37
|
+
// Advanced options
|
|
38
|
+
const qr2 = encode("https://example.com", {
|
|
39
|
+
ecc: "H", // L | M | Q | H
|
|
40
|
+
version: 5, // 1..40 or "auto"
|
|
41
|
+
mask: "auto", // 0..7 or "auto"
|
|
42
|
+
mode: "auto", // numeric | alphanumeric | byte | auto
|
|
43
|
+
charset: "utf-8", // utf-8 | iso-8859-1
|
|
44
|
+
quietZone: 4, // metadata only
|
|
45
|
+
strict: true
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
// Non-throwing variant
|
|
49
|
+
const result = encodeSafe("1234", { mode: "numeric" });
|
|
50
|
+
if (result.ok) {
|
|
51
|
+
console.log(result.value.version);
|
|
52
|
+
} else {
|
|
53
|
+
console.error(result.error.code, result.error.message);
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## API
|
|
58
|
+
|
|
59
|
+
### `encode(input, options?) => QrCode`
|
|
60
|
+
|
|
61
|
+
- `input`: `string | Uint8Array`
|
|
62
|
+
- `options`: `EncodeOptions` (see below)
|
|
63
|
+
- **throws** `QrException` on invalid input/options when `strict=true`
|
|
64
|
+
|
|
65
|
+
### `encodeSafe(input, options?) => Result<QrCode, QrError>`
|
|
66
|
+
|
|
67
|
+
Non-throwing wrapper that returns `{ ok: true, value }` or `{ ok: false, error }`.
|
|
68
|
+
|
|
69
|
+
### Types
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
export type EccLevel = "L" | "M" | "Q" | "H";
|
|
73
|
+
export type QrMode = "auto" | "byte" | "alphanumeric" | "numeric";
|
|
74
|
+
export type MaskId = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7;
|
|
75
|
+
|
|
76
|
+
export interface EncodeOptions {
|
|
77
|
+
ecc?: EccLevel; // default: "M"
|
|
78
|
+
version?: number | "auto"; // default: "auto"
|
|
79
|
+
mask?: MaskId | "auto"; // default: "auto"
|
|
80
|
+
mode?: QrMode; // default: "auto"
|
|
81
|
+
charset?: "utf-8" | "iso-8859-1";// default: "utf-8"
|
|
82
|
+
quietZone?: number; // default: 4 (metadata only)
|
|
83
|
+
strict?: boolean; // default: true
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export interface BitMatrix {
|
|
87
|
+
readonly size: number;
|
|
88
|
+
get(x: number, y: number): 0 | 1;
|
|
89
|
+
toPacked?(): Uint8Array; // row-major, MSB-first, row padded to byte
|
|
90
|
+
toRows?(): ReadonlyArray<Uint8Array>;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface QrCode {
|
|
94
|
+
version: number;
|
|
95
|
+
ecc: EccLevel;
|
|
96
|
+
mask: MaskId;
|
|
97
|
+
size: number;
|
|
98
|
+
matrix: BitMatrix;
|
|
99
|
+
meta?: QrMeta;
|
|
100
|
+
}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Matrix Packing Format
|
|
104
|
+
|
|
105
|
+
If `toPacked()` is available, it returns **row-major**, **MSB‑first** bits. Each row is padded to the next byte boundary with zero bits. Coordinates use `(0,0)` as the **top‑left** module.
|
|
106
|
+
|
|
107
|
+
## Benchmarks
|
|
108
|
+
|
|
109
|
+
Run `npm run bench` to reproduce.
|
|
110
|
+
|
|
111
|
+
| Scenario | Description | p50 (ms) | p95 (ms) |
|
|
112
|
+
| :--- | :--- | :---: | :---: |
|
|
113
|
+
| **Small** | Auto version/mask, ecc M ("HELLO WORLD") | **0.066** | **0.138** |
|
|
114
|
+
| **Medium** | Auto version/mask, ecc M (~500 bytes URL‑ish payload) | **1.262** | **1.403** |
|
|
115
|
+
| **Large** | Auto version/mask, ecc L (3000 bytes) | **3.849** | **3.984** |
|
|
116
|
+
|
|
117
|
+
> Benchmarks captured on 2026‑01‑31 with Node v24.7.0 (darwin arm64). Goal from RFC: version‑40 near‑capacity with auto‑mask < 5ms — **met**.
|
|
118
|
+
|
|
119
|
+
## Status & Roadmap
|
|
120
|
+
|
|
121
|
+
- v1 scope: numeric, alphanumeric, byte; versions 1–40; ECC L/M/Q/H; auto version/mask; deterministic output.
|
|
122
|
+
- Non‑goals in v1: rendering, Kanji, ECI, Structured Append, Micro QR.
|
|
123
|
+
|
|
124
|
+
## License
|
|
125
|
+
|
|
126
|
+
MIT
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { encode } from "../src/index.js";
|
|
2
|
+
function bench(name, fn, iterations = 100) {
|
|
3
|
+
// Warmup
|
|
4
|
+
for (let i = 0; i < 10; i++)
|
|
5
|
+
fn();
|
|
6
|
+
const times = [];
|
|
7
|
+
for (let i = 0; i < iterations; i++) {
|
|
8
|
+
const start = performance.now();
|
|
9
|
+
fn();
|
|
10
|
+
const end = performance.now();
|
|
11
|
+
times.push(end - start);
|
|
12
|
+
}
|
|
13
|
+
times.sort((a, b) => a - b);
|
|
14
|
+
const p50 = times[Math.floor(times.length * 0.5)] || 0;
|
|
15
|
+
const p95 = times[Math.floor(times.length * 0.95)] || 0;
|
|
16
|
+
const avg = times.reduce((a, b) => a + b, 0) / times.length;
|
|
17
|
+
console.log(`${name}:`);
|
|
18
|
+
console.log(` p50: ${p50.toFixed(3)}ms`);
|
|
19
|
+
console.log(` p95: ${p95.toFixed(3)}ms`);
|
|
20
|
+
console.log(` avg: ${avg.toFixed(3)}ms`);
|
|
21
|
+
}
|
|
22
|
+
async function runBenchmarks() {
|
|
23
|
+
console.log("Running benchmarks...\n");
|
|
24
|
+
const smallPayload = "HELLO WORLD";
|
|
25
|
+
bench("Small Payload (auto version/mask, ecc M)", () => {
|
|
26
|
+
encode(smallPayload, { ecc: "M" });
|
|
27
|
+
});
|
|
28
|
+
const mediumPayload = "https://example.com/search?q=" + "A".repeat(480);
|
|
29
|
+
bench("Medium Payload (~500 bytes, auto version/mask, ecc M)", () => {
|
|
30
|
+
encode(mediumPayload, { ecc: "M" });
|
|
31
|
+
});
|
|
32
|
+
const largePayload = "A".repeat(3000);
|
|
33
|
+
// Version 40-L holds 3181 data codewords; 3000 bytes fits.
|
|
34
|
+
bench("Large Payload (3000 bytes, auto version/mask, ecc L)", () => {
|
|
35
|
+
encode(largePayload, { ecc: "L" });
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
runBenchmarks();
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { EncodeOptions, QrCode, QrError, Result } from "../types/index.js";
|
|
2
|
+
/**
|
|
3
|
+
* High-level API to encode data into a QrCode structure.
|
|
4
|
+
*/
|
|
5
|
+
export declare function encode(input: string | Uint8Array, options?: EncodeOptions): QrCode;
|
|
6
|
+
/**
|
|
7
|
+
* Safe variant of encode returning a Result object.
|
|
8
|
+
*/
|
|
9
|
+
export declare function encodeSafe(input: string | Uint8Array, options?: EncodeOptions): Result<QrCode, QrError>;
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import { err, ok, QrException } from "../core/error.js";
|
|
2
|
+
import { buildBitstream } from "../encoding/bitstream.js";
|
|
3
|
+
import { interleave } from "../encoding/interleave.js";
|
|
4
|
+
import { setupFunctionPatterns, writeVersionInfo } from "../layout/patterns.js";
|
|
5
|
+
import { zigzag } from "../mapping/zigzag.js";
|
|
6
|
+
import { applyMask, writeFormatInformation } from "../mask/selection.js";
|
|
7
|
+
import { Matrix, ReadOnlyMatrix } from "../matrix/bit-matrix.js";
|
|
8
|
+
import { ALPHANUMERIC_CHARSET } from "../spec/constants.js";
|
|
9
|
+
import { BestMaskStrategy } from "../strategies/mask.js";
|
|
10
|
+
// Strategies
|
|
11
|
+
import { GreedySegmentationStrategy } from "../strategies/segmentation.js";
|
|
12
|
+
import { SmallestVersionStrategy } from "../strategies/version.js";
|
|
13
|
+
/**
|
|
14
|
+
* High-level API to encode data into a QrCode structure.
|
|
15
|
+
*/
|
|
16
|
+
export function encode(input, options = {}) {
|
|
17
|
+
const ecc = options.ecc ?? "M";
|
|
18
|
+
const quietZone = options.quietZone ?? 4;
|
|
19
|
+
const isStrict = options.strict ?? true;
|
|
20
|
+
const charset = options.charset ?? "utf-8";
|
|
21
|
+
validateOptions(options, ecc, charset, quietZone);
|
|
22
|
+
// 1. Segmentation
|
|
23
|
+
let segments;
|
|
24
|
+
if (typeof input === "string") {
|
|
25
|
+
if (options.mode && options.mode !== "auto") {
|
|
26
|
+
if (options.mode === "numeric" && !isNumeric(input)) {
|
|
27
|
+
throw new QrException("UNSUPPORTED_MODE", "Input is not representable in numeric mode.");
|
|
28
|
+
}
|
|
29
|
+
if (options.mode === "alphanumeric" && !isAlphanumeric(input)) {
|
|
30
|
+
throw new QrException("UNSUPPORTED_MODE", "Input is not representable in alphanumeric mode.");
|
|
31
|
+
}
|
|
32
|
+
segments = [{ mode: options.mode, data: input, count: input.length }];
|
|
33
|
+
}
|
|
34
|
+
else {
|
|
35
|
+
segments = GreedySegmentationStrategy.apply(input);
|
|
36
|
+
}
|
|
37
|
+
segments = prepareSegments(segments, charset, isStrict);
|
|
38
|
+
}
|
|
39
|
+
else {
|
|
40
|
+
if (options.mode && options.mode !== "auto" && options.mode !== "byte") {
|
|
41
|
+
throw new QrException("UNSUPPORTED_MODE", "Uint8Array input can only be encoded with byte mode.");
|
|
42
|
+
}
|
|
43
|
+
segments = [
|
|
44
|
+
{
|
|
45
|
+
mode: "byte",
|
|
46
|
+
data: "",
|
|
47
|
+
count: input.length,
|
|
48
|
+
bytes: input,
|
|
49
|
+
},
|
|
50
|
+
];
|
|
51
|
+
}
|
|
52
|
+
// 2. Version Selection
|
|
53
|
+
let version;
|
|
54
|
+
let minVersion = 1;
|
|
55
|
+
minVersion = SmallestVersionStrategy.select(segments, ecc);
|
|
56
|
+
if (options.version === "auto" || options.version === undefined) {
|
|
57
|
+
version = minVersion;
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
const requested = options.version;
|
|
61
|
+
if (requested < minVersion) {
|
|
62
|
+
if (isStrict) {
|
|
63
|
+
throw new QrException("DATA_TOO_LARGE", `Data requires version ${minVersion}, but ${requested} requested.`);
|
|
64
|
+
}
|
|
65
|
+
version = minVersion;
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
version = requested;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
// 3. Bitstream & ECC
|
|
72
|
+
const bitstream = buildBitstream(segments, version, ecc);
|
|
73
|
+
const interleaved = interleave(bitstream.toBytes(), version, ecc);
|
|
74
|
+
// 4. Matrix Initialization
|
|
75
|
+
const size = 21 + 4 * (version - 1);
|
|
76
|
+
const matrix = new Matrix(size);
|
|
77
|
+
setupFunctionPatterns(matrix, version);
|
|
78
|
+
// 5. Data Placement
|
|
79
|
+
zigzag(matrix, interleaved);
|
|
80
|
+
// 6. Masking
|
|
81
|
+
let maskId;
|
|
82
|
+
let penalties;
|
|
83
|
+
if (options.mask !== undefined && options.mask !== "auto") {
|
|
84
|
+
maskId = options.mask;
|
|
85
|
+
applyMask(matrix, maskId);
|
|
86
|
+
writeFormatInformation(matrix, ecc, maskId);
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
const result = BestMaskStrategy.select(matrix, ecc);
|
|
90
|
+
maskId = result.mask;
|
|
91
|
+
penalties = result.penalties;
|
|
92
|
+
}
|
|
93
|
+
// 7. Version Info (for V7+)
|
|
94
|
+
if (version >= 7) {
|
|
95
|
+
writeVersionInfo(matrix, version);
|
|
96
|
+
}
|
|
97
|
+
const meta = {
|
|
98
|
+
quietZone,
|
|
99
|
+
modeUsed: segments.length > 1 ? "mixed" : segments[0]?.mode || "byte",
|
|
100
|
+
segments: segments.map((s) => ({
|
|
101
|
+
mode: s.mode,
|
|
102
|
+
charCount: s.count,
|
|
103
|
+
})),
|
|
104
|
+
};
|
|
105
|
+
if (penalties) {
|
|
106
|
+
meta.maskPenalties = penalties;
|
|
107
|
+
const chosen = penalties[maskId];
|
|
108
|
+
if (chosen === undefined)
|
|
109
|
+
throw new Error("Internal error: Chosen penalty undefined");
|
|
110
|
+
meta.chosenPenalty = chosen;
|
|
111
|
+
}
|
|
112
|
+
return {
|
|
113
|
+
version,
|
|
114
|
+
ecc,
|
|
115
|
+
mask: maskId,
|
|
116
|
+
size,
|
|
117
|
+
matrix: new ReadOnlyMatrix(matrix),
|
|
118
|
+
meta,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Safe variant of encode returning a Result object.
|
|
123
|
+
*/
|
|
124
|
+
export function encodeSafe(input, options) {
|
|
125
|
+
try {
|
|
126
|
+
return ok(encode(input, options));
|
|
127
|
+
}
|
|
128
|
+
catch (e) {
|
|
129
|
+
if (e instanceof QrException) {
|
|
130
|
+
return err(e);
|
|
131
|
+
}
|
|
132
|
+
return err(new QrException("INTERNAL_INVARIANT_BROKEN", e instanceof Error ? e.message : String(e), e));
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
function validateOptions(options, ecc, charset, quietZone) {
|
|
136
|
+
if (!isEcc(ecc)) {
|
|
137
|
+
throw new QrException("INVALID_OPTIONS", `Invalid ecc level: ${ecc}`);
|
|
138
|
+
}
|
|
139
|
+
if (options.version !== undefined && options.version !== "auto") {
|
|
140
|
+
if (!isIntegerInRange(options.version, 1, 40)) {
|
|
141
|
+
throw new QrException("INVALID_VERSION", `Invalid version: ${options.version}`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (options.mask !== undefined && options.mask !== "auto") {
|
|
145
|
+
if (!isIntegerInRange(options.mask, 0, 7)) {
|
|
146
|
+
throw new QrException("INVALID_MASK", `Invalid mask: ${options.mask}`);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (!isIntegerInRange(quietZone, 0, 64)) {
|
|
150
|
+
throw new QrException("INVALID_OPTIONS", `Invalid quietZone: ${quietZone}`);
|
|
151
|
+
}
|
|
152
|
+
if (charset !== "utf-8" && charset !== "iso-8859-1") {
|
|
153
|
+
throw new QrException("INVALID_OPTIONS", `Invalid charset: ${charset}`);
|
|
154
|
+
}
|
|
155
|
+
if (options.mode !== undefined && options.mode !== "auto") {
|
|
156
|
+
if (options.mode !== "numeric" &&
|
|
157
|
+
options.mode !== "alphanumeric" &&
|
|
158
|
+
options.mode !== "byte") {
|
|
159
|
+
throw new QrException("INVALID_OPTIONS", `Invalid mode: ${options.mode}`);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
function isEcc(value) {
|
|
164
|
+
return value === "L" || value === "M" || value === "Q" || value === "H";
|
|
165
|
+
}
|
|
166
|
+
function isIntegerInRange(value, min, max) {
|
|
167
|
+
return Number.isInteger(value) && value >= min && value <= max;
|
|
168
|
+
}
|
|
169
|
+
function isNumeric(input) {
|
|
170
|
+
if (input.length === 0)
|
|
171
|
+
return true;
|
|
172
|
+
return /^[0-9]+$/.test(input);
|
|
173
|
+
}
|
|
174
|
+
function isAlphanumeric(input) {
|
|
175
|
+
for (let i = 0; i < input.length; i++) {
|
|
176
|
+
const ch = input[i];
|
|
177
|
+
if (ch === undefined || !ALPHANUMERIC_CHARSET.includes(ch))
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
return true;
|
|
181
|
+
}
|
|
182
|
+
function prepareSegments(segments, charset, strict) {
|
|
183
|
+
return segments.map((segment) => {
|
|
184
|
+
switch (segment.mode) {
|
|
185
|
+
case "numeric":
|
|
186
|
+
if (!isNumeric(segment.data)) {
|
|
187
|
+
throw new QrException("UNSUPPORTED_MODE", "Input is not representable in numeric mode.");
|
|
188
|
+
}
|
|
189
|
+
return { ...segment, count: segment.data.length };
|
|
190
|
+
case "alphanumeric":
|
|
191
|
+
if (!isAlphanumeric(segment.data)) {
|
|
192
|
+
throw new QrException("UNSUPPORTED_MODE", "Input is not representable in alphanumeric mode.");
|
|
193
|
+
}
|
|
194
|
+
return { ...segment, count: segment.data.length };
|
|
195
|
+
case "byte": {
|
|
196
|
+
const bytes = encodeByteString(segment.data, charset, strict);
|
|
197
|
+
return { ...segment, bytes, count: bytes.length };
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
function encodeByteString(input, charset, strict) {
|
|
203
|
+
if (charset === "utf-8") {
|
|
204
|
+
return new TextEncoder().encode(input);
|
|
205
|
+
}
|
|
206
|
+
const bytes = [];
|
|
207
|
+
for (let i = 0; i < input.length; i++) {
|
|
208
|
+
const codePoint = input.codePointAt(i);
|
|
209
|
+
if (codePoint === undefined)
|
|
210
|
+
continue;
|
|
211
|
+
if (codePoint > 0xff) {
|
|
212
|
+
if (strict) {
|
|
213
|
+
throw new QrException("ENCODING_FAILED", "Input contains characters outside ISO-8859-1 range.");
|
|
214
|
+
}
|
|
215
|
+
bytes.push(0x3f);
|
|
216
|
+
}
|
|
217
|
+
else {
|
|
218
|
+
bytes.push(codePoint);
|
|
219
|
+
}
|
|
220
|
+
if (codePoint > 0xffff)
|
|
221
|
+
i++;
|
|
222
|
+
}
|
|
223
|
+
return new Uint8Array(bytes);
|
|
224
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare class BitBuffer {
|
|
2
|
+
private buffer;
|
|
3
|
+
private _length;
|
|
4
|
+
get length(): number;
|
|
5
|
+
get byteLength(): number;
|
|
6
|
+
put(num: number, length: number): void;
|
|
7
|
+
putBit(bit: number): void;
|
|
8
|
+
putBytes(bytes: Uint8Array): void;
|
|
9
|
+
toBytes(): Uint8Array;
|
|
10
|
+
bitByteAlign(): void;
|
|
11
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
export class BitBuffer {
|
|
2
|
+
buffer = [];
|
|
3
|
+
_length = 0;
|
|
4
|
+
get length() {
|
|
5
|
+
return this._length;
|
|
6
|
+
}
|
|
7
|
+
get byteLength() {
|
|
8
|
+
return (this._length + 7) >>> 3;
|
|
9
|
+
}
|
|
10
|
+
put(num, length) {
|
|
11
|
+
if (length === 0)
|
|
12
|
+
return;
|
|
13
|
+
// We iterate from MSB to LSB
|
|
14
|
+
for (let i = 0; i < length; i++) {
|
|
15
|
+
const bit = (num >>> (length - 1 - i)) & 1;
|
|
16
|
+
this.putBit(bit);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
putBit(bit) {
|
|
20
|
+
const bufIndex = this._length >>> 3;
|
|
21
|
+
if (this.buffer.length <= bufIndex) {
|
|
22
|
+
this.buffer.push(0);
|
|
23
|
+
}
|
|
24
|
+
if (bit) {
|
|
25
|
+
const current = this.buffer[bufIndex];
|
|
26
|
+
// Initialize if undefined (though push(0) above should handle this)
|
|
27
|
+
// But relying on array index validity is key.
|
|
28
|
+
if (current !== undefined) {
|
|
29
|
+
this.buffer[bufIndex] = current | (0x80 >>> (this._length & 7));
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
// This branch should theoretically be unreachable due to the push check above
|
|
33
|
+
this.buffer[bufIndex] = 0x80 >>> (this._length & 7);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
this._length++;
|
|
37
|
+
}
|
|
38
|
+
putBytes(bytes) {
|
|
39
|
+
for (const byte of bytes) {
|
|
40
|
+
this.put(byte, 8);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
toBytes() {
|
|
44
|
+
return new Uint8Array(this.buffer);
|
|
45
|
+
}
|
|
46
|
+
// Helper to pad with zeroes to next byte boundary
|
|
47
|
+
bitByteAlign() {
|
|
48
|
+
const remainder = this._length & 7;
|
|
49
|
+
if (remainder > 0) {
|
|
50
|
+
this.put(0, 8 - remainder);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { QrError, QrErrorCode, Result } from "../types/index.js";
|
|
2
|
+
export declare class QrException extends Error implements QrError {
|
|
3
|
+
readonly code: QrErrorCode;
|
|
4
|
+
readonly details?: unknown;
|
|
5
|
+
constructor(code: QrErrorCode, message: string, details?: unknown);
|
|
6
|
+
}
|
|
7
|
+
export declare function ok<T>(value: T): Result<T, never>;
|
|
8
|
+
export declare function err<E>(error: E): Result<never, E>;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export class QrException extends Error {
|
|
2
|
+
code;
|
|
3
|
+
details;
|
|
4
|
+
constructor(code, message, details) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = "QrException";
|
|
7
|
+
this.code = code;
|
|
8
|
+
this.details = details;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
export function ok(value) {
|
|
12
|
+
return { ok: true, value };
|
|
13
|
+
}
|
|
14
|
+
export function err(error) {
|
|
15
|
+
return { ok: false, error };
|
|
16
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
const PRIMITIVE = 0x11d;
|
|
2
|
+
export const EXP = new Uint8Array(512); // Double size to avoid modulo in mul
|
|
3
|
+
export const LOG = new Uint8Array(256);
|
|
4
|
+
// Initialize tables
|
|
5
|
+
(function initTables() {
|
|
6
|
+
let x = 1;
|
|
7
|
+
for (let i = 0; i < 255; i++) {
|
|
8
|
+
EXP[i] = x;
|
|
9
|
+
LOG[x] = i;
|
|
10
|
+
x <<= 1;
|
|
11
|
+
if (x & 0x100) {
|
|
12
|
+
x ^= PRIMITIVE;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
// Fill the rest of EXP (periodic)
|
|
16
|
+
for (let i = 255; i < 512; i++) {
|
|
17
|
+
// Safe because i-255 is in [0, 255] range and EXP is initialized up to 254 in previous loop
|
|
18
|
+
// and initialized with 0s by default. Logic ensures we read valid data.
|
|
19
|
+
const val = EXP[i - 255];
|
|
20
|
+
EXP[i] = val !== undefined ? val : 0;
|
|
21
|
+
}
|
|
22
|
+
})();
|
|
23
|
+
export function mul(a, b) {
|
|
24
|
+
if (a === 0 || b === 0)
|
|
25
|
+
return 0;
|
|
26
|
+
// Check bounds or rely on safe access helper?
|
|
27
|
+
// Arrays are fixed size.
|
|
28
|
+
// LOG[a] can be undefined if a >= 256, but input is byte.
|
|
29
|
+
// We assume a, b are bytes.
|
|
30
|
+
const logA = LOG[a];
|
|
31
|
+
const logB = LOG[b];
|
|
32
|
+
// This is mathematically impossible if a,b are bytes != 0.
|
|
33
|
+
// But for type safety we must check.
|
|
34
|
+
if (logA === undefined || logB === undefined) {
|
|
35
|
+
throw new Error(`Invalid input for GF multiplication: ${a}, ${b}`);
|
|
36
|
+
}
|
|
37
|
+
const expIndex = logA + logB;
|
|
38
|
+
// expIndex max 508. EXP size 512.
|
|
39
|
+
const result = EXP[expIndex];
|
|
40
|
+
if (result === undefined) {
|
|
41
|
+
throw new Error(`Internal GF error: EXP table underflow/overflow at index ${expIndex}`);
|
|
42
|
+
}
|
|
43
|
+
return result;
|
|
44
|
+
}
|
|
45
|
+
export function inv(n) {
|
|
46
|
+
if (n === 0)
|
|
47
|
+
throw new Error("Division by zero");
|
|
48
|
+
const logN = LOG[n];
|
|
49
|
+
if (logN === undefined)
|
|
50
|
+
throw new Error(`Invalid input for GF inversion: ${n}`);
|
|
51
|
+
return EXP[255 - logN] ?? 0; // Fallback 0 should essentially never happen given table construction
|
|
52
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function computeEcc(data: Uint8Array, eccLen: number): Uint8Array;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { EXP, LOG, mul } from "./gf.js";
|
|
2
|
+
const GEN_POLY_CACHE = new Map();
|
|
3
|
+
function getGeneratorPoly(eccLen) {
|
|
4
|
+
const cached = GEN_POLY_CACHE.get(eccLen);
|
|
5
|
+
if (cached)
|
|
6
|
+
return cached;
|
|
7
|
+
const poly = new Uint8Array(eccLen + 1);
|
|
8
|
+
poly[0] = 1;
|
|
9
|
+
// We multiply successively by (x - 2^i) for i=0..eccLen-1
|
|
10
|
+
// In GF(2^8), subtraction is same as addition (XOR).
|
|
11
|
+
// So we multiply by (x + 2^i).
|
|
12
|
+
for (let i = 0; i < eccLen; i++) {
|
|
13
|
+
const root = EXP[i];
|
|
14
|
+
if (root === undefined)
|
|
15
|
+
throw new Error("Internal error: EXP lookup failed");
|
|
16
|
+
// Multiply poly by (x + root)
|
|
17
|
+
// Coeffs shift: new_coeff[j] = coeff[j] ^ (coeff[j-1] * root)
|
|
18
|
+
// We iterate backwards to use the 'old' values of j-1.
|
|
19
|
+
for (let j = i + 1; j >= 1; j--) {
|
|
20
|
+
const current = poly[j];
|
|
21
|
+
const prev = poly[j - 1];
|
|
22
|
+
if (current === undefined || prev === undefined) {
|
|
23
|
+
throw new Error("Internal error: Poly index out of bounds");
|
|
24
|
+
}
|
|
25
|
+
poly[j] = current ^ mul(prev, root);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
GEN_POLY_CACHE.set(eccLen, poly);
|
|
29
|
+
return poly;
|
|
30
|
+
}
|
|
31
|
+
export function computeEcc(data, eccLen) {
|
|
32
|
+
const genPoly = getGeneratorPoly(eccLen);
|
|
33
|
+
const remainder = new Uint8Array(eccLen);
|
|
34
|
+
const log = LOG;
|
|
35
|
+
const exp = EXP;
|
|
36
|
+
for (const byte of data) {
|
|
37
|
+
const firstCoeff = remainder[0] ?? 0;
|
|
38
|
+
const factor = firstCoeff ^ byte;
|
|
39
|
+
// Shift remainder left
|
|
40
|
+
// Using copyWithin is faster than set/subarray for small arrays?
|
|
41
|
+
// remainder.set(remainder.subarray(1), 0);
|
|
42
|
+
// remainder.copyWithin(0, 1); // standard
|
|
43
|
+
remainder.copyWithin(0, 1);
|
|
44
|
+
remainder[eccLen - 1] = 0;
|
|
45
|
+
if (factor !== 0) {
|
|
46
|
+
const logFactor = log[factor] ?? 0;
|
|
47
|
+
for (let i = 0; i < eccLen; i++) {
|
|
48
|
+
const genCoeff = genPoly[i + 1];
|
|
49
|
+
if (genCoeff !== 0 && genCoeff !== undefined) {
|
|
50
|
+
// Inlined mul
|
|
51
|
+
const logVal = log[genCoeff] ?? 0;
|
|
52
|
+
const expVal = exp[logVal + logFactor] ?? 0;
|
|
53
|
+
const current = remainder[i] ?? 0;
|
|
54
|
+
remainder[i] = current ^ expVal;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return remainder;
|
|
60
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { BitBuffer } from "../core/bit-buffer.js";
|
|
2
|
+
import type { EccLevel } from "../types/index.js";
|
|
3
|
+
import type { Segment } from "./segmentation.js";
|
|
4
|
+
/**
|
|
5
|
+
* Combines encoded segments and applies padding to create the final data bitstream.
|
|
6
|
+
*/
|
|
7
|
+
export declare function buildBitstream(segments: Segment[], version: number, ecc: EccLevel): BitBuffer;
|