qrdx 0.0.49 → 0.0.50

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.
@@ -0,0 +1,282 @@
1
+ /** biome-ignore-all lint/style/noMagicNumbers: image format magic bytes */
2
+ // Node-friendly rasterization for PNG export (getQRAsPNG in download.tsx).
3
+ // Both rasterizers are optional peer dependencies loaded only when a PNG is
4
+ // asked for, so installing qrdx never pulls in a native module:
5
+ //
6
+ // - @resvg/resvg-js is tried first: it draws the SVG the way browsers do,
7
+ // embedded logos included (PNG, JPEG, GIF, WebP and SVG images).
8
+ // - sharp is tried next, but its bundled SVG renderer skips embedded <image>
9
+ // elements, so the logo is located with a marker render and composited
10
+ // onto the pixels afterwards.
11
+
12
+ type SharpFactory = typeof import("sharp").default;
13
+
14
+ /** A logo loaded for rasterizing: the raw bytes, plus the data URL the SVG embeds. */
15
+ export interface RasterLogo {
16
+ bytes: Uint8Array;
17
+ dataUrl: string;
18
+ }
19
+
20
+ /** Largest logo the rasterizer loads (the cap apps/docs/lib/qr-api/logo.ts uses). */
21
+ const LOGO_MAX_BYTES = 1024 * 1024;
22
+
23
+ const LOGO_FETCH_TIMEOUT_MS = 10_000;
24
+
25
+ /** Reads the response body, giving up once it passes the size cap. */
26
+ async function readBodyCapped(
27
+ response: Response,
28
+ maxBytes: number
29
+ ): Promise<Uint8Array | null> {
30
+ if (!response.body) {
31
+ return null;
32
+ }
33
+ const reader = response.body.getReader();
34
+ const chunks: Uint8Array[] = [];
35
+ let received = 0;
36
+ for (;;) {
37
+ const { done, value } = await reader.read();
38
+ if (done) {
39
+ break;
40
+ }
41
+ received += value.byteLength;
42
+ if (received > maxBytes) {
43
+ await reader.cancel().catch(() => {
44
+ // Already over the cap; losing this read is fine.
45
+ });
46
+ return null;
47
+ }
48
+ chunks.push(value);
49
+ }
50
+ const bytes = new Uint8Array(received);
51
+ let offset = 0;
52
+ for (const chunk of chunks) {
53
+ bytes.set(chunk, offset);
54
+ offset += chunk.byteLength;
55
+ }
56
+ return bytes;
57
+ }
58
+
59
+ const base64ToBytes = (base64: string) =>
60
+ Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
61
+
62
+ const bytesToBase64 = (bytes: Uint8Array) => {
63
+ let binary = "";
64
+ for (let i = 0; i < bytes.length; i += 0x80_00) {
65
+ binary += String.fromCharCode(...bytes.subarray(i, i + 0x80_00));
66
+ }
67
+ return btoa(binary);
68
+ };
69
+
70
+ /**
71
+ * Sniffs a file's first bytes into an image MIME type, or null. These are
72
+ * the types the rasterizers draw (resvg renders PNG, JPEG, GIF and WebP
73
+ * images, plus nested SVG, the same way browsers do).
74
+ */
75
+ function sniffImageMime(bytes: Uint8Array): string | null {
76
+ if (bytes[0] === 0x89 && bytes[1] === 0x50) {
77
+ return "image/png";
78
+ }
79
+ if (bytes[0] === 0xff && bytes[1] === 0xd8) {
80
+ return "image/jpeg";
81
+ }
82
+ if (bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46) {
83
+ return "image/gif";
84
+ }
85
+ if (
86
+ bytes[0] === 0x52 &&
87
+ bytes[1] === 0x49 &&
88
+ bytes[2] === 0x46 &&
89
+ bytes[3] === 0x46 &&
90
+ bytes[8] === 0x57 &&
91
+ bytes[9] === 0x45 &&
92
+ bytes[10] === 0x42 &&
93
+ bytes[11] === 0x50
94
+ ) {
95
+ return "image/webp";
96
+ }
97
+ const head = new TextDecoder()
98
+ .decode(bytes.subarray(0, 512))
99
+ .trimStart()
100
+ .toLowerCase();
101
+ if (head.startsWith("<?xml") || head.startsWith("<svg")) {
102
+ return "image/svg+xml";
103
+ }
104
+ return null;
105
+ }
106
+
107
+ /**
108
+ * Loads a logo the way a Node export needs it: a data URL is decoded; an
109
+ * http(s) URL is fetched and anything else is read from disk — but only when
110
+ * the caller opts in with `loadExternal`, since a library function that runs
111
+ * on servers must not become a way to fetch internal URLs or read files
112
+ * (a data URL, which the caller already holds, needs no opt-in). Fetches are
113
+ * capped at 1 MB and refuse redirects. Returns null when it can't be loaded
114
+ * or isn't an image the rasterizers draw — the logo is left out then, the
115
+ * same thing the browser path does when an <img> fails to load.
116
+ */
117
+ export async function loadLogoForRasterizer(
118
+ src: string,
119
+ loadExternal = false
120
+ ): Promise<RasterLogo | null> {
121
+ if (src.startsWith("data:")) {
122
+ const comma = src.indexOf(",");
123
+ if (comma < 0) {
124
+ return null;
125
+ }
126
+ // Whatever the caller handed over stays the <image> href; the bytes are
127
+ // for sharp's composite path only and may fail to decode.
128
+ try {
129
+ const bytes = src.slice(5, comma).endsWith(";base64")
130
+ ? base64ToBytes(src.slice(comma + 1))
131
+ : new TextEncoder().encode(decodeURIComponent(src.slice(comma + 1)));
132
+ return { bytes, dataUrl: src };
133
+ } catch {
134
+ return null;
135
+ }
136
+ }
137
+
138
+ if (!loadExternal) {
139
+ return null;
140
+ }
141
+
142
+ let bytes: Uint8Array;
143
+ if (/^https?:\/\//i.test(src)) {
144
+ try {
145
+ // redirect: "error" keeps a URL a caller sent from being walked
146
+ // somewhere else by a redirect.
147
+ const response = await fetch(src, {
148
+ redirect: "error",
149
+ signal: AbortSignal.timeout(LOGO_FETCH_TIMEOUT_MS),
150
+ });
151
+ if (!response.ok) {
152
+ return null;
153
+ }
154
+ const body = await readBodyCapped(response, LOGO_MAX_BYTES);
155
+ if (!body) {
156
+ return null;
157
+ }
158
+ bytes = body;
159
+ } catch {
160
+ return null;
161
+ }
162
+ } else if (typeof process !== "undefined" && process.versions?.node) {
163
+ // A local path. The specifier is computed so browser bundlers never
164
+ // try to resolve node:fs.
165
+ try {
166
+ const specifier = ["node:fs", "promises"].join("/");
167
+ const fs = (await import(specifier)) as typeof import("node:fs/promises");
168
+ const stats = await fs.stat(src);
169
+ if (stats.size > LOGO_MAX_BYTES) {
170
+ return null;
171
+ }
172
+ bytes = new Uint8Array(await fs.readFile(src));
173
+ } catch {
174
+ return null;
175
+ }
176
+ } else {
177
+ return null;
178
+ }
179
+
180
+ const mime = sniffImageMime(bytes);
181
+ if (!mime) {
182
+ return null;
183
+ }
184
+ return { bytes, dataUrl: `data:${mime};base64,${bytesToBase64(bytes)}` };
185
+ }
186
+
187
+ /**
188
+ * Rasterizes the SVG the library renders into PNG bytes, at the SVG's own
189
+ * size (a fractional frame size rounds the way the browser's canvas does).
190
+ * The rasterizer is an optional peer dependency, loaded only here; when
191
+ * neither is installed the error names what to install.
192
+ */
193
+ export async function rasterizeSvgToPng(
194
+ svg: string,
195
+ logo: RasterLogo | null
196
+ ): Promise<Uint8Array> {
197
+ let Resvg: typeof import("@resvg/resvg-js").Resvg;
198
+ try {
199
+ ({ Resvg } = await import("@resvg/resvg-js"));
200
+ } catch (resvgError) {
201
+ // Not installed (or its binary didn't load): try sharp instead.
202
+ return await rasterizeWithSharp(svg, logo, resvgError);
203
+ }
204
+ // fitTo "original" (the default) renders at the SVG's own width and
205
+ // height, so the PNG is exactly as large as the SVG markup says.
206
+ const rendered = new Resvg(svg).render();
207
+ return new Uint8Array(rendered.asPng());
208
+ }
209
+
210
+ const describeError = (error: unknown) =>
211
+ error instanceof Error ? error.message : String(error);
212
+
213
+ async function rasterizeWithSharp(
214
+ svg: string,
215
+ logo: RasterLogo | null,
216
+ resvgError: unknown
217
+ ): Promise<Uint8Array> {
218
+ let sharp: SharpFactory;
219
+ try {
220
+ sharp = ((await import("sharp")) as { default: SharpFactory }).default;
221
+ } catch (sharpError) {
222
+ throw new Error(
223
+ "PNG export in Node needs an optional rasterizer package: " +
224
+ "`npm install @resvg/resvg-js` (draws embedded logos like a browser) " +
225
+ "or `npm install sharp`. " +
226
+ `(${describeError(resvgError)}; ${describeError(sharpError)})`
227
+ );
228
+ }
229
+
230
+ const png = await sharp(new TextEncoder().encode(svg)).png().toBuffer();
231
+ // sharp's bundled SVG renderer skips embedded <image> elements, so the
232
+ // logo never reaches the pixels: find where it belongs and composite it.
233
+ if (!logo) {
234
+ return new Uint8Array(png);
235
+ }
236
+ const box = await findLogoBox(sharp, svg);
237
+ if (!box) {
238
+ return new Uint8Array(png);
239
+ }
240
+ const logoPng = await sharp(logo.bytes)
241
+ .resize(box.width, box.height, { fit: "fill" })
242
+ .png()
243
+ .toBuffer();
244
+ const composited = await sharp(png)
245
+ .composite([{ input: logoPng, left: box.left, top: box.top }])
246
+ .png()
247
+ .toBuffer();
248
+ return new Uint8Array(composited);
249
+ }
250
+
251
+ /**
252
+ * Finds the logo's pixel box in the rendered output. The <image> is swapped
253
+ * for a lone visible rect, so the box comes out right even inside template
254
+ * transforms.
255
+ */
256
+ async function findLogoBox(sharp: SharpFactory, svg: string) {
257
+ const imageTag = svg.match(/<image\b[^>]*?(?:\/>|><\/image>)/)?.[0];
258
+ if (!imageTag) {
259
+ return null;
260
+ }
261
+ const markerTag = imageTag
262
+ .replace(/^<image\b/, '<rect class="qrdx-logo-box"')
263
+ .replace(/\shref="[^"]*"/, "")
264
+ .replace(/(?:\/>|><\/image>)$/, ' fill="#000"/>');
265
+ const markerSvg = svg
266
+ .replace(imageTag, markerTag)
267
+ .replace(
268
+ /<svg\b[^>]*>/,
269
+ (open) =>
270
+ `${open}<style>*{visibility:hidden}.qrdx-logo-box{visibility:visible}</style>`
271
+ );
272
+ const { info } = await sharp(new TextEncoder().encode(markerSvg))
273
+ .png()
274
+ .trim()
275
+ .toBuffer({ resolveWithObject: true });
276
+ return {
277
+ left: -(info.trimOffsetLeft ?? 0),
278
+ top: -(info.trimOffsetTop ?? 0),
279
+ width: info.width,
280
+ height: info.height,
281
+ };
282
+ }
package/src/utils.tsx CHANGED
@@ -43,6 +43,7 @@ import { generateCornerSquarePath } from "./corner-eye";
43
43
  import { isFrameActive, wrapWithFrame } from "./frame";
44
44
  import { LOGO_PLATE_INSET, LOGO_ROUNDED_RADIUS, renderLogo } from "./logo";
45
45
  import { capImageSettings } from "./logo-budget";
46
+ import { partMarker, type QRPart, type QRPartEye } from "./part-markers";
46
47
  import { getLayoutMargin, shapeBackground, shapeDecoration } from "./qr-shape";
47
48
  import { hashString } from "./shapes";
48
49
  import { getTemplate } from "./templates";
@@ -962,6 +963,7 @@ export function QRCodeSVG(props: QRPropsSVG) {
962
963
  autoLevel,
963
964
  shape,
964
965
  frameLabelMarkers,
966
+ partMarkers,
965
967
  ...otherProps
966
968
  } = props;
967
969
  // A logo no bigger than the code can repair (logo-budget.ts)
@@ -1006,15 +1008,33 @@ export function QRCodeSVG(props: QRPropsSVG) {
1006
1008
  // silhouette (a silhouette that can't hold the code draws square)
1007
1009
  const layoutMargin = getLayoutMargin(cells.length, margin, shape);
1008
1010
  const decoration = shapeDecoration(value, cells.length, margin, shape);
1011
+ // Editors find each part by its marker (partMarkers, part-markers.ts)
1012
+ const part = (name: QRPart, eye?: QRPartEye) =>
1013
+ partMarker(partMarkers, name, eye);
1009
1014
  const outline = (px: number, fill: FillProps) => {
1010
1015
  const background = shapeBackground(shape, px);
1011
1016
  if (!background) {
1012
- return <rect {...fill} height={px} width={px} x={0} y={0} />;
1017
+ return (
1018
+ <rect
1019
+ {...fill}
1020
+ height={px}
1021
+ width={px}
1022
+ x={0}
1023
+ y={0}
1024
+ {...part("background")}
1025
+ />
1026
+ );
1013
1027
  }
1014
1028
  return "circle" in background ? (
1015
- <circle cx={fmt(px / 2)} cy={fmt(px / 2)} {...fill} r={fmt(px / 2)} />
1029
+ <circle
1030
+ cx={fmt(px / 2)}
1031
+ cy={fmt(px / 2)}
1032
+ {...fill}
1033
+ r={fmt(px / 2)}
1034
+ {...part("background")}
1035
+ />
1016
1036
  ) : (
1017
- <path d={background.path} {...fill} />
1037
+ <path d={background.path} {...fill} {...part("background")} />
1018
1038
  );
1019
1039
  };
1020
1040
 
@@ -1075,6 +1095,9 @@ export function QRCodeSVG(props: QRPropsSVG) {
1075
1095
  w: imgWidth,
1076
1096
  h: imgHeight,
1077
1097
  });
1098
+ if (partMarkers) {
1099
+ image = React.cloneElement(image, part("logo"));
1100
+ }
1078
1101
  }
1079
1102
  }
1080
1103
 
@@ -1107,6 +1130,10 @@ export function QRCodeSVG(props: QRPropsSVG) {
1107
1130
  }),
1108
1131
  })
1109
1132
  : null;
1133
+ const markedArtLayer =
1134
+ artLayer && partMarkers
1135
+ ? React.cloneElement(artLayer, part("body"))
1136
+ : artLayer;
1110
1137
  const artEyes =
1111
1138
  artLayer && art
1112
1139
  ? getQRArtEyeColors({ art, version: qrCode.version, ...artColors })
@@ -1158,13 +1185,17 @@ export function QRCodeSVG(props: QRPropsSVG) {
1158
1185
  );
1159
1186
 
1160
1187
  // Data modules, plus a shaped code's decoration around them
1161
- const dataLayer = artLayer ? (
1188
+ const dataLayer = markedArtLayer ? (
1162
1189
  <>
1163
- {artLayer}
1164
- {decorationShapes && <g {...fgFillValue}>{decorationShapes}</g>}
1190
+ {markedArtLayer}
1191
+ {decorationShapes && (
1192
+ <g {...fgFillValue} {...part("body")}>
1193
+ {decorationShapes}
1194
+ </g>
1195
+ )}
1165
1196
  </>
1166
1197
  ) : (
1167
- <g {...fgFillValue}>
1198
+ <g {...fgFillValue} {...part("body")}>
1168
1199
  {dataCircles}
1169
1200
  {decorationShapes}
1170
1201
  </g>
@@ -1356,7 +1387,7 @@ export function QRCodeSVG(props: QRPropsSVG) {
1356
1387
  {dataLayer}
1357
1388
 
1358
1389
  {/* Top-left corner square */}
1359
- <g {...topLeftEyeFillValue}>
1390
+ <g {...topLeftEyeFillValue} {...part("eye-outer", "top-left")}>
1360
1391
  <path
1361
1392
  d={topLeftEye}
1362
1393
  fillRule="evenodd"
@@ -1365,10 +1396,12 @@ export function QRCodeSVG(props: QRPropsSVG) {
1365
1396
  </g>
1366
1397
 
1367
1398
  {/* Top-left corner dot */}
1368
- <g {...topLeftDotFillValue}>{topLeftDot}</g>
1399
+ <g {...topLeftDotFillValue} {...part("eye-centre", "top-left")}>
1400
+ {topLeftDot}
1401
+ </g>
1369
1402
 
1370
1403
  {/* Top-right corner square */}
1371
- <g {...topRightEyeFillValue}>
1404
+ <g {...topRightEyeFillValue} {...part("eye-outer", "top-right")}>
1372
1405
  <path
1373
1406
  d={topRightEye}
1374
1407
  fillRule="evenodd"
@@ -1377,10 +1410,12 @@ export function QRCodeSVG(props: QRPropsSVG) {
1377
1410
  </g>
1378
1411
 
1379
1412
  {/* Top-right corner dot */}
1380
- <g {...topRightDotFillValue}>{topRightDot}</g>
1413
+ <g {...topRightDotFillValue} {...part("eye-centre", "top-right")}>
1414
+ {topRightDot}
1415
+ </g>
1381
1416
 
1382
1417
  {/* Bottom-left corner square */}
1383
- <g {...bottomLeftEyeFillValue}>
1418
+ <g {...bottomLeftEyeFillValue} {...part("eye-outer", "bottom-left")}>
1384
1419
  <path
1385
1420
  d={bottomLeftEye}
1386
1421
  fillRule="evenodd"
@@ -1389,7 +1424,9 @@ export function QRCodeSVG(props: QRPropsSVG) {
1389
1424
  </g>
1390
1425
 
1391
1426
  {/* Bottom-left corner dot */}
1392
- <g {...bottomLeftDotFillValue}>{bottomLeftDot}</g>
1427
+ <g {...bottomLeftDotFillValue} {...part("eye-centre", "bottom-left")}>
1428
+ {bottomLeftDot}
1429
+ </g>
1393
1430
 
1394
1431
  {image}
1395
1432
  </>
@@ -1449,7 +1486,7 @@ export function QRCodeSVG(props: QRPropsSVG) {
1449
1486
  {dataLayer}
1450
1487
 
1451
1488
  {/* Top-left corner square */}
1452
- <g {...topLeftEyeFillValue}>
1489
+ <g {...topLeftEyeFillValue} {...part("eye-outer", "top-left")}>
1453
1490
  <path
1454
1491
  d={topLeftEye}
1455
1492
  fillRule="evenodd"
@@ -1458,10 +1495,12 @@ export function QRCodeSVG(props: QRPropsSVG) {
1458
1495
  </g>
1459
1496
 
1460
1497
  {/* Top-left corner dot */}
1461
- <g {...topLeftDotFillValue}>{topLeftDot}</g>
1498
+ <g {...topLeftDotFillValue} {...part("eye-centre", "top-left")}>
1499
+ {topLeftDot}
1500
+ </g>
1462
1501
 
1463
1502
  {/* Top-right corner square */}
1464
- <g {...topRightEyeFillValue}>
1503
+ <g {...topRightEyeFillValue} {...part("eye-outer", "top-right")}>
1465
1504
  <path
1466
1505
  d={topRightEye}
1467
1506
  fillRule="evenodd"
@@ -1470,10 +1509,12 @@ export function QRCodeSVG(props: QRPropsSVG) {
1470
1509
  </g>
1471
1510
 
1472
1511
  {/* Top-right corner dot */}
1473
- <g {...topRightDotFillValue}>{topRightDot}</g>
1512
+ <g {...topRightDotFillValue} {...part("eye-centre", "top-right")}>
1513
+ {topRightDot}
1514
+ </g>
1474
1515
 
1475
1516
  {/* Bottom-left corner square */}
1476
- <g {...bottomLeftEyeFillValue}>
1517
+ <g {...bottomLeftEyeFillValue} {...part("eye-outer", "bottom-left")}>
1477
1518
  <path
1478
1519
  d={bottomLeftEye}
1479
1520
  fillRule="evenodd"
@@ -1482,7 +1523,9 @@ export function QRCodeSVG(props: QRPropsSVG) {
1482
1523
  </g>
1483
1524
 
1484
1525
  {/* Bottom-left corner dot */}
1485
- <g {...bottomLeftDotFillValue}>{bottomLeftDot}</g>
1526
+ <g {...bottomLeftDotFillValue} {...part("eye-centre", "bottom-left")}>
1527
+ {bottomLeftDot}
1528
+ </g>
1486
1529
 
1487
1530
  {image}
1488
1531
  </g>
package/types/qr.ts CHANGED
@@ -242,6 +242,11 @@ export interface QRProps {
242
242
  // export (getQRAsSVGDataUri and the PNG, JPG, PDF and EPS built on it)
243
243
  // drops it, so downloads never carry the marker.
244
244
  frameLabelMarkers?: boolean;
245
+ // For editors drawing a live preview: marks the drawn parts with
246
+ // data-qrdx-part ("eye-outer" and "eye-centre", each with data-qrdx-eye,
247
+ // "body", "logo", "background"; see QR_PART_ATTRIBUTE). Off by default,
248
+ // and every export drops it, like frameLabelMarkers.
249
+ partMarkers?: boolean;
245
250
  }
246
251
 
247
252
  export type QRPropsCanvas = QRProps &