@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,403 @@
1
+ require("@colors/colors")
2
+ const output = require("../output")
3
+ const { getClient, sessionFor, confirmStated, run, unwrap, person, personRef, exactPerson, accessReasons, friendly } = require("../helpers")
4
+
5
+ /**
6
+ * `known <org> members` — the organization's people.
7
+ *
8
+ * Who is in the org and at which role — owner or member — who has been
9
+ * invited, and who is waiting to join. Every member sees who is in the org
10
+ * and what they themselves reach; email addresses, invitations, requests and
11
+ * every change are an owner's. Anyone leaves themselves, except the last
12
+ * owner.
13
+ *
14
+ * known acme members
15
+ * known acme members --query ada --role member
16
+ * known acme members get @ada
17
+ * known acme members invite ada@acme.com grace@acme.com --role member
18
+ * known acme members invitations
19
+ * known acme members resend orginv_2abc
20
+ * known acme members revoke ada@acme.com
21
+ * known acme members role @ada owner
22
+ * known acme members remove @ada
23
+ * known acme members requests
24
+ * known acme members approve grace@acme.com --role member
25
+ * known acme members leave
26
+ *
27
+ * A person is named by user id (user_…), @handle, or email address; the last
28
+ * two must match exactly one person. An invitation is named by its id
29
+ * (orginv_…) or the address it went to.
30
+ *
31
+ * Removing someone, or leaving, deletes every grant they hold on a wiki and
32
+ * every seat on a team. Coming back later restores nothing.
33
+ */
34
+ const ROLES = ["owner", "member"]
35
+ // The most the API answers with in one page; lists are read a page at a time.
36
+ const PAGE_SIZE = 100
37
+
38
+ const verbs = { list, get, invite, invitations, revoke, resend, role, remove, leave, requests, approve, decline }
39
+
40
+ module.exports = function (argv, ref, rest) {
41
+ const verb = rest && rest[0]
42
+ if (argv.help) return showMenu(ref)
43
+ if (!verb) return list(argv, ref, [])
44
+ const handler = verbs[verb]
45
+ if (!handler) {
46
+ output.info(require("../helpers").unknownCommand("members", verb, Object.keys(verbs)).grey)
47
+ return showMenu(ref)
48
+ }
49
+ return handler(argv, ref, rest.slice(1))
50
+ }
51
+
52
+ // Bare (`known members`), the org comes from the project binding, so the
53
+ // menu drops the org from every invocation.
54
+ function showMenu(ref) {
55
+ const org = ref ? ref + " " : ""
56
+ console.log()
57
+ console.log((" known " + org + "members").cyan + " the org's people — owners and members, invitations, requests to join".grey)
58
+ console.log()
59
+ const groups = [
60
+ ["people", [
61
+ [org + "members", "who is in the org, and at which role (--query <text>, --role owner|member, --limit <n>)"],
62
+ [org + "members get <person>", "one person, and what they reach and why: teams, wikis, sites (owners, or yourself)"],
63
+ [org + "members role <person> owner|member", "change someone's role (owners)"],
64
+ [org + "members remove <person>", "take someone out of the org; their grants and team seats are deleted (owners; --yes)"],
65
+ [org + "members leave", "leave the org yourself; your grants and team seats are deleted (--yes)"]
66
+ ]],
67
+ ["invitations", [
68
+ [org + "members invite <email>…", "invite people by email address (--role owner|member; member when unsaid)"],
69
+ [org + "members invitations", "the invitations still waiting"],
70
+ [org + "members revoke <invitation>", "withdraw an invitation, by its id or the address it went to"],
71
+ [org + "members resend <invitation>", "send it again; the old link stops working"]
72
+ ]],
73
+ ["requests to join", [
74
+ [org + "members requests", "who is waiting to join"],
75
+ [org + "members approve <person>", "let someone waiting in (--role owner|member; member when unsaid)"],
76
+ [org + "members decline <person>", "turn a request down"]
77
+ ]]
78
+ ]
79
+ const width = output.commandWidth(...groups.map(([, rows]) => rows))
80
+ for (const [title, rows] of groups) {
81
+ console.log(" " + title.bold)
82
+ output.commands(rows, width)
83
+ console.log()
84
+ }
85
+ process.exit(0)
86
+ }
87
+
88
+ // ---- people ----------------------------------------------------------------
89
+
90
+ // Everyone in the org, by name, read a page at a time (offset) until the
91
+ // list ends or --limit is reached. --query narrows by name or email address,
92
+ // --role by role. Owners also see each person's email address.
93
+ function list(argv, ref) {
94
+ return run(async () => {
95
+ const filter = {
96
+ ...(argv.query !== undefined ? { query: String(argv.query) } : {}),
97
+ ...(argv.role !== undefined ? { role: roleFlag(argv.role) } : {})
98
+ }
99
+ const limit = argv.limit !== undefined ? intFlag(argv.limit, "--limit") : null
100
+ const session = sessionFor(argv, ref)
101
+ const client = getClient(argv, { session })
102
+ const { items, total } = await pages((page) => client.members.list({ ...filter, ...page }), limit)
103
+ if (output.isJson()) return output.data({ items, total })
104
+ if (!items.length) return output.empty(Object.keys(filter).length ? "nobody matches" : "no members")
105
+ const emails = items.some((member) => member.email)
106
+ output.table(items.map((member) => ({
107
+ person: member.name || "—".grey,
108
+ handle: member.handle ? "@" + member.handle : "—".grey,
109
+ role: member.role === "owner" ? member.role : member.role.grey,
110
+ ...(emails ? { email: member.email || "—".grey } : {}),
111
+ joined: ago(member.joined_at),
112
+ id: member.user_id.grey
113
+ })))
114
+ if (items.length < total) output.status("more", items.length + " of " + total, "raise --limit to see the rest", "muted")
115
+ })
116
+ }
117
+
118
+ // One person and what they reach (members.get, the API's
119
+ // access.person): their role, their teams, every wiki they hold with its
120
+ // level and why, and the sites they may use or manage. Anyone asks about
121
+ // themselves; an owner about any member — for anyone else the person shows
122
+ // without their reach, and the API's reason is said beneath.
123
+ function get(argv, ref, rest) {
124
+ return run(async () => {
125
+ needPerson(rest[0], "get <person>")
126
+ const session = sessionFor(argv, ref)
127
+ const client = getClient(argv, { session })
128
+ const who = await person(client, rest[0])
129
+ const member = unwrap(await client.members.get({ user_id: who.id }))
130
+ const reach = await client.access.person({ user: who.id })
131
+ const access = reach && reach.refused ? null : unwrap(reach)
132
+ if (output.isJson()) return output.data({ member, access })
133
+ const teamName = (id) => {
134
+ const team = ((access && access.teams) || []).find((candidate) => candidate.id === id)
135
+ return (team && team.slug) || id
136
+ }
137
+ output.cards([{
138
+ title: (member.name || (member.handle ? "@" + member.handle : member.user_id)).cyan.bold,
139
+ aside: member.role.grey,
140
+ fields: [
141
+ ["handle", member.handle ? "@" + member.handle : null],
142
+ ["email", member.email || null],
143
+ ["id", member.user_id],
144
+ ["joined", member.joined_at ? ago(member.joined_at) : null],
145
+ ...(access ? [
146
+ null,
147
+ ["teams", columns(access.teams.map((team) => [team.slug, team.maintainer ? "maintainer" : "member"]))],
148
+ ["wikis", columns(access.wikis.flatMap((wiki) => reasoned([wiki.name, wiki.level || "no level"], accessReasons(wiki.via, teamName))))],
149
+ ["sites", columns(access.sites.flatMap((site) => reasoned([site.slug || site.name, site.manage ? "manage" : "use"], accessReasons(site.via, teamName))))]
150
+ ] : [])
151
+ ]
152
+ }], access ? {} : { footer: reach.refused.message })
153
+ })
154
+ }
155
+
156
+ function role(argv, ref, rest) {
157
+ return run(async () => {
158
+ if (rest[0] === undefined || rest[1] === undefined) throw friendly("name the person and the role — `known <org> members role <person> owner|member`")
159
+ const to = roleFlag(rest[1])
160
+ const session = sessionFor(argv, ref)
161
+ const client = getClient(argv, { session })
162
+ const who = await person(client, rest[0])
163
+ const member = unwrap(await client.members.setRole({ user_id: who.id, role: to }))
164
+ if (output.isJson()) return output.data(member)
165
+ output.status(member.role, member.name || who.name || who.id, "is now an org " + member.role)
166
+ })
167
+ }
168
+
169
+ // Taking someone out ends everything they held inside the org, so a person
170
+ // at a terminal is asked first; --yes skips it.
171
+ function remove(argv, ref, rest) {
172
+ return run(async () => {
173
+ needPerson(rest[0], "remove <person>")
174
+ const session = sessionFor(argv, ref)
175
+ const client = getClient(argv, { session })
176
+ const who = await person(client, rest[0])
177
+ const named = who.name || who.id
178
+ if (!(await confirmStated("Remove " + named + " from " + orgNameOf(session) + "? Their grants on wikis and their seats on teams are deleted; coming back restores nothing.", argv))) {
179
+ return output.status("kept", named, null, "muted")
180
+ }
181
+ const res = unwrap(await client.members.remove({ user_id: who.id }))
182
+ if (output.isJson()) return output.data(res)
183
+ output.status("removed", named, "their grants on wikis and their seats on teams are deleted", "danger")
184
+ })
185
+ }
186
+
187
+ function leave(argv, ref) {
188
+ return run(async () => {
189
+ const session = sessionFor(argv, ref)
190
+ const client = getClient(argv, { session })
191
+ if (!(await confirmStated("Leave " + orgNameOf(session) + "? Your grants on wikis and your seats on teams are deleted; coming back restores nothing.", argv))) {
192
+ return output.status("stayed", orgNameOf(session), null, "muted")
193
+ }
194
+ const res = unwrap(await client.members.leave({}))
195
+ if (output.isJson()) return output.data(res)
196
+ output.status("left", orgNameOf(session), "your grants and team seats are deleted; sign out with `known " + (ref ? ref + " " : "") + "logout`", "danger")
197
+ })
198
+ }
199
+
200
+ // ---- invitations -----------------------------------------------------------
201
+
202
+ // Every address is answered for on its own: those invited and those refused
203
+ // (already a member, already invited) print apart. When nobody was invited
204
+ // the command fails, saying why for each.
205
+ function invite(argv, ref, rest) {
206
+ return run(async () => {
207
+ const emails = rest.map((email) => String(email).trim()).filter(Boolean)
208
+ if (!emails.length) throw friendly("name who to invite — `known <org> members invite <email>… [--role owner|member]`")
209
+ const bad = emails.find((email) => !EMAIL.test(email))
210
+ if (bad) throw friendly("“" + bad + "” is not an email address")
211
+ const as = argv.role !== undefined ? roleFlag(argv.role) : undefined
212
+ const session = sessionFor(argv, ref)
213
+ const res = unwrap(await getClient(argv, { session }).members.invite({ emails, ...(as ? { role: as } : {}) }))
214
+ if (output.isJson()) return output.data(res)
215
+ if (!res.invited.length) {
216
+ throw friendly("nobody was invited", Object.fromEntries(res.refused.map((entry) => [entry.email, entry.message])))
217
+ }
218
+ output.pad(() => {
219
+ for (const entry of res.invited) console.log(" " + "invited".green + " " + entry.email.cyan + (" " + entry.role + " · " + entry.invitation_id).grey)
220
+ for (const entry of res.refused) console.log(" " + "refused".red + " " + entry.email.cyan + (" " + entry.message).grey)
221
+ })
222
+ })
223
+ }
224
+
225
+ function invitations(argv, ref) {
226
+ return run(async () => {
227
+ const limit = argv.limit !== undefined ? intFlag(argv.limit, "--limit") : null
228
+ const session = sessionFor(argv, ref)
229
+ const client = getClient(argv, { session })
230
+ const { items, total } = await pages((page) => client.members.invitations(page), limit)
231
+ if (output.isJson()) return output.data({ items, total })
232
+ if (!items.length) return output.empty("no invitations waiting")
233
+ output.table(items.map((entry) => ({
234
+ email: entry.email.cyan,
235
+ role: entry.role,
236
+ invited: ago(entry.invited_at),
237
+ expires: entry.expires_at ? new Date(entry.expires_at).toISOString().slice(0, 10) : "—".grey,
238
+ id: entry.invitation_id.grey
239
+ })))
240
+ if (items.length < total) output.status("more", items.length + " of " + total, "raise --limit to see the rest", "muted")
241
+ })
242
+ }
243
+
244
+ function revoke(argv, ref, rest) {
245
+ return run(async () => {
246
+ needInvitation(rest[0], "revoke")
247
+ const session = sessionFor(argv, ref)
248
+ const client = getClient(argv, { session })
249
+ const invitation = await invitationFor(client, rest[0])
250
+ const res = unwrap(await client.members.revokeInvitation({ invitation_id: invitation.invitation_id }))
251
+ if (output.isJson()) return output.data(res)
252
+ output.status("revoked", invitation.email || invitation.invitation_id, "the invitation no longer works", "muted")
253
+ })
254
+ }
255
+
256
+ function resend(argv, ref, rest) {
257
+ return run(async () => {
258
+ needInvitation(rest[0], "resend")
259
+ const session = sessionFor(argv, ref)
260
+ const client = getClient(argv, { session })
261
+ const invitation = await invitationFor(client, rest[0])
262
+ const sent = unwrap(await client.members.resendInvitation({ invitation_id: invitation.invitation_id }))
263
+ if (output.isJson()) return output.data(sent)
264
+ output.status("resent", sent.email, sent.role + " · " + sent.invitation_id + " — the old link no longer works")
265
+ })
266
+ }
267
+
268
+ // ---- requests to join ------------------------------------------------------
269
+
270
+ function requests(argv, ref) {
271
+ return run(async () => {
272
+ const session = sessionFor(argv, ref)
273
+ const res = unwrap(await getClient(argv, { session }).members.requests({}))
274
+ if (output.isJson()) return output.data(res)
275
+ if (!res.items.length) return output.empty("nobody is waiting to join")
276
+ output.table(res.items.map((entry) => ({
277
+ person: entry.name || "—".grey,
278
+ handle: entry.handle ? "@" + entry.handle : "—".grey,
279
+ email: entry.email || "—".grey,
280
+ asked: ago(entry.requested_at),
281
+ id: entry.user_id.grey
282
+ })))
283
+ })
284
+ }
285
+
286
+ function approve(argv, ref, rest) {
287
+ return run(async () => {
288
+ needPerson(rest[0], "approve <person>")
289
+ const as = argv.role !== undefined ? roleFlag(argv.role) : undefined
290
+ const session = sessionFor(argv, ref)
291
+ const client = getClient(argv, { session })
292
+ const who = await waiting(client, rest[0])
293
+ const member = unwrap(await client.members.approveRequest({ user_id: who.user_id, ...(as ? { role: as } : {}) }))
294
+ if (output.isJson()) return output.data(member)
295
+ output.status("approved", member.name || who.name || who.user_id, "joins as an org " + member.role)
296
+ })
297
+ }
298
+
299
+ function decline(argv, ref, rest) {
300
+ return run(async () => {
301
+ needPerson(rest[0], "decline <person>")
302
+ const session = sessionFor(argv, ref)
303
+ const client = getClient(argv, { session })
304
+ const who = await waiting(client, rest[0])
305
+ const res = unwrap(await client.members.declineRequest({ user_id: who.user_id }))
306
+ if (output.isJson()) return output.data(res)
307
+ output.status("declined", who.name || who.user_id, "their request to join", "muted")
308
+ })
309
+ }
310
+
311
+ // ---- helpers ---------------------------------------------------------------
312
+
313
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
314
+ const INVITATION_ID = /^orginv_[A-Za-z0-9]+$/
315
+
316
+ function needPerson(value, usage) {
317
+ if (value === undefined || value === true || !String(value).trim()) {
318
+ throw friendly("name the person — `known <org> members " + usage + "`, by user id, @handle, or email address")
319
+ }
320
+ }
321
+
322
+ function needInvitation(value, verb) {
323
+ const text = value === undefined || value === true ? "" : String(value)
324
+ if (!INVITATION_ID.test(text) && !EMAIL.test(text)) {
325
+ throw friendly("name the invitation — `known <org> members " + verb + " <invitation>`, by its id (orginv_…) or the address it went to")
326
+ }
327
+ }
328
+
329
+ function roleFlag(value) {
330
+ if (!ROLES.includes(value)) throw friendly("a role is owner or member — got “" + value + "”")
331
+ return value
332
+ }
333
+
334
+ function intFlag(value, name) {
335
+ const n = Number(value)
336
+ if (!Number.isInteger(n) || n <= 0) throw friendly(name + " must be a positive integer")
337
+ return n
338
+ }
339
+
340
+ function orgNameOf(session) {
341
+ return (session.org && (session.org.name || session.org.slug)) || "the organization"
342
+ }
343
+
344
+ // When something happened, as an age ("3 days ago"); the API's stamps are
345
+ // milliseconds.
346
+ function ago(stamp) {
347
+ return stamp ? output.timeAgo(new Date(stamp)) : "—".grey
348
+ }
349
+
350
+ // A paged list read whole, or up to `limit` items: `{ items, total }`.
351
+ // `fetch({ limit, offset })` answers one page (`{ items, total }`).
352
+ async function pages(fetch, limit) {
353
+ const items = []
354
+ let total = 0
355
+ for (;;) {
356
+ const want = limit === null ? PAGE_SIZE : Math.min(PAGE_SIZE, limit - items.length)
357
+ const page = unwrap(await fetch({ limit: want, offset: items.length }))
358
+ total = page.total
359
+ items.push(...page.items)
360
+ if (!page.items.length || items.length >= total || (limit !== null && items.length >= limit)) return { items, total }
361
+ }
362
+ }
363
+
364
+ // The waiting invitation a command names: by its id, taken as given, or by
365
+ // the address it went to, which must be exactly one of those waiting.
366
+ async function invitationFor(client, value) {
367
+ const text = String(value)
368
+ if (INVITATION_ID.test(text)) return { invitation_id: text, email: null }
369
+ const { items } = await pages((page) => client.members.invitations(page), null)
370
+ const matches = items.filter((entry) => String(entry.email).toLowerCase() === text.toLowerCase())
371
+ if (matches.length === 1) return matches[0]
372
+ throw friendly(
373
+ (matches.length ? matches.length + " invitations are waiting for " + text + " — name one by its id" : "no invitation is waiting for " + text) + (items.length ? "; waiting:" : ""),
374
+ items.length ? Object.fromEntries((matches.length ? matches : items).map((entry) => [entry.invitation_id, entry.email + " · " + entry.role])) : null
375
+ )
376
+ }
377
+
378
+ // Someone waiting to join is not in the org yet, so they are found among
379
+ // the requests rather than the members: by user id, @handle, or the address
380
+ // they asked from.
381
+ async function waiting(client, value) {
382
+ const ref = personRef(value)
383
+ const res = unwrap(await client.members.requests({}))
384
+ return exactPerson(res.items || [], ref, "waiting to join")
385
+ }
386
+
387
+ // Rows as columns, the first plain and the rest greyed:
388
+ // "labs write direct grant (write)".
389
+ // A row and its reasons, one reason a line under the first, so a long list
390
+ // of them never runs past the card.
391
+ function reasoned(cells, reasons) {
392
+ if (!reasons.length) return [[...cells, ""]]
393
+ return reasons.map((reason, i) => (i === 0 ? [...cells, reason] : [...cells.map(() => ""), reason]))
394
+ }
395
+
396
+ function columns(rows) {
397
+ const widths = []
398
+ for (const row of rows) row.forEach((cell, i) => { widths[i] = Math.max(widths[i] || 0, String(cell).length) })
399
+ return rows.map((row) => row.map((cell, i) => {
400
+ const text = String(cell) + (i < row.length - 1 ? " ".repeat(widths[i] - String(cell).length + 2) : "")
401
+ return i === 0 ? text : text.grey
402
+ }).join(""))
403
+ }
@@ -0,0 +1,49 @@
1
+ require("@colors/colors")
2
+ const output = require("../output")
3
+ const { getClient, sessionFor, accountLabel, run, unwrap } = require("../helpers")
4
+
5
+ // `known [<org>] ping` — prove a session still works, end to end.
6
+ //
7
+ // This is more than a reachability check. The API authorizes every method against
8
+ // a resolved organization membership, `system.ping` included, so a successful
9
+ // ping means: the token verified, the account still belongs to the org, and the
10
+ // policy allowed the call. That makes it the pre-flight for anything that reads
11
+ // or writes — which is why it reports *who it authenticated as* rather than a
12
+ // bare ok. Knowing the call succeeded is far less useful than knowing which
13
+ // tenant it succeeded against.
14
+ module.exports = function (argv, ref) {
15
+ return run(async () => {
16
+ const session = sessionFor(argv, ref)
17
+ const result = await getClient(argv, { session }).system.ping()
18
+ const body = unwrap(result)
19
+
20
+ if (output.isJson()) {
21
+ return output.data({
22
+ ok: !!(body && body.ok),
23
+ session: session.label,
24
+ from: session.source,
25
+ endpoint: session.endpoint,
26
+ org: (session.org && session.org.slug) || session.key,
27
+ org_id: (session.org && session.org.id) || null,
28
+ account: accountLabel(session.account),
29
+ role: session.role || null,
30
+ service: (body && body.service) || null,
31
+ server_time: (body && body.time) || null,
32
+ ms: typeof result.ms === "number" ? result.ms : null
33
+ })
34
+ }
35
+
36
+ output.record([
37
+ ["session", session.label],
38
+ ...(session.source ? [["from", session.source]] : []),
39
+ ["endpoint", session.endpoint],
40
+ ["org", ((session.org && session.org.name) || session.key) +
41
+ (session.org && session.org.id ? (" " + session.org.id).grey : "")],
42
+ ["account", accountLabel(session.account)],
43
+ ["role", session.role],
44
+ ["service", (body && body.service) || null],
45
+ ["latency", typeof result.ms === "number" ? result.ms + "ms" : null],
46
+ ["status", body && body.ok ? "ok".green : "unexpected response".red]
47
+ ])
48
+ })
49
+ }
@@ -0,0 +1,103 @@
1
+ require("@colors/colors")
2
+ const fs = require("fs")
3
+ const output = require("../output")
4
+ const { getClient, sessionFor, run, unwrap } = require("../helpers")
5
+
6
+ /**
7
+ * `known <org> post` — add authored content to the org's Engram stream.
8
+ *
9
+ * Text can come from a flag, a file, or standard input, because piping is the
10
+ * reason to have this at a terminal at all:
11
+ *
12
+ * known acme post --text "hello world"
13
+ * git log -1 --format=%B | known acme post
14
+ * known acme post --file notes.md --title "Design review"
15
+ *
16
+ * The API builds and publishes the Engram: the CLI sends text and an optional
17
+ * title, and the server derives identity, timestamp, author, and provenance from
18
+ * the authenticated session. Nothing about the post is the client's to assert.
19
+ */
20
+ const STDIN_MAX = 100000
21
+
22
+ module.exports = function (argv, ref) {
23
+ return run(async () => {
24
+ // Resolve the text before the session. Both checks are local, but reporting
25
+ // what's wrong with the request the user actually typed — a missing file, two
26
+ // input sources, empty content — is more useful than reporting a missing
27
+ // session first, and it keeps the input rules verifiable without any
28
+ // credentials on disk.
29
+ const text = await resolveText(argv)
30
+ const session = sessionFor(argv, ref)
31
+
32
+ const res = unwrap(await getClient(argv, { session }).engrams.post({
33
+ text,
34
+ ...(argv.title ? { title: argv.title } : {})
35
+ }))
36
+
37
+ if (output.isJson()) return output.data({ ...res, session: session.label })
38
+
39
+ output.status("posted", res.title || "note", [
40
+ res.engram_id,
41
+ "to " + session.label,
42
+ res.duplicate ? "already published".yellow : null
43
+ ].filter(Boolean).join(" · "))
44
+ })
45
+ }
46
+
47
+ // One source of text, named explicitly: --text, --file, or piped stdin. Two at
48
+ // once is refused rather than silently resolved by precedence — this call
49
+ // publishes, and quietly dropping the input someone passed is the wrong failure
50
+ // mode for a write. Stdin is only read when it isn't a terminal, so a bare
51
+ // `known acme post` reports what to do instead of hanging.
52
+ async function resolveText(argv) {
53
+ const piped = !process.stdin.isTTY
54
+ const given = [
55
+ argv.text !== undefined ? "--text" : null,
56
+ argv.file ? "--file" : null,
57
+ piped && argv.text === undefined && !argv.file ? "stdin" : null
58
+ ].filter(Boolean)
59
+
60
+ if (given.length > 1) {
61
+ throw friendly("pass only one of " + given.join(" or ") + " — not both")
62
+ }
63
+
64
+ if (argv.text !== undefined) return required(String(argv.text))
65
+
66
+ if (argv.file) {
67
+ try {
68
+ return required(fs.readFileSync(argv.file, "utf8"))
69
+ } catch (e) {
70
+ throw friendly("cannot read " + argv.file + ": " + e.message)
71
+ }
72
+ }
73
+
74
+ if (piped) return required(await readStdin())
75
+
76
+ throw friendly("nothing to post — pass --text \"…\", --file <path>, or pipe text in")
77
+ }
78
+
79
+ function required(text) {
80
+ if (!text.trim()) throw friendly("nothing to post — the text is empty")
81
+ return text
82
+ }
83
+
84
+ function readStdin() {
85
+ return new Promise((resolve, reject) => {
86
+ let text = ""
87
+ process.stdin.setEncoding("utf8")
88
+ process.stdin.on("data", (chunk) => {
89
+ text += chunk
90
+ if (text.length > STDIN_MAX) {
91
+ reject(friendly("input is too long — the maximum is " + STDIN_MAX + " characters"))
92
+ }
93
+ })
94
+ process.stdin.on("end", () => resolve(text))
95
+ process.stdin.on("error", reject)
96
+ })
97
+ }
98
+
99
+ function friendly(message) {
100
+ const e = new Error(message)
101
+ e.friendly = true
102
+ return e
103
+ }
@@ -0,0 +1,86 @@
1
+ const { getClient, sessionFor, run, unwrap, nearest } = require("../helpers")
2
+ const output = require("../output")
3
+
4
+ // Raw JSON-RPC escape hatch:
5
+ // known acme rpc every method the API answers, by namespace
6
+ // known acme rpc team the methods of one namespace
7
+ // known acme rpc system.ping
8
+ // known acme rpc auth.whoami
9
+ // known acme rpc connections.list '{"limit":10}'
10
+ //
11
+ // Params come from a single JSON positional arg, or from leftover flags. The org
12
+ // is never forwarded as a param — it is already implicit in the token.
13
+ //
14
+ // With no method, or a namespace alone, the API is asked what it answers
15
+ // (rpc.methods); a method it does not know is answered with the near ones.
16
+ const LISTING_METHOD = "rpc.methods"
17
+ const NOT_FOUND = /method not found/i
18
+
19
+ module.exports = function (argv, ref, rest = []) {
20
+ return run(async () => {
21
+ const method = rest[0]
22
+ const session = sessionFor(argv, ref)
23
+ const client = getClient(argv, { session })
24
+ if (!method || !method.includes(".")) return list(client, ref, method || null)
25
+
26
+ let params = {}
27
+ const raw = rest[1]
28
+ if (raw) {
29
+ try {
30
+ params = JSON.parse(raw)
31
+ } catch (e) {
32
+ throw new Error("params must be valid JSON")
33
+ }
34
+ } else {
35
+ const reserved = new Set(["_", "json", "yes", "y", "help", "h", "endpoint"])
36
+ for (const k of Object.keys(argv)) {
37
+ if (!reserved.has(k)) params[k] = argv[k]
38
+ }
39
+ }
40
+
41
+ let res
42
+ try {
43
+ res = unwrap(await client.call(method, params))
44
+ } catch (error) {
45
+ if (!NOT_FOUND.test(String(error && error.message))) throw error
46
+ const names = await answered(client).catch(() => [])
47
+ const near = nearest(method, names)
48
+ const space = method.split(".")[0]
49
+ const siblings = near.length ? near : names.filter((name) => name.split(".")[0] === space)
50
+ const e = new Error("no method named " + method + (siblings.length ? " — did you mean " + siblings.join(", ") + "?" : " — `known " + (ref ? ref + " " : "") + "rpc` lists them"))
51
+ e.friendly = true
52
+ throw e
53
+ }
54
+ output.data(res)
55
+ })
56
+ }
57
+
58
+ async function answered(client) {
59
+ const res = unwrap(await client.call(LISTING_METHOD, {}))
60
+ return [...(res.methods || []), ...(res.streams || [])]
61
+ }
62
+
63
+ // Every method the API answers, grouped by namespace; one namespace alone
64
+ // when it is named.
65
+ async function list(client, ref, space) {
66
+ const res = unwrap(await client.call(LISTING_METHOD, {}))
67
+ if (output.isJson()) return output.data(res)
68
+ const groups = new Map()
69
+ for (const name of [...(res.methods || []), ...(res.streams || [])].sort()) {
70
+ const key = name.includes(".") ? name.split(".")[0] : name
71
+ if (!groups.has(key)) groups.set(key, [])
72
+ groups.get(key).push(name.includes(".") ? name.slice(key.length + 1) : name)
73
+ }
74
+ if (space && !groups.has(space)) {
75
+ const near = nearest(space, [...groups.keys()])
76
+ const e = new Error("no methods under " + space + (near.length ? " — did you mean " + near.join(", ") + "?" : ""))
77
+ e.friendly = true
78
+ throw e
79
+ }
80
+ const org = ref ? ref + " " : ""
81
+ console.log()
82
+ output.commands([...groups.entries()].filter(([key]) => !space || key === space).map(([key, names]) => [" " + key, names.join(" ")]))
83
+ console.log()
84
+ console.log((" known " + org + "rpc <namespace>.<method> '{\"param\": \"value\"}'").grey)
85
+ console.log()
86
+ }