@gerege-systems/eid-mongolia-sdk 0.24.0 → 0.26.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/dist/pades.cjs CHANGED
@@ -24,7 +24,7 @@ __export(pades_exports, {
24
24
  PADES_ERROR_CODES: () => PADES_ERROR_CODES,
25
25
  PROFILE_VERSION: () => PROFILE_VERSION,
26
26
  PadesError: () => PadesError,
27
- complete: () => complete,
27
+ complete: () => complete2,
28
28
  prepare: () => prepare,
29
29
  profileVersion: () => profileVersion
30
30
  });
@@ -1404,6 +1404,58 @@ function zlibInflate(src, limit = 64 << 20, initial) {
1404
1404
  return inflateRaw(src.subarray(2), limit, void 0, initial);
1405
1405
  }
1406
1406
  function inflateRaw(src, limit = 64 << 20, info, initial) {
1407
+ return inflate(src, limit, info, initial, false);
1408
+ }
1409
+ function zlibInflateStrict(src, limit) {
1410
+ if (src.length < 2) throw new InflateError("zlib: header \u0430\u043B\u0433\u0430");
1411
+ const cmf = src[0];
1412
+ const flg = src[1];
1413
+ if ((cmf & 15) !== 8 || cmf >> 4 > 7 || (cmf << 8 | flg) % 31 !== 0) throw new InflateError("zlib: header \u0431\u0443\u0440\u0443\u0443");
1414
+ let start = 2;
1415
+ if (flg & 32) {
1416
+ if (src.length < 6) throw new InflateError("zlib: DICTID \u0434\u0443\u0442\u0443\u0443");
1417
+ if (src[2] !== 0 || src[3] !== 0 || src[4] !== 0 || src[5] !== 1) throw new InflateError("zlib: preset dictionary");
1418
+ start = 6;
1419
+ }
1420
+ const info = { end: 0, truncated: false };
1421
+ const out = inflate(src.subarray(start), limit, info, void 0, true);
1422
+ if (info.truncated) throw new InflateError("inflate: \u04E9\u0433\u04E9\u0433\u0434\u04E9\u043B \u0434\u0443\u0442\u0443\u0443");
1423
+ const at = start + info.end;
1424
+ if (at + 4 > src.length) throw new InflateError("zlib: adler32 \u0430\u043B\u0433\u0430");
1425
+ const want = (src[at] << 24 | src[at + 1] << 16 | src[at + 2] << 8 | src[at + 3]) >>> 0;
1426
+ if (adler32(out) !== want) throw new InflateError("zlib: adler32 \u0442\u0430\u0430\u0440\u0430\u0445\u0433\u04AF\u0439");
1427
+ return out;
1428
+ }
1429
+ function adler32(b) {
1430
+ let a = 1;
1431
+ let s = 0;
1432
+ for (let i = 0; i < b.length; ) {
1433
+ const n = Math.min(5552, b.length - i);
1434
+ for (let j = 0; j < n; j++, i++) {
1435
+ a += b[i];
1436
+ s += a;
1437
+ }
1438
+ a %= 65521;
1439
+ s %= 65521;
1440
+ }
1441
+ return (s << 16 | a) >>> 0;
1442
+ }
1443
+ function complete(lengths, n) {
1444
+ let max = 0;
1445
+ let sum = 0;
1446
+ let count = 0;
1447
+ for (let i = 0; i < n; i++) if (lengths[i] > max) max = lengths[i];
1448
+ if (max === 0) return true;
1449
+ for (let i = 0; i < n; i++) {
1450
+ const l = lengths[i];
1451
+ if (l) {
1452
+ sum += 2 ** (max - l);
1453
+ count++;
1454
+ }
1455
+ }
1456
+ return sum === 2 ** max || sum === 1 && max === 1 && count === 1;
1457
+ }
1458
+ function inflate(src, limit, info, initial, strict) {
1407
1459
  let pos = 0;
1408
1460
  let bitBuf = 0;
1409
1461
  let bitCnt = 0;
@@ -1478,8 +1530,10 @@ function inflateRaw(src, limit = 64 << 20, info, initial) {
1478
1530
  const hlit = bits(5) + 257;
1479
1531
  const hdist = bits(5) + 1;
1480
1532
  const hclen = bits(4) + 4;
1533
+ if (strict && (hlit > 286 || hdist > 30)) throw new InflateError("inflate: HLIT/HDIST");
1481
1534
  const cl = new Uint8Array(19);
1482
1535
  for (let i = 0; i < hclen; i++) cl[CL_ORDER[i]] = bits(3);
1536
+ if (strict && !complete(cl, 19)) throw new InflateError("inflate: \u043A\u043E\u0434 \u0431\u04AF\u0440\u044D\u043D \u0431\u0438\u0448");
1483
1537
  const clh = build(cl, 19);
1484
1538
  const lens = new Uint8Array(hlit + hdist);
1485
1539
  for (let i = 0; i < hlit + hdist; ) {
@@ -1500,6 +1554,9 @@ function inflateRaw(src, limit = 64 << 20, info, initial) {
1500
1554
  lens.fill(val, i, i + rep);
1501
1555
  i += rep;
1502
1556
  }
1557
+ if (strict && (!complete(lens.subarray(0, hlit), hlit) || !complete(lens.subarray(hlit), hdist))) {
1558
+ throw new InflateError("inflate: \u043A\u043E\u0434 \u0431\u04AF\u0440\u044D\u043D \u0431\u0438\u0448");
1559
+ }
1503
1560
  lit = build(lens.subarray(0, hlit), hlit);
1504
1561
  dist = build(lens.subarray(hlit), hdist);
1505
1562
  }
@@ -3486,14 +3543,15 @@ function nthPage(root, n) {
3486
3543
  };
3487
3544
  return walk(root, 0);
3488
3545
  }
3489
- function pageCount(doc) {
3546
+ var MAX_VERIFY_ANNOTS = 1e4;
3547
+ function defaultStampPage(doc, verifyUri) {
3490
3548
  const inc = new Incremental(doc);
3491
- let n = 0;
3549
+ const pages = [];
3492
3550
  const walk = (v, depth) => {
3493
- if (depth > MAX_DEPTH2 || n > 1 << 16) return;
3551
+ if (depth > MAX_DEPTH2 || pages.length > 1 << 16) return;
3494
3552
  switch (v.key("Type").name()) {
3495
3553
  case "Page":
3496
- n++;
3554
+ pages.push(v);
3497
3555
  break;
3498
3556
  case "Pages": {
3499
3557
  const kids = v.key("Kids");
@@ -3502,7 +3560,31 @@ function pageCount(doc) {
3502
3560
  }
3503
3561
  };
3504
3562
  walk(inc.root().key("Pages"), 0);
3505
- return n;
3563
+ const n = pages.length;
3564
+ for (let i = n - 1; i >= 0; i--) {
3565
+ if (!isVerifyPage(pages[i], verifyUri)) return { page: i + 1, n };
3566
+ }
3567
+ return { page: n, n };
3568
+ }
3569
+ function isVerifyPage(page, verifyUri) {
3570
+ try {
3571
+ const annots = page.key("Annots");
3572
+ if (annots.kind() !== "array") return false;
3573
+ const want = latin1(verifyUri);
3574
+ const m = Math.min(annots.len(), MAX_VERIFY_ANNOTS);
3575
+ for (let i = 0; i < m; i++) {
3576
+ const a = annots.index(i);
3577
+ if (a.kind() !== "dict" || a.key("Subtype").name() !== "Link") continue;
3578
+ const act = a.key("A");
3579
+ if (act.kind() !== "dict" || act.key("S").name() !== "URI") continue;
3580
+ const u = act.key("URI");
3581
+ if (u.kind() !== "string") continue;
3582
+ const got = u.rawString();
3583
+ if (got.length === want.length && got.every((b, j) => b === want[j])) return true;
3584
+ }
3585
+ } catch {
3586
+ }
3587
+ return false;
3506
3588
  }
3507
3589
 
3508
3590
  // src/pades/pdf/dss.ts
@@ -3591,13 +3673,915 @@ stream
3591
3673
  return inc.finish(catID);
3592
3674
  }
3593
3675
 
3676
+ // src/pades/page/occupancy.ts
3677
+ var MAX_BYTES = 4 << 20;
3678
+ var MAX_OPS = 1e5;
3679
+ var MAX_DEPTH3 = 8;
3680
+ var MAX_SAVE = 64;
3681
+ var MAX_OPERANDS = 65536;
3682
+ var MAX_NESTING2 = 32;
3683
+ var MAX_ANNOTS = 1e4;
3684
+ var MAX_W_ENTRIES = 65536;
3685
+ var MAX_W_ASSIGN = 262144;
3686
+ var MAX_NUM_LEN = 32;
3687
+ var CLAMP = 1e7;
3688
+ var MAX_INHERIT = 32;
3689
+ var UnscannableError = class extends Error {
3690
+ };
3691
+ var unscannable = (why) => new UnscannableError(`pades: page content not scannable: ${why}`);
3692
+ var IDENTITY = [1, 0, 0, 1, 0, 0];
3693
+ function mul(m, n) {
3694
+ return [
3695
+ m[0] * n[0] + m[1] * n[2],
3696
+ m[0] * n[1] + m[1] * n[3],
3697
+ m[2] * n[0] + m[3] * n[2],
3698
+ m[2] * n[1] + m[3] * n[3],
3699
+ m[4] * n[0] + m[5] * n[2] + n[4],
3700
+ m[4] * n[1] + m[5] * n[3] + n[5]
3701
+ ];
3702
+ }
3703
+ function apply(m, x, y) {
3704
+ return [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]];
3705
+ }
3706
+ var finite = (m) => m.every((v) => Number.isFinite(v));
3707
+ var pointRect = (x, y) => ({ x0: x, y0: y, x1: x, y1: y });
3708
+ function addPoint(r, x, y) {
3709
+ r.x0 = Math.min(r.x0, x);
3710
+ r.y0 = Math.min(r.y0, y);
3711
+ r.x1 = Math.max(r.x1, x);
3712
+ r.y1 = Math.max(r.y1, y);
3713
+ }
3714
+ function quantise(r) {
3715
+ const c = (v) => {
3716
+ if (Number.isNaN(v)) throw unscannable("NaN");
3717
+ return Math.min(Math.max(v, -CLAMP), CLAMP);
3718
+ };
3719
+ const x0 = c(r.x0);
3720
+ const y0 = c(r.y0);
3721
+ const x1 = c(r.x1);
3722
+ const y1 = c(r.y1);
3723
+ return [Math.floor(x0 * 100) + 0, Math.floor(y0 * 100) + 0, Math.ceil(x1 * 100) + 0, Math.ceil(y1 * 100) + 0];
3724
+ }
3725
+ var newFont = (kind) => ({ kind, first: 0, widths: [], missing: 1e3, dw: 1e3, w: /* @__PURE__ */ new Map() });
3726
+ var DEFAULT_FONT = newFont(3 /* Default */);
3727
+ var toInt = (v) => Math.min(Math.max(Math.trunc(v), -(2 ** 63)), 2 ** 63);
3728
+ function number(v) {
3729
+ const k = v.kind();
3730
+ return k === "int" || k === "real" ? v.float64() : void 0;
3731
+ }
3732
+ function loadFont(v) {
3733
+ switch (v.key("Subtype").name()) {
3734
+ case "Type3":
3735
+ return DEFAULT_FONT;
3736
+ case "Type0": {
3737
+ const enc2 = v.key("Encoding");
3738
+ if (enc2.kind() !== "name" || enc2.name() !== "Identity-H" && enc2.name() !== "Identity-V") return newFont(2 /* Composite */);
3739
+ const f2 = newFont(1 /* Identity */);
3740
+ const d = v.key("DescendantFonts").index(0);
3741
+ const dw = number(d.key("DW"));
3742
+ if (dw !== void 0) f2.dw = dw;
3743
+ const w = d.key("W");
3744
+ const n = Math.min(w.len(), MAX_W_ENTRIES);
3745
+ let budget = MAX_W_ASSIGN;
3746
+ const set2 = (cid, val) => {
3747
+ if (--budget < 0) return false;
3748
+ if (!f2.w.has(cid) && cid >= 0 && cid <= 65535) f2.w.set(cid, val);
3749
+ return true;
3750
+ };
3751
+ read: for (let i = 0; i < n; ) {
3752
+ const c0f = number(w.index(i));
3753
+ if (c0f === void 0 || i + 1 >= n) break;
3754
+ const c0 = toInt(c0f);
3755
+ const arr = w.index(i + 1);
3756
+ if (arr.kind() === "array") {
3757
+ const m2 = Math.min(arr.len(), MAX_W_ENTRIES);
3758
+ for (let j = 0; j < m2; j++) {
3759
+ const x2 = number(arr.index(j));
3760
+ if (x2 !== void 0 && !set2(c0 + j, x2)) break read;
3761
+ }
3762
+ i += 2;
3763
+ continue;
3764
+ }
3765
+ const c1 = number(w.index(i + 1));
3766
+ const x = number(w.index(i + 2));
3767
+ if (c1 === void 0 || x === void 0 || i + 2 >= n) break;
3768
+ const hi = toInt(c1);
3769
+ for (let c = Math.max(c0, 0); c <= hi && c <= 65535; c++) {
3770
+ if (!set2(c, x)) break read;
3771
+ }
3772
+ i += 3;
3773
+ }
3774
+ return f2;
3775
+ }
3776
+ }
3777
+ const f = newFont(0 /* Simple */);
3778
+ const fc = number(v.key("FirstChar"));
3779
+ if (fc !== void 0) f.first = toInt(fc);
3780
+ const ws = v.key("Widths");
3781
+ const m = Math.min(ws.len(), 256);
3782
+ for (let i = 0; i < m; i++) f.widths.push(number(ws.index(i)) ?? NaN);
3783
+ const mw = number(v.key("FontDescriptor").key("MissingWidth"));
3784
+ if (mw !== void 0 && mw > 0) f.missing = mw;
3785
+ return f;
3786
+ }
3787
+ function glyphs(f, b, fn) {
3788
+ if (f.kind === 1 /* Identity */) {
3789
+ for (let i = 0; i + 1 < b.length; i += 2) {
3790
+ const w = f.w.get(b[i] << 8 | b[i + 1]);
3791
+ fn(w ?? f.dw, false);
3792
+ }
3793
+ return;
3794
+ }
3795
+ for (const c of b) {
3796
+ let w = 1e3;
3797
+ if (f.kind === 0 /* Simple */) {
3798
+ w = f.missing;
3799
+ const i = c - f.first;
3800
+ if (i >= 0 && i < f.widths.length && !Number.isNaN(f.widths[i])) w = f.widths[i];
3801
+ }
3802
+ fn(w, f.kind !== 2 /* Composite */ && c === 32);
3803
+ }
3804
+ }
3805
+ var EMPTY = new Uint8Array(0);
3806
+ var opnd = (kind, num = 0, str = EMPTY, name = "") => ({ kind, num, str, name, arr: [] });
3807
+ var isSpace3 = (c) => c === 0 || c === 9 || c === 10 || c === 12 || c === 13 || c === 32;
3808
+ var isDelim3 = (c) => c === 40 || c === 41 || c === 60 || c === 62 || c === 91 || c === 93 || c === 123 || c === 125 || c === 47 || c === 37;
3809
+ function unhex2(c) {
3810
+ if (c >= 48 && c <= 57) return c - 48;
3811
+ if (c >= 97 && c <= 102) return c - 97 + 10;
3812
+ if (c >= 65 && c <= 70) return c - 65 + 10;
3813
+ return -1;
3814
+ }
3815
+ function isNumber(b, s, e) {
3816
+ if (e === s || e - s > MAX_NUM_LEN) return false;
3817
+ let i = s;
3818
+ if (b[i] === 43 || b[i] === 45) i++;
3819
+ let digits = 0;
3820
+ let dot = false;
3821
+ for (; i < e; i++) {
3822
+ const c = b[i];
3823
+ if (c >= 48 && c <= 57) digits++;
3824
+ else if (c === 46 && !dot) dot = true;
3825
+ else return false;
3826
+ }
3827
+ return digits > 0;
3828
+ }
3829
+ var latin12 = (b, s, e) => {
3830
+ let out = "";
3831
+ for (let i = s; i < e; i++) out += String.fromCharCode(b[i]);
3832
+ return out;
3833
+ };
3834
+ var EOF_TOKEN2 = { k: 0 /* EOF */, o: opnd(5 /* Other */), kw: "" };
3835
+ var Lexer2 = class {
3836
+ constructor(b) {
3837
+ this.b = b;
3838
+ }
3839
+ b;
3840
+ i = 0;
3841
+ skipSpace() {
3842
+ const b = this.b;
3843
+ while (this.i < b.length) {
3844
+ const c = b[this.i];
3845
+ if (isSpace3(c)) this.i++;
3846
+ else if (c === 37) {
3847
+ while (this.i < b.length && b[this.i] !== 13 && b[this.i] !== 10) this.i++;
3848
+ } else return;
3849
+ }
3850
+ }
3851
+ /** Regular bytes from the current position; returns the end index (this.i is advanced to it). */
3852
+ regular() {
3853
+ const b = this.b;
3854
+ while (this.i < b.length && !isSpace3(b[this.i]) && !isDelim3(b[this.i])) this.i++;
3855
+ return this.i;
3856
+ }
3857
+ /** After '(' : balanced parentheses, escapes; EOF ends the string. */
3858
+ literal() {
3859
+ const b = this.b;
3860
+ const out = [];
3861
+ let depth = 1;
3862
+ while (this.i < b.length) {
3863
+ let c = b[this.i++];
3864
+ switch (c) {
3865
+ case 40:
3866
+ depth++;
3867
+ break;
3868
+ case 41:
3869
+ if (--depth === 0) return Uint8Array.from(out);
3870
+ break;
3871
+ case 92: {
3872
+ if (this.i >= b.length) return Uint8Array.from(out);
3873
+ const e = b[this.i++];
3874
+ switch (e) {
3875
+ case 110:
3876
+ c = 10;
3877
+ break;
3878
+ case 114:
3879
+ c = 13;
3880
+ break;
3881
+ case 116:
3882
+ c = 9;
3883
+ break;
3884
+ case 98:
3885
+ c = 8;
3886
+ break;
3887
+ case 102:
3888
+ c = 12;
3889
+ break;
3890
+ case 13:
3891
+ if (this.i < b.length && b[this.i] === 10) this.i++;
3892
+ continue;
3893
+ case 10:
3894
+ continue;
3895
+ default:
3896
+ if (e >= 48 && e <= 55) {
3897
+ let v = e - 48;
3898
+ for (let k = 0; k < 2 && this.i < b.length && b[this.i] >= 48 && b[this.i] <= 55; k++) v = v * 8 + (b[this.i++] - 48);
3899
+ c = v & 255;
3900
+ } else c = e;
3901
+ }
3902
+ }
3903
+ }
3904
+ out.push(c);
3905
+ }
3906
+ return Uint8Array.from(out);
3907
+ }
3908
+ /** After '<' : hex digits, other bytes skipped, odd final nibble padded with 0; '>' or EOF ends it. */
3909
+ hexString() {
3910
+ const b = this.b;
3911
+ const out = [];
3912
+ let hi = 0;
3913
+ let half = false;
3914
+ while (this.i < b.length) {
3915
+ const c = b[this.i++];
3916
+ if (c === 62) break;
3917
+ const v = unhex2(c);
3918
+ if (v < 0) continue;
3919
+ if (half) out.push(hi << 4 | v);
3920
+ else hi = v;
3921
+ half = !half;
3922
+ }
3923
+ if (half) out.push(hi << 4);
3924
+ return Uint8Array.from(out);
3925
+ }
3926
+ /** After '/' : regular bytes, #xx decoded (latin1, like the PDF object reader). */
3927
+ name() {
3928
+ const s = this.i;
3929
+ const e = this.regular();
3930
+ const t = this.b;
3931
+ let out = "";
3932
+ for (let i = s; i < e; i++) {
3933
+ if (t[i] === 35 && i + 2 < e) {
3934
+ const h = unhex2(t[i + 1]);
3935
+ const lo = unhex2(t[i + 2]);
3936
+ if (h >= 0 && lo >= 0) {
3937
+ out += String.fromCharCode(h << 4 | lo);
3938
+ i += 2;
3939
+ continue;
3940
+ }
3941
+ }
3942
+ out += String.fromCharCode(t[i]);
3943
+ }
3944
+ return out;
3945
+ }
3946
+ /** One token. Keywords come back as Lx.Keyword; '{' '}', stray ')' and a lone '>' are skipped. */
3947
+ next() {
3948
+ const b = this.b;
3949
+ for (; ; ) {
3950
+ this.skipSpace();
3951
+ if (this.i >= b.length) return EOF_TOKEN2;
3952
+ switch (b[this.i]) {
3953
+ case 40:
3954
+ this.i++;
3955
+ return { k: 1 /* Obj */, o: opnd(1 /* Str */, 0, this.literal()), kw: "" };
3956
+ case 60:
3957
+ if (this.i + 1 < b.length && b[this.i + 1] === 60) {
3958
+ this.i += 2;
3959
+ return { k: 1 /* Obj */, o: opnd(4 /* Dict */), kw: "<<" };
3960
+ }
3961
+ this.i++;
3962
+ return { k: 1 /* Obj */, o: opnd(1 /* Str */, 0, this.hexString()), kw: "" };
3963
+ case 62:
3964
+ if (this.i + 1 < b.length && b[this.i + 1] === 62) {
3965
+ this.i += 2;
3966
+ return { k: 4 /* DictEnd */, o: EOF_TOKEN2.o, kw: "" };
3967
+ }
3968
+ this.i++;
3969
+ continue;
3970
+ case 91:
3971
+ this.i++;
3972
+ return { k: 1 /* Obj */, o: opnd(3 /* Arr */), kw: "[" };
3973
+ case 93:
3974
+ this.i++;
3975
+ return { k: 3 /* ArrEnd */, o: EOF_TOKEN2.o, kw: "" };
3976
+ case 47:
3977
+ this.i++;
3978
+ return { k: 1 /* Obj */, o: opnd(2 /* Name */, 0, EMPTY, this.name()), kw: "" };
3979
+ case 41:
3980
+ case 123:
3981
+ case 125:
3982
+ this.i++;
3983
+ continue;
3984
+ }
3985
+ const s = this.i;
3986
+ const e = this.regular();
3987
+ if (isNumber(b, s, e)) return { k: 1 /* Obj */, o: opnd(0 /* Num */, Number(latin12(b, s, e))), kw: "" };
3988
+ const t = latin12(b, s, e);
3989
+ if (t === "true" || t === "false" || t === "null") return { k: 1 /* Obj */, o: opnd(5 /* Other */), kw: "" };
3990
+ return { k: 2 /* Keyword */, o: EOF_TOKEN2.o, kw: t };
3991
+ }
3992
+ }
3993
+ /**
3994
+ * Completes an array or dictionary opened by next (open = "[" or "<<"). Inside, every token is an element; EOF ends
3995
+ * the content (returns eof = true). Nesting > MAX_NESTING or too many elements → UnscannableError.
3996
+ */
3997
+ object(o, open, depth, count) {
3998
+ if (open === "") return false;
3999
+ if (depth >= MAX_NESTING2) throw unscannable("nesting");
4000
+ for (; ; ) {
4001
+ const t = this.next();
4002
+ let e = t.o;
4003
+ switch (t.k) {
4004
+ case 0 /* EOF */:
4005
+ return true;
4006
+ case 3 /* ArrEnd */:
4007
+ if (open === "[") return false;
4008
+ continue;
4009
+ case 4 /* DictEnd */:
4010
+ if (open === "<<") return false;
4011
+ continue;
4012
+ case 2 /* Keyword */:
4013
+ e = opnd(5 /* Other */);
4014
+ break;
4015
+ case 1 /* Obj */:
4016
+ if (this.object(e, t.kw, depth + 1, count)) return true;
4017
+ }
4018
+ if (++count.n > MAX_OPERANDS) throw unscannable("operands");
4019
+ if (open === "[") o.arr.push(e);
4020
+ }
4021
+ }
4022
+ };
4023
+ function nums(ops, n) {
4024
+ if (ops.length !== n) return void 0;
4025
+ const out = [];
4026
+ for (const o of ops) {
4027
+ if (o.kind !== 0 /* Num */) return void 0;
4028
+ out.push(o.num);
4029
+ }
4030
+ return out;
4031
+ }
4032
+ function closePath(sp) {
4033
+ const seg = pointRect(sp.cx, sp.cy);
4034
+ addPoint(seg, sp.sx, sp.sy);
4035
+ sp.segs.push(seg);
4036
+ sp.cx = sp.sx;
4037
+ sp.cy = sp.sy;
4038
+ }
4039
+ var PATH_POINTS = { l: 2, c: 6, v: 4, y: 4 };
4040
+ function inherited(page, key) {
4041
+ let v = page;
4042
+ for (let i = 0; i < MAX_INHERIT; i++) {
4043
+ const x = v.key(key);
4044
+ if (!x.isNull()) return x;
4045
+ v = v.key("Parent");
4046
+ if (v.kind() !== "dict") break;
4047
+ }
4048
+ return void 0;
4049
+ }
4050
+ var Scanner = class {
4051
+ constructor(page) {
4052
+ this.page = page;
4053
+ }
4054
+ page;
4055
+ bytes = 0;
4056
+ ops = 0;
4057
+ boxes = [];
4058
+ fonts = /* @__PURE__ */ new Map();
4059
+ emit(r) {
4060
+ this.boxes.push(quantise(r));
4061
+ }
4062
+ /** Font cache keyed by the containing object's number, as the Go reference (digitorus Value.GetPtr) does. */
4063
+ font(v) {
4064
+ if (v.kind() !== "dict") return DEFAULT_FONT;
4065
+ const id = v.ptr.id;
4066
+ const hit = this.fonts.get(id);
4067
+ if (hit && id !== 0) return hit;
4068
+ const f = loadFont(v);
4069
+ if (id !== 0) this.fonts.set(id, f);
4070
+ return f;
4071
+ }
4072
+ /** Decoded bytes of a content/form stream: no filter, or exactly FlateDecode without parameters. */
4073
+ stream(v) {
4074
+ if (v.kind() !== "stream") throw unscannable("not a stream");
4075
+ const f = v.key("Filter");
4076
+ const p = v.key("DecodeParms");
4077
+ let flate;
4078
+ if (f.isNull() && p.isNull()) flate = false;
4079
+ else if (f.kind() === "name" && f.name() === "FlateDecode" && p.isNull()) flate = true;
4080
+ else if (f.kind() === "array" && f.len() === 1 && f.index(0).kind() === "name" && f.index(0).name() === "FlateDecode" && (p.isNull() || p.kind() === "array" && p.len() === 1 && p.index(0).isNull())) {
4081
+ flate = true;
4082
+ } else throw unscannable("filter");
4083
+ const x = v.data;
4084
+ const n = v.key("Length").int64();
4085
+ const raw = n > 0 ? v.r.bytes.subarray(x.offset, x.offset + n) : EMPTY;
4086
+ const left = MAX_BYTES - this.bytes;
4087
+ let b;
4088
+ if (flate) {
4089
+ try {
4090
+ b = zlibInflateStrict(raw, left + 1);
4091
+ } catch (e) {
4092
+ throw unscannable(e instanceof Error ? e.message : "inflate");
4093
+ }
4094
+ } else b = raw.subarray(0, left + 1);
4095
+ if (b.length > left) throw unscannable("content bytes");
4096
+ this.bytes += b.length;
4097
+ return b;
4098
+ }
4099
+ /** /Contents: absent → empty; a stream; or an array of streams joined with LF. */
4100
+ pageContent(c) {
4101
+ switch (c.kind()) {
4102
+ case "null":
4103
+ return EMPTY;
4104
+ case "stream":
4105
+ return this.stream(c);
4106
+ case "array": {
4107
+ const parts = [];
4108
+ let total = 0;
4109
+ for (let i = 0; i < c.len(); i++) {
4110
+ const b = this.stream(c.index(i));
4111
+ parts.push(b);
4112
+ total += b.length + (i > 0 ? 1 : 0);
4113
+ }
4114
+ const out = new Uint8Array(total);
4115
+ let at = 0;
4116
+ parts.forEach((b, i) => {
4117
+ if (i > 0) out[at++] = 10;
4118
+ out.set(b, at);
4119
+ at += b.length;
4120
+ });
4121
+ return out;
4122
+ }
4123
+ }
4124
+ throw unscannable("/Contents");
4125
+ }
4126
+ /** Executes one content stream (page content or a form) from graphics state g0, with its own operand stack, q stack,
4127
+ * path and text matrices. */
4128
+ run(content, res, g0, depth) {
4129
+ const l = new Lexer2(content);
4130
+ let g = { ...g0 };
4131
+ const stack = [];
4132
+ let path = [];
4133
+ let tm = IDENTITY;
4134
+ let tlm = IDENTITY;
4135
+ let ops = [];
4136
+ const count = { n: 0 };
4137
+ const key = (v, k) => v?.key(k);
4138
+ const textLine = (ty) => {
4139
+ tlm = mul([1, 0, 0, 1, 0, ty], tlm);
4140
+ if (!finite(tlm)) throw unscannable("text matrix");
4141
+ tm = tlm;
4142
+ };
4143
+ for (; ; ) {
4144
+ const t = l.next();
4145
+ if (t.k === 0 /* EOF */) return;
4146
+ if (t.k === 3 /* ArrEnd */ || t.k === 4 /* DictEnd */) continue;
4147
+ if (t.k === 1 /* Obj */) {
4148
+ if (l.object(t.o, t.kw, 0, count)) return;
4149
+ if (++count.n > MAX_OPERANDS) throw unscannable("operands");
4150
+ ops.push(t.o);
4151
+ continue;
4152
+ }
4153
+ if (++this.ops > MAX_OPS) throw unscannable("operators");
4154
+ const args = ops;
4155
+ ops = [];
4156
+ count.n = 0;
4157
+ const kw = t.kw;
4158
+ switch (kw) {
4159
+ case "q":
4160
+ case "Q":
4161
+ case "BT":
4162
+ if (args.length !== 0) break;
4163
+ if (kw === "BT") {
4164
+ tm = IDENTITY;
4165
+ tlm = IDENTITY;
4166
+ } else if (kw === "Q") {
4167
+ const s = stack.pop();
4168
+ if (s) g = s;
4169
+ } else {
4170
+ if (stack.length >= MAX_SAVE) throw unscannable("q nesting");
4171
+ stack.push({ ...g });
4172
+ }
4173
+ break;
4174
+ case "cm": {
4175
+ const v = nums(args, 6);
4176
+ if (v) {
4177
+ g.ctm = mul(v, g.ctm);
4178
+ if (!finite(g.ctm)) throw unscannable("CTM");
4179
+ }
4180
+ break;
4181
+ }
4182
+ case "w": {
4183
+ const v = nums(args, 1);
4184
+ if (v) g.lw = v[0];
4185
+ break;
4186
+ }
4187
+ case "g":
4188
+ case "G": {
4189
+ const v = nums(args, 1);
4190
+ if (v) {
4191
+ if (kw === "g") g.fillWhite = v[0] >= 1;
4192
+ else g.strokeWhite = v[0] >= 1;
4193
+ }
4194
+ break;
4195
+ }
4196
+ case "rg":
4197
+ case "RG": {
4198
+ const v = nums(args, 3);
4199
+ if (v) {
4200
+ const white = v[0] >= 1 && v[1] >= 1 && v[2] >= 1;
4201
+ if (kw === "rg") g.fillWhite = white;
4202
+ else g.strokeWhite = white;
4203
+ }
4204
+ break;
4205
+ }
4206
+ case "k":
4207
+ case "K": {
4208
+ const v = nums(args, 4);
4209
+ if (v) {
4210
+ const white = v[0] <= 0 && v[1] <= 0 && v[2] <= 0 && v[3] <= 0;
4211
+ if (kw === "k") g.fillWhite = white;
4212
+ else g.strokeWhite = white;
4213
+ }
4214
+ break;
4215
+ }
4216
+ case "cs":
4217
+ case "sc":
4218
+ case "scn":
4219
+ g.fillWhite = false;
4220
+ break;
4221
+ case "CS":
4222
+ case "SC":
4223
+ case "SCN":
4224
+ g.strokeWhite = false;
4225
+ break;
4226
+ // ── Path construction (points transformed by the CTM when given) ──
4227
+ case "m": {
4228
+ const v = nums(args, 2);
4229
+ if (v) {
4230
+ const [x, y] = apply(g.ctm, v[0], v[1]);
4231
+ path.push({ sx: x, sy: y, cx: x, cy: y, bbox: pointRect(x, y), segs: [] });
4232
+ }
4233
+ break;
4234
+ }
4235
+ case "l":
4236
+ case "c":
4237
+ case "v":
4238
+ case "y": {
4239
+ const n = PATH_POINTS[kw];
4240
+ const v = nums(args, n);
4241
+ if (!v || path.length === 0) break;
4242
+ const sp = path[path.length - 1];
4243
+ const seg = pointRect(sp.cx, sp.cy);
4244
+ for (let i = 0; i < n; i += 2) {
4245
+ const [x, y] = apply(g.ctm, v[i], v[i + 1]);
4246
+ addPoint(seg, x, y);
4247
+ addPoint(sp.bbox, x, y);
4248
+ sp.cx = x;
4249
+ sp.cy = y;
4250
+ }
4251
+ sp.segs.push(seg);
4252
+ break;
4253
+ }
4254
+ case "h":
4255
+ if (args.length === 0 && path.length > 0) closePath(path[path.length - 1]);
4256
+ break;
4257
+ case "re": {
4258
+ const v = nums(args, 4);
4259
+ if (v) {
4260
+ const [x0, y0] = apply(g.ctm, v[0], v[1]);
4261
+ const p1 = apply(g.ctm, v[0] + v[2], v[1]);
4262
+ const p2 = apply(g.ctm, v[0] + v[2], v[1] + v[3]);
4263
+ const p3 = apply(g.ctm, v[0], v[1] + v[3]);
4264
+ const sp = { sx: x0, sy: y0, cx: x0, cy: y0, bbox: pointRect(x0, y0), segs: [] };
4265
+ for (const [px, py] of [p1, p2, p3]) {
4266
+ const seg = pointRect(sp.cx, sp.cy);
4267
+ addPoint(seg, px, py);
4268
+ sp.segs.push(seg);
4269
+ addPoint(sp.bbox, px, py);
4270
+ sp.cx = px;
4271
+ sp.cy = py;
4272
+ }
4273
+ closePath(sp);
4274
+ path.push(sp);
4275
+ }
4276
+ break;
4277
+ }
4278
+ case "S":
4279
+ case "s":
4280
+ case "f":
4281
+ case "F":
4282
+ case "f*":
4283
+ case "B":
4284
+ case "B*":
4285
+ case "b":
4286
+ case "b*":
4287
+ case "n": {
4288
+ if (args.length !== 0) break;
4289
+ if ((kw === "s" || kw === "b" || kw === "b*") && path.length > 0) closePath(path[path.length - 1]);
4290
+ const fill = kw !== "S" && kw !== "s" && kw !== "n";
4291
+ const stroke = kw === "S" || kw === "s" || kw === "B" || kw === "B*" || kw === "b" || kw === "b*";
4292
+ if (fill && !g.fillWhite) this.fill(path);
4293
+ if (stroke && !g.strokeWhite) this.stroke(path, g);
4294
+ path = [];
4295
+ break;
4296
+ }
4297
+ // ── Text ──
4298
+ case "Tc":
4299
+ case "Tw":
4300
+ case "Tz":
4301
+ case "TL":
4302
+ case "Ts": {
4303
+ const v = nums(args, 1);
4304
+ if (!v) break;
4305
+ if (kw === "Tc") g.tc = v[0];
4306
+ else if (kw === "Tw") g.tw = v[0];
4307
+ else if (kw === "Tz") g.th = v[0] / 100;
4308
+ else if (kw === "TL") g.tl = v[0];
4309
+ else g.trise = v[0];
4310
+ break;
4311
+ }
4312
+ case "Tf":
4313
+ if (args.length === 2 && args[0].kind === 2 /* Name */ && args[1].kind === 0 /* Num */) {
4314
+ const fv = key(key(res, "Font"), args[0].name);
4315
+ g.font = fv ? this.font(fv) : DEFAULT_FONT;
4316
+ g.tfs = args[1].num;
4317
+ }
4318
+ break;
4319
+ case "Td":
4320
+ case "TD": {
4321
+ const v = nums(args, 2);
4322
+ if (v) {
4323
+ if (kw === "TD") g.tl = -v[1];
4324
+ tlm = mul([1, 0, 0, 1, v[0], v[1]], tlm);
4325
+ if (!finite(tlm)) throw unscannable("text matrix");
4326
+ tm = tlm;
4327
+ }
4328
+ break;
4329
+ }
4330
+ case "T*":
4331
+ if (args.length === 0) textLine(-g.tl);
4332
+ break;
4333
+ case "Tm": {
4334
+ const v = nums(args, 6);
4335
+ if (v) {
4336
+ tm = v;
4337
+ tlm = tm;
4338
+ }
4339
+ break;
4340
+ }
4341
+ case "Tj":
4342
+ case "'":
4343
+ case '"':
4344
+ case "TJ": {
4345
+ let items;
4346
+ if ((kw === "Tj" || kw === "'") && args.length === 1 && args[0].kind === 1 /* Str */) items = args;
4347
+ else if (kw === '"' && args.length === 3 && args[0].kind === 0 /* Num */ && args[1].kind === 0 /* Num */ && args[2].kind === 1 /* Str */) {
4348
+ g.tw = args[0].num;
4349
+ g.tc = args[1].num;
4350
+ items = args.slice(2);
4351
+ } else if (kw === "TJ" && args.length === 1 && args[0].kind === 3 /* Arr */) items = args[0].arr;
4352
+ else break;
4353
+ if (kw === "'" || kw === '"') textLine(-g.tl);
4354
+ tm = this.show(items, g, tm);
4355
+ break;
4356
+ }
4357
+ case "Do": {
4358
+ if (args.length !== 1 || args[0].kind !== 2 /* Name */) break;
4359
+ const x = key(key(res, "XObject"), args[0].name);
4360
+ if (!x) break;
4361
+ switch (x.key("Subtype").name()) {
4362
+ case "Image":
4363
+ this.unitSquare(g.ctm);
4364
+ break;
4365
+ case "Form": {
4366
+ if (x.kind() !== "stream") break;
4367
+ if (depth + 1 > MAX_DEPTH3) throw unscannable("form depth");
4368
+ let fm = IDENTITY;
4369
+ const m = x.key("Matrix");
4370
+ if (m.kind() === "array" && m.len() === 6) {
4371
+ const v = [];
4372
+ for (let i = 0; i < 6; i++) {
4373
+ const e = number(m.index(i));
4374
+ if (e === void 0) break;
4375
+ v.push(e);
4376
+ }
4377
+ if (v.length === 6) fm = v;
4378
+ }
4379
+ const ctm = mul(fm, g.ctm);
4380
+ if (!finite(ctm)) throw unscannable("form matrix");
4381
+ let fres = x.key("Resources");
4382
+ if (fres.kind() !== "dict") fres = res;
4383
+ const b = this.stream(x);
4384
+ this.run(b, fres, { ...g, ctm }, depth + 1);
4385
+ break;
4386
+ }
4387
+ }
4388
+ break;
4389
+ }
4390
+ case "BI":
4391
+ this.inlineImage(l, g.ctm);
4392
+ break;
4393
+ }
4394
+ }
4395
+ }
4396
+ /** One box per subpath; a subpath box covering ≥ half of the page box is a background and is skipped. */
4397
+ fill(path) {
4398
+ const p = this.page;
4399
+ for (const sp of path) {
4400
+ const q = quantise(sp.bbox);
4401
+ const w = Math.min(q[2], p[2]) - Math.max(q[0], p[0]);
4402
+ const h = Math.min(q[3], p[3]) - Math.max(q[1], p[1]);
4403
+ if (w > 0 && h > 0) {
4404
+ const pw = p[2] - p[0];
4405
+ const ph = p[3] - p[1];
4406
+ const lhs = 2 * w * h;
4407
+ const rhs = pw * ph;
4408
+ const bg = lhs < 2 ** 53 && rhs < 2 ** 53 ? lhs >= rhs : 2n * BigInt(w) * BigInt(h) >= BigInt(pw) * BigInt(ph);
4409
+ if (bg) continue;
4410
+ }
4411
+ this.boxes.push(q);
4412
+ }
4413
+ }
4414
+ /** One box per segment, widened by half the line width mapped through the CTM (|a|+|c|, |b|+|d|). */
4415
+ stroke(path, g) {
4416
+ const hw = Math.abs(g.lw) / 2;
4417
+ const ex = hw * Math.abs(g.ctm[0]) + hw * Math.abs(g.ctm[2]);
4418
+ const ey = hw * Math.abs(g.ctm[1]) + hw * Math.abs(g.ctm[3]);
4419
+ for (const sp of path) {
4420
+ for (const r of sp.segs) this.emit({ x0: r.x0 - ex, y0: r.y0 - ey, x1: r.x1 + ex, y1: r.y1 + ey });
4421
+ }
4422
+ }
4423
+ unitSquare(ctm) {
4424
+ const [x, y] = apply(ctm, 0, 0);
4425
+ const r = pointRect(x, y);
4426
+ for (const [px, py] of [
4427
+ [1, 0],
4428
+ [0, 1],
4429
+ [1, 1]
4430
+ ]) {
4431
+ const [qx, qy] = apply(ctm, px, py);
4432
+ addPoint(r, qx, qy);
4433
+ }
4434
+ this.emit(r);
4435
+ }
4436
+ /** One box per show operator: [min, max] of glyph extents in text space × [rise − 0.3·Tfs, rise + Tfs], through Tm
4437
+ * then the CTM. Returns the advanced Tm. */
4438
+ show(items, g, tm) {
4439
+ let x = 0;
4440
+ let lo = 0;
4441
+ let hi = 0;
4442
+ let ext = false;
4443
+ for (const it of items) {
4444
+ if (it.kind === 0 /* Num */) {
4445
+ x = x - it.num / 1e3 * g.tfs * g.th;
4446
+ } else if (it.kind === 1 /* Str */) {
4447
+ glyphs(g.font, it.str, (w0, space) => {
4448
+ const gw = w0 / 1e3 * g.tfs * g.th;
4449
+ const a = Math.min(x, x + gw);
4450
+ const b = Math.max(x, x + gw);
4451
+ if (!ext) {
4452
+ lo = a;
4453
+ hi = b;
4454
+ ext = true;
4455
+ } else {
4456
+ lo = Math.min(lo, a);
4457
+ hi = Math.max(hi, b);
4458
+ }
4459
+ let adv = w0 / 1e3 * g.tfs + g.tc;
4460
+ if (space) adv = adv + g.tw;
4461
+ x = x + adv * g.th;
4462
+ });
4463
+ }
4464
+ }
4465
+ if (ext) {
4466
+ const ya = g.trise + g.tfs * -0.3;
4467
+ const yb = g.trise + g.tfs;
4468
+ let r;
4469
+ for (const [px, py] of [
4470
+ [lo, ya],
4471
+ [hi, ya],
4472
+ [lo, yb],
4473
+ [hi, yb]
4474
+ ]) {
4475
+ const [tx, ty] = apply(tm, px, py);
4476
+ const [dx, dy] = apply(g.ctm, tx, ty);
4477
+ if (!r) r = pointRect(dx, dy);
4478
+ else addPoint(r, dx, dy);
4479
+ }
4480
+ this.emit(r);
4481
+ }
4482
+ const out = mul([1, 0, 0, 1, x, 0], tm);
4483
+ if (!finite(out)) throw unscannable("text matrix");
4484
+ return out;
4485
+ }
4486
+ /** BI <key value>… ID <data> EI: data ends at the first "EI" preceded by a whitespace byte and followed by a
4487
+ * whitespace byte or the end of the content. No EI → the content ends (no box). */
4488
+ inlineImage(l, ctm) {
4489
+ const count = { n: 0 };
4490
+ for (; ; ) {
4491
+ const t = l.next();
4492
+ if (t.k === 0 /* EOF */) return;
4493
+ if (t.k === 1 /* Obj */) {
4494
+ if (l.object(t.o, t.kw, 0, count)) return;
4495
+ continue;
4496
+ }
4497
+ if (t.k === 2 /* Keyword */ && t.kw === "ID") break;
4498
+ }
4499
+ const b = l.b;
4500
+ if (l.i < b.length && isSpace3(b[l.i])) l.i++;
4501
+ for (let p = l.i; p + 1 < b.length; p++) {
4502
+ if (b[p] === 69 && b[p + 1] === 73 && p > 0 && isSpace3(b[p - 1]) && (p + 2 === b.length || isSpace3(b[p + 2]))) {
4503
+ l.i = p + 2;
4504
+ this.unitSquare(ctm);
4505
+ return;
4506
+ }
4507
+ }
4508
+ l.i = b.length;
4509
+ }
4510
+ /** /Rect of every annotation except /Popup, hidden (/F bit 2) or NoView (/F bit 6) and zero-area rects. */
4511
+ annots(a) {
4512
+ if (a.kind() !== "array") return;
4513
+ if (a.len() > MAX_ANNOTS) throw unscannable("annotations");
4514
+ for (let i = 0; i < a.len(); i++) {
4515
+ const an = a.index(i);
4516
+ if (an.kind() !== "dict" || an.key("Subtype").name() === "Popup") continue;
4517
+ const f = an.key("F");
4518
+ if (f.data instanceof PInt && (f.data.v & 34n) !== 0n) continue;
4519
+ const r = an.key("Rect");
4520
+ if (r.kind() !== "array" || r.len() !== 4) continue;
4521
+ const v = [];
4522
+ for (let j = 0; j < 4; j++) {
4523
+ const e = number(r.index(j));
4524
+ if (e === void 0) break;
4525
+ v.push(e);
4526
+ }
4527
+ if (v.length !== 4 || v[0] === v[2] || v[1] === v[3]) continue;
4528
+ this.emit({ x0: Math.min(v[0], v[2]), y0: Math.min(v[1], v[3]), x1: Math.max(v[0], v[2]), y1: Math.max(v[1], v[3]) });
4529
+ }
4530
+ }
4531
+ };
4532
+ function occupancy(page, box) {
4533
+ try {
4534
+ const s = new Scanner(box);
4535
+ const content = s.pageContent(page.key("Contents"));
4536
+ const res = inherited(page, "Resources");
4537
+ s.run(content, res, { ctm: IDENTITY, lw: 1, fillWhite: false, strokeWhite: false, tc: 0, tw: 0, th: 1, tl: 0, tfs: 0, trise: 0, font: DEFAULT_FONT }, 0);
4538
+ s.annots(page.key("Annots"));
4539
+ return s.boxes;
4540
+ } catch (e) {
4541
+ if (e instanceof UnscannableError) throw e;
4542
+ throw new UnscannableError(`pades: page content not scannable: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
4543
+ }
4544
+ }
4545
+ var PLACE_PAD = 400;
4546
+ var PLACE_STEP = 1200;
4547
+ var PLACE_STEPS = 100;
4548
+ function placeCandidates(vw, vh, x, y, w, h) {
4549
+ const xl = vw - x - w;
4550
+ const out = [[x, y]];
4551
+ if (xl !== x) out.push([xl, y]);
4552
+ const cols = xl !== x ? [x, xl] : [x];
4553
+ for (const cx of cols) {
4554
+ for (let k = 1; k <= PLACE_STEPS && y + k * PLACE_STEP + h <= vh - y; k++) out.push([cx, y + k * PLACE_STEP]);
4555
+ }
4556
+ return out;
4557
+ }
4558
+ function placeVisible(box, rot, x, y, w, h, occ) {
4559
+ let vw = box[2] - box[0];
4560
+ let vh = box[3] - box[1];
4561
+ if (rot === 90 || rot === 270) [vw, vh] = [vh, vw];
4562
+ for (const [cx, cy] of placeCandidates(vw, vh, x, y, w, h)) {
4563
+ let r;
4564
+ try {
4565
+ r = visibleRect(box, rot, cx, cy, w, h);
4566
+ } catch {
4567
+ continue;
4568
+ }
4569
+ const e0 = r[0] - PLACE_PAD;
4570
+ const e1 = r[1] - PLACE_PAD;
4571
+ const e2 = r[2] + PLACE_PAD;
4572
+ const e3 = r[3] + PLACE_PAD;
4573
+ if (!occ.some((b) => b[0] < e2 && e0 < b[2] && b[1] < e3 && e1 < b[3])) return [cx, cy];
4574
+ }
4575
+ return void 0;
4576
+ }
4577
+
3594
4578
  // src/pades/pdf/signature.ts
3595
4579
  var MEASURED_MAX_CMS = 14 << 10;
3596
4580
  var PLACEHOLDER_BYTES = 2 * MEASURED_MAX_CMS;
3597
4581
  var SUB_FILTER = "ETSI.CAdES.detached";
3598
4582
  var REASON_MAX_UNITS = 127;
3599
4583
  var BYTE_RANGE_WIDTH = 40;
3600
- var MAX_DEPTH3 = 32;
4584
+ var MAX_DEPTH4 = 32;
3601
4585
  var PlaceholderOverflowError = class extends Error {
3602
4586
  };
3603
4587
  function pdfDate(t) {
@@ -3642,6 +4626,7 @@ async function prepareSignature(base, signingTime, signerName, reason, vis) {
3642
4626
  sig += "\n>>";
3643
4627
  const sigStart = inc.writeObject(sigID, sig);
3644
4628
  let page;
4629
+ let placement;
3645
4630
  if (!vis) {
3646
4631
  let fld = "<<\n /Type /Annot\n /Subtype /Widget\n /Rect [0 0 0 0]\n";
3647
4632
  page = firstPage(root.key("Pages"), 0);
@@ -3658,7 +4643,24 @@ async function prepareSignature(base, signingTime, signerName, reason, vis) {
3658
4643
  page = nthPage(root.key("Pages"), vis.page);
3659
4644
  if (!page) throw new AppearanceError(`\u0445\u0443\u0443\u0434\u0430\u0441 ${vis.page} \u0430\u043B\u0433\u0430`);
3660
4645
  const { box, rot } = pageGeometry(page);
3661
- const rect = visibleRect(box, rot, vis.x, vis.y, vis.w, vis.h);
4646
+ let rect = visibleRect(box, rot, vis.x, vis.y, vis.w, vis.h);
4647
+ placement = { x: vis.x, y: vis.y, status: "requested" };
4648
+ if (vis.avoid) {
4649
+ let occ;
4650
+ try {
4651
+ occ = occupancy(page, box);
4652
+ } catch {
4653
+ placement.status = "unscanned";
4654
+ }
4655
+ if (occ) {
4656
+ const at = placeVisible(box, rot, vis.x, vis.y, vis.w, vis.h, occ);
4657
+ if (!at) placement.status = "overlap";
4658
+ else if (at[0] !== vis.x || at[1] !== vis.y) {
4659
+ placement = { x: at[0], y: at[1], status: "moved" };
4660
+ rect = visibleRect(box, rot, at[0], at[1], vis.w, vis.h);
4661
+ }
4662
+ }
4663
+ }
3662
4664
  const bodies = appearanceObjects({ w: vis.w, h: vis.h, rotate: rot, name: vis.name, role: vis.role, lang: vis.lang, date: vis.date, url: vis.url }, apIDs);
3663
4665
  inc.writeObject(fieldID, visibleWidget(fieldName, rect, page.ptr.id, page.ptr.gen, sigID, apIDs[0]));
3664
4666
  bodies.forEach((b2, i) => inc.writeObject(apIDs[i], b2));
@@ -3692,7 +4694,7 @@ async function prepareSignature(base, signingTime, signerName, reason, vis) {
3692
4694
  const field = `[${br[0]} ${br[1]} ${br[2]} ${br[3]}]`;
3693
4695
  if (field.length > BYTE_RANGE_WIDTH) throw new PdfError("pades: ByteRange \u0442\u0430\u043B\u0431\u0430\u0440\u0442 \u0431\u0430\u0433\u0442\u0441\u0430\u043D\u0433\u04AF\u0439");
3694
4696
  doc.set(latin1(field), sigStart + brAt);
3695
- return { pdf: doc, byteRange: br, digest: await rangeDigest(doc, br), fieldName };
4697
+ return { pdf: doc, byteRange: br, digest: await rangeDigest(doc, br), fieldName, placement };
3696
4698
  }
3697
4699
  async function rangeDigest(doc, br) {
3698
4700
  const buf = new Uint8Array(br[1] + br[3]);
@@ -3743,7 +4745,7 @@ function addWidgetToPage(inc, page, widget) {
3743
4745
  inc.writeObject(pgp.id, b, pgp.gen);
3744
4746
  }
3745
4747
  function firstPage(v, depth) {
3746
- if (depth > MAX_DEPTH3) return void 0;
4748
+ if (depth > MAX_DEPTH4) return void 0;
3747
4749
  switch (v.key("Type").name()) {
3748
4750
  case "Page":
3749
4751
  return v;
@@ -4219,7 +5221,12 @@ async function prepare(pdf, opts) {
4219
5221
  preparedSha256: toHex(await sha256(prep.pdf)),
4220
5222
  pdf: prep.pdf
4221
5223
  });
4222
- return { dtbs: await sha256(attrs), digest: prep.digest, docId, state };
5224
+ const out = { dtbs: await sha256(attrs), digest: prep.digest, docId, state };
5225
+ if (vis && prep.placement) {
5226
+ const pl = prep.placement;
5227
+ out.placement = { page: vis.page, x: pl.x / 100, y: pl.y / 100, width: vis.w / 100, height: vis.h / 100, status: pl.status };
5228
+ }
5229
+ return out;
4223
5230
  }
4224
5231
  function checkAppearance(o) {
4225
5232
  const a = o.appearance;
@@ -4237,13 +5244,13 @@ function checkAppearance(o) {
4237
5244
  function visibleSpec(doc, o, name, now, docId, revIndex) {
4238
5245
  const a = o.appearance;
4239
5246
  if (docId === "") throw new PadesError("REQUEST_INVALID", "appearance: docId \u0437\u0430\u0430\u0432\u0430\u043B (\u0431\u0430\u0440\u0438\u043C\u0442\u0430\u0434 verify \u0445\u0443\u0443\u0434\u0430\u0441 \u0430\u043B\u0433\u0430)");
4240
- let n;
5247
+ let last, n;
4241
5248
  try {
4242
- n = pageCount(doc);
5249
+ ({ page: last, n } = defaultStampPage(doc, VERIFY_URL_PREFIX + docId));
4243
5250
  } catch (e) {
4244
5251
  throw new PadesError("PDF_INVALID", "PDF \u0437\u0430\u0434\u0430\u0440\u0441\u0430\u043D\u0433\u04AF\u0439", { cause: e });
4245
5252
  }
4246
- const page = a.page || n;
5253
+ const page = a.page || last;
4247
5254
  if (page > n) throw new PadesError("REQUEST_INVALID", `appearance: page ${page} > \u0445\u0443\u0443\u0434\u0430\u0441\u043D\u044B \u0442\u043E\u043E ${n}`);
4248
5255
  const z = new Date(now.getTime() + 8 * 36e5);
4249
5256
  const p2 = (v) => String(v).padStart(2, "0");
@@ -4257,7 +5264,8 @@ function visibleSpec(doc, o, name, now, docId, revIndex) {
4257
5264
  role: o.claimedRole ?? "",
4258
5265
  lang: a.lang || o.lang || "mn",
4259
5266
  date: `${String(z.getUTCFullYear()).padStart(4, "0")}-${p2(z.getUTCMonth() + 1)}-${p2(z.getUTCDate())} ${p2(z.getUTCHours())}:${p2(z.getUTCMinutes())} (+08)`,
4260
- url: `${VERIFY_URL_PREFIX}${docId}/${revIndex}`
5267
+ url: `${VERIFY_URL_PREFIX}${docId}/${revIndex}`,
5268
+ avoid: true
4261
5269
  };
4262
5270
  }
4263
5271
  var DEFAULT_LTV_RETRIES = 2;
@@ -4291,7 +5299,7 @@ function abortableSleep(sleep, ms, signal) {
4291
5299
  );
4292
5300
  });
4293
5301
  }
4294
- async function complete(state, signature, opts = {}) {
5302
+ async function complete2(state, signature, opts = {}) {
4295
5303
  let st;
4296
5304
  let cert;
4297
5305
  let chain;