dislop 0.7.1 → 0.8.1
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/.claude-plugin/marketplace.json +3 -3
- package/.claude-plugin/plugin.json +2 -2
- package/.codex-plugin/plugin.json +4 -3
- package/.cursor-plugin/plugin.json +3 -2
- package/PRODUCT.md +18 -4
- package/README.md +72 -38
- package/README.zh-CN.md +70 -40
- package/bin/dislop.mjs +2883 -309
- package/gemini-extension.json +2 -2
- package/package.json +19 -3
- package/packs/business-brief/pack.json +336 -6
- package/packs/core/pack.json +14 -7
- package/packs/deck-and-ui/pack.json +255 -6
- package/packs/literary-essay/pack.json +20 -0
- package/patterns/ai-tic-rubric.json +252 -0
- package/patterns/banks/composite-fusion.json +13 -1
- package/patterns/banks/lexical-signals.json +20 -2
- package/patterns/banks/syntactic-frames.json +10 -3
- package/patterns/banks/visual-deck.json +7 -0
- package/patterns/dimensions/discourse.json +26 -0
- package/patterns/dimensions/lexical.json +26 -0
- package/patterns/dimensions/rhythm.json +52 -0
- package/patterns/dimensions/visual-and-deck.json +209 -1
- package/plugin.json +4 -3
- package/server.json +2 -2
- package/skills/dislop/SKILL.md +35 -41
- package/skills/dislop/agents/openai.yaml +1 -1
- package/skills/dislop/references/essay.md +24 -0
- package/skills/dislop/references/essay.zh-CN.md +24 -0
- package/skills/dislop/references/office.md +23 -0
- package/skills/dislop/references/office.zh-CN.md +23 -0
- package/skills/dislop/references/web-ui.md +24 -0
- package/skills/dislop/references/web-ui.zh-CN.md +24 -0
- package/skills/dislop/references/work-docs.md +25 -0
- package/skills/dislop/references/work-docs.zh-CN.md +24 -0
- package/src/binary-node.mjs +1716 -1
- package/src/core.mjs +3215 -247
- package/src/local-model.mjs +31 -11
- package/src/pattern-engine.mjs +174 -24
- package/src/pocket-model.mjs +27 -5
- package/src/review-client.mjs +1064 -0
- package/skills/dislop/references/business-and-rfc.md +0 -26
- package/skills/dislop/references/editorial-and-essay.md +0 -20
- package/skills/dislop/references/regulated-and-precision.md +0 -27
- package/skills/dislop/references/web-ui-and-deck.md +0 -26
package/src/binary-node.mjs
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
import { inflateRawSync } from "node:zlib";
|
|
1
|
+
import { inflateRawSync, inflateSync } from "node:zlib";
|
|
2
2
|
|
|
3
3
|
const MAX_ZIP_ENTRIES = 3000;
|
|
4
4
|
const MAX_UNCOMPRESSED_BYTES = 120 * 1024 * 1024; // 120 MB zip-bomb ceiling
|
|
5
|
+
const MAX_STREAM_UNCOMPRESSED_BYTES = 32 * 1024 * 1024; // 32 MB zlib stream ceiling
|
|
6
|
+
const MAX_PNG_PIXELS = 16_000_000;
|
|
5
7
|
|
|
6
8
|
/**
|
|
7
9
|
* Pure Node.js standard-library ZIP reader for OOXML (`.docx`, `.pptx`).
|
|
@@ -83,3 +85,1716 @@ export function readZipXmlEntries(buffer) {
|
|
|
83
85
|
|
|
84
86
|
return entries;
|
|
85
87
|
}
|
|
88
|
+
|
|
89
|
+
// ---------- Shared Color & Math Helpers (100% parity with Python) ----------
|
|
90
|
+
|
|
91
|
+
function rgbToHslNormalized(r, g, b) {
|
|
92
|
+
const rn = r / 255;
|
|
93
|
+
const gn = g / 255;
|
|
94
|
+
const bn = b / 255;
|
|
95
|
+
const max = Math.max(rn, gn, bn);
|
|
96
|
+
const min = Math.min(rn, gn, bn);
|
|
97
|
+
const l = (max + min) / 2;
|
|
98
|
+
if (max === min) return [0, 0, l];
|
|
99
|
+
const d = max - min;
|
|
100
|
+
const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
|
101
|
+
let h = 0;
|
|
102
|
+
if (max === rn) h = (gn - bn) / d + (gn < bn ? 6 : 0);
|
|
103
|
+
else if (max === gn) h = (bn - rn) / d + 2;
|
|
104
|
+
else h = (rn - gn) / d + 4;
|
|
105
|
+
return [h * 60, s, l];
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function paethPredictor(a, b, c) {
|
|
109
|
+
const p = a + b - c;
|
|
110
|
+
const pa = Math.abs(p - a);
|
|
111
|
+
const pb = Math.abs(p - b);
|
|
112
|
+
const pc = Math.abs(p - c);
|
|
113
|
+
if (pa <= pb && pa <= pc) return a;
|
|
114
|
+
if (pb <= pc) return b;
|
|
115
|
+
return c;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function round4(v) {
|
|
119
|
+
return Math.round(v * 10000) / 10000;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function computePixelMetrics(width, height, getRgba) {
|
|
123
|
+
const stepX = Math.max(1, Math.floor(width / 160));
|
|
124
|
+
const stepY = Math.max(1, Math.floor(height / 160));
|
|
125
|
+
const startX = width >= 3 ? 1 : 0;
|
|
126
|
+
const endX = width >= 3 ? width - 1 : width;
|
|
127
|
+
const startY = height >= 3 ? 1 : 0;
|
|
128
|
+
const endY = height >= 3 ? height - 1 : height;
|
|
129
|
+
|
|
130
|
+
let opaquePixels = 0;
|
|
131
|
+
let neonPurpleCount = 0;
|
|
132
|
+
let neonCyanCount = 0;
|
|
133
|
+
let darkBgCount = 0;
|
|
134
|
+
let highSatCount = 0;
|
|
135
|
+
let smoothHighSatCount = 0;
|
|
136
|
+
let neutralCount = 0;
|
|
137
|
+
const quantized = new Set();
|
|
138
|
+
|
|
139
|
+
for (let y = startY; y < endY; y += stepY) {
|
|
140
|
+
for (let x = startX; x < endX; x += stepX) {
|
|
141
|
+
const [r, g, b, a] = getRgba(x, y);
|
|
142
|
+
if (a < 32) continue;
|
|
143
|
+
opaquePixels += 1;
|
|
144
|
+
quantized.add(((r >> 4) << 8) | ((g >> 4) << 4) | (b >> 4));
|
|
145
|
+
const [h, s, l] = rgbToHslNormalized(r, g, b);
|
|
146
|
+
if (l <= 0.14) darkBgCount += 1;
|
|
147
|
+
if (s <= 0.12) neutralCount += 1;
|
|
148
|
+
if (s >= 0.40 && l >= 0.15 && l <= 0.85 && h >= 235 && h <= 335) {
|
|
149
|
+
neonPurpleCount += 1;
|
|
150
|
+
}
|
|
151
|
+
if (s >= 0.45 && l >= 0.25 && l <= 0.80 && h >= 175 && h <= 210) {
|
|
152
|
+
neonCyanCount += 1;
|
|
153
|
+
}
|
|
154
|
+
if (s >= 0.78 && l >= 0.20 && l <= 0.85) {
|
|
155
|
+
highSatCount += 1;
|
|
156
|
+
const left = getRgba(Math.max(0, x - 1), y);
|
|
157
|
+
const right = getRgba(Math.min(width - 1, x + 1), y);
|
|
158
|
+
const up = getRgba(x, Math.max(0, y - 1));
|
|
159
|
+
const down = getRgba(x, Math.min(height - 1, y + 1));
|
|
160
|
+
const diffSum =
|
|
161
|
+
Math.abs(r - left[0]) + Math.abs(g - left[1]) + Math.abs(b - left[2]) +
|
|
162
|
+
Math.abs(r - right[0]) + Math.abs(g - right[1]) + Math.abs(b - right[2]) +
|
|
163
|
+
Math.abs(r - up[0]) + Math.abs(g - up[1]) + Math.abs(b - up[2]) +
|
|
164
|
+
Math.abs(r - down[0]) + Math.abs(g - down[1]) + Math.abs(b - down[2]);
|
|
165
|
+
if (diffSum / 4 < 18) {
|
|
166
|
+
smoothHighSatCount += 1;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
if (opaquePixels === 0) return null;
|
|
173
|
+
return {
|
|
174
|
+
sampledPixels: opaquePixels,
|
|
175
|
+
neonPurpleRatio: round4(neonPurpleCount / opaquePixels),
|
|
176
|
+
neonCyanRatio: round4(neonCyanCount / opaquePixels),
|
|
177
|
+
darkBgRatio: round4(darkBgCount / opaquePixels),
|
|
178
|
+
highSatRatio: round4(highSatCount / opaquePixels),
|
|
179
|
+
smoothHighSatRatio: highSatCount > 0 ? round4(smoothHighSatCount / highSatCount) : 0,
|
|
180
|
+
neutralRatio: round4(neutralCount / opaquePixels),
|
|
181
|
+
quantizedColors: quantized.size,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function decodePngScanlinesAndMetrics(idatChunks, width, height, bitDepth, colorType, interlace, palette) {
|
|
186
|
+
if (interlace !== 0 || bitDepth !== 8 || width <= 0 || height <= 0 || width * height > MAX_PNG_PIXELS) {
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
const bppMap = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 };
|
|
190
|
+
const bpp = bppMap[colorType];
|
|
191
|
+
if (!bpp) return null;
|
|
192
|
+
if (colorType === 3 && (!palette || palette.length === 0)) return null;
|
|
193
|
+
|
|
194
|
+
const compressed = Buffer.concat(idatChunks);
|
|
195
|
+
if (compressed.length === 0) return null;
|
|
196
|
+
|
|
197
|
+
let raw;
|
|
198
|
+
try {
|
|
199
|
+
raw = inflateSync(compressed, { maxOutputLength: MAX_STREAM_UNCOMPRESSED_BYTES });
|
|
200
|
+
} catch {
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const stride = width * bpp;
|
|
205
|
+
const expected = height * (1 + stride);
|
|
206
|
+
if (raw.length < expected) return null;
|
|
207
|
+
|
|
208
|
+
// Unfilter all scanlines into flat buffer to allow exact 4-neighbor lookups on sampled grid
|
|
209
|
+
const pixels = new Uint8Array(height * stride);
|
|
210
|
+
for (let y = 0; y < height; y += 1) {
|
|
211
|
+
const rowIn = y * (1 + stride);
|
|
212
|
+
const filterType = raw[rowIn];
|
|
213
|
+
const rowOut = y * stride;
|
|
214
|
+
const prevOut = (y - 1) * stride;
|
|
215
|
+
for (let x = 0; x < stride; x += 1) {
|
|
216
|
+
const filt = raw[rowIn + 1 + x];
|
|
217
|
+
const a = x >= bpp ? pixels[rowOut + x - bpp] : 0;
|
|
218
|
+
const b = y > 0 ? pixels[prevOut + x] : 0;
|
|
219
|
+
const c = y > 0 && x >= bpp ? pixels[prevOut + x - bpp] : 0;
|
|
220
|
+
let val = filt;
|
|
221
|
+
if (filterType === 1) val = (filt + a) & 0xff;
|
|
222
|
+
else if (filterType === 2) val = (filt + b) & 0xff;
|
|
223
|
+
else if (filterType === 3) val = (filt + ((a + b) >> 1)) & 0xff;
|
|
224
|
+
else if (filterType === 4) val = (filt + paethPredictor(a, b, c)) & 0xff;
|
|
225
|
+
pixels[rowOut + x] = val;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function getRgba(x, y) {
|
|
230
|
+
const off = y * stride + x * bpp;
|
|
231
|
+
if (colorType === 2) return [pixels[off], pixels[off + 1], pixels[off + 2], 255];
|
|
232
|
+
if (colorType === 6) return [pixels[off], pixels[off + 1], pixels[off + 2], pixels[off + 3]];
|
|
233
|
+
if (colorType === 0) {
|
|
234
|
+
const g = pixels[off];
|
|
235
|
+
return [g, g, g, 255];
|
|
236
|
+
}
|
|
237
|
+
if (colorType === 4) {
|
|
238
|
+
const g = pixels[off];
|
|
239
|
+
return [g, g, g, pixels[off + 1]];
|
|
240
|
+
}
|
|
241
|
+
const idx = pixels[off];
|
|
242
|
+
const pal = palette[idx] || [0, 0, 0];
|
|
243
|
+
return [pal[0], pal[1], pal[2], 255];
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
return computePixelMetrics(width, height, getRgba);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function decodeGifLzw(lzwBytes, minCodeSize, expectedLen) {
|
|
250
|
+
if (minCodeSize < 1 || minCodeSize > 8 || expectedLen <= 0) return null;
|
|
251
|
+
const clearCode = 1 << minCodeSize;
|
|
252
|
+
const eoiCode = clearCode + 1;
|
|
253
|
+
const prefixes = new Int32Array(4096);
|
|
254
|
+
const suffixes = new Uint8Array(4096);
|
|
255
|
+
const firstChars = new Uint8Array(4096);
|
|
256
|
+
const stack = new Uint8Array(4096);
|
|
257
|
+
const out = new Uint8Array(expectedLen);
|
|
258
|
+
|
|
259
|
+
let codeSize = minCodeSize + 1;
|
|
260
|
+
let nextCode = eoiCode + 1;
|
|
261
|
+
let prevCode = -1;
|
|
262
|
+
let outPos = 0;
|
|
263
|
+
|
|
264
|
+
let bitBuf = 0;
|
|
265
|
+
let bitCount = 0;
|
|
266
|
+
let bytePos = 0;
|
|
267
|
+
|
|
268
|
+
function readCode() {
|
|
269
|
+
while (bitCount < codeSize && bytePos < lzwBytes.length) {
|
|
270
|
+
bitBuf |= lzwBytes[bytePos] << bitCount;
|
|
271
|
+
bitCount += 8;
|
|
272
|
+
bytePos += 1;
|
|
273
|
+
}
|
|
274
|
+
if (bitCount < codeSize) return -1;
|
|
275
|
+
const code = bitBuf & ((1 << codeSize) - 1);
|
|
276
|
+
bitBuf >>= codeSize;
|
|
277
|
+
bitCount -= codeSize;
|
|
278
|
+
return code;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function resetTable() {
|
|
282
|
+
for (let i = 0; i < clearCode; i += 1) {
|
|
283
|
+
prefixes[i] = -1;
|
|
284
|
+
suffixes[i] = i;
|
|
285
|
+
firstChars[i] = i;
|
|
286
|
+
}
|
|
287
|
+
codeSize = minCodeSize + 1;
|
|
288
|
+
nextCode = eoiCode + 1;
|
|
289
|
+
prevCode = -1;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
resetTable();
|
|
293
|
+
|
|
294
|
+
while (outPos < expectedLen) {
|
|
295
|
+
const code = readCode();
|
|
296
|
+
if (code < 0 || code === eoiCode) break;
|
|
297
|
+
if (code === clearCode) {
|
|
298
|
+
resetTable();
|
|
299
|
+
continue;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
let inCode = code;
|
|
303
|
+
let stackLen = 0;
|
|
304
|
+
if (code === nextCode) {
|
|
305
|
+
if (prevCode < 0) break;
|
|
306
|
+
stack[stackLen++] = firstChars[prevCode];
|
|
307
|
+
inCode = prevCode;
|
|
308
|
+
} else if (code > nextCode) {
|
|
309
|
+
break;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
let walk = inCode;
|
|
313
|
+
while (walk >= clearCode && stackLen < 4096) {
|
|
314
|
+
stack[stackLen++] = suffixes[walk];
|
|
315
|
+
walk = prefixes[walk];
|
|
316
|
+
}
|
|
317
|
+
if (walk < 0 || stackLen >= 4096) break;
|
|
318
|
+
const baseChar = firstChars[walk];
|
|
319
|
+
stack[stackLen++] = baseChar;
|
|
320
|
+
|
|
321
|
+
for (let i = stackLen - 1; i >= 0 && outPos < expectedLen; i -= 1) {
|
|
322
|
+
out[outPos++] = stack[i];
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
if (prevCode >= 0 && nextCode < 4096) {
|
|
326
|
+
prefixes[nextCode] = prevCode;
|
|
327
|
+
suffixes[nextCode] = baseChar;
|
|
328
|
+
firstChars[nextCode] = firstChars[prevCode];
|
|
329
|
+
nextCode += 1;
|
|
330
|
+
if (nextCode === (1 << codeSize) && codeSize < 12) {
|
|
331
|
+
codeSize += 1;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
prevCode = code;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
return out;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Pure Node.js standard-library binary parser for PNG, JPEG, and WebP images.
|
|
342
|
+
* Extracts container dimensions, embedded workflow/provenance metadata, and PNG pixel heuristics.
|
|
343
|
+
*/
|
|
344
|
+
export function parseImageBuffer(buffer) {
|
|
345
|
+
if (!Buffer.isBuffer(buffer) || buffer.length < 12) {
|
|
346
|
+
throw new Error("Invalid or truncated image buffer");
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
const metadataTexts = [];
|
|
350
|
+
let hasC2pa = false;
|
|
351
|
+
|
|
352
|
+
// 1. PNG
|
|
353
|
+
if (
|
|
354
|
+
buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4e && buffer[3] === 0x47 &&
|
|
355
|
+
buffer[4] === 0x0d && buffer[5] === 0x0a && buffer[6] === 0x1a && buffer[7] === 0x0a
|
|
356
|
+
) {
|
|
357
|
+
let offset = 8;
|
|
358
|
+
let width = 0;
|
|
359
|
+
let height = 0;
|
|
360
|
+
let bitDepth = 0;
|
|
361
|
+
let colorType = 0;
|
|
362
|
+
let interlace = 0;
|
|
363
|
+
let hasIhdr = false;
|
|
364
|
+
let palette = null;
|
|
365
|
+
const idatChunks = [];
|
|
366
|
+
let idatBytes = 0;
|
|
367
|
+
|
|
368
|
+
while (offset + 12 <= buffer.length) {
|
|
369
|
+
const length = buffer.readUInt32BE(offset);
|
|
370
|
+
const type = buffer.subarray(offset + 4, offset + 8).toString("latin1");
|
|
371
|
+
const dataStart = offset + 8;
|
|
372
|
+
const dataEnd = dataStart + length;
|
|
373
|
+
if (dataEnd + 4 > buffer.length) break;
|
|
374
|
+
const data = buffer.subarray(dataStart, dataEnd);
|
|
375
|
+
offset = dataEnd + 4;
|
|
376
|
+
|
|
377
|
+
if (type === "IHDR" && data.length >= 13) {
|
|
378
|
+
hasIhdr = true;
|
|
379
|
+
width = data.readUInt32BE(0);
|
|
380
|
+
height = data.readUInt32BE(4);
|
|
381
|
+
bitDepth = data[8];
|
|
382
|
+
colorType = data[9];
|
|
383
|
+
interlace = data[12];
|
|
384
|
+
} else if (type === "PLTE") {
|
|
385
|
+
palette = [];
|
|
386
|
+
for (let i = 0; i + 2 < data.length; i += 3) {
|
|
387
|
+
palette.push([data[i], data[i + 1], data[i + 2]]);
|
|
388
|
+
}
|
|
389
|
+
} else if (type === "tEXt") {
|
|
390
|
+
const nul = data.indexOf(0);
|
|
391
|
+
if (nul >= 0) {
|
|
392
|
+
const key = data.subarray(0, nul).toString("latin1");
|
|
393
|
+
const value = data.subarray(nul + 1).toString("latin1");
|
|
394
|
+
metadataTexts.push({ key, value });
|
|
395
|
+
}
|
|
396
|
+
} else if (type === "zTXt") {
|
|
397
|
+
const nul = data.indexOf(0);
|
|
398
|
+
if (nul >= 0 && nul + 2 <= data.length) {
|
|
399
|
+
const key = data.subarray(0, nul).toString("latin1");
|
|
400
|
+
const method = data[nul + 1];
|
|
401
|
+
if (method === 0) {
|
|
402
|
+
try {
|
|
403
|
+
const value = inflateSync(data.subarray(nul + 2), { maxOutputLength: 4 * 1024 * 1024 }).toString("utf8");
|
|
404
|
+
metadataTexts.push({ key, value });
|
|
405
|
+
} catch {}
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
} else if (type === "iTXt") {
|
|
409
|
+
const nul1 = data.indexOf(0);
|
|
410
|
+
if (nul1 >= 0 && nul1 + 3 <= data.length) {
|
|
411
|
+
const key = data.subarray(0, nul1).toString("latin1");
|
|
412
|
+
const compFlag = data[nul1 + 1];
|
|
413
|
+
const compMethod = data[nul1 + 2];
|
|
414
|
+
const nul2 = data.indexOf(0, nul1 + 3);
|
|
415
|
+
const nul3 = nul2 >= 0 ? data.indexOf(0, nul2 + 1) : -1;
|
|
416
|
+
if (nul3 >= 0) {
|
|
417
|
+
const payload = data.subarray(nul3 + 1);
|
|
418
|
+
try {
|
|
419
|
+
const value =
|
|
420
|
+
compFlag === 1 && compMethod === 0
|
|
421
|
+
? inflateSync(payload, { maxOutputLength: 4 * 1024 * 1024 }).toString("utf8")
|
|
422
|
+
: payload.toString("utf8");
|
|
423
|
+
metadataTexts.push({ key, value });
|
|
424
|
+
} catch {}
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
} else if (type === "eXIf") {
|
|
428
|
+
metadataTexts.push({ key: "exif", value: data.toString("latin1").replace(/\x00+/g, " ") });
|
|
429
|
+
} else if (type === "caBX") {
|
|
430
|
+
hasC2pa = true;
|
|
431
|
+
metadataTexts.push({ key: "c2pa", value: data.toString("latin1").replace(/\x00+/g, " ") });
|
|
432
|
+
} else if (type === "IDAT") {
|
|
433
|
+
idatBytes += data.length;
|
|
434
|
+
if (idatBytes <= 24 * 1024 * 1024) {
|
|
435
|
+
idatChunks.push(data);
|
|
436
|
+
}
|
|
437
|
+
} else if (type === "IEND") {
|
|
438
|
+
break;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
if (!hasIhdr || width <= 0 || height <= 0) {
|
|
443
|
+
throw new Error("Invalid PNG missing valid IHDR chunk");
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
for (const m of metadataTexts) {
|
|
447
|
+
if (/(?:c2pa|trainedAlgorithmicMedia|jumbf)/i.test(`${m.key} ${m.value}`)) {
|
|
448
|
+
hasC2pa = true;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
const pixelMetrics = decodePngScanlinesAndMetrics(
|
|
453
|
+
idatChunks,
|
|
454
|
+
width,
|
|
455
|
+
height,
|
|
456
|
+
bitDepth,
|
|
457
|
+
colorType,
|
|
458
|
+
interlace,
|
|
459
|
+
palette
|
|
460
|
+
);
|
|
461
|
+
|
|
462
|
+
return { format: "png", width, height, metadataTexts, hasC2pa, pixelMetrics };
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// 2. JPEG
|
|
466
|
+
if (buffer[0] === 0xff && buffer[1] === 0xd8) {
|
|
467
|
+
let pos = 2;
|
|
468
|
+
let width = 0;
|
|
469
|
+
let height = 0;
|
|
470
|
+
while (pos < buffer.length) {
|
|
471
|
+
while (pos < buffer.length && buffer[pos] === 0xff) pos += 1;
|
|
472
|
+
if (pos >= buffer.length) break;
|
|
473
|
+
const marker = buffer[pos];
|
|
474
|
+
pos += 1;
|
|
475
|
+
if (marker === 0xd9 || marker === 0xda) break;
|
|
476
|
+
if (marker === 0x00 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) continue;
|
|
477
|
+
if (pos + 2 > buffer.length) break;
|
|
478
|
+
const segLen = buffer.readUInt16BE(pos);
|
|
479
|
+
if (segLen < 2 || pos + segLen > buffer.length) break;
|
|
480
|
+
const payload = buffer.subarray(pos + 2, pos + segLen);
|
|
481
|
+
pos += segLen;
|
|
482
|
+
|
|
483
|
+
if ((marker === 0xc0 || marker === 0xc1 || marker === 0xc2) && payload.length >= 5) {
|
|
484
|
+
height = payload.readUInt16BE(1);
|
|
485
|
+
width = payload.readUInt16BE(3);
|
|
486
|
+
} else if (marker === 0xe1) {
|
|
487
|
+
const s = payload.toString("latin1");
|
|
488
|
+
if (s.startsWith("http://ns.adobe.com/xap/1.0/\x00")) {
|
|
489
|
+
metadataTexts.push({ key: "xmp", value: payload.subarray(29).toString("utf8") });
|
|
490
|
+
} else if (s.startsWith("Exif\x00\x00")) {
|
|
491
|
+
metadataTexts.push({ key: "exif", value: s.slice(6).replace(/\x00+/g, " ") });
|
|
492
|
+
}
|
|
493
|
+
} else if (marker === 0xeb) {
|
|
494
|
+
const s = payload.toString("latin1").replace(/\x00+/g, " ");
|
|
495
|
+
if (/c2pa|jumb/i.test(s)) {
|
|
496
|
+
hasC2pa = true;
|
|
497
|
+
metadataTexts.push({ key: "c2pa", value: s });
|
|
498
|
+
}
|
|
499
|
+
} else if (marker === 0xfe) {
|
|
500
|
+
metadataTexts.push({ key: "comment", value: payload.toString("utf8") });
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
for (const m of metadataTexts) {
|
|
505
|
+
if (/(?:c2pa|trainedAlgorithmicMedia|jumbf)/i.test(`${m.key} ${m.value}`)) {
|
|
506
|
+
hasC2pa = true;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
return { format: "jpeg", width, height, metadataTexts, hasC2pa, pixelMetrics: null };
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// 3. WebP (RIFF....WEBP)
|
|
513
|
+
if (
|
|
514
|
+
buffer.subarray(0, 4).toString("ascii") === "RIFF" &&
|
|
515
|
+
buffer.subarray(8, 12).toString("ascii") === "WEBP"
|
|
516
|
+
) {
|
|
517
|
+
let pos = 12;
|
|
518
|
+
let width = 0;
|
|
519
|
+
let height = 0;
|
|
520
|
+
while (pos + 8 <= buffer.length) {
|
|
521
|
+
const fourcc = buffer.subarray(pos, pos + 4).toString("ascii");
|
|
522
|
+
const size = buffer.readUInt32LE(pos + 4);
|
|
523
|
+
const dataStart = pos + 8;
|
|
524
|
+
if (dataStart + size > buffer.length) break;
|
|
525
|
+
const data = buffer.subarray(dataStart, dataStart + size);
|
|
526
|
+
pos = dataStart + size + (size % 2);
|
|
527
|
+
|
|
528
|
+
if (fourcc === "VP8 " && data.length >= 10 && data[3] === 0x9d && data[4] === 0x01 && data[5] === 0x2a) {
|
|
529
|
+
width = data.readUInt16LE(6) & 0x3fff;
|
|
530
|
+
height = data.readUInt16LE(8) & 0x3fff;
|
|
531
|
+
} else if (fourcc === "VP8L" && data.length >= 5 && data[0] === 0x2f) {
|
|
532
|
+
const bits = data.readUInt32LE(1);
|
|
533
|
+
width = (bits & 0x3fff) + 1;
|
|
534
|
+
height = ((bits >> 14) & 0x3fff) + 1;
|
|
535
|
+
} else if (fourcc === "VP8X" && data.length >= 10) {
|
|
536
|
+
width = (data[4] | (data[5] << 8) | (data[6] << 16)) + 1;
|
|
537
|
+
height = (data[7] | (data[8] << 8) | (data[9] << 16)) + 1;
|
|
538
|
+
} else if (fourcc === "EXIF") {
|
|
539
|
+
metadataTexts.push({ key: "exif", value: data.toString("latin1").replace(/\x00+/g, " ") });
|
|
540
|
+
} else if (fourcc === "XMP ") {
|
|
541
|
+
metadataTexts.push({ key: "xmp", value: data.toString("utf8") });
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
if (width <= 0 || height <= 0) {
|
|
546
|
+
throw new Error("Invalid WebP missing dimension chunk");
|
|
547
|
+
}
|
|
548
|
+
for (const m of metadataTexts) {
|
|
549
|
+
if (/(?:c2pa|trainedAlgorithmicMedia|jumbf)/i.test(`${m.key} ${m.value}`)) {
|
|
550
|
+
hasC2pa = true;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
return { format: "webp", width, height, metadataTexts, hasC2pa, pixelMetrics: null };
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// 4. GIF (GIF87a / GIF89a)
|
|
557
|
+
const gifSig = buffer.subarray(0, 6).toString("ascii");
|
|
558
|
+
if ((gifSig === "GIF87a" || gifSig === "GIF89a") && buffer.length >= 13) {
|
|
559
|
+
const width = buffer.readUInt16LE(6);
|
|
560
|
+
const height = buffer.readUInt16LE(8);
|
|
561
|
+
if (width <= 0 || height <= 0) {
|
|
562
|
+
throw new Error("Invalid GIF missing valid screen dimensions");
|
|
563
|
+
}
|
|
564
|
+
const packed = buffer[10];
|
|
565
|
+
const hasGct = (packed & 0x80) !== 0;
|
|
566
|
+
const gctSize = hasGct ? 1 << ((packed & 0x07) + 1) : 0;
|
|
567
|
+
let pos = 13;
|
|
568
|
+
let gct = null;
|
|
569
|
+
if (hasGct) {
|
|
570
|
+
if (pos + gctSize * 3 > buffer.length) {
|
|
571
|
+
throw new Error("Truncated GIF global color table");
|
|
572
|
+
}
|
|
573
|
+
gct = [];
|
|
574
|
+
for (let i = 0; i < gctSize; i += 1) {
|
|
575
|
+
gct.push([buffer[pos + i * 3], buffer[pos + i * 3 + 1], buffer[pos + i * 3 + 2]]);
|
|
576
|
+
}
|
|
577
|
+
pos += gctSize * 3;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
let transparentIdx = -1;
|
|
581
|
+
let frame0Decoded = false;
|
|
582
|
+
let pixelMetrics = null;
|
|
583
|
+
|
|
584
|
+
while (pos < buffer.length) {
|
|
585
|
+
const blockId = buffer[pos++];
|
|
586
|
+
if (blockId === 0x3b) break; // Trailer
|
|
587
|
+
if (blockId === 0x21) {
|
|
588
|
+
if (pos >= buffer.length) break;
|
|
589
|
+
const label = buffer[pos++];
|
|
590
|
+
const chunks = [];
|
|
591
|
+
while (pos < buffer.length) {
|
|
592
|
+
const sz = buffer[pos++];
|
|
593
|
+
if (sz === 0) break;
|
|
594
|
+
const end = Math.min(buffer.length, pos + sz);
|
|
595
|
+
chunks.push(buffer.subarray(pos, end));
|
|
596
|
+
pos = end;
|
|
597
|
+
}
|
|
598
|
+
const payload = chunks.length > 0 ? Buffer.concat(chunks) : Buffer.alloc(0);
|
|
599
|
+
if (label === 0xf9 && payload.length >= 4 && !frame0Decoded) {
|
|
600
|
+
transparentIdx = (payload[0] & 0x01) !== 0 ? payload[3] : -1;
|
|
601
|
+
} else if (label === 0xfe && payload.length > 0) {
|
|
602
|
+
metadataTexts.push({ key: "comment", value: payload.toString("utf8") });
|
|
603
|
+
} else if (label === 0xff && payload.length >= 11) {
|
|
604
|
+
const appId = payload.subarray(0, 11).toString("latin1");
|
|
605
|
+
if (appId !== "NETSCAPE2.0" && appId !== "ANIMEXTS1.0") {
|
|
606
|
+
const text = payload.subarray(11).toString("utf8").replace(/\x00+/g, " ").trim();
|
|
607
|
+
if (text) {
|
|
608
|
+
const key = /xmp/i.test(appId) ? "xmp" : /c2pa|jumb/i.test(appId + text) ? "c2pa" : "app";
|
|
609
|
+
metadataTexts.push({ key, value: text });
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
} else if (blockId === 0x2c) {
|
|
614
|
+
if (pos + 9 > buffer.length) break;
|
|
615
|
+
const left = buffer.readUInt16LE(pos);
|
|
616
|
+
const top = buffer.readUInt16LE(pos + 2);
|
|
617
|
+
const imgW = buffer.readUInt16LE(pos + 4);
|
|
618
|
+
const imgH = buffer.readUInt16LE(pos + 6);
|
|
619
|
+
const imgPacked = buffer[pos + 8];
|
|
620
|
+
pos += 9;
|
|
621
|
+
const hasLct = (imgPacked & 0x80) !== 0;
|
|
622
|
+
const interlaced = (imgPacked & 0x40) !== 0;
|
|
623
|
+
const lctSize = hasLct ? 1 << ((imgPacked & 0x07) + 1) : 0;
|
|
624
|
+
let palette = gct;
|
|
625
|
+
if (hasLct) {
|
|
626
|
+
if (pos + lctSize * 3 > buffer.length) break;
|
|
627
|
+
palette = [];
|
|
628
|
+
for (let i = 0; i < lctSize; i += 1) {
|
|
629
|
+
palette.push([buffer[pos + i * 3], buffer[pos + i * 3 + 1], buffer[pos + i * 3 + 2]]);
|
|
630
|
+
}
|
|
631
|
+
pos += lctSize * 3;
|
|
632
|
+
}
|
|
633
|
+
if (pos >= buffer.length) break;
|
|
634
|
+
const minCodeSize = buffer[pos++];
|
|
635
|
+
const dataChunks = [];
|
|
636
|
+
while (pos < buffer.length) {
|
|
637
|
+
const sz = buffer[pos++];
|
|
638
|
+
if (sz === 0) break;
|
|
639
|
+
const end = Math.min(buffer.length, pos + sz);
|
|
640
|
+
if (!frame0Decoded) dataChunks.push(buffer.subarray(pos, end));
|
|
641
|
+
pos = end;
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
if (!frame0Decoded) {
|
|
645
|
+
frame0Decoded = true;
|
|
646
|
+
if (palette && imgW > 0 && imgH > 0 && width * height <= MAX_PNG_PIXELS) {
|
|
647
|
+
const lzwBytes = Buffer.concat(dataChunks);
|
|
648
|
+
const indices = decodeGifLzw(lzwBytes, minCodeSize, imgW * imgH);
|
|
649
|
+
if (indices) {
|
|
650
|
+
const rowMap = new Int32Array(imgH);
|
|
651
|
+
if (interlaced) {
|
|
652
|
+
let srcRow = 0;
|
|
653
|
+
for (const [start, step] of [[0, 8], [4, 8], [2, 4], [1, 2]]) {
|
|
654
|
+
for (let y = start; y < imgH; y += step) {
|
|
655
|
+
rowMap[y] = srcRow++;
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
} else {
|
|
659
|
+
for (let y = 0; y < imgH; y += 1) rowMap[y] = y;
|
|
660
|
+
}
|
|
661
|
+
const rgba = new Uint8Array(width * height * 4);
|
|
662
|
+
const bgRgb = gct && gct[0] ? gct[0] : [0, 0, 0];
|
|
663
|
+
if (transparentIdx === -1) {
|
|
664
|
+
for (let i = 0; i < width * height; i += 1) {
|
|
665
|
+
rgba[i * 4] = bgRgb[0];
|
|
666
|
+
rgba[i * 4 + 1] = bgRgb[1];
|
|
667
|
+
rgba[i * 4 + 2] = bgRgb[2];
|
|
668
|
+
rgba[i * 4 + 3] = 255;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
for (let iy = 0; iy < imgH; iy += 1) {
|
|
672
|
+
const cy = top + iy;
|
|
673
|
+
if (cy < 0 || cy >= height) continue;
|
|
674
|
+
const srcOff = rowMap[iy] * imgW;
|
|
675
|
+
for (let ix = 0; ix < imgW; ix += 1) {
|
|
676
|
+
const cx = left + ix;
|
|
677
|
+
if (cx < 0 || cx >= width) continue;
|
|
678
|
+
const cIdx = indices[srcOff + ix];
|
|
679
|
+
if (cIdx === transparentIdx) continue;
|
|
680
|
+
const rgb = palette[cIdx] || [0, 0, 0];
|
|
681
|
+
const dst = (cy * width + cx) * 4;
|
|
682
|
+
rgba[dst] = rgb[0];
|
|
683
|
+
rgba[dst + 1] = rgb[1];
|
|
684
|
+
rgba[dst + 2] = rgb[2];
|
|
685
|
+
rgba[dst + 3] = 255;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
pixelMetrics = computePixelMetrics(width, height, (x, y) => {
|
|
689
|
+
const off = (y * width + x) * 4;
|
|
690
|
+
return [rgba[off], rgba[off + 1], rgba[off + 2], rgba[off + 3]];
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
} else {
|
|
696
|
+
break;
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
for (const m of metadataTexts) {
|
|
701
|
+
if (/(?:c2pa|trainedAlgorithmicMedia|jumbf)/i.test(`${m.key} ${m.value}`)) {
|
|
702
|
+
hasC2pa = true;
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
return { format: "gif", width, height, metadataTexts, hasC2pa, pixelMetrics };
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
throw new Error("Unsupported or corrupted image header (expected PNG, JPEG, WebP, or GIF)");
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// ---------- Zero-Dependency PDF Parser ----------
|
|
712
|
+
|
|
713
|
+
function decodeUtf16BeHex(hexRaw) {
|
|
714
|
+
const clean = hexRaw.replace(/[^0-9a-fA-F]/g, "");
|
|
715
|
+
if (!clean) return "";
|
|
716
|
+
const padded = clean.length % 2 === 1 ? `${clean}0` : clean;
|
|
717
|
+
const start = /^feff/i.test(padded) && padded.length >= 4 ? 4 : 0;
|
|
718
|
+
let out = "";
|
|
719
|
+
for (let i = start; i + 3 < padded.length; i += 4) {
|
|
720
|
+
const code = parseInt(padded.slice(i, i + 4), 16);
|
|
721
|
+
if (code === 0) continue;
|
|
722
|
+
if (code >= 0xd800 && code <= 0xdbff) {
|
|
723
|
+
if (i + 7 < padded.length) {
|
|
724
|
+
const low = parseInt(padded.slice(i + 4, i + 8), 16);
|
|
725
|
+
if (low >= 0xdc00 && low <= 0xdfff) {
|
|
726
|
+
const cp = 0x10000 + (((code - 0xd800) << 10) | (low - 0xdc00));
|
|
727
|
+
out += String.fromCodePoint(cp);
|
|
728
|
+
i += 4;
|
|
729
|
+
continue;
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
continue; // Drop unpaired high surrogate
|
|
733
|
+
}
|
|
734
|
+
if (code >= 0xdc00 && code <= 0xdfff) {
|
|
735
|
+
continue; // Drop unpaired low surrogate
|
|
736
|
+
}
|
|
737
|
+
out += String.fromCharCode(code);
|
|
738
|
+
}
|
|
739
|
+
return out;
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
function decodePdfLiteralString(raw) {
|
|
743
|
+
let out = "";
|
|
744
|
+
for (let i = 0; i < raw.length; i += 1) {
|
|
745
|
+
const ch = raw[i];
|
|
746
|
+
if (ch !== "\\") {
|
|
747
|
+
out += ch;
|
|
748
|
+
continue;
|
|
749
|
+
}
|
|
750
|
+
i += 1;
|
|
751
|
+
if (i >= raw.length) break;
|
|
752
|
+
const esc = raw[i];
|
|
753
|
+
if (esc === "n") out += "\n";
|
|
754
|
+
else if (esc === "r") out += "\r";
|
|
755
|
+
else if (esc === "t") out += "\t";
|
|
756
|
+
else if (esc === "b") out += "\b";
|
|
757
|
+
else if (esc === "f") out += "\f";
|
|
758
|
+
else if (esc === "(" || esc === ")" || esc === "\\") out += esc;
|
|
759
|
+
else if (esc === "\r" && raw[i + 1] === "\n") i += 1;
|
|
760
|
+
else if (esc === "\n" || esc === "\r") continue;
|
|
761
|
+
else if (esc >= "0" && esc <= "7") {
|
|
762
|
+
const oct = raw.slice(i, i + 3).match(/^[0-7]{1,3}/)[0];
|
|
763
|
+
out += String.fromCharCode(parseInt(oct, 8));
|
|
764
|
+
i += oct.length - 1;
|
|
765
|
+
} else {
|
|
766
|
+
out += esc;
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
return out;
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
function decodePdfUnicodeLiteral(raw) {
|
|
773
|
+
const bytesStr = decodePdfLiteralString(raw);
|
|
774
|
+
if (bytesStr.length >= 4 && bytesStr.charCodeAt(0) === 0xfe && bytesStr.charCodeAt(1) === 0xff) {
|
|
775
|
+
let hex = "";
|
|
776
|
+
for (let i = 2; i < bytesStr.length; i += 1) {
|
|
777
|
+
hex += (bytesStr.charCodeAt(i) & 0xff).toString(16).padStart(2, "0");
|
|
778
|
+
}
|
|
779
|
+
return decodeUtf16BeHex(hex);
|
|
780
|
+
}
|
|
781
|
+
return bytesStr;
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
function decodePdfHexString(hexRaw) {
|
|
785
|
+
const clean = hexRaw.replace(/[^0-9a-fA-F]/g, "");
|
|
786
|
+
if (!clean) return "";
|
|
787
|
+
const padded = clean.length % 2 === 1 ? `${clean}0` : clean;
|
|
788
|
+
if (/^feff/i.test(padded) && padded.length >= 8) {
|
|
789
|
+
return decodeUtf16BeHex(padded);
|
|
790
|
+
}
|
|
791
|
+
let out = "";
|
|
792
|
+
for (let i = 0; i + 1 < padded.length; i += 2) {
|
|
793
|
+
const code = parseInt(padded.slice(i, i + 2), 16);
|
|
794
|
+
if (code >= 0x20 && code <= 0x7e) out += String.fromCharCode(code);
|
|
795
|
+
else if (code === 0x0a || code === 0x0d || code === 0x09) out += " ";
|
|
796
|
+
}
|
|
797
|
+
return out;
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
const AGL_GLYPH_MAP = {
|
|
801
|
+
space: " ", exclam: "!", quotedbl: '"', numbersign: "#", dollar: "$", percent: "%",
|
|
802
|
+
ampersand: "&", quotesingle: "'", parenleft: "(", parenright: ")", asterisk: "*", plus: "+",
|
|
803
|
+
comma: ",", hyphen: "-", period: ".", slash: "/", zero: "0", one: "1", two: "2",
|
|
804
|
+
three: "3", four: "4", five: "5", six: "6", seven: "7", eight: "8", nine: "9",
|
|
805
|
+
colon: ":", semicolon: ";", less: "<", equal: "=", greater: ">", question: "?", at: "@",
|
|
806
|
+
bracketleft: "[", backslash: "\\", bracketright: "]", underscore: "_", braceleft: "{",
|
|
807
|
+
bar: "|", braceright: "}", asciitilde: "~", endash: "–", emdash: "—", bullet: "•",
|
|
808
|
+
};
|
|
809
|
+
|
|
810
|
+
function parseToUnicodeCMap(cmapText) {
|
|
811
|
+
const map = new Map();
|
|
812
|
+
const ranges = [];
|
|
813
|
+
const codespaces = [];
|
|
814
|
+
const lenSet = new Set();
|
|
815
|
+
if (!cmapText) return { map, ranges, codespaces, byteLens: [] };
|
|
816
|
+
|
|
817
|
+
for (const sec of cmapText.matchAll(/begincodespacerange\b([\s\S]*?)endcodespacerange/g)) {
|
|
818
|
+
for (const pm of sec[1].matchAll(/<([0-9a-fA-F]+)>\s*<([0-9a-fA-F]+)>/g)) {
|
|
819
|
+
const sHex = pm[1].toLowerCase();
|
|
820
|
+
const eHex = pm[2].toLowerCase();
|
|
821
|
+
if (sHex.length === eHex.length && sHex.length >= 2 && sHex.length % 2 === 0) {
|
|
822
|
+
const byteLen = sHex.length / 2;
|
|
823
|
+
codespaces.push({ byteLen, start: parseInt(sHex, 16), end: parseInt(eHex, 16) });
|
|
824
|
+
lenSet.add(byteLen);
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
for (const sec of cmapText.matchAll(/beginbfchar\b([\s\S]*?)endbfchar/g)) {
|
|
830
|
+
for (const pm of sec[1].matchAll(/<([0-9a-fA-F]+)>\s*<([0-9a-fA-F]+)>/g)) {
|
|
831
|
+
const src = pm[1].toLowerCase();
|
|
832
|
+
const dst = decodeUtf16BeHex(pm[2]);
|
|
833
|
+
if (src.length >= 2 && src.length % 2 === 0 && dst) {
|
|
834
|
+
map.set(src, dst);
|
|
835
|
+
lenSet.add(src.length / 2);
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
for (const sec of cmapText.matchAll(/beginbfrange\b([\s\S]*?)endbfrange/g)) {
|
|
841
|
+
const body = sec[1];
|
|
842
|
+
const rangeRe = /<([0-9a-fA-F]+)>\s*<([0-9a-fA-F]+)>\s*(?:\[([\s\S]*?)\]|<([0-9a-fA-F]+)>)/g;
|
|
843
|
+
let rm;
|
|
844
|
+
while ((rm = rangeRe.exec(body)) !== null) {
|
|
845
|
+
const startHex = rm[1].toLowerCase();
|
|
846
|
+
const endHex = rm[2].toLowerCase();
|
|
847
|
+
if (startHex.length !== endHex.length || startHex.length % 2 !== 0) continue;
|
|
848
|
+
const startCode = parseInt(startHex, 16);
|
|
849
|
+
const endCode = parseInt(endHex, 16);
|
|
850
|
+
if (!(endCode >= startCode)) continue;
|
|
851
|
+
const hexWidth = startHex.length;
|
|
852
|
+
const byteLen = hexWidth / 2;
|
|
853
|
+
lenSet.add(byteLen);
|
|
854
|
+
|
|
855
|
+
if (rm[3] !== undefined) {
|
|
856
|
+
const items = [...rm[3].matchAll(/<([0-9a-fA-F]+)>/g)].map((m) => decodeUtf16BeHex(m[1]));
|
|
857
|
+
ranges.push({ startCode, endCode, byteLen, items, prefixHex: null, baseLastUnit: 0 });
|
|
858
|
+
} else if (rm[4] !== undefined) {
|
|
859
|
+
const dstBaseHex = rm[4];
|
|
860
|
+
if (dstBaseHex.length < 4) continue;
|
|
861
|
+
const prefixHex = dstBaseHex.slice(0, -4);
|
|
862
|
+
const baseLastUnit = parseInt(dstBaseHex.slice(-4), 16);
|
|
863
|
+
ranges.push({ startCode, endCode, byteLen, items: null, prefixHex, baseLastUnit });
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
return { map, ranges, codespaces, byteLens: Array.from(lenSet).sort((a, b) => b - a) };
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
function glyphNameToChar(rawName) {
|
|
872
|
+
if (!rawName) return "";
|
|
873
|
+
const name = rawName.replace(/#([0-9a-fA-F]{2})/g, (_, h) => String.fromCharCode(parseInt(h, 16)));
|
|
874
|
+
if (Object.hasOwn(AGL_GLYPH_MAP, name)) return AGL_GLYPH_MAP[name];
|
|
875
|
+
if (name.length === 1 && /[A-Za-z0-9]/.test(name)) return name;
|
|
876
|
+
const uni = name.match(/^uni((?:[0-9a-fA-F]{4})+)$/);
|
|
877
|
+
if (uni) {
|
|
878
|
+
return decodeUtf16BeHex(uni[1]);
|
|
879
|
+
}
|
|
880
|
+
const uhex = name.match(/^u([0-9a-fA-F]{4,6})$/);
|
|
881
|
+
if (uhex) {
|
|
882
|
+
const cp = parseInt(uhex[1], 16);
|
|
883
|
+
return cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : "";
|
|
884
|
+
}
|
|
885
|
+
return "";
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
function parseEncodingDifferences(fontDictRaw, objects) {
|
|
889
|
+
let encDict = "";
|
|
890
|
+
const refM = fontDictRaw.match(/\/Encoding\s+(\d+)\s+\d+\s+R/);
|
|
891
|
+
if (refM && objects.has(Number(refM[1]))) {
|
|
892
|
+
encDict = objects.get(Number(refM[1])).dictRaw || "";
|
|
893
|
+
} else {
|
|
894
|
+
const inlineM = fontDictRaw.match(/\/Encoding\s*<<([\s\S]*?)>>/);
|
|
895
|
+
if (inlineM) encDict = inlineM[1];
|
|
896
|
+
}
|
|
897
|
+
if (!encDict) return null;
|
|
898
|
+
const diffM = encDict.match(/\/Differences\s*\[([\s\S]*?)\]/);
|
|
899
|
+
if (!diffM) return null;
|
|
900
|
+
const map = new Map();
|
|
901
|
+
let curCode = 0;
|
|
902
|
+
for (const tok of diffM[1].matchAll(/(\d+)|\/([^\s\x00/[\]()<>]+)/g)) {
|
|
903
|
+
if (tok[1] !== undefined) {
|
|
904
|
+
curCode = Number(tok[1]);
|
|
905
|
+
} else if (tok[2] !== undefined) {
|
|
906
|
+
const ch = glyphNameToChar(tok[2]);
|
|
907
|
+
if (ch) map.set(curCode, ch);
|
|
908
|
+
curCode += 1;
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
return map.size > 0 ? map : null;
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
function lookupRangeCMap(ranges, code, byteLen) {
|
|
915
|
+
for (const r of ranges) {
|
|
916
|
+
if (r.byteLen !== byteLen) continue;
|
|
917
|
+
if (code < r.startCode || code > r.endCode) continue;
|
|
918
|
+
const offset = code - r.startCode;
|
|
919
|
+
if (r.items) {
|
|
920
|
+
return offset < r.items.length ? r.items[offset] : "";
|
|
921
|
+
}
|
|
922
|
+
const unitHex = ((r.baseLastUnit + offset) & 0xffff).toString(16).padStart(4, "0");
|
|
923
|
+
return decodeUtf16BeHex(r.prefixHex + unitHex);
|
|
924
|
+
}
|
|
925
|
+
return "";
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
function decodeHexViaToUnicode(hexLower, toUnicode) {
|
|
929
|
+
let out = "";
|
|
930
|
+
let pos = 0;
|
|
931
|
+
const codespaces = toUnicode.codespaces || [];
|
|
932
|
+
const byteLens = toUnicode.byteLens || [];
|
|
933
|
+
const stepMin = (byteLens[byteLens.length - 1] || 1) * 2;
|
|
934
|
+
while (pos < hexLower.length) {
|
|
935
|
+
let consumed = 0;
|
|
936
|
+
if (codespaces.length > 0) {
|
|
937
|
+
let csMatched = false;
|
|
938
|
+
for (const cs of codespaces) {
|
|
939
|
+
const hLen = cs.byteLen * 2;
|
|
940
|
+
if (pos + hLen <= hexLower.length) {
|
|
941
|
+
const key = hexLower.slice(pos, pos + hLen);
|
|
942
|
+
const codeVal = parseInt(key, 16);
|
|
943
|
+
if (codeVal >= cs.start && codeVal <= cs.end) {
|
|
944
|
+
if (toUnicode.map.has(key)) {
|
|
945
|
+
out += toUnicode.map.get(key);
|
|
946
|
+
} else if (toUnicode.ranges && toUnicode.ranges.length > 0) {
|
|
947
|
+
out += lookupRangeCMap(toUnicode.ranges, codeVal, cs.byteLen);
|
|
948
|
+
}
|
|
949
|
+
pos += hLen;
|
|
950
|
+
consumed = hLen;
|
|
951
|
+
csMatched = true;
|
|
952
|
+
break;
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
if (csMatched) continue;
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
let matched = false;
|
|
960
|
+
for (const bLen of byteLens) {
|
|
961
|
+
const hLen = bLen * 2;
|
|
962
|
+
if (pos + hLen <= hexLower.length) {
|
|
963
|
+
const key = hexLower.slice(pos, pos + hLen);
|
|
964
|
+
if (toUnicode.map.has(key)) {
|
|
965
|
+
out += toUnicode.map.get(key);
|
|
966
|
+
pos += hLen;
|
|
967
|
+
matched = true;
|
|
968
|
+
break;
|
|
969
|
+
}
|
|
970
|
+
if (toUnicode.ranges && toUnicode.ranges.length > 0) {
|
|
971
|
+
const rVal = lookupRangeCMap(toUnicode.ranges, parseInt(key, 16), bLen);
|
|
972
|
+
if (rVal) {
|
|
973
|
+
out += rVal;
|
|
974
|
+
pos += hLen;
|
|
975
|
+
matched = true;
|
|
976
|
+
break;
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
if (!matched && !consumed) pos += stepMin;
|
|
982
|
+
}
|
|
983
|
+
return out;
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
function decodePdfHexWithFont(hexRaw, fontEntry) {
|
|
987
|
+
const clean = hexRaw.replace(/[^0-9a-fA-F]/g, "");
|
|
988
|
+
if (!clean) return "";
|
|
989
|
+
const padded = (clean.length % 2 === 1 ? `${clean}0` : clean).toLowerCase();
|
|
990
|
+
if (/^feff/.test(padded) && padded.length >= 8) {
|
|
991
|
+
return decodeUtf16BeHex(padded);
|
|
992
|
+
}
|
|
993
|
+
if (fontEntry?.toUnicode && (fontEntry.toUnicode.map.size > 0 || (fontEntry.toUnicode.ranges?.length || 0) > 0)) {
|
|
994
|
+
return decodeHexViaToUnicode(padded, fontEntry.toUnicode);
|
|
995
|
+
}
|
|
996
|
+
if (fontEntry?.differences && fontEntry.differences.size > 0) {
|
|
997
|
+
let out = "";
|
|
998
|
+
for (let i = 0; i + 1 < padded.length; i += 2) {
|
|
999
|
+
const code = parseInt(padded.slice(i, i + 2), 16);
|
|
1000
|
+
if (fontEntry.differences.has(code)) out += fontEntry.differences.get(code);
|
|
1001
|
+
else if (!fontEntry.isCustomGlyph && code >= 0x20 && code <= 0x7e) out += String.fromCharCode(code);
|
|
1002
|
+
}
|
|
1003
|
+
return out;
|
|
1004
|
+
}
|
|
1005
|
+
if (fontEntry?.isCustomGlyph) return "";
|
|
1006
|
+
return decodePdfHexString(hexRaw);
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
function decodePdfLiteralWithFont(raw, fontEntry) {
|
|
1010
|
+
const bytesStr = decodePdfLiteralString(raw);
|
|
1011
|
+
if (bytesStr.length >= 4 && bytesStr.charCodeAt(0) === 0xfe && bytesStr.charCodeAt(1) === 0xff) {
|
|
1012
|
+
return decodePdfUnicodeLiteral(raw);
|
|
1013
|
+
}
|
|
1014
|
+
if (fontEntry?.toUnicode && (fontEntry.toUnicode.map.size > 0 || (fontEntry.toUnicode.ranges?.length || 0) > 0)) {
|
|
1015
|
+
let hex = "";
|
|
1016
|
+
for (let i = 0; i < bytesStr.length; i += 1) {
|
|
1017
|
+
hex += (bytesStr.charCodeAt(i) & 0xff).toString(16).padStart(2, "0");
|
|
1018
|
+
}
|
|
1019
|
+
return decodeHexViaToUnicode(hex, fontEntry.toUnicode);
|
|
1020
|
+
}
|
|
1021
|
+
if (fontEntry?.differences && fontEntry.differences.size > 0) {
|
|
1022
|
+
let out = "";
|
|
1023
|
+
for (let i = 0; i < bytesStr.length; i += 1) {
|
|
1024
|
+
const code = bytesStr.charCodeAt(i) & 0xff;
|
|
1025
|
+
if (fontEntry.differences.has(code)) out += fontEntry.differences.get(code);
|
|
1026
|
+
else if (!fontEntry.isCustomGlyph && code >= 0x20 && code <= 0x7e) out += String.fromCharCode(code);
|
|
1027
|
+
}
|
|
1028
|
+
return out;
|
|
1029
|
+
}
|
|
1030
|
+
if (fontEntry?.isCustomGlyph) return "";
|
|
1031
|
+
return bytesStr;
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
function readPdfLiteralAt(src, openIdx) {
|
|
1035
|
+
let depth = 1;
|
|
1036
|
+
let i = openIdx + 1;
|
|
1037
|
+
while (i < src.length && depth > 0) {
|
|
1038
|
+
const ch = src[i];
|
|
1039
|
+
if (ch === "\\") {
|
|
1040
|
+
i += 2;
|
|
1041
|
+
continue;
|
|
1042
|
+
}
|
|
1043
|
+
if (ch === "(") depth += 1;
|
|
1044
|
+
else if (ch === ")") depth -= 1;
|
|
1045
|
+
i += 1;
|
|
1046
|
+
}
|
|
1047
|
+
return { raw: src.slice(openIdx + 1, Math.max(openIdx + 1, i - 1)), endIdx: i };
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
function parseMediaBoxRect(dictText) {
|
|
1051
|
+
const m = dictText.match(/\/MediaBox\s*\[\s*(-?[\d.]+)\s+(-?[\d.]+)\s+(-?[\d.]+)\s+(-?[\d.]+)\s*\]/);
|
|
1052
|
+
if (!m) return null;
|
|
1053
|
+
const w = Math.abs(Number(m[3]) - Number(m[1]));
|
|
1054
|
+
const h = Math.abs(Number(m[4]) - Number(m[2]));
|
|
1055
|
+
if (!(w > 0 && h > 0)) return null;
|
|
1056
|
+
return [w, h];
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
function extractPdfObjects(buffer) {
|
|
1060
|
+
const latin = buffer.toString("latin1");
|
|
1061
|
+
const objects = new Map();
|
|
1062
|
+
const objRe = /(\d+)\s+(\d+)\s+obj\b/g;
|
|
1063
|
+
let m;
|
|
1064
|
+
|
|
1065
|
+
while ((m = objRe.exec(latin)) !== null) {
|
|
1066
|
+
const objNum = Number(m[1]);
|
|
1067
|
+
const bodyStart = m.index + m[0].length;
|
|
1068
|
+
const endObjIdx = latin.indexOf("endobj", bodyStart);
|
|
1069
|
+
if (endObjIdx === -1) break;
|
|
1070
|
+
|
|
1071
|
+
const streamTagIdx = latin.slice(bodyStart, endObjIdx).indexOf("stream");
|
|
1072
|
+
let dictPart = "";
|
|
1073
|
+
let streamBytes = null;
|
|
1074
|
+
let nextPos = endObjIdx + 6;
|
|
1075
|
+
|
|
1076
|
+
if (streamTagIdx !== -1) {
|
|
1077
|
+
const absStreamTagIdx = bodyStart + streamTagIdx;
|
|
1078
|
+
dictPart = latin.slice(bodyStart, absStreamTagIdx);
|
|
1079
|
+
let sStart = absStreamTagIdx + 6;
|
|
1080
|
+
if (latin[sStart] === "\r" && latin[sStart + 1] === "\n") sStart += 2;
|
|
1081
|
+
else if (latin[sStart] === "\n" || latin[sStart] === "\r") sStart += 1;
|
|
1082
|
+
|
|
1083
|
+
const lenMatch = dictPart.match(/\/Length\s+(\d+)\b(?!\s+\d+\s+R)/);
|
|
1084
|
+
let sEnd = -1;
|
|
1085
|
+
if (lenMatch) {
|
|
1086
|
+
const candEnd = sStart + Number(lenMatch[1]);
|
|
1087
|
+
if (candEnd <= buffer.length) {
|
|
1088
|
+
sEnd = candEnd;
|
|
1089
|
+
const afterStream = latin.indexOf("endstream", sEnd);
|
|
1090
|
+
const realEndObj = afterStream !== -1 ? latin.indexOf("endobj", afterStream) : -1;
|
|
1091
|
+
if (realEndObj !== -1) nextPos = realEndObj + 6;
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
if (sEnd === -1) {
|
|
1095
|
+
const endStreamIdx = latin.indexOf("endstream", sStart);
|
|
1096
|
+
if (endStreamIdx !== -1) {
|
|
1097
|
+
sEnd = endStreamIdx;
|
|
1098
|
+
if (sEnd > sStart && latin[sEnd - 1] === "\n") sEnd -= 1;
|
|
1099
|
+
if (sEnd > sStart && latin[sEnd - 1] === "\r") sEnd -= 1;
|
|
1100
|
+
const realEndObj = latin.indexOf("endobj", endStreamIdx);
|
|
1101
|
+
if (realEndObj !== -1) nextPos = realEndObj + 6;
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
if (sEnd >= sStart) {
|
|
1105
|
+
streamBytes = buffer.subarray(sStart, sEnd);
|
|
1106
|
+
}
|
|
1107
|
+
} else {
|
|
1108
|
+
dictPart = latin.slice(bodyStart, endObjIdx);
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
objects.set(objNum, { objNum, dictRaw: dictPart, streamBytes });
|
|
1112
|
+
objRe.lastIndex = nextPos;
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
// Extract PDF 1.5+ /Type /ObjStm compressed object streams
|
|
1116
|
+
let hasCompressedStreams = false;
|
|
1117
|
+
for (const obj of Array.from(objects.values())) {
|
|
1118
|
+
if (obj.streamBytes && /\/FlateDecode\b/.test(obj.dictRaw)) {
|
|
1119
|
+
hasCompressedStreams = true;
|
|
1120
|
+
}
|
|
1121
|
+
if (!obj.streamBytes || !/\/Type\s*\/ObjStm\b/.test(obj.dictRaw)) continue;
|
|
1122
|
+
const nMatch = obj.dictRaw.match(/\/N\s+(\d+)/);
|
|
1123
|
+
const firstMatch = obj.dictRaw.match(/\/First\s+(\d+)/);
|
|
1124
|
+
if (!nMatch || !firstMatch) continue;
|
|
1125
|
+
const count = Number(nMatch[1]);
|
|
1126
|
+
const first = Number(firstMatch[1]);
|
|
1127
|
+
const streamText = decodeObjectStream(obj);
|
|
1128
|
+
if (!streamText || first <= 0 || first > streamText.length || count <= 0) continue;
|
|
1129
|
+
const headerNums = streamText.slice(0, first).match(/\d+/g) || [];
|
|
1130
|
+
const pairs = [];
|
|
1131
|
+
for (let k = 0; k + 1 < headerNums.length && pairs.length < count; k += 2) {
|
|
1132
|
+
pairs.push({ objNum: Number(headerNums[k]), absStart: first + Number(headerNums[k + 1]) });
|
|
1133
|
+
}
|
|
1134
|
+
const sortedStarts = [...pairs].sort((a, b) => a.absStart - b.absStart);
|
|
1135
|
+
for (let k = 0; k < sortedStarts.length; k += 1) {
|
|
1136
|
+
const cur = sortedStarts[k];
|
|
1137
|
+
if (cur.absStart < first || cur.absStart >= streamText.length) continue;
|
|
1138
|
+
const nextStart = k + 1 < sortedStarts.length ? sortedStarts[k + 1].absStart : streamText.length;
|
|
1139
|
+
const body = streamText.slice(cur.absStart, Math.max(cur.absStart, Math.min(streamText.length, nextStart))).trim();
|
|
1140
|
+
if (!objects.has(cur.objNum) && body) {
|
|
1141
|
+
objects.set(cur.objNum, { objNum: cur.objNum, dictRaw: body, streamBytes: null, fromObjStm: true });
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
return { latin, objects, hasCompressedStreams };
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
function decodeObjectStream(obj) {
|
|
1150
|
+
if (!obj || !obj.streamBytes) return "";
|
|
1151
|
+
let bytes = obj.streamBytes;
|
|
1152
|
+
if (/\/FlateDecode\b/.test(obj.dictRaw)) {
|
|
1153
|
+
try {
|
|
1154
|
+
bytes = inflateSync(bytes, { maxOutputLength: MAX_STREAM_UNCOMPRESSED_BYTES });
|
|
1155
|
+
} catch {
|
|
1156
|
+
return "";
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
return bytes.toString("latin1");
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
function collectRgbStopsFromDict(dictText, outColors) {
|
|
1163
|
+
for (const m of dictText.matchAll(/\/C[01]\s*\[\s*([\d.]+)\s+([\d.]+)\s+([\d.]+)\s*\]/g)) {
|
|
1164
|
+
const r = Math.min(255, Math.max(0, Math.round(Number(m[1]) * 255)));
|
|
1165
|
+
const g = Math.min(255, Math.max(0, Math.round(Number(m[2]) * 255)));
|
|
1166
|
+
const b = Math.min(255, Math.max(0, Math.round(Number(m[3]) * 255)));
|
|
1167
|
+
outColors.push([r, g, b]);
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
function readPdfDictAt(src, openIdx) {
|
|
1172
|
+
let depth = 1;
|
|
1173
|
+
let j = openIdx + 2;
|
|
1174
|
+
while (j < src.length && depth > 0) {
|
|
1175
|
+
if (src[j] === "(") {
|
|
1176
|
+
j = readPdfLiteralAt(src, j).endIdx;
|
|
1177
|
+
continue;
|
|
1178
|
+
}
|
|
1179
|
+
if (src[j] === "<" && src[j + 1] === "<") {
|
|
1180
|
+
depth += 1;
|
|
1181
|
+
j += 2;
|
|
1182
|
+
continue;
|
|
1183
|
+
}
|
|
1184
|
+
if (src[j] === "<") {
|
|
1185
|
+
const close = src.indexOf(">", j + 1);
|
|
1186
|
+
j = close !== -1 ? close + 1 : j + 1;
|
|
1187
|
+
continue;
|
|
1188
|
+
}
|
|
1189
|
+
if (src[j] === ">" && src[j + 1] === ">") {
|
|
1190
|
+
depth -= 1;
|
|
1191
|
+
j += 2;
|
|
1192
|
+
continue;
|
|
1193
|
+
}
|
|
1194
|
+
j += 1;
|
|
1195
|
+
}
|
|
1196
|
+
return { raw: src.slice(openIdx, j), endIdx: j };
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
function extractActualTextFromPropDict(dictRaw) {
|
|
1200
|
+
const mIdx = dictRaw.search(/\/ActualText(?=\s|[<(])/);
|
|
1201
|
+
if (mIdx === -1) return null;
|
|
1202
|
+
let j = mIdx + "/ActualText".length;
|
|
1203
|
+
while (j < dictRaw.length && /\s/.test(dictRaw[j])) j += 1;
|
|
1204
|
+
if (dictRaw[j] === "<" && dictRaw[j + 1] !== "<") {
|
|
1205
|
+
const close = dictRaw.indexOf(">", j + 1);
|
|
1206
|
+
if (close !== -1) {
|
|
1207
|
+
const hex = dictRaw.slice(j + 1, close).replace(/\s+/g, "");
|
|
1208
|
+
if (/^feff/i.test(hex)) return decodeUtf16BeHex(hex);
|
|
1209
|
+
return decodePdfHexString(hex);
|
|
1210
|
+
}
|
|
1211
|
+
} else if (dictRaw[j] === "(") {
|
|
1212
|
+
return decodePdfUnicodeLiteral(readPdfLiteralAt(dictRaw, j).raw);
|
|
1213
|
+
}
|
|
1214
|
+
return null;
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
function isPdfWs(ch) {
|
|
1218
|
+
return ch === " " || ch === "\n" || ch === "\r" || ch === "\t" || ch === "\f" || ch === "\x00";
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
function isPdfDelimiter(ch) {
|
|
1222
|
+
return !ch || isPdfWs(ch) || ch === "/" || ch === "[" || ch === "]" || ch === "(" || ch === ")" || ch === "<" || ch === ">" || ch === "{" || ch === "}" || ch === "%";
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
function skipPdfWs(str, pos) {
|
|
1226
|
+
let p = pos;
|
|
1227
|
+
while (p < str.length && isPdfWs(str[p])) p += 1;
|
|
1228
|
+
return p;
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
function readPdfOpAt(str, pos) {
|
|
1232
|
+
const start = skipPdfWs(str, pos);
|
|
1233
|
+
let end = start;
|
|
1234
|
+
while (end < str.length && !isPdfDelimiter(str[end])) end += 1;
|
|
1235
|
+
return { op: str.slice(start, end), endIdx: end };
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
function stripInlineImagesLinear(streamText) {
|
|
1239
|
+
let imageCount = 0;
|
|
1240
|
+
const out = [];
|
|
1241
|
+
let pos = 0;
|
|
1242
|
+
const len = streamText.length;
|
|
1243
|
+
while (pos < len) {
|
|
1244
|
+
const biIdx = streamText.indexOf("BI", pos);
|
|
1245
|
+
if (biIdx === -1) {
|
|
1246
|
+
out.push(streamText.slice(pos));
|
|
1247
|
+
break;
|
|
1248
|
+
}
|
|
1249
|
+
const prevOk = biIdx === 0 || isPdfDelimiter(streamText[biIdx - 1]);
|
|
1250
|
+
const nextOk = biIdx + 2 < len && isPdfWs(streamText[biIdx + 2]);
|
|
1251
|
+
if (!prevOk || !nextOk) {
|
|
1252
|
+
out.push(streamText.slice(pos, biIdx + 2));
|
|
1253
|
+
pos = biIdx + 2;
|
|
1254
|
+
continue;
|
|
1255
|
+
}
|
|
1256
|
+
const idIdx = streamText.indexOf("ID", biIdx + 3);
|
|
1257
|
+
if (idIdx === -1 || !(isPdfWs(streamText[idIdx - 1]) && idIdx + 2 < len && isPdfWs(streamText[idIdx + 2]))) {
|
|
1258
|
+
out.push(streamText.slice(pos, biIdx + 2));
|
|
1259
|
+
pos = biIdx + 2;
|
|
1260
|
+
continue;
|
|
1261
|
+
}
|
|
1262
|
+
let searchFrom = idIdx + 3;
|
|
1263
|
+
let eiIdx = -1;
|
|
1264
|
+
while (searchFrom < len) {
|
|
1265
|
+
const cand = streamText.indexOf("EI", searchFrom);
|
|
1266
|
+
if (cand === -1) break;
|
|
1267
|
+
const beforeCh = streamText[cand - 1];
|
|
1268
|
+
const afterCh = cand + 2 < len ? streamText[cand + 2] : "";
|
|
1269
|
+
if (isPdfWs(beforeCh) && (!afterCh || isPdfDelimiter(afterCh))) {
|
|
1270
|
+
eiIdx = cand;
|
|
1271
|
+
break;
|
|
1272
|
+
}
|
|
1273
|
+
searchFrom = cand + 2;
|
|
1274
|
+
}
|
|
1275
|
+
if (eiIdx === -1) {
|
|
1276
|
+
out.push(streamText.slice(pos, biIdx + 2));
|
|
1277
|
+
pos = biIdx + 2;
|
|
1278
|
+
continue;
|
|
1279
|
+
}
|
|
1280
|
+
out.push(streamText.slice(pos, biIdx));
|
|
1281
|
+
out.push(" ");
|
|
1282
|
+
imageCount += 1;
|
|
1283
|
+
pos = eiIdx + 2;
|
|
1284
|
+
}
|
|
1285
|
+
return { cleaned: out.join(""), imageCount };
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
function parseContentStream(streamText, imageXObjNames, fontMap = new Map()) {
|
|
1289
|
+
const fontSizes = [];
|
|
1290
|
+
const rgbColors = [];
|
|
1291
|
+
let textOpCount = 0;
|
|
1292
|
+
const textParts = [];
|
|
1293
|
+
|
|
1294
|
+
// Count inline images (`BI ... ID ... EI`) linearly in O(N) without backtracking
|
|
1295
|
+
const { cleaned, imageCount: inlineImages } = stripInlineImagesLinear(streamText);
|
|
1296
|
+
let imageCount = inlineImages;
|
|
1297
|
+
|
|
1298
|
+
for (const m of cleaned.matchAll(/(?:^|[\s\]>])(0(?:\.\d+)?|1(?:\.0+)?|\.\d+)\s+(0(?:\.\d+)?|1(?:\.0+)?|\.\d+)\s+(0(?:\.\d+)?|1(?:\.0+)?|\.\d+)\s+(?:rg|RG)\b/g)) {
|
|
1299
|
+
rgbColors.push([
|
|
1300
|
+
Math.round(Number(m[1]) * 255),
|
|
1301
|
+
Math.round(Number(m[2]) * 255),
|
|
1302
|
+
Math.round(Number(m[3]) * 255),
|
|
1303
|
+
]);
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
for (const m of cleaned.matchAll(/\/([A-Za-z0-9_+.-]+)\s+Do\b/g)) {
|
|
1307
|
+
if (imageXObjNames.has(m[1])) {
|
|
1308
|
+
imageCount += 1;
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
// Scan text operators, active fonts, effective scaled sizes, /ActualText marked-content spans, and coordinate-aware line breaks
|
|
1313
|
+
let i = 0;
|
|
1314
|
+
let currentLine = "";
|
|
1315
|
+
let activeFont = null;
|
|
1316
|
+
let rawFontSize = 0;
|
|
1317
|
+
let lastName = null;
|
|
1318
|
+
let curY = null;
|
|
1319
|
+
let tm = [1, 0, 0, 1, 0, 0];
|
|
1320
|
+
let noArrayClose = false;
|
|
1321
|
+
const numStack = [];
|
|
1322
|
+
const mcStack = [];
|
|
1323
|
+
let actualTextDepth = 0;
|
|
1324
|
+
|
|
1325
|
+
const flushLine = () => {
|
|
1326
|
+
const t = currentLine.trim();
|
|
1327
|
+
if (t) textParts.push(t);
|
|
1328
|
+
currentLine = "";
|
|
1329
|
+
};
|
|
1330
|
+
|
|
1331
|
+
const recordEffectiveFontSize = () => {
|
|
1332
|
+
if (!(rawFontSize > 0)) return;
|
|
1333
|
+
const scaleY = Math.hypot(tm[2], tm[3]);
|
|
1334
|
+
const eff = Math.abs(rawFontSize) * (scaleY > 0 ? scaleY : 1);
|
|
1335
|
+
const rounded = Math.round(eff * 100) / 100;
|
|
1336
|
+
if (rounded >= 0.05 && rounded <= 300) {
|
|
1337
|
+
fontSizes.push(rounded);
|
|
1338
|
+
}
|
|
1339
|
+
};
|
|
1340
|
+
|
|
1341
|
+
const emitChunk = (str) => {
|
|
1342
|
+
if (!str) return;
|
|
1343
|
+
if (str.trim()) textOpCount += 1;
|
|
1344
|
+
currentLine += str;
|
|
1345
|
+
};
|
|
1346
|
+
|
|
1347
|
+
while (i < cleaned.length) {
|
|
1348
|
+
const ch = cleaned[i];
|
|
1349
|
+
if (isPdfWs(ch)) {
|
|
1350
|
+
i += 1;
|
|
1351
|
+
continue;
|
|
1352
|
+
}
|
|
1353
|
+
if (ch === "%") {
|
|
1354
|
+
const nl = cleaned.indexOf("\n", i);
|
|
1355
|
+
i = nl === -1 ? cleaned.length : nl + 1;
|
|
1356
|
+
continue;
|
|
1357
|
+
}
|
|
1358
|
+
if (ch === "(") {
|
|
1359
|
+
const { raw, endIdx } = readPdfLiteralAt(cleaned, i);
|
|
1360
|
+
const { op, endIdx: afterOp } = readPdfOpAt(cleaned, endIdx);
|
|
1361
|
+
if (op === "Tj" || op === "'" || op === '"') {
|
|
1362
|
+
recordEffectiveFontSize();
|
|
1363
|
+
if (actualTextDepth === 0) {
|
|
1364
|
+
if (op === "'" || op === '"') flushLine();
|
|
1365
|
+
emitChunk(decodePdfLiteralWithFont(raw, activeFont));
|
|
1366
|
+
}
|
|
1367
|
+
i = afterOp;
|
|
1368
|
+
numStack.length = 0;
|
|
1369
|
+
continue;
|
|
1370
|
+
}
|
|
1371
|
+
i = endIdx;
|
|
1372
|
+
continue;
|
|
1373
|
+
}
|
|
1374
|
+
if (ch === "<" && cleaned[i + 1] === "<") {
|
|
1375
|
+
const { raw: dictRaw, endIdx } = readPdfDictAt(cleaned, i);
|
|
1376
|
+
const { op, endIdx: afterOp } = readPdfOpAt(cleaned, endIdx);
|
|
1377
|
+
if (op === "BDC") {
|
|
1378
|
+
const actual = extractActualTextFromPropDict(dictRaw);
|
|
1379
|
+
if (actual !== null) {
|
|
1380
|
+
if (mcStack.length > 0) {
|
|
1381
|
+
mcStack[mcStack.length - 1].hasChildActual = true;
|
|
1382
|
+
}
|
|
1383
|
+
mcStack.push({ actualText: actual, hasChildActual: false });
|
|
1384
|
+
actualTextDepth += 1;
|
|
1385
|
+
} else {
|
|
1386
|
+
mcStack.push({ actualText: null, hasChildActual: false });
|
|
1387
|
+
}
|
|
1388
|
+
i = afterOp;
|
|
1389
|
+
numStack.length = 0;
|
|
1390
|
+
continue;
|
|
1391
|
+
}
|
|
1392
|
+
i = endIdx;
|
|
1393
|
+
continue;
|
|
1394
|
+
}
|
|
1395
|
+
if (ch === "<" && cleaned[i + 1] !== "<") {
|
|
1396
|
+
const closeIdx = cleaned.indexOf(">", i + 1);
|
|
1397
|
+
if (closeIdx !== -1) {
|
|
1398
|
+
const { op, endIdx: afterOp } = readPdfOpAt(cleaned, closeIdx + 1);
|
|
1399
|
+
if (op === "Tj" || op === "'" || op === '"') {
|
|
1400
|
+
recordEffectiveFontSize();
|
|
1401
|
+
if (actualTextDepth === 0) {
|
|
1402
|
+
if (op === "'" || op === '"') flushLine();
|
|
1403
|
+
emitChunk(decodePdfHexWithFont(cleaned.slice(i + 1, closeIdx), activeFont));
|
|
1404
|
+
}
|
|
1405
|
+
i = afterOp;
|
|
1406
|
+
numStack.length = 0;
|
|
1407
|
+
continue;
|
|
1408
|
+
}
|
|
1409
|
+
i = closeIdx + 1;
|
|
1410
|
+
continue;
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
if (ch === "[") {
|
|
1414
|
+
if (noArrayClose) {
|
|
1415
|
+
i += 1;
|
|
1416
|
+
continue;
|
|
1417
|
+
}
|
|
1418
|
+
let j = i + 1;
|
|
1419
|
+
let seg = "";
|
|
1420
|
+
let valid = false;
|
|
1421
|
+
let pendingSpace = false;
|
|
1422
|
+
let sawNum = false;
|
|
1423
|
+
let curNumStr = "";
|
|
1424
|
+
const flushKernNum = () => {
|
|
1425
|
+
if (curNumStr) {
|
|
1426
|
+
const kv = Number(curNumStr);
|
|
1427
|
+
if (Number.isFinite(kv) && kv <= -200 && seg.length > 0 && !/\s$/.test(seg)) {
|
|
1428
|
+
pendingSpace = true;
|
|
1429
|
+
}
|
|
1430
|
+
curNumStr = "";
|
|
1431
|
+
}
|
|
1432
|
+
sawNum = false;
|
|
1433
|
+
};
|
|
1434
|
+
while (j < cleaned.length) {
|
|
1435
|
+
const cj = cleaned[j];
|
|
1436
|
+
if (cj === "(") {
|
|
1437
|
+
flushKernNum();
|
|
1438
|
+
const lit = readPdfLiteralAt(cleaned, j);
|
|
1439
|
+
if (actualTextDepth === 0) {
|
|
1440
|
+
const dec = decodePdfLiteralWithFont(lit.raw, activeFont);
|
|
1441
|
+
if (dec) {
|
|
1442
|
+
if (pendingSpace && !/^\s/.test(dec)) seg += " ";
|
|
1443
|
+
pendingSpace = false;
|
|
1444
|
+
seg += dec;
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
j = lit.endIdx;
|
|
1448
|
+
continue;
|
|
1449
|
+
}
|
|
1450
|
+
if (cj === "<" && cleaned[j + 1] !== "<") {
|
|
1451
|
+
flushKernNum();
|
|
1452
|
+
const c2 = cleaned.indexOf(">", j + 1);
|
|
1453
|
+
if (c2 !== -1) {
|
|
1454
|
+
if (actualTextDepth === 0) {
|
|
1455
|
+
const dec = decodePdfHexWithFont(cleaned.slice(j + 1, c2), activeFont);
|
|
1456
|
+
if (dec) {
|
|
1457
|
+
if (pendingSpace && !/^\s/.test(dec)) seg += " ";
|
|
1458
|
+
pendingSpace = false;
|
|
1459
|
+
seg += dec;
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1462
|
+
j = c2 + 1;
|
|
1463
|
+
continue;
|
|
1464
|
+
}
|
|
1465
|
+
}
|
|
1466
|
+
if (cj === "]") {
|
|
1467
|
+
flushKernNum();
|
|
1468
|
+
const { op, endIdx: afterOp } = readPdfOpAt(cleaned, j + 1);
|
|
1469
|
+
if (op === "TJ") {
|
|
1470
|
+
valid = true;
|
|
1471
|
+
j = afterOp;
|
|
1472
|
+
} else {
|
|
1473
|
+
j += 1;
|
|
1474
|
+
}
|
|
1475
|
+
break;
|
|
1476
|
+
}
|
|
1477
|
+
if (cj === "[" || j - i > 262144) {
|
|
1478
|
+
break;
|
|
1479
|
+
}
|
|
1480
|
+
if ((cj >= "0" && cj <= "9") || cj === "-" || cj === "+" || cj === ".") {
|
|
1481
|
+
curNumStr += cj;
|
|
1482
|
+
sawNum = true;
|
|
1483
|
+
} else if (sawNum) {
|
|
1484
|
+
flushKernNum();
|
|
1485
|
+
}
|
|
1486
|
+
j += 1;
|
|
1487
|
+
}
|
|
1488
|
+
if (j >= cleaned.length && !valid) noArrayClose = true;
|
|
1489
|
+
if (valid) {
|
|
1490
|
+
recordEffectiveFontSize();
|
|
1491
|
+
if (actualTextDepth === 0) {
|
|
1492
|
+
emitChunk(seg);
|
|
1493
|
+
}
|
|
1494
|
+
i = j;
|
|
1495
|
+
numStack.length = 0;
|
|
1496
|
+
continue;
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
if (ch === "/") {
|
|
1500
|
+
let j = i + 1;
|
|
1501
|
+
while (j < cleaned.length && !isPdfDelimiter(cleaned[j])) j += 1;
|
|
1502
|
+
lastName = cleaned.slice(i + 1, j);
|
|
1503
|
+
i = j;
|
|
1504
|
+
continue;
|
|
1505
|
+
}
|
|
1506
|
+
// Read word/number token
|
|
1507
|
+
let endTok = i;
|
|
1508
|
+
while (endTok < cleaned.length && !isPdfDelimiter(cleaned[endTok])) endTok += 1;
|
|
1509
|
+
const tok = cleaned.slice(i, endTok);
|
|
1510
|
+
if (/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(tok)) {
|
|
1511
|
+
numStack.push(Number(tok));
|
|
1512
|
+
if (numStack.length > 8) numStack.shift();
|
|
1513
|
+
} else {
|
|
1514
|
+
if (tok === "Tf") {
|
|
1515
|
+
activeFont = (lastName && fontMap.get(lastName)) || null;
|
|
1516
|
+
if (numStack.length >= 1) {
|
|
1517
|
+
rawFontSize = Math.abs(numStack[numStack.length - 1]);
|
|
1518
|
+
}
|
|
1519
|
+
} else if (tok === "BT") {
|
|
1520
|
+
curY = null;
|
|
1521
|
+
tm = [1, 0, 0, 1, 0, 0];
|
|
1522
|
+
} else if (tok === "ET") {
|
|
1523
|
+
flushLine();
|
|
1524
|
+
curY = null;
|
|
1525
|
+
} else if (tok === "T*") {
|
|
1526
|
+
flushLine();
|
|
1527
|
+
} else if (tok === "Td" || tok === "TD") {
|
|
1528
|
+
const tx = numStack.length >= 2 ? numStack[numStack.length - 2] : 0;
|
|
1529
|
+
const ty = numStack.length >= 2 ? numStack[numStack.length - 1] : 0;
|
|
1530
|
+
tm[4] += tx;
|
|
1531
|
+
tm[5] += ty;
|
|
1532
|
+
if (Math.abs(ty) > 2.0) flushLine();
|
|
1533
|
+
curY = (curY ?? 0) + ty;
|
|
1534
|
+
} else if (tok === "Tm") {
|
|
1535
|
+
if (numStack.length >= 6) {
|
|
1536
|
+
const vals = numStack.slice(-6);
|
|
1537
|
+
const f = vals[5];
|
|
1538
|
+
if (curY !== null && Math.abs(f - curY) > 2.0) flushLine();
|
|
1539
|
+
curY = f;
|
|
1540
|
+
tm = vals;
|
|
1541
|
+
}
|
|
1542
|
+
} else if (tok === "BMC" || tok === "BDC") {
|
|
1543
|
+
mcStack.push({ actualText: null, hasChildActual: false });
|
|
1544
|
+
} else if (tok === "EMC") {
|
|
1545
|
+
const frame = mcStack.pop();
|
|
1546
|
+
if (frame && frame.actualText !== null) {
|
|
1547
|
+
actualTextDepth = Math.max(0, actualTextDepth - 1);
|
|
1548
|
+
if (!frame.hasChildActual && actualTextDepth === 0) {
|
|
1549
|
+
emitChunk(frame.actualText);
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
numStack.length = 0;
|
|
1554
|
+
}
|
|
1555
|
+
i = endTok === i ? i + 1 : endTok;
|
|
1556
|
+
}
|
|
1557
|
+
flushLine();
|
|
1558
|
+
|
|
1559
|
+
if (fontSizes.length === 0 && rawFontSize > 0) {
|
|
1560
|
+
recordEffectiveFontSize();
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
return {
|
|
1564
|
+
text: textParts.join("\n"),
|
|
1565
|
+
fontSizes,
|
|
1566
|
+
rgbColors,
|
|
1567
|
+
imageCount,
|
|
1568
|
+
textOpCount,
|
|
1569
|
+
};
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
function resolvePageFontMap(resText, objects, fontCache) {
|
|
1573
|
+
const fontMap = new Map();
|
|
1574
|
+
const fontRefs = [];
|
|
1575
|
+
const inlineM = resText.match(/\/Font\s*<<([\s\S]*?)>>/);
|
|
1576
|
+
if (inlineM) {
|
|
1577
|
+
for (const fm of inlineM[1].matchAll(/\/([A-Za-z0-9_+.-]+)\s+(\d+)\s+\d+\s+R/g)) {
|
|
1578
|
+
fontRefs.push([fm[1], Number(fm[2])]);
|
|
1579
|
+
}
|
|
1580
|
+
}
|
|
1581
|
+
for (const refM of resText.matchAll(/\/Font\s+(\d+)\s+\d+\s+R/g)) {
|
|
1582
|
+
const fDictObj = objects.get(Number(refM[1]));
|
|
1583
|
+
if (fDictObj) {
|
|
1584
|
+
for (const fm of fDictObj.dictRaw.matchAll(/\/([A-Za-z0-9_+.-]+)\s+(\d+)\s+\d+\s+R/g)) {
|
|
1585
|
+
fontRefs.push([fm[1], Number(fm[2])]);
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
for (const [alias, fObjNum] of fontRefs) {
|
|
1591
|
+
if (fontCache.has(fObjNum)) {
|
|
1592
|
+
fontMap.set(alias, fontCache.get(fObjNum));
|
|
1593
|
+
continue;
|
|
1594
|
+
}
|
|
1595
|
+
const fObj = objects.get(fObjNum);
|
|
1596
|
+
if (!fObj) continue;
|
|
1597
|
+
let fullDict = fObj.dictRaw || "";
|
|
1598
|
+
const descM = fullDict.match(/\/DescendantFonts\s*\[\s*(\d+)\s+\d+\s+R/);
|
|
1599
|
+
if (descM && objects.has(Number(descM[1]))) {
|
|
1600
|
+
fullDict += "\n" + (objects.get(Number(descM[1])).dictRaw || "");
|
|
1601
|
+
}
|
|
1602
|
+
let toUnicode = null;
|
|
1603
|
+
const tuM = fullDict.match(/\/ToUnicode\s+(\d+)\s+\d+\s+R/);
|
|
1604
|
+
if (tuM && objects.has(Number(tuM[1]))) {
|
|
1605
|
+
const cmapStr = decodeObjectStream(objects.get(Number(tuM[1])));
|
|
1606
|
+
const parsed = parseToUnicodeCMap(cmapStr);
|
|
1607
|
+
if (parsed.map.size > 0 || parsed.ranges.length > 0) toUnicode = parsed;
|
|
1608
|
+
}
|
|
1609
|
+
const differences = parseEncodingDifferences(fullDict, objects);
|
|
1610
|
+
const hasStdBaseEnc = /\/BaseEncoding\s*\/(?:WinAnsiEncoding|MacRomanEncoding|StandardEncoding)\b/.test(fullDict);
|
|
1611
|
+
const isCustomGlyph =
|
|
1612
|
+
(/\/Subtype\s*\/(?:Type3|Type0)\b|\/Identity-[HV]\b/.test(fullDict) || Boolean(toUnicode)) &&
|
|
1613
|
+
!hasStdBaseEnc;
|
|
1614
|
+
const entry = { toUnicode, differences, isCustomGlyph };
|
|
1615
|
+
fontCache.set(fObjNum, entry);
|
|
1616
|
+
fontMap.set(alias, entry);
|
|
1617
|
+
}
|
|
1618
|
+
return fontMap;
|
|
1619
|
+
}
|
|
1620
|
+
|
|
1621
|
+
/**
|
|
1622
|
+
* Pure Node.js standard-library PDF parser for visual/layout anti-slop inspection.
|
|
1623
|
+
* Supports FlateDecode streams, PDF 1.5+ /ObjStm, /ActualText, /ToUnicode CMap, Type3 /Differences, MediaBox inheritance, font sizes, RGB fills/shadings, and image XObjects.
|
|
1624
|
+
*/
|
|
1625
|
+
export function parsePdfBuffer(buffer) {
|
|
1626
|
+
if (!Buffer.isBuffer(buffer) || buffer.length < 8) {
|
|
1627
|
+
throw new Error("Invalid or truncated PDF buffer");
|
|
1628
|
+
}
|
|
1629
|
+
const head = buffer.subarray(0, Math.min(1024, buffer.length)).toString("latin1");
|
|
1630
|
+
if (!head.includes("%PDF-")) {
|
|
1631
|
+
throw new Error("Invalid PDF header (missing %PDF-)");
|
|
1632
|
+
}
|
|
1633
|
+
|
|
1634
|
+
const { latin, objects, hasCompressedStreams } = extractPdfObjects(buffer);
|
|
1635
|
+
|
|
1636
|
+
// Detect encrypted PDFs honestly: check trailer & non-stream dicts for /Encrypt
|
|
1637
|
+
const trailerMatch = latin.match(/trailer\s*<<[\s\S]*?>>/);
|
|
1638
|
+
if (trailerMatch && /\/Encrypt\b/.test(trailerMatch[0])) {
|
|
1639
|
+
return { encrypted: true, pageCount: 0, metadata: {}, pages: [] };
|
|
1640
|
+
}
|
|
1641
|
+
for (const obj of objects.values()) {
|
|
1642
|
+
if (!obj.streamBytes && /\/Encrypt\b/.test(obj.dictRaw)) {
|
|
1643
|
+
return { encrypted: true, pageCount: 0, metadata: {}, pages: [] };
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
|
|
1647
|
+
// Extract Producer/Creator metadata from /Info or XMP
|
|
1648
|
+
let producer = "";
|
|
1649
|
+
let creator = "";
|
|
1650
|
+
let hasFonts = false;
|
|
1651
|
+
for (const obj of objects.values()) {
|
|
1652
|
+
if (/\/Type\s*\/Font\b|\/Subtype\s*\/(?:Type0|Type1|Type3|TrueType|CIDFontType[02])\b/.test(obj.dictRaw)) {
|
|
1653
|
+
hasFonts = true;
|
|
1654
|
+
}
|
|
1655
|
+
if (!obj.streamBytes && (/\/Producer\b/.test(obj.dictRaw) || /\/Creator\b/.test(obj.dictRaw))) {
|
|
1656
|
+
const pm = obj.dictRaw.match(/\/Producer\s*\(([^)]*)\)/);
|
|
1657
|
+
if (pm) producer = decodePdfLiteralString(pm[1]);
|
|
1658
|
+
const cm = obj.dictRaw.match(/\/Creator\s*\(([^)]*)\)/);
|
|
1659
|
+
if (cm) creator = decodePdfLiteralString(cm[1]);
|
|
1660
|
+
}
|
|
1661
|
+
}
|
|
1662
|
+
|
|
1663
|
+
// Collect global image XObject numbers and shading RGB stops
|
|
1664
|
+
const imageObjNums = new Set();
|
|
1665
|
+
const shadingObjColors = new Map();
|
|
1666
|
+
for (const obj of objects.values()) {
|
|
1667
|
+
if (/\/Subtype\s*\/Image\b/.test(obj.dictRaw)) {
|
|
1668
|
+
imageObjNums.add(obj.objNum);
|
|
1669
|
+
}
|
|
1670
|
+
const cols = [];
|
|
1671
|
+
collectRgbStopsFromDict(obj.dictRaw, cols);
|
|
1672
|
+
if (cols.length > 0) shadingObjColors.set(obj.objNum, cols);
|
|
1673
|
+
}
|
|
1674
|
+
|
|
1675
|
+
function extractOwnResourcesText(dictRaw) {
|
|
1676
|
+
let out = dictRaw || "";
|
|
1677
|
+
const resRef = out.match(/\/Resources\s+(\d+)\s+\d+\s+R/);
|
|
1678
|
+
if (resRef && objects.has(Number(resRef[1]))) {
|
|
1679
|
+
out += "\n" + objects.get(Number(resRef[1])).dictRaw;
|
|
1680
|
+
}
|
|
1681
|
+
return out;
|
|
1682
|
+
}
|
|
1683
|
+
|
|
1684
|
+
// Order pages via /Catalog -> /Pages -> /Kids tree (iterative + inherited MediaBox & Resources)
|
|
1685
|
+
const orderedPageObjs = [];
|
|
1686
|
+
const inheritedMediaBox = new Map();
|
|
1687
|
+
const inheritedResources = new Map();
|
|
1688
|
+
const visitedTree = new Set();
|
|
1689
|
+
|
|
1690
|
+
function walkPagesTreeIterative(rootNum) {
|
|
1691
|
+
const work = [{ objNum: rootNum, parentBox: null, parentRes: "" }];
|
|
1692
|
+
while (work.length > 0) {
|
|
1693
|
+
const { objNum, parentBox, parentRes } = work.pop();
|
|
1694
|
+
if (visitedTree.has(objNum)) continue;
|
|
1695
|
+
visitedTree.add(objNum);
|
|
1696
|
+
const obj = objects.get(objNum);
|
|
1697
|
+
if (!obj) continue;
|
|
1698
|
+
const ownBox = parseMediaBoxRect(obj.dictRaw) || parentBox;
|
|
1699
|
+
const hasOwnRes = /\/Resources(?:\s|\n|<<)/.test(obj.dictRaw);
|
|
1700
|
+
const combinedRes = hasOwnRes ? `${parentRes}\n${extractOwnResourcesText(obj.dictRaw)}` : parentRes;
|
|
1701
|
+
if (/\/Type\s*\/Pages\b/.test(obj.dictRaw)) {
|
|
1702
|
+
const kidsMatch = obj.dictRaw.match(/\/Kids\s*\[([^\]]*)\]/);
|
|
1703
|
+
if (kidsMatch) {
|
|
1704
|
+
const kids = [...kidsMatch[1].matchAll(/(\d+)\s+\d+\s+R/g)].map((rm) => Number(rm[1]));
|
|
1705
|
+
for (let k = kids.length - 1; k >= 0; k -= 1) {
|
|
1706
|
+
work.push({ objNum: kids[k], parentBox: ownBox, parentRes: combinedRes });
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
continue;
|
|
1710
|
+
}
|
|
1711
|
+
if (/\/Type\s*\/Page(?![a-zA-Z])/.test(obj.dictRaw)) {
|
|
1712
|
+
inheritedMediaBox.set(objNum, ownBox || [612, 792]);
|
|
1713
|
+
inheritedResources.set(objNum, combinedRes || extractOwnResourcesText(obj.dictRaw));
|
|
1714
|
+
orderedPageObjs.push(obj);
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
|
|
1719
|
+
const catalogObj = Array.from(objects.values()).find((o) => /\/Type\s*\/Catalog\b/.test(o.dictRaw));
|
|
1720
|
+
if (catalogObj) {
|
|
1721
|
+
const pagesRef = catalogObj.dictRaw.match(/\/Pages\s+(\d+)\s+\d+\s+R/);
|
|
1722
|
+
if (pagesRef) walkPagesTreeIterative(Number(pagesRef[1]));
|
|
1723
|
+
}
|
|
1724
|
+
if (orderedPageObjs.length === 0) {
|
|
1725
|
+
for (const obj of Array.from(objects.values()).sort((a, b) => a.objNum - b.objNum)) {
|
|
1726
|
+
if (/\/Type\s*\/Page(?![a-zA-Z])/.test(obj.dictRaw)) {
|
|
1727
|
+
inheritedMediaBox.set(obj.objNum, parseMediaBoxRect(obj.dictRaw) || [612, 792]);
|
|
1728
|
+
inheritedResources.set(obj.objNum, extractOwnResourcesText(obj.dictRaw));
|
|
1729
|
+
orderedPageObjs.push(obj);
|
|
1730
|
+
}
|
|
1731
|
+
}
|
|
1732
|
+
}
|
|
1733
|
+
|
|
1734
|
+
const fontCache = new Map();
|
|
1735
|
+
const pages = orderedPageObjs.map((pageObj, idx) => {
|
|
1736
|
+
const [width, height] = inheritedMediaBox.get(pageObj.objNum) || [612, 792];
|
|
1737
|
+
const isLandscape = width > height;
|
|
1738
|
+
const resText = inheritedResources.get(pageObj.objNum) || extractOwnResourcesText(pageObj.dictRaw);
|
|
1739
|
+
|
|
1740
|
+
const fontMap = resolvePageFontMap(resText, objects, fontCache);
|
|
1741
|
+
if (fontMap.size > 0) hasFonts = true;
|
|
1742
|
+
|
|
1743
|
+
const imageXObjNames = new Set();
|
|
1744
|
+
for (const xm of resText.matchAll(/\/([A-Za-z0-9_+.-]+)\s+(\d+)\s+\d+\s+R/g)) {
|
|
1745
|
+
if (imageObjNums.has(Number(xm[2]))) {
|
|
1746
|
+
imageXObjNames.add(xm[1]);
|
|
1747
|
+
}
|
|
1748
|
+
}
|
|
1749
|
+
|
|
1750
|
+
const resourceColors = [];
|
|
1751
|
+
collectRgbStopsFromDict(resText, resourceColors);
|
|
1752
|
+
for (const rm of resText.matchAll(/(\d+)\s+\d+\s+R/g)) {
|
|
1753
|
+
const refNum = Number(rm[1]);
|
|
1754
|
+
const cols = shadingObjColors.get(refNum);
|
|
1755
|
+
if (cols) resourceColors.push(...cols);
|
|
1756
|
+
const refObj = objects.get(refNum);
|
|
1757
|
+
if (refObj) {
|
|
1758
|
+
for (const subRef of refObj.dictRaw.matchAll(/(\d+)\s+\d+\s+R/g)) {
|
|
1759
|
+
const subCols = shadingObjColors.get(Number(subRef[1]));
|
|
1760
|
+
if (subCols) resourceColors.push(...subCols);
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
|
|
1765
|
+
// Resolve /Contents stream(s)
|
|
1766
|
+
const contentRefs = [];
|
|
1767
|
+
const arrMatch = pageObj.dictRaw.match(/\/Contents\s*\[([^\]]*)\]/);
|
|
1768
|
+
if (arrMatch) {
|
|
1769
|
+
for (const rm of arrMatch[1].matchAll(/(\d+)\s+\d+\s+R/g)) contentRefs.push(Number(rm[1]));
|
|
1770
|
+
} else {
|
|
1771
|
+
const singleMatch = pageObj.dictRaw.match(/\/Contents\s+(\d+)\s+\d+\s+R/);
|
|
1772
|
+
if (singleMatch) contentRefs.push(Number(singleMatch[1]));
|
|
1773
|
+
}
|
|
1774
|
+
|
|
1775
|
+
const joinedStream = contentRefs.map((id) => decodeObjectStream(objects.get(id))).join("\n");
|
|
1776
|
+
const parsed = parseContentStream(joinedStream, imageXObjNames, fontMap);
|
|
1777
|
+
|
|
1778
|
+
return {
|
|
1779
|
+
pageNum: idx + 1,
|
|
1780
|
+
width: Math.round(width * 100) / 100,
|
|
1781
|
+
height: Math.round(height * 100) / 100,
|
|
1782
|
+
isLandscape,
|
|
1783
|
+
text: parsed.text,
|
|
1784
|
+
hasFonts: fontMap.size > 0,
|
|
1785
|
+
fontSizes: parsed.fontSizes,
|
|
1786
|
+
rgbColors: [...parsed.rgbColors, ...resourceColors],
|
|
1787
|
+
imageCount: parsed.imageCount,
|
|
1788
|
+
textOpCount: parsed.textOpCount,
|
|
1789
|
+
};
|
|
1790
|
+
});
|
|
1791
|
+
|
|
1792
|
+
return {
|
|
1793
|
+
encrypted: false,
|
|
1794
|
+
pageCount: pages.length,
|
|
1795
|
+
hasFonts,
|
|
1796
|
+
hasCompressedStreams,
|
|
1797
|
+
metadata: { producer, creator },
|
|
1798
|
+
pages,
|
|
1799
|
+
};
|
|
1800
|
+
}
|