MCPcopy Create free account
hub / github.com/LibPDF-js/core / DocumentParser

Class DocumentParser

src/parser/document-parser.ts:143–913  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

141 * ```
142 */
143export class DocumentParser {
144 private readonly scanner: Scanner;
145 private readonly options: ParseOptions;
146 private readonly warnings: string[] = [];
147
148 constructor(scanner: Scanner, options: ParseOptions = {}) {
149 this.scanner = scanner;
150 this.options = {
151 lenient: options.lenient ?? true,
152 credentials: options.credentials,
153 };
154 }
155
156 /**
157 * Parse the PDF document.
158 */
159 parse(): ParsedDocument {
160 try {
161 return this.parseNormal();
162 } catch (error) {
163 // Only attempt recovery for recoverable parsing errors
164 if (this.options.lenient && error instanceof RecoverableParseError) {
165 this.warnings.push(`Normal parsing failed: ${error.message}`);
166
167 return this.parseWithRecovery();
168 }
169
170 // All other errors propagate (credentials, unsupported features, etc.)
171 throw error;
172 }
173 }
174
175 /**
176 * Normal parsing path.
177 */
178 private parseNormal(): ParsedDocument {
179 // Phase 1: Parse header
180 const version = this.parseHeader();
181
182 // Phase 2: Find startxref
183 const xrefParser = new XRefParser(this.scanner);
184
185 const startXRef = xrefParser.findStartXRef();
186
187 // Phase 3: Parse XRef chain (follow /Prev)
188 const { xref, trailer } = this.parseXRefChain(xrefParser, startXRef);
189
190 // Phase 4: Build document with lazy object loading
191 return this.buildDocument(version, xref, trailer, false);
192 }
193
194 /**
195 * Recovery parsing using brute-force when normal parsing fails.
196 */
197 private parseWithRecovery(): ParsedDocument {
198 // Try to get version even if header is malformed
199 let version = DEFAULT_VERSION;
200

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected