pdf-skryba 0.9.0 → 0.10.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.
@@ -1393,6 +1393,58 @@ var PdfObjectsRefusal = class extends ReaderError {
1393
1393
  objectNumber;
1394
1394
  offset;
1395
1395
  };
1396
+ var REFUSAL_IS_BOUND = {
1397
+ syntax: false,
1398
+ truncated: false,
1399
+ "nesting-too-deep": true,
1400
+ "token-too-long": true,
1401
+ "string-too-long": true,
1402
+ "stream-length": false,
1403
+ "stream-end": false,
1404
+ "stream-too-large": true,
1405
+ "length-unresolved": false,
1406
+ "startxref-missing": false,
1407
+ "xref-offset": false,
1408
+ "xref-syntax": false,
1409
+ "xref-chain": false,
1410
+ "xref-too-large": true,
1411
+ "filter-unsupported": false,
1412
+ predictor: false,
1413
+ "stream-decode": false,
1414
+ "object-stream": false,
1415
+ "xref-stream": false,
1416
+ "xref-stale": false,
1417
+ "ref-hops": true,
1418
+ "page-tree": false,
1419
+ "page-box": false,
1420
+ "content-syntax": false,
1421
+ "content-operands": false,
1422
+ "content-too-long": true,
1423
+ "inline-image": false,
1424
+ encrypted: false,
1425
+ "to-unicode": false,
1426
+ "value-too-large": true,
1427
+ "document-too-large": true,
1428
+ "glyphs-too-many": true,
1429
+ "forms-too-many": true,
1430
+ "font-tables-too-many": true,
1431
+ "page-missing": false
1432
+ };
1433
+ function isSecurityRefusal(error) {
1434
+ if (error instanceof PdfObjectsRefusal) return REFUSAL_IS_BOUND[error.reason];
1435
+ return error instanceof ReaderError && error.code === "FILE_UNSAFE";
1436
+ }
1437
+ function rethrowSecurityRefusal(error) {
1438
+ if (isSecurityRefusal(error)) throw error;
1439
+ }
1440
+ function partOrAbsent(read) {
1441
+ try {
1442
+ return read();
1443
+ } catch (error) {
1444
+ if (error instanceof PdfObjectsRefusal && !isSecurityRefusal(error)) return void 0;
1445
+ throw error;
1446
+ }
1447
+ }
1396
1448
 
1397
1449
  // src/extractor/pdf-objects/parse.ts
1398
1450
  var MAX_OBJECT_NUMBER = 8388607;
@@ -1787,8 +1839,9 @@ import { inflateSync } from "node:zlib";
1787
1839
  import { unfilterPngRows } from "doc-ir/internal";
1788
1840
  var FLATE = "FlateDecode";
1789
1841
  var LZW = "LZWDecode";
1842
+ var takesPredictor = (filter) => filter === FLATE || filter === "Fl" || filter === LZW || filter === "LZW";
1790
1843
  function grownTo(buffer, length, needed) {
1791
- if (length + needed > MAX_DECODED_STREAM_BYTES) throw new PdfObjectsRefusal("stream-decode");
1844
+ if (length + needed > MAX_DECODED_STREAM_BYTES) throw new PdfObjectsRefusal("stream-too-large");
1792
1845
  if (length + needed <= buffer.length) return buffer;
1793
1846
  let next = buffer.length;
1794
1847
  while (next < length + needed) next *= 2;
@@ -2003,7 +2056,8 @@ var INFLATE_CHUNK_BYTES = 64 * 1024;
2003
2056
  function inflate(raw) {
2004
2057
  try {
2005
2058
  return inflateSync(raw, { maxOutputLength: MAX_DECODED_STREAM_BYTES, chunkSize: INFLATE_CHUNK_BYTES });
2006
- } catch {
2059
+ } catch (error) {
2060
+ if (error.code === "ERR_BUFFER_TOO_LARGE") throw new PdfObjectsRefusal("stream-too-large");
2007
2061
  throw new PdfObjectsRefusal("stream-decode");
2008
2062
  }
2009
2063
  }
@@ -2029,6 +2083,7 @@ var FILTERS = {
2029
2083
  [FLATE]: (data, parms) => unpredict(inflate(data), parms),
2030
2084
  Fl: (data, parms) => unpredict(inflate(data), parms),
2031
2085
  [LZW]: (data, parms) => unpredict(lzwDecode(data, earlyChangeOf(parms)), parms),
2086
+ LZW: (data, parms) => unpredict(lzwDecode(data, earlyChangeOf(parms)), parms),
2032
2087
  ASCIIHexDecode: (data) => asciiHexDecode(data),
2033
2088
  AHx: (data) => asciiHexDecode(data),
2034
2089
  ASCII85Decode: (data) => ascii85Decode(data),
@@ -2039,7 +2094,7 @@ var FILTERS = {
2039
2094
  var decodeStream = (bytes, stream) => {
2040
2095
  const filters = filtersOf(stream.dict);
2041
2096
  if (filters.length > MAX_FILTER_CHAIN) throw new PdfObjectsRefusal("filter-unsupported");
2042
- const predicted = filters.findIndex((filter) => filter === FLATE || filter === LZW);
2097
+ const predicted = filters.findIndex(takesPredictor);
2043
2098
  let data = bytes.subarray(stream.start, stream.start + stream.length);
2044
2099
  for (const [index, filter] of filters.entries()) {
2045
2100
  const decode = Object.hasOwn(FILTERS, filter) ? FILTERS[filter] : void 0;
@@ -2069,7 +2124,7 @@ var chainRefusal = (dict) => {
2069
2124
  var decodeToImageFilter = (data, dict) => {
2070
2125
  const filters = filtersOf(dict);
2071
2126
  if (filters.length > MAX_FILTER_CHAIN) throw new PdfObjectsRefusal("filter-unsupported");
2072
- const predicted = filters.findIndex((filter) => filter === FLATE || filter === LZW);
2127
+ const predicted = filters.findIndex(takesPredictor);
2073
2128
  let out = data;
2074
2129
  for (const [index, filter] of filters.entries()) {
2075
2130
  if (IMAGE_FILTERS.has(filter)) {
@@ -2087,7 +2142,8 @@ function integerAt(data, from) {
2087
2142
  let parsed2;
2088
2143
  try {
2089
2144
  parsed2 = parseValue(data, from);
2090
- } catch {
2145
+ } catch (error) {
2146
+ if (!(error instanceof PdfObjectsRefusal)) throw error;
2091
2147
  throw new PdfObjectsRefusal("object-stream");
2092
2148
  }
2093
2149
  if (parsed2.value.kind !== "number" || !Number.isInteger(parsed2.value.value) || parsed2.value.value < 0) {
@@ -2137,7 +2193,8 @@ function readObjectStream(bytes, stream, decode) {
2137
2193
  try {
2138
2194
  const parsed2 = parseValue(data, start);
2139
2195
  return { value: parsed2.value, nodes: parsed2.nodes };
2140
- } catch {
2196
+ } catch (error) {
2197
+ if (!(error instanceof PdfObjectsRefusal)) throw error;
2141
2198
  throw new PdfObjectsRefusal("object-stream", num);
2142
2199
  }
2143
2200
  }
@@ -2264,7 +2321,8 @@ function readStreamSection(bytes, offset, spend) {
2264
2321
  let object;
2265
2322
  try {
2266
2323
  object = parseIndirectObject(bytes, offset, () => void 0);
2267
- } catch {
2324
+ } catch (error) {
2325
+ if (!(error instanceof PdfObjectsRefusal)) throw error;
2268
2326
  throw new PdfObjectsRefusal("xref-offset");
2269
2327
  }
2270
2328
  const stream = object.value;
@@ -2835,7 +2893,8 @@ function paletteBytesOf(doc, table) {
2835
2893
  if (table?.kind !== "stream") return void 0;
2836
2894
  try {
2837
2895
  return doc.streamBytes(table);
2838
- } catch {
2896
+ } catch (error) {
2897
+ rethrowSecurityRefusal(error);
2839
2898
  return void 0;
2840
2899
  }
2841
2900
  }
@@ -2943,7 +3002,8 @@ function flatePixels(doc, stream, shape, spent) {
2943
3002
  let contents;
2944
3003
  try {
2945
3004
  contents = doc.rawStreamBytes(stream);
2946
- } catch {
3005
+ } catch (error) {
3006
+ rethrowSecurityRefusal(error);
2947
3007
  return void 0;
2948
3008
  }
2949
3009
  const parms = doc.resolve(stream.dict.get("DecodeParms"));
@@ -3006,7 +3066,8 @@ async function openEmbeddedImages(source) {
3006
3066
  let stream;
3007
3067
  try {
3008
3068
  stream = doc.resolve({ kind: "ref", num: Number(m[1]), gen: m[2] ? Number(m[2]) : 0 });
3009
- } catch {
3069
+ } catch (error) {
3070
+ rethrowSecurityRefusal(error);
3010
3071
  return void 0;
3011
3072
  }
3012
3073
  if (stream?.kind !== "stream") return void 0;
@@ -3026,7 +3087,8 @@ async function openEmbeddedImages(source) {
3026
3087
  let raw;
3027
3088
  try {
3028
3089
  raw = doc.imageStreamOf(stream).data;
3029
- } catch {
3090
+ } catch (error) {
3091
+ rethrowSecurityRefusal(error);
3030
3092
  return void 0;
3031
3093
  }
3032
3094
  if (!(raw[0] === 255 && raw[1] === 216 && raw[2] === 255)) return void 0;
@@ -4941,7 +5003,8 @@ function maskSamplesOf(doc, mask, filter, size) {
4941
5003
  if (filter === "CCITTFaxDecode") return ccittSamplesOf(doc, mask, size.mw, size.mh);
4942
5004
  if (filter === "DCTDecode") return dctSamplesOf(doc, mask, size.mw, size.mh);
4943
5005
  return flateSamplesOf(doc, mask, size.mw, size.mh);
4944
- } catch {
5006
+ } catch (error) {
5007
+ rethrowSecurityRefusal(error);
4945
5008
  return void 0;
4946
5009
  }
4947
5010
  }
@@ -5032,7 +5095,8 @@ function stencilLayoutOf(doc, dict) {
5032
5095
  function samplesOf(doc, stream, width, height) {
5033
5096
  try {
5034
5097
  return unpackSamples(doc.streamBytes(stream), width, height, 1, 1);
5035
- } catch {
5098
+ } catch (error) {
5099
+ rethrowSecurityRefusal(error);
5036
5100
  return void 0;
5037
5101
  }
5038
5102
  }
@@ -5097,7 +5161,6 @@ function ccittStreamOf(doc, declared) {
5097
5161
  if (nameOf2(doc.resolve(dict.get("Subtype"))) !== "Image") return void 0;
5098
5162
  if (boolOf(doc.resolve(dict.get("ImageMask")))) return void 0;
5099
5163
  if (singleFilterOf(doc, dict) !== "CCITTFaxDecode") return void 0;
5100
- if (doc.trailer().has("Encrypt")) return void 0;
5101
5164
  return stream;
5102
5165
  }
5103
5166
  function repack(image, width, height, invert) {
@@ -5112,7 +5175,7 @@ function repack(image, width, height, invert) {
5112
5175
  }
5113
5176
  return data;
5114
5177
  }
5115
- function ccittImageObjectOf(doc, file, scope, name, grey1Kind) {
5178
+ function ccittImageObjectOf(doc, scope, name, grey1Kind) {
5116
5179
  const declared = doc.dictOf(scope.resources?.get("XObject"))?.get(name);
5117
5180
  const stream = ccittStreamOf(doc, declared);
5118
5181
  if (stream === void 0) return void 0;
@@ -5122,7 +5185,8 @@ function ccittImageObjectOf(doc, file, scope, name, grey1Kind) {
5122
5185
  if (width === void 0 || height === void 0 || !pictureSizeOk(width, height)) return void 0;
5123
5186
  const parms = doc.dictOf(doc.resolve(dict.get("DecodeParms")));
5124
5187
  const parm = (key) => doc.resolve(parms?.get(key));
5125
- const raw = file.subarray(stream.start, stream.start + stream.length);
5188
+ const raw = partOrAbsent(() => doc.rawStreamBytes(stream));
5189
+ if (raw === void 0) return void 0;
5126
5190
  const image = decodeCcittFax(raw, {
5127
5191
  K: numberOf2(parm("K")) ?? 0,
5128
5192
  EndOfLine: boolOf(parm("EndOfLine")),
@@ -5209,7 +5273,8 @@ function samplesOf2(doc, stream, layout) {
5209
5273
  let samples;
5210
5274
  try {
5211
5275
  samples = doc.streamBytes(stream);
5212
- } catch {
5276
+ } catch (error) {
5277
+ rethrowSecurityRefusal(error);
5213
5278
  return void 0;
5214
5279
  }
5215
5280
  return unpackSamples(samples, layout.width, layout.height, layout.components, layout.bpc);
@@ -5262,7 +5327,8 @@ function jpegDeclaredOf(doc, dict) {
5262
5327
  function rawBytesOf(doc, stream) {
5263
5328
  try {
5264
5329
  return doc.imageStreamOf(stream).data;
5265
- } catch {
5330
+ } catch (error) {
5331
+ rethrowSecurityRefusal(error);
5266
5332
  return void 0;
5267
5333
  }
5268
5334
  }
@@ -7597,7 +7663,7 @@ function walkForm(walking, operands, scope, depth, state) {
7597
7663
  const { doc } = walking;
7598
7664
  const { resources, xobjects } = scope;
7599
7665
  const name = nameOf4(operands[0]);
7600
- const target = name === void 0 ? void 0 : doc.resolve(xobjects?.get(name));
7666
+ const target = name === void 0 ? void 0 : partOrAbsent(() => doc.resolve(xobjects?.get(name)));
7601
7667
  if (target?.kind !== "stream" || nameOf4(doc.resolve(target.dict.get("Subtype"))) !== "Form") return;
7602
7668
  const own = doc.dictOf(target.dict.get("Resources")) ?? resources;
7603
7669
  chargeFormCall(walking.budget);
@@ -8103,10 +8169,17 @@ function groupOperand(doc, entry) {
8103
8169
  }
8104
8170
  return null;
8105
8171
  }
8172
+ var UNREADABLE_XOBJECT_OP = "unreadableXObject";
8106
8173
  function doXObject(context, frame, name, out) {
8107
8174
  if (name === void 0) return;
8108
8175
  const xobjects = context.doc.dictOf(frame.resources?.get("XObject"));
8109
- const target = context.doc.resolve(xobjects?.get(name));
8176
+ const declared = xobjects?.get(name);
8177
+ const read = partOrAbsent(() => ({ target: context.doc.resolve(declared) }));
8178
+ if (read === void 0) {
8179
+ out.push({ op: UNREADABLE_XOBJECT_OP, args: [name] });
8180
+ return;
8181
+ }
8182
+ const { target } = read;
8110
8183
  if (target?.kind !== "stream") return;
8111
8184
  const subtype = nameOf6(context.doc.resolve(target.dict.get("Subtype")));
8112
8185
  if (subtype === "Image") {
@@ -8596,12 +8669,13 @@ function isSymbolFontOfWalk(walk2, fontName) {
8596
8669
  return answer;
8597
8670
  }
8598
8671
  var glyphUnicode = (unicode, inSymbolFont) => inSymbolFont ? symbolFontText(unicode ?? "") : unicode ?? "";
8599
- var INVENTED_CONTROL = /^[\u0000-\u0008\u000a-\u001f\u007f-\u009f]+$/u;
8600
- var isInventedControl = (text) => INVENTED_CONTROL.test(text);
8672
+ var CONTROL_CHARACTERS = /[\u0000-\u0008\u000a-\u001f\u007f-\u009f]/gu;
8673
+ var withoutControls = (text) => text.replace(CONTROL_CHARACTERS, "");
8601
8674
  function placedTextOf(g, inSymbolFont) {
8602
8675
  const unicode = glyphUnicode(g.unicode, inSymbolFont);
8603
8676
  if (unicode.length === 0) return g.read === "not-ours" ? { text: "", ...UNREAD_FONT_MARK } : void 0;
8604
- return isInventedControl(unicode) ? void 0 : { text: glyphText(unicode) };
8677
+ const kept = withoutControls(unicode);
8678
+ return kept.length === 0 ? void 0 : { text: glyphText(kept) };
8605
8679
  }
8606
8680
  function riseShiftOf(rise, params, textToDevice, origin) {
8607
8681
  if (rise === 0) return NO_RISE;
@@ -9150,7 +9224,7 @@ function fontObjectsOfPage(doc, page) {
9150
9224
  const resolve = (name, scope) => {
9151
9225
  const parent = resourcesOf.get(scope);
9152
9226
  const xobjects = doc.dictOf(parent?.get("XObject"));
9153
- const target = doc.resolve(xobjects?.get(name));
9227
+ const target = partOrAbsent(() => doc.resolve(xobjects?.get(name)));
9154
9228
  if (target?.kind !== "stream") return void 0;
9155
9229
  if (doc.resolve(target.dict.get("Subtype"))?.value !== "Form") return void 0;
9156
9230
  let ops;
@@ -9282,23 +9356,24 @@ function flattenOutline(tree) {
9282
9356
  }
9283
9357
  function outlineTreeOf(doc) {
9284
9358
  const catalog = doc.dictOf(doc.trailer().get("Root"));
9285
- const root = doc.dictOf(catalog?.get("Outlines"));
9359
+ const root = partOrAbsent(() => doc.dictOf(catalog?.get("Outlines")));
9286
9360
  if (root === void 0) return void 0;
9287
9361
  const seen = /* @__PURE__ */ new Set();
9288
9362
  let count2 = 0;
9289
9363
  const readSiblings = (first) => {
9290
9364
  const out = [];
9291
- let node = doc.dictOf(first);
9365
+ let node = partOrAbsent(() => doc.dictOf(first));
9292
9366
  while (node !== void 0 && !seen.has(node)) {
9293
9367
  seen.add(node);
9294
9368
  count2 += 1;
9295
9369
  if (count2 > OUTLINE_READ_MAX_ENTRIES) return void 0;
9296
- const titleValue = doc.resolve(node.get("Title"));
9370
+ const current = node;
9371
+ const titleValue = partOrAbsent(() => doc.resolve(current.get("Title")));
9297
9372
  const title = titleValue?.kind === "string" ? decodePdfTextString(titleValue.bytes) : void 0;
9298
9373
  const children = readSiblings(node.get("First"));
9299
9374
  if (children === void 0) return void 0;
9300
9375
  out.push({ title, items: children });
9301
- node = doc.dictOf(node.get("Next"));
9376
+ node = partOrAbsent(() => doc.dictOf(current.get("Next")));
9302
9377
  }
9303
9378
  return out;
9304
9379
  };
@@ -9475,23 +9550,27 @@ function isVisible(doc, annot) {
9475
9550
  const bits = flags?.kind === "number" ? flags.value : 0;
9476
9551
  return (bits & (FLAG_INVISIBLE | FLAG_HIDDEN | FLAG_NOVIEW)) === 0;
9477
9552
  }
9553
+ function linkOf(doc, item) {
9554
+ const annot = doc.dictOf(item);
9555
+ if (annot === void 0 || nameOf9(doc.resolve(annot.get("Subtype"))) !== "Link") return void 0;
9556
+ if (!isVisible(doc, annot)) return void 0;
9557
+ const action = doc.dictOf(annot.get("A"));
9558
+ if (action === void 0 || nameOf9(doc.resolve(action.get("S"))) !== "URI") return void 0;
9559
+ if (doc.resolve(action.get("NewWindow")) !== void 0) return void 0;
9560
+ const uriValue = doc.resolve(action.get("URI"));
9561
+ if (uriValue?.kind !== "string") return void 0;
9562
+ const url = absoluteTargetOf(Buffer.from(uriValue.bytes).toString("latin1"));
9563
+ const rect = rectOf(doc, annot);
9564
+ if (url === void 0 || rect === void 0) return void 0;
9565
+ return { url, rect };
9566
+ }
9478
9567
  function linkAnnotationsOfPage(doc, page) {
9479
9568
  const links = [];
9480
- const annots = doc.resolve(page.dict.get("Annots"));
9569
+ const annots = partOrAbsent(() => doc.resolve(page.dict.get("Annots")));
9481
9570
  if (annots?.kind !== "array") return links;
9482
9571
  for (const item of annots.items) {
9483
- const annot = doc.dictOf(item);
9484
- if (annot === void 0 || nameOf9(doc.resolve(annot.get("Subtype"))) !== "Link") continue;
9485
- if (!isVisible(doc, annot)) continue;
9486
- const action = doc.dictOf(annot.get("A"));
9487
- if (action === void 0 || nameOf9(doc.resolve(action.get("S"))) !== "URI") continue;
9488
- if (doc.resolve(action.get("NewWindow")) !== void 0) continue;
9489
- const uriValue = doc.resolve(action.get("URI"));
9490
- if (uriValue?.kind !== "string") continue;
9491
- const url = absoluteTargetOf(Buffer.from(uriValue.bytes).toString("latin1"));
9492
- const rect = rectOf(doc, annot);
9493
- if (url === void 0 || rect === void 0) continue;
9494
- links.push({ url, rect });
9572
+ const link = partOrAbsent(() => linkOf(doc, item));
9573
+ if (link !== void 0) links.push(link);
9495
9574
  }
9496
9575
  return links;
9497
9576
  }
@@ -9888,28 +9967,30 @@ function ourImagesOf(ctx, ops) {
9888
9967
  refusals.set(name, "ambiguous");
9889
9968
  continue;
9890
9969
  }
9891
- const scope = { resources: painted.resources };
9892
- const rawName = painted.stencil ? resourceNameOf(name) : name;
9893
- const decode = () => ccittImageObjectOf(ctx.ourDoc, ctx.file, scope, name, IMAGE_KIND.GRAYSCALE_1BPP) ?? jpegImageObjectOf(ctx.ourDoc, scope, name, { rgb: IMAGE_KIND.RGB_24BPP, rgba: IMAGE_KIND.RGBA_32BPP }) ?? flateImageObjectOf(ctx.ourDoc, scope, name, { rgb: IMAGE_KIND.RGB_24BPP, rgba: IMAGE_KIND.RGBA_32BPP });
9894
- const stream = ctx.ourDoc.resolve(ctx.ourDoc.dictOf(painted.resources?.get("XObject"))?.get(rawName));
9895
- if (stream?.kind !== "stream") {
9896
- refusals.set(name, "absent");
9897
- continue;
9898
- }
9899
- const image = painted.stencil ? stencilImageObjectOf(ctx.ourDoc, scope, rawName, { rgba: IMAGE_KIND.RGBA_32BPP }, painted.colour) : documentCacheOf(ctx.ourDoc).getOrCompute(
9900
- PICTURE,
9901
- stream,
9902
- // Never read `.data` here: on a JPEG it is a lazy accessor that decodes on first read, and the cache asks the
9903
- // size on every insertion. The size follows the kind, not an average: four bytes per pixel would charge a
9904
- // 1-bit CCITT page thirty-two times its size, past the cache ceiling, so it would never be kept.
9905
- (decodedImage) => decodedImage === void 0 ? 0 : cachedPictureBytes(decodedImage),
9906
- decode
9907
- );
9908
- if (image === void 0) refusals.set(name, pictureRefusalOf(ctx.ourDoc, stream.dict));
9909
- else decoded.set(name, image);
9970
+ const read = partOrAbsent(() => pictureOf(ctx, name, painted));
9971
+ if (read === void 0) refusals.set(name, "shape");
9972
+ else if ("image" in read) decoded.set(name, read.image);
9973
+ else refusals.set(name, read.refusal);
9910
9974
  }
9911
9975
  return { decoded, refusals };
9912
9976
  }
9977
+ function pictureOf(ctx, name, painted) {
9978
+ const scope = { resources: painted.resources };
9979
+ const rawName = painted.stencil ? resourceNameOf(name) : name;
9980
+ const decode = () => ccittImageObjectOf(ctx.ourDoc, scope, name, IMAGE_KIND.GRAYSCALE_1BPP) ?? jpegImageObjectOf(ctx.ourDoc, scope, name, { rgb: IMAGE_KIND.RGB_24BPP, rgba: IMAGE_KIND.RGBA_32BPP }) ?? flateImageObjectOf(ctx.ourDoc, scope, name, { rgb: IMAGE_KIND.RGB_24BPP, rgba: IMAGE_KIND.RGBA_32BPP });
9981
+ const stream = ctx.ourDoc.resolve(ctx.ourDoc.dictOf(painted.resources?.get("XObject"))?.get(rawName));
9982
+ if (stream?.kind !== "stream") return { refusal: "absent" };
9983
+ const image = painted.stencil ? stencilImageObjectOf(ctx.ourDoc, scope, rawName, { rgba: IMAGE_KIND.RGBA_32BPP }, painted.colour) : documentCacheOf(ctx.ourDoc).getOrCompute(
9984
+ PICTURE,
9985
+ stream,
9986
+ // Never read `.data` here: on a JPEG it is a lazy accessor that decodes on first read, and the cache asks the
9987
+ // size on every insertion. The size follows the kind, not an average: four bytes per pixel would charge a
9988
+ // 1-bit CCITT page thirty-two times its size, past the cache ceiling, so it would never be kept.
9989
+ (decodedImage) => decodedImage === void 0 ? 0 : cachedPictureBytes(decodedImage),
9990
+ decode
9991
+ );
9992
+ return image === void 0 ? { refusal: pictureRefusalOf(ctx.ourDoc, stream.dict) } : { image };
9993
+ }
9913
9994
  function scanHiddenCandidates(ops) {
9914
9995
  let candidate = false;
9915
9996
  let namesLayer = false;
@@ -9956,6 +10037,7 @@ function readPageText(ctx, pageIndex) {
9956
10037
  if (ops.length > PDF_MAX_OPS_PER_PAGE)
9957
10038
  throw new ReaderError4("FILE_UNSAFE", "the PDF has a page with too many drawing operations to be read");
9958
10039
  count(ctx.cost, "operatorsWalked", ops.length);
10040
+ const unreadObjects = ops.filter((op) => op.op === UNREADABLE_XOBJECT_OP).length;
9959
10041
  const fonts = fontObjectsOfPage(ctx.ourDoc, entry);
9960
10042
  const ourFont = (name) => fonts.get(name);
9961
10043
  const symbolVerdict = (name) => {
@@ -9992,46 +10074,11 @@ function readPageText(ctx, pageIndex) {
9992
10074
  glyphs: ctx.keepGlyphs ? glyphs : [],
9993
10075
  ...glyphsUnavailable !== void 0 ? { glyphsUnavailable } : {},
9994
10076
  ...fontUnread ? { fontUnread: true } : {},
10077
+ ...unreadObjects > 0 ? { unreadObjects } : {},
9995
10078
  runs,
9996
10079
  reference
9997
10080
  };
9998
10081
  }
9999
- var REFUSAL_IS_BOUND = {
10000
- syntax: false,
10001
- truncated: false,
10002
- "nesting-too-deep": true,
10003
- "token-too-long": true,
10004
- "string-too-long": true,
10005
- "stream-length": false,
10006
- "stream-end": false,
10007
- "length-unresolved": false,
10008
- "startxref-missing": false,
10009
- "xref-offset": false,
10010
- "xref-syntax": false,
10011
- "xref-chain": false,
10012
- "xref-too-large": true,
10013
- "filter-unsupported": false,
10014
- predictor: false,
10015
- "stream-decode": false,
10016
- "object-stream": false,
10017
- "xref-stream": false,
10018
- "xref-stale": false,
10019
- "ref-hops": true,
10020
- "page-tree": false,
10021
- "page-box": false,
10022
- "content-syntax": false,
10023
- "content-operands": false,
10024
- "content-too-long": true,
10025
- "inline-image": false,
10026
- encrypted: false,
10027
- "to-unicode": false,
10028
- "value-too-large": true,
10029
- "document-too-large": true,
10030
- "glyphs-too-many": true,
10031
- "forms-too-many": true,
10032
- "font-tables-too-many": true,
10033
- "page-missing": false
10034
- };
10035
10082
  function textUnreadReasonOf(error) {
10036
10083
  if (error instanceof GlyphBuilderAbstention) return "unsupported";
10037
10084
  if (error instanceof PdfObjectsRefusal) return REFUSAL_IS_BOUND[error.reason] ? "limit" : "damaged";
@@ -10098,6 +10145,7 @@ function readPageSource(text, pageIndex, wants, ctx) {
10098
10145
  glyphs,
10099
10146
  ...text.glyphsUnavailable !== void 0 ? { glyphsUnavailable: text.glyphsUnavailable } : {},
10100
10147
  ...text.fontUnread === true ? { fontUnread: true } : {},
10148
+ ...text.unreadObjects !== void 0 ? { unreadObjects: text.unreadObjects } : {},
10101
10149
  ...declaredOrder.length > 0 ? { declaredOrder: hoistAgainstTree(declaredOrder, runs) } : {},
10102
10150
  ...noteIds.size > 0 ? { noteIds } : {},
10103
10151
  reference,
@@ -10125,7 +10173,7 @@ async function readPdfSource(bytes, options = {}) {
10125
10173
  const ours = openOrRefuse(bytes);
10126
10174
  const pageCount = ours.document.pages().length;
10127
10175
  onOpen?.(pageCount);
10128
- const info = documentInfoOf(ours.document, bytes);
10176
+ const info = partOrAbsent(() => documentInfoOf(ours.document, bytes));
10129
10177
  const outline = outlineOfDocument(ours.document);
10130
10178
  let layerConfig;
10131
10179
  let layersRead = false;
@@ -10156,7 +10204,12 @@ async function readPdfSource(bytes, options = {}) {
10156
10204
  text.glyphs = [];
10157
10205
  return page;
10158
10206
  });
10159
- return { pages, document: ours.document, info, ...outline !== void 0 ? { outline } : {} };
10207
+ return {
10208
+ pages,
10209
+ document: ours.document,
10210
+ ...info !== void 0 ? { info } : {},
10211
+ ...outline !== void 0 ? { outline } : {}
10212
+ };
10160
10213
  }
10161
10214
 
10162
10215
  // src/extractor/pdf-model.ts
@@ -10716,6 +10769,9 @@ async function detectPdfPageSignals(bytes, partage, cost) {
10716
10769
  boxesByPage
10717
10770
  };
10718
10771
  }
10772
+ async function detectPdfTableGrids(bytes) {
10773
+ return (await detectPdfPageSignals(bytes)).grids;
10774
+ }
10719
10775
 
10720
10776
  // src/extractor/pdf-open.ts
10721
10777
  var openPdfSource = async (bytes, cost, pageLimit = NO_CAP, firstPages) => {
@@ -10729,7 +10785,7 @@ var openPdfSource = async (bytes, cost, pageLimit = NO_CAP, firstPages) => {
10729
10785
  // THE CEILING IS APPLIED BEFORE A SINGLE PAGE IS READ. A
10730
10786
  // refused document therefore pays for no extraction — that is the whole point
10731
10787
  // of a volume guard. The ceiling is the CALLER's (`pageLimit`, `NO_CAP` when it
10732
- // asked for none): see `core/document-caps.ts#DOCUMENT_PAGE_LIMIT` for the
10788
+ // asked for none): see the application's `DOCUMENT_PAGE_LIMIT` for the
10733
10789
  // product's value and for why detection can NOT be done on the file size.
10734
10790
  onOpen: (pageCount) => {
10735
10791
  if (firstPages !== void 0) return;
@@ -12791,7 +12847,12 @@ var segmentsInDeclaredOrder = (allSegments, rankOf) => {
12791
12847
  };
12792
12848
 
12793
12849
  // src/extractor/pdf-page-plan.ts
12794
- var isCapOfColumn = (cap, line, inks) => isDropCap(cap, line) && inks.some((ink) => ink !== void 0 && ink.size * MIN_DROP_CAP_RATIO <= cap.fontSize);
12850
+ var isCapOfColumn = (cap, line, smallestInk) => isDropCap(cap, line) && smallestInk * MIN_DROP_CAP_RATIO <= cap.fontSize;
12851
+ var smallestInkOf = (inks) => {
12852
+ let smallest = Number.POSITIVE_INFINITY;
12853
+ for (const ink of inks) if (ink !== void 0 && ink.size < smallest) smallest = ink.size;
12854
+ return smallest;
12855
+ };
12795
12856
  var capTarget = (cap, line, lineIndex, inks) => {
12796
12857
  const seated = line.some(
12797
12858
  (it) => it !== cap && it.text.trim() !== "" && it.fontSize * MIN_DROP_CAP_RATIO <= cap.fontSize
@@ -12802,9 +12863,10 @@ var capTarget = (cap, line, lineIndex, inks) => {
12802
12863
  };
12803
12864
  var capsOfColumn = (lines, inks) => {
12804
12865
  const found = [];
12866
+ const smallestInk = smallestInkOf(inks);
12805
12867
  for (const [lineIndex, line] of lines.entries()) {
12806
12868
  for (const cap of line) {
12807
- if (isCapOfColumn(cap, line, inks))
12869
+ if (isCapOfColumn(cap, line, smallestInk))
12808
12870
  found.push({ cap, from: lineIndex, to: capTarget(cap, line, lineIndex, inks) });
12809
12871
  }
12810
12872
  }
@@ -13122,6 +13184,7 @@ var figureOf = (anchor, lines, toBlocks) => {
13122
13184
  };
13123
13185
  };
13124
13186
  var asideFigures = (items, anchors, toBlocks) => {
13187
+ if (anchors.length === 0) return { figures: [], taken: /* @__PURE__ */ new Set() };
13125
13188
  const lines = visualLines(items);
13126
13189
  const taken = /* @__PURE__ */ new Set();
13127
13190
  const figures = [];
@@ -14578,6 +14641,15 @@ function pdfTextUnreadNotices(unreadByPage, replaced) {
14578
14641
  }
14579
14642
  return notices.length > 0 ? notices : void 0;
14580
14643
  }
14644
+ function pdfPartUnreadNotices(unreadByPage, replaced) {
14645
+ const kept = [...unreadByPage].filter(([pageIndex, count3]) => count3 > 0 && !replaced.has(pageIndex));
14646
+ if (kept.length === 0) return void 0;
14647
+ const pages = kept.map(([pageIndex]) => pageIndex).sort((left, right) => left - right);
14648
+ const ranges = pageRangesOf(pages).slice(0, MAX_NOTICE_PAGE_RANGES);
14649
+ const shown = ranges.reduce((sum, range) => sum + range.to - range.from + 1, 0);
14650
+ const count2 = kept.reduce((sum, [, objects]) => sum + objects, 0);
14651
+ return [{ kind: "pdf-part-unread", count: count2, pages: ranges, more: pages.length - shown }];
14652
+ }
14581
14653
  var enrichRuns = (source, readItems, glyphsByPage) => {
14582
14654
  const originalOf = /* @__PURE__ */ new Map();
14583
14655
  const items = readItems.map((runs, pageIndex) => {
@@ -14673,7 +14745,7 @@ var pageLayoutReader = (doc, pageIndex, pageItems, lostImageCounts, pagePlans) =
14673
14745
  top: c.yTop
14674
14746
  }));
14675
14747
  const planner = pagePlanReader(cut);
14676
- pagePlans.set(pageIndex, planner.plan);
14748
+ pagePlans?.set(pageIndex, planner.plan);
14677
14749
  laid = {
14678
14750
  ...markers,
14679
14751
  wordWidthAt: firstWordWidthReader(glyphsByPage[pageIndex]),
@@ -14693,10 +14765,10 @@ var pageLayoutReader = (doc, pageIndex, pageItems, lostImageCounts, pagePlans) =
14693
14765
  };
14694
14766
  };
14695
14767
  var reportPagePlans = (plans, onPagePlan) => {
14696
- if (onPagePlan === void 0) return;
14768
+ if (onPagePlan === void 0 || plans === void 0) return;
14697
14769
  for (const [pageIndex, plan] of [...plans].sort((a, b) => a[0] - b[0])) onPagePlan(pageIndex, plan);
14698
14770
  };
14699
- var layoutPages = (doc) => {
14771
+ var layoutPages = (doc, keepPlans) => {
14700
14772
  const { items, glyphsByPage, sourceRun, detected, bandsByPage, scale, source, declaredRankByPage } = doc;
14701
14773
  const pages = [];
14702
14774
  const scannedPageIndices = [];
@@ -14705,7 +14777,7 @@ var layoutPages = (doc) => {
14705
14777
  const lostImageCounts = /* @__PURE__ */ new Map();
14706
14778
  const tableBandsByPage = /* @__PURE__ */ new Map();
14707
14779
  const flattenedGridPages = [];
14708
- const pagePlans = /* @__PURE__ */ new Map();
14780
+ const pagePlans = keepPlans ? /* @__PURE__ */ new Map() : void 0;
14709
14781
  for (const [pageIndex, rawItems] of items.entries()) {
14710
14782
  const pageItems = rawItems;
14711
14783
  const keptGlyphs = glyphsByPage[pageIndex];
@@ -14797,6 +14869,10 @@ var assembleResult = (doc, laid, readItems, limits, pageLanguage) => {
14797
14869
  if (reason !== void 0) textUnreadByPage.set(pageIndex, reason);
14798
14870
  });
14799
14871
  const textUnreadNotices = pdfTextUnreadNotices(textUnreadByPage, /* @__PURE__ */ new Set());
14872
+ const unreadObjectsByPage = /* @__PURE__ */ new Map();
14873
+ source.pages.forEach((page, pageIndex) => {
14874
+ if (page.unreadObjects !== void 0) unreadObjectsByPage.set(pageIndex, page.unreadObjects);
14875
+ });
14800
14876
  let tablesWithheld = 0;
14801
14877
  const published = merged2.map((page, pageIndex) => {
14802
14878
  const { blocks, withheld } = withholdOversizedTables(
@@ -14813,6 +14889,7 @@ var assembleResult = (doc, laid, readItems, limits, pageLanguage) => {
14813
14889
  const notices = [
14814
14890
  ...imageNotices ?? [],
14815
14891
  ...textUnreadNotices ?? [],
14892
+ ...pdfPartUnreadNotices(unreadObjectsByPage, /* @__PURE__ */ new Set()) ?? [],
14816
14893
  ...unpublishedPartNotices({ chartsWithheld: 0, imagesMissing: 0, tablesWithheld })
14817
14894
  ];
14818
14895
  return {
@@ -14820,6 +14897,7 @@ var assembleResult = (doc, laid, readItems, limits, pageLanguage) => {
14820
14897
  ...notices.length > 0 ? { notices } : {},
14821
14898
  imageLossByPage,
14822
14899
  textUnreadByPage,
14900
+ unreadObjectsByPage,
14823
14901
  ...publishedImages.length > 0 ? { images: publishedImages, pagesOfImage: images.pagesOfImage } : {},
14824
14902
  scannedPageIndices,
14825
14903
  flattenedGridPages: laid.flattenedGridPages,
@@ -14881,7 +14959,7 @@ var extractPdf = async (bytes, pageLanguage = "en", opts) => {
14881
14959
  framed: opts?.framed ?? DEFAULT_FRAMED_BLOCKS,
14882
14960
  bandLayout: opts?.bands ?? DEFAULT_BAND_LAYOUT
14883
14961
  };
14884
- const laid = layoutPages(doc);
14962
+ const laid = layoutPages(doc, opts?.onPagePlan !== void 0);
14885
14963
  reportPagePlans(laid.pagePlans, opts?.onPagePlan);
14886
14964
  return assembleResult(doc, laid, readItems, opts?.limits, pageLanguage);
14887
14965
  };
@@ -14904,6 +14982,7 @@ export {
14904
14982
  PRODUCER_MAX_CHARS,
14905
14983
  PdfObjectsRefusal,
14906
14984
  detectLanguageFromSample,
14985
+ detectPdfTableGrids,
14907
14986
  extractPdf as extractPdfPages,
14908
14987
  openEmbeddedImages,
14909
14988
  openPdfObjects,