@betteroffice/docx 0.2.1 → 0.4.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.
Files changed (91) hide show
  1. package/README.md +586 -3
  2. package/dist/chunk-24Z6ZVFZ.mjs +1 -0
  3. package/dist/chunk-2QHGQA3V.mjs +1 -0
  4. package/dist/{chunk-ACGKK7IB.mjs → chunk-3CYO46ML.mjs} +1 -1
  5. package/dist/chunk-6CHGYCFU.mjs +1 -0
  6. package/dist/chunk-AOWJ4WDE.mjs +1 -0
  7. package/dist/chunk-DLXIZBB6.mjs +1 -0
  8. package/dist/chunk-F2VBW6RB.mjs +1 -0
  9. package/dist/chunk-HPZFJGGM.mjs +0 -0
  10. package/dist/chunk-L2ML3DDI.mjs +1 -0
  11. package/dist/chunk-LIGZ75FP.mjs +1 -0
  12. package/dist/chunk-LT2GCWZ3.mjs +0 -0
  13. package/dist/chunk-ND3FBCB3.mjs +16 -0
  14. package/dist/chunk-NMDQHUQB.mjs +57 -0
  15. package/dist/chunk-NVN26RHH.mjs +1 -0
  16. package/dist/chunk-OK5UFGX3.mjs +1 -0
  17. package/dist/chunk-RZQ3OXZY.mjs +2 -0
  18. package/dist/chunk-YLFKV2NT.mjs +1 -0
  19. package/dist/collaboration/index.d.mts +9 -6
  20. package/dist/compareDocx-IHFPGIGV.mjs +1 -0
  21. package/dist/computeLayout-4MNWHE2T.mjs +1 -0
  22. package/dist/{content-CvEtPl0c.d.mts → content-BzoC6bSz.d.mts} +48 -8
  23. package/dist/core.d.mts +172 -9
  24. package/dist/core.mjs +1 -1
  25. package/dist/{displayListQueries-DF8F6fMl.d.mts → displayListQueries-H5YnU_hX.d.mts} +23 -5
  26. package/dist/docx/index.d.mts +5 -4
  27. package/dist/docx/index.mjs +1 -1
  28. package/dist/editor/index.d.mts +19 -9
  29. package/dist/editor/index.mjs +1 -1
  30. package/dist/{fontLoader-b8eicJKV.d.mts → fontLoader-BNSs0E8K.d.mts} +55 -2
  31. package/dist/{formatting-7zKCTu5a.d.mts → formatting-gqLFeJ9X.d.mts} +8 -0
  32. package/dist/{frameDelta-pA4jrQ1G.d.mts → frameDelta-ByU7HBuB.d.mts} +34 -3
  33. package/dist/generated/edit/docx_edit_bg.wasm +0 -0
  34. package/dist/generated/layout/docx_layout_bg.wasm +0 -0
  35. package/dist/generated/opc/ooxml_opc_bg.wasm +0 -0
  36. package/dist/generated/parse/docx_parse_bg.wasm +0 -0
  37. package/dist/index-CHy6_Yuo.d.mts +2026 -0
  38. package/dist/layout/index.d.mts +6 -6
  39. package/dist/layout/index.mjs +1 -1
  40. package/dist/layout/pagination/index.d.mts +4 -4
  41. package/dist/layout/render/index.d.mts +122 -33
  42. package/dist/layout/render/index.mjs +1 -1
  43. package/dist/loadWasmAsset-Cr95TImt.d.mts +25 -0
  44. package/dist/pagedExport---0Dlmzo.d.mts +907 -0
  45. package/dist/parseWasm-NLAG22EU.mjs +1 -0
  46. package/dist/plugin-api/RenderedDomContext.d.mts +12 -9
  47. package/dist/plugin-api/RenderedDomContext.mjs +1 -1
  48. package/dist/plugin-api/index.d.mts +21 -4
  49. package/dist/plugin-api/resolveItemPositions.d.mts +3 -3
  50. package/dist/rezip-Bxiq4Z_R.d.mts +24 -0
  51. package/dist/{rustDisplayList-BJqaN9tt.d.mts → rustDisplayList-LcRZHCSL.d.mts} +12 -4
  52. package/dist/{rustMeasureSource-C0EZB055.d.mts → rustMeasureSource-BkCx1FDx.d.mts} +14 -4
  53. package/dist/{selectiveSave-CRh-_Y_C.d.mts → selectiveSave-r-NMK6aI.d.mts} +1 -22
  54. package/dist/styles/index.d.mts +2 -2
  55. package/dist/{styles-7e-mq3c-.d.mts → styles-AryxLAhx.d.mts} +1 -1
  56. package/dist/types/content.d.mts +2 -2
  57. package/dist/types/document.d.mts +9 -6
  58. package/dist/{types-C4A8mWjU.d.mts → types-D6Pra38E.d.mts} +31 -5
  59. package/dist/utils/comments.d.mts +2 -2
  60. package/dist/utils/index.d.mts +20 -5
  61. package/dist/utils/index.mjs +1 -1
  62. package/dist/utils/stylePreview.d.mts +2 -2
  63. package/dist/wasm-GSI2XMOH.mjs +1 -0
  64. package/dist/wasm-K6DRABAA.mjs +1 -0
  65. package/dist/wasm-NF6B3AH7.mjs +1 -0
  66. package/dist/wasm-edit.d.mts +420 -28
  67. package/dist/wasm-edit.mjs +1 -1
  68. package/dist/wasm-layout.d.mts +9 -2
  69. package/dist/wasm-layout.mjs +1 -1
  70. package/dist/wasm-opc.d.mts +1 -1
  71. package/dist/wasm-opc.mjs +1 -1
  72. package/dist/wasm-parse.d.mts +1 -1
  73. package/dist/wasm-parse.mjs +1 -1
  74. package/dist/yrs/index.d.mts +8 -5
  75. package/dist/yrs/index.mjs +1 -1
  76. package/dist/yrs/residentEngineWorker.mjs +1 -1
  77. package/package.json +2 -2
  78. package/dist/chunk-5F6DLQZP.mjs +0 -1
  79. package/dist/chunk-6LQJAKOC.mjs +0 -1
  80. package/dist/chunk-AFMVSI4Z.mjs +0 -57
  81. package/dist/chunk-GD4VNJ64.mjs +0 -1
  82. package/dist/chunk-HLDJMU3R.mjs +0 -1
  83. package/dist/chunk-J7LNO6SM.mjs +0 -1
  84. package/dist/chunk-JHJLG4I6.mjs +0 -16
  85. package/dist/chunk-PGMXWI5X.mjs +0 -1
  86. package/dist/chunk-WRWRCBLK.mjs +0 -1
  87. package/dist/chunk-WTFRNX5K.mjs +0 -1
  88. package/dist/index-CHl2zLJ7.d.mts +0 -1142
  89. package/dist/loadWasmAsset-CMvnVkfA.d.mts +0 -3
  90. package/dist/wasm-7SOSHNGP.mjs +0 -1
  91. package/dist/wasm-ZQAVP7P2.mjs +0 -1
@@ -0,0 +1,2026 @@
1
+ import { C as ColorValue } from './formatting-gqLFeJ9X.mjs';
2
+ import { Document, CompatibilityFlags } from './types/document.mjs';
3
+ import { a0 as DocxEditSuggestion, a1 as DocxEditFailure, a2 as DocxEditFailureCode, a3 as DocxReadParagraphsRequest, a4 as DocxReadParagraphsResult, a5 as DocxFindTextRequest, a6 as DocxFindTextResult, a7 as DocxEditRequest, a8 as DocxValidationResult, a9 as DocxEditResult, aa as DocxTextTarget, ab as DocxEditRefusal, a as DocxExportOptions, H as DocxExportResult, c as DocxStructuredContent, b as DocxMarkdownContent, d as DocxPageExportOptions, f as DocxPagedStructuredContent, i as DocxLayoutMap, g as DocxSnapshotLayoutMap, D as DocxExportFailure, V as DocxParagraphHeading, m as DocxContentControlsOptions, w as DocxContentControlsResult, l as DocxContentControlQuery } from './pagedExport---0Dlmzo.mjs';
4
+ import { R as RetainedFrame } from './frameDelta-ByU7HBuB.mjs';
5
+ import { a as WasmModuleMemory } from './loadWasmAsset-Cr95TImt.mjs';
6
+ import { R as RepackOptions } from './rezip-Bxiq4Z_R.mjs';
7
+
8
+ type CollaborationUpdateOrigin = 'local' | 'remote';
9
+ interface CollaborationReplica {
10
+ readonly clientId: number;
11
+ encodeStateVector(): Uint8Array;
12
+ encodeStateAsUpdate(remoteStateVector?: Uint8Array): Uint8Array;
13
+ applyUpdate(update: Uint8Array): unknown;
14
+ onUpdate(listener: (update: Uint8Array, origin: CollaborationUpdateOrigin) => void): () => void;
15
+ }
16
+ type CollaborationTransportEvent = {
17
+ type: 'open';
18
+ } | {
19
+ type: 'message';
20
+ data: Uint8Array;
21
+ } | {
22
+ type: 'close';
23
+ reason?: string;
24
+ } | {
25
+ type: 'error';
26
+ error: unknown;
27
+ } | {
28
+ type: 'drain';
29
+ };
30
+ interface CollaborationTransport {
31
+ /** Starts one connection attempt; transports may also reopen while still subscribed. */
32
+ connect(): void | Promise<void>;
33
+ disconnect(): void | Promise<void>;
34
+ /** Returns true only when the owned frame was accepted; false requires a later drain event. */
35
+ send(data: Uint8Array): boolean;
36
+ onEvent(listener: (event: CollaborationTransportEvent) => void): () => void;
37
+ }
38
+ type CollaborationStatus = 'disconnected' | 'connecting' | 'connected' | 'destroyed';
39
+ interface CollaborationStatusChange {
40
+ status: CollaborationStatus;
41
+ synced: boolean;
42
+ }
43
+ type CollaborationErrorCode = 'backpressure' | 'protocol' | 'replica' | 'transport';
44
+ declare class CollaborationError extends Error {
45
+ readonly code: CollaborationErrorCode;
46
+ readonly cause: unknown;
47
+ constructor(code: CollaborationErrorCode, message: string, cause?: unknown);
48
+ }
49
+ interface CollaborationProviderOptions {
50
+ maxFrameBytes?: number;
51
+ maxMessagesPerFrame?: number;
52
+ maxPendingBytes?: number;
53
+ user?: CollaborationUser;
54
+ }
55
+ interface CollaborationUser {
56
+ name: string;
57
+ color?: string;
58
+ }
59
+ interface CollaborationResolvedUser {
60
+ name: string;
61
+ color: string;
62
+ }
63
+ interface CollaborationCursor {
64
+ story: string;
65
+ anchor: Uint8Array;
66
+ head: Uint8Array;
67
+ }
68
+ interface CollaborationTextInsertion {
69
+ clientId: number;
70
+ story: string;
71
+ paraId: string;
72
+ endOffset: number;
73
+ }
74
+ interface CollaborationAwarenessState {
75
+ clientId: number;
76
+ clock: number;
77
+ user: CollaborationResolvedUser;
78
+ cursor: CollaborationCursor | null;
79
+ }
80
+ interface CollaborationPeer extends CollaborationAwarenessState {
81
+ lastSeenAt: number;
82
+ cursorMovedAt: number;
83
+ inferredCursor: CollaborationTextInsertion | null;
84
+ }
85
+ type CollaborationPeerListener = (peers: readonly CollaborationPeer[]) => void;
86
+ interface CollaborationPresence {
87
+ readonly peers: readonly CollaborationPeer[];
88
+ setCursor(cursor: CollaborationCursor | null, broadcast?: boolean): void;
89
+ onPeers(listener: CollaborationPeerListener): () => void;
90
+ }
91
+ type CollaborationStatusListener = (change: CollaborationStatusChange) => void;
92
+ type CollaborationErrorListener = (error: CollaborationError) => void;
93
+
94
+ /** Typed TypeScript boundary for the Rust package writer. */
95
+
96
+ /**
97
+ * Paragraph IDs a session save applies: IDs for source paragraphs outside
98
+ * the edited stories by part and `w:p` occurrence, and parts written as their
99
+ * source bytes with only these IDs patched in.
100
+ */
101
+ interface RustParagraphIds {
102
+ assignments: Array<{
103
+ part: string;
104
+ ordinal: number;
105
+ paraId: string;
106
+ }>;
107
+ patchedParts: Array<{
108
+ part: string;
109
+ paraIds: Array<[number, string]>;
110
+ }>;
111
+ }
112
+
113
+ /**
114
+ * Paragraph identity DTOs for `YrsSession` identity reads and saves.
115
+ *
116
+ * A session key (`YrsLoc.paraId`) addresses a paragraph in one collaborative
117
+ * document session. A Word paragraph ID (`w14:paraId`) is saved in the file;
118
+ * a paragraph has one once its source carried it, it was authored in a
119
+ * session, or the host called `YrsSession.persistParagraphIds()`.
120
+ */
121
+ /** A Word story qualified by the package part it is read from. */
122
+ type DocxSourceStory = {
123
+ partUri: string;
124
+ kind: 'body' | 'header' | 'footer';
125
+ } | {
126
+ partUri: string;
127
+ kind: 'footnote' | 'endnote' | 'comment';
128
+ itemId: string;
129
+ };
130
+ /** A paragraph in one collaborative document session, on any of its replicas. */
131
+ interface DocxSessionParagraphAnchor {
132
+ kind: 'session';
133
+ sessionId: string;
134
+ story: string;
135
+ paraId: string;
136
+ }
137
+ /**
138
+ * A `w:p` occurrence in the exact source package the session was opened
139
+ * from: its zero-based position among the part's paragraphs, nested ones
140
+ * included, as the source bytes hold them rather than as edited since.
141
+ */
142
+ interface DocxSourceParagraphAnchor {
143
+ kind: 'source';
144
+ packageSha256: string;
145
+ /** OPC part name, such as `/word/document.xml`. */
146
+ partUri: string;
147
+ paragraphOrdinal: number;
148
+ }
149
+ /**
150
+ * A saved Word paragraph ID within its source story. It resolves after the
151
+ * saved file is reopened, but it is scoped to a document the host chose: an
152
+ * eight-digit ID is not a document identifier.
153
+ */
154
+ interface DocxPersistedParagraphAnchor {
155
+ kind: 'persisted';
156
+ story: DocxSourceStory;
157
+ paraId: string;
158
+ }
159
+ type DocxParagraphAnchor = DocxSessionParagraphAnchor | DocxSourceParagraphAnchor | DocxPersistedParagraphAnchor;
160
+ /** A paragraph a resolution, assignment or diagnostic names. */
161
+ type DocxParagraphRef = DocxSessionParagraphAnchor | DocxSourceParagraphAnchor;
162
+ /**
163
+ * Where a Word paragraph ID comes from: `source` IDs are already in the source
164
+ * package; the others are prepared by the session and appear on save.
165
+ */
166
+ type DocxParagraphIdOrigin = 'source' | 'authored' | 'persisted' | 'repaired';
167
+ /** Where a paragraph comes from; `synthetic` ones are editor-only until authored into. */
168
+ type DocxParagraphOrigin = 'source' | 'authored' | 'synthetic';
169
+ interface DocxParagraphIdentity {
170
+ /** `null` for a source paragraph outside the session stories. */
171
+ session: DocxSessionParagraphAnchor | null;
172
+ origin: DocxParagraphOrigin;
173
+ /** The Word paragraph ID the paragraph saves with, or `null` when it saves without one. */
174
+ ooxmlParaId: string | null;
175
+ idOrigin: DocxParagraphIdOrigin | null;
176
+ /** `null` without a Word paragraph ID or a source story. */
177
+ persisted: DocxPersistedParagraphAnchor | null;
178
+ /** `null` unless the paragraph occurs in the retained source package. */
179
+ source: DocxSourceParagraphAnchor | null;
180
+ }
181
+ /**
182
+ * Every paragraph's identities: session paragraphs with stories sorted and in
183
+ * document order, then source paragraphs outside the stories in package order.
184
+ */
185
+ interface DocxParagraphIdentitySnapshot {
186
+ sessionId: string;
187
+ /** SHA-256 of the retained source package, or `null` without one. */
188
+ packageSha256: string | null;
189
+ paragraphs: DocxParagraphIdentity[];
190
+ }
191
+ /** A paragraph `YrsSession.persistParagraphIds()` gave a Word paragraph ID. */
192
+ interface DocxParagraphIdAssignment {
193
+ paragraph: DocxParagraphRef;
194
+ /** The duplicate session key the paragraph carried before repair. */
195
+ replacedParaId: string | null;
196
+ /** The duplicate Word paragraph ID it replaces. */
197
+ previousOoxmlParaId: string | null;
198
+ ooxmlParaId: string;
199
+ idOrigin: 'persisted' | 'repaired';
200
+ /** `null` when the paragraph has no source story. */
201
+ persisted: DocxPersistedParagraphAnchor | null;
202
+ }
203
+ type DocxParagraphIdDiagnostic = {
204
+ /** Saved claims to one ID conflict; the paragraphs keep it and resolve as ambiguous. */
205
+ kind: 'conflicting-saved-ids';
206
+ ooxmlParaId: string;
207
+ paragraphs: DocxParagraphRef[];
208
+ } | {
209
+ /** No retained source package, so source paragraphs outside the stories were not covered. */
210
+ kind: 'no-source-package';
211
+ };
212
+ /**
213
+ * Why `YrsSession.persistParagraphIds()` changed nothing: a duplicated
214
+ * comment paragraph ID the comment companion parts reference, where which
215
+ * comment they mean is ambiguous.
216
+ */
217
+ interface DocxParagraphIdRefusal {
218
+ kind: 'ambiguous-comment-reference';
219
+ ooxmlParaId: string;
220
+ commentIds: string[];
221
+ }
222
+ type DocxParagraphIdentityReceipt = {
223
+ status: 'applied';
224
+ assignments: DocxParagraphIdAssignment[];
225
+ diagnostics: DocxParagraphIdDiagnostic[];
226
+ } | {
227
+ status: 'refused';
228
+ refusal: DocxParagraphIdRefusal;
229
+ };
230
+ type DocxParagraphAnchorResult = {
231
+ status: 'found';
232
+ anchor: DocxParagraphRef;
233
+ } | {
234
+ status: 'missing';
235
+ } | {
236
+ status: 'ambiguous';
237
+ candidates: DocxParagraphRef[];
238
+ } | {
239
+ status: 'unsupported';
240
+ reason: 'foreign-session' | 'foreign-package' | 'no-source-package';
241
+ };
242
+ /** The paragraph IDs a session save applies, as the package writer's `paragraphIds`. @internal */
243
+ type DocxParagraphSavePlan = RustParagraphIds;
244
+
245
+ /**
246
+ * Host proposals: tracked changes a host proposes by paragraph anchor and search, grouped by the
247
+ * host's proposal ids. A round resolves against one version and applies as one atomic batch
248
+ * outside undo history. Decisions only change how the proposals' revisions render: the
249
+ * revisions stay in the document, and the document version and history are untouched until the
250
+ * host withdraws the proposals.
251
+ */
252
+
253
+ type DocxProposalState = 'proposed' | 'accepted' | 'rejected';
254
+ /** Which non-overlapping matches of a search a proposal replaces; numbers count from 1. */
255
+ type DocxOccurrence = 'first' | 'all' | number;
256
+ /**
257
+ * One proposal. `replaceText` with `replaceWith: ''` deletes; with `search: ''` it fills a
258
+ * paragraph whose accepted text is empty (an inline atom counts as text), where the empty search
259
+ * matches once, at offset 0. `insertText` offsets are UTF-16 units of the paragraph's accepted
260
+ * text.
261
+ */
262
+ type DocxProposalInput = {
263
+ id: string;
264
+ paragraph: DocxParagraphAnchor;
265
+ suggest: DocxEditSuggestion;
266
+ } & ({
267
+ op: 'replaceText';
268
+ search: string;
269
+ replaceWith: string;
270
+ occurrence?: DocxOccurrence;
271
+ } | {
272
+ op: 'insertText';
273
+ at: 'start' | 'end' | {
274
+ offset: number;
275
+ };
276
+ text: string;
277
+ });
278
+ interface DocxProposalRequest {
279
+ expectVersion: string;
280
+ proposals: readonly DocxProposalInput[];
281
+ }
282
+ interface DocxProposalRecord {
283
+ id: string;
284
+ state: DocxProposalState;
285
+ paragraph: DocxSessionParagraphAnchor;
286
+ revisionIds: readonly string[];
287
+ changed: boolean;
288
+ }
289
+ interface DocxProposalSnapshot {
290
+ version: string;
291
+ /** Increments whenever a decision changes. */
292
+ previewVersion: number;
293
+ proposals: readonly DocxProposalRecord[];
294
+ }
295
+ type DocxProposalFailure = Omit<DocxEditFailure, 'code'> & {
296
+ code: DocxEditFailureCode | 'stale-preview' | 'unknown-proposal' | 'proposal-id-conflict';
297
+ proposalId?: string;
298
+ };
299
+ type DocxProposalResult = {
300
+ ok: true;
301
+ snapshot: DocxProposalSnapshot;
302
+ } | {
303
+ ok: false;
304
+ version: string;
305
+ failure: DocxProposalFailure;
306
+ };
307
+ /** Ids that name no proposal are ignored, so a retried withdrawal changes nothing. */
308
+ interface DocxProposalWithdrawRequest {
309
+ expectVersion: string;
310
+ ids: readonly string[];
311
+ }
312
+ interface DocxProposalStateRequest {
313
+ expectVersion: string;
314
+ expectPreviewVersion: number;
315
+ changes: readonly {
316
+ id: string;
317
+ state: DocxProposalState;
318
+ }[];
319
+ }
320
+ /** The revision decisions a snapshot shows, for `YrsRenderEnv.revisionPreview`. */
321
+ declare function proposalRevisionPreview(snapshot: DocxProposalSnapshot): Readonly<Record<string, 'accepted' | 'rejected'>> | undefined;
322
+
323
+ /** One native paragraph in the yrs-backed display-position projection. */
324
+ interface YrsInputParagraphSpan {
325
+ paraId: string;
326
+ /** Number of UTF-16/inline units before the paragraph's pilcrow. */
327
+ length: number;
328
+ /** Block start emitted by the yrs display-position projection. */
329
+ displayStart: number;
330
+ }
331
+ /**
332
+ * Live converter between display-list positions and public yrs Locs.
333
+ *
334
+ * A native paragraph of length N occupies N+2 display positions (open token,
335
+ * content, close token), so this map can be rebuilt directly from the live yrs
336
+ * paragraph spans after every structural edit.
337
+ */
338
+ interface YrsInputPositionMap {
339
+ story: string;
340
+ paragraphs: readonly YrsInputParagraphSpan[];
341
+ }
342
+ interface YrsInputParagraphSeed {
343
+ paraId: string;
344
+ length: number;
345
+ }
346
+ declare function createYrsInputPositionMap(story: string, seeds: readonly YrsInputParagraphSeed[]): YrsInputPositionMap;
347
+ /** Convert a live yrs location to the position used by display-list geometry. */
348
+ declare function yrsLocToDisplayPosition(map: YrsInputPositionMap, loc: YrsLoc): number;
349
+ /** Convert a display-list hit position to a paragraph-keyed yrs location. */
350
+ declare function displayPositionToYrsLoc(map: YrsInputPositionMap, position: number): YrsLoc | null;
351
+ /** Compare two Locs in document order using one live map. */
352
+ declare function compareYrsLocs(map: YrsInputPositionMap, a: YrsLoc, b: YrsLoc): number;
353
+
354
+ /** Resolved styling for the worker-painted caret (the worker cannot read CSS vars). */
355
+ interface ResidentCaretPaintStyle {
356
+ color: string;
357
+ /** CSS-px stroke width, matching the DOM caret's un-zoomed width. */
358
+ width: number;
359
+ }
360
+ /** Device-px caret rect: geometry scales by dpr*zoom, stroke width by dpr only
361
+ * (the DOM caret keeps its CSS-px width across zoom levels). */
362
+ declare function residentCaretDeviceRect(rect: Pick<YrsResidentCaretRect, 'x' | 'y' | 'height'>, style: ResidentCaretPaintStyle, devicePixelRatio: number, zoom: number): {
363
+ x: number;
364
+ y: number;
365
+ width: number;
366
+ height: number;
367
+ };
368
+ declare function residentCaretSnapshotForFrame(snapshot: YrsResidentCaretSnapshot, frame: RetainedFrame): YrsResidentCaretSnapshot | null;
369
+
370
+ type ResidentEngineWorkerRequest = {
371
+ id: number;
372
+ type: 'warm';
373
+ } | {
374
+ id: number;
375
+ type: 'bootstrap';
376
+ snapshot: YrsResidentWorkerSnapshot;
377
+ extras: string;
378
+ expectedFrameEpoch: number;
379
+ layoutExtras?: string;
380
+ /** Pages `[start, end)` a full build compiles; the rest stay unbuilt. */
381
+ displayWindow?: [number, number];
382
+ retainBuiltPages?: boolean;
383
+ /**
384
+ * Lay out only as much of the body as fills this many pages; a reply
385
+ * marked `layoutProvisional` is finished by `completeLayout`.
386
+ */
387
+ provisionalPages?: number;
388
+ /**
389
+ * The document replaces the one this worker showed, which the host
390
+ * hands over from: keep the attached page surfaces for its pages.
391
+ */
392
+ keepSurfaces?: boolean;
393
+ /** Lay out the document `open` seeded here, not the snapshot's state. */
394
+ opened?: boolean;
395
+ /** The most the worker's editing core may allocate at once. */
396
+ heapLimitBytes?: number;
397
+ } | {
398
+ id: number;
399
+ type: 'open';
400
+ /** The DOCX package, parsed and seeded in a fresh session here. */
401
+ bytes: ArrayBuffer;
402
+ /** The package's SHA-256, when the caller already took it. */
403
+ digest?: string;
404
+ generation?: string;
405
+ /** The most the worker's editing core may allocate at once. */
406
+ heapLimitBytes?: number;
407
+ } | {
408
+ id: number;
409
+ type: 'fontRequirements';
410
+ layoutInput: string;
411
+ } | {
412
+ id: number;
413
+ type: 'encodeState';
414
+ } | {
415
+ id: number;
416
+ type: 'sync';
417
+ snapshot: YrsResidentWorkerSnapshot;
418
+ extras: string;
419
+ expectedFrameEpoch: number;
420
+ paintCaret: boolean;
421
+ /**
422
+ * Display extras without the header/footer payload. When present, the
423
+ * snapshot's layout is authoritative: the worker completes the extras
424
+ * from the layout it runs and returns that layout as `layoutJson`.
425
+ */
426
+ layoutExtras?: string;
427
+ displayWindow?: [number, number];
428
+ retainBuiltPages?: boolean;
429
+ } | {
430
+ id: number;
431
+ type: 'buildPages';
432
+ pages: number[];
433
+ expectedFrameEpoch: number;
434
+ paintCaret: boolean;
435
+ } | {
436
+ id: number;
437
+ type: 'completeLayout';
438
+ expectedFrameEpoch: number;
439
+ paintCaret: boolean;
440
+ /**
441
+ * Measure the rest this many body blocks a step to start with, letting
442
+ * requests that arrive meanwhile run between steps; absent, in one step.
443
+ */
444
+ sliceBlocks?: number;
445
+ } | {
446
+ id: number;
447
+ type: 'buildFrame';
448
+ extras: string;
449
+ expectedFrameEpoch: number;
450
+ paintCaret: boolean;
451
+ displayWindow?: [number, number];
452
+ retainBuiltPages?: boolean;
453
+ } | {
454
+ id: number;
455
+ type: 'applyInput';
456
+ text: string;
457
+ selection: YrsSelection;
458
+ expectedFrameEpoch: number;
459
+ profile: boolean;
460
+ paintCaret: boolean;
461
+ displayWindow?: [number, number];
462
+ retainBuiltPages?: boolean;
463
+ } | {
464
+ id: number;
465
+ type: 'applyDelete';
466
+ direction: 'backward' | 'forward';
467
+ count: number;
468
+ selection: YrsSelection;
469
+ expectedFrameEpoch: number;
470
+ profile: boolean;
471
+ paintCaret: boolean;
472
+ displayWindow?: [number, number];
473
+ retainBuiltPages?: boolean;
474
+ } | {
475
+ id: number;
476
+ type: 'applyUpdate';
477
+ update: Uint8Array;
478
+ selection: YrsSelection | null;
479
+ } | {
480
+ id: number;
481
+ type: 'attachCanvases';
482
+ pages: Array<{
483
+ pageId: string;
484
+ canvas: OffscreenCanvas;
485
+ }>;
486
+ activePageIds: string[];
487
+ devicePixelRatio: number;
488
+ zoom: number;
489
+ caretStyle: ResidentCaretPaintStyle;
490
+ } | {
491
+ id: number;
492
+ type: 'eraseCaret';
493
+ } | {
494
+ id: number;
495
+ type: 'destroy';
496
+ };
497
+ type ResidentEngineWorkerResponse = ({
498
+ id: number;
499
+ ok: true;
500
+ frame?: ArrayBuffer;
501
+ updates?: ArrayBuffer[];
502
+ engineMs?: number;
503
+ workerTotalMs?: number;
504
+ engineProfile?: YrsEngineApplyProfile;
505
+ caret?: YrsResidentCaretSnapshot;
506
+ selection?: YrsSelection | null;
507
+ /** The presented frame carries the worker-painted caret line. */
508
+ caretPainted?: boolean;
509
+ replayMs?: number;
510
+ replayedPages?: number;
511
+ layoutRevision?: number;
512
+ /** Characters an applyDelete removed. */
513
+ deletedUnits?: number;
514
+ /** The worker replica's yrs state vector after this operation, so the
515
+ * next sync can ship a diff instead of the whole document state. */
516
+ stateVector?: ArrayBuffer;
517
+ /** The region layout the worker ran, for a request carrying `layoutExtras`. */
518
+ layoutJson?: string;
519
+ /** `layoutJson` covers only the first pages of the body. */
520
+ layoutProvisional?: boolean;
521
+ /** An `open` reply: the opened package's host metadata JSON. */
522
+ hostJson?: string;
523
+ /** A `fontRequirements` reply. */
524
+ requirementsJson?: string;
525
+ /** An `encodeState` reply: the document state as one yrs v1 update. */
526
+ state?: ArrayBuffer;
527
+ } | {
528
+ id: number;
529
+ ok: false;
530
+ error: string;
531
+ residentUnavailable?: boolean;
532
+ /** A wasm trap poisoned the worker; it refuses every later request. */
533
+ terminal?: boolean;
534
+ /** The trap followed an allocation the worker's memory could not satisfy. */
535
+ outOfMemory?: boolean;
536
+ }) & {
537
+ /** The worker's wasm memories as the reply left. */
538
+ memory?: WasmModuleMemory[];
539
+ };
540
+
541
+ interface ResidentEngineWorkerFrame {
542
+ frame: Uint8Array;
543
+ updates: Uint8Array[];
544
+ engineMs: number;
545
+ workerTotalMs: number;
546
+ engineProfile?: YrsEngineApplyProfile;
547
+ caret: YrsResidentCaretSnapshot;
548
+ selection: YrsSelection | null;
549
+ /** The presented frame carries the worker-painted caret line. */
550
+ caretPainted: boolean;
551
+ replayMs: number;
552
+ replayedPages: number;
553
+ layoutRevision: number;
554
+ /** Characters an applyDelete removed. */
555
+ deletedUnits: number;
556
+ /** The region layout the worker ran, when the request handed it the layout. */
557
+ layoutJson?: string;
558
+ /** `layoutJson` covers only the first pages; `completeLayout` finishes it. */
559
+ layoutProvisional?: boolean;
560
+ }
561
+ /** A bootstrap/sync whose snapshot layout the worker runs as the only layout. */
562
+ interface ResidentEngineWorkerLayoutOptions {
563
+ /** Display extras minus the header/footer payload the worker's layout supplies. */
564
+ layoutExtras?: string;
565
+ /** The host state vector the snapshot brings the worker to. */
566
+ stateVector?: Uint8Array;
567
+ /** Bootstrap only: lay out just the body's first pages before replying. */
568
+ provisionalPages?: number;
569
+ /** Bootstrap only: lay out the document {@link ResidentEngineWorkerClient.open} opened. */
570
+ opened?: boolean;
571
+ /** Bootstrap only: the epoch of the frame the host shows; the worker's frames follow it. */
572
+ frameEpoch?: number;
573
+ /**
574
+ * Bootstrap only: the most the worker's editing core may allocate at once.
575
+ * An allocation past it stops the worker with {@link ResidentWorkerOutOfMemoryError}.
576
+ */
577
+ heapLimitBytes?: number;
578
+ }
579
+ /** What an {@link ResidentEngineWorkerClient.open} seeded in the worker. */
580
+ interface ResidentEngineWorkerOpened {
581
+ /** The package's host metadata JSON, for `decodeDocxHostJson`. */
582
+ hostJson: string;
583
+ /** The worker replica's state vector once seeded. */
584
+ stateVector: Uint8Array;
585
+ }
586
+ /** How a bootstrap or sync builds its frame. */
587
+ interface ResidentEngineWorkerSnapshotOptions {
588
+ /** Pages `[start, end)` the frame builds; the rest stay unbuilt. */
589
+ displayWindow?: [number, number];
590
+ }
591
+ interface ResidentEngineOffscreenPage {
592
+ pageId: string;
593
+ canvas: OffscreenCanvas;
594
+ }
595
+ interface ResidentEngineWorkerApplyResult extends ResidentEngineWorkerFrame {
596
+ applied: true;
597
+ }
598
+ interface ResidentEngineWorkerPort {
599
+ onmessage: ((event: MessageEvent<ResidentEngineWorkerResponse>) => void) | null;
600
+ onerror: ((event: ErrorEvent) => void) | null;
601
+ onmessageerror: ((event: MessageEvent) => void) | null;
602
+ postMessage(message: ResidentEngineWorkerRequest, transfer?: Transferable[]): void;
603
+ terminate(): void;
604
+ }
605
+ /** Dedicated-worker owner for resident input, pagination, and FrameDelta output. */
606
+ declare class ResidentEngineWorkerClient {
607
+ private readonly worker;
608
+ private readonly pending;
609
+ private watchdog;
610
+ private nextId;
611
+ private terminalError;
612
+ private ready;
613
+ private revision;
614
+ private remoteVector;
615
+ private appliedFontsRevision;
616
+ private bootstrapped;
617
+ /** Set once `open` is sent, with the heap limit it opened under. */
618
+ private openedHeapLimit;
619
+ private bootstraps;
620
+ /** Id of the last snapshot request sent; replies to earlier requests must
621
+ * not replace the state it recorded. */
622
+ private lastSnapshotId;
623
+ private keepSurfaces;
624
+ private lastMemory;
625
+ private answeredFrameEpoch;
626
+ private retainBuiltPages;
627
+ constructor(worker?: ResidentEngineWorkerPort);
628
+ isReady(): boolean;
629
+ /** @internal */
630
+ hasFailed(): boolean;
631
+ /** The worker's wasm memories as of its latest reply; null before one. */
632
+ memory(): WasmModuleMemory[] | null;
633
+ layoutRevision(): number;
634
+ /** @internal The newest frame epoch a reply carried; 0 before any frame. */
635
+ answeredFrame(): number;
636
+ /** @internal */
637
+ setRetainBuiltPages(retain: boolean): void;
638
+ /** @internal Whether a frame request other than `buildPages` awaits its reply. */
639
+ frameRequestPending(): boolean;
640
+ /** The worker replica's last reported yrs state vector (null before any). */
641
+ remoteStateVector(): Uint8Array | null;
642
+ /** The fonts revision this worker last applied (null before bootstrap). */
643
+ syncedFontsRevision(): number | null;
644
+ /** A bootstrap was sent; later snapshots go as syncs queued behind it. */
645
+ bootstrapSent(): boolean;
646
+ /**
647
+ * Starts over with another document in the same worker: the next request
648
+ * is a bootstrap, which keeps the page surfaces already attached so the
649
+ * new document's pages paint where the old ones were.
650
+ */
651
+ rebootstrap(): void;
652
+ /**
653
+ * Parses and seeds a DOCX in the worker, which then holds the document:
654
+ * its first layout is a bootstrap with `opened`, and the main replica loads
655
+ * {@link encodeState}. A copy of `bytes` is transferred.
656
+ */
657
+ open(bytes: Uint8Array, options?: {
658
+ digest?: string;
659
+ generation?: string;
660
+ heapLimitBytes?: number;
661
+ }): Promise<ResidentEngineWorkerOpened>;
662
+ /** The font requirements of a region layout request, read from the opened document. */
663
+ fontRequirements(layoutInput: string): Promise<string>;
664
+ /** The worker's whole document state as one yrs v1 update. */
665
+ encodeState(): Promise<Uint8Array>;
666
+ warm(): Promise<void>;
667
+ bootstrap(snapshot: YrsResidentWorkerSnapshot, extras: string, options?: ResidentEngineWorkerLayoutOptions & ResidentEngineWorkerSnapshotOptions): Promise<ResidentEngineWorkerFrame>;
668
+ sync(snapshot: YrsResidentWorkerSnapshot, extras: string, expectedFrameEpoch: number, paintCaret?: boolean, options?: ResidentEngineWorkerLayoutOptions & ResidentEngineWorkerSnapshotOptions): Promise<ResidentEngineWorkerFrame>;
669
+ /**
670
+ * Lay out the rest of a provisional bootstrap layout: its frame and full
671
+ * layout, or null when a later snapshot already replaced it.
672
+ */
673
+ completeLayout(expectedFrameEpoch: number, paintCaret?: boolean, sliceBlocks?: number): Promise<ResidentEngineWorkerFrame | null>;
674
+ buildFrame(extras: string, expectedFrameEpoch: number, paintCaret?: boolean, displayWindow?: [number, number]): Promise<ResidentEngineWorkerFrame>;
675
+ /** Build unbuilt display pages; the reply frame carries them. */
676
+ buildPages(pages: number[], expectedFrameEpoch: number, paintCaret?: boolean): Promise<ResidentEngineWorkerFrame>;
677
+ applyInput(text: string, selection: YrsSelection, expectedFrameEpoch: number, profile?: boolean, paintCaret?: boolean, displayWindow?: [number, number]): Promise<ResidentEngineWorkerApplyResult | {
678
+ applied: false;
679
+ }>;
680
+ applyDelete(direction: 'backward' | 'forward', selection: YrsSelection, expectedFrameEpoch: number, profile?: boolean, paintCaret?: boolean, count?: number, displayWindow?: [number, number]): Promise<ResidentEngineWorkerApplyResult | {
681
+ applied: false;
682
+ }>;
683
+ /** Drop the worker-painted caret line by re-presenting the caret page's
684
+ * retained raster. Fire-and-forget and idempotent. */
685
+ eraseCaret(): void;
686
+ invalidate(update: Uint8Array, selection: YrsSelection | null): void;
687
+ attachCanvases(pages: ResidentEngineOffscreenPage[], activePageIds: string[], devicePixelRatio: number, zoom: number, caretStyle: ResidentCaretPaintStyle): Promise<void>;
688
+ destroy(): void;
689
+ private request;
690
+ /**
691
+ * Requests run in order, so once a snapshot is sent every later request
692
+ * finds its state and fonts in the worker: the next sync can diff against
693
+ * them before this one answers.
694
+ */
695
+ private recordSent;
696
+ /** Restarted by every message, so a queue of slow but answered requests never trips it. */
697
+ private armWatchdog;
698
+ private disarmWatchdog;
699
+ /** Record a successfully applied bootstrap/sync payload's fonts revision.
700
+ * The state vector is tracked centrally in `onmessage`. */
701
+ private recordSync;
702
+ private fail;
703
+ }
704
+ declare class ResidentWorkerUnavailableError extends Error {
705
+ }
706
+ /** The worker itself failed (crash, timeout, torn-down, corrupt reply). */
707
+ declare class ResidentWorkerFailureError extends Error {
708
+ }
709
+ /** The worker trapped because its wasm memory could not grow any further. */
710
+ declare class ResidentWorkerOutOfMemoryError extends ResidentWorkerUnavailableError {
711
+ /** The worker's wasm memories when it trapped. */
712
+ readonly memory: WasmModuleMemory[];
713
+ constructor(message: string,
714
+ /** The worker's wasm memories when it trapped. */
715
+ memory: WasmModuleMemory[]);
716
+ }
717
+ declare function canUseResidentEngineWorker(): boolean;
718
+ /** @internal */
719
+ declare function preloadResidentEngineWorker(): Promise<void>;
720
+ /** @internal */
721
+ declare function retainPreloadedResidentEngineWorker(): () => void;
722
+ /** @internal */
723
+ declare function takePreloadedResidentEngineWorker(): ResidentEngineWorkerClient | null;
724
+
725
+ /**
726
+ * Preload the editing engine and one spare resident worker. Opt-in.
727
+ * @experimental
728
+ */
729
+ declare function preloadDocxEngine(): Promise<void>;
730
+
731
+ /** Direct Document-to-yrs load projection. */
732
+
733
+ /**
734
+ * Seeds every yrs-owned editable story directly from a parsed Document.
735
+ *
736
+ * Stories are `body`, `hf:{rId}`, `fn:{id}`, `en:{id}`, and recursively generated table
737
+ * cell / block-SDT stories. The target session must not already contain any of
738
+ * those story ids. Seeding starts a new opening; see {@link YrsSession.beginOpening}.
739
+ *
740
+ * @public
741
+ */
742
+ declare function documentToYrs(session: YrsSession, document: Document, options?: YrsOpeningOptions): void;
743
+
744
+ /** yrs-to-OOXML save projection. */
745
+
746
+ /**
747
+ * Rebuild all yrs-owned editable stories into the serializer-facing Document
748
+ * while preserving every package part the editor does not own.
749
+ */
750
+ interface YrsToDocumentOptions {
751
+ /**
752
+ * Root stories to project. Omit to rebuild every editable story. A `body`
753
+ * projection includes its nested table/content-control stories.
754
+ */
755
+ storyIds?: ReadonlySet<string>;
756
+ /**
757
+ * The session comment id of each comment in `base` whose OOXML id is not
758
+ * that id, such as one added with {@link YrsSession.addComment}. @internal
759
+ */
760
+ commentIds?: ReadonlyMap<number, string>;
761
+ }
762
+ declare function yrsToDocument(session: YrsSession, base: Document, options?: YrsToDocumentOptions): Document;
763
+
764
+ /** Session save that reports where each saved paragraph can be found after reopening. */
765
+
766
+ /** A saved paragraph's session anchor and the persisted anchor that resolves to it once reopened. */
767
+ interface DocxSavedParagraph {
768
+ session: DocxSessionParagraphAnchor;
769
+ persisted: DocxPersistedParagraphAnchor;
770
+ }
771
+ interface DocxSavedDocument {
772
+ bytes: Uint8Array;
773
+ /**
774
+ * Every session paragraph the bytes hold with a Word paragraph ID, in
775
+ * document order. Stories that share a part are views of its paragraphs:
776
+ * each view the part holds is listed, and its persisted anchor resolves to
777
+ * the first story's view once reopened.
778
+ */
779
+ paragraphs: DocxSavedParagraph[];
780
+ /**
781
+ * Saved paragraphs whose Word paragraph ID the live session reassigned
782
+ * while the save was written, such as by a duplicate repair after a remote
783
+ * update: their persisted anchor finds them in these bytes, not in the
784
+ * live session.
785
+ */
786
+ conflicts: DocxSavedParagraph[];
787
+ }
788
+ /** The identities and paragraph ID plan a session save applies. @internal */
789
+ interface DocxSessionSave {
790
+ identities: DocxParagraphIdentitySnapshot;
791
+ plan: DocxParagraphSavePlan;
792
+ }
793
+ /** Captures a save of `session`, in the task that projects the saved document. @internal */
794
+ declare function captureSessionSave(session: YrsSession): DocxSessionSave;
795
+ /**
796
+ * Writes `document`, projected from `session` when `capture` was taken, and
797
+ * records the Word paragraph IDs the bytes hold as saved. `patches` selects
798
+ * the planned parts written as `originalBuffer`'s bytes with IDs patched in;
799
+ * it selects none unless `originalBuffer` is the session's source package.
800
+ * @internal
801
+ */
802
+ declare function writeSessionSave(session: YrsSession, document: Document, capture: DocxSessionSave, originalBuffer: ArrayBuffer, options?: RepackOptions, patches?: (part: string) => boolean): Promise<DocxSavedDocument>;
803
+ /**
804
+ * Saves a session opened from DOCX bytes and reports each saved paragraph's
805
+ * persisted anchor, read from the same projection the bytes are written
806
+ * from and kept only where the written part holds its Word paragraph ID.
807
+ * Parts whose stories are unchanged since the session opened keep
808
+ * their source bytes, paragraph IDs aside. The comments the session holds
809
+ * are saved with their anchors, those added to it included; replies and
810
+ * resolution are saved as the source package has them. A source paragraph without a
811
+ * Word paragraph ID saves without one unless the host called
812
+ * `persistParagraphIds()` first; the IDs a save writes are recorded as
813
+ * saved, so they keep them against unsaved claims from other replicas, once
814
+ * reconciled with the live session.
815
+ */
816
+ declare function saveYrsDocx(session: YrsSession, options?: RepackOptions): Promise<DocxSavedDocument>;
817
+
818
+ interface YrsDocxHost {
819
+ document: Document;
820
+ referencedFonts: string[];
821
+ /**
822
+ * The `referencedFonts` a document seeded from its package names only for
823
+ * East Asian or complex-script text it does not contain, so no text is
824
+ * measured or drawn with them. Empty when its stories were not seeded; a
825
+ * preview's cover only its own first pages.
826
+ */
827
+ unusedScriptFonts?: string[];
828
+ embeddedFonts: Map<string, ArrayBuffer>;
829
+ fontTableRelationshipsXml?: string;
830
+ }
831
+ /** Durable authorship metadata for one suggested (tracked-change) operation. */
832
+ interface YrsAuthor {
833
+ name: string;
834
+ /** ISO timestamp supplied by the host so all peers share one clock policy. */
835
+ date: string;
836
+ }
837
+ /** One position: `(story, paraId, offset)` — offsets are UTF-16 units within the paragraph. */
838
+ interface YrsLoc {
839
+ story: string;
840
+ paraId: string;
841
+ offset: number;
842
+ }
843
+ /** One binary Yrs position that transforms with collaborative edits. */
844
+ interface YrsStickyPosition {
845
+ story: string;
846
+ encoded: Uint8Array;
847
+ }
848
+ /** A paragraph-addressed position without the story (used inside {@link YrsStoryRange}). */
849
+ interface YrsParaOffset {
850
+ paraId: string;
851
+ offset: number;
852
+ }
853
+ /**
854
+ * A half-open range `[start, end)` inside one story. Ends may sit in
855
+ * different paragraphs; the boundary pilcrows are then part of the range
856
+ * (deleting such a range merges paragraphs).
857
+ */
858
+ interface YrsStoryRange {
859
+ story: string;
860
+ start: YrsParaOffset;
861
+ end: YrsParaOffset;
862
+ }
863
+ /** One run-level mark for {@link YrsSession.toggleMark}. */
864
+ type YrsRunMark = {
865
+ type: 'bold';
866
+ } | {
867
+ type: 'italic';
868
+ } | {
869
+ type: 'underline';
870
+ } | {
871
+ type: 'superscript';
872
+ } | {
873
+ type: 'subscript';
874
+ } | {
875
+ type: 'fontFamily';
876
+ value: string;
877
+ } | {
878
+ type: 'fontSize';
879
+ value: number;
880
+ } | {
881
+ type: 'color';
882
+ value: string;
883
+ };
884
+ /** A direct text color written by {@link YrsSession.formatRange}. */
885
+ type YrsTextColor = {
886
+ rgb: string;
887
+ themeColor?: never;
888
+ } | {
889
+ rgb?: never;
890
+ themeColor: string;
891
+ };
892
+ /**
893
+ * Set-valued inline formatting for {@link YrsSession.formatRange}. Omitted
894
+ * fields are left unchanged; `null` clears a field. Boolean `false` also
895
+ * clears the corresponding mark.
896
+ */
897
+ interface YrsInlineFormatDelta {
898
+ bold?: boolean | null;
899
+ italic?: boolean | null;
900
+ underline?: boolean | {
901
+ style?: string;
902
+ color?: string;
903
+ } | null;
904
+ strike?: boolean | {
905
+ double?: boolean;
906
+ } | null;
907
+ color?: YrsTextColor | null;
908
+ highlight?: string | null;
909
+ /** Font size in points; Rust writes both OOXML half-point size fields. */
910
+ fontSize?: number | null;
911
+ fontFamily?: {
912
+ ascii: string;
913
+ hAnsi?: string;
914
+ } | null;
915
+ /** Passive run properties not covered by the typed fields. `null` clears. */
916
+ other?: Readonly<Record<string, unknown | null>>;
917
+ }
918
+ interface YrsHyperlinkAttrs {
919
+ href: string;
920
+ tooltip?: string | null;
921
+ rId?: string | null;
922
+ }
923
+ /** Seed shape for {@link YrsSession.loadStories}. */
924
+ interface YrsParagraphSeed {
925
+ /** Paragraph text; must not contain paragraph breaks. */
926
+ text: string;
927
+ /** Defaults to `"Normal"`. */
928
+ pStyle?: string;
929
+ /** Defaults to `"left"`. */
930
+ alignment?: string;
931
+ }
932
+ /** One story to seed via {@link YrsSession.loadStories}. */
933
+ interface YrsStorySeed {
934
+ storyId: string;
935
+ /** At least one paragraph. */
936
+ paragraphs: readonly YrsParagraphSeed[];
937
+ }
938
+ /** How a seeding entry point starts its opening; see {@link YrsSession.beginOpening}. */
939
+ interface YrsOpeningOptions {
940
+ /**
941
+ * A fixed opening generation, for a deterministic seed every replica loads
942
+ * as one session. Each opening mints a fresh one by default.
943
+ */
944
+ generation?: string;
945
+ /**
946
+ * Seeds images as `media:{n}` tokens naming their part of the package,
947
+ * instead of `data:` URLs, keeping them out of the document state. Only a
948
+ * replica opened from the same package on a version that reads tokens
949
+ * shows them, so every client of a shared room must be one. Off by default.
950
+ */
951
+ mediaTokens?: boolean;
952
+ }
953
+ /**
954
+ * A copy of `bytes` whose SHA-256 the platform takes off the calling thread,
955
+ * where it has Web Crypto. Opening that copy unchanged skips hashing the
956
+ * package on the calling thread; any other bytes open as before.
957
+ * @internal
958
+ */
959
+ declare function prepareDocxBytes(bytes: Uint8Array): Promise<Uint8Array>;
960
+ /** The SHA-256 {@link prepareDocxBytes} took of `bytes`, if it took one. @internal */
961
+ declare function preparedDocxDigest(bytes: Uint8Array): string | undefined;
962
+ /** Snapshot of one paragraph from {@link YrsSession.paragraphs}. */
963
+ interface YrsParagraph {
964
+ /** Session key; not the paragraph's Word `w14:paraId`. */
965
+ paraId: string;
966
+ text: string;
967
+ /** pStyle / alignment plus any op-set extras. */
968
+ properties: Record<string, unknown>;
969
+ }
970
+ interface YrsTextSearchOptions {
971
+ /** Defaults to false. */
972
+ caseSensitive?: boolean;
973
+ /** Maximum matches; unlimited by default. */
974
+ limit?: number;
975
+ }
976
+ /** Paragraph-local UTF-16 offsets. */
977
+ interface YrsTextMatch {
978
+ story: string;
979
+ paraId: string;
980
+ start: number;
981
+ end: number;
982
+ text: string;
983
+ }
984
+ /** One direct numbering reference (`w:numPr`) on a paragraph. */
985
+ interface YrsNumberingProperties {
986
+ numId?: number;
987
+ ilvl?: number;
988
+ }
989
+ /** One paragraph tab stop, measured in twips from the left margin. */
990
+ interface YrsParagraphTabStop {
991
+ position: number;
992
+ alignment: 'left' | 'center' | 'right' | 'decimal' | 'bar' | 'clear' | 'num';
993
+ leader?: 'none' | 'dot' | 'hyphen' | 'underscore' | 'heavy' | 'middleDot';
994
+ }
995
+ /**
996
+ * Tri-state properties for {@link YrsSession.setParagraphAttrs}. Omitted
997
+ * fields are kept and `null` clears. Numeric spacing and indents are OOXML
998
+ * twips/line-spacing units, never CSS pixels.
999
+ */
1000
+ interface YrsParagraphAttrs {
1001
+ alignment?: 'left' | 'center' | 'right' | 'both' | 'distribute' | 'mediumKashida' | 'highKashida' | 'lowKashida' | 'thaiDistribute' | null;
1002
+ lineSpacing?: number | null;
1003
+ lineSpacingRule?: 'auto' | 'exact' | 'atLeast' | null;
1004
+ spaceBefore?: number | null;
1005
+ spaceAfter?: number | null;
1006
+ indentLeft?: number | null;
1007
+ indentRight?: number | null;
1008
+ indentFirstLine?: number | null;
1009
+ hangingIndent?: boolean | null;
1010
+ bidi?: boolean | null;
1011
+ tabs?: readonly YrsParagraphTabStop[] | null;
1012
+ defaultTextFormatting?: Readonly<Record<string, unknown>> | null;
1013
+ numPr?: YrsNumberingProperties | null;
1014
+ numPrFromStyle?: YrsNumberingProperties | null;
1015
+ listNumFmt?: string | null;
1016
+ listIsBullet?: boolean | null;
1017
+ listMarker?: string | null;
1018
+ listMarkerHidden?: boolean | null;
1019
+ listMarkerFontFamily?: string | null;
1020
+ listMarkerFontSize?: number | null;
1021
+ listMarkerBold?: boolean | null;
1022
+ listMarkerItalic?: boolean | null;
1023
+ listMarkerColor?: ColorValue | null;
1024
+ listMarkerSuffix?: 'tab' | 'space' | 'nothing' | null;
1025
+ listLevelNumFmts?: readonly string[] | null;
1026
+ listAbstractNumId?: number | null;
1027
+ listStartOverride?: number | null;
1028
+ /** Passive pPr/model properties not covered by the typed fields. */
1029
+ other?: Readonly<Record<string, unknown | null>>;
1030
+ }
1031
+ /**
1032
+ * Typed value for a content control. A string fills a plain- or rich-text control's content
1033
+ * (as a `setContentControlText` edit step would); the objects set checkbox, dropdown and date
1034
+ * controls.
1035
+ */
1036
+ type YrsContentControlValue = {
1037
+ kind: 'dropdown';
1038
+ value: string;
1039
+ } | {
1040
+ kind: 'checkbox';
1041
+ checked: boolean;
1042
+ } | {
1043
+ kind: 'date';
1044
+ date: string;
1045
+ } | string;
1046
+ /** Image geometry authored in OOXML EMUs plus wrapping/position metadata. */
1047
+ interface YrsImageGeometry {
1048
+ widthEmu: number;
1049
+ heightEmu: number;
1050
+ wrap?: 'inline' | 'square' | 'tight' | 'through' | 'topAndBottom' | 'behind' | 'inFront';
1051
+ hOffsetEmu?: number | null;
1052
+ vOffsetEmu?: number | null;
1053
+ distTopEmu?: number | null;
1054
+ distBottomEmu?: number | null;
1055
+ distLeftEmu?: number | null;
1056
+ distRightEmu?: number | null;
1057
+ relativeFromHorizontal?: string | null;
1058
+ relativeFromVertical?: string | null;
1059
+ /** Additional image payload fields; `null` clears an existing field. */
1060
+ other?: Readonly<Record<string, unknown | null>>;
1061
+ }
1062
+ /** A text or picture watermark payload for {@link YrsSession.insertWatermark}. */
1063
+ type YrsWatermark = {
1064
+ kind: 'text';
1065
+ text: string;
1066
+ font: string;
1067
+ color: string;
1068
+ semitransparent: boolean;
1069
+ layout: 'diagonal' | 'horizontal';
1070
+ fontSize?: number;
1071
+ decorative?: boolean;
1072
+ } | {
1073
+ kind: 'picture';
1074
+ relId?: string;
1075
+ mediaPath?: string;
1076
+ dataUrl?: string;
1077
+ contentType?: string;
1078
+ scale: number;
1079
+ washout: boolean;
1080
+ widthEmu?: number;
1081
+ heightEmu?: number;
1082
+ decorative?: boolean;
1083
+ };
1084
+ /**
1085
+ * One formatted segment from {@link YrsSession.storySegments} — the render
1086
+ * bridge's input. `attributes` carries run marks plus `ins` / `del` revision
1087
+ * values (suggested deletions are retained text with a `del` attribute).
1088
+ */
1089
+ type YrsStorySegment = {
1090
+ kind: 'text';
1091
+ text: string;
1092
+ attributes: Record<string, unknown>;
1093
+ } | {
1094
+ kind: 'pilcrow';
1095
+ paraId: string;
1096
+ properties: Record<string, unknown>;
1097
+ attributes: Record<string, unknown>;
1098
+ } | {
1099
+ kind: 'embed';
1100
+ /** Map-backed embed discriminator (`table`, `noteRef`, `image`, …). */
1101
+ embedKind: string;
1102
+ /** Authored map entries excluding the discriminator. */
1103
+ payload: Record<string, unknown>;
1104
+ attributes: Record<string, unknown>;
1105
+ };
1106
+ /** Current offsets of one sticky comment anchor. */
1107
+ interface YrsResolvedCommentAnchor {
1108
+ story: string;
1109
+ start: number;
1110
+ end: number;
1111
+ }
1112
+ /** A paragraph's story span; `end` is its pilcrow, so `end - start` is the paragraph length. */
1113
+ interface YrsParagraphSpan {
1114
+ start: number;
1115
+ end: number;
1116
+ }
1117
+ /** Compact paragraph entry used to build the live input-position projection. */
1118
+ interface YrsParagraphLength {
1119
+ paraId: string;
1120
+ /** UTF-16 text and inline embed units before the paragraph's pilcrow. */
1121
+ length: number;
1122
+ }
1123
+ /** Receipt of an op that minted a paragraph id. */
1124
+ interface YrsParagraphReceipt {
1125
+ paraId: string;
1126
+ }
1127
+ /** Receipt of an op that may have minted a tracked-change revision (suggesting mode). */
1128
+ interface YrsRevisionReceipt {
1129
+ revisionId: string | null;
1130
+ }
1131
+ /** Where the replacement text landed; after the struck-out text when suggesting. */
1132
+ interface YrsReplaceReceipt extends YrsRevisionReceipt {
1133
+ range?: YrsStoryRange;
1134
+ }
1135
+ /**
1136
+ * Receipt of {@link YrsSession.splitParagraph}. The first half keeps the
1137
+ * original paraId and the second half is re-minted; suggesting
1138
+ * mode stamps a `pPrIns` revision on the first half.
1139
+ */
1140
+ interface YrsSplitReceipt {
1141
+ firstParaId: string;
1142
+ secondParaId: string;
1143
+ revisionId: string | null;
1144
+ }
1145
+ /** Low-level UTF-16 story operation for {@link YrsSession.applyRawOps}. */
1146
+ type YrsRawOp = {
1147
+ op: 'insert';
1148
+ index: number;
1149
+ text: string;
1150
+ attrs?: Record<string, unknown>;
1151
+ } | {
1152
+ op: 'delete';
1153
+ index: number;
1154
+ len: number;
1155
+ } | {
1156
+ op: 'format';
1157
+ index: number;
1158
+ len: number;
1159
+ attrs?: Record<string, unknown>;
1160
+ } | {
1161
+ /**
1162
+ * A pilcrow's `ooxmlParaId` binds its Word paragraph ID and is dropped
1163
+ * when it is not one; `sourceParaId` and `paraOrigin` are seeding's to set.
1164
+ */
1165
+ op: 'insertEmbed';
1166
+ index: number;
1167
+ kind: string;
1168
+ payload?: Record<string, unknown>;
1169
+ attrs?: Record<string, unknown>;
1170
+ } | {
1171
+ op: 'setEmbedAttr';
1172
+ index: number;
1173
+ key: string;
1174
+ value: unknown;
1175
+ } | {
1176
+ /** Upserts a side-map comment with sticky story-unit ranges. */
1177
+ op: 'setComment';
1178
+ id: string;
1179
+ ranges: ReadonlyArray<readonly [number, number]>;
1180
+ author?: string;
1181
+ date?: string;
1182
+ body?: unknown;
1183
+ } | {
1184
+ /** Removes the side-map comment keyed by `id`; errors when missing. */
1185
+ op: 'removeComment';
1186
+ id: string;
1187
+ };
1188
+ /** Host context for {@link YrsSession.yrsBlocksForStory} (theme + list numbering). */
1189
+ interface YrsRenderEnv {
1190
+ compatibilityFlags?: Partial<CompatibilityFlags>;
1191
+ tocStyleIds?: string[];
1192
+ paragraphSpacingLinePx?: number;
1193
+ /** Section document-grid snap pitch in px (w:docGrid). The engine derives this from sections; hosts may omit it. */
1194
+ docGridPitchPx?: number;
1195
+ defaultParagraphStyleId?: string;
1196
+ /** Theme color name → hex (`accent1` → `4472C4`), for theme-color resolution. */
1197
+ themeColors?: Record<string, string>;
1198
+ /** The document default tab stop in twips. */
1199
+ defaultTabStopTwips?: number | null;
1200
+ /** Current page content height in CSS px, for proportional drawing constraints. */
1201
+ pageContentHeight?: number | null;
1202
+ /** yrs revision/paragraph id → dense numeric layout id (list markers, revisions). */
1203
+ numericIds?: Record<string, number>;
1204
+ /** Include hidden text in visible layout without changing the document. */
1205
+ showHiddenText?: boolean;
1206
+ /** Revision id → decision shown in layout; unlisted revisions render as tracked changes. */
1207
+ revisionPreview?: Readonly<Record<string, 'accepted' | 'rejected'>>;
1208
+ /**
1209
+ * Lay the opened package's images out as `media:{n}` tokens, which a
1210
+ * resolver given the session's `mediaSource` reads. @internal
1211
+ */
1212
+ mediaTokens?: boolean;
1213
+ }
1214
+ /** Receipt of {@link YrsSession.addComment}. */
1215
+ interface YrsCommentReceipt {
1216
+ commentId: string;
1217
+ }
1218
+ /** A comment the session holds; see {@link YrsSession.listComments}. @internal */
1219
+ interface YrsCommentInfo {
1220
+ id: string;
1221
+ author: string;
1222
+ date: string;
1223
+ done: boolean;
1224
+ parentId: string | null;
1225
+ /** The body as it was given to {@link YrsSession.addComment} or `setComment`. */
1226
+ body: unknown;
1227
+ }
1228
+ /**
1229
+ * Target of {@link YrsSession.acceptChange} / {@link YrsSession.rejectChange}:
1230
+ * one coalesced revision id (resolved at every site, in any story — the
1231
+ * `acceptChangeById` twin) or an explicit story range (the range-command twin;
1232
+ * every tracked change overlapping the range resolves, no id filtering).
1233
+ */
1234
+ type YrsChangeTarget = {
1235
+ revisionId: string;
1236
+ } | YrsStoryRange;
1237
+ /** Receipt of {@link YrsSession.acceptChange} / {@link YrsSession.rejectChange}. */
1238
+ interface YrsResolveReceipt {
1239
+ /** The revision ids resolved by the op (resolution order, deduplicated). */
1240
+ revisionIds: string[];
1241
+ }
1242
+ /** This peer's awareness selection, resolved from two yrs sticky positions. */
1243
+ interface YrsSelection {
1244
+ anchor: YrsLoc;
1245
+ head: YrsLoc;
1246
+ }
1247
+ interface YrsResidentCaretRect {
1248
+ pageIndex: number;
1249
+ pageId: string;
1250
+ x: number;
1251
+ y: number;
1252
+ height: number;
1253
+ }
1254
+ interface YrsResidentCaretSnapshot {
1255
+ frameEpoch: number;
1256
+ caretRect: YrsResidentCaretRect | null;
1257
+ /** Selection the rect was computed for. Absent on raw engine snapshots. */
1258
+ selection?: YrsSelection | null;
1259
+ }
1260
+ declare function sameYrsSelection(left: YrsSelection | null, right: YrsSelection | null): boolean;
1261
+ /** How far a region layout begun with {@link YrsSession.beginRegionLayout} has come. */
1262
+ interface YrsRegionLayoutProgress {
1263
+ measuredBlocks: number;
1264
+ bodyBlocks: number;
1265
+ /** The retained region layout reply, once the pass is complete. */
1266
+ layoutJson?: string;
1267
+ }
1268
+ /** Opt-in internal stage timings for one resident engine input. @internal */
1269
+ interface YrsEngineApplyProfile {
1270
+ selectionMs: number;
1271
+ editMs: number;
1272
+ lowerMs: number;
1273
+ measureMs: number;
1274
+ paginateMs: number;
1275
+ displayInputMs: number;
1276
+ displayBuildMs: number;
1277
+ displayFinalizeMs: number;
1278
+ displayMs: number;
1279
+ encodeMs: number;
1280
+ }
1281
+ /**
1282
+ * Serializable bootstrap state for the dedicated resident-layout worker.
1283
+ * The main-thread yrs replica records the inputs that established resident
1284
+ * render, measurement, and pagination state; the worker replays them once and
1285
+ * then owns every ordinary input-to-frame transaction.
1286
+ *
1287
+ * @internal
1288
+ */
1289
+ /**
1290
+ * One resident font-store registration, in the order the main thread made it:
1291
+ * raw bytes, or a measurement view of an earlier id. The worker replays the
1292
+ * list to reproduce the same dense ids, so the order and the mix both matter.
1293
+ *
1294
+ * @internal
1295
+ */
1296
+ type YrsResidentFontRegistration = Uint8Array | {
1297
+ substituteOf: number;
1298
+ family: string;
1299
+ };
1300
+ interface YrsResidentWorkerSnapshot {
1301
+ clientId: number;
1302
+ /** Full document state, or a state-vector diff when the caller supplied
1303
+ * the worker's known vector — both apply through the same merge path. */
1304
+ state: Uint8Array;
1305
+ selection: YrsSelection | null;
1306
+ /** Empty when the caller declared the worker's fonts current
1307
+ * (`knownFontsRevision` matches); the worker then keeps its registrations. */
1308
+ fonts: YrsResidentFontRegistration[];
1309
+ /** Monotonic revision of the resident font set (bumped by register/clear). */
1310
+ fontsRevision: number;
1311
+ renderInputs: Array<{
1312
+ story: string;
1313
+ env: YrsRenderEnv;
1314
+ }>;
1315
+ measureInputs: string[];
1316
+ layoutInput: string;
1317
+ layoutWithRegions: boolean;
1318
+ layoutRevision: number;
1319
+ /** The document is a preview's cut of a package: its layouts render NUMPAGES empty. */
1320
+ partialDocument?: boolean;
1321
+ /** Which seeded `data:` image sources lay out as `media:{n}` tokens. @internal */
1322
+ mediaSources?: string;
1323
+ }
1324
+ /**
1325
+ * What the sync target already holds, so a snapshot can ship deltas instead
1326
+ * of the whole world.
1327
+ *
1328
+ * @internal
1329
+ */
1330
+ interface YrsResidentWorkerSyncOptions {
1331
+ /** The worker replica's last reported yrs state vector. */
1332
+ knownStateVector?: Uint8Array | null;
1333
+ /** The `fontsRevision` the worker last applied. */
1334
+ knownFontsRevision?: number | null;
1335
+ }
1336
+ /** A range-aggregated toggle mark. @public */
1337
+ type YrsTriState = boolean | 'mixed';
1338
+ /**
1339
+ * Read-only toolbar/a11y state aggregated from yrs over one story range.
1340
+ * Toggle marks are tri-state; value marks are `null` when absent or mixed.
1341
+ *
1342
+ * @public
1343
+ */
1344
+ interface YrsSelectionContext {
1345
+ bold: YrsTriState;
1346
+ italic: YrsTriState;
1347
+ underline: YrsTriState;
1348
+ strike: YrsTriState;
1349
+ superscript: YrsTriState;
1350
+ subscript: YrsTriState;
1351
+ /** Uniform ASCII font family, or `null` when absent/mixed. */
1352
+ fontFamily: string | null;
1353
+ /** Uniform font size in half-points (the OOXML `w:sz` unit). */
1354
+ fontSize: number | null;
1355
+ /** Uniform RGB hex or theme-color name, or `null` when absent/mixed. */
1356
+ color: string | null;
1357
+ /** Uniform highlight name (`yellow`, …) or unmapped hex, or `null` when absent/mixed. */
1358
+ highlight: string | null;
1359
+ /** Paragraph containing the range start. */
1360
+ paraId: string;
1361
+ styleId: string | null;
1362
+ alignment: string | null;
1363
+ /**
1364
+ * Full authored pilcrow property bag. Known toolbar fields retain their
1365
+ * names (`indentLeft`, `spaceBefore`, `lineSpacing`, `numPr`, and so on);
1366
+ * paragraph style is stored as `pStyle`.
1367
+ */
1368
+ paragraphProperties: {
1369
+ [key: string]: unknown;
1370
+ pStyle?: string;
1371
+ alignment?: string;
1372
+ indentLeft?: number;
1373
+ indentRight?: number;
1374
+ indentFirstLine?: number;
1375
+ hangingIndent?: boolean;
1376
+ spaceBefore?: number;
1377
+ spaceAfter?: number;
1378
+ lineSpacing?: number;
1379
+ lineSpacingRule?: string;
1380
+ numPr?: {
1381
+ numId?: number;
1382
+ ilvl?: number;
1383
+ };
1384
+ };
1385
+ hasSelection: boolean;
1386
+ isMultiParagraph: boolean;
1387
+ /** The range belongs to a table-cell story. */
1388
+ inTable: boolean;
1389
+ /** The range covers exactly one non-pilcrow embed unit. */
1390
+ isSingleEmbed: boolean;
1391
+ /** Embed discriminator (`image`, `drawing`, …), else `null`. */
1392
+ embedKind: string | null;
1393
+ /** Convenience flag for a single `image` embed selection. */
1394
+ isImage: boolean;
1395
+ inInsertion: boolean;
1396
+ inDeletion: boolean;
1397
+ }
1398
+ /**
1399
+ * One tracked insertion, deletion, or paragraph-mark revision read from yrs.
1400
+ *
1401
+ * @public
1402
+ */
1403
+ interface YrsRevisionInfo {
1404
+ revisionId: string;
1405
+ author: string;
1406
+ date: string;
1407
+ kind: 'insertion' | 'deletion' | 'pPrIns' | 'pPrDel' | 'pPrChange' | 'trIns' | 'trDel' | 'tableIns' | 'tableDel';
1408
+ story: string;
1409
+ /** Raw affected text, capped at 80 Unicode code points. */
1410
+ preview: string;
1411
+ range: YrsStoryRange;
1412
+ }
1413
+ /**
1414
+ * Story-local locator for one native table embed.
1415
+ *
1416
+ * @public
1417
+ */
1418
+ interface YrsTableLoc {
1419
+ story: string;
1420
+ /** Zero-based table ordinal in the parent story. */
1421
+ tableIndex: number;
1422
+ }
1423
+ /**
1424
+ * One table cell addressed in the resolved rectangular grid.
1425
+ *
1426
+ * @public
1427
+ */
1428
+ interface YrsCellLoc extends YrsTableLoc {
1429
+ row: number;
1430
+ column: number;
1431
+ }
1432
+ /**
1433
+ * Anchor-cell to head-cell rectangular selection, addressed by grid
1434
+ * coordinates rather than document positions.
1435
+ *
1436
+ * @public
1437
+ */
1438
+ interface YrsTableRange {
1439
+ anchor: YrsCellLoc;
1440
+ head: YrsCellLoc;
1441
+ }
1442
+ /**
1443
+ * Receipt shared by native table-structure and cell-format operations.
1444
+ *
1445
+ * @public
1446
+ */
1447
+ interface YrsTableReceipt {
1448
+ table: YrsTableLoc;
1449
+ rows: number;
1450
+ columns: number;
1451
+ createdStoryIds: string[];
1452
+ deletedStoryIds: string[];
1453
+ /** Existing stories whose content changed: the table's story, plus a merge's surviving cell. */
1454
+ changedStoryIds: string[];
1455
+ newParaIds: string[];
1456
+ deletedTable: boolean;
1457
+ revisionIds: string[];
1458
+ }
1459
+ /**
1460
+ * OOXML-shaped cell border value passed through to `tcPr.borders`.
1461
+ *
1462
+ * @public
1463
+ */
1464
+ interface YrsCellBorder {
1465
+ style: string;
1466
+ size?: number;
1467
+ color?: {
1468
+ rgb: string;
1469
+ };
1470
+ }
1471
+ /**
1472
+ * Per-side border patch for {@link YrsSession.setCellBorders}. An omitted side
1473
+ * is left alone, `style: 'none'` authors an explicit no-border, and `null`
1474
+ * drops the authored side.
1475
+ *
1476
+ * @public
1477
+ */
1478
+ type YrsCellBorders = Partial<Record<'top' | 'bottom' | 'left' | 'right' | 'insideH' | 'insideV', YrsCellBorder | null>>;
1479
+ /** Undo grouping for tracked local transactions. */
1480
+ type YrsUndoCaptureMode = 'auto' | 'manual';
1481
+ /** Outcome of a target-resolving helper edit. @internal */
1482
+ type YrsTargetEditResult = {
1483
+ ok: true;
1484
+ version: string;
1485
+ } | DocxEditRefusal;
1486
+ /** Accepted-view texts around a selection; U+FFFC stands for each inline atom. @internal */
1487
+ interface YrsSelectionText {
1488
+ paraId: string;
1489
+ selectedText: string;
1490
+ paragraphText: string;
1491
+ before: string;
1492
+ after: string;
1493
+ }
1494
+ /**
1495
+ * One live replica of the yrs editing model. Thin typed wrapper over the
1496
+ * wasm `EditSession` — no editing logic on this side of the boundary.
1497
+ */
1498
+ /** An embedded image's bytes, as its `media:{n}` source displays them. */
1499
+ interface YrsMediaSource {
1500
+ bytes: Uint8Array;
1501
+ mimeType: string;
1502
+ }
1503
+ interface YrsSession extends CollaborationReplica {
1504
+ /** The yrs client id this replica writes with. */
1505
+ readonly clientId: number;
1506
+ /** Register raw sfnt bytes in the session's measurement/display font store. */
1507
+ registerFont(bytes: Uint8Array): number;
1508
+ /**
1509
+ * Register a measurement view of `base` carrying the vertical metrics Word
1510
+ * measures `family` with, for a face the host substituted; `base` when the
1511
+ * engine knows no metrics for the family.
1512
+ */
1513
+ registerSubstituteFont(base: number, family: string): number;
1514
+ /** Clear the session's registered measurement/display fonts. */
1515
+ clearFonts(): void;
1516
+ /** Measure one paragraph through the session's resident text engine. */
1517
+ measureParagraphJson(input: string): string;
1518
+ /** Paginate and retain the measured input and Layout in the session. */
1519
+ layoutDocumentJson(input: string): string;
1520
+ /** Return the compact font requirements for resident region layout. */
1521
+ layoutFontRequirementsJson(input: string): string;
1522
+ /** Paginate and compose section/page regions in the resident engine. */
1523
+ layoutDocumentWithRegionsJson(input: string): string;
1524
+ /** Same pass, but the reply omits the measured arena (fetch it on demand
1525
+ * through {@link YrsSession.retainedKernelInputsJson}). */
1526
+ layoutDocumentWithRegionsRetainedJson(input: string): string;
1527
+ /**
1528
+ * {@link YrsSession.layoutDocumentWithRegionsRetainedJson} a step at a time:
1529
+ * this lowers the body, and each {@link YrsSession.resumeRegionLayout}
1530
+ * measures up to `blocks` more body blocks. `layoutJson` arrives with the
1531
+ * step that completes the pass, equal to the one-call reply. A document
1532
+ * change, a font registration or another layout in between abandons the
1533
+ * pass, and resuming it then throws.
1534
+ */
1535
+ beginRegionLayout(input: string): YrsRegionLayoutProgress;
1536
+ resumeRegionLayout(blocks: number): YrsRegionLayoutProgress;
1537
+ /** Retained `{ measured, options }` for the main-thread display fallback. */
1538
+ retainedKernelInputsJson(expectedLayoutRevision: number): string;
1539
+ /**
1540
+ * Record region layout `input` as the resident layout without running it
1541
+ * here: a resident worker replica runs it, and snapshots carry it there.
1542
+ * Returns the new layout revision. @internal
1543
+ */
1544
+ adoptResidentWorkerLayout?(input: string): number;
1545
+ /** The current resident layout ran only in a worker replica. @internal */
1546
+ residentLayoutInWorker?(): boolean;
1547
+ /** Build display primitives against the session's resident font store. */
1548
+ buildDisplayListJson(input: string): string;
1549
+ /** Build a binary FrameDelta v1 against the last host-applied frame. */
1550
+ buildDisplayListFrame(input: string, expectedFrameEpoch: number): Uint8Array;
1551
+ /**
1552
+ * Limit full display builds to pages `start..end` plus the pages already
1553
+ * built; the rest stay unbuilt placeholders carrying their geometry. @internal
1554
+ */
1555
+ setDisplayWindow(start: number, end: number): void;
1556
+ /** Keep every previously built page while windowed builds are on. @internal */
1557
+ setDisplayRetainBuiltPages(retain: boolean): void;
1558
+ /** Build the listed unbuilt pages into a FrameDelta v1. @internal */
1559
+ buildDisplayPagesFrame(pages: readonly number[], expectedFrameEpoch: number): Uint8Array;
1560
+ /** Make the next frame a full one, for a host taking over from another engine; no-op once destroyed. */
1561
+ resetFrameBase(): void;
1562
+ /** Caret geometry from the current resident display frame. */
1563
+ residentCaretSnapshot(): YrsResidentCaretSnapshot;
1564
+ /** Apply a collapsed plain-text insertion and return its resident FrameDelta. */
1565
+ applyInput(text: string, expectedFrameEpoch: number): Uint8Array;
1566
+ /**
1567
+ * Apply up to `count` (default 1) collapsed character deletions/paragraph
1568
+ * merges, lay out once, and return the resident FrameDelta.
1569
+ */
1570
+ applyDelete(direction: 'backward' | 'forward', expectedFrameEpoch: number, count?: number): Uint8Array;
1571
+ /** Characters the last resident deletion removed; fewer than asked at a document boundary. */
1572
+ residentDeletedUnits(): number;
1573
+ /** Instrumented apply used only by opt-in browser performance traces. */
1574
+ applyInputProfiled(text: string, expectedFrameEpoch: number): {
1575
+ frame: Uint8Array;
1576
+ profile: YrsEngineApplyProfile;
1577
+ };
1578
+ /** Instrumented deletion used only by opt-in browser performance traces. */
1579
+ applyDeleteProfiled(direction: 'backward' | 'forward', expectedFrameEpoch: number, count?: number): {
1580
+ frame: Uint8Array;
1581
+ profile: YrsEngineApplyProfile;
1582
+ };
1583
+ /** Snapshot the inputs needed to move resident layout ownership to a worker. */
1584
+ residentWorkerSnapshot(options?: YrsResidentWorkerSyncOptions): YrsResidentWorkerSnapshot | null;
1585
+ /**
1586
+ * Cheap worker-sync probe: the resident layout revision when a worker
1587
+ * snapshot would be available, without encoding document state or copying
1588
+ * font bytes. Steady-state frame builds consult this instead of building a
1589
+ * full snapshot.
1590
+ */
1591
+ residentWorkerProbe(): {
1592
+ layoutRevision: number;
1593
+ } | null;
1594
+ /** Resident display-list hit/range queries; results are small JSON records. */
1595
+ displayHitTestRegionsJson(pageIndex: number, x: number, y: number): string;
1596
+ displayVerticalMoveJson(position: number, direction: 'up' | 'down', goalX: number): string;
1597
+ displayRangeRectsJson(from: number, to: number): string;
1598
+ displayRangeRectsRegionJson(region: 'body' | 'header' | 'footer', rId: string, from: number, to: number): string;
1599
+ /** Read a glyph outline from the session's resident font store. */
1600
+ outlineGlyphJson(fontId: number, glyphId: number): string;
1601
+ /** Hydrates from an encoded yrs v1 update (typically a peer's {@link encodeState} output). */
1602
+ loadState(update: Uint8Array): void;
1603
+ /** Parses a DOCX, seeds its stories, and returns thin host metadata; see {@link openDocx}. */
1604
+ seedFromDocx(bytes: Uint8Array, options?: YrsOpeningOptions): YrsDocxHost;
1605
+ /**
1606
+ * Parses a DOCX and optionally seeds its stories. Seeding starts a new
1607
+ * opening, so its session anchors never resolve in another opening, even
1608
+ * one seeded alike by the same client; see {@link beginOpening}.
1609
+ */
1610
+ openDocx(bytes: Uint8Array, seedStories: boolean, options?: YrsOpeningOptions): YrsDocxHost;
1611
+ /**
1612
+ * Opens a DOCX for display only, from the body's first `blocks` blocks:
1613
+ * enough to lay out its first pages with a prefix pass before the whole
1614
+ * document is opened. The session cannot save. `null`, opening nothing,
1615
+ * for a document with a float placed from outside the text or a section
1616
+ * with columns, which no cut of the body lays out like the whole: open it
1617
+ * with {@link openDocx}. @internal
1618
+ */
1619
+ openDocxPreview(bytes: Uint8Array, blocks: number): YrsDocxHost | null;
1620
+ /** Opened by {@link openDocxPreview}: its document refuses every change. @internal */
1621
+ isDisplayOnly(): boolean;
1622
+ /**
1623
+ * Marks whether the document is a preview's, as a replica of one is: its
1624
+ * layouts render NUMPAGES empty. @internal
1625
+ */
1626
+ setPartialDocument(partial: boolean): void;
1627
+ /**
1628
+ * The region layout of only as much of the body as fills `pages` pages;
1629
+ * a reply marked `provisional` covers a prefix. @internal
1630
+ */
1631
+ layoutDocumentWithRegionsPrefixRetainedJson(input: string, pages: number): string;
1632
+ /**
1633
+ * Starts a new opening of the document: its generation, replicated to
1634
+ * every replica, becomes part of every session anchor. Every seeding entry
1635
+ * point calls it; call it after building a document another way.
1636
+ */
1637
+ beginOpening(generation?: string): void;
1638
+ /** Unions seeded opaque sequence names into document state. @internal */
1639
+ seedOpaqueSequences(names: readonly string[]): void;
1640
+ /** Materializes the retained canonical package for compatibility APIs. */
1641
+ materializeDocx(): Document | null;
1642
+ /**
1643
+ * The displayed bytes and media type of the package part a `media:{n}`
1644
+ * image source names, or `null` for any other source or a destroyed session.
1645
+ */
1646
+ mediaSource(token: string): YrsMediaSource | null;
1647
+ /** Changes on package opening and session destruction. */
1648
+ mediaScope(): number;
1649
+ /** The `data:` URL a token stands for, or `null` when unavailable or destroyed. */
1650
+ mediaDataUrl(token: string): string | null;
1651
+ /**
1652
+ * Lays this replica's `data:` image sources out as the `media:{n}` tokens a
1653
+ * snapshot's `mediaSources` names. @internal
1654
+ */
1655
+ loadMediaSources(json: string): void;
1656
+ /**
1657
+ * Seeds stories and returns paragraph IDs in document order. Seeding a
1658
+ * document that has no opening yet starts one; see {@link beginOpening}.
1659
+ */
1660
+ loadStories(stories: readonly YrsStorySeed[]): Record<string, string[]>;
1661
+ /** Full document state as one yrs v1 update (Yjs wire format). */
1662
+ encodeState(): Uint8Array;
1663
+ /** Current Yrs state vector in the Yjs v1 wire format. */
1664
+ encodeStateVector(): Uint8Array;
1665
+ /** Full state, or only the state missing from a peer vector. */
1666
+ encodeStateAsUpdate(remoteStateVector?: Uint8Array): Uint8Array;
1667
+ /** Applies a remote/incremental yrs v1 update. */
1668
+ applyUpdate(update: Uint8Array): CollaborationTextInsertion | null;
1669
+ /** Apply a same-user worker update under the local undo origin. @internal */
1670
+ applyLocalUpdate(update: Uint8Array): void;
1671
+ /**
1672
+ * Subscribes to every committed transaction's v1 update (local AND
1673
+ * applied-remote). Returns an unsubscribe function.
1674
+ */
1675
+ onUpdate(listener: (update: Uint8Array, origin: CollaborationUpdateOrigin) => void): () => void;
1676
+ /** Encode one location as a binary Yrs sticky position. */
1677
+ encodeStickyPosition(loc: YrsLoc): YrsStickyPosition;
1678
+ /** Resolve a binary Yrs sticky position against this replica. */
1679
+ resolveStickyPosition(position: YrsStickyPosition): YrsLoc | null;
1680
+ /** Store this peer's awareness selection as sticky positions. */
1681
+ setSelection(anchor: YrsLoc, head?: YrsLoc): void;
1682
+ /** Resolve this peer's current sticky selection, or null before initialization. */
1683
+ selection(): YrsSelection | null;
1684
+ /** Encode the current selection as binary Yrs sticky indices. */
1685
+ encodeSelection(): CollaborationCursor | null;
1686
+ /** Resolve a peer's binary Yrs sticky indices against this replica. */
1687
+ resolveSelection(cursor: CollaborationCursor): YrsSelection | null;
1688
+ /** Store this peer's rectangular table selection outside the document. */
1689
+ setCellSelection(range: YrsTableRange): void;
1690
+ /** Resolve the current sticky cell selection, or null before initialization. */
1691
+ cellSelection(): YrsTableRange | null;
1692
+ /** Begin local-origin undo capture once import/seeding has completed. */
1693
+ beginUndoCapture(): void;
1694
+ /** Separates subsequent local edits from the current undo step; safe before capture starts. */
1695
+ addUndoBoundary(): void;
1696
+ /** Changes grouping policy, closing the current group while retaining history. */
1697
+ setUndoCaptureMode(mode: YrsUndoCaptureMode): void;
1698
+ /** Current grouping policy; defaults to auto. */
1699
+ undoCaptureMode(): YrsUndoCaptureMode;
1700
+ /** Stories changed by the latest undo or redo, sorted. */
1701
+ historyStories(): string[];
1702
+ /** Undo/redo only local-origin direct operations (never remote/system transactions). */
1703
+ undo(): boolean;
1704
+ redo(): boolean;
1705
+ canUndo(): boolean;
1706
+ canRedo(): boolean;
1707
+ /** Adds a story with one paragraph; the receipt carries its paraId. */
1708
+ createStory(storyId: string, initialText: string, pStyle?: string, alignment?: string): YrsParagraphReceipt;
1709
+ /** Removes a complete story (including an unreachable table-cell story). */
1710
+ deleteStory(storyId: string): void;
1711
+ /** Inserts a row above or below the cell that `at` resolves into. */
1712
+ insertRow(at: YrsCellLoc, side: 'above' | 'below', suggesting?: YrsAuthor): YrsTableReceipt;
1713
+ /** Inserts a rectangular structural table at a paragraph-keyed location. */
1714
+ insertTable(at: YrsLoc, rows: number, columns: number, suggesting?: YrsAuthor): YrsTableReceipt;
1715
+ /** Inserts a column left or right of the cell that `at` resolves into. */
1716
+ insertColumn(at: YrsCellLoc, side: 'left' | 'right'): YrsTableReceipt;
1717
+ /** Deletes every row covered by an explicit rectangular cell range. */
1718
+ deleteRow(range: YrsTableRange, suggesting?: YrsAuthor): YrsTableReceipt;
1719
+ /** Deletes every column covered by an explicit rectangular cell range. */
1720
+ deleteColumn(range: YrsTableRange): YrsTableReceipt;
1721
+ /** Removes a complete table plus its reachable cell stories. */
1722
+ deleteTable(table: YrsTableLoc): YrsTableReceipt;
1723
+ /** Merges a rectangular range into its top-left cell. */
1724
+ mergeCells(range: YrsTableRange): YrsTableReceipt;
1725
+ /** Splits the merged cell covering `at` into one cell per grid slot. */
1726
+ splitCell(at: YrsCellLoc, rows?: number, columns?: number): YrsTableReceipt;
1727
+ /** Sets or clears the selected cells' background color. */
1728
+ setCellShading(range: YrsTableRange, color: string | null): YrsTableReceipt;
1729
+ /**
1730
+ * Merges an OOXML-shaped patch into selected cells' `tcPr`. JSON `null`
1731
+ * clears a property; merge/split-owned span keys are rejected.
1732
+ */
1733
+ setCellTextFormat(range: YrsTableRange, patch: Readonly<Record<string, unknown>>): YrsTableReceipt;
1734
+ /**
1735
+ * Merges border sides into the selected cells. `insideH`/`insideV` resolve
1736
+ * per cell to the physical edges interior to the selection.
1737
+ */
1738
+ setCellBorders(range: YrsTableRange, borders: YrsCellBorders): YrsTableReceipt;
1739
+ /** Sets one authored grid-column width in twips. */
1740
+ setColumnWidth(at: YrsCellLoc, widthTwips: number): YrsTableReceipt;
1741
+ /** Sets the table-wide preferred width in twips. */
1742
+ setTableWidth(table: YrsTableLoc, widthTwips: number): YrsTableReceipt;
1743
+ /** Inserts paragraph-break-free text. Suggesting mode mints a revision. */
1744
+ insertText(at: YrsLoc, text: string, suggesting?: YrsAuthor): YrsRevisionReceipt;
1745
+ /**
1746
+ * Deletes a range (plain) or marks it as a suggested deletion (suggesting).
1747
+ * A range spanning paragraphs also merges them (pilcrow-as-character).
1748
+ */
1749
+ deleteRange(range: YrsStoryRange, suggesting?: YrsAuthor): YrsRevisionReceipt;
1750
+ /** Replaces a range with text in one transaction (one shared revision when suggesting). */
1751
+ replaceRange(range: YrsStoryRange, text: string, suggesting?: YrsAuthor): YrsReplaceReceipt;
1752
+ /**
1753
+ * Splits a paragraph by inserting one pilcrow. The FIRST half keeps the
1754
+ * original paraId; the SECOND half is re-minted (`secondParaId`).
1755
+ */
1756
+ splitParagraph(at: YrsLoc, suggesting?: YrsAuthor): YrsSplitReceipt;
1757
+ /** Merges `paraId` with the FOLLOWING paragraph. Errors on the final paragraph. */
1758
+ mergeParagraphs(story: string, paraId: string, suggesting?: YrsAuthor): YrsRevisionReceipt;
1759
+ /**
1760
+ * Toggles one run mark across a range: removes it when every unit already
1761
+ * carries it, otherwise adds it. Adding superscript clears subscript and
1762
+ * vice versa.
1763
+ */
1764
+ toggleMark(range: YrsStoryRange, mark: YrsRunMark): void;
1765
+ /** Applies set-valued direct formatting; omitted fields are kept and `null` fields clear. */
1766
+ formatRange(range: YrsStoryRange, delta: YrsInlineFormatDelta): void;
1767
+ /** Sets or clears the protected hyperlink attribute over a non-empty range. */
1768
+ setHyperlink(range: YrsStoryRange, hyperlink: YrsHyperlinkAttrs | null): void;
1769
+ /** Clears direct formatting while retaining hyperlinks and tracked-change stamps. */
1770
+ clearFormatting(range: YrsStoryRange): void;
1771
+ /** Applies a paragraph style id to every paragraph intersecting the range. */
1772
+ applyParagraphStyle(range: YrsStoryRange, styleId: string, suggesting?: YrsAuthor): void;
1773
+ /** Applies tri-state paragraph properties to every paragraph intersecting the range. */
1774
+ setParagraphAttrs(range: YrsStoryRange, attrs: YrsParagraphAttrs, suggesting?: YrsAuthor): void;
1775
+ /** Inserts one inline image embed, optionally as a tracked insertion. */
1776
+ insertImage(at: YrsLoc, image: Readonly<Record<string, unknown>>, suggesting?: YrsAuthor): YrsRevisionReceipt;
1777
+ /**
1778
+ * Sets the value of a content-control embed addressed by stable payload id. A string fills a
1779
+ * text control's content as one version-checked step and throws when the fill is refused.
1780
+ */
1781
+ setContentControlValue(embedId: string, value: YrsContentControlValue): void;
1782
+ /** {@link setContentControlValue} for the embed at a paragraph-keyed position. */
1783
+ setContentControlValueAt(at: YrsLoc, value: YrsContentControlValue): void;
1784
+ /**
1785
+ * Removes an authored value from a content-control embed. It never erases a text control's
1786
+ * text: fill it with `''` for that.
1787
+ */
1788
+ clearContentControlValue(embedId: string): void;
1789
+ /** Commits image size/wrapping/position fields in one transaction. */
1790
+ setImageGeometry(embedId: string, geometry: YrsImageGeometry): void;
1791
+ /** Commits image geometry at a paragraph-keyed position; reaches images that share an id. */
1792
+ setImageGeometryAt(at: YrsLoc, geometry: YrsImageGeometry): void;
1793
+ /** Inserts a native page-break embed at a paragraph-keyed location. */
1794
+ insertPageBreak(at: YrsLoc): void;
1795
+ /** Inserts a native section-break embed at a paragraph-keyed location. */
1796
+ insertSectionBreak(at: YrsLoc, type: 'nextPage' | 'continuous' | 'oddPage' | 'evenPage'): void;
1797
+ /** Inserts a typed watermark embed at a paragraph-keyed location. */
1798
+ insertWatermark(at: YrsLoc, watermark: YrsWatermark): void;
1799
+ /**
1800
+ * Applies raw story operations in one transaction, then repairs any
1801
+ * paragraph identity a pilcrow they insert or re-key duplicates and
1802
+ * promotes an editor-only paragraph they author into.
1803
+ */
1804
+ applyRawOps(story: string, ops: readonly YrsRawOp[]): void;
1805
+ /** Applies seed raw operations with deterministic item ordering. */
1806
+ applySeedRawOps(story: string, ops: readonly YrsRawOp[]): void;
1807
+ /** Sets one paragraph property (any JSON value). `paraId` is reserved. */
1808
+ setParagraphAttr(paraId: string, key: string, value: unknown): void;
1809
+ /** Adds a sticky-anchored comment over one or more ranges. */
1810
+ addComment(ranges: readonly YrsStoryRange[], author: string, date: string, body: unknown): YrsCommentReceipt;
1811
+ /** Reanchors an existing comment with non-empty ranges; preserves metadata and joins local undo capture. */
1812
+ setCommentRanges(commentId: string, ranges: readonly YrsStoryRange[]): void;
1813
+ /**
1814
+ * Accepts tracked changes: pending insertions become plain content,
1815
+ * pending deletions are carried out; a `pPrIns` paragraph mark clears (the
1816
+ * split stays), a `pPrDel` mark joins with the following paragraph (whose
1817
+ * pPr survives — Word's surviving-`w:p` rule). Resolving never stamps a new
1818
+ * revision. Throws on an unknown revision id.
1819
+ */
1820
+ acceptChange(target: YrsChangeTarget): YrsResolveReceipt;
1821
+ /**
1822
+ * Rejects tracked changes — the inverse of {@link acceptChange}: pending
1823
+ * insertions roll back, pending deletions restore their text; a `pPrIns`
1824
+ * mark joins back with the following paragraph, a `pPrDel` mark clears.
1825
+ */
1826
+ rejectChange(target: YrsChangeTarget): YrsResolveReceipt;
1827
+ /** Aggregate toolbar/a11y state from yrs over one paragraph-addressed range. */
1828
+ selectionContext(range: YrsStoryRange): YrsSelectionContext;
1829
+ /** Enumerate tracked changes across every story in deterministic order. */
1830
+ listRevisions(): YrsRevisionInfo[];
1831
+ /** Current offsets of a comment's sticky anchors. Throws when an anchor no longer resolves. */
1832
+ resolveComment(commentId: string): YrsResolvedCommentAnchor[];
1833
+ /** Every comment the session holds, sorted by id. @internal */
1834
+ listComments(): YrsCommentInfo[];
1835
+ /** Story ids in the document, sorted. */
1836
+ storyIds(): string[];
1837
+ /** Whether the document has a story with this id, without listing them all. */
1838
+ hasStory(story: string): boolean;
1839
+ /** Story length in UTF-16 units (every embed, pilcrows included, counts 1). */
1840
+ storyLength(story: string): number;
1841
+ /** Returns the story's canonical-stream checksum. */
1842
+ storyChecksum(story: string): bigint;
1843
+ /** Lowers a story to layout blocks and rejects unsupported embeds. */
1844
+ yrsBlocksForStory(story: string, env?: YrsRenderEnv): unknown[];
1845
+ /** Paragraph snapshots in document order. */
1846
+ paragraphs(story: string): YrsParagraph[];
1847
+ /** Literal search in document order. */
1848
+ searchText(query: string, options?: YrsTextSearchOptions): YrsTextMatch[];
1849
+ /** Paragraph ids and inline-unit lengths, resolved in one Rust story traversal. */
1850
+ paragraphSpans(story: string): YrsParagraphLength[];
1851
+ /** The raw formatted-segment view (the render bridge's input). */
1852
+ storySegments(story: string): YrsStorySegment[];
1853
+ /**
1854
+ * The current story revision and the sorted ids of the stories created,
1855
+ * edited, or deleted after revision `since` (0 lists every story).
1856
+ */
1857
+ storiesChangedSince(since: number): {
1858
+ revision: number;
1859
+ stories: string[];
1860
+ };
1861
+ /**
1862
+ * One digest per unit of {@link YrsSession.storySegments}, split after each
1863
+ * pilcrow. Equal digests mean equal segments.
1864
+ */
1865
+ storySegmentUnitDigests(story: string): string[];
1866
+ /** The segments of the listed units, each as {@link YrsSession.storySegments} gives them. */
1867
+ storySegmentUnits(story: string, units: readonly number[]): YrsStorySegment[][];
1868
+ /**
1869
+ * The payload of the story's `tableIndex`-th table embed, as
1870
+ * {@link YrsSession.storySegments} gives it, or null when there is no such
1871
+ * table. Reads the one table rather than the whole story.
1872
+ */
1873
+ tablePayload(story: string, tableIndex: number): Record<string, unknown> | null;
1874
+ /** A paragraph's story span (start unit, pilcrow index). */
1875
+ locateParagraph(story: string, paraId: string): YrsParagraphSpan;
1876
+ /**
1877
+ * Session, persisted and source anchors of every paragraph, including the
1878
+ * source package's paragraphs outside the stories, and the Word paragraph ID
1879
+ * each saves with. Reads only.
1880
+ */
1881
+ paragraphIdentities(): DocxParagraphIdentitySnapshot;
1882
+ /**
1883
+ * Gives every paragraph that saves without a Word paragraph ID a fresh one,
1884
+ * editor-only paragraphs excepted, and repairs duplicates, so persisted
1885
+ * anchors survive save and reopen. Source IDs and saved claims keep their
1886
+ * IDs over unsaved claims and copies. A replicated change outside undo
1887
+ * history that later saves keep; a refusal changes nothing.
1888
+ */
1889
+ persistParagraphIds(): DocxParagraphIdentityReceipt;
1890
+ /** Resolves an anchor to the paragraph that currently holds it. Reads only. */
1891
+ resolveParagraphAnchor(anchor: DocxParagraphAnchor): DocxParagraphAnchorResult;
1892
+ /** The Word paragraph ID each paragraph of a story saves with, in pilcrow order. @internal */
1893
+ storyParagraphIds(story: string): Array<string | null>;
1894
+ /** The paragraph IDs a save of the session applies. @internal */
1895
+ paragraphSavePlan(): DocxParagraphSavePlan;
1896
+ /**
1897
+ * Publishes the `[owner, paraId]` pairs a save captured and returns those
1898
+ * whose binding changed since. @internal
1899
+ */
1900
+ recordSavedParagraphIds(saved: ReadonlyArray<readonly [string, string]>): Array<[string, string]>;
1901
+ /**
1902
+ * The Word paragraph IDs a DOCX package holds, by part URI, in document
1903
+ * order and upper case. Reads only. @internal
1904
+ */
1905
+ writtenParagraphIds(bytes: Uint8Array): Record<string, string[]>;
1906
+ /**
1907
+ * The session-scoped version token. It changes on every committed change, local or remote,
1908
+ * and when the document is replaced; compare tokens only within this session.
1909
+ */
1910
+ version(): string;
1911
+ /** Paragraph texts in one view, with the version they were read at. */
1912
+ readParagraphs(request: DocxReadParagraphsRequest): DocxReadParagraphsResult;
1913
+ /** Exact, case-sensitive, paragraph-local search; overlapping matches count separately. */
1914
+ findText(request: DocxFindTextRequest): DocxFindTextResult;
1915
+ /** Resolves and checks an edit batch without changing anything or reserving ids. */
1916
+ validateEdits(request: DocxEditRequest): DocxValidationResult;
1917
+ /**
1918
+ * Applies every step or none, resolving all targets against `expectVersion`. Policy
1919
+ * failures are returned; malformed requests throw.
1920
+ */
1921
+ applyEdits(request: DocxEditRequest): DocxEditResult;
1922
+ /** Resolves a text target and formats it in one call. @internal */
1923
+ formatTextTarget(target: DocxTextTarget, delta: YrsInlineFormatDelta): YrsTargetEditResult;
1924
+ /** Resolves a text target and anchors side-map comment `id` over it in one call. @internal */
1925
+ commentTextTarget(target: DocxTextTarget, comment: {
1926
+ id: string;
1927
+ author: string;
1928
+ date: string;
1929
+ body: unknown;
1930
+ }): YrsTargetEditResult;
1931
+ /** Accepted-view texts around a paragraph-keyed selection. @internal */
1932
+ selectionText(range: YrsStoryRange): YrsSelectionText;
1933
+ /**
1934
+ * Proposes a round of tracked changes: every new proposal resolves against `expectVersion` and
1935
+ * the round applies as one batch outside undo history, or nothing changes. A retried id with
1936
+ * the same edit is a no-op; the same id with another edit refuses. Opening another document
1937
+ * forgets every proposal.
1938
+ */
1939
+ proposeChanges(request: DocxProposalRequest): DocxProposalResult;
1940
+ /**
1941
+ * Sets how proposals render. Decisions change neither the document, its version nor undo
1942
+ * history; each call that changes one increments `previewVersion`.
1943
+ */
1944
+ setProposalStates(request: DocxProposalStateRequest): DocxProposalResult;
1945
+ /**
1946
+ * Withdraws proposals, settling each as its decision previews it: accepted ones apply for good,
1947
+ * rejected and undecided ones are removed. The settlement is one change against `expectVersion`
1948
+ * outside undo history, so a later round resolves against the text the preview showed.
1949
+ */
1950
+ withdrawProposals(request: DocxProposalWithdrawRequest): DocxProposalResult;
1951
+ /** The proposals in the order they were made. */
1952
+ getProposals(): DocxProposalSnapshot;
1953
+ /** Listens for new proposals, decisions and a forgotten registry. Returns the unsubscribe. */
1954
+ onProposalChange(listener: (snapshot: DocxProposalSnapshot) => void): () => void;
1955
+ /**
1956
+ * Exports the committed document as read-only structured content with the version it was read
1957
+ * at; anchors resolve against that version. Nothing is committed, flushed or published.
1958
+ * Unusable options are refused; malformed ones throw.
1959
+ */
1960
+ exportStructured(options: DocxExportOptions): DocxExportResult<DocxStructuredContent>;
1961
+ /** {@link exportStructured} rendered as Markdown from the same read. */
1962
+ exportMarkdown(options: DocxExportOptions): DocxExportResult<DocxMarkdownContent>;
1963
+ /**
1964
+ * {@link exportStructured} with the page map of the region layout this session retains. The
1965
+ * layout must have lowered the current version from this session's stories with section,
1966
+ * settings and note metadata that describe it, and measured every font the document uses
1967
+ * with the fonts registered now; this call lays nothing out, flushes nothing and loads no
1968
+ * font, and refuses a stale or incomplete layout.
1969
+ */
1970
+ exportStructuredWithPages(options: DocxPageExportOptions): DocxExportResult<DocxPagedStructuredContent<DocxLayoutMap>>;
1971
+ /**
1972
+ * {@link exportStructuredWithPages} for an editor: `currentRequest` is the region layout
1973
+ * request it would lay the document out with now, and the retained layout must have used the
1974
+ * same fonts, measurement defaults, render environment and pagination options. @internal
1975
+ */
1976
+ exportStructuredWithPagesFor(options: DocxPageExportOptions, currentRequest: string): DocxExportResult<DocxPagedStructuredContent<DocxLayoutMap>>;
1977
+ /**
1978
+ * Lays this private session out with `fonts` alone, in a measurement font store of its own,
1979
+ * and exports it with snapshot anchors and a snapshot map. `fonts` holds the font files back
1980
+ * to back and `fontLengths` their lengths; `request`'s font chains name them by index. Throws
1981
+ * for a font the engine rejects. @internal
1982
+ */
1983
+ exportSnapshotWithPrivateFonts(fonts: Uint8Array, fontLengths: Uint32Array, request: string, options: DocxPageExportOptions): {
1984
+ ok: true;
1985
+ content: DocxPagedStructuredContent<DocxSnapshotLayoutMap>;
1986
+ } | {
1987
+ ok: false;
1988
+ failure: DocxExportFailure;
1989
+ };
1990
+ /**
1991
+ * The heading paragraphs of `story` in document order, classified as the structured export
1992
+ * classifies them. Throws for an unknown story.
1993
+ */
1994
+ headings(story: string): DocxParagraphHeading[];
1995
+ /**
1996
+ * The content controls of the committed document with the version they were read at; control
1997
+ * ids and anchors resolve against that version. Nothing is committed, flushed or published.
1998
+ * Unusable options are refused; malformed ones throw.
1999
+ */
2000
+ listContentControls(options?: DocxContentControlsOptions): DocxContentControlsResult;
2001
+ /** The controls {@link listContentControls} lists that match `query` exactly; none or several. */
2002
+ findContentControls(query: DocxContentControlQuery, options?: DocxContentControlsOptions): DocxContentControlsResult;
2003
+ /** Drops the observer and frees the wasm-side replica. Idempotent. */
2004
+ destroy(): void;
2005
+ }
2006
+ /** Options for {@link createYrsSession}. */
2007
+ interface CreateYrsSessionOptions {
2008
+ /**
2009
+ * The yrs client id (non-negative safe integer). Omit to allocate a random
2010
+ * 32-bit id, yjs-style.
2011
+ */
2012
+ clientId?: number;
2013
+ }
2014
+ /**
2015
+ * Decodes the host metadata a resident worker's `open` replied with, for the
2016
+ * package `source` it opened. @internal
2017
+ */
2018
+ declare function decodeDocxHostJson(json: string, source: Uint8Array): YrsDocxHost;
2019
+ /**
2020
+ * Creates a yrs editing replica. The first call dynamically imports and
2021
+ * initializes the embedded docx-edit wasm (~440KB base64) — callers must
2022
+ * load it lazily so non-editor consumers avoid the wasm startup cost.
2023
+ */
2024
+ declare function createYrsSession(options?: CreateYrsSessionOptions): Promise<YrsSession>;
2025
+
2026
+ export { type DocxSourceStory as $, type DocxParagraphIdDiagnostic as A, type DocxParagraphIdOrigin as B, type CollaborationReplica as C, type DocxOccurrence as D, type DocxParagraphIdRefusal as E, type DocxParagraphIdentity as F, type DocxParagraphIdentityReceipt as G, type DocxParagraphIdentitySnapshot as H, type DocxParagraphOrigin as I, type DocxParagraphRef as J, type DocxParagraphSavePlan as K, type DocxPersistedParagraphAnchor as L, type DocxProposalFailure as M, type DocxProposalInput as N, type DocxProposalRecord as O, type DocxProposalRequest as P, type DocxProposalResult as Q, type DocxProposalSnapshot as R, type DocxProposalState as S, type DocxProposalStateRequest as T, type DocxProposalWithdrawRequest as U, type DocxSavedDocument as V, type DocxSavedParagraph as W, type DocxSessionParagraphAnchor as X, type YrsSession as Y, type DocxSessionSave as Z, type DocxSourceParagraphAnchor as _, type YrsRenderEnv as a, type YrsWatermark as a$, type ResidentCaretPaintStyle as a0, type ResidentEngineOffscreenPage as a1, type ResidentEngineWorkerApplyResult as a2, ResidentEngineWorkerClient as a3, type ResidentEngineWorkerFrame as a4, type ResidentEngineWorkerOpened as a5, ResidentWorkerFailureError as a6, ResidentWorkerOutOfMemoryError as a7, type YrsAuthor as a8, type YrsCellBorder as a9, type YrsRegionLayoutProgress as aA, type YrsReplaceReceipt as aB, type YrsResidentCaretRect as aC, type YrsResidentCaretSnapshot as aD, type YrsResidentFontRegistration as aE, type YrsResidentWorkerSnapshot as aF, type YrsResidentWorkerSyncOptions as aG, type YrsResolveReceipt as aH, type YrsResolvedCommentAnchor as aI, type YrsRevisionReceipt as aJ, type YrsRunMark as aK, type YrsSelectionContext as aL, type YrsSelectionText as aM, type YrsSplitReceipt as aN, type YrsStickyPosition as aO, type YrsStoryRange as aP, type YrsStorySeed as aQ, type YrsStorySegment as aR, type YrsTableLoc as aS, type YrsTableRange as aT, type YrsTableReceipt as aU, type YrsTargetEditResult as aV, type YrsTextColor as aW, type YrsTextMatch as aX, type YrsTextSearchOptions as aY, type YrsTriState as aZ, type YrsUndoCaptureMode as a_, type YrsCellBorders as aa, type YrsCellLoc as ab, type YrsChangeTarget as ac, type YrsCommentInfo as ad, type YrsCommentReceipt as ae, type YrsContentControlValue as af, type YrsDocxHost as ag, type YrsEngineApplyProfile as ah, type YrsHyperlinkAttrs as ai, type YrsImageGeometry as aj, type YrsInlineFormatDelta as ak, type YrsInputParagraphSeed as al, type YrsInputParagraphSpan as am, type YrsInputPositionMap as an, type YrsMediaSource as ao, type YrsNumberingProperties as ap, type YrsOpeningOptions as aq, type YrsParaOffset as ar, type YrsParagraph as as, type YrsParagraphAttrs as at, type YrsParagraphLength as au, type YrsParagraphReceipt as av, type YrsParagraphSeed as aw, type YrsParagraphSpan as ax, type YrsParagraphTabStop as ay, type YrsRawOp as az, type CollaborationTransport as b, canUseResidentEngineWorker as b0, captureSessionSave as b1, compareYrsLocs as b2, createYrsInputPositionMap as b3, createYrsSession as b4, decodeDocxHostJson as b5, displayPositionToYrsLoc as b6, documentToYrs as b7, preloadDocxEngine as b8, preloadResidentEngineWorker as b9, prepareDocxBytes as ba, preparedDocxDigest as bb, proposalRevisionPreview as bc, residentCaretDeviceRect as bd, residentCaretSnapshotForFrame as be, retainPreloadedResidentEngineWorker as bf, sameYrsSelection as bg, saveYrsDocx as bh, takePreloadedResidentEngineWorker as bi, writeSessionSave as bj, yrsLocToDisplayPosition as bk, yrsToDocument as bl, type CollaborationProviderOptions as c, type CollaborationStatus as d, type CollaborationPeer as e, type CollaborationCursor as f, type CollaborationPeerListener as g, type CollaborationStatusListener as h, type CollaborationErrorListener as i, type YrsSelection as j, type CollaborationAwarenessState as k, CollaborationError as l, type CollaborationErrorCode as m, type CollaborationPresence as n, type CollaborationResolvedUser as o, type CollaborationStatusChange as p, type CollaborationTextInsertion as q, type CollaborationTransportEvent as r, type CollaborationUpdateOrigin as s, type CollaborationUser as t, type YrsLoc as u, type YrsRevisionInfo as v, type CreateYrsSessionOptions as w, type DocxParagraphAnchor as x, type DocxParagraphAnchorResult as y, type DocxParagraphIdAssignment as z };