qrdx 0.0.45 → 0.0.47

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.
Files changed (206) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +353 -300
  3. package/dist/index.js +27 -7
  4. package/dist/index.js.map +1 -1
  5. package/dist/index.mjs +27 -7
  6. package/dist/index.mjs.map +1 -1
  7. package/dist/qr-code-canvas.js +12 -0
  8. package/dist/qr-code-canvas.js.map +1 -0
  9. package/dist/qr-code-canvas.mjs +12 -0
  10. package/dist/qr-code-canvas.mjs.map +1 -0
  11. package/dist/src/api.d.ts.map +1 -1
  12. package/dist/src/art-trace.d.ts +46 -0
  13. package/dist/src/art-trace.d.ts.map +1 -0
  14. package/dist/src/art.d.ts +138 -0
  15. package/dist/src/art.d.ts.map +1 -0
  16. package/dist/src/body-patterns.d.ts +34 -0
  17. package/dist/src/body-patterns.d.ts.map +1 -0
  18. package/dist/src/codegen.d.ts +5 -5
  19. package/dist/src/codegen.d.ts.map +1 -1
  20. package/dist/src/codeword-map.d.ts +40 -0
  21. package/dist/src/codeword-map.d.ts.map +1 -0
  22. package/dist/src/constants.d.ts +4 -7
  23. package/dist/src/constants.d.ts.map +1 -1
  24. package/dist/src/corner-dot.d.ts +3 -1
  25. package/dist/src/corner-dot.d.ts.map +1 -1
  26. package/dist/src/corner-eye.d.ts +5 -2
  27. package/dist/src/corner-eye.d.ts.map +1 -1
  28. package/dist/src/detection.d.ts.map +1 -1
  29. package/dist/src/download.d.ts +22 -5
  30. package/dist/src/download.d.ts.map +1 -1
  31. package/dist/src/eps.d.ts +62 -0
  32. package/dist/src/eps.d.ts.map +1 -0
  33. package/dist/src/frame-icons.d.ts +11 -0
  34. package/dist/src/frame-icons.d.ts.map +1 -0
  35. package/dist/src/frame-import.d.ts +61 -0
  36. package/dist/src/frame-import.d.ts.map +1 -0
  37. package/dist/src/frame-spec.d.ts +24 -0
  38. package/dist/src/frame-spec.d.ts.map +1 -0
  39. package/dist/src/frame-styles.d.ts +50 -0
  40. package/dist/src/frame-styles.d.ts.map +1 -0
  41. package/dist/src/frame.d.ts +126 -0
  42. package/dist/src/frame.d.ts.map +1 -0
  43. package/dist/src/frames/builtin.d.ts +8 -0
  44. package/dist/src/frames/builtin.d.ts.map +1 -0
  45. package/dist/src/frames/official.d.ts +18 -0
  46. package/dist/src/frames/official.d.ts.map +1 -0
  47. package/dist/src/helpers.d.ts +15 -2
  48. package/dist/src/helpers.d.ts.map +1 -1
  49. package/dist/src/index.d.ts +24 -13
  50. package/dist/src/index.d.ts.map +1 -1
  51. package/dist/src/logo-budget.d.ts +54 -0
  52. package/dist/src/logo-budget.d.ts.map +1 -0
  53. package/dist/src/logo-cleanup.d.ts +25 -0
  54. package/dist/src/logo-cleanup.d.ts.map +1 -0
  55. package/dist/src/logo.d.ts +28 -0
  56. package/dist/src/logo.d.ts.map +1 -0
  57. package/dist/src/print.d.ts +73 -0
  58. package/dist/src/print.d.ts.map +1 -0
  59. package/dist/src/qr-code-canvas.d.ts +13 -0
  60. package/dist/src/qr-code-canvas.d.ts.map +1 -0
  61. package/dist/src/qr-code.d.ts +4 -2
  62. package/dist/src/qr-code.d.ts.map +1 -1
  63. package/dist/src/qr-outline.d.ts +41 -0
  64. package/dist/src/qr-outline.d.ts.map +1 -0
  65. package/dist/src/qr-shape.d.ts +72 -0
  66. package/dist/src/qr-shape.d.ts.map +1 -0
  67. package/dist/src/scan-risk.d.ts +40 -0
  68. package/dist/src/scan-risk.d.ts.map +1 -0
  69. package/dist/src/scan-score.d.ts +154 -0
  70. package/dist/src/scan-score.d.ts.map +1 -0
  71. package/dist/src/shapes.d.ts +36 -0
  72. package/dist/src/shapes.d.ts.map +1 -0
  73. package/dist/src/silhouette.d.ts +28 -0
  74. package/dist/src/silhouette.d.ts.map +1 -0
  75. package/dist/src/utils/color.d.ts.map +1 -1
  76. package/dist/src/utils/fmt.d.ts +24 -0
  77. package/dist/src/utils/fmt.d.ts.map +1 -0
  78. package/dist/src/utils/paint.d.ts +80 -0
  79. package/dist/src/utils/paint.d.ts.map +1 -0
  80. package/dist/src/utils/parse-color.d.ts +21 -0
  81. package/dist/src/utils/parse-color.d.ts.map +1 -0
  82. package/dist/src/utils/path-data.d.ts +24 -0
  83. package/dist/src/utils/path-data.d.ts.map +1 -0
  84. package/dist/src/utils/png.d.ts +16 -0
  85. package/dist/src/utils/png.d.ts.map +1 -0
  86. package/dist/src/utils/polygon-clip.d.ts +26 -0
  87. package/dist/src/utils/polygon-clip.d.ts.map +1 -0
  88. package/dist/src/utils/print-shared.d.ts +20 -0
  89. package/dist/src/utils/print-shared.d.ts.map +1 -0
  90. package/dist/src/utils/svg-geometry.d.ts +49 -0
  91. package/dist/src/utils/svg-geometry.d.ts.map +1 -0
  92. package/dist/src/utils/svg-gradient.d.ts +59 -0
  93. package/dist/src/utils/svg-gradient.d.ts.map +1 -0
  94. package/dist/src/utils/svg-painter.d.ts +152 -0
  95. package/dist/src/utils/svg-painter.d.ts.map +1 -0
  96. package/dist/src/utils.d.ts +18 -2
  97. package/dist/src/utils.d.ts.map +1 -1
  98. package/dist/types/art.d.ts +64 -0
  99. package/dist/types/art.d.ts.map +1 -0
  100. package/dist/types/color.d.ts +125 -7
  101. package/dist/types/color.d.ts.map +1 -1
  102. package/dist/types/corner-dot.d.ts +52 -2
  103. package/dist/types/corner-dot.d.ts.map +1 -1
  104. package/dist/types/corner-eye.d.ts +43 -2
  105. package/dist/types/corner-eye.d.ts.map +1 -1
  106. package/dist/types/frame-spec.d.ts +3509 -0
  107. package/dist/types/frame-spec.d.ts.map +1 -0
  108. package/dist/types/frame.d.ts +68 -0
  109. package/dist/types/frame.d.ts.map +1 -0
  110. package/dist/types/image-pattern.d.ts +15 -1
  111. package/dist/types/image-pattern.d.ts.map +1 -1
  112. package/dist/types/index.d.ts +15 -9
  113. package/dist/types/index.d.ts.map +1 -1
  114. package/dist/types/index.js +6 -0
  115. package/dist/types/index.js.map +1 -0
  116. package/dist/types/index.mjs +6 -0
  117. package/dist/types/index.mjs.map +1 -0
  118. package/dist/types/qr.d.ts +1684 -4
  119. package/dist/types/qr.d.ts.map +1 -1
  120. package/dist/types/template.d.ts +2 -2
  121. package/dist/types/template.d.ts.map +1 -1
  122. package/package.json +63 -20
  123. package/src/api.tsx +67 -17
  124. package/src/art-trace.ts +554 -0
  125. package/src/art.tsx +2226 -0
  126. package/src/body-patterns.tsx +389 -0
  127. package/src/codegen.ts +10 -5
  128. package/src/codeword-map.ts +265 -0
  129. package/src/constants.ts +4 -8
  130. package/src/corner-dot.tsx +209 -33
  131. package/src/corner-eye.ts +328 -60
  132. package/src/detection.ts +5 -11
  133. package/src/download.tsx +123 -52
  134. package/src/eps.ts +701 -0
  135. package/src/frame-icons.ts +325 -0
  136. package/src/frame-import.ts +1198 -0
  137. package/src/frame-spec.ts +518 -0
  138. package/src/frame-styles.ts +1095 -0
  139. package/src/frame.tsx +630 -0
  140. package/src/frames/builtin/banner-bottom.json +58 -0
  141. package/src/frames/builtin/circle.json +81 -0
  142. package/src/frames/builtin/rounded-border.json +60 -0
  143. package/src/frames/builtin/ticket.json +51 -0
  144. package/src/frames/builtin.ts +20 -0
  145. package/src/frames/official/attendance.json +110 -0
  146. package/src/frames/official/audio-guide.json +95 -0
  147. package/src/frames/official/book-now.json +103 -0
  148. package/src/frames/official/check-in.json +110 -0
  149. package/src/frames/official/christmas.json +131 -0
  150. package/src/frames/official/donate.json +77 -0
  151. package/src/frames/official/event-ticket.json +77 -0
  152. package/src/frames/official/feedback-bubble.json +73 -0
  153. package/src/frames/official/follow-us.json +83 -0
  154. package/src/frames/official/get-the-app.json +107 -0
  155. package/src/frames/official/halloween.json +80 -0
  156. package/src/frames/official/new-year.json +94 -0
  157. package/src/frames/official/order-at-table.json +86 -0
  158. package/src/frames/official/product-info.json +119 -0
  159. package/src/frames/official/register-product.json +77 -0
  160. package/src/frames/official/review-us.json +127 -0
  161. package/src/frames/official/rsvp-card.json +112 -0
  162. package/src/frames/official/save-contact.json +117 -0
  163. package/src/frames/official/scan-to-pay.json +94 -0
  164. package/src/frames/official/shop-window.json +81 -0
  165. package/src/frames/official/sign-rider.json +81 -0
  166. package/src/frames/official/table-tent.json +75 -0
  167. package/src/frames/official/wifi-card.json +89 -0
  168. package/src/frames/official/winter.json +142 -0
  169. package/src/frames/official.ts +77 -0
  170. package/src/helpers.ts +168 -11
  171. package/src/index.tsx +141 -172
  172. package/src/logo-budget.ts +226 -0
  173. package/src/logo-cleanup.ts +146 -0
  174. package/src/logo.tsx +137 -0
  175. package/src/print.ts +794 -0
  176. package/src/qr-code-canvas.tsx +241 -0
  177. package/src/qr-code.tsx +51 -16
  178. package/src/qr-outline.ts +511 -0
  179. package/src/qr-shape.ts +255 -0
  180. package/src/scan-risk.ts +197 -0
  181. package/src/scan-score.ts +1629 -0
  182. package/src/shapes.ts +169 -0
  183. package/src/silhouette.ts +334 -0
  184. package/src/utils/color.ts +10 -1
  185. package/src/utils/fmt.ts +59 -0
  186. package/src/utils/paint.ts +317 -0
  187. package/src/utils/parse-color.ts +135 -0
  188. package/src/utils/path-data.ts +182 -0
  189. package/src/utils/png.ts +175 -0
  190. package/src/utils/polygon-clip.ts +163 -0
  191. package/src/utils/print-shared.ts +74 -0
  192. package/src/utils/svg-geometry.ts +838 -0
  193. package/src/utils/svg-gradient.ts +407 -0
  194. package/src/utils/svg-painter.ts +946 -0
  195. package/src/utils.tsx +794 -385
  196. package/types/art.ts +74 -0
  197. package/types/color.ts +132 -12
  198. package/types/corner-dot.ts +41 -4
  199. package/types/corner-eye.ts +31 -4
  200. package/types/frame-spec.ts +748 -0
  201. package/types/frame.ts +67 -0
  202. package/types/image-pattern.ts +15 -0
  203. package/types/index.ts +106 -4
  204. package/types/qr.ts +180 -2
  205. package/types/template.ts +2 -2
  206. package/dist/cli.js +0 -4231
package/src/eps.ts ADDED
@@ -0,0 +1,701 @@
1
+ /** biome-ignore-all lint/style/noMagicNumbers: PostScript output */
2
+ /** biome-ignore-all lint/suspicious/noBitwiseOperators: ASCII85 and JPEG parsing */
3
+ import type { QRProps } from "../types";
4
+ import { DEFAULT_BGCOLOR } from "./constants";
5
+ import { downloadFile } from "./download";
6
+ import { getPrintLayout, type PrintColorMode } from "./print";
7
+ import { getSolidColor } from "./utils/color";
8
+ import { fmt } from "./utils/fmt";
9
+ import { type RGBAColor, rgbToCmyk } from "./utils/parse-color";
10
+ import { decodePng, deflate } from "./utils/png";
11
+ import {
12
+ getPrintBleedColor,
13
+ getPrintBleedFill,
14
+ renderPrintSVG,
15
+ setBackdrop,
16
+ } from "./utils/print-shared";
17
+ import {
18
+ applyMatrix,
19
+ type Matrix,
20
+ matrixScale,
21
+ multiply,
22
+ parseSvgMarkup,
23
+ type Segment,
24
+ type SvgNode,
25
+ } from "./utils/svg-geometry";
26
+ import {
27
+ collectGradients,
28
+ formatMatrix,
29
+ invertMatrix,
30
+ type PlacedGradient,
31
+ type SvgGradient,
32
+ shadingDictionary,
33
+ } from "./utils/svg-gradient";
34
+ import {
35
+ collectGradientColors,
36
+ collectImageHrefs,
37
+ length,
38
+ type PaintState,
39
+ rasterizeImage,
40
+ SvgPainter,
41
+ } from "./utils/svg-painter";
42
+
43
+ const MM_PER_INCH = 25.4;
44
+ const POINTS_PER_MM = 72 / MM_PER_INCH;
45
+ const DEFAULT_EPS_SIZE_MM = 50;
46
+
47
+ export interface EPSOptions {
48
+ /** "cmyk" writes naive CMYK colors, see `rgbToCmyk` (default "rgb") */
49
+ colorMode?: PrintColorMode;
50
+ /** Width of the QR code itself in millimetres (default 50). A frame adds to it. */
51
+ sizeMm?: number;
52
+ /** Bleed on every side, in millimetres (default 0, at most 20) */
53
+ bleedMm?: number;
54
+ }
55
+
56
+ export interface SVGToEPSOptions {
57
+ /**
58
+ * Output width in PostScript points (72 per inch); the height follows the
59
+ * SVG's aspect ratio. Defaults to the SVG's own width (1 unit = 1 point).
60
+ */
61
+ width?: number;
62
+ colorMode?: PrintColorMode;
63
+ /** Bleed on every side, in points (default 0) */
64
+ bleed?: number;
65
+ /**
66
+ * CSS color that fills the bleed area, or `url(#id)` of a gradient in the
67
+ * SVG to continue it as the root's user space places it (default: none)
68
+ */
69
+ bleedColor?: string | null;
70
+ title?: string;
71
+ /**
72
+ * The code's background color: see-through paint is flattened over it
73
+ * (on white paper), since PostScript has no transparency. Default white.
74
+ */
75
+ background?: string;
76
+ }
77
+
78
+ // ── Embedded images ────────────────────────────────────────────────────────
79
+
80
+ type EpsImage =
81
+ | {
82
+ kind: "jpeg";
83
+ width: number;
84
+ height: number;
85
+ components: 1 | 3;
86
+ bytes: Uint8Array;
87
+ progressive: boolean;
88
+ }
89
+ | {
90
+ kind: "raw";
91
+ width: number;
92
+ height: number;
93
+ components: 3 | 4;
94
+ bytes: Uint8Array;
95
+ compressed: boolean;
96
+ };
97
+
98
+ function dataUrlBytes(href: string): Uint8Array | null {
99
+ const match = /^data:[^,]*?(;base64)?,(.*)$/s.exec(href);
100
+ if (!match) {
101
+ return null;
102
+ }
103
+ try {
104
+ const binary = match[1]
105
+ ? atob(match[2] as string)
106
+ : decodeURIComponent(match[2] as string);
107
+ const bytes = new Uint8Array(binary.length);
108
+ for (let i = 0; i < binary.length; i++) {
109
+ bytes[i] = binary.charCodeAt(i) & 0xff;
110
+ }
111
+ return bytes;
112
+ } catch {
113
+ return null;
114
+ }
115
+ }
116
+
117
+ /** Reads the frame header of a baseline or progressive JPEG. */
118
+ function readJpegInfo(bytes: Uint8Array) {
119
+ if (bytes[0] !== 0xff || bytes[1] !== 0xd8) {
120
+ return null;
121
+ }
122
+ let offset = 2;
123
+ while (offset + 9 < bytes.length) {
124
+ if (bytes[offset] !== 0xff) {
125
+ return null;
126
+ }
127
+ const marker = bytes[offset + 1] as number;
128
+ if (marker === 0xd8 || (marker >= 0xd0 && marker <= 0xd7)) {
129
+ offset += 2;
130
+ continue;
131
+ }
132
+ const segmentLength =
133
+ ((bytes[offset + 2] as number) << 8) | (bytes[offset + 3] as number);
134
+ if (marker === 0xc0 || marker === 0xc1 || marker === 0xc2) {
135
+ const height =
136
+ ((bytes[offset + 5] as number) << 8) | (bytes[offset + 6] as number);
137
+ const width =
138
+ ((bytes[offset + 7] as number) << 8) | (bytes[offset + 8] as number);
139
+ const components = bytes[offset + 9] as number;
140
+ return { width, height, components, progressive: marker === 0xc2 };
141
+ }
142
+ offset += 2 + segmentLength;
143
+ }
144
+ return null;
145
+ }
146
+
147
+ /** Composites RGBA over white and converts to RGB or naive CMYK samples. */
148
+ async function rawImage(
149
+ decoded: { width: number; height: number; data: Uint8Array },
150
+ cmyk: boolean
151
+ ): Promise<EpsImage> {
152
+ const { width, height, data } = decoded;
153
+ const components = cmyk ? 4 : 3;
154
+ const samples = new Uint8Array(width * height * components);
155
+ for (let i = 0; i < width * height; i++) {
156
+ const alpha = (data[i * 4 + 3] as number) / 255;
157
+ const r = (data[i * 4] as number) * alpha + 255 * (1 - alpha);
158
+ const g = (data[i * 4 + 1] as number) * alpha + 255 * (1 - alpha);
159
+ const b = (data[i * 4 + 2] as number) * alpha + 255 * (1 - alpha);
160
+ if (cmyk) {
161
+ const [c, m, y, k] = rgbToCmyk(r, g, b);
162
+ samples.set(
163
+ [c * 255, m * 255, y * 255, k * 255].map(Math.round),
164
+ i * components
165
+ );
166
+ } else {
167
+ samples.set(
168
+ [Math.round(r), Math.round(g), Math.round(b)],
169
+ i * components
170
+ );
171
+ }
172
+ }
173
+ const compressed = await deflate(samples);
174
+ return {
175
+ kind: "raw",
176
+ width,
177
+ height,
178
+ components,
179
+ bytes: compressed ?? samples,
180
+ compressed: Boolean(compressed),
181
+ };
182
+ }
183
+
184
+ async function prepareImage(
185
+ href: string,
186
+ cmyk: boolean
187
+ ): Promise<EpsImage | null> {
188
+ let source = href;
189
+ if (!/^data:image\/(png|jpe?g)[;,]/i.test(source)) {
190
+ // SVG/WebP logos and URLs: the browser can redraw them as PNG.
191
+ const png = await rasterizeImage(source);
192
+ if (!png) {
193
+ return null;
194
+ }
195
+ source = png;
196
+ }
197
+ const bytes = dataUrlBytes(source);
198
+ if (!bytes) {
199
+ return null;
200
+ }
201
+ const jpeg = readJpegInfo(bytes);
202
+ if (jpeg) {
203
+ if (!(jpeg.components === 1 || jpeg.components === 3)) {
204
+ return null;
205
+ }
206
+ return {
207
+ kind: "jpeg",
208
+ width: jpeg.width,
209
+ height: jpeg.height,
210
+ components: jpeg.components,
211
+ bytes,
212
+ progressive: jpeg.progressive,
213
+ };
214
+ }
215
+ const png = await decodePng(bytes);
216
+ return png ? await rawImage(png, cmyk) : null;
217
+ }
218
+
219
+ function ascii85(bytes: Uint8Array): string {
220
+ let out = "";
221
+ let line = 0;
222
+ const push = (chunk: string) => {
223
+ out += chunk;
224
+ line += chunk.length;
225
+ if (line >= 76) {
226
+ out += "\n";
227
+ line = 0;
228
+ }
229
+ };
230
+ for (let i = 0; i < bytes.length; i += 4) {
231
+ const count = Math.min(4, bytes.length - i);
232
+ let value = 0;
233
+ for (let j = 0; j < 4; j++) {
234
+ value = value * 256 + (j < count ? (bytes[i + j] as number) : 0);
235
+ }
236
+ if (value === 0 && count === 4) {
237
+ push("z");
238
+ continue;
239
+ }
240
+ const digits: string[] = [];
241
+ for (let j = 0; j < 5; j++) {
242
+ digits.unshift(String.fromCharCode((value % 85) + 33));
243
+ value = Math.floor(value / 85);
244
+ }
245
+ push(digits.slice(0, count + 1).join(""));
246
+ }
247
+ return `${out}~>`;
248
+ }
249
+
250
+ // ── PostScript writer ──────────────────────────────────────────────────────
251
+
252
+ const PROLOG = `/qrdxdict 40 dict def
253
+ qrdxdict begin
254
+ /m {moveto} bind def
255
+ /l {lineto} bind def
256
+ /c {curveto} bind def
257
+ /h {closepath} bind def
258
+ /n {newpath} bind def
259
+ /f {fill} bind def
260
+ /ef {eofill} bind def
261
+ /s {stroke} bind def
262
+ /w {setlinewidth} bind def
263
+ /rg {setrgbcolor} bind def
264
+ /cmyk {setcmykcolor} bind def
265
+ /latin1 {
266
+ findfont dup length dict begin
267
+ {1 index /FID ne {def} {pop pop} ifelse} forall
268
+ /Encoding ISOLatin1Encoding def
269
+ currentdict end definefont pop
270
+ } bind def
271
+ /QRDX-Regular /Helvetica latin1
272
+ /QRDX-Bold /Helvetica-Bold latin1
273
+ end`;
274
+
275
+ /** PostScript string literal; characters outside Latin-1 become "?". */
276
+ function psString(text: string): string {
277
+ let out = "(";
278
+ for (const char of text) {
279
+ const code = char.codePointAt(0) ?? 63;
280
+ if (char === "(" || char === ")" || char === "\\") {
281
+ out += `\\${char}`;
282
+ } else if (code >= 32 && code < 127) {
283
+ out += char;
284
+ } else if (code >= 160 && code <= 255) {
285
+ out += `\\${code.toString(8).padStart(3, "0")}`;
286
+ } else {
287
+ out += "?";
288
+ }
289
+ }
290
+ return `${out})`;
291
+ }
292
+
293
+ class EpsPainter extends SvgPainter {
294
+ readonly out: string[] = [];
295
+ /** Shading dictionary → the name it is defined under in qrdxdict */
296
+ readonly shadingNames = new Map<string, string>();
297
+ private readonly cmyk: boolean;
298
+ private readonly images: Map<string, EpsImage>;
299
+ usesLevel3 = false;
300
+
301
+ constructor(
302
+ cmyk: boolean,
303
+ gradients: Map<string, string>,
304
+ shadings: Map<string, SvgGradient>,
305
+ images: Map<string, EpsImage>
306
+ ) {
307
+ super(gradients, shadings);
308
+ this.cmyk = cmyk;
309
+ this.images = images;
310
+ }
311
+
312
+ color(color: RGBAColor): string {
313
+ if (this.cmyk) {
314
+ const [c, m, y, k] = rgbToCmyk(color.r, color.g, color.b);
315
+ return `${fmt(c)} ${fmt(m)} ${fmt(y)} ${fmt(k)} cmyk`;
316
+ }
317
+ return `${fmt(color.r / 255)} ${fmt(color.g / 255)} ${fmt(color.b / 255)} rg`;
318
+ }
319
+
320
+ tracePath(segments: Segment[], matrix: Matrix): string {
321
+ const ops: string[] = ["n"];
322
+ let open = false;
323
+ for (const segment of segments) {
324
+ if (segment.op === "M" || (segment.op === "L" && !open)) {
325
+ const [x, y] = applyMatrix(matrix, segment.x, segment.y);
326
+ ops.push(`${fmt(x)} ${fmt(y)} m`);
327
+ open = true;
328
+ } else if (segment.op === "L") {
329
+ const [x, y] = applyMatrix(matrix, segment.x, segment.y);
330
+ ops.push(`${fmt(x)} ${fmt(y)} l`);
331
+ } else if (segment.op === "C") {
332
+ if (!open) {
333
+ continue;
334
+ }
335
+ const [x1, y1] = applyMatrix(matrix, segment.x1, segment.y1);
336
+ const [x2, y2] = applyMatrix(matrix, segment.x2, segment.y2);
337
+ const [x, y] = applyMatrix(matrix, segment.x, segment.y);
338
+ ops.push(
339
+ `${fmt(x1)} ${fmt(y1)} ${fmt(x2)} ${fmt(y2)} ${fmt(x)} ${fmt(y)} c`
340
+ );
341
+ } else if (open) {
342
+ ops.push("h");
343
+ }
344
+ }
345
+ return ops.join(" ");
346
+ }
347
+
348
+ /** `gsave <path> clip n`: everything until `endClip` stays inside it. */
349
+ override beginClip(segments: Segment[], matrix: Matrix, evenOdd: boolean) {
350
+ this.out.push(
351
+ `gsave ${this.tracePath(segments, matrix)} ${evenOdd ? "eoclip" : "clip"} n`
352
+ );
353
+ return true;
354
+ }
355
+
356
+ override endClip() {
357
+ this.out.push("grestore");
358
+ }
359
+
360
+ rect(color: RGBAColor, x: number, y: number, width: number, height: number) {
361
+ this.out.push(
362
+ `${this.color(color)} n ${fmt(x)} ${fmt(y)} m ${fmt(x + width)} ${fmt(y)} l ${fmt(x + width)} ${fmt(y + height)} l ${fmt(x)} ${fmt(y + height)} l h f`
363
+ );
364
+ }
365
+
366
+ /**
367
+ * Fills the shape with a gradient: clip to its exact outline, then
368
+ * `shfill` (LanguageLevel 3) with the gradient space concatenated.
369
+ */
370
+ shade(segments: Segment[], state: PaintState, gradient: PlacedGradient) {
371
+ const matrix = multiply(state.matrix, gradient.matrix);
372
+ if (!invertMatrix(matrix)) {
373
+ return;
374
+ }
375
+ const dictionary = shadingDictionary(gradient, this.cmyk ? "cmyk" : "rgb");
376
+ let name = this.shadingNames.get(dictionary);
377
+ if (!name) {
378
+ name = `Sh${this.shadingNames.size}`;
379
+ this.shadingNames.set(dictionary, name);
380
+ }
381
+ this.usesLevel3 = true;
382
+ const clip = state.fillRule === "evenodd" ? "eoclip" : "clip";
383
+ this.out.push(
384
+ `gsave ${this.tracePath(segments, state.matrix)} ${clip} n [${formatMatrix(matrix)}] concat ${name} shfill grestore`
385
+ );
386
+ }
387
+
388
+ paint(segments: Segment[], _node: SvgNode, state: PaintState) {
389
+ if (segments.length === 0) {
390
+ return;
391
+ }
392
+ const opacity = state.opacity ?? 1;
393
+ if (opacity <= 0) {
394
+ return;
395
+ }
396
+ // PostScript has no transparency: see-through paint is flattened over
397
+ // the backdrop (the background on paper), see SvgPainter.flatten.
398
+ const paint = this.resolveFill(
399
+ state.fill,
400
+ segments,
401
+ state.viewport,
402
+ (state.fillOpacity ?? 1) * opacity
403
+ );
404
+ if (paint && "pattern" in paint) {
405
+ this.paintPattern(segments, state, paint.pattern, paint.alpha);
406
+ } else if (paint && "gradient" in paint) {
407
+ this.shade(segments, state, {
408
+ ...paint.gradient,
409
+ stops: paint.gradient.stops.map((stop) => ({
410
+ ...stop,
411
+ color: this.flatten({ ...stop.color, a: stop.color.a * paint.alpha }),
412
+ })),
413
+ });
414
+ }
415
+ const fill = paint && "color" in paint ? this.flatten(paint.color) : null;
416
+ const strokeColor =
417
+ state.strokeWidth > 0 ? this.resolveColor(state.stroke) : null;
418
+ const stroke =
419
+ strokeColor &&
420
+ this.flatten({ ...strokeColor, a: strokeColor.a * opacity });
421
+ if (!(fill || stroke)) {
422
+ return;
423
+ }
424
+ const path = this.tracePath(segments, state.matrix);
425
+ const fillOp = state.fillRule === "evenodd" ? "ef" : "f";
426
+ if (fill && stroke) {
427
+ this.out.push(`gsave ${this.color(fill)} ${path} ${fillOp} grestore`);
428
+ } else if (fill) {
429
+ this.out.push(`${this.color(fill)} ${path} ${fillOp}`);
430
+ }
431
+ if (stroke) {
432
+ this.out.push(
433
+ `${this.color(stroke)} ${fmt(state.strokeWidth * matrixScale(state.matrix))} w ${path} s`
434
+ );
435
+ }
436
+ }
437
+
438
+ text(node: SvgNode, state: PaintState) {
439
+ const content = node.text.replace(/\s+/g, " ").trim();
440
+ const color = this.resolveColor(state.fill);
441
+ if (!(content && color)) {
442
+ return;
443
+ }
444
+ const scale = matrixScale(state.matrix);
445
+ const [x, y] = applyMatrix(
446
+ state.matrix,
447
+ length(node.attrs.x, state.viewport[0]),
448
+ length(node.attrs.y, state.viewport[1])
449
+ );
450
+ const bold =
451
+ state.fontWeight === "bold" ||
452
+ Number.parseInt(state.fontWeight, 10) >= 600;
453
+ const font = bold ? "/QRDX-Bold" : "/QRDX-Regular";
454
+ const fontSize = fmt(state.fontSize * scale);
455
+ const maxWidth = Number.parseFloat(node.attrs["data-max-width"] ?? "");
456
+ const fit =
457
+ maxWidth > 0
458
+ ? ` dup stringwidth pop dup ${fmt(maxWidth * scale)} gt {${fmt(maxWidth * scale)} exch div ${fontSize} mul ${font} findfont exch scalefont setfont} {pop} ifelse`
459
+ : "";
460
+ const align =
461
+ state.textAnchor === "middle"
462
+ ? " dup stringwidth pop 2 div neg 0 rmoveto"
463
+ : state.textAnchor === "end"
464
+ ? " dup stringwidth pop neg 0 rmoveto"
465
+ : "";
466
+ // Rotated text (letters set on a curve): turn the baseline with the
467
+ // matrix. The matrix already flips y, so its x axis gives the PS angle.
468
+ const angle =
469
+ (Math.atan2(state.matrix[1], state.matrix[0]) * 180) / Math.PI;
470
+ if (Math.abs(angle) > 0.01) {
471
+ this.out.push(
472
+ `gsave ${this.color(color)} ${font} findfont ${fontSize} scalefont setfont ${fmt(x)} ${fmt(y)} translate ${fmt(angle)} rotate ${psString(content)}${fit} 0 0 moveto${align} show grestore`
473
+ );
474
+ return;
475
+ }
476
+ this.out.push(
477
+ `gsave ${this.color(color)} ${font} findfont ${fontSize} scalefont setfont ${psString(content)}${fit} ${fmt(x)} ${fmt(y)} moveto${align} show grestore`
478
+ );
479
+ }
480
+
481
+ image(node: SvgNode, state: PaintState) {
482
+ const href = node.attrs.href ?? node.attrs["xlink:href"];
483
+ const image = href ? this.images.get(href) : undefined;
484
+ if (!image) {
485
+ return;
486
+ }
487
+ const x = length(node.attrs.x, state.viewport[0]);
488
+ const y = length(node.attrs.y, state.viewport[1]);
489
+ const width = length(node.attrs.width, state.viewport[0]);
490
+ const height = length(node.attrs.height, state.viewport[1]);
491
+ if (width <= 0 || height <= 0) {
492
+ return;
493
+ }
494
+ const [x0, y0] = applyMatrix(state.matrix, x, y);
495
+ const [x1, y1] = applyMatrix(state.matrix, x + width, y + height);
496
+ const { components } = image;
497
+ const colorSpace =
498
+ components === 1
499
+ ? "/DeviceGray"
500
+ : components === 4
501
+ ? "/DeviceCMYK"
502
+ : "/DeviceRGB";
503
+ const decode = Array.from({ length: components }, () => "0 1").join(" ");
504
+ let filters = "/ASCII85Decode filter";
505
+ if (image.kind === "jpeg") {
506
+ filters += " /DCTDecode filter";
507
+ if (image.progressive) {
508
+ this.usesLevel3 = true;
509
+ }
510
+ } else if (image.compressed) {
511
+ filters += " /FlateDecode filter";
512
+ this.usesLevel3 = true;
513
+ }
514
+ this.out.push(
515
+ [
516
+ "gsave",
517
+ `${fmt(Math.min(x0, x1))} ${fmt(Math.min(y0, y1))} translate ${fmt(Math.abs(x1 - x0))} ${fmt(Math.abs(y1 - y0))} scale`,
518
+ `${colorSpace} setcolorspace`,
519
+ `<< /ImageType 1 /Width ${image.width} /Height ${image.height} /BitsPerComponent 8 /Decode [${decode}] /ImageMatrix [${image.width} 0 0 -${image.height} 0 ${image.height}] /DataSource currentfile ${filters} >> image`,
520
+ ascii85(image.bytes),
521
+ "grestore",
522
+ ].join("\n")
523
+ );
524
+ }
525
+ }
526
+
527
+ /**
528
+ * Converts SVG markup (as this library renders it) to an Encapsulated
529
+ * PostScript file: vector paths for modules, eyes and frames, Helvetica for
530
+ * frame text (Latin-1 only), no transparency (see-through colors are mixed
531
+ * with `background`, the background itself with white paper). Linear and radial gradient
532
+ * fills become smooth shadings clipped to each shape (`shfill`, which makes
533
+ * the file LanguageLevel 3); gradient strokes and text use their first color.
534
+ * PNG and JPEG logos are embedded; other logo formats are redrawn as PNG in
535
+ * the browser and left out elsewhere.
536
+ */
537
+ export async function svgToEPS(
538
+ svg: string,
539
+ options: SVGToEPSOptions = {}
540
+ ): Promise<string> {
541
+ const root = parseSvgMarkup(svg);
542
+ if (!root) {
543
+ throw new Error("Could not read the SVG to convert to EPS");
544
+ }
545
+ const rootWidth = length(root.attrs.width, 0, 0) || 512;
546
+ const rootHeight = length(root.attrs.height, 0, 0) || rootWidth;
547
+ const width = options.width ?? rootWidth;
548
+ if (!(Number.isFinite(width) && width > 0)) {
549
+ throw new Error("EPS width must be a positive number of points");
550
+ }
551
+ const scale = width / rootWidth;
552
+ const height = rootHeight * scale;
553
+ const bleed = Math.max(0, options.bleed ?? 0);
554
+ const pageWidth = width + 2 * bleed;
555
+ const pageHeight = height + 2 * bleed;
556
+ const cmyk = options.colorMode === "cmyk";
557
+
558
+ const images = new Map<string, EpsImage>();
559
+ for (const href of collectImageHrefs(root, new Set())) {
560
+ const image = await prepareImage(href, cmyk);
561
+ if (image) {
562
+ images.set(href, image);
563
+ }
564
+ }
565
+
566
+ const painter = new EpsPainter(
567
+ cmyk,
568
+ collectGradientColors(root, new Map()),
569
+ collectGradients(root),
570
+ images
571
+ );
572
+ setBackdrop(painter, { value: "", bgColor: options.background ?? "#ffffff" });
573
+
574
+ // SVG's y axis points down, PostScript's up.
575
+ const matrix: Matrix = multiply(
576
+ [1, 0, 0, -1, bleed, pageHeight - bleed],
577
+ [scale, 0, 0, scale, 0, 0]
578
+ );
579
+ const state: PaintState = {
580
+ matrix,
581
+ viewport: [rootWidth, rootHeight],
582
+ fill: "#000000",
583
+ fillRule: "nonzero",
584
+ stroke: "none",
585
+ strokeWidth: 1,
586
+ fontSize: 16,
587
+ fontWeight: "normal",
588
+ textAnchor: "start",
589
+ };
590
+
591
+ // Extend the edge color into the bleed so trimming leaves no white sliver;
592
+ // a gradient background continues into it.
593
+ const bleedFill = bleed > 0 ? (options.bleedColor ?? undefined) : undefined;
594
+ if (
595
+ !(
596
+ bleedFill &&
597
+ painter.paintBleed(root, state, bleedFill, [0, 0, pageWidth, pageHeight])
598
+ )
599
+ ) {
600
+ const bleedColor = bleedFill ? painter.resolveColor(bleedFill) : null;
601
+ if (bleedColor) {
602
+ painter.rect(bleedColor, 0, 0, pageWidth, pageHeight);
603
+ }
604
+ }
605
+
606
+ painter.walk(root, state, true);
607
+
608
+ const title = (options.title ?? "QR code").replace(/[^\x20-\x7e]/g, "?");
609
+ return [
610
+ "%!PS-Adobe-3.0 EPSF-3.0",
611
+ `%%BoundingBox: 0 0 ${Math.ceil(pageWidth)} ${Math.ceil(pageHeight)}`,
612
+ `%%HiResBoundingBox: 0 0 ${fmt(pageWidth)} ${fmt(pageHeight)}`,
613
+ `%%Title: ${psString(title)}`,
614
+ "%%Creator: qrdx",
615
+ `%%LanguageLevel: ${painter.usesLevel3 ? 3 : 2}`,
616
+ "%%DocumentData: Clean7Bit",
617
+ "%%EndComments",
618
+ "%%BeginProlog",
619
+ PROLOG,
620
+ "%%EndProlog",
621
+ "qrdxdict begin",
622
+ ...Array.from(
623
+ painter.shadingNames,
624
+ ([dictionary, name]) => `/${name} ${dictionary} def`
625
+ ),
626
+ "gsave",
627
+ ...painter.out,
628
+ "grestore",
629
+ "end",
630
+ "showpage",
631
+ "%%Trailer",
632
+ "%%EOF",
633
+ "",
634
+ ].join("\n");
635
+ }
636
+
637
+ /** Why EPS refuses a design with an image fill (see `hasImageFill`). */
638
+ export const EPS_IMAGE_FILL_REASON =
639
+ "EPS can't carry image fills: PostScript has no transparency and would repeat the picture for every dot. Download PDF, SVG or PNG instead.";
640
+
641
+ /** True when a color in the props is an image fill. */
642
+ export function hasImageFill(props: QRProps): boolean {
643
+ const paints = [
644
+ props.bgColor,
645
+ props.fgColor,
646
+ props.eyeColor,
647
+ props.dotColor,
648
+ ...Object.values(props.eyeColors ?? {}).flatMap((eye) => [
649
+ eye?.outer,
650
+ eye?.inner,
651
+ ]),
652
+ ];
653
+ return paints.some(
654
+ (paint) => typeof paint === "object" && paint?.type === "image"
655
+ );
656
+ }
657
+
658
+ /**
659
+ * Renders a vector EPS for print and design tools (Illustrator, InDesign,
660
+ * CorelDRAW): the QR code is `sizeMm` wide (default 50 mm), plus any frame
661
+ * and bleed. See `svgToEPS` for what is converted and what is left out.
662
+ * Throws `EPS_IMAGE_FILL_REASON` for a design with an image fill.
663
+ */
664
+ export async function getQRAsEPS(
665
+ props: QRProps,
666
+ options: EPSOptions = {}
667
+ ): Promise<string> {
668
+ if (hasImageFill(props)) {
669
+ throw new Error(EPS_IMAGE_FILL_REASON);
670
+ }
671
+ const layout = getPrintLayout(props, {
672
+ size: options.sizeMm ?? DEFAULT_EPS_SIZE_MM,
673
+ unit: "mm",
674
+ bleed: options.bleedMm,
675
+ });
676
+ const markup = await renderPrintSVG(props);
677
+ return await svgToEPS(markup, {
678
+ width: layout.trimWidth * POINTS_PER_MM,
679
+ bleed: layout.bleed * POINTS_PER_MM,
680
+ bleedColor:
681
+ layout.bleed > 0
682
+ ? getPrintBleedFill(props, markup)
683
+ : getPrintBleedColor(props),
684
+ colorMode: options.colorMode,
685
+ background: getSolidColor(props.bgColor, DEFAULT_BGCOLOR),
686
+ });
687
+ }
688
+
689
+ /** EPS text as a `data:application/postscript` URL (EPS output is 7-bit ASCII). */
690
+ export function epsToDataUrl(eps: string): string {
691
+ return `data:application/postscript;base64,${btoa(eps)}`;
692
+ }
693
+
694
+ /** Downloads `getQRAsEPS` output (browser only). */
695
+ export async function downloadPrintEPS(
696
+ props: QRProps,
697
+ options: EPSOptions & { filename?: string } = {}
698
+ ): Promise<void> {
699
+ const eps = await getQRAsEPS(props, options);
700
+ downloadFile(epsToDataUrl(eps), options.filename ?? "qr-code-print.eps");
701
+ }