@wae/open-word 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,38 @@
1
- # Temporary Holding Version
1
+ # @wae/open-word
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A session-oriented TypeScript API and the `open-word` CLI for creating, revising, inspecting and exporting Word-compatible documents.
4
+
5
+ [Product overview](../../../readme.md) · [Agent reference](../../../documentation/agents.md)
6
+
7
+ ## API surface
8
+
9
+ `new OpenWord(options?)` is the entry point. Construction is synchronous and opens no file, window or socket; every operation is async and reports a revision.
10
+
11
+ - **Session:** `capabilities()`, `create({ title, template, author })`, `open({ path, intent })`, `save(target, { overwrite })`, `dispose()`
12
+ - **Read:** `stats()`, `outline()`, `find(query, { limit })`
13
+ - **Edit:** `edit(operations, { expectedRevision })`, `replace(find, replacement, { caseSensitive, wholeWord, regex, limit, expectedRevision })`, `undo({ steps })`, `redo({ steps })`, `merge(path, { mode: 'append' })`
14
+ - **Templates:** `template` on `create()` starts from an existing document, and `edit([{ type: 'template.fill', values }])` substitutes `{{key}}` placeholders.
15
+ - **Review and delivery:** `inspect({ path }, { checks })`, `export({ format, target, overwrite })`
16
+ - **CLI:** `open-word capabilities | create | open | save | inspect | find | stats | outline | edit | replace | template | undo | redo | merge | export | gui`
17
+
18
+ An edit batch is validated as a whole before the first mutation, and each applied operation advances the revision once. `expectedRevision` rejects a stale write with `document/revision-conflict`.
19
+
20
+ ## Example
21
+
22
+ ```ts
23
+ import { OpenWord } from '@wae/open-word';
24
+
25
+ const word = new OpenWord();
26
+ await word.create({ title: 'Account review' });
27
+ await word.edit([{ type: 'heading.append', level: 1, text: 'Summary' }]);
28
+ await word.replace('draft', 'final', { wholeWord: true });
29
+ const { revision } = await word.export({ format: 'docx', target: 'account-review.docx' });
30
+ console.log(`exported revision ${revision}`);
31
+ await word.dispose();
32
+ ```
33
+
34
+ ## Related packages
35
+
36
+ - [`@wae/open-word-skills`](../open-word-skills/README.md) — agent skill documents.
37
+ - [`@wae/open-word-ui`](../open-word-ui/README.md) — OpenWord Studio.
38
+ - Platform addons `@wae/open-word-<platform>-<arch>` are installed automatically as optional dependencies.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Command-line assembly only.
4
+ *
5
+ * Every command maps options onto one method of `new OpenWord()`; document
6
+ * semantics, saving and export stay native. Help text and errors come from
7
+ * `@wae/commander`, so the CLI does not grow its own parser.
8
+ */
9
+ declare const cli: import("@wae/commander").Cli;
10
+ export { cli };
package/dist/cli.js ADDED
@@ -0,0 +1,608 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Command-line assembly only.
4
+ *
5
+ * Every command maps options onto one method of `new OpenWord()`; document
6
+ * semantics, saving and export stay native. Help text and errors come from
7
+ * `@wae/commander`, so the CLI does not grow its own parser.
8
+ */
9
+ import path from 'node:path';
10
+ import { fileURLToPath, pathToFileURL } from 'node:url';
11
+ import { createCli } from '@wae/commander';
12
+ import { OpenWord } from './open-word.js';
13
+ import { runGui } from './gui.js';
14
+ const here = path.dirname(fileURLToPath(import.meta.url));
15
+ const cli = createCli('open-word').locales(path.join(here, '..', 'locales')).intro('cli.intro');
16
+ /** Runs `work` against one session and always releases its handles. */
17
+ async function withSession(work) {
18
+ const word = new OpenWord();
19
+ try {
20
+ return await work(word);
21
+ }
22
+ finally {
23
+ await word.dispose();
24
+ }
25
+ }
26
+ // Exported for contract audits that import the built entry to inspect the
27
+ // command tree. Nothing runs until the file is executed as the program entry.
28
+ export { cli };
29
+ const text = (options, key) => typeof options[key] === 'string' ? options[key] : undefined;
30
+ const texts = (options, key) => {
31
+ const value = options[key];
32
+ return Array.isArray(value) ? value.filter((entry) => typeof entry === 'string') : [];
33
+ };
34
+ const flag = (options, key) => options[key] === true || options[key] === 'true';
35
+ const input = (options) => options._?.[0];
36
+ function parseInteger(value) {
37
+ if (value === undefined) {
38
+ return undefined;
39
+ }
40
+ const parsed = Number.parseInt(value, 10);
41
+ return Number.isInteger(parsed) && parsed >= 0 ? parsed : undefined;
42
+ }
43
+ function parseRows(value) {
44
+ let parsed;
45
+ try {
46
+ parsed = JSON.parse(value);
47
+ }
48
+ catch {
49
+ return undefined;
50
+ }
51
+ if (!Array.isArray(parsed) || parsed.length === 0) {
52
+ return undefined;
53
+ }
54
+ const rows = [];
55
+ for (const row of parsed) {
56
+ if (!Array.isArray(row) || row.length === 0) {
57
+ return undefined;
58
+ }
59
+ const cells = [];
60
+ for (const cell of row) {
61
+ if (typeof cell !== 'string') {
62
+ return undefined;
63
+ }
64
+ cells.push(cell);
65
+ }
66
+ rows.push(cells);
67
+ }
68
+ return rows;
69
+ }
70
+ function parseValues(value) {
71
+ if (value === undefined) {
72
+ return undefined;
73
+ }
74
+ let parsed;
75
+ try {
76
+ parsed = JSON.parse(value);
77
+ }
78
+ catch {
79
+ return undefined;
80
+ }
81
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
82
+ return undefined;
83
+ }
84
+ const entries = Object.entries(parsed);
85
+ if (entries.length === 0) {
86
+ return undefined;
87
+ }
88
+ const values = {};
89
+ for (const [key, entry] of entries) {
90
+ if (typeof entry !== 'string' && typeof entry !== 'number' && typeof entry !== 'boolean') {
91
+ return undefined;
92
+ }
93
+ values[key] = entry;
94
+ }
95
+ return values;
96
+ }
97
+ function describeCapabilities(matrix) {
98
+ const formats = Object.entries(matrix.formats)
99
+ .filter(([, entry]) => entry.import === 'supported')
100
+ .map(([name]) => name);
101
+ const checks = Object.entries(matrix.checks)
102
+ .filter(([, level]) => level === 'supported')
103
+ .map(([name]) => name);
104
+ return [
105
+ `engine: ${matrix.engine.package} ${matrix.engine.version}`,
106
+ `project: ${matrix.project}`,
107
+ `document formats: ${formats.length > 0 ? formats.join(', ') : 'none supported'}`,
108
+ `checks: ${checks.length > 0 ? checks.join(', ') : 'none supported'}`,
109
+ ].join('\n');
110
+ }
111
+ function describeDocument(document) {
112
+ return [
113
+ `document ${document.id} revision=${document.revision} sections=${document.sections.length} paragraphs=${document.paragraphs.length} tables=${document.tables.length}`,
114
+ ` title: ${document.title ?? '(none)'}`,
115
+ ].join('\n');
116
+ }
117
+ function describeReport(report) {
118
+ const lines = [`inspect revision=${report.revision} checker=${report.checkerVersion} passed=${report.passed}`];
119
+ for (const issue of report.issues) {
120
+ lines.push(` ${issue.severity} ${issue.code} ${issue.sectionId ?? '-'} ${issue.message}`);
121
+ }
122
+ return lines.join('\n');
123
+ }
124
+ function describeExport(report) {
125
+ return `export ${report.format} -> ${report.target} revision=${report.revision} editable=${report.editable} losses=${report.losses.length}`;
126
+ }
127
+ function describeStats(report) {
128
+ const headings = Object.entries(report.headings)
129
+ .filter(([, count]) => count > 0)
130
+ .map(([level, count]) => `h${level}=${count}`)
131
+ .join(', ');
132
+ return [
133
+ `revision=${report.revision} blocks=${report.blocks} paragraphs=${report.paragraphs} tables=${report.tables} rows=${report.tableRows}`,
134
+ `headings: ${headings.length > 0 ? headings : 'none'}`,
135
+ `words=${report.words} characters=${report.characters} (${report.charactersWithoutWhitespace} without spaces) reading=${report.readingMinutes} min`,
136
+ ].join('\n');
137
+ }
138
+ function describeOutline(report) {
139
+ const lines = [`revision=${report.revision} headings=${countOutline(report.items)}`];
140
+ const walk = (items, depth) => {
141
+ for (const item of items) {
142
+ const title = item.title ?? '(untitled)';
143
+ lines.push(`${' '.repeat(depth)}h${item.level} ${title} [${item.id} @${item.blockIndex}]`);
144
+ walk(item.children, depth + 1);
145
+ }
146
+ };
147
+ walk(report.items, 0);
148
+ return lines.join('\n');
149
+ }
150
+ function countOutline(items) {
151
+ return items.reduce((total, item) => total + 1 + countOutline(item.children), 0);
152
+ }
153
+ function parseSteps(options) {
154
+ const value = text(options, 'steps');
155
+ if (value === undefined) {
156
+ return undefined;
157
+ }
158
+ const steps = parseInteger(value);
159
+ return steps !== undefined && steps > 0 ? steps : null;
160
+ }
161
+ async function persistProject(file, word) {
162
+ return path.extname(file).toLowerCase() === '.oword' ? word.save(file, { overwrite: true }) : undefined;
163
+ }
164
+ function describeHistory(saved) {
165
+ return saved === undefined
166
+ ? '\n history is session-local: a freshly opened document has an empty history'
167
+ : `\n saved: ${saved.path} (${saved.bytes} bytes)`;
168
+ }
169
+ function describeHits(hits) {
170
+ if (hits.length === 0) {
171
+ return 'no matches';
172
+ }
173
+ return [
174
+ `${hits.length} match(es)`,
175
+ ...hits.map((hit) => ` ${hit.blockId} [${hit.start}, ${hit.end}) ${hit.text}`),
176
+ ].join('\n');
177
+ }
178
+ cli.command('capabilities', 'cli.cmd.capabilities').actionCtx(async (_options, _args, ctx) => {
179
+ const matrix = await withSession((word) => word.capabilities());
180
+ ctx.emitResult(matrix, describeCapabilities(matrix));
181
+ return 0;
182
+ });
183
+ cli
184
+ .command('create', 'cli.cmd.create')
185
+ .option('--out <file>', 'cli.opt.out')
186
+ .option('--title <title>', 'cli.opt.title')
187
+ .option('--template <file>', 'cli.opt.template')
188
+ .option('--overwrite', 'cli.opt.overwrite')
189
+ .actionCtx(async (options, _args, ctx) => {
190
+ const out = text(options, 'out');
191
+ if (out === undefined) {
192
+ ctx.fail('open-word.cli.out-required', { message: '`--out <file>` is required' });
193
+ return 2;
194
+ }
195
+ await withSession(async (word) => {
196
+ const document = await word.create({ title: text(options, 'title'), template: text(options, 'template') });
197
+ const report = await word.save(out, { overwrite: flag(options, 'overwrite') });
198
+ ctx.emitResult({ ...report, document }, `created ${out} revision=${report.revision}`);
199
+ });
200
+ return 0;
201
+ });
202
+ cli
203
+ .command('open', 'cli.cmd.open')
204
+ .actionCtx(async (options, _args, ctx) => {
205
+ const file = input(options);
206
+ if (file === undefined) {
207
+ ctx.fail('open-word.cli.file-required', { message: 'a document file is required' });
208
+ return 2;
209
+ }
210
+ await withSession(async (word) => {
211
+ const document = await word.open({ path: file });
212
+ ctx.emitResult(document, describeDocument(document));
213
+ });
214
+ return 0;
215
+ });
216
+ cli
217
+ .command('save', 'cli.cmd.save')
218
+ .option('--out <file>', 'cli.opt.out')
219
+ .option('--overwrite', 'cli.opt.overwrite')
220
+ .actionCtx(async (options, _args, ctx) => {
221
+ const file = input(options);
222
+ if (file === undefined) {
223
+ ctx.fail('open-word.cli.file-required', { message: 'a document file is required' });
224
+ return 2;
225
+ }
226
+ const out = text(options, 'out');
227
+ if (out === undefined) {
228
+ ctx.fail('open-word.cli.out-required', { message: '`--out <file>` is required' });
229
+ return 2;
230
+ }
231
+ await withSession(async (word) => {
232
+ await word.open({ path: file });
233
+ const report = await word.save(out, { overwrite: flag(options, 'overwrite') });
234
+ ctx.emitResult(report, `saved ${out} revision=${report.revision} bytes=${report.bytes}`);
235
+ });
236
+ return 0;
237
+ });
238
+ cli
239
+ .command('inspect', 'cli.cmd.inspect')
240
+ .option('--checks <list>', 'cli.opt.checks')
241
+ .actionCtx(async (options, _args, ctx) => {
242
+ const file = input(options);
243
+ if (file === undefined) {
244
+ ctx.fail('open-word.cli.file-required', { message: 'a document file is required' });
245
+ return 2;
246
+ }
247
+ const checks = text(options, 'checks')
248
+ ?.split(',')
249
+ .map((name) => name.trim())
250
+ .filter((name) => name.length > 0);
251
+ let passed = false;
252
+ await withSession(async (word) => {
253
+ const report = await word.inspect({ path: file }, { checks });
254
+ ctx.emitResult(report, describeReport(report));
255
+ passed = report.passed;
256
+ });
257
+ return passed ? 0 : 1;
258
+ });
259
+ cli
260
+ .command('find', 'cli.cmd.find')
261
+ .option('--limit <count>', 'cli.opt.limit')
262
+ .actionCtx(async (options, _args, ctx) => {
263
+ const file = input(options);
264
+ const query = options._?.[1];
265
+ if (file === undefined || query === undefined || query.length === 0) {
266
+ ctx.fail('open-word.cli.find-args', { message: 'a document file and a non-empty query are required' });
267
+ return 2;
268
+ }
269
+ const limitText = text(options, 'limit');
270
+ const limit = limitText === undefined ? undefined : parseInteger(limitText);
271
+ if (limitText !== undefined && (limit === undefined || limit < 1)) {
272
+ ctx.fail('open-word.cli.find-limit', { message: '`--limit <count>` must be a positive integer' });
273
+ return 2;
274
+ }
275
+ await withSession(async (word) => {
276
+ const hits = await word.open({ path: file }).then(() => word.find(query, { limit }));
277
+ ctx.emitResult(hits, describeHits(hits));
278
+ });
279
+ return 0;
280
+ });
281
+ cli.command('stats', 'cli.cmd.stats').actionCtx(async (options, _args, ctx) => {
282
+ const file = input(options);
283
+ if (file === undefined) {
284
+ ctx.fail('open-word.cli.file-required', { message: 'a document file is required' });
285
+ return 2;
286
+ }
287
+ await withSession(async (word) => {
288
+ await word.open({ path: file });
289
+ const report = await word.stats();
290
+ ctx.emitResult(report, describeStats(report));
291
+ });
292
+ return 0;
293
+ });
294
+ cli.command('outline', 'cli.cmd.outline').actionCtx(async (options, _args, ctx) => {
295
+ const file = input(options);
296
+ if (file === undefined) {
297
+ ctx.fail('open-word.cli.file-required', { message: 'a document file is required' });
298
+ return 2;
299
+ }
300
+ await withSession(async (word) => {
301
+ await word.open({ path: file });
302
+ const report = await word.outline();
303
+ ctx.emitResult(report, describeOutline(report));
304
+ });
305
+ return 0;
306
+ });
307
+ cli
308
+ .command('edit', 'cli.cmd.edit')
309
+ .option('--paragraph <text>', 'cli.opt.paragraph')
310
+ .option('--heading <text>', 'cli.opt.heading')
311
+ .option('--heading-id <id>', 'cli.opt.headingId')
312
+ .option('--level <level>', 'cli.opt.level')
313
+ .option('--bullet <text>...', 'cli.opt.bullet')
314
+ .option('--numbered <text>...', 'cli.opt.numbered')
315
+ .option('--numbered-start <n>', 'cli.opt.numberedStart')
316
+ .option('--task <text>...', 'cli.opt.task')
317
+ .option('--task-done <text>...', 'cli.opt.taskDone')
318
+ .option('--quote <text>', 'cli.opt.quote')
319
+ .option('--code <text>', 'cli.opt.code')
320
+ .option('--code-lang <lang>', 'cli.opt.codeLang')
321
+ .option('--table <json>', 'cli.opt.table')
322
+ .option('--duplicate-block <id>', 'cli.opt.duplicateBlock')
323
+ .option('--title <title>', 'cli.opt.title')
324
+ .option('--author <author>', 'cli.opt.author')
325
+ .option('--expected-revision <revision>', 'cli.opt.expectedRevision')
326
+ .option('--out <file>', 'cli.opt.out')
327
+ .option('--overwrite', 'cli.opt.overwrite')
328
+ .actionCtx(async (options, _args, ctx) => {
329
+ const file = input(options);
330
+ if (file === undefined) {
331
+ ctx.fail('open-word.cli.file-required', { message: 'a document file is required' });
332
+ return 2;
333
+ }
334
+ const operations = [];
335
+ const paragraph = text(options, 'paragraph');
336
+ if (paragraph !== undefined) {
337
+ operations.push({ type: 'paragraph.append', text: paragraph });
338
+ }
339
+ const heading = text(options, 'heading');
340
+ if (heading !== undefined) {
341
+ const level = parseInteger(text(options, 'level') ?? '1');
342
+ if (level === undefined || level < 1 || level > 6) {
343
+ ctx.fail('open-word.cli.edit-level', { message: '`--level <level>` must be between 1 and 6' });
344
+ return 2;
345
+ }
346
+ operations.push({ type: 'heading.append', level, text: heading });
347
+ }
348
+ const headingId = text(options, 'heading-id');
349
+ if (headingId !== undefined) {
350
+ const levelText = text(options, 'level');
351
+ if (levelText === undefined) {
352
+ ctx.fail('open-word.cli.edit-level', { message: '`--heading-id` requires `--level <1..6>`' });
353
+ return 2;
354
+ }
355
+ const level = parseInteger(levelText);
356
+ if (level === undefined || level < 1 || level > 6) {
357
+ ctx.fail('open-word.cli.edit-level', { message: '`--level <level>` must be between 1 and 6' });
358
+ return 2;
359
+ }
360
+ operations.push({ type: 'heading.setLevel', id: headingId, level });
361
+ }
362
+ const bullets = texts(options, 'bullet');
363
+ if (bullets.length > 0) {
364
+ operations.push({ type: 'list.append', ordered: false, items: bullets });
365
+ }
366
+ const numbered = texts(options, 'numbered');
367
+ const numberedStartText = text(options, 'numbered-start');
368
+ const numberedStart = numberedStartText === undefined ? undefined : parseInteger(numberedStartText);
369
+ if (numberedStartText !== undefined && (numberedStart === undefined || numberedStart < 1)) {
370
+ ctx.fail('open-word.cli.edit-numbered-start', { message: '`--numbered-start <n>` must be a positive integer' });
371
+ return 2;
372
+ }
373
+ if (numberedStartText !== undefined && numbered.length === 0) {
374
+ ctx.fail('open-word.cli.edit-numbered-start', { message: '`--numbered-start <n>` requires `--numbered`' });
375
+ return 2;
376
+ }
377
+ if (numbered.length > 0) {
378
+ operations.push({
379
+ type: 'list.append',
380
+ ordered: true,
381
+ items: numbered,
382
+ ...(numberedStart === undefined ? {} : { start: numberedStart }),
383
+ });
384
+ }
385
+ const tasks = [
386
+ ...texts(options, 'task').map((text) => ({ text })),
387
+ ...texts(options, 'task-done').map((text) => ({ text, checked: true })),
388
+ ];
389
+ if (tasks.length > 0) {
390
+ operations.push({ type: 'taskList.append', items: tasks });
391
+ }
392
+ const quote = text(options, 'quote');
393
+ if (quote !== undefined) {
394
+ operations.push({ type: 'quote.append', text: quote });
395
+ }
396
+ const code = text(options, 'code');
397
+ const codeLang = text(options, 'code-lang');
398
+ if (codeLang !== undefined && code === undefined) {
399
+ ctx.fail('open-word.cli.edit-code-lang', { message: '`--code-lang <lang>` requires `--code`' });
400
+ return 2;
401
+ }
402
+ if (code !== undefined) {
403
+ operations.push({ type: 'code.append', text: code, ...(codeLang === undefined ? {} : { language: codeLang }) });
404
+ }
405
+ const table = text(options, 'table');
406
+ if (table !== undefined) {
407
+ const rows = parseRows(table);
408
+ if (rows === undefined) {
409
+ ctx.fail('open-word.cli.edit-table', { message: '`--table <json>` must be an array of string rows' });
410
+ return 2;
411
+ }
412
+ operations.push({ type: 'table.append', rows });
413
+ }
414
+ const duplicateBlock = text(options, 'duplicate-block');
415
+ if (duplicateBlock !== undefined) {
416
+ operations.push({ type: 'block.duplicate', id: duplicateBlock });
417
+ }
418
+ const title = text(options, 'title');
419
+ const author = text(options, 'author');
420
+ if (title !== undefined || author !== undefined) {
421
+ operations.push({ type: 'metadata.set', title, author });
422
+ }
423
+ if (operations.length === 0) {
424
+ ctx.fail('open-word.cli.edit-args', {
425
+ message: 'pass at least one of `--paragraph`, `--heading`, `--heading-id`, `--bullet`, `--numbered`, `--quote`, `--code`, `--table`, `--duplicate-block`, `--title` or `--author`',
426
+ });
427
+ return 2;
428
+ }
429
+ const revisionText = text(options, 'expected-revision');
430
+ const expectedRevision = revisionText === undefined ? undefined : parseInteger(revisionText);
431
+ if (revisionText !== undefined && expectedRevision === undefined) {
432
+ ctx.fail('open-word.cli.edit-revision', { message: '`--expected-revision` must be a non-negative integer' });
433
+ return 2;
434
+ }
435
+ await withSession(async (word) => {
436
+ await word.open({ path: file });
437
+ const report = await word.edit(operations, { expectedRevision });
438
+ const out = text(options, 'out');
439
+ if (out !== undefined) {
440
+ const saved = await word.save(out, { overwrite: flag(options, 'overwrite') });
441
+ ctx.emitResult({ ...report, saved }, `${describeDocument(report.document)}\n saved: ${saved.path} (${saved.bytes} bytes)`);
442
+ }
443
+ else {
444
+ ctx.emitResult(report, describeDocument(report.document));
445
+ }
446
+ });
447
+ return 0;
448
+ });
449
+ cli
450
+ .command('replace', 'cli.cmd.replace')
451
+ .option('--find <text>', 'cli.opt.find')
452
+ .option('--with <text>', 'cli.opt.with')
453
+ .option('--ignore-case', 'cli.opt.ignoreCase')
454
+ .option('--whole-word', 'cli.opt.wholeWord')
455
+ .option('--regex', 'cli.opt.regex')
456
+ .option('--out <file>', 'cli.opt.out')
457
+ .option('--overwrite', 'cli.opt.overwrite')
458
+ .actionCtx(async (options, _args, ctx) => {
459
+ const file = input(options);
460
+ if (file === undefined) {
461
+ ctx.fail('open-word.cli.file-required', { message: 'a document file is required' });
462
+ return 2;
463
+ }
464
+ const find = text(options, 'find');
465
+ const replacement = text(options, 'with');
466
+ if (find === undefined || find.length === 0 || replacement === undefined) {
467
+ ctx.fail('open-word.cli.replace-args', { message: '`--find <text>` and `--with <text>` are required' });
468
+ return 2;
469
+ }
470
+ await withSession(async (word) => {
471
+ await word.open({ path: file });
472
+ const report = await word.replace(find, replacement, {
473
+ caseSensitive: !flag(options, 'ignore-case'),
474
+ wholeWord: flag(options, 'whole-word'),
475
+ regex: flag(options, 'regex'),
476
+ });
477
+ const replaced = report.replaced;
478
+ const out = text(options, 'out');
479
+ if (out !== undefined) {
480
+ const saved = await word.save(out, { overwrite: flag(options, 'overwrite') });
481
+ ctx.emitResult({ ...report, saved }, `${describeDocument(report.document)}\n replaced: ${replaced}\n saved: ${saved.path} (${saved.bytes} bytes)`);
482
+ }
483
+ else {
484
+ ctx.emitResult(report, `${describeDocument(report.document)}\n replaced: ${replaced}`);
485
+ }
486
+ });
487
+ return 0;
488
+ });
489
+ cli
490
+ .command('template', 'cli.cmd.template')
491
+ .option('--values <json>', 'cli.opt.values')
492
+ .option('--out <file>', 'cli.opt.out')
493
+ .option('--overwrite', 'cli.opt.overwrite')
494
+ .actionCtx(async (options, _args, ctx) => {
495
+ const file = input(options);
496
+ if (file === undefined) {
497
+ ctx.fail('open-word.cli.file-required', { message: 'a document file is required' });
498
+ return 2;
499
+ }
500
+ const values = parseValues(text(options, 'values'));
501
+ if (values === undefined) {
502
+ ctx.fail('open-word.cli.template-values', {
503
+ message: '`--values <json>` must be a non-empty JSON object of string, number or boolean values',
504
+ });
505
+ return 2;
506
+ }
507
+ const out = text(options, 'out');
508
+ if (out === undefined) {
509
+ ctx.fail('open-word.cli.out-required', { message: '`--out <file>` is required' });
510
+ return 2;
511
+ }
512
+ await withSession(async (word) => {
513
+ await word.open({ path: file });
514
+ const report = await word.edit([{ type: 'template.fill', values }]);
515
+ const replaced = report.results[0]?.replaced ?? 0;
516
+ const saved = await word.save(out, { overwrite: flag(options, 'overwrite') });
517
+ ctx.emitResult({ ...report, saved }, `${describeDocument(report.document)}\n replaced: ${replaced}\n saved: ${saved.path} (${saved.bytes} bytes)`);
518
+ });
519
+ return 0;
520
+ });
521
+ for (const action of ['undo', 'redo']) {
522
+ cli
523
+ .command(action, `cli.cmd.${action}`)
524
+ .option('--steps <count>', 'cli.opt.steps')
525
+ .actionCtx(async (options, _args, ctx) => {
526
+ const file = input(options);
527
+ if (file === undefined) {
528
+ ctx.fail('open-word.cli.file-required', { message: 'a document file is required' });
529
+ return 2;
530
+ }
531
+ const steps = parseSteps(options);
532
+ if (steps === null) {
533
+ ctx.fail('open-word.cli.history-steps', { message: '`--steps <count>` must be a positive integer' });
534
+ return 2;
535
+ }
536
+ await withSession(async (word) => {
537
+ await word.open({ path: file });
538
+ const result = action === 'undo' ? await word.undo({ steps }) : await word.redo({ steps });
539
+ const saved = await persistProject(file, word);
540
+ const count = 'undone' in result ? result.undone : result.redone;
541
+ const availability = 'undone' in result
542
+ ? `redoAvailable=${result.redoAvailable}`
543
+ : `undoAvailable=${result.undoAvailable}`;
544
+ ctx.emitResult({ ...result, saved }, `${action} ${count} step(s) -> revision=${result.revision} ${availability}\n${describeDocument(result.document)}${describeHistory(saved)}`);
545
+ });
546
+ return 0;
547
+ });
548
+ }
549
+ cli.command('merge', 'cli.cmd.merge').actionCtx(async (options, _args, ctx) => {
550
+ const file = input(options);
551
+ const other = options._?.[1];
552
+ if (file === undefined || other === undefined || other.length === 0) {
553
+ ctx.fail('open-word.cli.merge-args', { message: 'a document file and another document are required' });
554
+ return 2;
555
+ }
556
+ await withSession(async (word) => {
557
+ await word.open({ path: file });
558
+ const report = await word.merge(other);
559
+ const saved = await persistProject(file, word);
560
+ ctx.emitResult({ ...report, saved }, `merged ${report.blocksAdded} block(s) from ${other}\n${describeDocument(report.summary)}\n losses: ${report.losses.length}${describeHistory(saved)}`);
561
+ });
562
+ return 0;
563
+ });
564
+ cli
565
+ .command('export', 'cli.cmd.export')
566
+ .option('--format <format>', 'cli.opt.format', { enum: ['docx', 'dotx', 'pdf', 'html', 'md', 'txt', 'rtf'] })
567
+ .option('--out <file>', 'cli.opt.out')
568
+ .option('--overwrite', 'cli.opt.overwrite')
569
+ .actionCtx(async (options, _args, ctx) => {
570
+ const file = input(options);
571
+ if (file === undefined) {
572
+ ctx.fail('open-word.cli.file-required', { message: 'a document file is required' });
573
+ return 2;
574
+ }
575
+ const format = text(options, 'format');
576
+ const out = text(options, 'out');
577
+ if (format === undefined || out === undefined) {
578
+ ctx.fail('open-word.cli.export-args', { message: '`--format <format>` and `--out <file>` are required' });
579
+ return 2;
580
+ }
581
+ await withSession(async (word) => {
582
+ await word.open({ path: file });
583
+ const report = await word.export({
584
+ format: format,
585
+ target: out,
586
+ overwrite: flag(options, 'overwrite'),
587
+ });
588
+ ctx.emitResult(report, describeExport(report));
589
+ });
590
+ return 0;
591
+ });
592
+ cli.command('gui', 'cli.cmd.gui').actionCtx(async (_options, _args, ctx) => {
593
+ try {
594
+ const status = await runGui({});
595
+ ctx.emitResult(status, `window ${status.state}`);
596
+ return 0;
597
+ }
598
+ catch (error) {
599
+ const message = error instanceof Error ? error.message : String(error);
600
+ ctx.fail('open-word.cli.gui-failed', { message });
601
+ return 1;
602
+ }
603
+ });
604
+ const entry = process.argv[1];
605
+ if (entry !== undefined && import.meta.url === pathToFileURL(entry).href) {
606
+ const code = await cli.parse(process.argv);
607
+ process.exitCode = code;
608
+ }