-
Notifications
You must be signed in to change notification settings - Fork 177
Expand file tree
/
Copy pathdocument.ts
More file actions
538 lines (486 loc) · 17.8 KB
/
Copy pathdocument.ts
File metadata and controls
538 lines (486 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
import { readFile, writeFile } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import {
Editor,
BLANK_DOCX_BASE64,
DocxEncryptionError,
getDocumentApiAdapters,
markdownToPmDoc,
initPartsRuntime,
} from 'superdoc/super-editor';
import { createDocumentApi, type DocumentApi } from '@superdoc/document-api';
import { createCliDomEnvironment } from './dom-environment';
import type { CollaborationProfile } from './collaboration';
import { createCollaborationRuntime } from './collaboration';
import {
DEFAULT_BOOTSTRAP_SETTLING_MS,
waitForContentSettling,
detectRoomState,
resolveBootstrapDecision,
claimBootstrap,
clearBootstrapMarker,
writeBootstrapMarker,
detectBootstrapRace,
type RoomState,
type ObservedCompetitor,
type RaceDetectionResult,
} from './bootstrap';
import { CliError } from './errors';
import { pathExists } from './guards';
import { buildHeadlessCommentBridge } from './headless-comment-bridge';
import type { ContextMetadata } from './context';
import type { CliIO, DocumentSourceMeta, ExecutionMode, UserIdentity } from './types';
import type { SessionPool } from '../host/session-pool';
export type EditorWithDoc = Editor & {
doc: DocumentApi;
};
export interface OpenedDocument {
editor: EditorWithDoc;
meta: DocumentSourceMeta;
dispose(): void;
}
/** Content override options extracted before calling Editor.open(). */
interface ContentOverrideOptions {
markdown?: string;
html?: string;
plainText?: string;
}
type TrackChangesReplacementMode = 'paired' | 'independent';
/** Options passed through to Editor.open() alongside content overrides. */
export interface EditorPassThroughOptions {
password?: string;
modules?: {
trackChanges?: {
replacements?: TrackChangesReplacementMode;
};
};
}
interface OpenDocumentOptions {
documentId?: string;
ydoc?: unknown;
collaborationProvider?: unknown;
/** Options passed through to Editor.open() (e.g., markdown/html/plainText for content override). */
editorOpenOptions?: ContentOverrideOptions & EditorPassThroughOptions;
/** When set, overrides Editor's auto-detected isNewFile flag. */
isNewFile?: boolean;
/** Optional user identity for attribution (comments, tracked changes, collaboration presence). */
user?: UserIdentity;
}
export interface FileOutputMeta {
path: string;
byteLength: number;
}
function bindCurrentDocumentApi(editor: Editor): EditorWithDoc {
const editorWithDoc = editor as EditorWithDoc;
// Shadow the lazy getter with an eagerly-created DocumentApi so the CLI and
// story harnesses always dispatch against the same source-backed adapter graph.
Object.defineProperty(editorWithDoc, 'doc', {
configurable: true,
value: createDocumentApi(getDocumentApiAdapters(editor)),
});
return editorWithDoc;
}
async function toUint8Array(data: unknown): Promise<Uint8Array> {
if (data instanceof Uint8Array) return data;
if (data instanceof ArrayBuffer) return new Uint8Array(data);
if (ArrayBuffer.isView(data)) {
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
}
if (typeof Blob !== 'undefined' && data instanceof Blob) {
return new Uint8Array(await data.arrayBuffer());
}
if (typeof data === 'object' && data !== null && 'arrayBuffer' in data && typeof data.arrayBuffer === 'function') {
const arrayBuffer = await data.arrayBuffer();
return new Uint8Array(arrayBuffer);
}
const constructorName =
typeof data === 'object' && data !== null && 'constructor' in data && typeof data.constructor === 'function'
? data.constructor.name
: undefined;
const objectKeys = typeof data === 'object' && data !== null ? Object.keys(data).slice(0, 8) : [];
throw new CliError(
'DOCUMENT_EXPORT_FAILED',
`Exported document data is not binary (type=${typeof data}, constructor=${constructorName ?? 'unknown'}, keys=${objectKeys.join(',')}).`,
);
}
async function readDocumentSource(doc: string, io: CliIO): Promise<{ bytes: Uint8Array; meta: DocumentSourceMeta }> {
if (doc === '-') {
const bytes = await io.readStdinBytes();
if (bytes.byteLength === 0) {
throw new CliError('MISSING_REQUIRED', 'No DOCX bytes were provided on stdin.');
}
return {
bytes,
meta: {
source: 'stdin',
byteLength: bytes.byteLength,
},
};
}
let bytes: Uint8Array;
try {
const raw = await readFile(doc);
bytes = new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new CliError('FILE_READ_ERROR', `Unable to read document: ${doc}`, {
message,
});
}
return {
bytes,
meta: {
source: 'path',
path: doc,
byteLength: bytes.byteLength,
},
};
}
export async function openDocument(
doc: string | undefined,
io: CliIO,
options: OpenDocumentOptions = {},
): Promise<OpenedDocument> {
let source: Uint8Array;
let meta: DocumentSourceMeta;
if (doc != null) {
const result = await readDocumentSource(doc, io);
source = result.bytes;
meta = result.meta;
} else {
source = Buffer.from(BLANK_DOCX_BASE64, 'base64');
meta = { source: 'blank', byteLength: source.byteLength };
}
// Separate content overrides from options passed to Editor.open().
// Markdown and plainText are applied post-init (DOM-free AST pipelines).
// HTML passes through to Editor.open() directly — the CLI-provided happy-dom
// document enables the Editor's built-in HTML init path.
const {
markdown: markdownOverride,
html: htmlOverride,
plainText: plainTextOverride,
...passThroughEditorOpts
} = options.editorOpenOptions ?? {};
// Create a DOM environment for headless HTML support (getHtml, insert HTML,
// HTML content override). Always inject via options.document — never set globals.
const domEnv = createCliDomEnvironment();
// Wire headless comment/tracked-change bridge when collaboration is active.
const hasCollaboration = options.ydoc != null && options.collaborationProvider != null;
const commentBridge = hasCollaboration ? buildHeadlessCommentBridge(options.ydoc, options.user) : null;
let editor: Editor;
try {
const isTest = process.env.NODE_ENV === 'test';
editor = await Editor.open(Buffer.from(source), {
documentId: options.documentId ?? meta.path ?? 'blank.docx',
document: domEnv.document,
isHeadless: true,
user: options.user
? { name: options.user.name, email: options.user.email, image: null }
: { id: 'cli', name: 'CLI' },
...(isTest ? { telemetry: { enabled: false } } : {}),
ydoc: options.ydoc,
...(options.collaborationProvider != null ? { collaborationProvider: options.collaborationProvider } : {}),
...(options.isNewFile != null ? { isNewFile: options.isNewFile } : {}),
// Pass through HTML override directly — happy-dom provides DOM support.
...(htmlOverride != null ? { html: htmlOverride } : {}),
...(commentBridge?.editorOptions ?? {}),
...passThroughEditorOpts,
});
} catch (error) {
commentBridge?.dispose();
domEnv.dispose();
// Preserve DOCX encryption errors so callers get actionable codes
// (e.g. DOCX_PASSWORD_REQUIRED) instead of generic DOCUMENT_OPEN_FAILED.
if (error instanceof DocxEncryptionError) {
throw new CliError(error.code, error.message, { source: meta });
}
const message = error instanceof Error ? error.message : String(error);
throw new CliError('DOCUMENT_OPEN_FAILED', 'Failed to open document.', {
message,
source: meta,
});
}
// Parts/runtime registration is idempotent. Re-run it here so adapter-side
// afterCommit hooks are always wired, including in headless CLI sessions.
initPartsRuntime(editor as never);
// SD-3214: bridge observes ydoc.getArray('comments') and feeds remote
// (browser-authored) metadata into the editor's CommentEntityStore so the
// headless SDK can read text/creatorName/createdTime via doc.comments.list().
commentBridge?.attachEditor(editor as never);
// Apply content override post-init.
// - markdown: DOM-free AST pipeline
// - plainText: builds PM paragraphs directly, preserving all whitespace
if (markdownOverride != null) {
try {
const { doc: newDoc } = markdownToPmDoc(markdownOverride, editor);
const tr = editor.state.tr;
tr.replaceWith(0, editor.state.doc.content.size, newDoc.content);
editor.dispatch(tr);
} catch (error) {
editor.destroy();
domEnv.dispose();
const message = error instanceof Error ? error.message : String(error);
throw new CliError('DOCUMENT_OPEN_FAILED', 'Failed to apply content override.', {
message,
source: meta,
});
}
} else if (plainTextOverride != null) {
try {
const schema = editor.state.schema;
const lines = plainTextOverride.split('\n');
const paragraphs = lines.map((line) => {
const content = line.length > 0 ? [schema.text(line)] : undefined;
return schema.nodes.paragraph.create(null, content);
});
const tr = editor.state.tr;
tr.replaceWith(0, editor.state.doc.content.size, paragraphs);
editor.dispatch(tr);
} catch (error) {
editor.destroy();
domEnv.dispose();
const message = error instanceof Error ? error.message : String(error);
throw new CliError('DOCUMENT_OPEN_FAILED', 'Failed to apply text content override.', {
message,
source: meta,
});
}
}
const editorWithDoc = bindCurrentDocumentApi(editor);
return {
editor: editorWithDoc,
meta,
dispose() {
commentBridge?.dispose();
editor.destroy();
domEnv.dispose();
},
};
}
/**
* Describes the outcome of the bootstrap flow for a collaborative document.
*
* `raceSuspected` is a best-effort signal — when true, a competing finalized
* marker was observed shortly after seeding, strongly suggesting (but not
* proving) that two clients both seeded. `false` does not guarantee
* exactly-once seeding.
*/
export type BootstrapResult = {
roomState: RoomState;
bootstrapApplied: boolean;
bootstrapSource?: 'doc' | 'blank';
raceSuspected?: boolean;
raceCompetitor?: ObservedCompetitor;
};
export async function openCollaborativeDocument(
doc: string | undefined,
io: CliIO,
profile: CollaborationProfile,
options: { editorOpenOptions?: EditorPassThroughOptions; user?: UserIdentity } = {},
): Promise<OpenedDocument & { bootstrap?: BootstrapResult }> {
const runtime = createCollaborationRuntime(profile);
try {
await runtime.waitForSync();
// SD-2138: Some providers fire "synced" before Yjs updates are fully
// applied to local shared types. Give a brief window for the XmlFragment
// to be populated from incoming server state before checking room state.
await waitForContentSettling(runtime.ydoc);
const onMissing = profile.onMissing ?? 'seedFromDoc';
let finalRoomState = detectRoomState(runtime.ydoc);
let decision = resolveBootstrapDecision(finalRoomState, onMissing, doc != null);
if (decision.action === 'seed') {
const claim = await claimBootstrap(runtime.ydoc, profile.bootstrapSettlingMs ?? DEFAULT_BOOTSTRAP_SETTLING_MS);
if (!claim.granted) {
// Another client won the claim race — unconditionally yield.
// Even if the winner's marker is still pending (detectRoomState
// returns 'empty'), the winner will finalize shortly. Re-seeding
// here would produce a dual-seed race.
finalRoomState = detectRoomState(runtime.ydoc);
decision = { action: 'join' };
} else {
// SD-2138: Re-check room state after the claim settling period.
// Some providers fire "synced" before Yjs updates are fully applied,
// so content from the server may have arrived during the settling
// wait. If the room is now populated, join instead of seeding —
// seeding here would destructively overwrite existing content.
const postClaimState = detectRoomState(runtime.ydoc);
if (postClaimState === 'populated') {
clearBootstrapMarker(runtime.ydoc);
finalRoomState = postClaimState;
decision = { action: 'join' };
}
}
}
if (decision.action === 'error') {
throw new CliError('COLLABORATION_ROOM_EMPTY', decision.reason);
}
const shouldSeed = decision.action === 'seed';
// When joining an existing room, skip local doc reading — content
// comes from the Yjs document, not from the local file path.
const docForEditor = shouldSeed ? doc : undefined;
const opened = await openDocument(docForEditor, io, {
documentId: profile.documentId,
ydoc: runtime.ydoc,
collaborationProvider: runtime.provider,
// When seeding from a document, we need isNewFile: false so that
// #initComments() runs and emits commentsLoaded, pushing comments to Y.Array.
isNewFile: shouldSeed && !docForEditor,
editorOpenOptions: options.editorOpenOptions,
user: options.user,
});
let raceDetection: RaceDetectionResult | undefined;
if (shouldSeed) {
writeBootstrapMarker(runtime.ydoc, decision.source);
raceDetection = await detectBootstrapRace(runtime.ydoc);
}
const bootstrap: BootstrapResult = {
roomState: finalRoomState,
bootstrapApplied: shouldSeed,
bootstrapSource: shouldSeed ? decision.source : undefined,
raceSuspected: raceDetection?.raceSuspected,
raceCompetitor: raceDetection?.raceSuspected ? raceDetection.competitor : undefined,
};
return {
editor: opened.editor,
meta: opened.meta,
bootstrap,
dispose() {
try {
opened.dispose();
} finally {
runtime.dispose();
}
},
};
} catch (error) {
runtime.dispose();
throw error;
}
}
export async function openSessionDocument(
doc: string,
io: CliIO,
metadata: Pick<
ContextMetadata,
'contextId' | 'sessionType' | 'collaboration' | 'sourcePath' | 'workingDocPath' | 'user' | 'revision'
>,
options: {
sessionId?: string;
executionMode?: ExecutionMode;
sessionPool?: SessionPool;
} = {},
): Promise<OpenedDocument> {
const { executionMode, sessionPool, sessionId } = options;
// Host mode: always go through pool (local AND collab)
if (executionMode === 'host' && sessionPool) {
const resolvedSessionId = sessionId ?? metadata.contextId;
return sessionPool.acquire(
resolvedSessionId,
{
sessionType: metadata.sessionType,
workingDocPath: metadata.workingDocPath ?? doc,
metadataRevision: metadata.revision,
user: metadata.user,
collaboration: metadata.collaboration,
},
io,
);
}
// Oneshot mode: open fresh, caller is responsible for dispose
if (metadata.sessionType === 'collab') {
if (!metadata.collaboration) {
throw new CliError('COMMAND_FAILED', 'Session is marked as collaborative but has no collaboration profile.');
}
return openCollaborativeDocument(doc, io, metadata.collaboration, { user: metadata.user });
}
return openDocument(doc, io, { user: metadata.user });
}
export async function getFileChecksum(path: string): Promise<string> {
let bytes: Uint8Array;
try {
const data = await readFile(path);
bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new CliError('FILE_READ_ERROR', `Failed to read file checksum: ${path}`, {
message,
});
}
return createHash('sha256').update(bytes).digest('hex');
}
export type OptionalExportResult = {
output?: { path: string; byteLength: number };
warning?: {
code: string;
path: string;
message: string;
};
};
/**
* Attempts an optional session export, returning structured success/warning
* data instead of throwing on failure.
*
* @param editor - The editor instance to export from
* @param io - CLI I/O for diagnostic warnings
* @param outPath - Optional output path; returns `undefined` when absent
* @param force - Whether to overwrite an existing file
* @returns Export result with output or warning metadata, or `undefined` if no path
*/
export async function exportOptionalSessionOutput(
editor: EditorWithDoc,
io: CliIO,
outPath: string | undefined,
force: boolean,
): Promise<OptionalExportResult | undefined> {
if (!outPath) return undefined;
try {
return { output: await exportToPath(editor, outPath, force) };
} catch (error) {
const code = error instanceof CliError ? error.code : 'FILE_WRITE_ERROR';
const message = error instanceof Error ? error.message : String(error);
io.warn?.(`[warn] optional export to ${outPath} failed: ${message}\n`);
return {
warning: {
code,
path: outPath,
message,
},
};
}
}
export async function exportToPath(
editor: Editor,
outputPath: string,
force = false,
options: { isFinalDoc?: boolean } = {},
): Promise<FileOutputMeta> {
const exists = await pathExists(outputPath);
if (exists && !force) {
throw new CliError('OUTPUT_EXISTS', `Output path already exists: ${outputPath}`, {
path: outputPath,
hint: 'Use --force to overwrite.',
});
}
let exported: unknown;
try {
exported = await editor.exportDocument({ isFinalDoc: options.isFinalDoc });
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new CliError('DOCUMENT_EXPORT_FAILED', 'Failed to export document.', {
message,
});
}
const bytes = await toUint8Array(exported);
try {
await writeFile(outputPath, bytes);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new CliError('FILE_WRITE_ERROR', `Failed to write output file: ${outputPath}`, {
message,
});
}
return {
path: outputPath,
byteLength: bytes.byteLength,
};
}