@docling/docling-client 0.1.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.
@@ -0,0 +1,360 @@
1
+ # Python client parity
2
+
3
+ This document compares `@docling/docling-client` with Docling Python 2.115.0
4
+ at commit `f4380498`, specifically:
5
+
6
+ - `DoclingServiceClient`
7
+ - `AsyncDoclingServiceClient`
8
+ - `ConversionJob` and `AsyncConversionJob`
9
+ - the shared request, response, watcher, scheduler, and error contracts
10
+
11
+ TypeScript is naturally asynchronous, so Python's synchronous and asynchronous
12
+ facades map to one Promise/`AsyncIterable` API. No Python service-client
13
+ capability is deferred in this package. Language-specific adaptations and
14
+ additional TypeScript capabilities are documented after the parity tables.
15
+
16
+ ## Client configuration
17
+
18
+ | Python constructor capability | TypeScript | Parity notes |
19
+ | ----------------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
20
+ | Service URL | `baseUrl` | Both normalize trailing slashes and reject `/v1`, query, and fragment components. |
21
+ | API key | `apiKey` | HTTP uses `X-Api-Key`; WebSocket uses the query parameter and also the header in Node. |
22
+ | Default conversion options | `options` | Deep-copied at construction; per-call merge is shallow. |
23
+ | Status watcher | `statusWatcher` | `websocket` default or `polling`. |
24
+ | WebSocket polling fallback | `webSocketFallbackToPoll` | Enabled by default. |
25
+ | Poll server wait | `pollServerWaitSeconds` | Five seconds by default. |
26
+ | Poll client interval | `pollClientIntervalMs` | Defaults to the server-wait duration. |
27
+ | Job timeout | `jobTimeoutMs` | Five minutes by default. |
28
+ | Conversion concurrency | `maxConcurrency` | Eight by default; valid range 1–512. |
29
+ | HTTP retries | `httpRetries` | Three by default. |
30
+ | HTTP timeout | `httpTimeoutMs` | Fetch has one total per-attempt timeout; Python/httpx exposes distinct connect and read/write/pool timeouts. |
31
+ | HTTP backoff | `httpBackoffBaseMs` | One second by default. |
32
+ | Artifact timeout and size | `artifactDownload.timeoutMs`, `maxBytes` | Same 60-second and 512-MiB defaults. |
33
+ | Private artifact override | `artifactDownload.allowPrivateUrls` | Public TypeScript option; Python keeps its equivalent internal. |
34
+ | Owned resource cleanup | `close()` | TypeScript close is asynchronous, idempotent, closes an injected transport once, and prevents later requests. |
35
+
36
+ `fetch`, `transport`, `webSocketFactory`, `artifactDownloader`, and artifact
37
+ DNS/fetch injection are TypeScript extensions.
38
+
39
+ ## Public operations
40
+
41
+ | Capability | Python | TypeScript | Result/behavior |
42
+ | ------------------------ | ------------------------------- | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
43
+ | Health | `health()` | `health()` | No retries; validates `HealthCheckResponse`, including the default `"ok"` status. |
44
+ | Version | `version()` | `version()` | No retries; requires an object response. |
45
+ | Close | `close()` / `aclose()` | `close()` | Resource cleanup. |
46
+ | Convert one | sync `convert()` | async `convert()` | High-level `ConversionResult`; presigned-first, safe materialization, narrow in-body fallback, Markdown+JSON default. |
47
+ | Convert many | sync `convert_all()` | async iterable `convertAll()` | One task per source, lazy bounded scheduling, input order, per-source failure isolation. |
48
+ | Submit one | `submit()` | `submitSource()` or `submit()` | Typed job; explicit in-body target resolves to `ConversionResult`. |
49
+ | URL convenience | HTTP source model | `submitUrl()` | Adds separate source-fetch headers. |
50
+ | Base64 convenience | file source model | `submitFile()` | Unified base64 source. |
51
+ | Local/binary convenience | `Path` / `DocumentStream` | path string / `submitBinary()` | Multipart where the route can represent the target; unified base64 otherwise. |
52
+ | Batch connectors | `submit_batch()` | `submitBatch()` | Remote source enumeration and remote/presigned target. |
53
+ | Output-format override | `output_formats=` | `outputFormats` | Overrides merged `to_formats` for submit/batch convenience calls. |
54
+ | Submit chunk job | `submit_chunk()` | `submitChunk*()` | Hybrid or hierarchical job. |
55
+ | Convert and chunk | sync `chunk()` | async `chunk()` | Combined service conversion and chunking. |
56
+ | Per-item fan-out | `submit_and_retrieve_each()` | `submitAndRetrieveEach()` | Lazy bounded full-lifecycle scheduling; completion or input order. |
57
+ | Deprecated fan-out name | `submit_and_retrieve_many()` | `submitAndRetrieveMany()` | Alias retained. |
58
+ | Attach to task | internal job construction | `job()` | TypeScript exposes attachment publicly. |
59
+ | Poll | job `poll()` | client/job `poll()` | `wait=0` default; task-not-found mapping. |
60
+ | Watch | job `watch()` | client/job `watch()` | WebSocket handshake/reconnect/fallback or polling. |
61
+ | Wait | job `result()` waits internally | job `wait()` and `result()` | TypeScript exposes terminal wait separately. |
62
+ | Fetch typed result | job `result()` | job `getResult()` / `result()` | Target-specific loader. |
63
+ | Fetch raw result | internal helpers | `getRawResult()` / `getBinaryResult()` | TypeScript extension for integrations. |
64
+
65
+ The Python asynchronous facade intentionally omits high-level
66
+ `convert()`, `convert_all()`, and `chunk()` methods. TypeScript includes them
67
+ because async is its native execution model.
68
+
69
+ ## Sources
70
+
71
+ | Source | Ordinary conversion/chunk | Batch | Notes |
72
+ | ------------------------------------ | ------------------------- | ----- | -------------------------------------------------------------------------- |
73
+ | HTTP(S) | Yes | Yes | Headers are preserved; ordinary conversion rejects `.zip` URLs. |
74
+ | Base64 file | Yes | No | JSON `FileSource`. |
75
+ | Local path | Yes, Node | No | Read lazily when normalized, then multipart or base64 depending on target. |
76
+ | `Blob` / `ArrayBuffer` / typed array | Yes | No | TypeScript extension for Node/browser integrations. |
77
+ | S3 | No | Yes | Endpoint, SSL flag, keys, bucket, prefix, enumeration limit. |
78
+ | Azure Blob | No | Yes | Account, container, connection string, prefix, enumeration limit. |
79
+ | Google Cloud Storage | No | Yes | Bucket, prefix, project/ADC, optional service-account object. |
80
+ | Google Drive | No | Yes | Path, token/refresh token, credentials path/object. |
81
+ | Generic connector | No | Yes | Forward-compatible `kind` plus connector fields. |
82
+
83
+ TypeScript mirrors Python's extension-to-input-format map, including Office
84
+ templates/macros, images, XML variants, `tar.gz`, audio/video, email, EPUB, and
85
+ Box Note. Unknown extensions use the same PDF fallback. Local multipart MIME is
86
+ inferred from the filename when known.
87
+
88
+ ## Targets and target-specific results
89
+
90
+ | Target | Ordinary | Batch | TypeScript job result |
91
+ | -------------------- | ----------------- | ----- | ------------------------------------------------------------- |
92
+ | In body | Yes | No | `ConversionResult` |
93
+ | ZIP | Yes | No | `RawServiceResult` |
94
+ | Presigned URL | Yes | Yes | `PresignedUrlConvertResponse` with documents/artifacts/counts |
95
+ | S3 | Yes | Yes | outcome counts |
96
+ | Azure Blob | Yes | Yes | outcome counts |
97
+ | Google Cloud Storage | Yes | Yes | outcome counts |
98
+ | Google Drive | Yes | Yes | outcome counts |
99
+ | Generic | Python batch only | Yes | outcome counts |
100
+ | Put URL | Wire model only | No | TypeScript low-level ordinary-target extension |
101
+
102
+ `RemoteTargetResponse` is the clearer TypeScript alias for Python's historical
103
+ `PresignedUrlConvertDocumentResponse` counts-only name.
104
+
105
+ When a binary/local source uses Put or a storage target, TypeScript uses the
106
+ unified base64 endpoint rather than dropping target coordinates in the
107
+ multipart `target_type` field. This is stricter and more functional than the
108
+ overbroad Python multipart target annotation.
109
+
110
+ ## Conversion options and limits
111
+
112
+ The explicit TypeScript option surface covers every field in Python
113
+ `ConvertDocumentsOptions`:
114
+
115
+ - `from_formats`, `to_formats`, `pipeline`, `page_range`
116
+ - `image_export_mode`, `include_images`, `include_page_images`, `images_scale`
117
+ - `do_ocr`, `force_ocr`, `ocr_engine`, `ocr_preset`, `ocr_lang`,
118
+ `ocr_custom_config`
119
+ - `pdf_backend`
120
+ - `table_mode`, `table_cell_matching`, `do_table_structure`
121
+ - `do_code_enrichment`, `do_formula_enrichment`
122
+ - `do_picture_classification`, `do_picture_description`,
123
+ `do_chart_extraction`, `picture_description_area_threshold`
124
+ - the deprecated `picture_description_local`, `picture_description_api`,
125
+ `vlm_pipeline_model`, `vlm_pipeline_model_local`, and
126
+ `vlm_pipeline_model_api`
127
+ - VLM, picture-description, code/formula, table-structure, layout, and
128
+ picture-classification preset/custom-config pairs
129
+ - `document_timeout`, `abort_on_error`, and Markdown page-break placeholder
130
+
131
+ Known enums, page ranges, primitive shapes, and nested option object boundaries
132
+ are checked locally. Legacy VLM/picture-description model objects and the
133
+ Python model's preset/custom and legacy/new mutual-exclusion rules are also
134
+ validated before submission, including the exact Docling Core picture
135
+ classification labels. The string index accepts options introduced by a newer
136
+ managed service without forcing a client release.
137
+
138
+ Constructor options are copied. Per-call fields replace constructor fields at
139
+ the top level; `undefined` means no override and `null` clears an optional
140
+ default. Neither caller object is mutated.
141
+
142
+ High-level limits match Python:
143
+
144
+ - `maxNumPages` caps the effective page-range end.
145
+ - `pageRange` overrides the option's page range.
146
+ - `maxFileSize` preflights local, base64, and binary sources.
147
+ - Oversized input becomes a skipped result unless `raisesOnError` is enabled.
148
+ - Remote URL size remains unknown before service fetch.
149
+
150
+ TypeScript restricts limit values to safe integers, which is stricter than
151
+ Python's unbounded integer type.
152
+
153
+ ## Chunking
154
+
155
+ Both clients call the dedicated async routes:
156
+
157
+ ```text
158
+ POST /v1/chunk/hybrid/source/async
159
+ POST /v1/chunk/hybrid/file/async
160
+ POST /v1/chunk/hierarchical/source/async
161
+ POST /v1/chunk/hierarchical/file/async
162
+ ```
163
+
164
+ Both support:
165
+
166
+ - conversion options;
167
+ - hybrid `max_tokens`, `tokenizer`, and `merge_peers`;
168
+ - shared `use_markdown_tables`, `use_markdown_images`, `image_placeholder`,
169
+ and `include_raw_text`;
170
+ - `include_converted_doc`;
171
+ - in-body `ChunkDocumentResponse`;
172
+ - URL/base64/local/binary input.
173
+
174
+ TypeScript additionally exposes multi-source JSON chunk jobs, all chunker
175
+ options directly, and callbacks on JSON chunk requests. The multipart Serve
176
+ route has no callback form field, so the client rejects callbacks there rather
177
+ than silently discarding them. Known chunk-option primitives are validated
178
+ locally, and the route-selected chunker discriminator cannot be overridden by
179
+ an untyped payload.
180
+
181
+ `OutputFormat` still contains `"chunks"` because the Python enum does. That
182
+ value does not select a Serve chunk task; callers use the chunk routes.
183
+
184
+ ## Jobs, watchers, and scheduling
185
+
186
+ | Behavior | Python | TypeScript |
187
+ | ------------------------- | -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
188
+ | Initial task data | task id, submitted time, status, position | Same |
189
+ | `status` property | status string | Full cached `TaskStatusResponse` |
190
+ | Queue position | Yes | Yes |
191
+ | Done state | success/failure | Same |
192
+ | Poll default | `wait=0` | Same |
193
+ | Default watch | WebSocket | Same |
194
+ | WebSocket auth | query plus header | Query plus header in Node; browser WebSocket APIs prohibit custom headers, so browsers use the query credential. |
195
+ | Serve handshake | sends `"next"` after nonterminal update | Same |
196
+ | Transport reconnects | Three with exponential delays | Same |
197
+ | Protocol/server error | no transport reconnect | Same |
198
+ | Poll fallback | configurable | Same |
199
+ | Poll cadence | minimum client interval when server returns early | Same |
200
+ | Terminal cached `watch()` | contacts watcher and yields current service status | Same |
201
+ | Cancellation | coroutine/task cancellation | `AbortSignal` |
202
+
203
+ WebSockets and pending event waits are closed on success, error, timeout,
204
+ cancellation, callback failure, and early iterator return. A server error
205
+ falls back immediately when configured; only transport/connection failures
206
+ consume reconnect attempts.
207
+
208
+ Source normalization is cancellation-aware as well: pre-aborted calls do no
209
+ file I/O, Node path reads receive the caller signal, and binary materialization
210
+ checks cancellation before and after asynchronous reads.
211
+
212
+ Both schedulers:
213
+
214
+ - validate concurrency from 1 through 512;
215
+ - start lazily and bound complete submit/watch/result lifecycles;
216
+ - support completion order or input order;
217
+ - isolate ordinary item failures as values;
218
+ - cancel active work and close the input iterator when the consumer stops;
219
+ - switch fan-out waits above 64 in-flight jobs from WebSockets to polling.
220
+
221
+ Python's `submit_and_retrieve_each()` default is always eight even if the
222
+ client's conversion concurrency differs; TypeScript matches that behavior.
223
+ TypeScript also accepts `AsyncIterable`, preserves generic metadata, and
224
+ provides compile-time-correct auto-target result unions.
225
+
226
+ ## HTTP policy
227
+
228
+ The built-in transport matches Python:
229
+
230
+ | Condition | Policy |
231
+ | ---------------------------------------- | ---------------------------------------- |
232
+ | HTTP 500 or 502 | Retry every method, exponential backoff |
233
+ | HTTP 429 or 503 with valid `Retry-After` | Retry after numeric seconds or HTTP date |
234
+ | HTTP 429 or 503 without valid header | Do not retry |
235
+ | Network/transport failure | Retry GET, HEAD, and OPTIONS only |
236
+ | Caller cancellation | Never retry |
237
+ | Health/version | Zero retries |
238
+ | Successful service response | Exactly HTTP 200 |
239
+
240
+ Retried response bodies are canceled, zero-delay retries do not sleep, and the
241
+ exhausted error preserves status and service detail. The Fetch implementation
242
+ uses one total timeout per attempt instead of httpx's separate phase timeouts.
243
+
244
+ A custom `DoclingTransport` replaces the complete built-in HTTP policy. That
245
+ is an integration boundary, not a partial hook: the host owns response status,
246
+ headers, binary handling, retries, quotas, timeout, and error mapping.
247
+
248
+ ## Error mapping
249
+
250
+ | Python error | TypeScript |
251
+ | ---------------------------------------- | ------------------------------------ |
252
+ | `DoclingServiceClientError` | `DoclingError` |
253
+ | `ServiceError` | `DoclingServiceError` |
254
+ | generic non-retryable HTTP service error | `DoclingHttpError` |
255
+ | `ServiceUnavailableError` | `DoclingServiceUnavailableError` |
256
+ | `ResponseSchemaMismatchError` | `DoclingResponseSchemaMismatchError` |
257
+ | `UsageLimitExceededError` | `DoclingUsageLimitExceededError` |
258
+ | `TaskExecutionError` | `DoclingTaskError` |
259
+ | `TaskTimeoutError` | `DoclingTimeoutError` |
260
+ | `TaskNotFoundError` | `DoclingTaskNotFoundError` |
261
+ | `ResultNotReadyError` | `DoclingResultNotReadyError` |
262
+ | `ResultExpiredError` | `DoclingResultExpiredError` |
263
+ | `ArtifactDownloadError` | `DoclingArtifactDownloadError` |
264
+ | `ConversionError` | `DoclingConversionError` |
265
+ | `BatchConversionError` | `DoclingBatchConversionError` |
266
+
267
+ All service-originated TypeScript errors share `DoclingServiceError`, including
268
+ HTTP, availability, quota, and schema failures. Quota errors preserve the
269
+ service message, current usage, and limit.
270
+
271
+ Result lookup implements all Python branches:
272
+
273
+ - `"Task not found."` becomes task-not-found;
274
+ - missing result plus cached failure becomes authoritative task failure;
275
+ - missing result plus cached success becomes expired;
276
+ - missing result before a terminal state becomes not-ready;
277
+ - unexpected 404 detail remains a service error with status/detail;
278
+ - terminal task failure still fetches the result to recover structured failure
279
+ information.
280
+
281
+ ## Response and artifact validation
282
+
283
+ TypeScript validates the complete service boundary it consumes:
284
+
285
+ - task id/type/status, position, progress counts, and structured failure;
286
+ - converted document wrapper, status, errors, timings, confidence, and
287
+ processing time;
288
+ - every chunk and per-document chunk result;
289
+ - every presigned count, document item, artifact type, MIME, URI, error, and
290
+ timing;
291
+ - task-failure category, phase, retryability, and string details;
292
+ - health/version and binary metadata.
293
+
294
+ The exported `FailureCategory`, `DoclingComponentType`, `ProfilingScope`,
295
+ `QualityGrade`, and `ConfidenceScores` types mirror the corresponding Python
296
+ wire contracts; the public result types use those structured definitions
297
+ rather than unbounded strings or generic records.
298
+
299
+ Python Pydantic reconstructs and validates the complete version-pinned
300
+ `DoclingDocument`. TypeScript intentionally validates the document identity
301
+ (`schema_name` and `name`) at the client boundary and leaves the remaining
302
+ version-specific JSON generic. Applications can parameterize
303
+ `DoclingClient<TDocument>` with their installed
304
+ `@docling/docling-core` type. This avoids coupling the transport package to a
305
+ stale or mismatched core schema.
306
+
307
+ Presigned materialization otherwise matches Python and adds stricter checks:
308
+
309
+ - dedicated header-free artifact transport;
310
+ - public-address SSRF protection on every redirect;
311
+ - all DNS answers must be globally routable, rather than checking one answer;
312
+ - five redirect, timeout, and compressed-size limits;
313
+ - bounded streaming ZIP inflation, uncompressed-size and entry-count limits;
314
+ - path traversal rejection;
315
+ - exactly one top-level Docling JSON document;
316
+ - image MIME/signature validation before embedding.
317
+
318
+ ## TypeScript-only capabilities
319
+
320
+ These are deliberately richer than the Python client:
321
+
322
+ - `AbortSignal` on submissions, polling, watching, result fetching, artifact
323
+ download, and fan-out;
324
+ - injectable HTTP transport/fetch, WebSocket factory, artifact downloader,
325
+ artifact fetch, DNS resolver, sleep function, and private-URL policy;
326
+ - public task attachment and raw JSON/binary result methods;
327
+ - full cached status objects and a public `wait()` method;
328
+ - browser `Blob`, `ArrayBuffer`, typed-array, and base64 sources;
329
+ - `AsyncIterable` fan-out;
330
+ - low-level Put target support;
331
+ - complete target-aware generic return types and typed auto-target unions;
332
+ - batch callbacks and output-format override;
333
+ - full chunk options, multi-source JSON chunking, callbacks, and
334
+ `include_converted_doc`;
335
+ - stricter all-address artifact DNS validation and bounded bundle inflation;
336
+ - external-target binary submission that preserves coordinates by choosing the
337
+ unified JSON route;
338
+ - a version-neutral document boundary that can be parameterized with any
339
+ installed Docling Core schema.
340
+
341
+ ## Deliberate language adaptations
342
+
343
+ These are implemented adaptations, not postponed features:
344
+
345
+ - There is no blocking TypeScript facade; all I/O returns Promises or async
346
+ iterables.
347
+ - TypeScript `ConversionResult` carries a plain document JSON object, input
348
+ descriptor, status, errors, timings, confidence, and processing time.
349
+ Python additionally constructs a lightweight `InputDocument` and empty
350
+ `AssembledUnit`, which are Python runtime classes with no meaningful
351
+ JavaScript equivalent.
352
+ - On a failed/skipped result or missing JSON, TypeScript constructs a minimal
353
+ `{schema_name: "DoclingDocument", name}` document, matching Python's
354
+ non-null empty-document behavior.
355
+ - Fetch exposes a total attempt timeout rather than distinct socket phases.
356
+ - Node can enforce DNS-based artifact SSRF checks directly. Browser callers
357
+ must inject a trusted resolver/policy because browser APIs intentionally hide
358
+ DNS answers.
359
+ - The package uses camelCase for client control arguments and preserves
360
+ snake_case for Serve wire models.