-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathcli.test.ts
More file actions
2635 lines (2215 loc) · 89.9 KB
/
cli.test.ts
File metadata and controls
2635 lines (2215 loc) · 89.9 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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import { execFile } from 'node:child_process';
import { access, copyFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { promisify } from 'node:util';
import { run } from '../index';
import { resolveListDocFixture, resolveSourceDocFixture } from './fixtures';
import { writeListDocWithoutParaIds, writeTableOnlyDocFixture } from './unstable-list-fixture';
type RunResult = {
code: number;
stdout: string;
stderr: string;
};
type TextRange = {
kind: 'text';
blockId: string;
range: {
start: number;
end: number;
};
};
type ListItemAddress = {
kind: 'block';
nodeType: 'listItem';
nodeId: string;
};
type SuccessEnvelope<TData> = {
ok: true;
command: string;
data: TData;
meta: {
elapsedMs: number;
};
};
type ErrorEnvelope = {
ok: false;
error: {
code: string;
message: string;
};
};
type MutationReceiptEnvelope = SuccessEnvelope<{
receipt: {
success: boolean;
resolution?: {
target: TextRange;
};
};
}>;
const TEST_DIR = join(import.meta.dir, 'fixtures-cli');
const STATE_DIR = join(TEST_DIR, 'state');
const SAMPLE_DOC = join(TEST_DIR, 'sample.docx');
const LIST_SAMPLE_DOC = join(TEST_DIR, 'lists-sample.docx');
const ENCRYPTED_DOC = join(TEST_DIR, 'encrypted.docx');
const CLI_PACKAGE_JSON_PATH = join(import.meta.dir, '../../package.json');
const REPO_ROOT = join(import.meta.dir, '../../../..');
const ENCRYPTED_FIXTURE_SOURCE = join(
REPO_ROOT,
'packages/super-editor/src/editors/v1/core/ooxml-encryption/fixtures/encrypted-advanced-text.docx',
);
const TRACKED_CHANGE_FIXTURE_SOURCE = join(
REPO_ROOT,
'packages/super-editor/src/editors/v1/tests/data/basic-tracked-change.docx',
);
const execFileAsync = promisify(execFile);
const ZIP_MAX_BUFFER_BYTES = 10 * 1024 * 1024;
async function readCliPackageVersion(): Promise<string> {
const raw = await readFile(CLI_PACKAGE_JSON_PATH, 'utf8');
const parsed = JSON.parse(raw) as { version?: unknown };
if (typeof parsed.version !== 'string' || parsed.version.length === 0) {
throw new Error('Expected apps/cli/package.json to contain a non-empty version string.');
}
return parsed.version;
}
async function readDocxPart(docPath: string, partPath: string): Promise<string> {
const { stdout } = await execFileAsync('unzip', ['-p', docPath, partPath], {
maxBuffer: ZIP_MAX_BUFFER_BYTES,
});
return stdout;
}
async function runCli(args: string[], stdinBytes?: Uint8Array): Promise<RunResult> {
let stdout = '';
let stderr = '';
const code = await run(
args,
{
stdout(message: string) {
stdout += message;
},
stderr(message: string) {
stderr += message;
},
async readStdinBytes() {
return stdinBytes ?? new Uint8Array();
},
},
{ stateDir: STATE_DIR },
);
return { code, stdout, stderr };
}
function parseJsonOutput<T>(result: RunResult): T {
const source = result.stdout.trim() || result.stderr.trim();
if (!source) {
throw new Error('No JSON output found.');
}
return JSON.parse(source) as T;
}
function asRecord(value: unknown): Record<string, unknown> | null {
if (typeof value !== 'object' || value == null || Array.isArray(value)) return null;
return value as Record<string, unknown>;
}
function hasPrettyProperties(node: unknown): boolean {
const record = asRecord(node);
if (!record) return false;
const properties = asRecord(record.properties);
if (!properties) return false;
return Object.values(properties).some((value) => value != null && value !== '' && value !== false);
}
async function firstTextRange(args: string[]): Promise<TextRange> {
// SDM/1: find returns SDNodeResult with NodeAddress. For text searches,
// the address is block-level (the containing block). We extract the
// blockId and find the pattern position within the node's text content.
const result = await runCli(args);
expect(result.code).toBe(0);
const envelope = parseJsonOutput<
SuccessEnvelope<{
result: {
items?: Array<{
node?: { kind?: string; [key: string]: unknown };
address?: { kind?: string; nodeId?: string };
}>;
};
}>
>(result);
const item = envelope.data.result.items?.[0];
const address = item?.address;
if (!address?.nodeId) {
throw new Error('Expected at least one match from find result.');
}
// Extract concatenated text from the SDM/1 node's inline content
const node = item?.node as Record<string, unknown> | undefined;
const nodeKind = node?.kind as string | undefined;
const kindData = nodeKind ? (node?.[nodeKind] as Record<string, unknown> | undefined) : undefined;
const inlines = Array.isArray(kindData?.inlines) ? kindData!.inlines : [];
let fullText = '';
for (const inline of inlines) {
if (typeof inline === 'object' && inline != null && (inline as Record<string, unknown>).kind === 'run') {
const runData = (inline as Record<string, unknown>).run as Record<string, unknown> | undefined;
if (typeof runData?.text === 'string') fullText += runData.text as string;
}
}
// Extract the search pattern from args to find its position within the text
const patternIdx = args.indexOf('--pattern');
const pattern = patternIdx >= 0 ? args[patternIdx + 1] : undefined;
const matchIndex = pattern ? fullText.indexOf(pattern) : -1;
const start = matchIndex >= 0 ? matchIndex : 0;
const end = matchIndex >= 0 ? matchIndex + pattern!.length : Math.max(fullText.length, 1);
return {
kind: 'text',
blockId: address.nodeId,
range: { start, end },
};
}
function firstInsertedEntityId(result: RunResult): string {
const envelope = parseJsonOutput<
SuccessEnvelope<{
receipt?: {
inserted?: Array<{ entityId?: string }>;
};
}>
>(result);
const entityId = envelope.data.receipt?.inserted?.[0]?.entityId;
if (!entityId) {
throw new Error('Expected inserted entity id in receipt.');
}
return entityId;
}
async function firstListItemAddress(args: string[]): Promise<ListItemAddress> {
const result = await runCli(args);
expect(result.code).toBe(0);
const envelope = parseJsonOutput<
SuccessEnvelope<{
result: {
items: Array<{ address: ListItemAddress }>;
};
}>
>(result);
const address = envelope.data.result.items[0]?.address;
if (!address) {
throw new Error('Expected at least one list item address from lists.list result.');
}
return address;
}
describe('superdoc CLI', () => {
let cliPackageVersion = '';
beforeAll(async () => {
await mkdir(TEST_DIR, { recursive: true });
await copyFile(await resolveSourceDocFixture(), SAMPLE_DOC);
await copyFile(await resolveListDocFixture(), LIST_SAMPLE_DOC);
await copyFile(ENCRYPTED_FIXTURE_SOURCE, ENCRYPTED_DOC);
cliPackageVersion = await readCliPackageVersion();
});
beforeEach(async () => {
await rm(STATE_DIR, { recursive: true, force: true });
});
afterAll(async () => {
await rm(TEST_DIR, { recursive: true, force: true });
});
test('status returns inactive when no document is open', async () => {
const result = await runCli(['status']);
expect(result.code).toBe(0);
const envelope = parseJsonOutput<SuccessEnvelope<{ active: boolean }>>(result);
expect(envelope.command).toBe('status');
expect(envelope.data.active).toBe(false);
});
test('global --version prints installed CLI package version', async () => {
const result = await runCli(['--version']);
expect(result.code).toBe(0);
expect(result.stderr).toBe('');
expect(result.stdout.trim()).toBe(cliPackageVersion);
});
test('global -v prints installed CLI package version', async () => {
const result = await runCli(['-v']);
expect(result.code).toBe(0);
expect(result.stderr).toBe('');
expect(result.stdout.trim()).toBe(cliPackageVersion);
});
test('global --version takes precedence over command execution', async () => {
const result = await runCli(['status', '--version']);
expect(result.code).toBe(0);
expect(result.stderr).toBe('');
expect(result.stdout.trim()).toBe(cliPackageVersion);
});
test('global --help takes precedence over --version', async () => {
const result = await runCli(['--help', '--version']);
expect(result.code).toBe(0);
expect(result.stdout).toContain('Usage: superdoc <command> [options]');
});
test('commands without <doc> require an active context', async () => {
const result = await runCli(['find', '--type', 'text', '--pattern', 'Wilde']);
expect(result.code).toBe(1);
const envelope = parseJsonOutput<ErrorEnvelope>(result);
expect(envelope.error.code).toBe('NO_ACTIVE_DOCUMENT');
});
test('info returns required contract fields', async () => {
const result = await runCli(['info', SAMPLE_DOC]);
expect(result.code).toBe(0);
const envelope = parseJsonOutput<
SuccessEnvelope<{
document: { source: string; revision: number };
counts: { words: number; paragraphs: number };
capabilities: { canFind: boolean };
}>
>(result);
expect(envelope.ok).toBe(true);
expect(envelope.command).toBe('info');
expect(envelope.data.document.source).toBe('path');
expect(envelope.data.document.revision).toBe(0);
expect(envelope.data.counts.words).toBeGreaterThan(0);
expect(envelope.data.counts.paragraphs).toBeGreaterThan(0);
expect(envelope.data.capabilities.canFind).toBe(true);
expect(envelope.meta.elapsedMs).toBeGreaterThanOrEqual(0);
});
test('info pretty includes revision summary and outline section when available', async () => {
const jsonResult = await runCli(['info', SAMPLE_DOC]);
expect(jsonResult.code).toBe(0);
const jsonEnvelope = parseJsonOutput<
SuccessEnvelope<{
outline: Array<{ level: number; text: string; nodeId: string }>;
}>
>(jsonResult);
const prettyResult = await runCli(['info', SAMPLE_DOC, '--output', 'pretty']);
expect(prettyResult.code).toBe(0);
expect(prettyResult.stdout).toContain('Revision 0:');
expect(prettyResult.stdout).toContain('words');
if (jsonEnvelope.data.outline.length > 0) {
expect(prettyResult.stdout).toContain('Outline:');
}
});
test('describe returns contract overview', async () => {
const result = await runCli(['describe']);
expect(result.code).toBe(0);
const envelope = parseJsonOutput<
SuccessEnvelope<{
contractVersion: string;
operationCount: number;
operations: Array<{ id: string; command: string[] }>;
}>
>(result);
expect(envelope.command).toBe('describe');
expect(envelope.data.contractVersion.length).toBeGreaterThan(0);
expect(envelope.data.operationCount).toBeGreaterThan(0);
expect(envelope.data.operations.some((operation) => operation.id === 'doc.find')).toBe(true);
});
test('describe command returns one operation by id', async () => {
const result = await runCli(['describe', 'command', 'doc.find']);
expect(result.code).toBe(0);
const envelope = parseJsonOutput<
SuccessEnvelope<{
contractVersion: string;
operation: {
id: string;
command: string[];
};
}>
>(result);
expect(envelope.command).toBe('describe command');
expect(envelope.data.contractVersion.length).toBeGreaterThan(0);
expect(envelope.data.operation.id).toBe('doc.find');
expect(envelope.data.operation.command).toEqual(['find']);
});
test('describe command pretty prints parameters and constraints', async () => {
const result = await runCli(['describe', 'command', 'doc.find', '--output', 'pretty']);
expect(result.code).toBe(0);
expect(result.stdout).toContain('Parameters:');
expect(result.stdout).toContain('--session');
expect(result.stdout).toContain('--limit');
expect(result.stdout).toContain('Constraints:');
});
test('describe command pretty labels operation positional args by name', async () => {
const result = await runCli(['describe', 'command', 'doc.describeCommand', '--output', 'pretty']);
expect(result.code).toBe(0);
expect(result.stdout).toContain('<operationId>');
expect(result.stdout).not.toContain('<doc> Document path or stdin');
});
test('describe command pretty labels session ids as positional ids', async () => {
const result = await runCli(['describe', 'command', 'doc.session.save', '--output', 'pretty']);
expect(result.code).toBe(0);
expect(result.stdout).toContain('<sessionId>');
expect(result.stdout).not.toContain('<doc> Document path or stdin');
});
test('describe command doc.insert includes --target and --value flags', async () => {
const result = await runCli(['describe', 'command', 'doc.insert', '--output', 'pretty']);
expect(result.code).toBe(0);
expect(result.stdout).toContain('--target');
expect(result.stdout).toContain('--value');
});
test('call executes an operation from canonical input payload', async () => {
const result = await runCli([
'call',
'doc.find',
'--input-json',
JSON.stringify({
doc: SAMPLE_DOC,
query: {
select: {
type: 'text',
pattern: 'Wilde',
mode: 'contains',
},
limit: 1,
},
}),
]);
expect(result.code).toBe(0);
const envelope = parseJsonOutput<
SuccessEnvelope<{
operationId: string;
result: {
query: {
select: {
type: string;
};
};
document: {
source: string;
};
};
}>
>(result);
expect(envelope.command).toBe('call');
expect(envelope.data.operationId).toBe('doc.find');
expect(envelope.data.result.query.select.type).toBe('text');
expect(envelope.data.result.document.source).toBe('path');
});
test('call resolves operation ids from command-key shorthand', async () => {
const result = await runCli([
'call',
'find',
'--input-json',
JSON.stringify({
doc: SAMPLE_DOC,
query: {
select: {
type: 'text',
pattern: 'Wilde',
},
},
}),
]);
expect(result.code).toBe(0);
const envelope = parseJsonOutput<
SuccessEnvelope<{
operationId: string;
}>
>(result);
expect(envelope.data.operationId).toBe('doc.find');
});
test('call supports operations with non-doc positional kind:"doc" params', async () => {
const result = await runCli([
'call',
'doc.describeCommand',
'--input-json',
JSON.stringify({
operationId: 'doc.find',
}),
]);
expect(result.code).toBe(0);
const envelope = parseJsonOutput<
SuccessEnvelope<{
operationId: string;
result: {
operation: {
id: string;
};
};
}>
>(result);
expect(envelope.data.operationId).toBe('doc.describeCommand');
expect(envelope.data.result.operation.id).toBe('doc.find');
});
test('call supports alias command keys with spaces', async () => {
const sessionId = 'call-session-use-alias';
const openResult = await runCli(['open', SAMPLE_DOC, '--session', sessionId]);
expect(openResult.code).toBe(0);
const callResult = await runCli([
'call',
'session',
'use',
'--input-json',
JSON.stringify({
sessionId,
}),
]);
expect(callResult.code).toBe(0);
const envelope = parseJsonOutput<
SuccessEnvelope<{
operationId: string;
result: {
activeSessionId: string;
};
}>
>(callResult);
expect(envelope.data.operationId).toBe('doc.session.setDefault');
expect(envelope.data.result.activeSessionId).toBe(sessionId);
const closeResult = await runCli(['close', '--session', sessionId, '--discard']);
expect(closeResult.code).toBe(0);
});
test('call doc.open accepts doc + sessionId in input payload', async () => {
const sessionId = 'call-open-with-session-id';
const openCall = await runCli([
'call',
'doc.open',
'--input-json',
JSON.stringify({
doc: SAMPLE_DOC,
sessionId,
}),
]);
expect(openCall.code).toBe(0);
const openEnvelope = parseJsonOutput<
SuccessEnvelope<{
operationId: string;
result: {
contextId: string;
active: boolean;
};
}>
>(openCall);
expect(openEnvelope.data.operationId).toBe('doc.open');
expect(openEnvelope.data.result.contextId).toBe(sessionId);
expect(openEnvelope.data.result.active).toBe(true);
const closeResult = await runCli(['close', '--session', sessionId, '--discard']);
expect(closeResult.code).toBe(0);
});
test('call doc.save and doc.close use active session when input.sessionId is omitted', async () => {
const sessionId = 'call-save-close-active-session';
const savedOut = join(TEST_DIR, 'call-save-close-active-session.docx');
const openResult = await runCli(['open', SAMPLE_DOC, '--session', sessionId]);
expect(openResult.code).toBe(0);
const saveCall = await runCli([
'call',
'doc.save',
'--input-json',
JSON.stringify({
out: savedOut,
force: true,
}),
]);
expect(saveCall.code).toBe(0);
const closeCall = await runCli([
'call',
'doc.close',
'--input-json',
JSON.stringify({
discard: true,
}),
]);
expect(closeCall.code).toBe(0);
});
test('call rejects mixing stateless doc input with session targets', async () => {
const result = await runCli([
'call',
'doc.find',
'--input-json',
JSON.stringify({
doc: SAMPLE_DOC,
sessionId: 'mixed-mode-session',
query: {
select: {
type: 'text',
pattern: 'Wilde',
},
},
}),
]);
expect(result.code).toBe(1);
const envelope = parseJsonOutput<ErrorEnvelope>(result);
expect(envelope.error.code).toBe('INVALID_ARGUMENT');
expect(envelope.error.message).toContain('stateless input.doc cannot be combined');
});
test('call executes direct text-mutation operations without token round-trip semantics drift', async () => {
const source = join(TEST_DIR, 'call-insert-source.docx');
const out = join(TEST_DIR, 'call-insert-out.docx');
await copyFile(SAMPLE_DOC, source);
const callResult = await runCli([
'call',
'doc.insert',
'--input-json',
JSON.stringify({
doc: source,
value: 'CALL_INSERT_TOKEN_1597',
out,
}),
]);
expect(callResult.code).toBe(0);
const envelope = parseJsonOutput<
SuccessEnvelope<{
operationId: string;
result: {
document: { source: string };
receipt: { success: boolean };
};
}>
>(callResult);
expect(envelope.data.operationId).toBe('doc.insert');
expect(envelope.data.result.document.source).toBe('path');
expect(envelope.data.result.receipt.success).toBe(true);
const verifyResult = await runCli(['find', out, '--type', 'text', '--pattern', 'CALL_INSERT_TOKEN_1597']);
expect(verifyResult.code).toBe(0);
const verifyEnvelope = parseJsonOutput<SuccessEnvelope<{ result: { total: number } }>>(verifyResult);
expect(verifyEnvelope.data.result.total).toBeGreaterThan(0);
});
test('call only supports JSON output mode', async () => {
const result = await runCli([
'call',
'doc.find',
'--input-json',
JSON.stringify({
doc: SAMPLE_DOC,
query: {
select: {
type: 'text',
pattern: 'Wilde',
},
},
}),
'--output',
'pretty',
]);
expect(result.code).toBe(1);
expect(result.stderr).toContain('INVALID_ARGUMENT');
expect(result.stderr).toContain('call: only --output json is supported.');
});
test('describe command returns TARGET_NOT_FOUND for unknown operation', async () => {
const result = await runCli(['describe', 'command', 'doc.missing']);
expect(result.code).toBe(1);
const envelope = parseJsonOutput<ErrorEnvelope>(result);
expect(envelope.error.code).toBe('TARGET_NOT_FOUND');
});
test('find supports run node type', async () => {
const result = await runCli(['find', SAMPLE_DOC, '--type', 'run', '--limit', '1']);
expect(result.code).toBe(0);
const envelope = parseJsonOutput<
SuccessEnvelope<{
result: {
total: number;
items: Array<{ address: { kind: string; nodeType: string } }>;
};
}>
>(result);
expect(envelope.ok).toBe(true);
expect(envelope.command).toBe('find');
expect(envelope.data.result.total).toBeGreaterThan(0);
expect(envelope.data.result.items[0].node.kind).toBe('run');
});
test('find rejects legacy query.include payloads', async () => {
const result = await runCli([
'find',
SAMPLE_DOC,
'--query-json',
JSON.stringify({
select: { type: 'text', pattern: 'Wilde' },
include: ['context'],
}),
]);
expect(result.code).toBe(1);
const envelope = parseJsonOutput<ErrorEnvelope>(result);
expect(envelope.error.code).toBe('VALIDATION_ERROR');
expect(envelope.error.message).toContain('query.include');
});
test('find text queries return block addresses with node projections', async () => {
const result = await runCli([
'find',
SAMPLE_DOC,
'--query-json',
JSON.stringify({
select: { type: 'text', pattern: 'Wilde' },
limit: 1,
}),
]);
expect(result.code).toBe(0);
const envelope = parseJsonOutput<
SuccessEnvelope<{
result: {
items?: Array<{
node?: { kind?: string };
address?: { kind?: string; nodeType?: string; nodeId?: string };
}>;
};
}>
>(result);
const firstItem = envelope.data.result.items?.[0];
expect(firstItem).toBeDefined();
expect(firstItem?.address?.kind).toBe('block');
expect(firstItem?.address?.nodeType).toBeDefined();
expect(firstItem?.address?.nodeId).toBeDefined();
expect(firstItem?.node?.kind).toBeDefined();
});
test('get-node resolves address returned by find', async () => {
const findResult = await runCli(['find', SAMPLE_DOC, '--type', 'node', '--node-type', 'paragraph', '--limit', '1']);
expect(findResult.code).toBe(0);
const findEnvelope = parseJsonOutput<
SuccessEnvelope<{
result: {
items: Array<{ address: Record<string, unknown> }>;
};
}>
>(findResult);
const address = findEnvelope.data.result.items[0]?.address;
expect(address).toBeDefined();
// find returns NodeAddress with kind: 'block' for block-level nodes
const nodeId = address?.nodeId as string;
expect(nodeId).toBeDefined();
const getNodeResult = await runCli([
'get-node',
SAMPLE_DOC,
'--address-json',
JSON.stringify({ kind: 'block', nodeType: 'paragraph', nodeId }),
]);
expect(getNodeResult.code).toBe(0);
const nodeEnvelope = parseJsonOutput<SuccessEnvelope<{ node: unknown }>>(getNodeResult);
expect(nodeEnvelope.ok).toBe(true);
expect(nodeEnvelope.command).toBe('get-node');
expect(nodeEnvelope.data.node).toBeDefined();
});
test('get-node pretty includes resolved identity and optional node details', async () => {
const findResult = await runCli(['find', SAMPLE_DOC, '--type', 'node', '--node-type', 'paragraph', '--limit', '1']);
expect(findResult.code).toBe(0);
const findEnvelope = parseJsonOutput<
SuccessEnvelope<{
result: {
items: Array<{ address: Record<string, unknown> }>;
};
}>
>(findResult);
const address = findEnvelope.data.result.items[0]?.address;
expect(address).toBeDefined();
if (!address) return;
const nodeId = address.nodeId as string;
const blockAddress = { kind: 'block', nodeType: 'paragraph', nodeId };
const prettyResult = await runCli([
'get-node',
SAMPLE_DOC,
'--address-json',
JSON.stringify(blockAddress),
'--output',
'pretty',
]);
expect(prettyResult.code).toBe(0);
expect(prettyResult.stdout).toContain('Revision 0:');
const jsonResult = await runCli(['get-node', SAMPLE_DOC, '--address-json', JSON.stringify(blockAddress)]);
expect(jsonResult.code).toBe(0);
const jsonEnvelope = parseJsonOutput<SuccessEnvelope<{ node: unknown }>>(jsonResult);
const node = asRecord(jsonEnvelope.data.node);
// SDNodeResult: node is under result.node (which contains { kind, ... })
const sdNode = asRecord(node?.node) ?? node;
if (sdNode && typeof sdNode.kind === 'string') {
expect(prettyResult.stdout).toContain('Revision 0:');
}
});
test('get-node-by-id resolves block ID returned by find', async () => {
const findResult = await runCli(['find', SAMPLE_DOC, '--type', 'node', '--node-type', 'paragraph', '--limit', '1']);
expect(findResult.code).toBe(0);
const findEnvelope = parseJsonOutput<
SuccessEnvelope<{
result: {
items: Array<{ node: { kind: string }; address: { kind: string; nodeType: string; nodeId: string } }>;
};
}>
>(findResult);
const firstItem = findEnvelope.data.result.items[0];
expect(firstItem.address.kind).toBe('block');
const getByIdResult = await runCli([
'get-node-by-id',
SAMPLE_DOC,
'--id',
firstItem.address.nodeId,
'--node-type',
firstItem.node.kind,
]);
expect(getByIdResult.code).toBe(0);
const envelope = parseJsonOutput<SuccessEnvelope<{ node: unknown }>>(getByIdResult);
expect(envelope.command).toBe('get-node-by-id');
expect(envelope.data.node).toBeDefined();
});
test('get-node-by-id pretty includes resolved identity and optional node details', async () => {
const findResult = await runCli(['find', SAMPLE_DOC, '--type', 'node', '--node-type', 'paragraph', '--limit', '1']);
expect(findResult.code).toBe(0);
const findEnvelope = parseJsonOutput<
SuccessEnvelope<{
result: {
items: Array<{ node: { kind: string }; address: { kind: string; nodeType: string; nodeId: string } }>;
};
}>
>(findResult);
const firstItem = findEnvelope.data.result.items[0];
expect(firstItem.address.kind).toBe('block');
const prettyResult = await runCli([
'get-node-by-id',
SAMPLE_DOC,
'--id',
firstItem.address.nodeId,
'--node-type',
firstItem.node.kind,
'--output',
'pretty',
]);
expect(prettyResult.code).toBe(0);
expect(prettyResult.stdout).toContain('Revision 0:');
const jsonResult = await runCli([
'get-node-by-id',
SAMPLE_DOC,
'--id',
firstItem.address.nodeId,
'--node-type',
firstItem.node.kind,
]);
expect(jsonResult.code).toBe(0);
const jsonEnvelope = parseJsonOutput<SuccessEnvelope<{ node: unknown }>>(jsonResult);
expect(jsonEnvelope.data.node).toBeDefined();
});
test('replace dry-run does not write output file', async () => {
const target = await firstTextRange(['find', SAMPLE_DOC, '--type', 'text', '--pattern', 'Wilde']);
const dryRunOut = join(TEST_DIR, 'dry-run.docx');
const result = await runCli([
'replace',
SAMPLE_DOC,
'--target-json',
JSON.stringify(target),
'--text',
'WILDE_DRY_RUN',
'--out',
dryRunOut,
'--dry-run',
]);
expect(result.code).toBe(0);
const envelope = parseJsonOutput<SuccessEnvelope<{ dryRun: boolean }>>(result);
expect(envelope.ok).toBe(true);
expect(envelope.data.dryRun).toBe(true);
await expect(access(dryRunOut)).rejects.toThrow();
});
test('replace writes output and updates text target', async () => {
const replaceSource = join(TEST_DIR, 'replace-source.docx');
const replaceOut = join(TEST_DIR, 'replace-out.docx');
await copyFile(SAMPLE_DOC, replaceSource);
const target = await firstTextRange(['find', replaceSource, '--type', 'text', '--pattern', 'Wilde']);
const replaceResult = await runCli([
'replace',
replaceSource,
'--target-json',
JSON.stringify(target),
'--text',
'WILDE_CLI',
'--out',
replaceOut,
]);
expect(replaceResult.code).toBe(0);
const verifyResult = await runCli(['find', replaceOut, '--type', 'text', '--pattern', 'WILDE_CLI']);
expect(verifyResult.code).toBe(0);
const verifyEnvelope = parseJsonOutput<
SuccessEnvelope<{
result: { total: number };
}>
>(verifyResult);
expect(verifyEnvelope.data.result.total).toBeGreaterThan(0);
});
test('insert writes output and adds text at target', async () => {
const insertSource = join(TEST_DIR, 'insert-source.docx');
const insertOut = join(TEST_DIR, 'insert-out.docx');
await copyFile(SAMPLE_DOC, insertSource);
const target = await firstTextRange(['find', insertSource, '--type', 'text', '--pattern', 'Wilde']);
const collapsedTarget: TextRange = {
...target,
range: {
start: target.range.start,
end: target.range.start,
},
};
const insertResult = await runCli([
'insert',
insertSource,
'--target-json',
JSON.stringify(collapsedTarget),
'--value',
'CLI_INSERT_TOKEN_1597',
'--out',
insertOut,
]);
expect(insertResult.code).toBe(0);
const verifyResult = await runCli(['find', insertOut, '--type', 'text', '--pattern', 'CLI_INSERT_TOKEN_1597']);
expect(verifyResult.code).toBe(0);
const verifyEnvelope = parseJsonOutput<SuccessEnvelope<{ result: { total: number } }>>(verifyResult);
expect(verifyEnvelope.data.result.total).toBeGreaterThan(0);
});
test('insert without target defaults to document-start insertion', async () => {
const insertSource = join(TEST_DIR, 'insert-default-source.docx');
const insertOut = join(TEST_DIR, 'insert-default-out.docx');
await copyFile(SAMPLE_DOC, insertSource);
const insertResult = await runCli([
'insert',
insertSource,
'--value',
'CLI_DEFAULT_INSERT_TOKEN_1597',
'--out',
insertOut,
]);
expect(insertResult.code).toBe(0);
const insertEnvelope = parseJsonOutput<MutationReceiptEnvelope>(insertResult);
expect(insertEnvelope.data.receipt.success).toBe(true);
const target = insertEnvelope.data.receipt.resolution?.target;
expect(target?.kind).toBe('text');
expect(target?.blockId).toBeDefined();
expect(target?.range.start).toBe(0);
expect(target?.range.end).toBe(0);
const verifyResult = await runCli([
'find',
insertOut,
'--type',
'text',
'--pattern',
'CLI_DEFAULT_INSERT_TOKEN_1597',
]);
expect(verifyResult.code).toBe(0);
const verifyEnvelope = parseJsonOutput<SuccessEnvelope<{ result: { total: number } }>>(verifyResult);