@journey-to-code/symbology 0.0.0-stage → 0.3.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/mcp.js ADDED
@@ -0,0 +1,191 @@
1
+ // A Model Context Protocol server over stdio, with no dependencies. The client's own model calls
2
+ // these tools, so no API key reaches this package. Run it with `bin/symbology-mcp.js`, or add it
3
+ // to a client as the command `npx -y -p @journey-to-code/symbology symbology-mcp`.
4
+ //
5
+ // Tools: design_qr (style in, decoder-verified SVG out), list_presets, describe_style_schema.
6
+ // It speaks both protocol eras: stateless requests carrying
7
+ // `_meta["io.modelcontextprotocol/protocolVersion"]` (2026-07-28) and the `initialize` handshake.
8
+
9
+ import { createInterface } from 'node:readline';
10
+ import { loadQr } from './qr.js';
11
+ import { styleSchema, styleWithLogoSchema } from './schema.js';
12
+ import { styledQr, PRESETS } from './style.js';
13
+
14
+ const MODERN = ['2026-07-28'];
15
+ const LEGACY = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
16
+ const SERVER_INFO = { name: 'symbology', title: 'Symbology QR designer', version: '0.3.0' };
17
+ const INSTRUCTIONS =
18
+ 'Design scannable, branded QR codes for URLs. Call describe_style_schema or list_presets first if unsure, then design_qr with the URL and a style. ' +
19
+ 'If design_qr reports errors, change only what they name and call it again. Every returned SVG has been decoded back to the URL.';
20
+
21
+ const resultSchema = {
22
+ type: 'object',
23
+ properties: {
24
+ ok: { type: 'boolean' },
25
+ svg: { type: ['string', 'null'] },
26
+ errors: { type: 'array', items: { type: 'string' } },
27
+ warnings: { type: 'array', items: { type: 'string' } },
28
+ level: { type: 'string' },
29
+ version: { type: 'integer' },
30
+ score: { type: 'integer' },
31
+ printMinWidthMm: { type: 'number' },
32
+ },
33
+ required: ['ok', 'errors', 'warnings'],
34
+ };
35
+
36
+ export const TOOLS = [
37
+ {
38
+ name: 'design_qr',
39
+ title: 'Design a QR code',
40
+ description:
41
+ 'Draw a styled QR code for a URL and verify it scans. Returns SVG markup and a report; when ok is false, errors say exactly what to change. Pass logo.svg for a centred logo (a small flat SVG with a viewBox).',
42
+ inputSchema: {
43
+ type: 'object',
44
+ additionalProperties: false,
45
+ required: ['url'],
46
+ properties: {
47
+ url: { type: 'string', minLength: 1, maxLength: 213, description: 'The link to encode. Shorter URLs give smaller, sturdier codes.' },
48
+ style: { ...stripMeta(styleWithLogoSchema), description: 'How to draw it. All fields optional.' },
49
+ includeSvg: { type: 'boolean', description: 'Return the SVG markup (default true).' },
50
+ },
51
+ },
52
+ outputSchema: resultSchema,
53
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
54
+ },
55
+ {
56
+ name: 'list_presets',
57
+ title: 'List style presets',
58
+ description: 'Named starting styles for design_qr, with their settings.',
59
+ inputSchema: { type: 'object', additionalProperties: false, properties: {} },
60
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
61
+ },
62
+ {
63
+ name: 'describe_style_schema',
64
+ title: 'Describe the style schema',
65
+ description: 'The JSON Schema for design_qr\'s style argument, with what each field does to the printed code.',
66
+ inputSchema: { type: 'object', additionalProperties: false, properties: {} },
67
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
68
+ },
69
+ ];
70
+
71
+ function stripMeta(schema) {
72
+ const { $schema, $id, ...rest } = schema;
73
+ return rest;
74
+ }
75
+
76
+ const text = (value) => [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }];
77
+
78
+ /** Run one tool. Tool failures come back as `isError` results, as the protocol asks. */
79
+ export async function callTool(qr, name, args = {}) {
80
+ if (name === 'list_presets') return { content: text(PRESETS), structuredContent: { presets: PRESETS } };
81
+ if (name === 'describe_style_schema') return { content: text(styleSchema), structuredContent: { schema: styleWithLogoSchema } };
82
+ if (name !== 'design_qr') return null;
83
+ if (typeof args.url !== 'string' || !args.url) return { isError: true, content: text('url: required') };
84
+ const style = args.style ?? {};
85
+ if (typeof style !== 'object' || Array.isArray(style)) return { isError: true, content: text('style: must be an object') };
86
+ const { svg, report } = styledQr(qr, args.url, style);
87
+ const summary = {
88
+ ok: report.ok,
89
+ svg: args.includeSvg === false ? null : svg,
90
+ errors: report.errors,
91
+ warnings: report.warnings,
92
+ ...(report.level ? { level: report.level, version: report.version, score: report.score, printMinWidthMm: report.print.minWidthMm } : {}),
93
+ };
94
+ const lines = report.ok
95
+ ? [`Verified: decodes to ${args.url} (level ${report.level}, version ${report.version}, score ${report.score}/100). Print at least ${report.print.minWidthMm} mm wide.`]
96
+ : ['Refused; nothing was drawn. Fix these and call design_qr again:', ...report.errors.map((error) => `- ${error}`)];
97
+ if (report.warnings.length) lines.push('Warnings:', ...report.warnings.map((warning) => `- ${warning}`));
98
+ const content = text(lines.join('\n'));
99
+ if (summary.svg) content.push({ type: 'text', text: summary.svg });
100
+ return { content, structuredContent: summary, isError: !report.ok };
101
+ }
102
+
103
+ const PROTOCOL_KEY = 'io.modelcontextprotocol/protocolVersion';
104
+ const error = (id, code, message, data) => ({ jsonrpc: '2.0', id, error: { code, message, ...(data ? { data } : {}) } });
105
+ const result = (id, value) => ({ jsonrpc: '2.0', id, result: value });
106
+
107
+ /**
108
+ * A request handler. `handle(message)` resolves to the response object, or null for
109
+ * notifications. State is only the legacy era's negotiated version, per process.
110
+ */
111
+ export function createServer({ qr } = {}) {
112
+ let qrPromise = qr ? Promise.resolve(qr) : null;
113
+ let legacyVersion = null;
114
+
115
+ async function handle(message) {
116
+ if (!message || message.jsonrpc !== '2.0' || typeof message.method !== 'string') {
117
+ return message && 'id' in message ? error(message.id ?? null, -32600, 'Invalid Request') : null;
118
+ }
119
+ const { id, method } = message;
120
+ const params = message.params ?? {};
121
+ const notification = !('id' in message);
122
+ if (notification) return null;
123
+
124
+ if (method === 'initialize') {
125
+ const requested = params.protocolVersion;
126
+ legacyVersion = LEGACY.includes(requested) ? requested : LEGACY[0];
127
+ return result(id, { protocolVersion: legacyVersion, capabilities: { tools: {} }, serverInfo: SERVER_INFO, instructions: INSTRUCTIONS });
128
+ }
129
+ if (method === 'ping') return result(id, {});
130
+
131
+ const declared = params._meta?.[PROTOCOL_KEY];
132
+ const modern = declared != null;
133
+ if (modern && !MODERN.includes(declared)) {
134
+ return error(id, -32022, 'Unsupported protocol version', { supported: [...MODERN, ...LEGACY], requested: declared });
135
+ }
136
+ if (!modern && !legacyVersion && method !== 'server/discover') {
137
+ return error(id, -32600, `Missing _meta["${PROTOCOL_KEY}"]; send it on every request, or call initialize first`);
138
+ }
139
+ const complete = (value) => result(id, modern ? { resultType: 'complete', ...value } : value);
140
+
141
+ switch (method) {
142
+ case 'server/discover':
143
+ return result(id, {
144
+ resultType: 'complete',
145
+ supportedVersions: [...MODERN, ...LEGACY],
146
+ capabilities: { tools: {} },
147
+ _meta: { 'io.modelcontextprotocol/serverInfo': SERVER_INFO },
148
+ instructions: INSTRUCTIONS,
149
+ });
150
+ case 'tools/list':
151
+ return complete({ tools: TOOLS });
152
+ case 'tools/call': {
153
+ if (typeof params.name !== 'string') return error(id, -32602, 'tools/call: name is required');
154
+ if (!TOOLS.some((tool) => tool.name === params.name)) return error(id, -32602, `Unknown tool: ${params.name}`);
155
+ const instance = await (qrPromise ??= loadQr());
156
+ try {
157
+ return complete(await callTool(instance, params.name, params.arguments ?? {}));
158
+ } catch (cause) {
159
+ return complete({ isError: true, content: text(`design_qr failed: ${cause?.message ?? cause}`) });
160
+ }
161
+ }
162
+ default:
163
+ return error(id, -32601, `Method not found: ${method}`);
164
+ }
165
+ }
166
+
167
+ return { handle };
168
+ }
169
+
170
+ /** Serve newline-delimited JSON-RPC on stdin/stdout. Logs go to stderr only. */
171
+ export function serveStdio({ input = process.stdin, output = process.stdout } = {}) {
172
+ const server = createServer();
173
+ const lines = createInterface({ input, crlfDelay: Infinity });
174
+ let queue = Promise.resolve();
175
+ lines.on('line', (line) => {
176
+ if (!line.trim()) return;
177
+ queue = queue.then(async () => {
178
+ let message;
179
+ try {
180
+ message = JSON.parse(line);
181
+ } catch {
182
+ output.write(`${JSON.stringify(error(null, -32700, 'Parse error'))}\n`);
183
+ return;
184
+ }
185
+ const batch = Array.isArray(message);
186
+ const responses = (await Promise.all((batch ? message : [message]).map(server.handle))).filter(Boolean);
187
+ if (responses.length) output.write(`${JSON.stringify(batch ? responses : responses[0])}\n`);
188
+ }).catch((cause) => process.stderr.write(`symbology-mcp: ${cause?.stack ?? cause}\n`));
189
+ });
190
+ return lines;
191
+ }
package/package.json CHANGED
@@ -1,6 +1,75 @@
1
1
  {
2
2
  "name": "@journey-to-code/symbology",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0",
4
+ "description": "Dependency-free QR and linear barcode encoding and decoding in Rust, JavaScript, and a Zubra web component",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/journey-to-code-org/symbology.git",
10
+ "directory": "js"
11
+ },
12
+ "keywords": [
13
+ "qr",
14
+ "barcode",
15
+ "symbology",
16
+ "webassembly",
17
+ "web-component",
18
+ "zubra"
19
+ ],
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "exports": {
24
+ ".": {
25
+ "types": "./qr.d.ts",
26
+ "import": "./qr.js"
27
+ },
28
+ "./style": {
29
+ "types": "./style.d.ts",
30
+ "import": "./style.js"
31
+ },
32
+ "./ai": {
33
+ "types": "./ai.d.ts",
34
+ "import": "./ai.js"
35
+ },
36
+ "./mcp": "./mcp.js",
37
+ "./style.schema.json": "./style.schema.json",
38
+ "./symbology-code": {
39
+ "types": "./dist/symbology-code.d.ts",
40
+ "import": "./dist/symbology-code.js"
41
+ },
42
+ "./symbology.wasm": "./symbology.wasm"
43
+ },
44
+ "bin": {
45
+ "symbology-mcp": "bin/symbology-mcp.js"
46
+ },
47
+ "types": "./qr.d.ts",
48
+ "files": [
49
+ "qr.js",
50
+ "qr.d.ts",
51
+ "style.js",
52
+ "style.d.ts",
53
+ "schema.js",
54
+ "style.schema.json",
55
+ "ai.js",
56
+ "ai.d.ts",
57
+ "mcp.js",
58
+ "bin/",
59
+ "symbology.wasm",
60
+ "dist/",
61
+ "components/"
62
+ ],
63
+ "engines": {
64
+ "node": ">=20"
65
+ },
66
+ "scripts": {
67
+ "build": "node scripts/build.mjs",
68
+ "prepack": "npm run build",
69
+ "test": "node --test --test-concurrency=1 'test/*.test.js'"
70
+ },
71
+ "devDependencies": {
72
+ "@zubra/compiler": "5.9.2",
73
+ "playwright-core": "^1.65.0"
74
+ }
75
+ }
package/qr.d.ts ADDED
@@ -0,0 +1,136 @@
1
+ export type QrErrorCode =
2
+ | 'empty'
3
+ | 'too-long'
4
+ | 'not-found'
5
+ | 'unsupported'
6
+ | 'uncorrectable'
7
+ | 'malformed'
8
+ | 'bad-frame'
9
+ | 'frame-too-large'
10
+ | 'logo-too-large'
11
+ | 'invalid-options';
12
+ export type Level = 'L' | 'M' | 'Q' | 'H';
13
+ export type Role = 'data' | 'remainder' | 'finder' | 'separator' | 'timing' | 'alignment' | 'format' | 'version' | 'dark-module';
14
+ /** Role names, indexed by the numbers in `Layout.roles`. */
15
+ export const ROLES: readonly Role[];
16
+
17
+ export interface DesignOptions {
18
+ /** A fixed level, or `'auto'` (default) for the strongest that fits: H, then Q, M, L. */
19
+ level?: Level | 'auto';
20
+ /** Versions to consider, 1–10. Defaults 1 and 10. */
21
+ minVersion?: number;
22
+ maxVersion?: number;
23
+ /** A fixed mask 0–7, or `'auto'` (default). */
24
+ mask?: number | 'auto';
25
+ /** A centred logo area; sizes are fractions of the symbol side (at most 0.6). */
26
+ logo?: { shape?: 'circle' | 'square'; size?: number; width?: number; height?: number; padding?: number } | null;
27
+ /** Share of each block's correction budget the logo may use, (0, 1]. Default 0.5. */
28
+ safety?: number;
29
+ }
30
+
31
+ export interface LogoBudget {
32
+ blocks: number;
33
+ /** Check codewords per block. */
34
+ check: number;
35
+ /** Codeword errors a block can correct: `check / 2`. */
36
+ correctable: number;
37
+ /** Spoiled codewords a block may have, after the safety share. */
38
+ allowed: number;
39
+ /** Spoiled codewords per block. */
40
+ damaged: number[];
41
+ worst: number;
42
+ /** Corrections the worst block has left for wear and glare. */
43
+ spare: number;
44
+ coveredModules: number;
45
+ }
46
+
47
+ /** A planned symbol. Arrays are `size * size`, row-major. */
48
+ export interface Layout extends Code {
49
+ level: Level;
50
+ version: number;
51
+ mask: number;
52
+ /** Indices into `ROLES`. */
53
+ roles: Uint8Array;
54
+ /** 1 where the logo area lies; those modules are left out when drawn. */
55
+ covered: Uint8Array;
56
+ budget: LogoBudget;
57
+ }
58
+ export type BarcodeErrorCode = 'empty' | 'invalid-input' | 'invalid-length' | 'invalid-checksum' | 'bad-scanline' | 'not-found';
59
+ export type BarcodeType = 'code128' | 'code39' | 'ean13';
60
+
61
+ export class QrError extends Error {
62
+ readonly code: QrErrorCode;
63
+ }
64
+
65
+ export class BarcodeError extends Error {
66
+ readonly code: BarcodeErrorCode;
67
+ }
68
+
69
+ /** `modules` is `size * size` bytes, row-major, 1 dark, without the quiet zone. */
70
+ export interface Code {
71
+ size: number;
72
+ modules: Uint8Array;
73
+ }
74
+
75
+ /** An 8-bit grayscale frame, one byte per pixel, row-major. */
76
+ export interface Frame {
77
+ width: number;
78
+ height: number;
79
+ luma: Uint8Array;
80
+ }
81
+
82
+ /** A linear barcode row, including its quiet zones. */
83
+ export interface LinearCode {
84
+ type: BarcodeType;
85
+ width: number;
86
+ modules: Uint8Array;
87
+ }
88
+
89
+ export interface DecodedBarcode {
90
+ type: BarcodeType;
91
+ data: string;
92
+ }
93
+
94
+ export type DetectedCode =
95
+ | { type: 'qr'; data: Uint8Array }
96
+ | DecodedBarcode;
97
+
98
+ export interface SvgOptions {
99
+ /** Quiet zone in modules. Default 4. */
100
+ margin?: number;
101
+ dark?: string;
102
+ /** `'transparent'` or `''` for no background. Default `'#fff'`. */
103
+ light?: string;
104
+ /** Gives the image a name for screen readers; without it the SVG is hidden from them. */
105
+ title?: string;
106
+ }
107
+
108
+ export interface BarcodeSvgOptions {
109
+ /** Bar height in module units. Default 60. */
110
+ height?: number;
111
+ /** Extra white margin outside the encoded quiet zones. Default 0. */
112
+ margin?: number;
113
+ dark?: string;
114
+ light?: string;
115
+ title?: string;
116
+ }
117
+
118
+ export interface Qr {
119
+ encode(input: string | Uint8Array | ArrayBuffer): Code;
120
+ /** Plan a symbol at any level with a logo area checked against every block's budget. */
121
+ design(input: string | Uint8Array | ArrayBuffer, options?: DesignOptions): Layout;
122
+ decode(frame: Frame): Uint8Array;
123
+ decodeText(frame: Frame): string;
124
+ svg(code: Code | string | Uint8Array, options?: SvgOptions): string;
125
+ encodeBarcode(format: BarcodeType, input: string | Uint8Array | ArrayBuffer): LinearCode;
126
+ encodeCode128(input: string | Uint8Array | ArrayBuffer): LinearCode;
127
+ encodeCode39(input: string | Uint8Array | ArrayBuffer): LinearCode;
128
+ encodeEan13(input: string | Uint8Array | ArrayBuffer): LinearCode;
129
+ decodeBarcodeScanline(luma: Uint8Array): DecodedBarcode;
130
+ scanFrame(frame: Frame): DetectedCode;
131
+ barcodeSvg(code: LinearCode, options?: BarcodeSvgOptions): string;
132
+ }
133
+
134
+ export function loadQr(source?: BufferSource | Response | WebAssembly.Module | string | URL): Promise<Qr>;
135
+ export function svg(code: Code, options?: SvgOptions): string;
136
+ export function barcodeSvg(code: LinearCode, options?: BarcodeSvgOptions): string;
package/qr.js ADDED
@@ -0,0 +1,271 @@
1
+ // QR codes from the crate's WebAssembly build, the same on a server and in a browser.
2
+ //
3
+ // const qr = await loadQr(wasm); // bytes, a Response, a WebAssembly.Module, or a URL
4
+ // const code = qr.encode('https://potomac.solutions/t/8F3K'); // { size, modules }
5
+ // qr.svg(code); // an <svg> string, for a page or an email
6
+ // qr.decode({ width, height, luma }); // Uint8Array; qr.decodeText(...) for a string
7
+ // const bars = qr.encodeCode128('Ticket-42'); // { type, width, modules }
8
+ // qr.scanFrame({ width, height, luma }); // first QR or linear code found
9
+ // qr.design(url, { logo: { size: 0.22 } }); // level, roles, logo area; see style.js to draw it
10
+ //
11
+ // No dependencies. Errors are QrError, with `code` one of: empty, too-long, not-found,
12
+ // unsupported, uncorrectable, malformed, bad-frame, frame-too-large, logo-too-large,
13
+ // invalid-options.
14
+
15
+ const CODES = [null, 'empty', 'too-long', 'not-found', 'unsupported', 'uncorrectable', 'malformed', 'bad-frame', 'frame-too-large', 'logo-too-large', 'invalid-options'];
16
+ const MATRIX_HEADER = 12;
17
+ const STYLED_HEADER = 32;
18
+ const LEVELS = ['L', 'M', 'Q', 'H'];
19
+ const LOGO_SHAPES = { square: 1, circle: 2 };
20
+ /** What each module is for, by the role number `design()` reports. */
21
+ export const ROLES = ['data', 'remainder', 'finder', 'separator', 'timing', 'alignment', 'format', 'version', 'dark-module'];
22
+ const BARCODE_FORMATS = { code128: 1, code39: 2, ean13: 3 };
23
+ const BARCODE_CODES = ['empty', 'invalid-input', 'invalid-length', 'invalid-checksum', 'bad-scanline', 'not-found'];
24
+
25
+ export class QrError extends Error {
26
+ constructor(code) {
27
+ super(`qr: ${code}`);
28
+ this.name = 'QrError';
29
+ this.code = code;
30
+ }
31
+ }
32
+
33
+ export class BarcodeError extends Error {
34
+ constructor(code) {
35
+ super(`barcode: ${code}`);
36
+ this.name = 'BarcodeError';
37
+ this.code = code;
38
+ }
39
+ }
40
+
41
+ async function instantiate(source) {
42
+ if (source instanceof WebAssembly.Module) return WebAssembly.instantiate(source, {});
43
+ if (typeof Response !== 'undefined' && source instanceof Response) {
44
+ if (WebAssembly.instantiateStreaming && source.headers.get('content-type')?.startsWith('application/wasm')) {
45
+ return (await WebAssembly.instantiateStreaming(source, {})).instance;
46
+ }
47
+ source = await source.arrayBuffer();
48
+ } else if (typeof source === 'string' || source instanceof URL) {
49
+ const url = new URL(source, globalThis.location?.href);
50
+ if (url.protocol === 'file:') {
51
+ const { readFile } = await import('node:fs/promises');
52
+ source = await readFile(url);
53
+ } else {
54
+ return instantiate(await fetch(url));
55
+ }
56
+ }
57
+ return (await WebAssembly.instantiate(source, {})).instance;
58
+ }
59
+
60
+ /** Load the WebAssembly build. Pass its bytes, a fetch Response, a compiled Module, or a URL. */
61
+ export async function loadQr(source) {
62
+ source ??= new URL('./symbology.wasm', import.meta.url);
63
+ const { exports: wasm } = await instantiate(source);
64
+ for (const name of ['memory', 'qr_alloc', 'qr_free', 'qr_encode', 'qr_result_ptr', 'qr_result_len']) {
65
+ if (!(name in wasm)) throw new TypeError(`loadQr: this isn't the qr build (no ${name})`);
66
+ }
67
+
68
+ const call = (fn, input, ...args) => {
69
+ if (!fn) throw new TypeError('This WebAssembly build does not provide that operation');
70
+ const pointer = wasm.qr_alloc(input.length);
71
+ try {
72
+ new Uint8Array(wasm.memory.buffer, pointer, input.length).set(input);
73
+ const status = fn(pointer, input.length, ...args);
74
+ if (status >= 20 && status <= 25) throw new BarcodeError(BARCODE_CODES[status - 20]);
75
+ if (status !== 0) throw new QrError(CODES[status] ?? `error-${status}`);
76
+ // Copy out: the next call (or a memory.grow) invalidates the view.
77
+ return new Uint8Array(wasm.memory.buffer, wasm.qr_result_ptr(), wasm.qr_result_len()).slice();
78
+ } finally {
79
+ wasm.qr_free(pointer, input.length);
80
+ }
81
+ };
82
+ const bytesOf = (input) => (typeof input === 'string' ? new TextEncoder().encode(input) : input instanceof Uint8Array ? input : new Uint8Array(input));
83
+
84
+ /** Encode text (as UTF-8) or bytes. `modules` is `size * size` bytes, row-major, 1 dark; no quiet zone. */
85
+ function encode(input) {
86
+ const matrix = call(wasm.qr_encode, bytesOf(input));
87
+ const size = new DataView(matrix.buffer).getUint32(8, true);
88
+ return { size, modules: matrix.subarray(MATRIX_HEADER) };
89
+ }
90
+
91
+ /**
92
+ * Plan a symbol with any error-correction level and room for a centred logo. The logo area is
93
+ * accepted only if every Reed–Solomon block can still correct whatever the logo hides, within
94
+ * `safety` of its budget. `covered` marks the modules a renderer should leave out.
95
+ */
96
+ function design(input, { level = 'auto', minVersion = 1, maxVersion = 10, mask = 'auto', logo = null, safety = 0.5 } = {}) {
97
+ if (!wasm.qr_design) throw new TypeError('design: this WebAssembly build has no qr_design');
98
+ const data = bytesOf(input);
99
+ const head = new Uint8Array(16 + data.length);
100
+ const view = new DataView(head.buffer);
101
+ const byte = (value) => {
102
+ if (!Number.isInteger(value) || value < 0 || value > 254) throw new QrError('invalid-options');
103
+ return value;
104
+ };
105
+ const fixed = (value, unit) => {
106
+ const scaled = Math.round(Number(value) * unit);
107
+ if (!Number.isFinite(scaled) || scaled < 0 || scaled > 65535) throw new QrError('invalid-options');
108
+ return scaled;
109
+ };
110
+ head[0] = level === 'auto' ? 255 : byte(LEVELS.indexOf(level) < 0 ? -1 : LEVELS.indexOf(level));
111
+ head[1] = byte(minVersion);
112
+ head[2] = byte(maxVersion);
113
+ head[3] = mask === 'auto' ? 255 : byte(mask);
114
+ if (logo) {
115
+ const shape = LOGO_SHAPES[logo.shape ?? 'circle'];
116
+ if (!shape) throw new QrError('invalid-options');
117
+ head[4] = shape;
118
+ view.setUint16(6, fixed(logo.width ?? logo.size, 1000), true);
119
+ view.setUint16(8, fixed(logo.height ?? logo.size, 1000), true);
120
+ view.setUint16(10, fixed(logo.padding ?? 0.5, 100), true);
121
+ }
122
+ view.setUint16(12, fixed(safety, 1000), true);
123
+ head.set(data, 16);
124
+
125
+ const bytes = call(wasm.qr_design, head);
126
+ if (new TextDecoder().decode(bytes.subarray(0, 4)) !== 'KQRS' || bytes.length < STYLED_HEADER) {
127
+ throw new TypeError('design: invalid response from WebAssembly');
128
+ }
129
+ const out = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
130
+ const size = out.getUint32(12, true);
131
+ const cells = bytes.subarray(STYLED_HEADER);
132
+ if (cells.length !== size * size) throw new TypeError('design: invalid response from WebAssembly');
133
+ const [blocks, check, allowed] = bytes.subarray(16, 19);
134
+ const damaged = Array.from(bytes.subarray(24, 24 + blocks));
135
+ const worst = Math.max(0, ...damaged);
136
+ return {
137
+ size,
138
+ level: LEVELS[bytes[6]],
139
+ version: bytes[7],
140
+ mask: bytes[8],
141
+ modules: cells.map((cell) => cell & 1),
142
+ roles: cells.map((cell) => (cell >> 1) & 15),
143
+ covered: cells.map((cell) => (cell >> 5) & 1),
144
+ budget: {
145
+ blocks,
146
+ check,
147
+ correctable: check >> 1,
148
+ allowed,
149
+ damaged,
150
+ worst,
151
+ spare: (check >> 1) - worst,
152
+ coveredModules: out.getUint32(20, true),
153
+ },
154
+ };
155
+ }
156
+
157
+ /** Read the payload out of an 8-bit grayscale frame: `{ width, height, luma }`, one byte per pixel. */
158
+ function decode({ width, height, luma }) {
159
+ if (!wasm.qr_decode) throw new TypeError('decode: this build has no decoder (built without the decode feature)');
160
+ const input = new Uint8Array(8 + luma.length);
161
+ const view = new DataView(input.buffer);
162
+ view.setUint32(0, width, true);
163
+ view.setUint32(4, height, true);
164
+ input.set(luma, 8);
165
+ return call(wasm.qr_decode, input);
166
+ }
167
+
168
+ /** Encode a linear barcode; format is `code128`, `code39`, or `ean13`. */
169
+ function encodeBarcode(format, input) {
170
+ const id = BARCODE_FORMATS[format];
171
+ if (!id) throw new TypeError(`encodeBarcode: unsupported format ${format}`);
172
+ if (!wasm.qr_barcode_encode) throw new TypeError('encodeBarcode: unsupported by this WebAssembly build');
173
+ const bytes = call(wasm.qr_barcode_encode, bytesOf(input), id);
174
+ if (new TextDecoder().decode(bytes.subarray(0, 4)) !== 'KBC1' || bytes.length < 9) {
175
+ throw new TypeError('encodeBarcode: invalid response from WebAssembly');
176
+ }
177
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
178
+ const width = view.getUint32(5, true);
179
+ if (bytes[4] !== id || bytes.length !== 9 + width) {
180
+ throw new TypeError('encodeBarcode: invalid response from WebAssembly');
181
+ }
182
+ return { type: format, width, modules: bytes.slice(9) };
183
+ }
184
+
185
+ /** Decode an 8-bit grayscale scanline into `{ type, data }`. */
186
+ function decodeBarcodeScanline(luma) {
187
+ if (!wasm.qr_barcode_scanline) throw new TypeError('decodeBarcodeScanline: this build has no decoder (built without the decode feature)');
188
+ const result = call(wasm.qr_barcode_scanline, bytesOf(luma));
189
+ return decodedBarcode(result);
190
+ }
191
+
192
+ /** Scan a grayscale frame and return the first detected QR or linear code. */
193
+ function scanFrame({ width, height, luma }) {
194
+ if (!wasm.qr_scan) throw new TypeError('scanFrame: this build has no decoder (built without the decode feature)');
195
+ const input = new Uint8Array(8 + luma.length);
196
+ const view = new DataView(input.buffer);
197
+ view.setUint32(0, width, true);
198
+ view.setUint32(4, height, true);
199
+ input.set(luma, 8);
200
+ const result = call(wasm.qr_scan, input);
201
+ if (result.length === 0) throw new TypeError('scanFrame: empty response from WebAssembly');
202
+ if (result[0] === 0) return { type: 'qr', data: result.slice(1) };
203
+ return decodedBarcode(result);
204
+ }
205
+
206
+ return {
207
+ encode,
208
+ design,
209
+ decode,
210
+ decodeText: (frame) => new TextDecoder().decode(decode(frame)),
211
+ svg: (code, options) => svg(typeof code === 'string' || code instanceof Uint8Array ? encode(code) : code, options),
212
+ encodeBarcode,
213
+ encodeCode128: (input) => encodeBarcode('code128', input),
214
+ encodeCode39: (input) => encodeBarcode('code39', input),
215
+ encodeEan13: (input) => encodeBarcode('ean13', input),
216
+ decodeBarcodeScanline,
217
+ scanFrame,
218
+ barcodeSvg,
219
+ };
220
+ }
221
+
222
+ function decodedBarcode(result) {
223
+ const type = Object.keys(BARCODE_FORMATS).find((format) => BARCODE_FORMATS[format] === result[0]);
224
+ if (!type) throw new TypeError(`Unknown barcode type from WebAssembly: ${result[0]}`);
225
+ return { type, data: new TextDecoder().decode(result.subarray(1)) };
226
+ }
227
+
228
+ /**
229
+ * An SVG of a code, with a quiet zone of `margin` modules (4 is the standard). One path, a run
230
+ * of dark modules per segment, so it stays small and crisp at any size.
231
+ */
232
+ export function svg({ size, modules }, { margin = 4, dark = '#000', light = '#fff', title = '' } = {}) {
233
+ const side = size + 2 * margin;
234
+ let path = '';
235
+ for (let y = 0; y < size; y++) {
236
+ for (let x = 0; x < size; x++) {
237
+ if (!modules[y * size + x]) continue;
238
+ let run = 1;
239
+ while (x + run < size && modules[y * size + x + run]) run++;
240
+ path += `M${x + margin} ${y + margin}h${run}v1h-${run}z`;
241
+ x += run - 1;
242
+ }
243
+ }
244
+ const escape = (text) => String(text).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
245
+ return (
246
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${side} ${side}" shape-rendering="crispEdges"${title ? ` role="img" aria-label="${escape(title)}"` : ' aria-hidden="true"'}>` +
247
+ (title ? `<title>${escape(title)}</title>` : '') +
248
+ (light && light !== 'transparent' ? `<rect width="${side}" height="${side}" fill="${escape(light)}"/>` : '') +
249
+ `<path fill="${escape(dark)}" d="${path}"/></svg>`
250
+ );
251
+ }
252
+
253
+ /** Render a linear barcode row as SVG. Encoded rows already include quiet zones. */
254
+ export function barcodeSvg({ width, modules }, { height = 60, margin = 0, dark = '#000', light = '#fff', title = '' } = {}) {
255
+ const side = width + 2 * margin;
256
+ let path = '';
257
+ for (let x = 0; x < width; x++) {
258
+ if (!modules[x]) continue;
259
+ let run = 1;
260
+ while (x + run < width && modules[x + run]) run++;
261
+ path += `M${x + margin} ${margin}v${height}h${run}v-${height}z`;
262
+ x += run - 1;
263
+ }
264
+ const escape = (text) => String(text).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
265
+ return (
266
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${side} ${height + 2 * margin}" shape-rendering="crispEdges"${title ? ` role="img" aria-label="${escape(title)}"` : ' aria-hidden="true"'}>` +
267
+ (title ? `<title>${escape(title)}</title>` : '') +
268
+ (light && light !== 'transparent' ? `<rect width="${side}" height="${height + 2 * margin}" fill="${escape(light)}"/>` : '') +
269
+ `<path fill="${escape(dark)}" d="${path}"/></svg>`
270
+ );
271
+ }