@beyondwork/docx-react-component 1.0.19 → 1.0.20

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 (70) hide show
  1. package/package.json +1 -1
  2. package/src/api/public-types.ts +336 -0
  3. package/src/api/session-state.ts +2 -0
  4. package/src/core/commands/formatting-commands.ts +1 -1
  5. package/src/core/commands/index.ts +14 -2
  6. package/src/core/search/search-text.ts +28 -0
  7. package/src/core/state/editor-state.ts +3 -0
  8. package/src/index.ts +21 -0
  9. package/src/io/docx-session.ts +363 -17
  10. package/src/io/export/serialize-comments.ts +104 -34
  11. package/src/io/export/serialize-footnotes.ts +198 -1
  12. package/src/io/export/serialize-headers-footers.ts +203 -10
  13. package/src/io/export/serialize-main-document.ts +83 -3
  14. package/src/io/export/split-review-boundaries.ts +181 -19
  15. package/src/io/normalize/normalize-text.ts +82 -8
  16. package/src/io/ooxml/highlight-colors.ts +39 -0
  17. package/src/io/ooxml/parse-comments.ts +85 -19
  18. package/src/io/ooxml/parse-fields.ts +396 -0
  19. package/src/io/ooxml/parse-footnotes.ts +240 -2
  20. package/src/io/ooxml/parse-headers-footers.ts +431 -7
  21. package/src/io/ooxml/parse-inline-media.ts +15 -1
  22. package/src/io/ooxml/parse-main-document.ts +396 -14
  23. package/src/io/ooxml/parse-revisions.ts +317 -38
  24. package/src/legal/bookmarks.ts +44 -0
  25. package/src/legal/cross-references.ts +59 -1
  26. package/src/model/canonical-document.ts +117 -1
  27. package/src/model/snapshot.ts +85 -1
  28. package/src/review/store/revision-store.ts +6 -0
  29. package/src/review/store/revision-types.ts +1 -0
  30. package/src/runtime/document-navigation.ts +52 -13
  31. package/src/runtime/document-runtime.ts +1521 -75
  32. package/src/runtime/read-only-diagnostics-runtime.ts +8 -0
  33. package/src/runtime/session-capabilities.ts +33 -3
  34. package/src/runtime/surface-projection.ts +86 -25
  35. package/src/runtime/table-schema.ts +2 -2
  36. package/src/runtime/view-state.ts +24 -6
  37. package/src/runtime/workflow-markup.ts +349 -0
  38. package/src/ui/WordReviewEditor.tsx +850 -1315
  39. package/src/ui/editor-command-bag.ts +120 -0
  40. package/src/ui/editor-runtime-boundary.ts +1422 -0
  41. package/src/ui/editor-shell-view.tsx +134 -0
  42. package/src/ui/editor-surface-controller.tsx +51 -0
  43. package/src/ui/headless/revision-decoration-model.ts +4 -4
  44. package/src/ui/runtime-snapshot-selectors.ts +197 -0
  45. package/src/ui-tailwind/chrome/tw-alert-banner.tsx +18 -2
  46. package/src/ui-tailwind/chrome/tw-image-context-toolbar.tsx +129 -0
  47. package/src/ui-tailwind/chrome/tw-layout-panel.tsx +114 -0
  48. package/src/ui-tailwind/chrome/tw-object-context-toolbar.tsx +34 -0
  49. package/src/ui-tailwind/chrome/tw-selection-toolbar.tsx +27 -2
  50. package/src/ui-tailwind/chrome/tw-table-context-toolbar.tsx +128 -0
  51. package/src/ui-tailwind/editor-surface/perf-probe.ts +86 -14
  52. package/src/ui-tailwind/editor-surface/pm-command-bridge.ts +2 -2
  53. package/src/ui-tailwind/editor-surface/pm-decorations.ts +35 -0
  54. package/src/ui-tailwind/editor-surface/pm-position-map.ts +1 -1
  55. package/src/ui-tailwind/editor-surface/pm-schema.ts +139 -8
  56. package/src/ui-tailwind/editor-surface/pm-state-from-snapshot.ts +98 -48
  57. package/src/ui-tailwind/editor-surface/surface-build-keys.ts +51 -0
  58. package/src/ui-tailwind/editor-surface/tw-opaque-block.tsx +7 -1
  59. package/src/ui-tailwind/editor-surface/tw-prosemirror-surface.tsx +174 -48
  60. package/src/ui-tailwind/page-chrome-model.ts +27 -0
  61. package/src/ui-tailwind/review/tw-comment-sidebar.tsx +7 -7
  62. package/src/ui-tailwind/review/tw-health-panel.tsx +31 -2
  63. package/src/ui-tailwind/review/tw-review-rail.tsx +3 -3
  64. package/src/ui-tailwind/review/tw-revision-sidebar.tsx +15 -15
  65. package/src/ui-tailwind/theme/editor-theme.css +4 -0
  66. package/src/ui-tailwind/toolbar/tw-toolbar.tsx +543 -5
  67. package/src/ui-tailwind/tw-review-workspace.tsx +316 -19
  68. package/src/validation/compatibility-engine.ts +27 -4
  69. package/src/validation/compatibility-report.ts +1 -0
  70. package/src/validation/docx-comment-proof.ts +220 -0
@@ -0,0 +1,1422 @@
1
+ import React, { useEffect, useMemo, useRef, useState } from "react";
2
+
3
+ import type {
4
+ AutosaveState,
5
+ CompatibilityReport,
6
+ DocumentNavigationSnapshot,
7
+ EditorDatastoreAdapter,
8
+ EditorError,
9
+ EditorHostAdapter,
10
+ EditorSessionState,
11
+ EditorViewStateSnapshot,
12
+ EditorWarning,
13
+ ExportDocxOptions,
14
+ ExportResult,
15
+ FieldSnapshot,
16
+ PersistedEditorSnapshot,
17
+ RuntimeRenderSnapshot,
18
+ TocRefreshResult,
19
+ UpdateFieldsResult,
20
+ ViewMode as EditorViewMode,
21
+ WordReviewEditorEvent,
22
+ WordReviewEditorProps,
23
+ WorkspaceMode,
24
+ ZoomLevel,
25
+ } from "../api/public-types";
26
+ import {
27
+ editorSessionStateFromPersistedSnapshot,
28
+ persistedSnapshotFromEditorSessionState,
29
+ } from "../api/session-state.ts";
30
+ import { createCanonicalDocumentId } from "../core/state/editor-state.ts";
31
+ import {
32
+ createDocumentRuntime,
33
+ type DocumentRuntime,
34
+ } from "../runtime/document-runtime.ts";
35
+ import { loadDocxEditorSession } from "../io/docx-session.ts";
36
+ import {
37
+ decodePersistedSourcePackageBytes,
38
+ hasValidPersistedSourcePackageDigest,
39
+ } from "../io/source-package-provenance.ts";
40
+ import {
41
+ createEditorViewStateSnapshot,
42
+ createViewState,
43
+ } from "../runtime/view-state.ts";
44
+ import {
45
+ recordPerfSample,
46
+ } from "../ui-tailwind/editor-surface/perf-probe.ts";
47
+ import {
48
+ downloadExportResult,
49
+ withExportDelivery,
50
+ } from "./browser-export";
51
+
52
+ export interface ResolvedSource {
53
+ source: "docx" | "session" | "snapshot";
54
+ sourceLabel?: string;
55
+ initialDocx?: Uint8Array | ArrayBuffer;
56
+ initialSessionState?: EditorSessionState;
57
+ initialSnapshot?: PersistedEditorSnapshot;
58
+ }
59
+
60
+ export interface CreateRuntimeArgs {
61
+ documentId: string;
62
+ readOnly: boolean;
63
+ source: ResolvedSource;
64
+ initialViewState?: {
65
+ workspaceMode?: WorkspaceMode;
66
+ zoomLevel?: ZoomLevel;
67
+ };
68
+ hostAdapter?: EditorHostAdapter;
69
+ datastore?: EditorDatastoreAdapter;
70
+ currentUserId?: string;
71
+ }
72
+
73
+ interface RuntimeLifecycleHandlers {
74
+ onWarning?: (warning: EditorWarning) => void;
75
+ onError?: (error: EditorError) => void;
76
+ }
77
+
78
+ export interface WordReviewEditorRuntime extends DocumentRuntime {
79
+ getFatalError?(): EditorError | undefined;
80
+ dispose?(): void;
81
+ setDefaultAuthorId?(authorId?: string): void;
82
+ }
83
+
84
+ type PackageBackedDocxSession = ReturnType<typeof loadDocxEditorSession>;
85
+
86
+ interface SnapshotExportBarrier {
87
+ reason:
88
+ | "missing_source_package_provenance"
89
+ | "invalid_source_package_provenance";
90
+ message: string;
91
+ }
92
+
93
+ export interface EditorRuntimeBoundaryState {
94
+ runtime: WordReviewEditorRuntime | null;
95
+ loadError: EditorError | null;
96
+ activeRuntime: WordReviewEditorRuntime;
97
+ fallbackSnapshot: RuntimeRenderSnapshot;
98
+ loadingSessionState: EditorSessionState;
99
+ loadingViewState: EditorViewStateSnapshot;
100
+ loadingNavigation: DocumentNavigationSnapshot;
101
+ hostAdapterRef: React.MutableRefObject<EditorHostAdapter | undefined>;
102
+ datastoreRef: React.MutableRefObject<EditorDatastoreAdapter | undefined>;
103
+ onEventRef: React.MutableRefObject<((event: WordReviewEditorEvent) => void) | undefined>;
104
+ onWarningRef: React.MutableRefObject<((warning: EditorWarning) => void) | undefined>;
105
+ onErrorRef: React.MutableRefObject<((error: EditorError) => void) | undefined>;
106
+ autosaveTimerRef: React.MutableRefObject<ReturnType<typeof setTimeout> | null>;
107
+ lastSavedRevisionTokenRef: React.MutableRefObject<string | null>;
108
+ runtimeViewStateSeedRef: React.MutableRefObject<{
109
+ workspaceMode: WorkspaceMode;
110
+ zoomLevel: ZoomLevel;
111
+ }>;
112
+ }
113
+
114
+ export async function __resolveWordReviewEditorSource(
115
+ props: Pick<
116
+ WordReviewEditorProps,
117
+ | "documentId"
118
+ | "hostAdapter"
119
+ | "datastore"
120
+ | "externalDocSource"
121
+ | "initialDocx"
122
+ | "initialSessionState"
123
+ | "initialSnapshot"
124
+ | "initialSourceLabel"
125
+ | "loadRevision"
126
+ | "loadSourcePolicy"
127
+ >,
128
+ ): Promise<ResolvedSource> {
129
+ const explicitInitialCount =
130
+ Number(Boolean(props.initialDocx)) +
131
+ Number(Boolean(props.initialSessionState)) +
132
+ Number(Boolean(props.initialSnapshot));
133
+ if (explicitInitialCount > 1) {
134
+ throw new Error(
135
+ "Provide exactly one of initialDocx, initialSessionState, or initialSnapshot.",
136
+ );
137
+ }
138
+
139
+ if (props.externalDocSource) {
140
+ if (props.externalDocSource.kind === "docx") {
141
+ return {
142
+ source: "docx",
143
+ initialDocx: props.externalDocSource.bytes,
144
+ sourceLabel: props.externalDocSource.sourceLabel,
145
+ };
146
+ }
147
+
148
+ if (props.externalDocSource.kind === "session") {
149
+ return {
150
+ source: "session",
151
+ initialSessionState: props.externalDocSource.sessionState,
152
+ sourceLabel:
153
+ props.externalDocSource.sourceLabel ??
154
+ props.externalDocSource.sessionState.sourcePackage?.sourceLabel,
155
+ };
156
+ }
157
+
158
+ return {
159
+ source: "snapshot",
160
+ initialSnapshot: props.externalDocSource.snapshot,
161
+ sourceLabel: props.externalDocSource.sourceLabel,
162
+ };
163
+ }
164
+
165
+ if (props.initialSessionState) {
166
+ return {
167
+ source: "session",
168
+ initialSessionState: props.initialSessionState,
169
+ sourceLabel:
170
+ props.initialSourceLabel ??
171
+ props.initialSessionState.sourcePackage?.sourceLabel,
172
+ };
173
+ }
174
+
175
+ if (props.initialSnapshot) {
176
+ return {
177
+ source: "snapshot",
178
+ initialSnapshot: props.initialSnapshot,
179
+ sourceLabel: props.initialSourceLabel,
180
+ };
181
+ }
182
+
183
+ if (props.initialDocx) {
184
+ return {
185
+ source: "docx",
186
+ initialDocx: props.initialDocx,
187
+ sourceLabel: props.initialSourceLabel,
188
+ };
189
+ }
190
+
191
+ const loader = props.hostAdapter?.load ?? props.datastore?.load;
192
+ if (!loader) {
193
+ throw new Error(
194
+ `WordReviewEditor ${props.documentId} needs initialDocx, initialSessionState, initialSnapshot, or a host/datastore load source.`,
195
+ );
196
+ }
197
+
198
+ const loadResult = await loader({
199
+ documentId: props.documentId,
200
+ loadRevision: props.loadRevision,
201
+ loadSourcePolicy: props.loadSourcePolicy,
202
+ });
203
+
204
+ if (!loadResult.source) {
205
+ throw new Error(
206
+ `Host or datastore loader did not return a loadable source for ${props.documentId}.`,
207
+ );
208
+ }
209
+
210
+ if (loadResult.source.kind === "docx") {
211
+ return {
212
+ source: "docx",
213
+ initialDocx: loadResult.source.bytes,
214
+ sourceLabel: loadResult.source.sourceLabel,
215
+ };
216
+ }
217
+
218
+ if (loadResult.source.kind === "session") {
219
+ return {
220
+ source: "session",
221
+ initialSessionState: loadResult.source.sessionState,
222
+ sourceLabel:
223
+ loadResult.source.sourceLabel ??
224
+ loadResult.source.sessionState.sourcePackage?.sourceLabel,
225
+ };
226
+ }
227
+
228
+ return {
229
+ source: "snapshot",
230
+ initialSnapshot: loadResult.source.snapshot,
231
+ sourceLabel: loadResult.source.sourceLabel,
232
+ };
233
+ }
234
+
235
+ export function __createFallbackRuntime(args: CreateRuntimeArgs): WordReviewEditorRuntime {
236
+ return createRuntime(args);
237
+ }
238
+
239
+ export function useEditorRuntimeBoundary(
240
+ props: WordReviewEditorProps,
241
+ ): EditorRuntimeBoundaryState {
242
+ const {
243
+ currentUser,
244
+ datastore,
245
+ documentId,
246
+ externalDocSource,
247
+ externalDocumentRevision,
248
+ hostAdapter,
249
+ initialDocx,
250
+ initialSessionState,
251
+ initialSnapshot,
252
+ initialSourceLabel,
253
+ loadRevision,
254
+ loadSourcePolicy = "prefer-saved-state",
255
+ onError,
256
+ onEvent,
257
+ onWarning,
258
+ readOnly = false,
259
+ reviewMode = "review",
260
+ } = props;
261
+
262
+ const [runtime, setRuntime] = useState<WordReviewEditorRuntime | null>(null);
263
+ const [loadError, setLoadError] = useState<EditorError | null>(null);
264
+ const runtimeRef = useRef<WordReviewEditorRuntime | null>(null);
265
+ const autosaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
266
+ const lastSavedRevisionTokenRef = useRef<string | null>(null);
267
+ const hostAdapterRef = useRef(hostAdapter);
268
+ const datastoreRef = useRef(datastore);
269
+ const onEventRef = useRef(onEvent);
270
+ const onWarningRef = useRef(onWarning);
271
+ const onErrorRef = useRef(onError);
272
+ const runtimeViewStateSeedRef = useRef<{
273
+ workspaceMode: WorkspaceMode;
274
+ zoomLevel: ZoomLevel;
275
+ }>({
276
+ workspaceMode: "canvas",
277
+ zoomLevel: 100,
278
+ });
279
+ const initialSourceRef = useRef<{
280
+ documentId: string;
281
+ initialDocx?: Uint8Array | ArrayBuffer;
282
+ initialSessionState?: EditorSessionState;
283
+ initialSnapshot?: PersistedEditorSnapshot;
284
+ initialSourceLabel?: string;
285
+ } | null>(null);
286
+
287
+ if (!initialSourceRef.current || initialSourceRef.current.documentId !== documentId) {
288
+ initialSourceRef.current = {
289
+ documentId,
290
+ initialDocx,
291
+ initialSessionState,
292
+ initialSnapshot,
293
+ initialSourceLabel,
294
+ };
295
+ }
296
+
297
+ const stableInitialSource = initialSourceRef.current;
298
+ const sourceReloadKey = externalDocSource
299
+ ? `external:${externalDocSource.kind}:${externalDocumentRevision ?? "static"}`
300
+ : stableInitialSource?.initialSessionState
301
+ ? "initial-session"
302
+ : stableInitialSource?.initialSnapshot
303
+ ? "initial-snapshot"
304
+ : stableInitialSource?.initialDocx
305
+ ? "initial-docx"
306
+ : hostAdapter
307
+ ? `host-adapter:${loadRevision ?? "static"}`
308
+ : `datastore:${loadRevision ?? "static"}`;
309
+
310
+ useEffect(() => {
311
+ hostAdapterRef.current = hostAdapter;
312
+ datastoreRef.current = datastore;
313
+ onEventRef.current = onEvent;
314
+ onWarningRef.current = onWarning;
315
+ onErrorRef.current = onError;
316
+ }, [datastore, hostAdapter, onError, onEvent, onWarning]);
317
+
318
+ useEffect(() => {
319
+ runtimeRef.current?.setDefaultAuthorId?.(currentUser.userId);
320
+ }, [currentUser.userId]);
321
+
322
+ useEffect(() => {
323
+ let cancelled = false;
324
+
325
+ async function loadRuntime(): Promise<void> {
326
+ setLoadError(null);
327
+
328
+ try {
329
+ const source = await __resolveWordReviewEditorSource({
330
+ documentId,
331
+ hostAdapter: hostAdapterRef.current,
332
+ datastore: datastoreRef.current,
333
+ externalDocSource,
334
+ initialDocx: stableInitialSource?.initialDocx,
335
+ initialSessionState: stableInitialSource?.initialSessionState,
336
+ initialSnapshot: stableInitialSource?.initialSnapshot,
337
+ initialSourceLabel: stableInitialSource?.initialSourceLabel,
338
+ loadRevision,
339
+ loadSourcePolicy,
340
+ });
341
+
342
+ if (cancelled) {
343
+ return;
344
+ }
345
+
346
+ runtimeRef.current?.dispose?.();
347
+ const nextRuntime = createRuntime(
348
+ {
349
+ documentId,
350
+ readOnly,
351
+ source,
352
+ initialViewState: runtimeViewStateSeedRef.current,
353
+ hostAdapter: hostAdapterRef.current,
354
+ datastore: datastoreRef.current,
355
+ currentUserId: currentUser.userId,
356
+ },
357
+ {
358
+ onWarning: onWarningRef.current,
359
+ onError: onErrorRef.current,
360
+ },
361
+ );
362
+ recordPerfSample("runtime.create");
363
+ emitEditorEvent({
364
+ hostAdapter: hostAdapterRef.current,
365
+ datastore: datastoreRef.current,
366
+ onEvent: onEventRef.current,
367
+ event: createReadyEvent(nextRuntime, source.source),
368
+ });
369
+ runtimeRef.current = nextRuntime;
370
+ setRuntime(nextRuntime);
371
+ } catch (error) {
372
+ if (cancelled) {
373
+ return;
374
+ }
375
+
376
+ const normalized = normalizeEditorError(error);
377
+ setLoadError(normalized);
378
+ onErrorRef.current?.(normalized);
379
+ emitEditorEvent({
380
+ hostAdapter: hostAdapterRef.current,
381
+ datastore: datastoreRef.current,
382
+ onEvent: onEventRef.current,
383
+ event: {
384
+ type: "error",
385
+ documentId,
386
+ error: normalized,
387
+ },
388
+ });
389
+ }
390
+ }
391
+
392
+ void loadRuntime();
393
+
394
+ return () => {
395
+ cancelled = true;
396
+ };
397
+ }, [
398
+ documentId,
399
+ readOnly,
400
+ sourceReloadKey,
401
+ ]);
402
+
403
+ useEffect(() => {
404
+ if (!runtime?.subscribeToEvents) {
405
+ return;
406
+ }
407
+
408
+ return runtime.subscribeToEvents((event) => {
409
+ if (event.type === "export_completed" || event.type === "ready") {
410
+ return;
411
+ }
412
+ emitEditorEvent({
413
+ hostAdapter: hostAdapterRef.current,
414
+ datastore: datastoreRef.current,
415
+ onEvent: onEventRef.current,
416
+ event,
417
+ });
418
+ });
419
+ }, [runtime]);
420
+
421
+ useEffect(() => {
422
+ return () => {
423
+ if (autosaveTimerRef.current) {
424
+ clearTimeout(autosaveTimerRef.current);
425
+ autosaveTimerRef.current = null;
426
+ }
427
+ runtimeRef.current?.dispose?.();
428
+ runtimeRef.current = null;
429
+ };
430
+ }, []);
431
+
432
+ const fallbackSnapshot = useMemo(
433
+ () =>
434
+ loadError
435
+ ? createErrorSnapshot(documentId, loadError)
436
+ : createLoadingSnapshot(
437
+ documentId,
438
+ readOnly,
439
+ guessSourceLabel(
440
+ initialSourceLabel,
441
+ initialSessionState,
442
+ initialSnapshot,
443
+ externalDocSource,
444
+ ),
445
+ ),
446
+ [
447
+ documentId,
448
+ externalDocSource,
449
+ initialSessionState,
450
+ initialSnapshot,
451
+ initialSourceLabel,
452
+ loadError,
453
+ readOnly,
454
+ ],
455
+ );
456
+ const loadingPersistedSnapshot = useMemo(
457
+ () => createFallbackPersistedSnapshot(documentId, initialSourceLabel),
458
+ [documentId, initialSourceLabel],
459
+ );
460
+ const loadingSessionState = useMemo(
461
+ () =>
462
+ initialSessionState ??
463
+ (initialSnapshot
464
+ ? editorSessionStateFromPersistedSnapshot(initialSnapshot)
465
+ : editorSessionStateFromPersistedSnapshot(loadingPersistedSnapshot)),
466
+ [initialSessionState, initialSnapshot, loadingPersistedSnapshot],
467
+ );
468
+ const loadingViewState = useMemo(
469
+ () =>
470
+ createLoadingViewStateSnapshot(
471
+ fallbackSnapshot,
472
+ runtimeViewStateSeedRef.current,
473
+ deriveEditorViewMode(fallbackSnapshot.readOnly, reviewMode),
474
+ ),
475
+ [fallbackSnapshot, reviewMode],
476
+ );
477
+ const loadingNavigation = useMemo(
478
+ () => createLoadingNavigationSnapshot(),
479
+ [],
480
+ );
481
+ const loadingRuntimeBridge = useMemo(
482
+ () =>
483
+ createLoadingRuntimeBridge({
484
+ snapshot: fallbackSnapshot,
485
+ sessionState: loadingSessionState,
486
+ viewState: loadingViewState,
487
+ navigation: loadingNavigation,
488
+ }),
489
+ [fallbackSnapshot, loadingNavigation, loadingSessionState, loadingViewState],
490
+ );
491
+
492
+ return {
493
+ runtime,
494
+ loadError,
495
+ activeRuntime: runtime ?? loadingRuntimeBridge,
496
+ fallbackSnapshot,
497
+ loadingSessionState,
498
+ loadingViewState,
499
+ loadingNavigation,
500
+ hostAdapterRef,
501
+ datastoreRef,
502
+ onEventRef,
503
+ onWarningRef,
504
+ onErrorRef,
505
+ autosaveTimerRef,
506
+ lastSavedRevisionTokenRef,
507
+ runtimeViewStateSeedRef,
508
+ };
509
+ }
510
+
511
+ function createRuntime(
512
+ args: CreateRuntimeArgs,
513
+ handlers: RuntimeLifecycleHandlers = {},
514
+ ): WordReviewEditorRuntime {
515
+ const docxSession = args.source.initialDocx
516
+ ? loadDocxEditorSession({
517
+ documentId: args.documentId,
518
+ sourceLabel: args.source.sourceLabel,
519
+ bytes: args.source.initialDocx,
520
+ editorBuild: "dev",
521
+ })
522
+ : undefined;
523
+ const snapshotExportResolution = !args.source.initialDocx
524
+ ? resolvePackageBackedExportSession(args)
525
+ : undefined;
526
+ const initialSessionState =
527
+ args.source.initialSessionState ??
528
+ docxSession?.initialSessionState ??
529
+ (args.source.initialSnapshot
530
+ ? editorSessionStateFromPersistedSnapshot(args.source.initialSnapshot)
531
+ : editorSessionStateFromPersistedSnapshot(
532
+ createFallbackPersistedSnapshot(
533
+ args.documentId,
534
+ args.source.sourceLabel ?? "Generated shell snapshot",
535
+ ),
536
+ ));
537
+ const runtimeSessionState = snapshotExportResolution?.barrier
538
+ ? applySessionExportBarrier(initialSessionState, snapshotExportResolution.barrier)
539
+ : initialSessionState;
540
+
541
+ return createDocumentRuntime({
542
+ documentId: args.documentId,
543
+ initialSessionState: runtimeSessionState,
544
+ sourceKind: args.source.source,
545
+ sourceLabel: args.source.sourceLabel,
546
+ initialViewState: args.initialViewState,
547
+ readOnly: args.readOnly || docxSession?.readOnly,
548
+ editorBuild: runtimeSessionState.editorBuild,
549
+ fatalError: docxSession?.fatalError,
550
+ protectionSnapshot: docxSession?.protectionSnapshot,
551
+ exportDocx: async (sessionState, options) => {
552
+ if (docxSession) {
553
+ return docxSession.exportDocx(sessionState, options);
554
+ }
555
+
556
+ if (snapshotExportResolution?.session) {
557
+ return snapshotExportResolution.session.exportDocx(sessionState, options);
558
+ }
559
+
560
+ throw createSnapshotExportBlockedError(
561
+ args.documentId,
562
+ snapshotExportResolution?.barrier ?? {
563
+ reason: "missing_source_package_provenance",
564
+ message:
565
+ "DOCX export is blocked because this session does not carry embedded source package provenance.",
566
+ },
567
+ );
568
+ },
569
+ onWarning: handlers.onWarning,
570
+ onError: handlers.onError,
571
+ defaultAuthorId: args.currentUserId,
572
+ });
573
+ }
574
+
575
+ function createLoadingSnapshot(
576
+ documentId: string,
577
+ readOnly: boolean,
578
+ sourceLabel?: string,
579
+ ): RuntimeRenderSnapshot {
580
+ return {
581
+ documentId,
582
+ sessionId: `${documentId}-loading`,
583
+ sourceLabel,
584
+ revisionToken: `${documentId}:loading`,
585
+ isReady: false,
586
+ isDirty: false,
587
+ readOnly,
588
+ documentMode: "editing",
589
+ selection: collapsedSelection(),
590
+ activeStory: { kind: "main" },
591
+ documentStats: {
592
+ storyLength: 0,
593
+ commentCount: 0,
594
+ revisionCount: 0,
595
+ opaqueFragmentCount: 0,
596
+ },
597
+ comments: {
598
+ openCommentIds: [],
599
+ resolvedCommentIds: [],
600
+ detachedCommentIds: [],
601
+ totalCount: 0,
602
+ threads: [],
603
+ },
604
+ trackedChanges: {
605
+ pendingChangeIds: [],
606
+ acceptedChangeIds: [],
607
+ rejectedChangeIds: [],
608
+ detachedChangeIds: [],
609
+ actionableChangeIds: [],
610
+ preserveOnlyChangeIds: [],
611
+ totalCount: 0,
612
+ revisions: [],
613
+ },
614
+ compatibility: {
615
+ blockExport: false,
616
+ blockExportReasons: [],
617
+ warningCount: 0,
618
+ errorCount: 0,
619
+ featureEntries: [],
620
+ },
621
+ warnings: [],
622
+ commandState: {
623
+ canUndo: false,
624
+ canRedo: false,
625
+ readOnly,
626
+ },
627
+ protectionSnapshot: {
628
+ hasDocumentProtection: false,
629
+ enforcementActive: false,
630
+ ranges: [],
631
+ enforcedRangeCount: 0,
632
+ preservedRangeCount: 0,
633
+ },
634
+ };
635
+ }
636
+
637
+ function createLoadingNavigationSnapshot(): DocumentNavigationSnapshot {
638
+ return {
639
+ pageCount: 0,
640
+ pages: [],
641
+ headings: [],
642
+ activePageIndex: 0,
643
+ activeSectionIndex: 0,
644
+ };
645
+ }
646
+
647
+ function createLoadingViewStateSnapshot(
648
+ snapshot: RuntimeRenderSnapshot,
649
+ seed: {
650
+ workspaceMode?: WorkspaceMode;
651
+ zoomLevel?: ZoomLevel;
652
+ },
653
+ viewMode: EditorViewMode,
654
+ ): EditorViewStateSnapshot {
655
+ return createEditorViewStateSnapshot(
656
+ createViewState({
657
+ viewMode,
658
+ workspaceMode: seed.workspaceMode,
659
+ zoomLevel: seed.zoomLevel,
660
+ }),
661
+ snapshot.activeStory,
662
+ snapshot.selection,
663
+ snapshot.surface,
664
+ snapshot.surface,
665
+ snapshot.pageLayout,
666
+ );
667
+ }
668
+
669
+ function createLoadingRuntimeBridge(input: {
670
+ snapshot: RuntimeRenderSnapshot;
671
+ sessionState: EditorSessionState;
672
+ viewState: EditorViewStateSnapshot;
673
+ navigation: DocumentNavigationSnapshot;
674
+ }): WordReviewEditorRuntime {
675
+ const emptyFieldSnapshot: FieldSnapshot = {
676
+ totalCount: 0,
677
+ supportedCount: 0,
678
+ preserveOnlyCount: 0,
679
+ fields: [],
680
+ };
681
+ const emptyFieldResult: UpdateFieldsResult = {
682
+ totalCount: 0,
683
+ updatedCount: 0,
684
+ preserveOnlyCount: 0,
685
+ };
686
+ const emptyTocResult: TocRefreshResult = {
687
+ entryCount: 0,
688
+ entries: [],
689
+ };
690
+
691
+ return {
692
+ subscribe: () => () => undefined,
693
+ subscribeToEvents: () => () => undefined,
694
+ getRenderSnapshot: () => input.snapshot,
695
+ replaceText: () => undefined,
696
+ dispatch: () => undefined,
697
+ undo: () => undefined,
698
+ redo: () => undefined,
699
+ focus: () => undefined,
700
+ blur: () => undefined,
701
+ addComment: () => {
702
+ throw createLoadingBoundaryError(input.snapshot.documentId, "comment");
703
+ },
704
+ openComment: () => undefined,
705
+ resolveComment: () => undefined,
706
+ reopenComment: () => undefined,
707
+ addCommentReply: () => undefined,
708
+ editCommentBody: () => undefined,
709
+ acceptChange: () => undefined,
710
+ rejectChange: () => undefined,
711
+ acceptAllChanges: () => undefined,
712
+ rejectAllChanges: () => undefined,
713
+ openStory: () => false,
714
+ closeStory: () => undefined,
715
+ getActiveStory: () => input.snapshot.activeStory,
716
+ getViewState: () => input.viewState,
717
+ setViewMode: () => undefined,
718
+ setDocumentMode: () => undefined,
719
+ getProtectionSnapshot: () => input.snapshot.protectionSnapshot,
720
+ setWorkspaceMode: () => undefined,
721
+ setZoom: () => undefined,
722
+ getPageLayoutSnapshot: () => null,
723
+ getDocumentNavigationSnapshot: () => input.navigation,
724
+ getFieldSnapshot: () => emptyFieldSnapshot,
725
+ updateFields: () => emptyFieldResult,
726
+ updateTableOfContents: () => emptyTocResult,
727
+ getSessionState: () => {
728
+ throw createLoadingBoundaryError(input.snapshot.documentId, "session");
729
+ },
730
+ getPersistedSnapshot: () => {
731
+ throw createLoadingBoundaryError(input.snapshot.documentId, "snapshot");
732
+ },
733
+ getCompatibilityReport: () => ({
734
+ reportVersion: "compatibility-report/1",
735
+ generatedAt: input.sessionState.updatedAt,
736
+ blockExport: input.snapshot.compatibility.blockExport,
737
+ featureEntries: input.snapshot.compatibility.featureEntries,
738
+ warnings: input.snapshot.warnings,
739
+ errors: input.snapshot.fatalError ? [input.snapshot.fatalError] : [],
740
+ }),
741
+ getWarnings: () => input.snapshot.warnings,
742
+ exportDocx: () =>
743
+ Promise.reject(createLoadingBoundaryError(input.snapshot.documentId, "export")),
744
+ setWorkflowOverlay: () => undefined,
745
+ clearWorkflowOverlay: () => undefined,
746
+ getWorkflowScopeSnapshot: () => null,
747
+ getInteractionGuardSnapshot: () => ({ blockedReasons: [] }),
748
+ getWorkflowMarkupSnapshot: () => ({
749
+ totalCount: 0,
750
+ items: [],
751
+ highlights: [],
752
+ comments: [],
753
+ revisions: [],
754
+ fields: [],
755
+ protectedRanges: [],
756
+ opaqueFragments: [],
757
+ }),
758
+ getWorkflowCandidateRanges: () => [],
759
+ replaceWorkflowMarkupText: () => undefined,
760
+ };
761
+ }
762
+
763
+ function createLoadingBoundaryError(
764
+ documentId: string,
765
+ target: "comment" | "session" | "snapshot" | "export",
766
+ ): EditorError {
767
+ return {
768
+ errorId: `${documentId}-loading-${target}`,
769
+ code: "internal_invariant",
770
+ message: "Editor is still loading.",
771
+ isFatal: false,
772
+ source: "runtime",
773
+ };
774
+ }
775
+
776
+ function deriveEditorViewMode(
777
+ readOnly: boolean,
778
+ reviewMode: WordReviewEditorProps["reviewMode"] = "review",
779
+ ): EditorViewMode {
780
+ if (readOnly) {
781
+ return "view";
782
+ }
783
+ return reviewMode === "editing" ? "editing" : "review";
784
+ }
785
+
786
+ function createErrorSnapshot(documentId: string, error: EditorError): RuntimeRenderSnapshot {
787
+ return {
788
+ ...createLoadingSnapshot(documentId, true),
789
+ isReady: true,
790
+ sessionId: `${documentId}-error`,
791
+ revisionToken: `${documentId}:error`,
792
+ compatibility: {
793
+ blockExport: true,
794
+ blockExportReasons: [error.message],
795
+ warningCount: 0,
796
+ errorCount: 1,
797
+ featureEntries: [],
798
+ },
799
+ fatalError: error,
800
+ };
801
+ }
802
+
803
+ export async function persistAndExport(input: {
804
+ hostAdapter?: EditorHostAdapter;
805
+ datastore?: EditorDatastoreAdapter;
806
+ documentId: string;
807
+ runtime: WordReviewEditorRuntime;
808
+ onError?: (error: EditorError) => void;
809
+ onEvent?: (event: WordReviewEditorEvent) => void;
810
+ options?: ExportDocxOptions;
811
+ lastSavedRevisionTokenRef: React.MutableRefObject<string | null>;
812
+ autosaveTimerRef: React.MutableRefObject<ReturnType<typeof setTimeout> | null>;
813
+ }): Promise<ExportResult> {
814
+ if (input.autosaveTimerRef.current) {
815
+ clearTimeout(input.autosaveTimerRef.current);
816
+ input.autosaveTimerRef.current = null;
817
+ }
818
+
819
+ await persistSession({
820
+ hostAdapter: input.hostAdapter,
821
+ datastore: input.datastore,
822
+ documentId: input.documentId,
823
+ runtime: input.runtime,
824
+ isAutosave: false,
825
+ onError: input.onError,
826
+ onEvent: input.onEvent,
827
+ lastSavedRevisionTokenRef: input.lastSavedRevisionTokenRef,
828
+ });
829
+
830
+ let result: ExportResult;
831
+ try {
832
+ result = await input.runtime.exportDocx(input.options);
833
+ } catch (error) {
834
+ const normalized = normalizeExportError(error, input.documentId, input.options);
835
+ input.onError?.(normalized);
836
+ emitEditorEvent({
837
+ hostAdapter: input.hostAdapter,
838
+ datastore: input.datastore,
839
+ onEvent: input.onEvent,
840
+ event: {
841
+ type: "error",
842
+ documentId: input.documentId,
843
+ error: normalized,
844
+ },
845
+ });
846
+ throw normalized;
847
+ }
848
+
849
+ const saveExport = input.hostAdapter?.saveExport ?? input.datastore?.saveExport;
850
+ const saveExportSource = input.hostAdapter?.saveExport ? "host" : "datastore";
851
+ if (!saveExport) {
852
+ result = downloadExportResult(result);
853
+ emitEditorEvent({
854
+ hostAdapter: input.hostAdapter,
855
+ datastore: input.datastore,
856
+ onEvent: input.onEvent,
857
+ event: {
858
+ type: "export_completed",
859
+ documentId: input.documentId,
860
+ result,
861
+ },
862
+ });
863
+ return result;
864
+ }
865
+
866
+ try {
867
+ const saveResult = await saveExport({
868
+ documentId: input.documentId,
869
+ result,
870
+ });
871
+ result = withExportDelivery(result, {
872
+ mode: "persisted-by-host",
873
+ savedAt: saveResult.savedAt,
874
+ });
875
+ } catch (error) {
876
+ const normalized = normalizeStorageError(error, {
877
+ message: "Export persisted bytes could not be stored.",
878
+ source: saveExportSource,
879
+ details: {
880
+ operation: "saveExport",
881
+ },
882
+ });
883
+ input.onError?.(normalized);
884
+ emitEditorEvent({
885
+ hostAdapter: input.hostAdapter,
886
+ datastore: input.datastore,
887
+ onEvent: input.onEvent,
888
+ event: {
889
+ type: "error",
890
+ documentId: input.documentId,
891
+ error: normalized,
892
+ },
893
+ });
894
+ result = withExportDelivery(result, {
895
+ mode: "exported-bytes-only",
896
+ });
897
+ }
898
+
899
+ emitEditorEvent({
900
+ hostAdapter: input.hostAdapter,
901
+ datastore: input.datastore,
902
+ onEvent: input.onEvent,
903
+ event: {
904
+ type: "export_completed",
905
+ documentId: input.documentId,
906
+ result,
907
+ },
908
+ });
909
+
910
+ return result;
911
+ }
912
+
913
+ export function rejectExportWhileLoading(input: {
914
+ documentId: string;
915
+ hostAdapter?: EditorHostAdapter;
916
+ datastore?: EditorDatastoreAdapter;
917
+ onError?: (error: EditorError) => void;
918
+ onEvent?: (event: WordReviewEditorEvent) => void;
919
+ }): Promise<never> {
920
+ const error: EditorError = {
921
+ errorId: "word-review-editor-loading-export",
922
+ code: "internal_invariant",
923
+ message: "WordReviewEditor is still loading and cannot export yet.",
924
+ isFatal: false,
925
+ source: "runtime",
926
+ };
927
+ input.onError?.(error);
928
+ emitEditorEvent({
929
+ hostAdapter: input.hostAdapter,
930
+ datastore: input.datastore,
931
+ onEvent: input.onEvent,
932
+ event: {
933
+ type: "error",
934
+ documentId: input.documentId,
935
+ error,
936
+ },
937
+ });
938
+ return Promise.reject(error);
939
+ }
940
+
941
+ export async function persistSession(input: {
942
+ hostAdapter?: EditorHostAdapter;
943
+ datastore?: EditorDatastoreAdapter;
944
+ documentId: string;
945
+ runtime: WordReviewEditorRuntime;
946
+ isAutosave: boolean;
947
+ onError?: (error: EditorError) => void;
948
+ onEvent?: (event: WordReviewEditorEvent) => void;
949
+ lastSavedRevisionTokenRef: React.MutableRefObject<string | null>;
950
+ }): Promise<void> {
951
+ const saveSession = input.hostAdapter?.saveSession;
952
+ const saveSnapshot = input.datastore?.saveSnapshot;
953
+ if (!saveSession && !saveSnapshot) {
954
+ return;
955
+ }
956
+
957
+ const sessionState = input.runtime.getSessionState();
958
+ const snapshot = input.runtime.getPersistedSnapshot();
959
+ const revisionToken = input.runtime.getRenderSnapshot().revisionToken;
960
+
961
+ if (input.isAutosave) {
962
+ emitEditorEvent({
963
+ hostAdapter: input.hostAdapter,
964
+ datastore: input.datastore,
965
+ onEvent: input.onEvent,
966
+ event: {
967
+ type: "autosave_state",
968
+ documentId: input.documentId,
969
+ state: {
970
+ status: "saving",
971
+ } satisfies AutosaveState,
972
+ },
973
+ });
974
+ }
975
+
976
+ try {
977
+ const result = saveSession
978
+ ? await saveSession({
979
+ documentId: input.documentId,
980
+ sessionState,
981
+ isAutosave: input.isAutosave,
982
+ })
983
+ : await saveSnapshot!({
984
+ documentId: input.documentId,
985
+ snapshot,
986
+ isAutosave: input.isAutosave,
987
+ });
988
+ input.lastSavedRevisionTokenRef.current = revisionToken;
989
+ emitEditorEvent({
990
+ hostAdapter: input.hostAdapter,
991
+ datastore: input.datastore,
992
+ onEvent: input.onEvent,
993
+ event: saveSession
994
+ ? {
995
+ type: "session_saved",
996
+ documentId: input.documentId,
997
+ sessionState: input.runtime.getSessionState(),
998
+ savedAt: result.savedAt,
999
+ isAutosave: input.isAutosave,
1000
+ }
1001
+ : {
1002
+ type: "snapshot_saved",
1003
+ documentId: input.documentId,
1004
+ snapshot: {
1005
+ ...snapshot,
1006
+ savedAt: result.savedAt,
1007
+ },
1008
+ isAutosave: input.isAutosave,
1009
+ },
1010
+ });
1011
+ if (input.isAutosave) {
1012
+ emitEditorEvent({
1013
+ hostAdapter: input.hostAdapter,
1014
+ datastore: input.datastore,
1015
+ onEvent: input.onEvent,
1016
+ event: {
1017
+ type: "autosave_state",
1018
+ documentId: input.documentId,
1019
+ state: {
1020
+ status: "saved",
1021
+ savedAt: result.savedAt,
1022
+ } satisfies AutosaveState,
1023
+ },
1024
+ });
1025
+ }
1026
+ } catch (error) {
1027
+ const normalized = normalizeStorageError(error, {
1028
+ message: input.isAutosave
1029
+ ? saveSession
1030
+ ? "Autosave failed while storing the editor session."
1031
+ : "Autosave failed while storing the editor snapshot."
1032
+ : saveSession
1033
+ ? "Session save failed while preparing the export checkpoint."
1034
+ : "Snapshot save failed while preparing the export checkpoint.",
1035
+ source: saveSession ? "host" : "datastore",
1036
+ details: {
1037
+ operation: saveSession ? "saveSession" : "saveSnapshot",
1038
+ isAutosave: input.isAutosave,
1039
+ },
1040
+ });
1041
+ input.onError?.(normalized);
1042
+ emitEditorEvent({
1043
+ hostAdapter: input.hostAdapter,
1044
+ datastore: input.datastore,
1045
+ onEvent: input.onEvent,
1046
+ event: {
1047
+ type: "error",
1048
+ documentId: input.documentId,
1049
+ error: normalized,
1050
+ },
1051
+ });
1052
+ if (input.isAutosave) {
1053
+ emitEditorEvent({
1054
+ hostAdapter: input.hostAdapter,
1055
+ datastore: input.datastore,
1056
+ onEvent: input.onEvent,
1057
+ event: {
1058
+ type: "autosave_state",
1059
+ documentId: input.documentId,
1060
+ state: {
1061
+ status: "error",
1062
+ error: normalized,
1063
+ } satisfies AutosaveState,
1064
+ },
1065
+ });
1066
+ }
1067
+ if (!input.isAutosave) {
1068
+ throw normalized;
1069
+ }
1070
+ }
1071
+ }
1072
+
1073
+ function emitEditorEvent(input: {
1074
+ hostAdapter?: EditorHostAdapter;
1075
+ datastore?: EditorDatastoreAdapter;
1076
+ onEvent?: (event: WordReviewEditorEvent) => void;
1077
+ event: WordReviewEditorEvent;
1078
+ }): void {
1079
+ input.onEvent?.(input.event);
1080
+ const logEvent = input.hostAdapter?.logEvent ?? input.datastore?.logEvent;
1081
+ logEvent?.({
1082
+ type: input.event.type,
1083
+ documentId: input.event.documentId,
1084
+ detail: summarizeEventDetail(input.event),
1085
+ });
1086
+ }
1087
+
1088
+ function summarizeEventDetail(
1089
+ event: WordReviewEditorEvent,
1090
+ ): Record<string, unknown> | undefined {
1091
+ switch (event.type) {
1092
+ case "dirty_changed":
1093
+ return { isDirty: event.isDirty };
1094
+ case "comment_added":
1095
+ case "comment_resolved":
1096
+ return { commentId: event.commentId };
1097
+ case "change_accepted":
1098
+ case "change_rejected":
1099
+ return { changeId: event.changeId };
1100
+ case "warning_added":
1101
+ return { warningId: event.warning.warningId, code: event.warning.code };
1102
+ case "warning_cleared":
1103
+ return { warningId: event.warningId, code: event.code };
1104
+ case "error":
1105
+ return { errorId: event.error.errorId, code: event.error.code };
1106
+ case "autosave_state":
1107
+ return { status: event.state.status };
1108
+ case "snapshot_saved":
1109
+ return { isAutosave: event.isAutosave, savedAt: event.snapshot.savedAt };
1110
+ case "session_saved":
1111
+ return { isAutosave: event.isAutosave, savedAt: event.savedAt };
1112
+ case "export_completed":
1113
+ return {
1114
+ fileName: event.result.fileName,
1115
+ deliveryMode: event.result.delivery?.mode,
1116
+ savedAt: event.result.delivery?.savedAt,
1117
+ };
1118
+ case "story_changed":
1119
+ return { activeStory: event.activeStory };
1120
+ case "selection_changed":
1121
+ return {
1122
+ anchor: event.selection.anchor,
1123
+ head: event.selection.head,
1124
+ };
1125
+ case "ready":
1126
+ return {
1127
+ source: event.source,
1128
+ blockExport: event.compatibility.blockExport,
1129
+ };
1130
+ }
1131
+ }
1132
+
1133
+ function createReadyEvent(
1134
+ runtime: Pick<WordReviewEditorRuntime, "getCompatibilityReport" | "getRenderSnapshot">,
1135
+ source: "docx" | "session" | "snapshot",
1136
+ ): Extract<WordReviewEditorEvent, { type: "ready" }> {
1137
+ const snapshot = runtime.getRenderSnapshot();
1138
+ return {
1139
+ type: "ready",
1140
+ documentId: snapshot.documentId,
1141
+ sessionId: snapshot.sessionId,
1142
+ source,
1143
+ stats: snapshot.documentStats,
1144
+ compatibility: runtime.getCompatibilityReport(),
1145
+ comments: snapshot.comments,
1146
+ trackedChanges: snapshot.trackedChanges,
1147
+ };
1148
+ }
1149
+
1150
+ function normalizeEditorError(error: unknown): EditorError {
1151
+ if (
1152
+ typeof error === "object" &&
1153
+ error !== null &&
1154
+ "errorId" in error &&
1155
+ "code" in error &&
1156
+ "message" in error
1157
+ ) {
1158
+ return error as EditorError;
1159
+ }
1160
+
1161
+ return {
1162
+ errorId: "word-review-editor-load",
1163
+ code: "internal_invariant",
1164
+ message: error instanceof Error ? error.message : "Unknown editor load failure.",
1165
+ isFatal: true,
1166
+ source: "runtime",
1167
+ };
1168
+ }
1169
+
1170
+ function guessSourceLabel(
1171
+ initialSourceLabel?: string,
1172
+ initialSessionState?: EditorSessionState,
1173
+ initialSnapshot?: PersistedEditorSnapshot,
1174
+ externalDocSource?: WordReviewEditorProps["externalDocSource"],
1175
+ ): string | undefined {
1176
+ return (
1177
+ externalDocSource?.sourceLabel ??
1178
+ (externalDocSource?.kind === "session"
1179
+ ? externalDocSource.sessionState.sourcePackage?.sourceLabel
1180
+ : undefined) ??
1181
+ (externalDocSource?.kind === "snapshot"
1182
+ ? externalDocSource.snapshot.sourcePackage?.sourceLabel
1183
+ : undefined) ??
1184
+ initialSourceLabel ??
1185
+ initialSessionState?.sourcePackage?.sourceLabel ??
1186
+ initialSessionState?.editorBuild ??
1187
+ initialSnapshot?.sourcePackage?.sourceLabel ??
1188
+ initialSnapshot?.editorBuild ??
1189
+ undefined
1190
+ );
1191
+ }
1192
+
1193
+ function createFallbackPersistedSnapshot(
1194
+ documentId: string,
1195
+ label = "Generated shell snapshot",
1196
+ ): PersistedEditorSnapshot {
1197
+ const docId = createCanonicalDocumentId(documentId);
1198
+ return {
1199
+ snapshotVersion: "persisted-editor-snapshot/2",
1200
+ schemaVersion: "cds/1.0.0",
1201
+ documentId,
1202
+ docId,
1203
+ createdAt: "1970-01-01T00:00:00.000Z",
1204
+ updatedAt: "1970-01-01T00:00:00.000Z",
1205
+ savedAt: "1970-01-01T00:00:00.000Z",
1206
+ editorBuild: label,
1207
+ canonicalDocument: {
1208
+ schemaVersion: "cds/1.0.0",
1209
+ docId,
1210
+ createdAt: "1970-01-01T00:00:00.000Z",
1211
+ updatedAt: "1970-01-01T00:00:00.000Z",
1212
+ metadata: { customProperties: {} },
1213
+ styles: { paragraphs: {}, characters: {}, tables: {} },
1214
+ numbering: { abstractDefinitions: {}, instances: {} },
1215
+ media: { items: {} },
1216
+ content: {
1217
+ type: "doc",
1218
+ children: [{ type: "paragraph", children: [] }],
1219
+ },
1220
+ review: { comments: {}, revisions: {} },
1221
+ preservation: { opaqueFragments: {}, packageParts: {} },
1222
+ diagnostics: { warnings: [], errors: [] },
1223
+ },
1224
+ compatibility: emptyCompatibilityReport(),
1225
+ warningLog: [],
1226
+ };
1227
+ }
1228
+
1229
+ function emptyCompatibilityReport(): CompatibilityReport {
1230
+ return {
1231
+ reportVersion: "compatibility-report/1",
1232
+ generatedAt: "1970-01-01T00:00:00.000Z",
1233
+ blockExport: false,
1234
+ featureEntries: [],
1235
+ warnings: [],
1236
+ errors: [],
1237
+ };
1238
+ }
1239
+
1240
+ function resolvePackageBackedExportSession(args: CreateRuntimeArgs): {
1241
+ session?: PackageBackedDocxSession;
1242
+ barrier?: SnapshotExportBarrier;
1243
+ } {
1244
+ const sourcePackage =
1245
+ args.source.initialSessionState?.sourcePackage ??
1246
+ args.source.initialSnapshot?.sourcePackage;
1247
+ if (!sourcePackage) {
1248
+ return {
1249
+ barrier: {
1250
+ reason: "missing_source_package_provenance",
1251
+ message:
1252
+ "DOCX export is blocked because this session was loaded without embedded source package provenance.",
1253
+ },
1254
+ };
1255
+ }
1256
+
1257
+ try {
1258
+ const bytes = decodePersistedSourcePackageBytes(sourcePackage);
1259
+ if (!hasValidPersistedSourcePackageDigest(sourcePackage, bytes)) {
1260
+ return {
1261
+ barrier: {
1262
+ reason: "invalid_source_package_provenance",
1263
+ message:
1264
+ "DOCX export is blocked because the embedded source package provenance failed its integrity check.",
1265
+ },
1266
+ };
1267
+ }
1268
+
1269
+ const session = loadDocxEditorSession({
1270
+ documentId: args.documentId,
1271
+ sourceLabel: sourcePackage.sourceLabel ?? args.source.sourceLabel,
1272
+ bytes,
1273
+ editorBuild:
1274
+ args.source.initialSessionState?.editorBuild ??
1275
+ args.source.initialSnapshot?.editorBuild ??
1276
+ "dev",
1277
+ });
1278
+ if (session.readOnly || session.fatalError) {
1279
+ return {
1280
+ barrier: {
1281
+ reason: "invalid_source_package_provenance",
1282
+ message:
1283
+ "DOCX export is blocked because the embedded source package provenance is no longer loadable as a valid package-backed session.",
1284
+ },
1285
+ };
1286
+ }
1287
+
1288
+ return { session };
1289
+ } catch {
1290
+ return {
1291
+ barrier: {
1292
+ reason: "invalid_source_package_provenance",
1293
+ message:
1294
+ "DOCX export is blocked because the embedded source package provenance could not be decoded into a package-backed session.",
1295
+ },
1296
+ };
1297
+ }
1298
+ }
1299
+
1300
+ function applySessionExportBarrier(
1301
+ sessionState: EditorSessionState,
1302
+ barrier: SnapshotExportBarrier,
1303
+ ): EditorSessionState {
1304
+ const featureEntryId = `feature:source-package-provenance:${barrier.reason}`;
1305
+ const featureEntries = sessionState.compatibility.featureEntries.some(
1306
+ (entry) => entry.featureEntryId === featureEntryId,
1307
+ )
1308
+ ? sessionState.compatibility.featureEntries
1309
+ : [
1310
+ ...sessionState.compatibility.featureEntries,
1311
+ {
1312
+ featureEntryId,
1313
+ featureKey: "source-package-provenance",
1314
+ featureClass: "unsupported-fatal" as const,
1315
+ message: barrier.message,
1316
+ details: {
1317
+ reason: barrier.reason,
1318
+ },
1319
+ },
1320
+ ];
1321
+
1322
+ return {
1323
+ ...sessionState,
1324
+ compatibility: {
1325
+ ...sessionState.compatibility,
1326
+ blockExport: true,
1327
+ featureEntries,
1328
+ },
1329
+ };
1330
+ }
1331
+
1332
+ function createSnapshotExportBlockedError(
1333
+ documentId: string,
1334
+ barrier: SnapshotExportBarrier,
1335
+ ): EditorError {
1336
+ return {
1337
+ errorId: `${documentId}:export:${barrier.reason}`,
1338
+ code: "export_failed",
1339
+ message: barrier.message,
1340
+ isFatal: false,
1341
+ source: "export",
1342
+ details: {
1343
+ reason: barrier.reason,
1344
+ },
1345
+ };
1346
+ }
1347
+
1348
+ function normalizeStorageError(
1349
+ error: unknown,
1350
+ fallback: {
1351
+ message: string;
1352
+ source: "host" | "datastore";
1353
+ details?: Record<string, unknown>;
1354
+ },
1355
+ ): EditorError {
1356
+ if (
1357
+ typeof error === "object" &&
1358
+ error !== null &&
1359
+ "errorId" in error &&
1360
+ "code" in error &&
1361
+ "message" in error
1362
+ ) {
1363
+ return error as EditorError;
1364
+ }
1365
+
1366
+ return {
1367
+ errorId:
1368
+ fallback.source === "host"
1369
+ ? "word-review-editor-host"
1370
+ : "word-review-editor-datastore",
1371
+ code: "datastore_failed",
1372
+ message: error instanceof Error ? error.message : fallback.message,
1373
+ isFatal: false,
1374
+ source: fallback.source === "host" ? "host" : "datastore",
1375
+ details: fallback.details,
1376
+ };
1377
+ }
1378
+
1379
+ function normalizeExportError(
1380
+ error: unknown,
1381
+ documentId: string,
1382
+ options?: ExportDocxOptions,
1383
+ ): EditorError {
1384
+ if (
1385
+ typeof error === "object" &&
1386
+ error !== null &&
1387
+ "errorId" in error &&
1388
+ "code" in error &&
1389
+ "message" in error
1390
+ ) {
1391
+ return error as EditorError;
1392
+ }
1393
+
1394
+ return {
1395
+ errorId: `${documentId}:export:failed`,
1396
+ code: "export_failed",
1397
+ message:
1398
+ error instanceof Error ? error.message : "DOCX export failed for an unknown reason.",
1399
+ isFatal: false,
1400
+ source: "export",
1401
+ details: {
1402
+ requestedOptions: options ?? {},
1403
+ },
1404
+ };
1405
+ }
1406
+
1407
+ function collapsedSelection(): RuntimeRenderSnapshot["selection"] {
1408
+ return {
1409
+ anchor: 0,
1410
+ head: 0,
1411
+ isCollapsed: true,
1412
+ activeRange: {
1413
+ kind: "range",
1414
+ from: 0,
1415
+ to: 0,
1416
+ assoc: {
1417
+ start: -1,
1418
+ end: 1,
1419
+ },
1420
+ },
1421
+ };
1422
+ }