@wirunrom/hqr-generate 0.4.4 → 0.5.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 CHANGED
@@ -1,21 +1,21 @@
1
- The MIT License (MIT)
2
-
3
- Copyright (c) 2026 Wirunrom
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
13
- all 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
21
- THE SOFTWARE.
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Wirunrom
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
13
+ all 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
21
+ THE SOFTWARE.
package/README.md CHANGED
@@ -1,462 +1,165 @@
1
- # @wirunrom/hqr-generate
2
-
3
- A high-performance **QR Code generator and decoder**
4
- focused on **maximum scan reliability** and a **binary-first design**,
5
- powered by **Rust + WebAssembly (WASM)**.
6
-
7
- This library intentionally keeps its core **simple, fast, and environment-agnostic**.
8
-
9
- ---
10
-
11
- ## Design Philosophy
12
-
13
- This library follows a **byte-first architecture**:
14
-
15
- - Core APIs always return **raw binary (`Uint8Array`)**
16
- - No Base64 or Data URL generation in the core
17
- - Rendering is handled at the **UI / presentation layer**
18
- - Works consistently across:
19
- - Browser
20
- - React
21
- - Next.js (Client & Server Components)
22
- - Node.js (SSR / API routes)
23
-
24
- This design ensures:
25
-
26
- - Better performance
27
- - Lower memory usage
28
- - Clean separation between data and presentation
29
- - Predictable behavior across environments
30
-
31
- ---
32
-
33
- ## Features
34
-
35
- - High-contrast **black & white only** QR codes
36
- (scan reliability first)
37
- - Deterministic and consistent output
38
- - **Raw PNG bytes (`Uint8Array`)** generation
39
- - **SVG output** for resolution-independent rendering
40
- - QR decoding from:
41
- - `Uint8Array`
42
- - Browser `ImageData`
43
- - Optimized for:
44
- - React
45
- - Next.js (App Router & SSR)
46
- - Plain HTML / JavaScript
47
- - Lightweight and fast (Rust + WASM)
48
-
49
- ---
50
-
51
- ## Installation
52
-
53
- ```bash
54
- npm i @wirunrom/hqr-generate
55
- # or
56
- yarn add @wirunrom/hqr-generate
57
- # or
58
- pnpm i @wirunrom/hqr-generate
59
- ```
60
-
61
- ## API Reference
62
-
63
- | Function | Parameters | Returns |
64
- | ------------------------------ | --------------------------------------------- | --------------------------------- |
65
- | `generate(text, options?)` | `text: string`<br>`options?: GenerateOptions` | `Promise<Uint8Array>` (PNG bytes) |
66
- | `generate_svg(text, options?)` | `text: string`<br>`options?: GenerateOptions` | `Promise<string>` (SVG markup) |
67
- | `decode(input)` | `input: Uint8Array \| ImageData` | `Promise<string>` (decoded text) |
68
-
69
- ### GenerateOptions
70
-
71
- | Option | Type | Default | Description |
72
- | -------- | -------------------------- | ------- | ----------------------------- |
73
- | `size` | `number` | `320` | Output image size (px) |
74
- | `margin` | `number` | `4` | Quiet zone / margin (modules) |
75
- | `ecc` | `'L' \| 'M' \| 'Q' \| 'H'` | `'Q'` | Error correction level |
76
-
77
- ### Notes
78
-
79
- - All generate APIs return **raw data**, not Base64 or Data URLs.
80
- - PNG output is returned as **binary bytes (`Uint8Array`)**.
81
- - SVG output is returned as **plain string markup**.
82
-
83
- ---
84
-
85
- ## Client-side Usage (Recommended)
86
-
87
- When rendering QR codes in the browser or a Client Component,
88
- use the React hook provided by the `/react` entry.
89
-
90
- The hook automatically:
91
-
92
- - Calls the core API
93
- - Converts binary data to a `Blob URL`
94
- - Handles cleanup (`URL.revokeObjectURL`)
95
-
96
- ```tsx
97
- "use client";
98
-
99
- import { useGenerate } from "@wirunrom/hqr-generate/react";
100
-
101
- export default function QR() {
102
- const { src, loading } = useGenerate("hello world", {
103
- size: 320,
104
- ecc: "Q",
105
- });
106
-
107
- if (loading) return <p>Loading…</p>;
108
- return <img src={src ?? ""} alt="QR Code" />;
109
- }
110
- ```
111
-
112
- Internally, the hook performs:
113
-
114
- ```
115
- Uint8Array Blob → blob: URL
116
- ```
117
-
118
- ---
119
-
120
- ## Next.js SSR / Route Handlers
121
-
122
- When generating QR codes on the server,
123
- the API returns raw PNG bytes.
124
-
125
- ```ts
126
- import { generate } from "@wirunrom/hqr-generate";
127
-
128
- export async function GET() {
129
- const bytes = await generate("hello ssr");
130
-
131
- return new Response(bytes, {
132
- headers: {
133
- "Content-Type": "image/png",
134
- "Cache-Control": "public, max-age=60",
135
- },
136
- });
137
- }
138
- ```
139
-
140
- No Base64 conversion is required.
141
-
142
- ---
143
-
144
- ## SSR → Client Rendering
145
-
146
- If you generate QR codes on the server
147
- but render them on the client:
148
-
149
- 1. Generate bytes on the server
150
- 2. Convert bytes to a `Blob` on the client
151
-
152
- ```tsx
153
- // Server Component
154
- import { generate } from "@wirunrom/hqr-generate";
155
- import ClientQr from "./ClientQr";
156
-
157
- export default async function Page() {
158
- const bytes = await generate("hello ssr");
159
- return <ClientQr bytes={bytes} />;
160
- }
161
- ```
162
-
163
- ```tsx
164
- // Client Component
165
- "use client";
166
-
167
- import { useEffect, useState } from "react";
168
-
169
- export default function ClientQr({ bytes }: { bytes: Uint8Array }) {
170
- const [src, setSrc] = useState<string>("");
171
-
172
- useEffect(() => {
173
- const blob = new Blob([bytes], { type: "image/png" });
174
- const url = URL.createObjectURL(blob);
175
- setSrc(url);
176
- return () => URL.revokeObjectURL(url);
177
- }, [bytes]);
178
-
179
- return <img src={src} alt="QR Code" />;
180
- }
181
- ```
182
-
183
- ---
184
-
185
- ## Generate QR Code (SVG)
186
-
187
- If you want to generate a QR code as **SVG** in React,
188
- use the `useGenerateSvg` hook from the `/react` entry.
189
-
190
- This hook:
191
-
192
- - Calls the core `generate_svg()` API
193
- - Converts SVG markup into a `Blob URL`
194
- - Returns a `src` that can be used directly in `<img />`
195
- - Automatically handles cleanup (`URL.revokeObjectURL`)
196
-
197
- ### Example
198
-
199
- ```tsx
200
- "use client";
201
-
202
- import { useGenerateSvg } from "@wirunrom/hqr-generate/react";
203
-
204
- export default function QrSvg() {
205
- const { src, loading } = useGenerateSvg("hello svg", {
206
- size: 320,
207
- ecc: "Q",
208
- });
209
-
210
- if (loading) return <p>Loading…</p>;
211
-
212
- return src && <img src={src} alt="QR Code (SVG)" />;
213
- }
214
- ```
215
-
216
- ---
217
-
218
- ### Returned Values
219
-
220
- ```ts
221
- const {
222
- src, // string | null (Blob URL for <img>)
223
- svg, // string | null (raw SVG markup)
224
- loading,
225
- error,
226
- } = useGenerateSvg(text, options);
227
- ```
228
-
229
- ### Design Notes
230
-
231
- - SVG generation is **data-first** at the core level
232
- - Rendering decisions are handled in the React hook
233
- - `src` is provided for convenience and safety
234
- - Advanced users can use `svg` to render inline SVG manually if needed
235
-
236
- ---
237
-
238
- ## Decode QR Code (Client-side)
239
-
240
- To decode a QR code in the browser,
241
- use the `useDecode` hook from the `/react` entry.
242
-
243
- > ⚠️ `useDecode` accepts **ImageData only**
244
- > If you have PNG bytes or an image URL, convert them to `ImageData` first using Canvas APIs.
245
-
246
- ### Example (decode from Canvas ImageData)
247
-
248
- ```tsx
249
- "use client";
250
-
251
- import { useDecode } from "@wirunrom/hqr-generate/react";
252
-
253
- export default function DecodeQr({ imageData }: { imageData: ImageData }) {
254
- const { text, loading, error } = useDecode(imageData);
255
-
256
- if (loading) return <p>Decoding…</p>;
257
- if (error) return <p>Failed to decode</p>;
258
-
259
- return <p>Decoded text: {text}</p>;
260
- }
261
- ```
262
-
263
- ---
264
-
265
- ## `useDecode` API Reference
266
-
267
- ### Signature
268
-
269
- ```ts
270
- function useDecode(input?: ImageData): {
271
- text: string | null;
272
- loading: boolean;
273
- error: unknown | null;
274
- };
275
- ```
276
-
277
- ### Parameters
278
-
279
- | Name | Type | Description |
280
- | ------- | ---------------------- | -------------------------------------------------------------------- |
281
- | `input` | `ImageData` (optional) | Image data containing a QR code. Decoding is skipped if `undefined`. |
282
-
283
- ### Returns
284
-
285
- | Field | Type | Description |
286
- | --------- | ----------------- | --------------------------------------------- |
287
- | `text` | `string \| null` | Decoded QR text, or `null` if not decoded yet |
288
- | `loading` | `boolean` | `true` while decoding is in progress |
289
- | `error` | `unknown \| null` | Error object if decoding fails |
290
-
291
- ---
292
-
293
- ### Design Notes
294
-
295
- - `useDecode` is **browser-only**
296
- - It does **not** perform:
297
- - image loading
298
- - network requests
299
- - Base64 conversion
300
-
301
- - This keeps decoding:
302
- - predictable
303
- - side-effect free
304
- - consistent with the binary-first core API
305
-
306
- If you have an image URL or PNG bytes,
307
- convert them to `ImageData` explicitly before calling `useDecode`.
308
-
309
- ---
310
-
311
- ## Plain HTML / Vanilla JavaScript Usage
312
-
313
- The library can be used directly in **plain HTML** using ES Modules.
314
- No framework or build tool is required.
315
-
316
- > Note: The example assumes you are serving files over HTTP
317
- > (do not open the file via `file://`), because WASM requires HTTP.
318
-
319
- ---
320
-
321
- ### Generate QR Code (PNG)
322
-
323
- ```html
324
- <!doctype html>
325
- <html lang="en">
326
- <body>
327
- <h3>Generate PNG QR</h3>
328
-
329
- <input id="text" value="hello world" />
330
- <button id="btn">Generate</button>
331
-
332
- <br /><br />
333
- <img id="img" />
334
-
335
- <script type="module">
336
- import { generate } from "https://esm.sh/@wirunrom/hqr-generate";
337
-
338
- const btn = document.getElementById("btn");
339
- const img = document.getElementById("img");
340
- const input = document.getElementById("text");
341
-
342
- btn.onclick = async () => {
343
- const bytes = await generate(input.value, {
344
- size: 256,
345
- ecc: "Q",
346
- });
347
-
348
- const blob = new Blob([bytes], { type: "image/png" });
349
- const url = URL.createObjectURL(blob);
350
- img.src = url;
351
- };
352
- </script>
353
- </body>
354
- </html>
355
- ```
356
-
357
- ---
358
-
359
- ### Generate QR Code (SVG)
360
-
361
- ```html
362
- <!doctype html>
363
- <html lang="en">
364
- <body>
365
- <h3>Generate SVG QR</h3>
366
-
367
- <input id="text" value="hello world" />
368
- <button id="btn">Generate</button>
369
-
370
- <br /><br />
371
- <div id="svg"></div>
372
-
373
- <script type="module">
374
- import { generate_svg } from "https://esm.sh/@wirunrom/hqr-generate";
375
-
376
- const btn = document.getElementById("btn");
377
- const input = document.getElementById("text");
378
- const container = document.getElementById("svg");
379
-
380
- btn.onclick = async () => {
381
- const svg = await generate_svg(input.value, {
382
- size: 256,
383
- ecc: "Q",
384
- });
385
-
386
- container.innerHTML = svg;
387
- };
388
- </script>
389
- </body>
390
- </html>
391
- ```
392
-
393
- ---
394
-
395
- ### Decode QR Code
396
-
397
- ```html
398
- <!doctype html>
399
- <html lang="en">
400
- <body>
401
- <h3>Decode QR</h3>
402
-
403
- <input type="file" id="file" accept="image/*" />
404
- <p id="result"></p>
405
-
406
- <script type="module">
407
- import { decode } from "https://esm.sh/@wirunrom/hqr-generate";
408
-
409
- const fileInput = document.getElementById("file");
410
- const result = document.getElementById("result");
411
-
412
- fileInput.onchange = async () => {
413
- const file = fileInput.files?.[0];
414
- if (!file) return;
415
-
416
- const img = new Image();
417
- img.src = URL.createObjectURL(file);
418
-
419
- img.onload = async () => {
420
- const canvas = document.createElement("canvas");
421
- canvas.width = img.width;
422
- canvas.height = img.height;
423
-
424
- const ctx = canvas.getContext("2d");
425
- ctx.drawImage(img, 0, 0);
426
-
427
- const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
428
- const text = await decode(imageData);
429
-
430
- result.textContent = `Decoded text: ${text}`;
431
- };
432
- };
433
- </script>
434
- </body>
435
- </html>
436
- ```
437
-
438
- ---
439
-
440
- ## What This Library Does NOT Do
441
-
442
- - ❌ No Base64 or Data URL generation in the core
443
- - ❌ No JPG / WebP / GIF rendering
444
- - ❌ No DOM or framework-specific logic outside `/react`
445
-
446
- ---
447
-
448
- ## Summary
449
-
450
- - Core → returns `Uint8Array`
451
- - React hooks → handle `Blob` conversion
452
- - SSR → returns raw bytes or `Response`
453
- - Client → renders via `blob:` URL
454
-
455
- > Keep data binary.
456
- > Convert only at the UI boundary.
457
-
458
- ---
459
-
460
- ## Changelog
461
-
462
- See [CHANGELOG.md](./CHANGELOG.md)
1
+ # @wirunrom/hqr-generate
2
+
3
+ Fast, scan-reliable **QR code generator and decoder** powered by **Rust + WebAssembly**.
4
+
5
+ Binary-first: core APIs return raw `Uint8Array` (PNG) or `string` (SVG). Rendering and Blob conversion are handled at the UI layer, so the library works identically in the browser, React, Next.js (App Router / SSR / Route Handlers), and Node.js.
6
+
7
+ ---
8
+
9
+ ## Features
10
+
11
+ - High-contrast **black & white only** — scan reliability first
12
+ - **1-bit grayscale PNG** output — tiny payloads
13
+ - **SVG** emitted as a single compact `<path>` — resolution-independent
14
+ - QR **decoding** from `Uint8Array` or browser `ImageData`
15
+ - Optional React hooks (`react` is an optional peer dep)
16
+
17
+ ---
18
+
19
+ ## Performance
20
+
21
+ Sub-millisecond end-to-end generation on modern hardware. Benchmarked on Apple Silicon (release + LTO) for a typical URL payload at `size: 320`:
22
+
23
+ | Pipeline | Time | Output size |
24
+ | ------------------------- | ------ | ----------- |
25
+ | `generate` → 1-bit PNG | ~96 µs | ~5.5 KB |
26
+ | `generate_svg` → `<path>` | ~90 µs | ~5.2 KB |
27
+
28
+ Behind the numbers: QR encoding via [`fast_qr`](https://crates.io/crates/fast_qr), direct rasterization into a 1-bit PNG buffer (no 8-bit intermediate), run-length-merged SVG subpaths with relative commands, and React hooks that track primitive option fields so inline `opts` don't re-trigger WASM on every render.
29
+
30
+ Run the suite locally with `cargo bench --bench generate`.
31
+
32
+ ---
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ npm i @wirunrom/hqr-generate
38
+ # or: yarn add / pnpm i
39
+ ```
40
+
41
+ ---
42
+
43
+ ## API
44
+
45
+ | Function | Parameters | Returns |
46
+ | ------------------------------ | --------------------------------------------- | --------------------------- |
47
+ | `generate(text, options?)` | `text: string`, `options?: GenerateOptions` | `Promise<Uint8Array>` (PNG) |
48
+ | `generate_svg(text, options?)` | `text: string`, `options?: GenerateOptions` | `Promise<string>` (SVG) |
49
+ | `decode(input)` | `input: Uint8Array \| ImageData` | `Promise<string>` |
50
+
51
+ ### `GenerateOptions`
52
+
53
+ | Option | Type | Default | Description |
54
+ | -------- | -------------------------- | ------- | ----------------------------- |
55
+ | `size` | `number` | `320` | Output image size (px) |
56
+ | `margin` | `number` | `4` | Quiet zone / margin (modules) |
57
+ | `ecc` | `'L' \| 'M' \| 'Q' \| 'H'` | `'Q'` | Error correction level |
58
+
59
+ PNG output is raw bytes (`Uint8Array`), SVG output is plain markup (`string`). No Base64 or Data URL wrapping.
60
+
61
+ ---
62
+
63
+ ## Usage
64
+
65
+ ### React (client-side)
66
+
67
+ The `/react` entry provides hooks that call the core API, wrap the result in a `Blob URL`, and revoke it on cleanup.
68
+
69
+ ```tsx
70
+ "use client";
71
+ import { useGenerate, useGenerateSvg } from "@wirunrom/hqr-generate/react";
72
+
73
+ export function PngQr() {
74
+ const { src, loading } = useGenerate("hello world", { size: 320, ecc: "Q" });
75
+ if (loading) return <p>Loading…</p>;
76
+ return <img src={src ?? ""} alt="QR" />;
77
+ }
78
+
79
+ export function SvgQr() {
80
+ const { src, svg, loading } = useGenerateSvg("hello svg", { size: 320 });
81
+ if (loading) return <p>Loading…</p>;
82
+ return <img src={src ?? ""} alt="QR" />; // or render `svg` inline
83
+ }
84
+ ```
85
+
86
+ Both hooks return `{ src, bytes|svg, loading, error }`.
87
+
88
+ ### Next.js SSR / Route Handlers
89
+
90
+ Return the raw PNG bytes directly — no Base64.
91
+
92
+ ```ts
93
+ import { generate } from "@wirunrom/hqr-generate";
94
+
95
+ export async function GET() {
96
+ const bytes = await generate("hello ssr");
97
+ return new Response(bytes, {
98
+ headers: {
99
+ "Content-Type": "image/png",
100
+ "Cache-Control": "public, max-age=60",
101
+ },
102
+ });
103
+ }
104
+ ```
105
+
106
+ To generate on the server and render on the client, pass bytes to a client component and convert to a `Blob URL` there:
107
+
108
+ ```tsx
109
+ // ClientQr.tsx
110
+ "use client";
111
+ import { useEffect, useState } from "react";
112
+
113
+ export default function ClientQr({ bytes }: { bytes: Uint8Array }) {
114
+ const [src, setSrc] = useState("");
115
+ useEffect(() => {
116
+ const url = URL.createObjectURL(new Blob([bytes], { type: "image/png" }));
117
+ setSrc(url);
118
+ return () => URL.revokeObjectURL(url);
119
+ }, [bytes]);
120
+ return <img src={src} alt="QR" />;
121
+ }
122
+ ```
123
+
124
+ ### Decoding
125
+
126
+ ```tsx
127
+ "use client";
128
+ import { useDecode } from "@wirunrom/hqr-generate/react";
129
+
130
+ export default function DecodeQr({ imageData }: { imageData: ImageData }) {
131
+ const { text, loading, error } = useDecode(imageData);
132
+ if (loading) return <p>Decoding…</p>;
133
+ if (error) return <p>Failed to decode</p>;
134
+ return <p>{text}</p>;
135
+ }
136
+ ```
137
+
138
+ `useDecode` accepts **`ImageData` only**. If you have PNG bytes or a URL, draw them to a canvas first and call `ctx.getImageData(...)`. The core `decode()` also accepts raw `Uint8Array` (PNG/JPG/WebP) — use that for server-side decoding.
139
+
140
+ ### Vanilla JS
141
+
142
+ ES modules over HTTP (WASM won't load from `file://`):
143
+
144
+ ```html
145
+ <script type="module">
146
+ import { generate, generate_svg, decode } from "https://esm.sh/@wirunrom/hqr-generate";
147
+
148
+ // PNG
149
+ const bytes = await generate("hello", { size: 256 });
150
+ const url = URL.createObjectURL(new Blob([bytes], { type: "image/png" }));
151
+ document.querySelector("img").src = url;
152
+
153
+ // SVG
154
+ document.querySelector("#svg").innerHTML = await generate_svg("hello");
155
+
156
+ // Decode (from a canvas ImageData or raw PNG/JPG Uint8Array)
157
+ // const text = await decode(imageData);
158
+ </script>
159
+ ```
160
+
161
+ ---
162
+
163
+ ## Changelog
164
+
165
+ See [CHANGELOG.md](./CHANGELOG.md).