@workover/cli 0.2.0 → 0.3.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
@@ -14,6 +14,10 @@ npm i -g @workover/cli
14
14
  workover login # sign in (opens your browser to approve)
15
15
  workover login --publish # ...and also request permission to publish to WordPress
16
16
  workover login --draft # ...and also request permission to write drafts with AI
17
+ workover login --write # ...and also allow direct edits, with no suggestions to review
18
+ workover projects # the projects you can reach, with their ids
19
+ workover doc list --project 11
20
+ workover doc read 1234
17
21
  workover draft --org 3 --project 11 "Document the billing flow"
18
22
  workover whoami # show the current sign-in
19
23
  workover logout # sign out and revoke this device's token
@@ -21,12 +25,54 @@ workover logout # sign out and revoke this device's token
21
25
 
22
26
  `workover login` uses the browser device-authorization flow: it prints a short code, opens your browser, and you approve the connection while signed in to Workover. The token is stored at `~/.workover/config.json` (owner-only) and can be revoked anytime in **Workover → Settings → Developer**.
23
27
 
24
- A connected tool can read your documents and propose changes as suggestions you review. By default it **cannot** publish to WordPress.
28
+ A connected tool can read your documents, create new ones, and propose changes as suggestions you review. By default it **cannot** publish to WordPress, and it **cannot** edit an existing document without leaving you something to accept.
25
29
 
26
30
  Pass `--publish` if you want the tool to be able to publish to your connected WordPress sites — useful for an agent building out a documentation set rather than editing one. The browser shows exactly what is being granted before you approve, and even a publishing token **cannot** override a "WordPress is newer" conflict: forcing past someone else's edit needs a person who can go and look.
27
31
 
32
+ Pass `--write` if you want the tool to edit documents directly rather than suggesting changes — see
33
+ [Editing directly](#editing-directly) below for when that is the right call.
34
+
28
35
  Whatever you grant, a token can never change your account security, your billing, or your other tokens.
29
36
 
37
+ ## Working on documents
38
+
39
+ `workover doc` is the whole document surface, so signing in and then doing something with a document
40
+ are the same tool. Bodies come from `--file`, or from stdin:
41
+
42
+ ```sh
43
+ workover projects # find the project id
44
+ workover doc list --project 11 # documents in it, with their ids
45
+ workover doc read 1234 # the current text
46
+ workover doc read 1234 --json # ...for a script
47
+
48
+ workover doc create --project 11 --title "Billing" --file billing.md
49
+ cat billing.md | workover doc propose 1234 --note "tightened the intro"
50
+ ```
51
+
52
+ `doc create` writes the content **into** the new document. There is nothing to accept: a document
53
+ that did not exist a moment ago has no earlier version for anybody to review the new text against,
54
+ and asking would leave you accepting your own content against a blank page.
55
+
56
+ `doc propose` is the default for a document that already exists. It leaves tracked-change
57
+ suggestions for a person to accept or reject, which is what you want when the agent is working
58
+ unattended on somebody else's writing.
59
+
60
+ ### Editing directly
61
+
62
+ Sometimes review is the wrong answer: you are working alongside the agent on a document you have
63
+ open, you say "make that change", and fifty tracked suggestions to click through is not a safeguard,
64
+ it is the thing that teaches people to press *Accept all* without reading.
65
+
66
+ ```sh
67
+ workover login --write # once, and the browser says what it grants
68
+ workover doc write 1234 --file rewritten.md --note "as discussed"
69
+ ```
70
+
71
+ `doc write` **replaces the whole body**, so pass the complete document — anything you leave out is
72
+ deleted. Read it first with `workover doc read`. It needs a token from `workover login --write`;
73
+ without that scope it is refused and `doc propose` is the way through. Every direct edit is recorded
74
+ in the workspace's audit log, since unlike a proposal it leaves no review trail of its own.
75
+
30
76
  ## Queueing a draft
31
77
 
32
78
  `workover draft` asks Workover to write something; it does not write it itself. Workover reads the
@@ -56,6 +102,11 @@ claude mcp add workover -- npx -y @workover/mcp
56
102
 
57
103
  Then ask Claude Code to read or revise a document — its edits appear in Workover as tracked-change suggestions you accept or reject.
58
104
 
105
+ The MCP server and `workover doc` do the same things on purpose. A newly-registered MCP server is
106
+ not available in the session that registered it, so an agent that discovers mid-task that it needs
107
+ Workover has no route in until it restarts; a CLI subcommand works the moment the CLI is installed.
108
+ Either surface, same operations, same permissions.
109
+
59
110
  ## Configuration
60
111
 
61
112
  - `WORKOVER_API` — point the CLI at a different Workover API (defaults to `https://api.workover.dev`).
package/bin/workover.mjs CHANGED
@@ -17,6 +17,11 @@ import {
17
17
  browserCommand,
18
18
  pollDecision,
19
19
  summariseEvaluations,
20
+ parseArgs,
21
+ rowId,
22
+ stripHtml,
23
+ documentText,
24
+ contentCommitted,
20
25
  } from '../lib.mjs';
21
26
 
22
27
  // Point at a different API with WORKOVER_API (e.g. https://api.workover.test for local dev).
@@ -67,7 +72,20 @@ const authedCall = async (cfg, path, body) => {
67
72
  });
68
73
  const text = await res.text();
69
74
  if (!res.ok) {
70
- console.error(`\n ✗ ${res.status} ${text.slice(0, 300)}\n`);
75
+ // The API's own sentence when it sent one. Nest puts it in `message`, and the scope refusals
76
+ // in particular are written to tell you what to run next — which the raw JSON buries behind
77
+ // punctuation at exactly the moment somebody is trying to read it.
78
+ let detail = text.slice(0, 300);
79
+ try {
80
+ const parsed = JSON.parse(text);
81
+ const message = Array.isArray(parsed?.message)
82
+ ? parsed.message.join('; ')
83
+ : parsed?.message;
84
+ if (typeof message === 'string' && message) detail = message;
85
+ } catch {
86
+ /* not JSON — the raw prefix above is still better than nothing */
87
+ }
88
+ console.error(`\n ✗ ${res.status} ${detail}\n`);
71
89
  process.exit(1);
72
90
  }
73
91
  return text ? JSON.parse(text) : null;
@@ -81,7 +99,7 @@ const flagValue = (name) => {
81
99
  const requireSignIn = (hint) => {
82
100
  const cfg = loadConfig();
83
101
  if (!cfg?.token) {
84
- console.log(` Not signed in. Run \`workover login ${hint}\`.`);
102
+ console.log(` Not signed in. Run \`${`workover login ${hint || ''}`.trim()}\`.`);
85
103
  process.exit(1);
86
104
  }
87
105
  return cfg;
@@ -95,6 +113,7 @@ async function login() {
95
113
  const scopes = ['read', 'propose'];
96
114
  if (process.argv.includes('--publish')) scopes.push('publish');
97
115
  if (process.argv.includes('--draft')) scopes.push('draft');
116
+ if (process.argv.includes('--write')) scopes.push('write');
98
117
 
99
118
  let start;
100
119
  try {
@@ -116,6 +135,11 @@ async function login() {
116
135
  console.log(' repo-grounded draft also captures screenshots by signing in to your connected');
117
136
  console.log(' app with the credential you stored in Workover.');
118
137
  }
138
+ if (scopes.includes('write')) {
139
+ console.log('\n Requesting permission to EDIT DOCUMENTS DIRECTLY — `workover doc write`');
140
+ console.log(' replaces a document’s body with no suggestions to accept. Without it every');
141
+ console.log(' change is a proposal you review, which is the default and stays available.');
142
+ }
119
143
  console.log(`\n Your login code: \x1b[1m${start.user_code}\x1b[0m`);
120
144
  console.log(` Approve it here: ${start.verification_uri_complete}\n`);
121
145
  console.log(' Opening your browser…');
@@ -482,6 +506,279 @@ async function evaluateDocs() {
482
506
  );
483
507
  }
484
508
 
509
+ // ── Documents ────────────────────────────────────────────────────────────────
510
+ //
511
+ // Why these exist. `login` proved the CLI could reach Workover and then stopped: its verbs were
512
+ // login / logout / whoami / draft / draft-set / eval, so "connect to Workover and write this to a
513
+ // doc" was an instruction the CLI could do the first half of and had no word for the second. Doing
514
+ // it anyway meant reading apps/mcp/lib.mjs for the endpoints, digging the bearer token out of
515
+ // ~/.workover/config.json and hand-rolling curl — which an agent without a checkout of this repo
516
+ // cannot do at all.
517
+ //
518
+ // "Use the MCP server instead" is not an answer to that. A newly-registered MCP server is not
519
+ // available in the session that registered it, so an agent that discovers mid-task that it needs
520
+ // Workover has no route in until it is restarted — and it is mid-task, which is exactly when
521
+ // restarting costs the most. A subcommand works the moment the CLI is installed.
522
+ //
523
+ // So these mirror the MCP tools one for one, deliberately: list, read, create, propose, search. The
524
+ // two surfaces should never be able to do different things, because whichever one an agent reaches
525
+ // for is an accident of how it was set up.
526
+
527
+ /** The markdown body for a write: `--file <path>`, `--file -`, or piped stdin. */
528
+ const readBody = async (flags) => {
529
+ const file = flags.file;
530
+ if (typeof file === 'string' && file !== '-') {
531
+ try {
532
+ return readFileSync(file, 'utf8');
533
+ } catch {
534
+ console.error(`\n ✗ Couldn't read ${file}\n`);
535
+ process.exit(1);
536
+ }
537
+ }
538
+ // Piped input is the natural shape for an agent (a heredoc), so it is accepted without asking.
539
+ // Only when stdin is a terminal is there nothing to read — reading it then would hang forever,
540
+ // looking like a command that had silently stopped.
541
+ if (file === '-' || !process.stdin.isTTY) {
542
+ let body = '';
543
+ for await (const chunk of process.stdin) body += chunk;
544
+ return body;
545
+ }
546
+ return '';
547
+ };
548
+
549
+ /** A document id from the first positional argument, or a usage error naming what to pass. */
550
+ const docIdArg = (positionals, usage) => {
551
+ const id = rowId(positionals[0]);
552
+ if (id === null) {
553
+ console.log(`\n Usage: ${usage}`);
554
+ console.log(' The numeric document id — `workover doc list` prints it as "#123".\n');
555
+ process.exit(1);
556
+ }
557
+ return id;
558
+ };
559
+
560
+ const DOC_USAGE = [
561
+ '',
562
+ ' Usage: workover doc <command>',
563
+ '',
564
+ ' list --project <id> [--json] documents in a project',
565
+ ' read <docId> [--json] [--html] a document’s current text',
566
+ ' create --project <id> --title "<t>" a new document, content written in',
567
+ ' [--file <path> | piped stdin] [--json]',
568
+ ' propose <docId> [--note "<why>"] suggest a rewrite for review',
569
+ ' [--file <path> | piped stdin] [--json]',
570
+ ' write <docId> [--note "<why>"] REPLACE the body, no review step',
571
+ ' [--file <path> | piped stdin] [--json]',
572
+ ' needs `workover login --write`; use it only when asked to',
573
+ ' search "<query>" [--limit N] [--json] find documents by title/content',
574
+ '',
575
+ ' `workover projects` lists the project ids.',
576
+ '',
577
+ ' propose vs write: propose leaves tracked-change suggestions for a person to',
578
+ ' accept, and is the right default when nobody asked for anything else. write',
579
+ ' edits the document then and there — for when the person you are working with',
580
+ ' said to make the change.',
581
+ '',
582
+ ].join('\n');
583
+
584
+ async function docCommand() {
585
+ const sub = process.argv[3];
586
+ // Usage before sign-in: someone who typed the command wrong is asking what the commands are, and
587
+ // answering "not signed in" sends them to fix the wrong thing.
588
+ if (!['list', 'read', 'create', 'propose', 'write', 'search'].includes(sub)) {
589
+ console.log(DOC_USAGE);
590
+ process.exit(sub ? 1 : 0);
591
+ }
592
+ const { flags, positionals } = parseArgs(process.argv.slice(4), {
593
+ booleans: ['json', 'html'],
594
+ });
595
+ const cfg = requireSignIn();
596
+ const asJson = flags.json === true;
597
+
598
+ const projectIdFlag = (usage) => {
599
+ const id = rowId(flags.project);
600
+ if (id === null) {
601
+ console.log(`\n Usage: ${usage}`);
602
+ console.log(' Find the project id with `workover projects`.\n');
603
+ process.exit(1);
604
+ }
605
+ return id;
606
+ };
607
+
608
+ if (sub === 'list') {
609
+ const projectId = projectIdFlag('workover doc list --project <id>');
610
+ const all = (await authedCall(cfg, `/project/${projectId}/documents`)) || [];
611
+ const docs = all.filter((d) => !d.deletedAt);
612
+ if (asJson) return console.log(JSON.stringify(docs, null, 2));
613
+ if (!docs.length) return console.log('\n No documents in that project.\n');
614
+ console.log('');
615
+ for (const d of docs) {
616
+ console.log(
617
+ ` #${String(d.id).padEnd(6)} ${String(d.status || '').padEnd(18)} ${d.title || 'Untitled'}`,
618
+ );
619
+ }
620
+ console.log(`\n ${docs.length} document${docs.length === 1 ? '' : 's'}.\n`);
621
+ return;
622
+ }
623
+
624
+ if (sub === 'read') {
625
+ const docId = docIdArg(positionals, 'workover doc read <docId>');
626
+ const doc = await authedCall(cfg, `/project/doc/${docId}`);
627
+ if (!doc?.id) {
628
+ console.error(`\n ✗ Document ${docId} not found (or no access).\n`);
629
+ process.exit(1);
630
+ }
631
+ if (asJson) return console.log(JSON.stringify(doc, null, 2));
632
+ if (flags.html === true) return console.log(doc.content || '');
633
+ console.log(`\n# ${doc.title || 'Untitled'} (id ${doc.id})\n`);
634
+ console.log(documentText(doc) || '(empty document)');
635
+ console.log('');
636
+ return;
637
+ }
638
+
639
+ if (sub === 'create') {
640
+ const usage = 'workover doc create --project <id> --title "<title>" --file <path>';
641
+ const projectId = projectIdFlag(usage);
642
+ const title = typeof flags.title === 'string' ? flags.title.trim() : '';
643
+ if (!title) {
644
+ console.log(`\n Usage: ${usage}\n`);
645
+ process.exit(1);
646
+ }
647
+ const markdown = (await readBody(flags)).trim();
648
+ if (!markdown) {
649
+ console.log(`\n Usage: ${usage}`);
650
+ console.log(' The body comes from --file, or from stdin:');
651
+ console.log(` echo "# Hello" | ${usage.replace(' --file <path>', '')}\n`);
652
+ process.exit(1);
653
+ }
654
+
655
+ const doc = await authedCall(cfg, `/project/${projectId}/documents`, {
656
+ title,
657
+ markdown,
658
+ });
659
+ if (!doc?.id) {
660
+ console.error('\n ✗ Could not create the document.\n');
661
+ process.exit(1);
662
+ }
663
+
664
+ // The content went WITH the create, so on a current Workover it is simply in the document:
665
+ // there is no earlier version of a document this old for anyone to review it against.
666
+ if (contentCommitted(doc)) {
667
+ if (asJson) return console.log(JSON.stringify(doc, null, 2));
668
+ console.log(`\n \x1b[32m✓\x1b[0m Created "${title}" as document #${doc.id}.`);
669
+ console.log(' The content is in the document — nothing to accept.');
670
+ if (doc.documentUrl) console.log(` ${doc.documentUrl}`);
671
+ console.log('\n Changes to it from here go through `workover doc propose`.\n');
672
+ return;
673
+ }
674
+
675
+ // An older Workover validates the body against a whitelist and drops the field it does not
676
+ // know, which creates an EMPTY document and returns success. Proposing the content is the
677
+ // recovery; saying so is the point — a create that quietly lost the body would look identical.
678
+ const proposal = await authedCall(cfg, `/project/doc/${doc.id}/propose`, {
679
+ markdown,
680
+ source: 'Workover CLI',
681
+ });
682
+ if (asJson) {
683
+ return console.log(JSON.stringify({ ...doc, committed: false, proposal }, null, 2));
684
+ }
685
+ console.log(`\n Created "${title}" as document #${doc.id}, but it is EMPTY.`);
686
+ console.log(" This Workover can't write a new document's content directly, so the body");
687
+ console.log(' is waiting as suggestions. Open it and accept them:');
688
+ if (proposal?.documentUrl) console.log(` ${proposal.documentUrl}`);
689
+ console.log('');
690
+ return;
691
+ }
692
+
693
+ if (sub === 'propose') {
694
+ const usage = 'workover doc propose <docId> --file <path> [--note "<why>"]';
695
+ const docId = docIdArg(positionals, usage);
696
+ const markdown = (await readBody(flags)).trim();
697
+ if (!markdown) {
698
+ console.log(`\n Usage: ${usage}`);
699
+ console.log(' Pass the COMPLETE revised document, not just the changed part —');
700
+ console.log(' Workover diffs it against the current text to build the suggestions.');
701
+ console.log(' The body comes from --file, or from stdin.\n');
702
+ process.exit(1);
703
+ }
704
+ const res = await authedCall(cfg, `/project/doc/${docId}/propose`, {
705
+ markdown,
706
+ note: typeof flags.note === 'string' ? flags.note : undefined,
707
+ source: 'Workover CLI',
708
+ });
709
+ if (asJson) return console.log(JSON.stringify(res, null, 2));
710
+ console.log(`\n \x1b[32m✓\x1b[0m Proposed changes to document #${docId}.`);
711
+ console.log(' They appear as tracked-change suggestions for a person to accept or reject.');
712
+ if (res?.documentUrl) console.log(` ${res.documentUrl}`);
713
+ console.log('');
714
+ return;
715
+ }
716
+
717
+ if (sub === 'write') {
718
+ const usage = 'workover doc write <docId> --file <path> [--note "<why>"]';
719
+ const docId = docIdArg(positionals, usage);
720
+ const markdown = (await readBody(flags)).trim();
721
+ if (!markdown) {
722
+ console.log(`\n Usage: ${usage}`);
723
+ console.log(' Pass the COMPLETE document — this REPLACES the body, so anything');
724
+ console.log(' you leave out is deleted. Read it first with `workover doc read`.');
725
+ console.log(' Needs a token from `workover login --write`.\n');
726
+ process.exit(1);
727
+ }
728
+ const res = await authedCall(cfg, `/project/doc/${docId}/content`, {
729
+ markdown,
730
+ note: typeof flags.note === 'string' ? flags.note : undefined,
731
+ source: 'Workover CLI',
732
+ });
733
+ if (asJson) return console.log(JSON.stringify(res, null, 2));
734
+ console.log(`\n \x1b[32m✓\x1b[0m Wrote document #${docId} directly — nothing to review.`);
735
+ if (res?.replacedCharacters) {
736
+ console.log(` Replaced ${res.replacedCharacters} characters of existing text.`);
737
+ }
738
+ if (res?.documentUrl) console.log(` ${res.documentUrl}`);
739
+ console.log('');
740
+ return;
741
+ }
742
+
743
+ if (sub === 'search') {
744
+ const query = positionals.join(' ').trim();
745
+ if (!query) {
746
+ console.log('\n Usage: workover doc search "<query>" [--limit N]\n');
747
+ process.exit(1);
748
+ }
749
+ const limit = rowId(flags.limit) ?? 10;
750
+ const { results = [] } = await authedCall(
751
+ cfg,
752
+ `/search/documents?q=${encodeURIComponent(query)}&limit=${limit}`,
753
+ );
754
+ if (asJson) return console.log(JSON.stringify(results, null, 2));
755
+ if (!results.length) return console.log('\n No matching documents.\n');
756
+ console.log('');
757
+ for (const r of results) {
758
+ console.log(` #${String(r.id).padEnd(6)} ${r.title || 'Untitled'}`);
759
+ if (r.snippet) console.log(` ${stripHtml(r.snippet).slice(0, 160)}`);
760
+ }
761
+ console.log('');
762
+ return;
763
+ }
764
+
765
+ }
766
+
767
+ /** The project ids every `doc` command asks for. */
768
+ async function projects() {
769
+ const cfg = requireSignIn();
770
+ const { flags } = parseArgs(process.argv.slice(3), { booleans: ['json'] });
771
+ const res = await authedCall(cfg, '/project');
772
+ const list = Array.isArray(res) ? res : res?.projects || [];
773
+ if (flags.json === true) return console.log(JSON.stringify(list, null, 2));
774
+ if (!list.length) return console.log('\n No projects.\n');
775
+ console.log('');
776
+ for (const p of list) {
777
+ console.log(` #${String(p.id).padEnd(6)} ${p.name || p.title || 'Project'}`);
778
+ }
779
+ console.log('');
780
+ }
781
+
485
782
  const cmd = process.argv[2];
486
783
  if (cmd === 'login') await login();
487
784
  else if (cmd === 'logout') await logout();
@@ -489,12 +786,19 @@ else if (cmd === 'whoami') whoami();
489
786
  else if (cmd === 'draft') await draft();
490
787
  else if (cmd === 'draft-set') await draftSet();
491
788
  else if (cmd === 'eval') await evaluateDocs();
789
+ else if (cmd === 'doc') await docCommand();
790
+ else if (cmd === 'projects') await projects();
492
791
  else {
493
792
  console.log('\n Workover CLI\n');
494
793
  console.log(' Usage: workover <command>\n');
495
794
  console.log(' login Sign in to Workover (opens your browser to approve)');
496
795
  console.log(' --publish also request permission to publish to WordPress');
497
796
  console.log(' --draft also request permission to write drafts with AI');
797
+ console.log(' --write also allow direct edits (no suggestions to review)');
798
+ console.log(' doc Work on documents: list, read, create, propose, write, search');
799
+ console.log(' workover doc create --project 11 --title "Billing" --file b.md');
800
+ console.log(' workover doc read 123 · workover doc propose 123 --file new.md');
801
+ console.log(' projects List the projects you can reach, with their ids');
498
802
  console.log(' draft Queue a draft in Workover and wait for it');
499
803
  console.log(' --type tutorial|how-to|reference|explanation');
500
804
  console.log(' draft-set Plan a feature’s whole documentation set, then draft each article');
package/lib.mjs CHANGED
@@ -23,6 +23,103 @@ export const pollDecision = (res) => {
23
23
  return 'pending';
24
24
  };
25
25
 
26
+ /**
27
+ * Split `argv` into flags and positionals.
28
+ *
29
+ * Replaces the per-command `indexOf('--x') + 1` scan, which could not tell a flag's VALUE from a
30
+ * positional argument — so `workover doc read 12 --json` and `workover doc propose 12 --note fixed`
31
+ * needed different hand-written rules to find the same document id.
32
+ *
33
+ * `--flag value`, `--flag=value` and bare `--flag` all work. A flag named in `booleans`, or one
34
+ * followed by another flag or nothing, is `true`. Everything after a lone `--` is positional, so a
35
+ * body that starts with a dash can still be passed.
36
+ */
37
+ export const parseArgs = (argv, { booleans = [] } = {}) => {
38
+ const flags = {};
39
+ const positionals = [];
40
+ for (let i = 0; i < argv.length; i++) {
41
+ const arg = argv[i];
42
+ if (arg === '--') {
43
+ positionals.push(...argv.slice(i + 1));
44
+ break;
45
+ }
46
+ if (!arg.startsWith('--')) {
47
+ positionals.push(arg);
48
+ continue;
49
+ }
50
+ const rest = arg.slice(2);
51
+ const eq = rest.indexOf('=');
52
+ if (eq !== -1) {
53
+ flags[rest.slice(0, eq)] = rest.slice(eq + 1);
54
+ continue;
55
+ }
56
+ const next = argv[i + 1];
57
+ if (booleans.includes(rest) || next === undefined || next.startsWith('--')) {
58
+ flags[rest] = true;
59
+ continue;
60
+ }
61
+ flags[rest] = next;
62
+ i++;
63
+ }
64
+ return { flags, positionals };
65
+ };
66
+
67
+ /**
68
+ * Coerce a user-supplied row id, or null if it isn't one.
69
+ *
70
+ * People and agents pass what is in front of them: the `#12345` these commands print, or the handle
71
+ * out of a document URL. `Number('#12345')` is `NaN`, which we would then send as a literal
72
+ * `/project/doc/NaN` — the API answers 500 and pages on-call. The MCP server learned this in
73
+ * production; the CLI is the same shape of client and gets the same guard rather than the same
74
+ * incident.
75
+ */
76
+ export const rowId = (value) => {
77
+ const s = String(value ?? '')
78
+ .trim()
79
+ .replace(/^#/, '');
80
+ return /^\d+$/.test(s) ? Number(s) : null;
81
+ };
82
+
83
+ /** Flatten HTML to readable plain text: drop tags + named entities, collapse whitespace. */
84
+ export const stripHtml = (html) =>
85
+ (html || '')
86
+ .replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1\b[^>]*>/gi, ' ')
87
+ .replace(/<[^>]+>/g, ' ')
88
+ .replace(/&nbsp;/gi, ' ')
89
+ .replace(/&lt;/gi, '<')
90
+ .replace(/&gt;/gi, '>')
91
+ .replace(/&quot;/gi, '"')
92
+ .replace(/&#39;/g, "'")
93
+ // &amp; last: decoding it first turns the escaped text "&amp;lt;" into a "<" the source
94
+ // never contained.
95
+ .replace(/&amp;/gi, '&')
96
+ .replace(/\s+/g, ' ')
97
+ .trim();
98
+
99
+ /**
100
+ * A document's body as readable text.
101
+ *
102
+ * `bodyText` first: the collab server derives it from the live Yjs state on every save, so it is
103
+ * what the document currently SAYS. `content` is only refreshed on import and on creation, so
104
+ * reading it first would hand back the version a document had when it arrived, months of editing
105
+ * ago, with nothing to indicate the difference.
106
+ */
107
+ export const documentText = (doc) =>
108
+ (doc?.bodyText || '').trim() || stripHtml(doc?.content) || '';
109
+
110
+ /**
111
+ * Whether a just-created document came back with its body already in it.
112
+ *
113
+ * `doc create` sends the markdown WITH the create, and a Workover that understands it writes the
114
+ * content straight in — a document one call old has no prior text for anybody to review the first
115
+ * body against. An older API validates the request against a whitelist, silently drops the unknown
116
+ * field, and returns a perfectly successful empty document. That is the case worth catching: the
117
+ * content would be gone and the command would look like it worked. So it is read off the response
118
+ * rather than assumed, and the caller falls back to proposing the body instead of losing it.
119
+ */
120
+ export const contentCommitted = (doc) =>
121
+ typeof doc?.content === 'string' && doc.content.trim().length > 0;
122
+
26
123
  /**
27
124
  * Reduce a run of per-document evaluations to the shape a reader can act on.
28
125
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workover/cli",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Workover command line — sign in and cowork on your documents from the terminal.",
5
5
  "license": "UNLICENSED",
6
6
  "author": "ScaleMath",