@handijitcom/barcode 0.0.0-stage → 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/CHANGELOG.md +26 -0
- package/LICENSE +21 -0
- package/README.md +320 -2
- package/build/index.cjs +284 -0
- package/build/index.cjs.map +1 -0
- package/build/index.d.mts +45 -0
- package/build/index.d.ts +45 -0
- package/build/index.mjs +279 -0
- package/build/index.mjs.map +1 -0
- package/build/index.umd.js +2 -0
- package/build/index.umd.js.map +1 -0
- package/package.json +90 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this package are documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
|
+
and the package follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [Unreleased]
|
|
9
|
+
|
|
10
|
+
## [1.0.0] - 2026-11-27
|
|
11
|
+
|
|
12
|
+
First release.
|
|
13
|
+
|
|
14
|
+
### Added
|
|
15
|
+
|
|
16
|
+
- `encodeCode128(text)`: Code 128 encoder for ASCII 0–127 with optimal code set
|
|
17
|
+
selection (shortest symbol sequence over sets A, B and C, including SHIFT),
|
|
18
|
+
mod-103 check symbol and stop pattern; returns bar/space module widths.
|
|
19
|
+
- `code128Svg(text, options?)`: SVG string renderer (no DOM needed) with
|
|
20
|
+
`moduleWidth`, `unit` (`px` / `mm`), `height`, `quietZone`, `showText`,
|
|
21
|
+
`fontSize`, `foreground`, `background` and `title` options.
|
|
22
|
+
- `LABEL_SIZES` (`100x100`, `100x150`, `a4`, in millimetres) and
|
|
23
|
+
`labelPrintCss(size)` for edge-to-edge `@page` print rules.
|
|
24
|
+
|
|
25
|
+
[Unreleased]: https://github.com/handijit/barcode/compare/v1.0.0...HEAD
|
|
26
|
+
[1.0.0]: https://github.com/handijit/barcode/releases/tag/v1.0.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ahmet İlhan
|
|
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,321 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @handijitcom/barcode
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@handijitcom/barcode)
|
|
4
|
+
[](https://www.npmjs.com/package/@handijitcom/barcode)
|
|
5
|
+
[](./LICENSE)
|
|
6
|
+
|
|
7
|
+
Code 128 barcodes for shipping labels, written from scratch in TypeScript. The
|
|
8
|
+
encoder picks code sets A, B and C optimally (the shortest possible symbol), and
|
|
9
|
+
the renderer returns a plain SVG string with crisp, whole-module bars, so the
|
|
10
|
+
same call works in Node, in browsers, in workers and during SSR. Two small
|
|
11
|
+
helpers give you the label page sizes and the print CSS for thermal and A4
|
|
12
|
+
labels; the label layout itself stays in your app.
|
|
13
|
+
|
|
14
|
+
- **Zero runtime dependencies**, no DOM, no canvas, no side effects on import.
|
|
15
|
+
- **2.27 kB** gzip for the minified browser bundle (`npm run size`).
|
|
16
|
+
- **Optimal encoding:** dynamic programming over code sets A/B/C with SHIFT,
|
|
17
|
+
so digit runs, control characters and text mix in the fewest symbols.
|
|
18
|
+
- **Print-ready SVG:** `shape-rendering="crispEdges"`, positions computed in
|
|
19
|
+
whole modules, sizes in `px` or `mm`, a 10-module quiet zone by default.
|
|
20
|
+
- **Accessible:** `role="img"`, `aria-label` and an optional `<title>`.
|
|
21
|
+
- **68 unit tests, 100 % coverage** (statements, branches, functions, lines).
|
|
22
|
+
|
|
23
|
+
## Table of contents
|
|
24
|
+
|
|
25
|
+
- [Requirements](#requirements)
|
|
26
|
+
- [Installation](#installation)
|
|
27
|
+
- [Quick start](#quick-start)
|
|
28
|
+
- [When to use it](#when-to-use-it)
|
|
29
|
+
- [API reference](#api-reference)
|
|
30
|
+
- [Guides](#guides)
|
|
31
|
+
- [Semantics](#semantics)
|
|
32
|
+
- [Performance](#performance)
|
|
33
|
+
- [Bundle size](#bundle-size)
|
|
34
|
+
- [TypeScript](#typescript)
|
|
35
|
+
- [FAQ](#faq)
|
|
36
|
+
- [Roadmap](#roadmap)
|
|
37
|
+
- [Contributing](#contributing)
|
|
38
|
+
- [Releasing](#releasing)
|
|
39
|
+
- [License](#license)
|
|
40
|
+
|
|
41
|
+
## Requirements
|
|
42
|
+
|
|
43
|
+
- Node.js 24 or newer.
|
|
44
|
+
- Any evergreen browser (ES2022). The package never touches `window` or
|
|
45
|
+
`document`.
|
|
46
|
+
|
|
47
|
+
## Installation
|
|
48
|
+
|
|
49
|
+
```sh
|
|
50
|
+
npm install @handijitcom/barcode
|
|
51
|
+
# or
|
|
52
|
+
yarn add @handijitcom/barcode
|
|
53
|
+
# or
|
|
54
|
+
pnpm add @handijitcom/barcode
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Quick start
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
import { code128Svg, labelPrintCss } from "@handijitcom/barcode";
|
|
61
|
+
|
|
62
|
+
// 0.375 mm modules = 3 dots on a 203 dpi thermal printer.
|
|
63
|
+
const svg = code128Svg("HI345678", {
|
|
64
|
+
unit: "mm",
|
|
65
|
+
moduleWidth: 0.375,
|
|
66
|
+
height: 20,
|
|
67
|
+
title: "Tracking number",
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
// Put this in a <style> of the print view.
|
|
71
|
+
const css = labelPrintCss("100x150"); // "@page { size: 100mm 150mm; margin: 0; }"
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## When to use it
|
|
75
|
+
|
|
76
|
+
Use it when you need Code 128 (shipping labels, tracking numbers, order and
|
|
77
|
+
SKU codes, warehouse slips) as SVG or as raw module widths for your own
|
|
78
|
+
renderer (canvas, PDF, ZPL).
|
|
79
|
+
|
|
80
|
+
Do not use it for QR codes or other 2D symbologies (not in 1.0, see
|
|
81
|
+
[Roadmap](#roadmap)), for GS1-128 / FNC1 application identifiers, or for text
|
|
82
|
+
outside ASCII 0–127: Code 128 cannot encode it and the functions throw.
|
|
83
|
+
|
|
84
|
+
## API reference
|
|
85
|
+
|
|
86
|
+
### `encodeCode128(text)`
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
encodeCode128(text: string): number[]
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Encodes `text` and returns the module widths of the whole symbol: bar, space,
|
|
93
|
+
bar, … from the start symbol to the stop symbol including its termination bar.
|
|
94
|
+
Quiet zones are not included. The array always has an odd length and starts and
|
|
95
|
+
ends with a bar.
|
|
96
|
+
|
|
97
|
+
| Parameter | Type | Description |
|
|
98
|
+
| --------- | -------- | ------------------------------------- |
|
|
99
|
+
| `text` | `string` | ASCII characters 0–127, at least one. |
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
encodeCode128("12");
|
|
103
|
+
// Start C, 12, check 14, stop:
|
|
104
|
+
// [2,1,1,2,3,2, 1,1,2,2,3,2, 1,2,2,2,3,1, 2,3,3,1,1,1,2]
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Throws `TypeError` when `text` is not a string or contains a non-ASCII
|
|
108
|
+
character (the message names the character and its index), `RangeError` when
|
|
109
|
+
`text` is empty.
|
|
110
|
+
|
|
111
|
+
### `code128Svg(text, options?)`
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
code128Svg(text: string, options?: Code128SvgOptions): string
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Returns a standalone SVG document as a string. Every length option is in
|
|
118
|
+
`unit`; the `width`, `height` and `viewBox` of the SVG use the same unit, so
|
|
119
|
+
1 user unit = 1 px or 1 mm.
|
|
120
|
+
|
|
121
|
+
| Option | Type | Default | Description |
|
|
122
|
+
| ------------- | -------------- | ------------------ | ---------------------------------------------------------------- |
|
|
123
|
+
| `unit` | `"px" \| "mm"` | `"px"` | Unit of every length option and of the SVG size. |
|
|
124
|
+
| `moduleWidth` | `number` | `2` px / `0.33` mm | Width of the narrowest bar. |
|
|
125
|
+
| `height` | `number` | `80` px / `15` mm | Bar height, without the text line. |
|
|
126
|
+
| `quietZone` | `number` | `10` | Blank margin left and right, in modules (floored to an integer). |
|
|
127
|
+
| `showText` | `boolean` | `true` | Print the text under the bars (monospace, centred). |
|
|
128
|
+
| `fontSize` | `number` | `14` px / `3` mm | Font size of the text line. |
|
|
129
|
+
| `foreground` | `string` | `"#000000"` | Bar and text colour. |
|
|
130
|
+
| `background` | `string` | `"#ffffff"` | Background colour, quiet zones included. |
|
|
131
|
+
| `title` | `string` | none | Accessible name as `<title>` and `aria-label`. |
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
code128Svg("1234", { moduleWidth: 3, height: 40, showText: false });
|
|
135
|
+
// <svg xmlns="http://www.w3.org/2000/svg" width="231px" height="40px" viewBox="0 0 231 40" ...
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
Output structure: one background `<rect>`, one `<path>` holding every bar (one
|
|
139
|
+
`M…z` segment per bar), an optional `<text>`. Without `title`, `aria-label` is
|
|
140
|
+
the encoded text.
|
|
141
|
+
|
|
142
|
+
Edge cases:
|
|
143
|
+
|
|
144
|
+
- Invalid settings fall back to the default instead of producing a broken
|
|
145
|
+
image: a non-positive or non-finite `moduleWidth`, `height` or `fontSize`, a
|
|
146
|
+
negative or non-finite `quietZone`, an unknown `unit`.
|
|
147
|
+
- Text, title and colours are XML-escaped; characters XML 1.0 cannot carry
|
|
148
|
+
(NUL and most control characters) are left out of the text line and the
|
|
149
|
+
label, but they are still encoded in the bars.
|
|
150
|
+
- Errors for invalid `text` are the same as `encodeCode128` and name it.
|
|
151
|
+
|
|
152
|
+
### `LABEL_SIZES`
|
|
153
|
+
|
|
154
|
+
```ts
|
|
155
|
+
const LABEL_SIZES: Readonly<Record<LabelSize, LabelDimensions>>;
|
|
156
|
+
// { "100x100": { width: 100, height: 100 },
|
|
157
|
+
// "100x150": { width: 100, height: 150 },
|
|
158
|
+
// a4: { width: 210, height: 297 } } (millimetres)
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
Page sizes of common shipping labels: 100×100 mm and 100×150 mm (4×4″ and
|
|
162
|
+
4×6″ thermal) and A4. The object and its entries are frozen.
|
|
163
|
+
|
|
164
|
+
### `labelPrintCss(size)`
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
labelPrintCss(size: LabelSize): string
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
Returns the `@page` rule that makes the browser print on that label edge to
|
|
171
|
+
edge:
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
labelPrintCss("100x150"); // "@page { size: 100mm 150mm; margin: 0; }"
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
Throws `TypeError` for an unknown size (the message lists the valid ones).
|
|
178
|
+
|
|
179
|
+
## Guides
|
|
180
|
+
|
|
181
|
+
### Printing a 100×150 thermal label from a web app
|
|
182
|
+
|
|
183
|
+
```ts
|
|
184
|
+
import { code128Svg, labelPrintCss } from "@handijitcom/barcode";
|
|
185
|
+
|
|
186
|
+
const printLabel = (trackingNumber: string): void => {
|
|
187
|
+
const style = document.createElement("style");
|
|
188
|
+
style.textContent = labelPrintCss("100x150");
|
|
189
|
+
document.head.append(style);
|
|
190
|
+
|
|
191
|
+
// Your layout; the package only supplies the barcode and the page rule.
|
|
192
|
+
const label = document.querySelector("#label")!;
|
|
193
|
+
label.innerHTML = code128Svg(trackingNumber, {
|
|
194
|
+
unit: "mm",
|
|
195
|
+
moduleWidth: 0.375,
|
|
196
|
+
height: 25,
|
|
197
|
+
title: `Tracking number ${trackingNumber}`,
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
window.print();
|
|
201
|
+
};
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
Pick `moduleWidth` as a whole number of printer dots so every bar lands on
|
|
205
|
+
the dot grid: 0.125 mm per dot at 203 dpi (0.25 / 0.375 / 0.5 mm), 0.0847 mm
|
|
206
|
+
per dot at 300 dpi (0.254 / 0.339 mm).
|
|
207
|
+
|
|
208
|
+
### Server-side rendering
|
|
209
|
+
|
|
210
|
+
`code128Svg` returns a string, so it can be inlined into HTML on the server,
|
|
211
|
+
written to a `.svg` file, or turned into a data URL:
|
|
212
|
+
|
|
213
|
+
```ts
|
|
214
|
+
const src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(code128Svg("HI345678"))}`;
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
### Your own renderer
|
|
218
|
+
|
|
219
|
+
`encodeCode128` returns module widths; multiply by the module size and
|
|
220
|
+
alternate bar and space, starting with a bar, to draw on a canvas, in a PDF or
|
|
221
|
+
in a printer language.
|
|
222
|
+
|
|
223
|
+
## Semantics
|
|
224
|
+
|
|
225
|
+
| Input | Encoding |
|
|
226
|
+
| ----------------------------------- | --------------------------------------------------------------------- |
|
|
227
|
+
| Digits only, even count (`"1234"`) | Start C, one symbol per digit pair |
|
|
228
|
+
| Digits only, odd count (`"12345"`) | Start C for the pairs, CODE B for the last digit |
|
|
229
|
+
| Text then ≥ 4 digits at the end | Set B, CODE C before the digit run (`"HI345678"`) |
|
|
230
|
+
| ≥ 6 digits inside text | CODE C and back (4 digits inside text cost the same in B, so B stays) |
|
|
231
|
+
| One control character inside text | SHIFT (`"a\tb"`) |
|
|
232
|
+
| Several control characters | Start A or CODE A |
|
|
233
|
+
| Ties | Fewest symbols first; then stay in the current set; then C, B, A |
|
|
234
|
+
| Non-ASCII, empty string, non-string | `TypeError`, `RangeError`, `TypeError` |
|
|
235
|
+
|
|
236
|
+
The check symbol is (start value + Σ symbol value × position) mod 103.
|
|
237
|
+
|
|
238
|
+
## Performance
|
|
239
|
+
|
|
240
|
+
`npm run bench` (measures `build/index.mjs`):
|
|
241
|
+
|
|
242
|
+
Node v26.11.0 · Apple M5 · darwin/arm64
|
|
243
|
+
|
|
244
|
+
| Scenario | Iterations | Total (ms) | µs/op |
|
|
245
|
+
| ------------------------------------------ | ---------: | ---------: | -----: |
|
|
246
|
+
| encodeCode128: 8-char tracking number | 200,000 | 93.0 | 0.465 |
|
|
247
|
+
| encodeCode128: 30-char mixed text | 100,000 | 161.1 | 1.611 |
|
|
248
|
+
| encodeCode128: 100 digits | 50,000 | 218.1 | 4.362 |
|
|
249
|
+
| encodeCode128: control characters + digits | 100,000 | 84.2 | 0.842 |
|
|
250
|
+
| code128Svg: 8-char tracking number (px) | 100,000 | 660.4 | 6.604 |
|
|
251
|
+
| code128Svg: 30-char mixed text (mm) | 50,000 | 1138.9 | 22.777 |
|
|
252
|
+
|
|
253
|
+
Encoding is O(n) in time and memory.
|
|
254
|
+
|
|
255
|
+
## Bundle size
|
|
256
|
+
|
|
257
|
+
`npm run size`:
|
|
258
|
+
|
|
259
|
+
| File | Raw | Gzip | Brotli |
|
|
260
|
+
| -------------------- | -------- | ------- | ------- |
|
|
261
|
+
| `build/index.mjs` | 12.73 kB | 4.70 kB | 4.06 kB |
|
|
262
|
+
| `build/index.cjs` | 12.83 kB | 4.72 kB | 4.07 kB |
|
|
263
|
+
| `build/index.umd.js` | 4.59 kB | 2.27 kB | 2.03 kB |
|
|
264
|
+
| `build/index.d.ts` | 2.12 kB | 0.91 kB | 0.77 kB |
|
|
265
|
+
|
|
266
|
+
The minified browser bundle has a 2800 B gzip budget; `npm run verify` fails
|
|
267
|
+
above it.
|
|
268
|
+
|
|
269
|
+
| Entry | File |
|
|
270
|
+
| ---------- | ---------------------------------------------------------------- |
|
|
271
|
+
| ESM | `build/index.mjs` (`import`) |
|
|
272
|
+
| CommonJS | `build/index.cjs` (`require`) |
|
|
273
|
+
| `<script>` | `build/index.umd.js`, global `handijitBarcode` (unpkg, jsDelivr) |
|
|
274
|
+
| TypeScript | `build/index.d.mts` / `build/index.d.ts` |
|
|
275
|
+
|
|
276
|
+
## TypeScript
|
|
277
|
+
|
|
278
|
+
Exported types: `Code128SvgOptions`, `LengthUnit` (`"px" | "mm"`), `LabelSize`
|
|
279
|
+
(`"100x100" | "100x150" | "a4"`) and `LabelDimensions`. Passing an unknown
|
|
280
|
+
unit or label size is a compile error.
|
|
281
|
+
|
|
282
|
+
## FAQ
|
|
283
|
+
|
|
284
|
+
**Why does my barcode look blurry on screen?** Use a whole-pixel `moduleWidth`
|
|
285
|
+
(the default is 2 px) and do not scale the SVG by a fractional factor.
|
|
286
|
+
|
|
287
|
+
**Why do lowercase letters or `é` fail?** Lowercase works (set B). `é` and any
|
|
288
|
+
other character above ASCII 127 cannot be encoded in Code 128; transliterate
|
|
289
|
+
first.
|
|
290
|
+
|
|
291
|
+
**Does it support GS1-128 (FNC1)?** Not in 1.0.
|
|
292
|
+
|
|
293
|
+
## Roadmap
|
|
294
|
+
|
|
295
|
+
- QR code encoder and SVG renderer (not in 1.0).
|
|
296
|
+
- GS1-128 / FNC1 support.
|
|
297
|
+
|
|
298
|
+
## Contributing
|
|
299
|
+
|
|
300
|
+
```sh
|
|
301
|
+
npm install
|
|
302
|
+
npm run verify # lint, format, typecheck, tests (100 % coverage), build, size, package lint
|
|
303
|
+
npm run bench
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
68 unit tests (Vitest, node and jsdom), 100 % coverage of statements,
|
|
307
|
+
branches, functions and lines. No third-party barcode code: the symbol table
|
|
308
|
+
and the encoder are written here and checked against hand-computed references
|
|
309
|
+
and an independent decoder in the tests.
|
|
310
|
+
|
|
311
|
+
## Releasing
|
|
312
|
+
|
|
313
|
+
1. Add a `## [x.y.z] - date` section to `CHANGELOG.md`.
|
|
314
|
+
2. `npm version patch|minor|major`.
|
|
315
|
+
3. Push to `master`. `publish.yml` runs the same gates, smoke-tests the packed
|
|
316
|
+
tarball, publishes to npm with provenance using the repository's
|
|
317
|
+
`NPM_ACCESS_TOKEN` secret, tags `vx.y.z` and creates the GitHub Release.
|
|
318
|
+
|
|
319
|
+
## License
|
|
320
|
+
|
|
321
|
+
[MIT](./LICENSE)
|
package/build/index.cjs
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const XML_ENTITIES = new Map([
|
|
4
|
+
["&", "&"],
|
|
5
|
+
["<", "<"],
|
|
6
|
+
[">", ">"],
|
|
7
|
+
['"', """],
|
|
8
|
+
["'", "'"],
|
|
9
|
+
]);
|
|
10
|
+
// XML 1.0 "Char": anything else (NUL, most C0 controls, lone surrogates, U+FFFE/FFFF) makes the
|
|
11
|
+
// whole document unparseable, even as a character reference.
|
|
12
|
+
const isXmlChar = (codePoint) => codePoint === 0x09 ||
|
|
13
|
+
codePoint === 0x0a ||
|
|
14
|
+
codePoint === 0x0d ||
|
|
15
|
+
(codePoint >= 0x20 && codePoint <= 0xd7ff) ||
|
|
16
|
+
(codePoint >= 0xe000 && codePoint <= 0xfffd) ||
|
|
17
|
+
codePoint >= 0x10000;
|
|
18
|
+
/** Escapes a value for XML text and attributes, dropping characters XML cannot carry. */
|
|
19
|
+
const escapeXml = (value) => {
|
|
20
|
+
let escaped = "";
|
|
21
|
+
for (const character of value) {
|
|
22
|
+
if (!isXmlChar(character.codePointAt(0)))
|
|
23
|
+
continue;
|
|
24
|
+
escaped += XML_ENTITIES.get(character) ?? character;
|
|
25
|
+
}
|
|
26
|
+
return escaped;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const SET_A = 0;
|
|
30
|
+
const SET_B = 1;
|
|
31
|
+
const SET_C = 2;
|
|
32
|
+
// Tie-break order: when two plans are equally short, C (denser) wins, then B (text) before A.
|
|
33
|
+
const SETS_BY_PREFERENCE = [SET_C, SET_B, SET_A];
|
|
34
|
+
const SET_COUNT = 3;
|
|
35
|
+
// Indexed by code set: Start A/B/C, and the CODE A/B/C symbol that switches into that set.
|
|
36
|
+
const START_CODEWORDS = [103, 104, 105];
|
|
37
|
+
const SWITCH_CODEWORDS = [101, 100, 99];
|
|
38
|
+
const SHIFT_CODEWORD = 98;
|
|
39
|
+
const STOP_CODEWORD = 106;
|
|
40
|
+
const CHECKSUM_MODULUS = 103;
|
|
41
|
+
const MAX_ASCII = 127;
|
|
42
|
+
// Planner decisions per (position, code set); a switch is stored as ACTION_SWITCH + target set.
|
|
43
|
+
const ACTION_ENCODE = 0;
|
|
44
|
+
const ACTION_SHIFT = 1;
|
|
45
|
+
const ACTION_SWITCH = 2;
|
|
46
|
+
const isDigit = (code) => code >= 48 && code <= 57;
|
|
47
|
+
const otherTextSet = (set) => (set === SET_A ? SET_B : SET_A);
|
|
48
|
+
/** Characters one codeword of `set` consumes at `index`, or 0 when the set cannot encode them. */
|
|
49
|
+
const spanOf = (text, index, set) => {
|
|
50
|
+
const code = text.charCodeAt(index);
|
|
51
|
+
// charCodeAt past the end is NaN, so a trailing single digit is never taken as a pair.
|
|
52
|
+
if (set === SET_C) {
|
|
53
|
+
return isDigit(code) && isDigit(text.charCodeAt(index + 1)) ? 2 : 0;
|
|
54
|
+
}
|
|
55
|
+
if (set === SET_A)
|
|
56
|
+
return code < 96 ? 1 : 0;
|
|
57
|
+
return code >= 32 ? 1 : 0;
|
|
58
|
+
};
|
|
59
|
+
/** Symbol value of the characters at `index` in `set`; the caller has checked `spanOf`. */
|
|
60
|
+
const valueOf = (text, index, set) => {
|
|
61
|
+
const code = text.charCodeAt(index);
|
|
62
|
+
if (set === SET_C)
|
|
63
|
+
return (code - 48) * 10 + text.charCodeAt(index + 1) - 48;
|
|
64
|
+
// Set A puts the control characters (0–31) after the printable ones: NUL is value 64.
|
|
65
|
+
if (set === SET_A && code < 32)
|
|
66
|
+
return code + 64;
|
|
67
|
+
return code - 32;
|
|
68
|
+
};
|
|
69
|
+
const assertEncodable = (text, caller) => {
|
|
70
|
+
if (typeof text !== "string") {
|
|
71
|
+
throw new TypeError(`${caller}: expected a string, received ${text === null ? "null" : typeof text}`);
|
|
72
|
+
}
|
|
73
|
+
if (text.length === 0) {
|
|
74
|
+
throw new RangeError(`${caller}: text must contain at least one character`);
|
|
75
|
+
}
|
|
76
|
+
for (let index = 0; index < text.length; index++) {
|
|
77
|
+
if (text.charCodeAt(index) > MAX_ASCII) {
|
|
78
|
+
const character = String.fromCodePoint(text.codePointAt(index));
|
|
79
|
+
throw new TypeError(`${caller}: "${character}" at index ${index} is not ASCII; Code 128 encodes characters 0–127 only`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return text;
|
|
83
|
+
};
|
|
84
|
+
/**
|
|
85
|
+
* Plans the shortest symbol sequence by dynamic programming over (position, current code set),
|
|
86
|
+
* so CODE C runs, shifts and switches are placed optimally rather than by look-ahead heuristics.
|
|
87
|
+
*/
|
|
88
|
+
const planDataCodewords = (text) => {
|
|
89
|
+
const { length } = text;
|
|
90
|
+
// cost[i * 3 + set]: fewest symbols that encode text[i..] when `set` is active; the row for
|
|
91
|
+
// i = length stays 0.
|
|
92
|
+
const cost = new Float64Array((length + 1) * SET_COUNT);
|
|
93
|
+
const action = new Uint8Array(length * SET_COUNT);
|
|
94
|
+
const costAt = (index, set) => cost[index * SET_COUNT + set];
|
|
95
|
+
const direct = [0, 0, 0];
|
|
96
|
+
for (let index = length - 1; index >= 0; index--) {
|
|
97
|
+
for (const set of SETS_BY_PREFERENCE) {
|
|
98
|
+
let best = Infinity;
|
|
99
|
+
let choice = ACTION_ENCODE;
|
|
100
|
+
const span = spanOf(text, index, set);
|
|
101
|
+
if (span > 0)
|
|
102
|
+
best = 1 + costAt(index + span, set);
|
|
103
|
+
if (set !== SET_C && spanOf(text, index, otherTextSet(set)) > 0) {
|
|
104
|
+
const shifted = 2 + costAt(index + 1, set);
|
|
105
|
+
if (shifted < best) {
|
|
106
|
+
best = shifted;
|
|
107
|
+
choice = ACTION_SHIFT;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
direct[set] = best;
|
|
111
|
+
action[index * SET_COUNT + set] = choice;
|
|
112
|
+
}
|
|
113
|
+
// Every ASCII character fits set A or B, so a switch always leads to a finite plan; switching
|
|
114
|
+
// twice in a row is never shorter than switching once to the final set.
|
|
115
|
+
for (const set of SETS_BY_PREFERENCE) {
|
|
116
|
+
let best = direct[set];
|
|
117
|
+
for (const target of SETS_BY_PREFERENCE) {
|
|
118
|
+
if (target !== set && 1 + direct[target] < best) {
|
|
119
|
+
best = 1 + direct[target];
|
|
120
|
+
action[index * SET_COUNT + set] = ACTION_SWITCH + target;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
cost[index * SET_COUNT + set] = best;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
let set = SET_C;
|
|
127
|
+
for (const candidate of SETS_BY_PREFERENCE) {
|
|
128
|
+
if (costAt(0, candidate) < costAt(0, set))
|
|
129
|
+
set = candidate;
|
|
130
|
+
}
|
|
131
|
+
const codewords = [START_CODEWORDS[set]];
|
|
132
|
+
let index = 0;
|
|
133
|
+
while (index < length) {
|
|
134
|
+
const step = action[index * SET_COUNT + set];
|
|
135
|
+
if (step >= ACTION_SWITCH) {
|
|
136
|
+
set = (step - ACTION_SWITCH);
|
|
137
|
+
codewords.push(SWITCH_CODEWORDS[set]);
|
|
138
|
+
}
|
|
139
|
+
else if (step === ACTION_SHIFT) {
|
|
140
|
+
codewords.push(SHIFT_CODEWORD, valueOf(text, index, otherTextSet(set)));
|
|
141
|
+
index += 1;
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
codewords.push(valueOf(text, index, set));
|
|
145
|
+
index += spanOf(text, index, set);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return codewords;
|
|
149
|
+
};
|
|
150
|
+
/**
|
|
151
|
+
* Full Code 128 symbol sequence for `text`: start, data, mod-103 check symbol and stop.
|
|
152
|
+
* Throws TypeError for a non-string or non-ASCII text and RangeError for an empty one.
|
|
153
|
+
*/
|
|
154
|
+
const toCode128Codewords = (text, caller) => {
|
|
155
|
+
const codewords = planDataCodewords(assertEncodable(text, caller));
|
|
156
|
+
// The start symbol has weight 1, like the first data symbol.
|
|
157
|
+
let checksum = codewords[0];
|
|
158
|
+
for (let position = 1; position < codewords.length; position++) {
|
|
159
|
+
checksum += codewords[position] * position;
|
|
160
|
+
}
|
|
161
|
+
codewords.push(checksum % CHECKSUM_MODULUS, STOP_CODEWORD);
|
|
162
|
+
return codewords;
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
// Bar/space module widths of every Code 128 symbol (ISO/IEC 15417), indexed by symbol value.
|
|
166
|
+
// Each string alternates bar, space, bar...; 0–105 span 11 modules, the stop symbol (106) spans 13
|
|
167
|
+
// because it carries the final 2-module termination bar.
|
|
168
|
+
// prettier-ignore
|
|
169
|
+
const PATTERN_SOURCE = [
|
|
170
|
+
"212222", "222122", "222221", "121223", "121322", "131222", "122213", "122312",
|
|
171
|
+
"132212", "221213", "221312", "231212", "112232", "122132", "122231", "113222",
|
|
172
|
+
"123122", "123221", "223211", "221132", "221231", "213212", "223112", "312131",
|
|
173
|
+
"311222", "321122", "321221", "312212", "322112", "322211", "212123", "212321",
|
|
174
|
+
"232121", "111323", "131123", "131321", "112313", "132113", "132311", "211313",
|
|
175
|
+
"231113", "231311", "112133", "112331", "132131", "113123", "113321", "133121",
|
|
176
|
+
"313121", "211331", "231131", "213113", "213311", "213131", "311123", "311321",
|
|
177
|
+
"331121", "312113", "312311", "332111", "314111", "221411", "431111", "111224",
|
|
178
|
+
"111422", "121124", "121421", "141122", "141221", "112214", "112412", "122114",
|
|
179
|
+
"122411", "142112", "142211", "241211", "221114", "413111", "241112", "134111",
|
|
180
|
+
"111242", "121142", "121241", "114212", "124112", "124211", "411212", "421112",
|
|
181
|
+
"421211", "212141", "214121", "412121", "111143", "111341", "131141", "114113",
|
|
182
|
+
"114311", "411113", "411311", "113141", "114131", "311141", "411131", "211412",
|
|
183
|
+
"211214", "211232", "2331112",
|
|
184
|
+
];
|
|
185
|
+
/** Module widths per symbol value (0–106). */
|
|
186
|
+
const CODE128_PATTERNS = PATTERN_SOURCE.map((pattern) => Array.from(pattern, Number));
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Encodes ASCII text as a Code 128 symbol and returns its module widths: bar, space, bar...,
|
|
190
|
+
* from the start symbol to the stop symbol (quiet zones excluded).
|
|
191
|
+
*/
|
|
192
|
+
const encodeCode128 = (text) => {
|
|
193
|
+
const widths = [];
|
|
194
|
+
for (const codeword of toCode128Codewords(text, "encodeCode128")) {
|
|
195
|
+
// Codewords come from the encoder and are always 0–106, so the lookup cannot miss.
|
|
196
|
+
widths.push(...CODE128_PATTERNS[codeword]);
|
|
197
|
+
}
|
|
198
|
+
return widths;
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
const UNIT_DEFAULTS = {
|
|
202
|
+
px: { moduleWidth: 2, height: 80, fontSize: 14 },
|
|
203
|
+
mm: { moduleWidth: 0.33, height: 15, fontSize: 3 },
|
|
204
|
+
};
|
|
205
|
+
const DEFAULT_QUIET_ZONE = 10;
|
|
206
|
+
const DEFAULT_FOREGROUND = "#000000";
|
|
207
|
+
const DEFAULT_BACKGROUND = "#ffffff";
|
|
208
|
+
// Text line below the bars, in ems: the baseline sits 1.1 em under the bars, the line ends 1.4 em down.
|
|
209
|
+
const TEXT_BASELINE_EM = 1.1;
|
|
210
|
+
const TEXT_LINE_EM = 1.4;
|
|
211
|
+
// Enough for 0.001 mm / 0.001 px precision while cutting floating-point noise (0.9900000000000001).
|
|
212
|
+
const DECIMALS = 4;
|
|
213
|
+
const formatNumber = (value) => String(Number(value.toFixed(DECIMALS)));
|
|
214
|
+
const positiveOr = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value > 0
|
|
215
|
+
? value
|
|
216
|
+
: fallback;
|
|
217
|
+
/** Renders `text` as a Code 128 barcode SVG string; needs no DOM. */
|
|
218
|
+
const code128Svg = (text, { unit, moduleWidth, height, quietZone, showText = true, fontSize, foreground = DEFAULT_FOREGROUND, background = DEFAULT_BACKGROUND, title, } = {}) => {
|
|
219
|
+
const widths = encodeCode128(text);
|
|
220
|
+
const lengthUnit = unit === "mm" ? "mm" : "px";
|
|
221
|
+
const defaults = UNIT_DEFAULTS[lengthUnit];
|
|
222
|
+
const moduleSize = positiveOr(moduleWidth, defaults.moduleWidth);
|
|
223
|
+
const barHeight = positiveOr(height, defaults.height);
|
|
224
|
+
const textSize = positiveOr(fontSize, defaults.fontSize);
|
|
225
|
+
const margin = typeof quietZone === "number" &&
|
|
226
|
+
Number.isFinite(quietZone) &&
|
|
227
|
+
quietZone >= 0
|
|
228
|
+
? Math.floor(quietZone)
|
|
229
|
+
: DEFAULT_QUIET_ZONE;
|
|
230
|
+
const hasText = showText !== false;
|
|
231
|
+
// Positions are counted in whole modules and scaled once, so no rounding error accumulates
|
|
232
|
+
// from bar to bar.
|
|
233
|
+
const bars = [];
|
|
234
|
+
let cursor = margin;
|
|
235
|
+
widths.forEach((width, index) => {
|
|
236
|
+
if (index % 2 === 0) {
|
|
237
|
+
const barWidth = formatNumber(width * moduleSize);
|
|
238
|
+
bars.push(`M${formatNumber(cursor * moduleSize)} 0h${barWidth}v${formatNumber(barHeight)}h-${barWidth}z`);
|
|
239
|
+
}
|
|
240
|
+
cursor += width;
|
|
241
|
+
});
|
|
242
|
+
const totalWidth = formatNumber((cursor + margin) * moduleSize);
|
|
243
|
+
const totalHeight = formatNumber(barHeight + (hasText ? textSize * TEXT_LINE_EM : 0));
|
|
244
|
+
const hasTitle = typeof title === "string" && title.length > 0;
|
|
245
|
+
const label = escapeXml(hasTitle ? title : text);
|
|
246
|
+
const fill = escapeXml(foreground);
|
|
247
|
+
const parts = [
|
|
248
|
+
`<svg xmlns="http://www.w3.org/2000/svg" width="${totalWidth}${lengthUnit}" height="${totalHeight}${lengthUnit}" viewBox="0 0 ${totalWidth} ${totalHeight}" role="img" aria-label="${label}">`,
|
|
249
|
+
hasTitle ? `<title>${label}</title>` : "",
|
|
250
|
+
`<rect width="${totalWidth}" height="${totalHeight}" fill="${escapeXml(background)}"/>`,
|
|
251
|
+
`<path fill="${fill}" shape-rendering="crispEdges" d="${bars.join("")}"/>`,
|
|
252
|
+
hasText
|
|
253
|
+
? `<text x="${formatNumber(((cursor + margin) * moduleSize) / 2)}" y="${formatNumber(barHeight + textSize * TEXT_BASELINE_EM)}" fill="${fill}" font-family="monospace" font-size="${formatNumber(textSize)}" text-anchor="middle">${escapeXml(text)}</text>`
|
|
254
|
+
: "",
|
|
255
|
+
"</svg>",
|
|
256
|
+
];
|
|
257
|
+
return parts.join("");
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
/** Page sizes of common shipping labels, in millimetres: 100×100 and 100×150 thermal, A4. */
|
|
261
|
+
const LABEL_SIZES = Object.freeze({
|
|
262
|
+
"100x100": Object.freeze({ width: 100, height: 100 }),
|
|
263
|
+
"100x150": Object.freeze({ width: 100, height: 150 }),
|
|
264
|
+
a4: Object.freeze({ width: 210, height: 297 }),
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
/** Returns the `@page` rule that prints on a `size` label edge to edge (no page margin). */
|
|
268
|
+
const labelPrintCss = (size) => {
|
|
269
|
+
// Own keys only: "toString" or "__proto__" must not resolve through the prototype.
|
|
270
|
+
if (typeof size !== "string" || !Object.hasOwn(LABEL_SIZES, size)) {
|
|
271
|
+
const expected = Object.keys(LABEL_SIZES)
|
|
272
|
+
.map((key) => `"${key}"`)
|
|
273
|
+
.join(", ");
|
|
274
|
+
throw new TypeError(`labelPrintCss: unknown label size ${String(size)}; expected one of ${expected}`);
|
|
275
|
+
}
|
|
276
|
+
const { width, height } = LABEL_SIZES[size];
|
|
277
|
+
return `@page { size: ${width}mm ${height}mm; margin: 0; }`;
|
|
278
|
+
};
|
|
279
|
+
|
|
280
|
+
exports.LABEL_SIZES = LABEL_SIZES;
|
|
281
|
+
exports.code128Svg = code128Svg;
|
|
282
|
+
exports.encodeCode128 = encodeCode128;
|
|
283
|
+
exports.labelPrintCss = labelPrintCss;
|
|
284
|
+
//# sourceMappingURL=index.cjs.map
|