@future-unknown/known 0.0.0-stage → 0.2.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.
@@ -0,0 +1,1555 @@
1
+ require("@colors/colors")
2
+ const fs = require("fs")
3
+ const output = require("../output")
4
+ const { getClient, sessionFor, confirm, confirmByName, confirmStated, run, unwrap, actorNames, accessReasons, person } = require("../helpers")
5
+
6
+ /**
7
+ * `known <org> wiki` — the org's shared wiki.
8
+ *
9
+ * Every organization has a wiki named `general` and may hold more,
10
+ * including wikis another organization shares with it (marked in `wikis`
11
+ * with their home; addressed by this org's own name for them). Every path
12
+ * names its wiki: `general:docs.deploy` addresses that page in the general
13
+ * wiki, `labs:docs.deploy` (or `docs.deploy --wiki labs`) the same page in
14
+ * the org's `labs` wiki, and `labs:` the wiki's root. A path with no wiki is
15
+ * refused, never guessed. No path can reach
16
+ * outside the org's wikis. Content is Markdown.
17
+ *
18
+ * Pages are authored writing, and take the authoring verbs; records are
19
+ * data on a page, and take the data verbs:
20
+ *
21
+ * known acme wiki read general:docs.deploy
22
+ * known acme wiki write general:docs.deploy --file deploy.md --title "Deploying"
23
+ * known acme wiki edit general:docs.deploy --old "nightly" --new "hourly"
24
+ * git log -1 --format=%B | known acme wiki write general:notes.today
25
+ * known acme wiki tree general: --depth 2
26
+ * known acme wiki search "rollback" general:
27
+ * known acme wiki move general:docs.deploy general:runbooks.deploy
28
+ * known acme wiki rm general:scratch
29
+ * known acme wiki meta general:metrics.usage --text '{"retain": {"days": 90}}'
30
+ * known acme wiki records general:metrics.usage --latest
31
+ * known acme wiki get general:tasks/t-41
32
+ * known acme wiki set general:metrics.usage --text '{"requests": 1042}'
33
+ * known acme wiki del general:tasks/t-41
34
+ * known acme wiki history general:crm.contacts/jo
35
+ * known acme wiki diff general:crm.contacts/jo
36
+ * known acme wiki links general:crm.contacts/jo
37
+ * known acme wiki check capital:
38
+ * known acme wiki changes general:
39
+ * known acme wiki wikis
40
+ * known acme wiki create labs --title "Labs" --description "Experiments; nothing load-bearing"
41
+ * known acme wiki update labs --description "Experiments; nothing load-bearing"
42
+ * known acme wiki grant labs team:platform:write
43
+ * known acme wiki grant labs user:@ada:admin
44
+ * known acme wiki access labs
45
+ * known acme wiki rename labs research
46
+ * known acme wiki delete research
47
+ * known acme wiki deleted
48
+ * known acme wiki restore research
49
+ * known acme wiki share research globex --level write
50
+ * known globex wiki invitations
51
+ * known globex wiki accept acme/research --as acme-research
52
+ *
53
+ * Being in an organization gives nobody a wiki: what a person holds is
54
+ * what a wiki's grants give them, their own or a team's. Every member is on
55
+ * the built-in team `everyone`, so a wiki is open to the organization when
56
+ * that team is granted it (`wiki grant labs team:everyone:read`) and
57
+ * restricted when it is not (`wiki revoke labs team:everyone`); a new wiki
58
+ * starts granted to everyone unless --grant says who. Any member creates a
59
+ * wiki and is its admin; an org owner administers every wiki already, so one
60
+ * who creates a wiki gets no grant they did not name. A wiki's admins and
61
+ * the org's owners rename it, delete it (nothing is destroyed: `restore`
62
+ * brings it back whole) and share it with another organization, whose owners
63
+ * accept it under a name of their own. Levels are read, write and admin.
64
+ *
65
+ * Every path the CLI prints is written the same way, so it pastes back.
66
+ * `wikis` says what each wiki is for and who reads it.
67
+ *
68
+ * A page with a key is a table (a record set adds or replaces the row with
69
+ * its key, and every version of each row is kept); a page without one is a
70
+ * log (a record set adds an entry). A record is addressed as its page, a
71
+ * slash, and its key: `general:crm.contacts/jo`.
72
+ *
73
+ * Every page revision is kept forever; `--change <id>` / `--at <iso>` read the
74
+ * wiki as it was. The safe edit loop for scripts and agents: change part of a
75
+ * page with `edit` (the exact text you read); to rewrite one, read with
76
+ * --json, keep `revisionId`, and write back with `--if-revision <id>`; a
77
+ * conflict means someone else changed the page — re-read, merge, retry.
78
+ * Missing parents (and the wiki itself, on first write) are created
79
+ * automatically.
80
+ */
81
+ const STDIN_MAX = 100000
82
+
83
+ // An address someone is invited by, and the levels an invitation takes.
84
+ const EMAIL = /^[^\s@:]+@[^\s@:]+\.[^\s@:]+$/
85
+ const INVITE_LEVELS = ["read", "write", "admin"]
86
+
87
+ const verbs = { read, write, edit, move, rm, tree, search, links, check, meta, records, get, set, del, history, diff, changes, notes, note, resolve, wikis, create, update, grant, revoke, invite, uninvite, access, rename, delete: destroy, deleted, restore, shares, share, unshare, invitations, accept, decline, leave }
88
+
89
+ module.exports = function (argv, ref, rest) {
90
+ const verb = rest && rest[0]
91
+ if (argv.help) return showMenu(ref)
92
+ if (!verb) return showMenu(ref)
93
+ const handler = verbs[verb]
94
+ if (!handler) {
95
+ output.info(require("../helpers").unknownCommand("wiki", verb, Object.keys(verbs)).grey)
96
+ return showMenu(ref)
97
+ }
98
+ return handler(argv, ref, rest.slice(1))
99
+ }
100
+
101
+ // Bare (`known wiki`), the org comes from the project binding, so the menu
102
+ // drops the org from every invocation.
103
+ function showMenu(ref) {
104
+ const org = ref ? ref + " " : ""
105
+ console.log()
106
+ console.log((" known " + org + "wiki").cyan + " the org's shared wikis — versioned, Markdown; every path names its wiki (general:docs.deploy)".grey)
107
+ console.log()
108
+ // Pages are authored writing; records are data on a page: each has its
109
+ // own verbs, so each has its own list, aligned to one column.
110
+ const groups = [
111
+ ["pages — writing", [
112
+ [org + "wiki read <wiki>:<path>", "print a page (raw content; --json for revision ids; --change, --at)"],
113
+ [org + "wiki write <wiki>:<path>", "write a page whole from --text, --file, or stdin (--if-revision)"],
114
+ [org + "wiki edit <wiki>:<path>", "replace --old with --new; refused unless --old occurs exactly once (--all)"],
115
+ [org + "wiki move <wiki>:<from> <wiki>:<to>", "move or rename a page and its subtree"],
116
+ [org + "wiki rm <wiki>:<path>", "delete a page (--recursive for a subtree; the wiki's admins and org owners)"],
117
+ [org + "wiki tree <wiki>:[path]", "the page hierarchy (--depth, --change, --at)"],
118
+ [org + "wiki search <query> <wiki>:[path]", "full-text search over pages and table records, optionally scoped to a subtree"],
119
+ [org + "wiki links <wiki>:<path>[/<key>]", "what links to a page or a record"],
120
+ [org + "wiki check <wiki>:[path]", "the links a wiki holds that point at nothing, and where each is"],
121
+ [org + "wiki meta <wiki>:<path>", "merge metadata declarations: key, schema, retain (null removes; --replace)"]
122
+ ]],
123
+ ["records — data on a page", [
124
+ [org + "wiki records <wiki>:<path>", "read records (--latest, --reverse, --since/--until, --limit, --cursor, --at)"],
125
+ [org + "wiki get <wiki>:<path>/<key>", "one record: a table's row by key, or a log entry by _id"],
126
+ [org + "wiki set <wiki>:<path>", "write a record (--text/--file/stdin; a table adds or replaces by key, --if-version; a log adds, --ts)"],
127
+ [org + "wiki del <wiki>:<path>/<key>", "delete one record"]
128
+ ]],
129
+ ["history, changes and notes", [
130
+ [org + "wiki history <wiki>:<path>[/<key>]", "a page's revisions, or a table row's versions, newest first"],
131
+ [org + "wiki diff <wiki>:<path>[/<key>]", "what the latest revision or version changed (--change, --revision; --version for a row)"],
132
+ [org + "wiki changes <wiki>:[path]", "what changed in a wiki, newest first, and the pages each change touched (--limit, --before)"],
133
+ [org + "wiki notes <wiki>:[path]", "the feedback queue (the wiki's root: all of it; --deep: a subtree)"],
134
+ [org + "wiki note <wiki>:<path>", "leave a note (--text/--file/stdin)"],
135
+ [org + "wiki resolve <wiki>:<path> <id>", "resolve a note"]
136
+ ]],
137
+ ["wikis", [
138
+ [org + "wiki wikis", "the org's wikis — what each is for, who reads it, what changed since you looked, your level (--json: everything)"],
139
+ [org + "wiki create <name>", "create a wiki (--description, --title; --grant <kind>:<id>[:<level>] and --member <person> say who starts with it, everyone when unsaid; any member, who is its admin)"],
140
+ [org + "wiki update <wiki>", "say what it is for and retitle it (--description, --title)"],
141
+ [org + "wiki grant <wiki> <kind>:<id>[:<level>]", "grant a person (user:@handle, user:<email>, user:<id>) or a team (team:<slug>; team:everyone is every member) a level: read, write, admin; again to change it"],
142
+ [org + "wiki revoke <wiki> <kind>:<id>", "take a grant away (team:everyone restricts the wiki to its other grants)"],
143
+ [org + "wiki invite <wiki> <email>[:<level>]", "invite someone not yet in the organization, with the wiki waiting for them at a level (org owners); a member's address is granted"],
144
+ [org + "wiki uninvite <wiki> <email>", "take an invited address off the wiki"],
145
+ [org + "wiki access <wiki>", "who has access, at what level, and why (the org, a direct grant, a team, owning the org)"],
146
+ [org + "wiki rename <wiki> <new-name>", "rename it (its admins and org owners; --yes); sites must be republished, agents use the new name"],
147
+ [org + "wiki delete <wiki>", "delete it — type its name, or --confirm <name>; it can be restored"],
148
+ [org + "wiki deleted", "the deleted wikis you could restore"],
149
+ [org + "wiki restore <wiki>", "bring a deleted wiki back whole"]
150
+ ]],
151
+ ["sharing with other organizations", [
152
+ [org + "wiki shares <wiki>", "the organizations a wiki is shared with, and where each share stands"],
153
+ [org + "wiki share <wiki> <org>", "invite another organization to it (--level read or write; read when unsaid)"],
154
+ [org + "wiki unshare <wiki> <org>", "end a share, waiting or accepted"],
155
+ [org + "wiki invitations", "wikis other organizations have offered this one (org owners)"],
156
+ [org + "wiki accept <org>/<wiki>", "accept an invitation (--as <name> to call it something else here)"],
157
+ [org + "wiki decline <org>/<wiki>", "decline an invitation"],
158
+ [org + "wiki leave <wiki>", "stop taking part in a wiki another organization shares"]
159
+ ]]
160
+ ]
161
+ const width = output.commandWidth(...groups.map(([, rows]) => rows))
162
+ for (const [title, rows] of groups) {
163
+ console.log(" " + title.bold)
164
+ output.commands(rows, width)
165
+ console.log()
166
+ }
167
+ process.exit(0)
168
+ }
169
+
170
+ // ---- verbs -----------------------------------------------------------------
171
+
172
+ function read(argv, ref, rest) {
173
+ return run(async () => {
174
+ // Validate the typed input before resolving a session, so bad flags are
175
+ // reported even with no credentials on disk — the same order `post` keeps.
176
+ const when = historical(argv)
177
+ if (recordAddress(rest[0]).key !== null) throw friendly("that is a record — read it with `known <org> wiki get <wiki>:<path>/<key>`")
178
+ const address = wikiAddress(argv, [rest[0]])
179
+ const session = sessionFor(argv, ref)
180
+ const client = getClient(argv, { session })
181
+ const scope = await wikiScope(address, argv, session, client)
182
+ const node = unwrap(await client.wiki.read({
183
+ path: scope.full(rest[0]),
184
+ ...when
185
+ }))
186
+ if (output.isJson()) return output.data(node)
187
+ output.raw(node.content)
188
+ })
189
+ }
190
+
191
+ function write(argv, ref, rest) {
192
+ return run(async () => {
193
+ const text = await resolveText(argv)
194
+ const metadata = argv.metadata !== undefined ? metadataFlag(argv.metadata) : undefined
195
+ const address = wikiAddress(argv, [rest[0]])
196
+ const session = sessionFor(argv, ref)
197
+ const client = getClient(argv, { session })
198
+ const scope = await wikiScope(address, argv, session, client)
199
+ const res = unwrap(await client.wiki.write({
200
+ path: scope.full(rest[0]),
201
+ content: text,
202
+ ...(argv.title ? { title: argv.title } : {}),
203
+ ...(metadata !== undefined ? { metadata } : {}),
204
+ ...(argv.message ? { message: argv.message } : {}),
205
+ ...(argv["if-revision"] ? { ifRevision: argv["if-revision"] } : {})
206
+ }))
207
+ if (output.isJson()) return output.data(res)
208
+ if (!res.changed) output.status("unchanged", res.node.fullPath, "already this content", "muted")
209
+ else output.status(res.created ? "created" : "updated", res.node.fullPath, "revision " + res.node.revisionId)
210
+ reportProblems(res.problems)
211
+ })
212
+ }
213
+
214
+ // The links a write carried that point at nothing, a line each: the write
215
+ // stands, and what to fix is said where it was done.
216
+ function reportProblems(problems) {
217
+ if (!problems || !problems.length || output.isJson()) return
218
+ output.pad(() => {
219
+ for (const problem of problems) {
220
+ if (problem.link === null) console.log(" " + problem.message.grey)
221
+ else console.log(" " + "broken link".red + " " + ("[[" + problem.link + "]]").cyan + (" " + problem.message).grey)
222
+ }
223
+ })
224
+ }
225
+
226
+ // The links a move or removal left pointing at nothing, by where they are.
227
+ function reportLeftBroken(broken, scope, slug) {
228
+ if (!broken || !broken.total || output.isJson()) return
229
+ output.pad(() => {
230
+ for (const link of broken.links) {
231
+ const from = link.fullPath + (link.key ? "/" + link.key : "")
232
+ console.log(" " + "broken link".red + " " + from.cyan + (" still links to " + link.target.fullPath).grey)
233
+ }
234
+ if (broken.total > broken.links.length) console.log(" " + ((broken.total - broken.links.length) + " more — wiki check finds them all").grey)
235
+ })
236
+ }
237
+
238
+ // Every link a wiki — or a page and those beneath it — holds that points
239
+ // at nothing: the link, why, and the pages and records that carry it.
240
+ function check(argv, ref, rest) {
241
+ return run(async () => {
242
+ const target = rest[0]
243
+ if (!target) throw friendly("name the wiki or page — `known <org> wiki check <wiki>:[path]`")
244
+ const address = wikiAddress(argv, [target])
245
+ const session = sessionFor(argv, ref)
246
+ const client = getClient(argv, { session })
247
+ const scope = await wikiScope(address, argv, session, client)
248
+ const res = unwrap(await client.wiki.check({ path: scope.full(target) }))
249
+ if (output.isJson()) return output.data(res)
250
+ if (!res.problems.length) return output.empty("no broken links")
251
+ output.table(res.problems.map((problem) => ({
252
+ link: problem.link === null ? "" : ("[[" + problem.link + "]]").cyan,
253
+ problem: problem.message,
254
+ in: (problem.sources || []).map((source) => source.fullPath + (source.key ? "/" + source.key : "")).join(", ")
255
+ })))
256
+ })
257
+ }
258
+
259
+ // Change part of a page: one exact string for another, read and written in
260
+ // one step on the server, so nothing else on the page is touched and a
261
+ // change made meanwhile elsewhere on it survives. --old must occur exactly
262
+ // once (give more of the surrounding text), unless --all.
263
+ function edit(argv, ref, rest) {
264
+ return run(async () => {
265
+ const target = rest[0]
266
+ if (!target) throw friendly("name the page — `known <org> wiki edit <wiki>:<path> --old \"…\" --new \"…\"`")
267
+ if (!argv.old || argv.new === undefined) {
268
+ throw friendly("say what to replace and with what — `--old \"…\" --new \"…\"` (--new \"\" deletes)")
269
+ }
270
+ const address = wikiAddress(argv, [target])
271
+ const session = sessionFor(argv, ref)
272
+ const client = getClient(argv, { session })
273
+ const scope = await wikiScope(address, argv, session, client)
274
+ const res = unwrap(await client.wiki.edit({
275
+ path: scope.full(target),
276
+ oldString: String(argv.old),
277
+ newString: String(argv.new),
278
+ ...(argv.all ? { replaceAll: true } : {}),
279
+ ...(argv.message ? { message: argv.message } : {}),
280
+ ...(argv["if-revision"] ? { ifRevision: argv["if-revision"] } : {})
281
+ }))
282
+ if (output.isJson()) return output.data(res)
283
+ output.status("edited", res.node.fullPath, res.replaced + (res.replaced === 1 ? " place" : " places") + " · revision " + res.node.revisionId)
284
+ reportProblems(res.problems)
285
+ })
286
+ }
287
+
288
+ function tree(argv, ref, rest) {
289
+ return run(async () => {
290
+ const when = historical(argv)
291
+ const depth = argv.depth ? { depth: intFlag(argv.depth, "--depth") } : {}
292
+ const address = wikiAddress(argv, [rest[0]])
293
+ const session = sessionFor(argv, ref)
294
+ const client = getClient(argv, { session })
295
+ const scope = await wikiScope(address, argv, session, client)
296
+ const root = unwrap(await client.wiki.tree({
297
+ path: scope.full(rest[0]),
298
+ ...depth,
299
+ ...when
300
+ }))
301
+ if (output.isJson()) return output.data(root)
302
+
303
+ const rows = [[root.fullPath, preview(root)]]
304
+ walk(root, "")
305
+ function walk(node, prefix) {
306
+ node.children.forEach((child, i) => {
307
+ const last = i === node.children.length - 1
308
+ rows.push([prefix + (last ? "└── " : "├── ") + child.slug, preview(child)])
309
+ walk(child, prefix + (last ? " " : "│ "))
310
+ })
311
+ }
312
+ console.log()
313
+ output.commands(rows)
314
+ console.log()
315
+ })
316
+ }
317
+
318
+ function search(argv, ref, rest) {
319
+ return run(async () => {
320
+ const query = rest[0]
321
+ if (!query) throw friendly("nothing to search for — `known <org> wiki search <query> <wiki>:`")
322
+ const address = wikiAddress(argv, [rest[1]])
323
+ const session = sessionFor(argv, ref)
324
+ const client = getClient(argv, { session })
325
+ const scope = await wikiScope(address, argv, session, client)
326
+ const results = unwrap(await client.wiki.search({
327
+ path: scope.full(rest[1]),
328
+ query,
329
+ ...(argv.limit ? { limit: intFlag(argv.limit, "--limit") } : {})
330
+ }))
331
+ if (output.isJson()) return output.data(results)
332
+ if (!results.length) return output.empty("nothing matches “" + query + "”")
333
+ output.table(results.map((r) => ({
334
+ path: (r.fullPath + (r.key ? "/" + r.key : "")).cyan,
335
+ excerpt: (r.excerpt || "").replace(/\s+/g, " ")
336
+ })))
337
+ })
338
+ }
339
+
340
+ function history(argv, ref, rest) {
341
+ return run(async () => {
342
+ const address = wikiAddress(argv, [rest[0]])
343
+ const { page, key } = recordAddress(rest[0])
344
+ const session = sessionFor(argv, ref)
345
+ const client = getClient(argv, { session })
346
+ const scope = await wikiScope(address, argv, session, client)
347
+ if (key !== null) {
348
+ const res = unwrap(await client.wiki.history({
349
+ path: scope.full(page),
350
+ key,
351
+ ...(argv.limit ? { limit: intFlag(argv.limit, "--limit") } : {}),
352
+ ...(argv.cursor ? { cursor: String(argv.cursor) } : {})
353
+ }))
354
+ if (output.isJson()) return output.data(res)
355
+ const by = await actorNames(client, res.versions.map((v) => v._actor))
356
+ output.table(res.versions.map((v) => ({
357
+ version: String(v._v),
358
+ when: v._ts,
359
+ by: by(v._actor),
360
+ change: v._change === "deleted" ? "deleted".red : v._change
361
+ })))
362
+ if (res.cursor) output.status("more", "continue with", "--cursor " + res.cursor, "muted")
363
+ return
364
+ }
365
+ if (argv.cursor) throw friendly("--cursor pages a row's versions — address one as <path>/<key>")
366
+ const entries = unwrap(await client.wiki.history({
367
+ path: scope.full(rest[0]),
368
+ ...(argv.limit ? { limit: intFlag(argv.limit, "--limit") } : {})
369
+ }))
370
+ if (output.isJson()) return output.data(entries)
371
+ const by = await actorNames(client, entries.map((e) => e.change.actor))
372
+ output.table(entries.map((e) => ({
373
+ change: String(e.changeId),
374
+ revision: e.revisionId,
375
+ when: e.createdAt,
376
+ by: by(e.change.actor),
377
+ note: e.deleted ? "deleted".red : (e.change.message || "—".grey)
378
+ })))
379
+ })
380
+ }
381
+
382
+ // What one change did, against the one before it: a page revision as a
383
+ // unified diff of its Markdown (title and metadata changes first), or a
384
+ // table row's version as a unified diff of its fields (sorted JSON,
385
+ // stamps left out). The latest by default.
386
+ function diff(argv, ref, rest) {
387
+ return run(async () => {
388
+ const target = rest[0]
389
+ if (!target) throw friendly("name the page or record — `known <org> wiki diff <wiki>:<path>[/<key>]`")
390
+ const address = wikiAddress(argv, [target])
391
+ const { page, key } = recordAddress(target)
392
+ if (key !== null && (argv.change || argv.revision)) throw friendly("a row's versions take --version, not --change or --revision")
393
+ if (key === null && argv.version) throw friendly("--version reads a row — address one as <path>/<key>")
394
+ if (argv.change && argv.revision) throw friendly("pass --change or --revision, not both")
395
+ const session = sessionFor(argv, ref)
396
+ const client = getClient(argv, { session })
397
+ const scope = await wikiScope(address, argv, session, client)
398
+ const full = scope.full(page)
399
+
400
+ if (key !== null) {
401
+ let version = argv.version ? intFlag(argv.version, "--version") : null
402
+ if (version === null) {
403
+ const latest = unwrap(await client.wiki.history({ path: full, key, limit: 1 }))
404
+ version = latest.versions[0]._v
405
+ }
406
+ const res = unwrap(await client.wiki.getVersion({ path: full, key, version }))
407
+ if (output.isJson()) return output.data(res)
408
+ const by = await actorNames(client, [res.version._actor])
409
+ const before = res.previous && res.previous._change !== "deleted" ? res.previous : null
410
+ const after = res.version._change === "deleted" ? null : res.version
411
+ console.log()
412
+ console.log(" version " + res.version._v + " " + res.version._ts + " " + by(res.version._actor) + " " + res.version._change)
413
+ // Read the way a page revision is: other fields as before -> after,
414
+ // then the record's writing (its content) as a unified diff.
415
+ const from = otherFields(before)
416
+ const to = otherFields(after)
417
+ for (const name of [...new Set([...Object.keys(from), ...Object.keys(to)])].sort()) {
418
+ const a = name in from ? JSON.stringify(from[name]) : "null"
419
+ const b = name in to ? JSON.stringify(to[name]) : "null"
420
+ if (a !== b) console.log(" " + name + ": " + a + " -> " + b)
421
+ }
422
+ printPatch(full + "/" + key, before ? "v" + before._v : null, after ? "v" + after._v : null, writingOf(before), writingOf(after))
423
+ return
424
+ }
425
+
426
+ let revisionId = argv.revision ? String(argv.revision) : null
427
+ if (!revisionId) {
428
+ const node = unwrap(await client.wiki.read({ path: full, ...(argv.change ? { changeId: intFlag(argv.change, "--change") } : {}) }))
429
+ revisionId = node.revisionId
430
+ }
431
+ const revision = unwrap(await client.wiki.getRevision({ wiki: full.split(".")[0], revisionId }))
432
+ if (output.isJson()) return output.data(revision)
433
+ const by = await actorNames(client, [revision.change.actor])
434
+ const gone = revision.kind === "deleted"
435
+ const before = revision.previous && !revision.previous.deleted ? revision.previous : null
436
+ console.log()
437
+ console.log(" change " + revision.changeId + " " + revision.createdAt + " " + by(revision.change.actor) + " " + revision.kind +
438
+ (revision.change.message ? " " + revision.change.message : ""))
439
+ const field = (name, from, to) => {
440
+ if (from !== to) console.log(" " + name + ": " + JSON.stringify(from == null ? null : from) + " -> " + JSON.stringify(to == null ? null : to))
441
+ }
442
+ field("title", before ? before.title : null, gone ? null : revision.title)
443
+ const fromMeta = (before && before.metadata) || {}
444
+ const toMeta = gone ? {} : (revision.metadata || {})
445
+ for (const name of [...new Set([...Object.keys(fromMeta), ...Object.keys(toMeta)])].sort()) {
446
+ field("metadata." + name, fromMeta[name], toMeta[name])
447
+ }
448
+ printPatch(full, before ? "c" + before.changeId : null, gone ? null : "c" + revision.changeId,
449
+ before ? before.content : "", gone ? "" : revision.content)
450
+ })
451
+ }
452
+
453
+ // What links to a page or a table record: the pages whose content and the
454
+ // records that carry a wikilink to it, each by its address and heading.
455
+ function links(argv, ref, rest) {
456
+ return run(async () => {
457
+ const target = rest[0]
458
+ if (!target) throw friendly("name the page or record — `known <org> wiki links <wiki>:<path>[/<key>]`")
459
+ const address = wikiAddress(argv, [target])
460
+ const { page, key } = recordAddress(target)
461
+ const session = sessionFor(argv, ref)
462
+ const client = getClient(argv, { session })
463
+ const scope = await wikiScope(address, argv, session, client)
464
+ const res = unwrap(await client.wiki.links({
465
+ path: scope.full(page),
466
+ ...(key !== null ? { key } : {}),
467
+ ...(argv.limit ? { limit: intFlag(argv.limit, "--limit") } : {})
468
+ }))
469
+ if (output.isJson()) return output.data(res)
470
+ if (!res.links.length) return output.empty("nothing links here")
471
+ output.table(res.links.map((link) => ({
472
+ from: (link.fullPath + (link.key ? "/" + link.key : "")).cyan,
473
+ title: link.title || ""
474
+ })))
475
+ })
476
+ }
477
+
478
+ function move(argv, ref, rest) {
479
+ return run(async () => {
480
+ const [from, to] = rest
481
+ if (!from || !to) throw friendly("both paths are needed — `known <org> wiki move <wiki>:<from> <wiki>:<to>`")
482
+ const address = wikiAddress(argv, [from, to])
483
+ const session = sessionFor(argv, ref)
484
+ const client = getClient(argv, { session })
485
+ const scope = await wikiScope(address, argv, session, client)
486
+ const node = unwrap(await client.wiki.move({
487
+ from: scope.full(from),
488
+ to: scope.full(to),
489
+ ...(argv.message ? { message: argv.message } : {}),
490
+ ...(argv["if-revision"] ? { ifRevision: argv["if-revision"] } : {})
491
+ }))
492
+ if (output.isJson()) return output.data(node)
493
+ output.status("moved", node.fullPath, "from " + scope.full(from))
494
+ reportLeftBroken(node.brokenLinks, scope, session.org.slug)
495
+ })
496
+ }
497
+
498
+ function rm(argv, ref, rest) {
499
+ return run(async () => {
500
+ const target = rest[0]
501
+ if (!target) throw friendly("name the page to delete — `known <org> wiki rm <wiki>:<path>`")
502
+ const address = wikiAddress(argv, [target])
503
+ const session = sessionFor(argv, ref)
504
+ const client = getClient(argv, { session })
505
+ const scope = await wikiScope(address, argv, session, client)
506
+ const full = scope.full(target)
507
+
508
+ // Recursive deletion takes a whole subtree with it; pause for a human
509
+ // unless --yes or scripted. History survives either way.
510
+ if (argv.recursive && !(await confirm("delete the entire subtree at " + full + "?", argv))) {
511
+ return output.status("kept", full, null, "muted")
512
+ }
513
+
514
+ const res = unwrap(await client.wiki.remove({
515
+ path: full,
516
+ ...(argv.recursive ? { recursive: true } : {}),
517
+ ...(argv.message ? { message: argv.message } : {}),
518
+ ...(argv["if-revision"] ? { ifRevision: argv["if-revision"] } : {}),
519
+ ...(argv["if-change"] ? { ifChange: intFlag(argv["if-change"], "--if-change") } : {})
520
+ }))
521
+ if (output.isJson()) return output.data(res)
522
+ output.status("deleted", res.deletedPaths.join(", "), "change " + res.changeId, "danger")
523
+ reportLeftBroken(res.brokenLinks, scope, session.org.slug)
524
+ })
525
+ }
526
+
527
+ // A wiki's root (`general:`, or --wiki general) is its whole feedback
528
+ // queue; a page narrows to that page exactly, and --deep widens a page to
529
+ // its whole subtree.
530
+ function notes(argv, ref, rest) {
531
+ return run(async () => {
532
+ const target = rest[0]
533
+ const subtree = !splitColon(target).rest || argv.deep === true
534
+ const address = wikiAddress(argv, [target])
535
+ const session = sessionFor(argv, ref)
536
+ const client = getClient(argv, { session })
537
+ const scope = await wikiScope(address, argv, session, client)
538
+ const entries = unwrap(await client.wiki.notes({
539
+ path: scope.full(target),
540
+ ...(subtree ? { subtree: true } : {}),
541
+ ...(argv.all ? { includeResolved: true } : {})
542
+ }))
543
+ if (output.isJson()) return output.data(entries)
544
+ if (!entries.length) return output.empty(argv.all ? "no notes" : "no open notes")
545
+ const by = await actorNames(client, entries.map((entry) => entry.author))
546
+ output.table(entries.map((entry) => ({
547
+ page: entry.fullPath.cyan,
548
+ note: preview({ content: entry.body }),
549
+ by: by(entry.author),
550
+ when: entry.createdAt,
551
+ status: entry.resolvedAt ? "resolved".grey : "open",
552
+ id: entry.id
553
+ })))
554
+ })
555
+ }
556
+
557
+ function note(argv, ref, rest) {
558
+ return run(async () => {
559
+ const target = rest[0]
560
+ if (!target) throw friendly("name the page — `known <org> wiki note <wiki>:<path>`")
561
+ if (argv.resolve) throw friendly("resolving is its own verb — `known <org> wiki resolve <wiki>:<path> <id>`")
562
+ const address = wikiAddress(argv, [target])
563
+ const body = await resolveText(argv)
564
+ const session = sessionFor(argv, ref)
565
+ const client = getClient(argv, { session })
566
+ const scope = await wikiScope(address, argv, session, client)
567
+ const added = unwrap(await client.wiki.addNote({
568
+ path: scope.full(target),
569
+ body
570
+ }))
571
+ if (output.isJson()) return output.data(added)
572
+ output.status("noted", added.fullPath, "note " + added.id)
573
+ })
574
+ }
575
+
576
+ function resolve(argv, ref, rest) {
577
+ return run(async () => {
578
+ const [target, id] = rest
579
+ if (!target || !id) throw friendly("name the page and the note — `known <org> wiki resolve <wiki>:<path> <id>`")
580
+ const address = wikiAddress(argv, [target])
581
+ const session = sessionFor(argv, ref)
582
+ const client = getClient(argv, { session })
583
+ const scope = await wikiScope(address, argv, session, client)
584
+ const resolved = unwrap(await client.wiki.resolveNote({
585
+ path: scope.full(target),
586
+ noteId: String(id)
587
+ }))
588
+ if (output.isJson()) return output.data(resolved)
589
+ output.status("resolved", resolved.fullPath, "note " + resolved.id, "muted")
590
+ })
591
+ }
592
+
593
+ // A record set is stamped (_actor, _ts, _v, _id) and is not one of the
594
+ // wiki's changes. The page's declarations decide the behavior — a table
595
+ // adds or replaces the row with its key and keeps every version
596
+ // (--if-version is the compare-and-swap), a log adds an entry (--ts
597
+ // backfills when it happened).
598
+ function set(argv, ref, rest) {
599
+ return run(async () => {
600
+ const target = rest[0]
601
+ if (!target) throw friendly("name the page — `known <org> wiki set <wiki>:<path>`")
602
+ if (recordAddress(target).key !== null) throw friendly("a record carries its key in its fields — `known <org> wiki set <wiki>:<path> --text '{…}'`")
603
+ const address = wikiAddress(argv, [target])
604
+ const value = parseJson(await resolveText(argv))
605
+ const session = sessionFor(argv, ref)
606
+ const client = getClient(argv, { session })
607
+ const scope = await wikiScope(address, argv, session, client)
608
+ const res = unwrap(await client.wiki.set({
609
+ path: scope.full(target),
610
+ value,
611
+ ...(argv.ts ? { ts: String(argv.ts) } : {}),
612
+ ...(argv["if-version"] ? { ifVersion: intFlag(argv["if-version"], "--if-version") } : {})
613
+ }))
614
+ if (output.isJson()) return output.data(res)
615
+ output.status("set", res.fullPath, res.record._id + " (version " + res.record._v + ")")
616
+ reportProblems(res.problems)
617
+ })
618
+ }
619
+
620
+ // One record by its address: a table's row by its key, a log entry by _id.
621
+ function get(argv, ref, rest) {
622
+ return run(async () => {
623
+ const target = rest[0]
624
+ const { page, key } = recordAddress(target)
625
+ if (!target || key === null) throw friendly("name the record — `known <org> wiki get <wiki>:<path>/<key>` (a page is read with `wiki read`)")
626
+ if (argv.latest || argv.since || argv.until || argv.limit || argv.cursor || argv.reverse || argv.at) {
627
+ throw friendly("one record stands alone — drop --latest/--since/--until/--limit/--cursor/--reverse/--at (a row at a moment is its version: `wiki history <wiki>:<path>/<key>`)")
628
+ }
629
+ const address = wikiAddress(argv, [page])
630
+ const session = sessionFor(argv, ref)
631
+ const client = getClient(argv, { session })
632
+ const scope = await wikiScope(address, argv, session, client)
633
+ const res = unwrap(await client.wiki.get({ path: scope.full(page), key }))
634
+ if (output.isJson()) return output.data(res)
635
+ output.raw(JSON.stringify(res.record, null, 2))
636
+ })
637
+ }
638
+
639
+ function del(argv, ref, rest) {
640
+ return run(async () => {
641
+ const target = rest[0]
642
+ const { page, key } = recordAddress(target)
643
+ if (!target || key === null || rest[1] !== undefined) throw friendly("name the record — `known <org> wiki del <wiki>:<path>/<key>` (a page is deleted with `wiki rm`)")
644
+ const address = wikiAddress(argv, [page])
645
+ const session = sessionFor(argv, ref)
646
+ const client = getClient(argv, { session })
647
+ const scope = await wikiScope(address, argv, session, client)
648
+ const res = unwrap(await client.wiki.del({
649
+ path: scope.full(page),
650
+ key
651
+ }))
652
+ if (output.isJson()) return output.data(res)
653
+ output.status("deleted", res.fullPath, String(res.record._id))
654
+ })
655
+ }
656
+
657
+ // Declarations are authored intent: meta merges fields into the page's
658
+ // versioned metadata without clobbering the rest. A null value removes
659
+ // its field; --replace swaps the whole object.
660
+ function meta(argv, ref, rest) {
661
+ return run(async () => {
662
+ const target = rest[0]
663
+ if (!target) throw friendly("name the page — `known <org> wiki meta <wiki>:<path>`")
664
+ const address = wikiAddress(argv, [target])
665
+ const patch = metadataFlag(await resolveText(argv))
666
+ const session = sessionFor(argv, ref)
667
+ const client = getClient(argv, { session })
668
+ const scope = await wikiScope(address, argv, session, client)
669
+ const res = unwrap(await client.wiki.updateMeta({
670
+ path: scope.full(target),
671
+ metadata: patch,
672
+ ...(argv.replace ? { replace: true } : {}),
673
+ ...(argv["if-revision"] ? { ifRevision: argv["if-revision"] } : {}),
674
+ ...(argv.message ? { message: argv.message } : {})
675
+ }))
676
+ if (output.isJson()) return output.data(res)
677
+ if (!res.changed) return output.status("unchanged", res.node.fullPath, "already these declarations", "muted")
678
+ output.status("updated", res.node.fullPath, "revision " + res.node.revisionId)
679
+ })
680
+ }
681
+
682
+ function records(argv, ref, rest) {
683
+ return run(async () => {
684
+ const target = rest[0]
685
+ if (!target) throw friendly("name the page — `known <org> wiki records <wiki>:<path>`")
686
+ if (recordAddress(target).key !== null || rest[1] !== undefined) {
687
+ throw friendly("one record is read with `known <org> wiki get <wiki>:<path>/<key>` (and a row then is its version: `wiki history <wiki>:<path>/<key>`)")
688
+ }
689
+ const address = wikiAddress(argv, [target])
690
+ const range = recordRange(argv)
691
+ const session = sessionFor(argv, ref)
692
+ const client = getClient(argv, { session })
693
+ const scope = await wikiScope(address, argv, session, client)
694
+ const res = unwrap(await client.wiki.records({
695
+ path: scope.full(target),
696
+ ...range
697
+ }))
698
+ if (output.isJson()) return output.data(res)
699
+ if (res.unknown && res.unknown.length) output.status("unknown", "not kept at " + res.at, res.unknown.join(", "), "muted")
700
+ if (!res.records.length) return output.empty("no records")
701
+ output.table(res.records.map((record) => ({
702
+ when: record._ts,
703
+ record: JSON.stringify(recordFields(record)),
704
+ by: record._actor.onBehalfOf
705
+ ? record._actor.id + " for " + record._actor.onBehalfOf
706
+ : record._actor.id
707
+ })))
708
+ if (res.cursor) output.status("more", "continue with", "--cursor " + res.cursor, "muted")
709
+ })
710
+ }
711
+
712
+ // What changed in a wiki, newest first: each change with who made it, its
713
+ // note, and the pages it touched. A page narrows it to that subtree.
714
+ function changes(argv, ref, rest) {
715
+ return run(async () => {
716
+ const target = rest[0]
717
+ const address = wikiAddress(argv, [target])
718
+ const session = sessionFor(argv, ref)
719
+ const client = getClient(argv, { session })
720
+ const scope = await wikiScope(address, argv, session, client)
721
+ const entries = unwrap(await client.wiki.changes({
722
+ path: scope.full(target),
723
+ ...(argv.limit ? { limit: intFlag(argv.limit, "--limit") } : {}),
724
+ ...(argv.before ? { before: intFlag(argv.before, "--before") } : {})
725
+ }))
726
+ if (output.isJson()) return output.data(entries)
727
+ if (!entries.length) return output.empty("nothing has changed here")
728
+ const by = await actorNames(client, entries.map((entry) => entry.actor))
729
+ output.table(entries.map((entry) => ({
730
+ change: String(entry.id),
731
+ when: output.timeAgo(new Date(entry.createdAt)),
732
+ by: by(entry.actor),
733
+ pages: entry.pages.map((page) => (page.kind === "updated" ? "" : page.kind + " ") + page.fullPath).join(", "),
734
+ note: entry.message || "—".grey
735
+ })))
736
+ const last = entries[entries.length - 1]
737
+ if (argv.limit && entries.length === intFlag(argv.limit, "--limit")) output.status("more", "continue with", "--before " + last.id, "muted")
738
+ })
739
+ }
740
+
741
+ // A record's caller fields, stamps stripped — for compact listings.
742
+ function recordFields(record) {
743
+ const fields = {}
744
+ for (const field of Object.keys(record)) {
745
+ if (field.indexOf("_") !== 0) fields[field] = record[field]
746
+ }
747
+ return fields
748
+ }
749
+
750
+ // The org's wiki registry: every wiki the caller can see. Restricted wikis
751
+ // someone holds no grant on are absent entirely — that is the point; an
752
+ // org owner sees them with no level and `admin` alone.
753
+ function wikis(argv, ref, rest) {
754
+ return run(async () => {
755
+ const session = sessionFor(argv, ref)
756
+ const entries = unwrap(await getClient(argv, { session }).wiki.list({}))
757
+ if (output.isJson()) return output.data(entries)
758
+ if (!entries.length) return output.empty("no wikis")
759
+ const orgName = (session.org && (session.org.name || session.org.slug)) || "the organization"
760
+ // One block per wiki, read top to bottom the way a wiki is chosen:
761
+ // what it is for, then who reads it and
762
+ // which sites, then how lately it changed. `new` is per caller: someone
763
+ // else wrote to it after this session last looked (the app marks wikis
764
+ // seen; the CLI only reads). --json carries everything.
765
+ const standIns = entries.filter((entry) => entry.descriptionFrom !== "declared" && entry.capabilities.includes("write"))
766
+ output.cards(entries.map((entry) => ({
767
+ title: entry.name.cyan.bold,
768
+ aside: asideOf(entry),
769
+ body: entry.description || (entry.capabilities.includes("read") ? "No description yet." : "Restricted: not granted to you."),
770
+ // the home page's first paragraph standing in is not the wiki's own word
771
+ muted: entry.descriptionFrom !== "declared",
772
+ fields: [
773
+ ["read by", readerLines(entry.readers, orgName)],
774
+ ...(entry.shared ? [["shared", "from " + entry.shared.home.slug + ", " + (entry.shared.ceiling === "write" ? "read and write" : "read only")]] : []),
775
+ ...(entry.sharing && !entry.shared ? [["shared", "with " + entry.sharing.guests.map((guest) => guest.name || guest.slug || guest.id).join(", ")]] : []),
776
+ ["sites", siteLines(entry)],
777
+ ["changed", entry.activity?.at
778
+ ? output.timeAgo(new Date(entry.activity.at)) + (entry.unseen ? " · ".grey + "new since you looked".green : "")
779
+ : "never"]
780
+ ]
781
+ })), {
782
+ heading: (orgName + " · " + entries.length + (entries.length === 1 ? " wiki" : " wikis")).bold,
783
+ footer: standIns.length ? [
784
+ listOf(standIns.map((entry) => entry.name)) + (standIns.length === 1 ? " has no description of its own" : " have no descriptions of their own") + "; grey text is the home page standing in. Say what belongs in one:",
785
+ "known " + (ref ? ref + " " : "") + "wiki update " + standIns[0].name + " --description \"…\""
786
+ ] : null
787
+ })
788
+ })
789
+ }
790
+
791
+ // Names as prose: "a", "a and b", "a, b and c".
792
+ function listOf(names) {
793
+ return names.length < 2 ? names.join("") : names.slice(0, -1).join(", ") + " and " + names[names.length - 1]
794
+ }
795
+
796
+ // The heading's right side: how the wiki is kept, then what the caller
797
+ // holds. An org owner not granted on a restricted wiki sees it to manage
798
+ // who is.
799
+ function asideOf(entry) {
800
+ const parts = []
801
+ if (entry.visibility === "restricted") parts.push("restricted".yellow)
802
+ if (entry.shared) parts.push("shared".magenta)
803
+ parts.push((entry.level || (entry.capabilities.includes("admin") ? "you manage access" : "")).grey)
804
+ return parts.filter((part) => require("@colors/colors").strip(part)).join(" · ".grey)
805
+ }
806
+
807
+ // Who reads a wiki, one per line: every member (and how many), or a
808
+ // restricted wiki's teams and people, each with their level.
809
+ function readerLines(readers, orgName) {
810
+ if (!readers || readers.everyone) return "every member of " + orgName + (readers && readers.count != null ? " (" + readers.count + ")" : "")
811
+ const named = [
812
+ ...(readers.teams || []).map((t) => ["team " + (t.title || t.slug || t.id), t.level]),
813
+ ...(readers.people || []).map((p) => [p.name || p.id, p.level])
814
+ ]
815
+ // levels in a column of their own, two spaces past the longest name
816
+ const width = named.reduce((w, [name]) => Math.max(w, name.length), 0)
817
+ const lines = named.map(([name, level]) => name + " ".repeat(width - name.length + 2) + String(level).grey)
818
+ const more = (readers.count != null ? readers.count : (readers.people || []).length) - (readers.people || []).length
819
+ if (more > 0) lines.push(("and " + more + " more").grey)
820
+ return lines
821
+ }
822
+
823
+ // The sites that read a wiki, each by name with where it is published
824
+ // beneath it: a wiki is published where its sites are.
825
+ function siteLines(entry) {
826
+ const lines = []
827
+ for (const site of entry.sites || []) {
828
+ lines.push(site.name)
829
+ for (const address of site.addresses || []) lines.push(" " + siteHost(address).grey)
830
+ }
831
+ return lines
832
+ }
833
+
834
+ // A front-end's host, for a line of facts; null when the wiki names none.
835
+ function siteHost(site) {
836
+ if (!site) return null
837
+ try {
838
+ return new URL(site).host
839
+ } catch (e) {
840
+ return site
841
+ }
842
+ }
843
+
844
+ // Any member creates a wiki and is its admin: the grant is theirs whatever
845
+ // else was asked. An org owner administers every wiki already, and gets no
846
+ // grant by creating one. A wiki starts granted to everyone unless it says
847
+ // who starts with it, and then holds exactly those:
848
+ // --grant <kind>:<id>[:<level>] (repeatable; kind is user or team, level is
849
+ // read, write, or admin, write when unsaid) and --member <person>
850
+ // (repeatable; a person with write). A person is a user id, an @handle, or
851
+ // an email address (helpers.person).
852
+ const GRANT_KINDS = ["user", "team"]
853
+ const GRANT_LEVELS = ["read", "write", "admin"]
854
+ const DEFAULT_GRANT_LEVEL = "write"
855
+
856
+ function parseGrant(value) {
857
+ const [kind, id, level = DEFAULT_GRANT_LEVEL, ...extra] = String(value).split(":")
858
+ if (!GRANT_KINDS.includes(kind) || !id || !GRANT_LEVELS.includes(level) || extra.length) {
859
+ throw friendly("--grant takes <kind>:<id>[:<level>] — kind user or team, level read, write, or admin — got “" + value + "”")
860
+ }
861
+ return { kind, id, level }
862
+ }
863
+
864
+ function grantsOf(argv) {
865
+ const grants = []
866
+ if (argv.grant !== undefined) for (const value of [].concat(argv.grant)) grants.push(parseGrant(value))
867
+ if (argv.member !== undefined) for (const id of [].concat(argv.member)) grants.push({ kind: "user", id: String(id), level: DEFAULT_GRANT_LEVEL })
868
+ return grants.length ? grants : undefined
869
+ }
870
+
871
+ // A grant names who it is to by id on the wire. A person's @handle or email
872
+ // address is looked up first, and must be exactly one member; a team is
873
+ // named by its slug, as `teams` lists it, or by its id.
874
+ const TEAM_ID = /^team_/
875
+ async function namedGrant(client, grant) {
876
+ if (grant.kind === "user") return { ...grant, id: (await person(client, grant.id)).id }
877
+ if (TEAM_ID.test(grant.id)) return grant
878
+ const teams = unwrap(await client.team.list({}))
879
+ const team = teams.find((candidate) => candidate.slug === grant.id)
880
+ if (!team) throw friendly("no team named " + grant.id + " — `known <org> teams` lists them")
881
+ return { ...grant, id: team.id, named: team.slug }
882
+ }
883
+
884
+ function create(argv, ref, rest) {
885
+ return run(async () => {
886
+ const name = rest[0]
887
+ if (!name) throw friendly("name the wiki — `known <org> wiki create <name>`")
888
+ if (!WIKI_NAME.test(String(name))) {
889
+ throw friendly("wiki names are lowercase letters, digits, and hyphens — got “" + name + "”")
890
+ }
891
+ refuseVisibility(argv, String(name))
892
+ const grants = grantsOf(argv)
893
+ const session = sessionFor(argv, ref)
894
+ const client = getClient(argv, { session })
895
+ const named = []
896
+ for (const grant of grants || []) {
897
+ const { kind, id, level } = await namedGrant(client, grant)
898
+ named.push({ kind, id, level })
899
+ }
900
+ const entry = unwrap(await client.wiki.create({
901
+ name: String(name),
902
+ ...(argv.title ? { title: argv.title } : {}),
903
+ ...(argv.description ? { description: String(argv.description) } : {}),
904
+ ...(grants ? { grants: named } : {})
905
+ }))
906
+ if (output.isJson()) return output.data(entry)
907
+ output.status(
908
+ "created",
909
+ entry.name,
910
+ (entry.visibility === "restricted" ? "restricted wiki — " : "wiki — ") + "address its pages as " + entry.name + ":<path>"
911
+ )
912
+ })
913
+ }
914
+
915
+ // A wiki's own words about itself: --description and --title are its root
916
+ // page's (any writer of the wiki). Who holds it is its grants (grant,
917
+ // revoke): nothing here opens or restricts it.
918
+ function update(argv, ref, rest) {
919
+ return run(async () => {
920
+ const name = rest[0]
921
+ if (!name || !WIKI_NAME.test(String(name))) throw friendly("name the wiki — `known <org> wiki update <wiki> --description \"…\"`")
922
+ refuseVisibility(argv, String(name))
923
+ const changes = {
924
+ ...(argv.title !== undefined ? { title: String(argv.title) } : {}),
925
+ ...(argv.description !== undefined ? { description: String(argv.description) } : {})
926
+ }
927
+ if (!Object.keys(changes).length) throw friendly("nothing to change — pass --description or --title")
928
+ const session = sessionFor(argv, ref)
929
+ const entry = unwrap(await getClient(argv, { session }).wiki.update({ wiki: String(name), ...changes }))
930
+ if (output.isJson()) return output.data(entry)
931
+ const said = [
932
+ changes.description !== undefined ? "says what it is for" : null,
933
+ changes.title !== undefined ? "is titled " + entry.title : null
934
+ ].filter(Boolean)
935
+ output.status("updated", entry.name, said.join(", "))
936
+ })
937
+ }
938
+
939
+ // Grant a person or a team a level on a wiki; granting again changes the
940
+ // level. Its admins and org owners may.
941
+ function grant(argv, ref, rest) {
942
+ return run(async () => {
943
+ const [name, who] = rest
944
+ if (!name || !who) throw friendly("name the wiki and who — `known <org> wiki grant <wiki> <kind>:<id>[:<level>]`")
945
+ if (!WIKI_NAME.test(String(name))) throw friendly("wiki names are lowercase letters, digits, and hyphens — got “" + name + "”")
946
+ const parsed = parseGrant(who)
947
+ const session = sessionFor(argv, ref)
948
+ const client = getClient(argv, { session })
949
+ const { kind, id, level, named } = await namedGrant(client, parsed)
950
+ const entry = unwrap(await client.wiki.grant({ wiki: String(name), kind, id, level }))
951
+ if (output.isJson()) return output.data(entry)
952
+ output.status("granted", entry.name, kind + " " + (named || id) + " · " + level)
953
+ })
954
+ }
955
+
956
+ function revoke(argv, ref, rest) {
957
+ return run(async () => {
958
+ const [name, who] = rest
959
+ if (!name || !who) throw friendly("name the wiki and who — `known <org> wiki revoke <wiki> <kind>:<id>`")
960
+ if (!WIKI_NAME.test(String(name))) throw friendly("wiki names are lowercase letters, digits, and hyphens — got “" + name + "”")
961
+ const [kind, given, ...extra] = String(who).split(":")
962
+ if (!GRANT_KINDS.includes(kind) || !given || extra.length) throw friendly("revoke takes <kind>:<id> — kind user or team — got “" + who + "”")
963
+ const session = sessionFor(argv, ref)
964
+ const client = getClient(argv, { session })
965
+ const { id, named } = await namedGrant(client, { kind, id: given })
966
+ const entry = unwrap(await client.wiki.revoke({ wiki: String(name), kind, id }))
967
+ if (output.isJson()) return output.data(entry)
968
+ output.status("revoked", entry.name, kind + " " + (named || id), "muted")
969
+ })
970
+ }
971
+
972
+ // Invite someone by email onto a wiki: they are invited to the
973
+ // organization, and the wiki is theirs at the level named when they join.
974
+ // An address that is already a member's is granted at once. Organization
975
+ // owners may.
976
+ function invite(argv, ref, rest) {
977
+ return run(async () => {
978
+ const [name, who] = rest
979
+ if (!name || !who) throw friendly("name the wiki and the address — `known <org> wiki invite <wiki> <email>[:<level>]`")
980
+ if (!WIKI_NAME.test(String(name))) throw friendly("wiki names are lowercase letters, digits, and hyphens — got “" + name + "”")
981
+ const [email, level, ...extra] = String(who).split(":")
982
+ if (!EMAIL.test(email) || extra.length) throw friendly("invite takes <email>[:<level>] — got “" + who + "”")
983
+ if (level !== undefined && !INVITE_LEVELS.includes(level)) throw friendly("level is one of " + INVITE_LEVELS.join(", ") + " — got “" + level + "”")
984
+ const session = sessionFor(argv, ref)
985
+ const res = unwrap(await getClient(argv, { session }).wiki.invite({ wiki: String(name), email: email.toLowerCase(), ...(level ? { level } : {}) }))
986
+ if (output.isJson()) return output.data(res)
987
+ if (res.granted) return output.status("granted", String(name), "user " + res.granted.id + " · " + res.granted.level + " — already a member")
988
+ output.status("invited", String(name), res.invited.email + " · " + res.invited.level + " — theirs when they join")
989
+ })
990
+ }
991
+
992
+ function uninvite(argv, ref, rest) {
993
+ return run(async () => {
994
+ const [name, email] = rest
995
+ if (!name || !email) throw friendly("name the wiki and the address — `known <org> wiki uninvite <wiki> <email>`")
996
+ if (!WIKI_NAME.test(String(name))) throw friendly("wiki names are lowercase letters, digits, and hyphens — got “" + name + "”")
997
+ const session = sessionFor(argv, ref)
998
+ const res = unwrap(await getClient(argv, { session }).wiki.uninvite({ wiki: String(name), email: String(email).toLowerCase() }))
999
+ if (output.isJson()) return output.data(res)
1000
+ output.status("uninvited", String(name), res.email + (res.withdrawn ? " — their invitation to the organization was withdrawn too" : ""), "muted")
1001
+ })
1002
+ }
1003
+
1004
+ // ---- access, renaming, deleting --------------------------------------------
1005
+
1006
+ // A wiki is not opened or restricted by a flag: it is open to the
1007
+ // organization when the team everyone is granted it. Whoever asks the old
1008
+ // way is told the new one.
1009
+ function refuseVisibility(argv, name) {
1010
+ if (!argv.restricted && !argv.open) return
1011
+ throw friendly(argv.open
1012
+ ? "open it by granting everyone — `known <org> wiki grant " + name + " team:everyone:write` (or read)"
1013
+ : "restrict it by taking everyone off — `known <org> wiki revoke " + name + " team:everyone` (grant whoever keeps it first), or create it with --grant naming who starts with it")
1014
+ }
1015
+
1016
+ // A wiki named on its own, as these verbs take it (no path).
1017
+ function wikiArg(value, usage) {
1018
+ if (value === undefined || value === true || !WIKI_NAME.test(String(value))) {
1019
+ throw friendly("name the wiki — `known <org> wiki " + usage + "`")
1020
+ }
1021
+ return String(value)
1022
+ }
1023
+
1024
+ // Who reaches a wiki, at what level, and why (the API's access.wiki): a row
1025
+ // for everyone when the wiki is open to the org, one per team it is granted
1026
+ // to, and one per person who holds it for a reason of their own — a direct
1027
+ // grant, a team, owning the org. The reasons are muted.
1028
+ function access(argv, ref, rest) {
1029
+ return run(async () => {
1030
+ const name = wikiArg(rest[0], "access <wiki>")
1031
+ const session = sessionFor(argv, ref)
1032
+ const client = getClient(argv, { session })
1033
+ const res = unwrap(await client.access.wiki({ wiki: name }))
1034
+ if (output.isJson()) return output.data(res)
1035
+ const by = await actorNames(client, res.people.map((entry) => ({ id: entry.id })))
1036
+ const teamName = (id) => {
1037
+ const team = res.teams.find((candidate) => candidate.id === id)
1038
+ return (team && (team.slug || team.title)) || id
1039
+ }
1040
+ const rows = [
1041
+ // everyone first: the team every member is on, which is what makes a wiki open to the organization
1042
+ ...res.teams.map((team) => ({
1043
+ who: team.builtin ? "everyone" : "team " + (team.slug || team.title || team.id),
1044
+ level: team.level,
1045
+ why: ((team.builtin ? "every member of the organization · " : "granted to the team · ") + team.members + (team.members === 1 ? " person" : " people")).grey
1046
+ })),
1047
+ ...res.people.map((entry) => ({
1048
+ who: by({ id: entry.id }),
1049
+ // an org owner with no grant on a restricted wiki holds no level:
1050
+ // they manage who has access, and read nothing
1051
+ level: entry.level || "—".grey,
1052
+ why: (accessReasons(entry.via, teamName).join(", ") + (entry.level ? "" : " — manages access only")).grey
1053
+ })),
1054
+ // invited by email and not joined yet (listed to those who change access)
1055
+ ...(res.invited || []).map((entry) => ({
1056
+ who: entry.email,
1057
+ level: entry.level,
1058
+ why: "invited — theirs when they join".grey
1059
+ }))
1060
+ ]
1061
+ if (!rows.length) return output.empty("nobody has access to " + res.name)
1062
+ output.table(rows, { columns: ["who", "level", "why"] })
1063
+ if (res.shared && res.ceiling) {
1064
+ output.status("shared", res.name, "from another organization: nobody here holds more than " + res.ceiling, "muted")
1065
+ }
1066
+ })
1067
+ }
1068
+
1069
+ // Rename a wiki (the API's wiki.rename): its name is in every address of
1070
+ // every page, so the wiki's shares, sites and seen marks follow in one step.
1071
+ // Pages elsewhere that link to it by the old name keep those words and are
1072
+ // listed. A person at a terminal is asked first; --yes skips it.
1073
+ function rename(argv, ref, rest) {
1074
+ return run(async () => {
1075
+ if (rest[0] === undefined || rest[1] === undefined) throw friendly("name the wiki and its new name — `known <org> wiki rename <wiki> <new-name>`")
1076
+ const name = wikiArg(rest[0], "rename <wiki> <new-name>")
1077
+ const to = String(rest[1])
1078
+ if (!WIKI_NAME.test(to)) throw friendly("wiki names are lowercase letters, digits, and hyphens — got “" + to + "”")
1079
+ const session = sessionFor(argv, ref)
1080
+ const client = getClient(argv, { session })
1081
+ if (!(await confirmStated("Rename the " + name + " wiki to " + to + "? Every address of its pages changes.", argv))) {
1082
+ return output.status("kept", name, null, "muted")
1083
+ }
1084
+ const entry = unwrap(await client.wiki.rename({ wiki: name, name: to }))
1085
+ if (output.isJson()) return output.data(entry)
1086
+ output.status("renamed", entry.name, "was " + entry.renamedFrom)
1087
+ output.pad(() => {
1088
+ for (const link of entry.brokenLinks || []) {
1089
+ console.log(" " + "broken link".red + " " + (link.path + (link.key ? "/" + link.key : "")).cyan + (" still links to " + entry.renamedFrom).grey)
1090
+ }
1091
+ console.log(" " + ("Sites that read it must be republished, and agents must use the new name: " + entry.name + ":<path>.").grey)
1092
+ })
1093
+ })
1094
+ }
1095
+
1096
+ // Delete a wiki (the API's wiki.delete), confirmed by its name: typed at a
1097
+ // terminal, or --confirm <name> from a script. Nothing is destroyed — it
1098
+ // leaves every list, address, share and site at once, and `wiki restore`
1099
+ // brings it back whole. The server's refusal (a site still calls it home)
1100
+ // prints as it was said.
1101
+ function destroy(argv, ref, rest) {
1102
+ return run(async () => {
1103
+ const name = wikiArg(rest[0], "delete <wiki>")
1104
+ const session = sessionFor(argv, ref)
1105
+ const client = getClient(argv, { session })
1106
+ const typed = await confirmByName("Delete the " + name + " wiki? It leaves every list, share and site at once; it can be restored. Type its name to confirm:", argv)
1107
+ if (typed.asked && typed.value !== name) return output.status("kept", name, null, "muted")
1108
+ const res = unwrap(await client.wiki.delete({ wiki: name, confirm: typed.value }))
1109
+ if (output.isJson()) return output.data(res)
1110
+ output.status("deleted", res.name, "it can be restored: known " + (ref ? ref + " " : "") + "wiki restore " + res.name, "danger")
1111
+ })
1112
+ }
1113
+
1114
+ // The org's deleted wikis the caller could restore: those they
1115
+ // administered, which for an org owner is all of them.
1116
+ function deleted(argv, ref) {
1117
+ return run(async () => {
1118
+ const session = sessionFor(argv, ref)
1119
+ const client = getClient(argv, { session })
1120
+ const entries = unwrap(await client.wiki.deleted({}))
1121
+ if (output.isJson()) return output.data(entries)
1122
+ if (!entries.length) return output.empty("no deleted wikis")
1123
+ const by = await actorNames(client, entries.map((entry) => ({ id: entry.deletedBy })))
1124
+ output.table(entries.map((entry) => ({
1125
+ wiki: entry.name.cyan,
1126
+ deleted: entry.deletedAt ? output.timeAgo(new Date(entry.deletedAt)) : "",
1127
+ by: entry.deletedBy ? by({ id: entry.deletedBy }) : ""
1128
+ })))
1129
+ })
1130
+ }
1131
+
1132
+ function restore(argv, ref, rest) {
1133
+ return run(async () => {
1134
+ const name = wikiArg(rest[0], "restore <wiki>")
1135
+ const session = sessionFor(argv, ref)
1136
+ const entry = unwrap(await getClient(argv, { session }).wiki.restore({ wiki: name }))
1137
+ if (output.isJson()) return output.data(entry)
1138
+ output.status("restored", entry.name, "address its pages as " + entry.name + ":<path>")
1139
+ })
1140
+ }
1141
+
1142
+ // ---- sharing with other organizations --------------------------------------
1143
+
1144
+ // One organization owns a wiki and invites another by its slug, up to a
1145
+ // level (read or write, never admin). The other's owners see the invitation,
1146
+ // accept it under a name of their own or decline it, and may leave later;
1147
+ // the home ends a share whenever it likes (the API's share.*).
1148
+ const SHARE_LEVELS = ["read", "write"]
1149
+ const ORG_SLUG = /^[a-z0-9][a-z0-9-]*$/
1150
+ const ORG_ID = /^org_[A-Za-z0-9]+$/
1151
+
1152
+ function orgArg(value, usage) {
1153
+ const text = value === undefined || value === true ? "" : String(value)
1154
+ if (!ORG_SLUG.test(text) && !ORG_ID.test(text)) throw friendly("name the organization by its slug — `known <org> wiki " + usage + "`")
1155
+ return text
1156
+ }
1157
+
1158
+ function shares(argv, ref, rest) {
1159
+ return run(async () => {
1160
+ const name = wikiArg(rest[0], "shares <wiki>")
1161
+ const session = sessionFor(argv, ref)
1162
+ const client = getClient(argv, { session })
1163
+ const entries = unwrap(await client.share.list({ name }))
1164
+ if (output.isJson()) return output.data(entries)
1165
+ if (!entries.length) return output.empty(name + " is not shared with any organization")
1166
+ const by = await actorNames(client, entries.map((entry) => ({ id: entry.invitedBy })))
1167
+ output.table(entries.map((entry) => ({
1168
+ organization: ((entry.guest && (entry.guest.slug || entry.guest.name)) || entry.guestOrgId).cyan,
1169
+ level: entry.ceiling,
1170
+ status: ["invited", "accepted"].includes(entry.status) ? entry.status : entry.status.grey,
1171
+ called: entry.guestName || "—".grey,
1172
+ invited: output.timeAgo(new Date(entry.invitedAt)),
1173
+ by: by({ id: entry.invitedBy })
1174
+ })))
1175
+ })
1176
+ }
1177
+
1178
+ function share(argv, ref, rest) {
1179
+ return run(async () => {
1180
+ if (rest[0] === undefined || rest[1] === undefined) throw friendly("name the wiki and the organization — `known <org> wiki share <wiki> <org> [--level read|write]`")
1181
+ const name = wikiArg(rest[0], "share <wiki> <org>")
1182
+ const guest = orgArg(rest[1], "share <wiki> <org>")
1183
+ if (argv.level !== undefined && !SHARE_LEVELS.includes(argv.level)) throw friendly("--level is read or write — another organization never administers a shared wiki")
1184
+ const session = sessionFor(argv, ref)
1185
+ const entry = unwrap(await getClient(argv, { session }).share.invite({
1186
+ name,
1187
+ org: guest,
1188
+ ...(argv.level !== undefined ? { ceiling: argv.level } : {})
1189
+ }))
1190
+ if (output.isJson()) return output.data(entry)
1191
+ const slug = (entry.guest && entry.guest.slug) || guest
1192
+ output.status("invited", slug, "to " + name + " · " + entry.ceiling + " — its owners accept with `known " + slug + " wiki accept " + session.org.slug + "/" + name + "`")
1193
+ })
1194
+ }
1195
+
1196
+ function unshare(argv, ref, rest) {
1197
+ return run(async () => {
1198
+ if (rest[0] === undefined || rest[1] === undefined) throw friendly("name the wiki and the organization — `known <org> wiki unshare <wiki> <org>`")
1199
+ const name = wikiArg(rest[0], "unshare <wiki> <org>")
1200
+ const guest = orgArg(rest[1], "unshare <wiki> <org>")
1201
+ const session = sessionFor(argv, ref)
1202
+ const client = getClient(argv, { session })
1203
+ if (!(await confirmStated("Stop sharing the " + name + " wiki with " + guest + "? Its people lose it at once.", argv))) {
1204
+ return output.status("kept", name, null, "muted")
1205
+ }
1206
+ const entry = unwrap(await client.share.revoke({ name, org: guest }))
1207
+ if (output.isJson()) return output.data(entry)
1208
+ output.status("unshared", name, "no longer shared with " + ((entry.guest && entry.guest.slug) || guest), "muted")
1209
+ })
1210
+ }
1211
+
1212
+ // An invitation is named as it is listed: the inviting organization's slug,
1213
+ // a slash, the wiki's name there (acme/research).
1214
+ function invitationName(invite) {
1215
+ return (invite.homeSlug || invite.homeOrgId) + "/" + invite.name
1216
+ }
1217
+
1218
+ function invitations(argv, ref) {
1219
+ return run(async () => {
1220
+ const session = sessionFor(argv, ref)
1221
+ const pending = unwrap(await getClient(argv, { session }).share.pending({}))
1222
+ if (output.isJson()) return output.data(pending)
1223
+ if (!pending.length) return output.empty("no invitations waiting")
1224
+ output.table(pending.map((invite) => ({
1225
+ invitation: invitationName(invite).cyan,
1226
+ from: invite.homeName || invite.homeSlug || invite.homeOrgId,
1227
+ level: invite.ceiling,
1228
+ invited: output.timeAgo(new Date(invite.invitedAt))
1229
+ })))
1230
+ output.status("accept", "one with", "known " + (ref ? ref + " " : "") + "wiki accept <invitation> [--as <name>]", "muted")
1231
+ })
1232
+ }
1233
+
1234
+ // The waiting invitation a command names. The API takes the inviting
1235
+ // organization's id and the wiki's name there, so the words on the command
1236
+ // line (<org>/<wiki>, or the wiki alone when only one invitation carries
1237
+ // that name) are matched against what is waiting.
1238
+ async function invitationFor(client, value, verb) {
1239
+ const text = value === undefined || value === true ? "" : String(value)
1240
+ if (!text) throw friendly("name the invitation — `known <org> wiki " + verb + " <org>/<wiki>`, as `wiki invitations` lists them")
1241
+ const slash = text.indexOf("/")
1242
+ const home = slash === -1 ? null : text.slice(0, slash)
1243
+ const name = slash === -1 ? text : text.slice(slash + 1)
1244
+ const pending = unwrap(await client.share.pending({}))
1245
+ const matches = pending.filter((invite) => invite.name === name && (home === null || invite.homeSlug === home || invite.homeOrgId === home))
1246
+ if (matches.length === 1) return matches[0]
1247
+ const error = friendly((matches.length ? "several invitations are called " + text + " — name one as <org>/<wiki>" : "no invitation called " + text) + (pending.length ? "; waiting:" : ""))
1248
+ if (pending.length) error.fields = Object.fromEntries(pending.map((invite) => [invitationName(invite), (invite.homeName || invite.homeSlug || invite.homeOrgId) + " · " + invite.ceiling]))
1249
+ return Promise.reject(error)
1250
+ }
1251
+
1252
+ function accept(argv, ref, rest) {
1253
+ return run(async () => {
1254
+ if (argv.as !== undefined && !WIKI_NAME.test(String(argv.as))) throw friendly("--as takes the name the wiki has here: lowercase letters, digits, and hyphens")
1255
+ const session = sessionFor(argv, ref)
1256
+ const client = getClient(argv, { session })
1257
+ const invite = await invitationFor(client, rest[0], "accept")
1258
+ const res = unwrap(await client.share.accept({
1259
+ home: invite.homeOrgId,
1260
+ name: invite.name,
1261
+ ...(argv.as !== undefined ? { localName: String(argv.as) } : {})
1262
+ }))
1263
+ if (output.isJson()) return output.data(res)
1264
+ output.status("accepted", res.name, "from " + (invite.homeSlug || invite.homeOrgId) + " · " + res.share.ceiling + " — address its pages as " + res.name + ":<path>")
1265
+ })
1266
+ }
1267
+
1268
+ function decline(argv, ref, rest) {
1269
+ return run(async () => {
1270
+ const session = sessionFor(argv, ref)
1271
+ const client = getClient(argv, { session })
1272
+ const invite = await invitationFor(client, rest[0], "decline")
1273
+ const res = unwrap(await client.share.decline({ home: invite.homeOrgId, name: invite.name }))
1274
+ if (output.isJson()) return output.data(res)
1275
+ output.status("declined", invitationName(invite), null, "muted")
1276
+ })
1277
+ }
1278
+
1279
+ function leave(argv, ref, rest) {
1280
+ return run(async () => {
1281
+ const name = wikiArg(rest[0], "leave <wiki>")
1282
+ const session = sessionFor(argv, ref)
1283
+ const client = getClient(argv, { session })
1284
+ if (!(await confirmStated("Leave the " + name + " wiki? Everyone here loses it; its organization can invite this one again.", argv))) {
1285
+ return output.status("kept", name, null, "muted")
1286
+ }
1287
+ const res = unwrap(await client.share.leave({ name }))
1288
+ if (output.isJson()) return output.data(res)
1289
+ output.status("left", res.name, "it stays with its own organization", "muted")
1290
+ })
1291
+ }
1292
+
1293
+ // ---- path + flag helpers ---------------------------------------------------
1294
+
1295
+ // Every path on the command line names its wiki: a colon prefix
1296
+ // (`labs:docs.deploy`) or `--wiki labs`. A path without one is refused,
1297
+ // never sent to a wiki the caller did not name. The API spells paths the
1298
+ // same way, within the org the session is for.
1299
+
1300
+ const WIKI_NAME = /^[a-z0-9][a-z0-9-]*$/
1301
+
1302
+ function splitColon(arg) {
1303
+ if (arg == null) return { name: null, rest: arg }
1304
+ const text = String(arg)
1305
+ const i = text.indexOf(":")
1306
+ const slash = text.indexOf("/")
1307
+ // A colon past the first slash is part of a record's key, not a wiki name.
1308
+ if (i === -1 || (slash !== -1 && i > slash)) return { name: null, rest: text }
1309
+ return { name: text.slice(0, i), rest: text.slice(i + 1) }
1310
+ }
1311
+
1312
+ // A record's address: its page (wiki prefix kept), a slash, its key.
1313
+ // Slugs never contain a slash, so the first one is the boundary.
1314
+ function recordAddress(arg) {
1315
+ const text = String(arg == null ? "" : arg)
1316
+ const slash = text.indexOf("/")
1317
+ if (slash === -1) return { page: text, key: null }
1318
+ const key = text.slice(slash + 1)
1319
+ return { page: text.slice(0, slash), key: key === "" ? null : key }
1320
+ }
1321
+
1322
+ // A record's fields other than its writing, stamps left out.
1323
+ function otherFields(record) {
1324
+ const fields = record ? recordFields(record) : {}
1325
+ delete fields.content
1326
+ return fields
1327
+ }
1328
+
1329
+ // A record's writing: its content when that is a string.
1330
+ function writingOf(record) {
1331
+ return record && typeof record.content === "string" ? record.content : ""
1332
+ }
1333
+
1334
+ // A unified diff between two texts, colored, with a header naming both
1335
+ // sides (null for a side that does not exist).
1336
+ function printPatch(name, fromLabel, toLabel, fromText, toText) {
1337
+ if (fromText === toText) return
1338
+ const { createTwoFilesPatch } = require("diff")
1339
+ const patch = createTwoFilesPatch(fromLabel ? name + "@" + fromLabel : "/dev/null", toLabel ? name + "@" + toLabel : "/dev/null", fromText, toText, undefined, undefined, { context: 3 })
1340
+ const lines = patch.split("\n").filter((line) => !line.startsWith("====") && !line.startsWith("Index:"))
1341
+ console.log()
1342
+ for (const line of lines) {
1343
+ if (line.startsWith("+++") || line.startsWith("---")) console.log(" " + line.grey)
1344
+ else if (line.startsWith("+")) console.log(" " + line.green)
1345
+ else if (line.startsWith("-")) console.log(" " + line.red)
1346
+ else if (line.startsWith("@@")) console.log(" " + line.cyan)
1347
+ else console.log(" " + line)
1348
+ }
1349
+ }
1350
+
1351
+ // The pure half: which wiki does this command address? Validated before any
1352
+ // session is resolved, so conflicts and bad names report without credentials.
1353
+ function wikiAddress(argv, args) {
1354
+ const provided = args.filter((arg) => arg != null && String(arg).trim() !== "")
1355
+ const parsed = provided.map(splitColon)
1356
+ const prefixed = parsed.filter((p) => p.name !== null)
1357
+ const names = [...new Set(prefixed.map((p) => p.name))]
1358
+
1359
+ if (argv.wiki !== undefined && prefixed.length) {
1360
+ throw friendly("pass --wiki or a name: prefix, not both")
1361
+ }
1362
+ if (names.length > 1) {
1363
+ throw friendly("one wiki per command — the paths name " + names.join(" and "))
1364
+ }
1365
+ if (prefixed.length && prefixed.length !== parsed.length) {
1366
+ throw friendly("name the wiki on both paths, or pass --wiki")
1367
+ }
1368
+
1369
+ const name = argv.wiki !== undefined ? String(argv.wiki) : (names[0] ?? null)
1370
+ if (name === null) return { name: null, example: parsed[0] ? parsed[0].rest : null }
1371
+ if (!WIKI_NAME.test(name)) {
1372
+ throw friendly("wiki names are lowercase letters, digits, and hyphens — got “" + name + "”")
1373
+ }
1374
+ return { name }
1375
+ }
1376
+
1377
+ // The resolving half: the full path of each argument, in the wiki the
1378
+ // command names. `general` is every org's first wiki and needs no check;
1379
+ // another name is checked against the org's wikis, so a wrong one is
1380
+ // answered with the ones there are. A command that named no wiki is
1381
+ // refused here, once a session can say which wikis the caller has.
1382
+ const GENERAL = "general"
1383
+
1384
+ async function wikiScope(address, argv, session, client) {
1385
+ const slug = session.org && session.org.slug
1386
+ if (!slug) throw friendly("this session predates org slugs — run `known login` again")
1387
+
1388
+ if (address.name === null) throw await unnamed(address, slug, client)
1389
+
1390
+ if (address.name !== GENERAL) {
1391
+ const entries = unwrap(await client.wiki.list({}))
1392
+ if (!entries.some((e) => e.name === address.name)) {
1393
+ const names = entries.map((e) => e.name).join(", ")
1394
+ throw friendly("no wiki named " + address.name + " — you have: " + names)
1395
+ }
1396
+ }
1397
+
1398
+ return {
1399
+ full(arg) {
1400
+ const rest = splitColon(arg).rest
1401
+ return address.name + ":" + String(rest == null ? "" : rest).trim()
1402
+ }
1403
+ }
1404
+ }
1405
+
1406
+ // The refusal for a path that names no wiki: what to type instead, and the
1407
+ // wikis there are to name, each with what it is for, so the choice can be
1408
+ // made from the refusal alone. A path that
1409
+ // starts with a wiki's name and a dot (`labs.docs`) is the likeliest slip,
1410
+ // so it is answered with the colon (`labs:docs`). The list is best-effort;
1411
+ // the refusal is not.
1412
+ async function unnamed(address, slug, client) {
1413
+ let entries = []
1414
+ try {
1415
+ entries = unwrap(await client.wiki.list({}))
1416
+ } catch (e) {}
1417
+ const path = address.example ? String(address.example).trim() : ""
1418
+ const [first, ...rest] = path.split(".")
1419
+ const entry = entries.find((e) => e.name === first)
1420
+ const example = entry ? entry.name + ":" + rest.join(".") : GENERAL + ":" + path
1421
+ const error = friendly("name the wiki — " + example + " or --wiki " + (entry ? entry.name : GENERAL) + (entries.length ? "; the wikis you have:" : ""))
1422
+ if (entries.length) error.fields = Object.fromEntries(entries.map((e) => [e.name, aboutOf(e)]))
1423
+ return error
1424
+ }
1425
+
1426
+ // What a wiki is for, in a line: its description, else its title, else a
1427
+ // note that it says nothing yet.
1428
+ const ABOUT_MAX = 72
1429
+
1430
+ function aboutOf(entry) {
1431
+ const text = entry.description || entry.title || "no description yet"
1432
+ return text.length > ABOUT_MAX ? text.slice(0, ABOUT_MAX - 1) + "…" : text
1433
+ }
1434
+
1435
+ // One line to stand for a page in the tree: its title, else the first
1436
+ // non-empty content line, cleaned of heading marks and clamped.
1437
+ function preview(node) {
1438
+ let text = node.title || ""
1439
+ if (!text) {
1440
+ text = (node.content || "").split("\n").map((l) => l.trim()).find((l) => l) || ""
1441
+ text = text.replace(/^#+\s*/, "")
1442
+ }
1443
+ text = text.replace(/\s+/g, " ").trim()
1444
+ return text.length > 60 ? text.slice(0, 59) + "…" : text
1445
+ }
1446
+
1447
+ function historical(argv) {
1448
+ if (argv.change && argv.at) throw friendly("pass --change or --at, not both")
1449
+ if (argv.change) return { changeId: intFlag(argv.change, "--change") }
1450
+ if (argv.at) return { at: argv.at }
1451
+ return {}
1452
+ }
1453
+
1454
+ function intFlag(value, name) {
1455
+ const n = Number(value)
1456
+ if (!Number.isInteger(n) || n <= 0) throw friendly(name + " must be a positive integer")
1457
+ return n
1458
+ }
1459
+
1460
+ function recordRange(argv) {
1461
+ if (argv.latest && (argv.since || argv.until || argv.limit || argv.cursor || argv.reverse || argv.at)) {
1462
+ throw friendly("--latest stands alone — drop --since/--until/--limit/--cursor/--reverse/--at")
1463
+ }
1464
+ if (argv.latest) return { latest: true }
1465
+ if (argv.at && (argv.since || argv.until)) throw friendly("--at reads one moment — drop --since/--until")
1466
+ return {
1467
+ ...(argv.at ? { at: String(argv.at) } : {}),
1468
+ ...(argv.reverse ? { reverse: true } : {}),
1469
+ ...(argv.since ? { since: String(argv.since) } : {}),
1470
+ ...(argv.until ? { until: String(argv.until) } : {}),
1471
+ ...(argv.limit ? { limit: intFlag(argv.limit, "--limit") } : {}),
1472
+ ...(argv.cursor ? { cursor: String(argv.cursor) } : {})
1473
+ }
1474
+ }
1475
+
1476
+ function parseJson(text) {
1477
+ try {
1478
+ return JSON.parse(text)
1479
+ } catch (e) {
1480
+ throw friendly("the payload is not valid JSON: " + e.message)
1481
+ }
1482
+ }
1483
+
1484
+ // Metadata replaces whole (omitting it preserves what's there), and the
1485
+ // server wants a plain object — reject anything else before the wire.
1486
+ function metadataFlag(value) {
1487
+ let parsed
1488
+ try {
1489
+ parsed = JSON.parse(value)
1490
+ } catch (e) {
1491
+ throw friendly("--metadata is not valid JSON: " + e.message)
1492
+ }
1493
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
1494
+ throw friendly("--metadata must be a JSON object")
1495
+ }
1496
+ return parsed
1497
+ }
1498
+
1499
+ // ---- content input ---------------------------------------------------------
1500
+
1501
+ // The same input rules as `known post`: one source of text, named explicitly —
1502
+ // --text, --file, or piped stdin. Two at once is refused rather than resolved
1503
+ // by precedence, and stdin is only read when it isn't a terminal.
1504
+ async function resolveText(argv) {
1505
+ const piped = !process.stdin.isTTY
1506
+ const given = [
1507
+ argv.text !== undefined ? "--text" : null,
1508
+ argv.file ? "--file" : null,
1509
+ piped && argv.text === undefined && !argv.file ? "stdin" : null
1510
+ ].filter(Boolean)
1511
+
1512
+ if (given.length > 1) {
1513
+ throw friendly("pass only one of " + given.join(" or ") + " — not both")
1514
+ }
1515
+
1516
+ if (argv.text !== undefined) return required(String(argv.text))
1517
+
1518
+ if (argv.file) {
1519
+ try {
1520
+ return required(fs.readFileSync(argv.file, "utf8"))
1521
+ } catch (e) {
1522
+ throw friendly("cannot read " + argv.file + ": " + e.message)
1523
+ }
1524
+ }
1525
+
1526
+ if (piped) return required(await readStdin())
1527
+
1528
+ throw friendly("nothing to write — pass --text \"…\", --file <path>, or pipe content in")
1529
+ }
1530
+
1531
+ function required(text) {
1532
+ if (!text.trim()) throw friendly("nothing to write — the content is empty")
1533
+ return text
1534
+ }
1535
+
1536
+ function readStdin() {
1537
+ return new Promise((resolve, reject) => {
1538
+ let text = ""
1539
+ process.stdin.setEncoding("utf8")
1540
+ process.stdin.on("data", (chunk) => {
1541
+ text += chunk
1542
+ if (text.length > STDIN_MAX) {
1543
+ reject(friendly("input is too long — the maximum is " + STDIN_MAX + " characters"))
1544
+ }
1545
+ })
1546
+ process.stdin.on("end", () => resolve(text))
1547
+ process.stdin.on("error", reject)
1548
+ })
1549
+ }
1550
+
1551
+ function friendly(message) {
1552
+ const e = new Error(message)
1553
+ e.friendly = true
1554
+ return e
1555
+ }