@btps/sdk 1.2.0-rc.3 → 1.2.0-rc.3.2

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.
@@ -5,58 +5,17 @@
5
5
  * https://www.apache.org/licenses/LICENSE-2.0
6
6
  */
7
7
 
8
- import { CURRENCY_DECIMALS } from "../constants/currency.js";
9
8
  import {
10
9
  BtpBoundViewSchema
11
10
  } from "./boundViewSchema.js";
12
- import { boundValue } from "./boundViewBindings.js";
13
- const MONTHS = [
14
- "January",
15
- "February",
16
- "March",
17
- "April",
18
- "May",
19
- "June",
20
- "July",
21
- "August",
22
- "September",
23
- "October",
24
- "November",
25
- "December"
26
- ], grouped = (digits, separator) => digits.replace(/\B(?=(\d{3})+(?!\d))/g, separator), writeDate = (iso, pattern) => {
27
- const date = new Date(iso), d = String(date.getUTCDate()), dd = d.padStart(2, "0"), MM = String(date.getUTCMonth() + 1).padStart(2, "0"), month = MONTHS[date.getUTCMonth()] ?? "", yyyy = String(date.getUTCFullYear());
28
- return {
29
- "d MMM yyyy": `${d} ${month.slice(0, 3)} ${yyyy}`,
30
- "d MMMM yyyy": `${d} ${month} ${yyyy}`,
31
- "MMM d, yyyy": `${month.slice(0, 3)} ${d}, ${yyyy}`,
32
- "MMMM d, yyyy": `${month} ${d}, ${yyyy}`,
33
- "dd/MM/yyyy": `${dd}/${MM}/${yyyy}`,
34
- "MM/dd/yyyy": `${MM}/${dd}/${yyyy}`,
35
- "dd.MM.yyyy": `${dd}.${MM}.${yyyy}`,
36
- "dd-MM-yyyy": `${dd}-${MM}-${yyyy}`,
37
- "yyyy-MM-dd": `${yyyy}-${MM}-${dd}`
38
- }[pattern] ?? "";
39
- }, writtenValue = (value, bind) => {
40
- const format = bind.format;
41
- if (value.kind === "money" && format && "money" in format) {
42
- const { group, decimal, prefix = "", suffix = "" } = format.money, places = CURRENCY_DECIMALS[value.currency] ?? 2, digits = String(Math.abs(value.amount)).padStart(places + 1, "0"), whole = grouped(digits.slice(0, digits.length - places), group), number = places > 0 ? `${whole}${decimal}${digits.slice(-places)}` : whole;
43
- return `${value.amount < 0 ? "-" : ""}${prefix}${number}${suffix}`;
44
- }
45
- if (value.kind === "date" && format && "date" in format) return writeDate(value.date, format.date);
46
- if (value.kind === "percent" && format && "percent" in format) {
47
- const { decimals, decimal } = format.percent;
48
- return `${(value.basisPoints / 100).toFixed(decimals).replace(".", decimal)}%`;
49
- }
50
- if (value.kind !== "text") return "";
51
- if (format && "groups" in format) {
52
- const characters2 = [...value.text.replace(/ /g, "")], parts = [];
53
- let at = 0;
54
- for (const size of format.groups.sizes)
55
- parts.push(characters2.slice(at, at + size).join("")), at += size;
56
- return parts.join(format.groups.separator);
11
+ import { unzlibSync } from "fflate";
12
+ import { boundValue, markdownHidden, writtenValue } from "./boundViewBindings.js";
13
+ const pixelsOf = (data) => {
14
+ try {
15
+ return unzlibSync(Uint8Array.from(atob(data), (c) => c.charCodeAt(0)));
16
+ } catch {
17
+ return;
57
18
  }
58
- const characters = [...value.text];
59
- return bind.range ? characters.slice(bind.range[0], bind.range[1]).join("") : value.text;
60
19
  }, transformed = (text, transform) => [...text].map((char) => {
61
20
  if (transform === void 0) return char;
62
21
  const changed = transform === "uppercase" ? char.toUpperCase() : char.toLowerCase();
@@ -71,7 +30,7 @@ const MONTHS = [
71
30
  width += (glyph.advance + kerning) * scale + letterSpacing;
72
31
  }
73
32
  return width;
74
- }, overlaps = (a, b) => a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom, textBox = (element, view) => {
33
+ }, OVERLAP_TOLERANCE = 5e-3, overlaps = (a, b) => a.left < b.right - OVERLAP_TOLERANCE && b.left < a.right - OVERLAP_TOLERANCE && a.top < b.bottom - OVERLAP_TOLERANCE && b.top < a.bottom - OVERLAP_TOLERANCE, textBox = (element, view) => {
75
34
  const font = view.fonts?.[element.font], scale = font ? element.size / font.unitsPerEm : 0;
76
35
  return {
77
36
  left: element.x,
@@ -201,7 +160,7 @@ const MONTHS = [
201
160
  return (light + 0.05) / (dark + 0.05);
202
161
  }, samples = (start, end) => {
203
162
  const points = [];
204
- for (let at = start + 0.5; at <= end; at++) points.push(at);
163
+ for (let at = start + 0.5; at < end; at++) points.push(at);
205
164
  return points.length > 0 ? points : [(start + end) / 2];
206
165
  }, keyFacts = (document) => {
207
166
  const type = document.type, lines = () => {
@@ -211,25 +170,12 @@ const MONTHS = [
211
170
  return items.rows.flatMap(
212
171
  (row, index) => columns.filter((column) => row[column] !== void 0).map((column) => `lineItems.rows.${index}.${column}`)
213
172
  );
214
- }, listAmounts = (key) => Array.isArray(document[key]) ? document[key].map((_, index) => `${key}.${index}.amount`) : [], discount = document.discount, bill = [
215
- "id",
216
- "issuedAt",
217
- "totalAmount",
218
- "subtotalAmount",
219
- "taxAmount",
220
- ...discount === void 0 ? [] : [discount.amount !== void 0 ? "discount.amount" : "discount.percent"],
221
- "issuer.name",
222
- "recipient.name",
223
- "description",
224
- ...lines()
225
- ], letter = ["issuedAt", "issuer.name", "recipient.name", "body.content", "signatory.name", "signatory.title"];
173
+ }, entries = (key) => Array.isArray(document[key]) ? document[key].flatMap((_, index) => [`${key}.${index}.description`, `${key}.${index}.amount`]) : [], bill = ["id", "totalAmount", "taxAmount", "description", ...lines()], letter = ["issuedAt", "body.content", "signatory.name", "signatory.title"];
226
174
  return ({
227
175
  invoice: [...bill, "dueAt"],
228
176
  receipt: [...bill, "payment.amount", "payment.paidAt"],
229
177
  payslip: [
230
178
  "id",
231
- "issuedAt",
232
- "issuer.name",
233
179
  "employee.name",
234
180
  "payPeriod.start",
235
181
  "payPeriod.end",
@@ -237,30 +183,41 @@ const MONTHS = [
237
183
  "gross",
238
184
  "taxWithheld",
239
185
  "net",
240
- ...listAmounts("earnings"),
241
- ...listAmounts("deductions"),
242
- ...listAmounts("contributions")
186
+ ...entries("earnings"),
187
+ ...entries("deductions"),
188
+ ...entries("contributions")
243
189
  ],
244
190
  letter,
245
191
  agreement: [...letter, "acceptance.by"]
246
192
  }[typeof type == "string" ? type : ""] ?? []).filter(
247
193
  (field) => boundValue(document, field) !== void 0
248
194
  );
249
- }, requiredCharacters = (text, markdown) => [...text].map((char) => !/\s/u.test(char) && !(markdown && /[#*_`>-]/.test(char))), isMarkdown = (document, field) => {
195
+ }, requiredCharacters = (text, markdown) => {
196
+ const hidden = markdown ? markdownHidden(text) : [];
197
+ return [...text].map((char, at) => !/\s/u.test(char) && !hidden[at]);
198
+ }, isMarkdown = (document, field) => {
250
199
  const value = field === "body.content" ? document.body : field === "description" ? document.description : void 0;
251
200
  return typeof value == "object" && value !== null && value.format === "markdown";
252
201
  }, checkBoundView = (document, view) => {
253
202
  const problems = [], texts = view.elements.map((element, index) => ({ element, index })).filter((entry) => entry.element.type === "text");
254
203
  for (const field of keyFacts(document)) {
255
- const binds = texts.filter(({ element }) => element.bind.field === field).map(({ element }) => element.bind), value = boundValue(document, field);
256
- if (binds.length === 0)
204
+ const value = boundValue(document, field);
205
+ if (value === void 0) continue;
206
+ const markdown = isMarkdown(document, field), ways = new Map();
207
+ for (const { element } of texts) {
208
+ const other = boundValue(document, element.bind.field);
209
+ if (other === void 0 || other.kind !== value.kind) continue;
210
+ const format = { format: element.bind.format }, written = writtenValue(value, { ...format, field });
211
+ if (written === "" || writtenValue(other, { ...format, field: element.bind.field }) !== written || element.bind.field !== field && isMarkdown(document, element.bind.field) !== markdown) continue;
212
+ const key = JSON.stringify(element.bind.format ?? null), way = ways.get(key) ?? { written: [...written], shown: [...written].map(() => !1) }, [from, to] = element.bind.range ?? [0, way.written.length];
213
+ for (let at = from; at < Math.min(to, way.written.length); at++) way.shown[at] = !0;
214
+ ways.set(key, way);
215
+ }
216
+ if (ways.size === 0) {
257
217
  problems.push({ check: "keyFacts", field, message: `${field} is a key fact and is not shown` });
258
- else if (value?.kind === "text" && !binds.some((bind) => bind.range === void 0)) {
259
- const shown = [...value.text].map(() => !1);
260
- for (const { range } of binds)
261
- for (let at = range?.[0] ?? 0; at < (range?.[1] ?? 0); at++) shown[at] = !0;
262
- requiredCharacters(value.text, isMarkdown(document, field)).some((needed, at) => needed && !shown[at]) && problems.push({ check: "keyFacts", field, message: `every word of ${field} is shown` });
218
+ continue;
263
219
  }
220
+ [...ways.values()].some(({ written, shown }) => requiredCharacters(written.join(""), markdown).every((needed, at) => !needed || shown[at])) || problems.push({ check: "keyFacts", field, message: `every word of ${field} is shown` });
264
221
  }
265
222
  (document.signatory ?? {}).visualSignature !== void 0 && !view.elements.some(({ type }) => type === "signature") && problems.push({ check: "keyFacts", field: "signatory.visualSignature", message: "the signature is shown" });
266
223
  for (const { element, index } of texts) {
@@ -299,13 +256,20 @@ const MONTHS = [
299
256
  }
300
257
  }, boxes = view.elements.map(boxOf), edges = view.elements.map((element) => element.type === "path" ? edgesOf(polygons(element.d)) : []), page = parse(view.page.background ?? "#ffffff"), pageColour = over([255, 255, 255], page);
301
258
  let work = 0;
259
+ const decoded = new Map();
302
260
  return view.elements.forEach((element, index) => {
303
261
  if (element.type !== "text" && element.type !== "signature") return;
304
- const box = boxes[index], hidden = (message) => problems.push({ check: "notHidden", element: index, message });
305
- (box.left < 0 || box.top < 0 || box.right > view.page.width || box.bottom > view.page.height) && hidden("it lies outside the page"), boxes.slice(index + 1).some((later) => overlaps(box, later)) && hidden("an element drawn after it covers it"), view.elements.slice(0, index).some((earlier, at) => earlier.type === "image" && overlaps(box, boxes[at])) && hidden("an image lies under it");
262
+ const box = boxes[index], hidden = (message) => problems.push({ check: "notHidden", element: index, message }), t = OVERLAP_TOLERANCE;
263
+ (box.left < -t || box.top < -t || box.right > view.page.width + t || box.bottom > view.page.height + t) && hidden("it lies outside the page"), boxes.slice(index + 1).some((later) => overlaps(box, later)) && hidden("an element drawn after it covers it");
306
264
  const ink = over(pageColour, parse(element.colour)), beneath = view.elements.slice(0, index).map((earlier, at) => ({ earlier, at })).filter(
307
- ({ earlier, at }) => (earlier.type === "rect" || earlier.type === "path") && earlier.fill !== void 0 && overlaps(box, boxes[at])
308
- ), xs = samples(box.left, box.right);
265
+ ({ earlier, at }) => ((earlier.type === "rect" || earlier.type === "path") && earlier.fill !== void 0 || earlier.type === "image") && overlaps(box, boxes[at])
266
+ );
267
+ for (const { earlier } of beneath)
268
+ if (earlier.type === "image" && !decoded.has(earlier.image)) {
269
+ const image = view.images?.[earlier.image];
270
+ work += image ? image.width * image.height : 0, decoded.set(earlier.image, image ? pixelsOf(image.data) : void 0);
271
+ }
272
+ const xs = samples(box.left, box.right);
309
273
  let readable = !0;
310
274
  for (const y of samples(box.top, box.bottom)) {
311
275
  if (work += xs.length * beneath.length, work > CONTRAST_WORK_LIMIT) break;
@@ -317,6 +281,13 @@ const MONTHS = [
317
281
  for (const x of xs) {
318
282
  let colour = pageColour;
319
283
  if (beneath.forEach(({ earlier }, n) => {
284
+ if (earlier.type === "image") {
285
+ const image = view.images?.[earlier.image], pixels = decoded.get(earlier.image);
286
+ if (!image || !pixels || !rectCovers(earlier, [x, y])) return;
287
+ const px = Math.min(image.width - 1, Math.max(0, Math.floor((x - earlier.x) / earlier.width * image.width))), i = (Math.min(image.height - 1, Math.max(0, Math.floor((y - earlier.y) / earlier.height * image.height))) * image.width + px) * 4;
288
+ colour = over(colour, [pixels[i] ?? 0, pixels[i + 1] ?? 0, pixels[i + 2] ?? 0, (pixels[i + 3] ?? 0) / 255 * (earlier.opacity ?? 1)]);
289
+ return;
290
+ }
320
291
  if (earlier.type !== "rect" && earlier.type !== "path" || earlier.fill === void 0) return;
321
292
  const row = rows[n];
322
293
  if (!(earlier.type === "rect" ? rectCovers(earlier, [x, y]) : row !== void 0 && rowCovers(row, earlier.fillRule ?? "nonzero", x))) return;
@@ -340,5 +311,6 @@ export {
340
311
  CONTRAST_WORK_LIMIT,
341
312
  boundViewResultOf,
342
313
  checkBoundView,
314
+ keyFacts,
343
315
  writtenValue
344
316
  };
@@ -587,6 +587,7 @@ export declare const BtpBoundViewSchema: z.ZodEffects<z.ZodEffects<z.ZodObject<{
587
587
  opacity?: number | undefined;
588
588
  fillRule?: "nonzero" | "evenodd" | undefined;
589
589
  }>, z.ZodObject<{
590
+ radius: z.ZodOptional<z.ZodUnion<[z.ZodEffects<z.ZodNumber, number, number>, z.ZodTuple<[z.ZodEffects<z.ZodNumber, number, number>, z.ZodEffects<z.ZodNumber, number, number>, z.ZodEffects<z.ZodNumber, number, number>, z.ZodEffects<z.ZodNumber, number, number>], null>]>>;
590
591
  opacity: z.ZodOptional<z.ZodNumber>;
591
592
  x: z.ZodEffects<z.ZodNumber, number, number>;
592
593
  y: z.ZodEffects<z.ZodNumber, number, number>;
@@ -601,6 +602,7 @@ export declare const BtpBoundViewSchema: z.ZodEffects<z.ZodEffects<z.ZodObject<{
601
602
  width: number;
602
603
  height: number;
603
604
  image: string;
605
+ radius?: number | [number, number, number, number] | undefined;
604
606
  opacity?: number | undefined;
605
607
  }, {
606
608
  type: "image";
@@ -609,6 +611,7 @@ export declare const BtpBoundViewSchema: z.ZodEffects<z.ZodEffects<z.ZodObject<{
609
611
  width: number;
610
612
  height: number;
611
613
  image: string;
614
+ radius?: number | [number, number, number, number] | undefined;
612
615
  opacity?: number | undefined;
613
616
  }>, z.ZodObject<{
614
617
  x: z.ZodEffects<z.ZodNumber, number, number>;
@@ -621,7 +624,7 @@ export declare const BtpBoundViewSchema: z.ZodEffects<z.ZodEffects<z.ZodObject<{
621
624
  letterSpacing: z.ZodOptional<z.ZodEffects<z.ZodNumber, number, number>>;
622
625
  transform: z.ZodOptional<z.ZodEnum<["uppercase", "lowercase"]>>;
623
626
  type: z.ZodLiteral<"text">;
624
- bind: z.ZodEffects<z.ZodObject<{
627
+ bind: z.ZodObject<{
625
628
  field: z.ZodString;
626
629
  format: z.ZodOptional<z.ZodUnion<[z.ZodObject<{
627
630
  money: z.ZodEffects<z.ZodObject<{
@@ -760,52 +763,6 @@ export declare const BtpBoundViewSchema: z.ZodEffects<z.ZodEffects<z.ZodObject<{
760
763
  };
761
764
  } | undefined;
762
765
  range?: [number, number] | undefined;
763
- }>, {
764
- field: string;
765
- format?: {
766
- money: {
767
- group: "" | "," | "." | " " | "'";
768
- decimal: "," | ".";
769
- prefix?: string | undefined;
770
- suffix?: string | undefined;
771
- };
772
- } | {
773
- date: "d MMM yyyy" | "d MMMM yyyy" | "MMM d, yyyy" | "MMMM d, yyyy" | "dd/MM/yyyy" | "MM/dd/yyyy" | "dd.MM.yyyy" | "dd-MM-yyyy" | "yyyy-MM-dd";
774
- } | {
775
- percent: {
776
- decimal: "," | ".";
777
- decimals: 0 | 1 | 2;
778
- };
779
- } | {
780
- groups: {
781
- sizes: number[];
782
- separator: string;
783
- };
784
- } | undefined;
785
- range?: [number, number] | undefined;
786
- }, {
787
- field: string;
788
- format?: {
789
- money: {
790
- group: "" | "," | "." | " " | "'";
791
- decimal: "," | ".";
792
- prefix?: string | undefined;
793
- suffix?: string | undefined;
794
- };
795
- } | {
796
- date: "d MMM yyyy" | "d MMMM yyyy" | "MMM d, yyyy" | "MMMM d, yyyy" | "dd/MM/yyyy" | "MM/dd/yyyy" | "dd.MM.yyyy" | "dd-MM-yyyy" | "yyyy-MM-dd";
797
- } | {
798
- percent: {
799
- decimal: "," | ".";
800
- decimals: 0 | 1 | 2;
801
- };
802
- } | {
803
- groups: {
804
- separator: string;
805
- sizes?: unknown;
806
- };
807
- } | undefined;
808
- range?: [number, number] | undefined;
809
766
  }>;
810
767
  }, "strict", z.ZodTypeAny, {
811
768
  type: "text";
@@ -1028,6 +985,7 @@ export declare const BtpBoundViewSchema: z.ZodEffects<z.ZodEffects<z.ZodObject<{
1028
985
  width: number;
1029
986
  height: number;
1030
987
  image: string;
988
+ radius?: number | [number, number, number, number] | undefined;
1031
989
  opacity?: number | undefined;
1032
990
  } | {
1033
991
  type: "text";
@@ -1186,6 +1144,7 @@ export declare const BtpBoundViewSchema: z.ZodEffects<z.ZodEffects<z.ZodObject<{
1186
1144
  width: number;
1187
1145
  height: number;
1188
1146
  image: string;
1147
+ radius?: number | [number, number, number, number] | undefined;
1189
1148
  opacity?: number | undefined;
1190
1149
  } | {
1191
1150
  type: "text";
@@ -1372,6 +1331,7 @@ export declare const BtpBoundViewSchema: z.ZodEffects<z.ZodEffects<z.ZodObject<{
1372
1331
  width: number;
1373
1332
  height: number;
1374
1333
  image: string;
1334
+ radius?: number | [number, number, number, number] | undefined;
1375
1335
  opacity?: number | undefined;
1376
1336
  } | {
1377
1337
  type: "text";
@@ -1558,6 +1518,7 @@ export declare const BtpBoundViewSchema: z.ZodEffects<z.ZodEffects<z.ZodObject<{
1558
1518
  width: number;
1559
1519
  height: number;
1560
1520
  image: string;
1521
+ radius?: number | [number, number, number, number] | undefined;
1561
1522
  opacity?: number | undefined;
1562
1523
  } | {
1563
1524
  type: "text";
@@ -64,10 +64,7 @@ const limits = BTPS_FIELD_LIMITS.boundView, hasTwoDecimals = (value) => Math.abs
64
64
  field: z.string().min(1).max(BTPS_FIELD_LIMITS.documentId * 4),
65
65
  format: format.optional(),
66
66
  range: z.tuple([z.number().int().min(0), z.number().int().min(0)]).refine(([start, end]) => start < end, "a range starts before it ends").optional()
67
- }).strict().refine((bind) => bind.range === void 0 || bind.format === void 0, {
68
- message: "a range is for text written as it is",
69
- path: ["range"]
70
- }), textBox = {
67
+ }).strict(), textBox = {
71
68
  x: position,
72
69
  y: position,
73
70
  width: size,
@@ -101,7 +98,14 @@ const limits = BTPS_FIELD_LIMITS.boundView, hasTwoDecimals = (value) => Math.abs
101
98
  ...fill,
102
99
  ...stroke
103
100
  }).strict(),
104
- z.object({ type: z.literal("image"), image: z.string().min(1), ...box, opacity: opacity.optional() }).strict(),
101
+ z.object({
102
+ type: z.literal("image"),
103
+ image: z.string().min(1),
104
+ ...box,
105
+
106
+ radius: z.union([size, z.tuple([size, size, size, size])]).optional(),
107
+ opacity: opacity.optional()
108
+ }).strict(),
105
109
  z.object({ type: z.literal("text"), bind: binding, ...textBox }).strict(),
106
110
  z.object({
107
111
  type: z.literal("label"),
@@ -127,7 +131,12 @@ const limits = BTPS_FIELD_LIMITS.boundView, hasTwoDecimals = (value) => Math.abs
127
131
  }).strict().refine((value) => value.glyphs !== void 0 || value.fallback !== void 0, {
128
132
  message: "a font has glyphs, a fallback, or both"
129
133
  }), base64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/, inflatesTo = (data, length) => {
130
- const bytes = Buffer.from(data, "base64");
134
+ let bytes;
135
+ try {
136
+ bytes = Uint8Array.from(atob(data), (char) => char.charCodeAt(0));
137
+ } catch {
138
+ return !1;
139
+ }
131
140
  let total = 0;
132
141
  const stream = new Unzlib((chunk) => {
133
142
  total += chunk.length;