@journey-to-code/symbology 0.2.0 → 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/style.js ADDED
@@ -0,0 +1,771 @@
1
+ // Styled QR codes: shapes, colours, eyes, a centred logo and a call-to-action frame, drawn from a
2
+ // layout made by `qr.design()` (the Rust planner). No dependencies.
3
+ //
4
+ // const { svg, report } = styledQr(qr, 'https://example.com/jane', { preset: 'liquid', logo });
5
+ //
6
+ // Every style is checked before it is drawn: colours must parse (hex or rgb()), shapes must cover
7
+ // each module's centre, the foreground must contrast with the background, and a logo must fit the
8
+ // error-correction budget. Then the same geometry the SVG uses is rasterized and read back by the
9
+ // decoder, twice: once with the logo area as the plate shows it and once with every hidden module
10
+ // wrong. `report.ok` is true only when all of that passes.
11
+
12
+ export const MODULE_SHAPES = ['square', 'dot', 'rounded', 'diamond', 'squircle', 'liquid', 'bars-vertical', 'bars-horizontal'];
13
+ export const EYE_FRAMES = ['square', 'rounded', 'circle', 'leaf'];
14
+ export const EYE_BALLS = ['square', 'rounded', 'circle', 'diamond', 'leaf'];
15
+ export const LEVELS = ['auto', 'L', 'M', 'Q', 'H'];
16
+
17
+ /** Smallest module scale accepted: a shape must still cover the centre a reader samples. */
18
+ export const MIN_MODULE_SCALE = 0.7;
19
+ /** Largest logo side, as a fraction of the symbol. */
20
+ export const MAX_LOGO_SIZE = 0.4;
21
+ /** Recommended smallest printed module, in millimetres. */
22
+ export const PRINT_MODULE_MM = 0.4;
23
+
24
+ export const PRESETS = {
25
+ classic: {},
26
+ corporate: {
27
+ modules: { shape: 'rounded', scale: 0.92 },
28
+ eyes: { frame: 'rounded', ball: 'rounded' },
29
+ colors: { foreground: '#0b2545', eyeFrame: '#13315c', eyeBall: '#8d6a00', background: '#ffffff' },
30
+ },
31
+ 'minimal-dots': {
32
+ modules: { shape: 'dot', scale: 0.85 },
33
+ eyes: { frame: 'circle', ball: 'circle' },
34
+ colors: { foreground: '#111111', background: '#ffffff' },
35
+ },
36
+ liquid: {
37
+ modules: { shape: 'liquid', scale: 1 },
38
+ eyes: { frame: 'rounded', ball: 'circle' },
39
+ colors: { foreground: { type: 'linear', angle: 45, stops: ['#3a0ca3', '#7209b7'] }, background: '#ffffff' },
40
+ },
41
+ 'monochrome-print': {
42
+ modules: { shape: 'square', scale: 1 },
43
+ eyes: { frame: 'square', ball: 'square' },
44
+ colors: { foreground: '#000000', background: '#ffffff' },
45
+ margin: 4,
46
+ },
47
+ bars: {
48
+ modules: { shape: 'bars-vertical', scale: 0.85 },
49
+ eyes: { frame: 'leaf', ball: 'leaf' },
50
+ colors: { foreground: '#1b4332', eyeBall: '#2d6a4f', background: '#f8fff4' },
51
+ },
52
+ };
53
+
54
+ const DEFAULTS = {
55
+ modules: { shape: 'square', scale: 1 },
56
+ eyes: { frame: 'square', ball: 'square' },
57
+ colors: { foreground: '#000000', background: '#ffffff', eyeFrame: null, eyeBall: null },
58
+ logo: null,
59
+ frame: null,
60
+ margin: 4,
61
+ level: 'auto',
62
+ maxVersion: 10,
63
+ safety: 0.5,
64
+ minContrast: 4,
65
+ title: '',
66
+ };
67
+
68
+ // ---------------------------------------------------------------------------
69
+ // Colours: a strict grammar, so nothing from a style (or a model) reaches the SVG unparsed.
70
+ // ---------------------------------------------------------------------------
71
+
72
+ /** `#rgb`, `#rrggbb` or `rgb(r, g, b)` as `[r, g, b]`, or null. Alpha is refused: it hides contrast. */
73
+ export function parseColor(value) {
74
+ if (typeof value !== 'string') return null;
75
+ const text = value.trim().toLowerCase();
76
+ let match = /^#([0-9a-f]{3})$/.exec(text);
77
+ if (match) return [...match[1]].map((digit) => parseInt(digit + digit, 16));
78
+ match = /^#([0-9a-f]{6})$/.exec(text);
79
+ if (match) return [0, 2, 4].map((offset) => parseInt(match[1].slice(offset, offset + 2), 16));
80
+ match = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/.exec(text);
81
+ if (match) {
82
+ const channels = match.slice(1, 4).map(Number);
83
+ return channels.every((channel) => channel <= 255) ? channels : null;
84
+ }
85
+ return null;
86
+ }
87
+
88
+ const hex = ([r, g, b]) => `#${[r, g, b].map((channel) => channel.toString(16).padStart(2, '0')).join('')}`;
89
+
90
+ /** WCAG relative luminance, 0 (black) to 1 (white). */
91
+ export function luminance([r, g, b]) {
92
+ const linear = (channel) => {
93
+ const value = channel / 255;
94
+ return value <= 0.03928 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
95
+ };
96
+ return 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);
97
+ }
98
+
99
+ /** WCAG contrast ratio between two colours, 1 to 21. */
100
+ export function contrast(a, b) {
101
+ const [high, low] = [luminance(a), luminance(b)].sort((x, y) => y - x);
102
+ return (high + 0.05) / (low + 0.05);
103
+ }
104
+
105
+ /** The luma a camera pipeline sees (BT.601), as the tests compute it from a canvas. */
106
+ const luma = ([r, g, b]) => Math.round((r * 299 + g * 587 + b * 114) / 1000);
107
+
108
+ /** A paint: a colour, or `{ type: 'linear', angle, stops }` / `{ type: 'radial', stops }`. */
109
+ function parsePaint(value, path, errors) {
110
+ if (typeof value === 'string') {
111
+ const rgb = parseColor(value);
112
+ if (!rgb) errors.push(`${path}: "${String(value).slice(0, 40)}" is not a colour (use #rrggbb or rgb(r, g, b))`);
113
+ return rgb ? { type: 'solid', stops: [rgb] } : null;
114
+ }
115
+ if (!value || typeof value !== 'object' || !['linear', 'radial'].includes(value.type)) {
116
+ errors.push(`${path}: expected a colour or a { type: "linear" | "radial", stops } gradient`);
117
+ return null;
118
+ }
119
+ const stops = Array.isArray(value.stops) ? value.stops.map(parseColor) : [];
120
+ if (stops.length < 2 || stops.length > 4 || stops.some((stop) => !stop)) {
121
+ errors.push(`${path}.stops: two to four colours (#rrggbb or rgb(r, g, b))`);
122
+ return null;
123
+ }
124
+ const angle = value.angle ?? 0;
125
+ if (value.type === 'linear' && !(Number.isFinite(angle) && angle >= 0 && angle <= 360)) {
126
+ errors.push(`${path}.angle: degrees from 0 to 360`);
127
+ return null;
128
+ }
129
+ return { type: value.type, angle, stops };
130
+ }
131
+
132
+ // ---------------------------------------------------------------------------
133
+ // Logos: embedded as a data URI in <image>, which browsers render as a static image (no scripts,
134
+ // no network). The checks below are defence in depth on top of that sandbox.
135
+ // ---------------------------------------------------------------------------
136
+
137
+ /** Largest logo accepted, in bytes of markup or data URI. */
138
+ export const MAX_LOGO_BYTES = 200_000;
139
+ const DATA_URI = /^data:image\/(png|jpeg|webp|svg\+xml);base64,[a-z0-9+/]+={0,2}$/i;
140
+ const FORBIDDEN_SVG = [
141
+ [/<script\b/i, 'script elements'],
142
+ [/<foreignobject\b/i, 'foreignObject elements'],
143
+ [/<!(doctype|entity)\b/i, 'DOCTYPE or ENTITY declarations'],
144
+ [/<\?xml-stylesheet\b/i, 'external stylesheets'],
145
+ [/\son[a-z]+\s*=/i, 'event handler attributes'],
146
+ [/javascript\s*:/i, 'javascript: URLs'],
147
+ [/@import\b/i, 'CSS @import rules'],
148
+ [/(?:href|src)\s*=\s*["'](?!#|data:image\/(?:png|jpeg|webp);base64,)/i, 'links to anything but #fragments or embedded raster images'],
149
+ [/url\(\s*["']?(?!#)/i, 'CSS url() values other than #fragments'],
150
+ [/<(iframe|embed|object|audio|video|animate|set)\b/i, 'embedded or animated elements'],
151
+ ];
152
+
153
+ function base64(bytes) {
154
+ let binary = '';
155
+ for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
156
+ return btoa(binary);
157
+ }
158
+
159
+ /** Check logo SVG markup. Returns `{ href, errors }`; `href` is a base64 data URI. */
160
+ export function sanitizeLogoSvg(markup) {
161
+ const errors = [];
162
+ if (typeof markup !== 'string' || !/^\s*(<\?xml[^>]*\?>\s*)?<svg[\s>]/i.test(markup) || !/<\/svg>\s*$/i.test(markup)) {
163
+ errors.push('logo.svg: expected one <svg>…</svg> document');
164
+ } else if (markup.length > MAX_LOGO_BYTES) {
165
+ errors.push(`logo.svg: larger than ${MAX_LOGO_BYTES} bytes`);
166
+ } else {
167
+ for (const [pattern, what] of FORBIDDEN_SVG) if (pattern.test(markup)) errors.push(`logo.svg: ${what} are not allowed`);
168
+ if (!/\sviewbox\s*=/i.test(markup)) errors.push('logo.svg: needs a viewBox so it scales into the logo area');
169
+ }
170
+ if (errors.length) return { href: null, errors };
171
+ return { href: `data:image/svg+xml;base64,${base64(new TextEncoder().encode(markup))}`, errors };
172
+ }
173
+
174
+ function normalizeLogo(logo, errors) {
175
+ if (logo == null || logo === false) return null;
176
+ if (typeof logo !== 'object') {
177
+ errors.push('logo: expected { svg | href, size, shape, padding, plate }');
178
+ return null;
179
+ }
180
+ let href = null;
181
+ if (logo.svg != null) {
182
+ const checked = sanitizeLogoSvg(logo.svg);
183
+ errors.push(...checked.errors);
184
+ href = checked.href;
185
+ } else if (logo.href != null) {
186
+ if (typeof logo.href !== 'string' || logo.href.length > MAX_LOGO_BYTES || !DATA_URI.test(logo.href)) {
187
+ errors.push('logo.href: a base64 data URI of a PNG, JPEG, WebP or SVG image (remote URLs are refused so the SVG stays self-contained)');
188
+ } else if (logo.href.toLowerCase().startsWith('data:image/svg+xml')) {
189
+ const encoded = atob(logo.href.slice(logo.href.indexOf(',') + 1));
190
+ const checked = sanitizeLogoSvg(new TextDecoder().decode(Uint8Array.from(encoded, (c) => c.charCodeAt(0))));
191
+ errors.push(...checked.errors);
192
+ href = checked.href;
193
+ } else {
194
+ href = logo.href;
195
+ }
196
+ }
197
+ const size = logo.size ?? 0.22;
198
+ if (!(Number.isFinite(size) && size >= 0.05 && size <= MAX_LOGO_SIZE)) errors.push(`logo.size: a fraction of the symbol from 0.05 to ${MAX_LOGO_SIZE}`);
199
+ const shape = logo.shape ?? 'circle';
200
+ if (!['circle', 'square'].includes(shape)) errors.push('logo.shape: "circle" or "square"');
201
+ const padding = logo.padding ?? 0.5;
202
+ if (!(Number.isFinite(padding) && padding >= 0 && padding <= 2)) errors.push('logo.padding: modules of clear space, 0 to 2');
203
+ const plate = logo.plate == null ? null : parseColor(logo.plate);
204
+ if (logo.plate != null && !plate) errors.push('logo.plate: a colour (#rrggbb or rgb(r, g, b))');
205
+ return { href, size, shape, padding, plate };
206
+ }
207
+
208
+ // ---------------------------------------------------------------------------
209
+ // Style normalization
210
+ // ---------------------------------------------------------------------------
211
+
212
+ const pick = (value, allowed, fallback, path, errors) => {
213
+ if (value == null) return fallback;
214
+ if (allowed.includes(value)) return value;
215
+ errors.push(`${path}: one of ${allowed.join(', ')}`);
216
+ return fallback;
217
+ };
218
+
219
+ const STYLE_KEYS = new Set(['preset', 'modules', 'eyes', 'colors', 'logo', 'frame', 'margin', 'level', 'maxVersion', 'safety', 'minContrast', 'title']);
220
+
221
+ /**
222
+ * Merge a style with its preset and the defaults, and check every field. Unknown fields are
223
+ * reported as warnings and ignored. Returns `{ style, errors, warnings }`; `style` is null when
224
+ * there are errors.
225
+ */
226
+ export function normalizeStyle(input = {}) {
227
+ const errors = [];
228
+ const warnings = [];
229
+ if (input == null || typeof input !== 'object' || Array.isArray(input)) return { style: null, errors: ['style: expected an object'], warnings };
230
+ for (const key of Object.keys(input)) if (!STYLE_KEYS.has(key)) warnings.push(`style.${key}: unknown, ignored`);
231
+ if (input.preset != null && !Object.hasOwn(PRESETS, input.preset)) errors.push(`preset: one of ${Object.keys(PRESETS).join(', ')}`);
232
+ const preset = PRESETS[input.preset] ?? {};
233
+ const merged = (key) => ({ ...DEFAULTS[key], ...(preset[key] ?? {}), ...(input[key] ?? {}) });
234
+
235
+ const modulesIn = merged('modules');
236
+ const shape = pick(modulesIn.shape, MODULE_SHAPES, 'square', 'modules.shape', errors);
237
+ let scale = modulesIn.scale ?? 1;
238
+ if (!(Number.isFinite(scale) && scale >= MIN_MODULE_SCALE && scale <= 1)) {
239
+ errors.push(`modules.scale: from ${MIN_MODULE_SCALE} (shapes must still cover each module's centre) to 1`);
240
+ scale = 1;
241
+ }
242
+ if (shape === 'liquid') scale = 1;
243
+
244
+ const eyesIn = merged('eyes');
245
+ const eyes = {
246
+ frame: pick(eyesIn.frame, EYE_FRAMES, 'square', 'eyes.frame', errors),
247
+ ball: pick(eyesIn.ball, EYE_BALLS, 'square', 'eyes.ball', errors),
248
+ };
249
+
250
+ const colorsIn = merged('colors');
251
+ const foreground = parsePaint(colorsIn.foreground, 'colors.foreground', errors);
252
+ const background = parseColor(colorsIn.background);
253
+ if (!background) errors.push('colors.background: a solid colour (#rrggbb or rgb(r, g, b)); transparency is refused because the paper behind it is unknown');
254
+ const eyeFrame = colorsIn.eyeFrame == null ? foreground : parsePaint(colorsIn.eyeFrame, 'colors.eyeFrame', errors);
255
+ const eyeBall = colorsIn.eyeBall == null ? eyeFrame : parsePaint(colorsIn.eyeBall, 'colors.eyeBall', errors);
256
+
257
+ const number = (key, low, high, integer = false) => {
258
+ const value = input[key] ?? preset[key] ?? DEFAULTS[key];
259
+ if (Number.isFinite(value) && value >= low && value <= high && (!integer || Number.isInteger(value))) return value;
260
+ errors.push(`${key}: ${integer ? 'an integer' : 'a number'} from ${low} to ${high}`);
261
+ return DEFAULTS[key];
262
+ };
263
+ const margin = number('margin', 4, 8, true);
264
+ const maxVersion = number('maxVersion', 1, 10, true);
265
+ const safety = number('safety', 0.1, 0.8);
266
+ const minContrast = number('minContrast', 3, 21);
267
+ const level = pick(input.level ?? preset.level, LEVELS, 'auto', 'level', errors);
268
+
269
+ let frame = null;
270
+ const frameIn = input.frame ?? preset.frame;
271
+ if (frameIn) {
272
+ const text = String(frameIn.text ?? 'SCAN ME');
273
+ if (text.length > 32) errors.push('frame.text: at most 32 characters');
274
+ const color = parseColor(frameIn.color ?? '#000000');
275
+ const textColor = parseColor(frameIn.textColor ?? '#ffffff');
276
+ if (!color) errors.push('frame.color: a colour (#rrggbb or rgb(r, g, b))');
277
+ if (!textColor) errors.push('frame.textColor: a colour (#rrggbb or rgb(r, g, b))');
278
+ if (color && textColor && contrast(color, textColor) < 3) warnings.push('frame: the text barely contrasts with the frame');
279
+ frame = { text: text.slice(0, 32), color, textColor };
280
+ }
281
+
282
+ const logo = normalizeLogo(input.logo ?? preset.logo, errors);
283
+ if (logo && (level === 'L' || level === 'M')) warnings.push(`level ${level}: a logo usually needs level Q or H; the planner refuses it if it does not fit`);
284
+
285
+ if (foreground && background) {
286
+ for (const [name, paint] of [['foreground', foreground], ['eyeFrame', eyeFrame], ['eyeBall', eyeBall]]) {
287
+ for (const stop of paint?.stops ?? []) {
288
+ const ratio = contrast(stop, background);
289
+ if (luminance(stop) >= luminance(background)) {
290
+ errors.push(`colors.${name}: ${hex(stop)} is not darker than the background ${hex(background)}; many scanners only read dark codes on light backgrounds`);
291
+ } else if (ratio < minContrast) {
292
+ errors.push(`colors.${name}: ${hex(stop)} on ${hex(background)} has contrast ${ratio.toFixed(2)}, below ${minContrast}`);
293
+ }
294
+ }
295
+ }
296
+ }
297
+ if (logo?.plate && background && luminance(logo.plate) < 0.5) warnings.push('logo.plate: a dark plate can read as a cluster of modules; a light plate is safer');
298
+
299
+ const style = {
300
+ preset: input.preset ?? null,
301
+ modules: { shape, scale },
302
+ eyes,
303
+ colors: { foreground, background, eyeFrame, eyeBall },
304
+ logo,
305
+ frame,
306
+ margin,
307
+ level,
308
+ maxVersion,
309
+ safety,
310
+ minContrast,
311
+ title: String(input.title ?? '').slice(0, 200),
312
+ };
313
+ return { style: errors.length ? null : style, errors, warnings };
314
+ }
315
+
316
+ // ---------------------------------------------------------------------------
317
+ // Geometry. One shape list, in module units, feeds both the SVG and the rasterizer, so what is
318
+ // verified is exactly what is drawn. Shapes: rect (per-corner radii tl, tr, br, bl), circle,
319
+ // poly. Each group is filled with one paint under the even-odd rule.
320
+ // ---------------------------------------------------------------------------
321
+
322
+ const FINDER = 2;
323
+ const SEPARATOR = 3;
324
+ const rect = (x, y, w, h, r = [0, 0, 0, 0]) => {
325
+ const limit = Math.min(w, h) / 2;
326
+ return { t: 'rect', x, y, w, h, r: r.map((radius) => Math.min(Math.max(radius, 0), limit)) };
327
+ };
328
+ const circle = (cx, cy, r) => ({ t: 'circle', cx, cy, r });
329
+ const poly = (p) => ({ t: 'poly', p });
330
+ const diamond = (cx, cy, half) => poly([[cx, cy - half], [cx + half, cy], [cx, cy + half], [cx - half, cy]]);
331
+
332
+ /** Corner radii for a leaf: two opposite corners rounded, oriented away from the symbol centre. */
333
+ const leafCorners = (corner, radius) => (corner === 'tr' || corner === 'bl' ? [0, radius, 0, radius] : [radius, 0, radius, 0]);
334
+
335
+ function eyeShapes(style, ox, oy, corner) {
336
+ const outer = (inset, side, kind, rounding) => {
337
+ const [x, y] = [ox + inset, oy + inset];
338
+ if (kind === 'circle') return circle(x + side / 2, y + side / 2, side / 2);
339
+ if (kind === 'diamond') return diamond(x + side / 2, y + side / 2, side / 2);
340
+ if (kind === 'leaf') return rect(x, y, side, side, leafCorners(corner, side / 2.4));
341
+ const radius = kind === 'rounded' ? rounding : 0;
342
+ return rect(x, y, side, side, [radius, radius, radius, radius]);
343
+ };
344
+ return {
345
+ frame: [outer(0, 7, style.eyes.frame, 2), outer(1, 5, style.eyes.frame, 1.2)],
346
+ ball: [outer(2, 3, style.eyes.ball, 0.8)],
347
+ };
348
+ }
349
+
350
+ function barShapes(on, size, scale, vertical, ox, oy) {
351
+ const shapes = [];
352
+ const inset = (1 - scale) / 2;
353
+ const seen = new Uint8Array(size * size);
354
+ const radius = scale / 2;
355
+ for (let y = 0; y < size; y++) {
356
+ for (let x = 0; x < size; x++) {
357
+ if (!on(x, y) || seen[y * size + x]) continue;
358
+ let run = 1;
359
+ while (vertical ? on(x, y + run) : on(x + run, y)) run++;
360
+ for (let k = 0; k < run; k++) seen[vertical ? (y + k) * size + x : y * size + x + k] = 1;
361
+ const length = run - 1 + scale;
362
+ shapes.push(rect(ox + x + inset, oy + y + inset, vertical ? scale : length, vertical ? length : scale, [radius, radius, radius, radius]));
363
+ }
364
+ }
365
+ return shapes;
366
+ }
367
+
368
+ function moduleShapes(layout, style, ox, oy) {
369
+ const { size, modules, roles, covered } = layout;
370
+ const { shape, scale } = style.modules;
371
+ const on = (x, y) => {
372
+ if (x < 0 || y < 0 || x >= size || y >= size) return false;
373
+ const index = y * size + x;
374
+ return Boolean(modules[index]) && !covered[index] && roles[index] !== FINDER && roles[index] !== SEPARATOR;
375
+ };
376
+ if (shape === 'bars-vertical' || shape === 'bars-horizontal') return barShapes(on, size, scale, shape === 'bars-vertical', ox, oy);
377
+ const shapes = [];
378
+ const inset = (1 - scale) / 2;
379
+ for (let y = 0; y < size; y++) {
380
+ for (let x = 0; x < size; x++) {
381
+ if (!on(x, y)) continue;
382
+ const [left, top, cx, cy] = [ox + x + inset, oy + y + inset, ox + x + 0.5, oy + y + 0.5];
383
+ if (shape === 'dot') shapes.push(circle(cx, cy, scale / 2));
384
+ else if (shape === 'diamond') shapes.push(diamond(cx, cy, scale / 2 + 0.06));
385
+ else if (shape === 'rounded') shapes.push(rect(left, top, scale, scale, Array(4).fill(scale * 0.28)));
386
+ else if (shape === 'squircle') shapes.push(rect(left, top, scale, scale, Array(4).fill(scale * 0.42)));
387
+ else if (shape === 'liquid') {
388
+ // Round an outer corner only where both of its neighbours are light, so runs flow together.
389
+ const [n, s, w, e] = [on(x, y - 1), on(x, y + 1), on(x - 1, y), on(x + 1, y)];
390
+ const r = (a, b) => (a || b ? 0 : 0.5);
391
+ shapes.push(rect(ox + x, oy + y, 1, 1, [r(n, w), r(n, e), r(s, e), r(s, w)]));
392
+ } else shapes.push(rect(left, top, scale, scale));
393
+ }
394
+ }
395
+ return shapes;
396
+ }
397
+
398
+ const solid = (rgb) => ({ type: 'solid', stops: [rgb] });
399
+
400
+ /** The full drawing: canvas size in modules, and paint groups in painting order. */
401
+ function compose(layout, style) {
402
+ const { size } = layout;
403
+ const { margin, frame, logo, colors } = style;
404
+ const border = frame ? 1 : 0;
405
+ const band = frame ? 3.2 : 0;
406
+ const inner = size + 2 * margin;
407
+ const width = inner + 2 * border;
408
+ const height = width + band;
409
+ const [ox, oy] = [border + margin, border + margin];
410
+ const groups = [];
411
+ if (frame) {
412
+ groups.push({ paint: solid(frame.color), shapes: [rect(0, 0, width, height, [1.2, 1.2, 1.2, 1.2])], role: 'frame' });
413
+ groups.push({ paint: solid(colors.background), shapes: [rect(border, border, inner, inner, [0.8, 0.8, 0.8, 0.8])], role: 'background' });
414
+ } else {
415
+ groups.push({ paint: solid(colors.background), shapes: [rect(0, 0, width, height)], role: 'background' });
416
+ }
417
+ groups.push({ paint: colors.foreground, shapes: moduleShapes(layout, style, ox, oy), role: 'modules' });
418
+ const balls = [];
419
+ for (const [fx, fy, corner] of [[0, 0, 'tl'], [size - 7, 0, 'tr'], [0, size - 7, 'bl']]) {
420
+ const eye = eyeShapes(style, ox + fx, oy + fy, corner);
421
+ // A frame is a ring (outer then inner under even-odd), so each gets its own group.
422
+ groups.push({ paint: colors.eyeFrame, shapes: eye.frame, role: 'eye-frame' });
423
+ balls.push(...eye.ball);
424
+ }
425
+ groups.push({ paint: colors.eyeBall, shapes: balls, role: 'eye-ball' });
426
+
427
+ let logoBox = null;
428
+ if (logo) {
429
+ const centre = size / 2;
430
+ const half = (logo.size * size) / 2;
431
+ const padded = half + logo.padding;
432
+ const [cx, cy] = [ox + centre, oy + centre];
433
+ const plate = logo.shape === 'circle'
434
+ ? circle(cx, cy, padded)
435
+ : rect(cx - padded, cy - padded, 2 * padded, 2 * padded, Array(4).fill(Math.min(1, logo.padding + 0.5)));
436
+ groups.push({ paint: solid(logo.plate ?? colors.background), shapes: [plate], role: 'logo-plate' });
437
+ logoBox = { x: cx - half, y: cy - half, size: 2 * half, shape: logo.shape };
438
+ }
439
+ return { width, height, groups, logoBox, border, inner, band, origin: [ox, oy] };
440
+ }
441
+
442
+ // ---------------------------------------------------------------------------
443
+ // SVG
444
+ // ---------------------------------------------------------------------------
445
+
446
+ const num = (value) => String(Math.round(value * 1000) / 1000);
447
+ const escapeXml = (text) => String(text).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
448
+
449
+ function shapePath(shape) {
450
+ if (shape.t === 'circle') {
451
+ const { cx, cy, r } = shape;
452
+ return `M${num(cx - r)} ${num(cy)}a${num(r)} ${num(r)} 0 1 0 ${num(2 * r)} 0a${num(r)} ${num(r)} 0 1 0 ${num(-2 * r)} 0z`;
453
+ }
454
+ if (shape.t === 'poly') return `M${shape.p.map(([x, y]) => `${num(x)} ${num(y)}`).join('L')}z`;
455
+ const { x, y, w, h, r: [tl, tr, br, bl] } = shape;
456
+ if (!tl && !tr && !br && !bl) return `M${num(x)} ${num(y)}h${num(w)}v${num(h)}h${num(-w)}z`;
457
+ const arc = (radius, dx, dy) => (radius ? `a${num(radius)} ${num(radius)} 0 0 1 ${num(dx)} ${num(dy)}` : '');
458
+ return (
459
+ `M${num(x + tl)} ${num(y)}h${num(w - tl - tr)}${arc(tr, tr, tr)}` +
460
+ `v${num(h - tr - br)}${arc(br, -br, br)}` +
461
+ `h${num(-(w - br - bl))}${arc(bl, -bl, -bl)}` +
462
+ `v${num(-(h - bl - tl))}${arc(tl, tl, -tl)}z`
463
+ );
464
+ }
465
+
466
+ function paintDefinition(paint, id) {
467
+ const stops = paint.stops.map((stop, i) => `<stop offset="${num(i / (paint.stops.length - 1))}" stop-color="${hex(stop)}"/>`).join('');
468
+ if (paint.type === 'radial') return `<radialGradient id="${id}" cx="0.5" cy="0.5" r="0.7">${stops}</radialGradient>`;
469
+ const radians = (paint.angle * Math.PI) / 180;
470
+ const [dx, dy] = [Math.cos(radians) / 2, Math.sin(radians) / 2];
471
+ return `<linearGradient id="${id}" x1="${num(0.5 - dx)}" y1="${num(0.5 - dy)}" x2="${num(0.5 + dx)}" y2="${num(0.5 + dy)}">${stops}</linearGradient>`;
472
+ }
473
+
474
+ function toSvg(drawing, style, pixelSize) {
475
+ const { width, height, groups, logoBox } = drawing;
476
+ const defs = [];
477
+ const body = [];
478
+ groups.forEach((group, index) => {
479
+ if (!group.shapes.length) return;
480
+ let fill = hex(group.paint.stops[0]);
481
+ if (group.paint.type !== 'solid') {
482
+ const id = `symbology-paint-${index}`;
483
+ defs.push(paintDefinition(group.paint, id));
484
+ fill = `url(#${id})`;
485
+ }
486
+ body.push(`<path fill="${fill}" fill-rule="evenodd" d="${group.shapes.map(shapePath).join('')}"/>`);
487
+ });
488
+ if (logoBox && style.logo.href) {
489
+ const { x, y, size } = logoBox;
490
+ const round = style.logo.shape === 'circle';
491
+ if (round) defs.push(`<clipPath id="symbology-logo-clip"><circle cx="${num(x + size / 2)}" cy="${num(y + size / 2)}" r="${num(size / 2)}"/></clipPath>`);
492
+ body.push(`<image href="${escapeXml(style.logo.href)}" x="${num(x)}" y="${num(y)}" width="${num(size)}" height="${num(size)}" preserveAspectRatio="xMidYMid meet"${round ? ' clip-path="url(#symbology-logo-clip)"' : ''}/>`);
493
+ }
494
+ if (style.frame) {
495
+ const { text, textColor } = style.frame;
496
+ const fontSize = Math.min(2, (drawing.inner * 1.6) / Math.max(text.length, 1));
497
+ const baseline = drawing.border + drawing.inner + drawing.band / 2;
498
+ body.push(`<text x="${num(width / 2)}" y="${num(baseline)}" fill="${hex(textColor)}" font-family="system-ui, -apple-system, 'Segoe UI', sans-serif" font-weight="700" font-size="${num(fontSize)}" letter-spacing="0.08em" text-anchor="middle" dominant-baseline="central">${escapeXml(text)}</text>`);
499
+ }
500
+ const label = style.title ? ` role="img" aria-label="${escapeXml(style.title)}"` : ' aria-hidden="true"';
501
+ const dimensions = pixelSize ? ` width="${num(pixelSize)}" height="${num((pixelSize * height) / width)}"` : '';
502
+ return (
503
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${num(width)} ${num(height)}"${dimensions}${label}>` +
504
+ (style.title ? `<title>${escapeXml(style.title)}</title>` : '') +
505
+ (defs.length ? `<defs>${defs.join('')}</defs>` : '') +
506
+ body.join('') +
507
+ '</svg>'
508
+ );
509
+ }
510
+
511
+ // ---------------------------------------------------------------------------
512
+ // Rasterizer: the same shapes, filled into an 8-bit luma frame for the decoder. A pixel is in a
513
+ // shape when its centre is (no antialiasing), which is harsher than a browser.
514
+ // ---------------------------------------------------------------------------
515
+
516
+ function insideShape(shape, px, py) {
517
+ if (shape.t === 'circle') return (px - shape.cx) ** 2 + (py - shape.cy) ** 2 <= shape.r ** 2;
518
+ if (shape.t === 'poly') {
519
+ let inside = false;
520
+ const p = shape.p;
521
+ for (let i = 0, j = p.length - 1; i < p.length; j = i++) {
522
+ const [[xi, yi], [xj, yj]] = [p[i], p[j]];
523
+ if (yi > py !== yj > py && px < ((xj - xi) * (py - yi)) / (yj - yi) + xi) inside = !inside;
524
+ }
525
+ return inside;
526
+ }
527
+ const { x, y, w, h, r: [tl, tr, br, bl] } = shape;
528
+ if (px < x || py < y || px > x + w || py > y + h) return false;
529
+ const corner = (cx, cy, radius) => (px - cx) ** 2 + (py - cy) ** 2 <= radius ** 2;
530
+ if (tl && px < x + tl && py < y + tl) return corner(x + tl, y + tl, tl);
531
+ if (tr && px > x + w - tr && py < y + tr) return corner(x + w - tr, y + tr, tr);
532
+ if (br && px > x + w - br && py > y + h - br) return corner(x + w - br, y + h - br, br);
533
+ if (bl && px < x + bl && py > y + h - bl) return corner(x + bl, y + h - bl, bl);
534
+ return true;
535
+ }
536
+
537
+ function bounds(shape) {
538
+ if (shape.t === 'circle') return [shape.cx - shape.r, shape.cy - shape.r, shape.cx + shape.r, shape.cy + shape.r];
539
+ if (shape.t === 'poly') {
540
+ const xs = shape.p.map(([x]) => x);
541
+ const ys = shape.p.map(([, y]) => y);
542
+ return [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)];
543
+ }
544
+ return [shape.x, shape.y, shape.x + shape.w, shape.y + shape.h];
545
+ }
546
+
547
+ /** A paint's luma at a point; gradients span the group's bounding box, as SVG's default does. */
548
+ function paintLuma(paint, [x0, y0, x1, y1]) {
549
+ const lumas = paint.stops.map(luma);
550
+ if (paint.type === 'solid') return () => lumas[0];
551
+ const [w, h] = [Math.max(x1 - x0, 1e-9), Math.max(y1 - y0, 1e-9)];
552
+ const radians = (paint.angle * Math.PI) / 180;
553
+ const [dx, dy] = [Math.cos(radians), Math.sin(radians)];
554
+ const at = (t) => {
555
+ const scaled = Math.min(Math.max(t, 0), 1) * (lumas.length - 1);
556
+ const i = Math.min(Math.floor(scaled), lumas.length - 2);
557
+ return lumas[i] + (lumas[i + 1] - lumas[i]) * (scaled - i);
558
+ };
559
+ if (paint.type === 'radial') return (px, py) => at(Math.hypot((px - x0) / w - 0.5, (py - y0) / h - 0.5) / 0.7);
560
+ return (px, py) => at(((px - x0) / w - 0.5) * dx + ((py - y0) / h - 0.5) * dy + 0.5);
561
+ }
562
+
563
+ /** Rasterize at `scale` pixels per module; `logoFill(x, y)` (module units) paints the logo box. */
564
+ function rasterize(drawing, scale, logoFill) {
565
+ const width = Math.round(drawing.width * scale);
566
+ const height = Math.round(drawing.height * scale);
567
+ const pixels = new Uint8Array(width * height).fill(255);
568
+ const coverage = new Uint8Array(width * height);
569
+ for (const group of drawing.groups) {
570
+ if (!group.shapes.length) continue;
571
+ const boxes = group.shapes.map(bounds);
572
+ const box = boxes.reduce((a, b) => [Math.min(a[0], b[0]), Math.min(a[1], b[1]), Math.max(a[2], b[2]), Math.max(a[3], b[3])]);
573
+ const shade = paintLuma(group.paint, box);
574
+ const [gx0, gy0] = [Math.max(0, Math.floor(box[0] * scale)), Math.max(0, Math.floor(box[1] * scale))];
575
+ const [gx1, gy1] = [Math.min(width, Math.ceil(box[2] * scale)), Math.min(height, Math.ceil(box[3] * scale))];
576
+ for (let y = gy0; y < gy1; y++) coverage.fill(0, y * width + gx0, y * width + gx1);
577
+ group.shapes.forEach((shape, i) => {
578
+ const [bx0, by0, bx1, by1] = boxes[i];
579
+ const [x0, y0] = [Math.max(0, Math.floor(bx0 * scale)), Math.max(0, Math.floor(by0 * scale))];
580
+ const [x1, y1] = [Math.min(width, Math.ceil(bx1 * scale)), Math.min(height, Math.ceil(by1 * scale))];
581
+ for (let y = y0; y < y1; y++) {
582
+ for (let x = x0; x < x1; x++) {
583
+ if (insideShape(shape, (x + 0.5) / scale, (y + 0.5) / scale)) coverage[y * width + x] ^= 1;
584
+ }
585
+ }
586
+ });
587
+ for (let y = gy0; y < gy1; y++) {
588
+ for (let x = gx0; x < gx1; x++) {
589
+ if (coverage[y * width + x]) pixels[y * width + x] = shade((x + 0.5) / scale, (y + 0.5) / scale);
590
+ }
591
+ }
592
+ }
593
+ const logo = drawing.logoBox;
594
+ if (logo && logoFill) {
595
+ const r = logo.size / 2;
596
+ for (let y = Math.max(0, Math.floor(logo.y * scale)); y < Math.min(height, Math.ceil((logo.y + logo.size) * scale)); y++) {
597
+ for (let x = Math.max(0, Math.floor(logo.x * scale)); x < Math.min(width, Math.ceil((logo.x + logo.size) * scale)); x++) {
598
+ const [mx, my] = [(x + 0.5) / scale, (y + 0.5) / scale];
599
+ if (mx < logo.x || my < logo.y || mx > logo.x + logo.size || my > logo.y + logo.size) continue;
600
+ if (logo.shape === 'circle' && (mx - logo.x - r) ** 2 + (my - logo.y - r) ** 2 > r * r) continue;
601
+ pixels[y * width + x] = logoFill(mx, my);
602
+ }
603
+ }
604
+ }
605
+ return { width, height, luma: pixels };
606
+ }
607
+
608
+ /** A 3×3 box blur, standing in for a soft print or an out-of-focus camera. */
609
+ function blur({ width, height, luma: source }) {
610
+ const out = new Uint8Array(source.length);
611
+ for (let y = 0; y < height; y++) {
612
+ for (let x = 0; x < width; x++) {
613
+ let [sum, count] = [0, 0];
614
+ for (let dy = -1; dy <= 1; dy++) {
615
+ for (let dx = -1; dx <= 1; dx++) {
616
+ const [sx, sy] = [x + dx, y + dy];
617
+ if (sx >= 0 && sy >= 0 && sx < width && sy < height) {
618
+ sum += source[sy * width + sx];
619
+ count++;
620
+ }
621
+ }
622
+ }
623
+ out[y * width + x] = Math.round(sum / count);
624
+ }
625
+ }
626
+ return { width, height, luma: out };
627
+ }
628
+
629
+ // ---------------------------------------------------------------------------
630
+ // Verification
631
+ // ---------------------------------------------------------------------------
632
+
633
+ /** Notes on a payload meant to be a URL: scheme, length, and what the length costs. */
634
+ export function checkUrl(data) {
635
+ const warnings = [];
636
+ const text = typeof data === 'string' ? data : new TextDecoder().decode(data);
637
+ const bytes = new TextEncoder().encode(text).length;
638
+ let url = null;
639
+ try {
640
+ url = new URL(text);
641
+ } catch {
642
+ warnings.push('payload: not a URL; phones will show it as text');
643
+ }
644
+ if (url && !['https:', 'http:'].includes(url.protocol)) warnings.push(`payload: ${url.protocol} links may not open from a phone camera`);
645
+ if (url?.protocol === 'http:') warnings.push('payload: http links show a "not secure" warning on many phones; prefer https');
646
+ if (bytes > 58) warnings.push(`payload: ${bytes} bytes is too long for a logo at level H below version 7 (58 bytes); a shorter URL gives a smaller, sturdier code`);
647
+ else if (bytes > 42) warnings.push(`payload: ${bytes} bytes; under 42 keeps a logo code at version 5 or below`);
648
+ return { bytes, warnings };
649
+ }
650
+
651
+ function verifyScale(drawing) {
652
+ const fit = Math.min(1280 / drawing.width, Math.sqrt((1280 * 720) / (drawing.width * drawing.height)));
653
+ return Math.max(3, Math.min(8, Math.floor(fit)));
654
+ }
655
+
656
+ /**
657
+ * Read the drawing back with the decoder: as drawn, blurred, and (with a logo) with every hidden
658
+ * module shown wrong, which is the worst any logo could do.
659
+ */
660
+ function verify(qr, drawing, layout, expected, background) {
661
+ const scale = verifyScale(drawing);
662
+ const [ox, oy] = drawing.origin;
663
+ const reads = (frame) => {
664
+ try {
665
+ const got = qr.decode(frame);
666
+ return got.length === expected.length && got.every((byte, i) => byte === expected[i]);
667
+ } catch {
668
+ return false;
669
+ }
670
+ };
671
+ const light = luma(background);
672
+ const wrong = (mx, my) => {
673
+ const [x, y] = [Math.floor(mx - ox), Math.floor(my - oy)];
674
+ const inside = x >= 0 && y >= 0 && x < layout.size && y < layout.size;
675
+ return inside && !layout.modules[y * layout.size + x] ? 0 : light;
676
+ };
677
+ const asDrawn = rasterize(drawing, scale);
678
+ const checks = [
679
+ { name: 'reads as drawn', ok: reads(asDrawn) },
680
+ { name: 'reads when blurred', ok: reads(blur(asDrawn)) },
681
+ ];
682
+ if (drawing.logoBox) checks.push({ name: 'reads whatever the logo shows', ok: reads(rasterize(drawing, scale, wrong)) });
683
+ return checks;
684
+ }
685
+
686
+ function score({ style, layout, checks, minContrast }) {
687
+ let value = 100;
688
+ if (layout.budget.coveredModules) value -= Math.round((20 * layout.budget.worst) / Math.max(layout.budget.correctable, 1));
689
+ value -= Math.round(Math.max(0, 7 - minContrast) * 4);
690
+ value -= Math.round((1 - style.modules.scale) * 40);
691
+ if (['dot', 'diamond'].includes(style.modules.shape)) value -= 5;
692
+ if (style.colors.foreground.type !== 'solid') value -= 3;
693
+ value -= checks.filter((check) => !check.ok).length * 40;
694
+ return Math.max(0, Math.min(100, value));
695
+ }
696
+
697
+ // ---------------------------------------------------------------------------
698
+ // Public API
699
+ // ---------------------------------------------------------------------------
700
+
701
+ function plannerError(error, style, bytes) {
702
+ switch (error?.code) {
703
+ case 'logo-too-large':
704
+ return `logo: ${Math.round(style.logo.size * 100)}% of the symbol hides more than error correction can safely recover for a ${bytes}-byte payload; make the logo smaller, shorten the URL, or allow a larger maxVersion (a centred logo fits up to version 6)`;
705
+ case 'too-long':
706
+ return `payload: ${bytes} bytes does not fit level ${style.level} up to version ${style.maxVersion}`;
707
+ case 'empty':
708
+ return 'payload: nothing to encode';
709
+ default:
710
+ return null;
711
+ }
712
+ }
713
+
714
+ /**
715
+ * Draw `data` (a URL, ideally) as a styled QR code. `qr` is the object `loadQr()` returns.
716
+ *
717
+ * Returns `{ svg, report, layout, style }`. `svg` is null and `report.ok` false when the style is
718
+ * invalid or the drawing does not read back. Options: `verify` (default true; turn it off only for
719
+ * live previews), `pixelSize` (adds width and height attributes).
720
+ */
721
+ export function styledQr(qr, data, input = {}, { verify: shouldVerify = true, pixelSize } = {}) {
722
+ const { style, errors, warnings } = normalizeStyle(input);
723
+ const url = checkUrl(data);
724
+ warnings.push(...url.warnings);
725
+ const fail = (more) => ({ svg: null, layout: null, style, report: { ok: false, errors: [...errors, ...more], warnings, score: 0, checks: [] } });
726
+ if (!style) return fail([]);
727
+ if (pixelSize != null && !(Number.isFinite(pixelSize) && pixelSize > 0 && pixelSize <= 20000)) return fail(['pixelSize: a positive number of pixels up to 20000']);
728
+
729
+ let layout;
730
+ try {
731
+ layout = qr.design(data, {
732
+ level: style.level,
733
+ maxVersion: style.maxVersion,
734
+ safety: style.safety,
735
+ logo: style.logo && { shape: style.logo.shape, size: style.logo.size, padding: style.logo.padding },
736
+ });
737
+ } catch (error) {
738
+ const message = plannerError(error, style, url.bytes);
739
+ if (message) return fail([message]);
740
+ throw error;
741
+ }
742
+
743
+ const drawing = compose(layout, style);
744
+ const background = style.colors.background;
745
+ const minContrast = Math.min(...['foreground', 'eyeFrame', 'eyeBall'].flatMap((key) => style.colors[key].stops.map((stop) => contrast(stop, background))));
746
+ const expected = typeof data === 'string' ? new TextEncoder().encode(data) : new Uint8Array(data);
747
+ const checks = shouldVerify ? verify(qr, drawing, layout, expected, background) : [];
748
+ const failed = checks.filter((check) => !check.ok).map((check) => `verification: fails "${check.name}"`);
749
+ if (layout.budget.coveredModules && layout.budget.spare < 2) warnings.push(`logo: leaves ${layout.budget.spare} spare correction(s) in the worst block; a smaller logo survives wear better`);
750
+ if (style.modules.scale < 0.85) warnings.push('modules.scale: small modules print faint; 0.85 or more is safer on paper');
751
+
752
+ const report = {
753
+ ok: failed.length === 0,
754
+ errors: failed,
755
+ warnings,
756
+ level: layout.level,
757
+ version: layout.version,
758
+ mask: layout.mask,
759
+ size: layout.size,
760
+ budget: layout.budget,
761
+ contrast: Math.round(minContrast * 100) / 100,
762
+ checks,
763
+ verified: shouldVerify,
764
+ score: score({ style, layout, checks, minContrast }),
765
+ print: {
766
+ widthModules: Math.round(drawing.width * 1000) / 1000,
767
+ minWidthMm: Math.ceil(drawing.width * PRINT_MODULE_MM * 10) / 10,
768
+ },
769
+ };
770
+ return { svg: report.ok ? toSvg(drawing, style, pixelSize) : null, report, layout, style };
771
+ }