@cloudpdf/engine 3.0.0-next.1 → 3.0.0-next.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { AbortError, AbortablePromise, AbortablePromise as AbortablePromise$1, AnnotationAppearanceImageOptions, AnnotationAppearanceImagesResult, AnnotationAppearanceRenderOptions, AnnotationAppearancesResult, AnnotationCreateResult, AnnotationDeleteResult, AnnotationDraft, AnnotationListPageSnapshot, AnnotationListSnapshotAllPages, AnnotationMoveResult, AnnotationPatch, AnnotationRef, AnnotationUpdateResult, AttachmentContent, AttachmentsCache, DocumentAccessInfo, DocumentActionsService, DocumentAnnotationsService, DocumentAnnotationsService as DocumentAnnotationsService$1, DocumentAttachmentsService, DocumentCapabilities, DocumentEventStream, DocumentFormsService, DocumentHandle, DocumentHandle as DocumentHandle$1, DocumentIdentity, DocumentMetadata, DocumentPagesService, DocumentPagesService as DocumentPagesService$1, DocumentRedactionService, DocumentRenderService, DocumentSearchService, DocumentSecurityService, DocumentSecurityService as DocumentSecurityService$1, DocumentSecurityState, DocumentUnlockInput, DocumentUnlockResult, Engine, Engine as Engine$1, EngineError, EngineErrorCode, EngineFactory, MetadataCache, MetadataPatch, MetadataService, MetadataService as MetadataService$1, MetadataUpdateResult, MutationMeta, OpenInput, OpenInput as OpenInput$1, OpenOptions, OpenOptions as OpenOptions$1, PageAnnotationsService, PageAnnotationsService as PageAnnotationsService$1, PageDeleteResult, PageFlattenResult, PageFlattenUsage, PageGeometryService, PageGeometryService as PageGeometryService$1, PageGeometrySnapshot, PageHandle, PageHandle as PageHandle$1, PageImageHandle, PageImageOptions, PageListSnapshot, PageMoveResult, PageObjectNumber, PageRaster, PageRenderOptions, PageRenderService, PageRenderService as PageRenderService$1, PageRotateResult, PageRotation, PageStructureCache, PageTextService, PageTextService as PageTextService$1, PageTextSnapshot, PdfSaveMode, PdfSaveMode as PdfSaveMode$1, SearchRequest, SearchSlice, TokenSource, WeakAnnotationEditSession } from "@embedpdf/engine-core/runtime";
1
+ import { AbortError, AbortablePromise, AbortablePromise as AbortablePromise$1, AnnotationAppearanceImageOptions, AnnotationAppearanceImagesResult, AnnotationAppearanceRenderOptions, AnnotationAppearancesResult, AnnotationCreateResult, AnnotationDeleteResult, AnnotationDraft, AnnotationListPageSnapshot, AnnotationListSnapshotAllPages, AnnotationMoveResult, AnnotationPatch, AnnotationRef, AnnotationUpdateResult, AttachmentContent, AttachmentsCache, DocumentAccessInfo, DocumentActionsService, DocumentAnnotationsService, DocumentAnnotationsService as DocumentAnnotationsService$1, DocumentAttachmentsService, DocumentCapabilities, DocumentEventStream, DocumentFormsService, DocumentHandle, DocumentHandle as DocumentHandle$1, DocumentIdentity, DocumentMetadata, DocumentPagesService, DocumentPagesService as DocumentPagesService$1, DocumentRedactionService, DocumentRenderService, DocumentSearchService, DocumentSecurityService, DocumentSecurityService as DocumentSecurityService$1, DocumentSecurityState, DocumentUnlockInput, DocumentUnlockResult, Engine, Engine as Engine$1, EngineError, EngineError as EngineError$1, EngineErrorCode, EngineFactory, MetadataCache, MetadataPatch, MetadataService, MetadataService as MetadataService$1, MetadataUpdateResult, MutationMeta, OpenInput, OpenInput as OpenInput$1, OpenInputShare, OpenOptions, OpenOptions as OpenOptions$1, PageAnnotationsService, PageAnnotationsService as PageAnnotationsService$1, PageDeleteResult, PageFlattenResult, PageFlattenUsage, PageGeometryService, PageGeometryService as PageGeometryService$1, PageGeometrySnapshot, PageHandle, PageHandle as PageHandle$1, PageImageHandle, PageImageOptions, PageInsertBlankSpec, PageInsertResult, PageListSnapshot, PageMoveResult, PageObjectNumber, PageRaster, PageRenderOptions, PageRenderService, PageRenderService as PageRenderService$1, PageRotateResult, PageRotation, PageStructureCache, PageTextService, PageTextService as PageTextService$1, PageTextSnapshot, PdfSaveMode, PdfSaveMode as PdfSaveMode$1, SearchRequest, SearchSlice, TokenSource, WeakAnnotationEditSession } from "@embedpdf/engine-core/runtime";
2
2
  import { CdnAccessInfoForApply, DocumentHead, DocumentManifest, LayerScopePlane } from "@embedpdf/engine-core/wire";
3
3
  import { SessionEventPublisher } from "@embedpdf/engine-services";
4
4
  //#region src/transport/HttpClient.d.ts
@@ -21,6 +21,30 @@ interface HttpClientOptions {
21
21
  sessionId?: string;
22
22
  /** Replace the global fetch (e.g. in Node tests with undici). */
23
23
  fetch?: typeof globalThis.fetch;
24
+ /**
25
+ * Document affinity key: `X-CloudPDF-Doc` is sent BY DEFAULT on
26
+ * origin-bound doc requests so consistent-hash load balancers can pin
27
+ * a document's traffic to one warm replica. Routing hints are
28
+ * unconditional client behavior — whether they are USED is the
29
+ * operator's choice at the load balancer, never the app's. Derived
30
+ * from the request path (`/v1/docs/:docId/…` — the same extraction
31
+ * the Helm chart's uri-mode fallback uses); never sent on
32
+ * CDN-rewritten requests.
33
+ *
34
+ * `false` is an ESCAPE HATCH, not a feature toggle: use it only
35
+ * against a stale server whose CORS allowlist predates the header
36
+ * (browser preflights would fail) or behind a proxy that rejects
37
+ * unknown request headers.
38
+ */
39
+ docAffinityHeader?: boolean;
40
+ /** Observability: fired once per transport-level retry (engine busy /
41
+ * restarting). Lets apps count sheds without wrapping every call. */
42
+ onRetry?: (info: {
43
+ path: string;
44
+ code: string;
45
+ attempt: number;
46
+ waitMs: number;
47
+ }) => void;
24
48
  }
25
49
  /**
26
50
  * Per-document binding for CDN URL rewriting. `CloudDocumentHandle`
@@ -48,12 +72,26 @@ interface HttpFileResponse {
48
72
  headers: Headers;
49
73
  }
50
74
  declare class HttpClient {
51
- private readonly baseUrl;
75
+ private readonly base;
52
76
  private readonly tokenFn;
53
77
  private readonly fetchFn;
78
+ private readonly docAffinityHeader;
79
+ private readonly onRetry;
80
+ private static readonly MAX_RETRIES;
81
+ private static readonly RETRY_AFTER_CAP_MS;
82
+ private static readonly RETRY_AFTER_DEFAULT_MS;
54
83
  private readonly sessionId;
55
84
  private cdnBinding;
56
85
  constructor(opts: HttpClientOptions);
86
+ /** Normalized server base URL (no trailing slash). */
87
+ get baseUrl(): string;
88
+ /**
89
+ * The fetch implementation this client sends requests through (injected
90
+ * or global). Exposed so sibling transports spawned per-open — the
91
+ * share-session exchange, most of all — ride the same fetch the engine
92
+ * was configured with (test doubles, SSR `Origin`-attaching wrappers).
93
+ */
94
+ get fetchImpl(): typeof globalThis.fetch;
57
95
  /**
58
96
  * Return a clone of this client bound to a different bearer. Used
59
97
  * by `CloudEngine.open` to mint a per-handle client carrying the
@@ -141,6 +179,8 @@ declare class HttpClient {
141
179
  /** PATCH counterpart of {@link postMultipartJson} (binary-carrying mutations). */
142
180
  patchMultipartJson<T>(path: string, body: FormData, parser: (raw: unknown) => T, signal: AbortSignal): Promise<T>;
143
181
  postJson<T>(path: string, body: unknown, parser: (raw: unknown) => T, signal: AbortSignal): Promise<T>;
182
+ /** POST a JSON body and return the raw binary response (pages.extract). */
183
+ postJsonBytes(path: string, body: unknown, signal: AbortSignal): Promise<Uint8Array>;
144
184
  /** POST a raw binary body (FDF/XFDF import) and parse the JSON response. */
145
185
  postBytesJson<T>(path: string, bytes: Uint8Array, contentType: string, parser: (raw: unknown) => T, signal: AbortSignal): Promise<T>;
146
186
  patchJson<T>(path: string, body: unknown, parser: (raw: unknown) => T, signal: AbortSignal): Promise<T>;
@@ -149,6 +189,7 @@ declare class HttpClient {
149
189
  postEmpty(path: string, body: unknown, signal: AbortSignal): Promise<void>;
150
190
  private requestJson;
151
191
  private request;
192
+ private execute;
152
193
  private parseJsonResponse;
153
194
  /**
154
195
  * Decide where this request actually goes. With no CDN binding (or
@@ -255,6 +296,10 @@ interface ManifestAccessor {
255
296
  /** Same advance for a page delete, additionally dropping the deleted
256
297
  * pages' manifest rows so per-page leaf URLs stop resolving locally. */
257
298
  applyPageDelete(cache: PageStructureCache, deletedPages: PageObjectNumber[]): void;
299
+ /** Page insert: the cached manifest has no rows for the fresh PONs (the
300
+ * result carries only their object numbers), so the absorb drops the
301
+ * cache for a lazy refetch instead of patching. */
302
+ applyPageInsert(cache: PageStructureCache): void;
258
303
  /** Advance the cached manifest's docVersion + metadataVersion after a metadata write. */
259
304
  applyMetadata(cache: MetadataCache): void;
260
305
  /** Advance the cached manifest's docVersion + attachmentsVersion after an
@@ -356,6 +401,18 @@ declare class CloudDocumentHandle implements DocumentHandle$1 {
356
401
  * 404 anyway — this keeps the failure local and instant).
357
402
  */
358
403
  private absorbPageDelete;
404
+ /**
405
+ * Patch bookkeeping after a page insert — the mirror of
406
+ * {@link absorbPageDelete}, with one asymmetry: delete can patch the
407
+ * cached manifest losslessly (it only REMOVES rows), but an insert needs
408
+ * manifest rows for the fresh PONs and the result doesn't carry them. So
409
+ * this absorb flips the planes (insert changes the page SET, so like
410
+ * delete it owns content + annotations alongside layout), raises the
411
+ * version floor, and DROPS the cache — the next read refetches a manifest
412
+ * that includes the new pages' rows. The UI never waits on that refetch:
413
+ * the mutation result / event already carries the full new layout.
414
+ */
415
+ private absorbPageInsert;
359
416
  /**
360
417
  * Patch the cached manifest after a metadata write. Symmetric with
361
418
  * {@link absorbPageMove}: a metadata edit advances `docVersion` (so leaf
@@ -396,10 +453,29 @@ declare class CloudDocumentAnnotationsService implements DocumentAnnotationsServ
396
453
  private readonly isClosed;
397
454
  private readonly manifest;
398
455
  constructor(http: HttpClient, docId: string, layerName: string, isClosed: () => boolean, manifest: ManifestAccessor);
456
+ /**
457
+ * One COHERENT whole-document snapshot: a single read of the immutable
458
+ * `annotations/items@annotationsVersion=N` leaf at the manifest's pin —
459
+ * materialized server-side by one raw (no page-load) sweep, CDN-cacheable
460
+ * because the pin bumps only when annotation list bodies actually change.
461
+ * A stale pin mid-read (a concurrent mutation → 404) refreshes the
462
+ * manifest and retries, so the result always belongs to one document
463
+ * moment (the torn read this method exists to prevent).
464
+ */
399
465
  listRawAll(): AbortablePromise$1<AnnotationListSnapshotAllPages>;
466
+ /** One bulk leaf read at the manifest's pin. The server stamps the body's
467
+ * `auditHead` at materialization time; a CDN-cached body may carry a
468
+ * cursor older than the current manifest's, which is still safe — the
469
+ * pin proves no items-affecting mutation landed in between, so replaying
470
+ * that window over the body is all no-ops. */
471
+ private readBulkAt;
400
472
  listRaw(pageObjectNumber: PageObjectNumber): AbortablePromise$1<AnnotationListPageSnapshot>;
473
+ /** Versioned leaf URL for one manifest page entry, with the same
474
+ * plane routing as `CloudPageAnnotationsService.list()`: an inherited
475
+ * `annotations` plane reads the doc-level base leaf. */
476
+ private pagePathAt;
477
+ private versionedPagePath;
401
478
  beginWeakEdit(pageObjectNumbers: readonly PageObjectNumber[]): AbortablePromise$1<WeakAnnotationEditSession>;
402
- private readCurrentPage;
403
479
  }
404
480
  //#endregion
405
481
  //#region src/document/CloudDocumentPagesService.d.ts
@@ -439,6 +515,9 @@ declare class CloudDocumentPagesService implements DocumentPagesService$1 {
439
515
  move(pageObjectNumbers: PageObjectNumber[], destIndex: number): AbortablePromise$1<PageMoveResult>;
440
516
  rotate(pageObjectNumbers: PageObjectNumber[], rotation: PageRotation): AbortablePromise$1<PageRotateResult>;
441
517
  delete(pageObjectNumbers: PageObjectNumber[]): AbortablePromise$1<PageDeleteResult>;
518
+ insert(bytes: Uint8Array | ArrayBuffer, destIndex?: number): AbortablePromise$1<PageInsertResult>;
519
+ insertBlank(spec: PageInsertBlankSpec, destIndex?: number): AbortablePromise$1<PageInsertResult>;
520
+ extract(pageObjectNumbers: PageObjectNumber[]): AbortablePromise$1<Uint8Array>;
442
521
  flatten(pageObjectNumbers: PageObjectNumber[], usage?: PageFlattenUsage): AbortablePromise$1<PageFlattenResult>;
443
522
  }
444
523
  //#endregion
@@ -572,6 +651,69 @@ interface UnverifiedClaims {
572
651
  }
573
652
  declare function decodeUnverifiedClaims(token: string): UnverifiedClaims;
574
653
  //#endregion
654
+ //#region src/share.d.ts
655
+ /**
656
+ * Share-session exchange: the client half of the no-backend embed flow.
657
+ *
658
+ * A share token (`shr_…`) is a REFERENCE to a stored grant on the
659
+ * server, not a credential — `exchangeShareToken` trades it for an
660
+ * ordinary short-lived doc JWT, and `shareSessionSource` wraps that in
661
+ * a self-renewing token source. Because the engine's transport
662
+ * invokes its token source on every request (and SSE reconnects call
663
+ * it again), renewal is nothing more than "exchange again when the
664
+ * cached session is nearly out" — no timers, no listeners.
665
+ *
666
+ * The endpoint requires a browser `Origin` header (the server checks
667
+ * it against the grant's allowlist). Browsers attach it automatically;
668
+ * non-browser callers (tests, SSR) must supply a `fetch` that does.
669
+ */
670
+ interface ShareSession {
671
+ /** Doc-scoped session JWT carrying the grant's capabilities. */
672
+ token: string;
673
+ docId: string;
674
+ layerName: string;
675
+ /** Unix seconds when `token` expires. */
676
+ expiresAt: number;
677
+ }
678
+ interface ShareExchangeOptions {
679
+ /** Passphrase for protected grants (`SharePasswordRequired` otherwise). */
680
+ password?: string;
681
+ fetch?: typeof globalThis.fetch;
682
+ }
683
+ /**
684
+ * Thrown on a non-OK exchange. `code` is the server's wire code:
685
+ * `SharePasswordRequired` (prompt and retry with a password),
686
+ * `OriginNotAllowed` / `OriginRequired`, `ShareExpired`, `NotFound`
687
+ * (unknown or revoked — indistinguishable by design), or
688
+ * `TooManyRequests`.
689
+ */
690
+ declare class ShareExchangeError extends Error {
691
+ readonly code: string;
692
+ readonly status: number;
693
+ constructor(code: string, message: string, status: number);
694
+ }
695
+ declare function exchangeShareToken(baseUrl: string, shareToken: string, opts?: ShareExchangeOptions): Promise<ShareSession>;
696
+ /**
697
+ * Lift a {@link ShareExchangeError} into the engine's error taxonomy, so
698
+ * `open({ kind: 'share' })` and every later renewal fail with the same
699
+ * `EngineError` family as all other engine calls. The wire code and HTTP
700
+ * status survive in `details`; the original error rides as `cause`.
701
+ *
702
+ * `SharePasswordRequired` gets its own engine code — it is the one outcome
703
+ * callers branch on programmatically (prompt for the grant passphrase and
704
+ * retry). Everything else maps by meaning, with the HTTP status as the
705
+ * fallback discriminator.
706
+ */
707
+ declare function engineErrorFromShareExchange(error: ShareExchangeError): EngineError$1;
708
+ /**
709
+ * A caching, self-renewing token source over the exchange — the callable
710
+ * member of the engine's `TokenSource` union, assignable wherever one is
711
+ * taken.
712
+ * Concurrent callers share one in-flight exchange; a failed exchange
713
+ * clears it so the next request retries rather than caching the error.
714
+ */
715
+ declare function shareSessionSource(baseUrl: string, shareToken: string, opts?: ShareExchangeOptions): () => Promise<string>;
716
+ //#endregion
575
717
  //#region src/index.d.ts
576
718
  declare function createCloudEngine(opts: CloudEngineOptions): CloudEngine;
577
719
  /**
@@ -596,5 +738,5 @@ declare function createCloudEngine(opts: CloudEngineOptions): CloudEngine;
596
738
  */
597
739
  declare function cloudEngine(opts: CloudEngineOptions): CloudEngine;
598
740
  //#endregion
599
- export { AbortError, AbortablePromise, CloudDocumentAnnotationsService, CloudDocumentHandle, CloudDocumentPagesService, CloudEngine, type CloudEngineOptions, CloudMetadataService, CloudPageAnnotationsService, CloudPageGeometryService, CloudPageHandle, CloudPageRenderService, type DocumentAccessInfo, type DocumentAnnotationsService, type DocumentCapabilities, type DocumentHandle, type DocumentIdentity, type DocumentPagesService, type DocumentSecurityService, type DocumentSecurityState, type DocumentUnlockInput, type DocumentUnlockResult, type Engine, EngineError, EngineErrorCode, type EngineFactory, HttpClient, type HttpClientOptions, type MetadataService, type OpenInput, type OpenOptions, type PageAnnotationsService, type PageGeometryService, type PageHandle, type PageRenderService, type PageTextService, type PdfSaveMode, type TokenSource, type UnverifiedClaims, cloudEngine, createCloudEngine, decodeUnverifiedClaims };
741
+ export { AbortError, AbortablePromise, CloudDocumentAnnotationsService, CloudDocumentHandle, CloudDocumentPagesService, CloudEngine, type CloudEngineOptions, CloudMetadataService, CloudPageAnnotationsService, CloudPageGeometryService, CloudPageHandle, CloudPageRenderService, type DocumentAccessInfo, type DocumentAnnotationsService, type DocumentCapabilities, type DocumentHandle, type DocumentIdentity, type DocumentPagesService, type DocumentSecurityService, type DocumentSecurityState, type DocumentUnlockInput, type DocumentUnlockResult, type Engine, EngineError, EngineErrorCode, type EngineFactory, HttpClient, type HttpClientOptions, type MetadataService, type OpenInput, type OpenInputShare, type OpenOptions, type PageAnnotationsService, type PageGeometryService, type PageHandle, type PageRenderService, type PageTextService, type PdfSaveMode, ShareExchangeError, type ShareExchangeOptions, type ShareSession, type TokenSource, type UnverifiedClaims, cloudEngine, createCloudEngine, decodeUnverifiedClaims, engineErrorFromShareExchange, exchangeShareToken, shareSessionSource };
600
742
  //# sourceMappingURL=index.d.cts.map
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { AbortError, AbortablePromise, AbortablePromise as AbortablePromise$1, AnnotationAppearanceImageOptions, AnnotationAppearanceImagesResult, AnnotationAppearanceRenderOptions, AnnotationAppearancesResult, AnnotationCreateResult, AnnotationDeleteResult, AnnotationDraft, AnnotationListPageSnapshot, AnnotationListSnapshotAllPages, AnnotationMoveResult, AnnotationPatch, AnnotationRef, AnnotationUpdateResult, AttachmentContent, AttachmentsCache, DocumentAccessInfo, DocumentActionsService, DocumentAnnotationsService, DocumentAnnotationsService as DocumentAnnotationsService$1, DocumentAttachmentsService, DocumentCapabilities, DocumentEventStream, DocumentFormsService, DocumentHandle, DocumentHandle as DocumentHandle$1, DocumentIdentity, DocumentMetadata, DocumentPagesService, DocumentPagesService as DocumentPagesService$1, DocumentRedactionService, DocumentRenderService, DocumentSearchService, DocumentSecurityService, DocumentSecurityService as DocumentSecurityService$1, DocumentSecurityState, DocumentUnlockInput, DocumentUnlockResult, Engine, Engine as Engine$1, EngineError, EngineErrorCode, EngineFactory, MetadataCache, MetadataPatch, MetadataService, MetadataService as MetadataService$1, MetadataUpdateResult, MutationMeta, OpenInput, OpenInput as OpenInput$1, OpenOptions, OpenOptions as OpenOptions$1, PageAnnotationsService, PageAnnotationsService as PageAnnotationsService$1, PageDeleteResult, PageFlattenResult, PageFlattenUsage, PageGeometryService, PageGeometryService as PageGeometryService$1, PageGeometrySnapshot, PageHandle, PageHandle as PageHandle$1, PageImageHandle, PageImageOptions, PageListSnapshot, PageMoveResult, PageObjectNumber, PageRaster, PageRenderOptions, PageRenderService, PageRenderService as PageRenderService$1, PageRotateResult, PageRotation, PageStructureCache, PageTextService, PageTextService as PageTextService$1, PageTextSnapshot, PdfSaveMode, PdfSaveMode as PdfSaveMode$1, SearchRequest, SearchSlice, TokenSource, WeakAnnotationEditSession } from "@embedpdf/engine-core/runtime";
1
+ import { AbortError, AbortablePromise, AbortablePromise as AbortablePromise$1, AnnotationAppearanceImageOptions, AnnotationAppearanceImagesResult, AnnotationAppearanceRenderOptions, AnnotationAppearancesResult, AnnotationCreateResult, AnnotationDeleteResult, AnnotationDraft, AnnotationListPageSnapshot, AnnotationListSnapshotAllPages, AnnotationMoveResult, AnnotationPatch, AnnotationRef, AnnotationUpdateResult, AttachmentContent, AttachmentsCache, DocumentAccessInfo, DocumentActionsService, DocumentAnnotationsService, DocumentAnnotationsService as DocumentAnnotationsService$1, DocumentAttachmentsService, DocumentCapabilities, DocumentEventStream, DocumentFormsService, DocumentHandle, DocumentHandle as DocumentHandle$1, DocumentIdentity, DocumentMetadata, DocumentPagesService, DocumentPagesService as DocumentPagesService$1, DocumentRedactionService, DocumentRenderService, DocumentSearchService, DocumentSecurityService, DocumentSecurityService as DocumentSecurityService$1, DocumentSecurityState, DocumentUnlockInput, DocumentUnlockResult, Engine, Engine as Engine$1, EngineError, EngineError as EngineError$1, EngineErrorCode, EngineFactory, MetadataCache, MetadataPatch, MetadataService, MetadataService as MetadataService$1, MetadataUpdateResult, MutationMeta, OpenInput, OpenInput as OpenInput$1, OpenInputShare, OpenOptions, OpenOptions as OpenOptions$1, PageAnnotationsService, PageAnnotationsService as PageAnnotationsService$1, PageDeleteResult, PageFlattenResult, PageFlattenUsage, PageGeometryService, PageGeometryService as PageGeometryService$1, PageGeometrySnapshot, PageHandle, PageHandle as PageHandle$1, PageImageHandle, PageImageOptions, PageInsertBlankSpec, PageInsertResult, PageListSnapshot, PageMoveResult, PageObjectNumber, PageRaster, PageRenderOptions, PageRenderService, PageRenderService as PageRenderService$1, PageRotateResult, PageRotation, PageStructureCache, PageTextService, PageTextService as PageTextService$1, PageTextSnapshot, PdfSaveMode, PdfSaveMode as PdfSaveMode$1, SearchRequest, SearchSlice, TokenSource, WeakAnnotationEditSession } from "@embedpdf/engine-core/runtime";
2
2
  import { CdnAccessInfoForApply, DocumentHead, DocumentManifest, LayerScopePlane } from "@embedpdf/engine-core/wire";
3
3
  import { SessionEventPublisher } from "@embedpdf/engine-services";
4
4
  //#region src/transport/HttpClient.d.ts
@@ -21,6 +21,30 @@ interface HttpClientOptions {
21
21
  sessionId?: string;
22
22
  /** Replace the global fetch (e.g. in Node tests with undici). */
23
23
  fetch?: typeof globalThis.fetch;
24
+ /**
25
+ * Document affinity key: `X-CloudPDF-Doc` is sent BY DEFAULT on
26
+ * origin-bound doc requests so consistent-hash load balancers can pin
27
+ * a document's traffic to one warm replica. Routing hints are
28
+ * unconditional client behavior — whether they are USED is the
29
+ * operator's choice at the load balancer, never the app's. Derived
30
+ * from the request path (`/v1/docs/:docId/…` — the same extraction
31
+ * the Helm chart's uri-mode fallback uses); never sent on
32
+ * CDN-rewritten requests.
33
+ *
34
+ * `false` is an ESCAPE HATCH, not a feature toggle: use it only
35
+ * against a stale server whose CORS allowlist predates the header
36
+ * (browser preflights would fail) or behind a proxy that rejects
37
+ * unknown request headers.
38
+ */
39
+ docAffinityHeader?: boolean;
40
+ /** Observability: fired once per transport-level retry (engine busy /
41
+ * restarting). Lets apps count sheds without wrapping every call. */
42
+ onRetry?: (info: {
43
+ path: string;
44
+ code: string;
45
+ attempt: number;
46
+ waitMs: number;
47
+ }) => void;
24
48
  }
25
49
  /**
26
50
  * Per-document binding for CDN URL rewriting. `CloudDocumentHandle`
@@ -48,12 +72,26 @@ interface HttpFileResponse {
48
72
  headers: Headers;
49
73
  }
50
74
  declare class HttpClient {
51
- private readonly baseUrl;
75
+ private readonly base;
52
76
  private readonly tokenFn;
53
77
  private readonly fetchFn;
78
+ private readonly docAffinityHeader;
79
+ private readonly onRetry;
80
+ private static readonly MAX_RETRIES;
81
+ private static readonly RETRY_AFTER_CAP_MS;
82
+ private static readonly RETRY_AFTER_DEFAULT_MS;
54
83
  private readonly sessionId;
55
84
  private cdnBinding;
56
85
  constructor(opts: HttpClientOptions);
86
+ /** Normalized server base URL (no trailing slash). */
87
+ get baseUrl(): string;
88
+ /**
89
+ * The fetch implementation this client sends requests through (injected
90
+ * or global). Exposed so sibling transports spawned per-open — the
91
+ * share-session exchange, most of all — ride the same fetch the engine
92
+ * was configured with (test doubles, SSR `Origin`-attaching wrappers).
93
+ */
94
+ get fetchImpl(): typeof globalThis.fetch;
57
95
  /**
58
96
  * Return a clone of this client bound to a different bearer. Used
59
97
  * by `CloudEngine.open` to mint a per-handle client carrying the
@@ -141,6 +179,8 @@ declare class HttpClient {
141
179
  /** PATCH counterpart of {@link postMultipartJson} (binary-carrying mutations). */
142
180
  patchMultipartJson<T>(path: string, body: FormData, parser: (raw: unknown) => T, signal: AbortSignal): Promise<T>;
143
181
  postJson<T>(path: string, body: unknown, parser: (raw: unknown) => T, signal: AbortSignal): Promise<T>;
182
+ /** POST a JSON body and return the raw binary response (pages.extract). */
183
+ postJsonBytes(path: string, body: unknown, signal: AbortSignal): Promise<Uint8Array>;
144
184
  /** POST a raw binary body (FDF/XFDF import) and parse the JSON response. */
145
185
  postBytesJson<T>(path: string, bytes: Uint8Array, contentType: string, parser: (raw: unknown) => T, signal: AbortSignal): Promise<T>;
146
186
  patchJson<T>(path: string, body: unknown, parser: (raw: unknown) => T, signal: AbortSignal): Promise<T>;
@@ -149,6 +189,7 @@ declare class HttpClient {
149
189
  postEmpty(path: string, body: unknown, signal: AbortSignal): Promise<void>;
150
190
  private requestJson;
151
191
  private request;
192
+ private execute;
152
193
  private parseJsonResponse;
153
194
  /**
154
195
  * Decide where this request actually goes. With no CDN binding (or
@@ -255,6 +296,10 @@ interface ManifestAccessor {
255
296
  /** Same advance for a page delete, additionally dropping the deleted
256
297
  * pages' manifest rows so per-page leaf URLs stop resolving locally. */
257
298
  applyPageDelete(cache: PageStructureCache, deletedPages: PageObjectNumber[]): void;
299
+ /** Page insert: the cached manifest has no rows for the fresh PONs (the
300
+ * result carries only their object numbers), so the absorb drops the
301
+ * cache for a lazy refetch instead of patching. */
302
+ applyPageInsert(cache: PageStructureCache): void;
258
303
  /** Advance the cached manifest's docVersion + metadataVersion after a metadata write. */
259
304
  applyMetadata(cache: MetadataCache): void;
260
305
  /** Advance the cached manifest's docVersion + attachmentsVersion after an
@@ -356,6 +401,18 @@ declare class CloudDocumentHandle implements DocumentHandle$1 {
356
401
  * 404 anyway — this keeps the failure local and instant).
357
402
  */
358
403
  private absorbPageDelete;
404
+ /**
405
+ * Patch bookkeeping after a page insert — the mirror of
406
+ * {@link absorbPageDelete}, with one asymmetry: delete can patch the
407
+ * cached manifest losslessly (it only REMOVES rows), but an insert needs
408
+ * manifest rows for the fresh PONs and the result doesn't carry them. So
409
+ * this absorb flips the planes (insert changes the page SET, so like
410
+ * delete it owns content + annotations alongside layout), raises the
411
+ * version floor, and DROPS the cache — the next read refetches a manifest
412
+ * that includes the new pages' rows. The UI never waits on that refetch:
413
+ * the mutation result / event already carries the full new layout.
414
+ */
415
+ private absorbPageInsert;
359
416
  /**
360
417
  * Patch the cached manifest after a metadata write. Symmetric with
361
418
  * {@link absorbPageMove}: a metadata edit advances `docVersion` (so leaf
@@ -396,10 +453,29 @@ declare class CloudDocumentAnnotationsService implements DocumentAnnotationsServ
396
453
  private readonly isClosed;
397
454
  private readonly manifest;
398
455
  constructor(http: HttpClient, docId: string, layerName: string, isClosed: () => boolean, manifest: ManifestAccessor);
456
+ /**
457
+ * One COHERENT whole-document snapshot: a single read of the immutable
458
+ * `annotations/items@annotationsVersion=N` leaf at the manifest's pin —
459
+ * materialized server-side by one raw (no page-load) sweep, CDN-cacheable
460
+ * because the pin bumps only when annotation list bodies actually change.
461
+ * A stale pin mid-read (a concurrent mutation → 404) refreshes the
462
+ * manifest and retries, so the result always belongs to one document
463
+ * moment (the torn read this method exists to prevent).
464
+ */
399
465
  listRawAll(): AbortablePromise$1<AnnotationListSnapshotAllPages>;
466
+ /** One bulk leaf read at the manifest's pin. The server stamps the body's
467
+ * `auditHead` at materialization time; a CDN-cached body may carry a
468
+ * cursor older than the current manifest's, which is still safe — the
469
+ * pin proves no items-affecting mutation landed in between, so replaying
470
+ * that window over the body is all no-ops. */
471
+ private readBulkAt;
400
472
  listRaw(pageObjectNumber: PageObjectNumber): AbortablePromise$1<AnnotationListPageSnapshot>;
473
+ /** Versioned leaf URL for one manifest page entry, with the same
474
+ * plane routing as `CloudPageAnnotationsService.list()`: an inherited
475
+ * `annotations` plane reads the doc-level base leaf. */
476
+ private pagePathAt;
477
+ private versionedPagePath;
401
478
  beginWeakEdit(pageObjectNumbers: readonly PageObjectNumber[]): AbortablePromise$1<WeakAnnotationEditSession>;
402
- private readCurrentPage;
403
479
  }
404
480
  //#endregion
405
481
  //#region src/document/CloudDocumentPagesService.d.ts
@@ -439,6 +515,9 @@ declare class CloudDocumentPagesService implements DocumentPagesService$1 {
439
515
  move(pageObjectNumbers: PageObjectNumber[], destIndex: number): AbortablePromise$1<PageMoveResult>;
440
516
  rotate(pageObjectNumbers: PageObjectNumber[], rotation: PageRotation): AbortablePromise$1<PageRotateResult>;
441
517
  delete(pageObjectNumbers: PageObjectNumber[]): AbortablePromise$1<PageDeleteResult>;
518
+ insert(bytes: Uint8Array | ArrayBuffer, destIndex?: number): AbortablePromise$1<PageInsertResult>;
519
+ insertBlank(spec: PageInsertBlankSpec, destIndex?: number): AbortablePromise$1<PageInsertResult>;
520
+ extract(pageObjectNumbers: PageObjectNumber[]): AbortablePromise$1<Uint8Array>;
442
521
  flatten(pageObjectNumbers: PageObjectNumber[], usage?: PageFlattenUsage): AbortablePromise$1<PageFlattenResult>;
443
522
  }
444
523
  //#endregion
@@ -572,6 +651,69 @@ interface UnverifiedClaims {
572
651
  }
573
652
  declare function decodeUnverifiedClaims(token: string): UnverifiedClaims;
574
653
  //#endregion
654
+ //#region src/share.d.ts
655
+ /**
656
+ * Share-session exchange: the client half of the no-backend embed flow.
657
+ *
658
+ * A share token (`shr_…`) is a REFERENCE to a stored grant on the
659
+ * server, not a credential — `exchangeShareToken` trades it for an
660
+ * ordinary short-lived doc JWT, and `shareSessionSource` wraps that in
661
+ * a self-renewing token source. Because the engine's transport
662
+ * invokes its token source on every request (and SSE reconnects call
663
+ * it again), renewal is nothing more than "exchange again when the
664
+ * cached session is nearly out" — no timers, no listeners.
665
+ *
666
+ * The endpoint requires a browser `Origin` header (the server checks
667
+ * it against the grant's allowlist). Browsers attach it automatically;
668
+ * non-browser callers (tests, SSR) must supply a `fetch` that does.
669
+ */
670
+ interface ShareSession {
671
+ /** Doc-scoped session JWT carrying the grant's capabilities. */
672
+ token: string;
673
+ docId: string;
674
+ layerName: string;
675
+ /** Unix seconds when `token` expires. */
676
+ expiresAt: number;
677
+ }
678
+ interface ShareExchangeOptions {
679
+ /** Passphrase for protected grants (`SharePasswordRequired` otherwise). */
680
+ password?: string;
681
+ fetch?: typeof globalThis.fetch;
682
+ }
683
+ /**
684
+ * Thrown on a non-OK exchange. `code` is the server's wire code:
685
+ * `SharePasswordRequired` (prompt and retry with a password),
686
+ * `OriginNotAllowed` / `OriginRequired`, `ShareExpired`, `NotFound`
687
+ * (unknown or revoked — indistinguishable by design), or
688
+ * `TooManyRequests`.
689
+ */
690
+ declare class ShareExchangeError extends Error {
691
+ readonly code: string;
692
+ readonly status: number;
693
+ constructor(code: string, message: string, status: number);
694
+ }
695
+ declare function exchangeShareToken(baseUrl: string, shareToken: string, opts?: ShareExchangeOptions): Promise<ShareSession>;
696
+ /**
697
+ * Lift a {@link ShareExchangeError} into the engine's error taxonomy, so
698
+ * `open({ kind: 'share' })` and every later renewal fail with the same
699
+ * `EngineError` family as all other engine calls. The wire code and HTTP
700
+ * status survive in `details`; the original error rides as `cause`.
701
+ *
702
+ * `SharePasswordRequired` gets its own engine code — it is the one outcome
703
+ * callers branch on programmatically (prompt for the grant passphrase and
704
+ * retry). Everything else maps by meaning, with the HTTP status as the
705
+ * fallback discriminator.
706
+ */
707
+ declare function engineErrorFromShareExchange(error: ShareExchangeError): EngineError$1;
708
+ /**
709
+ * A caching, self-renewing token source over the exchange — the callable
710
+ * member of the engine's `TokenSource` union, assignable wherever one is
711
+ * taken.
712
+ * Concurrent callers share one in-flight exchange; a failed exchange
713
+ * clears it so the next request retries rather than caching the error.
714
+ */
715
+ declare function shareSessionSource(baseUrl: string, shareToken: string, opts?: ShareExchangeOptions): () => Promise<string>;
716
+ //#endregion
575
717
  //#region src/index.d.ts
576
718
  declare function createCloudEngine(opts: CloudEngineOptions): CloudEngine;
577
719
  /**
@@ -596,5 +738,5 @@ declare function createCloudEngine(opts: CloudEngineOptions): CloudEngine;
596
738
  */
597
739
  declare function cloudEngine(opts: CloudEngineOptions): CloudEngine;
598
740
  //#endregion
599
- export { AbortError, AbortablePromise, CloudDocumentAnnotationsService, CloudDocumentHandle, CloudDocumentPagesService, CloudEngine, type CloudEngineOptions, CloudMetadataService, CloudPageAnnotationsService, CloudPageGeometryService, CloudPageHandle, CloudPageRenderService, type DocumentAccessInfo, type DocumentAnnotationsService, type DocumentCapabilities, type DocumentHandle, type DocumentIdentity, type DocumentPagesService, type DocumentSecurityService, type DocumentSecurityState, type DocumentUnlockInput, type DocumentUnlockResult, type Engine, EngineError, EngineErrorCode, type EngineFactory, HttpClient, type HttpClientOptions, type MetadataService, type OpenInput, type OpenOptions, type PageAnnotationsService, type PageGeometryService, type PageHandle, type PageRenderService, type PageTextService, type PdfSaveMode, type TokenSource, type UnverifiedClaims, cloudEngine, createCloudEngine, decodeUnverifiedClaims };
741
+ export { AbortError, AbortablePromise, CloudDocumentAnnotationsService, CloudDocumentHandle, CloudDocumentPagesService, CloudEngine, type CloudEngineOptions, CloudMetadataService, CloudPageAnnotationsService, CloudPageGeometryService, CloudPageHandle, CloudPageRenderService, type DocumentAccessInfo, type DocumentAnnotationsService, type DocumentCapabilities, type DocumentHandle, type DocumentIdentity, type DocumentPagesService, type DocumentSecurityService, type DocumentSecurityState, type DocumentUnlockInput, type DocumentUnlockResult, type Engine, EngineError, EngineErrorCode, type EngineFactory, HttpClient, type HttpClientOptions, type MetadataService, type OpenInput, type OpenInputShare, type OpenOptions, type PageAnnotationsService, type PageGeometryService, type PageHandle, type PageRenderService, type PageTextService, type PdfSaveMode, ShareExchangeError, type ShareExchangeOptions, type ShareSession, type TokenSource, type UnverifiedClaims, cloudEngine, createCloudEngine, decodeUnverifiedClaims, engineErrorFromShareExchange, exchangeShareToken, shareSessionSource };
600
742
  //# sourceMappingURL=index.d.ts.map